lib/checks/check-project.py

556 lines · 20766 bytes

23 symbols in this file
  1"""Checks project health: URL reachability, GitHub repo stars, activity, and author match."""
  2
  3import json
  4import logging
  5import os
  6import re
  7import sys
  8from datetime import datetime, timedelta, timezone
  9from urllib.parse import urlparse
 10
 11import yaml
 12
 13sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
 14import utils
 15
 16utils.setup_logging()
 17logger = logging.getLogger(__name__)
 18
 19PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
 20DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
 21DIFF_PATH = "/tmp/pr-diff.json"
 22FINDINGS_PATH = "/tmp/findings-project.json"
 23
 24TIMEOUT = 10
 25USER_AGENT = "awesome-privacy-ci/1.0"
 26# Reachable but blocking automated probes (bot-block/rate-limit), not a missing page.
 27SOFT_HTTP = {401, 403, 405, 406, 429}
 28MIN_STARS = 100
 29INACTIVE_DAYS = 90
 30MIN_AGE_DAYS = 120
 31AI_COMMIT_RATIO = 0.8
 32BUS_FACTOR_RATIO = 0.96
 33SPAM_AWESOME_THRESHOLD = 3
 34SPAM_DISTINCT_REPO_THRESHOLD = 7
 35SPAM_WINDOW_DAYS = 2
 36NEW_ACCOUNT_DAYS = 14
 37TRACKER_LIMIT = 2
 38POOR_PRIVACY_GRADES = {"D", "E"}
 39# The API fetches and scans the page itself, so allow it longer to respond
 40TRACKERS_TIMEOUT = 30
 41# Code hosts and app stores, whose trackers belong to the platform rather than the project
 42PLATFORM_HOSTS = ("github.com", "gitlab.com", "codeberg.org", "play.google.com",
 43                  "apps.apple.com", "addons.mozilla.org", "chromewebstore.google.com")
 44
 45SESSION = utils.make_session(user_agent=USER_AGENT)
 46API_TOKEN = os.environ.get("API_TOKEN", "")
 47
 48LINK_MSG = (
 49    "The link(s) you included seem to be returning a 404."
 50    " Please double check all URLs listed are valid and publicly accessible"
 51)
 52AUTHOR_MSG = (
 53    "Looks like you are the author of this package. Please ensure that you"
 54    " have clearly disclosed this in your PR body for transparency"
 55)
 56STARS_MSG = (
 57    "It looks like your submission is quite a small project without a lot of users yet."
 58    " In some circumstances we may ask you to resubmit this once the project"
 59    " is more mature and has a proven track record of good practices and maintenance."
 60)
 61ACTIVITY_MSG = (
 62    "Please confirm that the project you are adding is actively maintained,"
 63    " as it looks to not have had any recent updates in the past 3 months."
 64)
 65MATURITY_MSG = (
 66    "This project appears to be quite new (created less than 4 months ago)."
 67    " Repositories should have a proven track record before listing,"
 68    " and at least 16 weeks since first stable release."
 69)
 70AI_CODE_MSG = (
 71    "This project appears to contain AI-generated code."
 72    " Additional care will be needed when reviewing the submission."
 73)
 74FORK_MSG = (
 75    "The GitHub link in this listing is a fork."
 76    " Please confirm it's the correct (and actively maintained) repository"
 77)
 78LICENSE_MSG = (
 79    "There doesn't appear to be a license included in the project's GitHub repo"
 80)
 81ARCHIVED_MSG = (
 82    "The GitHub project linked has been archived."
 83    " Additions must be actively maintained"
 84)
 85SECURITY_MSG = (
 86    "This project has published security advisories (critical or high severity)"
 87    " with no patched version listed. Please verify these have been addressed"
 88)
 89SPAM_AWESOME_MSG = (
 90    "You have made many similar submissions on other awesome-* repos today."
 91    " Please ensure that your submission is actually a good fit for awesome-privacy"
 92)
 93SPAM_MANY_MSG = (
 94    "The submitter of this PR appears to have been previously flagged as a spammer."
 95    " Caution is needed when reviewing this PR"
 96)
 97NEW_ACCOUNT_MSG = (
 98    "This user has only just joined GitHub."
 99    " New accounts submitting to awesome lists can be a spam signal, careful review needed"
100)
101DUPLICATE_URL_MSG = (
102    "The URL for this submission already exists in another listing."
103    " Please check that this is not a duplicate entry"
104)
105REPO_404_MSG = (
106    "The GitHub repository linked in this submission returns a 404."
107    " Please ensure the repo exists and is publicly accessible"
108)
109BUS_FACTOR_MSG = (
110    "This repository has a low bus factor, as maintained by a single contributor"
111)
112SECURITY_POLICY_MSG = (
113    "This repository has neither a security policy nor private"
114    " vulnerability reporting enabled, so there's no clear way to report security issues"
115)
116TRACKERS_MSG = (
117    "The Android app contains multiple known trackers, according to Exodus Privacy."
118    " Please confirm these are justified"
119)
120DEGOOGLED_MSG = (
121    "The Android app is reported as broken on de-Googled Android"
122    " (without Google Play Services), according to Plexus"
123)
124PRIVACY_GRADE_MSG = (
125    "The privacy policy for this service is graded as poor by ToS;DR,"
126    " indicating serious privacy concerns"
127)
128WEB_TRACKERS_MSG = (
129    "The website appears to load third-party trackers ({})"
130)
131
132
133def load_diff(path):
134    """Load the diff JSON, returning None on any error."""
135    try:
136        with open(path) as f:
137            return json.load(f)
138    except Exception:
139        return None
140
141
142def check_url(url):
143    """Return True if reachable. Transport errors and bot-block/rate-limit statuses
144    (SOFT_HTTP) count as reachable; only a real bad status (404, 5xx, ...) fails."""
145    ok, status = utils.check_url(url, SESSION, TIMEOUT)
146    if ok or status is None or status in SOFT_HTTP:
147        return True
148    logger.warning("URL check failed for %s (HTTP %d)", url, status)
149    return False
150
151
152def _gh_get(path, token, params=None, label=""):
153    """GET a GitHub API endpoint. Returns parsed JSON on 200, None otherwise."""
154    return utils.gh_get(path, token, session=SESSION, params=params, timeout=TIMEOUT, label=label)
155
156
157def load_yaml_data():
158    """Load the head YAML, returning None on any error."""
159    try:
160        with open(DATA_PATH) as f:
161            return yaml.safe_load(f)
162    except Exception:
163        return None
164
165
166def find_service_in_head(head, category, section, service_name):
167    """Look up a service in the head YAML by path."""
168    if not head:
169        return None
170    for cat in head.get("categories", []):
171        if cat.get("name") == category:
172            for sec in cat.get("sections", []):
173                if sec.get("name") == section:
174                    for svc in sec.get("services", []):
175                        if svc.get("name") == service_name:
176                            return svc
177    return None
178
179
180def get_services(diff, key):
181    """Safely extract a service list from the diff."""
182    return diff.get("services", {}).get(key, [])
183
184
185def check_links(diff, head):
186    """Return LINK_MSG if any service URL or icon URL is unreachable."""
187    for svc in get_services(diff, "added"):
188        fields = svc.get("fields", {})
189        url = fields.get("url")
190        if url and not check_url(url):
191            return LINK_MSG
192        icon = fields.get("icon")
193        if icon and not check_url(icon):
194            return LINK_MSG
195    for svc in get_services(diff, "modified"):
196        changed = svc.get("changed_fields", [])
197        if "url" not in changed and "icon" not in changed:
198            continue
199        head_svc = find_service_in_head(
200            head, svc["category"], svc["section"], svc["service"]
201        )
202        if head_svc:
203            if "url" in changed:
204                url = head_svc.get("url")
205                if url and not check_url(url):
206                    return LINK_MSG
207            if "icon" in changed:
208                icon = head_svc.get("icon")
209                if icon and not check_url(icon):
210                    return LINK_MSG
211    return None
212
213
214def check_ai_commits(owner, repo, token):
215    """Return AI_CODE_MSG if recent commits contain significant AI bot activity."""
216    commits = _gh_get(f"/repos/{owner}/{repo}/commits", token,
217                      params={"per_page": 100}, label="commits")
218    if not commits:
219        return None
220    bot_set = {a.lower() for a in utils.AI_BOT_AUTHORS}
221    count = sum(1 for c in commits if utils.commit_has_bot(c, bot_set))
222    if count / len(commits) >= AI_COMMIT_RATIO:
223        return AI_CODE_MSG
224    return None
225
226
227def check_security_alerts(owner, repo):
228    """Return SECURITY_MSG if the repo has unpatched critical/high security advisories."""
229    try:
230        report = utils.fetch_security_report(owner, repo, API_TOKEN, session=SESSION,
231                                             timeout=TIMEOUT, label=f"{owner}/{repo}")
232        if utils.unpatched_advisories(report)[1]:
233            return SECURITY_MSG
234    except Exception as exc:
235        logger.warning("check_security_alerts error for %s/%s: %s", owner, repo, exc)
236    return None
237
238
239def check_bus_factor(owner, repo, token):
240    """Return BUS_FACTOR_MSG if a single human contributor made nearly all commits."""
241    share = utils.top_contributor_share(owner, repo, token, session=SESSION, timeout=TIMEOUT)
242    if share is not None and share >= BUS_FACTOR_RATIO:
243        return BUS_FACTOR_MSG
244    return None
245
246
247def check_security_policy(owner, repo, token):
248    """Return SECURITY_POLICY_MSG if the repo has no security policy or private reporting."""
249    if utils.has_security_contact(owner, repo, token, session=SESSION, timeout=TIMEOUT) is False:
250        return SECURITY_POLICY_MSG
251    return None
252
253
254def check_android_app(pkg):
255    """Return findings for an Android app with multiple trackers or broken de-Googled support."""
256    findings = []
257    try:
258        app = utils.fetch_android_app(pkg, API_TOKEN, session=SESSION, timeout=TIMEOUT, label=pkg)
259        if (utils.tracker_count(app) or 0) >= TRACKER_LIMIT:
260            findings.append(TRACKERS_MSG)
261        if utils.degoogled_status(app) == "broken":
262            findings.append(DEGOOGLED_MSG)
263    except Exception as exc:
264        logger.warning("check_android_app error for %s: %s", pkg, exc)
265    return findings
266
267
268def check_privacy_grade(tosdr_id):
269    """Return PRIVACY_GRADE_MSG if the service's ToS;DR grade is poor."""
270    try:
271        policy = utils.fetch_privacy(tosdr_id, API_TOKEN, session=SESSION, timeout=TIMEOUT,
272                                     label=str(tosdr_id))
273        if utils.privacy_grade(policy) in POOR_PRIVACY_GRADES:
274            return PRIVACY_GRADE_MSG
275    except Exception as exc:
276        logger.warning("check_privacy_grade error for %s: %s", tosdr_id, exc)
277    return None
278
279
280def _is_platform(url):
281    """True if a URL is on a code host or app store, rather than the project's own site."""
282    host = (urlparse(url).hostname or "").lower()
283    return any(host == h or host.endswith(f".{h}") for h in PLATFORM_HOSTS)
284
285
286def check_website_trackers(url):
287    """Return WEB_TRACKERS_MSG naming the third-party trackers the website loads."""
288    try:
289        if _is_platform(url):
290            logger.info("Tracker check skipped for %s (not the project's own site)", url)
291            return None
292        report = utils.fetch_trackers(url, API_TOKEN, session=SESSION,
293                                      timeout=TRACKERS_TIMEOUT, label=url)
294        if not report:
295            return None
296        if _is_platform(report.get("finalUrl", "")):
297            logger.info("Tracker check skipped for %s (redirects to %s)", url, report["finalUrl"])
298            return None
299        domains = [t["domain"] for t in report.get("trackers", [])]
300        logger.info("Website trackers on %s: %s", url, ", ".join(domains) or "none found")
301        return WEB_TRACKERS_MSG.format(", ".join(domains)) if domains else None
302    except Exception as exc:
303        logger.warning("check_website_trackers error for %s: %s", url, exc)
304        return None
305
306
307def check_privacy_signals(diff):
308    """Check website trackers, Android trackers, de-Googled support and ToS;DR grade for additions."""
309    findings = []
310    for svc in get_services(diff, "added"):
311        fields = svc.get("fields", {})
312        if fields.get("url"):
313            findings.append(check_website_trackers(fields["url"]))
314        if fields.get("androidApp"):
315            findings.extend(check_android_app(fields["androidApp"]))
316        if fields.get("tosdrId"):
317            findings.append(check_privacy_grade(fields["tosdrId"]))
318    return [f for f in dict.fromkeys(findings) if f]
319
320
321def check_spam_prs(pr_user, token):
322    """Return list of spam findings based on recent PR activity."""
323    if not pr_user:
324        logger.warning("check_spam_prs skipped: no PR_USER")
325        return []
326    try:
327        since = (datetime.now(timezone.utc) - timedelta(days=SPAM_WINDOW_DAYS)).strftime("%Y-%m-%d")
328        data = _gh_get("/search/issues", token,
329                       params={"q": f"type:pr author:{pr_user} created:>={since}", "per_page": 100},
330                       label="spam")
331        if not data:
332            return []
333        items = data.get("items", [])
334        logger.info("check_spam_prs: %d total PRs for %s (fetched %d)",
335                     data.get("total_count", 0), pr_user, len(items))
336        this_repo = os.environ.get("GITHUB_REPOSITORY", "Lissy93/awesome-privacy").lower()
337        awesome_count = 0
338        distinct_repos = set()
339        for item in items:
340            repo_url = item.get("repository_url", "")
341            # repository_url looks like https://api.github.com/repos/owner/repo-name
342            repo_full = "/".join(repo_url.rstrip("/").split("/")[-2:]).lower()
343            if repo_full == this_repo:
344                continue
345            distinct_repos.add(repo_full)
346            repo_name = repo_url.rstrip("/").split("/")[-1].lower()
347            if repo_name.startswith("awesome-"):
348                awesome_count += 1
349        logger.info("check_spam_prs: %d awesome-* PRs, %d distinct repos",
350                     awesome_count, len(distinct_repos))
351        findings = []
352        if awesome_count >= SPAM_AWESOME_THRESHOLD:
353            findings.append(SPAM_AWESOME_MSG)
354        if len(distinct_repos) >= SPAM_DISTINCT_REPO_THRESHOLD:
355            findings.append(SPAM_MANY_MSG)
356        return findings
357    except Exception as exc:
358        logger.warning("check_spam_prs error for %s: %s", pr_user, exc)
359        return []
360
361
362def check_new_account(pr_user, token):
363    """Return NEW_ACCOUNT_MSG if the PR author's GitHub account is very new."""
364    if not pr_user:
365        return None
366    data = _gh_get(f"/users/{pr_user}", token, label="user")
367    if not data:
368        return None
369    created = data.get("created_at")
370    if not created:
371        return None
372    try:
373        created_dt = datetime.fromisoformat(created.replace("Z", "+00:00"))
374        if (datetime.now(timezone.utc) - created_dt).days < NEW_ACCOUNT_DAYS:
375            return NEW_ACCOUNT_MSG
376    except Exception:
377        pass
378    return None
379
380
381def check_duplicate_urls(diff, head):
382    """Return DUPLICATE_URL_MSG if an added service's URL already exists in the YAML."""
383    if not head:
384        return None
385    # Count how many times each URL appears in the head YAML
386    url_counts = {}
387    for cat in head.get("categories", []):
388        for sec in cat.get("sections", []):
389            for svc in sec.get("services", []):
390                url = svc.get("url", "").rstrip("/").lower()
391                if url:
392                    url_counts[url] = url_counts.get(url, 0) + 1
393    # The added service is in head already, so a count > 1 means a duplicate exists
394    for svc in get_services(diff, "added"):
395        url = svc.get("fields", {}).get("url", "").rstrip("/").lower()
396        if url and url_counts.get(url, 0) > 1:
397            return DUPLICATE_URL_MSG
398    return None
399
400
401_DISCLOSURE_RE = re.compile(
402    r"i am the author|i'm the author|my project|i created|i develop"
403    r"|i maintain|i built|my own project|i made|author of|maintainer of",
404    re.IGNORECASE,
405)
406
407
408def _pr_discloses_authorship(pr_body):
409    """Return True if the PR body already discloses the submitter is the author."""
410    return bool(pr_body and _DISCLOSURE_RE.search(pr_body))
411
412
413def check_repo_exists(diff, token):
414    """Return REPO_404_MSG if an added service's GitHub repo returns a 404."""
415    seen = set()
416    for svc in get_services(diff, "added"):
417        owner, repo = utils.parse_github_field(svc.get("fields", {}).get("github"))
418        if not owner or (owner, repo) in seen:
419            continue
420        seen.add((owner, repo))
421        if utils.repo_status(owner, repo, token, session=SESSION) == 404:
422            return {"msg": REPO_404_MSG, "level": "error"}
423    return None
424
425
426def check_repo_signals(diff, pr_user, token, pr_body=""):
427    """Check GitHub repo author match, stars, and activity for added services."""
428    findings = []
429    cache = {}
430    for svc in get_services(diff, "added"):
431        gh = svc.get("fields", {}).get("github")
432        owner, repo = utils.parse_github_field(gh)
433        if not owner:
434            continue
435        cache_key = f"{owner}/{repo}"
436        if cache_key not in cache:
437            cache[cache_key] = utils.fetch_repo(owner, repo, token, session=SESSION)
438        data = cache[cache_key]
439        if not data:
440            continue
441
442        repo_owner = data.get("owner", {})
443        if (
444            pr_user
445            and repo_owner.get("type") == "User"
446            and repo_owner.get("login", "").lower() == pr_user.lower()
447            and AUTHOR_MSG not in findings
448            and not _pr_discloses_authorship(pr_body)
449        ):
450            findings.append(AUTHOR_MSG)
451
452        stars = data.get("stargazers_count", 0)
453        if stars < MIN_STARS and STARS_MSG not in findings:
454            findings.append(STARS_MSG)
455
456        if data.get("fork") and FORK_MSG not in findings:
457            findings.append(FORK_MSG)
458
459        if not data.get("license") and LICENSE_MSG not in findings:
460            findings.append(LICENSE_MSG)
461
462        if data.get("archived") and ARCHIVED_MSG not in findings:
463            findings.append(ARCHIVED_MSG)
464
465        pushed = data.get("pushed_at")
466        if pushed and ACTIVITY_MSG not in findings:
467            try:
468                pushed_dt = datetime.fromisoformat(pushed.replace("Z", "+00:00"))
469                now = datetime.now(timezone.utc)
470                if (now - pushed_dt).days > INACTIVE_DAYS:
471                    findings.append(ACTIVITY_MSG)
472            except Exception:
473                pass
474
475        created = data.get("created_at")
476        if created and MATURITY_MSG not in findings:
477            try:
478                created_dt = datetime.fromisoformat(created.replace("Z", "+00:00"))
479                now = datetime.now(timezone.utc)
480                if (now - created_dt).days < MIN_AGE_DAYS:
481                    findings.append(MATURITY_MSG)
482            except Exception:
483                pass
484
485        if AI_CODE_MSG not in findings:
486            finding = check_ai_commits(owner, repo, token)
487            if finding:
488                findings.append(finding)
489
490        if SECURITY_MSG not in findings:
491            finding = check_security_alerts(owner, repo)
492            if finding:
493                findings.append(finding)
494
495        if BUS_FACTOR_MSG not in findings:
496            finding = check_bus_factor(owner, repo, token)
497            if finding:
498                findings.append(finding)
499
500        if SECURITY_POLICY_MSG not in findings:
501            finding = check_security_policy(owner, repo, token)
502            if finding:
503                findings.append(finding)
504
505    return findings
506
507
508def main():
509    findings = []
510    try:
511        pr_user = os.environ.get("PR_USER", "")
512        token = os.environ.get("GITHUB_TOKEN", "")
513        logger.info("Checking project health: links, spam, account age, duplicate URLs, privacy, repo signals")
514        logger.info("PR_USER=%s, GITHUB_TOKEN=%s", pr_user or "(empty)", "present" if token else "MISSING")
515
516        diff = load_diff(DIFF_PATH)
517        if not diff:
518            logger.info("No diff file at %s, nothing to check", DIFF_PATH)
519            with open(FINDINGS_PATH, "w") as f:
520                json.dump(findings, f)
521            sys.exit(0)
522
523        head = load_yaml_data()
524        finding = check_links(diff, head)
525        if finding:
526            findings.append(finding)
527
528        pr_body = os.environ.get("PR_BODY", "")
529
530        findings.extend(check_spam_prs(pr_user, token))
531
532        finding = check_new_account(pr_user, token)
533        if finding:
534            findings.append(finding)
535
536        finding = check_duplicate_urls(diff, head)
537        if finding:
538            findings.append(finding)
539
540        finding = check_repo_exists(diff, token)
541        if finding:
542            findings.append(finding)
543
544        findings.extend(check_privacy_signals(diff))
545        findings.extend(check_repo_signals(diff, pr_user, token, pr_body))
546    except Exception as exc:
547        logger.error("Unhandled error in main: %s", exc, exc_info=True)
548
549    logger.info("Project health: %d finding(s), writing to %s", len(findings), FINDINGS_PATH)
550    with open(FINDINGS_PATH, "w") as f:
551        json.dump(findings, f)
552    sys.exit(0)
553
554
555if __name__ == "__main__":
556    main()