lib/checks/check-project.py

410 lines · 14529 bytes

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