diff --git a/.github/advisory-baseline.json b/.github/advisory-baseline.json deleted file mode 100644 index 0c2db007a..000000000 --- a/.github/advisory-baseline.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "digest": "d8fa82e95fdb59244e2f635e667ba17f0796ca0a4f1f4bb8cc31febcd660b76c", - "next_entry": 0, - "accepted": 0, - "exhausted": false, - "finished_at": null, - "baseline": { - "digest": "d8fa82e95fdb59244e2f635e667ba17f0796ca0a4f1f4bb8cc31febcd660b76c", - "endpoint": "https://omg-advisories.latham.workers.dev", - "instance_id": "139c3e51b07f91d448128b043bd22fa0", - "session_id": "afb732ac-68e4-4549-98ec-e89224449b75" - }, - "publisher": { - "release_tag": "cve_2026-11-13_0000Z", - "asset": "2026-11-13_all_CVEs_at_midnight.zip.zip" - } -} diff --git a/.github/workflows/advisory-refresh.yml b/.github/workflows/advisory-refresh.yml deleted file mode 100644 index 98363fb53..000000000 --- a/.github/workflows/advisory-refresh.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: Refresh runtime advisory feeds - -on: - push: - branches: [main] - paths: - - .github/workflows/advisory-refresh.yml - - scripts/refresh-runtime-advisories.py - - scripts/advisory-baseline.py - - .github/advisory-baseline.json - - services/advisories/** - schedule: - - cron: '7,37 * * * *' - - cron: '22,52 * * * *' - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: runtime-advisory-feed-refresh - cancel-in-progress: false - -jobs: - baseline-proof: - if: github.ref == 'refs/heads/main' && (github.event_name != 'schedule' || github.event.schedule == '7,37 * * * *') - runs-on: ubuntu-24.04 - timeout-minutes: 10 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Advance server-owned archive publisher verification - env: - GITHUB_TOKEN: ${{ github.token }} - RUNTIME_REFRESH_SECRET: ${{ secrets.RUNTIME_REFRESH_SECRET }} - run: python3 scripts/advisory-baseline.py warm --max-steps 256 - - refresh: - if: github.ref == 'refs/heads/main' - runs-on: ubuntu-24.04 - timeout-minutes: 10 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Refresh fixed vendor sources - env: - GITHUB_TOKEN: ${{ github.token }} - RUNTIME_REFRESH_SECRET: ${{ secrets.RUNTIME_REFRESH_SECRET }} - run: python3 scripts/refresh-runtime-advisories.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f5a5adfb8..1ccdbdeab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -241,27 +241,6 @@ jobs: retention-days: 7 if-no-files-found: warn - - name: Verify Arch advisory service - if: matrix.shard == 0 && (github.event_name == 'push' || needs.quick-gate.outputs.checks-required == 'true') - env: - WRANGLER_SEND_METRICS: "false" - CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV: "false" - run: | - bun install --cwd services/advisories --frozen-lockfile --ignore-scripts - bun run --cwd services/advisories test - bun run --cwd services/advisories check - bun run --cwd services/advisories dry-run - - - name: Verify isolated advisory staging - if: matrix.shard == 0 && (github.event_name == 'push' || needs.quick-gate.outputs.checks-required == 'true') - env: - WRANGLER_SEND_METRICS: "false" - CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV: "false" - run: | - bun --cwd services/advisories tsc --project ../advisory-staging/tsconfig.json - bun test services/advisory-staging/test - bun --cwd services/advisories wrangler deploy --dry-run --config ../advisory-staging/wrangler.example.json - - name: Verify installer destination safety if: matrix.shard == 0 run: bash tests/installer_security.sh diff --git a/.gitignore b/.gitignore index abd990ddd..60c7e0879 100644 --- a/.gitignore +++ b/.gitignore @@ -23,7 +23,6 @@ bun.lock !/services/cloud-ci/runner/bun.lock !/services/ci-inspector/bun.lock !/services/ci-coder/bun.lock -!/services/advisories/bun.lock !/services/ci/bun.lock package-lock.json !.github/deps/release-tools/package-lock.json diff --git a/scripts/advisory-baseline.py b/scripts/advisory-baseline.py deleted file mode 100644 index b99d6e06e..000000000 --- a/scripts/advisory-baseline.py +++ /dev/null @@ -1,215 +0,0 @@ -"""Advance server-owned CVE publisher proof or refuse an unready release.""" - -import argparse -from datetime import datetime, timezone -import importlib.util -import json -import os -from pathlib import Path -import re -import sys -import time -import urllib.error -import urllib.request - -ORIGIN = "https://omg-advisories.latham.workers.dev" -BINDING_FILE = Path(__file__).resolve().parent.parent / ".github/advisory-baseline.json" -PROOF_PATH = "/internal/baseline/verify" -STATUS_PATH = "/v1/status" -MAX_BODY = 64 * 1024 -STOP_PHASES = ("verified", "awaiting_import", "awaiting_catchup") -MAX_PROOF_STEPS = 256 -PROOF_SECONDS = 8 * 60 -LEASE_ATTEMPTS = 5 - -_spec = importlib.util.spec_from_file_location("runtime_refresh_transport", Path(__file__).with_name("refresh-runtime-advisories.py")) -_transport = importlib.util.module_from_spec(_spec) -_spec.loader.exec_module(_transport) - - -def _object(value): - if type(value) is not dict: - raise ValueError("expected object") - return value - - -def _integer(value, maximum=1_000_000): - if type(value) is not int or not 0 <= value <= maximum: - raise ValueError("invalid bounded count") - return value - - -def _json(raw): - def unique(pairs): - result = {} - for key, value in pairs: - if key in result: - raise ValueError("duplicate response field") - result[key] = value - return result - return _object(json.loads(raw.decode("utf-8"), object_pairs_hook=unique)) - - -def load_binding(path=BINDING_FILE): - info = path.lstat() - if path.is_symlink() or not path.is_file() or info.st_size > 16 * 1024: - raise ValueError("invalid binding file") - state = _json(path.read_bytes()) - baseline, publisher = _object(state.get("baseline")), _object(state.get("publisher")) - digest = state.get("digest") - if not isinstance(digest, str) or not re.fullmatch(r"[a-f0-9]{64}", digest) or baseline.get("digest") != digest or baseline.get("endpoint") != ORIGIN: - raise ValueError("invalid baseline binding") - if not isinstance(baseline.get("instance_id"), str) or not re.fullmatch(r"[a-f0-9]{32}", baseline["instance_id"]) or not isinstance(baseline.get("session_id"), str) or not re.fullmatch(r"[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}", baseline["session_id"]): - raise ValueError("invalid baseline session binding") - if type(state.get("next_entry")) is not int or state["next_entry"] != 0 or type(state.get("accepted")) is not int or state["accepted"] != 0 or state.get("exhausted") is not False or "finished_at" not in state or state["finished_at"] is not None: - raise ValueError("repository binding must contain a zero checkpoint") - tag = publisher.get("release_tag") - match = re.fullmatch(r"cve_(\d{4}-\d{2}-\d{2})_0000Z", tag or "") - if not match or publisher.get("asset") not in (f"{match[1]}_all_CVEs_at_midnight.zip", f"{match[1]}_all_CVEs_at_midnight.zip.zip"): - raise ValueError("invalid baseline publisher release") - datetime.strptime(match[1], "%Y-%m-%d") - return {"digest": digest, "endpoint": ORIGIN, "instance_id": baseline["instance_id"], "session_id": baseline["session_id"], "release_tag": tag, "asset": publisher["asset"]} - - -def request_json(path, *, body=None, secret=None, opener=None, timeout=40): - if path not in (PROOF_PATH, STATUS_PATH) or (path == PROOF_PATH) != (body is not None): - raise ValueError("invalid fixed advisory operation") - headers = {"Cache-Control": "no-cache", "User-Agent": "omg-advisory-baseline/1.0"} - if body is not None: - headers.update({"Authorization": f"Bearer {secret}", "Content-Type": "application/json"}) - request = urllib.request.Request(ORIGIN + path, data=json.dumps(body).encode("utf-8") if body is not None else None, headers=headers, method="POST" if body is not None else "GET") - with (opener or _transport.secure_opener()).open(request, timeout=timeout) as response: - if response.status != 200 or response.geturl() != ORIGIN + path: - raise ValueError("invalid fixed-origin response") - raw = response.read(MAX_BODY + 1) - if len(raw) > MAX_BODY or (secret and secret.encode() in raw) or (body and body["github_token"].encode() in raw): - raise ValueError("invalid response bounds or credential echo") - return _json(raw) - - -def proof_progress(reply, binding): - """Match the canonical operator.ts proofProgress contract; never certify locally.""" - reply = _object(reply) - if type(reply.get("schema_version")) is not int or reply["schema_version"] != 1 or any(reply.get(key) != binding[key] for key in ("digest", "release_tag", "asset")) or not isinstance(reply.get("commit_sha"), str) or not re.fullmatch(r"[a-f0-9]{40}", reply["commit_sha"]): - raise ValueError("publisher proof binding mismatch") - phase = reply.get("phase") - expected, verified, pending = (_integer(reply.get(key)) for key in ("expected_count", "verified_count", "pending_trees")) - if phase not in ("traversing", "reconciling", *STOP_PHASES) or verified > expected or type(reply.get("archive_verified")) is not bool: - raise ValueError("invalid proof progress") - if reply["archive_verified"] != (phase == "verified") or (phase == "verified" and (expected == 0 or verified != expected or pending != 0)): - raise ValueError("inconsistent server certification") - return {"phase": phase, "expected_count": expected, "verified_count": verified, "pending_trees": pending} - - -def warm(binding, github_token, secret, *, max_steps=MAX_PROOF_STEPS, opener=None, emit=print, clock=time.monotonic, sleep=time.sleep): - if type(max_steps) is not int or not 1 <= max_steps <= MAX_PROOF_STEPS or not re.fullmatch(r"ghs_[A-Za-z0-9._-]{20,2044}", github_token or "") or not re.fullmatch(r"[A-Za-z0-9_-]{32,256}", secret or ""): - raise ValueError("invalid proof operator bounds or credentials") - body = dict(binding, github_token=github_token) - deadline = clock() + PROOF_SECONDS - progress = None - completed = 0 - - def exhausted(): - if progress is None: - raise TimeoutError("proof budget expired before observing server progress") - emit(json.dumps(dict(progress, step=completed, budget_exhausted=1))) - return progress - - for step in range(max_steps): - for attempt in range(LEASE_ATTEMPTS): - remaining = deadline - clock() - if remaining <= 0: - return exhausted() - try: - reply = request_json(PROOF_PATH, body=body, secret=secret, opener=opener, timeout=min(40, remaining)) - break - except urllib.error.HTTPError as error: - if error.code != 409 or attempt + 1 == LEASE_ATTEMPTS: - raise - error.close() - # Five attempts, with 1/2/4/8-second backoffs for Cron lease contention. - delay = 2 ** attempt - if deadline - clock() <= delay: - return exhausted() - sleep(delay) - progress = proof_progress(reply, binding) - completed = step + 1 - emit(json.dumps(dict(progress, step=step + 1))) - if progress["phase"] in STOP_PHASES: - return progress - return progress - - -def _timestamp(value): - if not isinstance(value, str) or len(value) > 64 or not value.endswith("Z"): - raise ValueError("invalid source timestamp") - stamp = datetime.fromisoformat(value[:-1] + "+00:00") - if stamp.tzinfo is None: - raise ValueError("source timestamp has no timezone") - return stamp - - -class AdvisoryNotReady(ValueError): - """A release blocker with a fixed message safe to show to operators.""" - - -def release_readiness(reply, binding, *, now=None): - reply = _object(reply) - baseline = _object(reply.get("baseline")) - if type(reply.get("schema_version")) is not int or reply["schema_version"] != 1: - raise ValueError("invalid advisory status schema") - if baseline.get("archive_verified") is not True: - raise AdvisoryNotReady("publisher archive verification is pending") - if baseline.get("caught_up") is not True or _integer(baseline.get("imported")) == 0: - raise AdvisoryNotReady("publisher archive import or catch-up is incomplete") - feeds = reply.get("feeds") - if not isinstance(feeds, list) or not 1 <= len(feeds) <= 16 or any(type(feed) is not dict for feed in feeds): - raise ValueError("invalid source status") - names = [feed.get("source") for feed in feeds] - if any(not isinstance(name, str) for name in names) or len(names) != len(set(names)) or names.count("cve") != 1: - raise ValueError("ambiguous CVE source") - cve = next(feed for feed in feeds if feed["source"] == "cve") - if cve.get("baseline_digest") != binding["digest"]: - raise AdvisoryNotReady("CVE delta points to a different publisher archive") - if (reply.get("bootstrap_complete") is not True or cve.get("complete") is not True - or cve.get("fresh") is not True or type(cve.get("bootstrap_complete")) is not int - or cve["bootstrap_complete"] != 1 or cve.get("error") is not None): - raise AdvisoryNotReady("CVE delta feed is incomplete or stale") - observed = now or datetime.now(timezone.utc) - checked = _timestamp(cve.get("checked_at")) - if not -60 <= (observed - checked).total_seconds() <= 30 * 60: - raise AdvisoryNotReady("CVE delta status is stale or future-dated") - cursor = cve.get("cursor") - if not isinstance(cursor, str) or len(cursor) > 512: - raise ValueError("CVE delta cursor unavailable") - cursor = _json(cursor.encode()) - if set(cursor) != {"event", "offset"} or _timestamp(cursor["event"]) > observed or type(cursor["offset"]) is not int: - raise ValueError("invalid CVE delta position") - _integer(cursor["offset"]) - return {"phase": "release_ready", "imported": baseline["imported"]} - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("operation", choices=("warm", "status")) - parser.add_argument("--max-steps", type=int, default=MAX_PROOF_STEPS) - args = parser.parse_args() - try: - binding = load_binding() - if args.operation == "warm": - warm(binding, os.environ.get("GITHUB_TOKEN"), os.environ.get("RUNTIME_REFRESH_SECRET"), max_steps=args.max_steps) - else: - print(json.dumps(release_readiness(request_json(STATUS_PATH), binding))) - return 0 - except urllib.error.HTTPError as error: - print(f"Advisory {args.operation} refused: HTTP {error.code}", file=sys.stderr) - error.close() - except AdvisoryNotReady as error: - print(f"Advisory release check refused because {error}.", file=sys.stderr) - except (urllib.error.URLError, TimeoutError, ValueError, UnicodeError, OSError, KeyError, TypeError): - print(f"Advisory {args.operation} unavailable, incomplete, or bound to a different baseline", file=sys.stderr) - return 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/refresh-runtime-advisories.py b/scripts/refresh-runtime-advisories.py deleted file mode 100644 index c84064f04..000000000 --- a/scripts/refresh-runtime-advisories.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Refresh fixed vendor advisory caches using a short-lived Actions job token.""" - -import json -import os -import re -import ssl -import sys -import urllib.error -import urllib.request - -ENDPOINT = "https://omg-advisories.latham.workers.dev/internal/runtime-refresh" -RUNTIMES = ("python", "rust", "ruby", "java", "bun", "deno", "zig", "erlang", "php", "swift") -MAX_RESPONSE_BYTES = 256 * 1024 - - -class NoRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, request, response, code, message, headers, new_url): - return None - - -def secure_opener(): - return urllib.request.build_opener( - urllib.request.ProxyHandler({}), - urllib.request.HTTPSHandler(context=ssl.create_default_context()), - NoRedirect(), - ) - - -def refresh_all(github_token, refresh_secret, opener=None): - if not re.fullmatch(r"ghs_[A-Za-z0-9._-]{20,2044}", github_token or "") or not re.fullmatch( - r"[A-Za-z0-9_-]{32,256}", refresh_secret or "" - ): - print("Runtime refresh credentials are missing or invalid", file=sys.stderr) - return 2 - opener = opener if opener is not None else secure_opener() - failures = 0 - for runtime in RUNTIMES: - request = urllib.request.Request( - ENDPOINT, - data=json.dumps({"runtime": runtime, "github_token": github_token}).encode("utf-8"), - headers={ - "Authorization": f"Bearer {refresh_secret}", - "Content-Type": "application/json", - "User-Agent": "omg-runtime-feed-refresh/1.0", - }, - method="POST", - ) - try: - with opener.open(request, timeout=40) as response: - raw = response.read(MAX_RESPONSE_BYTES + 1) - if response.status != 200 or len(raw) > MAX_RESPONSE_BYTES: - raise ValueError("invalid refresh response") - report = json.loads(raw.decode("utf-8")) - if not isinstance(report, dict) or report.get("schema_version") != 1 or report.get("runtime") != runtime: - raise ValueError("refresh identity mismatch") - sources = report.get("sources") - if report.get("refreshed") is not True or report.get("coverage") not in ("assessed", "partial", "unknown") or not isinstance(sources, list) or not sources or not all( - isinstance(source, dict) and source.get("complete") is True for source in sources - ): - raise ValueError("incomplete refresh") - print(f"{runtime}: refreshed {len(sources)} sources; coverage={report['coverage']}") - except urllib.error.HTTPError as error: - failures += 1 - print(f"{runtime}: refresh HTTP {error.code}", file=sys.stderr) - error.close() - except (urllib.error.URLError, TimeoutError, ValueError, UnicodeError, OSError): - failures += 1 - print(f"{runtime}: refresh unavailable or incomplete", file=sys.stderr) - return 1 if failures else 0 - - -if __name__ == "__main__": - raise SystemExit(refresh_all(os.environ.get("GITHUB_TOKEN"), os.environ.get("RUNTIME_REFRESH_SECRET"))) diff --git a/scripts/test_advisory_baseline.py b/scripts/test_advisory_baseline.py index 88ef38402..29f6bfb43 100644 --- a/scripts/test_advisory_baseline.py +++ b/scripts/test_advisory_baseline.py @@ -1,304 +1,16 @@ -import importlib.util -import copy -from contextlib import redirect_stderr -from datetime import datetime, timezone -import http.server -import io -import json import os from pathlib import Path import subprocess import tempfile -import threading import unittest -from unittest import mock -import urllib.error -import urllib.request from test_ci_gates import job_block from test_release_workflow_boundaries import BASH, step_script ROOT = Path(__file__).resolve().parent.parent -SPEC = importlib.util.spec_from_file_location("advisory_baseline", ROOT / "scripts/advisory-baseline.py") -DRIVER = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(DRIVER) -NOW = datetime(2026, 11, 17, 12, tzinfo=timezone.utc) -JOB_TOKEN = "ghs_12345_fixture.header-" + "0" * 475 + ".signature_fixture" -SECRET = "fixture_refresh_secret_" + "x" * 32 - - -class Response: - def __init__(self, value, path=DRIVER.PROOF_PATH, status=200, raw=None, url=None): - self.raw = json.dumps(value).encode() if raw is None else raw - self.status, self.url = status, url or DRIVER.ORIGIN + path - - def __enter__(self): - return self - - def __exit__(self, *_args): - return False - - def geturl(self): - return self.url - - def read(self, count): - return self.raw[:count] - - -class Opener: - def __init__(self, responses): - self.responses, self.calls = list(responses), [] - - def open(self, request, timeout): - self.calls.append((request, timeout)) - response = self.responses.pop(0) - if isinstance(response, Exception): - raise response - return response - - -def progress(binding, **changes): - return dict(schema_version=1, phase="traversing", expected_count=42, verified_count=0, - pending_trees=3, archive_verified=False, commit_sha="a" * 40, - **{key: binding[key] for key in ("digest", "release_tag", "asset")}) | changes - - -def status(binding): - return {"schema_version": 1, "baseline": {"imported": 42, "caught_up": True, "archive_verified": True}, - "bootstrap_complete": True, "feeds": [{"source": "cve", "complete": True, - "fresh": True, "bootstrap_complete": 1, "error": None, - "baseline_digest": binding["digest"], "checked_at": "2026-11-17T11:59:00.000Z", - "cursor": json.dumps({"event": "2026-11-17T11:58:00.000Z", "offset": 0})}]} - - -class AdvisoryBaselineDriverTests(unittest.TestCase): - def setUp(self): - self.binding = DRIVER.load_binding() - - def test_binding_rejects_stale_checkpoint_and_external_endpoint(self): - saved = json.loads(DRIVER.BINDING_FILE.read_text(encoding="utf-8")) - for change in ("endpoint", "digest", "checkpoint", "numeric-instance", "missing-finish"): - broken = copy.deepcopy(saved) - if change == "endpoint": - broken["baseline"]["endpoint"] = "https://untrusted.invalid" - elif change == "digest": - broken["baseline"]["digest"] = "0" * 64 - elif change == "numeric-instance": - broken["baseline"]["instance_id"] = int("1" * 32) - elif change == "missing-finish": - del broken["finished_at"] - else: - broken.update(accepted=42, next_entry=42, exhausted=True, finished_at="2026-11-17T00:00:00.000Z") - with self.subTest(change=change), tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "binding.json" - path.write_text(json.dumps(broken), encoding="utf-8") - with self.assertRaises(ValueError): - DRIVER.load_binding(path) - - def test_warming_is_serial_bounded_and_stops_for_real_import(self): - opener = Opener([Response(progress(self.binding)), Response(progress(self.binding, phase="awaiting_import", pending_trees=0))]) - output = [] - result = DRIVER.warm(self.binding, JOB_TOKEN, SECRET, opener=opener, emit=output.append) - self.assertEqual(result["phase"], "awaiting_import") - self.assertEqual(len(opener.calls), 2) - for request, timeout in opener.calls: - self.assertEqual(request.full_url, DRIVER.ORIGIN + DRIVER.PROOF_PATH) - self.assertEqual(request.method, "POST") - self.assertEqual(timeout, 40) - self.assertEqual(request.get_header("Authorization"), "Bearer " + SECRET) - body = json.loads(request.data) - self.assertEqual(body, dict(self.binding, github_token=JOB_TOKEN)) - self.assertNotIn("accepted", body) - for line in output: - row = json.loads(line) - self.assertEqual(set(row), {"phase", "expected_count", "verified_count", "pending_trees", "step"}) - self.assertNotIn(JOB_TOKEN, line) - self.assertNotIn(SECRET, line) - - def test_budget_exhaustion_never_claims_verified(self): - opener = Opener([Response(progress(self.binding)) for _ in range(20)]) - result = DRIVER.warm(self.binding, JOB_TOKEN, SECRET, max_steps=20, opener=opener, emit=lambda _line: None) - self.assertEqual(result["phase"], "traversing") - self.assertEqual(len(opener.calls), 20) - - def test_one_run_can_finish_the_full_publisher_traversal_and_reconciliation(self): - replies = [Response(progress(self.binding)) for _ in range(185)] - replies.append(Response(progress(self.binding, phase="verified", archive_verified=True, - expected_count=424_926, verified_count=424_926, pending_trees=0))) - opener = Opener(replies) - result = DRIVER.warm(self.binding, JOB_TOKEN, SECRET, max_steps=256, opener=opener, emit=lambda _line: None) - self.assertEqual(result["phase"], "verified") - self.assertEqual(len(opener.calls), 186) - - def test_cron_lease_contention_retries_five_attempts_with_bounded_backoff(self): - errors = [urllib.error.HTTPError(DRIVER.ORIGIN + DRIVER.PROOF_PATH, 409, "busy", {}, None) for _ in range(4)] - opener = Opener(errors + [Response(progress(self.binding, phase="awaiting_catchup", pending_trees=0))]) - delays = [] - result = DRIVER.warm(self.binding, JOB_TOKEN, SECRET, opener=opener, sleep=delays.append, emit=lambda _line: None) - self.assertEqual(result["phase"], "awaiting_catchup") - self.assertEqual(delays, [1, 2, 4, 8]) - self.assertEqual(len(opener.calls), 5) - self.assertTrue(all(error.closed for error in errors)) - - def test_lease_retries_are_capped_and_other_http_errors_are_not_retried(self): - for status_code, expected_calls, expected_delays in ((409, 5, [1, 2, 4, 8]), (403, 1, [])): - errors = [urllib.error.HTTPError(DRIVER.ORIGIN + DRIVER.PROOF_PATH, status_code, "controlled failure", {}, None) for _ in range(expected_calls)] - opener, delays = Opener(errors), [] - with self.subTest(status_code=status_code), self.assertRaises(urllib.error.HTTPError) as rejected: - DRIVER.warm(self.binding, JOB_TOKEN, SECRET, opener=opener, sleep=delays.append, emit=lambda _line: None) - rejected.exception.close() - self.assertEqual(len(opener.calls), expected_calls) - self.assertEqual(delays, expected_delays) - - def test_total_monotonic_deadline_caps_requests_without_claiming_verification(self): - elapsed = [0.0] - class TimedOpener(Opener): - def open(self, request, timeout): - response = super().open(request, timeout) - elapsed[0] += min(37, timeout) - return response - opener = TimedOpener([Response(progress(self.binding)) for _ in range(256)]) - output = [] - result = DRIVER.warm(self.binding, JOB_TOKEN, SECRET, opener=opener, - clock=lambda: elapsed[0], emit=output.append) - self.assertEqual(elapsed[0], 480) - self.assertEqual(len(opener.calls), 13) - self.assertEqual(opener.calls[-1][1], 36) - self.assertEqual(result["phase"], "traversing") - self.assertEqual(json.loads(output[-1])["budget_exhausted"], 1) - - def test_deadline_without_server_progress_cannot_fabricate_a_phase(self): - clock = iter((0, 481)) - opener, output = Opener([]), [] - with self.assertRaises(TimeoutError): - DRIVER.warm(self.binding, JOB_TOKEN, SECRET, opener=opener, - clock=lambda: next(clock), emit=output.append) - self.assertEqual(opener.calls, []) - self.assertEqual(output, []) - - def test_personal_token_and_invalid_secret_never_reach_transport(self): - opener = Opener([]) - for token, secret in (("ghp_" + "fixturefake" + "0" * 25, SECRET), (JOB_TOKEN, "short")): - with self.subTest(token_kind=token[:4]), self.assertRaises(ValueError): - DRIVER.warm(self.binding, token, secret, opener=opener) - self.assertEqual(opener.calls, []) - - def test_stale_or_fabricated_publisher_proofs_cannot_certify(self): - for fields in ( - {"digest": "0" * 64}, {"asset": "different.zip"}, {"release_tag": "cve_2000-01-01_0000Z"}, - {"commit_sha": "bad"}, {"commit_sha": int("1" * 40)}, {"phase": "verified", "archive_verified": False}, - {"phase": "verified", "archive_verified": True, "expected_count": 0, "verified_count": 0, "pending_trees": 0}, - {"phase": "verified", "archive_verified": True, "verified_count": 41, "pending_trees": 0}, - {"phase": "verified", "archive_verified": True, "verified_count": 42, "pending_trees": 1}, - {"archive_verified": True}, {"expected_count": True}, - ): - with self.subTest(fields=fields), self.assertRaises(ValueError): - DRIVER.proof_progress(progress(self.binding, **fields), self.binding) - self.assertEqual(DRIVER.proof_progress(progress(self.binding, phase="verified", archive_verified=True, verified_count=42, pending_trees=0), self.binding)["phase"], "verified") - - def test_fixed_origin_transport_rejects_redirect_oversize_and_credential_echo(self): - for response in ( - Response({}, status=302), Response({}, url="https://untrusted.invalid/leak"), - Response({}, raw=b"x" * (DRIVER.MAX_BODY + 1)), - Response({"echo": JOB_TOKEN}), Response({"echo": SECRET}), - ): - opener = Opener([response]) - with self.subTest(response=response.url), self.assertRaises(ValueError): - DRIVER.request_json(DRIVER.PROOF_PATH, body=dict(self.binding, github_token=JOB_TOKEN), secret=SECRET, opener=opener) - self.assertEqual(len(opener.calls), 1) - with self.assertRaises(ValueError): - DRIVER.request_json("https://untrusted.invalid/leak") - - def test_actual_secure_opener_does_not_follow_redirect_or_environment_proxy(self): - paths = [] - class Handler(http.server.BaseHTTPRequestHandler): - def do_GET(self): - paths.append(self.path) - self.send_response(302) - self.send_header("Location", "/credential-trap") - self.end_headers() - def log_message(self, *_args): - return - server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) - worker = threading.Thread(target=server.serve_forever, daemon=True) - worker.start() - try: - with mock.patch.dict(os.environ, {"HTTP_PROXY": "http://127.0.0.1:1", "http_proxy": "http://127.0.0.1:1", "NO_PROXY": "", "no_proxy": ""}): - opener = DRIVER._transport.secure_opener() - request = urllib.request.Request(f"http://127.0.0.1:{server.server_port}/original", headers={"Authorization": "Bearer " + SECRET}) - with self.assertRaises(urllib.error.HTTPError) as rejected: - opener.open(request, timeout=5) - self.assertEqual(rejected.exception.code, 302) - rejected.exception.close() - self.assertEqual(paths, ["/original"]) - finally: - server.shutdown() - server.server_close() - worker.join(timeout=5) - - def test_readiness_uses_server_certification_and_fresh_delta_not_operator_count(self): - ready = status(self.binding) - self.assertEqual(DRIVER.release_readiness(ready, self.binding, now=NOW)["phase"], "release_ready") - ready["baseline"]["imported"] = 1 - self.assertEqual(DRIVER.release_readiness(ready, self.binding, now=NOW)["imported"], 1) - for change in ("archive", "bootstrap", "catchup", "count-only", "stale", "future", "binding", "error", "duplicate", "cursor", "flag-type"): - broken = status(self.binding) - cve = broken["feeds"][0] - if change in ("archive", "count-only"): - broken["baseline"].update(archive_verified=False, imported=999_999) - elif change == "bootstrap": broken["bootstrap_complete"] = False - elif change == "catchup": broken["baseline"]["caught_up"] = False - elif change == "stale": cve["checked_at"] = "2026-11-17T11:29:59.000Z" - elif change == "future": cve["checked_at"] = "2026-11-17T12:01:01.000Z" - elif change == "binding": cve["baseline_digest"] = "0" * 64 - elif change == "error": cve["error"] = "partial upstream" - elif change == "duplicate": broken["feeds"].append(dict(cve)) - elif change == "cursor": cve["cursor"] = "null" - elif change == "flag-type": cve["complete"] = 1 - with self.subTest(change=change), self.assertRaises(ValueError): - DRIVER.release_readiness(broken, self.binding, now=NOW) - - def test_public_readiness_request_never_sends_credentials(self): - opener = Opener([Response(status(self.binding), path=DRIVER.STATUS_PATH)]) - reply = DRIVER.request_json(DRIVER.STATUS_PATH, opener=opener) - self.assertTrue(reply["bootstrap_complete"]) - request, _timeout = opener.calls[0] - self.assertEqual(request.get_header("Cache-control"), "no-cache") - self.assertIsNone(request.get_header("Authorization")) - self.assertIsNone(request.data) - - def test_status_names_archive_and_delta_blockers_without_printing_provider_text(self): - for archive_verified, reason in ( - (False, "publisher archive verification is pending"), - (True, "CVE delta feed is incomplete or stale"), - ): - reply = status(self.binding) - reply["baseline"]["archive_verified"] = archive_verified - reply["bootstrap_complete"] = False - reply["feeds"][0].update(complete=False, bootstrap_complete=0, error=SECRET) - stderr = io.StringIO() - with self.subTest(archive_verified=archive_verified), \ - mock.patch.object(DRIVER.sys, "argv", ["advisory-baseline.py", "status"]), \ - mock.patch.object(DRIVER, "request_json", return_value=reply), \ - redirect_stderr(stderr): - self.assertEqual(DRIVER.main(), 1) - self.assertIn(reason, stderr.getvalue()) - self.assertNotIn(SECRET, stderr.getvalue()) class AdvisoryReleaseBoundaryTests(unittest.TestCase): - def test_warming_stays_on_trusted_main_with_read_only_job_token(self): - workflow = (ROOT / ".github/workflows/advisory-refresh.yml").read_text(encoding="utf-8") - self.assertIn("contents: read", workflow) - self.assertNotIn("pull_request", workflow) - job = job_block(workflow, "baseline-proof") - self.assertIn("if: github.ref == 'refs/heads/main'", job) - self.assertIn("GITHUB_TOKEN: ${{ github.token }}", job) - self.assertIn("RUNTIME_REFRESH_SECRET: ${{ secrets.RUNTIME_REFRESH_SECRET }}", job) - self.assertIn("persist-credentials: false", job) - self.assertIn("warm --max-steps 256", job) - self.assertIn("timeout-minutes: 10", job) - def test_publication_has_no_live_advisory_readiness_dependency(self): release = (ROOT / ".github/workflows/release.yml").read_text(encoding="utf-8") self.assertNotIn("advisory-baseline.py status", release) diff --git a/scripts/test_ci_optimization.py b/scripts/test_ci_optimization.py index 681567d5c..ab7fb8e81 100644 --- a/scripts/test_ci_optimization.py +++ b/scripts/test_ci_optimization.py @@ -231,34 +231,10 @@ def pr_event(pr_head=head, pr_base=base): self.assertNotEqual(result.returncode, 0) self.assertEqual(calls, []) - @unittest.skipIf(os.name == "nt", "The hosted service workflow uses POSIX executable scripts") - def test_advisory_service_is_verified_without_remote_deployment(self): + def test_cli_workflow_uses_the_public_service_boundary(self): workflow = job_block((WORKFLOWS / 'ci.yml').read_text(), 'workflow-checks') - steps = dict(re.findall(r'^ - name: ([^\n]+)\n(.*?)(?=^ - (?:name:|uses:)|\Z)', - workflow, re.MULTILINE | re.DOTALL)) - scripts = [textwrap.dedent(block.split(' run: |\n', 1)[1]) - for name, block in steps.items() if name == 'Verify Arch advisory service'] - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - commands = root / 'commands.jsonl' - commands.touch() - recorder = root / 'bun' - recorder.write_text('#!' + sys.executable + '\nimport json,os,sys\n' - 'with open(os.environ["BUN_COMMANDS"], "a") as stream: ' - 'stream.write(json.dumps(sys.argv[1:])+"\\n")\n') - recorder.chmod(0o755) - for script in scripts: - result = subprocess.run([BASH, '-euo', 'pipefail', '-c', script], - env=dict(os.environ, PATH=str(root) + os.pathsep + os.environ.get('PATH', ''), - BUN_COMMANDS=str(commands)), capture_output=True, text=True, timeout=10) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - calls = [json.loads(line) for line in commands.read_text().splitlines()] - self.assertEqual(calls, [ - ['install', '--cwd', 'services/advisories', '--frozen-lockfile', '--ignore-scripts'], - ['run', '--cwd', 'services/advisories', 'test'], - ['run', '--cwd', 'services/advisories', 'check'], - ['run', '--cwd', 'services/advisories', 'dry-run'], - ], 'The advisory service must have frozen dependencies, behavioral tests, types and a non-deploying build') + self.assertNotIn('services/advisories', workflow) + self.assertNotIn('advisory-staging', workflow) @unittest.skipIf(os.name == 'nt', 'Native Arch input permissions require POSIX mode bits') def test_native_coverage_stages_protected_inputs_from_writable_sources(self): diff --git a/services/advisories/.gitignore b/services/advisories/.gitignore deleted file mode 100644 index 70df744e8..000000000 --- a/services/advisories/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules/ -.wrangler/ -.dev.vars* -.env* -*.bootstrap-state.json diff --git a/services/advisories/README.md b/services/advisories/README.md deleted file mode 100644 index 84cb49fed..000000000 --- a/services/advisories/README.md +++ /dev/null @@ -1,225 +0,0 @@ -# OMG advisory service - -This Worker serves public CVE records, Arch security issues, CISA KEV annotations, EPSS enrichment and vendor-specific assessments for 13 runtimes. An additional npm package assessment covers the Pi coding harness. OMG needs only its HTTPS URL. Arch package version comparisons remain in Rust's ALPM backend. A CVE identifier alone does not establish package or runtime applicability. - -D1 stores the current CVE index, provenance, feed checkpoints, leases, compact ingestion runs, baseline receipts, and KEV annotations. Private R2 stores payloads by SHA-256. A payload is persisted before its D1 pointer. Failed SQL may leave an unreferenced R2 object; SQL cannot reference a failed object write. Older CVE revisions cannot overwrite newer rejected records. Each production writer batch checks the current owner and lease expiry in a constraint guard inside the same D1 transaction. An expired or replaced writer cannot overwrite a snapshot, cursor, KEV membership or source error. Private content-addressed R2 orphans can remain after a fenced-out commit. All SQL values use prepared bindings. No client-supplied URL is fetched. - -## HTTP contract - -Public lookups require no Cloudflare account credentials. The v1 package discovery routes accept package names. The authenticated v2 pilot accepts exact versions. - -| Route | Response | -| --- | --- | -| `/v1/status` | Schema version 1, archive bootstrap flag, per-feed completion, checked/fetched times, freshness and last ingestion error. The additive `cve_delta` object shows the current cursor and the last fully consumed publisher event. | -| `/v1/reconciliation/nvd` | Live status of the NVD cross-check, including its last complete window and any pending verification. Uses `no-store`. | -| `/v1/arch/advisories` | `{schema_version:1,source:"arch-security",fetched_at,checked_at,complete,payload_sha256,payload_json:"exact upstream JSON string"}`. Returns 503 before a snapshot exists. | -| `/v1/cves/CVE-YYYY-NNNN` | Original CVE JSON string under `payload_json`, source provenance, optional KEV annotation and its independent freshness. Returns 404 for a missing record. | -| `/v1/cves/CVE-YYYY-NNNN?view=summary` | CVE provenance, completeness, and KEV annotation from one SQL read. Omits the original payload. | -| `/v1/cves/dashboard` | Feed status and up to 100 recent CVE revisions from one database snapshot. The returned cursor continues through `/v1/cves/recent`. | -| `/v1/cves/recent?limit=100&cursor=...` | Latest stored revisions modified within a rolling 30-day window, metadata only, newest first. At most 100 rows; opaque next cursor fixes the window for pagination. Independent CVE completeness and freshness remain explicit. | -| `/v1/epss/CVE-YYYY-NNNN` | FIRST exploitation probability, percentile and bounded history, with explicit missing/unavailable states. | -| `/v1/runtimes/{runtime}?version=...&vendor=...&os=...&arch=...` | Exact identity, coverage, disclosed findings, applicability gaps and source content hashes. All four parameters are mandatory and unique. | - -`fetched_at` identifies payload acquisition. `checked_at` also advances after a trusted upstream 304 revalidation. A feed is stale after 30 minutes. The Arch snapshot remains available with `complete:false` when stale or after refresh failure. Original `Unknown` Arch issue states remain visible to Rust; snapshot completeness does not turn them into known package safety results. - -The CVE delta's `completed_through` and `completed_offset` advance only after a validated feed response has been fully consumed and its selected revisions committed. The offset counts records with the same publisher timestamp. A partial batch can advance `cursor_event` and `cursor_offset` while the watermark remains at the last completed scan. Starting a new baseline resets the watermark. `cve_delta.state` describes live catch-up independently of archive verification. Its values are `unavailable`, `catching_up`, `caught_up`, `stale`, and `error`. Existing deployments acquire a watermark on the next complete check. - -Scheduled intake uses the CVE Project's commit Atom feed to pin the delta and its records to an immutable revision. The existing branch endpoint remains available when commit discovery is unavailable. If an official record download fails, CVE Services can provide that identifier directly. The fallback must return the exact ID and a supported revision at least as recent as the delta entry. Every five minutes, a bounded CIRCL discovery check can also recover missing or newer published records through CVE Services. It cannot advance the primary cursor or certify feed completeness. CISA KEV falls back to its official GitHub mirror if the primary request fails. Publisher revision and integrity checks still apply. - -The NVD CVE 2.0 API separately checks for missing IDs by NVD publication time. It starts with four hours of publications, then opens an overlapping window every two hours. A bounded page is checked every five minutes while the window is in progress. Missing IDs must match verified, supported CVE Services records before admission. On a failed page or unverified record, the check retries without advancing that page or the primary publisher cursor. NVD timestamps and enrichment do not replace publisher data. This product uses data from the NVD API but is not endorsed or certified by the NVD. [NVD API](https://nvd.nist.gov/developers/vulnerabilities) - -These are scheduled source checks. Each upstream controls publication and replication. A recent source check is not a guarantee that an upstream has published every applicable advisory. - -The scheduled CVE intake runs each minute. PostgreSQL accepts up to 512 publisher changes per invocation and commits the cursor after each group of at most 128 admitted changes. An interrupted invocation preserves its committed progress. Arch and KEV retain their five-minute schedule. The D1 deployment retains its 32-record intake limit. - -Successful fresh public data responses use full-representation SHA-256 ETags and the Workers Cache API. Cache lifetime is at most 60 seconds and ends before any included source check becomes stale. Fresh partial datasets retain `complete:false`; caching does not certify coverage. `/v1/status`, private or authenticated/cookie-bearing requests, errors and stale data return `Cache-Control: no-store`. `If-None-Match` supports conditional 304 responses; `Cache-Control: no-cache` or `max-age=0` forces an origin read for an update. Cache failures fall back to D1/R2. The Cache API is local to each Cloudflare data center, so cold requests still read storage; no production latency guarantee is implied. - -The recent view contains upstream modification times in `[as_of - 30 days, as_of]`. It includes rejected revisions and excludes future-dated entries. Older records remain directly retrievable; no CVEs or raw payloads are deleted. It is a latest-revision view rather than an immutable event history. Newer revisions can move between pages: clients must overlap subsequent refreshes and cannot infer a complete corpus from one traversal. Limits are 1–100, default 100; cursors expire after one hour. Unknown/duplicate parameters and malformed cursors fail with 400. Encode `next_cursor` as a query parameter using `URLSearchParams` or equivalent. - -Apply `0003_recent_cves.sql` before deploying the recent-view route. It adds a modification-time/ID index without changing existing data or writers. Index creation has a one-time read/write cost proportional to existing records; include that migration and continuing index maintenance in the account's quota/credit budget before remote execution. The migration and cache route were deployed and verified on 2026-11-16 as Worker version `1ae795ee-841f-4f78-9a99-da9ee600e18e`; the production page query read two rows for two records, and live warm/conditional/revalidation/private-isolation checks passed. See the compact receipt in `docs/superpowers/plans/2026-11-16-advisory-cache-production-receipt.md` at the repository root. Runtime assessment implementation below requires migration `0005_runtime_sources.sql`; its local test evidence does not establish production deployment. - -CVE bootstrap completeness remains false until the server independently reconciles every expected publisher Git member and original payload identity, then verifies completed delta catchup. Operator counts and ZIP exhaustion alone cannot certify archive coverage. Unknown CVE schemas/states are preserved, marked unsupported and block bootstrap completion. This is a metadata boundary validator, not a full implementation of the CVE JSON Schema. CNA and ADP content is preserved without attempting package matching. - -Private POST routes use a separate Worker secret `INGEST_TOKEN`, at least 32 random characters. Authorization is checked before reading the body or touching storage. HMAC verification uses Web Crypto rather than a handwritten timing comparison. - -* `/internal/ingest` accepts `{source:"cve",records:[originalJsonString,...],baseline?:{digest,instance_id,session_id,endpoint}}`. Baseline imports require the binding returned by baseline start; server-side membership counts distinct successfully imported CVE IDs, separately from delta ingestion. Maximum eight generic records or 64 distinct supported records with a baseline binding, 3 MiB of original UTF-8 JSON each, 4 MiB for the complete encoded request. Baseline bulk persistence uses at most six concurrent R2 puts, drains every started write before returning failure, and commits pointers and membership together under the writer fence. Generic and delta ingestion retain four-way concurrency. -* `/internal/cve-refresh` accepts exactly `{}` under the ingest credential. It runs one fixed official CVE delta batch of at most 32 records under the same source lease and commit fence, returning the actual cursor and completion state. Serial operator calls can drain backlog between scheduled runs; they cannot change archive certification or bootstrap completeness. -* `/internal/baseline/start` accepts the archive digest and midnight timestamp, initializes the delta watermark, and clears bootstrap completeness. It returns a database instance ID, import session ID, digest and endpoint origin. Resume requests and operator state bind all four values. Repeating the same active receipt does not rewind progress. -* `/internal/baseline` accepts the operator archive receipt after post-import catchup. It verifies the instance/session/endpoint/digest binding, exact server-counted distinct imported membership, fresh completed delta checkpoint, post-import check time, and absence of unsupported records under the CVE writer fence. Success returns `imported`, `caught_up:true`, `archive_verified:false` and `bootstrap_complete:false`. The operator exhaustion assertion is recorded but cannot certify archive coverage. - -Baseline membership is append-only. The writer inserts with `ON CONFLICT DO NOTHING`; migration `0002_baseline_member_counter.sql` maintains `baseline_receipt.accepted` with an `AFTER INSERT` trigger, so replay does not increment the distinct-member count. Member updates and deletes abort. Future member removal or rewriting requires an intentional migration that revises the triggers and reconciles the counter, rather than a new maintenance endpoint. Every import attempt clears its session's caught-up receipt even when all members were already present. Status reads the maintained count; finalization performs one membership count and rejects disagreement with the maintained counter or operator receipt. - -An import processes at most four distinct CVE IDs concurrently. Revisions of the same ID retain their request order, including rejection and conflicting-revision checks. Every started group settles before the writer lease is released, even when another group fails. A failed request can therefore leave successful records committed; the operator advances its resume position only after a successful response and safely replays otherwise. The eight-record and four-MiB request limits remain in force. - -Apply `0002` before deploying the Worker that reads the maintained counter. It reconciles existing sessions once and installs the triggers in the same migration batch. The already deployed `0001` migration is unchanged. The previous Worker remains compatible after `0002`, while the new Worker requires `0002` for correct counts. - -The ingest secret is a trusted operator capability. SHA-256 is computed over the UTF-8 encoding of the exact `payload_json` string. Consumers can verify the advertised hash before parsing it. JSON whitespace and key order are preserved. Invalid UTF-8 and UTF-8 BOMs are rejected. For archive certification, the server enumerates the official publisher's Git tree and reconciles each expected CVE ID and original blob identity against the import ledger. The [archive bootstrap procedure](#archive-bootstrap) covers this verification step. - -## Local checks - -```sh -bun install --frozen-lockfile -bun test test -bun run check -bun run types -bun run dry-run -bunx wrangler d1 migrations apply DB --local -bunx wrangler dev --ip 127.0.0.1 --port 8794 --test-scheduled -``` - -The migration and service tests use real SQLite. A separate Miniflare test uses real local D1 `meta.rows_read` to bound mutation reads for 128 and 256 successful imports and status reads at both membership sizes. Its private fixture storage has a 50 MiB limit and is disposed and removed after each run. It measures query rows rather than wall-clock speed or production CPU. Archive tests use tiny checked-in ZIP fixtures with no remote writes. All Wrangler resource bindings above are local unless explicitly told otherwise. - -## Provisioning and deployment - -The dedicated service is deployed at `https://omg-advisories.latham.workers.dev`. The committed configuration binds its dedicated `omg-advisories` D1 database and private `omg-advisories-raw` R2 bucket. Do not substitute the unrelated platform database. Check `/v1/status` for the current archive import count, publisher verification, and feed freshness. The Rust client validates the Arch snapshot separately from global CVE bootstrap status. - -For an update to this deployment, apply reviewed migrations before deploying code that depends on them: - -```sh -bun install --frozen-lockfile -bunx wrangler d1 migrations apply DB --remote -bun run types -bun run check -bun test test -bun run dry-run -bunx wrangler deploy --strict --secrets-file /absolute/private/advisories-secrets.json -``` - -The private JSON secret file contains `INGEST_TOKEN` and must be owned by the operator with mode `0600`. It is outside the repository. Preserve an existing secret when deploying without a secret update. A new account needs separately provisioned dedicated resources and matching configuration; validate its storage, write and CPU budgets before a historical import. - -`secret put` creates a deployed Worker version. The bucket is private and has no configured public access. The public API is read only; its private write routes still require the operator secret. Do not store a Cloudflare account/API token in OMG or in this ingest secret. - -The five-minute Cron reads only fixed official Arch, CISA and CVEProject URLs. The CVE rolling log is parsed incrementally with pinned `@streamparser/json` 0.0.26. It retains one event and the next bounded batch, validates the whole response before advancing the cursor, and rejects redirects. Event timestamp plus sorted position permits large events to span invocations. Scheduled refreshes and operator imports share a bounded ingestion routine: at most four distinct CVE IDs run concurrently, revisions of one ID remain serial, and all started work settles before a failure releases the writer lease. The delta cursor advances only after the entire selected batch succeeds. Failed batches replay idempotently. An expired ten-minute lease permits recovery. Falling behind the oldest retained delta requires a fresh archive reconciliation. - -The five-minute Cron admits up to 128 changes per invocation on PostgreSQL and 32 on D1, with a 30,000 ms CPU cap. The authenticated operator endpoint retains its 32-record limit. Multiple updates for one CVE stay ordered. Upstream bursts can still leave a backlog. `/v1/status` reports delta freshness and completion. See [release operations](../../docs/release-operations.md) for publication checks. Regenerate binding types and verify runtime limits when changing the worker configuration. - -Bounds are explicit. CVE records are 3 MiB, snapshots 16 MiB, delta transport 64 MiB, a streamed event about 8 MiB, an archive 1 GiB compressed, a CVE ZIP entry 3 MiB, and compression ratio 500. Oversized input fails partial. KEV normalized annotation JSON is capped below D1's 2,000,000-byte string limit. Updates replace its annotation index atomically only when content changes. Ingestion-run rows are retired after seven days. R2 retains historical payload hashes and SQL-failure orphans; a reviewed garbage collection policy remains future operator work. - -## Public registry assessment pilot - -`POST /v2/packages/assess` is an opt-in shadow endpoint. Set a dedicated Worker secret `PACKAGE_ASSESSMENT_TOKEN` with at least 32 random characters. The endpoint is unavailable without this secret. Use `Authorization: Bearer …` and `Content-Type: application/json`. - -```json -{ - "packages": [ - { "ecosystem": "npm", "name": "lodash", "version": "4.17.21" }, - { "ecosystem": "PyPI", "name": "requests", "version": "2.32.5" } - ] -} -``` - -The batch carries one to eight public npm or PyPI coordinates and receives one result per input in order. Repeated coordinates share the same upstream request within a batch. The Worker sends package coordinates to OSV. Use the pilot for known public registry packages, since a coordinate alone cannot establish artifact origin or authenticity. The response uses `Cache-Control: no-store`. The Worker neither stores the submitted inventory nor forwards the pilot token or cookies to OSV. - -OSV returns version candidates. The pilot checks named package identity and applies the corresponding SemVer or PEP 440 comparisons to the supported version evidence. It includes the advisory ID, modification time, matching range or listed version, and known fixed endpoints for matched ranges. A fixed endpoint is a publisher's stated version boundary. Repository availability and suitability of a replacement require separate evidence. Source receipts contain the query time and SHA-256 of every accepted OSV response page. These are observation receipts for a live source. - -| Per-package status | Meaning | -| --- | --- | -| `matched` | One or more advisories matched the coordinate within the supported OSV evidence. | -| `no_match` | The checked OSV pages yielded no confirmed match and no unresolved evidence. This is scoped to the source response at query time. | -| `partial` | A query returned evidence, with a remaining source or applicability gap. Confirmed matches remain in the result. | -| `unavailable` | The Worker accepted the coordinate but could not obtain an interpretable source page. | - -This endpoint revalidates versions supplied by the caller. Private SBOM upload, local advisory snapshots, signed replay, and install-policy enforcement are separate work. The pilot has a 12-second source deadline, at most four pages and 128 advisory records per coordinate, and a 512 KiB limit per source page. Incomplete reads disclose their gaps. [OSV query contract](https://google.github.io/osv.dev/post-v1-query/) · [OSV range schema](https://ossf.github.io/osv-schema/) · [PEP 440](https://packaging.python.org/en/latest/specifications/version-specifiers/) - -## EPSS enrichment - -`GET /v1/epss/CVE-YYYY-NNNN` enriches an already imported CVE with [FIRST EPSS](https://www.first.org/epss/data). It returns the score, percentile, score date, attribution and up to 30 days of history as of the response's `as_of` time. `scored`, `missing` and `unavailable` are separate states; a real zero is retained as zero, and a failed lookup never supplies a zero or claims safety. Scores older than two days remain unavailable. EPSS forecasts observed exploitation over the next 30 days; it does not establish package applicability or override CISA KEV, CVEs or required consent. - -The bounded fixed-origin lookup uses the [official time-series API](https://api.first.org/epss/) for individual requested CVEs. It does not mirror the whole EPSS dataset through that API. D1 caches successful results for six hours, backs off failures for one minute and retains the last successful history on upstream failure. Lease fencing prevents expired writers from replacing that history. Public responses use ETags and at most 60 seconds of edge caching. Unknown CVEs do not trigger upstream queries. Apply migration `0004_epss_cache.sql` before deploying this route. The [FIRST service terms](https://www.first.org/about/policies/terms) permit preventative cybersecurity use; attribution is included in every result. - -Migration 0004 and Worker version `2d494aaa-c66b-4333-b3dd-a92609663004` are deployed from `440de96f`. Live EPSS lookup, warm-body identity, conditional 304, D1 cache reuse and invalid/unknown request controls pass; see `docs/superpowers/plans/2026-11-16-epss-enrichment.md` at the repository root. The underlying CVE baseline remains incomplete, so CVEs missing from that baseline receive unavailable coverage rather than an invented EPSS score. - -## Runtime and Pi coding-harness assessments - -Apply `0005_runtime_sources.sql` before deploying the runtime route. The response is `{schema_version:1,identity:{runtime,vendor,version,os,arch},checked_at,coverage,findings,gaps,sources}`. Coverage is `assessed`, `partial` or `unknown`; it describes applicability of the selected disclosed-advisory sources. It does not assert that undisclosed vulnerabilities do not exist. Findings retain CVE-less vendor identifiers and distinguish `applicable` from `possible`. Every finding includes a public HTTPS reference. Clients must display gaps and obtain informed acknowledgment for incomplete assessments rather than silently treating an empty finding list as safety. - -Versions must identify an exact upstream release. Aliases, mismatched vendors and unsupported version forms produce `unknown`. Allowed operating systems are `linux`, `macos`, `windows`; architectures are `x86_64`, `aarch64`. The identity is echoed exactly. OS and architecture remain part of that identity even where the vendor source describes all platforms. No CPE guesses, `npm/node`, `PyPI/python`, Ruby gems or Rust crates stand in for an interpreter or toolchain. Pi is an npm-installed coding harness; its optional package assessment is separate from the 13 runtime adapters. - -| Runtime / vendor parameter | Authoritative disclosure input and applicability limit | -| --- | --- | -| `node` / `nodejs` | [Node security-wg core index](https://github.com/nodejs/security-wg/tree/main/vuln/core): vulnerable ranges minus patched ranges, preserving core IDs without CVEs. | -| `go` / `golang` | [Go vulnerability database through OSV](https://vuln.go.dev/): separate exact-version `Go/stdlib` and `Go/toolchain` queries, including every page. | -| `pi` / `earendil-works` | [OSV exact package queries](https://google.github.io/osv.dev/post-v1-query/): npm `@earendil-works/pi-coding-agent`, matching the installed package identity. | -| `python` / `cpython` | [PSF CPython records](https://github.com/psf/advisory-database) plus [CVEProject vendor records](https://github.com/CVEProject/cvelistV5): numeric vendor applicability where available; Git-only ranges remain possible. Bundled python-build-standalone libraries remain incomplete. | -| `ruby` / `ruby-lang` | [RubySec MRI interpreter records](https://github.com/rubysec/ruby-advisory-db/tree/master/rubies/ruby): genuine YAML and Ruby version requirements. Bundled gems remain incomplete. | -| `rust` / `rust-lang` | [RustSec toolchain records](https://github.com/RustSec/advisory-db/tree/main/rust): genuine TOML for `std`, `cargo`, `rustdoc`; supplemental coverage does not certify every compiler or bundled-tool component. | -| `bun` / `oven-sh` | [Bun publisher advisories](https://github.com/oven-sh/bun/security/advisories): exact product names and supported version ranges. | -| `deno` / `denoland` | [Deno publisher advisories](https://github.com/denoland/deno/security/advisories): exact runtime names and supported version ranges. | -| `erlang` / `erlang` | [OTP publisher advisories](https://github.com/erlang/otp/security/advisories) and [OTP component version table](https://github.com/erlang/otp/blob/master/otp_versions.table): whole-OTP and application versions are distinct; four-component versions and maintenance branches are retained. | -| `php` / `php` | [PHP publisher advisories](https://github.com/php/php-src/security/advisories): maintenance-branch fixes are selected before comparison. Unmapped extension versions remain possible. | -| `java` / `temurin` | [Adoptium Temurin VDR](https://github.com/adoptium/temurin-vdr-generator): official digest-verified CycloneDX asset. Requires a patch identity, retains the caller's build suffix and uses enumerated upstream affected releases; omitted builds/components remain incomplete. | -| `dotnet` / `microsoft` | [Microsoft release metadata](https://github.com/dotnet/core/tree/main/release-notes) maps the exact SDK to its runtime/ASP.NET components before comparing vendor CVE records. Later SDK-only and ASP.NET-only security updates remain candidates even when the bundled runtime version is unchanged. SDK `9.0.100` is never compared as runtime `9.0.100`. Ambiguous mappings remain unknown. | -| `zig` / `ziglang` | [Zig publisher advisories](https://github.com/ziglang/zig/security/advisories): disclosures are useful, but a complete applicability feed is not established. Empty results remain unknown. | -| `swift` / `swiftlang` | [Swift publisher advisories](https://github.com/swiftlang/swift/security/advisories): disclosures are useful, but a complete applicability feed is not established. Empty results remain unknown. | - -Inputs come from fixed origins. GitHub repository archives are pinned to an upstream commit before selection; no paths are extracted. ZIP compressed input is limited to 16 MiB, selected expansion to 8 MiB, individual selected files to 1 MiB, selected files to 4,096 and all archive entries to 32,768. Native ZIP CRC and overlap checks remain enabled. YAML, TOML, npm and Ruby Gem requirements use pinned maintained parsers rather than handwritten substitutes. Ruby's genuine Gem comparator preserves four-component patch levels, pessimistic requirements and exclusions; an old fix such as `>=1.8.6.111` correctly excludes Ruby 3.3.0. Paginated results are limited to 20 pages and 8 MiB of accumulated content; hitting a bound produces incomplete coverage. An invocation has a 25-second source deadline and a 768-subrequest budget; unauthenticated upstream rate limits can still produce unknown coverage. CVE lookups run eight at a time and retain at most 512 identifiers under the same byte budget. - -D1 points to private content-addressed R2 snapshots. Successful source checks are fresh for 30 minutes; failures back off for one minute. Expired or replaced lease holders cannot update D1. Transport failures, malformed source replacements and partial CVE applicability refreshes preserve the last good pointer. A source's SHA-256 covers its underlying source content, independent of request/retrieval timestamps. Revalidation of unchanged content keeps the hash stable. Source revision and source checked time remain separate fields. No known historical CVE is discarded because it is older than the recent-view window. - -Runtime responses contain at most 512 findings, 64 gaps, 16 sources and 2 MiB. Only fresh `assessed` reports receive public edge caching, for at most 60 seconds. Partial, unknown, stale and failed-source reports use `no-store`. `Cache-Control: no-cache` bypasses the edge cache and rereads D1/R2, allowing the client to compare evidence again after a user accepts a warning. For GitHub API-dependent sources, public reads reuse genuinely fresh snapshots without changing their original timestamps. Forced reads with five minutes or less remaining attempt actual upstream revalidation; only a successful check renews `checked_at`. These public checks use anonymous GitHub requests and can encounter quota limits. Failures preserve the last successful payload and timestamp with explicit coverage gaps. Authenticated scheduled refreshes force upstream checks; raw-file and OSV revalidation behavior remains unchanged. Contention or unusually long operations can still exhaust the 30-minute validity window and cause a safe refusal. - -### Scheduled GitHub source refresh - -The public GitHub REST quota is [60 requests/hour per originating IP](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api), so shared Worker egress can exhaust it even for public feeds. On quota and secondary throttling, the Worker shares the retry deadline across GitHub runtime sources. Public reads and authenticated refreshes have separate cooldowns. The deadline honors GitHub's reset and Retry-After headers. Diagnostics expose only bounded numeric headers, and the Worker does not report skipped reads as new source checks. - -The optional Cloudflare Cron checks one group of GitHub-backed sources every five minutes. Each of the ten configured sources has a planned 15-minute refresh interval. To enable it, supply the dedicated read-only GitHub App's client ID, installation ID and PKCS#8 PEM as the Worker secrets `ADVISORIES_GITHUB_APP_CLIENT_ID`, `ADVISORIES_GITHUB_APP_INSTALLATION_ID` and `ADVISORIES_GITHUB_APP_PRIVATE_KEY`. Use a dedicated installation with access limited to the repositories and permissions required for public advisory reads. The Worker exchanges a short-lived signed JWT for a GitHub installation token and passes that token through the existing allowlisted runtime refresh path. It forwards neither credential on redirects. The existing scheduled Actions workflow remains available while operators verify hosted Cron freshness. [GitHub App JWT](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app) · [Installation token](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-an-installation-access-token-for-a-github-app) · [Cloudflare Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/) - -`.github/workflows/advisory-refresh.yml` warms the ten GitHub API-dependent vendor feeds on trusted changes to `main`, every 15 minutes and manual dispatch on `main`. Its checkout is pinned and does not persist credentials; its sole token permission is `contents: read`. The Python standard-library driver posts only to the fixed advisory Worker origin, verifies TLS, disables proxy inheritance, refuses redirects and bounds response size. It continues through all approved feeds and fails the job if a required source refresh is incomplete. A successful source refresh can still have `coverage:unknown` when vendor applicability is incomplete; warming a feed does not certify a version as safe. Scheduler delays or upstream failures can leave a snapshot stale; freshness is never extended to hide that gap. - -Set a new independent `RUNTIME_REFRESH_SECRET` in both the advisory Worker and the repository's Actions secrets. Use 32–256 random ASCII letters, digits, underscores or hyphens. This secret authorizes runtime feed refresh and publisher baseline verification; it does not authorize CVE imports, delta catchup or baseline receipt creation/finalization. Preserve the existing `INGEST_TOKEN` unchanged. No secret values belong in committed files or command output. - -The private route accepts exactly `{runtime,github_token}` under `Authorization: Bearer RUNTIME_REFRESH_SECRET`, checks authentication before reading the bounded 4 KiB body, and permits only fixed refresh profiles. The job supplies its ephemeral `ghs_` GitHub installation token. The service accepts both legacy and stateless installation tokens up to 2 KiB. That token is attached only to exact allowlisted `api.github.com` GET routes with manual redirect handling; it is absent from archive/raw hosts, release assets and asset redirects. It is never written to D1/R2, returned or logged; reflected credentials are rejected and transport errors are redacted. No GitHub credential is stored as a Cloudflare secret. The response reports source success separately from incomplete runtime applicability. These jobs reuse the same source producers, cache keys, content hashes, leases and fences as public assessments, without a second advisory ingestion format. - -After the Worker is deployed and both copies of the refresh secret are configured, run the workflow on `main` and verify fresh source timestamps and complete source receipts through the public routes. Local tests prove the wiring and credential boundaries; they do not establish that the hosted Actions job has run successfully. - -[Cloudflare Zero Wire](https://radar.cloudflare.com/zero-wire) is currently **link-only / redistribution permission required**. Public access is not permission to mirror the content commercially: [Radar dataset licensing](https://developers.cloudflare.com/radar/) must be checked before enabling ingestion. No Zero Wire payload is mirrored, and startup credits do not change content licensing. Publisher CVE-less advisories remain available through the adapters above. - -The local suite exercises affected/fixed/unknown states across all 14 routes, source freshness and hash changes, OSV/publisher pagination, maintenance branches, exact SDK mappings, partial refresh preservation and real SQLite lease fences. A real workerd test reads a DEFLATE vendor archive, parses YAML, stores D1/R2 evidence and verifies partial responses bypass edge caching. These tests do not prove completeness of external disclosure programs. - -## Archive bootstrap - -Download the official full ZIP only after reserving local and Cloudflare capacity. The script accepts an existing archive and never downloads the corpus or extracts record paths. A sole `cves.zip` wrapper is decoded into a fixed private temporary file before the inner ZIP is scanned. Stored and DEFLATE wrappers require matching decoded size and CRC32, with a 1 GiB decoded limit and a 500:1 compression limit. Mixed or recursive wrappers and archives without CVE records are rejected. Source release filenames can include a doubled `.zip.zip` suffix. Select the exact official asset name, not an assumed filename. - -The script fetches bounded metadata from the fixed official GitHub release API, matches asset size, and verifies its published SHA-256 before any ingest. Pinned `yauzl` 3.4.0 reads ZIP entries lazily. It validates CVE filename/year/bucket consistency, entry size and compression bounds. Paths are never extracted. An atomic local resume file advances only after an accepted HTTP batch. Replay after a lost response is safe. - -```sh -bun run bootstrap --help -bun run bootstrap \ - --archive /absolute/operator-data/2026-11-13_all_CVEs_at_midnight.zip.zip \ - --asset 2026-11-13_all_CVEs_at_midnight.zip.zip \ - --release-tag cve_2026-11-13_0000Z \ - --state /absolute/operator-data/advisories.bootstrap-state.json \ - --max-records 1000 --dry-run -``` - -Use the actual official release tag returned by GitHub rather than copying an example date indefinitely. A dry run reads/verifies up to the record budget and never writes HTTP or a resume file. For ingestion, omit `--dry-run` and add `--endpoint https://DEPLOYED-WORKER` and `--token-file /absolute/private/ingest-token`. Alternatively provide the separate token through the `INGEST_TOKEN` environment variable. Token files must have private permissions. - -Repeat with the same archive/state until `exhausted:true`. Default admission is 1,000 records per invocation with no artificial batch delay. Requests remain serial: each complete envelope is at most 4 MiB and 64 records, the server retains its writer fence, and at most four R2 writes run concurrently inside that request. Supported distinct baseline IDs use one indexed old-state lookup and one fenced atomic metadata batch, including original membership and Git identity. All equal-revision conflicts are checked before R2 writes start, and all started writes settle before an error releases the writer. Duplicate IDs and unsupported records retain the existing serial-per-ID preservation path. Generic delta ingestion is unchanged. `--max-records` (up to 100,000) and `--delay-ms` bound a wave. Connection loss, response-body interruption and transient HTTP errors retry the exact same body at most five times with bounded backoff; `Retry-After` is respected up to 30 seconds. Permanent failures stop the wave. The checkpoint advances only after the server acknowledges the exact sent record count. Progress and elapsed time are emitted without credentials. - -Start with `--max-records 256 --delay-ms 0` to measure up to four serial requests before increasing the wave budget. The previous eight-record batches and one-second delay alone imposed 12,500 seconds per 100,000 records; removing that delay and redundant metadata round trips does not predict actual D1/R2 throughput. [Cloudflare's D1 limits](https://developers.cloudflare.com/d1/platform/limits/) and [Workers limits](https://developers.cloudflare.com/workers/platform/limits/) still apply. Paid Workers currently permit more subrequests than D1's per-invocation query budget; this operator does not raise either service limit or add concurrent HTTP writers. D1 free-tier daily writes are insufficient for an unpaced full backfill of two indexed rows per CVE plus metadata. Schedule waves or verify account coverage rather than treating HTTP success as an unbounded quota. - -If the private state file is lost, retrieve the existing instance/session binding through the authorized operator process and replay the original byte-verified archive from zero. Never infer a local ZIP position from the database's imported count: directory entries, ordering and already-imported members make those different quantities. A new missing state path can use `--resume-instance INSTANCE --resume-session SESSION` with the same endpoint, release and asset. Recovery records `accepted:0`, `next_entry:0`, `exhausted:false`, `finished_at:null`; the server must return the exact requested digest/instance/session/endpoint. These flags refuse an existing state file. Replayed ingestion is idempotent. Recovery establishes no archive certification, and `--yes` or an operator count cannot certify completeness. - -After the last import, let Cron catch up and run the same command with `--finalize`. Finalization fails while the delta checkpoint is incomplete/stale, predates the import's finish, has a mismatched instance/session/endpoint, or disagrees with server-counted imported members. Finalization alone keeps `archive_verified:false` and `bootstrap_complete:false`. - -The separate authenticated `POST /internal/baseline/verify` route pins the exact official midnight release asset and publisher commit, traverses bounded Git trees on the server, and reconciles every expected CVE ID/Git blob identity against the immutable original import ledger. Newer delta records do not overwrite those original baseline identities. The route accepts no operator manifest or claimed member count. Authorize it with the separate `RUNTIME_REFRESH_SECRET`, not `INGEST_TOKEN`, and provide only an ephemeral `ghs_` GitHub installation token for the allowlisted publisher API. Both credentials are passed through the operator child's environment and never through command arguments or state files. - -```sh -bun scripts/verify-baseline.ts --state /absolute/operator-data/advisories.bootstrap-state.json \ - --release-tag cve_2026-11-13_0000Z --asset 2026-11-13_all_CVEs_at_midnight.zip.zip \ - --max-steps 20 --delay-ms 0 -``` - -Repeat bounded proof waves while the phase is `traversing` or `reconciling`. `awaiting_import` requires the original archive replay to finish, including legacy imported rows missing original Git identity. `awaiting_catchup` requires a fresh completed delta checkpoint after import and finalization. Only a server response with phase `verified`, equal positive expected/verified counts, no pending trees and `archive_verified:true` is a successful proof. A local archive count or matching samples remains diagnostic evidence, not certification. - -Preserve the archive digest and compact receipts after retiring obsolete scratch data. Use one operator per resume file and do not overlap archive scans inside a shared storage budget. Existing resume files without a database/session/endpoint binding are rejected; do not reuse them against a new database. Each archive scan owns a private snapshot with a 1 GiB compressed budget and hashes those exact bytes before parsing. A wrapped archive needs up to another 1 GiB for the verified inner ZIP, for a 2 GiB temporary file budget plus bounded record buffers; budget the retained original archive in addition. Both temporary files are removed when the scan ends. Resume positions index the selected inner or flat corpus, while the official outer digest remains the session identity. Legacy resume files marked exhausted with zero accepted records are rejected; start with a new state file to rescan the archive. Keep operator scratch on C:. Check live `/v1/status` for actual imported and certified state; source changes and local tests do not establish a completed production import. - -## Primary references - -* [Official CVEProject download cadence, baseline/delta naming, and rolling log](https://github.com/CVEProject/cvelistV5/blob/main/README.md). -* [Official Arch issues](https://security.archlinux.org/issues/all.json). -* [Official CISA KEV feed](https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json). -* [D1 limits and batch semantics](https://developers.cloudflare.com/d1/platform/limits/). -* [Workers Web Crypto](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/). -* [yauzl lazy entry API](https://github.com/thejoshwolfe/yauzl). -* [Streaming JSON parser API](https://github.com/juanjoDiaz/streamparser-json/tree/main/packages/plainjs). diff --git a/services/advisories/VERIFICATION.md b/services/advisories/VERIFICATION.md deleted file mode 100644 index 5922c2a7b..000000000 --- a/services/advisories/VERIFICATION.md +++ /dev/null @@ -1,86 +0,0 @@ -# Local verification receipt - -## Shared scheduled and operator ingestion, November 14 - -The scheduled-delta concurrency regression first observed one started fetch where four were required. Both ingestion paths now use the same bounded routine. Tests verify the four-ID limit, same-ID serialization, rejection protection, cursor retention through partial failure, and idempotent replay. The scheduled failure test holds a second fetch open while another fails and verifies that another writer cannot acquire the CVE lease until started work settles. This is a requirement on the new concurrent path, not a claim that the previous serial path released a lease around active parallel work. - -All 46 tests and 346 assertions pass, including the real workerd/D1/R2 boundary tests. Type checking passes. The existing record, body, concurrency, retry, timeout, CPU and bootstrap acceptance limits remain unchanged. The example release tag now matches the archive used by the validated operator run. Production deployment and corpus completeness require separate receipts. - -## Bounded concurrent imports, November 14 - -The new gated import test first failed with one started write where four were required. The route now groups records by CVE ID and runs at most four groups concurrently. Each group's revisions remain serial. All started promises settle before the lease is released, preserving fenced writes when another group fails. New tests check the concurrency bound, lease retention through failure, rejected-version ordering and conflicting equal revisions. - -All 43 service tests and 327 assertions pass, along with type checking and deployment dry run. The real workerd/D1/R2 test additionally imports eight records in one request, including a structured 2.4 MB CVE, and verifies each returned payload and SHA-256. Existing row-read, request-size, lease-expiry and incomplete-baseline checks remain. No request limit, retry count, timeout or bootstrap acceptance rule changed. Production deployment and further backfill verification are recorded separately; these local checks do not certify a complete corpus. - -Run date 2026-11-13 UTC. Owner is the advisory-service implementation agent. Scope is `services/advisories/**`. No Cloudflare resources, secrets, deployed Workers or remote databases were changed. The full corpus ZIP was not downloaded. - -TDD first failed on the public status contract. Expected HTTP 200, received 503. The implementation then passed that behavior against the real SQLite migration. A subsequent actual workerd run exposed unsupported `redirect:'error'`; source fetches now use Workers-supported `manual` and reject redirect responses, with a regression test. - -Final unit/integration checks are 19 passing tests, 68 assertions, covering actual SQLite migration/prepared statements, raw-before-index ordering, old/rejected revision protection, unknown-schema replay, leases, checkpoint failure/replay, read-only routing, authorization-before-body, bounded input, Arch 304/stale handling, baseline start/catchup/finalization, KEV removals/rollback, streaming-delta pagination/continuity, and lazy ZIP hash/path/budget/resume failures. - -`bun run check`, `bun run types` with binding-only generation, and `bun run dry-run` passed locally. Versions remain Wrangler 4.160.0, TypeScript 7.0.2, Workers types 5.20261110.1 and Bun types 1.3.10. New runtime dependencies are exactly `@streamparser/json` 0.0.26 and `yauzl` 3.4.0, with yauzl typings 3.4.0. The ZIP library is confined to the local operator and is not bundled into the Worker. - -A read-only live-source probe consumed the current official delta log, 39,158,958 bytes, using the streaming parser and selected four records in 1,611 ms on this machine. This includes local network time and does not measure Cloudflare CPU or promise production throughput. - -Wrangler's local D1 migration executed successfully. A real local workerd scheduled invocation then ingested fixed upstream feeds into local D1/R2. `/v1/status` reported fresh complete Arch and KEV feeds, incomplete CVE bootstrap, and no ingestion errors. `/v1/arch/advisories` returned schema 1, source `arch-security`, `complete:true`, 2,444 original issues, and SHA-256 `aaba5defa65cdc4468546cb775b0aac06180fab40219103e3c2ad699ea2f2301`. The local CVE index contained four published records and kept bootstrap false. These source snapshots were local generated verification data, not remote Cloudflare writes. - -Local scratch owner is this service. Its `.wrangler` runtime state has a 100 MiB budget and may be retired after the implementing owner has reviewed this receipt. The local server was stopped. Production resource binding, account billing, remote migrations, authentication setup, deployment and full-corpus bootstrap remain the deploying owner's gates. Independent review has not been performed by this implementation agent. - -## Integrity fix round 12 - -The current implementation supersedes the baseline certification and parsed-object wire contracts above. The old 19 tests remain represented. The changed baseline test now checks server-counted import and catchup while requiring `archive_verified:false` and `bootstrap_complete:false`. Full corpus bootstrap remains unfinished pending an authoritative publisher-bound exhaustive archive member manifest. No remote schema or Worker deployment was performed in this round. - -The new regression tests failed before production changes. The stale snapshot test expected checkpoint `2026-11-13T02:11:00.000Z` but received the expired writer's `2026-11-13T02:00:00.000Z`. Raw wire payload expected the original formatted JSON string but received `undefined`. BOM rejection expected a rejected promise but received a resolved one. The inflated baseline receipt expected HTTP 400 but received HTTP 200 with an unaccounted `accepted:400000` assertion. - -Writer-scoped stores now prepend a lease owner and expiry constraint to every production mutation batch. SQL execution time checks expiry in production; tests can inject a deterministic clock. SQLite transactions prove stale/expired owner rejection rolls back snapshot/cursor/error/KEV writes. The design relies on D1 batch transaction rollback, as documented in [Cloudflare's D1 batch API](https://developers.cloudflare.com/d1/worker-api/d1-database/#batch). Content-addressed R2 writes precede the transaction and may leave unreferenced objects when the guard rejects a commit. - -Database instances and baseline sessions bind resume state to digest and endpoint origin. Distinct successfully imported CVE members are counted by the server. Replays do not inflate membership. Fresh database or endpoint reuse and a wrong session are rejected. Operator exhaustion and count assertions do not independently certify publisher archive coverage. New imports clear the session's caught-up receipt. - -Public CVE and Arch envelopes expose exact UTF-8 JSON text as `payload_json`. Hashes cover that string's UTF-8 bytes, including original whitespace and key order. BOMs and malformed UTF-8 are rejected. Archive scanning owns a private temporary copy, admits at most 1 GiB compressed bytes, hashes that snapshot, parses it and removes it when finished. A regression mutates the original archive after the first eight records and still receives all nine verified snapshot records. The new nine-record ZIP fixture is synthetic test data only. - -Final round checks are recorded below after the final run. No full CVE corpus was downloaded and no production data was imported. Independent correctness review remains a release gate for the coordinating owner. - -Final integrity-round run passed 27 tests and 91 assertions with `bun test test`, `bun run check`, `bun run types` and `bun run dry-run`. The final dry run packaged 84.44 KiB, 18.29 KiB gzip. It did not upload or deploy. This round performed no native build, worktree operation, Git mutation, remote migration or production import. Independent review is pending with the coordinating owner. The current source hash is reported to that owner separately. - -## Full ingest envelope budget follow-up - -Independent review reproduced an operator batch that measured only `{source,records}` while the transmitted request also included its baseline binding. The new real ZIP regression first failed with `Expected: <= 4194304`, `Received: 4194406` bytes. It constructs four valid 1,048,500-byte CVE records in a temporary stored ZIP and checks the actual POST body, including database/session/digest/endpoint fields. - -The scanner now receives the complete batch serializer up front, checks UTF-8 bytes of the resulting body, and sends that exact serialized string. The operator's HTTP helper transmits it unchanged. An individual record whose complete envelope cannot fit fails before sending. There is no reduced record-count limit or guessed padding allowance. The regression now delivers all four original records, advances accepted to four, and exhausts the archive using only bodies within the limit. Its temporary ZIP is removed after the test. - -Final follow-up checks passed 28 tests and 98 assertions, `bun run check`, and `bun run dry-run`. The existing 27 tests remain; only archive serializer API adaptations were required. The Worker bundle remains 84.44 KiB, 18.29 KiB gzip because these changes affect the local operator. No deployment or remote write occurred. Independent review of this follow-up remains with the coordinating owner. - -## Independent review and first production ingestion - -The coordinating review accepted the lease fencing, resume binding, exact payload hashing and immutable archive snapshot changes. A second review reproduced the full-request-envelope bug, then accepted its fix after the real ZIP boundary regression passed. The final local service suite passed 28 tests and 98 assertions. - -The dedicated Worker was deployed as version `016fe765-076b-40f2-ba87-9c6bd1fa4207` at `https://omg-advisories.latham.workers.dev`. Its dedicated D1 database received migration `0001_advisories.sql`; raw records use the private R2 binding. The configured batch limit is 32 records per five-minute Cron invocation, with a 30,000 ms CPU cap. No subscription upgrade was performed. Operator authentication is a deployed secret; no Cloudflare account credential belongs in the Rust client. - -The first observed scheduled ingestion completed on 2026-11-13 at 03:35 UTC. Subsequent checks confirmed fresh Arch and KEV checkpoints, 2,444 Arch advisory groups and 1,779 KEV records. An observed D1 query counted 96 CVE records after three scheduled batches, with no database mutation from that verification query. The Arch response's exact payload SHA-256 matched its `payload_json` bytes. An actual CVE lookup also matched its stored payload SHA-256 and reported unknown package applicability. These counts describe those observations, not a completed historical import. - -The historical CVE baseline is still unimported and independently unverified. Global bootstrap completeness remains false. Source-local Arch and KEV completion does not establish AUR upstream identity or CVE applicability. Rust client integration and its caller migration remain separate verification work. - -## Baseline counter migration and measured D1 reads - -The repeated member recount in every import and status request was replaced with a maintained distinct-member counter. The deployed `0001_advisories.sql` remains byte-identical with SHA-256 `85b3a49bf10e44ba2f7b1a67a29f0c4e0417ffe710ba090707238c479f742986`. New migration `0002_baseline_member_counter.sql` reconciles existing session counts once, increments only after a successful new member insert, and rejects member updates/deletes. Current writers use `INSERT ... ON CONFLICT DO NOTHING`. Future member rewriting/removal requires an intentional migration that changes the triggers and reconciles counters. No generic maintenance endpoint was added. - -The writer still invalidates caught-up/completed receipts unconditionally, including zero-new-member retries. Status reads `accepted` directly. Finalization still counts actual membership once and now rejects disagreement with either the maintained counter or supplied receipt. Instance/session/digest/origin binding, writer fencing and incomplete full-bootstrap status remain unchanged. Apply `0002` before publishing the new Worker; the previous Worker remains compatible after the migration. - -Before the fix, a real Miniflare D1 regression imported 128 and 256 distinct records successfully through the actual service routes. Mutation batch metadata reported 8,912 and 34,208 rows read, while status queries read 133 and 261 rows. The test failed `Expected: <= 4096`, `Received: 8912` for its fixed 32-rows-per-record budget at 128 records. This is actual `meta.rows_read`, rather than SQL-text matching, a timing threshold, or a mock database. Mutation measurements use the real `d1Sql` adapter with a typed `prepare`/`batch` decorator; separate status query instrumentation collects metadata from the same real D1 binding. Per-record point-query reads outside mutation batches and R2 operations are outside the mutation metric. - -After the fix, the same successful imports read 784 and 1,568 mutation rows, exactly doubling with the input size. Status reads five rows at both sizes. Fixture storage measured 4,419,200 and 4,525,720 bytes, under its 50 MiB budget; runtimes are disposed and owned scratch removed after each run. These bounded local fixture results are not measurements of a full corpus, production CPU or Cloudflare latency. - -Miniflare `5.20261110.0-beta` is now a direct pinned dev dependency, matching the version already installed through Wrangler. The tests apply SQL using the installed Wrangler splitter and real D1 transactional batches. [Cloudflare's D1 SQL documentation](https://developers.cloudflare.com/d1/sql-api/sql-statements/) describes SQLite semantics and recursive trigger controls; successful actual D1 fixture imports also exercise the new trigger. SQLite semantic regressions cover migration reconciliation, distinct retry counting, receipt invalidation, update/delete rejection, rollback of a triggered increment and finalization rejection of counter drift. No remote operation, native build, Git mutation or full archive download occurred in this round. Independent review and the remote migration/deployment remain the coordinating owner's gates. - -Final counter-round validation passed 31 tests and 174 assertions. `bun run check`, binding-only `bun run types` and `bun run dry-run` passed. The Worker package is 84.42 KiB, 18.29 KiB gzip. The measured D1 regression remains 784/1,568 mutation rows and five status rows for 128/256 members. Original migration and original 28 tests remain present. No migration or Worker was published in this round. - - -## Coordinating deployment and client verification - -The coordinating owner independently reviewed the integrity and counter changes, applied migrations 0001 and 0002 to the dedicated production database, and deployed Worker version `c19e40a1-a008-4af8-95f8-16c87b485ce0`. No billing plan was changed. The operator secret remains outside this repository. - -The production check at 2026-11-13T04:50:11Z verified the exact Arch payload hash, 2,444 issues, fresh Arch and KEV snapshots, unauthorized import rejection, and authenticated malformed import rejection. CVE ingestion reports `delta continuity lost; baseline reconciliation required`. Historical baseline import remains zero, archive verification is false, and bootstrap is incomplete. No complete CVE corpus or AUR applicability claim follows from this deployment. - -After comment cleanup, all 31 service tests and 174 assertions, TypeScript checking, and the Wrangler dry run passed. The Rust snapshot client passed 13 boundary tests, the full library suite of 2,343 tests with 13 ignored, and Clippy for default, no-default, and debian-pure builds. A real read-only host audit validated the production snapshot and left the installed package database unchanged. Seven disposable Arch guest scenarios passed with the current CLI, including a user-owned Omarchy checkout whose executable sentinel was never run. These guest checks do not establish LLVM coverage. - -The strict coverage comparison still rejects unproved retained execution in changed constructs. Its acceptance rules remain unchanged. This batch is a verified implementation checkpoint, not a declaration that PR #1057 or the full security migration is complete. diff --git a/services/advisories/bun.lock b/services/advisories/bun.lock deleted file mode 100644 index 19737d7e9..000000000 --- a/services/advisories/bun.lock +++ /dev/null @@ -1,291 +0,0 @@ -{ - "lockfileVersion": 3, - "configVersion": 1, - "workspaces": { - "": { - "name": "@omg/advisories", - "dependencies": { - "@renovatebot/pep440": "6.0.0", - "@renovatebot/ruby-semver": "6.0.0", - "@streamparser/json": "0.0.26", - "@zip.js/zip.js": "2.25.0", - "postgres": "^4.1.1", - "semver": "7.8.6", - "smol-toml": "1.9.1", - "yaml": "2.9.1", - "yauzl": "3.4.0", - }, - "devDependencies": { - "@cloudflare/workers-types": "5.20261110.1", - "@types/bun": "1.3.10", - "@types/semver": "7.8.0", - "@types/yauzl": "3.4.0", - "miniflare": "5.20261110.0-beta", - "typescript": "7.0.2", - "wrangler": "4.160.0", - }, - }, - }, - "overrides": { - "miniflare@5.20261110.0-beta": { - "undici": "7.30.2", - }, - }, - "packages": { - "@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.5.0", "", {}, "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg=="], - - "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.2", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ=="], - - "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20261110.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-RazOdADqTgwYhE60+i6c/R5BA1J5aC//39oousnWBxmoVAiqUh1qsXNCGMbaEV6UC5RnZyWsIBRIcAYNDe1xTg=="], - - "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20261110.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-TFsn/t+wczWnWdm+ytlWe+xHEO9sDgfIBmtMo8OxujuS2DXCmGimiyvJHmuv+6+N9OhUb0dM+fveXJI9yjuzew=="], - - "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20261110.1", "", { "os": "linux", "cpu": "x64" }, "sha512-i4080Pp6Q0nwS8OMqt3cbpJoWvbCrIlFKa+4Inbn+y2pWKTVsq6F9bgdi0l8CBZPMszd03gDlQR++dqMbErh2Q=="], - - "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261110.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-0l+JyYWOhEzTs7yOkIdf1ZzcXd9WalPZ1kD0bBAobFvDhO/1jBnQkS4rzzyUkGV7g8pb3dkfrBP9c2ZiRLOfdw=="], - - "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261110.1", "", { "os": "win32", "cpu": "x64" }, "sha512-zP8IGyWvohyJhbNjHOnTA9anRQtGN7X01T/dG+R9IA4vu2egRODsD02aoYzv0a0qImjt7tTpOOA+uVotDJPcSA=="], - - "@cloudflare/workers-types": ["@cloudflare/workers-types@5.20261110.1", "", {}, "sha512-XOr3TDQ2sNDiP9zoZtdwYVhuLZ3aFY+G+G4iSeNO9p/HDSveZJpyCbUtmpEElaClLBe9hIzfN26qd0i/S7ksPg=="], - - "@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="], - - "@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], - - "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], - - "@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="], - - "@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.2", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="], - - "@esbuild/android-x64": ["@esbuild/android-x64@0.28.2", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="], - - "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="], - - "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="], - - "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="], - - "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="], - - "@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.2", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="], - - "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="], - - "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.2", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="], - - "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="], - - "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="], - - "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="], - - "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="], - - "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="], - - "@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.2", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="], - - "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="], - - "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.2", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="], - - "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="], - - "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="], - - "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="], - - "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="], - - "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="], - - "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="], - - "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], - - "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], - - "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg=="], - - "@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.4" }, "os": "darwin", "cpu": "x64" }, "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw=="], - - "@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.5", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "os": "freebsd" }, "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw=="], - - "@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw=="], - - "@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ=="], - - "@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.4", "", { "os": "linux", "cpu": "arm" }, "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw=="], - - "@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A=="], - - "@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ=="], - - "@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.4", "", { "os": "linux", "cpu": "none" }, "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q=="], - - "@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ=="], - - "@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.4", "", { "os": "linux", "cpu": "x64" }, "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw=="], - - "@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA=="], - - "@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.4", "", { "os": "linux", "cpu": "x64" }, "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg=="], - - "@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.4" }, "os": "linux", "cpu": "arm" }, "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ=="], - - "@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ=="], - - "@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.4" }, "os": "linux", "cpu": "ppc64" }, "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA=="], - - "@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.4" }, "os": "linux", "cpu": "none" }, "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ=="], - - "@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.4" }, "os": "linux", "cpu": "s390x" }, "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA=="], - - "@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog=="], - - "@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg=="], - - "@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A=="], - - "@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.5", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ=="], - - "@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.5", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "cpu": "none" }, "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA=="], - - "@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q=="], - - "@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A=="], - - "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.5", "", { "os": "win32", "cpu": "x64" }, "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg=="], - - "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], - - "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], - - "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.9", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="], - - "@poppinss/colors": ["@poppinss/colors@4.1.6", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="], - - "@poppinss/dumper": ["@poppinss/dumper@0.6.5", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="], - - "@poppinss/exception": ["@poppinss/exception@1.2.3", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="], - - "@renovatebot/pep440": ["@renovatebot/pep440@6.0.0", "", {}, "sha512-L/HtOYInkZGLJCe9h/gpsm2Gig0JWzyvWajrEVK+pP6BGfRl1eFzg7jyVcis7tmht7hvpau/+pMzF60geiLq6w=="], - - "@renovatebot/ruby-semver": ["@renovatebot/ruby-semver@6.0.0", "", {}, "sha512-RGiSBw2vRYu5PnPTAaJR8R/VV86boURoojuohaJJcAZMgRKrpvRLlmUsK5A8WWLMH0JD9dHoYCpXHZdAZFlFTw=="], - - "@sindresorhus/is": ["@sindresorhus/is@7.2.0", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="], - - "@speed-highlight/core": ["@speed-highlight/core@1.2.24", "", {}, "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw=="], - - "@streamparser/json": ["@streamparser/json@0.0.26", "", {}, "sha512-46597LNFI+MFdUnzX2QJWwmdTRdq0XVD+vVNJTtGVzIrnCuhG9pFo1OAzbNBqci8UJgk/X5KJZ6LcV+y7PTuDQ=="], - - "@types/bun": ["@types/bun@1.3.10", "", { "dependencies": { "bun-types": "1.3.10" } }, "sha512-0+rlrUrOrTSskibryHbvQkDOWRJwJZqZlxrUs1u4oOoTln8+WIXBPmAuCF35SWB2z4Zl3E84Nl/D0P7803nigQ=="], - - "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], - - "@types/semver": ["@types/semver@7.8.0", "", {}, "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ=="], - - "@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="], - - "@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="], - - "@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="], - - "@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="], - - "@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="], - - "@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="], - - "@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="], - - "@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="], - - "@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="], - - "@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="], - - "@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="], - - "@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="], - - "@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="], - - "@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="], - - "@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="], - - "@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="], - - "@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="], - - "@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="], - - "@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="], - - "@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="], - - "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="], - - "@zip.js/zip.js": ["@zip.js/zip.js@2.25.0", "", {}, "sha512-oNRqUuU1XFu6G5d7Z0jufJ9dS9WteO0xiU/PNxsUrb4itZCsSbn191jpJzU00Gmc6S680X3DPZeF5EV4zAEMAg=="], - - "blake3-wasm": ["blake3-wasm@2.1.5", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="], - - "bun-types": ["bun-types@1.3.10", "", { "dependencies": { "@types/node": "*" } }, "sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg=="], - - "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], - - "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - - "error-stack-parser-es": ["error-stack-parser-es@1.0.5", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="], - - "esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], - - "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - - "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], - - "miniflare": ["miniflare@5.20261110.0-beta", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.5", "undici": "7.30.1", "workerd": "1.20261110.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" }, "peerDependencies": { "kerberos": "^2.0.0" }, "optionalPeers": ["kerberos"] }, "sha512-UiJRL6D4pNkHxgZ3QXDCaz/N27FFuuHRRgOmD/SucEZIwDOfWwX7s/n8ZrFemFlURRfnQpBfAdWy8ixsW0yJWA=="], - - "path-to-regexp": ["path-to-regexp@6.3.0", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="], - - "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="], - - "postgres": ["postgres@4.1.1", "", {}, "sha512-1kJDojqNZC+iTHHXh6eif0J98LUtyLAePe/qkW1GK35eh2JixlsAiIKq3FGI+xqI+SUGTNodzf7TScVeIIyUug=="], - - "semver": ["semver@7.8.6", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], - - "sharp": ["sharp@0.35.5", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="], - - "smol-toml": ["smol-toml@1.9.1", "", {}, "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ=="], - - "supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="], - - "tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], - - "typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="], - - "undici": ["undici@7.30.2", "", {}, "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA=="], - - "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], - - "unenv": ["unenv@2.0.0-rc.24", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="], - - "workerd": ["workerd@1.20261110.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261110.1", "@cloudflare/workerd-darwin-arm64": "1.20261110.1", "@cloudflare/workerd-linux-64": "1.20261110.1", "@cloudflare/workerd-linux-arm64": "1.20261110.1", "@cloudflare/workerd-windows-64": "1.20261110.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-GKdtki7t19f16vegol8Iw5Dh0mnjHLuwLx8rlhTPvyRBEXM0Osl9eYexWAW8uZD7OMw4WKNq9yvENg5kPDUJ9w=="], - - "wrangler": ["wrangler@4.160.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.5.0", "@cloudflare/unenv-preset": "2.16.2", "@cspotcode/source-map-support": "0.8.1", "blake3-wasm": "2.1.5", "esbuild": "0.28.2", "miniflare": "5.20261110.0-beta", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20261110.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "peerDependencies": { "@cloudflare/workers-types": "^5.20261110.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js", "cf-wrangler": "bin/cf-wrangler.js" } }, "sha512-nwzmpu7Hd5Csax02twpCNRAloC+kduXKw9rjfq+oEuo8RnjWRaahSV+qk+p0w88EgafMcDE0XnZRSfOM3lKEKg=="], - - "ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], - - "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], - - "yauzl": ["yauzl@3.4.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw=="], - - "youch": ["youch@4.1.0-beta.10", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="], - - "youch-core": ["youch-core@0.3.3", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="], - } -} diff --git a/services/advisories/migrations/0001_advisories.sql b/services/advisories/migrations/0001_advisories.sql deleted file mode 100644 index 6318101e8..000000000 --- a/services/advisories/migrations/0001_advisories.sql +++ /dev/null @@ -1,35 +0,0 @@ -CREATE TABLE source_checkpoint ( - source TEXT PRIMARY KEY CHECK(source IN ('cve','arch','kev')), - cursor TEXT, baseline_digest TEXT, checked_at TEXT, fetched_at TEXT, etag TEXT, - complete INTEGER NOT NULL DEFAULT 0, bootstrap_complete INTEGER NOT NULL DEFAULT 0, - error TEXT, object_key TEXT, payload_sha256 TEXT, revision TEXT -); -INSERT INTO source_checkpoint(source) VALUES ('cve'),('arch'),('kev'); -CREATE TABLE source_record ( - id TEXT PRIMARY KEY, source TEXT NOT NULL, source_url TEXT NOT NULL, - schema_version TEXT NOT NULL, state TEXT NOT NULL, published_at TEXT, - modified_at TEXT NOT NULL, fetched_at TEXT NOT NULL, payload_sha256 TEXT NOT NULL, - object_key TEXT NOT NULL, normalization_version INTEGER NOT NULL, supported INTEGER NOT NULL -); -CREATE TABLE cve ( - id TEXT PRIMARY KEY REFERENCES source_record(id), state TEXT NOT NULL, - modified_at TEXT NOT NULL, payload_sha256 TEXT NOT NULL -); -CREATE TABLE ingestion_run ( - id TEXT PRIMARY KEY, source TEXT NOT NULL, started_at TEXT NOT NULL, - finished_at TEXT, records INTEGER NOT NULL DEFAULT 0, error TEXT -); -CREATE TABLE ingestion_lease (source TEXT PRIMARY KEY, owner TEXT NOT NULL, expires_at TEXT NOT NULL); -CREATE TABLE baseline_receipt ( - digest TEXT PRIMARY KEY, instance_id TEXT NOT NULL, session_id TEXT NOT NULL UNIQUE, endpoint TEXT NOT NULL, baseline_at TEXT NOT NULL, accepted INTEGER NOT NULL, - exhausted INTEGER NOT NULL, caught_up INTEGER NOT NULL DEFAULT 0, completed_at TEXT -); -CREATE TABLE kev_annotation ( - cve_id TEXT PRIMARY KEY, payload_json TEXT NOT NULL, catalog_sha256 TEXT NOT NULL -); - -CREATE TABLE mutation_fence (id INTEGER PRIMARY KEY CHECK(id=1), valid INTEGER NOT NULL CHECK(valid=1)); - -CREATE TABLE database_instance (id TEXT PRIMARY KEY); -INSERT INTO database_instance(id) VALUES(lower(hex(randomblob(16)))); -CREATE TABLE baseline_member (session_id TEXT NOT NULL REFERENCES baseline_receipt(session_id), cve_id TEXT NOT NULL, payload_sha256 TEXT NOT NULL, PRIMARY KEY(session_id,cve_id)); diff --git a/services/advisories/migrations/0002_baseline_member_counter.sql b/services/advisories/migrations/0002_baseline_member_counter.sql deleted file mode 100644 index 33682b6de..000000000 --- a/services/advisories/migrations/0002_baseline_member_counter.sql +++ /dev/null @@ -1,20 +0,0 @@ -UPDATE baseline_receipt -SET accepted=(SELECT COUNT(*) FROM baseline_member WHERE session_id=baseline_receipt.session_id); - -CREATE TRIGGER baseline_member_count_insert -AFTER INSERT ON baseline_member -BEGIN - UPDATE baseline_receipt SET accepted=accepted+1 WHERE session_id=NEW.session_id; -END; - -CREATE TRIGGER baseline_member_no_update -BEFORE UPDATE ON baseline_member -BEGIN - SELECT RAISE(ABORT, 'baseline membership is append-only'); -END; - -CREATE TRIGGER baseline_member_no_delete -BEFORE DELETE ON baseline_member -BEGIN - SELECT RAISE(ABORT, 'baseline membership is append-only'); -END; diff --git a/services/advisories/migrations/0003_recent_cves.sql b/services/advisories/migrations/0003_recent_cves.sql deleted file mode 100644 index ca5253009..000000000 --- a/services/advisories/migrations/0003_recent_cves.sql +++ /dev/null @@ -1 +0,0 @@ -CREATE INDEX source_record_modified_id ON source_record(modified_at DESC,id DESC); diff --git a/services/advisories/migrations/0004_epss_cache.sql b/services/advisories/migrations/0004_epss_cache.sql deleted file mode 100644 index 916c1a0da..000000000 --- a/services/advisories/migrations/0004_epss_cache.sql +++ /dev/null @@ -1,5 +0,0 @@ -CREATE TABLE epss_cache ( - cve_id TEXT PRIMARY KEY REFERENCES source_record(id), - checked_at TEXT NOT NULL, fetched_at TEXT, - payload_json TEXT NOT NULL, error INTEGER NOT NULL CHECK(error IN (0,1)) -); diff --git a/services/advisories/migrations/0005_runtime_sources.sql b/services/advisories/migrations/0005_runtime_sources.sql deleted file mode 100644 index 612d0f88a..000000000 --- a/services/advisories/migrations/0005_runtime_sources.sql +++ /dev/null @@ -1,12 +0,0 @@ -CREATE TABLE runtime_source ( - cache_key TEXT PRIMARY KEY, - source_url TEXT NOT NULL, - checked_at TEXT NOT NULL, - successful_at TEXT, - revision TEXT, - payload_sha256 TEXT, - object_key TEXT, - error TEXT, - CHECK((successful_at IS NULL AND payload_sha256 IS NULL AND object_key IS NULL) - OR (successful_at IS NOT NULL AND payload_sha256 IS NOT NULL AND object_key IS NOT NULL)) -); diff --git a/services/advisories/migrations/0006_baseline_publisher_proof.sql b/services/advisories/migrations/0006_baseline_publisher_proof.sql deleted file mode 100644 index 3c845c748..000000000 --- a/services/advisories/migrations/0006_baseline_publisher_proof.sql +++ /dev/null @@ -1,46 +0,0 @@ -CREATE TABLE baseline_import_blob ( - session_id TEXT NOT NULL REFERENCES baseline_receipt(session_id), - cve_id TEXT NOT NULL, - payload_sha256 TEXT NOT NULL CHECK(length(payload_sha256)=64), - git_blob_sha1 TEXT NOT NULL CHECK(length(git_blob_sha1)=40), - PRIMARY KEY(session_id,cve_id) -); -CREATE TRIGGER baseline_import_blob_no_update BEFORE UPDATE ON baseline_import_blob BEGIN SELECT RAISE(ABORT,'baseline blob identity is immutable'); END; -CREATE TRIGGER baseline_import_blob_no_delete BEFORE DELETE ON baseline_import_blob BEGIN SELECT RAISE(ABORT,'baseline blob identity is immutable'); END; -CREATE TABLE baseline_publisher_proof ( - session_id TEXT PRIMARY KEY REFERENCES baseline_receipt(session_id), - release_tag TEXT NOT NULL, - asset_name TEXT NOT NULL, - asset_size INTEGER NOT NULL, - archive_digest TEXT NOT NULL, - commit_sha TEXT NOT NULL, - root_tree_sha TEXT NOT NULL, - cves_tree_sha TEXT NOT NULL, - provenance_key TEXT NOT NULL, - provenance_sha256 TEXT NOT NULL, - phase TEXT NOT NULL CHECK(phase IN ('traversing','reconciling','verified')), - after_id TEXT NOT NULL DEFAULT '', - expected_count INTEGER NOT NULL DEFAULT 0, - verified_count INTEGER NOT NULL DEFAULT 0, - checked_at TEXT NOT NULL, - verified_at TEXT -); -CREATE TABLE baseline_publisher_tree ( - session_id TEXT NOT NULL REFERENCES baseline_publisher_proof(session_id), - path TEXT NOT NULL, - tree_sha TEXT NOT NULL, - done INTEGER NOT NULL DEFAULT 0 CHECK(done IN (0,1)), - object_key TEXT, - payload_sha256 TEXT, - PRIMARY KEY(session_id,path) -); -CREATE INDEX baseline_publisher_tree_pending ON baseline_publisher_tree(session_id,done,path); -CREATE TABLE baseline_expected_member ( - session_id TEXT NOT NULL REFERENCES baseline_publisher_proof(session_id), - cve_id TEXT NOT NULL, - path TEXT NOT NULL, - git_blob_sha1 TEXT NOT NULL, - PRIMARY KEY(session_id,cve_id), - UNIQUE(session_id,path) -); -CREATE INDEX source_record_supported ON source_record(supported); diff --git a/services/advisories/package.json b/services/advisories/package.json deleted file mode 100644 index 8caa878b6..000000000 --- a/services/advisories/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "@omg/advisories", - "private": true, - "type": "module", - "scripts": { - "test": "bun test test", - "check": "tsc --noEmit", - "types": "wrangler types --include-runtime=false", - "bootstrap": "bun scripts/bootstrap.ts", - "dry-run": "wrangler deploy --dry-run" - }, - "dependencies": { - "@renovatebot/pep440": "6.0.0", - "@renovatebot/ruby-semver": "6.0.0", - "@streamparser/json": "0.0.26", - "@zip.js/zip.js": "2.25.0", - "postgres": "^4.1.1", - "semver": "7.8.6", - "smol-toml": "1.9.1", - "yaml": "2.9.1", - "yauzl": "3.4.0" - }, - "devDependencies": { - "@cloudflare/workers-types": "5.20261110.1", - "@types/bun": "1.3.10", - "@types/semver": "7.8.0", - "@types/yauzl": "3.4.0", - "miniflare": "5.20261110.0-beta", - "typescript": "7.0.2", - "wrangler": "4.160.0" - }, - "overrides": { - "miniflare@5.20261110.0-beta>undici": "7.30.2" - } -} diff --git a/services/advisories/scripts/archive.ts b/services/advisories/scripts/archive.ts deleted file mode 100644 index af6cf1ed7..000000000 --- a/services/advisories/scripts/archive.ts +++ /dev/null @@ -1,214 +0,0 @@ -import { createReadStream } from "node:fs"; -import { createHash } from "node:crypto"; -import { crc32 } from "node:zlib"; -import { stat, mkdtemp, open, rm } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { openPromise } from "yauzl"; -import { LIMITS, parseCve, decodeUtf8 } from "../src/domain"; -export type ArchiveState = { - digest: string; - next_entry: number; - accepted: number; - exhausted: boolean; - finished_at: string | null; -}; -export async function fileHash(path: string) { - const info = await stat(path); - if (info.size > 1024 ** 3) - throw new Error("archive exceeds 1 GiB operator budget"); - const hash = createHash("sha256"); - let bytes = 0; - for await (const chunk of createReadStream(path)) { - bytes += chunk.length; - if (bytes > 1024 ** 3) - throw new Error("archive exceeds 1 GiB operator budget"); - hash.update(chunk); - } - return hash.digest("hex"); -} -async function corpusArchive(snapshot: string, directory: string): Promise { - const outer = await openPromise(snapshot, { - lazyEntries: true, autoClose: false, strictFileNames: true, validateEntrySizes: true, - }); - try { - if (outer.entryCount !== 1) return snapshot; - for await (const entry of outer.eachEntry()) { - if (entry.fileName !== "cves.zip") return snapshot; - if ( - entry.uncompressedSize > 1024 ** 3 || - entry.uncompressedSize / Math.max(1, entry.compressedSize) > 500 || - (entry.generalPurposeBitFlag & 1) !== 0 || - ![0, 8].includes(entry.compressionMethod) - ) throw new Error("invalid or oversize CVE archive wrapper"); - const inner = join(directory, "corpus.zip"); - const output = await open(inner, "wx", 0o600); - try { - const stream = await outer.openReadStreamPromise(entry); - let bytes = 0; - let checksum = 0; - try { - for await (const chunk of stream) { - const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); - bytes += data.length; - if (bytes > 1024 ** 3) throw new Error("archive wrapper expansion exceeds budget"); - checksum = crc32(data, checksum); - await output.writeFile(data); - } - } finally { stream.destroy(); } - if (bytes !== entry.uncompressedSize || checksum !== entry.crc32) - throw new Error("archive wrapper size or checksum mismatch"); - } finally { await output.close(); } - return inner; - } - return snapshot; - } finally { outer.close(); } -} -export async function scanArchive(options: { - path: string; - digest: string; - state: ArchiveState; - maxRecords: number; - batchSize?: number; - encodeBatch: (records: string[]) => string; - send: (body: string) => Promise; - save: (state: ArchiveState) => Promise; -}) { - const batchSize = options.batchSize ?? LIMITS.records; - if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 64) - throw new Error("invalid archive batch size"); - if (options.state.digest !== options.digest) - throw new Error("archive digest mismatch"); - const emptyBody = options.encodeBatch([]); - if (Buffer.byteLength(emptyBody) > LIMITS.batch) - throw new Error("encoded ingest batch exceeds limit"); - const directory = await mkdtemp(join(tmpdir(), "omg-advisory-verified-")); - const snapshot = join(directory, "archive.zip"); - try { - const output = await open(snapshot, "wx", 0o600); - try { - let copied = 0; - for await (const chunk of createReadStream(options.path)) { - copied += chunk.length; - if (copied > 1024 ** 3) throw new Error("archive exceeds 1 GiB operator budget"); - await output.writeFile(chunk); - } - } finally { - await output.close(); - } - if (await fileHash(snapshot) !== options.digest) throw new Error("archive digest mismatch"); - const zip = await openPromise(await corpusArchive(snapshot, directory), { - lazyEntries: true, - strictFileNames: true, - validateEntrySizes: true, - }); - let index = 0; - let scanned = 0; - let corpusRecords = 0; - let expanded = 0; - let sent = 0; - let pending: string[] = []; - let pendingBody = emptyBody; - let pendingNext = options.state.next_entry; - let stop = false; - async function flush() { - if (!pending.length) return; - await options.send(pendingBody); - options.state.accepted += pending.length; - sent += pending.length; - options.state.next_entry = pendingNext; - await options.save(options.state); - pending = []; - pendingBody = emptyBody; - } - try { - if (zip.entryCount > 1_000_000) - throw new Error("too many archive entries"); - for await (const entry of zip.eachEntry()) { - const current = index++; - scanned++; - if (scanned > 1_000_000) - throw new Error("too many archive entries"); - if (entry.fileName === "cves.zip") - throw new Error("CVE archive wrapper must be sole and single-level"); - if (entry.fileName.endsWith("/")) continue; - const match = - /(?:^|\/)cves\/(\d{4})\/([0-9]+xxx)\/(CVE-\d{4}-\d{4,19})\.json$/.exec( - entry.fileName, - ); - if (!match) { - if (/CVE-.*\.json$/.test(entry.fileName)) - throw new Error("unexpected CVE record path"); - continue; - } - corpusRecords++; - if (current < options.state.next_entry) continue; - if (sent + pending.length >= options.maxRecords) { - stop = true; - break; - } - if ( - entry.uncompressedSize > LIMITS.cveRecord || - entry.uncompressedSize / Math.max(1, entry.compressedSize) > - 500 || - (entry.generalPurposeBitFlag & 1) !== 0 - ) - throw new Error( - "oversize, encrypted or excessive compression entry", - ); - expanded += entry.uncompressedSize; - if (expanded > 8 * 1024 ** 3) - throw new Error("archive expansion exceeds budget"); - const stream = await zip.openReadStreamPromise(entry); - const chunks: Buffer[] = []; - let bytes = 0; - for await (const chunk of stream) { - const data = Buffer.isBuffer(chunk) - ? chunk - : Buffer.from(chunk); - bytes += data.length; - if (bytes > LIMITS.cveRecord) { - stream.destroy(); - throw new Error("record exceeds limit"); - } - chunks.push(data); - } - const raw = decodeUtf8(Buffer.concat(chunks)); - const record = parseCve(raw, match[3]); - const [, year, number] = record.id.split("-"); - if ( - year !== match[1] || - !number || - `${number.slice(0, -3)}xxx` !== match[2] - ) - throw new Error("CVE path mismatch"); - if (!record.supported) - throw new Error("unsupported CVE schema or state"); - let body = options.encodeBatch([...pending, raw]); - if (Buffer.byteLength(body) > LIMITS.batch) { - await flush(); - body = options.encodeBatch([raw]); - if (Buffer.byteLength(body) > LIMITS.batch) - throw new Error("encoded ingest batch exceeds limit"); - } - pending.push(raw); - pendingBody = body; - pendingNext = index; - if (pending.length === batchSize) await flush(); - } - await flush(); - if (!stop) { - if (corpusRecords === 0) throw new Error("archive contains no CVE records"); - options.state.next_entry = index; - options.state.exhausted = true; - options.state.finished_at = new Date().toISOString(); - await options.save(options.state); - } - return { sent, exhausted: options.state.exhausted }; - } finally { - zip.close(); - } - } finally { - await rm(directory, { recursive: true, force: true }); - } -} diff --git a/services/advisories/scripts/bootstrap.ts b/services/advisories/scripts/bootstrap.ts deleted file mode 100644 index bd9a1db97..000000000 --- a/services/advisories/scripts/bootstrap.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { readFile, rename, stat, lstat, open, rm } from "node:fs/promises"; -import { randomUUID } from "node:crypto"; -import { basename } from "node:path"; -import { parseArgs } from "node:util"; -import { scanArchive, fileHash, type ArchiveState } from "./archive"; -import { boundedBody, object, string, date } from "../src/domain"; -import { baselineBinding, operatorPost, readCheckpoint, recoverCheckpoint, verifyIngestReply, type BaselineBinding } from "./operator"; -const { values } = parseArgs({ - options: { - archive: { type: "string" }, - state: { type: "string" }, - endpoint: { type: "string" }, - "release-tag": { type: "string" }, - asset: { type: "string" }, - "token-file": { type: "string" }, - "max-records": { type: "string", default: "1000" }, - "delay-ms": { type: "string", default: "0" }, - "resume-instance": { type: "string" }, - "resume-session": { type: "string" }, - "dry-run": { type: "boolean", default: false }, - finalize: { type: "boolean", default: false }, - help: { type: "boolean", default: false }, - }, - strict: true, -}); -if (values.help) { - process.stdout.write( - "bun run bootstrap --archive PATH --state PATH --release-tag TAG --asset NAME [--endpoint HTTPS_URL] [--token-file MODE_600_FILE] [--max-records 1000] [--delay-ms 0] [--resume-instance ID --resume-session UUID] [--dry-run] [--finalize]\nINGEST_TOKEN environment variable is supported. No Cloudflare account credential is needed. Dry run never writes HTTP. Recovery requires a missing state file and replays the exact bound archive/session from zero. Batches remain serial and bounded by service limits.\n", - ); - process.exit(0); -} -async function run() { - if ( - !values.archive || - !values.state || - !values["release-tag"] || - !values.asset - ) - throw new Error("archive, state, release-tag and asset required"); - const max = Number(values["max-records"]); - const delay = Number(values["delay-ms"]); - if ( - !Number.isSafeInteger(max) || - max < 1 || - max > 100_000 || - !Number.isSafeInteger(delay) || - delay < 0 || - delay > 60_000 - ) - throw new Error("invalid operator bounds"); - const tag = values["release-tag"]; - if (!/^[a-zA-Z0-9_.-]{1,100}$/.test(tag)) - throw new Error("invalid release tag"); - const name = values.asset; - const full = - /^(\d{4}-\d{2}-\d{2})_all_CVEs_at_midnight\.zip(?:\.zip)?$/.exec(name); - if (!full?.[1] || basename(values.archive) !== name) - throw new Error("expected full baseline asset filename"); - const response = await fetch( - `https://api.github.com/repos/CVEProject/cvelistV5/releases/tags/${encodeURIComponent(tag)}`, - { - redirect: "error", - signal: AbortSignal.timeout(20_000), - headers: { - "User-Agent": "omg-advisories-bootstrap", - Accept: "application/vnd.github+json", - }, - }, - ); - if (!response.ok) - throw new Error(`release metadata HTTP ${response.status}`); - const release = object( - JSON.parse(await boundedBody(response.body, 1024 * 1024)), - ); - if (release.tag_name !== tag || !Array.isArray(release.assets)) - throw new Error("invalid release metadata"); - const asset = release.assets.map(object).find((v) => v.name === name); - if (!asset) throw new Error("asset absent from official release"); - const digest = string(asset.digest).replace(/^sha256:/, ""); - if (!/^[a-f0-9]{64}$/.test(digest)) - throw new Error("official asset SHA-256 missing"); - if ( - (await stat(values.archive)).size !== asset.size || - (await fileHash(values.archive)) !== digest - ) - throw new Error("official asset bytes mismatch"); - const baseline = date(`${full[1]}T00:00:00Z`); - let token = process.env.INGEST_TOKEN; - if (values["token-file"]) { - const info = await stat(values["token-file"]); - if ((info.mode & 0o077) !== 0) - throw new Error("token file must be private"); - token = (await readFile(values["token-file"], "utf8")).trim(); - } - const endpoint = values.endpoint ? new URL(values.endpoint) : null; - if ( - !values["dry-run"] && - (!endpoint || - endpoint.protocol !== "https:" || - endpoint.username || - endpoint.password || - endpoint.search || - endpoint.hash || - endpoint.pathname !== "/" || - !token || - token.length < 32) - ) - throw new Error("HTTPS endpoint and strong ingest token required"); - async function post(path: string, body: string) { - if (values["dry-run"]) return {}; - if (!endpoint || !token) - throw new Error("missing writer configuration"); - return operatorPost({endpoint,token,path,body}); - } - let binding: BaselineBinding | null = null; - let state: ArchiveState = { - digest, - next_entry: 0, - accepted: 0, - exhausted: false, - finished_at: null, - }; - let resumed=false; - try { - const info=await lstat(values.state); - if(!info.isFile() || info.isSymbolicLink() || info.size>16*1024) throw new Error("resume state must be a bounded regular file"); - const saved = object(JSON.parse(await readFile(values.state, "utf8"))); - const savedBinding=object(saved.baseline); - binding=baselineBinding(savedBinding,digest,endpoint?.origin??string(savedBinding.endpoint)); - state=readCheckpoint(saved,binding); - resumed=true; - } catch (error) { - if ( - !( - error instanceof Error && - "code" in error && - error.code === "ENOENT" - ) - ) - throw error; - } - if(values["resume-instance"] || values["resume-session"]) { - if(resumed || !endpoint || !values["resume-instance"] || !values["resume-session"]) throw new Error("recovery requires both instance/session, endpoint and a missing state file"); - binding=baselineBinding({digest,endpoint:endpoint.origin,instance_id:values["resume-instance"],session_id:values["resume-session"]},digest,endpoint.origin); - state=recoverCheckpoint(binding); - } - const startAccepted=state.accepted; - const startedAt=performance.now(); - let lastProgress=startedAt; - async function save(next: ArchiveState) { - if (values["dry-run"]) return; - const path = values.state; - if (!path) throw new Error("missing state path"); - const temporary=`${path}.tmp-${randomUUID()}`; - try { - const file=await open(temporary,"wx",0o600); - try { await file.writeFile(JSON.stringify({...next,baseline:binding})+"\n"); await file.sync(); } - finally { await file.close(); } - await rename(temporary,path); - } finally { await rm(temporary,{force:true}); } - const now=performance.now(); - if(now-lastProgress>=5000 || next.exhausted) { - process.stderr.write(JSON.stringify({event:"bootstrap_progress",wave_records:next.accepted-startAccepted,accepted:next.accepted,next_entry:next.next_entry,exhausted:next.exhausted,elapsed_seconds:Math.round((now-startedAt)/1000)})+"\n"); - lastProgress=now; - } - } - if (!values["dry-run"]) { - const started = await post("/internal/baseline/start", JSON.stringify({ - digest, - baseline_at: baseline, - ...binding, - })); - const actual=baselineBinding(started,digest,endpoint?.origin??""); - if(binding && (actual.instance_id!==binding.instance_id || actual.session_id!==binding.session_id)) throw new Error("baseline response changed the requested session binding"); - binding=actual; - await save(state); - } - if (!state.exhausted) - await scanArchive({ - path: values.archive, - digest, - state, - maxRecords: max, - batchSize: 64, - encodeBatch: (records) => JSON.stringify({source: "cve", records, baseline: binding}), - send: async (body) => { - const reply=await post("/internal/ingest", body); - if(!values["dry-run"]) { - const sent=object(JSON.parse(body)).records; - if(!Array.isArray(sent)) throw new Error("invalid encoded ingest records"); - verifyIngestReply(reply,sent.length); - if(delay>0) await Bun.sleep(delay); - } - }, - save, - }); - let finalized: Record | undefined; - if (values.finalize) { - if (!state.exhausted) throw new Error("archive not exhausted"); - finalized = await post("/internal/baseline", JSON.stringify({ - ...binding, - digest, - baseline_at: baseline, - accepted: state.accepted, - exhausted: true, - finished_at: state.finished_at, - })); - } - process.stdout.write( - JSON.stringify({ - dry_run: values["dry-run"], - accepted: state.accepted, - exhausted: state.exhausted, - bootstrap_complete: finalized?.bootstrap_complete === true, - archive_verified: finalized?.archive_verified === true, - caught_up: finalized?.caught_up === true, - next_entry: state.next_entry, - wave_records:state.accepted-startAccepted, - elapsed_seconds:Math.round((performance.now()-startedAt)/1000), - }) + "\n", - ); -} -run().catch((error) => { - process.stderr.write( - `${error instanceof Error ? error.message : "bootstrap failed"}\n`, - ); - process.exitCode = 1; -}); diff --git a/services/advisories/scripts/operator.ts b/services/advisories/scripts/operator.ts deleted file mode 100644 index 9b9a80cc0..000000000 --- a/services/advisories/scripts/operator.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { boundedBody, date, object } from "../src/domain"; -import type { ArchiveState } from "./archive"; -export type BaselineBinding = { digest:string; endpoint:string; instance_id:string; session_id:string }; -export type Checkpoint = ArchiveState & { baseline:BaselineBinding }; -export type OperatorFetcher = (input:Parameters[0],init?:Parameters[1])=>ReturnType; -export function baselineBinding(value:unknown, digest:string, endpoint:string):BaselineBinding { - const input=object(value); - if(input.digest!==digest || input.endpoint!==endpoint || !/^[a-f0-9]{64}$/.test(digest) - || typeof input.instance_id!=="string" || !/^[a-f0-9]{32}$/.test(input.instance_id) - || typeof input.session_id!=="string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(input.session_id)) throw new Error("invalid baseline binding"); - const url=new URL(endpoint); - if(url.protocol!=="https:" || url.origin!==endpoint) throw new Error("invalid baseline endpoint binding"); - return {digest,endpoint,instance_id:input.instance_id,session_id:input.session_id}; -} -export function recoverCheckpoint(binding:BaselineBinding):Checkpoint { - const checked=baselineBinding(binding,binding.digest,binding.endpoint); - return {digest:checked.digest,next_entry:0,accepted:0,exhausted:false,finished_at:null,baseline:checked}; -} -export function readCheckpoint(value:unknown, binding:BaselineBinding):Checkpoint { - const saved=object(value), baseline=object(saved.baseline); - if (saved.digest!==binding.digest || baseline.digest!==binding.digest || baseline.endpoint!==binding.endpoint || baseline.instance_id!==binding.instance_id || baseline.session_id!==binding.session_id) - throw new Error("invalid resume binding"); - if (!Number.isSafeInteger(saved.next_entry) || !Number.isSafeInteger(saved.accepted) - || Number(saved.next_entry)<0 || Number(saved.next_entry)>1_000_000 || Number(saved.accepted)<0 || Number(saved.accepted)>Number(saved.next_entry) - || typeof saved.exhausted!=="boolean" || !(saved.finished_at===null || typeof saved.finished_at==="string") - || (saved.exhausted && (Number(saved.accepted)===0 || saved.finished_at===null)) || (!saved.exhausted && saved.finished_at!==null)) throw new Error("invalid resume position"); - return {digest:binding.digest,next_entry:Number(saved.next_entry),accepted:Number(saved.accepted),exhausted:saved.exhausted,finished_at:saved.finished_at===null?null:date(saved.finished_at),baseline:baselineBinding(baseline,binding.digest,binding.endpoint)}; -} -export async function operatorPost(options:{endpoint:URL;token:string;path:string;body:string;fetcher?:OperatorFetcher;sleep?:(ms:number)=>Promise}) { - const fetcher=options.fetcher??fetch, sleep=options.sleep??Bun.sleep; - for(let attempt=0;attempt<5;attempt++) { - let reply:Response; - try { - reply=await fetcher(new URL(options.path,options.endpoint),{method:"POST",redirect:"error",signal:AbortSignal.timeout(60_000),headers:{authorization:`Bearer ${options.token}`,"content-type":"application/json"},body:options.body}); - } catch { - if(attempt===4) throw new Error("ingest transport failed after bounded retries; progress retained"); - await sleep(Math.min(30_000,1000*2**attempt)); - continue; - } - if(reply.ok) { - let raw:string; - try { raw=await boundedBody(reply.body,16*1024); } - catch { - if(attempt===4) throw new Error("ingest response transport failed after bounded retries; progress retained"); - await sleep(Math.min(30_000,1000*2**attempt)); - continue; - } - try { return object(JSON.parse(raw)); } - catch { throw new Error("invalid bounded ingest response; progress retained"); } - } - const retryAfter=reply.headers.get("retry-after"); - await reply.body?.cancel(); - if(![409,429,500,502,503,504].includes(reply.status)||attempt===4) throw new Error(`ingest HTTP ${reply.status}; progress retained`); - const seconds=retryAfter!==null && /^\d+$/.test(retryAfter)?Number(retryAfter):NaN; - const requested=Number.isFinite(seconds)?seconds*1000:retryAfter===null?NaN:Date.parse(retryAfter)-Date.now(); - await sleep(Math.min(30_000,Math.max(1000*2**attempt,Number.isFinite(requested)?requested:0))); - } - throw new Error("operator request failed; progress retained"); -} -export function verifyIngestReply(value:unknown,expected:number):void { - if(object(value).accepted!==expected) throw new Error("ingest accepted count mismatch; progress retained"); -} - -export function proofProgress(value:unknown, expected:{digest:string;release_tag:string;asset:string}) { - const reply=object(value); - if(reply.digest!==expected.digest || reply.release_tag!==expected.release_tag || reply.asset!==expected.asset - || typeof reply.commit_sha!=="string" || !/^[a-f0-9]{40}$/.test(reply.commit_sha)) throw new Error("baseline proof publisher binding mismatch"); - const phase=reply.phase; - if(reply.schema_version!==1 || (phase!=="traversing" && phase!=="reconciling" && phase!=="awaiting_import" && phase!=="awaiting_catchup" && phase!=="verified") - || !Number.isSafeInteger(reply.expected_count) || Number(reply.expected_count)<0 || Number(reply.expected_count)>1_000_000 - || !Number.isSafeInteger(reply.verified_count) || Number(reply.verified_count)<0 || Number(reply.verified_count)>Number(reply.expected_count) - || !Number.isSafeInteger(reply.pending_trees) || Number(reply.pending_trees)<0 || Number(reply.pending_trees)>1_000_000 - || typeof reply.archive_verified!=="boolean") throw new Error("invalid baseline proof progress"); - if(reply.archive_verified!==(phase==="verified") || (phase==="verified" && (Number(reply.expected_count)===0 || reply.verified_count!==reply.expected_count || reply.pending_trees!==0))) - throw new Error("inconsistent baseline proof certification"); - return {schema_version:1,phase,expected_count:Number(reply.expected_count),verified_count:Number(reply.verified_count),pending_trees:Number(reply.pending_trees),archive_verified:reply.archive_verified,digest:expected.digest,release_tag:expected.release_tag,asset:expected.asset,commit_sha:reply.commit_sha}; -} diff --git a/services/advisories/scripts/verify-baseline.ts b/services/advisories/scripts/verify-baseline.ts deleted file mode 100644 index a4172c06c..000000000 --- a/services/advisories/scripts/verify-baseline.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { lstat, readFile } from "node:fs/promises"; -import { parseArgs } from "node:util"; -import { isGitHubInstallationToken, object, string } from "../src/domain"; -import { baselineBinding, operatorPost, proofProgress, readCheckpoint } from "./operator"; - -const { values }=parseArgs({options:{state:{type:"string"},"release-tag":{type:"string"},asset:{type:"string"},"max-steps":{type:"string",default:"20"},"delay-ms":{type:"string",default:"0"},help:{type:"boolean",default:false}},strict:true}); -if(values.help) { - process.stdout.write("bun scripts/verify-baseline.ts --state PATH --release-tag TAG --asset NAME [--max-steps 20] [--delay-ms 0]\nRequires RUNTIME_REFRESH_SECRET and an ephemeral ghs_ GITHUB_TOKEN through environment only. The server derives publisher membership; operator counts and manifests cannot certify coverage. Stops when awaiting import/catchup or after its bounded serial step budget.\n"); - process.exit(0); -} -async function run() { - if(!values.state || !values["release-tag"] || !values.asset) throw new Error("state, release-tag and asset required"); - const steps=Number(values["max-steps"]),delay=Number(values["delay-ms"]); - if(!Number.isSafeInteger(steps)||steps<1||steps>1000||!Number.isSafeInteger(delay)||delay<0||delay>60000) throw new Error("invalid proof operator bounds"); - const info=await lstat(values.state); - if(!info.isFile()||info.isSymbolicLink()||info.size>16*1024) throw new Error("state must be a bounded regular file"); - const saved=object(JSON.parse(await readFile(values.state,"utf8"))); - const rawBinding=object(saved.baseline); - const binding=baselineBinding(rawBinding,string(saved.digest),string(rawBinding.endpoint)); - readCheckpoint(saved,binding); - const secret=process.env.RUNTIME_REFRESH_SECRET, githubToken=process.env.GITHUB_TOKEN; - if(!secret || secret.length<32 || !isGitHubInstallationToken(githubToken)) throw new Error("separate proof secret and ephemeral GitHub installation token required through environment"); - const body=JSON.stringify({...binding,release_tag:values["release-tag"],asset:values.asset,github_token:githubToken}); - for(let step=0;step0 && step+1{process.stderr.write(`${error instanceof Error?error.message:"baseline proof operator failed"}\n`);process.exitCode=1;}); diff --git a/services/advisories/src/baseline.ts b/services/advisories/src/baseline.ts deleted file mode 100644 index 708760337..000000000 --- a/services/advisories/src/baseline.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { boundedBody, cveId, isGitHubInstallationToken, object, sha256 } from "./domain"; -import type { Fetcher } from "./ingestion"; -import { Store, type Command } from "./storage"; - -export type BaselineBinding = { digest: string; instance_id: string; session_id: string; endpoint: string; baseline_at: string }; -export class BaselineBusyError extends Error {} -type Receipt = BaselineBinding & { exhausted: number; caught_up: number; completed_at: string | null; accepted: number }; -type Proof = { session_id: string; release_tag: string; asset_name: string; asset_size: number; archive_digest: string; - commit_sha: string; root_tree_sha: string; cves_tree_sha: string; phase: "traversing" | "reconciling" | "verified"; - expected_count: number; verified_count: number; after_id: string; verified_at: string | null }; -type Tree = { path: string; tree_sha: string }; -type Entry = { path: string; sha: string; type: "tree" | "blob"; mode: "040000" | "100644" }; -const prefix = "/repos/CVEProject/cvelistV5/"; -const hashPattern = /^[a-f0-9]{40}$/; -function gitHash(value: unknown): string { - if (typeof value !== "string" || !hashPattern.test(value)) throw new Error("invalid publisher Git identity"); - return value; -} -export async function gitBlobSha1(raw: string): Promise { - const payload = new TextEncoder().encode(raw); - const header = new TextEncoder().encode(`blob ${payload.byteLength}\0`); - const bytes = new Uint8Array(header.length + payload.length); - bytes.set(header); bytes.set(payload, header.length); - return [...new Uint8Array(await crypto.subtle.digest("SHA-1", bytes))].map((byte) => byte.toString(16).padStart(2, "0")).join(""); -} -export async function baselineImportCommands(store: Store, session: string, records: readonly { id: string; raw: string }[]): Promise { - const rows = await Promise.all(records.map(async ({ id, raw }) => ({ id, hash: await sha256(raw), git: await gitBlobSha1(raw) }))); - const encoded = JSON.stringify(rows); - const conflict = await store.sql.first<{ cve_id: string }>( - "SELECT b.cve_id FROM json_each(?) j CROSS JOIN baseline_member b ON b.session_id=? AND b.cve_id=json_extract(j.value,'$.id') WHERE b.payload_sha256<>json_extract(j.value,'$.hash') LIMIT 1", [encoded, session]); - if (conflict) throw new Error("baseline original payload mismatch"); - return [ - { sql: "INSERT INTO baseline_member(session_id,cve_id,payload_sha256) SELECT ?,json_extract(value,'$.id'),json_extract(value,'$.hash') FROM json_each(?) WHERE 1 ON CONFLICT(session_id,cve_id) DO NOTHING", values: [session, encoded] }, - { sql: "INSERT INTO baseline_import_blob(session_id,cve_id,payload_sha256,git_blob_sha1) SELECT ?,json_extract(value,'$.id'),json_extract(value,'$.hash'),json_extract(value,'$.git') FROM json_each(?) WHERE 1 ON CONFLICT(session_id,cve_id) DO NOTHING", values: [session, encoded] }, - { sql: "UPDATE baseline_receipt SET caught_up=0,completed_at=NULL WHERE session_id=?", values: [session] }, - { sql: "UPDATE source_checkpoint SET bootstrap_complete=0 WHERE source='cve'", values: [] }, - { sql: "UPDATE baseline_publisher_proof SET phase=CASE WHEN phase='traversing' THEN phase ELSE 'reconciling' END,after_id='',verified_count=0,verified_at=NULL WHERE session_id=?", values: [session] }, - ]; -} -function entries(value: unknown, sha: string): Entry[] { - const data = object(value); - if (data.sha !== sha || data.truncated !== false || !Array.isArray(data.tree) || data.tree.length > 4096) - throw new Error("invalid or truncated publisher tree"); - const paths = new Set(); - return data.tree.map((item) => { - const row = object(item); - if (typeof row.path !== "string" || !/^[A-Za-z0-9_.-]{1,200}$/.test(row.path) || row.path === "." || row.path === ".." || paths.has(row.path)) - throw new Error("invalid duplicate publisher tree path"); - paths.add(row.path); - if (!((row.type === "tree" && row.mode === "040000") || (row.type === "blob" && row.mode === "100644"))) - throw new Error("invalid publisher tree mode"); - return { path: row.path, sha: gitHash(row.sha), type: row.type, mode: row.mode }; - }); -} -async function activeReceipt(store: Store, input: Record, endpoint: string): Promise { - const receipt = await store.sql.first("SELECT * FROM baseline_receipt WHERE digest=?", [typeof input.digest === "string" ? input.digest : ""]); - const checkpoint = await store.checkpoint("cve"); - if (!receipt || receipt.endpoint !== endpoint || input.endpoint !== endpoint || receipt.instance_id !== input.instance_id || - receipt.session_id !== input.session_id || checkpoint?.baseline_digest !== receipt.digest) throw new Error("invalid baseline session binding"); - return receipt; -} -export async function verifyBaseline(value: unknown, store: Store, endpoint: string, now: string, fetcher: Fetcher) { - const input = object(value); - const allowed = new Set(["digest", "instance_id", "session_id", "endpoint", "release_tag", "asset", "github_token", "started", "baseline_at"]); - if (Object.keys(input).some((key) => !allowed.has(key)) || !isGitHubInstallationToken(input.github_token)) - throw new Error("invalid baseline verification credential or fields"); - const token = input.github_token; - const initial = await activeReceipt(store, input, endpoint); - const day = initial.baseline_at.slice(0, 10); - if (initial.baseline_at !== `${day}T00:00:00.000Z` || input.release_tag !== `cve_${day}_0000Z` || - (input.asset !== `${day}_all_CVEs_at_midnight.zip` && input.asset !== `${day}_all_CVEs_at_midnight.zip.zip`)) - throw new Error("invalid baseline publisher release"); - const releaseTag = input.release_tag; - const assetName = input.asset; - const owner = crypto.randomUUID(); - if (!await store.lease("cve", owner, now)) throw new BaselineBusyError("baseline verification busy"); - const writer = store.writer("cve", owner); - let bytesRead = 0; - const signal = AbortSignal.timeout(25_000); - async function read(path: string) { - if (!new RegExp(`^${prefix}(?:releases/tags/cve_\\d{4}-\\d{2}-\\d{2}_0000Z|git/ref/tags/cve_\\d{4}-\\d{2}-\\d{2}_0000Z|git/(?:commits|trees)/[a-f0-9]{40})$`).test(path)) - throw new Error("invalid publisher request path"); - const response = await fetcher(`https://api.github.com${path}`, { method: "GET", redirect: "manual", signal, - headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "user-agent": "omg-advisories-baseline/1", "x-github-api-version": "2022-11-28" } }); - if (!response.ok) throw new Error(`publisher HTTP ${response.status}`); - const raw = await boundedBody(response.body, 2 * 1024 ** 2); - bytesRead += new TextEncoder().encode(raw).length; - if (bytesRead > 16 * 1024 ** 2 || raw.includes(token)) throw new Error("invalid publisher response bounds"); - const hash = await sha256(raw); - const key = `baseline-proof/${initial.session_id}/${hash}.json`; - await writer.raw.put(key, raw); - return { data: object(JSON.parse(raw)), key, hash }; - } - try { - const receipt = await activeReceipt(writer, input, endpoint); - let proof = await writer.sql.first("SELECT * FROM baseline_publisher_proof WHERE session_id=?", [receipt.session_id]); - if (!proof) { - const release = await read(`${prefix}releases/tags/${releaseTag}`); - if (release.data.tag_name !== releaseTag || !Array.isArray(release.data.assets)) throw new Error("invalid publisher release metadata"); - const assets = release.data.assets.map(object).filter((asset) => asset.name === assetName); - const asset = assets[0]; - if (assets.length !== 1 || !asset || asset.digest !== `sha256:${receipt.digest}` || typeof asset.size !== "number" || !Number.isSafeInteger(asset.size) || asset.size < 1 || asset.size > 1024 ** 3) - throw new Error("baseline publisher archive digest mismatch"); - const ref = await read(`${prefix}git/ref/tags/${releaseTag}`); - const target = object(ref.data.object); - if (target.type !== "commit") throw new Error("invalid publisher release commit"); - const commitSha = gitHash(target.sha); - const commit = await read(`${prefix}git/commits/${commitSha}`); - if (commit.data.sha !== commitSha) throw new Error("invalid publisher commit identity"); - const rootSha = gitHash(object(commit.data.tree).sha); - const root = await read(`${prefix}git/trees/${rootSha}`); - const cves = entries(root.data, rootSha).find((entry) => entry.path === "cves"); - if (cves?.type !== "tree") throw new Error("invalid publisher cves root"); - const provenance = JSON.stringify({ release: { key: release.key, sha256: release.hash }, ref: { key: ref.key, sha256: ref.hash }, commit: { key: commit.key, sha256: commit.hash }, root: { key: root.key, sha256: root.hash } }); - const provenanceHash = await sha256(provenance), provenanceKey = `baseline-proof/${receipt.session_id}/${provenanceHash}.json`; - await writer.raw.put(provenanceKey, provenance); - await writer.sql.batch([ - { sql: "INSERT INTO baseline_publisher_proof(session_id,release_tag,asset_name,asset_size,archive_digest,commit_sha,root_tree_sha,cves_tree_sha,provenance_key,provenance_sha256,phase,checked_at) VALUES(?,?,?,?,?,?,?,?,?,?,'traversing',?)", values: [receipt.session_id, releaseTag, assetName, asset.size, receipt.digest, commitSha, rootSha, cves.sha, provenanceKey, provenanceHash, now] }, - { sql: "INSERT INTO baseline_publisher_tree(session_id,path,tree_sha) VALUES(?,'cves',?)", values: [receipt.session_id, cves.sha] }, - ]); - proof = await writer.sql.first("SELECT * FROM baseline_publisher_proof WHERE session_id=?", [receipt.session_id]); - } - if (!proof || proof.release_tag !== releaseTag || proof.asset_name !== assetName || proof.archive_digest !== receipt.digest) throw new Error("baseline publisher proof binding mismatch"); - for (let step = 0; proof.phase === "traversing" && step < 8; step++) { - const tree = await writer.sql.first("SELECT path,tree_sha FROM baseline_publisher_tree WHERE session_id=? AND done=0 ORDER BY path LIMIT 1", [receipt.session_id]); - if (!tree) { - await writer.sql.batch([{ sql: "UPDATE baseline_publisher_proof SET phase='reconciling',checked_at=? WHERE session_id=?", values: [now, receipt.session_id] }]); - proof.phase = "reconciling"; break; - } - const fetched = await read(`${prefix}git/trees/${gitHash(tree.tree_sha)}`); - const children: { path: string; sha: string }[] = [], members: { id: string; path: string; sha: string }[] = []; - for (const entry of entries(fetched.data, tree.tree_sha)) { - const parts = tree.path.split("/"); - if (parts.length === 1) { - if (entry.type === "blob" && (entry.path === "delta.json" || entry.path === "deltaLog.json")) continue; - if (entry.type !== "tree" || !/^\d{4}$/.test(entry.path)) throw new Error("invalid publisher year member"); - } else if (parts.length === 2) { - if (entry.type !== "tree" || !/^\d{1,16}xxx$/.test(entry.path)) throw new Error("invalid publisher group member"); - } else if (parts.length === 3) { - if (entry.type !== "blob" || !entry.path.endsWith(".json")) throw new Error("invalid publisher CVE member"); - const id = cveId(entry.path.slice(0, -5)), match = /^CVE-(\d{4})-(\d+)$/.exec(id); - if (!match || match[1] !== parts[1] || `${match[2]?.slice(0, -3)}xxx` !== parts[2]) throw new Error("publisher CVE path mismatch"); - members.push({ id, path: `${tree.path}/${entry.path}`, sha: entry.sha }); continue; - } else throw new Error("invalid publisher tree depth"); - children.push({ path: `${tree.path}/${entry.path}`, sha: entry.sha }); - } - await writer.sql.batch([ - { sql: "INSERT INTO baseline_publisher_tree(session_id,path,tree_sha) SELECT ?,json_extract(value,'$.path'),json_extract(value,'$.sha') FROM json_each(?)", values: [receipt.session_id, JSON.stringify(children)] }, - { sql: "INSERT INTO baseline_expected_member(session_id,cve_id,path,git_blob_sha1) SELECT ?,json_extract(value,'$.id'),json_extract(value,'$.path'),json_extract(value,'$.sha') FROM json_each(?)", values: [receipt.session_id, JSON.stringify(members)] }, - { sql: "UPDATE baseline_publisher_tree SET done=1,object_key=?,payload_sha256=? WHERE session_id=? AND path=?", values: [fetched.key, fetched.hash, receipt.session_id, tree.path] }, - { sql: "UPDATE baseline_publisher_proof SET expected_count=expected_count+?,checked_at=? WHERE session_id=?", values: [members.length, now, receipt.session_id] }, - ]); - proof.expected_count += members.length; - } - const pending = await writer.sql.first<{ count: number }>("SELECT COUNT(*) AS count FROM baseline_publisher_tree WHERE session_id=? AND done=0", [receipt.session_id]); - let phase: string = proof.phase; - if (pending?.count === 0 && proof.phase === "traversing") { - await writer.sql.batch([{ sql: "UPDATE baseline_publisher_proof SET phase='reconciling',checked_at=? WHERE session_id=?", values: [now, receipt.session_id] }]); - proof.phase = "reconciling"; phase = proof.phase; - } - if (proof.phase === "reconciling") { - phase = receipt.exhausted === 1 && receipt.caught_up === 1 ? "reconciling" : "awaiting_import"; - for (let page = 0; phase === "reconciling" && page < 8; page++) { - const rows = await writer.sql.all<{ cve_id: string; expected_sha: string; member_sha: string | null; import_sha: string | null; git_sha: string | null }>( - "SELECT e.cve_id,e.git_blob_sha1 AS expected_sha,b.payload_sha256 AS member_sha,i.payload_sha256 AS import_sha,i.git_blob_sha1 AS git_sha FROM baseline_expected_member e LEFT JOIN baseline_member b ON b.session_id=e.session_id AND b.cve_id=e.cve_id LEFT JOIN baseline_import_blob i ON i.session_id=e.session_id AND i.cve_id=e.cve_id WHERE e.session_id=? AND e.cve_id>? ORDER BY e.cve_id LIMIT 512", [receipt.session_id, proof.after_id]); - if (!rows.length) { - const counts = await writer.sql.first<{ members: number; blobs: number; unsupported: number }>("SELECT (SELECT COUNT(*) FROM baseline_member WHERE session_id=?) AS members,(SELECT COUNT(*) FROM baseline_import_blob WHERE session_id=?) AS blobs,(SELECT COUNT(*) FROM source_record WHERE supported=0) AS unsupported", [receipt.session_id, receipt.session_id]); - if (!counts || proof.expected_count < 1 || counts.members !== proof.expected_count || counts.blobs !== proof.expected_count || receipt.accepted !== proof.expected_count || proof.verified_count !== proof.expected_count) throw new Error("baseline publisher membership count mismatch"); - if (counts.unsupported) throw new Error("unsupported records prevent completeness"); - const checkpoint = await writer.checkpoint("cve"); - const age = checkpoint?.checked_at ? Date.parse(now) - Date.parse(checkpoint.checked_at) : Infinity; - if (!checkpoint?.complete || checkpoint.error || age < 0 || age > 30 * 60_000 || !receipt.completed_at || !checkpoint.checked_at || checkpoint.checked_at < receipt.completed_at) { phase = "awaiting_catchup"; break; } - await writer.sql.batch([ - { sql: "UPDATE baseline_publisher_proof SET phase='verified',verified_at=?,checked_at=? WHERE session_id=?", values: [now, now, receipt.session_id] }, - { sql: "UPDATE source_checkpoint SET bootstrap_complete=1 WHERE source='cve' AND baseline_digest=?", values: [receipt.digest] }, - ]); - proof.phase = "verified"; phase = "verified"; break; - } - if (rows.some((row) => row.member_sha === null || row.import_sha === null || row.git_sha === null)) { phase = "awaiting_import"; break; } - if (rows.some((row) => row.member_sha !== row.import_sha || row.expected_sha !== row.git_sha)) throw new Error("baseline publisher original Git blob mismatch"); - const last = rows.at(-1); - if (!last) throw new Error("invalid publisher reconciliation page"); - proof.after_id = last.cve_id; proof.verified_count += rows.length; - await writer.sql.batch([{ sql: "UPDATE baseline_publisher_proof SET after_id=?,verified_count=?,checked_at=? WHERE session_id=?", values: [proof.after_id, proof.verified_count, now, receipt.session_id] }]); - } - } - return { schema_version: 1, phase, expected_count: proof.expected_count, verified_count: proof.verified_count, pending_trees: pending?.count ?? 0, - archive_verified: proof.phase === "verified", commit_sha: proof.commit_sha, release_tag: proof.release_tag, asset: proof.asset_name, digest: proof.archive_digest }; - } catch (error) { - throw new Error((error instanceof Error ? error.message : "publisher verification failed").replaceAll(token, "[redacted]")); - } finally { await store.release("cve", owner); } -} diff --git a/services/advisories/src/cache.ts b/services/advisories/src/cache.ts deleted file mode 100644 index 2f1afdef1..000000000 --- a/services/advisories/src/cache.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { object, sha256 } from "./domain"; - -const MAX_CACHE_URL_LENGTH = 8 * 1024; -const CACHE_ORIGIN = /^https?:\/\/(?:[a-z0-9.-]{1,253}|\[[a-f0-9:]{2,39}\])(?::[0-9]{1,5})?$/; -const CACHE_DIGEST = /^[a-f0-9]{64}$/; - -function publicRead(request: Request): boolean { - return request.method === "GET" && !request.headers.has("authorization") && - !request.headers.has("cookie") && - /^\/v1\/(?:arch\/advisories|bundles\/hot|packages\/check|eol(?:\/[a-z0-9-]+)?|cves\/(?:recent|CVE-\d{4}-\d{4,19})|epss\/CVE-\d{4}-\d{4,19}|runtimes\/[a-z]+)$/.test(new URL(request.url).pathname); -} -function conditional(request: Request, response: Response): Response { - const etag = response.headers.get("etag"); - const matches = request.headers.get("if-none-match")?.split(",") - .some((tag) => tag.trim() === "*" || tag.trim().replace(/^W\//, "") === etag); - - if (!etag || !matches) return response; - void response.body?.cancel().catch(() => undefined); - - return new Response(null, { status: 304, headers: response.headers }); -} - -async function writeCache(cache: Pick, key: Request, response: Response): Promise { - try { - await cache.put(key, response.clone()); - } catch (error) { - console.error("advisory_cache_write_failed", error); - } -} - -export async function publicResponse(request: Request, response: Response, now: string): Promise { - response.headers.set("Cache-Control", "no-store"); - if (!publicRead(request) || response.status !== 200) return response; - const text = await response.text(); - const body = object(JSON.parse(text)); - const checked: unknown[] = [body.checked_at, body.cve_checked_at, body.kev_checked_at] - .filter((value) => value !== undefined); - const milliseconds = Date.parse(now); - const epss = new URL(request.url).pathname.startsWith("/v1/epss/"); - const runtime = new URL(request.url).pathname.startsWith("/v1/runtimes/"); - if (runtime) { - if (body.coverage !== "assessed" || !Array.isArray(body.sources) || body.sources.length === 0 || - body.sources.some((source: unknown) => object(source).complete !== true)) - return new Response(text, { status: response.status, headers: response.headers }); - checked.push(...body.sources.map((source: unknown) => object(source).checked_at)); - } - if (epss && body.status === "unavailable") - return new Response(text, { status: response.status, headers: response.headers }); - const freshness = epss ? 6 * 60 * 60_000 : 30 * 60_000; - let ttl = checked.length ? 60 : 0; - for (const value of checked) { - const at = typeof value === "string" ? Date.parse(value) : NaN; - ttl = Math.min(ttl, Number.isFinite(at) && at <= milliseconds - ? Math.max(0, Math.floor((at + freshness - milliseconds) / 1000)) : 0); - } - if (epss && body.status === "scored") { - const day = object(body.score).date; - const at = typeof day === "string" ? Date.parse(`${day}T00:00:00Z`) : NaN; - ttl = Math.min(ttl, Number.isFinite(at) ? Math.max(0, Math.floor((at + 2 * 24 * 60 * 60_000 - milliseconds) / 1000)) : 0); - } - response.headers.set("ETag", `"${await sha256(text)}"`); - if (ttl > 0) { - response.headers.set("Cache-Control", `public, max-age=${ttl}, must-revalidate`); - response.headers.set("Date", new Date(milliseconds).toUTCString()); - response.headers.set("Expires", new Date(milliseconds + ttl * 1000).toUTCString()); - } - return conditional(request, new Response(text, { status: response.status, headers: response.headers })); -} - -export async function cachedRead( - request: Request, cache: Pick, - load: (request: Request) => Promise, now = Date.now(), - waitUntil?: (promise: Promise) => void, -): Promise { - if (request.url.length > MAX_CACHE_URL_LENGTH || !publicRead(request)) return load(request); - const origin = CACHE_ORIGIN.exec(new URL(request.url).origin)?.[0]; - if (!origin) return load(request); - const digest = CACHE_DIGEST.exec(await sha256(request.url))?.[0]; - if (!digest) return load(request); - // Keep the request's zone and distinguish every query without using it as a cache path. - const key = new Request(`${origin}/.omg/advisory-cache/v1/${digest}`); - const directives = request.headers.get("cache-control") ?? ""; - const noStore = /(?:^|,)\s*no-store\s*(?:,|$)/i.test(directives); - const revalidate = noStore || /(?:^|,)\s*(?:no-cache|max-age\s*=\s*0)\s*(?:,|$)/i.test(directives) || - request.headers.get("pragma")?.toLowerCase() === "no-cache"; - if (!revalidate) { - try { - const hit = await cache.match(key); - if (hit && Date.parse(hit.headers.get("Expires") ?? "") > now) - return conditional(request, hit); - } catch (error) { - console.error("advisory_cache_read_failed", error); - } - } - const response = await load(request); - if (!noStore && response.status === 200 && response.headers.get("Cache-Control")?.startsWith("public,")) { - const write = writeCache(cache, key, response); - - if (waitUntil) waitUntil(write); - else await write; - } - return conditional(request, response); -} diff --git a/services/advisories/src/delta.ts b/services/advisories/src/delta.ts deleted file mode 100644 index 9236b8ca0..000000000 --- a/services/advisories/src/delta.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { JSONParser } from "@streamparser/json"; -import { LIMITS, date, object, parseDelta, type DeltaItem } from "./domain"; - -type Cursor = { event: string; offset: number; feedOrder?: boolean }; - -type Pending = { item: DeltaItem; offset: number }; - -export const MAX_CVE_REFRESH_RECORDS = 512; - -interface DeltaRange { - oldest: string | null; - latest: string | null; -} - -export function readDeltaCursor(raw: string): Cursor { - const parsed = object(JSON.parse(raw)); - const event = date(parsed.event); - const offset = Number(parsed.offset); - - if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("invalid cursor"); - - return { event, offset, feedOrder: parsed.feedOrder === true }; -} - -export async function deltaBatch( - body: ReadableStream | null, - cursor: Cursor | null, - limit = LIMITS.deltaRecords, -) { - if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_CVE_REFRESH_RECORDS) - throw new Error("invalid delta batch limit"); - - if (!body) throw new Error("missing delta body"); - - const parser = new JSONParser({ - paths: ["$.*"], - keepStack: false, - stringBufferSize: 64 * 1024, - }); - - const candidates: Pending[] = []; - const offsets = new Map(); - const splitEvents = new Set(); - const legacyPrefix: Pending[] = []; - let skippedLegacy = 0; - let count = 0; - let events = 0; - const range: DeltaRange = { oldest: null, latest: null }; - let total = 0; - let eventBytes = 0; - parser.onValue = ({ value, parent, key }) => { - if (!Array.isArray(parent) || !Number.isSafeInteger(key)) - throw new Error("invalid delta root"); - eventBytes = 0; - events++; - - if (events > 100_000) throw new Error("too many delta events"); - const entries = parseDelta(JSON.stringify([value])); - const event = entries[0]?.event; - - if (!event) return; - - if (range.oldest === null || event < range.oldest) range.oldest = event; - - if (range.latest === null || event > range.latest) range.latest = event; - - const previousOffset = offsets.get(event) ?? 0; - - if (previousOffset > 0) splitEvents.add(event); - offsets.set(event, previousOffset + entries.length); - let offset = previousOffset; - - for (const item of entries) { - offset++; - - if (cursor && item.event < cursor.event) continue; - - if (cursor && item.event === cursor.event && offset <= cursor.offset) { - if (!cursor.feedOrder) { - skippedLegacy++; - - if (legacyPrefix.length < limit) legacyPrefix.push({ item, offset }); - } - - continue; - } - - count++; - candidates.push({ item, offset }); - candidates.sort( - (a, b) => - a.item.event.localeCompare(b.item.event) || - a.offset - b.offset, - ); - - if (candidates.length > limit) candidates.pop(); - } - }; - - const reader = body.getReader(); - - try { - while (true) { - const chunk = await reader.read(); - - if (chunk.done) break; - total += chunk.value.byteLength; - eventBytes += chunk.value.byteLength; - - if (total > 64 * 1024 * 1024 || eventBytes > 8 * 1024 * 1024) - throw new Error("delta stream exceeds budget"); - parser.write(chunk.value); - } - - if (!parser.isEnded) parser.end(); - } catch (error) { - void reader.cancel().catch(() => undefined); - throw error; - } finally { - reader.releaseLock(); - } - - if (range.oldest === null || range.latest === null) - throw new Error("empty delta log cannot prove continuity"); - - const latestOffset = offsets.get(range.latest); - - if (latestOffset === undefined) throw new Error("missing latest delta event offset"); - - if (cursor && cursor.event < range.oldest) - throw new Error( - "delta continuity lost; baseline reconciliation required", - ); - - if (cursor && splitEvents.has(cursor.event) && skippedLegacy) { - candidates.unshift(...legacyPrefix); - - if (candidates.length > limit) candidates.length = limit; - count += skippedLegacy; - } - - const cursorAt = ({ item, offset }: Pending): Cursor => { - const marker: Cursor = { event: item.event, offset }; - - if (splitEvents.has(marker.event)) marker.feedOrder = true; - - return marker; - }; - - const last = candidates.at(-1); - - return { - batch: candidates, caughtUp: count <= limit, cursorAt, - nextCursor: last ? cursorAt(last) : null, - latestCursor: { event: range.latest, offset: latestOffset }, - }; -} diff --git a/services/advisories/src/domain.ts b/services/advisories/src/domain.ts deleted file mode 100644 index 2f71e7606..000000000 --- a/services/advisories/src/domain.ts +++ /dev/null @@ -1,221 +0,0 @@ -export const LIMITS = { - cveRecord: 3 * 1024 * 1024, - batch: 4 * 1024 * 1024, - records: 8, - feed: 16 * 1024 * 1024, - deltaRecords: 4, - entries: 100_000, -}; -export const SOURCES = { - cve: "https://raw.githubusercontent.com/CVEProject/cvelistV5/main/cves/deltaLog.json", - arch: "https://security.archlinux.org/issues/all.json", - kev: "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json", -}; -export type Feed = keyof typeof SOURCES; -export function object(value: unknown): Record { - if (typeof value !== "object" || value === null || Array.isArray(value)) - throw new Error("expected object"); - return value as Record; -} -export function string(value: unknown): string { - if (typeof value !== "string") throw new Error("expected string"); - return value; -} -export function isGitHubInstallationToken(value: unknown): value is string { - // Keep space for the other fields in the private routes' 4 KiB bodies. - return typeof value === "string" && value.length >= 24 && value.length <= 2048 && - value.startsWith("ghs_") && !/[^A-Za-z0-9._-]/.test(value); -} -export function date(value: unknown): string { - const text = string(value); - const match = - /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d+)?(Z|[+-]\d\d:\d\d)?$/.exec( - text, - ); - if (!match) throw new Error("invalid date"); - const year = Number(match[1]), - month = Number(match[2]), - day = Number(match[3]); - if ( - month < 1 || - month > 12 || - day < 1 || - day > new Date(Date.UTC(year, month, 0)).getUTCDate() || - Number(match[4]) > 23 || - Number(match[5]) > 59 || - Number(match[6]) > 59 - ) - throw new Error("invalid date"); - const parsed = new Date(match[7] ? text : `${text}Z`); - if (!Number.isFinite(parsed.getTime())) throw new Error("invalid date"); - return parsed.toISOString(); -} -export function cveId(value: unknown): string { - const id = string(value); - if (!/^CVE-\d{4}-\d{4,19}$/.test(id)) throw new Error("invalid CVE id"); - return id; -} -export function cveUrl(id: string): string { - cveId(id); - const [, year, number] = id.split("-"); - if (!number || !year) throw new Error("invalid CVE id"); - return `https://raw.githubusercontent.com/CVEProject/cvelistV5/main/cves/${year}/${number.slice(0, -3)}xxx/${id}.json`; -} - -export function cveServicesUrl(id: string): string { - return `https://cveawg.mitre.org/api/cve/${cveId(id)}`; -} -export async function sha256(value: string | Uint8Array): Promise { - const bytes = - typeof value === "string" - ? new TextEncoder().encode(value) - : Uint8Array.from(value); - return Array.from( - new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), - (byte) => byte.toString(16).padStart(2, "0"), - ).join(""); -} -export async function boundedBody( - body: ReadableStream | null, - limit: number, -): Promise { - if (!body) throw new Error("missing body"); - const reader = body.getReader(); - const chunks: Uint8Array[] = []; - let length = 0; - try { - while (true) { - const part = await reader.read(); - if (part.done) break; - length += part.value.byteLength; - if (length > limit) { - void reader.cancel().catch(() => undefined); - throw new Error("body exceeds limit"); - } - chunks.push(part.value); - } - } finally { - reader.releaseLock(); - } - const result = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - result.set(chunk, offset); - offset += chunk.length; - } - return decodeUtf8(result); -} -export function decodeUtf8(bytes: Uint8Array): string { - const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); - if (text.startsWith("\uFEFF")) throw new Error("invalid UTF8 BOM"); - return text; -} -export function parseCve(raw: string, expectedId?: string) { - if (new TextEncoder().encode(raw).length > LIMITS.cveRecord) - throw new Error("record exceeds limit"); - const payload = object(JSON.parse(raw)); - const metadata = object(payload.cveMetadata); - const id = cveId(metadata.cveId); - if (expectedId && id !== expectedId) throw new Error("CVE id mismatch"); - if (payload.dataType !== "CVE_RECORD") throw new Error("invalid dataType"); - const schema = string(payload.dataVersion); - const state = string(metadata.state); - const modified = date(metadata.dateUpdated); - const published = - metadata.datePublished === undefined - ? null - : date(metadata.datePublished); - const containers = object(payload.containers); - object(containers.cna); - if (containers.adp !== undefined && !Array.isArray(containers.adp)) - throw new Error("invalid ADP"); - const supported = - ["5.0", "5.1", "5.1.1", "5.2", "5.2.0"].includes(schema) && - ["PUBLISHED", "REJECTED"].includes(state); - if (state === "PUBLISHED" && !published) - throw new Error("published record missing publication date"); - return { id, schema, state, modified, published, supported, payload }; -} -export function parseArch(raw: string): unknown[] { - const value: unknown = JSON.parse(raw); - if (!Array.isArray(value) || value.length > 50_000) - throw new Error("invalid Arch snapshot"); - for (const item of value) { - const issue = object(item); - if ( - !/^AVG-\d+$/.test(string(issue.name)) || - !Array.isArray(issue.packages) || - issue.packages.length === 0 || - !issue.packages.every( - (v) => typeof v === "string" && v.length > 0, - ) || - !Array.isArray(issue.issues) || - !issue.issues.every( - (v) => typeof v === "string" && /^CVE-\d{4}-\d{4,19}$/.test(v), - ) - ) - throw new Error("invalid Arch issue"); - for (const key of ["status", "severity", "type"]) string(issue[key]); - if ( - !["Fixed", "Not affected", "Unknown", "Vulnerable"].includes( - string(issue.status), - ) - ) - throw new Error("invalid Arch status"); - for (const key of ["affected", "fixed"]) - if (issue[key] !== null) string(issue[key]); - } - return value; -} -export function parseKev(raw: string) { - const value = object(JSON.parse(raw)); - const revision = string(value.catalogVersion); - date(value.dateReleased); - if ( - !Array.isArray(value.vulnerabilities) || - value.vulnerabilities.length > 50_000 || - value.count !== value.vulnerabilities.length - ) - throw new Error("invalid KEV catalog"); - const entries = value.vulnerabilities.map((v) => { - const entry = object(v); - cveId(entry.cveID); - return entry; - }); - return { revision, entries }; -} - -export type DeltaItem = { event: string; id: string; url: string; modified: string }; - -export function parseDelta(raw: string): DeltaItem[] { - const value: unknown = JSON.parse(raw); - if (!Array.isArray(value) || value.length > LIMITS.entries) - throw new Error("invalid delta log"); - const entries: DeltaItem[] = []; - for (const item of value) { - const event = object(item); - const time = date(event.fetchTime); - if (!Array.isArray(event.error) || event.error.length > 0) - throw new Error("upstream delta errors"); - if ( - !Array.isArray(event.new) || - !Array.isArray(event.updated) || - event.numberOfChanges !== event.new.length + event.updated.length - ) - throw new Error("delta count mismatch"); - for (const change of [...event.new, ...event.updated]) { - const record = object(change); - const id = cveId(record.cveId); - const url = cveUrl(id); - if (record.githubLink !== url) - throw new Error("untrusted delta URL"); - entries.push({ event: time, id, url, modified: date(record.dateUpdated) }); - - if (entries.length > LIMITS.entries) - throw new Error("too many delta records"); - } - } - return entries.sort( - (a, b) => a.event.localeCompare(b.event) || a.id.localeCompare(b.id), - ); -} diff --git a/services/advisories/src/epss.ts b/services/advisories/src/epss.ts deleted file mode 100644 index 8d358b607..000000000 --- a/services/advisories/src/epss.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { boundedBody, cveId, date, object, string } from "./domain"; -import { type Fetcher } from "./ingestion"; -import { type Store } from "./storage"; - -const DAY = 24 * 60 * 60_000; - -const EMPTY = JSON.stringify({ status: "OK", "status-code": 200, total: 0, offset: 0, data: [] }); - -type CacheRow = { checked_at: string; fetched_at: string | null; payload_json: string; error: number }; - -type Score = { epss: number; percentile: number; date: string }; - -type EpssRow = ReturnType; - -function probability(text: string): number { - if (!/^(?:0(?:\.\d{1,12})?|1(?:\.0{1,12})?)$/.test(text)) - throw new Error("invalid EPSS probability"); - - return Number(text); -} - -function score(row: EpssRow, now: string): Score { - const day = string(row.date); - - if (!/^\d{4}-\d\d-\d\d$/.test(day) || date(`${day}T00:00:00Z`).slice(0, 10) !== day || day > now.slice(0, 10)) - throw new Error("invalid EPSS score date"); - - return { epss: probability(string(row.epss)), percentile: probability(string(row.percentile)), date: day }; -} - -function parseEpss(raw: string, id: string, now: string) { - if (new TextEncoder().encode(raw).length > 64 * 1024) throw new Error("EPSS body exceeds limit"); - const body = object(JSON.parse(raw)); - - if (body.status !== "OK" || body["status-code"] !== 200 || body.offset !== 0 || - !Array.isArray(body.data) || ![0, 1].includes(Number(body.total)) || body.total !== body.data.length) - throw new Error("invalid or partial EPSS response"); - - if (body.data.length === 0) return { latest: null, history: [] }; - const row = object(body.data[0]); - - if (cveId(row.cve) !== id || !Array.isArray(row["time-series"]) || row["time-series"].length > 30) - throw new Error("invalid EPSS identity or history"); - const current = score(row, now); - const scores = [current, ...row["time-series"].map(value => score(object(value), now))]; - - if (new Set(scores.map((item) => item.date)).size !== scores.length || scores.some((item) => item.date > current.date)) - throw new Error("invalid EPSS history dates"); - const start = new Date(Date.parse(`${now.slice(0, 10)}T00:00:00Z`) - 29 * DAY).toISOString().slice(0, 10); - - return { latest: current, history: scores.filter((item) => item.date >= start).sort((a, b) => b.date.localeCompare(a.date)) }; -} - -function result(row: CacheRow | null, id: string, now: string, busy = false) { - const evidence = row ? parseEpss(row.payload_json, id, now) : null; - const latest = evidence?.latest; - const unavailable = busy || !row || !!row.error || (latest !== null && latest !== undefined && Date.parse(now) - Date.parse(`${latest.date}T00:00:00Z`) > 2 * DAY); - - return { - schema_version: 1, - as_of: now, - source: "FIRST EPSS", - source_url: `https://api.first.org/data/v1/epss?cve=${id}&scope=time-series`, - attribution: "EPSS by FIRST.org and the EPSS Special Interest Group", - cve: id, - checked_at: row?.checked_at ?? null, - fetched_at: row?.fetched_at ?? null, - status: unavailable ? "unavailable" : latest ? "scored" : "missing", - score: unavailable ? null : latest ?? null, - history: evidence?.history ?? [], - interpretation: "Probability of observed exploitation in the next 30 days; not proof of applicability, safety or current exploitation", - }; -} - -export async function epss(store: Store, id: string, now: string, fetcher: Fetcher) { - cveId(id); - date(now); - - if (!await store.sql.first("SELECT id FROM source_record WHERE id=?", [id])) - throw new Error("CVE unavailable"); - const read = () => store.sql.first("SELECT * FROM epss_cache WHERE cve_id=?", [id]); - - const fresh = (row: CacheRow | null) => row !== null && Date.parse(row.checked_at) <= Date.parse(now) && - Date.parse(now) - Date.parse(row.checked_at) < (row.error ? 60_000 : 6 * 60 * 60_000); - - let cached = await read(); - - if (fresh(cached)) return result(cached, id, now); - const owner = crypto.randomUUID(), lease = `epss:${id}`; - - if (!await store.lease(lease, owner, now)) return result(cached, id, now, true); - - try { - cached = await read(); - - if (fresh(cached)) return result(cached, id, now); - let raw = cached?.payload_json ?? EMPTY; - let error = 0; - - try { - const response = await fetcher(`https://api.first.org/data/v1/epss?cve=${id}&scope=time-series`, { - redirect: "manual", signal: AbortSignal.timeout(20_000), - headers: { "User-Agent": "omg-advisories/1.0", Accept: "application/json" }, - }); - - if (response.status !== 200) { - void response.body?.cancel().catch(() => undefined); - throw new Error("EPSS upstream unavailable"); - } - - const incoming = await boundedBody(response.body, 64 * 1024); - parseEpss(incoming, id, now); - raw = incoming; - } catch (failure) { - console.error("epss_refresh_failed", { cve: id, reason: failure instanceof Error ? failure.message : "unknown failure" }); - error = 1; - } - - const row: CacheRow = { checked_at: now, fetched_at: error ? cached?.fetched_at ?? null : now, payload_json: raw, error }; - await store.writer(lease, owner).sql.batch([{ - sql: "INSERT INTO epss_cache(cve_id,checked_at,fetched_at,payload_json,error) VALUES(?,?,?,?,?) ON CONFLICT(cve_id) DO UPDATE SET checked_at=excluded.checked_at,fetched_at=excluded.fetched_at,payload_json=excluded.payload_json,error=excluded.error", - values: [id, row.checked_at, row.fetched_at, row.payload_json, row.error], - }]); - - return result(row, id, now); - } finally { - await store.release(lease, owner); - } -} diff --git a/services/advisories/src/github-cooldown.ts b/services/advisories/src/github-cooldown.ts deleted file mode 100644 index 634e0bfe0..000000000 --- a/services/advisories/src/github-cooldown.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { boundedBody } from "./domain"; -import { type Fetcher } from "./ingestion"; -import { type RawStore } from "./storage"; - -const GITHUB = "https://api.github.com"; - -export class GitHubCooldownActive extends Error { - constructor() { - super("GitHub rate limit cooldown is active"); - } -} - -function headerNumber(headers: Headers, name: string) { - const value = headers.get(name); - - return value !== null && /^\d{1,12}$/.test(value) ? Number(value) : null; -} - -async function githubDelay(response: Response, now: number) { - const retry = headerNumber(response.headers, "retry-after"); - const remaining = headerNumber(response.headers, "x-ratelimit-remaining"); - const reset = headerNumber(response.headers, "x-ratelimit-reset"); - - if (retry === null && remaining !== 0 && response.status !== 429) { - const message = await boundedBody(response.body, 32 * 1024).catch(() => ""); - - if (!/rate[ -]limit/i.test(message)) return null; - } - - return Math.max(now + 60_000, now + (retry ?? 0) * 1000, remaining === 0 ? (reset ?? 0) * 1000 : 0); -} - -async function readUntil(raw: RawStore, key: string) { - const previous = await raw.get(key); - - return Number(await previous?.text() || 0); -} - -export async function githubAwareFetch( - fetcher: Fetcher, raw: RawStore, url: string, init: RequestInit, now: string, authenticated: boolean, -) { - if (new URL(url).origin !== GITHUB) return fetcher(url, init); - - const key = `runtime/github-cooldown-${authenticated ? "authenticated" : "public"}.txt`; - const timestamp = Date.parse(now); - - if (await readUntil(raw, key) > timestamp) throw new GitHubCooldownActive(); - - const response = await fetcher(url, init); - - if (response.status !== 403 && response.status !== 429) return response; - - const until = await githubDelay(response, timestamp); - - if (until !== null) { - await raw.put(key, String(Math.max(until, await readUntil(raw, key)))); - } - - return response; -} diff --git a/services/advisories/src/index.pg.ts b/services/advisories/src/index.pg.ts deleted file mode 100644 index 9317d23d2..000000000 --- a/services/advisories/src/index.pg.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { handle } from "./service"; -import { refreshScheduledAdvisories } from "./ingestion"; -import { Store, d1Sql, type Sql } from "./storage"; -import { pgSql } from "./pg"; -import { cachedRead } from "./cache"; -import { r2Raw } from "./raw-pack"; -import { scheduledPublisherFetcher } from "./publisher"; -import { NVD_RECONCILIATION_CRON, reconcileNvd } from "./nvd"; -import { RUNTIME_REFRESH_CRON, refreshScheduledRuntimes, type RuntimeRefreshEnvironment } from "./runtime-cron"; - -type Environment = Omit & RuntimeRefreshEnvironment & { - INGEST_TOKEN?: string; - RUNTIME_REFRESH_SECRET?: string; - PACKAGE_ASSESSMENT_TOKEN?: string; - HYPERDRIVE?: Hyperdrive; - HYPERDRIVE_REPLICA?: Hyperdrive; - DB_BACKEND?: string; -}; - -function normalizeAdvisoryRoute(pathname: string): string { - if (/^\/v1\/cves\/CVE-\d{4}-\d+$/i.test(pathname)) return "/v1/cves/:id"; - if (/^\/v1\/epss\/CVE-\d{4}-\d+$/i.test(pathname)) return "/v1/epss/:id"; - if (/^\/v1\/runtimes\/[a-z]+$/i.test(pathname)) return "/v1/runtimes/:name"; - if (/^\/v1\/eol\/[a-z0-9-]+$/i.test(pathname)) return "/v1/eol/:product"; - return pathname.slice(0, 64); -} - -function isReplicaSafeRead(request: Request): boolean { - const pathname = new URL(request.url).pathname; - if (request.method === "POST" && pathname === "/v1/packages/audit") return true; - if (request.method !== "GET") return false; - return ( - pathname === "/v1/status" || - pathname === "/v1/arch/advisories" || - pathname === "/v1/bundles/hot" || - pathname === "/v1/packages/check" || - pathname === "/v1/eol" || - /^\/v1\/eol\/[a-z0-9-]+$/.test(pathname) || - pathname === "/v1/cves/recent" || - pathname === "/v1/cves/dashboard" || - /^\/v1\/cves\/CVE-\d{4}-\d{4,19}$/.test(pathname) - ); -} - -function openSql( - env: Environment, - route: string, - preferReplica: boolean, -): { sql: Sql; close?: () => Promise } { - if (env.DB_BACKEND !== "d1") { - if (preferReplica && env.HYPERDRIVE_REPLICA) { - const pg = pgSql(env.HYPERDRIVE_REPLICA.connectionString, { - application: "omg-advisories", - route, - target: "replica", - }); - return { sql: pg, close: () => pg.close() }; - } - if (env.HYPERDRIVE) { - const pg = pgSql(env.HYPERDRIVE.connectionString, { - application: "omg-advisories", - route, - target: "primary", - }); - return { sql: pg, close: () => pg.close() }; - } - } - return { sql: d1Sql(env.DB) }; -} - -export default { - fetch(request, env, context) { - return cachedRead( - request, - caches.default, - async (input) => { - const route = normalizeAdvisoryRoute(new URL(input.url).pathname); - const { sql, close } = openSql(env, route, isReplicaSafeRead(input)); - try { - return await handle( - input, - new Store(sql, r2Raw(env.RAW)), - env.INGEST_TOKEN, - new Date().toISOString(), - undefined, - env.RUNTIME_REFRESH_SECRET, - env.PACKAGE_ASSESSMENT_TOKEN, - ); - } finally { - if (close) context.waitUntil(close()); - } - }, - Date.now(), - (promise) => context.waitUntil(promise), - ); - }, - scheduled(event, env, context) { - context.waitUntil( - (async () => { - const runtimeRefresh = event.cron === RUNTIME_REFRESH_CRON; - const nvd = event.cron === NVD_RECONCILIATION_CRON; - const route = nvd ? "cron:nvd" : runtimeRefresh ? "cron:runtime-refresh" : "cron:refresh"; - - const { sql, close } = openSql(env, route, false); - - try { - const store = new Store(sql, r2Raw(env.RAW)); - - if (nvd) { - await reconcileNvd(store, fetch, event.scheduledTime); - - return; - } - - if (runtimeRefresh) { - await refreshScheduledRuntimes(env, store, event.scheduledTime); - - return; - } - - await refreshScheduledAdvisories( - store, - scheduledPublisherFetcher(fetch), - event.scheduledTime, - Number(env.CVE_BATCH_SIZE), - ); - } finally { - if (close) await close(); - } - })(), - ); - }, -} satisfies ExportedHandler; diff --git a/services/advisories/src/index.ts b/services/advisories/src/index.ts deleted file mode 100644 index 0dd263d56..000000000 --- a/services/advisories/src/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { handle } from "./service"; -import { refreshScheduledAdvisories } from "./ingestion"; -import { Store, d1Sql } from "./storage"; -import { cachedRead } from "./cache"; -import { r2Raw } from "./raw-pack"; -import { scheduledPublisherFetcher } from "./publisher"; -import { NVD_RECONCILIATION_CRON, reconcileNvd } from "./nvd"; -import { RUNTIME_REFRESH_CRON, refreshScheduledRuntimes, type RuntimeRefreshEnvironment } from "./runtime-cron"; - -type Environment = Env & RuntimeRefreshEnvironment & { - INGEST_TOKEN?: string; RUNTIME_REFRESH_SECRET?: string; PACKAGE_ASSESSMENT_TOKEN?: string; -}; - -export default { - fetch(request, env) { - return cachedRead( - request, caches.default, - (input) => handle(input, new Store(d1Sql(env.DB), r2Raw(env.RAW)), env.INGEST_TOKEN, - new Date().toISOString(), undefined, env.RUNTIME_REFRESH_SECRET, env.PACKAGE_ASSESSMENT_TOKEN), - ); - }, - scheduled(event, env, context) { - const store = new Store(d1Sql(env.DB), r2Raw(env.RAW)); - - if (event.cron === NVD_RECONCILIATION_CRON) { - context.waitUntil(reconcileNvd(store, fetch, event.scheduledTime)); - - return; - } - - if (event.cron === RUNTIME_REFRESH_CRON) { - context.waitUntil(refreshScheduledRuntimes(env, store, event.scheduledTime)); - - return; - } - - context.waitUntil( - refreshScheduledAdvisories( - store, - scheduledPublisherFetcher(fetch), - event.scheduledTime, - Number(env.CVE_BATCH_SIZE), - ), - ); - }, -} satisfies ExportedHandler; diff --git a/services/advisories/src/ingestion.ts b/services/advisories/src/ingestion.ts deleted file mode 100644 index c2e5d3209..000000000 --- a/services/advisories/src/ingestion.ts +++ /dev/null @@ -1,409 +0,0 @@ -import { - LIMITS, - SOURCES, - boundedBody, - cveServicesUrl, - parseArch, - parseCve, - parseKev, - sha256, - string, - type Feed, -} from "./domain"; -import { Store, type Command } from "./storage"; -import { deltaBatch, readDeltaCursor } from "./delta"; -import { kevMirror, recentCveHints } from "./publisher"; - -const CVE_CHECKPOINT_INTERVAL = 128; - -export type Fetcher = (url: string, init?: RequestInit) => Promise; - -export async function ingestCveGroups( - records: readonly T[], - ingest: (record: T) => Promise, -) { - const byId = new Map(); - - for (const record of records) { - const group = byId.get(record.id); - - if (group) group.push(record); - else byId.set(record.id, [record]); - } - - const groups = [...byId.values()]; - - for (let start = 0; start < groups.length; start += 4) { - const outcomes = await Promise.allSettled( - groups.slice(start, start + 4).map(async (group) => { - for (const record of group) await ingest(record); - }), - ); - - const failed = outcomes.find((outcome) => outcome.status === "rejected"); - - if (failed) throw failed.reason; - } -} - -export async function upstream( - url: string, - etag: string | null, - fetcher: Fetcher, -): Promise { - const response = await fetcher(url, { - headers: etag ? { "If-None-Match": etag } : {}, - redirect: "manual", - signal: AbortSignal.timeout(20_000), - }); - - if (response.status !== 304 && !response.ok) { - void response.body?.cancel().catch(() => undefined); - throw new Error(`upstream HTTP ${response.status}`); - } - - return response; -} - -export async function refreshSnapshot( - store: Store, - source: "arch" | "kev", - fetcher: Fetcher, - now: string, -) { - const checkpoint = await store.checkpoint(source); - - if (!checkpoint) throw new Error("missing migration"); - - const primary = await upstream(SOURCES[source], checkpoint.etag, fetcher).catch(error => { - if (source !== "kev") throw error; - - return null; - }); - - const response = primary ?? await upstream(kevMirror, null, fetcher); - - if (response.status === 304) { - if (!primary || !checkpoint.object_key) - throw new Error("304 without stored snapshot"); - await store.sql.batch([ - { - sql: "UPDATE source_checkpoint SET checked_at=?,complete=1,error=NULL WHERE source=?", - values: [now, source], - }, - ]); - - return; - } - - const raw = await boundedBody(response.body, LIMITS.feed); - const revision = source === "arch" ? now : parseKev(raw).revision; - - if (source === "arch") parseArch(raw); - - if ( - source === "kev" && - checkpoint.revision && - revision < checkpoint.revision - ) - throw new Error("KEV revision rollback"); - const hash = await sha256(raw); - const key = `${source}/${hash}.json`; - - if (checkpoint.payload_sha256 !== hash) await store.raw.put(key, raw); - const annotations: Command[] = []; - - if (source === "kev" && checkpoint.payload_sha256 !== hash) { - const entries = JSON.stringify(parseKev(raw).entries); - - if (new TextEncoder().encode(entries).byteLength > 1_900_000) - throw new Error("KEV annotations exceed D1 string budget"); - annotations.push( - { sql: "DELETE FROM kev_annotation", values: [] }, - { - sql: "INSERT INTO kev_annotation(cve_id,payload_json,catalog_sha256) SELECT json_extract(value,'$.cveID'),value,? FROM json_each(?)", - values: [hash, entries], - }, - ); - } - - await store.sql.batch([ - ...annotations, - { - sql: "UPDATE source_checkpoint SET checked_at=?,fetched_at=?,etag=?,complete=1,bootstrap_complete=1,error=NULL,object_key=?,payload_sha256=?,revision=? WHERE source=?", - values: [ - now, - now, - primary?.headers.get("etag") ?? null, - key, - hash, - revision, - source, - ], - }, - ]); -} - -export async function refreshCves( - store: Store, - fetcher: Fetcher, - now: string, - batchSize = LIMITS.deltaRecords, -) { - const checkpoint = await store.checkpoint("cve"); - - if (!checkpoint) throw new Error("missing migration"); - - const validator = checkpoint.complete && checkpoint.revision ? checkpoint.etag : null; - - const response = await upstream(SOURCES.cve, validator, fetcher); - - if (response.status === 304) { - if (!validator) throw new Error("unexpected CVE delta revalidation"); - - await store.sql.batch([ - { - sql: "UPDATE source_checkpoint SET checked_at=?,error=NULL WHERE source=?", - values: [now, "cve"], - }, - ]); - - return; - } - - const cursor = checkpoint.cursor ? readDeltaCursor(checkpoint.cursor) : null; - - const { batch, caughtUp, cursorAt, latestCursor } = await deltaBatch( - response.body, - cursor, - batchSize, - ); - - if (checkpoint.revision) { - const completed = readDeltaCursor(checkpoint.revision); - - if (latestCursor.event < completed.event || - (latestCursor.event === completed.event && latestCursor.offset < completed.offset)) - throw new Error("CVE delta publisher watermark moved backwards"); - } - - const pages = Math.max(1, Math.ceil(batch.length / CVE_CHECKPOINT_INTERVAL)); - - for (let page = 0; page < pages; page++) { - const start = page * CVE_CHECKPOINT_INTERVAL; - const records = batch.slice(start, start + CVE_CHECKPOINT_INTERVAL); - await ingestCveGroups(records.map(({ item }) => item), async (item) => { - let raw: string; - let sourceUrl: string | undefined; - - try { - const record = await upstream(item.url, null, fetcher); - raw = await boundedBody(record.body, LIMITS.cveRecord); - } catch (originalError) { - sourceUrl = cveServicesUrl(item.id); - - try { - const direct = await upstream(sourceUrl, null, fetcher); - raw = await boundedBody(direct.body, LIMITS.cveRecord); - } catch { - throw originalError; - } - - const received = parseCve(raw, item.id); - - if (!received.supported || received.modified < item.modified || received.modified > now) { - throw new Error("CVE Services did not return the required published revision"); - } - } - - await store.cve(raw, now, item.id, sourceUrl); - }); - const last = records.at(-1); - const finished = caughtUp && page === pages - 1; - - await store.sql.batch([ - { - sql: "UPDATE source_checkpoint SET cursor=?,checked_at=?,fetched_at=?,etag=?,complete=?,revision=?,error=NULL WHERE source=?", - values: [ - last ? JSON.stringify(cursorAt(last)) : checkpoint.cursor, - now, - now, - finished ? response.headers.get("etag") : null, - Number(finished), - finished ? JSON.stringify(latestCursor) : checkpoint.revision, - "cve", - ], - }, - ]); - } -} - -export async function refreshSource( - store: Store, - source: Feed, - fetcher: Fetcher, - now: string, - batchSize = LIMITS.deltaRecords, -): Promise { - const owner = crypto.randomUUID(); - - if (!(await store.lease(source, owner, now))) return false; - const writer = store.writer(source, owner); - await writer.sql.batch([ - { - sql: "INSERT INTO ingestion_run(id,source,started_at) VALUES(?,?,?)", - values: [owner, source, now], - }, - ]); - - try { - if (source === "cve") - await refreshCves(writer, fetcher, now, batchSize); - else await refreshSnapshot(writer, source, fetcher, now); - await writer.sql.batch([ - { - sql: "UPDATE ingestion_run SET finished_at=? WHERE id=?", - values: [now, owner], - }, - ]); - } catch (error) { - const message = - error instanceof Error - ? error.message.slice(0, 200) - : "ingestion failed"; - - await writer.sql.batch([ - { - sql: "UPDATE source_checkpoint SET error=?,complete=0 WHERE source=?", - values: [message, source], - }, - { - sql: "UPDATE ingestion_run SET finished_at=?,error=? WHERE id=?", - values: [now, message, owner], - }, - ]); - console.error( - JSON.stringify({ - event: "ingestion_failed", - source, - error: message, - }), - ); - } finally { - await store.release(source, owner); - } - - return true; -} - -export async function refresh( - store: Store, - fetcher: Fetcher, - now = new Date().toISOString(), - batchSize = LIMITS.deltaRecords, -) { - for (const source of ["cve", "arch", "kev"] satisfies Feed[]) { - await refreshSource(store, source, fetcher, now, batchSize); - } - - await store.sql.batch([ - { - sql: "DELETE FROM ingestion_run WHERE started_at < ?", - values: [ - new Date(Date.parse(now) - 7 * 24 * 60 * 60_000).toISOString(), - ], - }, - ]); -} - -export async function refreshScheduledAdvisories( - store: Store, - fetcher: Fetcher, - scheduledTime: number, - batchSize: number, -) { - const scheduled = new Date(scheduledTime); - const now = new Date().toISOString(); - - if (scheduled.getUTCMinutes() % 5 === 0) { - await refresh(store, fetcher, now, batchSize); - await reconcilePublishedCves(store, fetcher, new Date().toISOString()); - } else { - await refreshSource(store, "cve", fetcher, now, batchSize); - } -} - -export async function reconcilePublishedCves(store: Store, fetcher: Fetcher, now: string) { - const hints = await recentCveHints(fetcher, now).catch(() => { - console.warn(JSON.stringify({ event: "cve_secondary_discovery_unavailable" })); - - return []; - }); - - if (hints.length === 0) return; - const owner = crypto.randomUUID(); - - if (!(await store.lease("cve", owner, now))) return; - const writer = store.writer("cve", owner); - - try { - const known = await writer.sql.all<{ id: string; modified_at: string }>( - `SELECT id,modified_at FROM source_record WHERE id IN (${hints.map(() => "?").join(",")})`, - hints.map(hint => hint.id), - ); - - const byId = new Map(known.map(row => [row.id, row.modified_at])); - const pending = hints.filter(hint => (byId.get(hint.id) ?? "") < hint.modified).slice(0, 12); - let recovered = 0; - let unavailable = 0; - await ingestCveGroups(pending, async hint => { - const url = cveServicesUrl(hint.id); - let raw: string; - - try { - const response = await fetcher(url, { redirect: "manual", signal: AbortSignal.timeout(5_000) }); - - if (!response.ok) { - void response.body?.cancel().catch(() => undefined); - unavailable++; - - return; - } - - raw = await boundedBody(response.body, LIMITS.cveRecord); - const canonical = parseCve(raw, hint.id); - - if (!canonical.supported || canonical.modified < hint.modified || canonical.modified > now) { - unavailable++; - - return; - } - } catch { - unavailable++; - - return; - } - - await writer.cve(raw, now, hint.id, url); - recovered++; - }); - - if (pending.length) console.info(JSON.stringify({ event: "cve_secondary_reconciliation", recovered, unavailable })); - } finally { - await store.release("cve", owner); - } -} - -type IngestEnvelope = ReturnType; - -export function parseBatch(batch: IngestEnvelope, maximum = LIMITS.records): string[] { - if ( - batch.source !== "cve" || - !Array.isArray(batch.records) || - batch.records.length === 0 || - batch.records.length > maximum - ) - throw new Error("invalid ingest batch"); - - return batch.records.map((item) => string(item)); -} diff --git a/services/advisories/src/nvd.ts b/services/advisories/src/nvd.ts deleted file mode 100644 index 3853e514c..000000000 --- a/services/advisories/src/nvd.ts +++ /dev/null @@ -1,237 +0,0 @@ -import { LIMITS, boundedBody, cveId, cveServicesUrl, date, object, parseCve } from "./domain"; -import { ingestCveGroups, type Fetcher } from "./ingestion"; -import { type Store } from "./storage"; - -export const NVD_RECONCILIATION_CRON = "3-58/5 * * * *"; - -const ENDPOINT = "https://services.nvd.nist.gov/rest/json/cves/2.0"; - -const STATE_KEY = "reconciliation/nvd-v1.json"; - -const LEASE = "reconciliation:nvd"; - -const PAGE_SIZE = 100; - -const VERIFY_LIMIT = 12; - -const HOUR = 60 * 60_000; - -const INTERVAL = 2 * HOUR; - -interface NvdCheckpoint { - window_start: string; - window_end: string; - checked_at: string; - next_index: number; - last_completed_at: string | null; - verified_through: string | null; - complete: boolean; - error: "upstream_unavailable" | "verification_pending" | null; -} - -function nonnegativeInteger(row: ReturnType, key: string) { - const value = row[key]; - - if (!Number.isSafeInteger(value) || Number(value) < 0) throw new Error("invalid NVD pagination"); - - return Number(value); -} - -async function readCheckpoint(store: Store): Promise { - const state = await store.raw.get(STATE_KEY); - - if (!state) return null; - const row = object(JSON.parse(await state.text())); - const error = row.error; - - if ((row.complete !== true && row.complete !== false) || - (error !== null && error !== "upstream_unavailable" && error !== "verification_pending")) { - throw new Error("invalid NVD checkpoint"); - } - - return { - window_start: date(row.window_start), - window_end: date(row.window_end), - checked_at: date(row.checked_at), - next_index: nonnegativeInteger(row, "next_index"), - last_completed_at: row.last_completed_at === null ? null : date(row.last_completed_at), - verified_through: row.verified_through === null ? null : date(row.verified_through), - complete: row.complete, - error, - }; -} - -export async function nvdReconciliationStatus(store: Store, now: string) { - const checkpoint = await readCheckpoint(store); - - return { - schema_version: 1, - source: ENDPOINT, - checkpoint, - fresh: !!checkpoint?.verified_through && checkpoint.verified_through <= now && - Date.parse(now) - Date.parse(checkpoint.verified_through) <= INTERVAL + HOUR, - }; -} - -async function page(checkpoint: NvdCheckpoint, fetcher: Fetcher) { - const params = new URLSearchParams({ - pubStartDate: checkpoint.window_start, - pubEndDate: checkpoint.window_end, - startIndex: String(checkpoint.next_index), - resultsPerPage: String(PAGE_SIZE), - }); - - params.set("noRejected", ""); - - const response = await fetcher(`${ENDPOINT}?${params}`, { - headers: { Accept: "application/json" }, - redirect: "manual", - signal: AbortSignal.timeout(12_000), - }); - - if (response.status !== 200) { - await response.body?.cancel(); - throw new Error(`NVD HTTP ${response.status}`); - } - - const result = object(JSON.parse(await boundedBody(response.body, LIMITS.feed))); - const start = nonnegativeInteger(result, "startIndex"); - const count = nonnegativeInteger(result, "resultsPerPage"); - const total = nonnegativeInteger(result, "totalResults"); - - if (start !== checkpoint.next_index || count > PAGE_SIZE || !Array.isArray(result.vulnerabilities) || - result.vulnerabilities.length !== count || count !== Math.min(PAGE_SIZE, Math.max(0, total - start))) { - throw new Error("inconsistent NVD page"); - } - - const ids = new Set(); - - for (const row of result.vulnerabilities) { - const cve = object(object(row).cve); - const id = cveId(cve.id); - const published = date(cve.published); - - if (ids.has(id) || published < checkpoint.window_start || published > checkpoint.window_end) { - throw new Error("invalid NVD publication entry"); - } - - ids.add(id); - } - - return { ids: [...ids], nextIndex: start + count, complete: start + count >= total }; -} - -async function missingRecords(store: Store, ids: string[]) { - if (!ids.length) return []; - - const known = await store.sql.all<{ id: string }>( - `SELECT id FROM source_record WHERE supported=1 AND id IN (${ids.map(() => "?").join(",")})`, - ids, - ); - - const present = new Set(known.map(row => row.id)); - - return ids.filter(id => !present.has(id)); -} - -async function verifiedRecords(ids: string[], fetcher: Fetcher, now: string) { - const verified: { id: string; raw: string }[] = []; - - await ingestCveGroups(ids.slice(0, VERIFY_LIMIT).map(id => ({ id })), async ({ id }) => { - try { - const response = await fetcher(cveServicesUrl(id), { redirect: "manual", signal: AbortSignal.timeout(5_000) }); - - if (!response.ok) { - await response.body?.cancel(); - - return; - } - - const raw = await boundedBody(response.body, LIMITS.cveRecord); - const record = parseCve(raw, id); - - if (record.supported && record.modified <= now) verified.push({ id, raw }); - } catch { - // NVD identifies missing IDs. Only a verified CVE Program record can fill a gap. - return; - } - }); - - return verified; -} - -async function recoverMissing(store: Store, ids: string[], fetcher: Fetcher, now: string) { - const missing = await missingRecords(store, ids); - - if (missing.length === 0) return true; - - const records = await verifiedRecords(missing, fetcher, now); - - if (records.length === 0) return false; - - const owner = crypto.randomUUID(); - - if (!(await store.lease("cve", owner, now))) return false; - - try { - const stillMissing = new Set(await missingRecords(store, records.map(record => record.id))); - const writer = store.writer("cve", owner); - - for (const { id, raw } of records) { - if (stillMissing.has(id)) await writer.cve(raw, now, id, cveServicesUrl(id)); - } - } finally { - await store.release("cve", owner); - } - - return (await missingRecords(store, missing)).length === 0; -} - -export async function reconcileNvd(store: Store, fetcher: Fetcher, scheduledTime: number, now = new Date().toISOString()) { - const owner = crypto.randomUUID(); - - if (!(await store.lease(LEASE, owner, now))) return; - - try { - const previous = await readCheckpoint(store); - const scheduled = new Date(scheduledTime).toISOString(); - - if (previous && (scheduled <= previous.checked_at || - (previous.complete && scheduledTime < Date.parse(previous.window_end) + INTERVAL))) return; - - const checkpoint: NvdCheckpoint = previous && !previous.complete ? previous : { - window_start: new Date(previous ? Date.parse(previous.window_end) - HOUR : scheduledTime - 4 * HOUR).toISOString(), - window_end: new Date(Math.min(scheduledTime, previous ? Date.parse(previous.window_end) + 3 * HOUR : scheduledTime)).toISOString(), - checked_at: scheduled, - next_index: 0, - last_completed_at: previous?.last_completed_at ?? null, - verified_through: previous?.verified_through ?? null, - complete: false, - error: null, - }; - - checkpoint.checked_at = scheduled; - checkpoint.error = null; - - const result = await page(checkpoint, fetcher).catch(() => null); - - if (!result) { - checkpoint.error = "upstream_unavailable"; - } else if (!(await recoverMissing(store, result.ids, fetcher, now))) { - checkpoint.error = "verification_pending"; - } else { - checkpoint.next_index = result.nextIndex; - checkpoint.complete = result.complete; - - if (result.complete) { - checkpoint.last_completed_at = now; - checkpoint.verified_through = checkpoint.window_end; - } - } - - await store.raw.put(STATE_KEY, JSON.stringify(checkpoint)); - console.info(JSON.stringify({ event: "nvd_reconciliation", ...checkpoint })); - } finally { - await store.release(LEASE, owner); - } -} diff --git a/services/advisories/src/package-advisories.ts b/services/advisories/src/package-advisories.ts deleted file mode 100644 index 501d4c108..000000000 --- a/services/advisories/src/package-advisories.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { Sql } from "./storage"; - -type PackageName = { ecosystem: string; name: string }; - -type PackageAdvisory = { - id: string; - ecosystem: string; - package_name: string; - is_malware: boolean; - summary: string | null; - severity: string | null; - aliases: string[]; - fixed_versions: string[]; - modified_at: string | null; - epss: number | null; - epss_percentile: number | null; - in_kev: boolean; - in_euvd: boolean; -}; - -export function packageAdvisories(sql: Sql, packages: readonly PackageName[], limit: number) { - const placeholders = packages.map(() => "(?,?)").join(","); - const values = packages.flatMap(({ ecosystem, name }) => [ecosystem, name]); - - return sql.all( - `SELECT a.id, a.ecosystem, a.package_name, a.is_malware, a.summary, a.severity, - a.aliases, a.fixed_versions, a.modified_at, - ep.epss, ep.percentile AS epss_percentile, - EXISTS (SELECT 1 FROM kev_annotation k WHERE k.cve_id = ANY(array_prepend(a.id, a.aliases))) AS in_kev, - EXISTS (SELECT 1 FROM euvd_exploited ev WHERE ev.cve_id = ANY(array_prepend(a.id, a.aliases))) AS in_euvd - FROM osv_package_advisory a - LEFT JOIN LATERAL ( - SELECT e.epss, e.percentile - FROM epss_scores e - WHERE e.cve_id = ANY(array_prepend(a.id, a.aliases)) - ORDER BY e.epss DESC, e.percentile DESC, e.cve_id - LIMIT 1 - ) ep ON true - WHERE (lower(a.ecosystem), lower(a.package_name)) IN (${placeholders}) - ORDER BY a.is_malware DESC, in_kev DESC, COALESCE(ep.epss, 0) DESC, a.modified_at DESC, - a.id, a.ecosystem, a.package_name - LIMIT ?`, - [...values, limit], - ); -} diff --git a/services/advisories/src/package-assessment.ts b/services/advisories/src/package-assessment.ts deleted file mode 100644 index 77a6232ce..000000000 --- a/services/advisories/src/package-assessment.ts +++ /dev/null @@ -1,382 +0,0 @@ -import { compare as comparePep440, valid as validPep440 } from "@renovatebot/pep440"; -import { compare as compareSemver, valid as validSemver } from "semver"; -import { boundedBody, date, object, sha256, string } from "./domain"; -import { type Fetcher } from "./ingestion"; - -export const PACKAGE_ASSESSMENT_PATH = "/v2/packages/assess"; - -const OSV = "https://api.osv.dev/v1/query"; - -const MAX_PACKAGES = 8; - -const MAX_PAGES = 4; - -const MAX_RECORDS = 128; - -const MAX_PAGE_BYTES = 512 * 1024; - -const MAX_VERSION = 128; - -const MAX_NAME = 214; - -const JSON_HEADERS = { "Content-Type": "application/json", Accept: "application/json" }; - -type Coordinate = { ecosystem: "npm" | "PyPI"; name: string; version: string }; - -type JsonObject = ReturnType; - -type Gap = "source_unavailable" | "source_rate_limited" | "source_deadline" | "source_invalid_response" | - "source_budget_exceeded" | "unresolved_advisory_evidence"; - -type RangeEvent = { kind: "introduced" | "fixed" | "last_affected" | "limit"; version: string }; - -type Interval = { introduced: string; end: RangeEvent | null }; - -type Evidence = { kind: "listed_version"; version: string } | ({ kind: "range"; type: string } & Interval); - -type Finding = { - id: string; - modified: string; - kind: "vulnerability" | "malware"; - aliases: string[]; - url: string; - fixed_versions: string[]; - evidence: Evidence[]; -}; - -type State = { findings: Finding[]; unresolved: Set; gaps: Set; hashes: string[] }; - -function list(row: JsonObject, field: string, limit: number): JsonObject[string][] { - const values = row[field]; - - if (values === undefined) return []; - - if (!Array.isArray(values)) throw new Error("invalid advisory array"); - - if (values.length > limit) throw new Error("advisory array exceeds limit"); - - return values; -} - -function nameKey(ecosystem: Coordinate["ecosystem"], name: string) { - return ecosystem === "PyPI" ? name.toLowerCase().replace(/[-_.]+/g, "-") : name; -} - -function validVersion(ecosystem: Coordinate["ecosystem"], version: string) { - if (!version || version.length > MAX_VERSION || version.trim() !== version) return false; - - if (ecosystem === "PyPI") { - // The comparator stores numeric components as JavaScript numbers. - const imprecise = version.match(/\d+/g)?.some(part => !Number.isSafeInteger(Number(part))); - - return !imprecise && validPep440(version) !== null; - } - - return /^\d/.test(version) && validSemver(version) !== null; -} - -function readCoordinate(row: JsonObject): Coordinate { - const ecosystem = row.ecosystem; - const name = string(row.name); - const version = string(row.version); - - if ((ecosystem !== "npm" && ecosystem !== "PyPI") || Object.keys(row).length !== 3) - throw new Error("invalid package ecosystem or fields"); - - const namePattern = ecosystem === "npm" - ? /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/ - : /^[A-Za-z0-9](?:[-_.A-Za-z0-9]*[A-Za-z0-9])?$/; - - if (name.length > MAX_NAME || name.trim() !== name || !namePattern.test(name) || !validVersion(ecosystem, version)) - throw new Error("invalid package coordinate"); - - return { ecosystem, name: nameKey(ecosystem, name), version }; -} - -function readEvent(row: JsonObject, ecosystem: Coordinate["ecosystem"]): RangeEvent { - const [kind] = Object.keys(row); - - if (Object.keys(row).length !== 1 || - (kind !== "introduced" && kind !== "fixed" && kind !== "last_affected" && kind !== "limit")) - throw new Error("invalid OSV range event"); - const version = string(row[kind]); - - if (!(kind === "introduced" && version === "0") && !(kind === "limit" && version === "*") && - !validVersion(ecosystem, version)) throw new Error("invalid OSV version"); - - return { kind, version }; -} - -function rangeEvidence(range: JsonObject, coordinate: Coordinate): Evidence[] { - const type = string(range.type); - - if (type !== "SEMVER" && type !== "ECOSYSTEM") throw new Error("unsupported OSV range"); - const ecosystem = type === "SEMVER" ? "npm" : coordinate.ecosystem; - const compare = ecosystem === "npm" ? compareSemver : comparePep440; - - if (!validVersion(ecosystem, coordinate.version)) throw new Error("incompatible OSV range type"); - const events = list(range, "events", 128).map(value => readEvent(object(value), ecosystem)); - const timeline = events.filter(event => event.kind !== "limit"); - let limit: RangeEvent | null = null; - - // OSV accepts versions below any limit. For a linear ordering, keep the widest one. - for (const event of events) { - if (event.kind !== "limit") continue; - - if (event.version === "*") { - limit = null; - break; - } - - if (limit === null || compare(event.version, limit.version) > 0) limit = event; - } - - const before = (a: RangeEvent, b: RangeEvent) => { - const aFirst = a.kind === "introduced" && a.version === "0"; - const bFirst = b.kind === "introduced" && b.version === "0"; - - if (aFirst && bFirst) return 0; - - if (aFirst || bFirst) return aFirst ? -1 : 1; - - return compare(a.version, b.version); - }; - - timeline.sort(before); - - if (timeline[0]?.kind !== "introduced" || - (timeline.some(event => event.kind === "fixed") && timeline.some(event => event.kind === "last_affected"))) - throw new Error("invalid OSV event sequence"); - const matches: Evidence[] = []; - - for (let index = 0; index < timeline.length; index += 2) { - const start = timeline[index]; - const end = timeline[index + 1] ?? null; - - if (start?.kind !== "introduced" || end?.kind === "introduced") throw new Error("invalid OSV event sequence"); - let upper = end; - - if (limit !== null) { - const order = end ? compare(limit.version, end.version) : -1; - - if (order < 0 || (order === 0 && end?.kind === "last_affected")) upper = limit; - } - - if (start.version !== "0" && compare(coordinate.version, start.version) < 0) continue; - - if (upper !== null) { - const relation = compare(coordinate.version, upper.version); - - if (relation > 0 || (relation === 0 && upper.kind !== "last_affected")) continue; - } - - matches.push({ kind: "range", type, introduced: start.version, end: upper }); - } - - return matches; -} - -function advisoryId(value: string) { - if (value.trim() !== value || !/^[A-Za-z0-9][A-Za-z0-9:_.-]{0,127}$/.test(value)) - throw new Error("invalid advisory id"); - - return value; -} - -function inspectAdvisory(row: JsonObject, id: string, coordinate: Coordinate, now: string, state: State) { - if (row.withdrawn !== undefined && date(row.withdrawn) <= now) return; - const modified = date(row.modified); - - if (row.schema_version !== undefined && !/^1\.\d+\.\d+$/.test(string(row.schema_version))) - throw new Error("unsupported OSV schema"); - const evidence: Evidence[] = []; - let identified = false; - - for (const value of list(row, "affected", 128)) { - const affected = object(value); - - // OSV also permits Git-only entries without package coordinates. - if (affected.package === undefined) continue; - const identity = object(affected.package); - const name = string(identity.name); - - if (identity.ecosystem !== coordinate.ecosystem || - (name !== "*" && nameKey(coordinate.ecosystem, name) !== coordinate.name)) continue; - identified = true; - - if (affected.ecosystem_specific !== undefined && Object.keys(object(affected.ecosystem_specific)).length) { - state.unresolved.add(id); - continue; - } - - const versions = list(affected, "versions", 4096); - const ranges = list(affected, "ranges", 32); - - if (!versions.length && !ranges.length) state.unresolved.add(id); - - for (const value of versions) { - const version = string(value); - - if (!validVersion(coordinate.ecosystem, version)) { - state.unresolved.add(id); - continue; - } - - const sameVersion = coordinate.ecosystem === "npm" ? coordinate.version === version : - comparePep440(coordinate.version, version) === 0; - - if (sameVersion) { - evidence.push({ kind: "listed_version", version }); - break; - } - } - - for (const range of ranges) { - try { - evidence.push(...rangeEvidence(object(range), coordinate)); - } catch { - state.unresolved.add(id); - } - } - } - - if (!identified) state.unresolved.add(id); - - if (!evidence.length) return; - - if (evidence.length > 32) state.unresolved.add(id); - const fixed = new Set(); - - for (const item of evidence) { - if (item.kind === "range" && item.end?.kind === "fixed") fixed.add(item.end.version); - } - - state.findings.push({ - id, modified, kind: id.startsWith("MAL-") ? "malware" : "vulnerability", - aliases: list(row, "aliases", 64).map(value => advisoryId(string(value))), - url: `https://osv.dev/vulnerability/${encodeURIComponent(id)}`, - fixed_versions: [...fixed].slice(0, 32), - evidence: evidence.slice(0, 32), - }); -} - -async function assessCoordinate(coordinate: Coordinate, fetcher: Fetcher, now: string, signal: AbortSignal) { - const state: State = { findings: [], unresolved: new Set(), gaps: new Set(), hashes: [] }; - const tokens = new Set(); - const seen = new Set(); - let pageToken = ""; - - for (let page = 0; page < MAX_PAGES; page++) { - try { - const { ecosystem, name, version } = coordinate; - - const body = pageToken ? { package: { ecosystem, name }, version, page_token: pageToken } - : { package: { ecosystem, name }, version }; - - const response = await fetcher(OSV, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body), - redirect: "manual", signal }).catch(() => null); - - if (!response) { - state.gaps.add(signal.aborted ? "source_deadline" : "source_unavailable"); - break; - } - - if (!response.ok) { - void response.body?.cancel().catch(() => undefined); - state.gaps.add(response.status === 429 ? "source_rate_limited" : "source_unavailable"); - break; - } - - const raw = await boundedBody(response.body, MAX_PAGE_BYTES); - const data = object(JSON.parse(raw)); - - if (Object.keys(data).some(key => key !== "vulns" && key !== "next_page_token") || - (Object.hasOwn(data, "vulns") && !Array.isArray(data.vulns))) throw new Error("invalid OSV query response"); - const rows = list(data, "vulns", MAX_RECORDS); - - if (seen.size + rows.length > MAX_RECORDS) { - state.gaps.add("source_budget_exceeded"); - break; - } - - state.hashes.push(await sha256(raw)); - - for (const value of rows) { - const row = object(value); - const id = advisoryId(string(row.id)); - - if (seen.has(id)) { - state.unresolved.add(id); - continue; - } - - seen.add(id); - - try { - inspectAdvisory(row, id, coordinate, now, state); - } catch { - state.unresolved.add(id); - } - } - - pageToken = data.next_page_token === undefined ? "" : string(data.next_page_token); - - if (!pageToken) break; - - if (pageToken.length > 4096 || tokens.has(pageToken)) throw new Error("invalid OSV pagination"); - tokens.add(pageToken); - - if (page + 1 === MAX_PAGES) state.gaps.add("source_budget_exceeded"); - } catch (error) { - if (signal.aborted) state.gaps.add("source_deadline"); - else if (error instanceof Error && /exceeds limit/.test(error.message)) state.gaps.add("source_budget_exceeded"); - else state.gaps.add("source_invalid_response"); - break; - } - } - - if (state.unresolved.size) state.gaps.add("unresolved_advisory_evidence"); - - const status = state.gaps.size ? (state.hashes.length ? "partial" : "unavailable") - : state.findings.length ? "matched" : "no_match"; - - return { - package: coordinate, status, findings: state.findings, gaps: [...state.gaps], - unresolved_advisories: [...state.unresolved], - source: { name: "OSV", url: OSV, queried_at: now, page_sha256: state.hashes }, - }; -} - -export async function assessPackages(request: Request, now: string, fetcher: Fetcher): Promise { - let packages: Coordinate[]; - - try { - const input = object(JSON.parse(await boundedBody(request.body, 8 * 1024))); - - if (Object.keys(input).join() !== "packages") throw new Error("unexpected fields"); - packages = list(input, "packages", MAX_PACKAGES).map(value => readCoordinate(object(value))); - - if (!packages.length) throw new Error("empty batch"); - } catch (error) { - const tooLarge = error instanceof Error && error.message === "body exceeds limit"; - - return Response.json({ error: tooLarge ? "request too large" : "expected 1–8 exact npm or PyPI coordinates" }, - { status: tooLarge ? 413 : 400 }); - } - - const signal = AbortSignal.timeout(12_000); - const assessments = new Map>(); - - const results = await Promise.all(packages.map(coordinate => { - const key = JSON.stringify(coordinate); - const existing = assessments.get(key); - - if (existing) return existing; - const pending = assessCoordinate(coordinate, fetcher, now, signal); - assessments.set(key, pending); - - return pending; - })); - - return Response.json({ schema_version: 2, matcher_version: 1, mode: "shadow", scope: "public_osv_advisory_matches", results }); -} diff --git a/services/advisories/src/pg.ts b/services/advisories/src/pg.ts deleted file mode 100644 index 5dc132e37..000000000 --- a/services/advisories/src/pg.ts +++ /dev/null @@ -1,138 +0,0 @@ -import postgres from "postgres"; -import type { Command, Sql } from "./storage"; - -/** - * Translates the bounded SQLite/D1 SQL subset used by omg-advisories into - * PostgreSQL SQL ($1..$n placeholders, clock_timestamp UTC formatting, and - * jsonb_array_elements for json_each/json_extract). - */ -export function translateSqlForPostgres(input: string): string { - let idx = 0; - let out = ""; - let inSingleQuote = false; - for (let i = 0; i < input.length; i++) { - const ch = input[i]!; - if (ch === "'") { - out += ch; - if (inSingleQuote && input[i + 1] === "'") { - out += "'"; - i++; - } else { - inSingleQuote = !inSingleQuote; - } - continue; - } - if (!inSingleQuote && ch === "?") { - out += `$${++idx}`; - continue; - } - out += ch; - } - - // 1. SQLite UTC ISO-8601 timestamp helper - out = out.replaceAll( - "strftime('%Y-%m-%dT%H:%M:%fZ','now')", - `to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`, - ); - - // Bind pre-serialized JSON as text so postgres.js does not encode it again. - // 2. json_each($N) with explicit alias (e.g. "FROM json_each($1) j") — ignore SQL keywords - out = out.replace( - /FROM\s+json_each\((\$\d+)\)\s+(?!(?:WHERE|ON|JOIN|CROSS|LEFT|RIGHT|INNER|OUTER|ORDER|GROUP|LIMIT|UNION|SET|VALUES)\b)([a-zA-Z_][a-zA-Z0-9_]*)\b/gi, - (_m, param: string, alias: string) => - `FROM jsonb_array_elements(${param}::text::jsonb) AS ${alias}(value)`, - ); - - // 3. json_each($N) without alias (e.g. "FROM json_each($2)") - out = out.replace( - /FROM\s+json_each\((\$\d+)\)/gi, - (_m, param: string) => - `FROM jsonb_array_elements(${param}::text::jsonb) AS _je(value)`, - ); - - // 4. json_extract(, '$.field') -> (->>'field') - out = out.replace( - /json_extract\(\s*([a-zA-Z_][a-zA-Z0-9_.]*)\s*,\s*'\$\.([a-zA-Z0-9_]+)'\s*\)/gi, - (_m, target: string, field: string) => { - const col = target === "value" ? "_je.value" : target; - return `(${col}->>'${field}')`; - }, - ); - - // 5. Bare `value` projection from unaliased json_each (kev_annotation payload_json) - out = out.replace(/,value,/g, ",_je.value::text,"); - - // 6. SQLite disambiguation clause "WHERE 1 ON CONFLICT" - out = out.replace(/\bWHERE\s+1\s+ON\s+CONFLICT\b/gi, "WHERE true ON CONFLICT"); - - // 7. Avoid transferring duplicate payload_jsonb over the wire on /v1/cves/:id (payload_raw is used) - out = out.replace( - "SELECT r.*, k.payload_json AS kev_payload_json FROM source_record r", - "SELECT r.id,r.source,r.source_url,r.schema_version,r.state,r.published_at,r.modified_at,r.fetched_at,r.payload_sha256,r.object_key,r.normalization_version,r.supported,r.payload_raw,k.payload_json AS kev_payload_json FROM source_record r", - ); - - return out; -} - -function normalizeRow(row: Record | undefined): T | null { - if (!row) return null; - const out: Record = {}; - for (const [k, v] of Object.entries(row)) { - // postgres.js returns int8 (e.g. COUNT(*), BIGINT) as string when fetch_types=false - if (typeof v === "string" && /^-?\d+$/.test(v) && (k === "count" || k === "members" || k === "blobs" || k === "unsupported" || k === "asset_size")) { - out[k] = Number(v); - } else { - out[k] = v; - } - } - return out as T; -} - -export interface QueryTags { - readonly application: string; - readonly route: string; - readonly target?: "primary" | "replica"; -} - -export function formatSqlCommenter(tags?: QueryTags): string { - if (!tags) return ""; - const parts: string[] = []; - const safe = (v: string) => encodeURIComponent(v).replaceAll("'", "%27"); - parts.push(`application='${safe(tags.application)}'`); - parts.push(`route='${safe(tags.route)}'`); - if (tags.target) parts.push(`target='${safe(tags.target)}'`); - return ` /*${parts.join(",")}*/`; -} - -export function pgSql(connectionString: string, tags?: QueryTags): Sql & { close(): Promise } { - const client = postgres(connectionString, { - max: 2, - // Hyperdrive + PgBouncer use transaction-mode pooling; disable server prepares - prepare: false, - fetch_types: false, - }); - const suffix = formatSqlCommenter(tags); - - return { - inlinePayloads: true, - async first(sql: string, values: (string | number | null)[] = []): Promise { - const rows = await client.unsafe(translateSqlForPostgres(sql) + suffix, values); - return normalizeRow(rows[0] as Record | undefined); - }, - async all(sql: string, values: (string | number | null)[] = []): Promise { - const rows = await client.unsafe(translateSqlForPostgres(sql) + suffix, values); - return rows.map((r) => normalizeRow(r as Record)!); - }, - async batch(commands: Command[]): Promise { - if (!commands.length) return; - await client.begin(async (tx) => { - for (const cmd of commands) { - await tx.unsafe(translateSqlForPostgres(cmd.sql) + suffix, cmd.values); - } - }); - }, - async close(): Promise { - await client.end({ timeout: 5 }); - }, - }; -} diff --git a/services/advisories/src/publisher.ts b/services/advisories/src/publisher.ts deleted file mode 100644 index d5d41aa33..000000000 --- a/services/advisories/src/publisher.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { SOURCES, boundedBody } from "./domain"; -import type { Fetcher } from "./ingestion"; - -export const cveCommitFeed = "https://github.com/CVEProject/cvelistV5/commits/main/cves/deltaLog.json.atom"; - -export const kevMirror = "https://raw.githubusercontent.com/cisagov/kev-data/develop/known_exploited_vulnerabilities.json"; - -export const cveDiscoveryFeed = "https://vulnerability.circl.lu/recent/cvelistv5.atom?per_page=50"; - -const cveDirectory = SOURCES.cve.slice(0, -"deltaLog.json".length); - -async function latestPublisherCommit(fetcher: Fetcher): Promise { - try { - const response = await fetcher(cveCommitFeed, { - redirect: "manual", - headers: { Accept: "application/atom+xml" }, - signal: AbortSignal.timeout(4_000), - }); - - if (!response.ok) { - void response.body?.cancel().catch(() => undefined); - - return null; - } - - const atom = await boundedBody(response.body, 256 * 1024); - const entry = /]*)?>\s*([\s\S]*?)<\/entry>/.exec(atom)?.[1]; - - return entry?.match(/tag:github\.com,2008:Grit::Commit\/([0-9a-f]{40})<\/id>/)?.[1] ?? null; - } catch { - return null; - } -} - -export function scheduledPublisherFetcher(fetcher: Fetcher): Fetcher { - let commit: string | null = null; - - return async (url, init) => { - if (url === SOURCES.cve) commit = await latestPublisherCommit(fetcher); - - if (commit && url.startsWith(cveDirectory)) { - return fetcher(url.replace("/main/cves/", `/${commit}/cves/`), init); - } - - return fetcher(url, init); - }; -} - -export async function recentCveHints(fetcher: Fetcher, now: string) { - const response = await fetcher(cveDiscoveryFeed, { - redirect: "manual", - headers: { - Accept: "application/atom+xml", - "User-Agent": "OMG-Advisories/1.0 (+https://getomg.dev/security/)", - }, - signal: AbortSignal.timeout(5_000), - }); - - if (!response.ok) { - void response.body?.cancel().catch(() => undefined); - throw new Error(`CVE discovery HTTP ${response.status}`); - } - - const atom = await boundedBody(response.body, 256 * 1024); - const hints = new Map(); - const cutoff = Date.parse(now) - 2 * 60 * 60_000; - - for (const entry of atom.matchAll(/]*)?>\s*([\s\S]*?)<\/entry>/g)) { - const body = entry[1] ?? ""; - const id = /https:\/\/vulnerability\.circl\.lu\/vuln\/(CVE-\d{4}-\d{4,19})<\/id>/i.exec(body)?.[1]?.toUpperCase(); - const updated = /([^<]+)<\/updated>/.exec(body)?.[1]; - const parsed = Date.parse(updated ?? ""); - - if (!id || !Number.isFinite(parsed) || parsed < cutoff || parsed > Date.parse(now)) continue; - const modified = new Date(parsed).toISOString(); - const previous = hints.get(id); - - if (previous === undefined || modified > previous) hints.set(id, modified); - - if (hints.size >= 50) break; - } - - return Array.from(hints, ([id, modified]) => ({ id, modified })); -} diff --git a/services/advisories/src/raw-pack.ts b/services/advisories/src/raw-pack.ts deleted file mode 100644 index be6d2a0d0..000000000 --- a/services/advisories/src/raw-pack.ts +++ /dev/null @@ -1,57 +0,0 @@ -import type { RawStore } from "./storage"; -import { LIMITS, boundedBody, decodeUtf8, sha256 } from "./domain"; - -const prefix = "cve-pack-v1/"; -const pointerPattern = /^(cve-pack-v1\/[a-f0-9]{64}\.raw)#(0|[1-9]\d{0,15}):([1-9]\d{0,15}):([a-f0-9]{64})$/; - -export async function packRecords(records: readonly string[]): Promise<{key:string;body:string;pointers:readonly string[]}> { - if (records.length < 1 || records.length > 64) throw new Error("invalid packed raw record count"); - let total = 0; - const parts = records.map((raw) => { - const bytes = new TextEncoder().encode(raw); - if (bytes.length < 1 || bytes.length > LIMITS.cveRecord || decodeUtf8(bytes) !== raw) - throw new Error("invalid packed raw UTF8 record"); - const offset = total; - total += bytes.length; - if (total > LIMITS.batch) throw new Error("packed raw records exceed batch byte bound"); - return { bytes, offset }; - }); - const body = records.join(""); - const key = `${prefix}${await sha256(body)}.raw`; - const pointers = await Promise.all(parts.map(async ({bytes, offset}) => - `${key}#${offset}:${bytes.length}:${await sha256(bytes)}`)); - return {key, body, pointers}; -} - -export function r2Raw(bucket: Pick): RawStore { - return { - put: (key, value) => bucket.put(key, value), - get: async (key) => { - if (!key.startsWith("cve-pack-")) return bucket.get(key); - const match = pointerPattern.exec(key); - if (!match) throw new Error("invalid packed raw pointer"); - const [, objectKey, offsetText, lengthText, digest] = match; - if (!objectKey || offsetText === undefined || !lengthText || !digest) - throw new Error("invalid packed raw pointer"); - const offset = Number(offsetText), length = Number(lengthText); - if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || - length > LIMITS.cveRecord || offset + length > LIMITS.batch) - throw new Error("invalid packed raw pointer"); - const object = await bucket.get(objectKey, {range:{offset, length}}); - if (!object) throw new Error("packed raw object missing"); - if (!("body" in object)) throw new Error("packed raw body missing"); - const range = object.range; - if (!range || !("offset" in range) || !("length" in range) || - range.offset !== offset || range.length !== length || - object.size < offset + length || object.size > LIMITS.batch) { - await object.body.cancel(); - throw new Error("packed raw range mismatch"); - } - const text = await boundedBody(object.body, length); - if (new TextEncoder().encode(text).length !== length) - throw new Error("packed raw range mismatch"); - if (await sha256(text) !== digest) throw new Error("packed raw digest mismatch"); - return {text: async () => text}; - }, - }; -} diff --git a/services/advisories/src/recent.ts b/services/advisories/src/recent.ts deleted file mode 100644 index 42228cdd8..000000000 --- a/services/advisories/src/recent.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { cveId, date, object } from "./domain"; -import { type Sql, type RecordRow } from "./storage"; - -const WINDOW = 30 * 24 * 60 * 60_000; - -export const firstPageSize = 100; - -export function recentWindowStart(asOf: string) { - return new Date(Date.parse(asOf) - WINDOW).toISOString(); -} - -export function recentPage>( - rows: readonly T[], asOf: string, limit: number, -) { - const records = rows.slice(0, limit); - const last = records.at(-1); - - return { - window_start: recentWindowStart(asOf), - as_of: asOf, - records, - next_cursor: rows.length > limit && last ? btoa(JSON.stringify({ - as_of: asOf, modified_at: last.modified_at, id: last.id, - })) : null, - }; -} - -export async function recentCves(url: URL, sql: Sql, now: string) { - for (const key of url.searchParams.keys()) { - if (!["limit", "cursor"].includes(key) || url.searchParams.getAll(key).length !== 1) - throw new Error("invalid recent query"); - } - - const limitText = url.searchParams.get("limit") ?? String(firstPageSize); - if (!/^(?:[1-9]\d?|100)$/.test(limitText)) throw new Error("invalid recent limit"); - - const limit = Number(limitText); - let asOf = now, modified = now, id = "\uffff"; - const cursor = url.searchParams.get("cursor"); - if (cursor !== null) { - try { - if (!cursor || cursor.length > 1024) throw new Error("invalid cursor size"); - const value = object(JSON.parse(atob(cursor))); - if (Object.keys(value).sort().join(",") !== "as_of,id,modified_at") - throw new Error("invalid cursor fields"); - asOf = date(value.as_of); - modified = date(value.modified_at); - id = cveId(value.id); - if (asOf !== value.as_of || modified !== value.modified_at || - asOf > now || Date.parse(now) - Date.parse(asOf) > 60 * 60_000 || - modified > asOf || Date.parse(modified) < Date.parse(asOf) - WINDOW) - throw new Error("invalid cursor bounds"); - } catch { - throw new Error("invalid recent cursor"); - } - } - const rows = await sql.all( - "SELECT id,source,source_url,schema_version,state,published_at,modified_at,fetched_at,payload_sha256,object_key,normalization_version,supported FROM source_record WHERE modified_at>=? AND modified_at<=? AND (modified_at,id)<(?,?) ORDER BY modified_at DESC,id DESC LIMIT ?", - [recentWindowStart(asOf), asOf, modified, id, limit + 1], - ); - - return recentPage(rows, asOf, limit); -} diff --git a/services/advisories/src/runtime-cron.ts b/services/advisories/src/runtime-cron.ts deleted file mode 100644 index 985abd505..000000000 --- a/services/advisories/src/runtime-cron.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { boundedBody, date, isGitHubInstallationToken, object } from "./domain"; -import { type Fetcher } from "./ingestion"; -import { refreshRuntimeProfile } from "./runtime"; -import { type Store } from "./storage"; - -export const RUNTIME_REFRESH_CRON = "2-57/5 * * * *"; - -const GROUPS = [ - ["java", "zig", "swift"], - ["python", "erlang", "deno"], - ["rust", "ruby", "bun", "php"], -] as const; - -const fetchUpstream: Fetcher = (url, init) => fetch(url, init); - -const RSA = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }; - -export interface RuntimeRefreshEnvironment { - ADVISORIES_GITHUB_APP_CLIENT_ID?: string; - ADVISORIES_GITHUB_APP_INSTALLATION_ID?: string; - ADVISORIES_GITHUB_APP_PRIVATE_KEY?: string; -} - -export function runtimeRefreshBatch(scheduledTime: number) { - const minute = new Date(scheduledTime).getUTCMinutes(); - - return GROUPS[Math.floor(minute / 5) % GROUPS.length] ?? []; -} - -function base64Url(bytes: Uint8Array) { - return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); -} - -export async function mintRuntimeRefreshToken( - clientId: string, installationId: string, pem: string, now: Date, fetcher: Fetcher, -) { - if (!/^[a-zA-Z0-9.-]{1,128}$/.test(clientId) || !/^[1-9]\d{0,19}$/.test(installationId) || pem.length > 8192) - throw new Error("invalid GitHub App configuration"); - const body = /^-----BEGIN PRIVATE KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END PRIVATE KEY-----$/.exec(pem.trim())?.[1]; - - if (!body) throw new Error("invalid GitHub App key format"); - - const key = await crypto.subtle.importKey("pkcs8", - Uint8Array.from(atob(body.replace(/\s/g, "")), char => char.charCodeAt(0)), RSA, false, ["sign"]); - - const encoder = new TextEncoder(); - const seconds = Math.floor(now.getTime() / 1000); - const header = base64Url(encoder.encode(JSON.stringify({ alg: "RS256", typ: "JWT" }))); - const claims = base64Url(encoder.encode(JSON.stringify({ iss: clientId, iat: seconds - 60, exp: seconds + 300 }))); - const unsigned = `${header}.${claims}`; - const signature = await crypto.subtle.sign(RSA, key, encoder.encode(unsigned)); - const jwt = `${unsigned}.${base64Url(new Uint8Array(signature))}`; - - const response = await fetcher(`https://api.github.com/app/installations/${installationId}/access_tokens`, { - method: "POST", - headers: { - Authorization: `Bearer ${jwt}`, - Accept: "application/vnd.github+json", - "Content-Type": "application/json", - "User-Agent": "OMG-Advisory-Intake", - "X-GitHub-Api-Version": "2022-11-28", - }, - body: JSON.stringify({ permissions: { contents: "read" } }), - redirect: "manual", - signal: AbortSignal.timeout(10_000), - }); - - if (response.status !== 201) { - void response.body?.cancel().catch(() => undefined); - throw new Error("GitHub rejected the installation token request"); - } - - const reply = object(JSON.parse(await boundedBody(response.body, 32 * 1024))); - - if (!isGitHubInstallationToken(reply.token) || Date.parse(date(reply.expires_at)) <= now.getTime() + 60_000) - throw new Error("invalid GitHub installation token response"); - - return reply.token; -} - -export async function refreshScheduledRuntimes( - env: RuntimeRefreshEnvironment, store: Store, scheduledTime: number, fetcher = fetchUpstream, -) { - const { ADVISORIES_GITHUB_APP_CLIENT_ID: clientId, ADVISORIES_GITHUB_APP_INSTALLATION_ID: installationId, - ADVISORIES_GITHUB_APP_PRIVATE_KEY: key } = env; - - let token: string | undefined; - - if (clientId && installationId && key) { - try { - token = await mintRuntimeRefreshToken(clientId, installationId, key, new Date(), fetcher); - } catch { - console.error(JSON.stringify({ event: "advisory_runtime_cron_token_failed" })); - } - } else if (clientId || installationId || key) { - console.error(JSON.stringify({ event: "advisory_runtime_cron_incomplete_configuration" })); - } - - for (const runtime of runtimeRefreshBatch(scheduledTime)) { - if (!token && runtime !== "python" && runtime !== "erlang") continue; - - try { - const checkedAt = new Date().toISOString(); - const result = await refreshRuntimeProfile(runtime, store, checkedAt, fetcher, token); - const checked = result.refreshed && result.sources.every(source => source.checked_at === checkedAt); - const event = checked ? "advisory_runtime_cron_complete" : "advisory_runtime_cron_incomplete"; - const evidence = JSON.stringify({ event, runtime, scheduled_at: new Date(scheduledTime).toISOString(), sources: result.sources.map(source => ({ name: source.name, complete: source.complete, checked_at: source.checked_at })) }); - - if (checked) console.info(evidence); - else console.warn(evidence); - } catch { - console.error(JSON.stringify({ event: "advisory_runtime_cron_failed", runtime })); - } - } -} diff --git a/services/advisories/src/runtime.ts b/services/advisories/src/runtime.ts deleted file mode 100644 index 6e369d6d6..000000000 --- a/services/advisories/src/runtime.ts +++ /dev/null @@ -1,922 +0,0 @@ -import { satisfies, valid, validRange, compare } from "semver"; -import { parseDocument } from "yaml"; -import { parse as parseToml } from "smol-toml"; -import { ZipReader, Uint8ArrayReader } from "@zip.js/zip.js/lib/zip-core-native.js"; -import { Requirement as RubyRequirement } from "@renovatebot/ruby-semver/dist/ruby/requirement.js"; -import { Version as RubyVersion } from "@renovatebot/ruby-semver/dist/ruby/version.js"; -import { boundedBody, cveId, cveServicesUrl, cveUrl, date, decodeUtf8, isGitHubInstallationToken, object, parseCve, sha256, string } from "./domain"; -import { type Fetcher } from "./ingestion"; -import { type Store } from "./storage"; -import { GitHubCooldownActive, githubAwareFetch } from "./github-cooldown"; - -const MINUTE = 60_000; -const SOURCE_TTL = 30 * MINUTE; -const SOURCE_REVIEW_HEADROOM = 5 * MINUTE; -const SOURCE_BYTES = 8 * 1024 * 1024; -const MAX_FINDINGS = 512; -const VENDORS = { - node: "nodejs", python: "cpython", go: "golang", rust: "rust-lang", ruby: "ruby-lang", - java: "temurin", bun: "oven-sh", pi: "earendil-works", deno: "denoland", zig: "ziglang", - dotnet: "microsoft", erlang: "erlang", php: "php", swift: "swiftlang", -}; -type Runtime = keyof typeof VENDORS; -export type RuntimeIdentity = { runtime: Runtime; vendor: string; version: string; os: string; arch: string }; -export type RuntimeFinding = { id: string; summary: string; applicability: "applicable" | "possible"; severity: string | null; urls: string[] }; -type SourceReceipt = { name: string; url: string; revision: string | null; payload_sha256: string; checked_at: string; complete: boolean }; -type SourceRow = { cache_key: string; source_url: string; checked_at: string; successful_at: string | null; revision: string | null; payload_sha256: string | null; object_key: string | null; error: string | null }; -type Previous = { raw: string; revision: string | null }; -type Produced = Previous & ({ complete: true } | { complete: false; gap: string }); -type Loaded = { raw: string; receipt: SourceReceipt }; -type Producer = (previous: Previous | null) => Promise; - -function runtimeName(value: string): Runtime { - switch (value) { - case "node": case "python": case "go": case "rust": case "ruby": case "java": case "bun": - case "pi": case "deno": case "zig": case "dotnet": case "erlang": case "php": case "swift": return value; - default: throw new Error("invalid runtime name"); - } -} -function identity(url: URL): RuntimeIdentity { - const match = /^\/v1\/runtimes\/([a-z]+)$/.exec(url.pathname); - if (!match?.[1]) throw new Error("invalid runtime route"); - const runtime = runtimeName(match[1]); - const keys = [...url.searchParams.keys()].sort(); - if (keys.join(",") !== "arch,os,vendor,version") throw new Error("invalid runtime query"); - const vendor = url.searchParams.get("vendor") ?? ""; - const version = url.searchParams.get("version") ?? ""; - const os = url.searchParams.get("os") ?? ""; - const arch = url.searchParams.get("arch") ?? ""; - if (!/^[a-z0-9][a-z0-9._-]{0,79}$/.test(vendor) || !/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(version) || - !["linux", "macos", "windows"].includes(os) || !["x86_64", "aarch64"].includes(arch)) - throw new Error("invalid runtime identity"); - return { runtime, vendor, version, os, arch }; -} -function text(value: unknown, limit = 256): string { - return string(value).replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, " ").trim().slice(0, limit); -} -function safeUrl(value: unknown): string | null { - if (typeof value !== "string" || value.length > 1024 || /[\u0000-\u0020\u007f-\u009f]/.test(value)) return null; - try { - const url = new URL(value); - if (url.protocol !== "https:" || url.username || url.password || url.port || !url.hostname.includes(".") || - /^(?:localhost|127\.|10\.|192\.168\.|169\.254\.|\[)/.test(url.hostname)) return null; - return url.href; - } catch { return null; } -} -function findingId(value: unknown): string { - const id = string(value); - if (!/^(?:CVE-\d{4}-\d{4,19}|GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}|GO-\d{4}-\d{4,8}|RUSTSEC-\d{4}-\d{4,8}|PSF-\d{4}-\d{1,8}|NODE-CORE-\d{1,9}|RUBY-CORE-[A-Za-z0-9._-]{1,100}|DOTNET-SECURITY-[A-Za-z0-9.+_-]{1,80}|MAL-\d{4}-\d{1,10})$/.test(id)) - throw new Error("unsupported advisory identifier"); - return id; -} -function reference(id: string): string { - if (id.startsWith("CVE-")) return `https://www.cve.org/CVERecord?id=${id}`; - if (id.startsWith("NODE-CORE-")) return `https://github.com/nodejs/security-wg/blob/main/vuln/core/${id.slice(10)}.json`; - if (id.startsWith("RUBY-CORE-")) return `https://github.com/rubysec/ruby-advisory-db/blob/master/rubies/ruby/${id.slice(10)}.yml`; - if (id.startsWith("DOTNET-SECURITY-")) return `https://github.com/dotnet/core/tree/main/release-notes/${id.slice(16).split(".").slice(0, 2).join(".")}`; - return `https://osv.dev/vulnerability/${id}`; -} -function array(value: unknown, limit = 4096): unknown[] { - if (!Array.isArray(value) || value.length > limit) throw new Error("invalid bounded source array"); - return value; -} -function semverMatch(version: string, requirement: unknown): boolean | null { - if (typeof requirement !== "string" || !requirement.trim() || requirement.length > 2048 || !valid(version)) return null; - const range = validRange(requirement); - return range === null ? null : satisfies(version, range, { includePrerelease: true }); -} -function numeric(value: string): number[] | null { - if (!/^\d{1,9}(?:\.\d{1,9}){0,3}$/.test(value)) return null; - return value.split(".").map(Number); -} -function numericCompare(a: string, b: string): number | null { - const left = numeric(a), right = numeric(b); - if (!left || !right) return null; - for (let i = 0; i < Math.max(left.length, right.length); i++) { - const difference = (left[i] ?? 0) - (right[i] ?? 0); - if (difference !== 0) return difference < 0 ? -1 : 1; - } - return 0; -} -function numericRange(version: string, range: unknown): boolean | null { - if (typeof range !== "string" || range.length > 2048) return null; - const alternatives = range.split("||"); - if (alternatives.length > 32) return null; - let unknown = false; - for (const alternative of alternatives) { - const terms = alternative.trim().replace(/,/g, " ").match(/(?:>=|<=|>|<|=)?\s*\d+(?:\.\d+){0,3}/g); - if (!terms || terms.length > 16 || alternative.replace(/(?:>=|<=|>|<|=)?\s*\d+(?:\.\d+){0,3}/g, "").replace(/[\s,]/g, "") !== "") { unknown = true; continue; } - let matched = true; - for (const term of terms) { - const match = /^(>=|<=|>|<|=)?\s*(\d+(?:\.\d+){0,3})$/.exec(term.trim()); - if (!match?.[2]) { unknown = true; matched = false; break; } - const compared = numericCompare(version, match[2]); - if (compared === null) { unknown = true; matched = false; break; } - const operator = match[1] ?? "="; - if (!(operator === ">=" ? compared >= 0 : operator === "<=" ? compared <= 0 : operator === ">" ? compared > 0 : operator === "<" ? compared < 0 : compared === 0)) matched = false; - } - if (matched) return true; - } - return unknown ? null : false; -} - -class Assessment { - readonly findings = new Map(); - readonly gaps = new Set(); - readonly sources = new Map(); - gap(value: string) { if (this.gaps.size < 64) this.gaps.add(value.slice(0, 1024)); } - add(idValue: unknown, summary: unknown, applicability: "applicable" | "possible", severity: unknown, urls: unknown[] = []) { - const id = findingId(idValue); - const accepted = [...new Set([reference(id), ...urls.map(safeUrl).filter((url): url is string => url !== null)])].slice(0, 4); - const previous = this.findings.get(id); - if (!previous && this.findings.size >= MAX_FINDINGS) { this.gap("Advisory finding limit reached; coverage remains incomplete"); return; } - this.findings.set(id, { id, summary: text(summary), applicability: previous?.applicability === "applicable" ? "applicable" : applicability, - severity: typeof severity === "string" ? text(severity, 64) : previous?.severity ?? null, - urls: [...new Set([...(previous?.urls ?? []), ...accepted])].slice(0, 4) }); - } - source(receipt: SourceReceipt) { - const key = `${receipt.name}\0${receipt.url}`; - if (!this.sources.has(key) && this.sources.size >= 16) throw new Error("source receipt limit reached"); - this.sources.set(key, receipt); - } -} - -class Sources { - readonly signal = AbortSignal.timeout(25_000); - private requests = 0; - constructor(readonly store: Store, readonly fetcher: Fetcher, readonly now: string, readonly force: boolean, readonly assessment: Assessment, private readonly credential?: string, private readonly trustedRefresh = false) {} - async response(url: string, init: RequestInit = {}): Promise { - if (++this.requests > 768) throw new Error("runtime source request budget exceeded"); - this.signal.throwIfAborted(); - const parsed = new URL(url); - if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.port || - !["raw.githubusercontent.com", "api.github.com", "codeload.github.com", "api.osv.dev", "builds.dotnet.microsoft.com", "github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com", "cveawg.mitre.org"].includes(parsed.hostname)) - throw new Error("unapproved runtime source origin"); - const headers = new Headers(init.headers); - - if (!headers.has("User-Agent")) headers.set("User-Agent", "omg-advisories/1.0"); - - if (!headers.has("Accept")) headers.set("Accept", "application/json"); - - if (this.force && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-cache"); - - const signal = init.signal ? AbortSignal.any([this.signal, init.signal]) : this.signal; - - return githubAwareFetch(this.fetcher, this.store.raw, url, { - ...init, headers, redirect: "manual", signal, - }, this.now, this.credential !== undefined); - } - async json(url: string, init?: RequestInit, limit = SOURCE_BYTES): Promise { - const response = await this.response(url, init); - if (response.status !== 200) throw await this.failure(response, url); - return JSON.parse(await boundedBody(response.body, limit)); - } - async failure(response: Response, url: string): Promise { - await response.body?.cancel(); - let diagnostic = ""; - if (new URL(url).origin === "https://api.github.com" && [403, 429].includes(response.status)) { - const number = (header: string) => { - const value = response.headers.get(header); - return value !== null && /^\d{1,12}$/.test(value) ? value : "unknown"; - }; - diagnostic = `; GitHub rate limit remaining=${number("x-ratelimit-remaining")} reset=${number("x-ratelimit-reset")} retry_after=${number("retry-after")}`; - } - return new Error(`source HTTP ${response.status}${diagnostic}`); - } - async read(key: string, name: string, url: string, produce: Producer): Promise { - const cacheKey = `v1:${key}`; - const read = () => this.store.sql.first("SELECT * FROM runtime_source WHERE cache_key=?", [cacheKey]); - let cached = await read(); - const stored = async (row: SourceRow | null): Promise => { - if (!row?.object_key || !row.payload_sha256 || !row.successful_at || row.source_url !== url) return null; - if (!/^[a-f0-9]{64}$/.test(row.payload_sha256) || !row.object_key.startsWith("runtime/")) throw new Error("invalid runtime cache pointer"); - const raw = await this.store.raw.get(row.object_key); - if (!raw) throw new Error("runtime source object missing"); - const body = await raw.text(); - if (new TextEncoder().encode(body).length > SOURCE_BYTES || await sha256(body) !== row.payload_sha256) throw new Error("runtime cache payload mismatch"); - JSON.parse(body); - const checked = date(row.successful_at); - const fresh = checked <= this.now && Date.parse(this.now) - Date.parse(checked) <= SOURCE_TTL; - return { raw: body, receipt: { name, url, revision: row.revision, payload_sha256: row.payload_sha256, checked_at: checked, complete: fresh && row.error === null } }; - }; - const use = (loaded: Loaded | null) => { - if (loaded) { - this.assessment.source(loaded.receipt); - if (!loaded.receipt.complete) this.assessment.gap(`${name} is stale or unavailable; retained last successful snapshot: ${url}`); - } else this.assessment.gap(`${name} is unavailable: ${url}`); - return loaded; - }; - let previous = await stored(cached); - const scheduledGitHubSource = key.startsWith("ghsa:") || ["python:psf", "rust:components", "ruby:mri", "java:temurin-vdr"].includes(key); - const hasReviewHeadroom = previous !== null && Date.parse(this.now) - Date.parse(previous.receipt.checked_at) < SOURCE_TTL - SOURCE_REVIEW_HEADROOM; - - if (!this.trustedRefresh && scheduledGitHubSource && previous?.receipt.complete && (!this.force || hasReviewHeadroom)) return use(previous); - const age = cached ? Date.parse(this.now) - Date.parse(cached.checked_at) : Infinity; - if (!this.force && age >= 0 && age < (cached?.error ? MINUTE : SOURCE_TTL)) return use(previous); - const lease = `runtime:${await sha256(cacheKey)}`, owner = crypto.randomUUID(); - if (!await this.store.lease(lease, owner, this.now)) { - if (previous?.receipt.complete) return use(previous); - this.assessment.gap(`${name} refresh is already in progress`); - return use(previous); - } - try { - cached = await read(); previous = await stored(cached); - let incoming: Produced; - try { - incoming = await produce(previous ? { raw: previous.raw, revision: previous.receipt.revision } : null); - if (new TextEncoder().encode(incoming.raw).length > SOURCE_BYTES) throw new Error("runtime source body exceeds limit"); - if (this.credential && incoming.raw.includes(this.credential)) throw new Error("source reflected a refresh credential"); - JSON.parse(incoming.raw); - if (incoming.revision !== null && (incoming.revision.length > 256 || /[\u0000-\u001f\u007f]/.test(incoming.revision))) throw new Error("invalid source revision"); - } catch (error) { - if (error instanceof GitHubCooldownActive) { - if (!previous?.receipt.complete) this.assessment.gap(`${name} refresh deferred until GitHub's retry window ends`); - - return use(previous); - } - - const message = error instanceof Error ? error.message : "unknown source failure"; - const reason = text(this.credential ? message.replaceAll(this.credential, "[redacted]") : message, 160); - await this.store.writer(lease, owner).sql.batch([{ - sql: "INSERT INTO runtime_source(cache_key,source_url,checked_at,error) VALUES(?,?,?,?) ON CONFLICT(cache_key) DO UPDATE SET checked_at=excluded.checked_at,error=excluded.error", - values: [cacheKey, url, this.now, reason], - }]); - this.assessment.gap(`${name} refresh failed (${reason}): ${url}`); - if (previous) previous.receipt.complete = false; - return use(previous); - } - const hash = await sha256(incoming.raw), keyHash = await sha256(cacheKey); - const objectKey = `runtime/${keyHash}/${hash}.json`; - if (cached?.payload_sha256 !== hash) await this.store.raw.put(objectKey, incoming.raw); - if (!incoming.complete && cached?.error === null && previous) { - await this.store.writer(lease, owner).sql.batch([{ sql: "UPDATE runtime_source SET checked_at=?,error=? WHERE cache_key=?", values: [this.now, incoming.gap, cacheKey] }]); - } else await this.store.writer(lease, owner).sql.batch([{ - sql: "INSERT INTO runtime_source(cache_key,source_url,checked_at,successful_at,revision,payload_sha256,object_key,error) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(cache_key) DO UPDATE SET source_url=excluded.source_url,checked_at=excluded.checked_at,successful_at=excluded.successful_at,revision=excluded.revision,payload_sha256=excluded.payload_sha256,object_key=excluded.object_key,error=excluded.error", - values: [cacheKey, url, this.now, this.now, incoming.revision, hash, objectKey, incoming.complete ? null : incoming.gap], - }]); - if (!incoming.complete) this.assessment.gap(incoming.gap); - return use({ raw: incoming.raw, receipt: { name, url, revision: incoming.revision, payload_sha256: hash, checked_at: this.now, complete: incoming.complete } }); - } finally { await this.store.release(lease, owner); } - } - jsonSource(key: string, name: string, url: string, validate?: (value: unknown) => void) { - return this.read(key, name, url, async (previous) => { - const response = await this.response(url, { headers: previous?.revision ? { "If-None-Match": previous.revision } : {} }); - if (response.status === 304 && previous) return { ...previous, complete: true }; - if (response.status !== 200) { await response.body?.cancel(); throw new Error(`source HTTP ${response.status}`); } - const raw = await boundedBody(response.body, SOURCE_BYTES); - const payload: unknown = JSON.parse(raw); - validate?.(payload); - return { raw, revision: response.headers.get("etag"), complete: true }; - }); - } - textSource(key: string, name: string, url: string) { - return this.read(key, name, url, async (previous) => { - const response = await this.response(url, { headers: previous?.revision ? { "If-None-Match": previous.revision } : {} }); - if (response.status === 304 && previous) return { ...previous, complete: true }; - if (response.status !== 200) { await response.body?.cancel(); throw new Error(`source HTTP ${response.status}`); } - return { raw: JSON.stringify({ text: await boundedBody(response.body, SOURCE_BYTES) }), revision: response.headers.get("etag"), complete: true }; - }); - } - archive(key: string, name: string, repo: string, branch: string, select: RegExp, validate?: (raw: string) => void) { - const sourceUrl = `https://github.com/${repo}/tree/${branch}`; - return this.read(key, name, sourceUrl, async (previous) => { - const commit = object(await this.json(`https://api.github.com/repos/${repo}/commits/${branch}`)); - const revision = string(commit.sha); - if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error("invalid upstream commit identity"); - if (previous?.revision === revision) return { ...previous, complete: true }; - const response = await this.response(`https://codeload.github.com/${repo}/zip/${revision}`); - if (response.status !== 200 || !response.body) { await response.body?.cancel(); throw new Error(`source archive HTTP ${response.status}`); } - const reader = response.body.getReader(), chunks: Uint8Array[] = []; - let bytes = 0; - try { - for (;;) { - const part = await reader.read(); - if (part.done) break; - bytes += part.value.byteLength; - if (bytes > 16 * 1024 * 1024) { await reader.cancel(); throw new Error("source archive exceeds compressed limit"); } - chunks.push(part.value); - } - } finally { reader.releaseLock(); } - const compressed = new Uint8Array(bytes); - let offset = 0; - for (const chunk of chunks) { compressed.set(chunk, offset); offset += chunk.length; } - const zip = new ZipReader(new Uint8ArrayReader(compressed), { useWebWorkers: false, useCompressionStream: true, checkCrc32: true, checkOverlappingEntry: true }); - const files: { path: string; raw: string }[] = []; - const names = new Set(); - let entries = 0, total = 0; - const prefix = `${repo.split("/")[1]}-${revision}/`; - try { - for await (const entry of zip.getEntriesGenerator()) { - if (++entries > 32768) throw new Error("source archive entry budget exceeded"); - if (entry.directory || !entry.filename.startsWith(prefix)) continue; - const path = entry.filename.slice(prefix.length); - if (!select.test(path)) continue; - if (entry.encrypted || entry.uncompressedSize > 1024 * 1024 || entry.uncompressedSize < 1 || files.length >= 4096 || names.has(path)) - throw new Error("invalid selected advisory archive entry"); - names.add(path); - const content: Uint8Array[] = []; - let size = 0; - await entry.getData(new WritableStream({ write(chunk) { - size += chunk.byteLength; total += chunk.byteLength; - if (size > 1024 * 1024 || total > SOURCE_BYTES) throw new Error("source archive expansion exceeds limit"); - content.push(chunk); - } }), { signal: this.signal, checkCrc32: true, useWebWorkers: false, useCompressionStream: true }); - if (size !== entry.uncompressedSize) throw new Error("source archive decoded size mismatch"); - const decoded = new Uint8Array(size); let position = 0; - for (const chunk of content) { decoded.set(chunk, position); position += chunk.length; } - const raw = decodeUtf8(decoded); - validate?.(raw); - files.push({ path, raw }); - } - } finally { await zip.close(); } - if (!files.length) throw new Error("source archive has no expected advisories"); - return { raw: JSON.stringify(files.sort((a, b) => a.path.localeCompare(b.path))), revision, complete: true }; - }); - } -} - -async function node(identity: RuntimeIdentity, sources: Sources, result: Assessment) { - const url = "https://raw.githubusercontent.com/nodejs/security-wg/main/vuln/core/index.json"; - const source = await sources.jsonSource("node:core", "Node.js core advisories", url, (payload) => { - const entries = Object.entries(object(payload)); - if (!entries.length || entries.length > 4096) throw new Error("invalid Node advisory index"); - for (const [key, value] of entries) { - if (!/^\d{1,9}$/.test(key)) throw new Error("invalid Node advisory key"); - const row = object(value); - string(row.vulnerable); string(row.patched); - for (const id of array(row.cve, 32)) cveId(id); - } - }); - if (!source) return; - const records = Object.entries(object(JSON.parse(source.raw))); - if (records.length === 0 || records.length > 4096) throw new Error("invalid Node advisory index"); - for (const [key, value] of records) { - if (!/^\d{1,9}$/.test(key)) throw new Error("invalid Node advisory key"); - const row = object(value); - const vulnerable = semverMatch(identity.version, row.vulnerable); - const patched = semverMatch(identity.version, row.patched); - if (vulnerable === false || patched === true) continue; - const certain = vulnerable === true && patched === false; - if (!certain) result.gap("Node advisory index contains an unsupported applicability range"); - const ids = array(row.cve, 32); - for (const id of ids.length ? ids : [`NODE-CORE-${key}`]) - result.add(id, row.description ?? "Published Node.js core advisory", certain ? "applicable" : "possible", row.severity, [row.ref, url]); - } -} -function osvSnapshot(rows: unknown[]): string { - // OSV can reorder object keys between otherwise identical responses. - // Keep every field and array position in the owned evidence snapshot. - return JSON.stringify(rows, (_key: string, value: unknown) => { - if (value === null || typeof value !== "object" || Array.isArray(value)) return value; - const row = object(value); - return Object.fromEntries(Object.keys(row).sort().map((key) => [key, row[key]])); - }); -} -async function osv(identity: RuntimeIdentity, sources: Sources, result: Assessment, ecosystem: string, packageName: string) { - const url = "https://api.osv.dev/v1/query"; - const loaded = await sources.read(`osv:${ecosystem}:${packageName}:${identity.version}`, `OSV ${ecosystem} ${packageName}`, url, async () => { - let token: string | null = null; - const tokens = new Set(), ids = new Set(), rows: unknown[] = []; - let bytes = 2; - for (let page = 0; page < 20; page++) { - const body: { package: { ecosystem: string; name: string }; version: string; page_token?: string } = { package: { ecosystem, name: packageName }, version: identity.version }; - if (token !== null) body.page_token = token; - const response = object(await sources.json(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })); - for (const value of response.vulns === undefined ? [] : array(response.vulns)) { - const row = object(value), id = findingId(row.id); - if (ids.has(id) || rows.length >= 4096) throw new Error("duplicate or excessive OSV findings"); - bytes += new TextEncoder().encode(JSON.stringify(row)).length + 1; - if (bytes > SOURCE_BYTES) throw new Error("OSV paginated source exceeds limit"); - ids.add(id); rows.push(row); - } - if (response.next_page_token === undefined || response.next_page_token === "") return { raw: osvSnapshot(rows.sort((a, b) => string(object(a).id).localeCompare(string(object(b).id)))), revision: null, complete: true }; - token = string(response.next_page_token); - if (token.length > 4096 || tokens.has(token)) throw new Error("invalid OSV pagination"); - tokens.add(token); - } - throw new Error("OSV pagination budget exceeded; complete result unavailable"); - }); - if (!loaded) return; - for (const value of array(JSON.parse(loaded.raw))) { - const row = object(value); - if (row.withdrawn !== undefined && date(row.withdrawn) <= sources.now) continue; - const aliases = row.aliases === undefined ? [] : array(row.aliases, 64); - const id = aliases.find((alias) => typeof alias === "string" && /^CVE-\d{4}-\d{4,19}$/.test(alias)) ?? row.id; - const refs = row.references === undefined ? [] : array(row.references, 128).map((ref) => object(ref).url); - const specific = row.database_specific === undefined ? {} : object(row.database_specific); - result.add(id, row.summary ?? "Published vulnerability affecting this exact runtime version", "applicable", specific.severity, refs); - } -} - -async function github(identity: RuntimeIdentity, sources: Sources, result: Assessment, repo: string, knownNames: string[], completeAuthority = true, components: Map | null = null) { - const url = `https://api.github.com/repos/${repo}/security-advisories`; - - const loaded = await sources.read(`ghsa:${repo}`, `${repo} publisher advisories`, url, async (previous) => { - const rows: unknown[] = [], ids = new Set(); - let bytes = 2; - let etag: string | null = null; - - for (let page = 1; page <= 20; page++) { - const pageUrl = `${url}?per_page=100&page=${page}`; - const etagToCheck = page === 1 && previous?.revision && array(JSON.parse(previous.raw)).length < 100 ? previous.revision : null; - const response = await sources.response(pageUrl, etagToCheck ? { headers: { "If-None-Match": etagToCheck } } : {}); - - if (response.status === 304 && etagToCheck && previous) return { ...previous, complete: true }; - - if (response.status !== 200) throw await sources.failure(response, pageUrl); - - if (page === 1) etag = response.headers.get("etag"); - - const batch = array(JSON.parse(await boundedBody(response.body, SOURCE_BYTES)), 100); - for (const value of batch) { - const row = object(value), id = findingId(row.ghsa_id); - if (ids.has(id)) throw new Error("duplicate publisher advisory across pages"); - bytes += new TextEncoder().encode(JSON.stringify(row)).length + 1; - if (bytes > SOURCE_BYTES) throw new Error("publisher paginated source exceeds limit"); - ids.add(id); rows.push(row); - } - - if (batch.length < 100) return { raw: JSON.stringify(rows.sort((a, b) => string(object(a).ghsa_id).localeCompare(string(object(b).ghsa_id)))), revision: page === 1 ? etag : null, complete: true }; - } - throw new Error("publisher advisory pagination budget exceeded"); - }); - if (!loaded) return; - if (!completeAuthority) result.gap(`${repo} has no established complete runtime applicability feed; empty publisher results are not clean coverage`); - for (const value of array(JSON.parse(loaded.raw))) { - const row = object(value); - if (row.withdrawn_at !== null && row.withdrawn_at !== undefined && date(row.withdrawn_at) <= sources.now) continue; - const entries = array(row.vulnerabilities, 256).map(object); - const hasRuntimeEntry = entries.some((entry) => knownNames.includes(string(object(entry.package).name))); - let applicable = false, possible = entries.length === 0; - if (possible) result.gap(`${repo} published an advisory without vulnerability applicability entries`); - for (const entry of entries) { - const packageRow = object(entry.package), name = string(packageRow.name); - const componentVersion = components?.get(name); - if (!knownNames.includes(name) && !componentVersion) { - if (identity.runtime === "erlang" && hasRuntimeEntry) continue; - possible = true; result.gap(`${repo} declares a component whose installed version is not established`); continue; - } - const assessedVersion = componentVersion ?? identity.version; - let match = identity.runtime === "erlang" ? numericRange(assessedVersion, entry.vulnerable_version_range) : semverMatch(assessedVersion, entry.vulnerable_version_range); - const fixes = typeof entry.patched_versions === "string" ? entry.patched_versions.split(",").map((item) => item.trim()).filter(Boolean) : []; - if (identity.runtime === "erlang") { - const version = numeric(assessedVersion); - if (!version) match = null; - const branch = fixes.filter((fix) => numeric(fix)?.[0] === version?.[0] && (!componentVersion || numeric(fix)?.[1] === version?.[1])); - if (branch.some((fix) => { const order = numericCompare(assessedVersion, fix); return order !== null && order >= 0; })) match = false; - if (match === true && fixes.length && !branch.length && version && fixes.every((fix) => (numeric(fix)?.[0] ?? Infinity) < (version[0] ?? 0))) match = null; - } else if (identity.runtime === "php" && fixes.length) { - const selected = numeric(identity.version), parsedFixes = fixes.map(numeric); - const same = parsedFixes.some((fix) => fix && selected && fix[0] === selected[0] && fix[1] === selected[1]); - const hasSameBranchEntry = entries.some((other) => typeof other.patched_versions === "string" && other.patched_versions.split(",").some((fix) => { const parts = numeric(fix.trim()); return parts && selected && parts[0] === selected[0] && parts[1] === selected[1]; })); - if (hasSameBranchEntry && !same) continue; - if (!same && match === true) match = null; - } - if (match === true) applicable = true; - if (match === null) { possible = true; result.gap(`${repo} has unsupported or ambiguous branch/component applicability`); } - } - if (applicable || possible) result.add(row.cve_id ?? row.ghsa_id, row.summary ?? "Published runtime security advisory", applicable && completeAuthority ? "applicable" : "possible", row.severity, [row.html_url, url]); - } -} - -function rubyMatch(version: string, requirement: unknown): boolean | null { - if (typeof requirement !== "string" || !requirement.trim() || requirement.length > 2048 || requirement.split(",").length > 16) return null; - try { return new RubyRequirement(...requirement.split(",")).isSatisfiedBy(new RubyVersion(version)); } - catch { return null; } -} -function versionLists(version: string, value: unknown, ruby = false): { matched: boolean; unsupported: boolean } { - let matched = false, unsupported = false; - for (const requirement of value === undefined ? [] : array(value, 64)) { - const result = ruby ? rubyMatch(version, requirement) : semverMatch(version, requirement); - if (result === true) matched = true; - if (result === null) unsupported = true; - } - return { matched, unsupported }; -} -async function ruby(identity: RuntimeIdentity, sources: Sources, result: Assessment) { - const parse = (raw: string) => { - const document = parseDocument(raw, { uniqueKeys: true, schema: "core" }); - if (document.errors.length || document.warnings.length) throw new Error("unsupported Ruby advisory YAML"); - const row = object(document.toJS({ maxAliasCount: 0 })); - versionLists(identity.version, row.patched_versions, true); versionLists(identity.version, row.unaffected_versions, true); - return row; - }; - const loaded = await sources.archive("ruby:mri", "RubySec MRI interpreter advisories", "rubysec/ruby-advisory-db", "master", /^rubies\/ruby\/[A-Za-z0-9_.-]+\.ya?ml$/, parse); - if (!loaded) return; - for (const file of array(JSON.parse(loaded.raw))) { - const row = parse(string(object(file).raw)); - const patched = versionLists(identity.version, row.patched_versions, true); - const unaffected = versionLists(identity.version, row.unaffected_versions, true); - if (patched.matched || unaffected.matched) continue; - const uncertain = patched.unsupported || unaffected.unsupported; - if (uncertain) result.gap("MRI advisory contains an unsupported Ruby version requirement"); - const stem = string(object(file).path).split("/").at(-1)?.replace(/\.ya?ml$/, ""); - const id = row.cve === undefined ? row.ghsa === undefined ? `RUBY-CORE-${stem}` : `GHSA-${string(row.ghsa).replace(/^GHSA-/, "")}` : `CVE-${string(row.cve).replace(/^CVE-/, "")}`; - result.add(id, row.title ?? "MRI interpreter advisory", uncertain ? "possible" : "applicable", null, [row.url, loaded.receipt.url]); - } - result.gap("MRI interpreter records do not establish the versions of every gem bundled by a prebuilt Ruby distribution"); -} -async function rust(identity: RuntimeIdentity, sources: Sources, result: Assessment) { - const parse = (raw: string) => { - const block = /^```toml\r?\n([\s\S]*?)\r?\n```/.exec(raw); - if (!block?.[1]) throw new Error("invalid Rust toolchain advisory TOML fence"); - const document = object(parseToml(block[1])); - const advisory = object(document.advisory), versions = object(document.versions); - findingId(advisory.id); versionLists(identity.version, versions.patched); versionLists(identity.version, versions.unaffected); - return { block, advisory, versions }; - }; - const loaded = await sources.archive("rust:components", "RustSec toolchain component advisories", "rustsec/advisory-db", "main", /^rust\/(?:std|cargo|rustdoc)\/[A-Za-z0-9_.-]+\.md$/, parse); - if (!loaded) return; - for (const value of array(JSON.parse(loaded.raw))) { - const raw = string(object(value).raw); - const { block, advisory, versions } = parse(raw); - if (advisory.withdrawn !== undefined) { - const withdrawn = advisory.withdrawn instanceof Date ? advisory.withdrawn.toISOString() : `${string(advisory.withdrawn)}T00:00:00Z`; - if (date(withdrawn) <= sources.now) continue; - } - const patched = versionLists(identity.version, versions.patched); - const unaffected = versionLists(identity.version, versions.unaffected); - if (patched.matched || unaffected.matched) continue; - const heading = raw.slice(block[0].length).split(/\r?\n/).find((line) => line.startsWith("# "))?.slice(2) ?? "Rust toolchain component vulnerability"; - const uncertain = patched.unsupported || unaffected.unsupported; - if (uncertain) result.gap("Rust toolchain component has an unsupported release range"); - result.add(advisory.id, heading, uncertain ? "possible" : "applicable", typeof advisory.cvss === "string" ? advisory.cvss : null, [advisory.url, loaded.receipt.url]); - } - result.gap("RustSec toolchain component records are supplemental; complete compiler and bundled-tool applicability is not established by this source"); -} - -type CveState = "affected" | "unaffected" | "unknown"; -type DotnetComponents = { sdk: string; runtime: string; aspnet: string | null }; -function cveState(payload: unknown, selected: RuntimeIdentity, dotnet?: DotnetComponents): CveState { - const parsed = parseCve(JSON.stringify(payload)); - if (parsed.state === "REJECTED") return "unaffected"; - if (!parsed.supported) return "unknown"; - const cna = object(object(object(payload).containers).cna); - const rows = cna.affected === undefined ? [] : array(cna.affected, 256); - let matchedProduct = false, affected = false, unknown = false; - for (const item of rows) { - const row = object(item); - const vendor = typeof row.vendor === "string" ? row.vendor.toLowerCase() : ""; - const product = typeof row.product === "string" ? row.product.toLowerCase() : ""; - const productMatches = selected.runtime === "python" - ? ["python software foundation", "psf", "python"].includes(vendor) && ["python", "cpython"].includes(product) - : selected.runtime === "dotnet" ? vendor === "microsoft" && /^(?:\.net|\.net core|asp\.net core|asp\.net|microsoft \.net)/.test(product) - : false; - if (!productMatches) continue; - matchedProduct = true; - const assessedVersion = dotnet ? product.includes("sdk") ? dotnet.sdk : product.includes("asp.net") || product.includes("aspnet") ? dotnet.aspnet : dotnet.runtime : selected.version; - if (assessedVersion === null) { unknown = true; continue; } - let status: CveState = row.defaultStatus === "affected" ? "affected" : row.defaultStatus === "unaffected" ? "unaffected" : "unknown"; - let explicit: CveState | null = null; - for (const versionValue of row.versions === undefined ? [] : array(row.versions, 256)) { - const version = object(versionValue), first = string(version.version); - let matches: boolean | null; - const lower = first === "*" ? 0 : numericCompare(assessedVersion, first); - if (version.lessThan !== undefined || version.lessThanOrEqual !== undefined) { - if (!["python", "semver", "custom"].includes(string(version.versionType))) { unknown = true; continue; } - const upper = numericCompare(assessedVersion, string(version.lessThan ?? version.lessThanOrEqual)); - matches = lower === null || upper === null ? null : lower >= 0 && (version.lessThan !== undefined ? upper < 0 : upper <= 0); - } else matches = first === "*" ? true : lower === null ? null : lower === 0; - if (matches === null) { unknown = true; continue; } - if (!matches) continue; - let current: CveState = version.status === "affected" ? "affected" : version.status === "unaffected" ? "unaffected" : "unknown"; - let previousChange: string | null = null; - for (const changeValue of version.changes === undefined ? [] : array(version.changes, 256)) { - const change = object(changeValue), at = string(change.at), order = numericCompare(assessedVersion, at); - if (order === null) { current = "unknown"; break; } - if (previousChange !== null && numericCompare(at, previousChange) !== 1) { current = "unknown"; break; } - previousChange = at; - if (order >= 0) current = change.status === "affected" ? "affected" : change.status === "unaffected" ? "unaffected" : "unknown"; - } - if (explicit !== null && explicit !== current) { unknown = true; current = "unknown"; } - explicit = current; - } - if (explicit !== null) status = explicit; - if (status === "affected") affected = true; - if (status === "unknown") unknown = true; - } - return affected ? "affected" : !matchedProduct || unknown ? "unknown" : "unaffected"; -} - -async function indexedCvePayload(sources: Sources, id: string, indexed: Map) { - const saved = indexed.get(id); - - if (saved && await sha256(saved.payload_raw) === saved.payload_sha256) { - const record = parseCve(saved.payload_raw, id); - - if (record.supported) return record.payload; - } - - for (const url of [cveUrl(id), cveServicesUrl(id)]) { - try { - const payload = await sources.json(url, { signal: AbortSignal.timeout(4_000) }, 1024 * 1024); - const parsed = parseCve(JSON.stringify(payload), id); - - if (parsed.supported) return payload; - } catch { - sources.signal.throwIfAborted(); - } - } - - throw new Error("authoritative CVE record unavailable"); -} - -async function cveRecords(sources: Sources, result: Assessment, ids: string[]) { - const allIds = [...new Set(ids.map(cveId))].sort(); - const chosen = allIds.slice(0, 512); - const key = `cve5:${await sha256(chosen.join("\n"))}`; - const loaded = await sources.read(key, "CVEProject vendor applicability records", "https://github.com/CVEProject/cvelistV5", async (previous) => { - const records: Record = previous ? object(JSON.parse(previous.raw)) : {}; - let bytes = new TextEncoder().encode(JSON.stringify(records)).length; - let failures = allIds.length - chosen.length; - const checkpoint = sources.store.sql.inlinePayloads ? await sources.store.checkpoint("cve") : null; - - const liveIndex = checkpoint?.complete && checkpoint.bootstrap_complete && !checkpoint.error && checkpoint.checked_at && - checkpoint.checked_at <= sources.now && Date.parse(sources.now) - Date.parse(checkpoint.checked_at) < SOURCE_TTL; - - for (let start = 0; start < chosen.length; start += 8) { - const batch = chosen.slice(start, start + 8); - - const stored = liveIndex ? await sources.store.sql.all<{ id: string; payload_raw: string; payload_sha256: string }>( - `SELECT id,payload_raw,payload_sha256 FROM source_record WHERE supported=1 AND payload_raw IS NOT NULL AND id IN (${batch.map(() => "?").join(",")})`, - batch, - ) : []; - - const indexed = new Map(stored.map(row => [row.id, row])); - const outcomes = await Promise.allSettled(batch.map(async (id) => ({ id, payload: await indexedCvePayload(sources, id, indexed) }))); - for (const outcome of outcomes) { - if (outcome.status === "fulfilled") { - const { id, payload } = outcome.value; - const removed = records[id] === undefined ? 0 : new TextEncoder().encode(JSON.stringify(records[id])).length; - const added = new TextEncoder().encode(JSON.stringify(payload)).length + (records[id] === undefined ? id.length + 4 : 0); - if (bytes - removed + added > SOURCE_BYTES - 2) failures++; - else { records[id] = payload; bytes += added - removed; } - } else failures++; - } - if (sources.signal.aborted) { failures += chosen.length - start - batch.length; break; } - } - const raw = JSON.stringify(Object.fromEntries(Object.entries(records).sort(([a], [b]) => a.localeCompare(b)))); - return failures ? { raw, revision: null, complete: false, gap: `CVEProject applicability lookup is incomplete (${failures} records unavailable or over budget)` } : { raw, revision: null, complete: true }; - }); - if (!loaded) { result.gap("Vendor CVE applicability records are unavailable"); return {}; } - return object(JSON.parse(loaded.raw)); -} -async function python(identity: RuntimeIdentity, sources: Sources, result: Assessment) { - const loaded = await sources.archive("python:psf", "PSF CPython advisories", "psf/advisory-database", "main", /^advisories\/python\/[A-Za-z0-9_.-]+\.json$/, (raw) => { - const row = object(JSON.parse(raw)); findingId(row.id); - if (row.aliases !== undefined) array(row.aliases, 64); - }); - if (!loaded) return; - const records = array(JSON.parse(loaded.raw)).map((file) => object(JSON.parse(string(object(file).raw)))); - const ids = records.flatMap((row) => row.aliases === undefined ? [] : array(row.aliases, 64).filter((id): id is string => typeof id === "string" && /^CVE-\d{4}-\d{4,19}$/.test(id))); - const cves = await cveRecords(sources, result, ids); - for (const row of records) { - if (row.withdrawn !== undefined && date(row.withdrawn) <= sources.now) continue; - const aliases = row.aliases === undefined ? [] : array(row.aliases, 64); - const refs = row.references === undefined ? [] : array(row.references, 128).map((value) => object(value).url); - const ids = aliases.filter((item): item is string => typeof item === "string" && /^CVE-\d{4}-\d{4,19}$/.test(item)); - for (const id of ids.length ? ids : [string(row.id)]) { - const state = cves[id] !== undefined ? cveState(cves[id], identity) : "unknown"; - if (state === "unaffected") continue; - if (state === "unknown") result.gap("Some CPython records have Git-only or unsupported version applicability; no package-name substitution was made"); - result.add(id, row.summary ?? "Published CPython advisory", state === "affected" ? "applicable" : "possible", null, refs); - } - } - result.gap("CPython core advisories do not establish complete applicability for libraries bundled by python-build-standalone"); -} - -async function erlang(identity: RuntimeIdentity, sources: Sources, result: Assessment) { - const url = "https://raw.githubusercontent.com/erlang/otp/master/otp_versions.table"; - const loaded = await sources.textSource("erlang:component-versions", "Erlang OTP component release table", url); - let components: Map | null = null; - if (loaded) { - const raw = string(object(JSON.parse(loaded.raw)).text); - const prefix = `OTP-${identity.version} `; - const lines = raw.split(/\r?\n/).filter((line) => line.startsWith(prefix)); - if (lines.length === 1) { - const line = lines[0]; - if (line === undefined) throw new Error("missing OTP release row"); - const data = line.slice(prefix.length).replace(/^\s*:\s*/, "").replace(/:\s*$/, "").replace(/#/g, " "); - components = new Map(); - for (const entry of data.trim().split(/\s+/)) { - const match = /^([a-z][a-z0-9_]*)-(\d+(?:\.\d+){0,3})$/.exec(entry); - if (!match?.[1] || !match[2] || components.has(match[1])) throw new Error("invalid OTP component version row"); - components.set(match[1], match[2]); - } - } else result.gap("Exact OTP release is absent or ambiguous in the component table"); - } - await github(identity, sources, result, "erlang/otp", ["OTP", "Erlang/OTP"], true, components); -} - -async function dotnet(identity: RuntimeIdentity, sources: Sources, result: Assessment) { - const parts = numeric(identity.version); - if (!parts || parts.length !== 3) { result.gap("Exact .NET SDK release identity is unresolved"); return; } - const channel = `${parts[0]}.${parts[1]}`; - const url = `https://builds.dotnet.microsoft.com/dotnet/release-metadata/${channel}/releases.json`; - const loaded = await sources.jsonSource(`dotnet:${channel}`, "Microsoft .NET SDK and runtime release metadata", url, (value) => { - const row = object(value); - if (row["channel-version"] !== channel) throw new Error(".NET release channel mismatch"); - array(row.releases, 2048); - }); - if (!loaded) return; - const payload = object(JSON.parse(loaded.raw)); - if (payload["channel-version"] !== channel) throw new Error(".NET release channel mismatch"); - const releases = array(payload.releases, 2048).map(object); - const selected = releases.filter((release) => { - const sdks = [...(release.sdk === undefined ? [] : [release.sdk]), ...(release.sdks === undefined ? [] : array(release.sdks, 128))]; - return sdks.some((sdk) => object(sdk).version === identity.version); - }); - if (selected.length !== 1) { result.gap("Exact .NET SDK has no unique upstream SDK-to-component release mapping"); return; } - const release = selected[0]; - if (!release) throw new Error("missing selected .NET release"); - const components: DotnetComponents = { sdk: identity.version, runtime: string(object(release.runtime).version), aspnet: release.aspnetcore === undefined ? null : string(object(release.aspnetcore).version) }; - if (!valid(components.runtime) || (components.aspnet !== null && !valid(components.aspnet))) throw new Error("invalid .NET component release identity"); - const later = releases.filter((row) => { - if (typeof row["release-date"] === "string" && string(row["release-date"]) > sources.now.slice(0, 10)) { result.gap(".NET metadata includes a future release"); return false; } - const sdks = [...(row.sdk === undefined ? [] : [row.sdk]), ...(row.sdks === undefined ? [] : array(row.sdks, 128))]; - const candidates: [string | null, string | null][] = [ - [row.runtime === undefined ? null : string(object(row.runtime).version), components.runtime], - [row.aspnetcore === undefined ? null : string(object(row.aspnetcore).version), components.aspnet], - ...sdks.map((sdk): [string, string] => [string(object(sdk).version), components.sdk]), - ]; - let advances = false; - for (const [version, installed] of candidates) { - if (version === null || installed === null) continue; - if (!valid(version)) result.gap(".NET metadata contains unsupported component versions"); - else if (compare(version, installed) > 0) advances = true; - } - return advances; - }); - const ids: string[] = []; - for (const row of later) { - const cves = row["cve-list"] === undefined ? [] : array(row["cve-list"], 256); - for (const item of cves) ids.push(cveId(object(item)["cve-id"])); - if (row.security === true && !cves.length) { - result.gap("Microsoft marks a later release as security-related without machine-readable CVE identifiers"); - result.add(`DOTNET-SECURITY-${string(row["release-version"])}`, "Microsoft published a later security release without CVE applicability identifiers", "possible", null, [url]); - } - } - const cves = await cveRecords(sources, result, ids); - for (const id of [...new Set(ids)]) { - const state = cves[id] === undefined ? "unknown" : cveState(cves[id], identity, components); - if (state === "unaffected") continue; - if (state === "unknown") result.gap("Some Microsoft security fixes lack exact SDK/runtime/component applicability; release-list membership alone is not proof of an affected version"); - result.add(id, ".NET security fix published after the selected SDK or one of its bundled components", state === "affected" ? "applicable" : "possible", null, [url]); - } -} - -async function java(identity: RuntimeIdentity, sources: Sources, result: Assessment) { - const version = identity.version.split("+")[0] ?? ""; - if ((numeric(version)?.length ?? 0) < 3) { result.gap("Temurin requires an exact upstream patch/build identity; a Java feature number does not establish applicability"); return; } - const url = "https://api.github.com/repos/adoptium/temurin-vdr-generator/releases/latest"; - const loaded = await sources.read("java:temurin-vdr", "Eclipse Adoptium Temurin vulnerability disclosure report", url, async (previous) => { - const release = object(await sources.json(url)); - const revision = string(release.tag_name); - const assets = array(release.assets, 128).map(object).filter((asset) => /^temurin-vdr-[A-Za-z0-9_-]+\.json$/.test(string(asset.name))); - if (assets.length !== 1) throw new Error("Temurin VDR asset is missing or ambiguous"); - const asset = assets[0]; - if (!asset) throw new Error("missing Temurin VDR asset"); - const digest = string(asset.digest).replace(/^sha256:/, ""); - if (!/^[a-f0-9]{64}$/.test(digest) || typeof asset.size !== "number" || asset.size < 1 || asset.size > SOURCE_BYTES) throw new Error("invalid Temurin VDR asset bounds or digest"); - if (previous?.revision === revision && await sha256(previous.raw) === digest) return { ...previous, complete: true }; - let next = string(asset.browser_download_url); - if (!next.startsWith("https://github.com/adoptium/temurin-vdr-generator/releases/download/")) throw new Error("invalid Temurin VDR download origin"); - let raw: string | null = null; - for (let redirects = 0; redirects <= 3; redirects++) { - const response = await sources.response(next); - if (response.status === 200) { raw = await boundedBody(response.body, SOURCE_BYTES); break; } - if (![301, 302, 303, 307, 308].includes(response.status)) { await response.body?.cancel(); throw new Error(`Temurin VDR HTTP ${response.status}`); } - const location = response.headers.get("location"); await response.body?.cancel(); - if (!location) throw new Error("missing Temurin VDR redirect"); - const redirect = new URL(location, next); - if (!["release-assets.githubusercontent.com", "objects.githubusercontent.com"].includes(redirect.hostname)) throw new Error("unapproved Temurin VDR redirect"); - next = redirect.href; - } - if (raw === null || new TextEncoder().encode(raw).length !== asset.size || await sha256(raw) !== digest) throw new Error("Temurin VDR bytes do not match the official asset"); - return { raw, revision, complete: true }; - }); - if (!loaded) return; - const payload = object(JSON.parse(loaded.raw)); - if (payload.bomFormat !== "CycloneDX" || !["1.4", "1.5", "1.6", "1.7"].includes(string(payload.specVersion)) || object(object(payload.metadata).component).name !== "Eclipse Temurin") - throw new Error("invalid Temurin vulnerability disclosure report"); - for (const value of array(payload.vulnerabilities)) { - const row = object(value); - let affected = false, possible = false; - for (const item of row.affects === undefined ? [] : array(row.affects, 128)) { - const target = object(item); - if (target.ref !== "pkg:github/openjdk/jdk") { possible = true; continue; } - for (const entry of target.versions === undefined ? [] : array(target.versions, 256)) { - const range = object(entry); - if (typeof range.range !== "string" || !range.range.startsWith("vers:generic/")) { possible = true; continue; } - const versions = range.range.slice("vers:generic/".length).split("|"); - if (versions.length > 128) throw new Error("Temurin VDR version list exceeds limit"); - for (const declared of versions) { - const oldJava = /^8u(\d+)$/.exec(declared); - const candidate = oldJava?.[1] ? `8.0.${oldJava[1]}` : declared; - const order = numericCompare(version, candidate); - if (order === 0) affected = true; - else if (order !== null && order < 0 && numeric(version)?.[0] === numeric(candidate)?.[0]) possible = true; - else if (order === null) possible = true; - } - } - } - if (row.affects === undefined || array(row.affects, 128).length === 0) possible = true; - if (affected || possible) { - const source = row.source === undefined ? {} : object(row.source); - result.add(row.id, row.description ?? "Temurin/OpenJDK published vulnerability", affected ? "applicable" : "possible", null, [source.url, url]); - } - } - result.gap("Temurin VDR enumerates affected upstream releases; omitted builds, older branch versions and bundled components are not established as unaffected"); -} - -export async function refreshRuntime(input: unknown, store: Store, now: string, fetcher: Fetcher) { - const body = object(input); - if (Object.keys(body).sort().join(",") !== "github_token,runtime") throw new Error("invalid runtime refresh fields"); - const runtime = runtimeName(string(body.runtime)); - const token = body.github_token; - if (!isGitHubInstallationToken(token)) throw new Error("invalid ephemeral GitHub installation token"); - - return refreshRuntimeProfile(runtime, store, now, fetcher, token); -} - -export async function refreshRuntimeProfile(runtime: Runtime, store: Store, now: string, fetcher: Fetcher, token?: string) { - let version: string, sourceUrl: string; - switch (runtime) { - case "python": version = "3.12.14"; sourceUrl = "https://github.com/psf/advisory-database/tree/main"; break; - case "rust": version = "1.85.0"; sourceUrl = "https://github.com/rustsec/advisory-db/tree/main"; break; - case "ruby": version = "3.3.0"; sourceUrl = "https://github.com/rubysec/ruby-advisory-db/tree/master"; break; - case "java": version = "21.0.1+12"; sourceUrl = "https://api.github.com/repos/adoptium/temurin-vdr-generator/releases/latest"; break; - case "bun": version = "1.1.0"; sourceUrl = "https://api.github.com/repos/oven-sh/bun/security-advisories"; break; - case "deno": version = "1.40.0"; sourceUrl = "https://api.github.com/repos/denoland/deno/security-advisories"; break; - case "zig": version = "0.13.0"; sourceUrl = "https://api.github.com/repos/ziglang/zig/security-advisories"; break; - case "erlang": version = "27.0"; sourceUrl = "https://api.github.com/repos/erlang/otp/security-advisories"; break; - case "php": version = "8.3.0"; sourceUrl = "https://api.github.com/repos/php/php-src/security-advisories"; break; - case "swift": version = "5.10.0"; sourceUrl = "https://api.github.com/repos/swiftlang/swift/security-advisories"; break; - default: throw new Error("invalid runtime refresh selector"); - } - const approved = new Set([ - "/repos/psf/advisory-database/commits/main", "/repos/rustsec/advisory-db/commits/main", - "/repos/rubysec/ruby-advisory-db/commits/master", "/repos/adoptium/temurin-vdr-generator/releases/latest", - "/repos/oven-sh/bun/security-advisories", "/repos/denoland/deno/security-advisories", - "/repos/ziglang/zig/security-advisories", "/repos/erlang/otp/security-advisories", - "/repos/php/php-src/security-advisories", "/repos/swiftlang/swift/security-advisories", - ]); - const authenticated: Fetcher = (url, init = {}) => { - const target = new URL(url), headers = new Headers(init.headers); - headers.delete("authorization"); - - if (token && target.origin === "https://api.github.com") { - if (target.username || target.password || !approved.has(target.pathname) || (init.method ?? "GET") !== "GET") - throw new Error("invalid authenticated source request"); - headers.set("Authorization", `Bearer ${token}`); - } - return fetcher(url, { ...init, headers, redirect: "manual" }); - }; - const url = new URL(`https://advisories.invalid/v1/runtimes/${runtime}`); - url.search = new URLSearchParams({ vendor: VENDORS[runtime], version, os: "linux", arch: "x86_64" }).toString(); - const report = await runtimeReport(url, store, now, authenticated, true, token, true); - const refreshed = report.sources.some((source) => source.url === sourceUrl) && report.sources.every((source) => source.complete) && - !report.gaps.some((gap) => gap.startsWith("Runtime evidence could not be established") || gap.includes("refresh failed") || gap.includes("refresh is already in progress")); - return { schema_version: 1, runtime, refreshed, coverage: report.coverage, checked_at: report.checked_at, sources: report.sources, gaps: report.gaps }; -} - -export async function runtimeReport(url: URL, store: Store, now: string, fetcher: Fetcher, force = false, credential?: string, trustedRefresh = false) { - const selected = identity(url); - date(now); - const result = new Assessment(); - const sources = new Sources(store, fetcher, now, force, result, credential, trustedRefresh); - if (selected.vendor !== VENDORS[selected.runtime]) result.gap(`Vendor mapping is not established; expected ${VENDORS[selected.runtime]} for ${selected.runtime}`); - else if (!valid(selected.version) && !(["java", "erlang"].includes(selected.runtime) && numeric(selected.version.split("+")[0] ?? ""))) - result.gap("Exact upstream runtime release identity is unresolved; aliases and unsupported version forms cannot establish applicability"); - else { - try { - switch (selected.runtime) { - case "node": await node(selected, sources, result); break; - case "go": await osv(selected, sources, result, "Go", "stdlib"); await osv(selected, sources, result, "Go", "toolchain"); break; - case "pi": await osv(selected, sources, result, "npm", "@earendil-works/pi-coding-agent"); break; - case "bun": await github(selected, sources, result, "oven-sh/bun", ["bun"]); break; - case "deno": await github(selected, sources, result, "denoland/deno", ["Deno", "deno"]); break; - case "erlang": await erlang(selected, sources, result); break; - case "php": await github(selected, sources, result, "php/php-src", ["PHP", "php", "php-src", "core", "ext-standard"]); break; - case "zig": await github(selected, sources, result, "ziglang/zig", ["Zig", "zig"], false); break; - case "swift": await github(selected, sources, result, "swiftlang/swift", ["Swift", "swift"], false); break; - case "python": await python(selected, sources, result); break; - case "rust": await rust(selected, sources, result); break; - case "ruby": await ruby(selected, sources, result); break; - case "java": await java(selected, sources, result); break; - case "dotnet": await dotnet(selected, sources, result); break; - default: { const exhaustive: never = selected.runtime; throw new Error(`unsupported runtime ${exhaustive}`); } - } - } catch (error) { result.gap(`Runtime evidence could not be established: ${error instanceof Error ? text(error.message, 200) : "source failure"}`); } - } - const receipts = [...result.sources.values()].sort((a, b) => a.name.localeCompare(b.name)); - if (!receipts.length && !result.gaps.size) result.gap("No authoritative source evidence was established"); - if (receipts.some((source) => !source.complete)) result.gap("One or more required source snapshots are incomplete or stale"); - const findings = [...result.findings.values()].sort((a, b) => a.id.localeCompare(b.id)); - const report = { schema_version: 1, identity: selected, - checked_at: receipts.reduce((oldest, source) => source.checked_at < oldest ? source.checked_at : oldest, now), - coverage: result.gaps.size ? findings.length ? "partial" : "unknown" : "assessed", - findings, gaps: [...result.gaps].sort(), sources: receipts }; - if (new TextEncoder().encode(JSON.stringify(report)).length > 2 * 1024 * 1024) throw new Error("runtime report exceeds limit"); - return report; -} diff --git a/services/advisories/src/service.ts b/services/advisories/src/service.ts deleted file mode 100644 index e684e395d..000000000 --- a/services/advisories/src/service.ts +++ /dev/null @@ -1,834 +0,0 @@ -import { packageAdvisories } from "./package-advisories"; -import { - LIMITS, - SOURCES, - boundedBody, - cveId, - object, - date, - parseCve, - sha256, -} from "./domain"; -import { ingestCveGroups, parseBatch, refreshSource } from "./ingestion"; -import { Store, type Checkpoint, type RecordRow } from "./storage"; -import { firstPageSize, recentCves, recentPage, recentWindowStart } from "./recent"; -import { epss } from "./epss"; -import { runtimeReport, refreshRuntime } from "./runtime"; -import { type Fetcher } from "./ingestion"; -import { publicResponse } from "./cache"; -import { BaselineBusyError, baselineImportCommands, verifyBaseline } from "./baseline"; -import { PACKAGE_ASSESSMENT_PATH, assessPackages } from "./package-assessment"; -import { readDeltaCursor } from "./delta"; -import { nvdReconciliationStatus } from "./nvd"; -async function authorized( - request: Request, - token: string | undefined, -): Promise { - if (!token || token.length < 32) return false; - const provided = - request.headers.get("authorization")?.replace(/^Bearer /, "") ?? ""; - if (provided.length > 1024) return false; - const encoder = new TextEncoder(); - const algorithm = { name: "HMAC", hash: "SHA-256" }; - const expected = await crypto.subtle.importKey( - "raw", - encoder.encode(token), - algorithm, - false, - ["verify"], - ); - const supplied = await crypto.subtle.importKey( - "raw", - encoder.encode(provided || "missing"), - algorithm, - false, - ["sign"], - ); - const message = encoder.encode("omg-advisories-ingest-v1"); - const signature = await crypto.subtle.sign("HMAC", supplied, message); - return crypto.subtle.verify("HMAC", expected, signature, message); -} -type BaselineSession = { - digest: string; - instance_id: string; - session_id: string; - endpoint: string; - baseline_at: string; -}; -async function baselineSession( - store: Store, - binding: Record, - endpoint: string, -): Promise { - const row = await store.sql.first( - "SELECT * FROM baseline_receipt WHERE digest=?", - [typeof binding.digest === "string" ? binding.digest : ""], - ); - const active = await store.checkpoint("cve"); - if ( - !row || - row.instance_id !== binding.instance_id || - row.session_id !== binding.session_id || - row.endpoint !== endpoint || - binding.endpoint !== endpoint || - active?.baseline_digest !== row.digest - ) - throw new Error("invalid baseline session binding"); - return row; -} -function fresh(checkpoint: Pick, now: string) { - return ( - checkpoint.checked_at !== null && - Date.parse(now) - Date.parse(checkpoint.checked_at) <= 30 * 60_000 - ); -} - -function deltaStatus(checkpoint: Pick | undefined, now: string) { - let cursor = null; - let completed = null; - - try { - if (checkpoint?.cursor) cursor = readDeltaCursor(checkpoint.cursor); - - if (checkpoint?.revision) completed = readDeltaCursor(checkpoint.revision); - } catch { - return { - state: "error", - checked_at: checkpoint?.checked_at ?? null, - completed_through: completed?.event ?? null, - completed_offset: completed?.offset ?? null, - cursor_event: cursor?.event ?? null, - cursor_offset: cursor?.offset ?? null, - }; - } - - const checked = checkpoint?.checked_at ?? null; - - const state = checkpoint?.error ? "error" : - checked === null ? "unavailable" : - Date.parse(checked) > Date.parse(now) || !fresh({ checked_at: checked }, now) ? "stale" : - checkpoint?.complete ? "caught_up" : "catching_up"; - - return { - state, - checked_at: checked, - completed_through: completed?.event ?? null, - completed_offset: completed?.offset ?? null, - cursor_event: cursor?.event ?? null, - cursor_offset: cursor?.offset ?? null, - }; -} - -type FeedCheckpoint = Pick; - -type FeedProof = FeedCheckpoint & { - baseline_imported: number | null; - baseline_caught_up: number | null; - baseline_archive_verified: number; -}; - -const baselineFields = `r.accepted AS baseline_imported, r.caught_up AS baseline_caught_up, - CASE WHEN p.phase='verified' AND p.verified_at IS NOT NULL THEN 1 ELSE 0 END AS baseline_archive_verified`; - -const feedJoin = `FROM source_checkpoint c - LEFT JOIN baseline_receipt r ON c.source='cve' AND r.digest=c.baseline_digest - LEFT JOIN baseline_publisher_proof p ON p.session_id=r.session_id`; - -function isCurrent(checkpoint: Pick, now: string) { - return !!checkpoint.complete && !!checkpoint.bootstrap_complete && !checkpoint.error && fresh(checkpoint, now); -} - -function statusModel(checkpoints: readonly T[], now: string) { - const cve = checkpoints.find(checkpoint => checkpoint.source === "cve"); - - return { - schema_version: 1, - baseline: { - imported: cve?.baseline_imported ?? 0, - caught_up: cve?.baseline_caught_up === 1, - archive_verified: cve?.baseline_archive_verified === 1, - }, - bootstrap_complete: cve?.bootstrap_complete === 1, - feeds: checkpoints.map(({ baseline_imported: _count, baseline_caught_up: _caughtUp, baseline_archive_verified: _verified, ...checkpoint }) => ({ - ...checkpoint, - complete: isCurrent(checkpoint, now), - fresh: fresh(checkpoint, now), - })), - package_applicability: "Arch feed only; AUR mapping unknown", - }; -} - -type DashboardRevision = Pick; - -type DashboardRow = ({ kind: "feed" } & FeedProof) | ({ kind: "record" } & DashboardRevision); - -async function dashboardModel(store: Store, now: string) { - const rows = await store.sql.all( - `WITH recent AS ( - SELECT id, state, published_at, modified_at, fetched_at FROM source_record - WHERE modified_at>=? AND modified_at<=? - ORDER BY modified_at DESC, id DESC LIMIT ? - ) - SELECT 'record' AS kind, id, state, published_at, modified_at, fetched_at, - NULL AS source, NULL AS checked_at, NULL AS complete, NULL AS bootstrap_complete, - NULL AS error, NULL AS baseline_imported, NULL AS baseline_caught_up, NULL AS baseline_archive_verified - FROM recent - UNION ALL - SELECT 'feed', NULL, NULL, NULL, NULL, c.fetched_at, - c.source, c.checked_at, c.complete, c.bootstrap_complete, c.error, ${baselineFields} - ${feedJoin} - ORDER BY kind, modified_at DESC, id DESC, source`, - [recentWindowStart(now), now, firstPageSize + 1], - ); - - const feeds: FeedProof[] = []; - const records: DashboardRevision[] = []; - - for (const row of rows) { - if (row.kind === "record") { - const { id, state, published_at, modified_at, fetched_at } = row; - - records.push({ id, state, published_at, modified_at, fetched_at }); - } else { - const { source, checked_at, fetched_at, complete, bootstrap_complete, error, - baseline_imported, baseline_caught_up, baseline_archive_verified } = row; - - feeds.push({ source, checked_at, fetched_at, complete, bootstrap_complete, error, - baseline_imported, baseline_caught_up, baseline_archive_verified }); - } - } - - const cve = feeds.find(feed => feed.source === "cve"); - const status = statusModel(feeds, now); - - return { - status: { - ...status, - feeds: status.feeds.map(({ source, checked_at, fetched_at, complete, fresh, error }) => ({ - source, checked_at, fetched_at, complete, fresh, error, - })), - }, - recent: { - schema_version: 1, - ...recentPage(records, now, firstPageSize), - checked_at: cve?.checked_at ?? null, - complete: !!cve && isCurrent(cve, now), - package_applicability: "unknown", - }, - }; -} - -type PublicCveSummary = RecordRow & { - source: string; - cve_checked_at: string | null; - cve_complete: number | null; - cve_bootstrap_complete: number | null; - cve_error: string | null; - kev_payload_json: string | null; - kev_checked_at: string | null; - kev_complete: number | null; - kev_error: string | null; -}; - -async function cveSummary(store: Store, id: string, now: string): Promise { - const row = await store.sql.first( - `SELECT r.id, r.source, r.source_url, r.schema_version, r.state, r.published_at, - r.modified_at, r.fetched_at, r.payload_sha256, r.object_key, - r.normalization_version, r.supported, c.checked_at AS cve_checked_at, c.complete AS cve_complete, - c.bootstrap_complete AS cve_bootstrap_complete, c.error AS cve_error, - k.payload_json AS kev_payload_json, s.checked_at AS kev_checked_at, - s.complete AS kev_complete, s.error AS kev_error - FROM source_record r - LEFT JOIN source_checkpoint c ON c.source='cve' - LEFT JOIN kev_annotation k ON k.cve_id=r.id - LEFT JOIN source_checkpoint s ON s.source='kev' - WHERE r.id=?`, - [id], - ); - - if (!row) - return Response.json( - { error: "CVE unavailable", complete: false }, - { status: 404 }, - ); - - const { - cve_checked_at, cve_complete, cve_bootstrap_complete, cve_error, - kev_payload_json, kev_checked_at, kev_complete, kev_error, ...provenance - } = row; - - return Response.json({ - schema_version: 1, - provenance, - cve_checked_at, - cve_complete: !!cve_complete && !!cve_bootstrap_complete && !cve_error && - fresh({ checked_at: cve_checked_at }, now), - kev: kev_payload_json ? JSON.parse(kev_payload_json) : null, - kev_checked_at, - kev_complete: !!kev_complete && !kev_error && fresh({ checked_at: kev_checked_at }, now), - package_applicability: "unknown", - }); -} - -export async function handle( - request: Request, - store: Store, - token?: string, - now = new Date().toISOString(), - fetcher: Fetcher = (url, init) => fetch(url, init), - runtimeRefreshSecret?: string, - packageAssessmentToken?: string, -): Promise { - const url = new URL(request.url); - - if (url.pathname === PACKAGE_ASSESSMENT_PATH) { - let response: Response; - - if (!packageAssessmentToken || packageAssessmentToken.length < 32 || - packageAssessmentToken === token || packageAssessmentToken === runtimeRefreshSecret) { - response = Response.json({ error: "not found" }, { status: 404 }); - } else if (request.method !== "POST") { - response = Response.json({ error: "method not allowed" }, { status: 405, headers: { Allow: "POST" } }); - } else if (!request.headers.get("authorization")?.startsWith("Bearer ") || - !await authorized(request, packageAssessmentToken)) { - response = Response.json({ error: "unauthorized" }, { status: 401 }); - } else if (url.search || request.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() !== "application/json") { - response = Response.json({ error: "expected application/json and no query parameters" }, { status: 400 }); - } else { - response = await assessPackages(request, now, fetcher); - } - - response.headers.set("Cache-Control", "no-store"); - - return response; - } - - return publicResponse(request, await route(request, store, token, now, fetcher, runtimeRefreshSecret), now); -} - -async function route( - request: Request, - store: Store, - token: string | undefined, - now: string, - fetcher: Fetcher, - runtimeRefreshSecret: string | undefined, -): Promise { - const url = new URL(request.url); - try { - if (url.pathname === "/internal/cve-refresh") { - if (request.method !== "POST") return Response.json({ error: "method not allowed" }, { status: 405 }); - if (!await authorized(request, token)) return Response.json({ error: "unauthorized" }, { status: 401 }); - const input = object(JSON.parse(await boundedBody(request.body, 1024))); - if (Object.keys(input).length) throw new Error("invalid CVE refresh fields"); - if (!await refreshSource(store, "cve", fetcher, now, 32)) return Response.json({ error: "ingestion busy" }, { status: 409 }); - const checkpoint = await store.checkpoint("cve"); - if (!checkpoint) throw new Error("missing migration"); - return Response.json({ schema_version: 1, source: "cve", complete: !!checkpoint.complete && !checkpoint.error, - cursor: checkpoint.cursor, checked_at: checkpoint.checked_at, bootstrap_complete: checkpoint.bootstrap_complete === 1, - error: checkpoint.error }, { status: checkpoint.error ? 503 : 200 }); - } - if (url.pathname === "/internal/baseline/verify") { - if (request.method !== "POST") return Response.json({ error: "method not allowed" }, { status: 405 }); - if (!await authorized(request, runtimeRefreshSecret)) return Response.json({ error: "unauthorized" }, { status: 401 }); - const input: unknown = JSON.parse(await boundedBody(request.body, 4096)); - return Response.json(await verifyBaseline(input, store, url.origin, now, fetcher)); - } - if (url.pathname === "/internal/runtime-refresh") { - if (request.method !== "POST") return Response.json({ error: "method not allowed" }, { status: 405 }); - if (!await authorized(request, runtimeRefreshSecret)) return Response.json({ error: "unauthorized" }, { status: 401 }); - const input: unknown = JSON.parse(await boundedBody(request.body, 4096)); - return Response.json(await refreshRuntime(input, store, now, fetcher)); - } - if (url.pathname === "/internal/ingest") { - if (request.method !== "POST") - return Response.json( - { error: "method not allowed" }, - { status: 405 }, - ); - if (!(await authorized(request, token))) - return Response.json( - { error: "unauthorized" }, - { status: 401 }, - ); - const input = object( - JSON.parse(await boundedBody(request.body, LIMITS.batch)), - ); - const records = parseBatch(input, input.baseline === undefined ? LIMITS.records : 64); - const binding = - input.baseline === undefined ? null : object(input.baseline); - const owner = crypto.randomUUID(); - if (!(await store.lease("cve", owner, now))) - return Response.json( - { error: "ingestion busy" }, - { status: 409 }, - ); - try { - const writer = store.writer("cve", owner); - const baseline = binding - ? await baselineSession(writer, binding, url.origin) - : null; - const parsed = records.map((raw) => { - const record = parseCve(raw); - return { id: record.id, supported: record.supported, raw }; - }); - if (baseline && new Set(parsed.map((record) => record.id)).size === parsed.length && parsed.every((record) => record.supported)) { - const after = await baselineImportCommands(writer, baseline.session_id, parsed); - await writer.cveBatch(parsed, now, after, "packed"); - } else { - if (records.length > LIMITS.records) throw new Error("invalid duplicate or unsupported large ingest batch"); - await ingestCveGroups( - parsed, - async ({ id, raw }) => { - const after = baseline ? await baselineImportCommands(writer, baseline.session_id, [{ id, raw }]) : []; - await writer.cve(raw, now); - if (after.length) await writer.sql.batch(after); - }, - ); - } - } finally { - await store.release("cve", owner); - } - return Response.json({ accepted: records.length }); - } - if (url.pathname === "/internal/baseline/start") { - if (request.method !== "POST") - return Response.json( - { error: "method not allowed" }, - { status: 405 }, - ); - if (!(await authorized(request, token))) - return Response.json( - { error: "unauthorized" }, - { status: 401 }, - ); - const receipt = object( - JSON.parse(await boundedBody(request.body, 4096)), - ); - if ( - typeof receipt.digest !== "string" || - !/^[a-f0-9]{64}$/.test(receipt.digest) - ) - throw new Error("invalid baseline digest"); - const baseline = date(receipt.baseline_at); - const existing = await store.sql.first( - "SELECT * FROM baseline_receipt WHERE digest=?", - [receipt.digest], - ); - if (existing) { - await baselineSession( - store, - { - ...receipt, - instance_id: receipt.instance_id ?? existing.instance_id, - session_id: receipt.session_id ?? existing.session_id, - endpoint: receipt.endpoint ?? existing.endpoint, - }, - url.origin, - ); - return Response.json({ started: true, ...existing }); - } - if (receipt.instance_id !== undefined || receipt.session_id !== undefined) - throw new Error("invalid baseline resume instance"); - const instance = await store.sql.first<{ id: string }>( - "SELECT id FROM database_instance", - ); - if (!instance) throw new Error("missing database instance"); - const session = crypto.randomUUID(); - const owner = crypto.randomUUID(); - if (!(await store.lease("cve", owner, now))) - return Response.json( - { error: "ingestion busy" }, - { status: 409 }, - ); - try { - await store.writer("cve", owner).sql.batch([ - { - sql: "INSERT INTO baseline_receipt(digest,instance_id,session_id,endpoint,baseline_at,accepted,exhausted) VALUES(?,?,?,?,?,0,0)", - values: [receipt.digest, instance.id, session, url.origin, baseline], - }, - { - sql: "UPDATE source_checkpoint SET cursor=?,baseline_digest=?,complete=0,bootstrap_complete=0,error=NULL,etag=NULL,revision=NULL WHERE source=?", - values: [ - JSON.stringify({ event: baseline, offset: 0 }), - receipt.digest, - "cve", - ], - }, - ]); - } finally { - await store.release("cve", owner); - } - return Response.json({ - started: true, - digest: receipt.digest, - instance_id: instance.id, - session_id: session, - endpoint: url.origin, - }); - } - if (url.pathname === "/internal/baseline") { - if (request.method !== "POST") - return Response.json( - { error: "method not allowed" }, - { status: 405 }, - ); - if (!(await authorized(request, token))) - return Response.json( - { error: "unauthorized" }, - { status: 401 }, - ); - const receipt = object( - JSON.parse(await boundedBody(request.body, 4096)), - ); - if ( - typeof receipt.digest !== "string" || - !/^[a-f0-9]{64}$/.test(receipt.digest) || - !Number.isSafeInteger(receipt.accepted) || - typeof receipt.accepted !== "number" || - receipt.accepted < 1 || - receipt.exhausted !== true - ) - throw new Error("invalid baseline receipt"); - const baseline = date(receipt.baseline_at); - const finished = date(receipt.finished_at); - const started = await baselineSession(store, receipt, url.origin); - if (!started || started.baseline_at !== baseline) - throw new Error("invalid baseline receipt"); - const owner = crypto.randomUUID(); - if (!(await store.lease("cve", owner, now))) - return Response.json( - { error: "ingestion busy" }, - { status: 409 }, - ); - try { - await baselineSession(store, receipt, url.origin); - const checkpoint = await store.checkpoint("cve"); - if ( - !checkpoint?.complete || - checkpoint.baseline_digest !== receipt.digest || - !checkpoint.checked_at || - checkpoint.error || - !fresh(checkpoint, now) || - checkpoint.checked_at < finished || - !checkpoint.cursor - ) - throw new Error("delta catchup required"); - const cursor = object(JSON.parse(checkpoint.cursor)); - if (date(cursor.event) < baseline) - throw new Error("delta precedes baseline"); - const unsupported = await store.sql.first<{ count: number }>( - "SELECT COUNT(*) AS count FROM source_record WHERE supported=0", - ); - if (unsupported?.count) - throw new Error("unsupported records prevent completeness"); - const imported = await store.sql.first<{ - count: number; - accepted: number; - }>( - "SELECT COUNT(*) AS count,(SELECT accepted FROM baseline_receipt WHERE session_id=?) AS accepted FROM baseline_member WHERE session_id=?", - [started.session_id, started.session_id], - ); - if ( - !imported || - imported.count !== receipt.accepted || - imported.count !== imported.accepted - ) - throw new Error("invalid baseline member count"); - const proof = await store.sql.first<{ phase: string }>("SELECT phase FROM baseline_publisher_proof WHERE session_id=?", [started.session_id]); - const verified = proof?.phase === "verified"; - await store.writer("cve", owner).sql.batch([ - { - sql: "UPDATE baseline_receipt SET accepted=?,exhausted=1,caught_up=1,completed_at=? WHERE session_id=?", - values: [imported.count, now, started.session_id], - }, - { - sql: "UPDATE source_checkpoint SET bootstrap_complete=? WHERE source=?", - values: [Number(verified), "cve"], - }, - ]); - return Response.json({ - bootstrap_complete: verified, - archive_verified: verified, - imported: imported.count, - caught_up: true, - }); - } finally { - await store.release("cve", owner); - } - } - if (request.method === "POST" && url.pathname === "/v1/packages/audit") { - const raw = await boundedBody(request.body, 256 * 1024); - const body = object(JSON.parse(raw)); - const pkgs = Array.isArray(body.packages) ? body.packages : null; - if (!pkgs || pkgs.length === 0 || pkgs.length > 500) { - return Response.json({ error: "packages must be a non-empty array of up to 500 items" }, { status: 400 }); - } - const pairs: { ecosystem: string; name: string }[] = []; - for (const item of pkgs) { - const entry = object(item); - if (typeof entry.ecosystem !== "string" || typeof entry.name !== "string" || !entry.ecosystem.trim() || !entry.name.trim()) { - return Response.json({ error: "each package requires non-empty ecosystem and name" }, { status: 400 }); - } - pairs.push({ ecosystem: entry.ecosystem.trim().toLowerCase(), name: entry.name.trim().toLowerCase() }); - } - const rows = await packageAdvisories(store.sql, pairs, 1000); - return Response.json({ - schema_version: 1, - checked_at: now, - queried: pairs.length, - malware_count: rows.filter((r) => r.is_malware).length, - kev_count: rows.filter((r) => r.in_kev).length, - findings: rows, - }); - } - if (request.method !== "GET") - return Response.json( - { error: "method not allowed" }, - { status: 405 }, - ); - if (url.pathname === "/v1/packages/check") { - const ecosystem = (url.searchParams.get("ecosystem") ?? "").trim().toLowerCase(); - const name = (url.searchParams.get("name") ?? "").trim().toLowerCase(); - if (!ecosystem || !name || ecosystem.length > 64 || name.length > 256) { - return Response.json({ error: "ecosystem and name query parameters are required" }, { status: 400 }); - } - const rows = await packageAdvisories(store.sql, [{ ecosystem, name }], 200); - return Response.json({ - schema_version: 1, - checked_at: now, - ecosystem, - name, - malware: rows.some((r) => r.is_malware), - actively_exploited: rows.some((r) => r.in_kev || r.in_euvd), - advisories: rows, - }); - } - const eolMatch = /^\/v1\/eol(?:\/([a-z0-9-]+))?$/.exec(url.pathname); - if (eolMatch) { - const product = eolMatch[1]; - const cycles = product - ? await store.sql.all("SELECT product,cycle,eol,lts,latest,release_date,support,updated_at FROM runtime_eol WHERE product=? ORDER BY release_date DESC NULLS LAST, cycle DESC", [product]) - : await store.sql.all("SELECT product,cycle,eol,lts,latest,release_date,support,updated_at FROM runtime_eol ORDER BY product ASC, release_date DESC NULLS LAST"); - return Response.json({ - schema_version: 1, - checked_at: now, - product: product ?? "all", - cycles, - }); - } - - if (url.pathname === "/v1/reconciliation/nvd" && !url.search) { - return Response.json(await nvdReconciliationStatus(store, now), { - headers: { "Cache-Control": "no-store" }, - }); - } - if (url.pathname === "/v1/status") { - const checkpoints = await store.sql.all( - "SELECT * FROM source_checkpoint ORDER BY source", - ); - const baseline = await store.sql.first<{ - imported: number; - caught_up: number; - archive_verified: number; - }>( - "SELECT r.accepted AS imported,r.caught_up,CASE WHEN p.phase='verified' AND p.verified_at IS NOT NULL THEN 1 ELSE 0 END AS archive_verified FROM baseline_receipt r JOIN source_checkpoint c ON c.baseline_digest=r.digest LEFT JOIN baseline_publisher_proof p ON p.session_id=r.session_id WHERE c.source='cve'", - ); - return Response.json({ - schema_version: 1, - cve_delta: deltaStatus(checkpoints.find(checkpoint => checkpoint.source === "cve"), now), - baseline: { - imported: baseline?.imported ?? 0, - caught_up: baseline?.caught_up === 1, - archive_verified: baseline?.archive_verified === 1, - }, - bootstrap_complete: - checkpoints.find((c) => c.source === "cve") - ?.bootstrap_complete === 1, - feeds: checkpoints.map((c) => ({ - ...c, - complete: - !!c.complete && - !!c.bootstrap_complete && - !c.error && - fresh(c, now), - fresh: fresh(c, now), - })), - package_applicability: "Arch feed only; AUR mapping unknown", - }); - } - if (url.pathname.startsWith("/v1/runtimes/")) { - const force = /(?:^|,)\s*(?:no-cache|max-age\s*=\s*0)\s*(?:,|$)/i.test(request.headers.get("cache-control") ?? ""); - return Response.json(await runtimeReport(url, store, now, fetcher, force)); - } - const epssMatch = /^\/v1\/epss\/(CVE-\d{4}-\d{4,19})$/.exec(url.pathname); - if (epssMatch?.[1]) { - if (url.search) throw new Error("invalid EPSS query"); - if (!await store.sql.first("SELECT id FROM source_record WHERE id=?", [epssMatch[1]])) - return Response.json({ error: "CVE unavailable", status: "unavailable" }, { status: 404 }); - return Response.json(await epss(store, epssMatch[1], now, fetcher)); - } - if (url.pathname === "/v1/arch/advisories") { - const checkpoint = await store.checkpoint("arch"); - if (!checkpoint?.object_key) - return Response.json( - { error: "snapshot unavailable", complete: false }, - { status: 503 }, - ); - const raw = await store.raw.get(checkpoint.object_key); - if (!raw) throw new Error("snapshot object missing"); - return Response.json({ - schema_version: 1, - source: "arch-security", - source_url: SOURCES.arch, - fetched_at: checkpoint.fetched_at, - checked_at: checkpoint.checked_at, - complete: - !!checkpoint.complete && - !checkpoint.error && - fresh(checkpoint, now), - payload_sha256: checkpoint.payload_sha256, - payload_json: await raw.text(), - }); - } - if (url.pathname === "/v1/bundles/hot") { - const [recent, kevs, checkpoints] = await Promise.all([ - store.sql.all( - "SELECT r.id,r.source,r.source_url,r.schema_version,r.state,r.published_at,r.modified_at,r.fetched_at,r.payload_sha256,r.object_key,r.normalization_version,r.supported,k.payload_json AS kev_payload_json FROM source_record r LEFT JOIN kev_annotation k ON k.cve_id=r.id ORDER BY r.modified_at DESC,r.id DESC LIMIT 50", - ), - store.sql.all<{ cve_id: string; payload_json: string }>( - "SELECT cve_id,payload_json FROM kev_annotation ORDER BY cve_id DESC LIMIT 200", - ), - store.sql.all( - "SELECT * FROM source_checkpoint WHERE source IN ('cve','kev')", - ), - ]); - const cve = checkpoints.find((row) => row.source === "cve") ?? null; - const kev = checkpoints.find((row) => row.source === "kev") ?? null; - return Response.json({ - schema_version: 1, - generated_at: now, - cve_checked_at: cve?.checked_at ?? null, - kev_checked_at: kev?.checked_at ?? null, - recent_count: recent.length, - kev_count: kevs.length, - recent: recent.map(({ kev_payload_json, ...rec }) => ({ - ...rec, - kev: kev_payload_json ? JSON.parse(kev_payload_json) : null, - })), - kev_latest: kevs.map((k) => ({ cve_id: k.cve_id, kev: JSON.parse(k.payload_json) })), - }); - } - - if (url.pathname === "/v1/cves/dashboard") { - if (url.search) throw new Error("invalid dashboard query"); - - return Response.json(await dashboardModel(store, now)); - } - if (url.pathname === "/v1/cves/recent") { - const [page, checkpoint] = await Promise.all([ - recentCves(url, store.sql, now), - store.checkpoint("cve"), - ]); - return Response.json({ - schema_version: 1, ...page, - checked_at: checkpoint?.checked_at ?? null, - complete: !!checkpoint?.complete && !!checkpoint.bootstrap_complete && - !checkpoint.error && fresh(checkpoint, now), - package_applicability: "unknown", - }); - } - const match = /^\/v1\/cves\/(CVE-\d{4}-\d{4,19})$/.exec(url.pathname); - if (match?.[1]) { - const id = cveId(match[1]); - - if (url.searchParams.get("view") === "summary") return await cveSummary(store, id, now); - const [joined, checkpoints] = await Promise.all([ - store.sql.first< - RecordRow & { - kev_payload_json: string | null; - payload_raw?: string | null; - payload_jsonb?: unknown; - } - >( - "SELECT r.*, k.payload_json AS kev_payload_json FROM source_record r LEFT JOIN kev_annotation k ON k.cve_id=r.id WHERE r.id=?", - [id], - ), - store.sql.all( - "SELECT * FROM source_checkpoint WHERE source IN ('cve','kev')", - ), - ]); - if (!joined) - return Response.json( - { error: "CVE unavailable", complete: false }, - { status: 404 }, - ); - const { - kev_payload_json: kevPayloadJson, - payload_raw: inlinePayloadRaw, - payload_jsonb: _inlineJsonb, - ...record - } = joined; - const payload = - inlinePayloadRaw != null - ? inlinePayloadRaw - : await store.raw - .get(record.object_key) - .catch((cause: unknown) => { - throw new Error("CVE storage unavailable", { cause }); - }) - .then((raw) => { - if (!raw) throw new Error("CVE object missing"); - return raw.text(); - }); - if (await sha256(payload) !== record.payload_sha256) - throw new Error("CVE stored payload failed integrity"); - const kev = checkpoints.find((row) => row.source === "kev") ?? null; - const cve = checkpoints.find((row) => row.source === "cve") ?? null; - return Response.json({ - schema_version: 1, - payload_json: payload, - provenance: record, - cve_checked_at: cve?.checked_at ?? null, - cve_complete: !!cve?.complete && !!cve.bootstrap_complete && - !cve.error && fresh(cve, now), - kev: kevPayloadJson ? JSON.parse(kevPayloadJson) : null, - kev_checked_at: kev?.checked_at, - kev_complete: kev - ? !!kev.complete && !kev.error && fresh(kev, now) - : false, - package_applicability: "unknown", - }); - } - return Response.json({ error: "not found" }, { status: 404 }); - } catch (error) { - if (error instanceof BaselineBusyError) return Response.json({ error: "ingestion busy" }, { status: 409 }); - const invalid = - error instanceof Error && - /invalid|expected|exceeds|missing publication|mismatch|catchup|baseline|completeness/.test( - error.message, - ); - if (!invalid && url.pathname.startsWith("/internal/")) { - const reasons: string[] = []; - let cause: unknown = error; - for (let depth = 0; depth < 3 && cause instanceof Error; depth++) { - let message = cause.message; - for (const secret of [token, runtimeRefreshSecret]) { - if (secret) message = message.replaceAll(secret, "[redacted]"); - } - reasons.push(message.replace(/ghs_[A-Za-z0-9._-]+/g, "[redacted]").slice(0, 300)); - cause = cause.cause; - } - console.error(JSON.stringify({ event: "internal_advisory_failure", path: url.pathname, reasons })); - } - return Response.json( - { - error: invalid - ? "invalid or incomplete input" - : "service unavailable", - complete: false, - }, - { status: invalid ? 400 : 503 }, - ); - } -} diff --git a/services/advisories/src/storage.ts b/services/advisories/src/storage.ts deleted file mode 100644 index c5a3038c5..000000000 --- a/services/advisories/src/storage.ts +++ /dev/null @@ -1,303 +0,0 @@ -import { parseCve, sha256, cveServicesUrl, cveUrl } from "./domain"; -import { packRecords } from "./raw-pack"; -export type Command = { sql: string; values: (string | number | null)[] }; -export interface Sql { - readonly inlinePayloads?: boolean; - first( - sql: string, - values?: (string | number | null)[], - ): Promise; - all(sql: string, values?: (string | number | null)[]): Promise; - batch(commands: Command[]): Promise; -} -export interface RawStore { - put(key: string, value: string): Promise; - get(key: string): Promise<{ text(): Promise } | null>; -} -export function d1Sql(db: Pick): Sql { - return { - first: (sql, values = []) => - db - .prepare(sql) - .bind(...values) - .first(), - all: async (sql: string, values: (string | number | null)[] = []) => - ( - await db - .prepare(sql) - .bind(...values) - .all() - ).results, - batch: async (commands) => { - await db.batch( - commands.map((c) => db.prepare(c.sql).bind(...c.values)), - ); - }, - }; -} -export type Checkpoint = { - source: string; - cursor: string | null; - baseline_digest: string | null; - checked_at: string | null; - fetched_at: string | null; - etag: string | null; - complete: number; - bootstrap_complete: number; - error: string | null; - object_key: string | null; - payload_sha256: string | null; - revision: string | null; -}; -export type RecordRow = { - id: string; - source_url: string; - schema_version: string; - state: string; - published_at: string | null; - modified_at: string; - fetched_at: string; - payload_sha256: string; - object_key: string; - normalization_version: number; - supported: number; -}; - -const cveRevisionColumns = "id, modified_at, payload_sha256, supported, source_url, object_key"; - -type CveRevision = Pick; - -type CveRecord = ReturnType; - -function compactJson(value: string): string { - return value.replace(/"(?:\\[\s\S]|[^"\\])*"|[ \t\r\n]+/g, token => - token.startsWith('"') ? token : "", - ); -} - -function cveChanged(record: CveRecord, hash: string, old: CveRevision | undefined | null): boolean { - if(old && old.modified_at>record.modified)return false; - if(old?.payload_sha256===hash) { - if(!old.supported)throw new Error("unsupported CVE schema or state preserved as partial"); - return false; - } - if(old && old.modified_at===record.modified)throw new Error("conflicting equal CVE revision"); - return true; -} -const MAX_INLINE_PAYLOAD_BYTES = 256 * 1024; -function cveCommands( - record: CveRecord, - hash: string, - key: string, - fetchedAt: string, - inlineRaw?: string | null, - sourceUrl = cveUrl(record.id), -): Command[] { - const useInline = inlineRaw !== undefined; - const inlineValue = - useInline && inlineRaw !== null && inlineRaw.length <= MAX_INLINE_PAYLOAD_BYTES - ? inlineRaw - : null; - return [ - useInline - ? { - sql: "INSERT INTO source_record(id,source,source_url,schema_version,state,published_at,modified_at,fetched_at,payload_sha256,object_key,normalization_version,supported,payload_raw,payload_jsonb) SELECT ?,?,?,?,?,?,?,?,?,?,?,?,payload.raw,payload.raw::jsonb FROM (VALUES (?::text)) AS payload(raw) WHERE true ON CONFLICT(id) DO UPDATE SET source_url=excluded.source_url,schema_version=excluded.schema_version,state=excluded.state,published_at=excluded.published_at,modified_at=excluded.modified_at,fetched_at=excluded.fetched_at,payload_sha256=excluded.payload_sha256,object_key=excluded.object_key,normalization_version=excluded.normalization_version,supported=excluded.supported,payload_raw=excluded.payload_raw,payload_jsonb=excluded.payload_jsonb WHERE excluded.modified_at > source_record.modified_at", - values: [ - record.id, - "cve", - sourceUrl, - record.schema, - record.state, - record.published, - record.modified, - fetchedAt, - hash, - key, - 1, - Number(record.supported), - inlineValue, - ], - } - : { - sql: "INSERT INTO source_record(id,source,source_url,schema_version,state,published_at,modified_at,fetched_at,payload_sha256,object_key,normalization_version,supported) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET source_url=excluded.source_url,schema_version=excluded.schema_version,state=excluded.state,published_at=excluded.published_at,modified_at=excluded.modified_at,fetched_at=excluded.fetched_at,payload_sha256=excluded.payload_sha256,object_key=excluded.object_key,normalization_version=excluded.normalization_version,supported=excluded.supported WHERE excluded.modified_at > source_record.modified_at", - values: [ - record.id, - "cve", - sourceUrl, - record.schema, - record.state, - record.published, - record.modified, - fetchedAt, - hash, - key, - 1, - Number(record.supported), - ], - }, - { - sql: "INSERT INTO cve(id,state,modified_at,payload_sha256) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET state=excluded.state,modified_at=excluded.modified_at,payload_sha256=excluded.payload_sha256 WHERE excluded.modified_at > cve.modified_at", - values: [record.id, record.state, record.modified, hash], - }, - ]; -} -export class Store { - constructor( - readonly sql: Sql, - readonly raw: RawStore, - readonly clock?: () => string, - ) {} - private async changed(record: CveRecord, raw: string, hash: string, old: CveRevision | undefined | null, sourceUrl?: string) { - const direct = cveServicesUrl(record.id); - // Office-issued copies can differ in whitespace. Preserve the stored bytes and - // digest while requiring identical JSON tokens and an intact stored payload. - - if (old?.supported && old.modified_at === record.modified && old.payload_sha256 !== hash && - (old.source_url === direct || sourceUrl === direct)) { - const previous = await this.raw.get(old.object_key); - - if (previous) { - const text = await previous.text(); - - if (await sha256(text) === old.payload_sha256 && compactJson(text) === compactJson(raw)) return false; - } - } - - return cveChanged(record, hash, old); - } - writer(source: string, owner: string): Store { - const sql = this.sql; - return new Store( - { - inlinePayloads: sql.inlinePayloads, - first: sql.first.bind(sql), - all: sql.all.bind(sql), - batch: (commands) => sql.batch([ - { - sql: "INSERT INTO mutation_fence(id,valid) VALUES(1,CASE WHEN EXISTS(SELECT 1 FROM ingestion_lease WHERE source=? AND owner=? AND expires_at>COALESCE(?,strftime('%Y-%m-%dT%H:%M:%fZ','now'))) THEN 1 ELSE 0 END) ON CONFLICT(id) DO UPDATE SET valid=excluded.valid", - values: [source, owner, this.clock?.() ?? null], - }, - ...commands, - ]), - }, - this.raw, - this.clock, - ); - } - checkpoint(source: string) { - return this.sql.first( - "SELECT * FROM source_checkpoint WHERE source=?", - [source], - ); - } - async lease(source: string, owner: string, now: string): Promise { - await this.sql.batch([ - { - sql: "INSERT INTO ingestion_lease(source,owner,expires_at) VALUES(?,?,?) ON CONFLICT(source) DO UPDATE SET owner=excluded.owner,expires_at=excluded.expires_at WHERE ingestion_lease.expires_at < ?", - values: [ - source, - owner, - new Date(Date.parse(now) + 600_000).toISOString(), - now, - ], - }, - ]); - const row = await this.sql.first<{ owner: string }>( - "SELECT owner FROM ingestion_lease WHERE source=?", - [source], - ); - return row?.owner === owner; - } - async release(source: string, owner: string) { - await this.sql.batch([ - { - sql: "DELETE FROM ingestion_lease WHERE source=? AND owner=?", - values: [source, owner], - }, - ]); - } - async cveBatch(records:readonly {id:string;raw:string}[],fetchedAt:string,after:Command[]=[],layout:"individual"|"packed"="individual"):Promise { - const started=performance.now(); - if(records.length<1 || records.length>64 || new Set(records.map(record=>record.id)).size!==records.length)throw new Error("bulk CVE admission requires one to 64 distinct IDs"); - let bytes=0; - const parsed=records.map(({id,raw})=>{ - bytes+=new TextEncoder().encode(raw).byteLength; - if(bytes>4*1024*1024)throw new Error("bulk CVE records exceed the batch byte bound"); - const record=parseCve(raw,id); - if(!record.supported)throw new Error("bulk CVE admission requires supported records; use the serial preservation path"); - return {record,raw}; - }); - const prepared=await Promise.all(parsed.map(async({record,raw})=>{ - const hash=await sha256(raw); - return {record,raw,hash,key:`cve/${record.id}/${hash}.json`}; - })); - const preparedAt=performance.now(); - const oldRows=await this.sql.all(`SELECT ${cveRevisionColumns} FROM source_record WHERE id IN (${records.map(()=>"?").join(",")})`,records.map(record=>record.id)); - const readAt=performance.now(); - const oldById=new Map(oldRows.map(record=>[record.id,record])); - const changed: typeof prepared = []; - - for (const candidate of prepared) { - const { record, raw, hash } = candidate; - - if (await this.changed(record, raw, hash, oldById.get(record.id))) changed.push(candidate); - } - - if(layout==="packed" && changed.length) { - const packed=await packRecords(changed.map(candidate=>candidate.raw)); - for(const [index,candidate] of changed.entries()) { - const key=packed.pointers[index]; - if(!key || !key.endsWith(`:${candidate.hash}`))throw new Error("packed original payload identity mismatch"); - candidate.key=key; - } - await this.raw.put(packed.key,packed.body); - } else { - let next=0; - const failures:unknown[]=[]; - await Promise.all(Array.from({length:Math.min(6,changed.length)},async()=>{ - while(failures.length===0) { - const candidate=changed[next++]; - if(!candidate)return; - try {await this.raw.put(candidate.key,candidate.raw);} - catch(error){failures.push(error);} - } - })); - if(failures.length)throw failures[0]; - } - const rawAt=performance.now(); - const commands=changed.flatMap(({record,raw,hash,key})=>cveCommands(record,hash,key,fetchedAt,this.sql.inlinePayloads ? raw : undefined)); - if(commands.length || after.length)await this.sql.batch([...commands,...after]); - console.info(JSON.stringify({event:"baseline_write_phases",records:records.length,changed:changed.length, - prepare_ms:preparedAt-started,read_ms:readAt-preparedAt,raw_ms:rawAt-readAt,metadata_ms:performance.now()-rawAt})); - } - async cve( - raw: string, - fetchedAt: string, - expectedId?: string, - sourceUrl?: string, - ): Promise { - const record = parseCve(raw, expectedId); - const hash = await sha256(raw); - const old = await this.sql.first( - `SELECT ${cveRevisionColumns} FROM source_record WHERE id=?`, - [record.id], - ); - - if (!await this.changed(record, raw, hash, old, sourceUrl)) return; - const key = `cve/${record.id}/${hash}.json`; - await this.raw.put(key, raw); - await this.sql.batch(cveCommands(record,hash,key,fetchedAt,this.sql.inlinePayloads ? raw : undefined,sourceUrl)); - - if (!record.supported) { - await this.sql.batch([ - { - sql: "UPDATE source_checkpoint SET complete=0,error=? WHERE source=?", - values: ["unsupported CVE schema or state", "cve"], - }, - ]); - throw new Error( - "unsupported CVE schema or state preserved as partial", - ); - } - } -} diff --git a/services/advisories/test/archive.test.ts b/services/advisories/test/archive.test.ts deleted file mode 100644 index e742b263e..000000000 --- a/services/advisories/test/archive.test.ts +++ /dev/null @@ -1,399 +0,0 @@ -import { test, expect } from "bun:test"; -import { crc32, deflateRawSync } from "node:zlib"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { parseBatch } from "../src/ingestion"; -import { scanArchive, fileHash, type ArchiveState } from "../scripts/archive"; -const encodeBatch = (records: string[]) => JSON.stringify({source: "cve", records}); -const path = fileURLToPath(new NodeURL("./fixtures/tiny.zip", import.meta.url)); - -test("baseline scans honor the bounded batch size and reject invalid budgets", async () => { - const digest = await fileHash(path); - const sizes: number[] = []; - const options = { - path, digest, state: { digest, next_entry: 0, accepted: 0, exhausted: false, finished_at: null } as ArchiveState, - maxRecords: 100, batchSize: 2, encodeBatch, - send: async (body: string) => { sizes.push(JSON.parse(body).records.length); }, - save: async () => {}, - }; - await scanArchive(options); - expect(sizes).toEqual([2, 1]); - await expect(scanArchive({ ...options, batchSize: 65 })).rejects.toThrow("batch size"); -}); -test("tiny ZIP scans lazily, stops at record budget and resumes without extracting files", async () => { - const digest = await fileHash(path); - const state: ArchiveState = { - digest, - next_entry: 0, - accepted: 0, - exhausted: false, - finished_at: null, - }; - const received: string[] = []; - let saves = 0; - const options = { - path, - digest, - state, - maxRecords: 1, - encodeBatch, - send: async (body: string) => { - received.push(...parseBatch(JSON.parse(body))); - }, - save: async () => { - saves++; - }, - }; - expect(await scanArchive(options)).toEqual({ sent: 1, exhausted: false }); - expect(state.next_entry).toBe(1); - expect(await scanArchive({ ...options, maxRecords: 4 })).toEqual({ - sent: 2, - exhausted: true, - }); - expect(state.accepted).toBe(3); - expect(new Set(received).size).toBe(3); - expect(saves).toBeGreaterThan(0); -}); -test("archive hash and year mismatch fail before accepting records", async () => { - let sends = 0; - const state: ArchiveState = { - digest: "a".repeat(64), - next_entry: 0, - accepted: 0, - exhausted: false, - finished_at: null, - }; - await expect( - scanArchive({ - path, - digest: state.digest, - state, - maxRecords: 1, - encodeBatch, - send: async () => { - sends++; - }, - save: async () => {}, - }), - ).rejects.toThrow("digest mismatch"); - const bad = fileURLToPath(new NodeURL("./fixtures/wrong-year.zip", import.meta.url)); - const digest = await fileHash(bad); - await expect( - scanArchive({ - path: bad, - digest, - state: { ...state, digest }, - maxRecords: 1, - encodeBatch, - send: async () => { - sends++; - }, - save: async () => {}, - }), - ).rejects.toThrow("path mismatch"); - expect(sends).toBe(0); -}); -test("failed batch does not advance resumable archive position", async () => { - const digest = await fileHash(path); - const state: ArchiveState = { - digest, - next_entry: 0, - accepted: 0, - exhausted: false, - finished_at: null, - }; - await expect( - scanArchive({ - path, - digest, - state, - maxRecords: 3, - encodeBatch, - send: async () => { - throw new Error("ingest unavailable"); - }, - save: async () => {}, - }), - ).rejects.toThrow("ingest unavailable"); - expect(state.accepted).toBe(0); - expect(state.next_entry).toBe(0); -}); -test("archive mutation after verification cannot change the bytes being parsed", async () => { - const {mkdtemp,copyFile,writeFile,rm} = await import("node:fs/promises"); - const {tmpdir} = await import("node:os"); - const {join} = await import("node:path"); - const directory = await mkdtemp(join(tmpdir(),"advisory-archive-test-")); - const mutable = join(directory,"archive.zip"); - try { - await copyFile(fileURLToPath(new NodeURL("./fixtures/nine.zip",import.meta.url)),mutable); - const digest = await fileHash(mutable); - const state: ArchiveState = {digest,next_entry:0,accepted:0,exhausted:false,finished_at:null}; - const records:string[] = []; - await scanArchive({path:mutable,digest,state,maxRecords:20,encodeBatch,send:async(body)=>{ - records.push(...parseBatch(JSON.parse(body))); - await writeFile(mutable,"corrupted original after first batch"); - },save:async()=>{}}); - expect(records.length).toBe(9); - expect(state.exhausted).toBe(true); - } finally { - await rm(directory,{recursive:true,force:true}); - } -}); -function storedZip(records: string[]): Buffer { - return zipEntries(records.map((raw, index) => ({name: `cves/2026/1xxx/CVE-2026-${1234 + index}.json`, data: Buffer.from(raw)}))); -} -function zipEntries(entries: {name: string; data: Buffer; deflate?: boolean; checksum?: number; declaredSize?: number}[]): Buffer { - const files: Buffer[] = []; - const directory: Buffer[] = []; - let offset = 0; - for (const entry of entries) { - const name = Buffer.from(entry.name); - const data = entry.deflate ? deflateRawSync(entry.data) : entry.data; - const checksum = entry.checksum ?? crc32(entry.data); - const method = entry.deflate ? 8 : 0; - const local = Buffer.alloc(30); - local.writeUInt32LE(0x04034b50, 0); - local.writeUInt16LE(20, 4); - local.writeUInt16LE(method, 8); - local.writeUInt32LE(checksum, 14); - local.writeUInt32LE(data.length, 18); - local.writeUInt32LE(entry.declaredSize ?? entry.data.length, 22); - local.writeUInt16LE(name.length, 26); - files.push(local, name, data); - const central = Buffer.alloc(46); - central.writeUInt32LE(0x02014b50, 0); - central.writeUInt16LE(20, 4); - central.writeUInt16LE(20, 6); - central.writeUInt16LE(method, 10); - central.writeUInt32LE(checksum, 16); - central.writeUInt32LE(data.length, 20); - central.writeUInt32LE(entry.declaredSize ?? entry.data.length, 24); - central.writeUInt16LE(name.length, 28); - central.writeUInt32LE(offset, 42); - directory.push(central, name); - offset += local.length + name.length + data.length; - } - const central = Buffer.concat(directory); - const end = Buffer.alloc(22); - end.writeUInt32LE(0x06054b50, 0); - end.writeUInt16LE(entries.length, 8); - end.writeUInt16LE(entries.length, 10); - end.writeUInt32LE(central.length, 12); - end.writeUInt32LE(offset, 16); - return Buffer.concat([...files, central, end]); -} -test("archive batches budget the complete bound POST envelope at the byte limit", async () => { - const { mkdtemp, writeFile, rm } = await import("node:fs/promises"); - const { tmpdir } = await import("node:os"); - const { join } = await import("node:path"); - const { LIMITS, object } = await import("../src/domain"); - const records = Array.from({ length: 4 }, (_, index) => { - const payload = { - dataType: "CVE_RECORD", dataVersion: "5.2", - cveMetadata: { cveId: `CVE-2026-${1234 + index}`, state: "PUBLISHED", dateUpdated: "2026-11-13T00:00:00Z", datePublished: "2026-11-13T00:00:00Z" }, - containers: { cna: { description: "" } }, - }; - payload.containers.cna.description = "x".repeat(1_048_500 - JSON.stringify(payload).length); - return JSON.stringify(payload); - }); - const baseline = { digest: "a".repeat(64), instance_id: "a".repeat(32), session_id: "a".repeat(36), endpoint: "https://advisories.example" }; - const encodeBatch = (batch: string[]) => JSON.stringify({source: "cve", records: batch, baseline}); - const directory = await mkdtemp(join(tmpdir(), "advisory-wire-test-")); - const path = join(directory, "archive.zip"); - try { - await writeFile(path, storedZip(records)); - const digest = await fileHash(path); - const state: ArchiveState = {digest, next_entry: 0, accepted: 0, exhausted: false, finished_at: null}; - const received: string[] = []; - const options = { - path, digest, state, maxRecords: 4, encodeBatch, - send: async (body: string) => { - const request = new Request("https://advisories.example/internal/ingest", {method: "POST", body}); - const wire = await request.text(); - expect(Buffer.byteLength(wire)).toBeLessThanOrEqual(LIMITS.batch); - const payload = object(JSON.parse(wire)); - expect(payload.baseline).toEqual(baseline); - received.push(...parseBatch(JSON.parse(wire))); - }, - save: async () => {}, - }; - await scanArchive(options); - expect(received).toEqual(records); - expect(state.accepted).toBe(4); - expect(state.exhausted).toBe(true); - } finally { - await rm(directory, {recursive: true, force: true}); - } -}); - - -test("publisher cves.zip wrapper resumes the inner corpus under the outer digest", async () => { - const {mkdtemp, readFile, writeFile, rm} = await import("node:fs/promises"); - const {tmpdir} = await import("node:os"); - const {join} = await import("node:path"); - const directory = await mkdtemp(join(tmpdir(), "advisory-nested-test-")); - try { - const inner = await readFile(path); - for (const deflate of [false, true]) { - const archive = join(directory, "publisher.zip.zip"); - await writeFile(archive, zipEntries([{name: "cves.zip", data: inner, deflate}])); - const digest = await fileHash(archive); - const state: ArchiveState = {digest, next_entry: 0, accepted: 0, exhausted: false, finished_at: null}; - const received: string[] = []; - const options = {path: archive, digest, state, maxRecords: 1, encodeBatch, - send: async (body: string) => { received.push(...parseBatch(JSON.parse(body))); }, save: async () => {}, - }; - expect(await scanArchive(options)).toEqual({sent: 1, exhausted: false}); - expect(state.digest).toBe(digest); - expect(await scanArchive({...options, maxRecords: 4})).toEqual({sent: 2, exhausted: true}); - expect(state.accepted).toBe(3); - expect(new Set(received).size).toBe(3); - expect(await scanArchive({...options, maxRecords: 4})).toEqual({sent: 0, exhausted: true}); - } - } finally { await rm(directory, {recursive: true, force: true}); } -}); - -test("archive wrappers reject corrupt, mixed, recursive and empty corpora without completion", async () => { - const {mkdtemp, readFile, writeFile, rm} = await import("node:fs/promises"); - const {tmpdir} = await import("node:os"); - const {join} = await import("node:path"); - const directory = await mkdtemp(join(tmpdir(), "advisory-invalid-wrapper-test-")); - try { - const inner = await readFile(path); - const validWrapper = zipEntries([{name: "cves.zip", data: inner, deflate: true}]); - const cases = [ - {name: "crc", data: zipEntries([{name: "cves.zip", data: inner, deflate: true, checksum: (crc32(inner) ^ 1) >>> 0}]), error: "checksum"}, - {name: "mixed", data: zipEntries([{name: "cves.zip", data: inner}, {name: "README", data: Buffer.from("mixed")}]), error: "wrapper"}, - {name: "recursive", data: zipEntries([{name: "cves.zip", data: validWrapper, deflate: true}]), error: "wrapper"}, - {name: "oversize", data: zipEntries([{name: "cves.zip", data: inner, deflate: true, declaredSize: 2 * 1024 ** 3}]), error: "oversize"}, - {name: "ratio", data: zipEntries([{name: "cves.zip", data: Buffer.alloc(512 * 1024), deflate: true}]), error: "oversize"}, - {name: "empty", data: zipEntries([{name: "README", data: Buffer.from("no records")}]), error: "no CVE records"}, - ]; - for (const fixture of cases) { - const archive = join(directory, fixture.name + ".zip"); - await writeFile(archive, fixture.data); - const digest = await fileHash(archive); - const state: ArchiveState = {digest, next_entry: 0, accepted: 0, exhausted: false, finished_at: null}; - let sends = 0; - await expect(scanArchive({path: archive, digest, state, maxRecords: 10, encodeBatch, - send: async () => { sends++; }, save: async () => {}, - })).rejects.toThrow(fixture.error); - expect(sends).toBe(0); - expect(state.exhausted).toBe(false); - expect(state.finished_at).toBeNull(); - if (fixture.name === "mixed") { - state.next_entry = 2; - state.accepted = 1; - await expect(scanArchive({path: archive, digest, state, maxRecords: 10, encodeBatch, - send: async () => { sends++; }, save: async () => {}, - })).rejects.toThrow("wrapper"); - expect(sends).toBe(0); - } - } - } finally { await rm(directory, {recursive: true, force: true}); } -}); - -function largeCveFixture(id = "CVE-2026-1234", bytes = 2_402_038): string { - const description = {lang: "en", value: "Generated structured CNA/ADP fixture; preserve UTF8 é and raw whitespace."}; - const payload = { - dataType: "CVE_RECORD", dataVersion: "5.2", - cveMetadata: {cveId: id, state: "PUBLISHED", dateUpdated: "2026-11-13T02:00:00.000Z", datePublished: "2026-11-11T00:00:00Z"}, - containers: { - cna: { - providerMetadata: {orgId: "00000000-0000-4000-8000-000000000001", shortName: "fixture-CNA"}, - descriptions: [description], - affected: [{vendor: "fixture-vendor", product: "fixture-product", defaultStatus: "unaffected", - versions: Array.from({length: 11_000}, (_, index) => ({version: `${index}.0.0`, status: "affected", lessThan: `${index + 1}.0.0`, versionType: "semver"}))}], - }, - adp: [{providerMetadata: {orgId: "00000000-0000-4000-8000-000000000002", shortName: "fixture-ADP"}, - affected: Array.from({length: 1_600}, (_, index) => ({vendor: `vendor-${index}`, product: `product-${index}`, versions: [{version: `${index}.1`, status: "affected"}]}))}], - }, - }; - const encode = () => `\n${JSON.stringify(payload, null, 2)}\n`; - const padding = bytes - Buffer.byteLength(encode()); - if (padding < 0) throw new Error("large CVE fixture structure exceeds requested byte size"); - description.value += "x".repeat(padding); - const raw = encode(); - if (Buffer.byteLength(raw) !== bytes) throw new Error("large CVE fixture byte size mismatch"); - return raw; -} - -test("large structured CVE records preserve exact raw bytes while complete envelopes split below four MiB", async () => { - const {mkdtemp, writeFile, rm} = await import("node:fs/promises"); - const {tmpdir} = await import("node:os"); - const {join} = await import("node:path"); - const {LIMITS} = await import("../src/domain"); - const directory = await mkdtemp(join(tmpdir(), "advisory-large-cve-")); - const archive = join(directory, "archive.zip"); - const records = [largeCveFixture(), largeCveFixture("CVE-2026-1235")]; - const baseline = {digest: "a".repeat(64), instance_id: "a".repeat(32), session_id: "a".repeat(36), endpoint: "https://advisories.example"}; - const encode = (batch: string[]) => JSON.stringify({source: "cve", records: batch, baseline}); - expect(Buffer.byteLength(encode(records))).toBeGreaterThan(LIMITS.batch); - const received: string[] = []; - const bodies: string[] = []; - try { - await writeFile(archive, storedZip(records)); - const digest = await fileHash(archive); - const state: ArchiveState = {digest, next_entry: 0, accepted: 0, exhausted: false, finished_at: null}; - await scanArchive({path: archive, digest, state, maxRecords: 2, encodeBatch: encode, - send: async (body) => { - expect(Buffer.byteLength(body)).toBeLessThanOrEqual(4 * 1024 ** 2); - bodies.push(body); - received.push(...parseBatch(JSON.parse(body))); - }, save: async () => {}}); - expect(received).toEqual(records); - expect(bodies.length).toBe(2); - expect(state.accepted).toBe(2); - expect(state.exhausted).toBe(true); - } finally { - await rm(directory, {recursive: true, force: true}); - } -}); - -test("CVE raw allowance does not admit a single escaped envelope above four MiB", async () => { - const {mkdtemp, writeFile, rm} = await import("node:fs/promises"); - const {tmpdir} = await import("node:os"); - const {join} = await import("node:path"); - const raw = JSON.stringify({dataType: "CVE_RECORD", dataVersion: "5.2", - cveMetadata: {cveId: "CVE-2026-1234", state: "PUBLISHED", dateUpdated: "2026-11-13T02:00:00.000Z", datePublished: "2026-11-11T00:00:00Z"}, - containers: {cna: {descriptions: [{lang: "en", value: '"'.repeat(1_100_000)}]}}}); - expect(Buffer.byteLength(raw)).toBeLessThan(3 * 1024 ** 2); - expect(Buffer.byteLength(encodeBatch([raw]))).toBeGreaterThan(4 * 1024 ** 2); - const directory = await mkdtemp(join(tmpdir(), "advisory-escaped-cve-")); - const archive = join(directory, "archive.zip"); - let sends = 0; - try { - await writeFile(archive, storedZip([raw])); - const digest = await fileHash(archive); - const state: ArchiveState = {digest, next_entry: 0, accepted: 0, exhausted: false, finished_at: null}; - await expect(scanArchive({path: archive, digest, state, maxRecords: 1, encodeBatch, - send: async () => { sends++; }, save: async () => {}})).rejects.toThrow("encoded ingest batch exceeds limit"); - expect(sends).toBe(0); - expect(state.accepted).toBe(0); - expect(state.next_entry).toBe(0); - expect(state.exhausted).toBe(false); - } finally { - await rm(directory, {recursive: true, force: true}); - } -}); - -test("archive raw CVE records above three MiB fail before send or checkpoint advancement", async () => { - const {mkdtemp, writeFile, rm} = await import("node:fs/promises"); - const {tmpdir} = await import("node:os"); - const {join} = await import("node:path"); - const directory = await mkdtemp(join(tmpdir(), "advisory-oversize-cve-")); - const archive = join(directory, "archive.zip"); - let sends = 0; - try { - await writeFile(archive, storedZip([largeCveFixture("CVE-2026-1234", 3 * 1024 ** 2 + 1)])); - const digest = await fileHash(archive); - const state: ArchiveState = {digest, next_entry: 0, accepted: 0, exhausted: false, finished_at: null}; - await expect(scanArchive({path: archive, digest, state, maxRecords: 1, encodeBatch, - send: async () => {sends++;}, save: async () => {}})).rejects.toThrow("oversize"); - expect(sends).toBe(0); - expect(state.accepted).toBe(0); - expect(state.next_entry).toBe(0); - expect(state.exhausted).toBe(false); - } finally { - await rm(directory, {recursive: true, force: true}); - } -}); diff --git a/services/advisories/test/baseline-packed-ingest.test.ts b/services/advisories/test/baseline-packed-ingest.test.ts deleted file mode 100644 index 6640d08f6..000000000 --- a/services/advisories/test/baseline-packed-ingest.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { expect, test } from "bun:test"; -import { readFile, readdir } from "node:fs/promises"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { Miniflare, convertV4MiniflareOptions } from "miniflare"; -import { unstable_splitSqlQuery } from "wrangler"; -import { object, sha256 } from "../src/domain"; -import { gitBlobSha1 } from "../src/baseline"; - -const token="controlled-packed-baseline-token-at-least-32"; -const payload=(id:string,title:string,modified="2026-11-12T00:00:00.000Z")=>JSON.stringify({dataType:"CVE_RECORD",dataVersion:"5.2",cveMetadata:{cveId:id,state:"PUBLISHED",dateUpdated:modified,datePublished:"2026-11-11T00:00:00.000Z"},containers:{cna:{title}}}); - -test("actual baseline ingest packs large exact originals once while ordinary newer revisions remain individual",async()=>{ - const build=await Bun.build({entrypoints:[fileURLToPath(new NodeURL("../src/index.ts",import.meta.url))],target:"browser"}); - expect(build.success).toBe(true); - const bundle=build.outputs[0];if(!bundle)throw new Error("missing packed writer Worker bundle"); - const runtime=new Miniflare(convertV4MiniflareOptions({modules:true,script:await bundle.text(),compatibilityDate:"2026-11-13",d1Databases:["DB"],r2Buckets:["RAW"],bindings:{CVE_BATCH_SIZE:"32",INGEST_TOKEN:token}})); - try { - const db=await runtime.getD1Database("DB"),raw=await runtime.getR2Bucket("RAW"); - const directory=new NodeURL("../migrations/",import.meta.url); - for(const name of (await readdir(directory)).filter(name=>name.endsWith(".sql")).sort()) - await db.batch(unstable_splitSqlQuery(await readFile(new NodeURL(name,directory),"utf8")).map(query=>db.prepare(query))); - const worker=await runtime.getWorker(); - const post=(path:string,body:unknown)=>worker.fetch(`https://advisories.example${path}`,{method:"POST",headers:{authorization:`Bearer ${token}`,"content-type":"application/json"},body:JSON.stringify(body)}); - const start=await post("/internal/baseline/start",{digest:"b".repeat(64),baseline_at:"2026-11-13T00:00:00.000Z"}); - expect(start.status).toBe(200);const baseline=object(await start.json()); - const first=payload("CVE-2026-6100","x".repeat(2_600_000)),second=payload("CVE-2026-6101","original café ☕"); - const imported=await post("/internal/ingest",{source:"cve",records:[first,second],baseline}); - expect(imported.status).toBe(200); - const objects=await raw.list({prefix:"cve-pack-v1/"}); - expect(objects.objects).toHaveLength(1); - expect((await raw.list({prefix:"cve/"})).objects).toHaveLength(0); - for(const [id,expected] of new Map([["CVE-2026-6100",first],["CVE-2026-6101",second]])){ - const response=await worker.fetch(`https://advisories.example/v1/cves/${id}`); - expect(response.status).toBe(200);expect(object(await response.json()).payload_json).toBe(expected); - const ledger=await db.prepare("SELECT payload_sha256,git_blob_sha1 FROM baseline_import_blob WHERE cve_id=?").bind(id).first<{payload_sha256:string;git_blob_sha1:string}>(); - expect(ledger).toEqual({payload_sha256:await sha256(expected),git_blob_sha1:await gitBlobSha1(expected)}); - } - const replay=await post("/internal/ingest",{source:"cve",records:[first,second],baseline}); - expect(replay.status).toBe(200);expect((await raw.list({prefix:"cve-pack-v1/"})).objects).toHaveLength(1); - const newer=payload("CVE-2026-6101","newer ordinary delta","2026-11-13T00:00:00.000Z"); - expect((await post("/internal/ingest",{source:"cve",records:[newer]})).status).toBe(200); - expect((await raw.list({prefix:"cve/"})).objects).toHaveLength(1); - expect(object(await (await worker.fetch("https://advisories.example/v1/cves/CVE-2026-6101")).json()).payload_json).toBe(newer); - expect(await db.prepare("SELECT payload_sha256,git_blob_sha1 FROM baseline_import_blob WHERE cve_id=?").bind("CVE-2026-6101").first<{payload_sha256:string;git_blob_sha1:string}>()) - .toEqual({payload_sha256:await sha256(second),git_blob_sha1:await gitBlobSha1(second)}); - }finally{await runtime.dispose();} -}); diff --git a/services/advisories/test/baseline-packed-worker.test.ts b/services/advisories/test/baseline-packed-worker.test.ts deleted file mode 100644 index 0bd3fda9b..000000000 --- a/services/advisories/test/baseline-packed-worker.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { expect, test } from "bun:test"; -import { readFile, readdir } from "node:fs/promises"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { Miniflare, convertV4MiniflareOptions } from "miniflare"; -import { unstable_splitSqlQuery } from "wrangler"; -import { Store, d1Sql } from "../src/storage"; -import { object, sha256 } from "../src/domain"; - -const payload=(id:string,title:string)=>JSON.stringify({dataType:"CVE_RECORD",dataVersion:"5.2", - cveMetadata:{cveId:id,state:"PUBLISHED",dateUpdated:"2026-11-12T00:00:00.000Z",datePublished:"2026-11-11T00:00:00.000Z"}, - containers:{cna:{title}}}); - -test("actual Worker reads original UTF8 packed ranges and legacy CVEs, refusing altered packed bytes",async()=>{ - const build=await Bun.build({entrypoints:[fileURLToPath(new NodeURL("../src/index.ts",import.meta.url))],target:"browser"}); - expect(build.success).toBe(true); - const bundle=build.outputs[0];if(!bundle)throw new Error("missing controlled Worker bundle"); - const runtime=new Miniflare(convertV4MiniflareOptions({modules:true,script:await bundle.text(),compatibilityDate:"2026-11-13",d1Databases:["DB"],r2Buckets:["RAW"],bindings:{CVE_BATCH_SIZE:"32"}})); - try { - const db=await runtime.getD1Database("DB"),raw=await runtime.getR2Bucket("RAW"); - const directory=new NodeURL("../migrations/",import.meta.url); - for(const name of (await readdir(directory)).filter(name=>name.endsWith(".sql")).sort()){ - const source=await readFile(new NodeURL(name,directory),"utf8"); - await db.batch(unstable_splitSqlQuery(source).map(query=>db.prepare(query))); - } - const store=new Store(d1Sql(db),raw),now=new Date().toISOString(); - const first=payload("CVE-2026-6000","café ☕"),second=payload("CVE-2026-6001","second original record"),legacy=payload("CVE-2026-6002","legacy individual object"); - for(const value of [first,second,legacy])await store.cve(value,now); - const packed=first+second,key=`cve-pack-v1/${await sha256(packed)}.raw`; - await raw.put(key,packed); - const firstLength=new TextEncoder().encode(first).length,secondLength=new TextEncoder().encode(second).length; - await db.batch([ - db.prepare("UPDATE source_record SET object_key=? WHERE id=?").bind(`${key}#0:${firstLength}:${await sha256(first)}`,"CVE-2026-6000"), - db.prepare("UPDATE source_record SET object_key=? WHERE id=?").bind(`${key}#${firstLength}:${secondLength}:${await sha256(second)}`,"CVE-2026-6001"), - ]); - const worker=await runtime.getWorker(); - for(const [id,expected] of new Map([["CVE-2026-6000",first],["CVE-2026-6001",second],["CVE-2026-6002",legacy]])){ - const response=await worker.fetch(`https://advisories.example/v1/cves/${id}`); - expect(response.status).toBe(200); - const body=object(await response.json()); - expect(body.payload_json).toBe(expected); - expect(object(body.provenance).payload_sha256).toBe(await sha256(expected)); - } - await db.prepare("UPDATE source_record SET object_key=? WHERE id=?") - .bind(`${key}#${firstLength}:${secondLength}:${await sha256(second)}`,"CVE-2026-6000").run(); - expect((await worker.fetch("https://advisories.example/v1/cves/CVE-2026-6000")).status).toBe(503); - await db.prepare("UPDATE source_record SET object_key=? WHERE id=?") - .bind(`${key}#0:${firstLength}:${await sha256(first)}`,"CVE-2026-6000").run(); - await raw.put(key,packed.replace("☕","☀")); - expect((await worker.fetch("https://advisories.example/v1/cves/CVE-2026-6000")).status).toBe(503); - expect((await worker.fetch("https://advisories.example/v1/cves/CVE-2026-6002")).status).toBe(200); - }finally{await runtime.dispose();} -}); diff --git a/services/advisories/test/baseline.test.ts b/services/advisories/test/baseline.test.ts deleted file mode 100644 index 28fda8df6..000000000 --- a/services/advisories/test/baseline.test.ts +++ /dev/null @@ -1,311 +0,0 @@ -import { test, expect } from "bun:test"; -import { Database } from "bun:sqlite"; -import { readFileSync, readdirSync } from "node:fs"; -import { URL as NodeURL } from "node:url"; -import { handle } from "../src/service"; -import { Store, type Sql, type Command } from "../src/storage"; -import type { Fetcher } from "../src/ingestion"; -import { baselineImportCommands, gitBlobSha1 } from "../src/baseline"; - -const now = "2026-11-13T02:00:00.000Z"; -const ingestToken = "controlled-ingest-token-at-least-32-characters"; -const refreshToken = "controlled-refresh-token-at-least-32-characters"; -const githubToken = `ghs_12345_fixture.header-${"A".repeat(475)}.signature_fixture`; -const archiveDigest = "a".repeat(64); -const commit = "1".repeat(40), rootTree = "2".repeat(40), cvesTree = "3".repeat(40); -const yearTree = "4".repeat(40), groupTree = "5".repeat(40); -const raw = JSON.stringify({ dataType: "CVE_RECORD", dataVersion: "5.2", cveMetadata: { - cveId: "CVE-2026-1234", state: "PUBLISHED", dateUpdated: "2026-11-12T00:00:00.000Z", - datePublished: "2026-11-11T00:00:00.000Z", -}, containers: { cna: { title: "controlled archive member" } } }); - -function setup() { - const db = new Database(":memory:"); - const migrations = new NodeURL("../migrations/", import.meta.url); - for (const name of readdirSync(migrations).filter((name) => name.endsWith(".sql")).sort()) - db.exec(readFileSync(new NodeURL(name, migrations), "utf8")); - const sql: Sql = { - first: async (text: string, values: (string | number | null)[] = []) => db.query(text).get(...values), - all: async (text: string, values: (string | number | null)[] = []) => db.query(text).all(...values), - batch: async (commands: Command[]) => { db.transaction(() => { - for (const command of commands) db.query(command.sql).run(...command.values); - })(); }, - }; - const objects = new Map(); - const store = new Store(sql, { - put: async (key, value) => { objects.set(key, value); }, - get: async (key) => { - const value = objects.get(key); - return value === undefined ? null : { text: async () => value }; - }, - }, () => now); - return { db, store, objects }; -} - -function request(path: string, body: unknown, token: string) { - return new Request(`https://advisories.example${path}`, { - method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, - body: JSON.stringify(body), - }); -} - -async function binding(store: Store) { - const started = await handle(request("/internal/baseline/start", { - digest: archiveDigest, baseline_at: "2026-11-13T00:00:00.000Z", - }, ingestToken), store, ingestToken, now); - expect(started.status).toBe(200); - const value: unknown = await started.json(); - if (!value || typeof value !== "object" || !("session_id" in value)) throw new Error("missing test baseline session"); - return value; -} - -async function publisherFetcher() { - const bytes = new TextEncoder().encode(raw); - const header = new TextEncoder().encode(`blob ${bytes.length}\0`); - const object = new Uint8Array(header.length + bytes.length); - object.set(header); object.set(bytes, header.length); - const blob = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-1", object)), (byte) => byte.toString(16).padStart(2, "0")).join(""); - const calls: string[] = []; - const entry = (path: string, type: "tree" | "blob", sha: string) => ({ path, type, sha, mode: type === "tree" ? "040000" : "100644" }); - const payloads = new Map([ - ["/repos/CVEProject/cvelistV5/releases/tags/cve_2026-11-13_0000Z", { tag_name: "cve_2026-11-13_0000Z", assets: [{ - name: "2026-11-13_all_CVEs_at_midnight.zip.zip", digest: `sha256:${archiveDigest}`, size: 100, - }] }], - ["/repos/CVEProject/cvelistV5/git/ref/tags/cve_2026-11-13_0000Z", { object: { type: "commit", sha: commit } }], - [`/repos/CVEProject/cvelistV5/git/commits/${commit}`, { sha: commit, tree: { sha: rootTree } }], - [`/repos/CVEProject/cvelistV5/git/trees/${rootTree}`, { sha: rootTree, truncated: false, tree: [entry("cves", "tree", cvesTree)] }], - [`/repos/CVEProject/cvelistV5/git/trees/${cvesTree}`, { sha: cvesTree, truncated: false, tree: [entry("2026", "tree", yearTree)] }], - [`/repos/CVEProject/cvelistV5/git/trees/${yearTree}`, { sha: yearTree, truncated: false, tree: [entry("1xxx", "tree", groupTree)] }], - [`/repos/CVEProject/cvelistV5/git/trees/${groupTree}`, { sha: groupTree, truncated: false, tree: [entry("CVE-2026-1234.json", "blob", blob)] }], - ]); - const fetcher: Fetcher = async (input, init) => { - const url = new URL(input); - expect(url.origin).toBe("https://api.github.com"); - expect(new Headers(init?.headers).get("authorization")).toBe(`Bearer ${githubToken}`); - expect(init?.redirect).toBe("manual"); - calls.push(url.pathname); - const payload = payloads.get(url.pathname); - if (!payload) throw new Error(`unexpected publisher request: ${url.pathname}`); - return Response.json(payload); - }; - return { fetcher, calls, blob, payloads }; -} - -test("authenticated publisher proof enumerates official nonrecursive Git membership instead of trusting operator exhaustion", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store); - const publisher = await publisherFetcher(); - const response = await handle(request("/internal/baseline/verify", { - ...baseline, release_tag: "cve_2026-11-13_0000Z", - asset: "2026-11-13_all_CVEs_at_midnight.zip.zip", github_token: githubToken, - }, refreshToken), fixture.store, ingestToken, now, publisher.fetcher, refreshToken); - expect(response.status).toBe(200); - const proof = await response.json(); - expect(proof).toMatchObject({ expected_count: 1, phase: "awaiting_import", archive_verified: false }); - expect(publisher.calls).toContain(`/repos/CVEProject/cvelistV5/git/trees/${groupTree}`); - expect(JSON.stringify(proof)).not.toContain(githubToken); - } finally { fixture.db.close(); } -}); - -async function verify(store: Store, baseline: object, fetcher: Fetcher, changes: Record = {}) { - return handle(request("/internal/baseline/verify", { ...baseline, - release_tag: "cve_2026-11-13_0000Z", asset: "2026-11-13_all_CVEs_at_midnight.zip.zip", - github_token: githubToken, ...changes, - }, refreshToken), store, ingestToken, now, fetcher, refreshToken); -} -async function ingest(store: Store, baseline: object, payload = raw) { - return handle(request("/internal/ingest", { source: "cve", baseline, records: [payload] }, ingestToken), store, ingestToken, now); -} -async function finish(fixture: ReturnType, baseline: object) { - fixture.db.query("UPDATE source_checkpoint SET complete=1,error=NULL,checked_at=?,cursor=? WHERE source='cve'").run(now, JSON.stringify({event:now,offset:0})); - return handle(request("/internal/baseline", { ...baseline, baseline_at: "2026-11-13T00:00:00.000Z", finished_at: now, accepted: 1, exhausted: true }, ingestToken), fixture.store, ingestToken, now); -} - -test("publisher certification binds original imports while retaining newer delta payloads", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store), publisher = await publisherFetcher(); - const newer = raw.replace("2026-11-12T00:00:00.000Z", "2026-11-13T01:00:00.000Z").replace("controlled archive member", "newer delta revision"); - await fixture.store.cve(newer, now); - expect((await ingest(fixture.store, baseline)).status).toBe(200); - expect((await finish(fixture, baseline)).status).toBe(200); - const response = await verify(fixture.store, baseline, publisher.fetcher); - expect(response.status).toBe(200); - expect(await response.json()).toMatchObject({ phase: "verified", expected_count: 1, verified_count: 1, pending_trees: 0, archive_verified: true }); - const row = fixture.db.query<{object_key:string}, []>("SELECT object_key FROM source_record").get(); - expect(row && fixture.objects.get(row.object_key)).toBe(newer); - const status = await handle(new Request("https://advisories.example/v1/status"), fixture.store, undefined, now); - expect(await status.json()).toMatchObject({ baseline: { imported: 1, archive_verified: true }, bootstrap_complete: true }); - expect(await (await finish(fixture, baseline)).json()).toMatchObject({ bootstrap_complete: true, archive_verified: true }); - expect(JSON.stringify([...fixture.objects.values()])).not.toContain(githubToken); - expect((await ingest(fixture.store, baseline)).status).toBe(200); - expect(fixture.db.query<{bootstrap_complete:number}, []>("SELECT bootstrap_complete FROM source_checkpoint WHERE source='cve'").get()?.bootstrap_complete).toBe(0); - expect(await (await verify(fixture.store, baseline, publisher.fetcher)).json()).toMatchObject({phase:"awaiting_import",archive_verified:false}); - } finally { fixture.db.close(); } -}); - -test("legacy members without original Git identities require exact replay", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store), publisher = await publisherFetcher(); - const session = fixture.db.query<{session_id:string}, []>("SELECT session_id FROM baseline_receipt").get(); - if (!session) throw new Error("missing fixture session"); - const hash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(raw)))].map((b) => b.toString(16).padStart(2,"0")).join(""); - fixture.db.query("INSERT INTO baseline_member VALUES(?,?,?)").run(session.session_id, "CVE-2026-1234", hash); - expect((await finish(fixture, baseline)).status).toBe(200); - expect(await (await verify(fixture.store, baseline, publisher.fetcher)).json()).toMatchObject({phase:"awaiting_import",archive_verified:false}); - expect((await ingest(fixture.store, baseline)).status).toBe(200); - expect((await finish(fixture, baseline)).status).toBe(200); - expect(await (await verify(fixture.store, baseline, publisher.fetcher)).json()).toMatchObject({phase:"verified",archive_verified:true}); - expect(fixture.db.query<{accepted:number}, []>("SELECT accepted FROM baseline_receipt").get()?.accepted).toBe(1); - } finally { fixture.db.close(); } -}); - -test("publisher proof requires fresh delta catchup after import exhaustion", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store), publisher = await publisherFetcher(); - expect((await ingest(fixture.store, baseline)).status).toBe(200); - expect((await finish(fixture, baseline)).status).toBe(200); - fixture.db.exec("UPDATE source_checkpoint SET checked_at='2026-11-13T01:00:00.000Z' WHERE source='cve'"); - expect(await (await verify(fixture.store, baseline, publisher.fetcher)).json()).toMatchObject({phase:"awaiting_catchup",verified_count:1,archive_verified:false}); - fixture.db.query("UPDATE source_checkpoint SET checked_at=? WHERE source='cve'").run(now); - expect(await (await verify(fixture.store, baseline, publisher.fetcher)).json()).toMatchObject({phase:"verified",archive_verified:true}); - } finally { fixture.db.close(); } -}); - -for (const malformed of ["digest", "truncated", "duplicate", "wrong-path", "symlink", "blob-mismatch"] as const) { - test(`publisher proof refuses ${malformed} without enabling completeness`, async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store), publisher = await publisherFetcher(); - expect((await ingest(fixture.store, baseline)).status).toBe(200); - expect((await finish(fixture, baseline)).status).toBe(200); - const group = `/repos/CVEProject/cvelistV5/git/trees/${groupTree}`; - if (malformed === "digest") publisher.payloads.set("/repos/CVEProject/cvelistV5/releases/tags/cve_2026-11-13_0000Z", {tag_name:"cve_2026-11-13_0000Z", assets:[{name:"2026-11-13_all_CVEs_at_midnight.zip.zip",digest:`sha256:${"b".repeat(64)}`,size:100}]}); - else { - const item = { path: malformed === "wrong-path" ? "CVE-2025-1234.json" : "CVE-2026-1234.json", type:"blob", mode:malformed === "symlink" ? "120000":"100644", sha:malformed === "blob-mismatch" ? "f".repeat(40):publisher.blob }; - publisher.payloads.set(group, {sha:groupTree,truncated:malformed === "truncated",tree:malformed === "duplicate"?[item,item]:[item]}); - } - expect((await verify(fixture.store, baseline, publisher.fetcher)).status).toBe(400); - expect(fixture.db.query<{bootstrap_complete:number}, []>("SELECT bootstrap_complete FROM source_checkpoint WHERE source='cve'").get()?.bootstrap_complete).toBe(0); - } finally { fixture.db.close(); } - }); -} - -test("verification authorizes before input and refuses operator manifests or arbitrary URLs", async () => { - const fixture = setup(); - try { - let calls = 0; - const fetcher: Fetcher = async () => { calls++; throw new Error("unexpected fetch"); }; - expect((await handle(request("/internal/baseline/verify", {github_token:githubToken}, ingestToken), fixture.store, ingestToken, now, fetcher, refreshToken)).status).toBe(401); - const baseline = await binding(fixture.store); - expect((await verify(fixture.store, baseline, fetcher, {manifest:["CVE-2026-1234"],url:"https://attacker.example"})).status).toBe(400); - expect(calls).toBe(0); - } finally { fixture.db.close(); } -}); - -test("failed publisher fetches redact credentials and cannot advance proof state", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store); - const response = await verify(fixture.store, baseline, async () => { throw new Error(`provider failed ${githubToken}`); }); - expect(response.status).toBe(503); - expect(await response.text()).not.toContain(githubToken); - expect(fixture.db.query<{count:number}, []>("SELECT COUNT(*) AS count FROM baseline_publisher_proof").get()?.count).toBe(0); - } finally { fixture.db.close(); } -}); - -test("commit-time lease expiry prevents fetched publisher state becoming authority", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store), publisher = await publisherFetcher(); - const response = await verify(fixture.store, baseline, async (url, init) => { - const result = await publisher.fetcher(url, init); - fixture.db.exec("UPDATE ingestion_lease SET expires_at='2026-11-13T01:00:00.000Z'"); - return result; - }); - expect(response.status).toBe(503); - expect(fixture.db.query<{count:number}, []>("SELECT COUNT(*) AS count FROM baseline_publisher_proof").get()?.count).toBe(0); - } finally { fixture.db.close(); } -}); - -test("original Git blob identities include the UTF8 byte-length header", async () => { - expect(await gitBlobSha1("")).toBe("e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"); - expect(await gitBlobSha1("hello\n")).toBe("ce013625030ba8dba906f756967f9e9ca394464a"); -}); - -test("publisher traversal resumes bounded work without fetching completed trees again", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store), publisher = await publisherFetcher(); - const groups = Array.from({length:12}, (_, index) => ({path:`${index}xxx`,type:"tree",mode:"040000",sha:(index+100).toString(16).padStart(40,"0")})); - publisher.payloads.set(`/repos/CVEProject/cvelistV5/git/trees/${yearTree}`, {sha:yearTree,truncated:false,tree:groups}); - for (const group of groups) publisher.payloads.set(`/repos/CVEProject/cvelistV5/git/trees/${group.sha}`, {sha:group.sha,truncated:false,tree:[]}); - const first = await verify(fixture.store, baseline, publisher.fetcher); - expect(first.status).toBe(200); - expect(await first.json()).toMatchObject({phase:"traversing",pending_trees:6,expected_count:0,verified_count:0,archive_verified:false}); - const alreadyFetched = [...publisher.calls]; - const second = await verify(fixture.store, baseline, publisher.fetcher); - expect(second.status).toBe(200); - expect(await second.json()).toMatchObject({phase:"awaiting_import",pending_trees:0,archive_verified:false}); - expect(publisher.calls.slice(alreadyFetched.length).some((path) => alreadyFetched.includes(path))).toBe(false); - expect(publisher.calls).toHaveLength(18); // four metadata/root reads plus fourteen queued trees - } finally { fixture.db.close(); } -}); - -test("import exhaustion with extra members cannot certify publisher membership", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store), publisher = await publisherFetcher(); - expect((await ingest(fixture.store, baseline)).status).toBe(200); - expect((await ingest(fixture.store, baseline, raw.replace("CVE-2026-1234", "CVE-2026-1235"))).status).toBe(200); - fixture.db.query("UPDATE baseline_receipt SET exhausted=1,caught_up=1,completed_at=?").run(now); - const response = await verify(fixture.store, baseline, publisher.fetcher); - expect(response.status).toBe(400); - expect(await response.json()).toMatchObject({complete:false}); - expect(fixture.db.query<{bootstrap_complete:number}, []>("SELECT bootstrap_complete FROM source_checkpoint WHERE source='cve'").get()?.bootstrap_complete).toBe(0); - } finally { fixture.db.close(); } -}); - -test("missing publisher members remain awaiting import despite operator exhaustion", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store), publisher = await publisherFetcher(); - fixture.db.query("UPDATE baseline_receipt SET exhausted=1,caught_up=1,completed_at=?").run(now); - expect(await (await verify(fixture.store, baseline, publisher.fetcher)).json()).toMatchObject({phase:"awaiting_import",expected_count:1,verified_count:0,archive_verified:false}); - } finally { fixture.db.close(); } -}); - -test("replay conflict checks probe exact member keys instead of scanning the imported corpus", async () => { - const fixture = setup(); - try { - const plans: string[] = []; - const sql: Sql = { ...fixture.store.sql, first: async (text: string, values: (string | number | null)[] = []) => { - plans.push(...fixture.db.query<{detail:string}, (string | number | null)[]>(`EXPLAIN QUERY PLAN ${text}`).all(...values).map((row) => row.detail)); - return fixture.store.sql.first(text, values); - } }; - await baselineImportCommands(new Store(sql, fixture.store.raw), "controlled-session", [{id:"CVE-2026-1234",raw}]); - expect(plans.join("\n")).toContain("session_id=? AND cve_id=?"); - expect(plans.some((plan) => plan.endsWith("(session_id=?)"))).toBe(false); - } finally { fixture.db.close(); } -}); - -test("publisher proof reports an active writer as retryable without upstream fetches or ownership changes", async () => { - const fixture = setup(); - try { - const baseline = await binding(fixture.store); - await fixture.store.lease("cve", "active-import-owner", now); - let fetched = 0; - const response = await verify(fixture.store, baseline, async () => { - fetched++; - throw new Error("busy proof must not fetch"); - }); - expect(response.status).toBe(409); - expect(response.headers.get("Cache-Control")).toBe("no-store"); - expect(fetched).toBe(0); - expect(fixture.db.query<{owner:string}, []>("SELECT owner FROM ingestion_lease WHERE source='cve'").get()?.owner).toBe("active-import-owner"); - expect(fixture.db.query<{count:number}, []>("SELECT COUNT(*) AS count FROM baseline_publisher_proof").get()?.count).toBe(0); - } finally { fixture.db.close(); } -}); diff --git a/services/advisories/test/bootstrap.test.ts b/services/advisories/test/bootstrap.test.ts deleted file mode 100644 index 4308e73b4..000000000 --- a/services/advisories/test/bootstrap.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { expect, test } from "bun:test"; -import { operatorPost, recoverCheckpoint, readCheckpoint, verifyIngestReply, proofProgress, type OperatorFetcher } from "../scripts/operator"; - -const binding = { digest:"a".repeat(64), endpoint:"https://advisories.example", instance_id:"1".repeat(32), session_id:"afb732ac-68e4-4549-98ec-e89224449b75" }; -test("lost state recovery replays from zero with exact supplied session and archive bindings", () => { - const recovered = recoverCheckpoint(binding); - expect(recovered).toEqual({ digest:binding.digest, next_entry:0, accepted:0, exhausted:false, finished_at:null, baseline:binding }); - expect(() => readCheckpoint({...recovered, baseline:{...binding, endpoint:"https://other.example"}}, binding)).toThrow("binding"); - expect(() => readCheckpoint({...recovered, accepted:132600}, binding)).toThrow("position"); - expect(() => readCheckpoint({...recovered, exhausted:true}, binding)).toThrow(); -}); - -test("idempotent operator transport retries connection loss and rate limits with byte-identical bodies", async () => { - const bodies:string[] = [], waits:number[] = []; - const fetcher:OperatorFetcher = async (_input, init) => { - bodies.push(String(init?.body)); - if (bodies.length===1) throw new TypeError("connection interrupted after commit"); - if (bodies.length===2) return new Response("busy",{status:429, headers:{"retry-after":"2"}}); - return Response.json({accepted:1}); - }; - const reply = await operatorPost({endpoint:new URL(binding.endpoint),token:"operator-fixture-token-at-least-32-characters",path:"/internal/ingest",body:'{"records":["exact bytes"]}',fetcher,sleep:async ms => { waits.push(ms); }}); - expect(reply).toEqual({accepted:1}); - expect(new Set(bodies).size).toBe(1); - expect(waits).toEqual([1000,2000]); -}); - -test("operator retry budget stops permanent failures and never echoes credentials", async () => { - let calls=0; - const token="operator-fixture-token-at-least-32-characters"; - const operation=operatorPost({endpoint:new URL(binding.endpoint),token,path:"/internal/ingest",body:"{}",fetcher:async()=>{calls++;throw new Error(token);},sleep:async()=>{}}); - await expect(operation).rejects.toThrow("progress retained"); - try { await operation; } catch(error) { expect(String(error)).not.toContain(token); } - expect(calls).toBe(5); - calls=0; - await expect(operatorPost({endpoint:new URL(binding.endpoint),token,path:"/internal/ingest",body:"{}",fetcher:async()=>{calls++;return new Response("denied",{status:401});},sleep:async()=>{}})).rejects.toThrow("401"); - expect(calls).toBe(1); -}); - -test("successful HTTP without the exact accepted count cannot advance an archive checkpoint", () => { - expect(()=>verifyIngestReply({accepted:7},8)).toThrow("accepted count"); - expect(()=>verifyIngestReply({accepted:"8"},8)).toThrow("accepted count"); - expect(verifyIngestReply({accepted:8},8)).toBeUndefined(); -}); - -test("a response-body connection failure retries the same idempotent request", async () => { - let calls=0; - const reply=await operatorPost({endpoint:new URL(binding.endpoint),token:"operator-fixture-token-at-least-32-characters",path:"/internal/ingest",body:"{}",sleep:async()=>{},fetcher:async()=>{ - calls++; - return calls===1 ? new Response(new ReadableStream({start(controller){controller.error(new Error("body disconnected"));}})) : Response.json({accepted:8}); - }}); - expect(reply.accepted).toBe(8); - expect(calls).toBe(2); -}); - -test("operator progress never treats partial membership or an assertion as archive certification",()=>{ - const expected={digest:binding.digest,release_tag:"cve_2026-11-13_0000Z",asset:"2026-11-13_all_CVEs_at_midnight.zip.zip"}; - const partial={...expected,commit_sha:"1".repeat(40),schema_version:1,phase:"awaiting_import",expected_count:424926,verified_count:132600,pending_trees:0,archive_verified:false}; - expect(proofProgress(partial,expected).archive_verified).toBe(false); - expect(()=>proofProgress({...partial,digest:"b".repeat(64)},expected)).toThrow("binding"); - expect(()=>proofProgress({...partial,archive_verified:true},expected)).toThrow("certification"); - expect(()=>proofProgress({...partial,phase:["awaiting_import"]},expected)).toThrow("progress"); - expect(()=>proofProgress({...partial,phase:"verified",archive_verified:true},expected)).toThrow("certification"); - expect(()=>proofProgress({...partial,phase:"verified",archive_verified:true,verified_count:424926,pending_trees:1},expected)).toThrow("certification"); - expect(proofProgress({...partial,phase:"verified",archive_verified:true,verified_count:424926},expected).archive_verified).toBe(true); -}); diff --git a/services/advisories/test/bounded-body.test.ts b/services/advisories/test/bounded-body.test.ts deleted file mode 100644 index 47240a95c..000000000 --- a/services/advisories/test/bounded-body.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { expect, test } from "bun:test"; -import { boundedBody } from "../src/domain"; - -test("an oversized body releases its reader and retains the limit diagnostic", async () => { - const body = new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array([1, 2])); - }, - cancel() { - throw new Error("upstream cleanup failed"); - }, - }); - - await expect(boundedBody(body, 1)).rejects.toThrow("body exceeds limit"); - expect(body.locked).toBeFalse(); -}); diff --git a/services/advisories/test/cache-failure.test.ts b/services/advisories/test/cache-failure.test.ts deleted file mode 100644 index e35c65175..000000000 --- a/services/advisories/test/cache-failure.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { expect, mock, test } from "bun:test"; -import { cachedRead } from "../src/cache"; - -const request = new Request("https://advisories.example/v1/cves/recent"); - -const expires = "Mon, 30 Nov 2026 18:00:00 GMT"; - -test("delivers a fresh advisory when writing to the cache throws synchronously", async () => { - const put = mock(() => { throw new Error("cache unavailable"); }); - - const result = await cachedRead( - request, - { match: async () => undefined, put }, - async () => new Response("from origin", { headers: { "Cache-Control": "public, max-age=60" } }), - ); - - expect(await result.text()).toBe("from origin"); - expect(put).toHaveBeenCalledTimes(1); -}); - -test("cancels the unused cached body on a matching conditional request", async () => { - const cancel = mock(() => undefined); - const body = new ReadableStream({ cancel }); - const incoming = new Request(request, { headers: { "If-None-Match": 'W/"known"' } }); - const hit = new Response(body, { headers: { ETag: '"known"', Expires: expires } }); - - const result = await cachedRead( - incoming, - { match: async () => hit, put: async () => undefined }, - async () => { throw new Error("unexpected origin call"); }, - Date.parse(expires) - 1000, - ); - - expect(result.status).toBe(304); - expect(result.body).toBeNull(); - expect(cancel).toHaveBeenCalledTimes(1); -}); diff --git a/services/advisories/test/cache-worker.test.ts b/services/advisories/test/cache-worker.test.ts deleted file mode 100644 index ba8fd69f2..000000000 --- a/services/advisories/test/cache-worker.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { expect, test } from "bun:test"; -import { readFile } from "node:fs/promises"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { Miniflare, convertV4MiniflareOptions } from "miniflare"; -import { unstable_splitSqlQuery } from "wrangler"; -import { Store, d1Sql, type Sql } from "../src/storage"; -import { recentCves } from "../src/recent"; -import { object } from "../src/domain"; - -test("real Worker caches public reads, isolates private reads and uses indexed recent pages", async () => { - const build = await Bun.build({ - entrypoints: [fileURLToPath(new NodeURL("../src/index.ts", import.meta.url))], target: "browser", - }); - expect(build.success).toBe(true); - const output = build.outputs[0]; - if (!output) throw new Error("missing Worker bundle"); - const runtime = new Miniflare(convertV4MiniflareOptions({ - modules: true, script: await output.text(), compatibilityDate: "2026-11-13", - d1Databases: ["DB"], r2Buckets: ["RAW"], - bindings: { CVE_BATCH_SIZE: "32" }, - })); - try { - const db = await runtime.getD1Database("DB"); - for (const name of ["0001_advisories.sql", "0002_baseline_member_counter.sql", "0004_epss_cache.sql", "0006_baseline_publisher_proof.sql"]) { - const source = await readFile(new NodeURL(`../migrations/${name}`, import.meta.url), "utf8"); - await db.batch(unstable_splitSqlQuery(source).map((query) => db.prepare(query))); - } - const raw = await runtime.getR2Bucket("RAW"); - const sql = d1Sql(db); - const store = new Store(sql, raw); - const now = new Date().toISOString(); - await db.prepare("UPDATE source_checkpoint SET checked_at=?,complete=1,bootstrap_complete=1").bind(now).run(); - const id = "CVE-2026-9999"; - await store.cve(JSON.stringify({ - dataType: "CVE_RECORD", dataVersion: "5.2", - cveMetadata: { cveId: id, state: "PUBLISHED", dateUpdated: now, datePublished: now }, - containers: { cna: {} }, - }), now); - const worker = await runtime.getWorker(); - const url = `https://advisories.example/v1/cves/${id}`; - const first = await worker.fetch(url); - expect(first.status).toBe(200); - expect(first.headers.get("cache-control")).toMatch(/^public, max-age=\d+, must-revalidate$/); - const tag = first.headers.get("etag"); - expect(object(await first.json()).kev).toBeNull(); - await db.prepare("INSERT INTO kev_annotation VALUES(?,?,?)").bind(id, JSON.stringify({ cveID: id }), "a".repeat(64)).run(); - const hit = await worker.fetch(url); - expect(object(await hit.json()).kev).toBeNull(); - expect((await worker.fetch(url, { headers: { "if-none-match": String(tag) } })).status).toBe(304); - const bypass = await worker.fetch(url, { headers: { authorization: "Bearer private" } }); - expect(bypass.headers.get("cache-control")).toBe("no-store"); - expect(object(await bypass.json()).kev).toEqual({ cveID: id }); - const refreshed = await worker.fetch(url, { headers: { "cache-control": "no-cache" } }); - expect(object(await refreshed.json()).kev).toEqual({ cveID: id }); - expect(refreshed.headers.get("etag")).not.toBe(tag); - expect((await worker.fetch("https://advisories.example/v1/status")).headers.get("cache-control")).toBe("no-store"); - - const summaryUrl = `${url}?view=summary`; - - const summary = await worker.fetch(summaryUrl, { - headers: { "if-none-match": String(refreshed.headers.get("etag")) }, - }); - - const summaryTag = summary.headers.get("etag"); - - expect(summary.status).toBe(200); - expect(summaryTag).not.toBe(refreshed.headers.get("etag")); - expect(object(await summary.json())).not.toHaveProperty("payload_json"); - expect((await worker.fetch(summaryUrl, { - headers: { "if-none-match": String(summaryTag) }, - })).status).toBe(304); - - const stillExact = await worker.fetch(url, { - headers: { "if-none-match": String(summaryTag) }, - }); - - expect(stillExact.status).toBe(200); - expect(object(await stillExact.json())).toHaveProperty("payload_json"); - - await db.prepare("INSERT INTO epss_cache VALUES(?,?,?,?,0)").bind(id, now, now, JSON.stringify({ - status: "OK", "status-code": 200, total: 1, offset: 0, - data: [{ cve: id, epss: "0.25", percentile: "0.9", date: now.slice(0, 10), "time-series": [] }], - })).run(); - const epssUrl = `https://advisories.example/v1/epss/${id}`; - const scored = await worker.fetch(epssUrl); - const epssTag = scored.headers.get("etag"); - expect(object(await scored.json()).status).toBe("scored"); - expect(scored.headers.get("cache-control")).toContain("public"); - expect((await worker.fetch(epssUrl, { headers: { "if-none-match": String(epssTag) } })).status).toBe(304); - await db.prepare("UPDATE epss_cache SET error=1 WHERE cve_id=?").bind(id).run(); - expect(object(await (await worker.fetch(epssUrl)).json()).status).toBe("scored"); - const failedEpss = object(await (await worker.fetch(epssUrl, { headers: { "cache-control": "no-cache" } })).json()); - expect(failedEpss.status).toBe("unavailable"); - expect(failedEpss.score).toBeNull(); - - await db.prepare("INSERT INTO source_record SELECT 'CVE-2020-'||(1000+value),'cve','https://example.invalid','5.2','PUBLISHED','2020-01-01T00:00:00.000Z','2020-01-01T00:00:00.000Z',?,'hash','fixture',1,1 FROM json_each(?)") - .bind(now, JSON.stringify(Array.from({ length: 4096 }, (_, n) => n))).run(); - const migration = await readFile(new NodeURL("../migrations/0003_recent_cves.sql", import.meta.url), "utf8"); - const index = await db.prepare(migration).run(); - let rowsRead = 0; - const measured: Sql = { ...sql, all: async (query: string, values: (string | number | null)[] = []) => { - const result = await db.prepare(query).bind(...values).all(); - rowsRead += result.meta.rows_read; - return result.results; - } }; - const page = await recentCves(new URL("https://advisories.example/v1/cves/recent?limit=2"), measured, now); - expect(page.records.map((record) => record.id)).toEqual([id]); - expect(rowsRead).toBeLessThanOrEqual(12); - process.stdout.write(`recent D1 page: ${JSON.stringify({ totalRecords: 4097, returned: page.records.length, rowsRead, migrationRowsRead: index.meta.rows_read, migrationRowsWritten: index.meta.rows_written })}\n`); - await db.prepare("UPDATE source_checkpoint SET bootstrap_complete=0 WHERE source='cve'").run(); - await store.cve(JSON.stringify({ - dataType: "CVE_RECORD", dataVersion: "5.2", - cveMetadata: { cveId: "CVE-2026-10000", state: "PUBLISHED", dateUpdated: now, datePublished: now }, - containers: { cna: {} }, - }), now); - const recentUrl = "https://advisories.example/v1/cves/recent"; - const recent = await worker.fetch(recentUrl); - expect(object(await recent.json())).toMatchObject({ - complete: false, records: [{ id }, { id: "CVE-2026-10000" }], - }); - // These requests have the same pathname and different public representations. - const narrowerUrl = `${recentUrl}?limit=1`; - const narrower = await worker.fetch(narrowerUrl); - expect(narrower.status).toBe(200); - expect(narrower.headers.get("etag")).not.toBe(recent.headers.get("etag")); - expect(object(await narrower.json())).toMatchObject({ records: [{ id }] }); - const conditional = await worker.fetch(narrowerUrl, { - headers: { "if-none-match": String(narrower.headers.get("etag")) }, - }); - expect(conditional.status).toBe(304); - const invalidPage = await worker.fetch(`${recentUrl}?limit=0`); - expect(invalidPage.status).toBe(400); - expect(invalidPage.headers.get("cache-control")).toBe("no-store"); - } finally { - await runtime.dispose(); - } -}, 30_000); diff --git a/services/advisories/test/d1-cost.test.ts b/services/advisories/test/d1-cost.test.ts deleted file mode 100644 index c11934e63..000000000 --- a/services/advisories/test/d1-cost.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { expect, test } from "bun:test"; -import { mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { Miniflare, convertV4MiniflareOptions } from "miniflare"; -import { unstable_splitSqlQuery } from "wrangler"; -import { handle } from "../src/service"; -import { d1Sql, Store, type Sql } from "../src/storage"; -import { object } from "../src/domain"; - -const token = "baseline-cost-fixture-token-at-least-32-characters"; -const now = "2026-11-13T02:00:00.000Z"; - -async function directoryBytes(path: string): Promise { - let bytes = 0; - for (const entry of await readdir(path, { withFileTypes: true })) { - const child = join(path, entry.name); - bytes += entry.isDirectory() ? await directoryBytes(child) : (await stat(child)).size; - } - return bytes; -} - -async function measureImport(count: number) { - const scratch = await mkdtemp(join(tmpdir(), "omg-advisory-counter-cost-")); - const runtime = new Miniflare(convertV4MiniflareOptions({ - modules: true, - script: "export default { fetch() { return new Response('fixture'); } };", - compatibilityDate: "2026-11-13", - d1Databases: ["DB"], - resourcePersistencePath: scratch, - })); - try { - const db = await runtime.getD1Database("DB"); - const initial = await readFile(new NodeURL("../migrations/0001_advisories.sql", import.meta.url), "utf8"); - await db.batch(unstable_splitSqlQuery(initial).map((statement) => db.prepare(statement))); - const counter = await readFile(new NodeURL("../migrations/0002_baseline_member_counter.sql", import.meta.url), "utf8"); - await db.batch(unstable_splitSqlQuery(counter).map((statement) => db.prepare(statement))); - const proof = await readFile(new NodeURL("../migrations/0006_baseline_publisher_proof.sql", import.meta.url), "utf8"); - await db.batch(unstable_splitSqlQuery(proof).map((statement) => db.prepare(statement))); - let rowsRead = 0; - const measured = { - prepare: db.prepare.bind(db), - batch: async ( - statements: D1PreparedStatement[], - ): Promise[]> => { - const result = await db.batch(statements); - rowsRead += result.reduce((sum, row) => sum + row.meta.rows_read, 0); - return result; - }, - } satisfies Pick; - const sql = d1Sql(measured); - const store = new Store(sql, { put: async () => {}, get: async () => null }, () => now); - const post = async (path: string, payload: unknown) => { - const response = await handle(new Request(`https://advisories.example${path}`, { - method: "POST", - headers: { authorization: `Bearer ${token}` }, - body: JSON.stringify(payload), - }), store, token, now); - expect(response.status).toBe(200); - return object(await response.json()); - }; - const baseline = await post("/internal/baseline/start", { digest: "a".repeat(64), baseline_at: now }); - rowsRead = 0; - for (let offset = 0; offset < count; offset += 8) { - const records = Array.from({ length: Math.min(8, count - offset) }, (_, index) => JSON.stringify({ - dataType: "CVE_RECORD", - dataVersion: "5.2", - cveMetadata: { - cveId: `CVE-2026-${1000 + offset + index}`, - state: "PUBLISHED", - dateUpdated: now, - datePublished: now, - }, - containers: { cna: {} }, - })); - await post("/internal/ingest", { source: "cve", records, baseline }); - } - const mutationRowsRead = rowsRead; - const receipt = await db.prepare("SELECT accepted FROM baseline_receipt").first<{ accepted: number }>(); - expect(receipt?.accepted).toBe(count); - let statusRows = 0; - const statusSql: Sql = { - ...sql, - first: async (query: string, values: (string | number | null)[] = []) => { - const result = await db.prepare(query).bind(...values).all(); - statusRows += result.meta.rows_read; - return result.results[0] ?? null; - }, - all: async (query: string, values: (string | number | null)[] = []) => { - const result = await db.prepare(query).bind(...values).all(); - statusRows += result.meta.rows_read; - return result.results; - }, - }; - const status = await handle(new Request("https://advisories.example/v1/status"), new Store(statusSql, store.raw), undefined, now); - const body = object(await status.json()); - expect(object(body.baseline).imported).toBe(count); - expect(body.bootstrap_complete).toBe(false); - const scratchBytes = await directoryBytes(scratch); - expect(scratchBytes).toBeLessThanOrEqual(50 * 1024 ** 2); - return { count, mutationRowsRead, statusRows, scratchBytes }; - } finally { - try { - await runtime.dispose(); - } finally { - await rm(scratch, { recursive: true, force: true }); - } - } -} - -test("D1 baseline mutations have a linear read budget and status has a constant read budget", async () => { - const small = await measureImport(128); - const large = await measureImport(256); - process.stdout.write(`D1 rows_read ${JSON.stringify({ small, large })}\n`); - expect(small.mutationRowsRead).toBeLessThanOrEqual(32 * small.count); - expect(large.mutationRowsRead).toBeLessThanOrEqual(32 * large.count); - expect(large.mutationRowsRead).toBeLessThanOrEqual(2 * small.mutationRowsRead + 32); - expect(small.statusRows).toBeLessThanOrEqual(16); - expect(large.statusRows).toBeLessThanOrEqual(16); -}, 30_000); - -function largeCveFixture(id = "CVE-2026-1234", bytes = 2_402_038): string { - const description = {lang: "en", value: "Generated structured CNA/ADP fixture; preserve UTF8 é and raw whitespace."}; - const payload = { - dataType: "CVE_RECORD", dataVersion: "5.2", - cveMetadata: {cveId: id, state: "PUBLISHED", dateUpdated: "2026-11-13T02:00:00.000Z", datePublished: "2026-11-11T00:00:00Z"}, - containers: { - cna: { - providerMetadata: {orgId: "00000000-0000-4000-8000-000000000001", shortName: "fixture-CNA"}, - descriptions: [description], - affected: [{vendor: "fixture-vendor", product: "fixture-product", defaultStatus: "unaffected", - versions: Array.from({length: 11_000}, (_, index) => ({version: `${index}.0.0`, status: "affected", lessThan: `${index + 1}.0.0`, versionType: "semver"}))}], - }, - adp: [{providerMetadata: {orgId: "00000000-0000-4000-8000-000000000002", shortName: "fixture-ADP"}, - affected: Array.from({length: 1_600}, (_, index) => ({vendor: `vendor-${index}`, product: `product-${index}`, versions: [{version: `${index}.1`, status: "affected"}]}))}], - }, - }; - const encode = () => `\n${JSON.stringify(payload, null, 2)}\n`; - const padding = bytes - Buffer.byteLength(encode()); - if (padding < 0) throw new Error("large CVE fixture structure exceeds requested byte size"); - description.value += "x".repeat(padding); - const raw = encode(); - if (Buffer.byteLength(raw) !== bytes) throw new Error("large CVE fixture byte size mismatch"); - return raw; -} - -test("real workerd route roundtrips a structured 2.4 MB CVE through private R2 and small D1 rows", async () => { - const {sha256, string, parseCve} = await import("../src/domain"); - const build = await Bun.build({entrypoints: [fileURLToPath(new NodeURL("../src/index.ts", import.meta.url))], target: "browser"}); - expect(build.success).toBe(true); - const output = build.outputs[0]; - if (!output) throw new Error("missing bundled real Worker entrypoint"); - const scratch = await mkdtemp(join(tmpdir(), "omg-advisory-large-worker-")); - const runtime = new Miniflare(convertV4MiniflareOptions({modules: true, script: await output.text(), - compatibilityDate: "2026-11-13", d1Databases: ["DB"], r2Buckets: ["RAW"], - bindings: {INGEST_TOKEN: token, CVE_BATCH_SIZE: "32"}, resourcePersistencePath: scratch})); - try { - const db = await runtime.getD1Database("DB"); - for (const name of ["0001_advisories.sql", "0002_baseline_member_counter.sql", "0006_baseline_publisher_proof.sql"]) { - const source = await readFile(new NodeURL(`../migrations/${name}`, import.meta.url), "utf8"); - await db.batch(unstable_splitSqlQuery(source).map((statement) => db.prepare(statement))); - } - const worker = await runtime.getWorker(); - const initialStatus = await worker.fetch("https://advisories.example/v1/status"); - expect(initialStatus.status).toBe(200); - expect(object(await initialStatus.json()).bootstrap_complete).toBe(false); - const raw = largeCveFixture(); - const hash = await sha256(raw); - const wire = JSON.stringify({source: "cve", records: [raw]}); - expect(Buffer.byteLength(raw)).toBe(2_402_038); - expect(Buffer.byteLength(wire)).toBeLessThanOrEqual(4 * 1024 ** 2); - const started = performance.now(); - const imported = await worker.fetch("https://advisories.example/internal/ingest", {method: "POST", headers: {authorization: `Bearer ${token}`}, body: wire}); - expect(imported.status).toBe(200); - const response = await worker.fetch("https://advisories.example/v1/cves/CVE-2026-1234"); - expect(response.status).toBe(200); - const encodedResponse = await response.text(); - expect(Buffer.byteLength(encodedResponse)).toBeLessThanOrEqual(4 * 1024 ** 2); - const body = object(JSON.parse(encodedResponse)); - expect(string(body.payload_json)).toBe(raw); - expect(await sha256(string(body.payload_json))).toBe(hash); - expect(object(body.provenance).payload_sha256).toBe(hash); - expect(body.package_applicability).toBe("unknown"); - const row = await db.prepare("SELECT *,length(id)+length(source)+length(source_url)+length(schema_version)+length(state)+length(published_at)+length(modified_at)+length(fetched_at)+length(payload_sha256)+length(object_key) AS scalar_bytes FROM source_record").first<{object_key: string; payload_sha256: string; scalar_bytes: number}>(); - if (!row) throw new Error("large CVE metadata pointer missing"); - expect(row.payload_sha256).toBe(hash); - expect(row.scalar_bytes).toBeLessThan(1024); - const bucket = await runtime.getR2Bucket("RAW"); - expect(await (await bucket.get(row.object_key))?.text()).toBe(raw); - const bulkRecords = [largeCveFixture("CVE-2026-1240"), - ...Array.from({length: 7}, (_, index) => JSON.stringify({ - dataType: "CVE_RECORD", dataVersion: "5.2", - cveMetadata: {cveId: `CVE-2026-${2000+index}`, state: "PUBLISHED", - dateUpdated: now, datePublished: now}, - containers: {cna: {}}, - }))]; - const bulkWire = JSON.stringify({source: "cve", records: bulkRecords}); - expect(Buffer.byteLength(bulkWire)).toBeLessThanOrEqual(4 * 1024 ** 2); - const bulk = await worker.fetch("https://advisories.example/internal/ingest", { - method: "POST", headers: {authorization: `Bearer ${token}`}, body: bulkWire, - }); - expect(bulk.status).toBe(200); - expect(object(await bulk.json()).accepted).toBe(8); - for (const expected of bulkRecords) { - const response = await worker.fetch(`https://advisories.example/v1/cves/${parseCve(expected).id}`); - expect(response.status).toBe(200); - const body = object(await response.json()); - expect(string(body.payload_json)).toBe(expected); - expect(object(body.provenance).payload_sha256).toBe(await sha256(expected)); - expect(body.package_applicability).toBe("unknown"); - } - expect(await db.prepare("SELECT COUNT(*) AS count FROM source_record").first<{count: number}>()) - .toEqual({count: 9}); - const over = JSON.stringify({source: "cve", records: [largeCveFixture("CVE-2026-1235", 3 * 1024 ** 2 + 1)]}); - expect(Buffer.byteLength(over)).toBeLessThan(4 * 1024 ** 2); - const refused = await worker.fetch("https://advisories.example/internal/ingest", {method: "POST", headers: {authorization: `Bearer ${token}`}, body: over}); - expect(refused.status).toBe(400); - expect(await db.prepare("SELECT id FROM source_record WHERE id=?").bind("CVE-2026-1235").first()).toBe(null); - const status = object(await (await worker.fetch("https://advisories.example/v1/status")).json()); - expect(status.bootstrap_complete).toBe(false); - const scratchBytes = await directoryBytes(scratch); - expect(scratchBytes).toBeLessThanOrEqual(50 * 1024 ** 2); - process.stdout.write(`large CVE real workerd ${JSON.stringify({rawBytes: Buffer.byteLength(raw), wireBytes: Buffer.byteLength(wire), responseBytes: Buffer.byteLength(encodedResponse), scalarBytes: row.scalar_bytes, scratchBytes, routeWallMilliseconds: performance.now() - started, cpuAndIsolateRss: "not measured by this binding test"})}\n`); - } finally { - try { - await runtime.dispose(); - } finally { - await rm(scratch, {recursive: true, force: true}); - } - } -}, 30_000); diff --git a/services/advisories/test/delta.test.ts b/services/advisories/test/delta.test.ts deleted file mode 100644 index d95263890..000000000 --- a/services/advisories/test/delta.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { test, expect } from "bun:test"; -import { deltaBatch, readDeltaCursor } from "../src/delta"; -import { cveUrl } from "../src/domain"; - -test("preserves a parse error when canceling the delta stream fails", async () => { - const body = new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode('{"wrong":{}}')); - }, - cancel() { - throw new Error("transport cleanup failed"); - }, - }); - - await expect(deltaBatch(body, null)).rejects.toThrow("invalid delta root"); - expect(body.locked).toBe(false); -}); - -const time = "2026-11-13T01:00:00.000Z"; - -function event(ids: string[]) { - return { - fetchTime: time, - numberOfChanges: ids.length, - new: ids.map((id) => ({ - cveId: id, - githubLink: cveUrl(id), - dateUpdated: time, - })), - updated: [], - error: [], - }; -} - -test("streamed delta drains oversized events across bounded checkpoint batches", async () => { - const raw = JSON.stringify([ - event(Array.from({ length: 10 }, (_, i) => `CVE-2026-${1234 + i}`)), - ]); - - const one = await deltaBatch(new Response(raw).body, null); - expect(one.batch.length).toBe(4); - expect(one.caughtUp).toBe(false); - const last = one.batch.at(-1); - - if (!last) throw new Error("missing batch"); - - const two = await deltaBatch(new Response(raw).body, { - event: time, - offset: last.offset, - }); - - expect(two.batch[0]?.item.id).toBe("CVE-2026-1238"); - expect(two.caughtUp).toBe(false); - - const three = await deltaBatch(new Response(raw).body, { - event: time, - offset: 8, - }); - - expect(three.batch.length).toBe(2); - expect(three.caughtUp).toBe(true); -}); - -test("resumes between feed entries that share a timestamp", async () => { - const raw = JSON.stringify([ - event(["CVE-2026-1234", "CVE-2026-1236"]), - event(["CVE-2026-1235", "CVE-2026-1237"]), - ]); - - const first = await deltaBatch(new Response(raw).body, null, 2); - expect(first.batch.map(({ item, offset }) => [item.id, offset])).toEqual([ - ["CVE-2026-1234", 1], - ["CVE-2026-1236", 2], - ]); - expect(first.caughtUp).toBe(false); - - expect(first.nextCursor).toEqual({ event: time, offset: 2, feedOrder: true }); - - const resumed = await deltaBatch(new Response(raw).body, first.nextCursor, 2); - expect(resumed.batch.map(({ item, offset }) => [item.id, offset])).toEqual([ - ["CVE-2026-1235", 3], - ["CVE-2026-1237", 4], - ]); - expect(resumed.caughtUp).toBe(true); -}); - -test("replays a shared timestamp once when resuming a legacy cursor", async () => { - const raw = JSON.stringify([ - event(["CVE-2026-1236", "CVE-2026-1237"]), - event(["CVE-2026-1234", "CVE-2026-1235"]), - ]); - - const replay = await deltaBatch(new Response(raw).body, { event: time, offset: 2 }, 2); - - expect(replay.batch.map(({ item }) => item.id)).toEqual(["CVE-2026-1236", "CVE-2026-1237"]); - expect(replay.nextCursor).toEqual({ event: time, offset: 2, feedOrder: true }); - expect(replay.caughtUp).toBe(false); - - const next = await deltaBatch(new Response(raw).body, readDeltaCursor(JSON.stringify(replay.nextCursor)), 2); - expect(next.batch.map(({ item }) => item.id)).toEqual(["CVE-2026-1234", "CVE-2026-1235"]); - expect(next.caughtUp).toBe(true); -}); - -test("production batch drains 128 changes before resuming from its last committed offset", async () => { - const raw = JSON.stringify([ - event(Array.from({ length: 129 }, (_, i) => `CVE-2026-${1234 + i}`)), - ]); - - const first = await deltaBatch(new Response(raw).body, null, 128); - - expect(first.batch).toHaveLength(128); - expect(first.batch.at(-1)?.item.id).toBe("CVE-2026-1361"); - expect(first.caughtUp).toBe(false); - - const remaining = await deltaBatch(new Response(raw).body, { event: time, offset: 128 }, 128); - - expect(remaining.batch.map(({ item }) => item.id)).toEqual(["CVE-2026-1362"]); - expect(remaining.caughtUp).toBe(true); - await expect(deltaBatch(new Response(raw).body, null, 513)).rejects.toThrow("invalid delta batch limit"); -}); - -test("malformed streams and missing replay history fail closed", async () => { - await expect( - deltaBatch( - new Response( - JSON.stringify([event(["CVE-2026-1234"])]).slice(0, -1), - ).body, - null, - ), - ).rejects.toThrow(); - await expect( - deltaBatch( - new Response(JSON.stringify([event(["CVE-2026-1234"])])).body, - { event: "2026-10-01T00:00:00.000Z", offset: 0 }, - ), - ).rejects.toThrow("continuity"); - await expect( - deltaBatch(new Response('{"wrong":{}}').body, null), - ).rejects.toThrow("root"); -}); diff --git a/services/advisories/test/epss.test.ts b/services/advisories/test/epss.test.ts deleted file mode 100644 index e9dc05901..000000000 --- a/services/advisories/test/epss.test.ts +++ /dev/null @@ -1,247 +0,0 @@ -import { test, expect } from "bun:test"; -import { Database } from "bun:sqlite"; -import { readFileSync } from "node:fs"; -import { URL as NodeURL } from "node:url"; -import { Store, type Sql, type Command } from "../src/storage"; -import { epss } from "../src/epss"; -import { handle } from "../src/service"; -import { object } from "../src/domain"; - -const id = "CVE-2021-23337"; - -const now = "2026-11-17T02:00:00.000Z"; - -function setup() { - const db = new Database(":memory:"); - - for (const name of ["0001_advisories.sql", "0004_epss_cache.sql", "0006_baseline_publisher_proof.sql"]) - db.exec(readFileSync(new NodeURL(`../migrations/${name}`, import.meta.url), "utf8")); - - const sql: Sql = { - first: async (text: string, values: (string | number | null)[] = []) => db.query(text).get(...values), - all: async (text: string, values: (string | number | null)[] = []) => db.query(text).all(...values), - batch: async (commands: Command[]) => { db.transaction(() => { for (const command of commands) db.query(command.sql).run(...command.values); })(); }, - }; - - db.exec(`INSERT INTO source_record VALUES('${id}','cve','https://example.test','5.2','PUBLISHED',NULL,'${now}','${now}','hash','key',1,1)`); - let clock = now; - - return { db, store: new Store(sql, { put: async () => {}, get: async () => null }, () => clock), setClock: (value: string) => { clock = value; } }; -} - -function payload(score = "0.000000000") { - return { status: "OK", "status-code": 200, total: 1, offset: 0, data: [{ cve: id, epss: score, percentile: "0.100000000", date: "2026-11-16", "time-series": [{ epss: "0.2", percentile: "0.9", date: "2026-11-15" }] }] }; -} - -test("EPSS caches genuine zero scores and bounded history in real SQLite", async () => { - const { store, db } = setup(); - - try { - let calls = 0; - - const fetcher = async (url: string, init?: RequestInit) => { - calls++; - expect(url).toBe(`https://api.first.org/data/v1/epss?cve=${id}&scope=time-series`); - expect(init?.redirect).toBe("manual"); - expect(init?.signal).toBeDefined(); - - return Response.json(payload()); - }; - - const first = await epss(store, id, now, fetcher); - expect(first.status).toBe("scored"); - expect(first.score?.epss).toBe(0); - expect(first.history.length).toBe(2); - expect(await epss(store, id, now, fetcher)).toEqual(first); - expect(calls).toBe(1); - expect(db.query("SELECT count(*) AS n FROM epss_cache").get()).toEqual({ n: 1 }); - } finally { db.close(); } -}); - -test("an upstream HTTP failure releases the EPSS lease despite pending body cleanup", async () => { - const { store, db } = setup(); - const cleanup = new AbortController(); - - const body = new ReadableStream({ - cancel() { - return new Promise(resolve => { - cleanup.signal.addEventListener("abort", () => resolve(), { once: true }); - }); - }, - }); - - let timeout: ReturnType | undefined; - const refresh = epss(store, id, now, async () => new Response(body, { status: 503 })); - - try { - const result = await Promise.race([ - refresh, - new Promise(resolve => { - timeout = setTimeout(() => resolve(null), 200); - }), - ]); - - expect(result?.status).toBe("unavailable"); - expect(await store.lease(`epss:${id}`, "replacement", now)).toBeTrue(); - } finally { - clearTimeout(timeout); - cleanup.abort(); - await refresh; - db.close(); - } -}); - -test("missing EPSS scores and transport failures never become zero", async () => { - for (const missing of [true, false]) { - const { store, db } = setup(); - - try { - const result = await epss(store, id, now, async () => missing ? Response.json({ status: "OK", "status-code": 200, total: 0, offset: 0, data: [] }) : new Response(null, { status: 503 })); - expect(result.status).toBe(missing ? "missing" : "unavailable"); - expect(result.score).toBeNull(); - expect(result.history).toEqual([]); - } finally { db.close(); } - } -}); - -test("malformed, mismatched, partial and future EPSS evidence is unavailable", async () => { - for (const change of ["id", "score", "future", "duplicate", "partial", "oversize"]) { - const { store, db } = setup(); - - try { - const value = payload(); - const row = value.data[0]; - - if (!row) throw new Error("missing fixture row"); - - if (change === "id") row.cve = "CVE-2021-99999"; - - if (change === "score") row.epss = "NaN"; - - if (change === "future") row.date = "2026-11-18"; - - if (change === "duplicate") row["time-series"].push({ epss: "0.2", percentile: "0.9", date: "2026-11-15" }); - - if (change === "partial") value.total = 2; - const result = await epss(store, id, now, async () => change === "oversize" ? new Response("x".repeat(64 * 1024 + 1)) : Response.json(value)); - expect(result.status).toBe("unavailable"); - expect(result.score).toBeNull(); - } finally { db.close(); } - } -}); - -test("failed refresh preserves last history, backs off and recovers", async () => { - const { store, db, setClock } = setup(); - - try { - await epss(store, id, now, async () => Response.json(payload("0.25"))); - const later = "2026-11-17T09:00:00.000Z"; - setClock(later); - let calls = 0; - const unavailable = async () => { calls++; throw new Error("offline"); }; - - const failed = await epss(store, id, later, unavailable); - expect(failed.status).toBe("unavailable"); - expect(failed.score).toBeNull(); - expect(failed.history[0]?.epss).toBe(0.25); - await epss(store, id, later, unavailable); - expect(calls).toBe(1); - const recoveredAt = "2026-11-17T09:02:00.000Z"; - setClock(recoveredAt); - expect((await epss(store, id, recoveredAt, async () => Response.json(payload("0.4")))).score?.epss).toBe(0.4); - } finally { db.close(); } -}); - -test("unknown CVEs do not trigger upstream lookups or cache writes", async () => { - const { store, db } = setup(); - - try { - await expect(epss(store, "CVE-2026-9999999", now, async () => { throw new Error("must not fetch"); })).rejects.toThrow("CVE unavailable"); - expect(db.query("SELECT count(*) AS n FROM epss_cache").get()).toEqual({ n: 0 }); - } finally { db.close(); } -}); - -test("EPSS history rolls at thirty days and stale scores stay unavailable", async () => { - const { store, db, setClock } = setup(); - - try { - const value = payload("0.3"); - const row = value.data[0]; - - if (!row) throw new Error("missing fixture row"); - row.date = "2026-11-17"; - row["time-series"] = Array.from({ length: 30 }, (_, index) => ({ epss: "0.2", percentile: "0.9", date: new Date(Date.parse("2026-11-17T00:00:00Z") - (index + 1) * 86400000).toISOString().slice(0, 10) })); - const first = await epss(store, id, now, async () => Response.json(value)); - expect(first.history.length).toBe(30); - expect(first.history.at(-1)?.date).toBe("2026-10-19"); - const later = "2026-11-20T02:00:00.000Z"; - setClock(later); - const stale = await epss(store, id, later, async () => Response.json(value)); - expect(stale.status).toBe("unavailable"); - expect(stale.score).toBeNull(); - expect(stale.history.at(-1)?.date).toBe("2026-10-22"); - } finally { db.close(); } -}); - -test("EPSS refresh respects another writer and rejects an expired lease atomically", async () => { - const { store, db, setClock } = setup(); - - try { - expect(await store.lease(`epss:${id}`, "other", now)).toBeTrue(); - let calls = 0; - - const fetcher = async () => { - calls++; - - return Response.json(payload("0.25")); - }; - - expect((await epss(store, id, now, fetcher)).status).toBe("unavailable"); - expect(calls).toBe(0); - await store.release(`epss:${id}`, "other"); - await epss(store, id, now, fetcher); - const previous = db.query("SELECT * FROM epss_cache").get(); - const later = "2026-11-17T09:00:00.000Z"; - setClock(later); - await expect(epss(store, id, later, async () => { - setClock("2026-11-17T09:11:00.000Z"); - - return Response.json(payload("0.5")); - })).rejects.toThrow(); - expect(db.query("SELECT * FROM epss_cache").get()).toEqual(previous); - } finally { db.close(); } -}); - -test("EPSS HTTP routing supports ETags and rejects invalid queries without upstream work", async () => { - const { store, db } = setup(); - - try { - let calls = 0; - - const fetcher = async () => { - calls++; - - return Response.json(payload("0.25")); - }; - - const url = `https://advisories.example/v1/epss/${id}`; - const response = await handle(new Request(url), store, undefined, now, fetcher); - expect(response.status).toBe(200); - expect(object(await response.json()).status).toBe("scored"); - expect(response.headers.get("Cache-Control")).toContain("public"); - const etag = response.headers.get("ETag"); - - if (!etag) throw new Error("missing EPSS ETag"); - const conditional = await handle(new Request(url, { headers: { "If-None-Match": etag } }), store, undefined, now, fetcher); - expect(conditional.status).toBe(304); - expect(await conditional.text()).toBe(""); - const invalid = await handle(new Request(`${url}?cve=other`), store, undefined, now, fetcher); - expect(invalid.status).toBe(400); - expect(invalid.headers.get("Cache-Control")).toBe("no-store"); - db.exec("UPDATE epss_cache SET error=1"); - const unavailable = await handle(new Request(url), store, undefined, now, fetcher); - expect(object(await unavailable.json()).status).toBe("unavailable"); - expect(unavailable.headers.get("Cache-Control")).toBe("no-store"); - expect(calls).toBe(1); - } finally { db.close(); } -}); diff --git a/services/advisories/test/fixtures/nine.zip b/services/advisories/test/fixtures/nine.zip deleted file mode 100644 index 568d46c9c..000000000 Binary files a/services/advisories/test/fixtures/nine.zip and /dev/null differ diff --git a/services/advisories/test/fixtures/tiny.zip b/services/advisories/test/fixtures/tiny.zip deleted file mode 100644 index 56e036ca6..000000000 Binary files a/services/advisories/test/fixtures/tiny.zip and /dev/null differ diff --git a/services/advisories/test/fixtures/wrong-year.zip b/services/advisories/test/fixtures/wrong-year.zip deleted file mode 100644 index 056172a29..000000000 Binary files a/services/advisories/test/fixtures/wrong-year.zip and /dev/null differ diff --git a/services/advisories/test/github-cooldown.test.ts b/services/advisories/test/github-cooldown.test.ts deleted file mode 100644 index df66bef39..000000000 --- a/services/advisories/test/github-cooldown.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { expect, test } from "bun:test"; -import { githubAwareFetch } from "../src/github-cooldown"; - -const now = "2026-11-30T19:33:00Z"; - -const firstUrl = "https://api.github.com/repos/adoptium/temurin-vdr-generator/releases/latest"; - -const otherUrl = "https://api.github.com/repos/oven-sh/bun/security-advisories"; - -function memory() { - const objects = new Map(); - - return { - put: async (key: string, value: string) => { objects.set(key, value); }, - get: async (key: string) => { - const value = objects.get(key); - - return value === undefined ? null : { text: async () => value }; - }, - }; -} - -test("public cooldown applies across GitHub sources without disabling authenticated refresh or release assets", async () => { - const raw = memory(); - const reset = Date.parse(now) / 1000 + 600; - const seen: string[] = []; - - const fetcher = async (url: string) => { - seen.push(url); - - if (seen.length === 1) return new Response(null, { - status: 403, - headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) }, - }); - - return Response.json([]); - }; - - expect((await githubAwareFetch(fetcher, raw, firstUrl, {}, now, false)).status).toBe(403); - await expect(githubAwareFetch(fetcher, raw, otherUrl, {}, now, false)).rejects.toThrow("cooldown"); - expect((await githubAwareFetch(fetcher, raw, otherUrl, {}, now, true)).status).toBe(200); - - const asset = "https://release-assets.githubusercontent.com/fixture"; - expect((await githubAwareFetch(fetcher, raw, asset, {}, now, false)).status).toBe(200); - expect((await githubAwareFetch(fetcher, raw, firstUrl, {}, new Date(reset * 1000).toISOString(), false)).status).toBe(200); - expect(seen).toEqual([firstUrl, otherUrl, asset, firstUrl]); -}); - -test("secondary throttling follows Retry-After without blocking ordinary permission errors", async () => { - const raw = memory(); - const forbidden = async () => Response.json({ message: "Resource not accessible" }, { status: 403 }); - const throttled = async () => new Response(null, { status: 429, headers: { "Retry-After": "300" } }); - - expect((await githubAwareFetch(forbidden, raw, firstUrl, {}, now, true)).status).toBe(403); - expect((await githubAwareFetch(throttled, raw, firstUrl, {}, now, true)).status).toBe(429); - await expect(githubAwareFetch(forbidden, raw, otherUrl, {}, "2026-11-30T19:37:59Z", true)).rejects.toThrow("cooldown"); - expect((await githubAwareFetch(forbidden, raw, otherUrl, {}, "2026-11-30T19:38:00Z", true)).status).toBe(403); -}); diff --git a/services/advisories/test/nvd.test.ts b/services/advisories/test/nvd.test.ts deleted file mode 100644 index 3ba0455dd..000000000 --- a/services/advisories/test/nvd.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { Database } from "bun:sqlite"; -import { expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; -import { URL as NodeURL } from "node:url"; -import { handle } from "../src/service"; -import { reconcileNvd, nvdReconciliationStatus } from "../src/nvd"; -import { Store, type Command, type Sql } from "../src/storage"; - -const now = "2026-11-30T19:33:00.000Z"; - -const fiveMinutesLater = "2026-11-30T19:38:00.000Z"; - -const tenMinutesLater = "2026-11-30T19:43:00.000Z"; - -const knownId = "CVE-2026-1234"; - -const missingId = "CVE-2026-1235"; - -const nvdOnlyId = "CVE-2026-1236"; - -function setup() { - const db = new Database(":memory:"); - db.exec(readFileSync(new NodeURL("../migrations/0001_advisories.sql", import.meta.url), "utf8")); - - const sql: Sql = { - first: async (query: string, values: Command["values"] = []) => db.query(query).get(...values), - all: async (query: string, values: Command["values"] = []) => db.query(query).all(...values), - batch: async (commands) => { - db.transaction(() => { - for (const command of commands) db.query(command.sql).run(...command.values); - })(); - }, - }; - - const objects = new Map(); - - const raw = { - put: async (key: string, value: string) => { objects.set(key, value); }, - get: async (key: string) => { - const value = objects.get(key); - - return value === undefined ? null : { text: async () => value }; - }, - }; - - return { store: new Store(sql, raw, () => now), db }; -} - -function canonical(id: string) { - return JSON.stringify({ - dataType: "CVE_RECORD", - dataVersion: "5.2", - cveMetadata: { - cveId: id, - state: "PUBLISHED", - datePublished: "2026-11-30T18:20:00Z", - dateUpdated: "2026-11-30T18:21:00Z", - }, - containers: { cna: {} }, - }); -} - -function page(ids: string[], startIndex = 0, totalResults = ids.length) { - return Response.json({ - startIndex, - resultsPerPage: ids.length, - totalResults, - vulnerabilities: ids.map(id => ({ cve: { id, published: "2026-11-30T19:30:00.000" } })), - }); -} - -test("NVD recovers official records, retains unverified gaps and never moves the publisher checkpoint", async () => { - const { store, db } = setup(); - - try { - await store.cve(canonical(knownId), now, knownId); - const original = await store.checkpoint("cve"); - const verified: string[] = []; - let calls = 0; - - const fetcher = async (url: string, init?: RequestInit) => { - const target = new URL(url); - expect(init?.redirect).toBe("manual"); - - if (target.hostname === "services.nvd.nist.gov") { - calls++; - expect(target.searchParams.get("pubStartDate")).toBe("2026-11-30T15:33:00.000Z"); - expect(target.searchParams.get("pubEndDate")).toBe(now); - - return page([knownId, missingId, nvdOnlyId]); - } - - expect(target.hostname).toBe("cveawg.mitre.org"); - const id = target.pathname.split("/").at(-1) || ""; - verified.push(id); - - return new Response(canonical(id === nvdOnlyId && calls === 1 ? knownId : id)); - }; - - await reconcileNvd(store, fetcher, Date.parse(now), now); - expect(await store.checkpoint("cve")).toEqual(original); - expect(await nvdReconciliationStatus(store, now)).toMatchObject({ - fresh: false, - checkpoint: { error: "verification_pending", next_index: 0, verified_through: null }, - }); - const recovered = await store.sql.first("SELECT source_url FROM source_record WHERE id=?", [missingId]); - expect(recovered).toEqual({ source_url: `https://cveawg.mitre.org/api/cve/${missingId}` }); - expect(await store.sql.first("SELECT id FROM source_record WHERE id=?", [nvdOnlyId])).toBeNull(); - - await reconcileNvd(store, fetcher, Date.parse(now), now); - await reconcileNvd(store, fetcher, Date.parse(fiveMinutesLater), fiveMinutesLater); - await reconcileNvd(store, fetcher, Date.parse(tenMinutesLater), tenMinutesLater); - expect(verified.sort()).toEqual([missingId, nvdOnlyId, nvdOnlyId]); - expect(calls).toBe(2); - expect(await store.checkpoint("cve")).toEqual(original); - - const status = await handle(new Request("https://advisories.example/v1/reconciliation/nvd"), store, undefined, tenMinutesLater); - expect(status.headers.get("Cache-Control")).toBe("no-store"); - expect(await status.json()).toMatchObject({ - fresh: true, - checkpoint: { error: null, next_index: 3, verified_through: now, complete: true }, - }); - } finally { - db.close(); - } -}); - -test("NVD persists the exact page position through a failed request", async () => { - const { store, db } = setup(); - - try { - const known = Array.from({ length: 100 }, (_, index) => `CVE-2026-${2000 + index}`); - await store.cveBatch(known.slice(0, 50).map(id => ({ id, raw: canonical(id) })), now); - await store.cveBatch(known.slice(50).map(id => ({ id, raw: canonical(id) })), now); - - await store.cve(canonical(knownId), now, knownId); - - const starts: string[] = []; - - const fetcher = async (url: string) => { - const target = new URL(url); - expect(target.hostname).toBe("services.nvd.nist.gov"); - const start = target.searchParams.get("startIndex") || ""; - starts.push(start); - - if (starts.length === 2) return new Response(null, { status: 429 }); - - if (start === "0") return page(known, 0, 101); - - expect(target.searchParams.get("pubEndDate")).toBe(now); - - return page([knownId], 100, 101); - }; - - await reconcileNvd(store, fetcher, Date.parse(now), now); - await reconcileNvd(store, fetcher, Date.parse(fiveMinutesLater), fiveMinutesLater); - expect(await nvdReconciliationStatus(store, fiveMinutesLater)).toMatchObject({ - fresh: false, - checkpoint: { complete: false, next_index: 100, error: "upstream_unavailable" }, - }); - - await reconcileNvd(store, fetcher, Date.parse(tenMinutesLater), tenMinutesLater); - expect(starts).toEqual(["0", "100", "100"]); - expect(await nvdReconciliationStatus(store, tenMinutesLater)).toMatchObject({ - fresh: true, - checkpoint: { complete: true, next_index: 101, error: null }, - }); - } finally { - db.close(); - } -}); diff --git a/services/advisories/test/package-assessment-worker.test.ts b/services/advisories/test/package-assessment-worker.test.ts deleted file mode 100644 index dff7a4f4c..000000000 --- a/services/advisories/test/package-assessment-worker.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { expect, test } from "bun:test"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { Miniflare, convertV4MiniflareOptions } from "miniflare"; -import { object } from "../src/domain"; - -test("workerd keeps the shadow assessment opt-in and sends only public coordinates to OSV", async () => { - const entry = fileURLToPath(new NodeURL("../src/index.ts", import.meta.url)); - const build = await Bun.build({ entrypoints: [entry], target: "browser" }); - const output = build.outputs[0]; - - if (!build.success || !output) throw new Error("missing Worker bundle"); - const script = await output.text(); - const token = "package-shadow-fixture-token-minimum-32"; - let requests = 0; - const forwarded: { url: string; authorization: boolean; cookie: boolean; body: object }[] = []; - - const outbound = async (request: Request) => { - requests++; - forwarded.push({ - url: request.url, - authorization: request.headers.has("authorization"), - cookie: request.headers.has("cookie"), - body: object(await request.json()), - }); - - return Response.json({ vulns: [{ - id: "PYSEC-2026-1", modified: "2026-11-20T14:00:00Z", - affected: [{ package: { ecosystem: "PyPI", name: "demo-project" }, versions: ["1.0.0"] }], - }] }); - }; - - const makeWorker = (bindings: Record) => new Miniflare(convertV4MiniflareOptions({ - modules: true, script, compatibilityDate: "2026-11-13", d1Databases: ["DB"], - r2Buckets: ["RAW"], bindings, outboundService: outbound, - })); - - const url = "https://advisories.example/v2/packages/assess"; - const headers = { authorization: `Bearer ${token}`, cookie: "tenant=private", "content-type": "application/json" }; - const packageCoordinate = { ecosystem: "PyPI", name: "Demo_Project", version: "1.0" }; - const body = JSON.stringify({ packages: [packageCoordinate, packageCoordinate] }); - const off = makeWorker({}); - - try { - const worker = await off.getWorker(); - expect((await worker.fetch(url, { method: "POST", headers, body })).status).toBe(404); - expect(requests).toBe(0); - } finally { - await off.dispose(); - } - - const on = makeWorker({ PACKAGE_ASSESSMENT_TOKEN: token }); - - try { - const worker = await on.getWorker(); - const response = await worker.fetch(url, { method: "POST", headers, body }); - expect(response.status).toBe(200); - expect(response.headers.get("cache-control")).toBe("no-store"); - expect(response.headers.has("etag")).toBe(false); - expect(requests).toBe(1); - expect(forwarded).toEqual([{ - url: "https://api.osv.dev/v1/query", authorization: false, cookie: false, - body: { package: { ecosystem: "PyPI", name: "demo-project" }, version: "1.0" }, - }]); - - const assessment = { status: "matched", findings: [{ id: "PYSEC-2026-1" }], - source: { page_sha256: [expect.stringMatching(/^[0-9a-f]{64}$/)] } }; - - expect(await response.json()).toMatchObject({ results: [assessment, assessment] }); - } finally { - await on.dispose(); - } -}, 30_000); diff --git a/services/advisories/test/package-assessment.test.ts b/services/advisories/test/package-assessment.test.ts deleted file mode 100644 index b56b19d25..000000000 --- a/services/advisories/test/package-assessment.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { expect, test } from "bun:test"; -import { object } from "../src/domain"; -import { type Fetcher } from "../src/ingestion"; -import { handle } from "../src/service"; -import { Store, type Sql } from "../src/storage"; - -const NOW = "2026-11-30T14:30:00.000Z"; - -const TOKEN = "public-registry-shadow-token-for-tests"; - -const PATH = "/v2/packages/assess"; - -const OSV_URL = "https://api.osv.dev/v1/query"; - -const SQL: Sql = { - first: async () => { throw new Error("unexpected database read"); }, - all: async () => { throw new Error("unexpected database read"); }, - batch: async () => { throw new Error("unexpected database write"); }, -}; - -const STORE = new Store(SQL, { - get: async () => { throw new Error("unexpected object read"); }, - put: async () => { throw new Error("unexpected object write"); }, -}); - -function assess(packages: { ecosystem: string; name: string; version: string }[], fetcher: Fetcher, credential = TOKEN) { - return handle( - new Request(`https://advisories.example${PATH}`, { - method: "POST", - headers: { Authorization: `Bearer ${credential}`, "Content-Type": "application/json" }, - body: JSON.stringify({ packages }), - }), - STORE, undefined, NOW, fetcher, undefined, TOKEN, - ); -} - -function advisory(id: string, ecosystem: string, name: string, type: string, events: object[]) { - return { - id, - modified: NOW, - affected: [{ package: { ecosystem, name }, ranges: [{ type, events }] }], - }; -} - -test("rechecks fuzzy OSV matches against the requested npm and PyPI versions", async () => { - const reply = await assess([ - { ecosystem: "npm", name: "lodash", version: "4.17.10" }, - { ecosystem: "npm", name: "lodash", version: "4.17.21" }, - { ecosystem: "PyPI", name: "Demo_Project", version: "1!1.0rc1" }, - { ecosystem: "PyPI", name: "demo-project", version: "1!1.0" }, - ], async (url, init) => { - expect(url).toBe(OSV_URL); - expect(init?.redirect).toBe("manual"); - const headers = new Headers(init?.headers); - expect(headers.has("authorization")).toBe(false); - const subject = object(object(JSON.parse(String(init?.body))).package); - - return Response.json({ vulns: subject.ecosystem === "npm" - ? [advisory("GHSA-29mw-wpgm-hmr9", "npm", "lodash", "SEMVER", [{ introduced: "0" }, { fixed: "4.17.21" }])] - : [advisory("PYSEC-2026-1", "PyPI", "demo-project", "ECOSYSTEM", [{ introduced: "1!1.0a1" }, { fixed: "1!1.0" }])] }); - }); - - expect(reply.status).toBe(200); - expect(reply.headers.get("Cache-Control")).toBe("no-store"); - expect(await reply.json()).toMatchObject({ - scope: "public_osv_advisory_matches", - results: [ - { package: { name: "lodash", version: "4.17.10" }, status: "matched", - findings: [{ id: "GHSA-29mw-wpgm-hmr9", modified: NOW, fixed_versions: ["4.17.21"] }] }, - { package: { version: "4.17.21" }, status: "no_match", findings: [] }, - { package: { name: "demo-project", version: "1!1.0rc1" }, status: "matched", - findings: [{ id: "PYSEC-2026-1", fixed_versions: ["1!1.0"] }] }, - { package: { version: "1!1.0" }, status: "no_match", findings: [] }, - ], - }); -}); - -test("retains established matches when a later page is rate limited", async () => { - let attempts = 0; - - const response = await assess([{ ecosystem: "npm", name: "demo", version: "1.0.0" }], async () => { - attempts++; - - if (attempts === 2) return new Response("ignored", { status: 429 }); - - return Response.json({ - vulns: [advisory("MAL-2026-1", "npm", "demo", "SEMVER", [{ introduced: "0" }, { last_affected: "1.0.0" }])], - next_page_token: "page-2", - }); - }); - - expect(response.status).toBe(200); - expect(await response.json()).toMatchObject({ - results: [{ status: "partial", findings: [{ id: "MAL-2026-1", kind: "malware", fixed_versions: [] }], - gaps: ["source_rate_limited"] }], - }); -}); - -test("reports unsupported Git-only evidence and withholds OSV calls for rejected input", async () => { - let attempts = 0; - - const fetcher: Fetcher = async () => { - attempts++; - - return Response.json({ vulns: [advisory("TEST-1", "npm", "demo", "GIT", [{ introduced: "0" }])] }); - }; - - const coordinate = { ecosystem: "npm", name: "demo", version: "1.0.0" }; - expect((await assess([coordinate], fetcher, "wrong")).status).toBe(401); - expect((await assess([{ ...coordinate, version: "latest" }], fetcher)).status).toBe(400); - expect((await assess([{ ...coordinate, ecosystem: "PyPI", version: "9007199254740993.0" }], fetcher)).status).toBe(400); - expect(attempts).toBe(0); - const response = await assess([coordinate], fetcher); - expect(await response.json()).toMatchObject({ - results: [{ status: "partial", findings: [], unresolved_advisories: ["TEST-1"], - gaps: ["unresolved_advisory_evidence"] }], - }); -}); - -test("OSV limits form a union and a wildcard leaves the version range open", async () => { - const entries = [ - { ecosystem: "npm", name: "demo", version: "2.5.0" }, - { ecosystem: "npm", name: "demo", version: "3.0.0" }, - ]; - - const response = await assess(entries, async () => Response.json({ vulns: [ - advisory("TEST-1", "npm", "demo", "SEMVER", [ - { introduced: "0" }, { limit: "2.0.0" }, { limit: "3.0.0" }, - ]), - advisory("TEST-2", "npm", "demo", "SEMVER", [ - { introduced: "0" }, { limit: "2.0.0" }, { limit: "*" }, - ]), - ] })); - - expect(await response.json()).toMatchObject({ - results: [ - { status: "matched", findings: [{ id: "TEST-1" }, { id: "TEST-2" }] }, - { status: "matched", findings: [{ id: "TEST-2" }] }, - ], - }); -}); - -test("rejects upstream redirects and never reports a completed lookup", async () => { - const response = await assess([{ ecosystem: "npm", name: "demo", version: "1.0.0" }], async () => - new Response(null, { status: 302, headers: { Location: "https://other.example/" } })); - - expect(await response.json()).toMatchObject({ - results: [{ status: "unavailable", findings: [], gaps: ["source_unavailable"] }], - }); -}); - -test("reports a source budget gap for an oversized advisory page", async () => { - const response = await assess([{ ecosystem: "npm", name: "demo", version: "1.0.0" }], async () => - Response.json({ vulns: Array.from({ length: 129 }, (_, i) => ({ id: `TEST-${i}` })) })); - - expect(await response.json()).toMatchObject({ - results: [{ status: "unavailable", gaps: ["source_budget_exceeded"] }], - }); -}); diff --git a/services/advisories/test/pg.test.ts b/services/advisories/test/pg.test.ts deleted file mode 100644 index 0d52b1da7..000000000 --- a/services/advisories/test/pg.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { translateSqlForPostgres } from "../src/pg"; - -describe("translateSqlForPostgres", () => { - test("rewrites ? placeholders while preserving string literals", () => { - const sql = "SELECT * FROM source_record WHERE id=? AND source_url LIKE 'https://example.com/?a=1' AND supported=?"; - expect(translateSqlForPostgres(sql)).toBe( - "SELECT * FROM source_record WHERE id=$1 AND source_url LIKE 'https://example.com/?a=1' AND supported=$2", - ); - }); - - test("translates mutation_fence strftime UTC timestamp", () => { - const sql = - "INSERT INTO mutation_fence(id,valid) VALUES(1,CASE WHEN EXISTS(SELECT 1 FROM ingestion_lease WHERE source=? AND owner=? AND expires_at>COALESCE(?,strftime('%Y-%m-%dT%H:%M:%fZ','now'))) THEN 1 ELSE 0 END) ON CONFLICT(id) DO UPDATE SET valid=excluded.valid"; - const pg = translateSqlForPostgres(sql); - expect(pg).toContain("source=$1 AND owner=$2 AND expires_at>COALESCE($3,to_char(clock_timestamp() AT TIME ZONE 'UTC'"); - expect(pg).not.toContain("strftime"); - }); - - test("translates aliased json_each and json_extract in baseline conflict check", () => { - const sql = - "SELECT b.cve_id FROM json_each(?) j CROSS JOIN baseline_member b ON b.session_id=? AND b.cve_id=json_extract(j.value,'$.id') WHERE b.payload_sha256<>json_extract(j.value,'$.hash') LIMIT 1"; - expect(translateSqlForPostgres(sql)).toBe( - "SELECT b.cve_id FROM jsonb_array_elements($1::text::jsonb) AS j(value) CROSS JOIN baseline_member b ON b.session_id=$2 AND b.cve_id=(j.value->>'id') WHERE b.payload_sha256<>(j.value->>'hash') LIMIT 1", - ); - }); - - test("translates unaliased json_each with WHERE 1 ON CONFLICT", () => { - const sql = - "INSERT INTO baseline_member(session_id,cve_id,payload_sha256) SELECT ?,json_extract(value,'$.id'),json_extract(value,'$.hash') FROM json_each(?) WHERE 1 ON CONFLICT(session_id,cve_id) DO NOTHING"; - expect(translateSqlForPostgres(sql)).toBe( - "INSERT INTO baseline_member(session_id,cve_id,payload_sha256) SELECT $1,(_je.value->>'id'),(_je.value->>'hash') FROM jsonb_array_elements($2::text::jsonb) AS _je(value) WHERE true ON CONFLICT(session_id,cve_id) DO NOTHING", - ); - }); - - test("translates kev_annotation bulk insert", () => { - const sql = - "INSERT INTO kev_annotation(cve_id,payload_json,catalog_sha256) SELECT json_extract(value,'$.cveID'),value,? FROM json_each(?)"; - expect(translateSqlForPostgres(sql)).toBe( - "INSERT INTO kev_annotation(cve_id,payload_json,catalog_sha256) SELECT (_je.value->>'cveID'),_je.value::text,$1 FROM jsonb_array_elements($2::text::jsonb) AS _je(value)", - ); - }); -}); diff --git a/services/advisories/test/raw-pack-worker-fixture.ts b/services/advisories/test/raw-pack-worker-fixture.ts deleted file mode 100644 index 13e8e26ac..000000000 --- a/services/advisories/test/raw-pack-worker-fixture.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { r2Raw } from "../src/raw-pack"; - -export default { - async fetch(request: Request, environment: { RAW: R2Bucket }): Promise { - try { - const key = new URL(request.url).searchParams.get("key"); - if (key === null) throw new Error("missing fixture object key"); - const raw = await r2Raw(environment.RAW).get(key); - return Response.json({text: raw ? await raw.text() : null}); - } catch (error) { - return Response.json({error: error instanceof Error ? error.message : "unexpected fixture failure"}, {status:500}); - } - }, -}; diff --git a/services/advisories/test/raw-pack.test.ts b/services/advisories/test/raw-pack.test.ts deleted file mode 100644 index 0965c5046..000000000 --- a/services/advisories/test/raw-pack.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { expect, test } from "bun:test"; -import { Miniflare, convertV4MiniflareOptions } from "miniflare"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { LIMITS, object, sha256, string } from "../src/domain"; -import { packRecords } from "../src/raw-pack"; - -test("immutable raw packs preserve exact UTF8 byte boundaries and individual digests", async () => { - const records = ["{\"title\":\"π,世界,🦀\"}\r\n", "{\"title\":\"second\"}"]; - const packed = await packRecords(records); - expect(packed.body).toBe(records.join("")); - expect(packed.key).toBe(`cve-pack-v1/${await sha256(packed.body)}.raw`); - let offset = 0; - const bytes = new TextEncoder().encode(packed.body); - for (const [index, raw] of records.entries()) { - const length = new TextEncoder().encode(raw).length; - expect(packed.pointers[index]).toBe(`${packed.key}#${offset}:${length}:${await sha256(raw)}`); - expect(new TextDecoder("utf-8", {fatal:true, ignoreBOM:true}).decode(bytes.slice(offset, offset + length))).toBe(raw); - offset += length; - } - expect(await packRecords(records)).toEqual(packed); -}); - -test("packs retain existing record count and exact aggregate byte bounds", async () => { - expect((await packRecords(Array(64).fill("x"))).pointers).toHaveLength(64); - const atLimit = await packRecords(["x".repeat(LIMITS.cveRecord), "y".repeat(LIMITS.batch-LIMITS.cveRecord)]); - expect(new TextEncoder().encode(atLimit.body).length).toBe(LIMITS.batch); - for (const records of [[], [""], Array(65).fill("x"), ["x".repeat(LIMITS.cveRecord+1)], ["x".repeat(LIMITS.cveRecord), "y".repeat(LIMITS.batch-LIMITS.cveRecord+1)], ["\ud800"], ["\ufeff{}"]]) { - await expect(packRecords(records)).rejects.toThrow(); - } -}); - -test("real R2 range reader preserves legacy keys and refuses corrupt packed evidence", async () => { - const build = await Bun.build({entrypoints:[fileURLToPath(new NodeURL("./raw-pack-worker-fixture.ts", import.meta.url))],target:"browser"}); - expect(build.success).toBe(true); - const output = build.outputs[0]; - if (!output) throw new Error("missing bundled raw reader fixture"); - const runtime = new Miniflare(convertV4MiniflareOptions({modules:true, script:await output.text(), compatibilityDate:"2026-11-13", r2Buckets:["RAW"]})); - try { - const bucket = await runtime.getR2Bucket("RAW"); - const worker = await runtime.getWorker(); - async function read(key: string): Promise { - const response = await worker.fetch(`https://raw.example/?key=${encodeURIComponent(key)}`); - const payload = object(await response.json()); - if (!response.ok) throw new Error(string(payload.error)); - return payload.text === null ? null : string(payload.text); - } - const records = ["π controlled first bytes", "second exact record"]; - const packed = await packRecords(records); - await bucket.put("cve/legacy/hash.json", "legacy original bytes"); - expect(await read("cve/legacy/hash.json")).toBe("legacy original bytes"); - expect(await read("cve/missing/hash.json")).toBeNull(); - await bucket.put(packed.key, packed.body); - for (const [index, expected] of records.entries()) { - const pointer = packed.pointers[index]; - if (!pointer) throw new Error("missing controlled range pointer"); - expect(await read(pointer)).toBe(expected); - } - const first = packed.pointers[0]; - if (!first) throw new Error("missing controlled first pointer"); - const suffix = first.slice(first.indexOf("#")); - for (const pointer of [packed.key, packed.key.replace("v1/", "v2/") + suffix, `${packed.key}#01:2:${"a".repeat(64)}`, `${packed.key}#-1:2:${"a".repeat(64)}`, `${packed.key}#0:0:${"a".repeat(64)}`, `${packed.key}#0:${LIMITS.cveRecord+1}:${"a".repeat(64)}`, `${packed.key}#${LIMITS.batch}:1:${"a".repeat(64)}`, `${packed.key}#9007199254740993:1:${"a".repeat(64)}`, `${packed.key}#0:1:${"A".repeat(64)}`, first + ":extra"]) { - await expect(read(pointer)).rejects.toThrow("invalid packed raw pointer"); - } - await expect(read(first.slice(0, -64) + "0".repeat(64))).rejects.toThrow("digest mismatch"); - const wrongOffset = `${packed.key}#1:1:${await sha256("x")}`; - await expect(read(wrongOffset)).rejects.toThrow(); - const truncatedKey = `cve-pack-v1/${"b".repeat(64)}.raw`; - await bucket.put(truncatedKey, "x"); - await expect(read(truncatedKey + suffix)).rejects.toThrow("range mismatch"); - const missingKey = `cve-pack-v1/${"c".repeat(64)}.raw`; - await expect(read(missingKey + suffix)).rejects.toThrow("object missing"); - await bucket.put(packed.key, packed.body.replace("controlled", "CORRUPTED!")); - await expect(read(first)).rejects.toThrow("digest mismatch"); - } finally { await runtime.dispose(); } -}, 30_000); diff --git a/services/advisories/test/recent.test.ts b/services/advisories/test/recent.test.ts deleted file mode 100644 index ea9bc6614..000000000 --- a/services/advisories/test/recent.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { expect, test } from "bun:test"; -import { Database } from "bun:sqlite"; -import { readFileSync } from "node:fs"; -import { URL as NodeURL } from "node:url"; -import { handle } from "../src/service"; -import { Store, type Sql, type Command } from "../src/storage"; -import { object } from "../src/domain"; -import { cachedRead } from "../src/cache"; - -const now = "2026-11-16T12:00:00.000Z"; -function setup() { - const db = new Database(":memory:"); - for (const name of ["0001_advisories.sql", "0002_baseline_member_counter.sql", "0003_recent_cves.sql", "0006_baseline_publisher_proof.sql"]) - db.exec(readFileSync(new NodeURL(`../migrations/${name}`, import.meta.url), "utf8")); - const sql: Sql = { - first: async (query: string, values: (string | number | null)[] = []) => - db.query(query).get(...values), - all: async (query: string, values: (string | number | null)[] = []) => - db.query(query).all(...values), - batch: async (commands: Command[]) => { - db.transaction(() => { - for (const command of commands) db.query(command.sql).run(...command.values); - })(); - }, - }; - const objects = new Map(); - const store = new Store(sql, { - put: async (key, value) => { objects.set(key, value); }, - get: async (key) => { - const value = objects.get(key); - return value === undefined ? null : { text: async () => value }; - }, - }); - db.query("UPDATE source_checkpoint SET checked_at=?,complete=1,bootstrap_complete=1").run(now); - const get = (path: string, headers?: HeadersInit, time = now) => - handle(new Request(`https://advisories.example${path}`, { headers }), store, undefined, time); - const add = (id: string, modified: string, state = "PUBLISHED") => store.cve(JSON.stringify({ - dataType: "CVE_RECORD", dataVersion: "5.2", - cveMetadata: { cveId: id, state, dateUpdated: modified, datePublished: modified }, containers: { cna: {} }, - }), now); - return { db, store, get, add }; -} - -test("recent CVEs paginate tied revisions in a fixed rolling window and retain old records", async () => { - const { get, add, db } = setup(); - for (const id of ["CVE-2026-1000", "CVE-2026-1001", "CVE-2026-1002"]) - await add(id, "2026-11-15T00:00:00Z"); - await add("CVE-2020-1000", "2026-10-16T12:00:00Z"); - await add("CVE-2026-1003", "2026-10-17T12:00:00Z", "REJECTED"); - await add("CVE-2026-1004", "2026-11-17T00:00:00Z"); - const first = await get("/v1/cves/recent?limit=2"); - expect(first.status).toBe(200); - const body = object(await first.json()); - expect(body).toMatchObject({ complete: true, as_of: now, window_start: "2026-10-17T12:00:00.000Z" }); - expect(body.records).toMatchObject([{ id: "CVE-2026-1002" }, { id: "CVE-2026-1001" }]); - expect(typeof body.next_cursor).toBe("string"); - const next = object(await (await get(`/v1/cves/recent?limit=2&cursor=${encodeURIComponent(String(body.next_cursor))}`, undefined, "2026-11-16T12:01:00.000Z")).json()); - expect(next.as_of).toBe(now); - expect(next.records).toMatchObject([{ id: "CVE-2026-1000" }, { id: "CVE-2026-1003", state: "REJECTED" }]); - expect(next.next_cursor).toBeNull(); - expect((await get("/v1/cves/CVE-2020-1000")).status).toBe(200); - expect(db.query("SELECT COUNT(*) AS n FROM source_record").get()).toEqual({ n: 6 }); -}); - -test("recent CVEs reject malformed bounds and cursors and expose incomplete sources", async () => { - const { get, db } = setup(); - for (const query of ["limit=0", "limit=101", "limit=01", "limit=1&limit=2", "days=300", "cursor=oops", "cursor=" + "a".repeat(1025)]) - expect((await get(`/v1/cves/recent?${query}`)).status).toBe(400); - const future = btoa(JSON.stringify({ as_of: "2027-01-01T00:00:00.000Z", modified_at: now, id: "CVE-2026-1000" })); - expect((await get(`/v1/cves/recent?cursor=${encodeURIComponent(future)}`)).status).toBe(400); - db.exec("UPDATE source_checkpoint SET bootstrap_complete=0 WHERE source='cve'"); - expect(object(await (await get("/v1/cves/recent")).json()).complete).toBe(false); -}); - -test("public CVE reads support representation ETags but never cache private or stale responses", async () => { - const { get, add, db } = setup(); - await add("CVE-2026-1000", now); - const first = await get("/v1/cves/CVE-2026-1000"); - expect(first.headers.get("cache-control")).toBe("public, max-age=60, must-revalidate"); - const etag = first.headers.get("etag"); - expect(etag).toMatch(/^"[a-f0-9]{64}"$/); - expect((await get("/v1/cves/CVE-2026-1000", { "if-none-match": String(etag) })).status).toBe(304); - db.query("INSERT INTO kev_annotation VALUES(?,?,?)").run("CVE-2026-1000", '{"cveID":"CVE-2026-1000"}', "a".repeat(64)); - const changed = await get("/v1/cves/CVE-2026-1000", { "if-none-match": String(etag) }); - expect(changed.status).toBe(200); - expect(changed.headers.get("etag")).not.toBe(etag); - const near = await get("/v1/cves/CVE-2026-1000", undefined, "2026-11-16T12:29:50.000Z"); - expect(near.headers.get("cache-control")).toBe("public, max-age=10, must-revalidate"); - for (const response of [ - await get("/v1/status"), await get("/v1/cves/CVE-2026-9999"), - await get("/internal/ingest"), await get("/v1/cves/CVE-2026-1000", { authorization: "Bearer private" }), - await get("/v1/cves/CVE-2026-1000", undefined, "2026-11-16T12:30:01.000Z"), - ]) expect(response.headers.get("cache-control")).toBe("no-store"); -}); - -test("an edge entry expires before its freshness claim and cache failure falls back to origin", async () => { - const request = new Request("https://advisories.example/v1/cves/CVE-2026-1000"); - const milliseconds = Date.parse(now); - const entry = new Response("cached", { headers: { Expires: new Date(milliseconds + 1000).toUTCString() } }); - let loads = 0; - const load = async () => { loads++; return new Response("origin"); }; - const cache = { match: async () => entry.clone(), put: async () => {} }; - expect(await (await cachedRead(request, cache, load, milliseconds)).text()).toBe("cached"); - expect(loads).toBe(0); - expect(await (await cachedRead(request, cache, load, milliseconds + 1000)).text()).toBe("origin"); - expect(loads).toBe(1); - const unavailable = { ...cache, match: async (): Promise => { throw new Error("fixture cache unavailable"); } }; - expect(await (await cachedRead(request, unavailable, load, milliseconds)).text()).toBe("origin"); - expect(loads).toBe(2); -}); - -test("edge cache keys stay on the request origin and bound the URL sent to cache storage", async () => { - const origin = "https://advisories.example"; - const request = new Request(`${origin}/v1/cves/recent?limit=2`); - const anotherPage = new Request(`${origin}/v1/cves/recent?limit=3`); - const preview = new Request("http://[::1]:8787/v1/cves/recent?limit=2"); - const oversized = new Request(`${origin}/v1/cves/recent?cursor=${"a".repeat(8192)}`); - const oversizedHost = new Request(`https://${"a".repeat(254)}/v1/cves/recent`); - const unsupportedHost = new Request("https://under_score.example/v1/cves/recent"); - const reads: string[] = []; - const writes: string[] = []; - const loads: string[] = []; - const cache: Pick = { - match: async (key) => { - reads.push(new Request(key).url); - return undefined; - }, - put: async (key) => { writes.push(new Request(key).url); }, - }; - const load = async (input: Request) => { - loads.push(input.url); - return new Response(input.url, { headers: { "Cache-Control": "public, max-age=60" } }); - }; - const requests = [request, anotherPage, preview, oversized, oversizedHost, unsupportedHost]; - for (const input of requests) - expect(await (await cachedRead(input, cache, load)).text()).toBe(input.url); - expect(loads).toEqual(requests.map((input) => input.url)); - expect(reads).toEqual(writes); - expect(reads).toHaveLength(3); - expect(reads[0]).toMatch(/^https:\/\/advisories\.example\/\.omg\/advisory-cache\/v1\/[a-f0-9]{64}$/); - expect(reads[1]).not.toBe(reads[0]); - expect(reads[2]).toMatch(/^http:\/\/\[::1\]:8787\/\.omg\/advisory-cache\/v1\/[a-f0-9]{64}$/); -}); diff --git a/services/advisories/test/runtime-cron.test.ts b/services/advisories/test/runtime-cron.test.ts deleted file mode 100644 index 4b1c0698b..000000000 --- a/services/advisories/test/runtime-cron.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { expect, test } from "bun:test"; -import { object } from "../src/domain"; -import { mintRuntimeRefreshToken, runtimeRefreshBatch } from "../src/runtime-cron"; - -const NOW = new Date("2026-11-30T14:02:00Z"); - -test("checks every GitHub source within fifteen minutes of its previous scheduled refresh", () => { - const slots = [0, 5, 10].map(minutes => runtimeRefreshBatch(NOW.getTime() + minutes * 60_000)); - expect(slots.flat().sort()).toEqual(["bun", "deno", "erlang", "java", "php", "python", "ruby", "rust", "swift", "zig"]); - expect(runtimeRefreshBatch(NOW.getTime() + 15 * 60_000)).toEqual(runtimeRefreshBatch(NOW.getTime())); -}); - -test("exchanges a locally signed short-lived JWT only for the configured installation", async () => { - const algorithm = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256", modulusLength: 2048, - publicExponent: new Uint8Array([1, 0, 1]) }; - - const keys = await crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]); - - if (!("privateKey" in keys)) throw new Error("expected an RSA key pair"); - - const bytes = await crypto.subtle.exportKey("pkcs8", keys.privateKey); - - if (!(bytes instanceof ArrayBuffer)) throw new Error("expected PKCS#8 bytes"); - - const keyLabel = "PRIVATE KEY"; - - const pem = `-----BEGIN ${keyLabel}-----\n${btoa(String.fromCharCode(...new Uint8Array(bytes)))}\n-----END ${keyLabel}-----`; - const token = "ghs_abcdefghijklmnopqrstuvwxyz"; - - const outcome = await mintRuntimeRefreshToken("Iv1.AppClientId", "1234", pem, NOW, async (url, init) => { - expect(url).toBe("https://api.github.com/app/installations/1234/access_tokens"); - expect(init?.method).toBe("POST"); - expect(init?.redirect).toBe("manual"); - expect(init?.body).toBe(JSON.stringify({ permissions: { contents: "read" } })); - const headers = new Headers(init?.headers); - - expect(headers.get("user-agent")).toBe("OMG-Advisory-Intake"); - expect(headers.get("content-type")).toBe("application/json"); - const bearer = headers.get("authorization")?.slice(7); - const [header, claims, signature] = bearer?.split(".") ?? []; - - if (!header || !claims || !signature) throw new Error("expected signed JWT"); - expect(JSON.parse(atob(header))).toEqual({ alg: "RS256", typ: "JWT" }); - const expected = Math.floor(NOW.getTime() / 1000); - expect(object(JSON.parse(atob(claims.replaceAll("-", "+").replaceAll("_", "/"))))).toEqual({ - iss: "Iv1.AppClientId", iat: expected - 60, exp: expected + 300, - }); - const signed = Uint8Array.from(atob(signature.replaceAll("-", "+").replaceAll("_", "/")), char => char.charCodeAt(0)); - expect(await crypto.subtle.verify(algorithm.name, keys.publicKey, signed, - new TextEncoder().encode(`${header}.${claims}`))).toBe(true); - - return Response.json({ token, expires_at: "2026-11-30T15:00:00Z" }, { status: 201 }); - }); - - expect(outcome).toBe(token); -}); - -test("rejects malformed installation configuration without network access", async () => { - let requests = 0; - await expect(mintRuntimeRefreshToken("App", "123/other", "not a private key", NOW, async () => { - requests++; - - return Response.json({}); - })).rejects.toThrow("invalid GitHub App configuration"); - expect(requests).toBe(0); -}); diff --git a/services/advisories/test/runtime-driver.test.ts b/services/advisories/test/runtime-driver.test.ts deleted file mode 100644 index a84a33066..000000000 --- a/services/advisories/test/runtime-driver.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { expect, test } from "bun:test"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { readFileSync } from "node:fs"; -import { parseDocument } from "yaml"; - -const driver = fileURLToPath(new NodeURL("../../../scripts/refresh-runtime-advisories.py", import.meta.url)); -function python(code: string) { - const result = Bun.spawnSync(["python", "-c", `import importlib.util, sys, json, io, contextlib, urllib.error\nspec = importlib.util.spec_from_file_location("refresh_driver", sys.argv[1])\ndriver = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(driver)\n${code}`, driver]); - const stderr = result.stderr.toString(); - if (result.exitCode !== 0) throw new Error(`Python driver test failed: ${stderr}`); - return result.stdout.toString(); -} -test("refresh driver sends credentials only to the fixed endpoint and refreshes every approved feed", () => { - const output = python(` -requests = [] -job_token = "ghs_12345_fixture.header-" + "a" * 475 + ".signature_fixture" -class Reply: - status = 200 - def __init__(self, runtime): self.runtime = runtime - def __enter__(self): return self - def __exit__(self, *args): pass - def read(self, limit): return json.dumps({"schema_version": 1, "runtime": self.runtime, "refreshed": True, "coverage": "unknown", "sources": [{"complete": True}]}).encode() -class Opener: - def open(self, request, timeout): - assert request.full_url == "https://omg-advisories.latham.workers.dev/internal/runtime-refresh" - assert request.method == "POST" - assert request.get_header("Authorization") == "Bearer " + "s" * 40 - body = json.loads(request.data) - assert set(body) == {"runtime", "github_token"} - assert body["github_token"] == job_token - requests.append(body["runtime"]) - return Reply(body["runtime"]) -assert driver.refresh_all(job_token, "s" * 40, Opener()) == 0 -assert requests == ["python", "rust", "ruby", "java", "bun", "deno", "zig", "erlang", "php", "swift"], requests -print("fixed origin verified") -`); - expect(output).toContain("fixed origin verified"); -}); -test("refresh driver rejects redirects, incomplete refreshes and invalid credentials without printing tokens", () => { - const output = python(` -secret = "s" * 40 -token = "ghs_12345_fixture.header-" + "a" * 475 + ".signature_fixture" -class Redirect: - def open(self, request, timeout): raise urllib.error.HTTPError(request.full_url, 307, token + secret, {"Location": "https://attacker.invalid/"}, None) -buffer = io.StringIO() -with contextlib.redirect_stdout(buffer), contextlib.redirect_stderr(buffer): - assert driver.refresh_all(token, secret, Redirect()) == 1 -assert token not in buffer.getvalue() and secret not in buffer.getvalue() -assert driver.refresh_all("ghp_personal_token", secret, Redirect()) == 2 -assert driver.refresh_all(token, "short", Redirect()) == 2 -assert driver.refresh_all(token + "\\n", secret, Redirect()) == 2 -assert driver.refresh_all("ghs_" + "a" * 4096, secret, Redirect()) == 2 -print("secrets and redirects verified") -`); - expect(output).toContain("secrets and redirects verified"); -}); -test("refresh driver rejects incomplete, mismatched and oversized responses and installs its no-redirect handler", () => { - const output = python(` -assert any(isinstance(handler, driver.NoRedirect) for handler in driver.secure_opener().handlers) -assert driver.NoRedirect().redirect_request(None, None, 307, "redirect", {}, "https://attacker.invalid") is None -class Reply: - status = 200 - def __init__(self, raw): self.raw = raw - def __enter__(self): return self - def __exit__(self, *args): pass - def read(self, limit): return self.raw[:limit] -class Opener: - def __init__(self, raw): self.raw = raw - def open(self, request, timeout): return Reply(self.raw) -for raw in [b'{"schema_version":1,"runtime":"bun","refreshed":false,"coverage":"unknown","sources":[]}', b'{"schema_version":1,"runtime":"wrong","refreshed":true}', b'x' * (driver.MAX_RESPONSE_BYTES + 1)]: - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - assert driver.refresh_all("ghs_" + "a" * 36, "s" * 40, Opener(raw)) == 1 -print("response bounds verified") -`); - expect(output).toContain("response bounds verified"); -}); -test("refresh workflow has read-only permissions, pinned checkout and trusted-main triggers", () => { - const source = readFileSync(new NodeURL("../../../.github/workflows/advisory-refresh.yml", import.meta.url), "utf8"); - const document = parseDocument(source); expect(document.errors).toEqual([]); - const workflow: unknown = document.toJS(); - expect(workflow).toMatchObject({ permissions: { contents: "read" }, on: { push: { branches: ["main"] }, schedule: [{ cron: "7,37 * * * *" }, { cron: "22,52 * * * *" }], workflow_dispatch: null }, jobs: { refresh: { if: "github.ref == 'refs/heads/main'", steps: [{ uses: "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1", with: { "persist-credentials": false } }, { env: { GITHUB_TOKEN: "${{ github.token }}", RUNTIME_REFRESH_SECRET: "${{ secrets.RUNTIME_REFRESH_SECRET }}" }, run: "python3 scripts/refresh-runtime-advisories.py" }] } } }); - expect(source).not.toContain("pull_request"); expect(source).not.toContain("INGEST_TOKEN"); -}); diff --git a/services/advisories/test/runtime-worker.test.ts b/services/advisories/test/runtime-worker.test.ts deleted file mode 100644 index ba6b22a2e..000000000 --- a/services/advisories/test/runtime-worker.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { expect, test } from "bun:test"; -import { readFile } from "node:fs/promises"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { Miniflare, convertV4MiniflareOptions } from "miniflare"; -import { unstable_splitSqlQuery } from "wrangler"; -import { ZipWriter, Uint8ArrayWriter, TextReader } from "@zip.js/zip.js/lib/zip-core-native.js"; - -test("real Worker parses vendor ZIP/YAML, persists D1/R2 evidence and never HTTP-caches partial coverage", async () => { - const jobToken = `ghs_12345_fixture.header-${"a".repeat(475)}.signature_fixture`; - const zip = new ZipWriter(new Uint8ArrayWriter(), { useWebWorkers: false, useCompressionStream: true, level: 6 }); - await zip.add(`ruby-advisory-db-${"a".repeat(40)}/rubies/ruby/CVE-2026-12345.yml`, new TextReader('cve: "2026-12345"\ntitle: Interpreter vulnerability\npatched_versions:\n - ">= 3.2.1"\n')); - await zip.add(`ruby-advisory-db-${"a".repeat(40)}/rubies/ruby/CVE-2007-5162.yml`, new TextReader('cve: "2007-5162"\ntitle: Historical patched interpreter vulnerability\npatched_versions:\n - "~> 1.8.5.114"\n - ">= 1.8.6.111"\n')); - const bytes = await zip.close(); - const build = await Bun.build({ entrypoints: [fileURLToPath(new NodeURL("../src/index.ts", import.meta.url))], target: "browser" }); - expect(build.success).toBe(true); - const output = build.outputs[0]; if (!output) throw new Error("missing Worker bundle"); - let requests = 0; - let nodeRequests = 0; - const runtime = new Miniflare(convertV4MiniflareOptions({ - modules: true, script: await output.text(), compatibilityDate: "2026-11-13", d1Databases: ["DB"], r2Buckets: ["RAW"], - bindings: { RUNTIME_REFRESH_SECRET: "runtime-refresh-only-workerd-secret-at-least-32" }, - outboundService: async (request) => { - requests++; - const url = new URL(request.url); - if (url.hostname === "api.github.com" && url.pathname === "/repos/rubysec/ruby-advisory-db/commits/master") return Response.json({ sha: "a".repeat(40) }); - if (url.hostname === "codeload.github.com" && url.pathname === `/rubysec/ruby-advisory-db/zip/${"a".repeat(40)}`) return new Response(bytes); - if (url.hostname === "api.github.com" && url.pathname === "/repos/oven-sh/bun/security-advisories") { - expect(request.headers.get("authorization")).toBe(`Bearer ${jobToken}`); - return Response.json([]); - } - if (url.hostname === "raw.githubusercontent.com" && url.pathname === "/nodejs/security-wg/main/vuln/core/index.json") { - nodeRequests++; - if (nodeRequests > 1) expect(request.headers.get("cache-control")).toBe("no-cache"); - return Response.json({ "1": { cve: ["CVE-2026-12345"], vulnerable: "3.x", patched: ">=3.2.1", description: "fixture" } }); - } - return new Response("unexpected fixture URL", { status: 404 }); - }, - })); - try { - const db = await runtime.getD1Database("DB"); - for (const name of ["0001_advisories.sql", "0002_baseline_member_counter.sql", "0003_recent_cves.sql", "0004_epss_cache.sql", "0005_runtime_sources.sql", "0006_baseline_publisher_proof.sql"]) { - const source = await readFile(new NodeURL(`../migrations/${name}`, import.meta.url), "utf8"); - await db.batch(unstable_splitSqlQuery(source).map((query) => db.prepare(query))); - } - const worker = await runtime.getWorker(); - const url = "https://advisories.example/v1/runtimes/ruby?version=3.2.0&vendor=ruby-lang&os=linux&arch=x86_64"; - const first = await worker.fetch(url); - expect(first.status).toBe(200); expect(first.headers.get("cache-control")).toBe("no-store"); - const body = await first.json(); - expect(body).toMatchObject({ coverage: "partial", findings: [{ id: "CVE-2026-12345", applicability: "applicable" }], sources: [{ revision: "a".repeat(40), complete: true }] }); - expect(requests).toBe(2); - const row = await db.prepare("SELECT object_key,payload_sha256 FROM runtime_source").first<{ object_key: string; payload_sha256: string }>(); - expect(row?.payload_sha256).toMatch(/^[a-f0-9]{64}$/); - const raw = await runtime.getR2Bucket("RAW"); expect(await raw.get(row?.object_key ?? "missing")).not.toBeNull(); - const second = await worker.fetch(url); expect(second.status).toBe(200); expect(requests).toBe(2); - expect(await second.json()).toEqual(body); - await worker.fetch(url, { headers: { "cache-control": "no-cache" } }); - expect(requests).toBe(2); - const refreshed = await worker.fetch("https://advisories.example/internal/runtime-refresh", { method: "POST", headers: { authorization: "Bearer runtime-refresh-only-workerd-secret-at-least-32" }, body: JSON.stringify({ runtime: "bun", github_token: jobToken }) }); - expect(refreshed.status).toBe(200); expect(await refreshed.json()).toMatchObject({ runtime: "bun", refreshed: true }); - expect(refreshed.headers.get("cache-control")).toBe("no-store"); expect(requests).toBe(3); - const nodeUrl = "https://advisories.example/v1/runtimes/node?version=3.2.0&vendor=nodejs&os=linux&arch=x86_64"; - await worker.fetch(nodeUrl); await worker.fetch(nodeUrl, { headers: { "cache-control": "no-cache" } }); - expect(nodeRequests).toBe(2); expect(requests).toBe(5); - } finally { await runtime.dispose(); } -}, 30_000); diff --git a/services/advisories/test/runtime.test.ts b/services/advisories/test/runtime.test.ts deleted file mode 100644 index e65621cce..000000000 --- a/services/advisories/test/runtime.test.ts +++ /dev/null @@ -1,760 +0,0 @@ -import { test, expect } from "bun:test"; -import { Database } from "bun:sqlite"; -import { readFileSync } from "node:fs"; -import { URL as NodeURL } from "node:url"; -import { Store, type Sql, type Command } from "../src/storage"; -import { handle } from "../src/service"; -import { refreshScheduledRuntimes } from "../src/runtime-cron"; -import { object } from "../src/domain"; -import { sha256 } from "../src/domain"; -import { ZipWriter, Uint8ArrayWriter, TextReader } from "@zip.js/zip.js/lib/zip-core-native.js"; - -const now = "2026-11-17T02:00:00.000Z"; -const nodeUrl = "https://raw.githubusercontent.com/nodejs/security-wg/main/vuln/core/index.json"; -function setup() { - const db = new Database(":memory:"); - db.exec(readFileSync(new NodeURL("../migrations/0001_advisories.sql", import.meta.url), "utf8")); - db.exec(readFileSync(new NodeURL("../migrations/0005_runtime_sources.sql", import.meta.url), "utf8")); - const sql: Sql = { - first: async (text: string, values: (string | number | null)[] = []) => db.query(text).get(...values), - all: async (text: string, values: (string | number | null)[] = []) => db.query(text).all(...values), - batch: async (commands: Command[]) => { db.transaction(() => { for (const command of commands) db.query(command.sql).run(...command.values); })(); }, - }; - const objects = new Map(); - let clock = now; - const store = new Store(sql, { put: async (key, value) => { objects.set(key, value); }, get: async (key) => { const value = objects.get(key); return value === undefined ? null : { text: async () => value }; } }, () => clock); - return { store, db, objects, setClock: (value: string) => { clock = value; } }; -} -function request(runtime = "node", version = "20.10.0", vendor = "nodejs", headers?: HeadersInit) { - return new Request(`https://advisories.example/v1/runtimes/${runtime}?version=${encodeURIComponent(version)}&vendor=${vendor}&os=linux&arch=x86_64`, { headers }); -} -test("runtime Node route reports affected and fixed versions with source provenance", async () => { - const { store, db } = setup(); - try { - const fetcher = async (url: string) => { - expect(url).toBe(nodeUrl); - return Response.json({ "1": { cve: ["CVE-2026-12345"], vulnerable: "20.x", patched: ">=20.11.0", description: "fixture vulnerability", severity: "high", ref: "https://nodejs.org/en/blog/vulnerability/fixture" } }); - }; - const affected = await handle(request(), store, undefined, now, fetcher); - expect(affected.status).toBe(200); - const body = object(await affected.json()); - expect(body.coverage).toBe("assessed"); - expect(body.identity).toEqual({ runtime: "node", vendor: "nodejs", version: "20.10.0", os: "linux", arch: "x86_64" }); - expect(body.findings).toMatchObject([{ id: "CVE-2026-12345", applicability: "applicable" }]); - expect(body.sources).toMatchObject([{ name: "Node.js core advisories", url: nodeUrl, complete: true }]); - const fixed = object(await (await handle(request("node", "20.11.0"), store, undefined, now, fetcher)).json()); - expect(fixed.coverage).toBe("assessed"); - expect(fixed.findings).toEqual([]); - } finally { db.close(); } -}); - -const nodePayload = { "1": { cve: ["CVE-2026-12345"], vulnerable: "20.x || 18.x", patched: ">=20.11.0 || >=18.20.0 <19", description: "fixture", severity: "high" } }; -async function report(store: Store, runtime: string, version: string, vendor: string, fetcher: (url: string, init?: RequestInit) => Promise, at = now, force = false) { - return object(await (await handle(request(runtime, version, vendor, force ? { "cache-control": "no-cache" } : undefined), store, undefined, at, fetcher)).json()); -} -async function zipFixture(repo: string, files: Record, revision = "a".repeat(40)) { - const writer = new ZipWriter(new Uint8ArrayWriter(), { useWebWorkers: false, useCompressionStream: true, level: 0 }); - for (const [path, raw] of Object.entries(files)) await writer.add(`${repo.split("/")[1]}-${revision}/${path}`, new TextReader(raw)); - return await writer.close(); -} -async function archiveFetcher(repo: string, files: Record, fallback?: (url: string) => Promise) { - const bytes = await zipFixture(repo, files); - return async (url: string) => { - if (url.startsWith(`https://api.github.com/repos/${repo}/commits/`)) return Response.json({ sha: "a".repeat(40) }); - if (url === `https://codeload.github.com/${repo}/zip/${"a".repeat(40)}`) return new Response(bytes); - if (fallback) return fallback(url); - throw new Error(`unexpected fixture URL ${url}`); - }; -} -function advisory(name: string, range: string, fixes?: string) { - return { ghsa_id: "GHSA-abcd-1234-abcd", cve_id: "CVE-2026-12345", summary: "publisher fixture", severity: "high", vulnerabilities: [{ package: { name }, vulnerable_version_range: range, patched_versions: fixes }], html_url: "https://github.com/security/advisories/GHSA-abcd-1234-abcd" }; -} -function cve(id: string, vendor: string, product: string, lower: string, upper: string) { - return { dataType: "CVE_RECORD", dataVersion: "5.2", cveMetadata: { cveId: id, state: "PUBLISHED", dateUpdated: now, datePublished: now }, containers: { cna: { affected: [{ vendor, product, defaultStatus: "unaffected", versions: [{ version: lower, lessThan: upper, versionType: "semver", status: "affected" }] }] } } }; -} - -test("all runtime routes report Unknown with evidence gaps when providers fail", async () => { - const vendors = { node: "nodejs", python: "cpython", go: "golang", rust: "rust-lang", ruby: "ruby-lang", java: "temurin", bun: "oven-sh", pi: "earendil-works", deno: "denoland", zig: "ziglang", dotnet: "microsoft", erlang: "erlang", php: "php", swift: "swiftlang" }; - const { store, db } = setup(); - try { for (const [runtime, vendor] of Object.entries(vendors)) { - const response = await handle(request(runtime, "20.0.0", vendor), store, undefined, now, async () => new Response("unavailable", { status: 503 })); - expect(response.status).toBe(200); - const body = object(await response.json()); - expect(body.coverage).toBe("unknown"); expect(body.gaps).not.toEqual([]); expect(body.identity).toMatchObject({ runtime, vendor }); - expect(response.headers.get("cache-control")).toBe("no-store"); - } } finally { db.close(); } -}); -test("runtime identity rejects duplicate or extra parameters and does not guess vendors", async () => { - const { store, db } = setup(); let calls = 0; - const fetcher = async () => { calls++; return Response.json(nodePayload); }; - try { - for (const extra of ["&version=20.0.0", "&component=sdk", "&os=windows"]) expect((await handle(new Request(`${request().url}${extra}`), store, undefined, now, fetcher)).status).toBe(400); - const unknown = await report(store, "node", "20.10.0", "npm", fetcher); - expect(unknown.coverage).toBe("unknown"); expect(calls).toBe(0); - } finally { db.close(); } -}); -test("Node retains CVE-less disclosures and unsupported ranges as possible risks", async () => { - const { store, db } = setup(); - try { - const body = await report(store, "node", "20.10.0", "nodejs", async () => Response.json({ "7": { cve: [], vulnerable: "20.x", patched: "unparsed vendor prose", description: "disclosed issue without a CVE" } })); - expect(body.coverage).toBe("partial"); expect(body.findings).toMatchObject([{ id: "NODE-CORE-7", applicability: "possible" }]); - } finally { db.close(); } -}); -test("source hashes remain stable on revalidation and change only with content; stale errors retain last good evidence", async () => { - const { store, db, setClock } = setup(); let payload = nodePayload; let fail = false; - const fetcher = async () => fail ? new Response(null, { status: 503 }) : Response.json(payload, { headers: { etag: '"revision"' } }); - try { - const first = await report(store, "node", "20.10.0", "nodejs", fetcher); - const hash = object((first.sources as unknown[])[0]).payload_sha256; - const later = "2026-11-17T02:01:00.000Z"; setClock(later); - const refreshed = await report(store, "node", "20.10.0", "nodejs", fetcher, later, true); - expect(object((refreshed.sources as unknown[])[0]).payload_sha256).toBe(hash); - expect(object((refreshed.sources as unknown[])[0]).checked_at).toBe(later); - payload = { "1": { ...nodePayload["1"], description: "changed disclosure" } }; - const changed = await report(store, "node", "20.10.0", "nodejs", fetcher, later, true); - expect(object((changed.sources as unknown[])[0]).payload_sha256).not.toBe(hash); - const row = db.query<{ object_key: string }, []>("SELECT object_key FROM runtime_source").get(); - fail = true; const stale = "2026-11-17T03:00:00.000Z"; setClock(stale); - const failed = await handle(request(), store, undefined, stale, fetcher); const body = object(await failed.json()); - expect(body.coverage).toBe("partial"); expect(body.findings).toMatchObject([{ id: "CVE-2026-12345" }]); - expect(object((body.sources as unknown[])[0]).complete).toBe(false); expect(failed.headers.get("cache-control")).toBe("no-store"); - expect(db.query<{ object_key: string }, []>("SELECT object_key FROM runtime_source").get()?.object_key).toBe(row?.object_key); - } finally { db.close(); } -}); -test("assessed runtime HTTP freshness is bounded and no-cache reaches upstream", async () => { - const { store, db } = setup(); let calls = 0; - try { - const fetcher = async (_url: string, init?: RequestInit) => { calls++; if (calls > 1) expect(new Headers(init?.headers).get("cache-control")).toBe("no-cache"); return Response.json(nodePayload); }; - const first = await handle(request(), store, undefined, now, fetcher); - expect(first.headers.get("cache-control")).toBe("public, max-age=60, must-revalidate"); - await handle(request(), store, undefined, now, fetcher); expect(calls).toBe(1); - await handle(request("node", "20.10.0", "nodejs", { "cache-control": "no-cache" }), store, undefined, now, fetcher); expect(calls).toBe(2); - } finally { db.close(); } -}); - -test("concurrent forced runtime revalidation retains a genuinely fresh verified snapshot", async () => { - const { store, db, setClock } = setup(); - const entered = Promise.withResolvers(); - const release = Promise.withResolvers(); - try { - const first = await report(store, "node", "20.10.0", "nodejs", async () => Response.json(nodePayload)); - const later = "2026-11-17T02:01:00.000Z"; - setClock(later); - const owner = report(store, "node", "20.10.0", "nodejs", async () => { - entered.resolve(); - await release.promise; - return Response.json(nodePayload); - }, later, true); - try { - await entered.promise; - let contenderFetches = 0; - const concurrent = await report(store, "node", "20.10.0", "nodejs", async () => { - contenderFetches++; - return new Response(null, { status: 503 }); - }, later, true); - expect(concurrent.coverage).toBe("assessed"); - expect(concurrent.findings).toEqual(first.findings); - expect(concurrent.gaps).toEqual([]); - expect(concurrent.sources).toEqual(first.sources); - expect(concurrent.checked_at).toBe(now); - expect(contenderFetches).toBe(0); - expect(db.query<{ successful_at: string; error: string | null }, []>("SELECT successful_at,error FROM runtime_source").get()) - .toEqual({ successful_at: now, error: null }); - } finally { release.resolve(); await owner; } - } finally { release.resolve(); db.close(); } -}); - -test("busy runtime refresh never certifies stale failed missing or corrupt prior evidence", async () => { - for (const state of ["stale", "failed", "missing", "corrupt"] as const) { - const { store, db, objects, setClock } = setup(); - try { - if (state !== "missing") { - await report(store, "node", "20.10.0", "nodejs", async () => Response.json(nodePayload)); - } - const at = state === "stale" ? "2026-11-17T02:31:00.000Z" : "2026-11-17T02:01:00.000Z"; - setClock(at); - if (state === "failed") { - await report(store, "node", "20.10.0", "nodejs", async () => new Response(null, { status: 503 }), at, true); - } - if (state === "corrupt") { - const key = db.query<{ object_key: string }, []>("SELECT object_key FROM runtime_source").get()?.object_key; - if (!key) throw new Error("missing controlled source object"); - objects.set(key, "{}"); - } - const lease = `runtime:${await sha256("v1:node:core")}`; - expect(await store.lease(lease, "controlled-refresh-owner", at)).toBe(true); - let fetched = false; - const response = await handle(request("node", "20.10.0", "nodejs", { "cache-control": "no-cache" }), store, undefined, at, async () => { - fetched = true; - return Response.json(nodePayload); - }); - const body = object(await response.json()); - expect(body.coverage).toBe(state === "stale" || state === "failed" ? "partial" : "unknown"); - expect(body.gaps).not.toEqual([]); - expect(response.headers.get("cache-control")).toBe("no-store"); - expect(fetched).toBe(false); - if (state === "stale" || state === "failed") { - expect(body.findings).toMatchObject([{ id: "CVE-2026-12345" }]); - expect(body.sources).toMatchObject([{ checked_at: now, complete: false }]); - } else { - expect(body.sources).toEqual([]); - } - await store.release(lease, "controlled-refresh-owner"); - } finally { db.close(); } - } -}); -test("Go uses both exact OSV standard-library and toolchain coordinates with full pagination", async () => { - const { store, db } = setup(); const queries: Record[] = []; - try { - const body = await report(store, "go", "1.24.0", "golang", async (url, init) => { - expect(url).toBe("https://api.osv.dev/v1/query"); const query = object(JSON.parse(String(init?.body))); queries.push(query); - if (query.page_token === "next") return Response.json({ vulns: [{ id: "GO-2026-1112", summary: "page two" }] }); - return Response.json({ vulns: [{ id: "GO-2026-1111", aliases: ["CVE-2026-12345"], summary: "page one" }], next_page_token: "next" }); - }); - expect(body.coverage).toBe("assessed"); expect((body.sources as unknown[]).length).toBe(2); expect(queries.length).toBe(4); - expect(queries.map((query) => object(query.package).name)).toEqual(["stdlib", "stdlib", "toolchain", "toolchain"]); - expect(queries.every((query) => query.version === "1.24.0" && object(query.package).ecosystem === "Go")).toBe(true); - } finally { db.close(); } -}); -test("fresh Go OSV evidence ignores object key order but binds every field and ordered array", async () => { - const { store, db } = setup(); - const reverseKeys=(value:unknown):unknown=>{ - if(Array.isArray(value))return value.map(reverseKeys); - if(value!==null && typeof value==="object")return Object.fromEntries(Object.entries(object(value)).reverse().map(([key,item])=>[key,reverseKeys(item)])); - return value; - }; - let variant="original"; - const fetcher=async(url:string,init?:RequestInit)=>{ - expect(url).toBe("https://api.osv.dev/v1/query"); - const query=object(JSON.parse(String(init?.body))),name=object(query.package).name; - const record={id:name==="stdlib"?"GO-2026-1111":"GO-2026-1112",summary:"Exact Go disclosure",modified:now, - aliases:[name==="stdlib"?"CVE-2026-12345":"CVE-2026-12346"],database_specific:{severity:"HIGH"}, - affected:[{package:{ecosystem:"Go",name},ranges:[{type:"SEMVER",events:[{introduced:"0"},{fixed:variant==="field"?"1.29.0":"1.28.0"}]}], - ecosystem_specific:{imports:[{path:"net/http",symbols:variant==="array"?["Server.Serve","Serve"]:["Serve","Server.Serve"]}]}}]}; - return Response.json({vulns:[variant==="keys"?reverseKeys(record):record]}); - }; - const hashes=(value:Record)=>{ - const sources=value.sources;if(!Array.isArray(sources))throw new Error("missing controlled OSV source receipts"); - return sources.map(source=>object(source).payload_sha256); - }; - try { - const first=await report(store,"go","1.27.1","golang",fetcher,now,true); - variant="keys"; - const reordered=await report(store,"go","1.27.1","golang",fetcher,now,true); - expect(first.coverage).toBe("assessed");expect(reordered.coverage).toBe("assessed"); - expect(reordered.findings).toEqual(first.findings); - expect(hashes(reordered)).toEqual(hashes(first)); - for(const changed of ["field","array"]){ - variant=changed; - const update=await report(store,"go","1.27.1","golang",fetcher,now,true); - expect(update.coverage).toBe("assessed");expect(update.findings).toEqual(first.findings); - expect(hashes(update)).not.toEqual(hashes(first)); - } - }finally{db.close();} -}); -test("Pi scans its actual npm package and cyclic OSV pagination cannot become clean", async () => { - const { store, db } = setup(); - try { - const body = await report(store, "pi", "0.50.0", "earendil-works", async (_url, init) => { const query = object(JSON.parse(String(init?.body))); expect(query.package).toEqual({ ecosystem: "npm", name: "@earendil-works/pi-coding-agent" }); return Response.json({ next_page_token: "cycle" }); }); - expect(body.coverage).toBe("unknown"); expect(body.sources).toEqual([]); - } finally { db.close(); } -}); -test("Bun and Deno publisher advisories distinguish affected, fixed and withdrawn", async () => { - for (const [runtime, vendor, name] of [["bun", "oven-sh", "bun"], ["deno", "denoland", "Deno"]]) { - if (!runtime || !vendor || !name) throw new Error("missing fixture identity"); - const { store, db } = setup(); - try { - const fetcher = async () => Response.json([advisory(name, ">=1.0.0 <1.2.0"), { ...advisory(name, "*"), ghsa_id: "GHSA-abcd-1234-efgh", cve_id: "CVE-2026-12346", withdrawn_at: now }]); - expect((await report(store, runtime, "1.1.0", vendor, fetcher)).findings).toMatchObject([{ id: "CVE-2026-12345", applicability: "applicable" }]); - expect((await report(store, runtime, "1.2.0", vendor, fetcher)).findings).toEqual([]); - } finally { db.close(); } - } -}); -test("publisher disclosures without applicability entries remain possible risks", async () => { - for (const { runtime, vendor, version } of [ - { runtime: "bun", vendor: "oven-sh", version: "1.1.0" }, - { runtime: "deno", vendor: "denoland", version: "1.1.0" }, - { runtime: "php", vendor: "php", version: "8.2.33" }, - { runtime: "erlang", vendor: "erlang", version: "28.5.0.8" }, - ]) { - const { store, db } = setup(); - try { - const row = { ...advisory(runtime, "*"), vulnerabilities: [] }; - const body = await report(store, runtime, version, vendor, async (url) => - url.endsWith("otp_versions.table") - ? new Response("OTP-28.5.0.8 : ssl-11.6.0.7 # compiler-9.0.1 :") - : Response.json([row])); - expect(body.coverage).toBe("partial"); - expect(body.findings).toMatchObject([{ id: row.cve_id, applicability: "possible", - urls: expect.arrayContaining([row.html_url]) }]); - expect(body.gaps).not.toEqual([]); - if (!Array.isArray(body.sources)) throw new Error("missing publisher sources"); - expect(body.sources.length).toBe(runtime === "erlang" ? 2 : 1); - expect(body.sources.every((value) => object(value).complete === true)).toBe(true); - } finally { db.close(); } - } -}); - -test("empty publisher lists and withdrawn incomplete disclosures do not fabricate findings", async () => { - for (const rows of [[], [{ ...advisory("bun", "*"), vulnerabilities: [], withdrawn_at: now }]]) { - const { store, db } = setup(); - try { - const body = await report(store, "bun", "1.1.0", "oven-sh", async () => Response.json(rows)); - expect(body.coverage).toBe("assessed"); - expect(body.findings).toEqual([]); - expect(body.gaps).toEqual([]); - } finally { db.close(); } - } -}); - -test("PHP maintenance-branch fixes are not ORed into a false affected result", async () => { - const { store, db } = setup(); - try { - const row = advisory("ext-standard", "<8.2.34", "8.2.34"); row.vulnerabilities.push({ package: { name: "ext-standard" }, vulnerable_version_range: "<8.3.35", patched_versions: "8.3.35" }); - const fetcher = async () => Response.json([row]); - expect((await report(store, "php", "8.2.34", "php", fetcher)).findings).toEqual([]); - expect((await report(store, "php", "8.2.33", "php", fetcher)).findings).toMatchObject([{ applicability: "applicable" }]); - } finally { db.close(); } -}); -test("Erlang resolves four-component OTP and application release versions", async () => { - const { store, db } = setup(); - try { - const row = advisory("ssl", ">=7.0", "11.7.8, 11.6.0.7"); - const fetcher = async (url: string) => url.endsWith("otp_versions.table") ? new Response("OTP-28.5.0.8 : ssl-11.6.0.7 # compiler-9.0.1 :\nOTP-28.5.0.7 : ssl-11.6.0.6 # compiler-9.0.1 :") : Response.json([row]); - expect((await report(store, "erlang", "28.5.0.8", "erlang", fetcher)).findings).toEqual([]); - expect((await report(store, "erlang", "28.5.0.7", "erlang", fetcher)).findings).toMatchObject([{ applicability: "applicable" }]); - } finally { db.close(); } -}); - -test("the runtime timer checks Python and Erlang without an Actions credential", async () => { - const { store, db, setClock } = setup(); - const id = "CVE-2026-12345"; - const etag = '"fixture-otp"'; - const schedule = Date.parse("2026-11-30T14:07:00Z"); - let rawCves = 0; - let canonicalCves = 0; - let conditionalChecks = 0; - - const psf = await archiveFetcher("psf/advisory-database", { - "advisories/python/PSF-2026-1.json": JSON.stringify({ id: "PSF-2026-1", aliases: [id] }), - }); - - const fetcher = async (url: string, init?: RequestInit) => { - const headers = new Headers(init?.headers); - - expect(headers.get("authorization")).toBeNull(); - - if (url.endsWith(`/${id}.json`)) { - rawCves++; - - return new Response(null, { status: 503 }); - } - - if (url === `https://cveawg.mitre.org/api/cve/${id}`) { - canonicalCves++; - - return Response.json(cve(id, "Python Software Foundation", "CPython", "3.12.0", "3.12.15")); - } - - if (url.endsWith("otp_versions.table")) return new Response("OTP-27.0 : ssl-11.0 :"); - - if (url.includes("/erlang/otp/security-advisories?")) { - if (headers.get("if-none-match") === etag) { - conditionalChecks++; - - return new Response(null, { status: 304 }); - } - - return Response.json([advisory("OTP", ">=27.0")], { headers: { etag } }); - } - - return psf(url); - }; - - try { - setClock(new Date().toISOString()); - await refreshScheduledRuntimes({}, store, schedule, fetcher); - await refreshScheduledRuntimes({}, store, schedule + 15 * 60_000, fetcher); - const complete = db.query("SELECT count(*) AS count FROM runtime_source WHERE successful_at IS NOT NULL AND error IS NULL").get(); - - expect(complete).toEqual({ count: 4 }); - expect(rawCves).toBe(2); - expect(canonicalCves).toBe(2); - expect(conditionalChecks).toBe(1); - } finally { - db.close(); - } -}); -test("Zig and Swift empty publisher lists remain explicitly Unknown", async () => { - const { store, db } = setup(); - try { for (const [runtime, vendor] of [["zig", "ziglang"], ["swift", "swiftlang"]]) { - if (!runtime || !vendor) throw new Error("missing fixture"); - const body = await report(store, runtime, "1.0.0", vendor, async () => Response.json([])); - expect(body.coverage).toBe("unknown"); expect(body.gaps).not.toEqual([]); expect(body.sources).toMatchObject([{ complete: true }]); - } } finally { db.close(); } -}); -test("Ruby YAML and Rust TOML apply exact toolchain ranges without matching third-party packages", async () => { - for (const runtime of ["ruby", "rust"]) { - const { store, db } = setup(); - try { - const ruby = runtime === "ruby"; - const fetcher = await archiveFetcher(ruby ? "rubysec/ruby-advisory-db" : "rustsec/advisory-db", ruby ? { "rubies/ruby/CVE-2026-12345.yml": 'cve: "2026-12345"\ntitle: Ruby interpreter fixture\npatched_versions:\n - ">= 3.2.1"\nunaffected_versions:\n - "< 3.2.0"\n' } : { "rust/std/RUSTSEC-2026-0001.md": '```toml\n[advisory]\nid = "RUSTSEC-2026-0001"\n[versions]\npatched = [">= 1.58.1"]\nunaffected = []\n```\n# Standard library fixture\n' }); - const vendor = ruby ? "ruby-lang" : "rust-lang"; - expect((await report(store, runtime, ruby ? "3.2.0" : "1.58.0", vendor, fetcher)).findings).toMatchObject([{ applicability: "applicable" }]); - expect((await report(store, runtime, ruby ? "3.2.1" : "1.58.1", vendor, fetcher)).findings).toEqual([]); - } finally { db.close(); } - } -}); -test("CPython Git-only records use vendor CVE numeric applicability and preserve unsupported findings", async () => { - const { store, db } = setup(); - try { - const fetcher = await archiveFetcher("psf/advisory-database", { "advisories/python/PSF-2026-1.json": JSON.stringify({ id: "PSF-2026-1", aliases: ["CVE-2026-12345", "CVE-2026-12346"], summary: "CPython core issue", affected: [{ ranges: [{ type: "GIT", events: [] }] }] }) }, async (url) => url.endsWith("CVE-2026-12345.json") ? Response.json(cve("CVE-2026-12345", "Python Software Foundation", "CPython", "3.12.0", "3.12.9")) : Response.json(cve("CVE-2026-12346", "unknown", "unknown", "0", "4"))); - const affected = await report(store, "python", "3.12.8", "cpython", fetcher); - expect(affected.findings).toMatchObject([{ id: "CVE-2026-12345", applicability: "applicable" }, { id: "CVE-2026-12346", applicability: "possible" }]); - const fixed = await report(store, "python", "3.12.9", "cpython", fetcher); - expect(fixed.findings).toMatchObject([{ id: "CVE-2026-12346", applicability: "possible" }]); - expect((fixed.findings as unknown[]).length).toBe(1); - } finally { db.close(); } -}); -test(".NET compares SDK-bundled runtime versions with runtime CVE ranges", async () => { - const { store, db } = setup(); - try { - const fetcher = async (url: string) => url.includes("releases.json") ? Response.json({ "channel-version": "9.0", releases: [ { "release-version": "9.0.0", sdk: { version: "9.0.100" }, runtime: { version: "9.0.0" } }, { "release-version": "9.0.1", sdk: { version: "9.0.101" }, runtime: { version: "9.0.1" }, security: true, "cve-list": [{ "cve-id": "CVE-2026-12345" }] } ] }) : Response.json(cve("CVE-2026-12345", "Microsoft", ".NET", "9.0.0", "9.0.1")); - expect((await report(store, "dotnet", "9.0.100", "microsoft", fetcher)).findings).toMatchObject([{ applicability: "applicable" }]); - expect((await report(store, "dotnet", "9.0.101", "microsoft", fetcher)).findings).toEqual([]); - } finally { db.close(); } -}); -test(".NET includes SDK-only security releases when the bundled runtime has not changed", async () => { - const { store, db } = setup(); - try { - const fetcher = async (url: string) => url.includes("releases.json") ? Response.json({ "channel-version": "9.0", releases: [ - { "release-version": "9.0.0", sdk: { version: "9.0.100" }, runtime: { version: "9.0.0" } }, - { "release-version": "9.0.0", sdks: [{ version: "9.0.101" }], runtime: { version: "9.0.0" }, security: true, "cve-list": [{ "cve-id": "CVE-2026-12345" }] }, - ] }) : Response.json(cve("CVE-2026-12345", "Microsoft", ".NET SDK", "9.0.100", "9.0.101")); - expect((await report(store, "dotnet", "9.0.100", "microsoft", fetcher)).findings).toMatchObject([{ id: "CVE-2026-12345", applicability: "applicable" }]); - expect((await report(store, "dotnet", "9.0.101", "microsoft", fetcher)).findings).toEqual([]); - } finally { db.close(); } -}); -test(".NET includes ASP.NET-only security releases and compares the installed ASP.NET component", async () => { - const { store, db } = setup(); - try { - const fetcher = async (url: string) => url.includes("releases.json") ? Response.json({ "channel-version": "9.0", releases: [ - { "release-version": "9.0.0", sdk: { version: "9.0.100" }, runtime: { version: "9.0.0" }, aspnetcore: { version: "9.0.0" } }, - { "release-version": "9.0.1", runtime: { version: "9.0.0" }, aspnetcore: { version: "9.0.1" }, security: true, "cve-list": [{ "cve-id": "CVE-2026-12345" }] }, - ] }) : Response.json(cve("CVE-2026-12345", "Microsoft", "ASP.NET Core", "9.0.0", "9.0.1")); - expect((await report(store, "dotnet", "9.0.100", "microsoft", fetcher)).findings).toMatchObject([{ id: "CVE-2026-12345", applicability: "applicable" }]); - } finally { db.close(); } -}); -test("Temurin accepts the official CycloneDX 1.4 report with partial exact-build evidence", async () => { - const { store, db } = setup(); - try { - const raw = JSON.stringify({ bomFormat: "CycloneDX", specVersion: "1.4", metadata: { component: { name: "Eclipse Temurin" } }, vulnerabilities: [{ id: "CVE-2026-12345", description: "Temurin fixture", affects: [{ ref: "pkg:github/openjdk/jdk", versions: [{ range: "vers:generic/21.0.1|8u392" }] }] }] }); - const digest = await sha256(raw); - const fetcher = async (url: string) => url.endsWith("/latest") ? Response.json({ tag_name: "vdr-fixture", assets: [{ name: "temurin-vdr-fixture.json", digest: `sha256:${digest}`, size: new TextEncoder().encode(raw).length, browser_download_url: "https://github.com/adoptium/temurin-vdr-generator/releases/download/fixture/temurin-vdr-fixture.json" }] }) : new Response(raw); - expect(await report(store, "java", "21.0.1+12", "temurin", fetcher)).toMatchObject({ coverage: "partial", findings: [{ applicability: "applicable" }] }); - expect((await report(store, "java", "21.0.2+13", "temurin", fetcher)).findings).toEqual([]); - expect((await report(store, "java", "21", "temurin", fetcher)).coverage).toBe("unknown"); - } finally { db.close(); } -}); -test("competing and expired fenced runtime refreshes cannot publish authoritative evidence", async () => { - const { store, db, setClock } = setup(); - try { - const lease = `runtime:${await sha256("v1:node:core")}`; - expect(await store.lease(lease, "competing-owner", now)).toBe(true); - const locked = await report(store, "node", "20.10.0", "nodejs", async () => { throw new Error("must not fetch under another owner's lease"); }); - expect(locked.coverage).toBe("unknown"); await store.release(lease, "competing-owner"); - const expired = await report(store, "node", "20.10.0", "nodejs", async () => { setClock("2026-11-17T02:11:00.000Z"); return Response.json(nodePayload); }); - expect(expired.coverage).toBe("unknown"); expect(db.query<{ n: number }, []>("SELECT COUNT(*) n FROM runtime_source").get()?.n).toBe(0); - } finally { db.close(); } -}); - -test("publisher pagination consumes every page and rejects repeated page identities", async () => { - const { store, db } = setup(); let pages = 0; - try { - const body = await report(store, "bun", "1.0.0", "oven-sh", async (url) => { - pages++; - if (url.endsWith("page=2")) return Response.json([advisory("bun", "<1.1.0")]); - return Response.json(Array.from({ length: 100 }, (_, index) => ({ ...advisory("bun", "<0.1.0"), ghsa_id: `GHSA-abcd-${index.toString(16).padStart(4, "0")}-abcd`, cve_id: null }))); - }); - expect(pages).toBe(2); expect(body.coverage).toBe("assessed"); expect(body.findings).toMatchObject([{ id: "CVE-2026-12345" }]); - await handle(refreshRequest({ runtime: "bun", github_token: jobToken }), store, undefined, now, async () => Response.json(Array.from({ length: 100 }, (_, index) => ({ ...advisory("bun", "<0.1.0"), ghsa_id: `GHSA-abcd-${index.toString(16).padStart(4, "0")}-abcd`, cve_id: null }))), refreshSecret); - const failed = await report(store, "bun", "1.0.0", "oven-sh", async () => { throw new Error("failure backoff must reuse retained evidence"); }); - expect(failed.coverage).toBe("partial"); expect(failed.findings).toMatchObject([{ id: "CVE-2026-12345" }]); - } finally { db.close(); } -}); -test("trusted 304 revalidation retains source content hash and malformed replacements preserve good snapshots", async () => { - const { store, db } = setup(); - try { - const first = await report(store, "node", "20.10.0", "nodejs", async () => Response.json(nodePayload, { headers: { etag: '"a"' } })); - const hash = object((first.sources as unknown[])[0]).payload_sha256; - const checked = await report(store, "node", "20.10.0", "nodejs", async (_url, init) => { expect(new Headers(init?.headers).get("if-none-match")).toBe('"a"'); return new Response(null, { status: 304 }); }, now, true); - expect(checked.coverage).toBe("assessed"); expect(object((checked.sources as unknown[])[0]).payload_sha256).toBe(hash); - const failed = await report(store, "node", "20.10.0", "nodejs", async () => Response.json({ "1": { vulnerable: "*" } }), now, true); - expect(failed.coverage).toBe("partial"); expect(object((failed.sources as unknown[])[0]).payload_sha256).toBe(hash); - expect(failed.findings).toMatchObject([{ id: "CVE-2026-12345" }]); - } finally { db.close(); } -}); -test("incomplete CVE applicability refresh cannot replace a previously complete snapshot", async () => { - const { store, db } = setup(); let fail = false; - try { - const fetcher = await archiveFetcher("psf/advisory-database", { "advisories/python/PSF-2026-1.json": JSON.stringify({ id: "PSF-2026-1", aliases: ["CVE-2026-12345", "CVE-2026-12346"], summary: "Python fixture" }) }, async (url) => { - if (fail && /CVE-2026-12346(?:\.json)?$/.test(url)) return new Response(null, { status: 503 }); - const id = url.endsWith("CVE-2026-12345.json") ? "CVE-2026-12345" : "CVE-2026-12346"; - return Response.json(cve(id, "Python Software Foundation", "CPython", "3.12.0", fail ? "3.12.8" : "3.12.9")); - }); - await report(store, "python", "3.12.8", "cpython", fetcher); - const first = db.query<{ object_key: string }, []>("SELECT object_key FROM runtime_source WHERE cache_key LIKE 'v1:cve5:%'").get(); - fail = true; const partial = await report(store, "python", "3.12.8", "cpython", fetcher, now, true); - expect(partial.coverage).toBe("partial"); expect((partial.sources as unknown[]).some((value) => object(value).complete === false)).toBe(true); - expect(db.query<{ object_key: string }, []>("SELECT object_key FROM runtime_source WHERE cache_key LIKE 'v1:cve5:%'").get()?.object_key).toBe(first?.object_key); - } finally { db.close(); } -}); - -test("Ruby four-component Gem patch requirements exclude historical vulnerabilities from modern releases", async () => { - const { store, db } = setup(); - try { - const fetcher = await archiveFetcher("rubysec/ruby-advisory-db", { - "rubies/ruby/CVE-2007-5162.yml": 'cve: "2007-5162"\ntitle: Historical Net HTTPS issue\npatched_versions:\n - "~> 1.8.5.114"\n - ">= 1.8.6.111"\n', - }); - expect((await report(store, "ruby", "3.3.0", "ruby-lang", fetcher)).findings).toEqual([]); - } finally { db.close(); } -}); - -const refreshSecret = "runtime-refresh-only-fixture-secret-at-least-32"; -const jobToken = `ghs_${"a".repeat(36)}`; -function refreshRequest(body: unknown, secret = refreshSecret) { - return new Request("https://advisories.example/internal/runtime-refresh", { method: "POST", headers: { authorization: `Bearer ${secret}`, "content-type": "application/json" }, body: JSON.stringify(body) }); -} -test("runtime refresh uses its separate secret and sends ephemeral job credentials only to approved GitHub API requests", async () => { - const { store, db, objects } = setup(); - try { - let calls = 0; - const fetcher = async (url: string, init?: RequestInit) => { - calls++; expect(url).toBe("https://api.github.com/repos/oven-sh/bun/security-advisories?per_page=100&page=1"); - expect(new Headers(init?.headers).get("authorization")).toBe(`Bearer ${jobToken}`); - expect(init?.redirect).toBe("manual"); return Response.json([]); - }; - const result = await handle(refreshRequest({ runtime: "bun", github_token: jobToken }), store, "different-bootstrap-credential-at-least-32", now, fetcher, refreshSecret); - expect(result.status).toBe(200); expect(result.headers.get("cache-control")).toBe("no-store"); - expect(await result.json()).toMatchObject({ runtime: "bun", refreshed: true, coverage: "assessed" }); expect(calls).toBe(1); - expect([...objects.values()].some((value) => value.includes(jobToken) || value.includes(refreshSecret))).toBe(false); - const sqlRows = JSON.stringify(db.query("SELECT * FROM runtime_source").all()); - expect(sqlRows.includes(jobToken) || sqlRows.includes(refreshSecret)).toBe(false); - const denied = await handle(refreshRequest({ runtime: "bun", github_token: jobToken }, "bootstrap-credential-at-least-32"), store, "bootstrap-credential-at-least-32", now, fetcher, refreshSecret); - expect(denied.status).toBe(401); expect(calls).toBe(1); - expect((await handle(refreshRequest({ runtime: "bun", github_token: jobToken }), store, refreshSecret, now, fetcher)).status).toBe(401); - } finally { db.close(); } -}); -test("runtime refresh refuses arbitrary URLs, personal tokens and unsupported runtime selectors", async () => { - const { store, db } = setup(); let calls = 0; - const personalTokenFixture = "ghp_" + "fixturefake" + "0".repeat(25); - expect(personalTokenFixture).toMatch(/^ghp_[A-Za-z0-9]{36}$/); - try { - for (const body of [{ runtime: "bun", github_token: jobToken, url: "https://example.com" }, { runtime: "bun", github_token: personalTokenFixture }, { runtime: "../node", github_token: jobToken }]) { - const response = await handle(refreshRequest(body), store, undefined, now, async () => { calls++; return Response.json([]); }, refreshSecret); - expect(response.status).toBe(400); - } - expect(calls).toBe(0); - } finally { db.close(); } -}); -test("rate-limited GitHub source responses expose only bounded numeric diagnostic headers", async () => { - const { store, db } = setup(); - try { - const body = await report(store, "bun", "1.1.0", "oven-sh", async () => new Response(jobToken, { status: 403, headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": "1794891075", "retry-after": "15" } })); - expect(body.coverage).toBe("unknown"); - expect(JSON.stringify(body.gaps)).toContain("GitHub rate limit remaining=0 reset=1794891075 retry_after=15"); - expect(JSON.stringify(body)).not.toContain(jobToken); - } finally { db.close(); } -}); -test("ephemeral GitHub credentials are absent from Temurin assets and every release-asset redirect", async () => { - const { store, db } = setup(); const seen: string[] = []; - try { - const raw = JSON.stringify({ bomFormat: "CycloneDX", specVersion: "1.6", metadata: { component: { name: "Eclipse Temurin" } }, vulnerabilities: [] }); - const digest = await sha256(raw); - const fetcher = async (url: string, init?: RequestInit) => { - seen.push(url); const authorization = new Headers(init?.headers).get("authorization"); - expect(init?.redirect).toBe("manual"); - if (url.endsWith("/latest")) { - expect(authorization).toBe(`Bearer ${jobToken}`); - return Response.json({ tag_name: "fixture", assets: [{ name: "temurin-vdr-fixture.json", digest: `sha256:${digest}`, size: new TextEncoder().encode(raw).length, browser_download_url: "https://github.com/adoptium/temurin-vdr-generator/releases/download/fixture/temurin-vdr-fixture.json" }] }); - } - expect(authorization).toBeNull(); - if (url.startsWith("https://github.com/")) return new Response(null, { status: 302, headers: { location: "https://release-assets.githubusercontent.com/fixture" } }); - return new Response(raw); - }; - const response = await handle(refreshRequest({ runtime: "java", github_token: jobToken }), store, undefined, now, fetcher, refreshSecret); - expect(await response.json()).toMatchObject({ runtime: "java", refreshed: true, coverage: "unknown" }); - expect(seen.length).toBe(3); - } finally { db.close(); } -}); -test("upstream credential reflections and transport errors cannot persist or return the job token", async () => { - for (const reflected of [true, false]) { - const { store, db, objects } = setup(); - try { - const response = await handle(refreshRequest({ runtime: "bun", github_token: jobToken }), store, undefined, now, async () => { - if (!reflected) throw new Error(`transport refused ${jobToken}`); - return Response.json([{ ...advisory("bun", "*"), summary: jobToken }]); - }, refreshSecret); - const body = object(await response.json()); - expect(body.refreshed).toBe(false); expect(JSON.stringify(body)).not.toContain(jobToken); - expect([...objects.values()].join("")).not.toContain(jobToken); - expect(JSON.stringify(db.query("SELECT * FROM runtime_source").all())).not.toContain(jobToken); - } finally { db.close(); } - } -}); -test("runtime refresh authentication happens before body parsing and GitHub redirects are not followed", async () => { - const { store, db } = setup(); let calls = 0; - try { - const denied = new Request("https://advisories.example/internal/runtime-refresh", { method: "POST", body: "invalid JSON" }); - expect((await handle(denied, store, undefined, now, async () => { calls++; return Response.json([]); }, refreshSecret)).status).toBe(401); - const result = await handle(refreshRequest({ runtime: "bun", github_token: jobToken }), store, undefined, now, async (_url, init) => { - calls++; expect(init?.redirect).toBe("manual"); - return new Response(null, { status: 302, headers: { location: "https://attacker.invalid" } }); - }, refreshSecret); - expect(await result.json()).toMatchObject({ refreshed: false, coverage: "unknown" }); expect(calls).toBe(1); - } finally { db.close(); } -}); -test("Ruby genuine Gem requirements preserve exclusion and pessimistic range semantics", async () => { - const { store, db } = setup(); - try { - const fetcher = await archiveFetcher("rubysec/ruby-advisory-db", { "rubies/ruby/CVE-2026-12345.yml": 'cve: "2026-12345"\ntitle: Interpreter fixture\npatched_versions:\n - "~> 3.2.0, != 3.2.1"\n' }); - expect((await report(store, "ruby", "3.2.1", "ruby-lang", fetcher)).findings).toMatchObject([{ applicability: "applicable" }]); - expect((await report(store, "ruby", "3.2.2", "ruby-lang", fetcher)).findings).toEqual([]); - expect((await report(store, "ruby", "3.3.0", "ruby-lang", fetcher)).findings).toMatchObject([{ applicability: "applicable" }]); - } finally { db.close(); } -}); -test("public post-consent revalidation rereads fresh GitHub snapshots without poisoning or extending their checked time", async () => { - const { store, db, setClock } = setup(); let calls = 0; - try { - const primed = await handle(refreshRequest({ runtime: "bun", github_token: jobToken }), store, undefined, now, async () => { calls++; return Response.json([advisory("bun", "<1.2.0")]); }, refreshSecret); - expect(await primed.json()).toMatchObject({ refreshed: true }); expect(calls).toBe(1); - const later = "2026-11-17T02:02:00.000Z"; setClock(later); - const response = await handle(request("bun", "1.1.0", "oven-sh", { "cache-control": "no-cache" }), store, undefined, later, async () => { calls++; return new Response(null, { status: 403 }); }); - const body = object(await response.json()); expect(body.coverage).toBe("assessed"); expect(body.sources).toMatchObject([{ checked_at: now, complete: true }]); expect(calls).toBe(1); - const row = db.query<{ successful_at: string; error: string | null }, []>("SELECT successful_at,error FROM runtime_source").get(); - expect(row).toEqual({ successful_at: now, error: null }); - const expired = "2026-11-17T02:31:00.000Z"; setClock(expired); - const stale = await handle(request("bun", "1.1.0", "oven-sh", { "cache-control": "no-cache" }), store, undefined, expired, async () => { calls++; return new Response(null, { status: 403 }); }); - expect(object(await stale.json()).coverage).toBe("partial"); expect(stale.headers.get("cache-control")).toBe("no-store"); expect(calls).toBe(2); - } finally { db.close(); } -}); - -const rustHeadroomFiles = (title = "Published standard-library finding") => ({ - "rust/std/RUSTSEC-2026-0001.md": '```toml\n[advisory]\nid = "RUSTSEC-2026-0001"\n[versions]\npatched = [">= 1.85.1"]\nunaffected = []\n```\n# ' + title + '\n', -}); -const nearExpiry = "2026-11-17T02:29:55.000Z"; - -test("forced public GitHub revalidation begins at exactly five minutes of remaining freshness", async () => { - const { store, db, setClock } = setup(); - try { - const payload = [advisory("bun", "<1.2.0")]; - const original = await report(store, "bun", "1.1.0", "oven-sh", async () => Response.json(payload)); - const before = "2026-11-17T02:24:59.999Z", boundary = "2026-11-17T02:25:00.000Z"; - let calls = 0; - setClock(before); - const cached = await report(store, "bun", "1.1.0", "oven-sh", async () => { calls++; throw new Error("freshness headroom remains"); }, before, true); - expect(calls).toBe(0); - expect(cached.sources).toEqual(original.sources); - setClock(boundary); - const renewed = await report(store, "bun", "1.1.0", "oven-sh", async () => { calls++; return Response.json(payload); }, boundary, true); - expect(calls).toBe(1); - expect(renewed.sources).toMatchObject([{ checked_at: boundary, complete: true }]); - } finally { db.close(); } -}); - -test("forced public Rust reads renew near-expiry proof only after actual unchanged publisher revalidation", async () => { - const { store, db, setClock } = setup(); - const entered = Promise.withResolvers(), release = Promise.withResolvers(); - try { - const original = await report(store, "rust", "1.85.0", "rust-lang", await archiveFetcher("rustsec/advisory-db", rustHeadroomFiles())); - expect(original.findings).toMatchObject([{ id: "RUSTSEC-2026-0001", applicability: "applicable" }]); - let calls = 0; - setClock(nearExpiry); - const unchanged = await report(store, "rust", "1.85.0", "rust-lang", async () => { calls++; throw new Error("unforced fresh read must not fetch"); }, nearExpiry); - expect(calls).toBe(0); - expect(unchanged.sources).toEqual(original.sources); - const renewed = report(store, "rust", "1.85.0", "rust-lang", async (url, init) => { - calls++; - expect(url).toBe("https://api.github.com/repos/rustsec/advisory-db/commits/main"); - expect(init?.redirect).toBe("manual"); - expect(new Headers(init?.headers).get("authorization")).toBeNull(); - expect(new Headers(init?.headers).get("cache-control")).toBe("no-cache"); - entered.resolve(); - await release.promise; - return Response.json({ sha: "a".repeat(40) }); - }, nearExpiry, true); - try { - await Promise.race([entered.promise, renewed]); - expect(calls).toBe(1); - expect(db.query<{ successful_at: string }, []>("SELECT successful_at FROM runtime_source").get()?.successful_at).toBe(now); - } finally { release.resolve(); } - const body = await renewed; - expect(body.findings).toEqual(original.findings); - expect(body.gaps).toEqual(original.gaps); - expect(body.coverage).toBe(original.coverage); - if (!Array.isArray(body.sources) || !Array.isArray(original.sources)) throw new Error("missing Rust source receipts"); - expect(body.sources).toEqual(original.sources.map((source) => ({ ...object(source), checked_at: nearExpiry }))); - expect(db.query<{ successful_at: string; error: string | null }, []>("SELECT successful_at,error FROM runtime_source").get()).toEqual({ successful_at: nearExpiry, error: null }); - } finally { release.resolve(); db.close(); } -}); - -test("near-expiry Rust publisher changes replace semantic evidence after actual archive validation", async () => { - const { store, db, setClock } = setup(); - try { - const original = await report(store, "rust", "1.85.0", "rust-lang", await archiveFetcher("rustsec/advisory-db", rustHeadroomFiles())); - const revision = "b".repeat(40), archive = await zipFixture("rustsec/advisory-db", rustHeadroomFiles("Changed published finding"), revision); - const urls: string[] = []; - setClock(nearExpiry); - const changed = await report(store, "rust", "1.85.0", "rust-lang", async (url, init) => { - urls.push(url); - expect(new Headers(init?.headers).get("authorization")).toBeNull(); - expect(new Headers(init?.headers).get("cache-control")).toBe("no-cache"); - if (url === "https://api.github.com/repos/rustsec/advisory-db/commits/main") return Response.json({ sha: revision }); - expect(url).toBe(`https://codeload.github.com/rustsec/advisory-db/zip/${revision}`); - return new Response(archive); - }, nearExpiry, true); - expect(urls.length).toBe(2); - expect(changed.findings).toMatchObject([{ id: "RUSTSEC-2026-0001", summary: "Changed published finding" }]); - if (!Array.isArray(changed.sources) || !Array.isArray(original.sources)) throw new Error("missing Rust source receipts"); - expect(object(changed.sources[0]).payload_sha256).not.toBe(object(original.sources[0]).payload_sha256); - expect(changed.sources).toMatchObject([{ checked_at: nearExpiry, revision, complete: true }]); - } finally { db.close(); } -}); - -test("failed near-expiry Rust revalidation never renews last-success dates or drops findings", async () => { - for (const failure of ["http", "commit", "archive"]) { - const { store, db, setClock } = setup(); - try { - const original = await report(store, "rust", "1.85.0", "rust-lang", await archiveFetcher("rustsec/advisory-db", rustHeadroomFiles())); - let calls = 0; - setClock(nearExpiry); - const failed = await report(store, "rust", "1.85.0", "rust-lang", async (url) => { - calls++; - if (failure === "http") return new Response(null, { status: 403 }); - if (failure === "commit") return Response.json({ sha: "invalid" }); - return url.startsWith("https://api.github.com/") ? Response.json({ sha: "b".repeat(40) }) : new Response("not a zip archive"); - }, nearExpiry, true); - expect(calls).toBe(failure === "archive" ? 2 : 1); - expect(failed.coverage).toBe("partial"); - expect(failed.findings).toEqual(original.findings); - expect(failed.sources).toMatchObject([{ checked_at: now, complete: false }]); - expect(db.query<{ successful_at: string }, []>("SELECT successful_at FROM runtime_source").get()?.successful_at).toBe(now); - } finally { db.close(); } - } -}); - -test("near-expiry Rust refresh contention cannot manufacture newer source proof", async () => { - const { store, db, setClock } = setup(); - const lease = `runtime:${await sha256("v1:rust:components")}`, owner = "headroom-contender"; - try { - const original = await report(store, "rust", "1.85.0", "rust-lang", await archiveFetcher("rustsec/advisory-db", rustHeadroomFiles())); - setClock(nearExpiry); - expect(await store.lease(lease, owner, nearExpiry)).toBe(true); - let calls = 0; - const contender = await report(store, "rust", "1.85.0", "rust-lang", async () => { calls++; throw new Error("lease holder owns upstream refresh"); }, nearExpiry, true); - expect(calls).toBe(0); - expect(contender.sources).toEqual(original.sources); - expect(contender.findings).toEqual(original.findings); - expect(db.query<{ successful_at: string }, []>("SELECT successful_at FROM runtime_source").get()?.successful_at).toBe(now); - } finally { await store.release(lease, owner); db.close(); } -}); diff --git a/services/advisories/test/service.test.ts b/services/advisories/test/service.test.ts deleted file mode 100644 index 1aa29b1d4..000000000 --- a/services/advisories/test/service.test.ts +++ /dev/null @@ -1,1447 +0,0 @@ -import { test, expect } from "bun:test"; -import { Database } from "bun:sqlite"; -import { handle } from "../src/service"; -import { Store, type Sql, type Command, type Checkpoint } from "../src/storage"; -import { reconcilePublishedCves, refreshSource, refreshScheduledAdvisories, refresh, refreshCves, refreshSnapshot } from "../src/ingestion"; -import { cveCommitFeed, cveDiscoveryFeed, kevMirror, scheduledPublisherFetcher } from "../src/publisher"; -import { - SOURCES, - cveServicesUrl, - cveUrl, - parseCve, - sha256, - boundedBody, - parseDelta, - object, -} from "../src/domain"; -const now = "2026-11-13T02:00:00.000Z"; -const token = "test-ingest-token-at-least-32-characters"; -function setup(counterMigration = true) { - const db = new Database(":memory:"); - db.exec( - require("fs").readFileSync( - new URL("../migrations/0001_advisories.sql", import.meta.url), - "utf8", - ), - ); - if (counterMigration) - db.exec( - require("fs").readFileSync( - new URL("../migrations/0002_baseline_member_counter.sql", import.meta.url), - "utf8", - ), - ); - db.exec(require("fs").readFileSync(new URL("../migrations/0006_baseline_publisher_proof.sql", import.meta.url), "utf8")); - const sql: Sql = { - first: async ( - text: string, - values: (string | number | null)[] = [], - ) => db.query(text).get(...values), - all: async (text: string, values: (string | number | null)[] = []) => - db.query(text).all(...values), - batch: async (commands: Command[]) => { - db.transaction(() => { - for (const command of commands) - db.query(command.sql).run(...command.values); - })(); - }, - }; - const objects = new Map(); - const raw = { - put: async (key: string, value: string) => { - objects.set(key, value); - }, - get: async (key: string) => { - const value = objects.get(key); - return value === undefined ? null : { text: async () => value }; - }, - }; - return { store: new Store(sql, raw, () => now), objects, db }; -} -function cve( - state = "PUBLISHED", - modified = "2026-11-12T00:00:00.000Z", - schema = "5.2", - id = "CVE-2026-1234", -) { - return JSON.stringify({ - dataType: "CVE_RECORD", - dataVersion: schema, - cveMetadata: { - cveId: id, - state, - dateUpdated: modified, - datePublished: "2026-11-11T00:00:00Z", - }, - containers: { - cna: { title: "original" }, - adp: [{ providerMetadata: { shortName: "CVE" } }], - }, - }); -} -const arch = JSON.stringify([ - { - name: "AVG-1", - packages: ["foo"], - status: "Vulnerable", - severity: "High", - type: "test", - affected: "1:2-3", - fixed: "1:2-4", - issues: ["CVE-2026-1234"], - advisories: [], - ticket: null, - }, -]); -const req = (path: string, method = "GET", body?: string, auth?: string) => - new Request(`https://advisories.example${path}`, { - method, - body, - headers: auth ? { authorization: `Bearer ${auth}` } : {}, - }); -function gate() { - let release: () => void = () => { throw new Error("gate not initialized"); }; - const blocked = new Promise((resolve) => { release = resolve; }); - return { blocked, release: () => release() }; -} - -test("independent CVE imports use at most four concurrent fenced writes", async () => { - const { store, db, objects } = setup(); - const started = gate(), finish = gate(); - let launched = 0, active = 0, peak = 0; - const original = store.writer.bind(store); - store.writer = (...args: Parameters) => { - const writer = original(...args), write = writer.cve.bind(writer); - writer.cve = async (...values: Parameters) => { - launched++; - active++; - peak = Math.max(peak, active); - started.release(); - try { - await finish.blocked; - await write(...values); - } finally { active--; } - }; - return writer; - }; - const records = Array.from({ length: 8 }, (_, i) => cve("PUBLISHED", now, "5.2", `CVE-2026-${2000+i}`)); - const pending = handle(req("/internal/ingest", "POST", JSON.stringify({ source: "cve", records }), token), store, token, now); - try { - await started.blocked; - expect(launched).toBe(4); - finish.release(); - expect((await pending).status).toBe(200); - expect(peak).toBe(4); - expect(objects.size).toBe(8); - expect(db.query("SELECT COUNT(*) AS count FROM source_record").get()).toEqual({ count: 8 }); - expect(db.query("SELECT COUNT(*) AS count FROM ingestion_lease").get()).toEqual({ count: 0 }); - } finally { - finish.release(); - await Promise.allSettled([pending]); - db.close(); - } -}); - -test("failed CVE groups drain started writes before releasing the lease", async () => { - const { store, db } = setup(); - const started = gate(), fail = gate(), finish = gate(); - const writes: Promise[] = []; - const original = store.writer.bind(store); - store.writer = (...args: Parameters) => { - const writer = original(...args), write = writer.cve.bind(writer); - writer.cve = (...values: Parameters) => { - const pending = (async () => { - if (parseCve(values[0]).id === "CVE-2026-2000") { - started.release(); - await fail.blocked; - throw new Error("R2 failure"); - } - await finish.blocked; - await write(...values); - })(); - writes.push(pending); - return pending; - }; - return writer; - }; - const records = [2000, 2001].map((id) => cve("PUBLISHED", now, "5.2", `CVE-2026-${id}`)); - const pending = handle(req("/internal/ingest", "POST", JSON.stringify({ source: "cve", records }), token), store, token, now); - try { - await started.blocked; - fail.release(); - await new Promise((resolve) => setImmediate(resolve)); - expect(db.query("SELECT COUNT(*) AS count FROM ingestion_lease").get()).toEqual({ count: 1 }); - finish.release(); - expect((await pending).status).toBe(503); - await Promise.allSettled(writes); - expect(db.query("SELECT id FROM source_record").all()).toEqual([{ id: "CVE-2026-2001" }]); - expect(db.query("SELECT COUNT(*) AS count FROM ingestion_lease").get()).toEqual({ count: 0 }); - } finally { - fail.release(); finish.release(); - await Promise.allSettled([pending, ...writes]); - db.close(); - } -}); - -test("concurrent imports preserve serial revision checks for each CVE identity", async () => { - const { store, db } = setup(); - const active = new Set(); - let overlap = false; - const original = store.writer.bind(store); - store.writer = (...args: Parameters) => { - const writer = original(...args), write = writer.cve.bind(writer); - writer.cve = async (...values: Parameters) => { - const id = parseCve(values[0]).id; - overlap ||= active.has(id); - active.add(id); - try { await write(...values); } - finally { active.delete(id); } - }; - return writer; - }; - const records = [2000, 2001].map((id) => cve("PUBLISHED", "2026-11-12T00:00:00Z", "5.2", `CVE-2026-${id}`)); - records.push(...[2000, 2001].map((id) => cve("REJECTED", now, "5.2", `CVE-2026-${id}`)), ...records); - try { - const response = await handle(req("/internal/ingest", "POST", JSON.stringify({ source: "cve", records }), token), store, token, now); - expect(response.status).toBe(200); - expect(overlap).toBe(false); - expect(db.query("SELECT id,state FROM cve ORDER BY id").all()).toEqual([ - { id: "CVE-2026-2000", state: "REJECTED" }, { id: "CVE-2026-2001", state: "REJECTED" }, - ]); - } finally { db.close(); } -}); - -test("conflicting equal revisions still refuse within a concurrent import", async () => { - const { store, db } = setup(); - const original = cve(); - const records = [original, cve("PUBLISHED", now, "5.2", "CVE-2026-2000"), - original.replace('"original"', '"different"')]; - try { - const response = await handle(req("/internal/ingest", "POST", JSON.stringify({ source: "cve", records }), token), store, token, now); - expect(response.status).toBe(503); - expect(db.query("SELECT payload_sha256 FROM source_record WHERE id='CVE-2026-1234'").get()) - .toEqual({ payload_sha256: await sha256(original) }); - expect(db.query("SELECT COUNT(*) AS count FROM ingestion_lease").get()).toEqual({ count: 0 }); - } finally { db.close(); } -}); - -async function json(response: Response) { - return object(await response.json()); -} -test("public status is readable before bootstrap and never claims completeness", async () => { - const { store, db } = setup(); - const response = await handle(req("/v1/status"), store, undefined, now); - expect(response.status).toBe(200); - expect((await json(response)).bootstrap_complete).toBe(false); - db.close(); -}); -test("CNA and ADP survive ingest and rejected updates cannot be resurrected by old revisions", async () => { - const { store, db } = setup(); - await store.cve(cve(), now); - await store.cve(cve("REJECTED", now), now); - await store.cve(cve(), now); - const response = await handle( - req("/v1/cves/CVE-2026-1234"), - store, - undefined, - now, - ); - const body = await json(response); - expect(object(object(JSON.parse(String(body.payload_json))).cveMetadata).state).toBe("REJECTED"); - expect(object(JSON.parse(String(body.payload_json))).containers).toEqual( - JSON.parse(cve()).containers, - ); - db.close(); -}); -test("idempotent hashes do not rewrite objects and conflicting equal revisions fail closed", async () => { - const { store, objects, db } = setup(); - await store.cve(cve(), now); - await store.cve(cve(), now); - expect(objects.size).toBe(1); - await expect(store.cve(cve("REJECTED"), now)).rejects.toThrow( - "conflicting", - ); - db.close(); -}); -test("unknown schema is retained but cannot become complete on replay", async () => { - const { store, db } = setup(); - await expect(store.cve(cve("PUBLISHED", now, "99"), now)).rejects.toThrow( - "unsupported", - ); - await expect(store.cve(cve("PUBLISHED", now, "99"), now)).rejects.toThrow( - "unsupported", - ); - expect( - await store.sql.first<{ supported: number }>( - "SELECT supported FROM source_record", - ), - ).toEqual({ supported: 0 }); - db.close(); -}); -test("raw persistence failure never commits an index pointer", async () => { - const { store, db } = setup(); - const broken = new Store(store.sql, { - get: store.raw.get, - put: async () => { - throw new Error("R2 failure"); - }, - }); - await expect(broken.cve(cve(), now)).rejects.toThrow("R2 failure"); - expect(await store.sql.first("SELECT * FROM cve")).toBe(null); - db.close(); -}); -test("expired leases can be recovered and active leases prevent concurrent writers", async () => { - const { store, db } = setup(); - expect(await store.lease("cve", "one", now)).toBe(true); - expect(await store.lease("cve", "two", now)).toBe(false); - expect(await store.lease("cve", "two", "2026-11-13T02:11:00.000Z")).toBe( - true, - ); - await store.release("cve", "one"); - expect(await store.lease("cve", "three", "2026-11-13T02:11:01.000Z")).toBe( - false, - ); - db.close(); -}); -test("public routes cannot mutate and private authorization happens before body parsing", async () => { - const { store, objects, db } = setup(); - expect( - (await handle(req("/v1/status", "POST", "bad"), store, token, now)) - .status, - ).toBe(405); - expect( - ( - await handle( - req("/internal/ingest", "POST", "bad"), - store, - token, - now, - ) - ).status, - ).toBe(401); - expect( - ( - await handle( - req( - "/internal/ingest", - "POST", - JSON.stringify({ source: "cve", records: [cve()] }), - token, - ), - store, - token, - now, - ) - ).status, - ).toBe(200); - expect(objects.size).toBe(1); - db.close(); -}); -test("oversize bodies cancel and CVE IDs and filenames must match", async () => { - await expect(boundedBody(new Response("12345").body, 4)).rejects.toThrow( - "exceeds", - ); - expect(() => parseCve(cve(), "CVE-2026-9999")).toThrow("mismatch"); - expect(() => - parseDelta( - JSON.stringify([ - { - fetchTime: now, - new: [ - { - cveId: "CVE-2026-1234", - githubLink: "https://evil.test/x", - dateUpdated: now, - }, - ], - updated: [], - error: [], - numberOfChanges: 1, - }, - ]), - ), - ).toThrow("untrusted"); -}); -test("Arch envelope retains upstream issues and 304 revalidation updates freshness", async () => { - const { store, db } = setup(); - await refreshSnapshot( - store, - "arch", - async () => new Response(arch, { headers: { etag: '"1"' } }), - now, - ); - let response = await handle( - req("/v1/arch/advisories"), - store, - undefined, - now, - ); - let body = await json(response); - expect(body.complete).toBe(true); - expect(JSON.parse(String(body.payload_json))).toEqual(JSON.parse(arch)); - expect(body.payload_sha256).toMatch(/^[a-f0-9]{64}$/); - const later = "2026-11-13T03:00:00.000Z"; - response = await handle( - req("/v1/arch/advisories"), - store, - undefined, - later, - ); - expect((await json(response)).complete).toBe(false); - await refreshSnapshot( - store, - "arch", - async (_url, init) => { - expect(new Headers(init?.headers).get("if-none-match")).toBe('"1"'); - return new Response(null, { status: 304 }); - }, - later, - ); - body = await json( - await handle(req("/v1/arch/advisories"), store, undefined, later), - ); - expect(body.complete).toBe(true); - expect(body.fetched_at).toBe(now); - db.close(); -}); -test("delta ingestion bounds independent downloads and writes to four CVEs", async () => { - const { store, db } = setup(); - const started = gate(), finish = gate(); - const ids = Array.from({ length: 8 }, (_, index) => `CVE-2026-${3000 + index}`); - const payloads = new Map(ids.map((id) => [cveUrl(id), cve("PUBLISHED", now, "5.2", id)])); - const delta = JSON.stringify([{ fetchTime: now, numberOfChanges: ids.length, - new: ids.map((id) => ({ cveId: id, githubLink: cveUrl(id), dateUpdated: now })), - updated: [], error: [] }]); - let active = 0, peak = 0, launched = 0; - const pending = refreshCves(store, async (url) => { - if (url === SOURCES.cve) return new Response(delta); - const payload = payloads.get(url); - if (payload === undefined) throw new Error("unexpected CVE URL"); - launched++; active++; peak = Math.max(peak, active); started.release(); - try { - await finish.blocked; - return new Response(payload); - } finally { active--; } - }, now, 8); - try { - await started.blocked; - expect(launched).toBe(4); - expect((await store.checkpoint("cve"))?.cursor).toBe(null); - finish.release(); - await pending; - expect(peak).toBe(4); - expect(launched).toBe(8); - expect(db.query("SELECT COUNT(*) AS count FROM source_record").get()).toEqual({ count: 8 }); - expect((await store.checkpoint("cve"))?.cursor).toBe(JSON.stringify({ event: now, offset: 8 })); - } finally { - finish.release(); - await Promise.allSettled([pending]); - db.close(); - } -}); - -test("failed scheduled delta groups drain before releasing the writer lease or advancing the cursor", async () => { - const { store, db } = setup(); - const started = gate(), fail = gate(), finish = gate(); - const ids = ["CVE-2026-3000", "CVE-2026-3001"]; - const delta = JSON.stringify([{ fetchTime: now, numberOfChanges: ids.length, - new: ids.map((id) => ({ cveId: id, githubLink: cveUrl(id), dateUpdated: now })), - updated: [], error: [] }]); - const pending = refresh(store, async (url) => { - if (url === SOURCES.arch) return new Response("[]"); - if (url === SOURCES.kev) return new Response(JSON.stringify({ catalogVersion: "2026.11.13", dateReleased: now, count: 0, vulnerabilities: [] })); - if (url === SOURCES.cve) return new Response(delta); - if (url === cveUrl("CVE-2026-3000")) { - started.release(); - await fail.blocked; - return new Response("unavailable", { status: 503 }); - } - if (url !== cveUrl("CVE-2026-3001")) throw new Error("unexpected CVE URL"); - await finish.blocked; - return new Response(cve("PUBLISHED", now, "5.2", "CVE-2026-3001")); - }, now, 8); - try { - await started.blocked; - fail.release(); - await new Promise((resolve) => setImmediate(resolve)); - expect(await store.lease("cve", "probe", now)).toBe(false); - expect((await store.checkpoint("cve"))?.cursor).toBe(null); - finish.release(); - await pending; - expect(db.query("SELECT id FROM source_record").all()).toEqual([{ id: "CVE-2026-3001" }]); - expect((await store.checkpoint("cve"))?.cursor).toBe(null); - expect((await store.checkpoint("cve"))?.error).toContain("503"); - expect(db.query("SELECT COUNT(*) AS count FROM ingestion_lease").get()).toEqual({ count: 0 }); - await refresh(store, async (url) => { - if (url === SOURCES.arch) return new Response("[]"); - if (url === SOURCES.kev) return new Response(JSON.stringify({ catalogVersion: "2026.11.13", dateReleased: now, count: 0, vulnerabilities: [] })); - if (url === SOURCES.cve) return new Response(delta); - const id = ids.find((candidate) => cveUrl(candidate) === url); - if (id === undefined) throw new Error("unexpected CVE URL"); - return new Response(cve("PUBLISHED", now, "5.2", id)); - }, now, 8); - expect(db.query("SELECT COUNT(*) AS count FROM source_record").get()).toEqual({ count: 2 }); - expect((await store.checkpoint("cve"))?.cursor).toBe(JSON.stringify({ event: now, offset: 2 })); - expect((await store.checkpoint("cve"))?.error).toBe(null); - } finally { - fail.release(); finish.release(); - await Promise.allSettled([pending]); - await store.release("cve", "probe"); - db.close(); - } -}); - -test("repeated delta CVEs remain serial and an older publication cannot resurrect a rejection", async () => { - const { store, db } = setup(); - const started = gate(), finish = gate(); - const id = "CVE-2026-3000"; - const delta = JSON.stringify(["2026-11-13T01:59:00.000Z", now].map((event) => ({ - fetchTime: event, numberOfChanges: 1, - new: [], updated: [{ cveId: id, githubLink: cveUrl(id), dateUpdated: event }], error: [], - }))); - let launched = 0; - const pending = refreshCves(store, async (url) => { - if (url === SOURCES.cve) return new Response(delta); - if (url !== cveUrl(id)) throw new Error("unexpected CVE URL"); - launched++; - if (launched === 1) { - started.release(); - await finish.blocked; - return new Response(cve("REJECTED", now, "5.2", id)); - } - return new Response(cve("PUBLISHED", "2026-11-12T00:00:00.000Z", "5.2", id)); - }, now, 8); - try { - await started.blocked; - expect(launched).toBe(1); - finish.release(); - await pending; - expect(launched).toBe(2); - expect(db.query("SELECT id,state FROM source_record").all()).toEqual([{ id, state: "REJECTED" }]); - expect((await store.checkpoint("cve"))?.cursor).toBe(JSON.stringify({ event: now, offset: 1 })); - } finally { - finish.release(); - await Promise.allSettled([pending]); - db.close(); - } -}); - -test("delta checkpoint stays unchanged after a bounded batch fails and succeeds on replay", async () => { - const { store, db } = setup(); - const delta = JSON.stringify([ - { - fetchTime: now, - numberOfChanges: 1, - new: [ - { - cveId: "CVE-2026-1234", - githubLink: cveUrl("CVE-2026-1234"), - dateUpdated: now, - }, - ], - updated: [], - error: [], - }, - ]); - await expect( - refreshCves( - store, - async (url) => - url === SOURCES.cve - ? new Response(delta) - : new Response("failure", { status: 503 }), - now, - ), - ).rejects.toThrow("503"); - expect((await store.checkpoint("cve"))?.cursor).toBe(null); - await refreshCves( - store, - async (url) => new Response(url === SOURCES.cve ? delta : cve()), - now, - ); - const checkpoint = await store.checkpoint("cve"); - expect(checkpoint?.complete).toBe(1); - expect(checkpoint?.bootstrap_complete).toBe(0); - db.close(); -}); -test("incomplete baseline cannot finalize", async () => { - const { store, db } = setup(); - const response = await handle( - req( - "/internal/baseline", - "POST", - JSON.stringify({ - digest: "a".repeat(64), - baseline_at: now, - accepted: 1, - exhausted: true, - }), - token, - ), - store, - token, - now, - ); - expect(response.status).toBe(400); - expect((await store.checkpoint("cve"))?.bootstrap_complete).toBe(0); - db.close(); -}); -test("baseline tracks imported members and catchup without claiming archive completeness", async () => { - const { store, db } = setup(); - const digest = "b".repeat(64); - const baseline = "2026-11-13T00:00:00.000Z"; - const start = () => - handle( - req( - "/internal/baseline/start", - "POST", - JSON.stringify({ digest, baseline_at: baseline }), - token, - ), - store, - token, - now, - ); - const started = await start(); - expect(started.status).toBe(200); - const binding = await json(started); - const imported = await handle(req("/internal/ingest", "POST", JSON.stringify({source:"cve",records:[cve()],baseline:binding}),token), store,token,now); - expect(imported.status).toBe(200); - const delta = JSON.stringify([ - { - fetchTime: "2026-11-12T23:59:00.000Z", - numberOfChanges: 1, - new: [ - { - cveId: "CVE-2026-1234", - githubLink: cveUrl("CVE-2026-1234"), - dateUpdated: now, - }, - ], - updated: [], - error: [], - }, - { - fetchTime: now, - numberOfChanges: 1, - new: [ - { - cveId: "CVE-2026-1234", - githubLink: cveUrl("CVE-2026-1234"), - dateUpdated: now, - }, - ], - updated: [], - error: [], - }, - ]); - await refreshCves( - store, - async (url) => new Response(url === SOURCES.cve ? delta : cve()), - now, - ); - const cursor = (await store.checkpoint("cve"))?.cursor; - expect((await start()).status).toBe(200); - expect((await store.checkpoint("cve"))?.cursor).toBe(cursor); - const finish = await handle( - req( - "/internal/baseline", - "POST", - JSON.stringify({ - digest, - baseline_at: baseline, - ...binding, - accepted: 1, - exhausted: true, - finished_at: now, - }), - token, - ), - store, - token, - now, - ); - expect(finish.status).toBe(200); - expect((await store.checkpoint("cve"))?.bootstrap_complete).toBe(0); - expect((await json(finish)).archive_verified).toBe(false); - expect( - await store.sql.first<{ accepted: number; exhausted: number }>( - "SELECT accepted,exhausted FROM baseline_receipt", - ), - ).toEqual({ accepted: 1, exhausted: 1 }); - const replay = await handle( - req("/internal/ingest", "POST", JSON.stringify({ source: "cve", records: [cve()], baseline: binding }), token), - store, - token, - now, - ); - expect(replay.status).toBe(200); - expect(await store.sql.first<{ accepted: number; caught_up: number; completed_at: string | null }>( - "SELECT accepted,caught_up,completed_at FROM baseline_receipt", - )).toEqual({ accepted: 1, caught_up: 0, completed_at: null }); - db.close(); -}); -test("KEV annotation replacement removes withdrawn entries and rejects older catalogs", async () => { - const { store, db } = setup(); - await store.cve(cve(), now); - const catalog = (version: string, entries: unknown[]) => - JSON.stringify({ - catalogVersion: version, - dateReleased: now, - count: entries.length, - vulnerabilities: entries, - }); - await refreshSnapshot( - store, - "kev", - async () => - new Response( - catalog("2026.11.13", [ - { cveID: "CVE-2026-1234", vendorProject: "fixture" }, - ]), - ), - now, - ); - expect( - ( - await json( - await handle( - req("/v1/cves/CVE-2026-1234"), - store, - undefined, - now, - ), - ) - ).kev, - ).toEqual({ cveID: "CVE-2026-1234", vendorProject: "fixture" }); - await refreshSnapshot( - store, - "kev", - async () => new Response(catalog("2026.11.14", [])), - now, - ); - expect( - ( - await json( - await handle( - req("/v1/cves/CVE-2026-1234"), - store, - undefined, - now, - ), - ) - ).kev, - ).toBe(null); - await expect( - refreshSnapshot( - store, - "kev", - async () => new Response(catalog("2026.11.12", [])), - now, - ), - ).rejects.toThrow("rollback"); - db.close(); -}); -test("upstream redirects are rejected with the Workers-supported manual redirect policy", async () => { - const { store, db } = setup(); - await expect( - refreshSnapshot( - store, - "arch", - async (_url, init) => { - expect(init?.redirect).toBe("manual"); - return new Response(null, { - status: 302, - headers: { location: "https://untrusted.example" }, - }); - }, - now, - ), - ).rejects.toThrow("302"); - expect((await store.checkpoint("arch"))?.object_key).toBe(null); - db.close(); -}); -test("expired writer cannot overwrite snapshot after another owner commits", async () => { - const { store, db } = setup(); - await store.lease("arch", "old", now); - let deliver: (value: Response) => void = () => { throw new Error("not ready"); }; - const pending = new Promise((resolve) => { deliver = resolve; }); - const old = refreshSnapshot(store.writer("arch", "old"), "arch", async () => pending, now); - await Bun.sleep(0); - const later = "2026-11-13T02:11:00.000Z"; - await store.lease("arch", "new", later); - await refreshSnapshot(store.writer("arch", "new"), "arch", async () => new Response(arch.replace("AVG-1", "AVG-2")), later); - deliver(new Response(arch)); - await expect(old).rejects.toThrow("CHECK constraint failed"); - expect((await store.checkpoint("arch"))?.checked_at).toBe(later); - db.close(); -}); -test("payload_json preserves exact wire bytes for independent SHA verification", async () => { - const { store, db } = setup(); - const raw = JSON.stringify(JSON.parse(arch), null, 2) + "\n"; - await refreshSnapshot(store, "arch", async () => new Response(raw), now); - const body = await json(await handle(req("/v1/arch/advisories"), store, undefined, now)); - expect(body.payload_json).toBe(raw); - expect(await sha256(String(body.payload_json))).toBe(String(body.payload_sha256)); - db.close(); -}); -test("UTF8 BOM is rejected instead of silently changing hashed bytes", async () => { - await expect(boundedBody(new Response(new Uint8Array([239,187,191,91,93])).body, 10)).rejects.toThrow("BOM"); -}); -test("inflated operator baseline receipt cannot certify unimported archive members", async () => { - const { store, db } = setup(); - const digest = "c".repeat(64); - const post = (path: string, payload: unknown) => handle(req(path, "POST", JSON.stringify(payload), token), store, token, now); - const binding = await json(await post("/internal/baseline/start", { digest, baseline_at: now })); - await store.sql.batch([{ sql: "UPDATE source_checkpoint SET complete=1,checked_at=?,cursor=? WHERE source='cve'", values:[now,JSON.stringify({event:now,offset:0})] }]); - const result = await post("/internal/baseline", {...binding,digest, baseline_at:now, accepted:400000, exhausted:true, finished_at:now}); - expect(result.status).toBe(400); - expect((await store.checkpoint("cve"))?.bootstrap_complete).toBe(0); - db.close(); -}); -test("expired same-owner transaction rolls back all mutations using commit-time clock", async () => { - const { store, db } = setup(); - let clock = now; - const timed = new Store(store.sql, store.raw, () => clock); - await timed.lease("cve", "one", now); - const writer = timed.writer("cve", "one"); - clock = "2026-11-13T02:10:00.000Z"; - await expect(writer.sql.batch([ - {sql:"UPDATE source_checkpoint SET cursor='corrupt' WHERE source='cve'",values:[]}, - {sql:"UPDATE source_checkpoint SET error='stale failure',complete=0 WHERE source='cve'",values:[]}, - ])).rejects.toThrow("CHECK constraint failed"); - expect((await store.checkpoint("cve"))?.cursor).toBe(null); - expect((await store.checkpoint("cve"))?.error).toBe(null); - db.close(); -}); -test("stale KEV writer cannot delete annotations or record a stale error", async () => { - const { store, db } = setup(); - await store.lease("kev", "old", now); - const stale = store.writer("kev", "old"); - const later = "2026-11-13T02:11:00.000Z"; - await store.lease("kev", "new", later); - const current = store.writer("kev", "new"); - await current.sql.batch([{sql:"INSERT INTO kev_annotation VALUES(?,?,?)",values:["CVE-2026-1234",'{}',"new"]}]); - await expect(stale.sql.batch([ - {sql:"DELETE FROM kev_annotation",values:[]}, - {sql:"UPDATE source_checkpoint SET error='old failure',complete=0 WHERE source='kev'",values:[]}, - ])).rejects.toThrow("CHECK constraint failed"); - expect(await store.sql.first<{catalog_sha256:string}>("SELECT catalog_sha256 FROM kev_annotation")).toEqual({catalog_sha256:"new"}); - expect((await store.checkpoint("kev"))?.error).toBe(null); - db.close(); -}); -test("baseline resume is bound to database instance, endpoint and distinct server-counted members", async () => { - const {store,db} = setup(); - const other = setup(); - const digest = "d".repeat(64); - const post = (path:string,payload:unknown, target=store, host="advisories.example") => handle(new Request(`https://${host}${path}`,{method:"POST",headers:{authorization:`Bearer ${token}`},body:JSON.stringify(payload)}),target,token,now); - const binding = await json(await post("/internal/baseline/start",{digest,baseline_at:now})); - expect((await post("/internal/baseline/start",{...binding,baseline_at:now},other.store)).status).toBe(400); - expect((await post("/internal/baseline/start",{...binding,baseline_at:now},store,"other.example")).status).toBe(400); - expect((await post("/internal/ingest",{source:"cve",records:[cve(),cve()],baseline:binding})).status).toBe(200); - expect(await store.sql.first<{count:number}>("SELECT COUNT(*) AS count FROM baseline_member")).toEqual({count:1}); - expect((await post("/internal/ingest",{source:"cve",records:[cve()],baseline:{...binding,session_id:"wrong"}})).status).toBe(400); - expect((await store.checkpoint("cve"))?.bootstrap_complete).toBe(0); - db.close(); other.db.close(); -}); -test("counter migration reconciles existing members and enforces atomic append-only counting", async () => { - const { store, db } = setup(false); - try { - await store.sql.batch([ - { - sql: "INSERT INTO baseline_receipt(digest,instance_id,session_id,endpoint,baseline_at,accepted,exhausted) VALUES(?,?,?,?,?,?,0)", - values: ["e".repeat(64), "fixture-instance", "fixture-session", "https://advisories.example", now, 99], - }, - { - sql: "INSERT INTO baseline_member VALUES(?,?,?)", - values: ["fixture-session", "CVE-2026-1234", "first"], - }, - { - sql: "INSERT INTO baseline_member VALUES(?,?,?)", - values: ["fixture-session", "CVE-2026-1235", "second"], - }, - ]); - db.exec(require("fs").readFileSync(new URL("../migrations/0002_baseline_member_counter.sql", import.meta.url), "utf8")); - const count = () => store.sql.first<{ accepted: number }>("SELECT accepted FROM baseline_receipt"); - expect(await count()).toEqual({ accepted: 2 }); - const insert = { - sql: "INSERT INTO baseline_member VALUES(?,?,?) ON CONFLICT(session_id,cve_id) DO NOTHING", - values: ["fixture-session", "CVE-2026-1236", "third"], - }; - await store.sql.batch([insert]); - await store.sql.batch([insert]); - expect(await count()).toEqual({ accepted: 3 }); - await expect(store.sql.batch([{ - sql: "UPDATE baseline_member SET payload_sha256='changed'", - values: [], - }])).rejects.toThrow("append-only"); - await expect(store.sql.batch([{ - sql: "DELETE FROM baseline_member", - values: [], - }])).rejects.toThrow("append-only"); - await expect(store.sql.batch([ - { ...insert, values: ["fixture-session", "CVE-2026-1237", "rollback"] }, - { sql: "INSERT INTO missing_table VALUES(1)", values: [] }, - ])).rejects.toThrow("missing_table"); - expect(await count()).toEqual({ accepted: 3 }); - expect(await store.sql.first<{ count: number }>("SELECT COUNT(*) AS count FROM baseline_member")).toEqual({ count: 3 }); - } finally { - db.close(); - } -}); -test("baseline finalization rejects a maintained counter that differs from actual membership", async () => { - const { store, db } = setup(); - try { - const post = (path: string, payload: unknown) => handle( - req(path, "POST", JSON.stringify(payload), token), store, token, now, - ); - const binding = await json(await post("/internal/baseline/start", { - digest: "f".repeat(64), baseline_at: now, - })); - expect((await post("/internal/ingest", { - source: "cve", records: [cve()], baseline: binding, - })).status).toBe(200); - await store.sql.batch([ - { sql: "UPDATE baseline_receipt SET accepted=2", values: [] }, - { - sql: "UPDATE source_checkpoint SET complete=1,checked_at=?,cursor=? WHERE source='cve'", - values: [now, JSON.stringify({ event: now, offset: 0 })], - }, - ]); - const response = await post("/internal/baseline", { - ...binding, baseline_at: now, finished_at: now, accepted: 1, exhausted: true, - }); - expect(response.status).toBe(400); - expect((await store.checkpoint("cve"))?.bootstrap_complete).toBe(0); - expect(await store.sql.first<{ caught_up: number }>("SELECT caught_up FROM baseline_receipt")).toEqual({ caught_up: 0 }); - } finally { - db.close(); - } -}); - -function largeCveFixture(id = "CVE-2026-1234", bytes = 2_402_038): string { - const description = {lang: "en", value: "Generated structured CNA/ADP fixture; preserve UTF8 é and raw whitespace."}; - const payload = { - dataType: "CVE_RECORD", dataVersion: "5.2", - cveMetadata: {cveId: id, state: "PUBLISHED", dateUpdated: "2026-11-13T02:00:00.000Z", datePublished: "2026-11-11T00:00:00Z"}, - containers: { - cna: { - providerMetadata: {orgId: "00000000-0000-4000-8000-000000000001", shortName: "fixture-CNA"}, - descriptions: [description], - affected: [{vendor: "fixture-vendor", product: "fixture-product", defaultStatus: "unaffected", - versions: Array.from({length: 11_000}, (_, index) => ({version: `${index}.0.0`, status: "affected", lessThan: `${index + 1}.0.0`, versionType: "semver"}))}], - }, - adp: [{providerMetadata: {orgId: "00000000-0000-4000-8000-000000000002", shortName: "fixture-ADP"}, - affected: Array.from({length: 1_600}, (_, index) => ({vendor: `vendor-${index}`, product: `product-${index}`, versions: [{version: `${index}.1`, status: "affected"}]}))}], - }, - }; - const encode = () => `\n${JSON.stringify(payload, null, 2)}\n`; - const padding = bytes - Buffer.byteLength(encode()); - if (padding < 0) throw new Error("large CVE fixture structure exceeds requested byte size"); - description.value += "x".repeat(padding); - const raw = encode(); - if (Buffer.byteLength(raw) !== bytes) throw new Error("large CVE fixture byte size mismatch"); - return raw; -} - -test("CVE raw allowance and caller-supplied body bounds remain independent of encoded request limits", async () => { - const {LIMITS} = await import("../src/domain"); - const raw = largeCveFixture("CVE-2026-1234", 3 * 1024 ** 2); - expect(parseCve(raw).supported).toBe(true); - expect(() => parseCve(`${raw} `)).toThrow("record exceeds limit"); - expect(LIMITS.batch).toBe(4 * 1024 ** 2); - expect(LIMITS.records).toBe(8); - await expect(boundedBody(new Response("x".repeat(1024 ** 2 + 1)).body, 1024 ** 2)).rejects.toThrow("exceeds"); - const {store, db, objects} = setup(); - try { - const body = JSON.stringify({source: "cve", records: [largeCveFixture()], padding: "x".repeat(2 * 1024 ** 2)}); - expect(Buffer.byteLength(body)).toBeGreaterThan(LIMITS.batch); - const response = await handle(req("/internal/ingest", "POST", body, token), store, token, now); - expect(response.status).toBe(400); - expect(await store.sql.first("SELECT * FROM source_record")).toBe(null); - expect(objects.size).toBe(0); - } finally { - db.close(); - } -}); - -test("official delta fetching accepts large CVE records and preserves checkpoint and pointer safety on failures", async () => { - const raw = largeCveFixture(); - const oversized = largeCveFixture("CVE-2026-1234", 3 * 1024 ** 2 + 1); - const delta = JSON.stringify([{fetchTime: now, numberOfChanges: 1, - new: [{cveId: "CVE-2026-1234", githubLink: cveUrl("CVE-2026-1234"), dateUpdated: now}], updated: [], error: []}]); - const {store, db, objects} = setup(); - try { - const before = await store.checkpoint("cve"); - await expect(refreshCves(store, async (url) => new Response(url === SOURCES.cve ? delta : oversized), now)).rejects.toThrow("exceeds"); - expect(await store.checkpoint("cve")).toEqual(before); - expect(await store.sql.first("SELECT * FROM cve")).toBe(null); - expect(objects.size).toBe(0); - await refreshCves(store, async (url) => new Response(url === SOURCES.cve ? delta : raw), now); - const response = await handle(req("/v1/cves/CVE-2026-1234"), store, undefined, now); - expect(response.status).toBe(200); - const body = await json(response); - expect(body.payload_json).toBe(raw); - expect(object(body.provenance).payload_sha256).toBe(await sha256(raw)); - expect((await store.checkpoint("cve"))?.complete).toBe(1); - const rejected = setup(); - try { - const broken = new Store(rejected.store.sql, {get: rejected.store.raw.get, put: async () => {throw new Error("R2 large-record failure");}}); - await expect(broken.cve(raw, now)).rejects.toThrow("R2 large-record failure"); - expect(await rejected.store.sql.first("SELECT * FROM source_record")).toBe(null); - expect(await rejected.store.sql.first("SELECT * FROM cve")).toBe(null); - const failedSql: Sql = {...rejected.store.sql, batch: async () => {throw new Error("D1 large-record failure");}}; - const failedIndex = new Store(failedSql, rejected.store.raw); - await expect(failedIndex.cve(raw, now)).rejects.toThrow("D1 large-record failure"); - expect(await rejected.store.sql.first("SELECT * FROM source_record")).toBe(null); - expect(await rejected.store.sql.first("SELECT * FROM cve")).toBe(null); - expect([...rejected.objects.values()]).toEqual([raw]); - } finally { - rejected.db.close(); - } - } finally { - db.close(); - } -}); - - -test("authenticated ingestion failures retain bounded redacted platform diagnostics", async () => { - const fixture = setup(); - const jobToken = `ghs_12345_fixture.header-${"a".repeat(475)}.signature_fixture`; - const logs: unknown[][] = []; - const original = console.error; - console.error = (...parts: unknown[]) => { logs.push(parts); }; - try { - const failing = new Store({ ...fixture.store.sql, batch: async () => { - throw new Error(`D1_ERROR: platform request failed ${token} ${jobToken} ${"x".repeat(1000)}`, {cause:new Error("database operation budget exceeded")}); - } }, fixture.store.raw, () => now); - const response = await handle(new Request("https://advisories.example/internal/ingest", {method:"POST",headers:{authorization:`Bearer ${token}`,"content-type":"application/json"},body:JSON.stringify({source:"cve",records:[cve()]})}), failing, token, now); - expect(response.status).toBe(503); - expect(logs).toHaveLength(1); - const encoded = JSON.stringify(logs); - expect(encoded).toContain("D1_ERROR"); - expect(encoded).toContain("database operation budget exceeded"); - expect(encoded).not.toContain(token); - expect(encoded).not.toContain(".header-"); - expect(encoded.length).toBeLessThan(1200); - } finally { console.error = original; fixture.db.close(); } -}); - - -function refreshRequest(body:unknown={},credential=token) { - return new Request("https://advisories.example/internal/cve-refresh",{method:"POST",headers:{authorization:`Bearer ${credential}`,"content-type":"application/json"},body:JSON.stringify(body)}); -} -test("private CVE catchup authenticates before parsing and refuses caller source or budget",async()=>{ - const {store,db}=setup();try{ - let fetched=0; - const fetcher=async()=>{fetched++;throw new Error("unexpected source");}; - const denied=await handle(new Request("https://advisories.example/internal/cve-refresh",{method:"POST",headers:{authorization:"Bearer wrong"},body:"invalid JSON"}),store,token,now,fetcher); - expect(denied.status).toBe(401); - expect((await handle(refreshRequest({url:"https://attacker.example",batch_size:999}),store,token,now,fetcher)).status).toBe(400); - expect(fetched).toBe(0); - }finally{db.close();} -}); -test("private CVE catchup advances fixed 32-record delta batches without fabricating bootstrap",async()=>{ - const {store,db}=setup();try{ - const ids=Array.from({length:33},(_,index)=>`CVE-2026-${7000+index}`); - const delta=JSON.stringify([{fetchTime:now,numberOfChanges:33,new:ids.map(id=>({cveId:id,githubLink:cveUrl(id),dateUpdated:now})),updated:[],error:[]}]); - let active=0,peak=0; - const fetcher=async(url:string)=>{ - if(url===SOURCES.cve)return new Response(delta); - const id=ids.find(id=>cveUrl(id)===url); - if(!id)throw new Error("unexpected source"); - active++;peak=Math.max(peak,active); - await Bun.sleep(1);active--; - return new Response(cve("PUBLISHED",now,"5.2",id)); - }; - const first=await handle(refreshRequest(),store,token,now,fetcher); - expect(first.status).toBe(200); - expect(await first.json()).toMatchObject({source:"cve",complete:false,bootstrap_complete:false,cursor:JSON.stringify({event:now,offset:32})}); - const pending = await handle(req("/v1/status"), store, token, now); - expect(await pending.json()).toMatchObject({ - cve_delta: { state: "catching_up", completed_through: null, completed_offset: null, cursor_event: now, cursor_offset: 32 }, - }); - expect(db.query("SELECT COUNT(*) count FROM source_record").get()).toEqual({count:32}); - const second=await handle(refreshRequest(),store,token,now,fetcher); - expect(second.status).toBe(200); - expect(await second.json()).toMatchObject({complete:true,bootstrap_complete:false,cursor:JSON.stringify({event:now,offset:33})}); - const current = await handle(req("/v1/status"), store, token, now); - expect(await current.json()).toMatchObject({ - bootstrap_complete: false, - cve_delta: { state: "caught_up", completed_through: now, completed_offset: 33, cursor_event: now, cursor_offset: 33 }, - }); - expect(db.query("SELECT COUNT(*) count FROM source_record").get()).toEqual({count:33}); - expect(peak).toBe(4);expect(active).toBe(0); - expect(db.query("SELECT COUNT(*) count FROM ingestion_lease").get()).toEqual({count:0}); - - const later = "2026-11-13T02:05:00.000Z"; - const laterIds = ["CVE-2026-8000", "CVE-2026-8001"]; - - const extended = JSON.stringify([ - ...JSON.parse(delta), - { fetchTime: later, numberOfChanges: 2, new: laterIds.map(id => ({ - cveId: id, githubLink: cveUrl(id), dateUpdated: later, - })), updated: [], error: [] }, - ]); - - const nextFeed = async (url: string) => { - if (url === SOURCES.cve) return new Response(extended); - const id = laterIds.find(candidate => cveUrl(candidate) === url); - - if (!id) throw new Error("unexpected source"); - - return new Response(cve("PUBLISHED", later, "5.2", id)); - }; - await refreshCves(store, nextFeed, later, 1); - const nextPending = await handle(req("/v1/status"), store, token, later); - expect(await nextPending.json()).toMatchObject({ - cve_delta: { state: "catching_up", completed_through: now, completed_offset: 33, cursor_event: later, cursor_offset: 1 }, - }); - }finally{db.close();} -}); -test("private CVE catchup respects active owners and fences expired writes",async()=>{ - const {store,db}=setup();try{ - let fetched=0; - await store.lease("cve","existing-owner",now); - expect((await handle(refreshRequest(),store,token,now,async()=>{fetched++;return new Response("[]");})).status).toBe(409); - expect(fetched).toBe(0); - await store.release("cve","existing-owner"); - let clock=now; - const guarded=new Store(store.sql,store.raw,()=>clock); - const id="CVE-2026-7333",delta=JSON.stringify([{fetchTime:now,numberOfChanges:1,new:[{cveId:id,githubLink:cveUrl(id),dateUpdated:now}],updated:[],error:[]}]); - const response=await handle(refreshRequest(),guarded,token,now,async(url)=>{ - if(url===SOURCES.cve)return new Response(delta); - expect(url).toBe(cveUrl(id));clock="2026-11-13T02:11:00.000Z"; - return new Response(cve("PUBLISHED",now,"5.2",id)); - }); - expect(response.status).toBe(503); - expect((await store.checkpoint("cve"))?.cursor).toBe(null); - expect(db.query("SELECT COUNT(*) count FROM source_record").get()).toEqual({count:0}); - expect(db.query("SELECT COUNT(*) count FROM ingestion_lease").get()).toEqual({count:0}); - }finally{db.close();} -}); - -test("a failed catch-up page preserves the last 128 admitted changes", async () => { - const { db, store } = setup(); - const ids = Array.from({ length: 132 }, (_, index) => `CVE-2026-${4000 + index}`); - - const delta = JSON.stringify([{ - fetchTime: now, numberOfChanges: ids.length, - new: ids.map((id) => ({ cveId: id, githubLink: cveUrl(id), dateUpdated: now })), - updated: [], error: [], - }]); - - const idByUrl = new Map(ids.map((id) => [cveUrl(id), id])); - const requests: string[] = []; - let failSecondPage = true; - - const retrieve = async (url: string) => { - if (url === SOURCES.cve) return new Response(delta); - const id = idByUrl.get(url); - - if (!id) throw new Error("unexpected CVE URL"); - requests.push(id); - - if (id === "CVE-2026-4128" && failSecondPage) return new Response(null, { status: 503 }); - - return new Response(cve("PUBLISHED", now, "5.2", id)); - }; - - try { - await refreshSource(store, "cve", retrieve, now, 512); - - expect((await store.checkpoint("cve"))?.cursor).toBe(JSON.stringify({ event: now, offset: 128 })); - expect((await store.checkpoint("cve"))?.revision).toBeNull(); - expect((await store.checkpoint("cve"))?.error).toContain("503"); - - requests.length = 0; - failSecondPage = false; - await refreshSource(store, "cve", retrieve, now, 512); - - expect(requests).toEqual(ids.slice(128)); - expect((await store.checkpoint("cve"))?.cursor).toBe(JSON.stringify({ event: now, offset: 132 })); - expect((await store.checkpoint("cve"))?.revision).toBe(JSON.stringify({ event: now, offset: 132 })); - expect(db.query("SELECT COUNT(*) AS count FROM source_record").get()).toEqual({ count: 132 }); - } finally { - db.close(); - } -}); - -test("refreshes CVEs every minute and keeps Arch and KEV on their five-minute cadence", async () => { - const { db, store } = setup(); - const seen: string[] = []; - - const fetcher = async (url: string) => { - seen.push(url); - - if (url === cveDiscoveryFeed) return new Response(""); - - if (url === SOURCES.arch) return new Response("[]"); - - if (url === SOURCES.kev) - return new Response(JSON.stringify({ catalogVersion: "2026.11.13", dateReleased: now, count: 0, vulnerabilities: [] })); - - if (url === SOURCES.cve) - return new Response(JSON.stringify([{ - fetchTime: now, numberOfChanges: 1, - new: [{ cveId: "CVE-2026-5000", githubLink: cveUrl("CVE-2026-5000"), dateUpdated: now }], - updated: [], error: [], - }])); - - if (url === cveUrl("CVE-2026-5000")) return new Response(cve("PUBLISHED", now, "5.2", "CVE-2026-5000")); - - throw new Error("unexpected scheduled CVE source"); - }; - - try { - await refreshScheduledAdvisories(store, fetcher, Date.parse("2026-11-30T16:01:00Z"), 32); - expect(seen).toEqual([SOURCES.cve, cveUrl("CVE-2026-5000")]); - seen.length = 0; - - await refreshScheduledAdvisories(store, fetcher, Date.parse("2026-11-30T16:05:00Z"), 32); - expect(seen).toEqual([SOURCES.cve, SOURCES.arch, SOURCES.kev, cveDiscoveryFeed]); - } finally { - db.close(); - } -}); - -test("pins scheduled CVE manifests and record reads to the same publisher commit", async () => { - const gitSha = "a".repeat(40); - const id = "CVE-2026-1234"; - const seen: string[] = []; - - const fetcher = scheduledPublisherFetcher(async url => { - seen.push(url); - - if (url === cveCommitFeed) { - return new Response('tag:github.com,2008:Grit::Commit/' + gitSha + ''); - } - - return new Response(null, { status: 200 }); - }); - - await fetcher(SOURCES.cve); - await fetcher(cveUrl(id)); - expect(seen).toEqual([ - cveCommitFeed, - SOURCES.cve.replace("/main/cves/", "/" + gitSha + "/cves/"), - cveUrl(id).replace("/main/cves/", "/" + gitSha + "/cves/"), - ]); -}); - -test("uses CISA's official mirror without retaining its validator for the primary", async () => { - const { store, db } = setup(); - - try { - const seen: string[] = []; - await refreshSnapshot(store, "kev", async url => { - seen.push(url); - - if (url === SOURCES.kev) return new Response(null, { status: 503 }); - - return Response.json( - { catalogVersion: "2026.11.13", dateReleased: now, count: 1, vulnerabilities: [{ cveID: "CVE-2026-1234" }] }, - { headers: { ETag: '"mirror"' } }, - ); - }, now); - expect(seen).toEqual([SOURCES.kev, kevMirror]); - expect(await store.checkpoint("kev")).toMatchObject({ complete: 1, etag: null, revision: "2026.11.13" }); - expect(db.query("SELECT cve_id FROM kev_annotation").get()).toEqual({ cve_id: "CVE-2026-1234" }); - } finally { - db.close(); - } -}); - -test("independent discovery stores official records without certifying the primary watermark", async () => { - const { store, db } = setup(); - const id = "CVE-2026-1234"; - const recovery = cveServicesUrl(id); - const original = cve("PUBLISHED", now); - - try { - await reconcilePublishedCves(store, async (url, init) => { - if (url === cveDiscoveryFeed) { - expect(new Headers(init?.headers).get("User-Agent")).toContain("https://getomg.dev/security/"); - - return new Response('https://vulnerability.circl.lu/vuln/cve-2026-1234' + now + ''); - } - - expect(url).toBe(recovery); - - return new Response(original); - }, now); - const stored = db.query("SELECT source_url,payload_sha256 FROM source_record WHERE id=?").get(id); - expect(stored).toEqual({ source_url: recovery, payload_sha256: await sha256(original) }); - expect(await store.checkpoint("cve")).toMatchObject({ cursor: null, revision: null, complete: 0 }); - const formattedCopy = JSON.stringify(JSON.parse(original), null, 2); - await store.cve(formattedCopy, now, id); - await store.cveBatch([{ id, raw: formattedCopy }], now); - expect(db.query("SELECT source_url,payload_sha256 FROM source_record WHERE id=?").get(id)).toEqual(stored); - await expect(store.cve(original.replace('"original"', '"conflict"'), now, id)) - .rejects.toThrow("conflicting equal CVE revision"); - } finally { - db.close(); - } -}); - -test("direct CVE fallback rejects an older revision before advancing the primary cursor", async () => { - const { store, db } = setup(); - const id = "CVE-2026-1234"; - let direct = cve(); - - const delta = [{ - fetchTime: now, - numberOfChanges: 1, - new: [{ cveId: id, githubLink: cveUrl(id), dateUpdated: now }], - updated: [], - error: [], - }]; - - const fetcher = async (url: string) => { - if (url === SOURCES.cve) return Response.json(delta); - - if (url === cveUrl(id)) return new Response(null, { status: 404 }); - expect(url).toBe(cveServicesUrl(id)); - - return new Response(direct); - }; - - try { - await expect(refreshCves(store, fetcher, now)).rejects.toThrow("required published revision"); - expect(await store.checkpoint("cve")).toMatchObject({ revision: null, cursor: null }); - direct = cve("REJECTED", now); - await refreshCves(store, fetcher, now); - expect(await store.checkpoint("cve")).toMatchObject({ complete: 1 }); - expect(db.query("SELECT state,source_url FROM source_record WHERE id=?").get(id)) - .toEqual({ state: "REJECTED", source_url: cveServicesUrl(id) }); - } finally { - db.close(); - } -}); - -test("CVE summary reads one committed projection without fetching the raw payload", async () => { - const { store } = setup(); - const raw = cve().replace('"original"', JSON.stringify("x".repeat(32 * 1024))); - - await store.cve(raw, now); - await store.sql.batch([ - { - sql: "UPDATE source_checkpoint SET checked_at=?, complete=1, bootstrap_complete=1 WHERE source IN ('cve','kev')", - values: [now], - }, - { - sql: "INSERT INTO kev_annotation(cve_id, payload_json, catalog_sha256) VALUES(?,?,?)", - values: [ - "CVE-2026-1234", - JSON.stringify({ cveID: "CVE-2026-1234", dateAdded: "2026-11-12" }), - "0".repeat(64), - ], - }, - ]); - - const exact = await handle(req("/v1/cves/CVE-2026-1234"), store, undefined, now); - expect(exact.status).toBe(200); - - const exactBody = await exact.text(); - const { payload_json, ...expected } = object(JSON.parse(exactBody)); - - expect(payload_json).toBe(raw); - expect(expected.cve_complete).toBe(true); - expect(expected.kev_complete).toBe(true); - - const statements: string[] = []; - - const readModel = new Store({ - ...store.sql, - first: (query: string, values?: (string | number | null)[]) => { - statements.push(query); - - return store.sql.first(query, values); - }, - all: (query: string, values?: (string | number | null)[]) => { - statements.push(query); - - return store.sql.all(query, values); - }, - }, { - put: async () => { throw new Error("unexpected raw write"); }, - get: async () => { throw new Error("unexpected raw read"); }, - }); - - const summary = await handle( - req("/v1/cves/CVE-2026-1234?view=summary"), readModel, undefined, now, - ); - - expect(summary.status).toBe(200); - - const summaryBody = await summary.text(); - - expect(JSON.parse(summaryBody)).toEqual(expected); - expect(summaryBody.length).toBeLessThan(exactBody.length / 10); - expect(statements).toHaveLength(1); - expect(statements[0]).not.toMatch(/payload_raw|payload_jsonb|r\.\*/i); -}); - -test("dashboard reads status and the first recent page in one consistent projection", async () => { - const { store } = setup(); - await store.cve(cve(), now); - - for (let id = 2000; id < 2101; id++) await store.cve(cve("PUBLISHED", now, "5.2", `CVE-2026-${id}`), now); - - await store.sql.batch([{ - sql: "UPDATE source_checkpoint SET checked_at=?, complete=1, bootstrap_complete=1 WHERE source='cve'", - values: [now], - }]); - - const status = await (await handle(req("/v1/status"), store, undefined, now)).json(); - const recent = await (await handle(req("/v1/cves/recent"), store, undefined, now)).json(); - const statements: string[] = []; - - const readOnly = new Store({ - ...store.sql, - first: (query: string, values?: (string | number | null)[]) => { - statements.push(query); - - return store.sql.first(query, values); - }, - all: (query: string, values?: (string | number | null)[]) => { - statements.push(query); - - return store.sql.all(query, values); - }, - }, { - put: async () => { throw new Error("unexpected raw write"); }, - get: async () => { throw new Error("unexpected raw read"); }, - }); - - const response = await handle(req("/v1/cves/dashboard"), readOnly, undefined, now); - - expect(response.status).toBe(200); - const data = object(await response.json()); - const statusModel = object(data.status); - const recentModel = object(data.recent); - expect(statusModel.baseline).toEqual(object(status).baseline); - expect(statusModel.bootstrap_complete).toBe(true); - const feeds = object(status).feeds; - - if (!Array.isArray(feeds)) throw new Error("expected status feeds"); - expect(statusModel.feeds).toEqual(feeds.map( - ({ source, checked_at, fetched_at, complete, fresh, error }) => ({ - source, checked_at, fetched_at, complete, fresh, error, - }), - )); - const records = object(recent).records; - - if (!Array.isArray(records)) throw new Error("expected recent revisions"); - expect(recentModel.records).toEqual(records.map( - ({ id, state, published_at, modified_at, fetched_at }) => ({ - id, state, published_at, modified_at, fetched_at, - }), - )); - expect(recentModel.checked_at).toBe(now); - expect(recentModel.complete).toBe(true); - expect(recentModel.next_cursor).toEqual(expect.any(String)); - expect(recentModel.next_cursor).toBe(object(recent).next_cursor); - expect(statements).toHaveLength(1); - expect(statements[0]).not.toMatch(/payload_raw|payload_jsonb|payload_sha256|object_key/i); -}); diff --git a/services/advisories/test/storage-bulk.test.ts b/services/advisories/test/storage-bulk.test.ts deleted file mode 100644 index 5bb768f7b..000000000 --- a/services/advisories/test/storage-bulk.test.ts +++ /dev/null @@ -1,291 +0,0 @@ -import { expect, spyOn, test } from "bun:test"; -import { Database } from "bun:sqlite"; -import { readFileSync, readdirSync } from "node:fs"; -import { fileURLToPath, URL as NodeURL } from "node:url"; -import { Store, type Command, type Sql } from "../src/storage"; - -const now="2026-11-13T02:00:00.000Z"; -const row=(id:string,modified=now,title="first",schema="5.2")=>({id,raw:JSON.stringify({dataType:"CVE_RECORD",dataVersion:schema,cveMetadata:{cveId:id,state:"PUBLISHED",dateUpdated:modified,datePublished:now},containers:{cna:{title}}})}); -function fixture() { - const db=new Database(":memory:"); - const directory=fileURLToPath(new NodeURL("../migrations/",import.meta.url)); - for(const name of readdirSync(directory).filter(v=>v.endsWith(".sql")).sort()) db.exec(readFileSync(new NodeURL(name,new NodeURL("../migrations/",import.meta.url)),"utf8")); - let clock=now,firsts=0,alls=0,batches=0,maxBinds=0; - let put=async (_key:string,_raw:string)=>{}; - const sql:Sql={ - first:async(text:string,values:(string|number|null)[]=[])=>{firsts++;return db.query(text).get(...values);}, - all:async(text:string,values:(string|number|null)[]=[])=>{alls++;maxBinds=Math.max(maxBinds,values.length);return db.query(text).all(...values);}, - batch:async(commands:Command[])=>{batches++;db.transaction(()=>{for(const command of commands){maxBinds=Math.max(maxBinds,command.values.length);db.query(command.sql).run(...command.values);}})();}, - }; - const store=new Store(sql,{put:async(key,raw)=>put(key,raw),get:async()=>null},()=>clock); - return {db,store,writer:store.writer("cve","owner"),clock:(value:string)=>{clock=value;},put:(value:typeof put)=>{put=value;},reset:()=>{firsts=alls=batches=maxBinds=0;},counts:()=>({firsts,alls,batches,maxBinds})}; -} - -test("64 distinct supported baseline records use one read and one fenced metadata batch",async()=>{ - const f=fixture();try{ - await f.store.lease("cve","owner",now);f.reset();let active=0,peak=0; - f.put(async()=>{active++;peak=Math.max(peak,active);await Bun.sleep(1);active--;}); - await f.writer.cveBatch(Array.from({length:64},(_,i)=>row(`CVE-2026-${1000+i}`)),now); - expect(f.counts()).toEqual({firsts:0,alls:1,batches:1,maxBinds:64}); - expect(peak).toBe(6);expect(active).toBe(0); - expect(f.db.query("SELECT count(*) n FROM source_record").get()).toEqual({n:64}); - expect(f.db.query("SELECT count(*) n FROM cve").get()).toEqual({n:64}); - }finally{f.db.close();} -}); - -test("bulk prevalidation preserves newer records and rejects every equal-date conflict before R2 writes",async()=>{ - const f=fixture();try{ - await f.store.lease("cve","owner",now); - await f.writer.cve(row("CVE-2026-1001","2026-11-14T00:00:00.000Z").raw,now); - await f.writer.cve(row("CVE-2026-1002").raw,now); - f.reset();let writes=0;f.put(async()=>{writes++;}); - await expect(f.writer.cveBatch([row("CVE-2026-1000"),row("CVE-2026-1002",now,"conflict")],now)).rejects.toThrow("conflicting equal"); - expect(writes).toBe(0);expect(f.counts().batches).toBe(0); - await f.writer.cveBatch([row("CVE-2026-1001"),row("CVE-2026-1002")],now); - expect(writes).toBe(0); - expect(f.db.query("SELECT modified_at FROM source_record WHERE id='CVE-2026-1001'").get()).toEqual({modified_at:"2026-11-14T00:00:00.000Z"}); - }finally{f.db.close();} -}); - -test("unchanged CVE admission reads revision metadata without returning stored payloads", async () => { - const f = fixture(); - - try { - const record = row("CVE-2026-1001"); - await f.store.lease("cve", "owner", now); - await f.writer.cve(record.raw, now); - f.db.exec("ALTER TABLE source_record ADD COLUMN payload_raw text; ALTER TABLE source_record ADD COLUMN payload_jsonb text"); - f.db.run("UPDATE source_record SET payload_raw=?,payload_jsonb=?", [record.raw, record.raw]); - - const projected: string[][] = []; - - function recordColumns(value: T) { - if (value != null) projected.push(Object.keys(value).sort()); - } - - const original = f.store.sql; - - const sql: Sql = { - ...original, - first: async (text: string, values?: (string | number | null)[]) => { - const result = await original.first(text, values); - - recordColumns(result); - - return result; - }, - all: async (text: string, values?: (string | number | null)[]) => { - const results = await original.all(text, values); - - for (const result of results) recordColumns(result); - - return results; - }, - }; - - const rawWrites: string[] = []; - - const store = new Store(sql, { put: async (key) => { rawWrites.push(key); }, get: async () => null }, () => now); - const writer = store.writer("cve", "owner"); - await writer.cve(record.raw, now); - await writer.cveBatch([record], now); - - expect(rawWrites).toEqual([]); - - const columns = ["id", "modified_at", "object_key", "payload_sha256", "source_url", "supported"]; - - expect(projected).toEqual([columns, columns]); - } finally { - f.db.close(); - } -}); - -test("Postgres admission sends the inline original once for both stored representations", async () => { - const writes: Command[] = []; - - const sql: Sql = { - inlinePayloads: true, - first: async () => null, - all: async () => [], - batch: async (commands) => { writes.push(...commands); }, - }; - - const store = new Store(sql, { put: async () => {}, get: async () => null }); - const single = row("CVE-2026-1001"); - const bulk = row("CVE-2026-1002"); - - await store.cve(single.raw, now); - await store.cveBatch([bulk], now); - - const inlineWrites = writes.filter(({ sql }) => sql.startsWith("INSERT INTO source_record")); - - expect(inlineWrites).toHaveLength(2); - expect(inlineWrites[0]?.values.filter((value) => value === single.raw)).toHaveLength(1); - expect(inlineWrites[1]?.values.filter((value) => value === bulk.raw)).toHaveLength(1); -}); - -test("bulk R2 failure settles all started writes before rejecting without metadata or after commands",async()=>{ - const f=fixture();try{ - await f.store.lease("cve","owner",now);f.reset();let active=0,settled=0,started=0; - f.put(async()=>{started++;active++;try{if(started===2)throw new Error("R2 unavailable");await Bun.sleep(15);}finally{active--;settled++;}}); - await expect(f.writer.cveBatch(Array.from({length:8},(_,i)=>row(`CVE-2026-${1000+i}`)),now,[{sql:"UPDATE source_checkpoint SET complete=1 WHERE source='cve'",values:[]}])).rejects.toThrow("R2 unavailable"); - expect(started).toBe(6);expect(settled).toBe(6);expect(active).toBe(0);expect(f.counts().batches).toBe(0); - expect(f.db.query("SELECT count(*) n FROM source_record").get()).toEqual({n:0}); - }finally{f.db.close();} -}); - -test("expired writer fences and failing metadata keep source pointers and attached membership atomic",async()=>{ - for(const fault of ["expired","metadata"]) { - const f=fixture();try{ - await f.store.lease("cve","owner",now); - f.put(async()=>{if(fault==="expired")f.clock("2026-11-13T02:11:00.000Z");}); - const after=[{sql:"UPDATE source_checkpoint SET complete=1 WHERE source='cve'",values:[]}]; - if(fault==="metadata")after.push({sql:"INSERT INTO table_that_does_not_exist VALUES(1)",values:[]}); - await expect(f.writer.cveBatch([row("CVE-2026-1000")],now,after)).rejects.toThrow(); - expect(f.db.query("SELECT count(*) n FROM source_record").get()).toEqual({n:0}); - expect(f.db.query("SELECT count(*) n FROM cve").get()).toEqual({n:0}); - expect(f.db.query("SELECT complete FROM source_checkpoint WHERE source='cve'").get()).toEqual({complete:0}); - }finally{f.db.close();} - } -}); - - -test("bulk R2 phase waits for old-row reads and finishes before fenced metadata commit", async () => { - const f=fixture(); - try { - await f.store.lease("cve","owner",now); - let readFinished=false, active=0, peak=0, puts=0; - const original=f.store.sql; - const sql:Sql={...original, - all:async(text:string,values:(string|number|null)[]=[])=>{ - await Bun.sleep(5); - const rows=await original.all(text,values);readFinished=true;return rows; - }, - batch:async(commands:Command[])=>{ - expect(readFinished).toBe(true);expect(active).toBe(0);expect(puts).toBe(19); - await original.batch(commands); - }, - }; - const store=new Store(sql,{get:async()=>null,put:async()=>{ - expect(readFinished).toBe(true);active++;peak=Math.max(peak,active); - expect(active).toBeLessThanOrEqual(6); - try {await Bun.sleep(1);puts++;}finally{active--;} - }},()=>now); - await store.writer("cve","owner").cveBatch(Array.from({length:19},(_,i)=>row(`CVE-2026-${2000+i}`)),now); - expect(peak).toBe(6);expect(puts).toBe(19);expect(active).toBe(0); - }finally{f.db.close();} -}); - -test("a slow baseline put does not idle completed R2 slots or commit metadata early", async () => { - const f=fixture(); - const slow=Promise.withResolvers(), seventh=Promise.withResolvers(); - let work:Promise|undefined; - try { - await f.store.lease("cve","owner",now);f.reset(); - let active=0,peak=0,started=0,settled=0; - f.put(async()=>{ - const position=++started; - active++;peak=Math.max(peak,active); - try { - if(position===1)await slow.promise; - else {if(position===7)seventh.resolve();await Bun.sleep(1);} - }finally{active--;settled++;} - }); - work=f.writer.cveBatch(Array.from({length:19},(_,i)=>row(`CVE-2026-${3000+i}`)),now); - const seventhBeforeSlow=await Promise.race([seventh.promise.then(()=>true),Bun.sleep(100).then(()=>false)]); - const beforeRelease={active,batches:f.counts().batches}; - slow.resolve();await work; - expect(seventhBeforeSlow).toBe(true); - expect(beforeRelease.active).toBeGreaterThanOrEqual(1); - expect(beforeRelease.batches).toBe(0); - expect(peak).toBe(6);expect(active).toBe(0);expect(settled).toBe(19); - expect(f.db.query("SELECT count(*) n FROM source_record").get()).toEqual({n:19}); - }finally{slow.resolve();await work;f.db.close();} -}); - -test("a refilled R2 slot failure drains its slow peer and starts no further writes", async () => { - const f=fixture(),slow=Promise.withResolvers(),failed=Promise.withResolvers(); - let work:Promise|undefined; - try { - await f.store.lease("cve","owner",now);f.reset(); - let active=0,started=0,settled=0; - f.put(async()=>{ - const position=++started;active++; - try { - if(position===1)await slow.promise; - else if(position===7){failed.resolve();throw new Error("refilled slot failed");} - else await Bun.sleep(5); - }finally{active--;settled++;} - }); - work=f.writer.cveBatch(Array.from({length:19},(_,i)=>row(`CVE-2026-${4000+i}`)),now) - .then(()=>{throw new Error("failed R2 transaction unexpectedly committed");},error=>error); - await failed.promise; - await Bun.sleep(10); - const observed={started,active,batches:f.counts().batches}; - slow.resolve(); - expect(await work).toBeInstanceOf(Error); - expect(String(await work)).toContain("refilled slot failed"); - expect(observed).toEqual({started:7,active:1,batches:0}); - expect(started).toBe(7);expect(active).toBe(0);expect(settled).toBe(7); - expect(f.db.query("SELECT count(*) n FROM source_record").get()).toEqual({n:0}); - }finally{slow.resolve();await work;f.db.close();} -}); - -test("baseline phase diagnostics contain only fixed counts and finite durations", async () => { - const f=fixture(),log=spyOn(console,"info").mockImplementation(()=>{}); - try { - await f.store.lease("cve","owner",now); - await f.writer.cveBatch([row("CVE-2026-5000")],now); - expect(log).toHaveBeenCalledTimes(1); - const metric:unknown=JSON.parse(String(log.mock.calls[0]?.[0])); - expect(metric).toEqual({event:"baseline_write_phases",records:1,changed:1, - prepare_ms:expect.any(Number),read_ms:expect.any(Number),raw_ms:expect.any(Number),metadata_ms:expect.any(Number)}); - if(!metric || typeof metric!=="object")throw new Error("missing structured baseline metric"); - for(const [name,value] of Object.entries(metric)){ - if(name.endsWith("_ms")){expect(Number.isFinite(value)).toBe(true);expect(value).toBeGreaterThanOrEqual(0);} - } - expect(JSON.stringify(metric)).not.toContain("CVE-"); - }finally{log.mockRestore();f.db.close();} -}); - -test("packed baseline writes keep originals and metadata atomic through R2 and fenced SQL failures",async()=>{ - for(const fault of ["raw","expired","metadata","conflict"]){ - const f=fixture(); - try { - await f.store.lease("cve","owner",now); - if(fault==="conflict")await f.writer.cve(row("CVE-2026-7000").raw,now); - f.reset();let writes=0; - f.put(async()=>{ - writes++; - if(fault==="raw")throw new Error("packed R2 unavailable"); - if(fault==="expired")f.clock("2026-11-13T02:11:00.000Z"); - }); - const after=[{sql:"UPDATE source_checkpoint SET complete=1 WHERE source='cve'",values:[]}]; - if(fault==="metadata")after.push({sql:"INSERT INTO missing_packed_metadata_table VALUES(1)",values:[]}); - await expect(f.writer.cveBatch([row("CVE-2026-7000",now,"replacement"),row("CVE-2026-7001")],now,after,"packed")).rejects.toThrow(); - expect(writes).toBe(fault==="conflict"?0:1); - expect(f.db.query("SELECT count(*) n FROM source_record").get()).toEqual({n:fault==="conflict"?1:0}); - expect(f.db.query("SELECT count(*) n FROM cve").get()).toEqual({n:fault==="conflict"?1:0}); - expect(f.db.query("SELECT complete FROM source_checkpoint WHERE source='cve'").get()).toEqual({complete:0}); - }finally{f.db.close();} - } -}); - -test("64 packed originals make one immutable put and exact per-CVE pointers with no replay writes",async()=>{ - const f=fixture();try{ - await f.store.lease("cve","owner",now);f.reset(); - const writes=new Map(); - f.put(async(key,raw)=>{writes.set(key,raw);}); - const records=Array.from({length:64},(_,index)=>row(`CVE-2026-${8000+index}`)); - await f.writer.cveBatch(records,now,[],"packed"); - expect(writes.size).toBe(1); - const [key]=writes.keys();expect(key).toMatch(/^cve-pack-v1\/[a-f0-9]{64}\.raw$/); - expect(key && writes.get(key)).toBe(records.map(record=>record.raw).join("")); - const rows=f.db.query<{object_key:string;payload_sha256:string},[]>("SELECT object_key,payload_sha256 FROM source_record ORDER BY id").all(); - expect(rows).toHaveLength(64); - for(const row of rows){expect(row.object_key.startsWith(`${key}#`)).toBe(true);expect(row.object_key.endsWith(`:${row.payload_sha256}`)).toBe(true);} - f.put(async()=>{throw new Error("unchanged packed replay attempted raw write");}); - await f.writer.cveBatch(records,now,[],"packed"); - expect(f.db.query("SELECT count(*) n FROM source_record").get()).toEqual({n:64}); - }finally{f.db.close();} -}); diff --git a/services/advisories/tsconfig.json b/services/advisories/tsconfig.json deleted file mode 100644 index 66096b5d8..000000000 --- a/services/advisories/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["ES2022"], - "types": ["@cloudflare/workers-types", "bun"], - "strict": true, - "noUncheckedIndexedAccess": true, - "skipLibCheck": true, - "noEmit": true - }, - "include": [ - "src/**/*.ts", - "test/**/*.ts", - "scripts/**/*.ts", - "worker-configuration.d.ts" - ] -} diff --git a/services/advisories/worker-configuration.d.ts b/services/advisories/worker-configuration.d.ts deleted file mode 100644 index 21d746c8b..000000000 --- a/services/advisories/worker-configuration.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -/* eslint-disable */ -// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: 3fa84b2e30d0b37fd1bdd5a78a2d88ef) -interface __BaseEnv_Env { - RAW: R2Bucket; - DB: D1Database; - HYPERDRIVE: Hyperdrive; - CVE_BATCH_SIZE: "32"; - DB_BACKEND: "d1"; -} -declare namespace Cloudflare { - interface GlobalProps { - mainModule: typeof import("./src/index"); - } - interface Env extends __BaseEnv_Env {} -} -interface Env extends __BaseEnv_Env {} -type StringifyValues> = { - [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; -}; -declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} -} -declare module "*.txt" { - const value: string; - export default value; -} -declare module "*.html" { - const value: string; - export default value; -} -declare module "*.sql" { - const value: string; - export default value; -} -declare module "*.bin" { - const value: ArrayBuffer; - export default value; -} -declare module "*.wasm" { - const value: WebAssembly.Module; - export default value; -} -declare module "*.wasm?module" { - const value: WebAssembly.Module; - export default value; -} \ No newline at end of file diff --git a/services/advisories/wrangler.jsonc b/services/advisories/wrangler.jsonc deleted file mode 100644 index 68982af9a..000000000 --- a/services/advisories/wrangler.jsonc +++ /dev/null @@ -1,32 +0,0 @@ -{ - "$schema": "node_modules/wrangler/config-schema.json", - "name": "omg-advisories", - "main": "src/index.ts", - "compatibility_date": "2026-11-13", - "compatibility_flags": ["nodejs_compat"], - "account_id": "f1e95b3e1b502cf366dfc81a863695fa", - "d1_databases": [ - { - "binding": "DB", - "database_name": "omg-advisories", - "database_id": "98202f8c-7d5f-4de9-8ddd-cea35fd95d09", - "migrations_dir": "migrations", - }, - ], - "hyperdrive": [ - { - "binding": "HYPERDRIVE", - "id": "edb12adb4d9941ffa291ca95285dfb24", - }, - ], - "r2_buckets": [{ "binding": "RAW", "bucket_name": "omg-advisories-raw" }], - "vars": { "CVE_BATCH_SIZE": "32", "DB_BACKEND": "d1" }, - "limits": { "cpu_ms": 30000 }, - // Baseline imports make bounded R2/D1 round trips; place execution near those stores. - "placement": { "mode": "smart" }, - "triggers": { "crons": ["* * * * *", "2-57/5 * * * *", "3-58/5 * * * *"] }, - "observability": { - "enabled": true, - "traces": { "enabled": true, "head_sampling_rate": 0.1 }, - }, -} diff --git a/services/advisories/wrangler.pg.jsonc b/services/advisories/wrangler.pg.jsonc deleted file mode 100644 index e2458be41..000000000 --- a/services/advisories/wrangler.pg.jsonc +++ /dev/null @@ -1,38 +0,0 @@ -{ - "$schema": "node_modules/wrangler/config-schema.json", - "name": "omg-advisories", - "main": "src/index.pg.ts", - "compatibility_date": "2026-11-13", - "compatibility_flags": ["nodejs_compat"], - "account_id": "f1e95b3e1b502cf366dfc81a863695fa", - "workers_dev": true, - "routes": [{ "pattern": "advisories.latham.cloud", "custom_domain": true }], - "d1_databases": [ - { - "binding": "DB", - "database_name": "omg-advisories", - "database_id": "98202f8c-7d5f-4de9-8ddd-cea35fd95d09", - "migrations_dir": "migrations", - }, - ], - "hyperdrive": [ - { - "binding": "HYPERDRIVE", - "id": "edb12adb4d9941ffa291ca95285dfb24", - }, - { - "binding": "HYPERDRIVE_REPLICA", - "id": "7ae6aa5033a94a2c9c1c77e2f25cf54f", - }, - ], - "r2_buckets": [{ "binding": "RAW", "bucket_name": "omg-advisories-raw" }], - "vars": { "CVE_BATCH_SIZE": "512", "DB_BACKEND": "postgres" }, - "limits": { "cpu_ms": 30000 }, - "placement": { "mode": "smart" }, - "triggers": { "crons": ["* * * * *", "2-57/5 * * * *", "3-58/5 * * * *"] }, - "tail_consumers": [{ "service": "omg-cve" }], - "observability": { - "enabled": true, - "traces": { "enabled": true, "head_sampling_rate": 0.1 }, - }, -} diff --git a/services/advisory-staging/README.md b/services/advisory-staging/README.md deleted file mode 100644 index 41d6a24bf..000000000 --- a/services/advisory-staging/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Isolated advisory baseline staging - -`wrangler.example.json` is a disabled example for the isolated Nov 21 baseline stage, not deployment configuration. Do not target production or enable the stage without separate operator approval. The stage uses its own Wrangler config, Worker, D1 database and private R2 bucket. Its only admitted hostname is `https://omg-advisories-stage-20261121-1d6c61c4.latham.workers.dev`; keep version previews off. Configure the exact hostname's Cloudflare Access application before exposing it and use its application AUD as `STAGE_ACCESS_AUD`. The Worker requires the trusted invocation's Access context with that AUD, not an Access or forwarding header supplied by the caller. Confirm Service Auth ingress on the existing plan, rather than enabling Access account-wide. - -After independently checking both resource bindings, record the fresh database's `database_instance.id` as `STAGE_DATABASE_INSTANCE_ID`. Only the approved isolated bucket gets the empty marker object `stage-isolation/`. Both checks must match before the stage handler can read or write advisory state. Enable `STAGE_MODE=isolated-baseline-v1` only with these checks and distinct stage-only `STAGE_INGEST_TOKEN` and `STAGE_RUNTIME_REFRESH_SECRET` secrets, neither copied from production. Cron remains off unless separately configured and enabled with `STAGE_ENABLE_CRON=true`. - -The stage operator targets only the pinned host, refuses redirects, and uses `STAGE_ACCESS_CLIENT_ID` and `STAGE_ACCESS_CLIENT_SECRET` plus the respective stage operation secret from the environment. Proof also needs the usual ephemeral GitHub installation token. The operator doesn't accept an endpoint or a token file. Its private checkpoint envelope is incompatible with the production tools. Do not use the production advisory workflow on staging. - -The stage handler binds private baseline operations to the fixed production origin from the first write, without sending anything to production or changing which environment receives the request. Switching the resource bindings of the **unmodified** production Worker after separately approved proof and cutover can preserve the exact canonical session. Do not copy or edit an endpoint in a receipt to make promotion work. Stage cron and writers must be stopped before promotion; rollback reselects the intact incumbent Worker and resource pair. Cloud deployment, Access enforcement, real resource IDs, limits, import and cutover still require operator receipts; an offline fixture or a dry bundle cannot establish them. - -## Physical admission before routing - -After separate approval, boot an inert stage stub with `STAGE_MODE=disabled`, no D1/R2, no Cron, routes, workers.dev subdomain or Version URLs. Do not deploy the example directly. Independently record the approved physical D1 UUID and Standard R2 bucket name/default jurisdiction in a local JSON manifest with `account_id`, `worker`, `d1_id`, `r2_bucket` and `r2_jurisdiction`. Use the approved UUID in the stage config, not the placeholder. Confirm the exact title/identity of the resources and reserve the quota before uploading an enabled draft. Upload the reviewed candidate as a version with the subdomain and Version URLs off; do not deploy it or create a route. The latest active version stays the inert stub. - -Use a read-only Cloudflare API credential through the existing approved environment mechanism. Do not pass it on the command line. With the explicit JSON config used for the upload and the exact returned version ID: - -```sh -bun services/advisory-staging/admission.ts --approved "$APPROVED_IDS" --config "$STAGE_CONFIG" --version "$DRAFT_VERSION" -``` - -The admission command does not change resources. It queries Cloudflare's exact effective draft and serving versions and reads the named D1/R2 resources in the expected account. It refuses unknown or incumbent identities, active candidates, a non-inert stub, enabled stage ingress/previews, and config/effective mismatches. The logical instance and bucket marker are additional runtime protections, not proof of which physical stores Cloudflare bound. Save the receipt, recheck admission immediately before any separately approved activation, and use only the returned version ID. Never shortcut with a normal `wrangler deploy`. Require the exact host's Access policy independently before enabling that host, leave previews and any alternate routes off, and verify both positive and denied live probes before any import. If any provider data is missing, ambiguous or no longer matches, leave routing off. Cron remains off for this admission; a later staged Cron change must preserve both admitted bindings and be independently checked without changing production. - -Once the operator has approved the protected route, verified actual bindings and the delta window, and obtained separate import authorization: - -```sh -bun services/advisory-staging/operator.ts ingest --state "$PRIVATE_STAGE_STATE" --archive "$EXACT_ZIP" --max-records 256 -bun services/advisory-staging/operator.ts finalize --state "$PRIVATE_STAGE_STATE" -bun services/advisory-staging/operator.ts prove --state "$PRIVATE_STAGE_STATE" -``` - -The remaining ingest waves are serial, at most 1,000 records, and must finish with the archive exhausted before finalization. Finalize only after fresh catch-up; proof is capped at 20 calls. The stage operator is qualified for the exact Nov 21 digest and tag commit, not for newer sources. Stop on mismatch or missing receipts. No command here authorizes provisioning, import, cutover, merge, or release. diff --git a/services/advisory-staging/admission.ts b/services/advisory-staging/admission.ts deleted file mode 100644 index 70bda3e5b..000000000 --- a/services/advisory-staging/admission.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { readFile } from "node:fs/promises"; -import { parseArgs } from "node:util"; -import { boundedBody, object } from "../advisories/src/domain"; -import { STAGE_MODE } from "./stage-identity"; - -const ACCOUNT = "f1e95b3e1b502cf366dfc81a863695fa"; -const STAGE = "omg-advisories-stage-20261121-1d6c61c4"; -const INCUMBENT = "omg-advisories"; -const INCUMBENT_D1 = "98202f8c-7d5f-4de9-8ddd-cea35fd95d09"; -const INCUMBENT_R2 = "omg-advisories-raw"; -const HOST = "https://api.cloudflare.com"; -const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; - -function require(condition: unknown, message: string): asserts condition { - if (!condition) throw new Error(message); -} - -function array(value: unknown) { - require(Array.isArray(value) && value.length <= 256, "invalid bounded provider list"); - return value.map(object); -} - -function exactOne(values: unknown) { - const entries = array(values); - require(entries.length === 1 && entries[0], "expected exactly one binding or active version"); - return entries[0]; -} - -function named(entries: ReturnType, name: string) { - return exactOne(entries.filter(entry => entry.name === name)); -} - -function bindings(version: Record) { - return array(object(version.resources).bindings); -} - -function physical(entries: ReturnType) { - const d1 = named(entries, "DB"), r2 = named(entries, "RAW"); - require(d1.type === "d1" && typeof d1.id === "string" && UUID.test(d1.id), "missing effective physical D1 ID"); - require(r2.type === "r2_bucket" && typeof r2.bucket_name === "string" && - (r2.jurisdiction === undefined || r2.jurisdiction === "default"), "missing or non-default effective R2 identity"); - return { d1: d1.id, r2: r2.bucket_name }; -} - -function active(deployments: Record) { - const latest = array(deployments.deployments)[0]; - require(latest, "no effective live deployment to compare"); - const serving = exactOne(latest.versions); - require(serving.percentage === 100 && typeof serving.version_id === "string" && UUID.test(serving.version_id), "ambiguous active deployment"); - return serving.version_id; -} - -type ApiFetcher = (url: string, init: RequestInit) => Promise; - -export async function admit(approved: Record, config: Record, - candidate: string, credential: string, fetcher: ApiFetcher = fetch) { - const d1 = approved.d1_id, r2 = approved.r2_bucket; - require(approved.account_id === ACCOUNT && approved.worker === STAGE && - typeof d1 === "string" && UUID.test(d1) && d1 !== INCUMBENT_D1 && - d1 !== "00000000-0000-0000-0000-000000000000" && - r2 !== INCUMBENT_R2 && r2 === `${STAGE}-raw` && approved.r2_jurisdiction === "default", "unapproved physical stage identities"); - require(UUID.test(candidate) && credential.length > 0, "exact candidate version and read-only API authorization required"); - require(config.account_id === ACCOUNT && config.name === STAGE && config.main === "stage.ts" && - config.workers_dev === false && config.preview_urls === false && - !("route" in config || "routes" in config || "env" in config || "triggers" in config), "intended stage routing must be disabled"); - const intendedD1 = exactOne(config.d1_databases), intendedR2 = exactOne(config.r2_buckets), vars = object(config.vars); - require(intendedD1.binding === "DB" && intendedD1.database_id === d1 && intendedD1.database_name === STAGE && - intendedR2.binding === "RAW" && intendedR2.bucket_name === r2 && - (intendedR2.jurisdiction === undefined || intendedR2.jurisdiction === "default"), "intended physical stage bindings differ"); - require(vars.STAGE_MODE === STAGE_MODE && vars.STAGE_ENABLE_CRON === "false" && - typeof vars.STAGE_ACCESS_AUD === "string" && /^[a-f0-9]{64}$/.test(vars.STAGE_ACCESS_AUD) && - typeof vars.STAGE_DATABASE_INSTANCE_ID === "string" && /^[a-f0-9]{32}$/.test(vars.STAGE_DATABASE_INSTANCE_ID), "intended draft policy is incomplete"); - - async function get(path: string) { - const url = `${HOST}/client/v4/accounts/${ACCOUNT}/${path}`; - const res = await fetcher(url, { redirect: "error", signal: AbortSignal.timeout(15_000), - headers: { authorization: `Bearer ${credential}`, "cf-r2-jurisdiction": "default" } }); - require(res.ok && !res.redirected && (!res.url || res.url === url), "Cloudflare read-only evidence unavailable"); - const envelope = object(JSON.parse(await boundedBody(res.body, 1024 * 1024))); - require(envelope.success === true, "Cloudflare rejected read-only evidence"); - return object(envelope.result); - } - - const stageScript = `workers/scripts/${STAGE}`, prodScript = `workers/scripts/${INCUMBENT}`; - const [route, stageDeployments, prodDeployments, database, bucket, draft] = await Promise.all([ - get(`${stageScript}/subdomain`), get(`${stageScript}/deployments`), get(`${prodScript}/deployments`), - get(`d1/database/${d1}`), get(`r2/buckets/${r2}`), get(`${stageScript}/versions/${candidate}`), - ]); - require(route.enabled === false && route.previews_enabled === false, "stage routes or previews are already enabled"); - const oldStage = active(stageDeployments), oldProd = active(prodDeployments); - require(oldStage !== candidate, "candidate is already active"); - const [stub, prod] = await Promise.all([get(`${stageScript}/versions/${oldStage}`), get(`${prodScript}/versions/${oldProd}`)]); - require(stub.id === oldStage && prod.id === oldProd && draft.id === candidate, "effective version identity differs"); - const inert = bindings(stub); - const stubMode = named(inert, "STAGE_MODE"); - require(stubMode.type === "plain_text" && stubMode.text === "disabled" && - !inert.some(entry => entry.type === "d1" || entry.type === "r2_bucket"), - "active staging stub is not inert"); - const actual = bindings(draft), candidateStores = physical(actual), prodStores = physical(bindings(prod)); - require(actual.filter(entry => entry.type === "d1" || entry.type === "r2_bucket").length === 2 && - candidateStores.d1 === d1 && candidateStores.r2 === r2 && - candidateStores.d1 !== prodStores.d1 && candidateStores.r2 !== prodStores.r2, "effective stage stores are unknown or overlap the incumbent"); - require(database.uuid === d1 && database.name === STAGE && - bucket.name === r2 && bucket.jurisdiction === "default" && bucket.storage_class === "Standard", "physical resource descriptions differ"); - for (const name of ["STAGE_MODE", "STAGE_ENABLE_CRON", "STAGE_ACCESS_AUD", "STAGE_DATABASE_INSTANCE_ID"]) { - const entry = named(actual, name); - require(entry.type === "plain_text" && entry.text === vars[name], "effective draft policy differs"); - } - return { phase: "admitted_off_traffic", version: candidate, stage_d1_id: d1, stage_r2_bucket: r2, incumbent_version: oldProd }; -} - -if (import.meta.main) { - try { - const { values } = parseArgs({ strict: true, options: { approved: { type: "string" }, config: { type: "string" }, version: { type: "string" } } }); - require(values.approved && values.config && values.version, "approved manifest, fixed stage config and exact draft version required"); - const json = async (path: string) => object(JSON.parse(await readFile(path, "utf8"))); - const [approved, config] = await Promise.all([json(values.approved), json(values.config)]); - console.log(JSON.stringify(await admit(approved, config, values.version, process.env.CLOUDFLARE_API_TOKEN ?? ""))); - } catch { - console.error("Stage admission refused; do not enable routes or deploy the draft"); - process.exitCode = 1; - } -} diff --git a/services/advisory-staging/operator.ts b/services/advisory-staging/operator.ts deleted file mode 100644 index 37821ce8f..000000000 --- a/services/advisory-staging/operator.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { lstat, open, readFile, rename, rm } from "node:fs/promises"; -import { basename } from "node:path"; -import { parseArgs } from "node:util"; -import { fileHash, scanArchive, type ArchiveState } from "../advisories/scripts/archive"; -import { baselineBinding, operatorPost, proofProgress, readCheckpoint, verifyIngestReply, type BaselineBinding } from "../advisories/scripts/operator"; -import { boundedBody, isGitHubInstallationToken, object } from "../advisories/src/domain"; -import { CANONICAL_ORIGIN, STAGE_ORIGIN } from "./stage-identity"; -import { stageCheckpoint, stageOperatorFetcher } from "./transport"; - -const digest = "1d6c61c44cf3e269b6d60ed2fe0a3aa1f7e55445c7f170f16f2fa063bbf73db3"; -const size = 670607648; -const release_tag = "cve_2026-11-21_0000Z"; -const asset = "2026-11-21_all_CVEs_at_midnight.zip.zip"; -const commit = "0acf54247f05316804b369e2e2eb715f7e4ec71d"; -const baseline_at = "2026-11-21T00:00:00.000Z"; - -async function run() { - const { values, positionals } = parseArgs({ strict: true, allowPositionals: true, - options: { state: { type: "string" }, archive: { type: "string" }, "max-records": { type: "string", default: "256" } } }); - const [operation] = positionals; - const path = values.state; - const max = Number(values["max-records"]); - if (positionals.length !== 1 || !path || !Number.isSafeInteger(max) || max < 1 || max > 1000 || - (operation !== "ingest" && operation !== "finalize" && operation !== "prove")) - throw new Error("expected ingest, finalize or prove with --state, and ingest with --archive and at most 1000 records"); - const endpoint = new URL(STAGE_ORIGIN); - const fetcher = stageOperatorFetcher(process.env.STAGE_ACCESS_CLIENT_ID, process.env.STAGE_ACCESS_CLIENT_SECRET); - const token = operation === "prove" ? process.env.STAGE_RUNTIME_REFRESH_SECRET : process.env.STAGE_INGEST_TOKEN; - if (!token || token.length < 32) throw new Error("stage-only operation secret required"); - const post = (path: string, body: unknown) => operatorPost({ endpoint, token, path, body: JSON.stringify(body), fetcher }); - let state: ArchiveState = { digest, next_entry: 0, accepted: 0, exhausted: false, finished_at: null }; - let binding: BaselineBinding | undefined; - try { - const info = await lstat(path); - if (!info.isFile() || info.isSymbolicLink() || info.size > 16384 || (info.mode & 0o077) !== 0) - throw new Error("checkpoint must be a bounded private file"); - const saved = stageCheckpoint(JSON.parse(await readFile(path, "utf8"))); - binding = baselineBinding(saved.baseline, digest, CANONICAL_ORIGIN); - state = readCheckpoint(saved, binding); - } catch (error) { - if (!(error instanceof Error && "code" in error && error.code === "ENOENT" && operation === "ingest")) throw error; - } - if (operation === "prove") { - const githubToken = process.env.GITHUB_TOKEN; - if (!state.exhausted || !binding || !isGitHubInstallationToken(githubToken)) throw new Error("exhausted stage session and ephemeral GitHub token required"); - for (let step = 1; step <= 20; step++) { - const result = proofProgress(await post("/internal/baseline/verify", { - ...binding, release_tag, asset, github_token: githubToken, - }), { digest, release_tag, asset }); - if (result.commit_sha !== commit) throw new Error("publisher commit pin differs"); - console.log(JSON.stringify({ ...result, step })); - if (result.phase === "verified" || result.phase === "awaiting_import" || result.phase === "awaiting_catchup") return; - } - return; - } - if (operation === "finalize") { - if (!binding || !state.exhausted) throw new Error("stage archive is not exhausted"); - const result = await post("/internal/baseline", { ...binding, baseline_at, accepted: state.accepted, exhausted: true, finished_at: state.finished_at }); - console.log(JSON.stringify({ caught_up: result.caught_up === true, archive_verified: result.archive_verified === true })); - return; - } - const archive = values.archive; - if (!archive || basename(archive) !== asset || (await lstat(archive)).size !== size || await fileHash(archive) !== digest) - throw new Error("bound stage archive bytes required"); - const publisher = "https://api.github.com/repos/CVEProject/cvelistV5"; - async function publisherMetadata(path: string) { - const result = await fetch(publisher + path, { redirect: "error", signal: AbortSignal.timeout(15000), - headers: { accept: "application/vnd.github+json", "user-agent": "omg-advisories-stage" } }); - if (!result.ok) throw new Error("publisher metadata unavailable"); - return object(JSON.parse(await boundedBody(result.body, 1024 * 1024))); - } - const [release, ref] = await Promise.all([publisherMetadata(`/releases/tags/${release_tag}`), publisherMetadata(`/git/ref/tags/${release_tag}`)]); - const target = object(ref.object); - if (target.type !== "commit" || target.sha !== commit || release.tag_name !== release_tag || !Array.isArray(release.assets) || - release.assets.map(object).filter(entry => entry.name === asset && entry.size === size && entry.digest === `sha256:${digest}`).length !== 1) - throw new Error("publisher stage identity differs"); - const started = baselineBinding(await post("/internal/baseline/start", { digest, baseline_at, ...binding }), digest, CANONICAL_ORIGIN); - if (binding && (started.instance_id !== binding.instance_id || started.session_id !== binding.session_id)) - throw new Error("stage resume session differs"); - const save = async (next: ArchiveState) => { - const temp = `${path}.${randomUUID()}`; - try { - const file = await open(temp, "wx", 0o600); - try { await file.writeFile(JSON.stringify({ transport_endpoint: STAGE_ORIGIN, checkpoint: { ...next, baseline: started } })); await file.sync(); } - finally { await file.close(); } - await rename(temp, path); - } finally { - await rm(temp, { force: true }); - } - state = next; - }; - await save(state); - if (!state.exhausted) await scanArchive({ path: archive, digest, state, maxRecords: max, batchSize: 64, - encodeBatch: (records) => JSON.stringify({ source: "cve", records, baseline: started }), - send: async body => { - const batch = object(JSON.parse(body)); - if (!Array.isArray(batch.records)) throw new Error("invalid stage batch"); - verifyIngestReply(await post("/internal/ingest", batch), batch.records.length); - }, save }); - console.log(JSON.stringify({ accepted: state.accepted, next_entry: state.next_entry, exhausted: state.exhausted })); -} - -run().catch(() => { - console.error("Stage operation refused; inspect the private checkpoint and sanitized operator evidence"); - process.exitCode = 1; -}); diff --git a/services/advisory-staging/stage-identity.ts b/services/advisory-staging/stage-identity.ts deleted file mode 100644 index b31b2fc3c..000000000 --- a/services/advisory-staging/stage-identity.ts +++ /dev/null @@ -1,10 +0,0 @@ -export const STAGE_ORIGIN = "https://omg-advisories-stage-20261121-1d6c61c4.latham.workers.dev"; -export const CANONICAL_ORIGIN = "https://omg-advisories.latham.workers.dev"; -export const STAGE_MODE = "isolated-baseline-v1"; - -export const BASELINE_PATHS = new Set([ - "/internal/baseline/start", "/internal/ingest", "/internal/baseline", "/internal/baseline/verify", -]); -export const STAGE_POST_PATHS = new Set([ - ...BASELINE_PATHS, "/internal/cve-refresh", "/internal/runtime-refresh", -]); diff --git a/services/advisory-staging/stage.ts b/services/advisory-staging/stage.ts deleted file mode 100644 index 63dd647d5..000000000 --- a/services/advisory-staging/stage.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { refresh, type Fetcher } from "../advisories/src/ingestion"; -import { r2Raw } from "../advisories/src/raw-pack"; -import { handle } from "../advisories/src/service"; -import { BASELINE_PATHS, CANONICAL_ORIGIN, STAGE_MODE, STAGE_ORIGIN, STAGE_POST_PATHS } from "./stage-identity"; -import { d1Sql, Store } from "../advisories/src/storage"; - -type StagePolicy = { - STAGE_MODE?: string; - STAGE_ACCESS_AUD?: string; - STAGE_DATABASE_INSTANCE_ID?: string; - STAGE_INGEST_TOKEN?: string; - STAGE_RUNTIME_REFRESH_SECRET?: string; -}; -type StageEnv = StagePolicy & Pick & { STAGE_ENABLE_CRON?: string }; - -function configured(policy: StagePolicy) { - const { STAGE_ACCESS_AUD: aud, STAGE_DATABASE_INSTANCE_ID: id, STAGE_INGEST_TOKEN: ingest, STAGE_RUNTIME_REFRESH_SECRET: proof } = policy; - if (policy.STAGE_MODE !== STAGE_MODE || !id || !/^[a-f0-9]{32}$/.test(id) || - !aud || !/^[a-f0-9]{64}$/.test(aud) || - !ingest || !proof || ingest.length < 32 || proof.length < 32 || ingest === proof) return null; - return { aud, id, ingest, proof }; -} - -async function isolated(store: Store, id: string) { - const database = await store.sql.first<{id: string}>("SELECT id FROM database_instance"); - return database?.id === id && (await store.raw.get(`stage-isolation/${id}`)) !== null; -} - -const unavailable = () => new Response(null, { status: 503, headers: { "Cache-Control": "no-store" } }); - -export async function handleStage( - request: Request, access: Pick, policy: StagePolicy, - makeStore: () => Store, now: string, fetcher?: Fetcher, -) { - const url = new URL(request.url); - if (url.origin !== STAGE_ORIGIN || !access.access) { - return new Response(null, { status: 403, headers: { "Cache-Control": "no-store" } }); - } - const options = configured(policy); - if (!options) return unavailable(); - if (access.access.aud !== options.aud) { - return new Response(null, { status: 403, headers: { "Cache-Control": "no-store" } }); - } - if (!(request.method === "GET" && url.pathname.startsWith("/v1/")) && - !(request.method === "POST" && !url.search && STAGE_POST_PATHS.has(url.pathname))) { - return new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } }); - } - const store = makeStore(); - try { - if (!await isolated(store, options.id)) return unavailable(); - } catch { - return unavailable(); - } - const input = BASELINE_PATHS.has(url.pathname) - ? new Request(new URL(url.pathname, CANONICAL_ORIGIN), { - method: request.method, body: request.body, - headers: { - authorization: request.headers.get("authorization") ?? "", - "content-type": request.headers.get("content-type") ?? "", - }, - }) - : request; - const response = await handle(input, store, options.ingest, now, fetcher, options.proof); - const headers = new Headers(response.headers); - headers.set("Cache-Control", "no-store"); - return new Response(response.body, { status: response.status, headers }); -} - -export default { - fetch(request, env, ctx) { - return handleStage(request, ctx, env, () => new Store(d1Sql(env.DB), r2Raw(env.RAW)), new Date().toISOString()); - }, - async scheduled(_event, env) { - if (env.STAGE_ENABLE_CRON !== "true") return; - const options = configured(env); - const store = new Store(d1Sql(env.DB), r2Raw(env.RAW)); - if (!options || !await isolated(store, options.id)) throw new Error("stage bindings not admitted"); - await refresh(store, (url, init) => fetch(url, init), new Date().toISOString(), 32); - }, -} satisfies ExportedHandler; diff --git a/services/advisory-staging/test/admission.test.ts b/services/advisory-staging/test/admission.test.ts deleted file mode 100644 index 19a72e605..000000000 --- a/services/advisory-staging/test/admission.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { expect, test } from "bun:test"; -import { admit } from "../admission"; -import { STAGE_MODE } from "../stage-identity"; - -const account = "f1e95b3e1b502cf366dfc81a863695fa"; -const worker = "omg-advisories-stage-20261121-1d6c61c4"; -const d1 = "11111111-1111-4111-a111-111111111111"; -const oldD1 = "98202f8c-7d5f-4de9-8ddd-cea35fd95d09"; -const unknownD1 = "22222222-2222-4222-a222-222222222222"; -const r2 = `${worker}-raw`, oldR2 = "omg-advisories-raw"; -const draft = "aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaaa"; -const stub = "bbbbbbbb-bbbb-4bbb-bbbb-bbbbbbbbbbbb"; -const prod = "cccccccc-cccc-4ccc-accc-cccccccccccc"; -const vars = { STAGE_MODE, STAGE_ENABLE_CRON: "false", STAGE_ACCESS_AUD: "a".repeat(64), STAGE_DATABASE_INSTANCE_ID: "b".repeat(32) }; -const approved = { account_id: account, worker, d1_id: d1, r2_bucket: r2, r2_jurisdiction: "default" }; -const config = { - account_id: account, name: worker, main: "stage.ts", workers_dev: false, preview_urls: false, vars, - d1_databases: [{ binding: "DB", database_id: d1, database_name: worker }], - r2_buckets: [{ binding: "RAW", bucket_name: r2 }], -}; -const paths = { - stage: `workers/scripts/${worker}`, - prod: "workers/scripts/omg-advisories", -}; - -function stores(db: string, raw: string) { - return [{ type: "d1", name: "DB", id: db }, { type: "r2_bucket", name: "RAW", bucket_name: raw }]; -} - -function fixture() { - const actual = [...stores(d1, r2), ...Object.entries(vars).map(([name, text]) => ({ type: "plain_text", name, text }))]; - const data = new Map([ - [`${paths.stage}/subdomain`, { enabled: false, previews_enabled: false }], - [`${paths.stage}/deployments`, { deployments: [{ versions: [{ version_id: stub, percentage: 100 }] }] }], - [`${paths.prod}/deployments`, { deployments: [{ versions: [{ version_id: prod, percentage: 100 }] }] }], - [`${paths.stage}/versions/${draft}`, { id: draft, resources: { bindings: actual } }], - [`${paths.stage}/versions/${stub}`, { id: stub, resources: { bindings: [{ name: "STAGE_MODE", type: "plain_text", text: "disabled" }] } }], - [`${paths.prod}/versions/${prod}`, { id: prod, resources: { bindings: stores(oldD1, oldR2) } }], - [`d1/database/${d1}`, { uuid: d1, name: worker }], - [`r2/buckets/${r2}`, { jurisdiction: "default", name: r2, storage_class: "Standard" }], - ]); - const calls: string[] = []; - const fetcher = async (url: string, init: RequestInit) => { - const prefix = `https://api.cloudflare.com/client/v4/accounts/${account}/`; - expect(url.startsWith(prefix)).toBe(true); - expect(init.redirect).toBe("error"); - expect(init.method ?? "GET").toBe("GET"); - const path = url.slice(prefix.length); - calls.push(path); - return data.has(path) ? Response.json({ success: true, result: data.get(path) }) : new Response(null, { status: 404 }); - }; - return { data, fetcher, actual, calls }; -} - -test("admission verifies the approved intended and off-traffic effective bindings", async () => { - const f = fixture(); - expect(await admit(approved, config, draft, "fixture-read-only", f.fetcher)).toEqual({ - phase: "admitted_off_traffic", version: draft, stage_d1_id: d1, stage_r2_bucket: r2, incumbent_version: prod, - }); - expect(f.calls).toHaveLength(8); -}); - -test("unapproved or wrong intended stores are refused before querying Cloudflare", async () => { - const f = fixture(); - for (const [manifest, intended] of [ - [{ ...approved, d1_id: oldD1 }, config], [{ ...approved, r2_bucket: oldR2 }, config], - [approved, { ...config, d1_databases: [{ ...config.d1_databases[0], database_id: unknownD1 }] }], - [approved, { ...config, workers_dev: true }], [approved, { ...config, routes: [] }], - ] as const) await expect(admit(manifest, intended, draft, "fixture-read-only", f.fetcher)).rejects.toThrow(); - expect(f.calls).toHaveLength(0); -}); - -test("admission rejects wrong, missing, duplicate, live incumbent, and already-routed bindings", async () => { - for (const [db, raw] of [[unknownD1, r2], [oldD1, r2], [d1, oldR2]]) { - const f = fixture(); - f.actual.splice(0, 2, ...stores(db ?? "", raw ?? "")); - await expect(admit(approved, config, draft, "fixture-read-only", f.fetcher)).rejects.toThrow("effective"); - } - for (const [path, value] of [ - [`${paths.stage}/subdomain`, { enabled: false, previews_enabled: true }], - [`${paths.stage}/subdomain`, { enabled: true, previews_enabled: false }], - [`${paths.stage}/deployments`, { deployments: [{ versions: [{ version_id: draft, percentage: 100 }] }] }], - [`${paths.stage}/versions/${stub}`, { id: stub, resources: { bindings: stores(d1, r2) } }], - [`${paths.prod}/versions/${prod}`, { id: prod, resources: { bindings: stores(d1, r2) } }], - [`r2/buckets/${r2}`, { name: r2, jurisdiction: "eu", storage_class: "Standard" }], - [`d1/database/${d1}`, { uuid: unknownD1, name: worker }], - ] as const) { - const f = fixture(); - f.data.set(path, value); - await expect(admit(approved, config, draft, "fixture-read-only", f.fetcher)).rejects.toThrow(); - } - const duplicate = fixture(); - duplicate.actual.push(...stores(d1, r2)); - await expect(admit(approved, config, draft, "fixture-read-only", duplicate.fetcher)).rejects.toThrow(); - const absent = fixture(); - absent.data.delete(`${paths.stage}/versions/${draft}`); - await expect(admit(approved, config, draft, "fixture-read-only", absent.fetcher)).rejects.toThrow(); -}); diff --git a/services/advisory-staging/test/stage.test.ts b/services/advisory-staging/test/stage.test.ts deleted file mode 100644 index fb9682283..000000000 --- a/services/advisory-staging/test/stage.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { test, expect } from "bun:test"; -import { Database } from "bun:sqlite"; -import { readFileSync, readdirSync } from "node:fs"; -import { URL as NodeURL } from "node:url"; -import { handle } from "../../advisories/src/service"; -import { Store, type Sql, type Command } from "../../advisories/src/storage"; -import type { Fetcher } from "../../advisories/src/ingestion"; -import { object } from "../../advisories/src/domain"; -import { handleStage } from "../stage"; -import { CANONICAL_ORIGIN, STAGE_MODE, STAGE_ORIGIN } from "../stage-identity"; - -const now = "2026-11-13T02:00:00.000Z"; -const ingestToken = "controlled-ingest-token-at-least-32-characters"; -const refreshToken = "controlled-refresh-token-at-least-32-characters"; -const githubToken = `ghs_12345_fixture.header-${"A".repeat(475)}.signature_fixture`; -const archiveDigest = "a".repeat(64); -const commit = "1".repeat(40), rootTree = "2".repeat(40), cvesTree = "3".repeat(40); -const yearTree = "4".repeat(40), groupTree = "5".repeat(40); -const raw = JSON.stringify({ dataType: "CVE_RECORD", dataVersion: "5.2", cveMetadata: { - cveId: "CVE-2026-1234", state: "PUBLISHED", dateUpdated: "2026-11-12T00:00:00.000Z", - datePublished: "2026-11-11T00:00:00.000Z", -}, containers: { cna: { title: "controlled archive member" } } }); - -function setup() { - const db = new Database(":memory:"); - const migrations = new NodeURL("../../advisories/migrations/", import.meta.url); - for (const name of readdirSync(migrations).filter((name) => name.endsWith(".sql")).sort()) - db.exec(readFileSync(new NodeURL(name, migrations), "utf8")); - const sql: Sql = { - first: async (text: string, values: (string | number | null)[] = []) => db.query(text).get(...values), - all: async (text: string, values: (string | number | null)[] = []) => db.query(text).all(...values), - batch: async (commands: Command[]) => { db.transaction(() => { - for (const command of commands) db.query(command.sql).run(...command.values); - })(); }, - }; - const objects = new Map(); - const store = new Store(sql, { - put: async (key, value) => { objects.set(key, value); }, - get: async (key) => { - const value = objects.get(key); - return value === undefined ? null : { text: async () => value }; - }, - }, () => now); - return { db, store, objects }; -} - -function request(path: string, body: unknown, token: string) { - return new Request(`https://advisories.example${path}`, { - method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, - body: JSON.stringify(body), - }); -} - -async function binding(store: Store) { - const started = await handle(request("/internal/baseline/start", { - digest: archiveDigest, baseline_at: "2026-11-13T00:00:00.000Z", - }, ingestToken), store, ingestToken, now); - expect(started.status).toBe(200); - const value: unknown = await started.json(); - if (!value || typeof value !== "object" || !("session_id" in value)) throw new Error("missing test baseline session"); - return value; -} - -async function publisherFetcher() { - const bytes = new TextEncoder().encode(raw); - const header = new TextEncoder().encode(`blob ${bytes.length}\0`); - const object = new Uint8Array(header.length + bytes.length); - object.set(header); object.set(bytes, header.length); - const blob = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-1", object)), (byte) => byte.toString(16).padStart(2, "0")).join(""); - const calls: string[] = []; - const entry = (path: string, type: "tree" | "blob", sha: string) => ({ path, type, sha, mode: type === "tree" ? "040000" : "100644" }); - const payloads = new Map([ - ["/repos/CVEProject/cvelistV5/releases/tags/cve_2026-11-13_0000Z", { tag_name: "cve_2026-11-13_0000Z", assets: [{ - name: "2026-11-13_all_CVEs_at_midnight.zip.zip", digest: `sha256:${archiveDigest}`, size: 100, - }] }], - ["/repos/CVEProject/cvelistV5/git/ref/tags/cve_2026-11-13_0000Z", { object: { type: "commit", sha: commit } }], - [`/repos/CVEProject/cvelistV5/git/commits/${commit}`, { sha: commit, tree: { sha: rootTree } }], - [`/repos/CVEProject/cvelistV5/git/trees/${rootTree}`, { sha: rootTree, truncated: false, tree: [entry("cves", "tree", cvesTree)] }], - [`/repos/CVEProject/cvelistV5/git/trees/${cvesTree}`, { sha: cvesTree, truncated: false, tree: [entry("2026", "tree", yearTree)] }], - [`/repos/CVEProject/cvelistV5/git/trees/${yearTree}`, { sha: yearTree, truncated: false, tree: [entry("1xxx", "tree", groupTree)] }], - [`/repos/CVEProject/cvelistV5/git/trees/${groupTree}`, { sha: groupTree, truncated: false, tree: [entry("CVE-2026-1234.json", "blob", blob)] }], - ]); - const fetcher: Fetcher = async (input, init) => { - const url = new URL(input); - expect(url.origin).toBe("https://api.github.com"); - expect(new Headers(init?.headers).get("authorization")).toBe(`Bearer ${githubToken}`); - expect(init?.redirect).toBe("manual"); - calls.push(url.pathname); - const payload = payloads.get(url.pathname); - if (!payload) throw new Error(`unexpected publisher request: ${url.pathname}`); - return Response.json(payload); - }; - return { fetcher, calls, blob, payloads }; -} - -test("private staging proves the canonical session through promotion and reverse binding", async () => { - const incumbent = setup(), stage = setup(); - try { - const prior = await binding(incumbent.store); - const previousDatabase = incumbent.db.serialize(); - const id = stage.db.query<{id:string}, []>("SELECT id FROM database_instance").get()?.id; - if (!id) throw new Error("missing fixture stage instance"); - const aud = "a".repeat(64); - const access = { access: { aud, getIdentity: async () => undefined } }; - const policy = { STAGE_MODE, STAGE_ACCESS_AUD: aud, STAGE_DATABASE_INSTANCE_ID: id, - STAGE_INGEST_TOKEN: ingestToken, STAGE_RUNTIME_REFRESH_SECRET: refreshToken }; - const publisher = await publisherFetcher(); - const start = { digest: archiveDigest, baseline_at: "2026-11-13T00:00:00.000Z" }; - const stagePost = (path: string, payload: unknown, token = ingestToken, origin = STAGE_ORIGIN) => - new Request(origin + path, { method: "POST", body: JSON.stringify(payload), - headers: { authorization: `Bearer ${token}`, "content-type": "application/json", - "x-forwarded-host": "attacker.example", "cf-access-jwt-assertion": "fixture-untrusted-header" } }); - const route = (req: Request, store = stage.store) => - handleStage(req, access, policy, () => store, now, publisher.fetcher); - const req = () => stagePost("/internal/baseline/start", start); - const forbiddenStore = () => { throw new Error("unexpected storage access"); }; - expect((await handleStage(req(), {}, policy, forbiddenStore, now)).status).toBe(403); - expect((await handleStage(req(), access, { ...policy, STAGE_ACCESS_AUD: "b".repeat(64) }, forbiddenStore, now)).status).toBe(403); - expect((await handleStage(req(), access, { ...policy, STAGE_MODE: "disabled" }, forbiddenStore, now)).status).toBe(503); - expect((await route(stagePost("/internal/baseline/start", start, ingestToken, CANONICAL_ORIGIN))).status).toBe(403); - expect((await route(req(), incumbent.store)).status).toBe(503); - expect((await route(req())).status).toBe(503); - expect(stage.db.query("SELECT COUNT(*) AS count FROM baseline_receipt").get()).toEqual({count:0}); - expect(stage.objects.size).toBe(0); - stage.objects.set(`stage-isolation/${id}`, ""); - expect((await route(stagePost("/internal/baseline/start", start, "wrong-token"))).status).toBe(401); - expect(stage.db.query("SELECT COUNT(*) AS count FROM baseline_receipt").get()).toEqual({count:0}); - - const started = await route(req()); - expect(started.status).toBe(200); - expect(started.headers.get("cache-control")).toBe("no-store"); - const canonical = object(await started.json()); - expect(canonical).toMatchObject({ endpoint: CANONICAL_ORIGIN, instance_id: id }); - const payload = { source: "cve", records: [raw], baseline: canonical }; - expect((await route(stagePost("/internal/ingest", { ...payload, baseline: prior }))).status).toBe(400); - expect(stage.objects.size).toBe(1); - expect((await route(stagePost("/internal/ingest", payload))).status).toBe(200); - const originalObjects = stage.objects.size; - expect(await (await route(stagePost("/internal/baseline/start", { ...start, ...canonical }))).json()).toMatchObject(canonical); - expect((await route(stagePost("/internal/ingest", payload))).status).toBe(200); - expect(stage.objects.size).toBe(originalObjects); - expect(stage.db.query("SELECT accepted FROM baseline_receipt").get()).toEqual({accepted:1}); - - const proof = { ...canonical, release_tag: "cve_2026-11-13_0000Z", - asset: "2026-11-13_all_CVEs_at_midnight.zip.zip", github_token: githubToken }; - expect((await route(stagePost("/internal/baseline/verify", proof))).status).toBe(401); - expect(await (await route(stagePost("/internal/baseline/verify", proof, refreshToken))).json()).toMatchObject({ - phase: "awaiting_import", expected_count: 1, pending_trees: 0, - }); - stage.db.query("UPDATE source_checkpoint SET complete=1,checked_at=?,cursor=? WHERE source='cve'").run(now, JSON.stringify({event:now,offset:0})); - expect((await route(stagePost("/internal/baseline", { ...canonical, ...start, finished_at: now, accepted: 1, exhausted: true }))).status).toBe(200); - expect(await (await route(stagePost("/internal/baseline/verify", proof, refreshToken))).json()).toMatchObject({ - phase: "verified", verified_count: 1, pending_trees: 0, - }); - - const status = (store: Store) => handle(new Request(CANONICAL_ORIGIN + "/v1/status"), store, undefined, now); - const verifyAtCanonical = (store: Store) => handle(stagePost("/internal/baseline/verify", proof, refreshToken, CANONICAL_ORIGIN), - store, ingestToken, now, publisher.fetcher, refreshToken); - const upstreamCalls = publisher.calls.length; - expect(await (await verifyAtCanonical(stage.store)).json()).toMatchObject({ phase: "verified", verified_count: 1 }); - expect(await (await status(stage.store)).json()).toMatchObject({ bootstrap_complete: true }); - expect((await verifyAtCanonical(incumbent.store)).status).toBe(400); - expect(await (await status(incumbent.store)).json()).toMatchObject({ baseline: { imported: 0, archive_verified: false }, bootstrap_complete: false }); - expect(incumbent.db.serialize()).toEqual(previousDatabase); - expect(incumbent.objects.size).toBe(0); - expect(publisher.calls.length).toBe(upstreamCalls); - } finally { - incumbent.db.close(); - stage.db.close(); - } -}); diff --git a/services/advisory-staging/test/transport.test.ts b/services/advisory-staging/test/transport.test.ts deleted file mode 100644 index 8cb4618dd..000000000 --- a/services/advisory-staging/test/transport.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { expect, test } from "bun:test"; -import { readCheckpoint, recoverCheckpoint } from "../../advisories/scripts/operator"; -import { stageCheckpoint, stageOperatorFetcher } from "../transport"; -import { CANONICAL_ORIGIN, STAGE_ORIGIN } from "../stage-identity"; - -const binding = { digest:"a".repeat(64), endpoint:"https://advisories.example", instance_id:"1".repeat(32), session_id:"afb732ac-68e4-4549-98ec-e89224449b75" }; - -test("stage credentials cannot leave the fixed protected origin or follow a redirect", async () => { - let calls = 0; - const init = { method: "POST", redirect: "error" } satisfies RequestInit; - const fetcher = stageOperatorFetcher("fixture-id", "fixture-secret", async (input, options) => { - calls++; - expect(String(input)).toBe(STAGE_ORIGIN + "/internal/ingest"); - expect(options?.redirect).toBe("error"); - expect(new Headers(options?.headers).get("cf-access-client-secret")).toBe("fixture-secret"); - return Response.redirect(CANONICAL_ORIGIN + "/internal/ingest"); - }); - for (const url of [ - CANONICAL_ORIGIN + "/internal/ingest", "https://other.example/internal/ingest", - STAGE_ORIGIN + "/internal/ingest?target=other", STAGE_ORIGIN + "/v1/status", - ]) await expect(fetcher(new URL(url), init)).rejects.toThrow("destination refused"); - await expect(fetcher(new URL(STAGE_ORIGIN + "/internal/ingest"), { ...init, redirect: "follow" })).rejects.toThrow("destination refused"); - expect(calls).toBe(0); - await expect(fetcher(new URL(STAGE_ORIGIN + "/internal/ingest"), init)).rejects.toThrow("redirect refused"); - expect(calls).toBe(1); - const canonical = { ...binding, endpoint: CANONICAL_ORIGIN }; - const checkpoint = recoverCheckpoint(canonical); - const envelope = { transport_endpoint: STAGE_ORIGIN, checkpoint }; - expect(() => stageCheckpoint(checkpoint)).toThrow("transport"); - expect(() => readCheckpoint(envelope, canonical)).toThrow(); - expect(readCheckpoint(stageCheckpoint(envelope), canonical)).toEqual(checkpoint); -}); diff --git a/services/advisory-staging/transport.ts b/services/advisory-staging/transport.ts deleted file mode 100644 index 7c4fc937a..000000000 --- a/services/advisory-staging/transport.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type { OperatorFetcher } from "../advisories/scripts/operator"; -import { object } from "../advisories/src/domain"; -import { STAGE_ORIGIN, STAGE_POST_PATHS } from "./stage-identity"; - -export function stageOperatorFetcher(clientId: string | undefined, clientSecret: string | undefined, fetcher: OperatorFetcher = fetch): OperatorFetcher { - if (!clientId || !clientSecret) throw new Error("stage Access credentials required"); - return async (input, init) => { - if (!(input instanceof URL) || input.origin !== STAGE_ORIGIN || input.username || input.password || - input.search || input.hash || !STAGE_POST_PATHS.has(input.pathname) || - init?.method !== "POST" || init.redirect !== "error") throw new Error("stage credential destination refused"); - const headers = new Headers(init.headers); - headers.set("CF-Access-Client-Id", clientId); - headers.set("CF-Access-Client-Secret", clientSecret); - const reply = await fetcher(input, { ...init, headers }); - if (reply.redirected || (reply.status >= 300 && reply.status < 400) || (reply.url && reply.url !== input.href)) { - await reply.body?.cancel(); - throw new Error("stage redirect refused"); - } - return reply; - }; -} - -export function stageCheckpoint(value: unknown) { - const saved = object(value); - if (saved.transport_endpoint !== STAGE_ORIGIN) { - throw new Error("checkpoint transport does not match operator mode"); - } - return object(saved.checkpoint); -} diff --git a/services/advisory-staging/tsconfig.json b/services/advisory-staging/tsconfig.json deleted file mode 100644 index 7c600dd2b..000000000 --- a/services/advisory-staging/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../advisories/tsconfig.json", - "compilerOptions": { - "types": ["bun"], - "typeRoots": ["../advisories/node_modules/@types"] - }, - "include": [ - "*.ts", - "test/**/*.ts", - "../advisories/node_modules/@cloudflare/workers-types/index.d.ts", - "../advisories/worker-configuration.d.ts" - ] -} diff --git a/services/advisory-staging/wrangler.example.json b/services/advisory-staging/wrangler.example.json deleted file mode 100644 index adfa4cca4..000000000 --- a/services/advisory-staging/wrangler.example.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "$schema": "../advisories/node_modules/wrangler/config-schema.json", - "account_id": "f1e95b3e1b502cf366dfc81a863695fa", - "name": "omg-advisories-stage-20261121-1d6c61c4", - "main": "stage.ts", - "compatibility_date": "2026-11-13", - "workers_dev": false, - "preview_urls": false, - "d1_databases": [{ - "binding": "DB", - "database_name": "omg-advisories-stage-20261121-1d6c61c4", - "database_id": "00000000-0000-0000-0000-000000000000", - "migrations_dir": "../advisories/migrations" - }], - "r2_buckets": [{ "binding": "RAW", "bucket_name": "omg-advisories-stage-20261121-1d6c61c4-raw" }], - "vars": { "STAGE_MODE": "disabled", "STAGE_ENABLE_CRON": "false" }, - "limits": { "cpu_ms": 30000 } -}