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