lib/checks/check-project.py

477 lines · 16335 bytes

  1"""Checks project health: URL reachability, GitHub repo stars, activity, and author match."""
  2
  3import json
  4import os
  5import re
  6import sys
  7from datetime import datetime, timedelta, timezone
  8
  9import requests
 10import yaml
 11
 12PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
 13DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
 14DIFF_PATH = "/tmp/pr-diff.json"
 15FINDINGS_PATH = "/tmp/findings-project.json"
 16
 17TIMEOUT = 10
 18USER_AGENT = "awesome-privacy-ci/1.0"
 19MIN_STARS = 100
 20INACTIVE_DAYS = 90
 21MIN_AGE_DAYS = 120
 22AI_COMMIT_RATIO = 0.2
 23AI_BOT_AUTHORS = [
 24    "noreply@anthropic.com",
 25    "devin-ai-integration[bot]",
 26    "copilot-swe-agent.github.com",
 27    "noreply@cursor.com",
 28]
 29SPAM_AWESOME_THRESHOLD = 3
 30SPAM_DISTINCT_REPO_THRESHOLD = 7
 31SPAM_WINDOW_DAYS = 2
 32NEW_ACCOUNT_DAYS = 14
 33
 34LINK_MSG = (
 35    "The link(s) you included seem to be returning a 404."
 36    " Please double check all URLs listed are valid and publicly accessible"
 37)
 38AUTHOR_MSG = (
 39    "Looks like you are the author of this package. Please ensure that you"
 40    " have clearly disclosed this in your PR body for transparency"
 41)
 42STARS_MSG = (
 43    "It looks like your submission is quite a small project without a lot of users yet."
 44    " In some circumstances we may ask you to resubmit this once the project"
 45    " is more mature and has a proven track record of good practices and maintenance."
 46)
 47ACTIVITY_MSG = (
 48    "Please confirm that the project you are adding is actively maintained,"
 49    " as it looks to not have had any recent updates in the past 3 months."
 50)
 51MATURITY_MSG = (
 52    "This project appears to be quite new (created less than 4 months ago)."
 53    " Repositories should have a proven track record before listing,"
 54    " and at least 16 weeks since first stable release."
 55)
 56AI_CODE_MSG = (
 57    "This project appears to contain AI-generated code."
 58    " Additional care will be needed when reviewing the submission."
 59)
 60FORK_MSG = (
 61    "The GitHub link in this listing is a fork."
 62    " Please confirm it's the correct (and actively maintained) repository"
 63)
 64LICENSE_MSG = (
 65    "There doesn't appear to be a license included in the project's GitHub repo"
 66)
 67ARCHIVED_MSG = (
 68    "The GitHub project linked has been archived."
 69    " Additions must be actively maintained"
 70)
 71SECURITY_MSG = (
 72    "This project has open security vulnerabilities (critical or high severity)"
 73    " flagged by GitHub Dependabot. Please verify these have been addressed"
 74)
 75SPAM_AWESOME_MSG = (
 76    "You have made many similar submissions on other awesome-* repos today."
 77    " Please ensure that your submission is actually a good fit for awesome-privacy"
 78)
 79SPAM_MANY_MSG = (
 80    "The submitter of this PR appears to have been previously flagged as a spammer."
 81    " Caution is needed when reviewing this PR"
 82)
 83NEW_ACCOUNT_MSG = (
 84    "This user has only just joined GitHub."
 85    " New accounts submitting to awesome lists can be a spam signal, careful review needed"
 86)
 87DUPLICATE_URL_MSG = (
 88    "The URL for this submission already exists in another listing."
 89    " Please check that this is not a duplicate entry"
 90)
 91
 92
 93def load_diff(path):
 94    """Load the diff JSON, returning None on any error."""
 95    try:
 96        with open(path) as f:
 97            return json.load(f)
 98    except Exception:
 99        return None
100
101
102def check_url(url):
103    """Return True if the URL is reachable, True on any error (no false positives)."""
104    try:
105        resp = requests.head(
106            url, timeout=TIMEOUT, allow_redirects=True,
107            headers={"User-Agent": USER_AGENT},
108        )
109        if resp.status_code >= 400:
110            resp = requests.get(
111                url, timeout=TIMEOUT, allow_redirects=True,
112                headers={"User-Agent": USER_AGENT}, stream=True,
113            )
114            resp.close()
115        return resp.status_code < 400
116    except Exception:
117        return True
118
119
120def parse_github_field(value):
121    """Parse a github field into (owner, repo), or (None, None) on failure."""
122    if not value:
123        return None, None
124    if value.startswith("https://github.com/"):
125        parts = value.removeprefix("https://github.com/").strip("/").split("/")
126        if len(parts) >= 2:
127            return parts[0], parts[1]
128        return None, None
129    if "/" in value:
130        parts = value.split("/")
131        if len(parts) == 2:
132            return parts[0], parts[1]
133    return None, None
134
135
136def fetch_repo(owner, repo, token):
137    """Fetch GitHub repo metadata, returning None on any error."""
138    try:
139        headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
140        if token:
141            headers["Authorization"] = f"token {token}"
142        resp = requests.get(
143            f"https://api.github.com/repos/{owner}/{repo}",
144            headers=headers, timeout=TIMEOUT,
145        )
146        if resp.status_code == 200:
147            return resp.json()
148    except Exception:
149        pass
150    return None
151
152
153def load_yaml_data():
154    """Load the head YAML, returning None on any error."""
155    try:
156        with open(DATA_PATH) as f:
157            return yaml.safe_load(f)
158    except Exception:
159        return None
160
161
162def find_service_in_head(head, category, section, service_name):
163    """Look up a service in the head YAML by path."""
164    if not head:
165        return None
166    for cat in head.get("categories", []):
167        if cat.get("name") == category:
168            for sec in cat.get("sections", []):
169                if sec.get("name") == section:
170                    for svc in sec.get("services", []):
171                        if svc.get("name") == service_name:
172                            return svc
173    return None
174
175
176def get_services(diff, key):
177    """Safely extract a service list from the diff."""
178    return diff.get("services", {}).get(key, [])
179
180
181def check_links(diff, head):
182    """Return LINK_MSG if any service URL or icon URL is unreachable."""
183    for svc in get_services(diff, "added"):
184        fields = svc.get("fields", {})
185        url = fields.get("url")
186        if url and not check_url(url):
187            return LINK_MSG
188        icon = fields.get("icon")
189        if icon and not check_url(icon):
190            return LINK_MSG
191    for svc in get_services(diff, "modified"):
192        changed = svc.get("changed_fields", [])
193        if "url" not in changed and "icon" not in changed:
194            continue
195        head_svc = find_service_in_head(
196            head, svc["category"], svc["section"], svc["service"]
197        )
198        if head_svc:
199            if "url" in changed:
200                url = head_svc.get("url")
201                if url and not check_url(url):
202                    return LINK_MSG
203            if "icon" in changed:
204                icon = head_svc.get("icon")
205                if icon and not check_url(icon):
206                    return LINK_MSG
207    return None
208
209
210def _commit_has_bot(commit, bot_set):
211    """Check if a commit was authored or co-authored by a known AI bot."""
212    author = commit.get("commit", {}).get("author", {})
213    email = (author.get("email") or "").lower()
214    name = (author.get("name") or "").lower()
215    if email in bot_set or name in bot_set:
216        return True
217    message = (commit.get("commit", {}).get("message") or "").lower()
218    for line in message.splitlines():
219        if line.strip().startswith("co-authored-by:"):
220            if any(bot in line for bot in bot_set):
221                return True
222    return False
223
224
225def check_ai_commits(owner, repo, token):
226    """Return AI_CODE_MSG if recent commits contain significant AI bot activity."""
227    try:
228        headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
229        if token:
230            headers["Authorization"] = f"token {token}"
231        resp = requests.get(
232            f"https://api.github.com/repos/{owner}/{repo}/commits",
233            headers=headers, timeout=TIMEOUT, params={"per_page": 100},
234        )
235        if resp.status_code != 200:
236            return None
237        commits = resp.json()
238        if not commits:
239            return None
240        bot_set = {a.lower() for a in AI_BOT_AUTHORS}
241        count = sum(1 for c in commits if _commit_has_bot(c, bot_set))
242        if count / len(commits) >= AI_COMMIT_RATIO:
243            return AI_CODE_MSG
244    except Exception:
245        pass
246    return None
247
248
249def check_security_alerts(owner, repo, token):
250    """Return SECURITY_MSG if the repo has open critical/high Dependabot alerts."""
251    try:
252        headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
253        if token:
254            headers["Authorization"] = f"token {token}"
255        resp = requests.get(
256            f"https://api.github.com/repos/{owner}/{repo}/dependabot/alerts",
257            headers=headers, timeout=TIMEOUT,
258            params={"state": "open", "severity": "critical,high", "per_page": 1},
259        )
260        if resp.status_code == 200 and resp.json():
261            return SECURITY_MSG
262    except Exception:
263        pass
264    return None
265
266
267def check_spam_prs(pr_user, token):
268    """Return list of spam findings based on recent PR activity."""
269    if not pr_user or not token:
270        return []
271    try:
272        since = (datetime.now(timezone.utc) - timedelta(days=SPAM_WINDOW_DAYS)).strftime("%Y-%m-%d")
273        headers = {
274            "Accept": "application/vnd.github.v3+json",
275            "User-Agent": USER_AGENT,
276            "Authorization": f"token {token}",
277        }
278        resp = requests.get(
279            "https://api.github.com/search/issues",
280            headers=headers, timeout=TIMEOUT,
281            params={"q": f"type:pr author:{pr_user} created:>={since}"},
282        )
283        if resp.status_code != 200:
284            return []
285        items = resp.json().get("items", [])
286        this_repo = os.environ.get("GITHUB_REPOSITORY", "Lissy93/awesome-privacy").lower()
287        awesome_count = 0
288        distinct_repos = set()
289        for item in items:
290            repo_url = item.get("repository_url", "")
291            # repository_url looks like https://api.github.com/repos/owner/repo-name
292            repo_full = "/".join(repo_url.rstrip("/").split("/")[-2:]).lower()
293            if repo_full == this_repo:
294                continue
295            distinct_repos.add(repo_full)
296            repo_name = repo_url.rstrip("/").split("/")[-1].lower()
297            if repo_name.startswith("awesome-"):
298                awesome_count += 1
299        findings = []
300        if awesome_count >= SPAM_AWESOME_THRESHOLD:
301            findings.append(SPAM_AWESOME_MSG)
302        if len(distinct_repos) >= SPAM_DISTINCT_REPO_THRESHOLD:
303            findings.append(SPAM_MANY_MSG)
304        return findings
305    except Exception:
306        return []
307
308
309def check_new_account(pr_user, token):
310    """Return NEW_ACCOUNT_MSG if the PR author's GitHub account is very new."""
311    if not pr_user or not token:
312        return None
313    try:
314        headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
315        headers["Authorization"] = f"token {token}"
316        resp = requests.get(
317            f"https://api.github.com/users/{pr_user}",
318            headers=headers, timeout=TIMEOUT,
319        )
320        if resp.status_code != 200:
321            return None
322        created = resp.json().get("created_at")
323        if not created:
324            return None
325        created_dt = datetime.fromisoformat(created.replace("Z", "+00:00"))
326        if (datetime.now(timezone.utc) - created_dt).days < NEW_ACCOUNT_DAYS:
327            return NEW_ACCOUNT_MSG
328    except Exception:
329        pass
330    return None
331
332
333def check_duplicate_urls(diff, head):
334    """Return DUPLICATE_URL_MSG if an added service's URL already exists in the YAML."""
335    if not head:
336        return None
337    # Count how many times each URL appears in the head YAML
338    url_counts = {}
339    for cat in head.get("categories", []):
340        for sec in cat.get("sections", []):
341            for svc in sec.get("services", []):
342                url = svc.get("url", "").rstrip("/").lower()
343                if url:
344                    url_counts[url] = url_counts.get(url, 0) + 1
345    # The added service is in head already, so a count > 1 means a duplicate exists
346    for svc in get_services(diff, "added"):
347        url = svc.get("fields", {}).get("url", "").rstrip("/").lower()
348        if url and url_counts.get(url, 0) > 1:
349            return DUPLICATE_URL_MSG
350    return None
351
352
353_DISCLOSURE_RE = re.compile(
354    r"i am the author|i'm the author|my project|i created|i develop"
355    r"|i maintain|i built|my own project|i made|author of|maintainer of",
356    re.IGNORECASE,
357)
358
359
360def _pr_discloses_authorship(pr_body):
361    """Return True if the PR body already discloses the submitter is the author."""
362    return bool(pr_body and _DISCLOSURE_RE.search(pr_body))
363
364
365def check_repo_signals(diff, pr_user, token, pr_body=""):
366    """Check GitHub repo author match, stars, and activity for added services."""
367    findings = []
368    if not token:
369        return findings
370    cache = {}
371    for svc in get_services(diff, "added"):
372        gh = svc.get("fields", {}).get("github")
373        owner, repo = parse_github_field(gh)
374        if not owner:
375            continue
376        cache_key = f"{owner}/{repo}"
377        if cache_key not in cache:
378            cache[cache_key] = fetch_repo(owner, repo, token)
379        data = cache[cache_key]
380        if not data:
381            continue
382
383        repo_owner = data.get("owner", {})
384        if (
385            pr_user
386            and repo_owner.get("type") == "User"
387            and repo_owner.get("login", "").lower() == pr_user.lower()
388            and AUTHOR_MSG not in findings
389            and not _pr_discloses_authorship(pr_body)
390        ):
391            findings.append(AUTHOR_MSG)
392
393        stars = data.get("stargazers_count", 0)
394        if stars < MIN_STARS and STARS_MSG not in findings:
395            findings.append(STARS_MSG)
396
397        if data.get("fork") and FORK_MSG not in findings:
398            findings.append(FORK_MSG)
399
400        if not data.get("license") and LICENSE_MSG not in findings:
401            findings.append(LICENSE_MSG)
402
403        if data.get("archived") and ARCHIVED_MSG not in findings:
404            findings.append(ARCHIVED_MSG)
405
406        pushed = data.get("pushed_at")
407        if pushed and ACTIVITY_MSG not in findings:
408            try:
409                pushed_dt = datetime.fromisoformat(pushed.replace("Z", "+00:00"))
410                now = datetime.now(timezone.utc)
411                if (now - pushed_dt).days > INACTIVE_DAYS:
412                    findings.append(ACTIVITY_MSG)
413            except Exception:
414                pass
415
416        created = data.get("created_at")
417        if created and MATURITY_MSG not in findings:
418            try:
419                created_dt = datetime.fromisoformat(created.replace("Z", "+00:00"))
420                now = datetime.now(timezone.utc)
421                if (now - created_dt).days < MIN_AGE_DAYS:
422                    findings.append(MATURITY_MSG)
423            except Exception:
424                pass
425
426        if AI_CODE_MSG not in findings:
427            finding = check_ai_commits(owner, repo, token)
428            if finding:
429                findings.append(finding)
430
431        if SECURITY_MSG not in findings:
432            finding = check_security_alerts(owner, repo, token)
433            if finding:
434                findings.append(finding)
435
436    return findings
437
438
439def main():
440    findings = []
441    try:
442        diff = load_diff(DIFF_PATH)
443        if not diff:
444            with open(FINDINGS_PATH, "w") as f:
445                json.dump(findings, f)
446            sys.exit(0)
447
448        head = load_yaml_data()
449        finding = check_links(diff, head)
450        if finding:
451            findings.append(finding)
452
453        pr_user = os.environ.get("PR_USER", "")
454        pr_body = os.environ.get("PR_BODY", "")
455        token = os.environ.get("GITHUB_TOKEN", "")
456
457        findings.extend(check_spam_prs(pr_user, token))
458
459        finding = check_new_account(pr_user, token)
460        if finding:
461            findings.append(finding)
462
463        finding = check_duplicate_urls(diff, head)
464        if finding:
465            findings.append(finding)
466
467        findings.extend(check_repo_signals(diff, pr_user, token, pr_body))
468    except Exception:
469        pass
470
471    with open(FINDINGS_PATH, "w") as f:
472        json.dump(findings, f)
473    sys.exit(0)
474
475
476if __name__ == "__main__":
477    main()