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