lib/review-listings.py
917 lines · 34620 bytes
1#!/usr/bin/env python3
2"""Audit every service in awesome-privacy.yml.
3
4Checks:
5- url-reachable: homepage URL does not 404
6- https-url: homepage URL uses HTTPS
7- icon-reachable: icon URL does not 404
8- description-len: description is 50 to 280 chars (over 420 escalates to warn)
9- opensource-github: openSource listings include a repo link (error); not open source is noted (info)
10- duplicate-url: no URL appears in more than one listing
11- androidApp-valid: androidApp is a package name, not a URL
12- iosApp-valid: iosApp is a valid App Store URL with an app id
13- subreddit-exists: subreddit page exists on reddit.com
14- tosdr-valid: tosdrId still resolves on tosdr.org
15- discord-invite-valid: Discord invite code is still valid
16- github-exists: github repo is accessible (needs token)
17- github-archived: github repo is not archived (needs token)
18- github-activity: github repo was pushed recently (needs token)
19- github-license: github repo has a license (needs token)
20- github-fork: github repo is not a fork (needs token)
21- security-advisories: no open unpatched CVEs (needs API_TOKEN)
22- android-trackers: android app has few trackers (1 info, 2+ warn) (needs API_TOKEN)
23- ios-app: iOS app exists, is maintained and rated (missing/stale/low-rating warn) (needs API_TOKEN)
24- degoogled-compat: android app works on de-googled android (needs API_TOKEN)
25- privacy-grade: tosdr privacy grade is B or better (C info, D/E warn) (needs API_TOKEN)
26
27Findings have three severities: error (must fix), warn (should review), info (FYI).
28HTTP 403/406/429 (and 404 on known bot-blocking hosts such as play.google.com) on
29reachability checks means the probe was rate-limited or blocked, not that the resource is
30missing, so it is logged during the run but left out of the results.
31
32Exit codes:
33 1 when pass rate drops below FAIL_PASS_RATE or errors exceed FAIL_MAX_ERRORS (5)
34 2 you didn't run the script right / something else fucked up
35 0 everything is amazing
36
37Flags:
38- --save-json PATH: save a JSON report to this file
39- --save-markdown PATH: save a markdown report to this file (for GH Actions summaries)
40- --category / --section / --service: narrow to one entry
41- --only / --skip: pick or drop checks by name
42- --severity {all,warn,error}: filter findings
43- --max-workers N: parallel workers (default 8)
44- --timeout N: HTTP timeout in seconds (default 10)
45- --token: GitHub token, else $GITHUB_TOKEN
46- --no-color: disable ANSI colors
47- --list-checks: list checks and exit
48- -v / -q: verbose or quiet logging
49"""
50
51import argparse
52import json
53import logging
54import os
55import re
56import signal
57import sys
58from concurrent.futures import ThreadPoolExecutor, as_completed
59from dataclasses import asdict, dataclass, field
60from datetime import datetime, timezone
61from threading import Lock, local
62from time import monotonic
63from typing import Callable, Iterable
64from urllib.parse import urlparse
65
66sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
67try:
68 import utils
69except ImportError as exc:
70 print(f"ERROR: missing dependency ({exc}). Run `make install_lib_deps`.", file=sys.stderr)
71 sys.exit(2)
72
73MIN_DESC = 50
74MAX_DESC = 280
75MAX_DESC_HARD = 420
76DEFAULT_WORKERS = 8
77DEFAULT_TIMEOUT = 10
78
79# github-activity age bands (days since last push). Order matters: most severe first.
80ACTIVITY_BANDS = (
81 (365 * 8, "error"),
82 (365 * 3, "warn"),
83 (365, "info"),
84)
85
86SEVERITIES = ("error", "warn", "info")
87_SEV_COLOR = {"error": "red", "warn": "yellow", "info": "cyan"}
88_SEV_EMOJI = {"error": "🔴", "warn": "🟠", "info": "🟡"}
89_SOFT_HTTP = {403, 406, 429}
90_SOFT_404_HOSTS = {"play.google.com"}
91_PKG_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$")
92
93FAIL_PASS_RATE = 95.0
94FAIL_MAX_ERRORS = 5
95
96
97@dataclass
98class Entry:
99 category: str
100 section: str
101 service: dict
102
103 @property
104 def name(self):
105 return self.service.get("name", "")
106
107
108@dataclass
109class Finding:
110 category: str
111 section: str
112 service: str
113 check: str
114 severity: str
115 message: str
116
117
118@dataclass
119class Context:
120 token: str
121 timeout: int
122 api_token: str = ""
123 url_occurrences: dict = field(default_factory=dict)
124 repo_cache: dict = field(default_factory=dict)
125 security_cache: dict = field(default_factory=dict)
126 android_cache: dict = field(default_factory=dict)
127 privacy_cache: dict = field(default_factory=dict)
128 ios_cache: dict = field(default_factory=dict)
129 repo_lock: Lock = field(default_factory=Lock)
130 _sessions: local = field(default_factory=local)
131
132 @property
133 def session(self):
134 """Per-thread session, since a requests.Session is not safe to share across threads."""
135 session = getattr(self._sessions, "value", None)
136 if session is None:
137 session = utils.make_session()
138 self._sessions.value = session
139 return session
140
141
142@dataclass
143class CheckSpec:
144 name: str
145 scope: str
146 needs_github: bool
147 needs_api: bool
148 fn: Callable
149 doc: str
150
151
152CHECKS: dict[str, CheckSpec] = {}
153
154
155def check(name, *, scope="service", needs_github=False, needs_api=False):
156 def deco(fn):
157 CHECKS[name] = CheckSpec(
158 name, scope, needs_github, needs_api, fn, (fn.__doc__ or "").strip()
159 )
160 return fn
161 return deco
162
163
164def _finding(entry: Entry, check_name: str, severity: str, message: str) -> Finding:
165 return Finding(entry.category, entry.section, entry.name, check_name, severity, message)
166
167
168def _normalize_url(url: str) -> str:
169 return (url or "").strip().rstrip("/").lower()
170
171
172def _get_repo(entry: Entry, ctx: Context):
173 owner, repo = utils.parse_github_field(entry.service.get("github"))
174 if not owner:
175 return None
176 key = f"{owner}/{repo}"
177 with ctx.repo_lock:
178 if key in ctx.repo_cache:
179 return ctx.repo_cache[key]
180 data = utils.fetch_repo(owner, repo, ctx.token, session=ctx.session)
181 with ctx.repo_lock:
182 ctx.repo_cache[key] = data
183 return data
184
185
186def _get_security_report(entry: Entry, ctx: Context):
187 owner, repo = utils.parse_github_field(entry.service.get("github"))
188 if not owner:
189 return None
190 key = f"{owner}/{repo}"
191 with ctx.repo_lock:
192 if key in ctx.security_cache:
193 return ctx.security_cache[key]
194 data = utils.fetch_security_report(owner, repo, ctx.api_token,
195 session=ctx.session, label=entry.name)
196 with ctx.repo_lock:
197 ctx.security_cache[key] = data
198 return data
199
200
201def _get_android(entry: Entry, ctx: Context):
202 pkg = entry.service.get("androidApp")
203 if not pkg:
204 return None
205 with ctx.repo_lock:
206 if pkg in ctx.android_cache:
207 return ctx.android_cache[pkg]
208 data = utils.fetch_android_app(pkg, ctx.api_token, session=ctx.session, label=entry.name)
209 with ctx.repo_lock:
210 ctx.android_cache[pkg] = data
211 return data
212
213
214def _get_privacy(entry: Entry, ctx: Context):
215 tid = entry.service.get("tosdrId")
216 if not tid:
217 return None
218 key = str(tid)
219 with ctx.repo_lock:
220 if key in ctx.privacy_cache:
221 return ctx.privacy_cache[key]
222 data = utils.fetch_privacy(tid, ctx.api_token, session=ctx.session, label=entry.name)
223 with ctx.repo_lock:
224 ctx.privacy_cache[key] = data
225 return data
226
227
228def _get_ios(entry: Entry, ctx: Context):
229 """Return (report, http_status) for the listing's iOS app, both None if no valid id."""
230 app_id = utils.ios_app_id(entry.service.get("iosApp"))
231 if not app_id:
232 return None, None
233 with ctx.repo_lock:
234 if app_id in ctx.ios_cache:
235 return ctx.ios_cache[app_id]
236 result = utils.fetch_ios(entry.service.get("iosApp"), ctx.api_token,
237 session=ctx.session, label=entry.name, return_status=True)
238 with ctx.repo_lock:
239 ctx.ios_cache[app_id] = result
240 return result
241
242
243def _reachability_finding(entry, check_name, field, url, default_sev, ctx):
244 ok, status = utils.check_url(url, ctx.session, ctx.timeout)
245 if ok:
246 return None
247 host = urlparse(url).netloc.lower()
248 if status in _SOFT_HTTP or (status == 404 and host in _SOFT_404_HOSTS):
249 # Rate-limited or bot-blocked probe, inconclusive so log it but do not report
250 logging.info("%s for %s inconclusive (HTTP %s) possibly just rate-limited/blocked", check_name, url, status)
251 return None
252 detail = f"{url} returned HTTP {status}" if status else f"{url} could not be reached"
253 return _finding(entry, check_name, default_sev, f"{field} is unreachable, {detail}")
254
255
256@check("url-reachable")
257def _url_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
258 """Homepage URL must not 404."""
259 url = entry.service.get("url")
260 if url:
261 f = _reachability_finding(entry, "url-reachable", "url", url, "error", ctx)
262 if f:
263 yield f
264
265
266@check("https-url")
267def _https_url(entry: Entry, ctx: Context) -> Iterable[Finding]:
268 """Homepage URL must use HTTPS."""
269 url = entry.service.get("url", "")
270 if url and not url.startswith("https://"):
271 yield _finding(entry, "https-url", "warn", f"url is not HTTPS: {url}")
272
273
274@check("icon-reachable")
275def _icon_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
276 """Icon URL must not 404."""
277 icon = entry.service.get("icon")
278 if icon:
279 f = _reachability_finding(entry, "icon-reachable", "icon", icon, "warn", ctx)
280 if f:
281 yield f
282
283
284@check("description-len")
285def _description_len(entry: Entry, ctx: Context) -> Iterable[Finding]:
286 """Description length within 50 to 280 characters (over 420 escalates to warn)."""
287 length = len((entry.service.get("description") or "").strip())
288 if length < MIN_DESC:
289 yield _finding(entry, "description-len", "warn",
290 f"description is {length} chars (min {MIN_DESC})")
291 elif length > MAX_DESC_HARD:
292 yield _finding(entry, "description-len", "warn",
293 f"description is {length} chars (max {MAX_DESC_HARD})")
294 elif length > MAX_DESC:
295 yield _finding(entry, "description-len", "info",
296 f"description is {length} chars (target {MIN_DESC} to {MAX_DESC})")
297
298
299@check("opensource-github")
300def _opensource_github(entry: Entry, ctx: Context) -> Iterable[Finding]:
301 """openSource: true needs a repo link (error); not open source is noted (info)."""
302 svc = entry.service
303 has_repo = svc.get("github") or svc.get("codeberg") or svc.get("git")
304 if svc.get("openSource") is True and not has_repo:
305 yield _finding(entry, "opensource-github", "error",
306 "marked openSource but missing a repository link ")
307 elif svc.get("openSource") is False or not has_repo:
308 reason = "openSource is false" if svc.get("openSource") is False else "no repository linked"
309 yield _finding(entry, "opensource-github", "info",
310 f"not open source ({reason})")
311
312
313@check("androidApp-valid")
314def _android_app_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
315 """androidApp must be a package name like com.example.app, not a URL."""
316 val = entry.service.get("androidApp")
317 if val and not _PKG_RE.match(val):
318 yield _finding(entry, "androidApp-valid", "warn",
319 f"androidApp {val} is not a package name (expected com.example.app)")
320
321
322@check("iosApp-valid")
323def _iosapp_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
324 """iosApp must be an App Store URL with an app id."""
325 url = entry.service.get("iosApp")
326 if url and not utils.ios_app_id(url):
327 yield _finding(entry, "iosApp-valid", "warn",
328 f"iosApp {url} is not a valid App Store URL (expected .../idNNNN)")
329
330
331@check("subreddit-exists")
332def _subreddit_exists(entry: Entry, ctx: Context) -> Iterable[Finding]:
333 """Subreddit page must exist."""
334 name = (entry.service.get("subreddit") or "").strip()
335 if not name:
336 return
337 url = f"https://old.reddit.com/r/{name}"
338 f = _reachability_finding(entry, "subreddit-exists", f"r/{name}", url, "info", ctx)
339 if f:
340 yield f
341
342
343@check("tosdr-valid")
344def _tosdr_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
345 """tosdrId must still resolve on tosdr.org."""
346 tid = entry.service.get("tosdrId")
347 if not tid:
348 return
349 url = f"https://tosdr.org/en/service/{tid}"
350 ok, status = utils.check_url(url, ctx.session, ctx.timeout)
351 if not ok:
352 detail = f"HTTP {status}" if status else "not reachable"
353 yield _finding(entry, "tosdr-valid", "info",
354 f"tosdrId {tid} did not validate ({detail})")
355
356
357@check("discord-invite-valid")
358def _discord_invite_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
359 """Discord invite code must still be valid."""
360 code = (entry.service.get("discordInvite") or "").strip()
361 if not code:
362 return
363 url = f"https://discord.com/api/v10/invites/{code}"
364 ok, status = utils.check_url(url, ctx.session, ctx.timeout)
365 if not ok:
366 detail = f"HTTP {status}" if status else "not reachable"
367 yield _finding(entry, "discord-invite-valid", "info",
368 f"discord invite {code} invalid or expired ({detail})")
369
370
371@check("github-exists", needs_github=True)
372def _github_exists(entry: Entry, ctx: Context) -> Iterable[Finding]:
373 """GitHub repo must be accessible."""
374 gh = entry.service.get("github")
375 if not gh:
376 return
377 owner, repo = utils.parse_github_field(gh)
378 if not owner:
379 yield _finding(entry, "github-exists", "warn",
380 f"github field {gh} is not in owner/repo form")
381 return
382 if _get_repo(entry, ctx) is None:
383 yield _finding(entry, "github-exists", "error",
384 f"repo {owner}/{repo} not accessible (deleted, private, or API error)")
385
386
387@check("github-archived", needs_github=True)
388def _github_archived(entry: Entry, ctx: Context) -> Iterable[Finding]:
389 """GitHub repo must not be archived."""
390 if utils.repo_is_archived(_get_repo(entry, ctx)):
391 yield _finding(entry, "github-archived", "error", "repository is archived on GitHub")
392
393
394@check("github-fork", needs_github=True)
395def _github_fork(entry: Entry, ctx: Context) -> Iterable[Finding]:
396 """GitHub repo should not be a fork."""
397 data = _get_repo(entry, ctx)
398 if utils.repo_is_fork(data):
399 parent = (data.get("parent") or {}).get("full_name")
400 suffix = f" of {parent}" if parent else ""
401 yield _finding(entry, "github-fork", "warn", f"repository is a fork{suffix}")
402
403
404@check("github-activity", needs_github=True)
405def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]:
406 """GitHub repo has been pushed to recently (info at 1y, warn at 3y, error at 8y)."""
407 age = utils.repo_pushed_days_ago(_get_repo(entry, ctx))
408 if age is None:
409 return
410 for threshold, sev in ACTIVITY_BANDS:
411 if age >= threshold:
412 yield _finding(entry, "github-activity", sev, f"last push {age} days ago")
413 return
414
415
416@check("github-license", needs_github=True)
417def _github_license(entry: Entry, ctx: Context) -> Iterable[Finding]:
418 """GitHub repo must have a declared license."""
419 data = _get_repo(entry, ctx)
420 if data and not utils.repo_has_license(data):
421 yield _finding(entry, "github-license", "warn", "repository has no declared license")
422
423
424@check("security-advisories", needs_api=True)
425def _security_advisories(entry: Entry, ctx: Context) -> Iterable[Finding]:
426 """No open unpatched CVEs (low/medium warn, high/critical error)."""
427 if not entry.service.get("github"):
428 return
429 low_med, high_crit = utils.unpatched_advisories(_get_security_report(entry, ctx))
430 if high_crit:
431 yield _finding(entry, "security-advisories", "error",
432 f"{high_crit} open high/critical "
433 f"advisor{'ies' if high_crit != 1 else 'y'}")
434 if low_med:
435 yield _finding(entry, "security-advisories", "warn",
436 f"{low_med} open low/medium "
437 f"advisor{'ies' if low_med != 1 else 'y'}")
438
439
440@check("android-trackers", needs_api=True)
441def _android_trackers(entry: Entry, ctx: Context) -> Iterable[Finding]:
442 """Android app has few trackers (1 info, 2+ warn)."""
443 if not entry.service.get("androidApp"):
444 return
445 count = utils.tracker_count(_get_android(entry, ctx))
446 if not count:
447 return
448 sev = "info" if count == 1 else "warn"
449 yield _finding(entry, "android-trackers", sev,
450 f"Android app reports {count} tracker{'s' if count != 1 else ''}")
451
452
453@check("ios-app", needs_api=True)
454def _ios_app(entry: Entry, ctx: Context) -> Iterable[Finding]:
455 """iOS app exists, is maintained and rated (missing/stale/<2 stars warn)."""
456 if not utils.ios_app_id(entry.service.get("iosApp")):
457 return
458 report, status = _get_ios(entry, ctx)
459 if status == 404:
460 yield _finding(entry, "ios-app", "warn",
461 "iOS app not found on the App Store (may have been removed)")
462 return
463 days = utils.ios_days_since_update(report)
464 if days is not None and days >= 365:
465 yield _finding(entry, "ios-app", "warn",
466 f"iOS app not updated in over a year (last release {days} days ago)")
467 rating, count = utils.ios_rating(report)
468 if count and rating is not None and rating < 2:
469 yield _finding(entry, "ios-app", "warn",
470 f"iOS app is rated below 2 stars ({rating:.1f} from {count:,} ratings)")
471
472
473@check("degoogled-compat", needs_api=True)
474def _degoogled_compat(entry: Entry, ctx: Context) -> Iterable[Finding]:
475 """Android app works on de-Googled Android (broken warn, limited info)."""
476 if not entry.service.get("androidApp"):
477 return
478 status = utils.degoogled_status(_get_android(entry, ctx))
479 if status == "broken":
480 yield _finding(entry, "degoogled-compat", "warn",
481 "Android app is broken on de-Googled Android")
482 elif status == "bronze":
483 yield _finding(entry, "degoogled-compat", "info",
484 "Android app has limited de-Googled support")
485
486
487@check("privacy-grade", needs_api=True)
488def _privacy_grade(entry: Entry, ctx: Context) -> Iterable[Finding]:
489 """ToS;DR privacy grade is B or better (C info, D/E warn)."""
490 if not entry.service.get("tosdrId"):
491 return
492 grade = utils.privacy_grade(_get_privacy(entry, ctx))
493 if grade == "C":
494 yield _finding(entry, "privacy-grade", "info", "privacy policy has minor concerns")
495 elif grade in ("D", "E"):
496 yield _finding(entry, "privacy-grade", "warn", f"privacy policy has major issues (graded: {grade})")
497
498
499@check("duplicate-url", scope="global")
500def _duplicate_url(entries, ctx: Context) -> Iterable[Finding]:
501 """No two listings share the same homepage URL."""
502 in_scope = {(e.category, e.section, e.name) for e in entries}
503 for url, matches in ctx.url_occurrences.items():
504 if len(matches) <= 1:
505 continue
506 for me in matches:
507 if (me.category, me.section, me.name) not in in_scope:
508 continue
509 others = [e for e in matches if e is not me]
510 shown = ", ".join(f"{e.category} > {e.section}: {e.name}" for e in others[:2])
511 if len(others) > 2:
512 shown += f" (+{len(others) - 2} more)"
513 yield _finding(me, "duplicate-url", "warn",
514 f"URL {url} also used by {shown}")
515
516
517_interrupted = False
518
519
520def _install_sigint():
521 def handler(signum, frame):
522 global _interrupted
523 if _interrupted:
524 raise KeyboardInterrupt
525 _interrupted = True
526 logging.warning("Interrupt received, finishing in-flight checks (Ctrl-C again to abort)")
527 signal.signal(signal.SIGINT, handler)
528
529
530def build_context(args, data, token, api_token):
531 ctx = Context(
532 token=token,
533 timeout=args.timeout,
534 api_token=api_token,
535 )
536 for cat, sec, svc in utils.iter_services(data):
537 url = _normalize_url(svc.get("url"))
538 if url:
539 ctx.url_occurrences.setdefault(url, []).append(Entry(cat, sec, svc))
540 return ctx
541
542
543def changed_service_keys(ref, head):
544 """Return {(category, section, name)} for services added or modified vs a git ref."""
545 from yaml_diff import build_index, diff_index, load_yaml_at_ref
546 base = load_yaml_at_ref(ref)
547 if base is None:
548 logging.error("Could not read awesome-privacy.yml at git ref %s", ref)
549 sys.exit(2)
550 added, _, modified = diff_index(build_index(base, 3), build_index(head, 3))
551 return set(added) | {k for k, _ in modified}
552
553
554def filter_entries(data, args):
555 for cat, sec, svc in utils.iter_services(data):
556 if args.category and args.category.lower() != cat.lower():
557 continue
558 if args.section and args.section.lower() != sec.lower():
559 continue
560 if args.service and args.service.lower() != svc.get("name", "").lower():
561 continue
562 yield Entry(cat, sec, svc)
563
564
565def _run_one(entry, enabled, ctx):
566 findings = []
567 for name in enabled:
568 spec = CHECKS[name]
569 if spec.scope != "service":
570 continue
571 try:
572 findings.extend(spec.fn(entry, ctx) or [])
573 except Exception as exc:
574 logging.warning("check %s on %s failed: %s", name, entry.name, exc)
575 return findings
576
577
578def _run_global(enabled, entries, ctx):
579 findings = []
580 for name in enabled:
581 spec = CHECKS[name]
582 if spec.scope != "global":
583 continue
584 try:
585 findings.extend(spec.fn(entries, ctx) or [])
586 except Exception as exc:
587 logging.warning("global check %s failed: %s", name, exc)
588 return findings
589
590
591def run_checks(entries, enabled, ctx, workers):
592 findings = []
593 total = len(entries)
594 with ThreadPoolExecutor(max_workers=workers) as ex:
595 futures = {ex.submit(_run_one, e, enabled, ctx): e for e in entries}
596 for i, fut in enumerate(as_completed(futures), start=1):
597 if _interrupted:
598 ex.shutdown(wait=False, cancel_futures=True)
599 break
600 try:
601 findings.extend(fut.result())
602 except Exception as exc:
603 logging.warning("worker error: %s", exc)
604 if i % 25 == 0 or i == total:
605 logging.info("Progress: %d/%d services reviewed", i, total)
606 findings.extend(_run_global(enabled, entries, ctx))
607 return findings
608
609
610def _sev_color(severity, colors):
611 return colors[_SEV_COLOR.get(severity, "yellow")]
612
613
614def _compute_summary(findings, entries, enabled, elapsed):
615 n_services = len(entries)
616 total_checks = n_services * len(enabled)
617 failed = {(f.category, f.section, f.service, f.check) for f in findings}
618 passed_checks = total_checks - len(failed)
619 pass_rate = (passed_checks / total_checks * 100) if total_checks else 100.0
620 services_with_findings = {(f.category, f.section, f.service) for f in findings}
621 return {
622 "services_scanned": n_services,
623 "services_passed": n_services - len(services_with_findings),
624 "total_checks": total_checks,
625 "passed_checks": passed_checks,
626 "pass_rate": round(pass_rate, 1),
627 "findings": len(findings),
628 "errors": sum(1 for f in findings if f.severity == "error"),
629 "warnings": sum(1 for f in findings if f.severity == "warn"),
630 "info": sum(1 for f in findings if f.severity == "info"),
631 "elapsed_seconds": round(elapsed, 2),
632 }
633
634
635_SUMMARY_ROWS = (("errors", "error"), ("warnings", "warn"), ("info", "info"))
636
637
638def _summary(s, colors):
639 parts = ", ".join(
640 colors[_SEV_COLOR[sev]](f"{s[key]} {key}") if s[key] else f"0 {key}"
641 for key, sev in _SUMMARY_ROWS
642 )
643 return "\n".join([
644 colors["bold"]("Summary"),
645 "-------",
646 f"{s['services_scanned']} listings scanned "
647 f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)",
648 f"{s['findings']} findings ({parts})",
649 f"{s['services_passed']} listings passed all checks",
650 f"Took {s['elapsed_seconds']:.1f}s",
651 ])
652
653
654def _markdown_summary(s):
655 return "\n".join([
656 "### Summary",
657 "",
658 f"- ℹ️ {s['services_scanned']} listings scanned "
659 f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)",
660 f"- ⚠️ {s['findings']} findings "
661 f"({s['errors']} errors, {s['warnings']} warnings, {s['info']} info)",
662 f"- ✅ {s['services_passed']} listings passed all checks",
663 f"- ⏱️ Triggered at {s['triggered_at']}, took {s['elapsed_seconds']:.1f}s",
664 ])
665
666
667def render_list(findings, colors, summary):
668 lines = ["", colors["bold"]("Findings"), "--------"]
669 if not findings:
670 lines.append(colors["green"]("✓ All services passed."))
671 grouped: dict = {}
672 for f in findings:
673 grouped.setdefault((f.category, f.section, f.service), []).append(f)
674 for (cat, sec, name), items in grouped.items():
675 lines.append(f"{colors['bold'](name)} {colors['dim'](f'({cat} > {sec})')}")
676 for f in items:
677 badge = _sev_color(f.severity, colors)(f"[{f.severity.upper():<5}]")
678 lines.append(f" {badge} {colors['cyan'](f.check.ljust(20))} {f.message}")
679 lines.append("")
680 lines.append(_summary(summary, colors))
681 return "\n".join(lines)
682
683
684def render_json(findings, colors, summary):
685 return json.dumps(
686 {"summary": summary, "findings": [asdict(f) for f in findings]},
687 indent=2,
688 )
689
690
691_MD_URL_RE = re.compile(r"https?://[^\s)\]]+")
692_URL_TRAIL = ".,;:!?"
693
694
695def _md_message(msg, url_limit=42):
696 def shorten(m):
697 url = m.group()
698 trail = ""
699 while url and url[-1] in _URL_TRAIL:
700 trail = url[-1] + trail
701 url = url[:-1]
702 label = url if len(url) <= url_limit else url[:url_limit - 3] + "..."
703 return f"[`{label}`]({url}){trail}"
704 return _MD_URL_RE.sub(shorten, msg)
705
706
707def render_markdown(findings, colors, summary):
708 def cell(s):
709 return str(s).replace("|", "\\|").replace("\n", " ")
710
711 lines = []
712
713 lines += ["# Awesome Privacy Auto Checks", ""]
714
715 need_review = summary["findings"] - summary["errors"]
716 lines += [
717 f"_Ran {summary['total_checks']} checks across {summary['services_scanned']} "
718 f"listings, with a {summary['pass_rate']:.1f}% pass rate._",
719 f"_{summary['errors']} issues require action, plus another {need_review} "
720 f"findings need reviewing._",
721 "",
722 ]
723
724 errors = [f for f in findings if f.severity == "error"]
725 if errors:
726 lines += ["### Critical Issues", ""]
727 for f in errors:
728 lines.append(
729 f"- {_SEV_EMOJI[f.severity]} **{cell(f.service)}** - "
730 f"{_md_message(cell(f.message))}"
731 )
732 lines.append("")
733
734 lines += [
735 "---",
736 "",
737 "### Full Issue List",
738 "",
739 "| Service | Review Required |",
740 "|---|---|",
741 ]
742 grouped: dict = {}
743 for f in findings:
744 grouped.setdefault((f.category, f.section, f.service), []).append(f)
745 for (cat, sec, name), items in grouped.items():
746 review = "<br>".join(
747 f"{_SEV_EMOJI[f.severity]} {_md_message(cell(f.message))}"
748 for f in items
749 )
750 link = f"https://awesome-privacy.xyz/{utils.slugify(cat)}/{utils.slugify(sec)}/{utils.slugify(name)}"
751 lines.append(
752 f"| **{cell(name)}** [↗]({link})<br>"
753 f"<sup>{cell(cat)} > {cell(sec)}</sup> | {review} |"
754 )
755 lines += ["", "---", "", _markdown_summary(summary)]
756 lines += [
757 "",
758 "> [!IMPORTANT]",
759 "> The automated checks can produce false positives, fail to include real issues, and does not "
760 "take the context of the listings into account. Careful human review is needed!",
761 ""
762 ]
763 return "\n".join(lines)
764
765
766def _csv(s):
767 return [x.strip() for x in s.split(",") if x.strip()]
768
769
770def parse_args():
771 p = argparse.ArgumentParser(
772 description="Review all listings in awesome-privacy.yml against our criteria.",
773 )
774 p.add_argument("--save-json", metavar="PATH", help="save a JSON report to this file")
775 p.add_argument("--save-markdown", metavar="PATH",
776 help="save a markdown report to this file (for GH Actions summaries)")
777 p.add_argument("--category", help="filter to a single category")
778 p.add_argument("--section", help="filter to a single section")
779 p.add_argument("--service", help="filter to a single service")
780 p.add_argument("--changed-since", metavar="REF",
781 help="only review services added or modified vs this git ref (e.g. main)")
782 p.add_argument("--only", type=_csv, default=[], help="comma-separated checks to run")
783 p.add_argument("--skip", type=_csv, default=[], help="comma-separated checks to skip")
784 p.add_argument("--severity", choices=["all", "warn", "error"], default="all")
785 p.add_argument("--max-workers", type=int, default=DEFAULT_WORKERS)
786 p.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT)
787 p.add_argument("--token", help="GitHub token (else $GITHUB_TOKEN)")
788 p.add_argument("--no-color", action="store_true")
789 p.add_argument("--list-checks", action="store_true", help="list available checks and exit")
790 p.add_argument("-v", "--verbose", action="store_true")
791 p.add_argument("-q", "--quiet", action="store_true")
792 return p.parse_args()
793
794
795def resolve_enabled(only, skip):
796 unknown = [n for n in only + skip if n not in CHECKS]
797 if unknown:
798 logging.error("Unknown check(s): %s. Available: %s",
799 ", ".join(unknown), ", ".join(CHECKS))
800 sys.exit(2)
801 enabled = list(only) if only else list(CHECKS)
802 return [n for n in enabled if n not in skip]
803
804
805def filter_severity(findings, level):
806 if level == "error":
807 return [f for f in findings if f.severity == "error"]
808 if level == "warn":
809 return [f for f in findings if f.severity in ("warn", "error")]
810 return findings
811
812
813def main():
814 _install_sigint()
815 args = parse_args()
816 utils.setup_logging("DEBUG" if args.verbose else "WARNING" if args.quiet else "INFO")
817 colors = utils.make_colors(enabled=False if args.no_color else None)
818
819 if args.list_checks:
820 for name, spec in CHECKS.items():
821 tag = colors["dim"](" (needs GITHUB_TOKEN)") if spec.needs_github else ""
822 tag += colors["dim"](" (needs API_TOKEN)") if spec.needs_api else ""
823 print(f" {colors['cyan'](name.ljust(22))} {spec.doc}{tag}")
824 return
825
826 enabled = resolve_enabled(args.only, args.skip)
827 token = args.token or os.environ.get("GITHUB_TOKEN", "")
828 api_token = os.environ.get("API_TOKEN", "")
829
830 # A targeted review (single entry/diff) runs external checks unauthenticated, as probz won't hit rate limit
831 targeted = bool(args.service or args.category or args.section or args.changed_since)
832
833 if not token:
834 gh_checks = [n for n in enabled if CHECKS[n].needs_github]
835 if gh_checks and not targeted:
836 logging.warning(
837 "GITHUB_TOKEN not set, skipping GitHub checks (%s) for a full review. "
838 "Export GITHUB_TOKEN, or narrow with --service/--category/--changed-since.",
839 ", ".join(gh_checks),
840 )
841 enabled = [n for n in enabled if not CHECKS[n].needs_github]
842 elif gh_checks:
843 logging.info("GITHUB_TOKEN not set, running GitHub checks unauthenticated (may be rate-limited)")
844
845 if not api_token:
846 api_checks = [n for n in enabled if CHECKS[n].needs_api]
847 if api_checks and not targeted:
848 logging.warning(
849 "API_TOKEN not set, skipping API checks (%s) for a full review. "
850 "Export API_TOKEN, or narrow the review to run them.",
851 ", ".join(api_checks),
852 )
853 enabled = [n for n in enabled if not CHECKS[n].needs_api]
854 elif api_checks:
855 logging.info("API_TOKEN not set, running API checks unauthenticated (may be rate-limited)")
856
857 if not enabled:
858 logging.error("No checks to run after filters.")
859 sys.exit(2)
860
861 try:
862 data = utils.load_yaml()
863 except FileNotFoundError:
864 logging.error("awesome-privacy.yml not found at %s", utils.DATA_PATH)
865 sys.exit(2)
866 except Exception as exc:
867 logging.error("Failed to parse awesome-privacy.yml: %s", exc)
868 sys.exit(2)
869
870 entries = list(filter_entries(data, args))
871 if args.changed_since:
872 keys = changed_service_keys(args.changed_since, data)
873 entries = [e for e in entries if (e.category, e.section, e.name) in keys]
874 if not entries:
875 logging.info("No added or modified services since %s, nothing to review",
876 args.changed_since)
877 return
878 if not entries:
879 logging.error("No services matched filters (category=%s, section=%s, service=%s)",
880 args.category, args.section, args.service)
881 sys.exit(2)
882
883 ctx = build_context(args, data, token, api_token)
884 logging.info("Reviewing %d service(s) with %d check(s): %s",
885 len(entries), len(enabled), ", ".join(enabled))
886
887 triggered_at = datetime.now(timezone.utc)
888 start = monotonic()
889 findings = run_checks(entries, enabled, ctx, args.max_workers)
890 elapsed = monotonic() - start
891
892 summary = _compute_summary(findings, entries, enabled, elapsed)
893 summary["triggered_at"] = triggered_at.strftime("%Y-%m-%d %H:%M UTC")
894 display = filter_severity(findings, args.severity)
895 display.sort(key=lambda f: (f.category, f.section, f.service, f.check))
896
897 print(render_list(display, colors, summary))
898
899 for path, renderer in (
900 (args.save_json, render_json),
901 (args.save_markdown, render_markdown),
902 ):
903 if not path:
904 continue
905 try:
906 with open(path, "w") as f:
907 f.write(renderer(display, colors, summary) + "\n")
908 logging.info("Wrote %s", path)
909 except OSError as exc:
910 logging.warning("Could not write %s: %s", path, exc)
911
912 fail = summary["pass_rate"] < FAIL_PASS_RATE or summary["errors"] > FAIL_MAX_ERRORS
913 sys.exit(1 if fail else 0)
914
915
916if __name__ == "__main__":
917 main()