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