lib/review-listings.py

708 lines · 25066 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 github field
 10- duplicate-url: no URL appears in more than one listing
 11- androidApp-valid: androidApp is a package name, not a URL
 12- iosApp-reachable: App Store URL resolves
 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
 22Findings have three severities: error (must fix), warn (should review), info (FYI).
 23HTTP 403/429 on reachability checks is demoted from error to warn (bot-blocking).
 24
 25Flags:
 26- --save-json PATH: save a JSON report to this file
 27- --save-markdown PATH: save a markdown report to this file (for GH Actions summaries)
 28- --category / --section / --service: narrow to one entry
 29- --only / --skip: pick or drop checks by name
 30- --severity {all,warn,error}: filter findings
 31- --max-workers N: parallel workers (default 8)
 32- --timeout N: HTTP timeout in seconds (default 10)
 33- --token: GitHub token, else $GITHUB_TOKEN
 34- --no-color: disable ANSI colors
 35- --list-checks: list checks and exit
 36- -v / -q: verbose or quiet logging
 37"""
 38
 39import argparse
 40import json
 41import logging
 42import os
 43import re
 44import signal
 45import sys
 46from concurrent.futures import ThreadPoolExecutor, as_completed
 47from dataclasses import asdict, dataclass, field
 48from datetime import datetime, timezone
 49from threading import Lock
 50from time import monotonic
 51from typing import Callable, Iterable
 52
 53sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
 54try:
 55    import utils
 56except ImportError as exc:
 57    print(f"ERROR: missing dependency ({exc}). Run `make install_lib_deps`.", file=sys.stderr)
 58    sys.exit(2)
 59
 60MIN_DESC = 50
 61MAX_DESC = 280
 62MAX_DESC_HARD = 420
 63DEFAULT_WORKERS = 8
 64DEFAULT_TIMEOUT = 10
 65
 66# github-activity age bands (days since last push). Order matters: most severe first.
 67ACTIVITY_BANDS = (
 68    (365 * 8, "error"),
 69    (365 * 3, "warn"),
 70    (365,     "info"),
 71)
 72
 73SEVERITIES = ("error", "warn", "info")
 74_SEV_COLOR = {"error": "red", "warn": "yellow", "info": "cyan"}
 75_SEV_EMOJI = {"error": "🔴", "warn": "🟠", "info": "🟡"}
 76_SOFT_HTTP = {403, 429}
 77_PKG_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$")
 78
 79
 80@dataclass
 81class Entry:
 82    category: str
 83    section: str
 84    service: dict
 85
 86    @property
 87    def name(self):
 88        return self.service.get("name", "")
 89
 90
 91@dataclass
 92class Finding:
 93    category: str
 94    section: str
 95    service: str
 96    check: str
 97    severity: str
 98    message: str
 99
100
101@dataclass
102class Context:
103    session: object
104    token: str
105    timeout: int
106    url_occurrences: dict = field(default_factory=dict)
107    repo_cache: dict = field(default_factory=dict)
108    repo_lock: Lock = field(default_factory=Lock)
109
110
111@dataclass
112class CheckSpec:
113    name: str
114    scope: str
115    needs_github: bool
116    fn: Callable
117    doc: str
118
119
120CHECKS: dict[str, CheckSpec] = {}
121
122
123def check(name, *, scope="service", needs_github=False):
124    def deco(fn):
125        CHECKS[name] = CheckSpec(name, scope, needs_github, fn, (fn.__doc__ or "").strip())
126        return fn
127    return deco
128
129
130def _finding(entry: Entry, check_name: str, severity: str, message: str) -> Finding:
131    return Finding(entry.category, entry.section, entry.name, check_name, severity, message)
132
133
134def _normalize_url(url: str) -> str:
135    return (url or "").strip().rstrip("/").lower()
136
137
138def _get_repo(entry: Entry, ctx: Context):
139    owner, repo = utils.parse_github_field(entry.service.get("github"))
140    if not owner:
141        return None
142    key = f"{owner}/{repo}"
143    with ctx.repo_lock:
144        if key in ctx.repo_cache:
145            return ctx.repo_cache[key]
146    data = utils.fetch_repo(owner, repo, ctx.token, session=ctx.session)
147    with ctx.repo_lock:
148        ctx.repo_cache[key] = data
149    return data
150
151
152def _unreachable(field, url, status, default_sev):
153    """Return (severity, message). 403/429 demote error to warn."""
154    sev = "warn" if default_sev == "error" and status in _SOFT_HTTP else default_sev
155    detail = f"{url} returned HTTP {status}" if status else f"{url} could not be reached"
156    return sev, f"{field} is unreachable, {detail}"
157
158
159def _reachability_finding(entry, check_name, field, url, default_sev, ctx):
160    ok, status = utils.check_url(url, ctx.session, ctx.timeout)
161    if ok:
162        return None
163    sev, msg = _unreachable(field, url, status, default_sev)
164    return _finding(entry, check_name, sev, msg)
165
166
167@check("url-reachable")
168def _url_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
169    """Homepage URL must not 404."""
170    url = entry.service.get("url")
171    if url:
172        f = _reachability_finding(entry, "url-reachable", "url", url, "error", ctx)
173        if f:
174            yield f
175
176
177@check("https-url")
178def _https_url(entry: Entry, ctx: Context) -> Iterable[Finding]:
179    """Homepage URL must use HTTPS."""
180    url = entry.service.get("url", "")
181    if url and not url.startswith("https://"):
182        yield _finding(entry, "https-url", "warn", f"url is not HTTPS: {url}")
183
184
185@check("icon-reachable")
186def _icon_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
187    """Icon URL must not 404."""
188    icon = entry.service.get("icon")
189    if icon:
190        f = _reachability_finding(entry, "icon-reachable", "icon", icon, "warn", ctx)
191        if f:
192            yield f
193
194
195@check("description-len")
196def _description_len(entry: Entry, ctx: Context) -> Iterable[Finding]:
197    """Description length within 50 to 280 characters (over 420 escalates to warn)."""
198    length = len((entry.service.get("description") or "").strip())
199    if length < MIN_DESC:
200        yield _finding(entry, "description-len", "warn",
201                       f"description is {length} chars (min {MIN_DESC})")
202    elif length > MAX_DESC_HARD:
203        yield _finding(entry, "description-len", "warn",
204                       f"description is {length} chars (max {MAX_DESC_HARD})")
205    elif length > MAX_DESC:
206        yield _finding(entry, "description-len", "info",
207                       f"description is {length} chars (target {MIN_DESC} to {MAX_DESC})")
208
209
210@check("opensource-github")
211def _opensource_github(entry: Entry, ctx: Context) -> Iterable[Finding]:
212    """openSource: true services must include a github field."""
213    if entry.service.get("openSource") is True and not entry.service.get("github"):
214        yield _finding(entry, "opensource-github", "warn",
215                       "marked openSource but missing `github` field")
216
217
218@check("androidApp-valid")
219def _android_app_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
220    """androidApp must be a package name like com.example.app, not a URL."""
221    val = entry.service.get("androidApp")
222    if val and not _PKG_RE.match(val):
223        yield _finding(entry, "androidApp-valid", "warn",
224                       f"androidApp {val} is not a package name (expected com.example.app)")
225
226
227@check("iosApp-reachable")
228def _iosapp_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]:
229    """iOS App Store link must resolve."""
230    url = entry.service.get("iosApp")
231    if url:
232        f = _reachability_finding(entry, "iosApp-reachable", "iosApp", url, "warn", ctx)
233        if f:
234            yield f
235
236
237@check("subreddit-exists")
238def _subreddit_exists(entry: Entry, ctx: Context) -> Iterable[Finding]:
239    """Subreddit page must exist."""
240    name = (entry.service.get("subreddit") or "").strip()
241    if not name:
242        return
243    url = f"https://old.reddit.com/r/{name}"
244    f = _reachability_finding(entry, "subreddit-exists", f"r/{name}", url, "info", ctx)
245    if f:
246        yield f
247
248
249@check("tosdr-valid")
250def _tosdr_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
251    """tosdrId must still resolve on tosdr.org."""
252    tid = entry.service.get("tosdrId")
253    if not tid:
254        return
255    url = f"https://tosdr.org/en/service/{tid}"
256    ok, status = utils.check_url(url, ctx.session, ctx.timeout)
257    if not ok:
258        detail = f"HTTP {status}" if status else "not reachable"
259        yield _finding(entry, "tosdr-valid", "info",
260                       f"tosdrId {tid} did not validate ({detail})")
261
262
263@check("discord-invite-valid")
264def _discord_invite_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
265    """Discord invite code must still be valid."""
266    code = (entry.service.get("discordInvite") or "").strip()
267    if not code:
268        return
269    url = f"https://discord.com/api/v10/invites/{code}"
270    ok, status = utils.check_url(url, ctx.session, ctx.timeout)
271    if not ok:
272        detail = f"HTTP {status}" if status else "not reachable"
273        yield _finding(entry, "discord-invite-valid", "info",
274                       f"discord invite {code} invalid or expired ({detail})")
275
276
277@check("github-exists", needs_github=True)
278def _github_exists(entry: Entry, ctx: Context) -> Iterable[Finding]:
279    """GitHub repo must be accessible."""
280    gh = entry.service.get("github")
281    if not gh:
282        return
283    owner, repo = utils.parse_github_field(gh)
284    if not owner:
285        yield _finding(entry, "github-exists", "warn",
286                       f"github field {gh} is not in owner/repo form")
287        return
288    if _get_repo(entry, ctx) is None:
289        yield _finding(entry, "github-exists", "error",
290                       f"repo {owner}/{repo} not accessible (deleted, private, or API error)")
291
292
293@check("github-archived", needs_github=True)
294def _github_archived(entry: Entry, ctx: Context) -> Iterable[Finding]:
295    """GitHub repo must not be archived."""
296    if utils.repo_is_archived(_get_repo(entry, ctx)):
297        yield _finding(entry, "github-archived", "error", "repository is archived on GitHub")
298
299
300@check("github-fork", needs_github=True)
301def _github_fork(entry: Entry, ctx: Context) -> Iterable[Finding]:
302    """GitHub repo should not be a fork."""
303    data = _get_repo(entry, ctx)
304    if utils.repo_is_fork(data):
305        parent = (data.get("parent") or {}).get("full_name")
306        suffix = f" of {parent}" if parent else ""
307        yield _finding(entry, "github-fork", "warn", f"repository is a fork{suffix}")
308
309
310@check("github-activity", needs_github=True)
311def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]:
312    """GitHub repo has been pushed to recently (info at 1y, warn at 3y, error at 8y)."""
313    age = utils.repo_pushed_days_ago(_get_repo(entry, ctx))
314    if age is None:
315        return
316    for threshold, sev in ACTIVITY_BANDS:
317        if age >= threshold:
318            yield _finding(entry, "github-activity", sev, f"last push {age} days ago")
319            return
320
321
322@check("github-license", needs_github=True)
323def _github_license(entry: Entry, ctx: Context) -> Iterable[Finding]:
324    """GitHub repo must have a declared license."""
325    data = _get_repo(entry, ctx)
326    if data and not utils.repo_has_license(data):
327        yield _finding(entry, "github-license", "warn", "repository has no declared license")
328
329
330@check("duplicate-url", scope="global")
331def _duplicate_url(entries, ctx: Context) -> Iterable[Finding]:
332    """No two listings share the same homepage URL."""
333    in_scope = {(e.category, e.section, e.name) for e in entries}
334    for url, matches in ctx.url_occurrences.items():
335        if len(matches) <= 1:
336            continue
337        for me in matches:
338            if (me.category, me.section, me.name) not in in_scope:
339                continue
340            others = [e for e in matches if e is not me]
341            shown = ", ".join(f"{e.category} > {e.section}: {e.name}" for e in others[:2])
342            if len(others) > 2:
343                shown += f" (+{len(others) - 2} more)"
344            yield _finding(me, "duplicate-url", "warn",
345                           f"URL {url} also used by {shown}")
346
347
348_interrupted = False
349
350
351def _install_sigint():
352    def handler(signum, frame):
353        global _interrupted
354        if _interrupted:
355            raise KeyboardInterrupt
356        _interrupted = True
357        logging.warning("Interrupt received, finishing in-flight checks (Ctrl-C again to abort)")
358    signal.signal(signal.SIGINT, handler)
359
360
361def build_context(args, data, token):
362    ctx = Context(
363        session=utils.make_session(),
364        token=token,
365        timeout=args.timeout,
366    )
367    for cat, sec, svc in utils.iter_services(data):
368        url = _normalize_url(svc.get("url"))
369        if url:
370            ctx.url_occurrences.setdefault(url, []).append(Entry(cat, sec, svc))
371    return ctx
372
373
374def filter_entries(data, args):
375    for cat, sec, svc in utils.iter_services(data):
376        if args.category and args.category.lower() != cat.lower():
377            continue
378        if args.section and args.section.lower() != sec.lower():
379            continue
380        if args.service and args.service.lower() != svc.get("name", "").lower():
381            continue
382        yield Entry(cat, sec, svc)
383
384
385def _run_one(entry, enabled, ctx):
386    findings = []
387    for name in enabled:
388        spec = CHECKS[name]
389        if spec.scope != "service":
390            continue
391        try:
392            findings.extend(spec.fn(entry, ctx) or [])
393        except Exception as exc:
394            logging.warning("check %s on %s failed: %s", name, entry.name, exc)
395    return findings
396
397
398def _run_global(enabled, entries, ctx):
399    findings = []
400    for name in enabled:
401        spec = CHECKS[name]
402        if spec.scope != "global":
403            continue
404        try:
405            findings.extend(spec.fn(entries, ctx) or [])
406        except Exception as exc:
407            logging.warning("global check %s failed: %s", name, exc)
408    return findings
409
410
411def run_checks(entries, enabled, ctx, workers):
412    findings = []
413    total = len(entries)
414    with ThreadPoolExecutor(max_workers=workers) as ex:
415        futures = {ex.submit(_run_one, e, enabled, ctx): e for e in entries}
416        for i, fut in enumerate(as_completed(futures), start=1):
417            if _interrupted:
418                ex.shutdown(wait=False, cancel_futures=True)
419                break
420            try:
421                findings.extend(fut.result())
422            except Exception as exc:
423                logging.warning("worker error: %s", exc)
424            if i % 25 == 0 or i == total:
425                logging.info("Progress: %d/%d services reviewed", i, total)
426    findings.extend(_run_global(enabled, entries, ctx))
427    return findings
428
429
430def _sev_color(severity, colors):
431    return colors[_SEV_COLOR.get(severity, "yellow")]
432
433
434def _compute_summary(findings, entries, enabled, elapsed):
435    n_services = len(entries)
436    total_checks = n_services * len(enabled)
437    failed = {(f.category, f.section, f.service, f.check) for f in findings}
438    passed_checks = total_checks - len(failed)
439    pass_rate = (passed_checks / total_checks * 100) if total_checks else 100.0
440    services_with_findings = {(f.category, f.section, f.service) for f in findings}
441    return {
442        "services_scanned": n_services,
443        "services_passed": n_services - len(services_with_findings),
444        "total_checks": total_checks,
445        "passed_checks": passed_checks,
446        "pass_rate": round(pass_rate, 1),
447        "findings": len(findings),
448        "errors": sum(1 for f in findings if f.severity == "error"),
449        "warnings": sum(1 for f in findings if f.severity == "warn"),
450        "info": sum(1 for f in findings if f.severity == "info"),
451        "elapsed_seconds": round(elapsed, 2),
452    }
453
454
455_SUMMARY_ROWS = (("errors", "error"), ("warnings", "warn"), ("info", "info"))
456
457
458def _summary(s, colors):
459    parts = ", ".join(
460        colors[_SEV_COLOR[sev]](f"{s[key]} {key}") if s[key] else f"0 {key}"
461        for key, sev in _SUMMARY_ROWS
462    )
463    return "\n".join([
464        colors["bold"]("Summary"),
465        "-------",
466        f"{s['services_scanned']} listings scanned "
467        f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)",
468        f"{s['findings']} findings ({parts})",
469        f"{s['services_passed']} listings passed all checks",
470        f"Took {s['elapsed_seconds']:.1f}s",
471    ])
472
473
474def _markdown_summary(s):
475    return "\n".join([
476        "### Summary",
477        "",
478        f"- ℹ️ {s['services_scanned']} listings scanned "
479        f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)",
480        f"- ⚠️ {s['findings']} findings "
481        f"({s['errors']} errors, {s['warnings']} warnings, {s['info']} info)",
482        f"- ✅ {s['services_passed']} listings passed all checks",
483        f"- ⏱️ Triggered at {s['triggered_at']}, took {s['elapsed_seconds']:.1f}s",
484    ])
485
486
487def render_list(findings, colors, summary):
488    lines = []
489    if not findings:
490        lines.append(colors["green"]("✓ All services passed."))
491    grouped: dict = {}
492    for f in findings:
493        grouped.setdefault((f.category, f.section, f.service), []).append(f)
494    for (cat, sec, name), items in grouped.items():
495        lines.append(f"{colors['bold'](name)}  {colors['dim'](f'({cat} > {sec})')}")
496        for f in items:
497            badge = _sev_color(f.severity, colors)(f"[{f.severity.upper():<5}]")
498            lines.append(f"  {badge} {colors['cyan'](f.check.ljust(20))} {f.message}")
499        lines.append("")
500    lines.append(_summary(summary, colors))
501    return "\n".join(lines)
502
503
504def render_json(findings, colors, summary):
505    return json.dumps(
506        {"summary": summary, "findings": [asdict(f) for f in findings]},
507        indent=2,
508    )
509
510
511_MD_URL_RE = re.compile(r"https?://[^\s)\]]+")
512_URL_TRAIL = ".,;:!?"
513
514
515def _md_message(msg, url_limit=42):
516    def shorten(m):
517        url = m.group()
518        trail = ""
519        while url and url[-1] in _URL_TRAIL:
520            trail = url[-1] + trail
521            url = url[:-1]
522        label = url if len(url) <= url_limit else url[:url_limit - 3] + "..."
523        return f"[`{label}`]({url}){trail}"
524    return _MD_URL_RE.sub(shorten, msg)
525
526
527def render_markdown(findings, colors, summary):
528    def cell(s):
529        return str(s).replace("|", "\\|").replace("\n", " ")
530
531    lines = []
532
533    lines += ["# Awesome Privacy Auto Checks", ""]
534
535    need_review = summary["findings"] - summary["errors"]
536    lines += [
537        f"_Ran {summary['total_checks']} checks across {summary['services_scanned']} "
538        f"listings, with a {summary['pass_rate']:.1f}% pass rate._",
539        f"_{summary['errors']} issues require action, plus another {need_review} "
540        f"findings need reviewing._",
541        "",
542    ]
543
544    errors = [f for f in findings if f.severity == "error"]
545    if errors:
546        lines += ["### Critical Issues", ""]
547        for f in errors:
548            lines.append(
549                f"- {_SEV_EMOJI[f.severity]} **{cell(f.service)}** - "
550                f"{_md_message(cell(f.message))}"
551            )
552        lines.append("")
553
554    lines += [
555        "---",
556        "",
557        "### Full Issue List",
558        "",
559        "| Service | Review Required |",
560        "|---|---|",
561    ]
562    grouped: dict = {}
563    for f in findings:
564        grouped.setdefault((f.category, f.section, f.service), []).append(f)
565    for (cat, sec, name), items in grouped.items():
566        review = "<br>".join(
567            f"{_SEV_EMOJI[f.severity]} {_md_message(cell(f.message))}"
568            for f in items
569        )
570        link = f"https://awesome-privacy.xyz/{utils.slugify(cat)}/{utils.slugify(sec)}/{utils.slugify(name)}"
571        lines.append(
572            f"| **{cell(name)}** [↗]({link})<br>"
573            f"<sup>{cell(cat)} > {cell(sec)}</sup> | {review} |"
574        )
575    lines += ["", "---", "", _markdown_summary(summary)]
576    lines += [
577        "",
578        "> [!IMPORTANT]",
579        "> The automated checks can produce false positives, fail to include real issues, and does not "
580        "take the context of the listings into account. Careful human review is needed!",
581        ""
582    ]
583    return "\n".join(lines)
584
585
586def _csv(s):
587    return [x.strip() for x in s.split(",") if x.strip()]
588
589
590def parse_args():
591    p = argparse.ArgumentParser(
592        description="Review all listings in awesome-privacy.yml against our criteria.",
593    )
594    p.add_argument("--save-json", metavar="PATH", help="save a JSON report to this file")
595    p.add_argument("--save-markdown", metavar="PATH",
596                   help="save a markdown report to this file (for GH Actions summaries)")
597    p.add_argument("--category", help="filter to a single category")
598    p.add_argument("--section", help="filter to a single section")
599    p.add_argument("--service", help="filter to a single service")
600    p.add_argument("--only", type=_csv, default=[], help="comma-separated checks to run")
601    p.add_argument("--skip", type=_csv, default=[], help="comma-separated checks to skip")
602    p.add_argument("--severity", choices=["all", "warn", "error"], default="all")
603    p.add_argument("--max-workers", type=int, default=DEFAULT_WORKERS)
604    p.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT)
605    p.add_argument("--token", help="GitHub token (else $GITHUB_TOKEN)")
606    p.add_argument("--no-color", action="store_true")
607    p.add_argument("--list-checks", action="store_true", help="list available checks and exit")
608    p.add_argument("-v", "--verbose", action="store_true")
609    p.add_argument("-q", "--quiet", action="store_true")
610    return p.parse_args()
611
612
613def resolve_enabled(only, skip):
614    unknown = [n for n in only + skip if n not in CHECKS]
615    if unknown:
616        logging.error("Unknown check(s): %s. Available: %s",
617                      ", ".join(unknown), ", ".join(CHECKS))
618        sys.exit(2)
619    enabled = list(only) if only else list(CHECKS)
620    return [n for n in enabled if n not in skip]
621
622
623def filter_severity(findings, level):
624    if level == "error":
625        return [f for f in findings if f.severity == "error"]
626    if level == "warn":
627        return [f for f in findings if f.severity in ("warn", "error")]
628    return findings
629
630
631def main():
632    _install_sigint()
633    args = parse_args()
634    utils.setup_logging("DEBUG" if args.verbose else "WARNING" if args.quiet else "INFO")
635    colors = utils.make_colors(enabled=False if args.no_color else None)
636
637    if args.list_checks:
638        for name, spec in CHECKS.items():
639            tag = colors["dim"](" (needs GITHUB_TOKEN)") if spec.needs_github else ""
640            print(f"  {colors['cyan'](name.ljust(22))} {spec.doc}{tag}")
641        return
642
643    enabled = resolve_enabled(args.only, args.skip)
644    token = args.token or os.environ.get("GITHUB_TOKEN", "")
645
646    if not token:
647        gh_checks = [n for n in enabled if CHECKS[n].needs_github]
648        if gh_checks:
649            logging.warning(
650                "GITHUB_TOKEN not set, skipping GitHub checks (%s). "
651                "Export GITHUB_TOKEN to enable them.",
652                ", ".join(gh_checks),
653            )
654            enabled = [n for n in enabled if not CHECKS[n].needs_github]
655
656    if not enabled:
657        logging.error("No checks to run after filters.")
658        sys.exit(2)
659
660    try:
661        data = utils.load_yaml()
662    except FileNotFoundError:
663        logging.error("awesome-privacy.yml not found at %s", utils.DATA_PATH)
664        sys.exit(2)
665    except Exception as exc:
666        logging.error("Failed to parse awesome-privacy.yml: %s", exc)
667        sys.exit(2)
668
669    entries = list(filter_entries(data, args))
670    if not entries:
671        logging.error("No services matched filters (category=%s, section=%s, service=%s)",
672                      args.category, args.section, args.service)
673        sys.exit(2)
674
675    ctx = build_context(args, data, token)
676    logging.info("Reviewing %d service(s) with %d check(s): %s",
677                 len(entries), len(enabled), ", ".join(enabled))
678
679    triggered_at = datetime.now(timezone.utc)
680    start = monotonic()
681    findings = run_checks(entries, enabled, ctx, args.max_workers)
682    elapsed = monotonic() - start
683
684    summary = _compute_summary(findings, entries, enabled, elapsed)
685    summary["triggered_at"] = triggered_at.strftime("%Y-%m-%d %H:%M UTC")
686    display = filter_severity(findings, args.severity)
687    display.sort(key=lambda f: (f.category, f.section, f.service, f.check))
688
689    print(render_list(display, colors, summary))
690
691    for path, renderer in (
692        (args.save_json, render_json),
693        (args.save_markdown, render_markdown),
694    ):
695        if not path:
696            continue
697        try:
698            with open(path, "w") as f:
699                f.write(renderer(display, colors, summary) + "\n")
700            logging.info("Wrote %s", path)
701        except OSError as exc:
702            logging.warning("Could not write %s: %s", path, exc)
703
704    sys.exit(1 if any(f.severity == "error" for f in findings) else 0)
705
706
707if __name__ == "__main__":
708    main()