| @@ -0,0 +1,713 @@ |
| 1 | #!/usr/bin/env python3 |
| 2 | """Audit every service in awesome-privacy.yml. |
| 3 | |
| 4 | Checks: |
| 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 | |
| 22 | Findings have three severities: error (must fix), warn (should review), info (FYI). |
| 23 | HTTP 403/429 on reachability checks is demoted from error to warn (bot-blocking). |
| 24 | |
| 25 | Flags: |
| 26 | - --output {list,table,json,markdown}: report format (default list) |
| 27 | - --output-file PATH: also write the report to a file |
| 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 | - --inactive-days N: info threshold for github-activity (default 365; warn at 2x) |
| 34 | - --token: GitHub token, else $GITHUB_TOKEN |
| 35 | - --no-color: disable ANSI colors |
| 36 | - --list-checks: list checks and exit |
| 37 | - -v / -q: verbose or quiet logging |
| 38 | """ |
| 39 | |
| 40 | import argparse |
| 41 | import json |
| 42 | import logging |
| 43 | import os |
| 44 | import re |
| 45 | import signal |
| 46 | import sys |
| 47 | from concurrent.futures import ThreadPoolExecutor, as_completed |
| 48 | from dataclasses import asdict, dataclass, field |
| 49 | from datetime import datetime, timezone |
| 50 | from threading import Lock |
| 51 | from time import monotonic |
| 52 | from typing import Callable, Iterable |
| 53 | |
| 54 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 55 | try: |
| 56 | import utils |
| 57 | except ImportError as exc: |
| 58 | print(f"ERROR: missing dependency ({exc}). Run `make install_lib_deps`.", file=sys.stderr) |
| 59 | sys.exit(2) |
| 60 | |
| 61 | INACTIVE_DAYS = 365 |
| 62 | MIN_DESC = 50 |
| 63 | MAX_DESC = 280 |
| 64 | MAX_DESC_HARD = 420 |
| 65 | DEFAULT_WORKERS = 8 |
| 66 | DEFAULT_TIMEOUT = 10 |
| 67 | DEFAULT_OUTPUT = "list" |
| 68 | |
| 69 | SEVERITIES = ("error", "warn", "info") |
| 70 | _SEV_COLOR = {"error": "red", "warn": "yellow", "info": "cyan"} |
| 71 | _SEV_EMOJI = {"error": "🔴", "warn": "🟡", "info": "🔵"} |
| 72 | _SOFT_HTTP = {403, 429} |
| 73 | _PKG_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$") |
| 74 | |
| 75 | |
| 76 | @dataclass |
| 77 | class Entry: |
| 78 | category: str |
| 79 | section: str |
| 80 | service: dict |
| 81 | |
| 82 | @property |
| 83 | def name(self): |
| 84 | return self.service.get("name", "") |
| 85 | |
| 86 | |
| 87 | @dataclass |
| 88 | class Finding: |
| 89 | category: str |
| 90 | section: str |
| 91 | service: str |
| 92 | check: str |
| 93 | severity: str |
| 94 | message: str |
| 95 | |
| 96 | |
| 97 | @dataclass |
| 98 | class Context: |
| 99 | session: object |
| 100 | token: str |
| 101 | timeout: int |
| 102 | inactive_days: int |
| 103 | url_occurrences: dict = field(default_factory=dict) |
| 104 | repo_cache: dict = field(default_factory=dict) |
| 105 | repo_lock: Lock = field(default_factory=Lock) |
| 106 | |
| 107 | |
| 108 | @dataclass |
| 109 | class CheckSpec: |
| 110 | name: str |
| 111 | scope: str |
| 112 | needs_github: bool |
| 113 | fn: Callable |
| 114 | doc: str |
| 115 | |
| 116 | |
| 117 | CHECKS: dict[str, CheckSpec] = {} |
| 118 | |
| 119 | |
| 120 | def check(name, *, scope="service", needs_github=False): |
| 121 | def deco(fn): |
| 122 | CHECKS[name] = CheckSpec(name, scope, needs_github, fn, (fn.__doc__ or "").strip()) |
| 123 | return fn |
| 124 | return deco |
| 125 | |
| 126 | |
| 127 | def _finding(entry: Entry, check_name: str, severity: str, message: str) -> Finding: |
| 128 | return Finding(entry.category, entry.section, entry.name, check_name, severity, message) |
| 129 | |
| 130 | |
| 131 | def _normalize_url(url: str) -> str: |
| 132 | return (url or "").strip().rstrip("/").lower() |
| 133 | |
| 134 | |
| 135 | def _get_repo(entry: Entry, ctx: Context): |
| 136 | owner, repo = utils.parse_github_field(entry.service.get("github")) |
| 137 | if not owner: |
| 138 | return None |
| 139 | key = f"{owner}/{repo}" |
| 140 | with ctx.repo_lock: |
| 141 | if key in ctx.repo_cache: |
| 142 | return ctx.repo_cache[key] |
| 143 | data = utils.gh_get( |
| 144 | f"/repos/{owner}/{repo}", ctx.token, ctx.session, |
| 145 | timeout=ctx.timeout, label="repos", |
| 146 | ) |
| 147 | with ctx.repo_lock: |
| 148 | ctx.repo_cache[key] = data |
| 149 | return data |
| 150 | |
| 151 | |
| 152 | def _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 | |
| 159 | def _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") |
| 168 | def _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") |
| 178 | def _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") |
| 186 | def _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") |
| 196 | def _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") |
| 211 | def _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") |
| 219 | def _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") |
| 228 | def _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") |
| 238 | def _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") |
| 250 | def _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") |
| 264 | def _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) |
| 278 | def _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) |
| 294 | def _github_archived(entry: Entry, ctx: Context) -> Iterable[Finding]: |
| 295 | """GitHub repo must not be archived.""" |
| 296 | data = _get_repo(entry, ctx) |
| 297 | if data and data.get("archived"): |
| 298 | yield _finding(entry, "github-archived", "error", "repository is archived on GitHub") |
| 299 | |
| 300 | |
| 301 | @check("github-fork", needs_github=True) |
| 302 | def _github_fork(entry: Entry, ctx: Context) -> Iterable[Finding]: |
| 303 | """GitHub repo should not be a fork.""" |
| 304 | data = _get_repo(entry, ctx) |
| 305 | if data and data.get("fork"): |
| 306 | parent = (data.get("parent") or {}).get("full_name") |
| 307 | suffix = f" of {parent}" if parent else "" |
| 308 | yield _finding(entry, "github-fork", "warn", f"repository is a fork{suffix}") |
| 309 | |
| 310 | |
| 311 | @check("github-activity", needs_github=True) |
| 312 | def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]: |
| 313 | """GitHub repo has been pushed to recently.""" |
| 314 | data = _get_repo(entry, ctx) |
| 315 | pushed = data.get("pushed_at") if data else None |
| 316 | if not pushed: |
| 317 | return |
| 318 | try: |
| 319 | pushed_dt = datetime.fromisoformat(pushed.replace("Z", "+00:00")) |
| 320 | except ValueError: |
| 321 | return |
| 322 | age = (datetime.now(timezone.utc) - pushed_dt).days |
| 323 | warn_days = ctx.inactive_days * 2 |
| 324 | if age > warn_days: |
| 325 | sev = "warn" |
| 326 | elif age > ctx.inactive_days: |
| 327 | sev = "info" |
| 328 | else: |
| 329 | return |
| 330 | yield _finding(entry, "github-activity", sev, f"last push {age} days ago") |
| 331 | |
| 332 | |
| 333 | @check("github-license", needs_github=True) |
| 334 | def _github_license(entry: Entry, ctx: Context) -> Iterable[Finding]: |
| 335 | """GitHub repo must have a declared license.""" |
| 336 | data = _get_repo(entry, ctx) |
| 337 | if data and not data.get("license"): |
| 338 | yield _finding(entry, "github-license", "warn", "repository has no declared license") |
| 339 | |
| 340 | |
| 341 | @check("duplicate-url", scope="global") |
| 342 | def _duplicate_url(entries, ctx: Context) -> Iterable[Finding]: |
| 343 | """No two listings share the same homepage URL.""" |
| 344 | in_scope = {(e.category, e.section, e.name) for e in entries} |
| 345 | for url, matches in ctx.url_occurrences.items(): |
| 346 | if len(matches) <= 1: |
| 347 | continue |
| 348 | for me in matches: |
| 349 | if (me.category, me.section, me.name) not in in_scope: |
| 350 | continue |
| 351 | others = [e for e in matches if e is not me] |
| 352 | shown = ", ".join(f"{e.category} > {e.section}: {e.name}" for e in others[:2]) |
| 353 | if len(others) > 2: |
| 354 | shown += f" (+{len(others) - 2} more)" |
| 355 | yield _finding(me, "duplicate-url", "warn", |
| 356 | f"URL {url} also used by {shown}") |
| 357 | |
| 358 | |
| 359 | _interrupted = False |
| 360 | |
| 361 | |
| 362 | def _install_sigint(): |
| 363 | def handler(signum, frame): |
| 364 | global _interrupted |
| 365 | if _interrupted: |
| 366 | raise KeyboardInterrupt |
| 367 | _interrupted = True |
| 368 | logging.warning("Interrupt received, finishing in-flight checks (Ctrl-C again to abort)") |
| 369 | signal.signal(signal.SIGINT, handler) |
| 370 | |
| 371 | |
| 372 | def build_context(args, data, token): |
| 373 | ctx = Context( |
| 374 | session=utils.make_session(), |
| 375 | token=token, |
| 376 | timeout=args.timeout, |
| 377 | inactive_days=args.inactive_days, |
| 378 | ) |
| 379 | for cat, sec, svc in utils.iter_services(data): |
| 380 | url = _normalize_url(svc.get("url")) |
| 381 | if url: |
| 382 | ctx.url_occurrences.setdefault(url, []).append(Entry(cat, sec, svc)) |
| 383 | return ctx |
| 384 | |
| 385 | |
| 386 | def filter_entries(data, args): |
| 387 | for cat, sec, svc in utils.iter_services(data): |
| 388 | if args.category and args.category.lower() != cat.lower(): |
| 389 | continue |
| 390 | if args.section and args.section.lower() != sec.lower(): |
| 391 | continue |
| 392 | if args.service and args.service.lower() != svc.get("name", "").lower(): |
| 393 | continue |
| 394 | yield Entry(cat, sec, svc) |
| 395 | |
| 396 | |
| 397 | def _run_one(entry, enabled, ctx): |
| 398 | findings = [] |
| 399 | for name in enabled: |
| 400 | spec = CHECKS[name] |
| 401 | if spec.scope != "service": |
| 402 | continue |
| 403 | try: |
| 404 | findings.extend(spec.fn(entry, ctx) or []) |
| 405 | except Exception as exc: |
| 406 | logging.warning("check %s on %s failed: %s", name, entry.name, exc) |
| 407 | return findings |
| 408 | |
| 409 | |
| 410 | def _run_global(enabled, entries, ctx): |
| 411 | findings = [] |
| 412 | for name in enabled: |
| 413 | spec = CHECKS[name] |
| 414 | if spec.scope != "global": |
| 415 | continue |
| 416 | try: |
| 417 | findings.extend(spec.fn(entries, ctx) or []) |
| 418 | except Exception as exc: |
| 419 | logging.warning("global check %s failed: %s", name, exc) |
| 420 | return findings |
| 421 | |
| 422 | |
| 423 | def run_checks(entries, enabled, ctx, workers): |
| 424 | findings = [] |
| 425 | total = len(entries) |
| 426 | with ThreadPoolExecutor(max_workers=workers) as ex: |
| 427 | futures = {ex.submit(_run_one, e, enabled, ctx): e for e in entries} |
| 428 | for i, fut in enumerate(as_completed(futures), start=1): |
| 429 | if _interrupted: |
| 430 | ex.shutdown(wait=False, cancel_futures=True) |
| 431 | break |
| 432 | try: |
| 433 | findings.extend(fut.result()) |
| 434 | except Exception as exc: |
| 435 | logging.warning("worker error: %s", exc) |
| 436 | if i % 25 == 0 or i == total: |
| 437 | logging.info("Progress: %d/%d services reviewed", i, total) |
| 438 | findings.extend(_run_global(enabled, entries, ctx)) |
| 439 | return findings |
| 440 | |
| 441 | |
| 442 | def _sev_color(severity, colors): |
| 443 | return colors[_SEV_COLOR.get(severity, "yellow")] |
| 444 | |
| 445 | |
| 446 | def _compute_summary(findings, entries, enabled, elapsed): |
| 447 | n_services = len(entries) |
| 448 | total_checks = n_services * len(enabled) |
| 449 | failed = {(f.category, f.section, f.service, f.check) for f in findings} |
| 450 | passed_checks = total_checks - len(failed) |
| 451 | pass_rate = (passed_checks / total_checks * 100) if total_checks else 100.0 |
| 452 | services_with_findings = {(f.category, f.section, f.service) for f in findings} |
| 453 | return { |
| 454 | "services_scanned": n_services, |
| 455 | "services_passed": n_services - len(services_with_findings), |
| 456 | "total_checks": total_checks, |
| 457 | "passed_checks": passed_checks, |
| 458 | "pass_rate": round(pass_rate, 1), |
| 459 | "findings": len(findings), |
| 460 | "errors": sum(1 for f in findings if f.severity == "error"), |
| 461 | "warnings": sum(1 for f in findings if f.severity == "warn"), |
| 462 | "info": sum(1 for f in findings if f.severity == "info"), |
| 463 | "elapsed_seconds": round(elapsed, 2), |
| 464 | } |
| 465 | |
| 466 | |
| 467 | _SUMMARY_ROWS = (("errors", "error"), ("warnings", "warn"), ("info", "info")) |
| 468 | |
| 469 | |
| 470 | def _summary(s, colors): |
| 471 | parts = ", ".join( |
| 472 | colors[_SEV_COLOR[sev]](f"{s[key]} {key}") if s[key] else f"0 {key}" |
| 473 | for key, sev in _SUMMARY_ROWS |
| 474 | ) |
| 475 | return "\n".join([ |
| 476 | colors["bold"]("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 ({parts})", |
| 481 | f"{s['services_passed']} listings passed all checks", |
| 482 | f"Took {s['elapsed_seconds']:.1f}s", |
| 483 | ]) |
| 484 | |
| 485 | |
| 486 | def _markdown_summary(s): |
| 487 | return "\n".join([ |
| 488 | "### Summary", |
| 489 | "", |
| 490 | f"- {s['services_scanned']} listings scanned " |
| 491 | f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)", |
| 492 | f"- {s['findings']} findings " |
| 493 | f"({s['errors']} errors, {s['warnings']} warnings, {s['info']} info)", |
| 494 | f"- {s['services_passed']} listings passed all checks", |
| 495 | f"- Took {s['elapsed_seconds']:.1f}s", |
| 496 | ]) |
| 497 | |
| 498 | |
| 499 | def render_list(findings, colors, summary): |
| 500 | lines = [] |
| 501 | if not findings: |
| 502 | lines.append(colors["green"]("✓ All services passed.")) |
| 503 | grouped: dict = {} |
| 504 | for f in findings: |
| 505 | grouped.setdefault((f.category, f.section, f.service), []).append(f) |
| 506 | for (cat, sec, name), items in grouped.items(): |
| 507 | lines.append(f"{colors['bold'](name)} {colors['dim'](f'({cat} > {sec})')}") |
| 508 | for f in items: |
| 509 | badge = _sev_color(f.severity, colors)(f"[{f.severity.upper():<5}]") |
| 510 | lines.append(f" {badge} {colors['cyan'](f.check.ljust(20))} {f.message}") |
| 511 | lines.append("") |
| 512 | lines.append(_summary(summary, colors)) |
| 513 | return "\n".join(lines) |
| 514 | |
| 515 | |
| 516 | def render_table(findings, colors, summary): |
| 517 | header = ("Service", "Path", "Check", "Sev", "Message") |
| 518 | rows = [header] + [ |
| 519 | ( |
| 520 | f.service[:30], |
| 521 | f"{f.category} > {f.section}"[:40], |
| 522 | f.check, |
| 523 | f.severity.upper()[:5], |
| 524 | f.message[:80], |
| 525 | ) |
| 526 | for f in findings |
| 527 | ] |
| 528 | widths = [max(len(r[i]) for r in rows) for i in range(len(header))] |
| 529 | lines = [] |
| 530 | for i, row in enumerate(rows): |
| 531 | cells = [row[j].ljust(widths[j]) for j in range(len(row))] |
| 532 | if i == 0: |
| 533 | lines.append(colors["bold"](" ".join(cells))) |
| 534 | lines.append(colors["dim"](" ".join("-" * w for w in widths))) |
| 535 | else: |
| 536 | cells[3] = _sev_color(row[3].lower(), colors)(cells[3]) |
| 537 | lines.append(" ".join(cells)) |
| 538 | lines.append("") |
| 539 | lines.append(_summary(summary, colors)) |
| 540 | return "\n".join(lines) |
| 541 | |
| 542 | |
| 543 | def render_json(findings, colors, summary): |
| 544 | return json.dumps( |
| 545 | {"summary": summary, "findings": [asdict(f) for f in findings]}, |
| 546 | indent=2, |
| 547 | ) |
| 548 | |
| 549 | |
| 550 | _MD_URL_RE = re.compile(r"https?://[^\s)\]]+") |
| 551 | _URL_TRAIL = ".,;:!?" |
| 552 | |
| 553 | |
| 554 | def _md_message(msg, url_limit=42): |
| 555 | def shorten(m): |
| 556 | url = m.group() |
| 557 | trail = "" |
| 558 | while url and url[-1] in _URL_TRAIL: |
| 559 | trail = url[-1] + trail |
| 560 | url = url[:-1] |
| 561 | label = url if len(url) <= url_limit else url[:url_limit - 3] + "..." |
| 562 | return f"[`{label}`]({url}){trail}" |
| 563 | return _MD_URL_RE.sub(shorten, msg) |
| 564 | |
| 565 | |
| 566 | def render_markdown(findings, colors, summary): |
| 567 | def cell(s): |
| 568 | return str(s).replace("|", "\\|").replace("\n", " ") |
| 569 | lines = ["| Service | Review Required |", "|---|---|"] |
| 570 | grouped: dict = {} |
| 571 | for f in findings: |
| 572 | grouped.setdefault((f.category, f.section, f.service), []).append(f) |
| 573 | for (cat, sec, name), items in grouped.items(): |
| 574 | review = "<br>".join( |
| 575 | f"{_SEV_EMOJI[f.severity]} {_md_message(cell(f.message))}" |
| 576 | for f in items |
| 577 | ) |
| 578 | link = f"https://awesome-privacy.xyz/{utils.slugify(cat)}/{utils.slugify(sec)}/{utils.slugify(name)}" |
| 579 | lines.append( |
| 580 | f"| **{cell(name)}** [↗]({link})<br>" |
| 581 | f"<sup>{cell(cat)} > {cell(sec)}</sup> | {review} |" |
| 582 | ) |
| 583 | lines += ["", _markdown_summary(summary)] |
| 584 | return "\n".join(lines) |
| 585 | |
| 586 | |
| 587 | RENDERERS = {"list": render_list, "table": render_table, "json": render_json, |
| 588 | "markdown": render_markdown} |
| 589 | |
| 590 | _ANSI_RE = re.compile(r"\x1b\[[0-9;]*m") |
| 591 | |
| 592 | |
| 593 | def strip_ansi(s: str) -> str: |
| 594 | return _ANSI_RE.sub("", s) |
| 595 | |
| 596 | |
| 597 | def _csv(s): |
| 598 | return [x.strip() for x in s.split(",") if x.strip()] |
| 599 | |
| 600 | |
| 601 | def parse_args(): |
| 602 | p = argparse.ArgumentParser( |
| 603 | description="Review all listings in awesome-privacy.yml against our criteria.", |
| 604 | ) |
| 605 | p.add_argument("--output", choices=RENDERERS.keys(), default=DEFAULT_OUTPUT) |
| 606 | p.add_argument("--output-file", help="also write the report here (ANSI stripped)") |
| 607 | p.add_argument("--category", help="filter to a single category") |
| 608 | p.add_argument("--section", help="filter to a single section") |
| 609 | p.add_argument("--service", help="filter to a single service") |
| 610 | p.add_argument("--only", type=_csv, default=[], help="comma-separated checks to run") |
| 611 | p.add_argument("--skip", type=_csv, default=[], help="comma-separated checks to skip") |
| 612 | p.add_argument("--severity", choices=["all", "warn", "error"], default="all") |
| 613 | p.add_argument("--max-workers", type=int, default=DEFAULT_WORKERS) |
| 614 | p.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT) |
| 615 | p.add_argument("--inactive-days", type=int, default=INACTIVE_DAYS) |
| 616 | p.add_argument("--token", help="GitHub token (else $GITHUB_TOKEN)") |
| 617 | p.add_argument("--no-color", action="store_true") |
| 618 | p.add_argument("--list-checks", action="store_true", help="list available checks and exit") |
| 619 | p.add_argument("-v", "--verbose", action="store_true") |
| 620 | p.add_argument("-q", "--quiet", action="store_true") |
| 621 | return p.parse_args() |
| 622 | |
| 623 | |
| 624 | def resolve_enabled(only, skip): |
| 625 | unknown = [n for n in only + skip if n not in CHECKS] |
| 626 | if unknown: |
| 627 | logging.error("Unknown check(s): %s. Available: %s", |
| 628 | ", ".join(unknown), ", ".join(CHECKS)) |
| 629 | sys.exit(2) |
| 630 | enabled = list(only) if only else list(CHECKS) |
| 631 | return [n for n in enabled if n not in skip] |
| 632 | |
| 633 | |
| 634 | def filter_severity(findings, level): |
| 635 | if level == "error": |
| 636 | return [f for f in findings if f.severity == "error"] |
| 637 | if level == "warn": |
| 638 | return [f for f in findings if f.severity in ("warn", "error")] |
| 639 | return findings |
| 640 | |
| 641 | |
| 642 | def main(): |
| 643 | _install_sigint() |
| 644 | args = parse_args() |
| 645 | utils.setup_logging("DEBUG" if args.verbose else "WARNING" if args.quiet else "INFO") |
| 646 | colors = utils.make_colors(enabled=False if args.no_color else None) |
| 647 | |
| 648 | if args.list_checks: |
| 649 | for name, spec in CHECKS.items(): |
| 650 | tag = colors["dim"](" (needs GITHUB_TOKEN)") if spec.needs_github else "" |
| 651 | print(f" {colors['cyan'](name.ljust(22))} {spec.doc}{tag}") |
| 652 | return |
| 653 | |
| 654 | enabled = resolve_enabled(args.only, args.skip) |
| 655 | token = args.token or os.environ.get("GITHUB_TOKEN", "") |
| 656 | |
| 657 | if not token: |
| 658 | gh_checks = [n for n in enabled if CHECKS[n].needs_github] |
| 659 | if gh_checks: |
| 660 | logging.warning( |
| 661 | "GITHUB_TOKEN not set, skipping GitHub checks (%s). " |
| 662 | "Export GITHUB_TOKEN to enable them.", |
| 663 | ", ".join(gh_checks), |
| 664 | ) |
| 665 | enabled = [n for n in enabled if not CHECKS[n].needs_github] |
| 666 | |
| 667 | if not enabled: |
| 668 | logging.error("No checks to run after filters.") |
| 669 | sys.exit(2) |
| 670 | |
| 671 | try: |
| 672 | data = utils.load_yaml() |
| 673 | except FileNotFoundError: |
| 674 | logging.error("awesome-privacy.yml not found at %s", utils.DATA_PATH) |
| 675 | sys.exit(2) |
| 676 | except Exception as exc: |
| 677 | logging.error("Failed to parse awesome-privacy.yml: %s", exc) |
| 678 | sys.exit(2) |
| 679 | |
| 680 | entries = list(filter_entries(data, args)) |
| 681 | if not entries: |
| 682 | logging.error("No services matched filters (category=%s, section=%s, service=%s)", |
| 683 | args.category, args.section, args.service) |
| 684 | sys.exit(2) |
| 685 | |
| 686 | ctx = build_context(args, data, token) |
| 687 | logging.info("Reviewing %d service(s) with %d check(s): %s", |
| 688 | len(entries), len(enabled), ", ".join(enabled)) |
| 689 | |
| 690 | start = monotonic() |
| 691 | findings = run_checks(entries, enabled, ctx, args.max_workers) |
| 692 | elapsed = monotonic() - start |
| 693 | |
| 694 | summary = _compute_summary(findings, entries, enabled, elapsed) |
| 695 | display = filter_severity(findings, args.severity) |
| 696 | display.sort(key=lambda f: (f.category, f.section, f.service, f.check)) |
| 697 | |
| 698 | report = RENDERERS[args.output](display, colors, summary) |
| 699 | print(report) |
| 700 | |
| 701 | if args.output_file: |
| 702 | try: |
| 703 | with open(args.output_file, "w") as f: |
| 704 | f.write(strip_ansi(report) + "\n") |
| 705 | logging.info("Wrote report to %s", args.output_file) |
| 706 | except OSError as exc: |
| 707 | logging.warning("Could not write %s: %s", args.output_file, exc) |
| 708 | |
| 709 | sys.exit(1 if any(f.severity == "error" for f in findings) else 0) |
| 710 | |
| 711 | |
| 712 | if __name__ == "__main__": |
| 713 | main() |