Commit ed89881583

ed89881583dbc3dae1653bafe28db2eece3ac502

parent: 1fd2d1a61c

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-04-19 20:33 UTC

Workflow to flag dead links and bad listings

Layout: unified · split

.github/workflows/health-check.yml added +69
@@ -0,0 +1,69 @@
1name: 🩺 Listing Health Checks
2
3on:
4 workflow_dispatch:
5 inputs:
6 category:
7 description: Just run for specific category (optional)
8 type: string
9 section:
10 description: Just run for a specific section (optional)
11 type: string
12 service:
13 description: Just run for a specific entry (optional)
14 type: string
15
16permissions:
17 contents: read
18
19jobs:
20 health-check:
21 name: Health check
22 runs-on: ubuntu-latest
23 steps:
24 - uses: actions/checkout@v5
25
26 - uses: actions/setup-python@v6
27 with:
28 python-version: "3.12"
29
30 - name: Install dependencies
31 run: pip install -q -r lib/requirements.txt
32
33 - name: Run health check
34 id: check
35 continue-on-error: true
36 env:
37 GITHUB_TOKEN: ${{ github.token }}
38 CATEGORY: ${{ inputs.category }}
39 SECTION: ${{ inputs.section }}
40 SERVICE: ${{ inputs.service }}
41 run: |
42 args=()
43 [ -n "$CATEGORY" ] && args+=(--category "$CATEGORY")
44 [ -n "$SECTION" ] && args+=(--section "$SECTION")
45 [ -n "$SERVICE" ] && args+=(--service "$SERVICE")
46 python lib/review-listings.py "${args[@]}" \
47 --save-json /tmp/findings.json \
48 --save-markdown /tmp/findings.md
49
50 - name: Write summary
51 if: always()
52 run: |
53 if [ -f /tmp/findings.md ]; then
54 cat /tmp/findings.md >> "$GITHUB_STEP_SUMMARY"
55 else
56 echo "We somehow lost the /tmp/findings.md file"
57 fi
58
59 - name: Upload findings JSON
60 if: always()
61 uses: actions/upload-artifact@v6
62 with:
63 name: listing-health-findings
64 path: /tmp/findings.json
65 if-no-files-found: ignore
66
67 - name: Fail if critical issues
68 if: steps.check.outcome == 'failure'
69 run: exit 1
lib/review-listings.py +76 −69
@@ -23,14 +23,13 @@ Findings have three severities: error (must fix), warn (should review), info (FY
23HTTP 403/429 on reachability checks is demoted from error to warn (bot-blocking). 23HTTP 403/429 on reachability checks is demoted from error to warn (bot-blocking).
24 24
25Flags: 25Flags:
26- --output {list,table,json,markdown}: report format (default list) 26- --save-json PATH: save a JSON report to this file
27- --output-file PATH: also write the report to a file 27- --save-markdown PATH: save a markdown report to this file (for GH Actions summaries)
28- --category / --section / --service: narrow to one entry 28- --category / --section / --service: narrow to one entry
29- --only / --skip: pick or drop checks by name 29- --only / --skip: pick or drop checks by name
30- --severity {all,warn,error}: filter findings 30- --severity {all,warn,error}: filter findings
31- --max-workers N: parallel workers (default 8) 31- --max-workers N: parallel workers (default 8)
32- --timeout N: HTTP timeout in seconds (default 10) 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 33- --token: GitHub token, else $GITHUB_TOKEN
35- --no-color: disable ANSI colors 34- --no-color: disable ANSI colors
36- --list-checks: list checks and exit 35- --list-checks: list checks and exit
@@ -46,6 +45,7 @@ import signal
46import sys 45import sys
47from concurrent.futures import ThreadPoolExecutor, as_completed 46from concurrent.futures import ThreadPoolExecutor, as_completed
48from dataclasses import asdict, dataclass, field 47from dataclasses import asdict, dataclass, field
48from datetime import datetime, timezone
49from threading import Lock 49from threading import Lock
50from time import monotonic 50from time import monotonic
51from typing import Callable, Iterable 51from typing import Callable, Iterable
@@ -57,17 +57,22 @@ except ImportError as exc:
57 print(f"ERROR: missing dependency ({exc}). Run `make install_lib_deps`.", file=sys.stderr) 57 print(f"ERROR: missing dependency ({exc}). Run `make install_lib_deps`.", file=sys.stderr)
58 sys.exit(2) 58 sys.exit(2)
59 59
60INACTIVE_DAYS = 365
61MIN_DESC = 50 60MIN_DESC = 50
62MAX_DESC = 280 61MAX_DESC = 280
63MAX_DESC_HARD = 420 62MAX_DESC_HARD = 420
64DEFAULT_WORKERS = 8 63DEFAULT_WORKERS = 8
65DEFAULT_TIMEOUT = 10 64DEFAULT_TIMEOUT = 10
66DEFAULT_OUTPUT = "list" 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)
67 72
68SEVERITIES = ("error", "warn", "info") 73SEVERITIES = ("error", "warn", "info")
69_SEV_COLOR = {"error": "red", "warn": "yellow", "info": "cyan"} 74_SEV_COLOR = {"error": "red", "warn": "yellow", "info": "cyan"}
70_SEV_EMOJI = {"error": "🔴", "warn": "🟡", "info": "🔵"} 75_SEV_EMOJI = {"error": "🔴", "warn": "🟠", "info": "🟡"}
71_SOFT_HTTP = {403, 429} 76_SOFT_HTTP = {403, 429}
72_PKG_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$") 77_PKG_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$")
73 78
@@ -98,7 +103,6 @@ class Context:
98 session: object 103 session: object
99 token: str 104 token: str
100 timeout: int 105 timeout: int
101 inactive_days: int
102 url_occurrences: dict = field(default_factory=dict) 106 url_occurrences: dict = field(default_factory=dict)
103 repo_cache: dict = field(default_factory=dict) 107 repo_cache: dict = field(default_factory=dict)
104 repo_lock: Lock = field(default_factory=Lock) 108 repo_lock: Lock = field(default_factory=Lock)
@@ -305,17 +309,14 @@ def _github_fork(entry: Entry, ctx: Context) -> Iterable[Finding]:
305 309
306@check("github-activity", needs_github=True) 310@check("github-activity", needs_github=True)
307def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]: 311def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]:
308 """GitHub repo has been pushed to recently.""" 312 """GitHub repo has been pushed to recently (info at 1y, warn at 3y, error at 8y)."""
309 age = utils.repo_pushed_days_ago(_get_repo(entry, ctx)) 313 age = utils.repo_pushed_days_ago(_get_repo(entry, ctx))
310 if age is None: 314 if age is None:
311 return 315 return
312 if age > ctx.inactive_days * 2: 316 for threshold, sev in ACTIVITY_BANDS:
313 sev = "warn" 317 if age >= threshold:
314 elif age > ctx.inactive_days: 318 yield _finding(entry, "github-activity", sev, f"last push {age} days ago")
315 sev = "info" 319 return
316 else:
317 return
318 yield _finding(entry, "github-activity", sev, f"last push {age} days ago")
319 320
320 321
321@check("github-license", needs_github=True) 322@check("github-license", needs_github=True)
@@ -362,7 +363,6 @@ def build_context(args, data, token):
362 session=utils.make_session(), 363 session=utils.make_session(),
363 token=token, 364 token=token,
364 timeout=args.timeout, 365 timeout=args.timeout,
365 inactive_days=args.inactive_days,
366 ) 366 )
367 for cat, sec, svc in utils.iter_services(data): 367 for cat, sec, svc in utils.iter_services(data):
368 url = _normalize_url(svc.get("url")) 368 url = _normalize_url(svc.get("url"))
@@ -475,12 +475,12 @@ def _markdown_summary(s):
475 return "\n".join([ 475 return "\n".join([
476 "### Summary", 476 "### Summary",
477 "", 477 "",
478 f"- {s['services_scanned']} listings scanned " 478 f"- ℹ️ {s['services_scanned']} listings scanned "
479 f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)", 479 f"({s['total_checks']} checks, {s['pass_rate']:.1f}% pass rate)",
480 f"- {s['findings']} findings " 480 f"- ⚠️ {s['findings']} findings "
481 f"({s['errors']} errors, {s['warnings']} warnings, {s['info']} info)", 481 f"({s['errors']} errors, {s['warnings']} warnings, {s['info']} info)",
482 f"- {s['services_passed']} listings passed all checks", 482 f"- ✅ {s['services_passed']} listings passed all checks",
483 f"- Took {s['elapsed_seconds']:.1f}s", 483 f"- ⏱️ Triggered at {s['triggered_at']}, took {s['elapsed_seconds']:.1f}s",
484 ]) 484 ])
485 485
486 486
@@ -501,33 +501,6 @@ def render_list(findings, colors, summary):
501 return "\n".join(lines) 501 return "\n".join(lines)
502 502
503 503
504def render_table(findings, colors, summary):
505 header = ("Service", "Path", "Check", "Sev", "Message")
506 rows = [header] + [
507 (
508 f.service[:30],
509 f"{f.category} > {f.section}"[:40],
510 f.check,
511 f.severity.upper()[:5],
512 f.message[:80],
513 )
514 for f in findings
515 ]
516 widths = [max(len(r[i]) for r in rows) for i in range(len(header))]
517 lines = []
518 for i, row in enumerate(rows):
519 cells = [row[j].ljust(widths[j]) for j in range(len(row))]
520 if i == 0:
521 lines.append(colors["bold"](" ".join(cells)))
522 lines.append(colors["dim"](" ".join("-" * w for w in widths)))
523 else:
524 cells[3] = _sev_color(row[3].lower(), colors)(cells[3])
525 lines.append(" ".join(cells))
526 lines.append("")
527 lines.append(_summary(summary, colors))
528 return "\n".join(lines)
529
530
531def render_json(findings, colors, summary): 504def render_json(findings, colors, summary):
532 return json.dumps( 505 return json.dumps(
533 {"summary": summary, "findings": [asdict(f) for f in findings]}, 506 {"summary": summary, "findings": [asdict(f) for f in findings]},
@@ -554,7 +527,38 @@ def _md_message(msg, url_limit=42):
554def render_markdown(findings, colors, summary): 527def render_markdown(findings, colors, summary):
555 def cell(s): 528 def cell(s):
556 return str(s).replace("|", "\\|").replace("\n", " ") 529 return str(s).replace("|", "\\|").replace("\n", " ")
557 lines = ["| Service | Review Required |", "|---|---|"] 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 ]
558 grouped: dict = {} 562 grouped: dict = {}
559 for f in findings: 563 for f in findings:
560 grouped.setdefault((f.category, f.section, f.service), []).append(f) 564 grouped.setdefault((f.category, f.section, f.service), []).append(f)
@@ -568,20 +572,17 @@ def render_markdown(findings, colors, summary):
568 f"| **{cell(name)}** [↗]({link})<br>" 572 f"| **{cell(name)}** [↗]({link})<br>"
569 f"<sup>{cell(cat)} > {cell(sec)}</sup> | {review} |" 573 f"<sup>{cell(cat)} > {cell(sec)}</sup> | {review} |"
570 ) 574 )
571 lines += ["", _markdown_summary(summary)] 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 ]
572 return "\n".join(lines) 583 return "\n".join(lines)
573 584
574 585
575RENDERERS = {"list": render_list, "table": render_table, "json": render_json,
576 "markdown": render_markdown}
577
578_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
579
580
581def strip_ansi(s: str) -> str:
582 return _ANSI_RE.sub("", s)
583
584
585def _csv(s): 586def _csv(s):
586 return [x.strip() for x in s.split(",") if x.strip()] 587 return [x.strip() for x in s.split(",") if x.strip()]
587 588
@@ -590,8 +591,9 @@ def parse_args():
590 p = argparse.ArgumentParser( 591 p = argparse.ArgumentParser(
591 description="Review all listings in awesome-privacy.yml against our criteria.", 592 description="Review all listings in awesome-privacy.yml against our criteria.",
592 ) 593 )
593 p.add_argument("--output", choices=RENDERERS.keys(), default=DEFAULT_OUTPUT) 594 p.add_argument("--save-json", metavar="PATH", help="save a JSON report to this file")
594 p.add_argument("--output-file", help="also write the report here (ANSI stripped)") 595 p.add_argument("--save-markdown", metavar="PATH",
596 help="save a markdown report to this file (for GH Actions summaries)")
595 p.add_argument("--category", help="filter to a single category") 597 p.add_argument("--category", help="filter to a single category")
596 p.add_argument("--section", help="filter to a single section") 598 p.add_argument("--section", help="filter to a single section")
597 p.add_argument("--service", help="filter to a single service") 599 p.add_argument("--service", help="filter to a single service")
@@ -600,7 +602,6 @@ def parse_args():
600 p.add_argument("--severity", choices=["all", "warn", "error"], default="all") 602 p.add_argument("--severity", choices=["all", "warn", "error"], default="all")
601 p.add_argument("--max-workers", type=int, default=DEFAULT_WORKERS) 603 p.add_argument("--max-workers", type=int, default=DEFAULT_WORKERS)
602 p.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT) 604 p.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT)
603 p.add_argument("--inactive-days", type=int, default=INACTIVE_DAYS)
604 p.add_argument("--token", help="GitHub token (else $GITHUB_TOKEN)") 605 p.add_argument("--token", help="GitHub token (else $GITHUB_TOKEN)")
605 p.add_argument("--no-color", action="store_true") 606 p.add_argument("--no-color", action="store_true")
606 p.add_argument("--list-checks", action="store_true", help="list available checks and exit") 607 p.add_argument("--list-checks", action="store_true", help="list available checks and exit")
@@ -675,24 +676,30 @@ def main():
675 logging.info("Reviewing %d service(s) with %d check(s): %s", 676 logging.info("Reviewing %d service(s) with %d check(s): %s",
676 len(entries), len(enabled), ", ".join(enabled)) 677 len(entries), len(enabled), ", ".join(enabled))
677 678
679 triggered_at = datetime.now(timezone.utc)
678 start = monotonic() 680 start = monotonic()
679 findings = run_checks(entries, enabled, ctx, args.max_workers) 681 findings = run_checks(entries, enabled, ctx, args.max_workers)
680 elapsed = monotonic() - start 682 elapsed = monotonic() - start
681 683
682 summary = _compute_summary(findings, entries, enabled, elapsed) 684 summary = _compute_summary(findings, entries, enabled, elapsed)
685 summary["triggered_at"] = triggered_at.strftime("%Y-%m-%d %H:%M UTC")
683 display = filter_severity(findings, args.severity) 686 display = filter_severity(findings, args.severity)
684 display.sort(key=lambda f: (f.category, f.section, f.service, f.check)) 687 display.sort(key=lambda f: (f.category, f.section, f.service, f.check))
685 688
686 report = RENDERERS[args.output](display, colors, summary) 689 print(render_list(display, colors, summary))
687 print(report)
688 690
689 if args.output_file: 691 for path, renderer in (
692 (args.save_json, render_json),
693 (args.save_markdown, render_markdown),
694 ):
695 if not path:
696 continue
690 try: 697 try:
691 with open(args.output_file, "w") as f: 698 with open(path, "w") as f:
692 f.write(strip_ansi(report) + "\n") 699 f.write(renderer(display, colors, summary) + "\n")
693 logging.info("Wrote report to %s", args.output_file) 700 logging.info("Wrote %s", path)
694 except OSError as exc: 701 except OSError as exc:
695 logging.warning("Could not write %s: %s", args.output_file, exc) 702 logging.warning("Could not write %s: %s", path, exc)
696 703
697 sys.exit(1 if any(f.severity == "error" for f in findings) else 0) 704 sys.exit(1 if any(f.severity == "error" for f in findings) else 0)
698 705