Commit 281749441c

281749441ca32bd3aa039b1627274d2b12f9d3d7

parent: 3ecb71ee10

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-06-09 13:42 UTC

Unified API client for PR check and review report

Layout: unified · split

.github/workflows/health-check.yml +1
@@ -37,6 +37,7 @@ jobs:
37 continue-on-error: true 37 continue-on-error: true
38 env: 38 env:
39 GITHUB_TOKEN: ${{ github.token }} 39 GITHUB_TOKEN: ${{ github.token }}
40 API_TOKEN: ${{ secrets.API_TOKEN }}
40 CATEGORY: ${{ inputs.category }} 41 CATEGORY: ${{ inputs.category }}
41 SECTION: ${{ inputs.section }} 42 SECTION: ${{ inputs.section }}
42 SERVICE: ${{ inputs.service }} 43 SERVICE: ${{ inputs.service }}
lib/checks/make-info-stats.py +16 −16
@@ -44,27 +44,14 @@ RESTRICTIVE_LICENSES = {
44 44
45SESSION = utils.make_session(user_agent=USER_AGENT) 45SESSION = utils.make_session(user_agent=USER_AGENT)
46 46
47API_URL = os.environ.get("API_URL", "https://api.awesome-privacy.xyz").rstrip("/")
48API_TOKEN = os.environ.get("API_TOKEN", "") 47API_TOKEN = os.environ.get("API_TOKEN", "")
49 48
50GREEN, ORANGE, RED, BLUE, WHITE = "\U0001f7e2", "\U0001f7e0", "\U0001f534", "\U0001f535", "\u26aa" 49GREEN, ORANGE, RED, BLUE, WHITE = "\U0001f7e2", "\U0001f7e0", "\U0001f534", "\U0001f535", "\u26aa"
51 50
52 51
53def _api_get(url, params=None, timeout=TIMEOUT, headers=None):
54 """GET a URL, return parsed JSON on 200, else None."""
55 try:
56 resp = SESSION.get(url, headers=headers, timeout=timeout, params=params)
57 if resp.status_code == 200:
58 return resp.json()
59 except Exception as e:
60 logger.warning("Fetch failed for %s: %s", url, e)
61 return None
62
63
64def _enrich_get(path, params=None, timeout=TIMEOUT): 52def _enrich_get(path, params=None, timeout=TIMEOUT):
65 """GET an enrichment endpoint on the unified API, adding auth when configured.""" 53 """GET a unified-API enrichment endpoint with this script's session and token."""
66 headers = {"Authorization": f"Bearer {API_TOKEN}"} if API_TOKEN else None 54 return utils.enrich_get(path, params=params, token=API_TOKEN, session=SESSION, timeout=timeout)
67 return _api_get(f"{API_URL}/v1/enrich/{path}", params=params, headers=headers, timeout=timeout)
68 55
69 56
70def relative_time(iso_str): 57def relative_time(iso_str):
@@ -271,7 +258,7 @@ def grade_stats(data):
271 if adv is None: 258 if adv is None:
272 stats.append((WHITE, "Security Advisories", "Unknown")) 259 stats.append((WHITE, "Security Advisories", "Unknown"))
273 elif adv > 0: 260 elif adv > 0:
274 stats.append((ORANGE, "Security Advisories", f"{adv} unpatched CVEs")) 261 stats.append((ORANGE, "Security Advisories", f"{adv} potentially unpatched CVEs"))
275 else: 262 else:
276 stats.append((GREEN, "Security Advisories", "No unpatched active CVEs found")) 263 stats.append((GREEN, "Security Advisories", "No unpatched active CVEs found"))
277 264
@@ -421,6 +408,14 @@ def fetch_android_data(package_id):
421 return data if data and not data.get("error") else None 408 return data if data and not data.get("error") else None
422 409
423 410
411_DEGOOGLED = {
412 "gold": (GREEN, "Gold (works)"),
413 "silver": (GREEN, "Silver (minor issues)"),
414 "bronze": (ORANGE, "Bronze (limited)"),
415 "broken": (RED, "Broken"),
416}
417
418
424def grade_android_stats(data): 419def grade_android_stats(data):
425 """Grade Android app stats.""" 420 """Grade Android app stats."""
426 stats = [] 421 stats = []
@@ -443,6 +438,11 @@ def grade_android_stats(data):
443 stats.append(_info_or_unknown("Created", _friendly_date(data.get("created")))) 438 stats.append(_info_or_unknown("Created", _friendly_date(data.get("created"))))
444 stats.append(_info_or_unknown("Last Updated", _friendly_date(data.get("updated")))) 439 stats.append(_info_or_unknown("Last Updated", _friendly_date(data.get("updated"))))
445 440
441 status = utils.degoogled_status(data)
442 if status:
443 color, label = _DEGOOGLED.get(status, (BLUE, status.title()))
444 stats.append((color, "De-Googled", label))
445
446 return stats 446 return stats
447 447
448 448
lib/review-listings.py +196 −32
@@ -6,10 +6,10 @@ Checks:
6- https-url: homepage URL uses HTTPS 6- https-url: homepage URL uses HTTPS
7- icon-reachable: icon URL does not 404 7- icon-reachable: icon URL does not 404
8- description-len: description is 50 to 280 chars (over 420 escalates to warn) 8- description-len: description is 50 to 280 chars (over 420 escalates to warn)
9- opensource-github: openSource listings include a github, codeberg or git field 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 10- duplicate-url: no URL appears in more than one listing
11- androidApp-valid: androidApp is a package name, not a URL 11- androidApp-valid: androidApp is a package name, not a URL
12- iosApp-reachable: App Store URL resolves 12- iosApp-valid: iosApp is a valid App Store URL with an app id
13- subreddit-exists: subreddit page exists on reddit.com 13- subreddit-exists: subreddit page exists on reddit.com
14- tosdr-valid: tosdrId still resolves on tosdr.org 14- tosdr-valid: tosdrId still resolves on tosdr.org
15- discord-invite-valid: Discord invite code is still valid 15- discord-invite-valid: Discord invite code is still valid
@@ -18,10 +18,16 @@ Checks:
18- github-activity: github repo was pushed recently (needs token) 18- github-activity: github repo was pushed recently (needs token)
19- github-license: github repo has a license (needs token) 19- github-license: github repo has a license (needs token)
20- github-fork: github repo is not a fork (needs token) 20- github-fork: github repo is not a fork (needs token)
21- security-advisories: no open unpatched CVEs (needs API_TOKEN)
22- android-trackers: android app has few trackers (1 info, 2+ warn) (needs API_TOKEN)
23- ios-app: iOS app exists, is maintained and rated (missing/stale/low-rating warn) (needs API_TOKEN)
24- degoogled-compat: android app works on de-googled android (needs API_TOKEN)
25- privacy-grade: tosdr privacy grade is B or better (C info, D/E warn) (needs API_TOKEN)
21 26
22Findings have three severities: error (must fix), warn (should review), info (FYI). 27Findings have three severities: error (must fix), warn (should review), info (FYI).
23HTTP 403/406/429 (and 404 on known bot-blocking hosts such as play.google.com) on 28HTTP 403/406/429 (and 404 on known bot-blocking hosts such as play.google.com) on
24reachability checks is demoted from error to warn. 29reachability checks means the probe was rate-limited or blocked, not that the resource is
30missing, so it is logged during the run but left out of the results.
25 31
26Exit codes: 32Exit codes:
27 1 when pass rate drops below FAIL_PASS_RATE or errors exceed FAIL_MAX_ERRORS (5) 33 1 when pass rate drops below FAIL_PASS_RATE or errors exceed FAIL_MAX_ERRORS (5)
@@ -52,7 +58,7 @@ import sys
52from concurrent.futures import ThreadPoolExecutor, as_completed 58from concurrent.futures import ThreadPoolExecutor, as_completed
53from dataclasses import asdict, dataclass, field 59from dataclasses import asdict, dataclass, field
54from datetime import datetime, timezone 60from datetime import datetime, timezone
55from threading import Lock 61from threading import Lock, local
56from time import monotonic 62from time import monotonic
57from typing import Callable, Iterable 63from typing import Callable, Iterable
58from urllib.parse import urlparse 64from urllib.parse import urlparse
@@ -111,12 +117,26 @@ class Finding:
111 117
112@dataclass 118@dataclass
113class Context: 119class Context:
114 session: object
115 token: str 120 token: str
116 timeout: int 121 timeout: int
122 api_token: str = ""
117 url_occurrences: dict = field(default_factory=dict) 123 url_occurrences: dict = field(default_factory=dict)
118 repo_cache: dict = field(default_factory=dict) 124 repo_cache: dict = field(default_factory=dict)
125 security_cache: dict = field(default_factory=dict)
126 android_cache: dict = field(default_factory=dict)
127 privacy_cache: dict = field(default_factory=dict)
128 ios_cache: dict = field(default_factory=dict)
119 repo_lock: Lock = field(default_factory=Lock) 129 repo_lock: Lock = field(default_factory=Lock)
130 _sessions: local = field(default_factory=local)
131
132 @property
133 def session(self):
134 """Per-thread session, since a requests.Session is not safe to share across threads."""
135 session = getattr(self._sessions, "value", None)
136 if session is None:
137 session = utils.make_session()
138 self._sessions.value = session
139 return session
120 140
121 141
122@dataclass 142@dataclass
@@ -124,6 +144,7 @@ class CheckSpec:
124 name: str 144 name: str
125 scope: str 145 scope: str
126 needs_github: bool 146 needs_github: bool
147 needs_api: bool
127 fn: Callable 148 fn: Callable
128 doc: str 149 doc: str
129 150
@@ -131,9 +152,11 @@ class CheckSpec:
131CHECKS: dict[str, CheckSpec] = {} 152CHECKS: dict[str, CheckSpec] = {}
132 153
133 154
134def check(name, *, scope="service", needs_github=False): 155def check(name, *, scope="service", needs_github=False, needs_api=False):
135 def deco(fn): 156 def deco(fn):
136 CHECKS[name] = CheckSpec(name, scope, needs_github, fn, (fn.__doc__ or "").strip()) 157 CHECKS[name] = CheckSpec(
158 name, scope, needs_github, needs_api, fn, (fn.__doc__ or "").strip()
159 )
137 return fn 160 return fn
138 return deco 161 return deco
139 162
@@ -160,21 +183,74 @@ def _get_repo(entry: Entry, ctx: Context):
160 return data 183 return data
161 184
162 185
163def _unreachable(field, url, status, default_sev): 186def _get_security_report(entry: Entry, ctx: Context):
164 """Return (severity, message). Bot-blocking signatures demote error to warn.""" 187 owner, repo = utils.parse_github_field(entry.service.get("github"))
165 host = urlparse(url).netloc.lower() 188 if not owner:
166 soft = status in _SOFT_HTTP or (status == 404 and host in _SOFT_404_HOSTS) 189 return None
167 sev = "warn" if default_sev == "error" and soft else default_sev 190 key = f"{owner}/{repo}"
168 detail = f"{url} returned HTTP {status}" if status else f"{url} could not be reached" 191 with ctx.repo_lock:
169 return sev, f"{field} is unreachable, {detail}" 192 if key in ctx.security_cache:
193 return ctx.security_cache[key]
194 data = utils.fetch_security_report(owner, repo, ctx.api_token,
195 session=ctx.session, label=entry.name)
196 with ctx.repo_lock:
197 ctx.security_cache[key] = data
198 return data
199
200
201def _get_android(entry: Entry, ctx: Context):
202 pkg = entry.service.get("androidApp")
203 if not pkg:
204 return None
205 with ctx.repo_lock:
206 if pkg in ctx.android_cache:
207 return ctx.android_cache[pkg]
208 data = utils.fetch_android_app(pkg, ctx.api_token, session=ctx.session, label=entry.name)
209 with ctx.repo_lock:
210 ctx.android_cache[pkg] = data
211 return data
212
213
214def _get_privacy(entry: Entry, ctx: Context):
215 tid = entry.service.get("tosdrId")
216 if not tid:
217 return None
218 key = str(tid)
219 with ctx.repo_lock:
220 if key in ctx.privacy_cache:
221 return ctx.privacy_cache[key]
222 data = utils.fetch_privacy(tid, ctx.api_token, session=ctx.session, label=entry.name)
223 with ctx.repo_lock:
224 ctx.privacy_cache[key] = data
225 return data
226
227
228def _get_ios(entry: Entry, ctx: Context):
229 """Return (report, http_status) for the listing's iOS app, both None if no valid id."""
230 app_id = utils.ios_app_id(entry.service.get("iosApp"))
231 if not app_id:
232 return None, None
233 with ctx.repo_lock:
234 if app_id in ctx.ios_cache:
235 return ctx.ios_cache[app_id]
236 result = utils.fetch_ios(entry.service.get("iosApp"), ctx.api_token,
237 session=ctx.session, label=entry.name, return_status=True)
238 with ctx.repo_lock:
239 ctx.ios_cache[app_id] = result
240 return result
170 241
171 242
172def _reachability_finding(entry, check_name, field, url, default_sev, ctx): 243def _reachability_finding(entry, check_name, field, url, default_sev, ctx):
173 ok, status = utils.check_url(url, ctx.session, ctx.timeout) 244 ok, status = utils.check_url(url, ctx.session, ctx.timeout)
174 if ok: 245 if ok:
175 return None 246 return None
176 sev, msg = _unreachable(field, url, status, default_sev) 247 host = urlparse(url).netloc.lower()
177 return _finding(entry, check_name, sev, msg) 248 if status in _SOFT_HTTP or (status == 404 and host in _SOFT_404_HOSTS):
249 # Rate-limited or bot-blocked probe, inconclusive so log it but do not report
250 logging.info("%s for %s inconclusive (HTTP %s) possibly just rate-limited/blocked", check_name, url, status)
251 return None
252 detail = f"{url} returned HTTP {status}" if status else f"{url} could not be reached"
253 return _finding(entry, check_name, default_sev, f"{field} is unreachable, {detail}")
178 254
179 255
180@check("url-reachable") 256@check("url-reachable")
@@ -222,14 +298,16 @@ def _description_len(entry: Entry, ctx: Context) -> Iterable[Finding]:
222 298
223@check("opensource-github") 299@check("opensource-github")
224def _opensource_github(entry: Entry, ctx: Context) -> Iterable[Finding]: 300def _opensource_github(entry: Entry, ctx: Context) -> Iterable[Finding]:
225 """openSource: true services must include a github, codeberg or git field.""" 301 """openSource: true needs a repo link (error); not open source is noted (info)."""
226 svc = entry.service 302 svc = entry.service
227 if svc.get("openSource") is True and not ( 303 has_repo = svc.get("github") or svc.get("codeberg") or svc.get("git")
228 svc.get("github") or svc.get("codeberg") or svc.get("git") 304 if svc.get("openSource") is True and not has_repo:
229 ):
230 yield _finding(entry, "opensource-github", "error", 305 yield _finding(entry, "opensource-github", "error",
231 "marked openSource but missing a repository link " 306 "marked openSource but missing a repository link ")
232 "(`github`, `codeberg` or `git`)") 307 elif svc.get("openSource") is False or not has_repo:
308 reason = "openSource is false" if svc.get("openSource") is False else "no repository linked"
309 yield _finding(entry, "opensource-github", "info",
310 f"not open source ({reason})")
233 311
234 312
235@check("androidApp-valid") 313@check("androidApp-valid")
@@ -241,14 +319,13 @@ def _android_app_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
241 f"androidApp {val} is not a package name (expected com.example.app)") 319 f"androidApp {val} is not a package name (expected com.example.app)")
242 320
243 321
244@check("iosApp-reachable") 322@check("iosApp-valid")
245def _iosapp_reachable(entry: Entry, ctx: Context) -> Iterable[Finding]: 323def _iosapp_valid(entry: Entry, ctx: Context) -> Iterable[Finding]:
246 """iOS App Store link must resolve.""" 324 """iosApp must be an App Store URL with an app id."""
247 url = entry.service.get("iosApp") 325 url = entry.service.get("iosApp")
248 if url: 326 if url and not utils.ios_app_id(url):
249 f = _reachability_finding(entry, "iosApp-reachable", "iosApp", url, "warn", ctx) 327 yield _finding(entry, "iosApp-valid", "warn",
250 if f: 328 f"iosApp {url} is not a valid App Store URL (expected .../idNNNN)")
251 yield f
252 329
253 330
254@check("subreddit-exists") 331@check("subreddit-exists")
@@ -344,6 +421,81 @@ def _github_license(entry: Entry, ctx: Context) -> Iterable[Finding]:
344 yield _finding(entry, "github-license", "warn", "repository has no declared license") 421 yield _finding(entry, "github-license", "warn", "repository has no declared license")
345 422
346 423
424@check("security-advisories", needs_api=True)
425def _security_advisories(entry: Entry, ctx: Context) -> Iterable[Finding]:
426 """No open unpatched CVEs (low/medium warn, high/critical error)."""
427 if not entry.service.get("github"):
428 return
429 low_med, high_crit = utils.unpatched_advisories(_get_security_report(entry, ctx))
430 if high_crit:
431 yield _finding(entry, "security-advisories", "error",
432 f"{high_crit} open high/critical "
433 f"advisor{'ies' if high_crit != 1 else 'y'}")
434 if low_med:
435 yield _finding(entry, "security-advisories", "warn",
436 f"{low_med} open low/medium "
437 f"advisor{'ies' if low_med != 1 else 'y'}")
438
439
440@check("android-trackers", needs_api=True)
441def _android_trackers(entry: Entry, ctx: Context) -> Iterable[Finding]:
442 """Android app has few trackers (1 info, 2+ warn)."""
443 if not entry.service.get("androidApp"):
444 return
445 count = utils.tracker_count(_get_android(entry, ctx))
446 if not count:
447 return
448 sev = "info" if count == 1 else "warn"
449 yield _finding(entry, "android-trackers", sev,
450 f"Android app reports {count} tracker{'s' if count != 1 else ''}")
451
452
453@check("ios-app", needs_api=True)
454def _ios_app(entry: Entry, ctx: Context) -> Iterable[Finding]:
455 """iOS app exists, is maintained and rated (missing/stale/<2 stars warn)."""
456 if not utils.ios_app_id(entry.service.get("iosApp")):
457 return
458 report, status = _get_ios(entry, ctx)
459 if status == 404:
460 yield _finding(entry, "ios-app", "warn",
461 "iOS app not found on the App Store (may have been removed)")
462 return
463 days = utils.ios_days_since_update(report)
464 if days is not None and days >= 365:
465 yield _finding(entry, "ios-app", "warn",
466 f"iOS app not updated in over a year (last release {days} days ago)")
467 rating, count = utils.ios_rating(report)
468 if count and rating is not None and rating < 2:
469 yield _finding(entry, "ios-app", "warn",
470 f"iOS app is rated below 2 stars ({rating:.1f} from {count:,} ratings)")
471
472
473@check("degoogled-compat", needs_api=True)
474def _degoogled_compat(entry: Entry, ctx: Context) -> Iterable[Finding]:
475 """Android app works on de-Googled Android (broken warn, limited info)."""
476 if not entry.service.get("androidApp"):
477 return
478 status = utils.degoogled_status(_get_android(entry, ctx))
479 if status == "broken":
480 yield _finding(entry, "degoogled-compat", "warn",
481 "Android app is broken on de-Googled Android")
482 elif status == "bronze":
483 yield _finding(entry, "degoogled-compat", "info",
484 "Android app has limited de-Googled support")
485
486
487@check("privacy-grade", needs_api=True)
488def _privacy_grade(entry: Entry, ctx: Context) -> Iterable[Finding]:
489 """ToS;DR privacy grade is B or better (C info, D/E warn)."""
490 if not entry.service.get("tosdrId"):
491 return
492 grade = utils.privacy_grade(_get_privacy(entry, ctx))
493 if grade == "C":
494 yield _finding(entry, "privacy-grade", "info", "privacy policy has minor concerns")
495 elif grade in ("D", "E"):
496 yield _finding(entry, "privacy-grade", "warn", f"privacy policy has major issues (graded: {grade})")
497
498
347@check("duplicate-url", scope="global") 499@check("duplicate-url", scope="global")
348def _duplicate_url(entries, ctx: Context) -> Iterable[Finding]: 500def _duplicate_url(entries, ctx: Context) -> Iterable[Finding]:
349 """No two listings share the same homepage URL.""" 501 """No two listings share the same homepage URL."""
@@ -375,11 +527,11 @@ def _install_sigint():
375 signal.signal(signal.SIGINT, handler) 527 signal.signal(signal.SIGINT, handler)
376 528
377 529
378def build_context(args, data, token): 530def build_context(args, data, token, api_token):
379 ctx = Context( 531 ctx = Context(
380 session=utils.make_session(),
381 token=token, 532 token=token,
382 timeout=args.timeout, 533 timeout=args.timeout,
534 api_token=api_token,
383 ) 535 )
384 for cat, sec, svc in utils.iter_services(data): 536 for cat, sec, svc in utils.iter_services(data):
385 url = _normalize_url(svc.get("url")) 537 url = _normalize_url(svc.get("url"))
@@ -654,11 +806,13 @@ def main():
654 if args.list_checks: 806 if args.list_checks:
655 for name, spec in CHECKS.items(): 807 for name, spec in CHECKS.items():
656 tag = colors["dim"](" (needs GITHUB_TOKEN)") if spec.needs_github else "" 808 tag = colors["dim"](" (needs GITHUB_TOKEN)") if spec.needs_github else ""
809 tag += colors["dim"](" (needs API_TOKEN)") if spec.needs_api else ""
657 print(f" {colors['cyan'](name.ljust(22))} {spec.doc}{tag}") 810 print(f" {colors['cyan'](name.ljust(22))} {spec.doc}{tag}")
658 return 811 return
659 812
660 enabled = resolve_enabled(args.only, args.skip) 813 enabled = resolve_enabled(args.only, args.skip)
661 token = args.token or os.environ.get("GITHUB_TOKEN", "") 814 token = args.token or os.environ.get("GITHUB_TOKEN", "")
815 api_token = os.environ.get("API_TOKEN", "")
662 816
663 if not token: 817 if not token:
664 gh_checks = [n for n in enabled if CHECKS[n].needs_github] 818 gh_checks = [n for n in enabled if CHECKS[n].needs_github]
@@ -670,6 +824,16 @@ def main():
670 ) 824 )
671 enabled = [n for n in enabled if not CHECKS[n].needs_github] 825 enabled = [n for n in enabled if not CHECKS[n].needs_github]
672 826
827 if not api_token:
828 api_checks = [n for n in enabled if CHECKS[n].needs_api]
829 if api_checks:
830 logging.warning(
831 "API_TOKEN not set, skipping API checks (%s). "
832 "Export API_TOKEN to enable them.",
833 ", ".join(api_checks),
834 )
835 enabled = [n for n in enabled if not CHECKS[n].needs_api]
836
673 if not enabled: 837 if not enabled:
674 logging.error("No checks to run after filters.") 838 logging.error("No checks to run after filters.")
675 sys.exit(2) 839 sys.exit(2)
@@ -689,7 +853,7 @@ def main():
689 args.category, args.section, args.service) 853 args.category, args.section, args.service)
690 sys.exit(2) 854 sys.exit(2)
691 855
692 ctx = build_context(args, data, token) 856 ctx = build_context(args, data, token, api_token)
693 logging.info("Reviewing %d service(s) with %d check(s): %s", 857 logging.info("Reviewing %d service(s) with %d check(s): %s",
694 len(entries), len(enabled), ", ".join(enabled)) 858 len(entries), len(enabled), ", ".join(enabled))
695 859
lib/utils/__init__.py +29 −2
@@ -8,6 +8,20 @@ imports are skipped there, letting `setup_logging()` work without them.
8from .term import make_colors, setup_logging 8from .term import make_colors, setup_logging
9 9
10try: 10try:
11 from .api import (
12 degoogled_status,
13 enrich_get,
14 fetch_android_app,
15 fetch_ios,
16 fetch_privacy,
17 fetch_security_report,
18 ios_app_id,
19 ios_days_since_update,
20 ios_rating,
21 privacy_grade,
22 tracker_count,
23 unpatched_advisories,
24 )
11 from .data import DATA_PATH, PROJECT_ROOT, iter_services, load_yaml, slugify 25 from .data import DATA_PATH, PROJECT_ROOT, iter_services, load_yaml, slugify
12 from .github import ( 26 from .github import (
13 AI_BOT_AUTHORS, 27 AI_BOT_AUTHORS,
@@ -23,8 +37,9 @@ try:
23 repo_status, 37 repo_status,
24 ) 38 )
25 from .http import DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, check_url, make_session 39 from .http import DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, check_url, make_session
26except ImportError: 40except ImportError as exc:
27 pass 41 if exc.name not in ("requests", "yaml"):
42 raise
28 43
29__all__ = [ 44__all__ = [
30 "AI_BOT_AUTHORS", 45 "AI_BOT_AUTHORS",
@@ -34,8 +49,18 @@ __all__ = [
34 "PROJECT_ROOT", 49 "PROJECT_ROOT",
35 "check_url", 50 "check_url",
36 "commit_has_bot", 51 "commit_has_bot",
52 "degoogled_status",
53 "enrich_get",
54 "fetch_android_app",
55 "fetch_ios",
56 "fetch_privacy",
37 "fetch_repo", 57 "fetch_repo",
58 "fetch_security_report",
38 "gh_get", 59 "gh_get",
60 "ios_app_id",
61 "ios_days_since_update",
62 "ios_rating",
63 "privacy_grade",
39 "iter_services", 64 "iter_services",
40 "load_yaml", 65 "load_yaml",
41 "make_colors", 66 "make_colors",
@@ -49,4 +74,6 @@ __all__ = [
49 "repo_status", 74 "repo_status",
50 "setup_logging", 75 "setup_logging",
51 "slugify", 76 "slugify",
77 "tracker_count",
78 "unpatched_advisories",
52] 79]
lib/utils/api.py added +133
@@ -0,0 +1,133 @@
1"""Helpers for the unified Awesome Privacy API (enrichment endpoints)."""
2
3import logging
4import os
5import re
6from datetime import datetime, timezone
7
8from .http import DEFAULT_TIMEOUT, make_session
9
10API_URL = os.environ.get("API_URL", "https://api.awesome-privacy.xyz").rstrip("/")
11
12_HIGH_SEVERITIES = {"high", "critical"}
13_LOW_SEVERITIES = {"low", "medium"}
14
15
16def enrich_get(path, params=None, token=None, session=None, timeout=DEFAULT_TIMEOUT,
17 label=None, return_status=False):
18 """GET a unified-API enrichment endpoint. Returns parsed JSON on 200, else None.
19
20 With return_status=True, returns (data, http_status), where http_status is None on a
21 network error, letting callers tell a genuine 404 apart from a transient failure.
22 """
23 session = session or make_session()
24 headers = {"Authorization": f"Bearer {token}"} if token else None
25 tag = f" ({label})" if label else ""
26 data, status = None, None
27 try:
28 resp = session.get(f"{API_URL}/v1/enrich/{path}",
29 headers=headers, params=params, timeout=timeout)
30 status = resp.status_code
31 if status == 200:
32 try:
33 data = resp.json()
34 except ValueError:
35 logging.warning("[enrich] empty or invalid JSON body for %s%s", path, tag)
36 else:
37 logging.warning("[enrich] HTTP %d for %s%s", status, path, tag)
38 except Exception as exc:
39 logging.warning("[enrich] request error for %s%s: %s", path, tag, exc)
40 return (data, status) if return_status else data
41
42
43def fetch_security_report(owner, repo, token, session=None, timeout=DEFAULT_TIMEOUT, label=None):
44 """Fetch a repo's security report from the unified API. Returns JSON or None."""
45 return enrich_get(f"security/{owner}/{repo}",
46 token=token, session=session, timeout=timeout, label=label)
47
48
49def fetch_android_app(pkg, token, session=None, timeout=DEFAULT_TIMEOUT, label=None):
50 """Fetch an Android app's privacy report from the unified API. Returns JSON or None."""
51 return enrich_get(f"android/{pkg}",
52 token=token, session=session, timeout=timeout, label=label)
53
54
55def fetch_privacy(tosdr_id, token, session=None, timeout=DEFAULT_TIMEOUT, label=None):
56 """Fetch a service's ToS;DR privacy report from the unified API. Returns JSON or None."""
57 return enrich_get(f"privacy/{tosdr_id}",
58 token=token, session=session, timeout=timeout, label=label)
59
60
61def unpatched_advisories(report):
62 """Return (low_medium, high_critical) counts of open, unpatched advisories."""
63 items = (report.get("advisories") or {}).get("items") or [] if report else []
64 low_med = high_crit = 0
65 for adv in items:
66 if adv.get("isPatched"):
67 continue
68 sev = str(adv.get("severity", "")).lower()
69 if sev in _HIGH_SEVERITIES:
70 high_crit += 1
71 elif sev in _LOW_SEVERITIES:
72 low_med += 1
73 return low_med, high_crit
74
75
76def tracker_count(report):
77 """Number of trackers in an Android app report, or None if unavailable."""
78 trackers = report.get("trackers") if report else None
79 return len(trackers) if isinstance(trackers, list) else None
80
81
82def privacy_grade(report):
83 """ToS;DR letter grade for a service (e.g. A to E), or None if absent."""
84 grade = (report or {}).get("rating")
85 return str(grade).upper() if grade else None
86
87
88def degoogled_status(report):
89 """Plexus de-Googled (no microG) status from an android report, or None."""
90 native = ((report or {}).get("degoogled") or {}).get("native") or {}
91 return native.get("status") if native.get("available") else None
92
93
94_IOS_ID_RE = re.compile(r"(?:apps|itunes)\.apple\.com/\S*\bid(\d+)")
95_IOS_COUNTRY_RE = re.compile(r"(?:apps|itunes)\.apple\.com/([a-z]{2})/")
96
97
98def ios_app_id(app_url):
99 """Numeric App Store id from an iosApp URL, or None if not a valid store URL."""
100 match = _IOS_ID_RE.search(app_url or "")
101 return match.group(1) if match else None
102
103
104def fetch_ios(app_url, token, session=None, timeout=DEFAULT_TIMEOUT, label=None,
105 return_status=False):
106 """Fetch iTunes app info for an App Store URL from the unified API, or None."""
107 app_id = ios_app_id(app_url)
108 if not app_id:
109 return (None, None) if return_status else None
110 country = _IOS_COUNTRY_RE.search(app_url or "")
111 return enrich_get(f"ios/{app_id}", params={"country": country.group(1) if country else "us"},
112 token=token, session=session, timeout=timeout, label=label,
113 return_status=return_status)
114
115
116def ios_days_since_update(report):
117 """Days since the iOS app's current version was released, or None."""
118 raw = (report or {}).get("currentVersionReleaseDate")
119 if not raw:
120 return None
121 try:
122 dt = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
123 except ValueError:
124 return None
125 if dt.tzinfo is None:
126 dt = dt.replace(tzinfo=timezone.utc)
127 return (datetime.now(timezone.utc) - dt).days
128
129
130def ios_rating(report):
131 """(averageUserRating, userRatingCount) from an iOS report, each None if absent."""
132 data = report or {}
133 return data.get("averageUserRating"), data.get("userRatingCount")