lib/checks/check-project.py

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