From 8b883fb59fb34a28b20b68be1db4488946fbf354 Mon Sep 17 00:00:00 2001 From: notplants <@notplants> Date: Mon, 23 Nov 2026 20:09:45 +0000 Subject: [PATCH 1/2] Move active CI tooling into scripts and archive plans --- README.md | 16 +- archive/README.md | 2 + .../plan-ccci-compose-overlay-policy.md | 80 + ...plan-domain-migration-ci-autonomic-zone.md | 172 ++ .../cc-ci-plan/plan-ghostpr-debug-fix.md | 54 + .../plan-lasuite-drive-oidc-robustness.md | 97 ++ .../plan-lasuite-drive-recipe-pr.md | 77 + .../plans/cc-ci-plan/plan-sso-dep-testing.md | 210 +++ .../cc-ci-plan/task-consolidate-recipe-prs.md | 43 + cc-ci-plan/advisory-scan.SPEC.md | 392 +---- cc-ci-plan/advisory-scan.py | 1438 +---------------- cc-ci-plan/agent-log.py | 200 +-- cc-ci-plan/agents.py | 851 +--------- cc-ci-plan/agents.toml | 106 +- cc-ci-plan/ai-progress-monitor-prompt.txt | 6 +- cc-ci-plan/audit-advisory-scan.py | 152 +- cc-ci-plan/audit-sources.py | 312 +--- cc-ci-plan/launch-assistant.py | 160 +- cc-ci-plan/launch-report.py | 175 +- cc-ci-plan/launch-supervisor.py | 199 +-- cc-ci-plan/launch-upgrader.py | 668 +------- cc-ci-plan/load-env.sh | 18 +- .../plan-ccci-compose-overlay-policy.md | 81 +- ...plan-domain-migration-ci-autonomic-zone.md | 173 +- cc-ci-plan/plan-ghostpr-debug-fix.md | 55 +- .../plan-lasuite-drive-oidc-robustness.md | 98 +- cc-ci-plan/plan-lasuite-drive-recipe-pr.md | 78 +- cc-ci-plan/plan-sso-dep-testing.md | 211 +-- cc-ci-plan/pr-survey.py | 235 +-- cc-ci-plan/reboot-log.sh | 23 +- cc-ci-plan/recipe-report.py | 378 +---- cc-ci-plan/reconcile-upstream.sh | 64 +- cc-ci-plan/resolve-images.py | 520 +----- cc-ci-plan/task-consolidate-recipe-prs.md | 44 +- cc-ci-plan/test-advisory-scan.py | 956 +---------- cc-ci-plan/test-resolve-images.py | 56 +- scripts/cc-ci/advisory-scan.SPEC.md | 391 +++++ scripts/cc-ci/advisory-scan.py | 1437 ++++++++++++++++ scripts/cc-ci/agent-log.py | 199 +++ scripts/cc-ci/agents.py | 850 ++++++++++ scripts/cc-ci/agents.toml | 105 ++ scripts/cc-ci/ai-progress-monitor-prompt.txt | 5 + scripts/cc-ci/audit-advisory-scan.py | 151 ++ scripts/cc-ci/audit-sources.py | 311 ++++ scripts/cc-ci/launch-assistant.py | 159 ++ scripts/cc-ci/launch-report.py | 174 ++ scripts/cc-ci/launch-supervisor.py | 198 +++ scripts/cc-ci/launch-upgrader.py | 667 ++++++++ scripts/cc-ci/load-env.sh | 17 + scripts/cc-ci/pr-survey.py | 234 +++ scripts/cc-ci/reboot-log.sh | 22 + scripts/cc-ci/recipe-report.py | 377 +++++ scripts/cc-ci/reconcile-upstream.sh | 63 + scripts/cc-ci/resolve-images.py | 519 ++++++ scripts/cc-ci/test-advisory-scan.py | 955 +++++++++++ scripts/cc-ci/test-resolve-images.py | 55 + scripts/cc-ci/upstream | 1 + scripts/cc-ci/used-recipes.md | 1 + 58 files changed, 7662 insertions(+), 7629 deletions(-) create mode 100644 archive/plans/cc-ci-plan/plan-ccci-compose-overlay-policy.md create mode 100644 archive/plans/cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md create mode 100644 archive/plans/cc-ci-plan/plan-ghostpr-debug-fix.md create mode 100644 archive/plans/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md create mode 100644 archive/plans/cc-ci-plan/plan-lasuite-drive-recipe-pr.md create mode 100644 archive/plans/cc-ci-plan/plan-sso-dep-testing.md create mode 100644 archive/plans/cc-ci-plan/task-consolidate-recipe-prs.md mode change 100644 => 120000 cc-ci-plan/advisory-scan.SPEC.md mode change 100755 => 120000 cc-ci-plan/advisory-scan.py mode change 100755 => 120000 cc-ci-plan/agent-log.py mode change 100644 => 120000 cc-ci-plan/agents.py mode change 100644 => 120000 cc-ci-plan/agents.toml mode change 100644 => 120000 cc-ci-plan/ai-progress-monitor-prompt.txt mode change 100755 => 120000 cc-ci-plan/audit-advisory-scan.py mode change 100755 => 120000 cc-ci-plan/audit-sources.py mode change 100644 => 120000 cc-ci-plan/launch-assistant.py mode change 100755 => 120000 cc-ci-plan/launch-report.py mode change 100644 => 120000 cc-ci-plan/launch-supervisor.py mode change 100644 => 120000 cc-ci-plan/launch-upgrader.py mode change 100755 => 120000 cc-ci-plan/load-env.sh mode change 100644 => 120000 cc-ci-plan/plan-ccci-compose-overlay-policy.md mode change 100644 => 120000 cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md mode change 100644 => 120000 cc-ci-plan/plan-ghostpr-debug-fix.md mode change 100644 => 120000 cc-ci-plan/plan-lasuite-drive-oidc-robustness.md mode change 100644 => 120000 cc-ci-plan/plan-lasuite-drive-recipe-pr.md mode change 100644 => 120000 cc-ci-plan/plan-sso-dep-testing.md mode change 100755 => 120000 cc-ci-plan/pr-survey.py mode change 100755 => 120000 cc-ci-plan/reboot-log.sh mode change 100755 => 120000 cc-ci-plan/recipe-report.py mode change 100755 => 120000 cc-ci-plan/reconcile-upstream.sh mode change 100644 => 120000 cc-ci-plan/resolve-images.py mode change 100644 => 120000 cc-ci-plan/task-consolidate-recipe-prs.md mode change 100755 => 120000 cc-ci-plan/test-advisory-scan.py mode change 100644 => 120000 cc-ci-plan/test-resolve-images.py create mode 100644 scripts/cc-ci/advisory-scan.SPEC.md create mode 100755 scripts/cc-ci/advisory-scan.py create mode 100755 scripts/cc-ci/agent-log.py create mode 100644 scripts/cc-ci/agents.py create mode 100644 scripts/cc-ci/agents.toml create mode 100644 scripts/cc-ci/ai-progress-monitor-prompt.txt create mode 100755 scripts/cc-ci/audit-advisory-scan.py create mode 100755 scripts/cc-ci/audit-sources.py create mode 100644 scripts/cc-ci/launch-assistant.py create mode 100755 scripts/cc-ci/launch-report.py create mode 100644 scripts/cc-ci/launch-supervisor.py create mode 100644 scripts/cc-ci/launch-upgrader.py create mode 100755 scripts/cc-ci/load-env.sh create mode 100755 scripts/cc-ci/pr-survey.py create mode 100755 scripts/cc-ci/reboot-log.sh create mode 100755 scripts/cc-ci/recipe-report.py create mode 100755 scripts/cc-ci/reconcile-upstream.sh create mode 100644 scripts/cc-ci/resolve-images.py create mode 100755 scripts/cc-ci/test-advisory-scan.py create mode 100644 scripts/cc-ci/test-resolve-images.py create mode 120000 scripts/cc-ci/upstream create mode 120000 scripts/cc-ci/used-recipes.md diff --git a/README.md b/README.md index e355683..54fbb3f 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,15 @@ the [cc-ci repository](https://git.autonomic.zone/recipe-maintainers/cc-ci). | Current component | Location | |---|---| | Combined host and timers | `flake.nix`, `nix/hosts/cc-ci/`, `nix/modules/` | -| Operator session, weekly upgrade and report launchers | `cc-ci-plan/agents.py`, `cc-ci-plan/launch-{upgrader,report,supervisor}.py` | -| Recipe inventory, upstream notes, reporting tools | `cc-ci-plan/used-recipes.md`, `cc-ci-plan/upstream/`, `cc-ci-plan/recipe-report.py` | +| Operator session, weekly upgrade and report launchers | `scripts/cc-ci/agents.py`, `scripts/cc-ci/launch-{upgrader,report,supervisor}.py` | +| Recipe inventory, upstream notes, reporting tools | `cc-ci-plan/used-recipes.md`, `cc-ci-plan/upstream/`, `scripts/cc-ci/recipe-report.py` | | Host provisioning and migration | [`docs/host-provisioning-and-migration.md`](docs/host-provisioning-and-migration.md) | | Original Builder/Adversary build | [`archive/original-build/`](archive/original-build/README.md) | -Secrets and runtime state are gitignored. The completed two-loop build is -archived; no Builder or Adversary session should be running. The Nix +Secrets and runtime state are gitignored. The completed two-loop build and remaining historical plans are +archived. Active executables live under `scripts/cc-ci/`; the old +`cc-ci-plan/` paths remain as compatibility links for unchanged Nix units. +No Builder or Adversary session should be running. The Nix `cc-ci-loops` unit still invokes a compatibility launcher on boot and exits when it sees the completed phase state. Its Nix behavior is unchanged. @@ -44,9 +46,9 @@ when it sees the completed phase state. Its Nix behavior is unchanged. # Operating the orchestrator -The cc-ci orchestrator on this host is an **opencode agent** (`cc-ci-plan/agents.toml`: -backend `opencode`, model configured in `cc-ci-plan/agents.toml`), launched on boot by `cc-ci-orchestrator.service` -via `cc-ci-plan/agents.py up orchestrator` into tmux session `cc-ci-orchestrator`, attached to +The cc-ci orchestrator on this host is an **opencode agent** (`scripts/cc-ci/agents.toml`: +backend `opencode`, model configured in `scripts/cc-ci/agents.toml`), launched on boot by `cc-ci-orchestrator.service` +via the compatibility path `cc-ci-plan/agents.py up orchestrator` into tmux session `cc-ci-orchestrator`, attached to the shared opencode web server. Steer it from the web UI, **https://oc.ci.commoninternet.net** (basic auth, user `oc`), where the weekly upgrader's and report's sessions show up too. There is no Claude Code on this host: Claude sessions run on the notplants-orchestrator box and diff --git a/archive/README.md b/archive/README.md index 8f9f549..64064fb 100644 --- a/archive/README.md +++ b/archive/README.md @@ -21,3 +21,5 @@ that did it is `../cc-ci-plan/plan-cc-ci-combined-host.md`). The cc-ci server's own history (machine-docs, decisions, the clean-room rebuild that proved "two repos + one age key + one `nixos-rebuild switch`") is in the cc-ci repo under `machine-docs/` and `docs/`. + +Current CI plans formerly under `cc-ci-plan/` are in `plans/cc-ci-plan/`. diff --git a/archive/plans/cc-ci-plan/plan-ccci-compose-overlay-policy.md b/archive/plans/cc-ci-plan/plan-ccci-compose-overlay-policy.md new file mode 100644 index 0000000..430dd87 --- /dev/null +++ b/archive/plans/cc-ci-plan/plan-ccci-compose-overlay-policy.md @@ -0,0 +1,80 @@ +# Policy + cleanup — cc-ci compose overlays (when they're justified) & upgrade-tier from-version + +**Status:** POLICY (codifies `plan.md §9`) + a small set of follow-ups. **Owner:** Builder + Adversary. +**This file:** `/srv/cc-ci/cc-ci-plan/plan-ccci-compose-overlay-policy.md` +**Supersedes** the earlier `plan-prefer-env-over-compose-overlay.md` (its premise — parameterize +`start_period` via an env var — is **wrong: abra does not support an env value for `start_period`**). + +--- + +## 0. Policy (operator, 2026-05-30) + +A cc-ci-authored compose overlay (the single `compose.ccci.yml`, layered via `COMPOSE_FILE`) risks +**drift** from the recipe users run — so **avoid where possible and justify each use**. But it is a +**legitimate, uniform fallback pattern**, not forbidden: + +- **Prefer an upstream recipe PR** in most cases — a real robustness fix, or exposing a knob the recipe + should expose. That's where a fix usually belongs. +- **A ccci overlay is the right tool when the value can't be supplied any other way** — notably a + healthcheck **`start_period`**, which **abra cannot take from an env var**. The ghost/discourse + `start_period` bumps therefore **stay as overlays** (an env PR is impossible for that field). +- **Uniform pattern (acceptable fallback):** a single, fixed-name **`compose.ccci.yml`** per recipe + (NOT per-purpose suffixes — one file holds all cc-ci-side deploy tweaks for that recipe), provided + into the checkout by `install_steps.sh`, wired by `recipe_meta` `COMPOSE_FILE` + (`compose.yml:compose.ccci.yml`), kept as an untracked file so it survives the upgrade + `git checkout -f` (`CHAOS_BASE_DEPLOY=True`; `assert_upgraded` strips the `+U` marker — see + DECISIONS 2026-05-30). +- **Each overlay must:** be **minimal + single-purpose**, **document WHY** in its header (the exact + abra/upstream limitation that forces it), and be **Adversary-confirmed** to not weaken a test or mask + a recipe defect. Where the fix also belongs upstream (e.g. a `start_period` too tight for any slow + host), **file the upstream PR too** — the overlay is the cc-ci-side fallback, not a reason to skip it. + +## 1. Upgrade tier: always test the upgrade to LATEST + +Don't drop the upgrade test because the *from* (older) version is awkward. +- **Always perform the upgrade to the latest version and run the full assertions on the latest.** +- If the older from-version can't be fully deployed/tested (image tag removed from the registry, or it + predates an overlay/feature), you do **NOT** need that older version's **custom tests** to run. + Deploy it minimally (a justified overlay is fine) or upgrade from the nearest deployable prior; skip + only the from-version's custom assertions, and **record** that. +- Skipping a from-version's custom tests = honest, recorded. Skipping upgrade-to-latest = not OK. + +## 2. Disposition of the current overlays + +- [ ] **RENAME the overlay files to the uniform `compose.ccci.yml`.** `tests/ghost/compose.ccci-health.yml` + and `tests/discourse/compose.ccci-health.yml` → `compose.ccci.yml`; update each recipe's + `install_steps.sh` (the `cp` target) and `recipe_meta` `COMPOSE_FILE` + (`compose.yml:compose.ccci-health.yml` → `compose.yml:compose.ccci.yml`). One fixed filename per + recipe going forward. +- [ ] **ghost `compose.ccci.yml` (start_period 900s) — KEEP, justified.** abra can't env-param + `start_period`; the fresh-DB migration needs the larger grace or swarm kills it → deadlock. + Confirm the header documents this; consider an upstream PR raising ghost's `start_period` (it's a + real slow-host fragility) — but the overlay stays regardless. +- [ ] **discourse `compose.ccci.yml` — KEEP, justified (both parts).** (a) `start_period 1200s` + (same reason as ghost). (b) The `bitnami/discourse:3.3.1 → bitnamilegacy/discourse:3.3.1` re-pin + makes the from-version (0.7.0, whose `bitnami/discourse` tag Docker Hub now 404s) **deployable so + the upgrade-to-latest test can run** — namespace-only, identical discourse version, applied to + base+head. This is the §1 case: keep the upgrade-to-latest test; the 0.7.0 custom tests need not + run. Document it; if a deployable prior without the re-pin exists, prefer upgrading from that. +- [ ] **mumble `compose.host-ports.yml` (cc-ci copy for the old base) — DROP it.** Deploying mumble + 0.2.0 does NOT need host-ports (that overlay only *publishes* 64738 for on-host tests). Per §1: + deploy 0.2.0 without it, **skip 0.2.0's voice/on-host custom tests**, then upgrade to the latest + version (which ships `compose.host-ports.yml` natively) and run the voice tests on the latest. + Remove the cc-ci copy + its `install_steps`/`COMPOSE_FILE` wiring for the old base; the current + version's native overlay is untouched. + +## 3. Definition of Done (Adversary cold-verifies) +- [ ] Every surviving cc-ci overlay is minimal, header-documents its justification (the abra/upstream + limitation), and is Adversary-confirmed to not weaken a test or mask a defect. +- [ ] The mumble old-base cc-ci host-ports copy is removed; mumble still **upgrades to latest** and runs + its voice tests **on the latest** (0.2.0's voice tests skipped + recorded). +- [ ] ghost + discourse still pass full suites; discourse still tests the upgrade to latest. +- [ ] Any upstream PR opened (e.g. ghost/discourse `start_period`) follows the recipe-PR rule + (cc-ci-green via `!testme` before operator merge); the overlay remains as the cc-ci fallback. +- [ ] No upgrade-to-latest test was dropped to avoid an awkward from-version. + +## 4. Guardrails +- **Correctness first** — never weaken/skip/soften a check to make a deploy or upgrade pass; an + overlay tunes deploy/infra only (its header must say how), the real assertions stand. +- **Justify + document every overlay**; prefer the upstream PR where the fix belongs. +- **Real abra path** throughout. diff --git a/archive/plans/cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md b/archive/plans/cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md new file mode 100644 index 0000000..86e63bd --- /dev/null +++ b/archive/plans/cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md @@ -0,0 +1,172 @@ +# Plan: migrate cc-ci domains from `*.commoninternet.net` to `ci.autonomic.zone` + +**Date:** 2026-09-21 · **Status:** DRAFT — blocked only on operator DNS access (Gandi zone `autonomic.zone`) +**Principle:** same host, same IP (195.201.88.249), same services — only names change. Dual-run new +alongside old; old names retire last; rollback at any point is "change nothing further" because the +old DNS zone keeps answering until Phase 4. + +--- + +## 1. Inventory — what answers on what today + +| Name | Served by | Router/config source | +|---|---|---| +| `ci.commoninternet.net` | results dashboard + bridge `/hook` | `cc-ci/nix/modules/dashboard.nix`, `bridge.nix` (traefik Host rules) | +| `report.ci.commoninternet.net` | weekly report static site | `cc-ci/nix/modules/reports.nix` | +| `drone.ci.commoninternet.net` | Drone server | `cc-ci/nix/modules/drone.nix` (abra app; env `DOMAIN`, `DRONE_SERVER_HOST`); runner RPC: `drone-runner.nix` | +| `oc.ci.commoninternet.net` | opencode UI (traefik → host nginx basic auth) | `cc-ci-orch/nix/modules/orchestrator-host.nix` (`opencodeUiHost`), set in `nix/hosts/cc-ci/configuration.nix` | +| `traefik.ci.commoninternet.net` | traefik stack identity + deploy-proxy health gate | `cc-ci/nix/modules/proxy.nix` | +| `warm-*.ci.commoninternet.net` | warm canonical recipe stacks | `warm-keycloak.nix`, warm-bluesky-pds (caddy labels) | +| `-<6hex>.ci.commoninternet.net` | per-run recipe test deploys | `cc-ci/runner/harness/naming.py` `app_domain()` — **resolves via public DNS** (containers use 1.1.1.1/8.8.8.8) | +| `backups.ci.commoninternet.net` | backup-bot-two — stack name only, no web route | `backupbot.nix` | +| `acme.commoninternet.net` (NS `ns-acme`) | local acme-dns (systemd, port 53) | `cc-ci/nix/modules/acme-dns.nix` | + +**Cert chain today:** nixos `security.acme` (lego) issues `ci.commoninternet.net` + `*.ci.commoninternet.net` +via DNS-01 through the local acme-dns; Gandi delegates `_acme-challenge.ci.commoninternet.net` CNAME → +`9d3f0428-eb97-4b14-bb07-da2f0f6c2073.acme.commoninternet.net`. `postRun` fires +`cc-ci-acme-traefik-handoff.service` → installs cert into `/var/lib/ci-certs/live` → restarts +`deploy-proxy.service`, whose reconciler re-derives the `traefik_ci_commoninternet_net_ssl_{cert,key}_v` +swarm secrets (traefik runs co-op-cloud wildcard/no-ACME mode off those secrets). +**DNS:** both zones on Gandi. IPv4-only (no AAAA records anywhere; none needed). + +**External references:** Gitea OAuth app for Drone (redirect URI → drone.ci…); per-repo webhooks → +`/hook` — **only `recipe-maintainers/ghost` and `recipe-maintainers/discourse` have any** (everything +else is bridge-driven via the Drone API); ~60 doc references across cc-ci-orch (AGENTS.md, README, +plan.md, skills). + +## 2. Target naming + +| Old | New | +|---|---| +| ci.commoninternet.net | ci.autonomic.zone | +| report.ci.commoninternet.net | report.ci.autonomic.zone | +| drone.ci.commoninternet.net | drone.ci.autonomic.zone | +| oc.ci.commoninternet.net | oc.ci.autonomic.zone | +| traefik.ci.commoninternet.net | traefik.ci.autonomic.zone | +| *.ci.commoninternet.net (warm-\*, per-run apps, backups identity) | *.ci.autonomic.zone | +| acme.commoninternet.net | **stays** through Phases 1–2 (infra, not a front door); optional Phase 3 | + +Swarm **stack names** (`traefik_ci_commoninternet_net`, `ccci-*`, warm stacks) are identifiers, not +domains — keep them where possible to avoid churn in keep-lists/prune filters, EXCEPT abra-managed +apps whose name **is** the domain (drone, backup-bot, per-run apps). + +## 3. DNS records to set (zone `autonomic.zone`, Gandi — operator) + +| # | Name | Type | Value | TTL | Purpose | +|---|---|---|---|---|---| +| 1 | `ci.autonomic.zone` | A | `195.201.88.249` | 300 | apex front door (wildcard does NOT cover the apex) | +| 2 | `*.ci.autonomic.zone` | A | `195.201.88.249` | 300 | report/drone/oc/traefik/warm-\*/`-<6hex>` run apps | +| 3 | `_acme-challenge.ci.autonomic.zone` | CNAME | `9d3f0428-eb97-4b14-bb07-da2f0f6c2073.acme.commoninternet.net.` | 300 | DNS-01 for the new wildcard — **reuses the existing restricted acme-dns account** (`disable_registration=true`; the lego *account* authenticates, not the FQDN, so one acme-dns subdomain serves both zones) | + +Also: lower TTL to 300 on the old `ci`/`*.ci` records a few days ahead (fast rollback later). +Phase 3 (optional) adds: `acme.ci.autonomic.zone` + `ns-acme.ci.autonomic.zone` A records. + +**DNS verification (before touching the host):** +```bash +dig +short ci.autonomic.zone A @ns-187-a.gandi.net # 195.201.88.249 +dig +short report.ci.autonomic.zone @1.1.1.1 # 195.201.88.249 (via wildcard) +dig +short drone.ci.autonomic.zone @8.8.8.8 # 195.201.88.249 +dig +short _acme-challenge.ci.autonomic.zone CNAME # 9d3f0428-….acme.commoninternet.net. +``` + +## 4. Phase 1a — certificate (issue BEFORE any routing change) + +1. `cc-ci/nix/modules/acme-dns.nix`: add a second `security.acme.certs."ci.autonomic.zone"` entry + (domain + `*.ci.autonomic.zone` SAN, `dnsProvider = "acmedns"`, `dnsResolver = "1.1.1.1:53"`). + Split the lego env per cert — today `ACME_DNS_STORAGE_PATH` is baked to + `/var/lib/acme/ci.commoninternet.net/…`; generate one env file per cert so each keeps its own + acme-dns account file. +2. Extend `cc-ci-acme-traefik-handoff` to stage the new cert alongside the old + (`/var/lib/ci-certs/live` holds both, e.g. `fullchain.pem` = new + `fullchain-old.pem`). +3. Extend the **deploy-proxy reconciler** (`proxy.nix`) for **dual-cert SNI**: new wildcard pair as + `ssl_cert/ssl_key` (default store) + old pair as a second secret pair wired through a small + file-provider `[[tls.certificates]]` so `*.ci.commoninternet.net` keeps serving during the bake + window. This is the one fiddly bit — validate against the **Let's Encrypt staging** endpoint + first (the module already has the staging-marker pattern). +4. `nixos-rebuild test` → confirm both certs issued and served (`openssl s_client -servername` for a + name in each zone, check SANs) → `switch`. + +## 5. Phase 1b — routing + service config (one stack at a time, health-gated) + +During the bake window every router rule carries **both** hostnames +(`Host(`ci.autonomic.zone`) || Host(`ci.commoninternet.net`)`); old names drop out only in Phase 4. + +- `dashboard.nix` + `bridge.nix` (share the `ci` host: dashboard `/` + bridge `/hook`), `reports.nix`, + and the traefik health-gate name in `proxy.nix`. +- `bridge.py` / `dashboard.py` code defaults for `DRONE_URL` / `DASH_URL`. +- `recipe-report.py` — footer, publish URL text and its verification curl → `report.ci.autonomic.zone` + (regenerate the index after, so the home page stops linking the old name). +- Drone **abra app rename** (name = domain, so this is a new stack): + 1. Export enabled-repo list from the old Drone API. + 2. Deploy new abra app `drone.ci.autonomic.zone` (same module; secrets `rpc_secret`, + `client_secret` re-insert from `/run/secrets` as today). **Fresh DB** — Drone data volume is + stack-name-prefixed; repos re-sync on Gitea login, build history is lost (accepted; export the + old repo list and re-enable via API). + 3. Point `drone-runner.nix` `DRONE_RPC_HOST` at the new name; restart runner. + 4. Re-run `scripts/bootstrap-drone-oauth.sh` with `DRONE=https://drone.ci.autonomic.zone` + (updates the Gitea OAuth redirect URI; script already uses `--resolve` to hit loopback). + 5. Update the two webhooks (ghost, discourse) to `https://drone.ci.autonomic.zone/hook?secret=` + — read the secret off the existing hook config before deleting it. + 6. `abra app undeploy` + remove the old drone app once green. +- `configuration.nix`: `opencodeUiHost = "oc.ci.autonomic.zone"`; extend the `networking.hosts` + self-pin list with the new names (keep old pins during bake). +- Gitea `GITEA_SERVER` stays `git.autonomic.zone` — unchanged. + +## 6. Phase 2 — harness / warm / per-run naming (the `_ci_commoninternet_net` blast radius) + +- `cc-ci/runner/harness/naming.py` `app_domain()` → `.ci.autonomic.zone` (single source of truth). +- Regexes/patterns that match the derived names: `docker-prune.nix` run-app filter, + `tests/concurrency/concutil.py` (`DOMAIN` const + `RUN_APP_RE`), any separate `RUN_APP_RE` in + `lifecycle.py` / `warm.py` / `warm_reconcile.py` / `canonical.py` / `generic.py` / `http.py`, + `nightly-sweep` keep-list patterns, `tests/gitea/recipe_meta.py` comment. +- Redeploy warm stacks under new names (abra `warm-.ci.autonomic.zone`), reconcile, drain old. +- `backupbot.nix` `DOMAIN` (stack-name-only change). +- Verify: full deterministic test suite + one live `!testme` run end-to-end. + +## 7. Phase 3 (optional) — move acme-dns off commoninternet.net + +Only if `commoninternet.net` is being dropped entirely: new `domain`/`nsname` in acme-dns config +(`acme.ci.autonomic.zone` / `ns-acme.ci.autonomic.zone` + Gandi records), briefly re-enable +registration or hand-migrate the account DB, re-point `_acme-challenge` CNAMEs, re-issue both certs. + +## 8. Phase 4 — retirement (after ≥7 clean days) + +Remove old names from the dual router rules → remove `security.acme.certs."ci.commoninternet.net"` ++ its env file + old cert secret pair → drop old `networking.hosts` pins → delete old Gandi records +(`ci`, `*.ci`, `_acme-challenge.ci`) → restore TTLs to 3600. Keep `acme.commoninternet.net` unless +Phase 3 was done. + +## 9. Verification checklist + +- **DNS:** the dig table in §3 against a Gandi NS and a public resolver. +- **Cert:** `openssl s_client -connect 195.201.88.249:443 -servername ` for one name per zone — + SANs correct for both, `ssl_verify_result=0`. +- **Front doors:** `ci` → 200 · `report.ci` → 200 · `drone.ci` → 200/303 · `oc.ci` → **401** + (basic auth intact) · `traefik.ci/api/version` → 200. +- **SSO:** Drone login through Gitea on the new redirect URI. +- **Webhook:** empty commit to `recipe-maintainers/ghost` main → build fires on the new host. +- **Bridge/!testme:** `!testme` on a scratch PR → build runs, `results.json` written, PR comment + contains **new** domain links. +- **Report:** publish one report page and verify it at `https://report.ci.autonomic.zone`. +- **Host:** `systemctl --failed` empty; `deploy-proxy` reconcile logs clean. + +## 10. Risks / gotchas + +- **Dual-cert SNI in the traefik reconciler** is the highest-risk change — stage-first, verify SNI + selection for both zones before switching. +- **Drone DB** does not follow the abra rename — accept fresh build history; export/re-apply the + enabled-repo list; re-insert secrets from `/run/secrets` (module already does). +- **Per-run recipe domains resolve via public DNS** — the `*.ci.autonomic.zone` wildcard A record is + load-bearing for every test deploy; never merge Phase 2 before it propagates. +- Old PR comments/badges link old names — they keep working until Phase 4 removes the old records. +- ~60 doc references (AGENTS.md, README, plan.md, skills, status skill) — one cosmetic doc PR at the + end so the docs don't lie. +- No domain-bearing secret values were found (webhook secrets are per-repo and copied as-is). + +## 11. Sequencing + +1. **Operator:** TTLs down + 3 Gandi records (§3) — 5 minutes. +2. **Agent:** cert PR (§4) → `test` → verify dual SNI → `switch`. +3. **Agent:** routing/env PRs (§5) stack-by-stack, health-gated; OAuth + webhooks + drone rename. +4. **Agent:** end-to-end verification (§9) + report republish under the new name. +5. **Bake ≥7 days** → Phase 2 PR → full suite → bake → Phase 4 retirement. diff --git a/archive/plans/cc-ci-plan/plan-ghostpr-debug-fix.md b/archive/plans/cc-ci-plan/plan-ghostpr-debug-fix.md new file mode 100644 index 0000000..9df8504 --- /dev/null +++ b/archive/plans/cc-ci-plan/plan-ghostpr-debug-fix.md @@ -0,0 +1,54 @@ +# Plan — debug & fix the ghost recipe upgrade PR + +**Context:** during the 2026-06-12 weekly upgrade, ghost (ghost 6.42.0→6.44.1 + mysql bump) was the +recipe whose `!testme` kept wedging. Its test deploys (`ghos-bdd2f3` etc.) hung at 0/1 in Swarm +`New` state — which we now know was the **`proxy` VIP exhaustion** (see +[[proxy-vip-exhaustion-runbook]] / `plan-proxy-vip-exhaustion-fix.md`), NOT necessarily a ghost +defect. It also got run by a DUPLICATE subagent during the interrupt churn, so the PR/branch state +may be messy. This plan figures out what actually went wrong and leaves the ghost PR clean + green. + +**Execute AFTER** the proxy VIP fix (so the infra confound is gone) and the current upgrade settles. +Owner: orchestrator, or a focused `/recipe-upgrade ghost` re-run. + +## What the upgrader already found (2026-06-12 summary — start here) +ghost 6.42.0→6.44.1 (+ mysql 8.0→8.4). PR is **recipe-maintainers/ghost #4**, open with an analysis +comment. Three `!testme` attempts: +- run 1 (2026-06-05): **PASS** at 6.44.0 + mysql:8.4 (under lighter load). +- run 2 (2026-06-12): FAIL — **IPAM/proxy-VIP exhaustion** (infra; the [[proxy-vip-exhaustion-runbook]] issue). +- run 3 (2026-06-12): FAIL — **a REAL issue**: Swarm `UpdateStatus=paused` on the **mysql 8.0→8.4 + data-dir upgrade race** — the default 5s `update_config.monitor` is too tight for the mysql + data-dir migration under load, so Swarm marks the update paused/failed. +The upgrader's suggested fix: add **`update_config.monitor: 300s`** (and likely +`failure_action: continue` / a longer `start_period`) to the ghost **app** service so the mysql +data-dir upgrade has time to converge. So the likely real fix is a small recipe-PR change to ghost's +`update_config`, then re-verify — NOT a test change. + +## Steps +1. **Inventory the ghost PR state.** On recipe-maintainers/ghost: list open PRs — is there ONE + upgrade PR or a DUPLICATE (two branches/PRs from the two ghost subagents)? Capture each PR's + branch, diff (image tag + version-label bumps), and its `!testme` comment history / build + results. Read the upgrader transcript for both ghost subagents to see what each did. +2. **Separate infra failure from real failure.** The deploy wedges were proxy-VIP exhaustion + (infra). Determine whether ghost ALSO has a genuine upgrade problem: does ghost 6.44.1 + the + mysql bump deploy + pass its tests on a HEALTHY swarm? Re-run `!testme` on the ghost PR now that + the box is healthy (post docker-restart / post proxy fix) and watch the real result. +3. **Dedup.** If two ghost PRs/branches exist, keep the correct one (right version bump, clean + diff), close the duplicate with a note, and ensure no leftover `dev-ghost`/`ghos-*` stacks remain + (reap). +4. **Fix forward to green.** If `!testme` is RED for a REAL reason (e.g. ghost 6.44.1 needs a config + change, or the mysql major bump needs a migration step / a genuinely-stale test): apply the + minimal recipe fix per `/recipe-upgrade` rules — recipe PR changes only; if a cc-ci TEST is + genuinely stale, leave an explanatory PR COMMENT (do NOT edit tests in default mode). Iterate + `!testme` ≤3× to green. +5. **Leave it operator-ready.** One clean ghost PR, `!testme` GREEN (or a clear comment explaining a + legitimately-deferred issue), no duplicate, no leaked deploys. NEVER merge — operator merges. + +## Acceptance +The ghost upgrade is represented by exactly one PR with a clear, green (or clearly-explained) +`!testme`, the duplicate-subagent mess cleaned, and a one-line note on whether ghost's original +failure was purely the proxy-VIP infra issue or a real upgrade problem (and how it was fixed). + +## Guardrails +Recipe mirror = PR only, never merge / never push main. Reap any `dev-ghost`/`ghos-*` test stacks on +exit. No secrets in logs/commits. Don't run while the proxy recreate (maintenance window) is in +progress. diff --git a/archive/plans/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md b/archive/plans/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md new file mode 100644 index 0000000..8155d53 --- /dev/null +++ b/archive/plans/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md @@ -0,0 +1,97 @@ +# Plan — lasuite-drive OIDC-setup flakiness: harness restructure + recipe robustness PR + +**Status:** QUEUED — picks up the deferred lasuite-drive `[~]` item (Q3.2) when the loops return to it. +The disk blocker is now lifted (host grew to 70 GB, 2026-05-29), so the upgrade tier can run too. +**Owner:** Builder + Adversary loops. **Two deliverables:** (A) a cc-ci harness change, (B) a +**lasuite-drive recipe PR** (we maintain the recipe via recipe-maintainer). +**This file:** `/srv/cc-ci/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md` + +--- + +## 0. The problem (ground it in real logs FIRST) + +lasuite-drive's `setup_custom_tests` wires OIDC by doing a **full 12-service `abra app deploy --chaos` +redeploy** of an already-running heavy stack. That reconverge is **flaky**: a collabora reconverge +race + a **transient backend gunicorn-perms / WOPI-404 window**. Only **backend/app** consume the +OIDC env, so re-converging collabora/onlyoffice/minio/db is unnecessary exposure. The Builder +correctly did NOT claim Q3.2 (a flaky setup isn't a reliable green) and filed this. + +**Step 0 (do before fixing):** capture the actual failure from a flaky run — collabora WOPI-discovery +timing, the backend log at the 404, and the exact gunicorn perms error — so we fix the real root +cause, not a guess. Record in JOURNAL. + +--- + +## Part A — cc-ci harness: wire OIDC at INSTALL, eliminate the redeploy + +Leverage the now **live-warm keycloak** (WC1): instead of deploy-recipe-then-redeploy-with-OIDC, the +dep is already running, so configure OIDC **before the single deploy**: + +1. Create the per-run namespaced realm+client in the **warm keycloak** (lightweight API calls — no + deploy). +2. Set lasuite-drive's OIDC env in its `.env` **before** the first `abra app deploy`. +3. Deploy lasuite-drive **once**, OIDC already wired. **No mid-run `--chaos` reconverge** → the flaky + window is gone. + +- **Use REAL abra commands only** (operator decision, 2026-05-29): the install is a normal + `abra app deploy`. Do **NOT** use `docker service update`/`docker service scale` to surgically + patch services — CI must exercise the same abra path a real operator uses. If any redeploy ever + remains necessary, it is `abra app deploy` (+ proper readiness gating, §C), never a docker-level + bypass. +- **Generic-first invariant still holds.** keycloak is live-warm (persistent infra, ~always up), so + there's no per-run dep *deploy* that could fail and break a generic tier. Generic tiers still + assert serving recipe-alone; if realm creation or the provider is unreachable, only the OIDC + *custom* test fails (isolated). This is SAFE **iff** the recipe boots with OIDC-env-set even when + the provider isn't reachable at boot — which Part B guarantees (lazy OIDC). A and B reinforce each + other. +- **Revises `plan-sso-dep-testing.md`** for recipes whose app tolerates OIDC-at-boot: prefer + install-time wiring against the warm dep over the post-deploy `setup_custom_tests` redeploy. Keep + the redeploy path only for recipes that genuinely can't take OIDC env at first boot. +- **Verify:** lasuite-drive full suite green **without** a mid-run reconverge; run it repeatedly + (e.g. 3×) to show the flakiness is gone, not just absent once. + +## Part B — lasuite-drive recipe PR (root-cause robustness, we're maintainers) + +> **Broken out into its own sub-plan: `plan-lasuite-drive-recipe-pr.md`** (operator, 2026-05-29) — +> it now also folds in the F2-12 upgrade-convergence fix (collabora healthcheck) so cc-ci can return +> to abra-native convergence. The summary below is retained; the sub-plan is authoritative. + +Fix the fragility in the recipe itself so it's robust under ANY reconverge — this helps real +operators, not just CI, and is the real payoff of maintaining the recipe. On a branch of the +lasuite-drive recipe (recipe-maintainer): + +1. **Order backend behind collabora's WOPI readiness.** Add a Docker **healthcheck on collabora** + (WOPI discovery endpoint → 200) and make backend **wait for it / retry WOPI discovery with + backoff** instead of failing during collabora startup. Turns the race into deterministic ordering. +2. **Fix the gunicorn-perms race.** The transient perms error is a volume-permission race at startup + (gunicorn can't read/write a mount until perms are set). Fix in the entrypoint: set perms before + exec'ing gunicorn (or a proper init step). +3. **Make OIDC discovery lazy / retrying.** If backend validates the OIDC provider eagerly at boot + and dies when it's briefly unreachable, that's what forces the deploy-with-dep dance. Resolve OIDC + discovery lazily (at first login, with retry) so the app boots without the provider up. (This is + also the property Part A relies on for the generic-first invariant.) + +### The PR is "working" ONLY when cc-ci verifies it green (operator rule, 2026-05-29) +A lasuite-drive recipe change is **not** considered done until **our CI server has run the full suite +on the PR and it passes** — install + upgrade + backup + restore + custom (incl. the OIDC login +test), repeatedly-green (no flakiness). Concretely: push the recipe branch/PR, trigger cc-ci +(`!testme` on the lasuite-drive PR), and require a clean green (Adversary cold-verified). **Only then +does the operator merge** the recipe PR. This dogfoods cc-ci: the CI that surfaced the bug also gates +its fix. + +## C. If any redeploy must remain (fallback only) +If a recipe genuinely needs OIDC env applied after first boot, do it with **`abra app deploy`** (real +abra — never `docker service update`), and **gate readiness properly**: poll collabora WOPI = 200 + +backend health with retries/timeout before declaring ready. This is strictly a fallback; Part A + +Part B should remove the need. + +## Definition of done +- [ ] Step 0 root-cause logs captured + recorded. +- [ ] Part A: lasuite-drive tested via install-time OIDC wiring against the warm keycloak, **no + mid-run reconverge**, full suite green **3× in a row** (flakiness gone), Adversary cold-verified. +- [ ] Part B: lasuite-drive recipe branch with the WOPI-healthcheck-gating + gunicorn-perms + lazy-OIDC + fixes; **cc-ci runs the full suite (incl. upgrade tier) on the PR and it is repeatedly green**; + Adversary cold-verifies; operator merges. +- [ ] Q3.2 (lasuite-drive) claimed + DEFERRED.md entry closed (flaky-OIDC item) — only after the above. +- [ ] `plan-sso-dep-testing.md` updated to prefer install-time OIDC wiring (warm dep) where the recipe + supports it. diff --git a/archive/plans/cc-ci-plan/plan-lasuite-drive-recipe-pr.md b/archive/plans/cc-ci-plan/plan-lasuite-drive-recipe-pr.md new file mode 100644 index 0000000..b5181db --- /dev/null +++ b/archive/plans/cc-ci-plan/plan-lasuite-drive-recipe-pr.md @@ -0,0 +1,77 @@ +# Sub-plan — lasuite-drive recipe robustness PR (fix the root cause upstream) + +**Status:** QUEUED — a **recipe-maintainer PR to the lasuite-drive recipe** (we maintain it). Picks up +after the Q3.2 lasuite-drive test work settles. Complements — and largely **obsoletes** — the +CI-side workarounds the harness currently uses for lasuite-drive's fragility. +**Owner:** Builder + Adversary loops. **This file:** `/srv/cc-ci/cc-ci-plan/plan-lasuite-drive-recipe-pr.md` +**Relationship:** this is the **recipe-side** deliverable. The cc-ci **harness-side** OIDC-at-install +work is `plan-lasuite-drive-oidc-robustness.md` Part A; this sub-plan is its Part B, broken out. + +--- + +## 0. Why (CI surfaced real recipe bugs — fix them at the source) + +cc-ci has surfaced genuine fragility in the lasuite-drive recipe that a **real operator would also +hit**, currently papered over by CI-side workarounds: +- **Install-time:** backend comes up before collabora's WOPI discovery is ready → transient + **WOPI-404** + a **gunicorn-perms** startup race. The flaky 12-service `--chaos` OIDC redeploy. +- **Upgrade-time (F2-12):** upgrading to the heavier new collabora (25.04.9.4.1) **does not converge + within abra's monitor window** → abra FATAs. The harness currently works around this by skipping + abra's convergence monitor (`-c`) and using its own collabora WOPI-200 `READY_PROBE`. + +These are recipe defects. Fixing them upstream helps every lasuite-drive operator **and** lets cc-ci +**go back to abra's native convergence** (per the guardrail "prefer abra convergence; custom probe +only when necessary") — turning the harness `-c`/READY_PROBE from a *necessity* into a *backstop*. + +## 1. The fixes (lasuite-drive recipe) + +1. **Collabora healthcheck + start_period (the keystone).** Add a real Docker **healthcheck** to the + collabora service — WOPI discovery endpoint returns 200 — with a `start_period` generous enough + for the heavy 25.04 image to boot. Effect: (a) swarm/abra see collabora as *unhealthy until WOPI + is actually up*, so **abra's own convergence monitor waits correctly** (fixes F2-12 at the source + — no `-c` skip needed); (b) the install-time WOPI-404 window closes because dependents can gate on + collabora health. +2. **Backend tolerates / waits for collabora WOPI.** Make backend **retry WOPI discovery with + backoff** (and/or order it behind collabora health) instead of failing on the transient 404. +3. **Fix the gunicorn-perms startup race.** Set the volume permissions in the backend entrypoint + (or an init step) **before** exec'ing gunicorn, so there's no read/write race on a freshly-mounted + volume at startup. +4. **Lazy / retrying OIDC discovery.** Backend resolves the OIDC provider **at first login with + retry**, not eagerly at boot — so the app boots cleanly with OIDC env set even if the provider + isn't reachable yet. (This is also what the harness-side OIDC-at-install pattern relies on, and + what keeps the generic-first invariant safe.) + +## 2. Mechanics — branch, PR, and the merge rule + +- Make the change on a **lasuite-drive recipe branch** and open a PR via the **`recipe-create-pr` + skill** (`/srv/recipe-maintainer/.opencode/skills/recipe-create-pr/SKILL.md`) — mirror to + `git.autonomic.zone/recipe-maintainers/lasuite-drive` as needed; upstream is + `git.coopcloud.tech`. +- **The PR is "working" ONLY when cc-ci verifies it green** (operator rule): trigger cc-ci + (`!testme` on the lasuite-drive PR) and require the **full suite incl. the UPGRADE tier** to pass + **repeatedly-green** (e.g. 3 consecutive passes, not a one-off), **Adversary cold-verified**. + **Only then does the operator merge.** This dogfoods cc-ci: the CI that found the bugs gates the fix. + - **SCOPE (operator, 2026-05-29):** this repeated-green / 3× bar is **specific to lasuite-drive + because it was demonstrably FLAKY** — it's a *flakiness proof* (show the fix made it reliably + green, not green-by-luck-once). It is **NOT the general testing standard.** Normal recipe gates + remain **one Adversary cold-verified green** (`plan.md §6.1`); do not generalize 3× to other + recipes/gates. + +## 3. Definition of done +- [ ] Recipe branch with fixes #1–#4; PR opened (recipe-create-pr). +- [ ] **cc-ci runs the full suite (install + upgrade + backup + restore + custom/OIDC) on the PR, + repeatedly green, Adversary cold-verified.** +- [ ] **Root-cause proof:** with the collabora healthcheck in place, demonstrate the upgrade tier + passes under **abra's NATIVE convergence** (i.e. drop `-c` for lasuite-drive and it still + converges + stays green) — confirming the recipe fix resolved F2-12 at the source. If it still + needs the harness backstop, say so honestly (record why). +- [ ] Operator merges the recipe PR. Then: cc-ci can **revert the lasuite-drive `-c`/READY_PROBE + workaround to abra-native convergence** (per the guardrail), and close the lasuite-drive flaky + items. + +## 4. Guardrails +- **Don't weaken any test** to make the PR pass — the fixes must make the recipe genuinely robust, + proven by repeated-green cc-ci runs, not by loosening assertions. +- **Real abra path** throughout (no docker-level bypass). +- **Bounded** — the four targeted robustness fixes; not a recipe rewrite. Bigger recipe improvements + → upstream issues / IDEAS, not this PR. diff --git a/archive/plans/cc-ci-plan/plan-sso-dep-testing.md b/archive/plans/cc-ci-plan/plan-sso-dep-testing.md new file mode 100644 index 0000000..d335306 --- /dev/null +++ b/archive/plans/cc-ci-plan/plan-sso-dep-testing.md @@ -0,0 +1,210 @@ +# SSO-dep testing pattern (OIDC + co-deployed provider) — reference plan + +**Status:** active reference for Phase 2 (does not need its own phase; it's a pattern Phase 2 +overlays apply per recipe). +**Operator clarification (2026-05-28):** integrating a recipe with an OIDC/SSO dep is **loop work, +not operator work**. Anything that was deferred citing "operator input needed for OIDC" should be +re-opened and done autonomously per this plan. +**This file's path:** `/srv/cc-ci/cc-ci-plan/plan-sso-dep-testing.md` +**Companion:** the running harness in `runner/harness/sso.py` (existing primitives: +`setup_keycloak_realm`, `oidc_password_grant`, `assert_discovery_endpoint`). + +--- + +## 0. Why this plan + +Several recipes test their authenticated functionality through an OIDC/SSO provider (keycloak, +authentik). The cc-ci pattern is to **co-deploy the provider with the recipe under test in the same +ephemeral run** — one shared deployment per dep, configured at install time, used by the +recipe-under-test's authenticated tests, torn down with it. This file is the canonical pattern for +how to wire that up so any recipe that declares `DEPS = ["keycloak"]` (or `["authentik"]`) Just Works +without per-recipe ad-hoc plumbing. Recipes that need OIDC are not blocked on the operator — they +follow this plan. + +## 1. The DEPS model — deps deploy AFTER generic tiers (operator-2026-05-28) + +**Critical ordering rule:** generic tiers (install / upgrade / backup / restore) run against the +**recipe alone, with no dep available**, so a failure in dep-deploy or OIDC setup **cannot break +generic-tier signal**. Deps + OIDC wiring move to a **`setup_custom_tests` step** that runs *after* +generic tiers and *before* the custom tier — its failure is isolated to the SSO-marked custom tests. + +A recipe's `tests//recipe_meta.py` declares its SSO dep: +```python +DEPS = ["keycloak"] # or ["authentik"] when that backend lands +``` + +### Lifecycle order (single run, per recipe) + +``` +1. Deploy recipe-under-test ALONE (no deps, OIDC env unset or stubbed). + - app_new #1 for the recipe; generic install_steps.sh runs RECIPE-ONLY setup (no deps). +2. INSTALL tier: generic [+ overlay] assertions against the recipe alone. +3. UPGRADE tier: abra app upgrade in place, assertions against the recipe alone. +4. BACKUP tier: in place (if backup-capable), recipe-alone marker. +5. RESTORE tier: in place, recipe-alone marker. +6. setup_custom_tests step ← NEW (operator-2026-05-28) + a. For each dep in DEPS, deploy + provision realm/client via harness.sso.setup__realm. + b. Write $CCCI_DEPS_FILE with each dep's {domain, realm, client_id, client_secret, admin_*}. + c. Run the per-recipe post-deps hook `tests//setup_custom_tests.sh` to wire the OIDC + env into the running recipe (abra app config set + abra app secret insert) and trigger an + in-place redeploy of the affected services so the env takes effect. + d. Mark deps-ready = True on success; on ANY failure mark deps-ready = False and CONTINUE + (log the error; do NOT abort the run). +7. CUSTOM tier: + - If deps-ready: run all custom tests, including those tagged @pytest.mark.requires_deps. + - If NOT deps-ready: still run custom tests, but tests tagged @pytest.mark.requires_deps are + reported as ERROR/SKIP (with the captured setup_custom_tests error attached). Non-deps + custom tests still run normally. +8. Teardown (in finally): recipe first; then each dep in reverse declaration order. +``` + +### DG4.1 deploy-count guard, generalised +The "one deploy per run" guard becomes **one `abra app new` per app in the run** (recipe + each +dep). In-place reconfigure-and-redeploy (the step 6c env update) is **NOT** a fresh `app_new` and +does NOT increment the per-recipe count. So a run with `DEPS = ["keycloak"]` has exactly 2 +`app_new` calls (recipe + keycloak), no matter how many tiers ran. The per-run summary reports +deploy-count per app for verification. + +### Why this ordering +- **Generic-tier signal is preserved** when SSO/dep setup is broken — the recipe's own deploy/ + upgrade/backup/restore behaviour is still tested honestly. +- **Failure isolation**: a recipe whose generic tier passes but whose SSO setup is broken yields + per-op `pass/pass/pass/pass/skip(deps-not-ready)` — far more useful than the previous + all-or-nothing. +- A recipe that genuinely can't boot without OIDC fails its generic install honestly (the recipe + should accept a stubbed/empty OIDC env at install time and only require the env when an + authenticated endpoint is hit). That's a real recipe finding, not a CI artifact. + +## 2. Provider pluggability + +- **Provider-agnostic primitives** (today, in `harness/sso.py`) — these stay pluggable: + - `oidc_password_grant(discovery_url, client_id, client_secret, username, password) -> token` — + pure OIDC; works against any compliant provider. + - `assert_discovery_endpoint(discovery_url, expected_issuer)` — pure OIDC. +- **Provider-specific setup** (admin API calls) — one function per provider: + - `setup_keycloak_realm(domain, admin_user, admin_password, realm, client_id, redirect_uris) -> + {client_secret, discovery_url}` — exists today. + - `setup_authentik_realm(...)` — same shape, authentik admin API; **deferred** to a future Q4 + enrollment that actually wants authentik (see `machine-docs/DEFERRED.md`). Pluggable: a recipe + declaring `DEPS = ["authentik"]` would just call this instead. No change to the per-recipe + `install_steps.sh` shape beyond which provider it asks for from `$CCCI_DEPS_FILE`. +- **Don't write per-recipe SSO logic.** All recipes use the same DEPS+install_steps shape. + +## 3. Per-recipe hooks — two distinct scripts (recipe-only vs post-deps) + +A recipe with `DEPS = ["keycloak"]` ships **two** optional hook scripts (either may be absent if +not needed): + +### 3.1 `tests//install_steps.sh` — RECIPE-ONLY setup, runs at install time +This is the Phase-1d custom-install-steps hook. It runs **before** the recipe deploys, **with no +dep available** (the dep hasn't been deployed yet at this point). Use it only for recipe-only +setup that the recipe needs to boot at all (e.g. seed a fixture, set a non-OIDC env). **Do NOT +read `$CCCI_DEPS_FILE` here** — it doesn't exist yet. If the recipe requires OIDC to *boot at +all*, set a safe stub here (e.g. disable auth) so the recipe can come up for generic tiers; the +real OIDC wiring happens in §3.2. + +### 3.2 `tests//setup_custom_tests.sh` — POST-DEPS wiring, runs after generic tiers +This is the new (operator-2026-05-28) hook that wires the recipe to its already-deployed dep, +*after* the generic tiers have run. The orchestrator has already deployed each dep and written +`$CCCI_DEPS_FILE` by the time this runs. Roughly: + +```sh +#!/usr/bin/env bash +set -euo pipefail +# Read the dep's connection info from $CCCI_DEPS_FILE (orchestrator-written). +KC_DOMAIN=$(jq -r '.keycloak.domain' "$CCCI_DEPS_FILE") +KC_CLIENT=$(jq -r '.keycloak.client_id' "$CCCI_DEPS_FILE") +KC_SECRET=$(jq -r '.keycloak.client_secret' "$CCCI_DEPS_FILE") +KC_REALM=$( jq -r '.keycloak.realm' "$CCCI_DEPS_FILE") + +# Inject the OIDC client secret as an abra app secret (recipe-conventional name varies — match +# the recipe's .env.sample SECRET_*). +echo "$KC_SECRET" | abra app secret insert -n "$CCCI_APP_DOMAIN" oidc_rpcs v1 - + +# Write the OIDC env vars to the parent .env (names per the recipe's .env.sample). +abra app config set "$CCCI_APP_DOMAIN" \ + OIDC_REALM="$KC_REALM" \ + OIDC_OP_DISCOVERY_ENDPOINT="https://${KC_DOMAIN}/realms/${KC_REALM}/.well-known/openid-configuration" \ + OIDC_OP_AUTHORIZATION_URL="https://${KC_DOMAIN}/realms/${KC_REALM}/protocol/openid-connect/auth" \ + OIDC_OP_TOKEN_URL="https://${KC_DOMAIN}/realms/${KC_REALM}/protocol/openid-connect/token" \ + OIDC_OP_USER_URL="https://${KC_DOMAIN}/realms/${KC_REALM}/protocol/openid-connect/userinfo" \ + OIDC_RP_CLIENT_ID="$KC_CLIENT" \ + OIDC_RP_REDIRECT_URI="https://${CCCI_APP_DOMAIN}/auth/oidc/callback" + +# Force an in-place redeploy of the affected services to pick up the new env. This is NOT a fresh +# app_new (deploy-count guard still 1 for this recipe). +abra app deploy --force --chaos --no-input "$CCCI_APP_DOMAIN" +``` + +The OIDC env-var **names are recipe-specific** (`OIDC_OP_*` for lasuite-docs, different prefixes +elsewhere). Read the recipe's `.env.sample` to see which keys the recipe expects; the *values* follow +this template. If a recipe needs more than this (extra group/claim mappings, etc.), extend its +`setup_custom_tests.sh` only — never the shared harness. + +## 4. Test pattern: authenticated endpoints (mark + isolate) + +- **Mark dep-requiring tests:** every custom test that needs the dep up + OIDC wired must use + `@pytest.mark.requires_deps`. The orchestrator skips these with reason `"deps-not-ready: "` + if `setup_custom_tests` failed. Non-deps custom tests are unaffected by SSO setup failures. +- **Headless API tests** — use `harness.sso.oidc_password_grant` to mint an access token, then call + the recipe's authenticated endpoint with `Authorization: Bearer `. Asserts on the response. +- **Browser flows (Playwright)** — navigate to the recipe, follow the redirect to keycloak, fill the + pre-provisioned test user's credentials, return to the recipe, exercise the UI. (Use the + pre-provisioned `ci-user@example.com` / known password the realm setup creates.) +- **The realm/client is fresh per run** — no cross-run state, no shared accounts. The realm setup + creates one or more test users with known passwords (pass-through from a per-run secret) so the + tests can authenticate without prompts. + +## 5. Concrete recipes that use this pattern (Phase-2 scope) + +These are **loop work** under this plan, not deferred: + +- **lasuite-docs** — `DEPS = ["keycloak"]`; ports the upstream `oidc_login.py` + + `upload_conversion.py` parity tests + the §4.3-prescribed `create-a-doc + read-back via + authenticated /api/v1.0/documents/`. (Re-enters `DEFERRED.md` entry #5 — this plan IS the + re-entry, not operator input.) +- **cryptpad** — `DEPS = ["keycloak"]` (cryptpad upstream tests use authentik, but a keycloak-backed + cryptpad OIDC test is equally valid and uses the same primitives). The cryptpad create-a-pad + Playwright test (DEFERRED #6) is a separate concern — that one really does need a stable + CryptPad app-launch contract; it stays deferred. +- **lasuite-drive, lasuite-meet** — same pattern when mirrored (`recipe-create-pr` skill — loop work). +- Any future recipe that requires OIDC follows this plan; no operator handoff. + +## 6. What stays deferred (genuinely operator-input) + +- **authentik enrollment + `setup_authentik_realm` backend** (DEFERRED #9) — **RESOLVED (operator, + 2026-05-29): keycloak is our default SSO provider; default ALL recipe OIDC tests to keycloak.** Do + NOT test authentik↔keycloak integration, and do NOT enroll authentik just to "prove pluggability" + — **Phase-2 DONE is NOT gated on authentik.** Enroll authentik + add `setup_authentik_realm` ONLY + if/when a recipe genuinely **requires** authentik (won't work under keycloak). If a recipe works + with keycloak, use keycloak. So DEFERRED #9's re-entry trigger narrows to "a recipe requires + authentik" — the cross-provider-coverage trigger is dropped. (E.g. cryptpad: its upstream test + uses authentik, but test it under **keycloak** — equally valid.) +- The `--extra` flag IDEA is **not** a precondition for this plan; OIDC-dep tests are part + of the default suite for the recipes that need them. + +## 7. Definition of done for this pattern +- [ ] `DEPS = [...]` honored by `runner/run_recipe_ci.py`, with the **deps-AFTER-generic** ordering + (§1): deps deploy + `setup_custom_tests` step runs between RESTORE and CUSTOM tiers; + `$CCCI_DEPS_FILE` written; deps torn down LAST in reverse order. +- [ ] **Failure isolation proven:** a forced `setup_custom_tests` failure (e.g. simulate keycloak + realm-setup error) yields a run where generic tiers report **pass** and CUSTOM + `requires_deps` tests report **skip(deps-not-ready)** — no false fail of the generic tier, + no aborted run. +- [ ] **lasuite-docs** ships `tests/lasuite-docs/setup_custom_tests.sh` per §3.2 + authenticated + tests per §4 marked `@pytest.mark.requires_deps` (closes DEFERRED #5 — keep the entry there + with the closing commit, do not re-defer). +- [ ] At least one other OIDC-dep recipe (cryptpad oidc_login or a lasuite-* once mirrored) lands + cold-green using the same pattern, demonstrating reuse. +- [ ] `docs/sso-dep-testing.md` (in the cc-ci repo) explains the pattern for future recipe + enrollments — link to this plan. +- [ ] Adversary cold-verifies the full run for one such recipe + the forced-failure isolation + case, posts PASS in `REVIEW-2.md`. + +## 8. Mirror+enroll reminder (also loop work) + +If a recipe in scope (e.g. `lasuite-drive`, `lasuite-meet`, `immich`) **isn't mirrored to +`git.autonomic.zone/recipe-maintainers/`**, mirror it autonomously via the `recipe-create-pr` skill +at `/srv/recipe-maintainer/.opencode/skills/recipe-create-pr/SKILL.md` (see also +`plan-phase2-recipe-tests.md §0b`). Mirror+enroll is **not** operator-pending; the bot is admin on +the org. diff --git a/archive/plans/cc-ci-plan/task-consolidate-recipe-prs.md b/archive/plans/cc-ci-plan/task-consolidate-recipe-prs.md new file mode 100644 index 0000000..5151eb8 --- /dev/null +++ b/archive/plans/cc-ci-plan/task-consolidate-recipe-prs.md @@ -0,0 +1,43 @@ +# Assistant task — consolidate open recipe PRs (one open PR per recipe) + +**Dispatched:** 2026-06-02 by the orchestrator. **Owner:** the Assistant (one-shot). **Not** the +Builder/Adversary loops — they are busy on the regression phase; do not touch their clones. + +## Goal +Every recipe mirror should have **at most ONE open PR**. For any recipe with more than one open PR, +combine them into a single open PR (the union of their changes) and close the rest. + +## Steps + +1. **Survey.** Creds in `/srv/cc-ci/.testenv` (`GITEA_USERNAME`/`GITEA_PASSWORD`/`GITEA_URL`). For every + **recipe** mirror under the `recipe-maintainers` org, list its open PRs: + - `GET /api/v1/orgs/recipe-maintainers/repos?limit=100` + - `GET /api/v1/repos/recipe-maintainers//pulls?state=open` + Recipes = real recipe mirrors only — **exclude** infra repos: `cc-ci`, `cc-ci-orchestrator`, + `cc-ci-secrets`, `archived-*`. Build the list of recipes with **>1** open PR. + +2. **Consolidate** each such recipe into ONE open PR holding the union of the changes, then close the others: + - Work in a **fresh clone** of the mirror (e.g. under `/tmp`). **Never** use the loops' clones + (`/srv/cc-ci/cc-ci`, `/srv/cc-ci/cc-ci-adv`). + - Combine the open PR branches onto one branch (cherry-pick/merge). **Never force-push over unmerged + work** — preserve every change. Prefer **extending the lowest-numbered open PR** by pushing the + combined branch onto its head (the no-force "commit on top" pattern in + `/srv/cc-ci/.claude/skills/recipe-upgrade/open-recipe-pr.sh`). + - **Conflict policy:** two upgrade PRs to different versions → keep the **newest** version. An upgrade + PR + a different-purpose PR (e.g. a backup/restore fix) → include **both** changes. + - **Close** the now-redundant PRs with a comment: `Consolidated into # — one open PR per recipe.` + - **Re-test** the surviving consolidated PR by commenting `!testme` on it (real CI; results show in + the PR; iterate up to 3×). If a genuine pre-existing failure blocks it, leave an explanatory + comment — do **not** weaken/skip/delete any test. + +3. **Report & stop.** Summarise: which recipes had >1 open PR, what you consolidated, the surviving PR + URL per recipe, conflicts resolved, and any PR left red with an explanatory comment. Then go idle + (one-shot — do not loop). + +## Guardrails +- **NEVER merge any PR into `main`** — the operator merges. "Merge them together" = consolidate multiple + open PRs into ONE open PR, **not** merge to main. +- Only touch **recipe mirror** PRs. Do **not** touch cc-ci-repo PRs (build/test PRs). +- Recipes with 0 or 1 open PR: leave untouched. +- Known starting point (re-verify live — state may have changed): `custom-html` had 2 upgrade PRs + (#1 1.12.0, #2 1.13.0); `ghost` had #1 (backup fix) + #2 (upgrade). Survey fresh for the full set. diff --git a/cc-ci-plan/advisory-scan.SPEC.md b/cc-ci-plan/advisory-scan.SPEC.md deleted file mode 100644 index 577a37a..0000000 --- a/cc-ci-plan/advisory-scan.SPEC.md +++ /dev/null @@ -1,391 +0,0 @@ -# Advisory scan — specification - -What `cc-ci-plan/advisory-scan.py` does, step by step, and why each step exists. This documents the -implementation as it stands (2026-08-11); if you change the code, change this file in the same commit. -`cc-ci-plan/test-advisory-scan.py` is the executable half of this spec — every rule below is asserted -there. - -**Role.** A per-recipe CVE detector run as a **pre-step of `/recipe-upgrade`** (step 2a). It is -**strictly additive**: it never replaces the release-note reading the upgrade agent already does. The -CVE count reported for a recipe is the **union** of what the agent read and what this scan found; the -scan may never *lower* a count established by reading. - -**Why it exists.** gitea 1.27.1 fixed CVE-2026-60004 and CVE-2026-59774 (both CVSS 9.8). The weekly -report printed gitea's CVE count as `1`, then `none`. The upgrade agent had read the GitHub *release -notes*, which name neither — both were announced only in the vendor's blog security section — and the -report then derived security content from those notes plus model knowledge, which predates the CVEs. -Nothing in the pipeline queried an advisory source. This scan closes that hole. - ---- - -## Two passes - -| | Pass 1 — measure | Pass 2 — judge (`--adjudicate`) | -|---|---|---| -| Who | Pure Python, no model | The calling agent, a model | -| Does | Collects evidence and decides every case it can by arithmetic | Weighs the collected evidence on cases arithmetic cannot settle | -| Output | A count, or `UNKNOWN` | FIXED / NOT-FIXED / STILL-UNKNOWN per open case | -| Rule | Deterministic and reproducible | May only **raise** the count, never lower it | - -**Prefer pass 1.** Every case pass 1 decides is one that reproduces identically next week. Pass 2 exists -for evidence that is prose rather than data — a fallback, not a co-equal stage. When a class of case -keeps landing in pass 2, the fix is a new deterministic method in pass 1. §4c is exactly that: it moved -12 redis advisories out of pass 2 and into arithmetic. - ---- - -## Inputs - -``` -advisory-scan.py [--from ] [--to ] - [--image =:]... [--adjudicate] [--json] [--registry DIR] - -advisory-scan.py --compose-to [--compose-from ] # windows derived, not typed -``` - -| Input | Meaning | -|---|---| -| `` | Recipe name; selects `cc-ci-plan/upstream/.md` (the per-recipe URL registry) | -| `--from` / `--to` | The **primary app image's** version window being upgraded across | -| `--image NAME=FROM:TO` | A **sidecar image and the versions it moved between** (repeatable, all in ONE call). `NAME` is substring-matched against source repo names. Malformed values warn on stderr and are skipped. Without it that image's advisories stay unclassified. | -| `--compose-to URL` | **Derive every window by diffing this compose against its baseline**, instead of typing `--from/--to/--image`. Point it at a PR's `compose.yml`. | -| `--compose-from URL` | Baseline for the above. Default: the same repo's **default branch, resolved from the API** — never assumed to be `main`. | -| `--adjudicate` | Run pass 2: append the evidence dossier for judgement | -| `--registry` | Registry dir; also `CCCI_UPSTREAM_REGISTRY` | -| `GITHUB_TOKEN` / `GITHUB_TOKEN_FILE` | Read-only token; **rate limit only** (60/hr anonymous → 5000/hr). Default file `/srv/cc-ci/.github-token`, mode 600. Public advisories need **no scopes**. | - -Exit code is always 0 — this is informational. Failures are *reported*, never raised. - -For PR attribution, pin both compose URLs to commits: the PR head and its merge base with the -target branch. A previous release or warm canonical can include image changes already present -before the PR. A compose diff with only sidecar changes has no primary app window; every changed -sidecar is scanned under its own image name. - ---- - -# Pass 1 — deterministic - -## Step 1 — Collect source URLs from the registry - -Read `cc-ci-plan/upstream/.md` and extract every `http(s)://…` URL. - -**Trailing markdown punctuation is stripped** (`` ` `` `'` `"` `*` `.` `,` `;` `:` `>` `)`). The registry -is markdown, so URLs appear inside backticks and quotes; capturing the punctuation produced fetches of -`https://docs.n8n.io/release-notes/\`` which 404, and made immich and n8n render `?` for no real reason. - -> **Registry hygiene matters.** The scan can only look where the registry points. Two classes of defect -> have been found and fixed by running it: a **wrong URL** (`pgautoupgrade/pgautoupgrade`, which 404s — -> the repo is `pgautoupgrade/docker-pgautoupgrade`) and a **missing** one (gitea's CVEs are announced at -> `blog.gitea.com`, which the registry didn't list). When a vendor publishes security notes somewhere -> the registry lacks, add it. - -## Step 2 — Query the sources - -Three source classes, each recording **its own status** so *"checked, none found"* is never confused -with *"not checked"*. - -### 2a. GitHub Security Advisories — PRIMARY - -For every `github.com//` URL in the registry: -`GET /repos///security-advisories`. - -Captured per advisory: `cve_id`, `ghsa_id`, `severity`, `summary`, **`description`**, `published_at`, -and **all** `vulnerabilities[]` entries' `vulnerable_version_range` + `patched_versions` (joined `;`). - -- **All entries, not just the first.** An advisory carries one entry **per patched release line** — - n8n patches three (1.123.32, 2.17.4, 2.18.1). Reading only `vulnerabilities[0]` silently dropped the - line a deployment was actually on, and misclassified CVE-2026-42231/42232 as out-of-window. -- **Pagination via the `Link rel="next"` cursor**, to exhaustion (cap 20 hops). This endpoint returns - at most 100 rows **and ignores `?page=`** — it re-returns the same rows, which silently truncates busy - projects. discourse has 286 advisories; a single page cannot even cover one upgrade window. -- **The description is kept from this response.** It is already present here, and pass 2 needs the - prose; re-fetching it per advisory would cost one request each. -- **HTTP 404 ⇒ `no-advisories-published`** — a benign absence (many sidecar images publish none), **not** - a failure. Conflating the two pushed nearly every recipe to `?` and destroyed the signal. - -### 2b. Vendor release / security pages - -Every other registry URL is fetched, HTML-stripped, and scanned for `CVE-\d{4}-\d{4,7}`, keeping ±160 -characters of context per hit. - -URLs containing `<`, `>`, `{`, `}`, `VERSION`, or `vX.Y.Z` are **skipped as templates** — they are -human documentation (`…/changelog/v/`), not fetchable, and counting them as failures is wrong. - -This is the source that would have caught gitea: the vendor blog names both CVEs, the GitHub release -page names neither. - -**When the page is a changelog organised by release, each CVE is attributed to the release heading it -appears under** (`Changes with nginx 1.31.3`, `## v1.31.3`, …) and that becomes its fixed-in version. -Without this, a project that publishes no advisory feed can never contribute a CVE: - -> **nginx publishes NO GitHub security advisories.** Every nginx CVE we can see comes from -> `nginx.org/en/CHANGES`. Scraping ids out of it without attributing them to a release left them with -> no patched version, so they were never classifiable — and every nginx bump in the fleet reported -> **0** forever. nginx is a sidecar in most recipes. Measured: `1.31.1 → 1.31.3` fixes **six** CVEs -> (three in .2, three in .3); lasuite-docs#7 went 0 → 6 and lasuite-drive#6 went 0 → 3 on this alone. - -A changelog CVE is tied to a window by the **image name appearing in the page URL** (window `nginx` ↔ -`nginx.org/...`). A CVE found on a vendor page with no attributable release still has no version data, -so pass 1 cannot place it — it goes to pass 2 (§6). - -### 2c. NVD by CPE — the fallback for projects that publish nothing - -Declared per recipe in the registry as `nvd-cpe: = `. - -> **Why it exists.** Two recipes could not see CVEs *at all*: `mattermost-lts` (empty GitHub advisory -> feed, security bulletins rendered client-side so a text sweep finds nothing) and `mumble` (nothing -> published anywhere the registry points). Their scans returned `?` — nothing measured. NVD is -> CPE-indexed and carries structured ranges, so it answers where the vendor does not: mattermost -> 10.5.0 → 10.12.4 now scores **165**, and mumble finds `CVE-2025-71264` (fixed 1.6.870). - -Two range forms, both used: - -| NVD field | meaning | how it is judged | -|---|---|---| -| `versionEndExcluding X` | fixed in X exactly | a normal patched version (§4a) | -| `versionEndIncluding X` | affected **up to and including** X; fix version unpublished | fixed when the upgrade crosses X, i.e. `from ≤ X < to` | - -**NVD lags the vendor** — it had neither gitea CVSS-9.8 RCE at publication — so this is a fallback, -never a replacement for 2a/2b. Unauthenticated calls are rate-limited (~5/30s), hence the retry. - -### 2d. OSV.dev — supplementary - -Only when the recipe has an entry in `OSV_PACKAGES` (ecosystem + package) and a version is given. - -> **Measured, not assumed.** For the two gitea CVEs, OSV **404'd on both** and returned only Go -> *dependency* advisories for the package; NVD's API had them by neither CPE, CVE id, nor keyword. -> **Advisory databases lag the vendor**, which is why 2a and 2b lead and this is supplementary. - -## Step 3 — Union - -All findings merge into one CVE map: id → `{sources[], severity, ghsa, vulnerable_range, patched, -description, published_at, url, cvss, context}`. A CVE seen by several sources keeps them all. - -## Step 4 — Classify against the upgrade window - -Two invariants govern this step, both learned from a wrong answer in production. - -> **A. Every image is judged by its OWN versions.** The app repo uses `--from/--to`; each sidecar uses -> its own `--image NAME=FROM:TO`. **Pass them all in ONE invocation** — the count is a union across -> images, and the UNKNOWN guarantee in B only holds when a single run sees every one. An image with no -> window is **not** classified; its advisories are listed as unclassified so they stay visible without -> inflating the count. Each window is classified independently, so one may use version ranges while -> another falls back to dates. -> *Why:* discourse once reported **133**, of which **34 were redis CVEs** — including -> `CVE-2021-21309`, patched in redis 6.0.11 in 2021 — counted purely because 6.0.11 sits numerically -> inside discourse's `3.5.3 → 2026.7.1` range. The fix is not to ignore sidecars but to give each one -> the versions it actually moved through: with `--image redis=7.4:8.10`, discourse scores -> **140 = 123 (app, by date) + 17 (redis)**, and the redis seventeen include `CVE-2025-49844`, -> **critical**, invisible while sidecars went uncounted. -> -> **B. Never emit a number you cannot justify.** If no method can order a window, the count is -> `null` / `UNKNOWN`, never `0`. A `0` in a security column asserts safety. Equally, an advisory that -> cannot be judged is **indeterminate** (§4d) — never silently counted as "not fixed". - -### 3b. Deriving the windows from a compose diff (`--compose-to`) - -Typing `--from/--to/--image` by hand means someone has to remember that the recipe also bumped its -redis. That is how sidecar CVEs went uncounted for months. This mode reads the windows off the diff: - -1. Fetch both compose files (baseline = the repo's **default branch from the API**, since several - recipes keep a stale `main` beside a live `master`). -2. Parse `{service: (image-repo, tag)}` — keyed by **service, not image repo**, because an upgrade - may change the repo itself (plausible moved `plausible/analytics` → - `ghcr.io/plausible/community-edition`; keyed by repo that reads as one image vanishing and an - unrelated one appearing, losing the app window entirely). -3. Every service whose tag or repo changed becomes a window. The `app` service drives `--from/--to` - (coop-cloud convention: it is the recipe's primary image); the rest become `--image` windows. - Unchanged images produce no window — inventing one would be a false count. -4. The derived windows are printed to stderr before the scan, so the inputs are auditable. - -Image names are matched against advisory sources **both ways** — an image name is often longer than -its source repo (`clickhouse/clickhouse-server` vs `ClickHouse/ClickHouse`) and sometimes shorter -(`redis` vs `redis/redis`). - -Verified on plausible PR #5: from the compose URL alone it derives `v2.0.0 → v3.2.1` plus -`clickhouse-server 23.4.2.11-alpine → 24.12-alpine`, and reports **6** — identical to the -hand-specified args. - -`--from/--to/--image` remain available for finer-grained checks (scanning a window that is not a -literal compose diff, e.g. "what would the compatibility-safe target fix?"). - -### 4a. By patched version (preferred — exact) - -**A fix on the line you are upgrading FROM was already yours.** Projects that maintain several lines -patch them all at once: mattermost fixed `CVE-2025-11794` in 10.11.4, 10.12.1 *and* 10.5.12. An -upgrade 10.11.22 → 10.12.4 crosses 10.12.1, so a naive window test counts it — but 10.11.22 is -already past 10.11.4, so the deployment had the fix before the upgrade. Counting it credits the -upgrade with work it did not do. This check is **skipped for placeholder versions** (`7.4.X` parses -to a bare `7.4`, which would read as "already fixed at 7.4" and silently drop a real fix — exactly -how redis `CVE-2024-46981` was lost when the rule was first added). - - -`patched_versions` is a **range expression** (`">= 2.18.1"`), possibly several joined by `;`. Extract -every version-looking token; the advisory is **fixed-by-this-upgrade** if **any** patched version `p` -satisfies `from < p <= to` — exclusive lower (a fix already in the version you were on is not this -upgrade's doing), inclusive upper. - -**Comparison is zero-padded to equal length**, so `18` == `18.0` == `18.0.0` as semver means it. -Without padding, plain tuple order makes `(18,) < (18,0)`, i.e. a fix in 18.0 falls *outside* a window -ending at 18 — and bare major tags are the norm for sidecars (`postgres:18`, `redis:8-alpine`). Padding -is permissive at the lower bound and conservative at the upper: with `to = 18`, a fix in `18.5` is -**not** counted, because nothing proves which 18.x a floating tag resolved to. - -### 4b. By advisory publish date (fallback — temporal) - -Used **only** when 4a cannot be trusted: a **version-scheme change**, detected as the leading version -component jumping by ≥ `SCHEME_JUMP` (100) — e.g. semver `3.5.3` → calver `2026.7.1`. - -Version strings are unorderable across such a jump (`2025.12.2` compares "newer" than `3.5.3` while -shipping earlier), but **release dates always order**. So: - -1. Resolve `--from` and `--to` to **git tag dates** on that source (tries `v` then - ``; annotated tag → tagger date, else commit date). -2. An advisory counts as fixed when `date_from < published_at <= date_to` — the same exclusive/inclusive - boundaries as 4a, so the two methods agree at the edges. - -This reproduces, automatically, the hand count that established discourse `3.5.3` (2025-12-30) → -`2026.7.1` (2026-07-31) = **123 CVEs**. - -*Assumption:* the vendor publishes advisories at fix time (true for discourse). The count includes -**first-party plugin advisories** where the vendor files them on the same repo — which is why a -plugin-rich project scores far higher than a monolith, not a statement about relative security. - -### 4c. By release notes naming the CVE (rescue — for advisories with no fix version) - -Applied to advisories 4a/4b could not decide, **before** giving up on them. Fetch the source repo's -GitHub **releases** (cached per repo, 4 pages) and find every tag whose notes **name the CVE id**. If -any such tag falls inside the window by 4a's rule, the advisory is fixed by this upgrade, and the -naming tags are recorded in `fix_versions_from_release_notes` as the citation. - -> **Why this is not optional.** Vendors routinely publish an advisory with `patched_versions: "TBD"` -> and then name the CVE in the release notes of every branch that got the fix. **All 12** redis -> advisories crossed by discourse's redis bump are exactly this shape — `TBD`, or a placeholder like -> `7.4.X`, with an open-ended `vulnerable_version_range` (`All`, `>= 7.0.0`) — yet each is named in -> concrete releases (`CVE-2025-32023` → 6.2.19, 7.2.10, 7.4.5, 8.0.3, 8.2.0). Without this method -> discourse's redis contribution reads 5; with it, 17. Six of the twelve are high severity. - -### 4d. Otherwise — indeterminate, not excluded - -An advisory from a **windowed** source that none of 4a–4c could decide — no usable `patched_versions`, -an open-ended vulnerable range, and no release note naming it — is recorded as **indeterminate**. It is: - -- **not** added to the count (nothing justifies counting it), and -- **not** treated as unaffected (nothing justifies dismissing it either). - -It is listed prominently, the headline reads *"(at least — see undetermined below)"*, and it becomes an -input to pass 2. Silently excluding these is the same defect class as printing `0` for an unscanned -recipe, one level down. - -### 4e. Unorderable window - -If neither 4a nor 4b can order a window at all, `count_known = false`, `cve_count_fixed = null`, and the -headline reads **"CVEs fixed by this upgrade: UNKNOWN — the scan could NOT determine a count"** with an -explicit *"This is NOT zero"*. If **any** requested window is unorderable the whole count is suppressed; -a partial number would understate a security figure. - -## Step 5 — Output - -Markdown (default) for pasting into the per-recipe upgrade log, or `--json`. - -| Field | Meaning | -|---|---| -| `cve_count_fixed` | Union across all windows, or **`null`** if any window was unorderable | -| `count_known` | Distinguishes "counted zero" from "could not count" | -| `cve_count_indeterminate` / `indeterminate[]` | Judged by nothing; a **floor marker** on the count | -| `resolved_by_release_notes` | CVE → the tags that named it (4c citations) | -| `windows` | Every source classified, with its from/to | -| `classified_by` | **Per source**: which method decided it | -| `date_window` | **Per source**, when 4b was used | -| `fixed_by_this_upgrade[]` | CVE ids, with severity / GHSA / fixed-in per id | -| `unclassified[]` | Seen but not attributable (other images, or vendor-page-only) | -| `sources[]` / `sources_failed[]` / `sources_benign[]` | Per-source status; only genuine failures in `failed` | - ---- - -# Pass 2 — adjudication (`--adjudicate`) - -## Step 6 — What gets judged - -Two kinds of open case, both real gaps rather than noise: - -1. **Indeterminate** (§4d) — from an image *with* a window, but no fix version is knowable anywhere. -2. **Vendor-page-only** — a CVE seen only on a vendor security page, with no structured advisory - behind it. **gitea's two CVSS-9.8 RCEs are this shape.** They carry no version data, so no - arithmetic can place them, but the page prose usually states the fixed release. - -## Step 7 — The evidence dossier - -Pass 1 collects; pass 2 judges. Nothing in the dossier interprets — it assembles what was *measured*, -so the judgement is made against evidence rather than recollection. That distinction is the whole -point: the original failure was a report leaning on model knowledge that predated the CVEs, with no -source queried at all. - -Per open case: severity, CVSS, sources, its window, why it is undecided, `patched_versions` and -`vulnerable_version_range` **as published**, summary, full description, references, affected ranges -with `first_patched_version`, and **every release tag naming the CVE** — whether or not in window, since -the model may reason about branch lines the arithmetic deliberately will not. - -**Pass 2 also sees every decision pass 1 made** — a compact table of counted and excluded advisories -with the evidence behind each verdict. A deterministic verdict can still be wrong (a mis-parsed range, -a release note that mentions a CVE without fixing it), and only a reader with the evidence in front of -it can catch that. Silence means agreement. - -## Step 8 — The verdict contract - -For each open case: **FIXED** / **NOT-FIXED** / **STILL-UNKNOWN**, each with a one-line reason -**citing the evidence shown**. Every FIXED is added to the recipe's count — pass 1's number is a floor, -not a total. If the evidence does not settle it, **STILL-UNKNOWN**: do not infer from memory of the -project, and never record an undecided CVE as unaffected. - -**No silent caps.** `MAX_ADJUDICATE` (25) and `MAX_REVIEW_ROWS` (400) bound the output; whenever either -truncates, the block says how many were dropped and that the unshown remain undetermined. - ---- - -## How consumers must read it - -`/recipe-report` renders the `cve` column from the **union** of this scan and the agent's own reading: - -- a clean scan → its number, **including `0`**; -- **failed sources**, or `UNKNOWN` → **`?`**, never `none` — a blank reads as "clean", which is exactly - how two CVSS-9.8 gitea RCEs were published as `none`; -- **no upgrade this run** → `0`, not `?` — nothing an upgrade could have fixed; -- a count with **indeterminate advisories** → the number is a floor; say so in the notes; -- benign notes → never `?`. - -`?` must stay **rare**: it means *we tried and could not tell*, not *we did not look*. A rash of `?` is -a bug to raise in the report's Addendum, not a normal outcome — every instance so far traced to a defect -in this tool or stale registry data. - -## Testing - -`test-advisory-scan.py` — 58 offline tests (fixtures, no network) plus 6 live regressions against the -counts published in week-2026-08-07. **The offline tier covers pass 1 only, by design**: pass 2's -judgement is a model's and cannot be asserted deterministically. What *is* tested about pass 2 is the -part that stays deterministic — which cases it selects, and that truncation is always announced. - -``` -python3 test-advisory-scan.py # offline -python3 test-advisory-scan.py --live # + historic report numbers -``` - -`audit-advisory-scan.py` re-derives the counts with a **separate** semver implementation and its own -release fetch, then diffs against the scanner. Run it after changing classification; it is what caught -the 12 undercounted redis CVEs. - -## Known limits - -1. **Versions must be supplied per image.** An image with no `--image` is not counted — the scan will - not guess a version range it was not given. `/recipe-upgrade` passes one per image it bumped. -2. **Date-based counts are temporal**, not exact — they assume publish-at-fix-time. -3. **Registry-bound.** Unlisted vendor security pages are invisible; the scan cannot know what it was - never pointed at. -4. **`NAME` matching is substring-against-source-name**, so a short or generic name can attach to more - than one repo (`postgres` matches `discourse/discourse-postgres`). The primary source is claimed - first and cannot be stolen. A name matching **nothing** is silently ignored — a typo costs coverage - without warning. -5. **Release-note rescue (4c) trusts that naming implies fixing.** A release note that merely mentions a - CVE would be read as fixing it. Pass 2's review table exists partly to catch this. -6. **Rate limit** without a token is 60/hr — a full weekly sweep will exhaust it and degrade to failed - sources (visibly, but degraded). diff --git a/cc-ci-plan/advisory-scan.SPEC.md b/cc-ci-plan/advisory-scan.SPEC.md new file mode 120000 index 0000000..e5dc1d8 --- /dev/null +++ b/cc-ci-plan/advisory-scan.SPEC.md @@ -0,0 +1 @@ +../scripts/cc-ci/advisory-scan.SPEC.md \ No newline at end of file diff --git a/cc-ci-plan/advisory-scan.py b/cc-ci-plan/advisory-scan.py deleted file mode 100755 index a38e407..0000000 --- a/cc-ci-plan/advisory-scan.py +++ /dev/null @@ -1,1437 +0,0 @@ -#!/usr/bin/env python3 -"""Deterministic per-recipe CVE/advisory scan — an ADDITIVE pre-step for /recipe-upgrade. - -WHY THIS EXISTS (2026-08-10): gitea 1.27.1 fixed two CVSS-9.8 RCEs (CVE-2026-60004, -CVE-2026-59774). Our weekly report showed gitea's CVE count as "1", then "none". The upgrade -subagent had scanned the GitHub *release notes*, which mention neither; the two CVEs were announced -only in the vendor's blog security section. The report generator then derived security content from -those notes plus model knowledge — and the model's training predates the CVEs. Nothing in the -pipeline ever queried an advisory source, so a critical CVE that is newer than the model and absent -from the changelog was invisible by construction. - -WHAT IT DOES NOT DO: it does not replace or alter any existing security analysis. It is a strictly -ADDITIONAL evidence source whose findings are unioned into the CVE count. - -SOURCES (measured against the gitea case before being chosen): - 1. GitHub Security Advisories API — repos///security-advisories. PRIMARY: carries - CVE id, GHSA id, severity AND vulnerable/patched version ranges, so "fixed by THIS upgrade" is - computable rather than guessed. Found both gitea CVEs. Derived from the source-repo URLs the - per-recipe registry already records — no new per-recipe config needed. - 2. Vendor release/security pages — every URL in cc-ci-plan/upstream/.md, fetched and - regex-scanned for CVE ids. This is what would have caught gitea: the vendor blog names both, - while the GitHub releases page names neither. Add vendor security/announcement URLs to the - registry to widen this. - 3. OSV.dev — supplementary, best-effort, only when the recipe declares an ecosystem/package - mapping below. NOTE: for gitea, OSV returned only Go *dependency* advisories and 404'd on both - application CVEs; NVD's API had them neither by CPE, CVE id, nor keyword. Advisory databases - lag the vendor — which is exactly why (1) and (2) lead. - -Every source reports its own status, so "checked, none found" is never confused with "not checked". - -Usage: - advisory-scan.py [--from ] [--to ] [--json] [--registry DIR] - - --from/--to are the app versions being upgraded between (e.g. 1.26.2 -> 1.27.1). When given, each - advisory is classified fixed-by-this-upgrade / still-open / older. Without them everything known - is listed unclassified. Exits 0 even when sources fail (informational; failures are reported). -""" - -from __future__ import annotations - -import argparse -import gzip -import ipaddress -import json -import os -import re -import sys -import time -import urllib.error -import urllib.parse -import urllib.request - -REGISTRY_DIR = os.environ.get("CCCI_UPSTREAM_REGISTRY", "/srv/cc-ci/cc-ci-plan/upstream") -UA = "cc-ci-advisory-scan (+https://git.autonomic.zone/recipe-maintainers/cc-ci)" -TIMEOUT = int(os.environ.get("ADVISORY_SCAN_TIMEOUT", "45")) -CVE_RE = re.compile(r"CVE-\d{4}-\d{4,7}") -# Leading-version-component jump that means the scheme changed (semver → calver). -SCHEME_JUMP = 100 -# A patched_versions field that names no usable version. GitHub carries these verbatim from the -# vendor: redis publishes "TBD" for 11 advisories and "6.2.X, 7.2.X, 7.4.X" for another, and their -# vulnerable_version_range is open-ended ("All", ">= 7.0.0"), so the fix version is NOT recoverable. -# Such an advisory must be reported as INDETERMINATE, never silently counted as "not fixed" — that -# would assert an upgrade did not fix something we simply cannot judge. -PLACEHOLDER_RE = re.compile(r"\bTBD\b|\bunknown\b|\bnone\b|\d+\.[Xx]\b|\?", re.I) - -# Optional OSV mappings: recipe -> (ecosystem, package). Supplementary only (see module docstring). -OSV_PACKAGES: dict[str, tuple[str, str]] = { - "gitea": ("Go", "code.gitea.io/gitea"), - "n8n": ("npm", "n8n"), -} - - -def _github_token() -> str | None: - """Read-only GitHub token, for the API rate limit ONLY (60/hr anonymous → 5000/hr with a token). - - Env `GITHUB_TOKEN` wins; otherwise the file at `GITHUB_TOKEN_FILE` (default - /srv/cc-ci/.github-token, chmod 600, never in git). Reading PUBLIC security advisories needs NO - scopes at all — create a classic PAT with every box unticked, or a fine-grained token limited to - "Public repositories: read". Do NOT grant repo/write scopes: this tool only ever GETs advisories. - A missing token is not an error — the scan simply runs anonymously and will report sources as - failed once the 60/hr limit bites, which is visible rather than silent. - """ - tok = os.environ.get("GITHUB_TOKEN") - if tok: - return tok.strip() - path = os.environ.get("GITHUB_TOKEN_FILE", "/srv/cc-ci/.github-token") - try: - with open(path) as f: - return f.read().strip() or None - except OSError: - return None - - -def _gh_paginate(url: str, hdrs: dict, max_pages: int = 20): - """Yield every row from a GitHub list endpoint, following Link rel=\"next\" cursors.""" - seen_keys = set() - for _ in range(max_pages): - req = urllib.request.Request(url, headers={"User-Agent": UA, **hdrs}) - with urllib.request.urlopen(req, timeout=TIMEOUT) as r: - rows = json.load(r) - link = r.headers.get("Link", "") or "" - fresh = 0 - for a in rows: - k = a.get("ghsa_id") or json.dumps(a, sort_keys=True)[:120] - if k not in seen_keys: - seen_keys.add(k); fresh += 1 - yield a - nxt = None - for part in link.split(","): - if 'rel="next"' in part: - nxt = part.split(";")[0].strip().strip("<>") - if not nxt or fresh == 0: - return - url = nxt - - -def _tag_date(owner: str, repo: str, version: str | None) -> str | None: - """Publish date of a release tag, for DATE-BASED classification (see classify_by_date). - - Version strings cannot be ordered across a scheme change (semver → calver), but tag dates - always can. Tries the common tag spellings; returns an ISO timestamp or None.""" - if not version: - return None - hdrs = {"Accept": "application/vnd.github+json"} - tok = _github_token() - if tok: - hdrs["Authorization"] = f"Bearer {tok}" - for tag in (f"v{version}", version): - try: - ref = json.loads(_fetch(f"https://api.github.com/repos/{owner}/{repo}/git/ref/tags/{tag}", hdrs)) - obj = ref.get("object", {}) - sha, typ = obj.get("sha"), obj.get("type") - if typ == "tag": - t = json.loads(_fetch(f"https://api.github.com/repos/{owner}/{repo}/git/tags/{sha}", hdrs)) - if t.get("tagger", {}).get("date"): - return t["tagger"]["date"] - sha = t.get("object", {}).get("sha") - c = json.loads(_fetch(f"https://api.github.com/repos/{owner}/{repo}/commits/{sha}", hdrs)) - return c["commit"]["committer"]["date"] - except Exception: # noqa: BLE001 — try the next spelling - continue - return None - - -def _fetch(url: str, headers: dict | None = None) -> str: - h = {"User-Agent": UA, "Accept-Encoding": "gzip"} - h.update(headers or {}) - with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=TIMEOUT) as r: - raw = r.read() - if r.headers.get("Content-Encoding") == "gzip": - raw = gzip.decompress(raw) - return raw.decode(errors="replace") - - -def _vkey(v: str | None) -> tuple: - """Loose version ordering key: leading integers of each dot-part ('1.27.1-rootless' -> (1,27,1)).""" - if not v: - return () - v = v.strip().lstrip("vV").split("+")[0] - out = [] - for part in re.split(r"[.\-_]", v): - m = re.match(r"^\d+", part) - if m: - out.append(int(m.group())) - elif out: - break - return tuple(out) - - -def _nvd_affects(version: str | None, ranges: list[dict]) -> bool | None: - """Whether NVD marks a concrete image version affected; None means tag lacks precision.""" - current = _vkey(version) - if not current: - return None - uncertain = False - for row in ranges: - exact = _vkey(row.get("version")) if row.get("version") not in (None, "*") else () - bounds = [(name, _vkey(row.get(name))) for name in ( - "versionStartIncluding", "versionStartExcluding", - "versionEndIncluding", "versionEndExcluding") if row.get(name)] - versions = ([exact] if exact else []) + [value for _, value in bounds] - if any(not value for value in versions): - uncertain = True - continue - if any(len(value) > len(current) and value[:len(current)] == current for value in versions): - uncertain = True # e.g. postgres:13-alpine does not say which 13.x patch is running - continue - def compare(other): - length = max(len(current), len(other)) - return (current + (0,) * (length - len(current))) > (other + (0,) * (length - len(other))) - if exact and current != exact: - continue - def outside(name, value): - if name == "versionStartExcluding": - return not compare(value) - if name == "versionStartIncluding": - return not compare(value) and current != value - if name == "versionEndIncluding": - return compare(value) - return compare(value) or current == value # versionEndExcluding - if any(outside(name, value) for name, value in bounds): - continue - return True - return None if uncertain else False - - -def _already_fixed_on_from_line(kf: tuple, cands: list[tuple]) -> bool: - """Was it ALREADY fixed on the line we are upgrading FROM? - - The mirror image of _superseded_on_target_line, and just as necessary. mattermost fixes each CVE - across several maintained lines at once — CVE-2025-11794 is patched in 10.11.4, 10.12.1 and - 10.5.12. Upgrading 10.11.22 -> 10.12.4 crosses 10.12.1, so a naive window test counts it; but - 10.11.22 is already past 10.11.4, so the deployment HAD the fix before the upgrade. Counting it - credits the upgrade with work it did not do.""" - if len(kf) < 2: - return False - line = kf[:2] - for c in cands: - if len(c) < 2 or c[:2] != line: - continue - n = max(len(kf), len(c)) - pad = lambda z: z + (0,) * (n - len(z)) - if pad(c) <= pad(kf): - return True - return False - - -def _superseded_on_target_line(kt: tuple, cands: list[tuple]) -> bool: - """Does a patched version on the TARGET's own release line sit ABOVE the target? - - Projects maintain several branches at once and backport per branch, so "some patched version is - inside the numeric window" is not the same as "the version we land on has the fix". ClickHouse - fixed CVE-2023-48704 in 23.9.6.20 AND 23.10.5.20; an upgrade landing on 23.10.4.25 crosses the - 23.9 fix numerically but is still BELOW its own line's fix, so it does NOT have it. When the - advisory names a fix on the target's own line and the target is older than it, that is proof of - absence and outranks any other candidate.""" - if len(kt) < 2: - return False - line = kt[:2] - return any(c[:2] == line and c > kt for c in cands if len(c) >= 2) - - -def _within(kf: tuple, kt: tuple, c: tuple) -> bool: - """Is patched-version `c` inside the window (kf, kt] — exclusive lower, inclusive upper? - - Compares ZERO-PADDED to equal length, so "18" == "18.0" == "18.0.0" the way semver means it. - Without the padding, plain tuple order says (18,) < (18,0), i.e. a CVE patched in 18.0 falls - OUTSIDE a window ending at 18 — and bare major tags are the norm for sidecars (postgres:18, - redis:8-alpine), so that silently dropped real fixes. Padding also keeps the upper bound - conservative: a fix in 18.5 is still outside a window ending at "18", because nothing proves - which 18.x a floating tag resolved to. - """ - n = max(len(kf), len(kt), len(c)) - pad = lambda t: t + (0,) * (n - len(t)) - return pad(kf) < pad(c) <= pad(kt) - - -def registry_urls(recipe: str, registry_dir: str) -> tuple[list[str], str | None]: - path = os.path.join(registry_dir, f"{recipe}.md") - try: - with open(path) as f: - text = f.read() - except OSError: - return [], None - urls = [] - for u in re.findall(r"https?://[^\s)|\]]+", text): - # The registry is MARKDOWN: urls appear inside `backticks`, 'quotes', **bold**, and at the - # end of sentences. Trailing punctuation captured into the url makes the fetch 404 and the - # recipe render '?' for no real reason — that is what put immich and n8n in the unknown - # column on 2026-08-07 (https://docs.n8n.io/release-notes/` ← note the backtick). - u = u.rstrip("`'\"*.,;:>)") - if "…" in u or "..." in u: - continue # prose placeholder, not a fetchable security source - host = urllib.parse.urlsplit(u).hostname - if not host or host == "localhost" or "." not in host: - continue # a container/loopback URL in operational notes, not a public advisory source - try: - if not ipaddress.ip_address(host).is_global: - continue - except ValueError: - pass - if u and u not in urls: - urls.append(u) - return urls, path - - -def github_advisories(urls: list[str]) -> list[dict]: - """Query GitHub Security Advisories for every github.com// in the registry.""" - seen, results = set(), [] - for u in urls: - m = re.match(r"https?://github\.com/([^/]+)/([^/#?]+)", u) - if not m: - continue - owner, repo = m.group(1), m.group(2).removesuffix(".git") - if (owner, repo) in seen: - continue - seen.add((owner, repo)) - api = f"https://api.github.com/repos/{owner}/{repo}/security-advisories?per_page=100" - hdrs = {"Accept": "application/vnd.github+json"} - tok = _github_token() - if tok: - hdrs["Authorization"] = f"Bearer {tok}" - entry = {"source": f"github-advisories:{owner}/{repo}", "status": "ok", "advisories": []} - try: - # PAGINATE. This endpoint caps at 100 per response and IGNORES ?page= — it returns the - # same rows again, which silently truncates busy projects (discourse has 286; a hand - # count on 2026-08-10 found 123 CVEs in one upgrade window that a single page missed). - # Follow the Link rel="next" cursor to exhaustion instead. - for a in _gh_paginate(api, hdrs): - # An advisory carries ONE ENTRY PER PATCHED RELEASE LINE. n8n patches three - # (1.123.32, 2.17.4, 2.18.1); reading only vulnerabilities[0] silently dropped the - # line our deployment is actually on, so CVE-2026-42231/42232 classified as - # out-of-window. Keep them ALL and let the classifier match any of them. - vulns = a.get("vulnerabilities") or [] - entry["advisories"].append( - { - "cve": a.get("cve_id"), - "ghsa": a.get("ghsa_id"), - "severity": a.get("severity"), - "summary": (a.get("summary") or "")[:200], - "vulnerable_range": "; ".join( - filter(None, (v.get("vulnerable_version_range") for v in vulns)) - ) or None, - "patched": "; ".join( - filter(None, (v.get("patched_versions") for v in vulns)) - ) or None, - "url": a.get("html_url"), - "published_at": a.get("published_at"), - # The list response ALREADY carries the prose. Keep it: the adjudication - # pass needs it, and re-fetching per advisory costs a request each. - "description": (a.get("description") or "")[:4000], - "cvss": ((a.get("cvss") or {}).get("vector_string")), - } - ) - except urllib.error.HTTPError as e: - # 404 = this repo simply publishes no security advisories (e.g. sidecar images like - # pgautoupgrade). That is a BENIGN ABSENCE, not a failed check — conflating the two - # would push nearly every recipe to "unknown" and make the ? signal meaningless again. - entry["status"] = "no-advisories-published" if e.code == 404 else f"error: HTTP {e.code}" - except Exception as e: # noqa: BLE001 — a genuinely dead source must be REPORTED, never silent - entry["status"] = f"error: {type(e).__name__}: {e}" - results.append(entry) - return results - - -# Release headings in a vendor changelog. nginx's CHANGES uses "Changes with nginx 1.31.3", most -# markdown changelogs use "## 1.31.3" / "## v1.31.3". -_HEADING_RE = re.compile( - r"^\s*(?:#{1,4}\s*)?(?:Changes with\s+\S+\s+|Version\s+|Release\s+)?v?(\d+\.\d+(?:\.\d+)*)\s*$" - r"|^\s*Changes with\s+\S+\s+(\d+\.\d+(?:\.\d+)*)", re.I) - - -def _changelog_versions(text: str) -> dict: - """{cve: version} for a changelog that is ORGANISED BY RELEASE. - - Why this exists: nginx publishes NO GitHub security advisories. Every nginx CVE we can see comes - from nginx.org/en/CHANGES, and scraping ids out of it without attributing them to a release - leaves them with no patched version — so they can never be classified, and an nginx bump reports - 0 CVEs forever. nginx 1.31.1 -> 1.31.3 in fact fixes SIX (three in .2, three in .3), and nginx is - a sidecar in most of the fleet, so that was a fleet-wide blind spot. - - Attributes each CVE to the nearest PRECEDING release heading — the release that fixed it. - """ - plain = re.sub(r"<[^>]+>", " ", text) - out, cur = {}, None - for line in plain.splitlines(): - m = _HEADING_RE.match(line) - if m: - cur = m.group(1) or m.group(2) - continue - if cur: - for cve in CVE_RE.findall(line): - out.setdefault(cve, cur) - return out - - -_BLOB_RE = re.compile(r"^https://github\.com/([^/]+)/([^/]+)/blob/(.+)$") - - -def _raw_if_blob(url: str) -> str: - """A GitHub *blob* URL is an HTML viewer, not the file. - - The registry pointed ONLYOFFICE's CHANGELOG.md at its blob page. Fetching that returns 636KB of - markup in which the release headings do not survive HTML-stripping, so 24 CVEs were visible and - NONE attributable to a release — the same shape of blind spot as nginx. The raw URL attributes - all 24. Normalising here fixes every registry entry at once, present and future.""" - m = _BLOB_RE.match(url) - return f"https://raw.githubusercontent.com/{m.group(1)}/{m.group(2)}/{m.group(3)}" if m else url - - -def vendor_pages(urls: list[str]) -> list[dict]: - """Fetch each registry URL and regex out CVE ids, with a little surrounding context.""" - out = [] - for u in urls: - if u.startswith("https://api.github.com"): - continue - if re.search(r"[<>{}]|\bVERSION\b|\bvX\.Y\.Z\b", u): - # Registry entries sometimes carry TEMPLATE urls for humans - # (…/changelog/v/). They are documentation, not fetchable — skipping them is - # correct; counting them as failures would wrongly mark the recipe's count unreliable. - out.append({"source": u, "status": "skipped: template URL (not fetchable)", "cves": [], "context": {}}) - continue - entry = {"source": u, "status": "ok", "cves": [], "context": {}, "fixed_in": {}} - try: - text = _fetch(_raw_if_blob(u)) - plain = re.sub(r"<[^>]+>", " ", text) - for cve in sorted(set(CVE_RE.findall(plain))): - entry["cves"].append(cve) - i = plain.find(cve) - entry["context"][cve] = re.sub(r"\s+", " ", plain[max(0, i - 160) : i + 200]).strip() - entry["fixed_in"] = _changelog_versions(text) - except Exception as e: # noqa: BLE001 - entry["status"] = f"error: {type(e).__name__}: {e}" - out.append(entry) - return out - - -NVD_API = "https://services.nvd.nist.gov/rest/json/cves/2.0" -NVD_CPE_RE = re.compile(r"^\s*[-*]?\s*nvd-cpe:\s*(\S+)\s*=\s*(cpe:2\.3:[^\s`]+)", re.M | re.I) -_NVD_CACHE: dict[str, dict] = {} -COMMON_IMAGE_CPES = { - "postgres": "cpe:2.3:a:postgresql:postgresql:*:*:*:*:*:*:*:*", - "mariadb": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", - "mysql": "cpe:2.3:a:oracle:mysql:*:*:*:*:*:*:*:*", -} - - -def registry_cpes(recipe: str, registry_dir: str) -> list[tuple[str, str]]: - """Explicit CPEs plus common database CPEs for images listed in the registry table.""" - path = os.path.join(registry_dir, f"{recipe}.md") - try: - text = open(path).read() - except OSError: - return [] - out = [(m.group(1), m.group(2)) for m in NVD_CPE_RE.finditer(text)] - explicit = {key for key, _ in out} - for line in text.splitlines(): - if not line.startswith("|"): - continue - cells = [cell.strip().strip("`") for cell in line.strip().strip("|").split("|")] - if len(cells) < 2: - continue - image = cells[1].split("/")[-1].lower() - if image in COMMON_IMAGE_CPES and image not in explicit: - out.append((image, COMMON_IMAGE_CPES[image])) - explicit.add(image) - return out - - -def registry_image_sources(recipe: str, registry_dir: str) -> dict[str, set[str]]: - """Map image repo basenames to GitHub advisory sources from the registry table.""" - path = os.path.join(registry_dir, f"{recipe}.md") - try: - lines = open(path).read().splitlines() - except OSError: - return {} - out: dict[str, set[str]] = {} - for line in lines: - if not line.startswith("|"): - continue - cells = [cell.strip().strip("`") for cell in line.strip().strip("|").split("|")] - if len(cells) < 3: - continue - image = cells[1].split("/")[-1].lower() - match = re.search(r"https?://github\.com/([^/\s|]+)/([^/\s|)]+)", cells[2]) - if not match or image in ("image", "---", ""): - continue - source = f"github-advisories:{match.group(1)}/{match.group(2).removesuffix('.git')}" - out.setdefault(image, set()).add(source) - return out - - -def nvd_advisories(cpe: str, key: str) -> dict: - """CVEs for a CPE from NVD, with the version data the classifier needs. - - THE FALLBACK FOR PROJECTS THAT PUBLISH NOTHING MACHINE-READABLE. mattermost's GitHub advisory - feed is empty and its security bulletins are client-side rendered; mumble publishes neither. Both - scanned as `?` — nothing measured — until here. NVD is CPE-indexed and carries structured ranges: - - versionEndExcluding X -> fixed in X exactly (a patched version) - versionEndIncluding X -> affected up to and INCLUDING X, fixed in some later release. The - exact fix version is unknown, but the upgrade fixes it whenever it - crosses X — recorded as `affected_max` and judged in the classifier. - - NVD LAGS the vendor (it had neither gitea CVSS-9.8 RCE at publication), so this is a fallback, - never a replacement for 2a/2b. Unauthenticated calls are rate-limited to ~5/30s, hence the retry. - """ - if cpe in _NVD_CACHE: - return {**_NVD_CACHE[cpe], "source": f"nvd:{key}"} - entry = {"source": f"nvd:{key}", "status": "ok", "advisories": []} - url = f"{NVD_API}?resultsPerPage=2000&virtualMatchString={urllib.parse.quote(cpe)}" - data = None - for attempt in range(3): - try: - data = json.loads(_fetch(url)) - break - except Exception as e: # noqa: BLE001 - if attempt == 2: - entry["status"] = f"error: {type(e).__name__}" - return entry - time.sleep(8) - vulnerabilities = (data or {}).get("vulnerabilities", []) - if (data or {}).get("totalResults", len(vulnerabilities)) > len(vulnerabilities): - entry["status"] = "error: NVD result set truncated" - return entry - for v in vulnerabilities: - c = v.get("cve") or {} - cid = c.get("id") - if not cid or c.get("vulnStatus") == "Rejected": - continue - fixed, affected_max, affected_ranges = set(), set(), [] - cpe_product = ":".join(cpe.split(":")[:5]) + ":" - cpe_edition = cpe.split(":")[9] if len(cpe.split(":")) > 9 else "*" - for cfg in c.get("configurations", []): - for node in cfg.get("nodes", []): - for m in node.get("cpeMatch", []): - criteria = m.get("criteria") or "" - if not m.get("vulnerable") or not criteria.startswith(cpe_product): - continue - edition = criteria.split(":")[9] if len(criteria.split(":")) > 9 else "*" - if cpe_edition != "*" and edition not in (cpe_edition, "*"): - continue - affected_ranges.append({k: m.get(k) for k in ( - "versionStartIncluding", "versionStartExcluding", - "versionEndIncluding", "versionEndExcluding") if m.get(k)}) - affected_ranges[-1]["version"] = criteria.split(":")[5] - if m.get("versionEndExcluding"): - fixed.add(m["versionEndExcluding"]) - elif m.get("versionEndIncluding"): - affected_max.add(m["versionEndIncluding"]) - sev = None - for mk in ("cvssMetricV31", "cvssMetricV30", "cvssMetricV2"): - got = (c.get("metrics") or {}).get(mk) or [] - if got: - sev = (got[0].get("cvssData") or {}).get("baseSeverity") - break - entry["advisories"].append({ - "cve": cid, "ghsa": None, "severity": (sev or "").lower() or None, - "summary": next((d.get("value") for d in c.get("descriptions", []) - if d.get("lang") == "en"), "")[:200], - "vulnerable_range": None, - "patched": "; ".join(sorted(fixed)) or None, - "affected_max": "; ".join(sorted(affected_max)) or None, - "affected_ranges": affected_ranges or None, - "url": f"https://nvd.nist.gov/vuln/detail/{cid}", - "published_at": c.get("published"), "description": None, "cvss": None, - }) - _NVD_CACHE[cpe] = entry - return entry - - -def osv(recipe: str, version: str | None) -> dict | None: - pkg = OSV_PACKAGES.get(recipe) - if not pkg or not version: - return None - eco, name = pkg - entry = {"source": f"osv:{eco}/{name}@{version}", "status": "ok", "cves": []} - try: - body = json.dumps({"package": {"name": name, "ecosystem": eco}, "version": version}).encode() - req = urllib.request.Request( - "https://api.osv.dev/v1/query", data=body, - headers={"Content-Type": "application/json", "User-Agent": UA}, method="POST", - ) - with urllib.request.urlopen(req, timeout=TIMEOUT) as r: - data = json.load(r) - ids = set() - for v in data.get("vulns", []): - for a in [v.get("id")] + (v.get("aliases") or []): - if a and a.startswith("CVE"): - ids.add(a) - entry["cves"] = sorted(ids) - except Exception as e: # noqa: BLE001 - entry["status"] = f"error: {type(e).__name__}: {e}" - return entry - - -_RELEASE_CACHE: dict[str, list[tuple[str, str]]] = {} - - -def _releases(owner: str, repo: str, max_pages: int = 4) -> list[tuple[str, str]]: - """[(tag, body)] for a repo's GitHub releases, cached per repo for the process.""" - key = f"{owner}/{repo}" - if key in _RELEASE_CACHE: - return _RELEASE_CACHE[key] - hdrs = {"Accept": "application/vnd.github+json"} - tok = _github_token() - if tok: - hdrs["Authorization"] = f"Bearer {tok}" - out: list[tuple[str, str]] = [] - try: - for rel in _gh_paginate( - f"https://api.github.com/repos/{owner}/{repo}/releases?per_page=100", hdrs, max_pages - ): - out.append((rel.get("tag_name") or "", - f"{rel.get('name') or ''}\n{rel.get('body') or ''}")) - except Exception: # noqa: BLE001 — best effort; absence just leaves advisories undetermined - pass - _RELEASE_CACHE[key] = out - return out - - -def _source_repo(source: str) -> tuple[str, str] | None: - """(owner, repo) for a source, whether it is an advisory feed or a vendor page on GitHub. - - A CVE that appears ONLY on a vendor page still deserves the release-note method when that page - lives on GitHub — mailu announces its Roundcube CVEs on github.com/Mailu/Mailu/releases and - nowhere structured, so requiring an advisory feed sent a deterministic case to pass 2.""" - if source.startswith("github-advisories:"): - owner, _, repo = source.split(":", 1)[1].partition("/") - return (owner, repo) if owner and repo else None - m = re.match(r"https?://github\.com/([^/]+)/([^/#?]+)", source) - return (m.group(1), m.group(2).removesuffix(".git")) if m else None - - -def release_fix_versions(source: str, cve: str) -> list[str]: - """Release tags whose notes NAME this CVE — a deterministic fix version when the advisory has none. - - Vendors routinely publish an advisory with `patched_versions: "TBD"` and then name the CVE in the - release notes of every branch that got the fix. redis does exactly this: all 12 of its advisories - that discourse's redis bump crosses carry TBD, yet each is named in concrete releases - (CVE-2025-32023 → 6.2.19, 7.2.10, 7.4.5, 8.0.3, 8.2.0). Ignoring that evidence undercounted - discourse by 12 CVEs, so this is checked BEFORE giving up on an advisory. - """ - ref = _source_repo(source) - if not ref: - return [] - return [tag for tag, body in _releases(*ref) if cve in body] - - -def advisory_text(ghsa: str, source: str | None = None) -> dict: - """Full text of one advisory, for the ADJUDICATION pass (see adjudication_block). - - The structured `patched_versions` field is often "TBD" while the prose description and the - linked references DO state where the fix landed. That prose is not machine-parseable in general - — which is the point: it is collected here for a MODEL to judge, not for a regex.""" - hdrs = {"Accept": "application/vnd.github+json"} - tok = _github_token() - if tok: - hdrs["Authorization"] = f"Bearer {tok}" - out = {"ghsa": ghsa, "status": "ok"} - # Repo-scoped FIRST. Many repository advisories are never mirrored into the global GitHub - # Advisory Database, so /advisories/ 404s for them (all 12 redis ones, for instance) - # while /repos///security-advisories/ returns the full record. - cands = [] - if source and source.startswith("github-advisories:"): - cands.append(f"https://api.github.com/repos/{source.split(':',1)[1]}/security-advisories/{ghsa}") - cands.append(f"https://api.github.com/advisories/{ghsa}") - try: - a, last = None, None - for u in cands: - try: - a = json.loads(_fetch(u, hdrs)); break - except Exception as ex: # noqa: BLE001 — try the next endpoint - last = ex - if a is None: - raise last or RuntimeError("no advisory endpoint responded") - out.update({ - "summary": a.get("summary"), - "description": (a.get("description") or "")[:4000], - "severity": a.get("severity"), - "published_at": a.get("published_at"), - "references": [r for r in (a.get("references") or [])][:12] or ( - [a.get("html_url")] if a.get("html_url") else []), - "cvss": (a.get("cvss") or {}).get("vector_string"), - "vulnerabilities": [ - {"package": (v.get("package") or {}).get("name"), - "vulnerable_version_range": v.get("vulnerable_version_range"), - "first_patched_version": v.get("first_patched_version")} - for v in (a.get("vulnerabilities") or []) - ], - }) - except Exception as e: # noqa: BLE001 - out["status"] = f"error: {type(e).__name__}: {e}" - return out - - -MAX_ADJUDICATE = int(os.environ.get("ADVISORY_SCAN_MAX_ADJUDICATE", "25")) -# Compact review rows for advisories pass 1 DID decide. Pass 2 sees these too, so a wrong -# deterministic verdict can be caught rather than inherited. -MAX_REVIEW_ROWS = int(os.environ.get("ADVISORY_SCAN_MAX_REVIEW", "400")) - - -def needs_judgement(rep: dict) -> list[str]: - """CVEs the deterministic pass could not decide — the input set for the adjudication pass. - - Two kinds, both real gaps rather than noise: - 1. INDETERMINATE — from an image WITH a window, but no fix version is knowable (advisory says - `TBD`/`7.4.X`, range is open-ended, and no release note names it). - 2. VENDOR-PAGE-ONLY — a CVE seen only on a vendor security page, with no structured advisory - behind it at all. gitea's two CVSS-9.8 RCEs are this shape. They carry no version data, so - no arithmetic can place them, but the page's prose usually states the fixed release. - """ - windows = rep.get("windows") or {} - out = list(rep.get("indeterminate") or []) - for cve in rep.get("unclassified") or []: - srcs = rep["cves"][cve]["sources"] - if not any(s.startswith("github-advisories:") for s in srcs) and cve not in out: - out.append(cve) - return sorted(out) - - -def evidence_bundle(rep: dict, cve: str) -> dict: - """EVERY deterministic signal held about one CVE, gathered for a model to weigh. - - Pass 1 collects; pass 2 judges. Nothing here interprets — it assembles what was measured, so the - judgement is made against evidence rather than recollection (the exact failure that let two - CVSS-9.8 gitea RCEs be published as "none": the report leaned on model knowledge that predated - them, and no source had been queried at all). - """ - e = rep["cves"][cve] - src = e["sources"][0] - windows = rep.get("windows") or {} - win = next((windows[s] for s in e["sources"] if s in windows), None) - ev = { - "cve": cve, - "severity": e.get("severity"), - "cvss": e.get("cvss"), - "sources": e["sources"], - "window": win, - "why_undecided": ("no fix version published and no release note names it" - if cve in (rep.get("indeterminate") or []) - else "seen only on a vendor page — no structured advisory, no version data"), - "patched_as_published": e.get("patched"), - "vulnerable_range_as_published": e.get("vulnerable_range"), - "summary": e.get("context"), - "description": e.get("description"), - "advisory_url": e.get("url"), - # Release tags NAMING this CVE, whether or not they fall in the window — the model may - # reason about branch lines the arithmetic deliberately would not. - "releases_naming_it": release_fix_versions(src, cve) if src.startswith("github-advisories:") else [], - "references": [], - } - if e.get("ghsa"): - t = advisory_text(e["ghsa"], src) - if t.get("status") == "ok": - ev["references"] = t.get("references") or [] - ev["description"] = t.get("description") or ev["description"] - ev["summary"] = t.get("summary") or ev["summary"] - ev["affected"] = t.get("vulnerabilities") or [] - else: - ev["detail_fetch"] = t.get("status") - return ev - - -def adjudication_block(rep: dict) -> str: - """SECOND PASS: present the collected evidence and ask for a judgement on each open case. - - This block decides nothing. The deterministic count stands as a FLOOR; a verdict here may only - ADD to it, matching the rule that this scan raises a count on evidence but never lowers one. - """ - todo = needs_judgement(rep) - if not todo: - return "" - shown, dropped = todo[:MAX_ADJUDICATE], max(0, len(todo) - MAX_ADJUDICATE) - L = ["", "---", "", - f"## Adjudication pass — {len(todo)} advisory/advisories need judgement", "", - "Pass 1 collected the evidence below deterministically and could NOT decide these cases. " - "Weigh the evidence and decide each one.", "", - "**For each: did the version move in its window fix it?** Answer **FIXED** / **NOT-FIXED** / " - "**STILL-UNKNOWN**, each with a one-line reason **citing the evidence shown** — a fixed " - "release named in the text, a branch line, an affected range. Add every FIXED to the " - "recipe's CVE count; the deterministic number is a floor, not a total. If the evidence does " - "not settle it, say STILL-UNKNOWN: do NOT infer from memory of the project, and never " - "record an undecided CVE as unaffected.", ""] - for src, win in (rep.get("windows") or {}).items(): - L.append(f"- window: `{src.split(':',1)[-1]}` {win['from']} → {win['to']}") - if dropped: - L += ["", f"⚠ Showing the first {MAX_ADJUDICATE} of {len(todo)}; **{dropped} not shown** " - f"(raise ADVISORY_SCAN_MAX_ADJUDICATE). The unshown remain undetermined — do not " - f"treat them as absent."] - L.append("") - for cve in shown: - ev = evidence_bundle(rep, cve) - L.append(f"### {cve} — {ev['severity'] or '?'}") - L.append(f"- undecided because: {ev['why_undecided']}") - L.append(f"- source: `{ev['sources'][0]}`" - + (f" · window {ev['window']['from']} → {ev['window']['to']}" if ev["window"] else - " · **no version window** for this image")) - L.append(f"- patched_versions as published: `{ev['patched_as_published']}`") - L.append(f"- vulnerable_range as published: `{ev['vulnerable_range_as_published']}`") - if ev["releases_naming_it"]: - L.append(f"- **releases naming this CVE**: {', '.join(ev['releases_naming_it'][:14])}") - for v in ev.get("affected") or []: - L.append(f"- affects `{v.get('package')}` {v.get('vulnerable_version_range')} — " - f"first_patched_version: {v.get('first_patched_version')}") - if ev["references"]: - L.append(f"- references: {', '.join(r.strip() for r in ev['references'][:6])}") - if ev.get("detail_fetch"): - L.append(f"- ⚠ detail fetch failed: {ev['detail_fetch']} (evidence below is from pass 1)") - if ev["summary"]: - L += ["", f"> {ev['summary']}"] - if ev["description"]: - L += ["", "```", (ev["description"] or "").strip()[:2000], "```"] - L.append("") - - # ── everything pass 1 DID decide, with the evidence behind each verdict ────────────────────── - # Pass 2 must see the whole picture, not only the leftovers: a deterministic verdict can still - # be wrong (a mis-parsed range, a release note that names a CVE without fixing it), and only a - # reader with the evidence in front of it can catch that. - decided = [] - for cve in rep.get("fixed_by_this_upgrade") or []: - e = rep["cves"][cve] - decided.append((cve, "COUNTED", e)) - for cve, e in sorted(rep.get("cves", {}).items()): - if e.get("classification") == "outside-window": - decided.append((cve, "excluded (outside window)", e)) - if decided: - shown_rows, dropped_rows = decided[:MAX_REVIEW_ROWS], max(0, len(decided) - MAX_REVIEW_ROWS) - L += ["---", "", - f"## Pass 1 decisions — {len(decided)} already judged deterministically", "", - "Review these too. If any verdict looks wrong given its evidence, say so and explain; " - "a correction here changes the count. Silence means you agree.", ""] - if dropped_rows: - L.append(f"⚠ Showing {MAX_REVIEW_ROWS} of {len(decided)}; **{dropped_rows} not shown** " - f"(raise ADVISORY_SCAN_MAX_REVIEW).") - L.append("") - L += ["| CVE | verdict | severity | patched as published | releases naming it | source |", - "|---|---|---|---|---|---|"] - for cve, verdict, e in shown_rows: - rel = e.get("fix_versions_from_release_notes") or [] - L.append(f"| {cve} | {verdict} | {e.get('severity') or '?'} | " - f"{(e.get('patched') or '—')[:60]} | {', '.join(rel[:5]) or '—'} | " - f"{e['sources'][0].split(':',1)[-1]} |") - L.append("") - return "\n".join(L) - - -def scan(recipe: str, v_from: str | None, v_to: str | None, registry_dir: str, - images: list[tuple[str, str, str]] | None = None) -> dict: - urls, reg_path = registry_urls(recipe, registry_dir) - report: dict = { - "recipe": recipe, - "from": v_from, - "to": v_to, - "registry": reg_path, - "registry_urls": len(urls), - "sources": [], - "cves": {}, - } - if reg_path is None: - report["sources"].append( - {"source": f"registry:{recipe}.md", "status": "error: registry file not found"} - ) - - def record(cve: str, src: str, **extra): - e = report["cves"].setdefault(cve, {"sources": [], "severity": None, "ghsa": None, - "vulnerable_range": None, "patched": None, - "context": None, "published_at": None, - "description": None, "url": None, "cvss": None, - "changelog_fixed_in": None, "affected_max": None, - "affected_ranges": None}) - if src not in e["sources"]: - e["sources"].append(src) - for k, v in extra.items(): - if v and not e.get(k): - e[k] = v - - for entry in github_advisories(urls): - report["sources"].append({"source": entry["source"], "status": entry["status"], - "found": len(entry.get("advisories", []))}) - for a in entry.get("advisories", []): - advisory_id = a.get("cve") or a.get("ghsa") - if advisory_id: - record(advisory_id, entry["source"], severity=a.get("severity"), ghsa=a.get("ghsa"), - vulnerable_range=a.get("vulnerable_range"), patched=a.get("patched"), - context=a.get("summary"), published_at=a.get("published_at"), - description=a.get("description"), url=a.get("url"), cvss=a.get("cvss")) - - for key, cpe in registry_cpes(recipe, registry_dir): - entry = nvd_advisories(cpe, key) - report["sources"].append({"source": entry["source"], "status": entry["status"], - "found": len(entry.get("advisories") or [])}) - for a in entry.get("advisories", []): - record(a["cve"], entry["source"], severity=a.get("severity"), - patched=a.get("patched"), affected_max=a.get("affected_max"), - affected_ranges=a.get("affected_ranges"), - context=a.get("summary"), published_at=a.get("published_at"), - url=a.get("url")) - - for entry in vendor_pages(urls): - report["sources"].append({"source": entry["source"], "status": entry["status"], - "found": len(entry.get("cves", []))}) - for cve in entry.get("cves", []): - record(cve, entry["source"], context=entry["context"].get(cve), - changelog_fixed_in=(entry.get("fixed_in") or {}).get(cve)) - - for version in filter(None, (v_from, v_to)): - o = osv(recipe, version) - if o: - report["sources"].append({"source": o["source"], "status": o["status"], - "found": len(o.get("cves", []))}) - for cve in o.get("cves", []): - record(cve, o["source"]) - - # Classify against the upgrade window when we know it: an advisory is "fixed by this upgrade" - # when its patched version is newer than `from` and no newer than `to`. - # - # TWO HARD-WON CONSTRAINTS (2026-08-10, discourse reported a false 133): - # a) The window belongs to ONE image. Advisories from OTHER repos in the registry (redis, - # postgres, nginx sidecars) must NOT be judged by it — redis CVE-2021-21309, patched in - # redis 6.0.11, scored as "fixed" because 6.0.11 sits numerically inside discourse's - # 3.5.3 → 2026.7.1 window. Only the PRIMARY app repo is classified; every other source is - # reported as unclassified so a human/agent still sees it but it never inflates the count. - # b) A version-SCHEME change (semver → calver, 3.5.3 → 2026.7.1) makes numeric ordering - # meaningless: 2025.12.2 compares "newer" than 3.5.3 while shipping earlier. When the - # leading component jumps by more than SCHEME_JUMP we refuse to classify and say so, - # rather than emitting a confident wrong number. - # ── Classification ──────────────────────────────────────────────────────────────────────── - # A recipe upgrades SEVERAL images (app + redis/postgres/nginx sidecars), each with its OWN - # version window. Judging every advisory by the app's window is how discourse once reported a - # false 133 (34 of them redis CVEs, incl. one patched in redis 6.0.11 in 2021). So each source - # is classified against ITS OWN window, and the count is the union across windows. - # - # --from/--to → the PRIMARY app repo (first github source in the registry) - # --image NAME=FROM:TO → any other source whose name contains NAME (repeatable), - # e.g. --image redis=7.4:8.10 - # - # A source with no window is not classified: its advisories are listed as unclassified so they - # stay visible without inflating the count. - gh_sources = [x["source"] for x in report["sources"] - if x["source"].startswith(("github-advisories:", "nvd:"))] - primary = gh_sources[0] if (gh_sources and (v_from or v_to)) else None - report["primary_source"] = primary - - windows = {} # source name -> (from, to) - window_key = {} # source name -> the image name it covers - if primary: - windows[primary] = (v_from, v_to) - window_key[primary] = primary.split("/")[-1] - # The app's window must also cover its NVD entry. NVD sources are keyed by IMAGE name - # (`mattermost-team-edition`) while the advisory feed is keyed by REPO (`mattermost/ - # mattermost`), so without this the fallback source that exists precisely because the feed - # is empty would itself go unwindowed — and mumble/mattermost would still report nothing. - pname = primary.split("/")[-1].lower() - for src in gh_sources: - if src.startswith("nvd:") and src not in windows: - k = src.split(":", 1)[1].lower() - if pname in k or k in pname: - windows[src] = (v_from, v_to) - window_key[src] = k - image_sources = registry_image_sources(recipe, registry_dir) - for key, wf, wt in (images or []): - matched = False - explicit = image_sources.get(key.lower(), set()) - for src in gh_sources: - # Match BOTH ways: an image name is often longer than its source repo - # (`clickhouse/clickhouse-server` vs source `ClickHouse/ClickHouse`) and sometimes - # shorter (`redis` vs `redis/redis`). One-directional matching silently dropped the - # clickhouse window when the key was derived from a compose file. - k, name = key.lower(), src.split("/")[-1].lower() - if src in explicit or k in src.lower() or name in k: - if src in windows: - matched |= windows[src] == (wf, wt) - continue # two images in one monorepo share a source and version window - windows[src] = (wf, wt) - window_key[src] = key - matched = True - if not matched: - report.setdefault("unmatched_image_windows", []).append(key) - report["windows"] = {k: {"from": f, "to": t} for k, (f, t) in windows.items()} - - def _classify_window(src, wf, wt): - """Return (fixed, method, date_window|None, unresolved, indeterminate) for one source. - - `indeterminate` = advisories from this source that the method COULD NOT JUDGE (no usable - patched version, or no publish date). They are neither counted nor dismissed.""" - if src.startswith("nvd:"): - got, undecidable = set(), set() - for advisory, evidence in report["cves"].items(): - if src not in evidence["sources"]: - continue - if not evidence.get("affected_ranges"): - undecidable.add(advisory) - continue - old = _nvd_affects(wf, evidence["affected_ranges"]) - new = _nvd_affects(wt, evidence["affected_ranges"]) - if old is True and new is False: - got.add(advisory) - elif old is None or (old is True and new is None): - undecidable.add(advisory) - return got, "NVD affected-version ranges", None, False, undecidable - kf, kt = _vkey(wf), _vkey(wt) - # A version-SCHEME change (semver 3.5.3 → calver 2026.7.1) makes numeric ordering - # meaningless: 2025.12.2 compares "newer" than 3.5.3 while shipping earlier. - scheme = bool(kf and kt and abs(kt[0] - kf[0]) >= SCHEME_JUMP) - if not scheme: - got, undecidable = set(), set() - for cve, e in report["cves"].items(): - if src not in e["sources"]: - continue - patched = e.get("patched") or "" - cands = [_vkey(t) for t in re.findall(r"\d+(?:\.\d+)*", patched)] - # NEVER on a placeholder: "7.4.X" parses to the bare 7.4, which then reads as - # "already fixed at 7.4" and silently drops a real fix (redis CVE-2024-46981). - # A placeholder means the fix version is unknown — that is the indeterminate path. - if (kf and kt and not PLACEHOLDER_RE.search(patched) - and _already_fixed_on_from_line(kf, cands)): - # already had it before the upgrade - e.setdefault("classification", "outside-window") - continue - if kf and kt and _superseded_on_target_line(kt, cands): - # The target's own line got the fix LATER than the target: not fixed here. - e.setdefault("classification", "outside-window") - continue - if kf and kt and any(_within(kf, kt, c) for c in cands): - got.add(cve) - elif kf and kt and e.get("affected_max"): - # NVD's `versionEndIncluding X`: affected up to and INCLUDING X, fixed in some - # later release. The exact fix version is unpublished, but the upgrade delivers - # it whenever it crosses X — i.e. from <= X < to. - for t in re.findall(r"\d+(?:\.\d+)*", e["affected_max"]): - x = _vkey(t) - n = max(len(kf), len(kt), len(x)) - pad = lambda z: z + (0,) * (n - len(z)) - if x and pad(kf) <= pad(x) < pad(kt): - got.add(cve) - break - elif not patched or PLACEHOLDER_RE.search(patched): - # No fix version published ("TBD") or only a placeholder ("7.4.X" — which could - # be 7.4.1, inside the window). We cannot say either way, so say so. - undecidable.add(cve) - return got, "patched version ranges", None, False, undecidable - # DATE FALLBACK: release DATES always order, even across a scheme change. Resolve both - # versions to git tag dates and count advisories PUBLISHED in that window — the method a - # hand count used to establish discourse 3.5.3 (2025-12-30) → 2026.7.1 (2026-07-31) = 123. - owner, _, repo = src.split(":", 1)[1].partition("/") - d_from, d_to = _tag_date(owner, repo, wf), _tag_date(owner, repo, wt) - if d_from and d_to and d_from < d_to: - got = {cve for cve, e in report["cves"].items() - if src in e["sources"] and e.get("published_at") - and d_from < e["published_at"] <= d_to} - undecidable = {cve for cve, e in report["cves"].items() - if src in e["sources"] and not e.get("published_at")} - return got, "advisory publish date (version scheme changed)", (d_from, d_to), False, undecidable - return set(), "unresolved", None, True, set() - - fixed_set, methods, date_windows, unresolved_any = set(), {}, {}, False - indeterminate: set = set() - for src, (wf, wt) in windows.items(): - got, method, dw, unresolved, undecidable = _classify_window(src, wf, wt) - indeterminate |= undecidable - methods[src] = method - if dw: - date_windows[src] = {"from": dw[0], "to": dw[1]} - if unresolved: - unresolved_any = True - for cve in got: - report["cves"][cve]["classification"] = f"fixed-by-this-upgrade ({method}) via {src}" - fixed_set.add(cve) - - # A CVE seen only in a vendor CHANGELOG has no advisory feed behind it, but the changelog says - # which release fixed it (see _changelog_versions). Tie it to a window by the image name - # appearing in the page URL — nginx's window is `nginx`, and its changelog is nginx.org/... . - # Without this, projects that publish no GitHub advisories (nginx being the big one) can never - # contribute a CVE, and every nginx bump in the fleet silently reports 0. - from_changelog = {} - for cve, e in report["cves"].items(): - if cve in fixed_set or not e.get("changelog_fixed_in"): - continue - for src, (wf, wt) in windows.items(): - key = (window_key.get(src) or "").lower() - if not key: - continue - if not any(key in s_.lower() for s_ in e["sources"] if s_.startswith("http")): - continue - kf, kt = _vkey(wf), _vkey(wt) - cand = _vkey(e["changelog_fixed_in"]) - if kf and kt and cand and _within(kf, kt, cand): - e["classification"] = (f"fixed-by-this-upgrade (named under {e['changelog_fixed_in']} " - f"in the vendor changelog) via {src}") - fixed_set.add(cve) - from_changelog[cve] = e["changelog_fixed_in"] - break - if from_changelog: - report["resolved_by_changelog"] = from_changelog - - unknown = [] - for cve, e in report["cves"].items(): - if cve in fixed_set: - continue - if not any(src in e["sources"] for src in windows): - e["classification"] = "unclassified: no versions given for this image" - unknown.append(cve) - else: - e.setdefault("classification", "outside-window") - if e["classification"] == "outside-window": - pass - else: - unknown.append(cve) - - report["classified_by"] = methods - if date_windows: - report["date_window"] = date_windows - # THIRD METHOD: before declaring an advisory undecidable, look for the CVE id in the project's - # own release notes. A tag that names it, inside the window, IS the fix version the advisory - # failed to publish. Deterministic and citable — not a judgement call. - # A window is keyed by advisory-feed source; map it to its repo so a vendor page on the SAME - # repo can be judged by the same window. - win_by_repo = {} - for wsrc, wv in windows.items(): - ref = _source_repo(wsrc) - if ref: - win_by_repo[ref] = wv - resolved_by_release, already_fixed = {}, set() - candidates = set(indeterminate) | { - c for c in unknown - if not any(s in windows for s in report["cves"][c]["sources"]) - and any(_source_repo(s) in win_by_repo for s in report["cves"][c]["sources"]) - } - for cve in sorted(candidates - fixed_set): - e = report["cves"][cve] - for src in e["sources"]: - ref = _source_repo(src) - if src not in windows and ref not in win_by_repo: - continue - wf, wt = windows[src] if src in windows else win_by_repo[ref] - kf, kt = _vkey(wf), _vkey(wt) - if not (kf and kt): - continue - naming = release_fix_versions(src, cve) - hits = [t for t in naming if _within(kf, kt, _vkey(t))] - if hits: - fixed_set.add(cve) - resolved_by_release[cve] = sorted(hits) - e["classification"] = (f"fixed-by-this-upgrade (named in release notes " - f"{', '.join(sorted(hits))}) via {src}") - e["fix_versions_from_release_notes"] = sorted(hits) - break - # Naming releases exist but ALL predate the version we were already on: the fix shipped - # before this upgrade, so the upgrade did not deliver it. That is a DECISION, not an - # unknown — mailu's redis 8.8.0 → 8.10.0 crosses 12 advisories all fixed by 8.6.3 or - # earlier, and reporting them as "could not judge" overstates the uncertainty. - if naming and all(_vkey(t) and not _within(kf, kt, _vkey(t)) for t in naming) \ - and max(_vkey(t) for t in naming if _vkey(t)) <= kf: - e["classification"] = ("outside-window: fixed in " - f"{', '.join(sorted(naming))}, all at or before {wf}") - e["fix_versions_from_release_notes"] = sorted(naming) - already_fixed.add(cve) - break - if resolved_by_release: - report["resolved_by_release_notes"] = resolved_by_release - - indeterminate -= fixed_set | already_fixed - if already_fixed: - report["already_fixed_before_upgrade"] = sorted(already_fixed) - for cve in indeterminate: - report["cves"][cve]["classification"] = "indeterminate: no fix version published" - unknown = [c for c in unknown if c not in fixed_set] - report["fixed_by_this_upgrade"] = sorted(fixed_set) - report["fixed_non_cve_advisories"] = sorted(x for x in fixed_set if not x.startswith("CVE-")) - report["indeterminate"] = sorted(indeterminate) - report["cve_count_indeterminate"] = len(indeterminate) - report["unclassified"] = sorted(unknown) - # NEVER report 0 for something we could not determine — a 0 asserts safety. If ANY requested - # window could not be ordered at all, the total is UNKNOWN rather than a partial number. - # A scan with NO usable source has not measured anything, so it must not report a number — - # least of all 0, which asserts safety. mumble had no cc-ci-plan/upstream/mumble.md at all and - # still produced "0 identified", which was then published as a clean 0 in a CVE report. - usable_sources = [s for s in report["sources"] if s["status"] == "ok"] - no_sources = not usable_sources - if no_sources: - report["no_usable_sources"] = True - report["sources_failed"] = [ - s["source"] - for s in report["sources"] - if not (s["status"] == "ok" or s["status"].startswith(("no-advisories-published", "skipped:"))) - ] - coverage_failed = bool(report.get("unmatched_image_windows")) or bool(v_from and not primary) - report["count_known"] = not unresolved_any and not no_sources and not coverage_failed and not report["sources_failed"] - report["cve_count_fixed"] = (sum(x.startswith("CVE-") for x in fixed_set) - if report["count_known"] else None) - report["cve_count_total_seen"] = sum(x.startswith("CVE-") for x in report["cves"]) - # Only GENUINE failures make a count unreliable. "no-advisories-published" (404: the repo has - # no advisory feed) and "skipped: template URL" are benign and must not degrade the verdict. - report["sources_benign"] = [ - s["source"] - for s in report["sources"] - if s["status"].startswith(("no-advisories-published", "skipped:")) - ] - return report - - -def markdown(rep: dict) -> str: - """Human/agent-readable block for pasting into the per-recipe upgrade log.""" - L = [f"### Advisory scan (deterministic pre-step) — {rep['recipe']} " - f"{rep.get('from') or '?'} → {rep.get('to') or '?'}"] - if not rep.get("count_known", True): - L.append("\n**CVEs fixed by this upgrade: UNKNOWN — the scan could NOT determine a count.**") - if rep.get("fixed_by_this_upgrade"): - L.append(f"\nAt least {len(rep['fixed_by_this_upgrade'])} fixed advisory/advisories were identified: " - + ", ".join(rep["fixed_by_this_upgrade"][:15])) - if rep.get("no_usable_sources"): - L.append("\n⚠ This is NOT zero. **No usable source was checked at all** — the registry " - "file `cc-ci-plan/upstream/.md` is missing or every source failed, so " - "nothing was measured. Render this recipe's cve cell as `?`, never `0`, and add " - "the registry file.") - else: - L.append("\n⚠ This is NOT zero. At least one version window or advisory source could " - "not be checked completely. Render this recipe's cve cell as `?`, never `0`.") - if rep.get("unmatched_image_windows"): - L.append("\n⚠ image windows with no matching advisory source: " - + ", ".join(rep["unmatched_image_windows"])) - if rep["unclassified"]: - L.append(f"\nAdvisories seen but unclassifiable ({len(rep['unclassified'])}) — includes " - f"other images in this recipe: " + ", ".join(rep["unclassified"][:12])) - if rep["sources_failed"]: - L.append(f"\n⚠ sources that FAILED: {', '.join(rep['sources_failed'])}") - L.append(f"\n_Sources checked: {len(rep['sources'])} ({rep['registry_urls']} registry URLs + " - f"advisory APIs). This scan is ADDITIVE — it does not replace the release-note " - f"reading in the upgrade step._") - return "\n".join(L) - ind = rep.get("cve_count_indeterminate") or 0 - fixed_cves = [x for x in rep["fixed_by_this_upgrade"] if x.startswith("CVE-")] - if fixed_cves: - floor = " (at least — see undetermined below)" if ind else "" - L.append(f"\n**CVEs fixed by this upgrade: {rep['cve_count_fixed']}**{floor}\n") - cb = rep.get("classified_by") or {} - if isinstance(cb, dict) and cb: - for src, method in cb.items(): - dw = (rep.get("date_window") or {}).get(src) - win = (rep.get("windows") or {}).get(src, {}) - span = f"{win.get('from')} → {win.get('to')}" - extra = (f" (dates {dw['from'][:10]} → {dw['to'][:10]})" if dw else "") - L.append(f"_{src.split(':',1)[-1]}: {span} — counted by {method}{extra}._") - L.append("") - L.append("| CVE | severity | fixed in | advisory | source |") - L.append("|---|---|---|---|---|") - for cve in fixed_cves: - e = rep["cves"][cve] - L.append(f"| {cve} | {e.get('severity') or '?'} | {e.get('patched') or '?'} | " - f"{e.get('ghsa') or '-'} | {e['sources'][0]} |") - else: - L.append("\n**CVEs fixed by this upgrade: 0 identified by the deterministic scan.**") - if rep.get("fixed_non_cve_advisories"): - L.append("\n**Security advisories fixed without CVE IDs: " - + str(len(rep["fixed_non_cve_advisories"])) + "** — " - + ", ".join(rep["fixed_non_cve_advisories"][:15]) - + ". In the report CVEs column, use YES when the CVE count is zero.") - if ind: - L.append(f"\n⚠ **{ind} advisory/advisories could NOT be judged** — the vendor published no fix " - f"version (GitHub carries `TBD` or a placeholder like `7.4.X`) and the vulnerable " - f"range is open-ended, so neither method can tell whether this upgrade fixed them. " - f"They are NOT included in the count above and must NOT be read as unaffected: " - + ", ".join(f"{c} ({rep['cves'][c].get('severity') or '?'})" - for c in rep["indeterminate"][:15]) - + (" …" if len(rep["indeterminate"]) > 15 else "") - + "\n\nRe-run with `--adjudicate` for the collected evidence on each, to judge.") - if rep["unclassified"]: - L.append(f"\nSeen but not version-classified ({len(rep['unclassified'])}) — includes advisories " - f"from OTHER images in this recipe (sidecars), which this window cannot judge: " - + ", ".join(rep["unclassified"][:12])) - if rep["sources_failed"]: - L.append(f"\n⚠ sources that FAILED (treat counts as incomplete): {', '.join(rep['sources_failed'])}") - L.append(f"\n_Sources checked: {len(rep['sources'])} " - f"({rep['registry_urls']} registry URLs + advisory APIs). This scan is ADDITIVE — it does " - f"not replace the release-note reading in the upgrade step._") - return "\n".join(L) - - -def _gitea_auth(url: str) -> dict: - """Basic auth for the private mirror, using public config plus .testenv. - - Sent as a HEADER, never embedded in the URL: in-URL credentials leak into shell history, process - lists and error messages, and urllib mis-parses a password containing a colon.""" - host = re.sub(r"^https?://", "", url).split("/")[0] - env = {} - for path in ( - "/srv/cc-ci/cc-ci/.env.public", - os.environ.get("CCCI_TESTENV", "/srv/cc-ci/.testenv"), - ): - try: - lines = open(path) - except OSError: - continue - for ln in lines: - if "=" in ln and not ln.strip().startswith("#"): - k, v = ln.strip().split("=", 1) - env[k] = v.strip().strip("\"'") - if host != env.get("GITEA_URL", "git.autonomic.zone"): - return {} - u, pw = env.get("GITEA_USERNAME"), env.get("GITEA_PASSWORD") - if not (u and pw): - return {} - import base64 as _b64 - return {"Authorization": "Basic " + _b64.b64encode(f"{u}:{pw}".encode()).decode()} - - -def _compose_images(url: str) -> dict[str, tuple[str, str]]: - """{service: (image-repo, tag)} for a compose file. - - Keyed by SERVICE, not by image repo, because an upgrade may change the repo itself: plausible - moved `plausible/analytics` -> `ghcr.io/plausible/community-edition`. Keyed by repo that reads - as one image vanishing and an unrelated one appearing, and the app's version window is lost — - which is exactly the upgrade most worth scanning.""" - txt = _fetch(url, _gitea_auth(url)) - out, svc = {}, None - in_services = False - for line in txt.splitlines(): - if re.match(r"^services:\s*$", line): - in_services = True - continue - if in_services and re.match(r"^\S", line): - in_services = False - if not in_services: - continue - m = re.match(r"^ (\S+):\s*$", line) - if m: - svc = m.group(1) - continue - m = re.match(r"^\s+image:\s*[\"']?([^\"'\s]+)", line) - if m and svc: - ref = m.group(1).split("@", 1)[0] - if "${" in ref or "$(" in ref: - continue - repo, _, tag = ref.rpartition(":") - if repo and tag: - out[svc] = (repo, tag) - return out - - -def _default_branch_compose(url: str) -> str | None: - """Same repo as `url`, but its DEFAULT branch — resolved from the API, never assumed. - - Several coopcloud recipes keep a stale `main` beside the real default `master` (gitea's `main` - is 1.24.2-rootless while `master` has 1.27.1-rootless), so guessing the branch produces a - confidently wrong baseline.""" - m = re.match(r"(https?://[^/]+)/([^/]+)/([^/]+)/(?:raw|src)/branch/[^/]+/(.*)$", url) - if not m: - return None - host, owner, repo, path = m.groups() - try: - meta = json.loads(_fetch(f"{host}/api/v1/repos/{owner}/{repo}", _gitea_auth(host))) - br = meta.get("default_branch") - except Exception: # noqa: BLE001 - return None - return f"{host}/{owner}/{repo}/raw/branch/{br}/{path}" if br else None - - -def windows_from_compose(to_url: str, from_url: str | None = None, - include_primary: bool = False) -> tuple: - """Derive the scan's version windows by DIFFING two compose files. - - This is the deterministic alternative to a human (or a model) deciding which `--image` args a - given upgrade needs. Point it at a PR's compose and it reads the windows straight off the diff: - every image whose tag changed becomes a window, every image that did not change is correctly - left out, and nothing depends on anyone remembering that the recipe also bumped its redis. - - Returns (windows, note) where windows is [(image-name, from, to)]. - """ - if from_url is None: - from_url = _default_branch_compose(to_url) - if not from_url: - raise SystemExit("could not resolve a baseline compose; pass --compose-from explicitly") - new, old = _compose_images(to_url), _compose_images(from_url) - app, others = None, [] - for svc, (repo, tag) in sorted(new.items()): - if svc not in old: - continue - prev_repo, prev_tag = old[svc] - if prev_tag == tag and prev_repo == repo: - continue - # The `app` service is the recipe's primary image by coop-cloud convention; its window drives - # --from/--to so the scan's primary advisory source is judged against it. Everything else is - # a sidecar window keyed by its image name. - if svc == "app": - app = (repo.split("/")[-1], prev_tag, tag) - else: - others.append((repo.split("/")[-1], prev_tag, tag)) - wins = ([app] if app else []) + others - result = (wins, f"baseline {from_url}") - return (*result, bool(app)) if include_primary else result - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("recipe") - ap.add_argument("--from", dest="v_from", default=None) - ap.add_argument("--to", dest="v_to", default=None) - ap.add_argument("--json", action="store_true", help="emit raw JSON instead of markdown") - ap.add_argument("--adjudicate", action="store_true", - help="SECOND PASS: for advisories the deterministic pass could not judge (no " - "fix version published), fetch their full text + references and append a " - "block for the agent to judge. Additive: it never changes the count above.") - ap.add_argument("--registry", default=REGISTRY_DIR) - ap.add_argument("--compose-to", default=None, metavar="URL", - help="derive the windows by DIFFING this compose against its baseline, instead " - "of passing --from/--to/--image by hand. Point it at a PR's compose.yml " - "(e.g. .../raw/branch//compose.yml).") - ap.add_argument("--compose-from", default=None, metavar="URL", - help="baseline compose for --compose-to. Default: the same repo's DEFAULT " - "branch, resolved from the API (never assumed to be `main`).") - ap.add_argument("--image", action="append", default=[], metavar="NAME=FROM:TO", - help="a sidecar image and the versions it moved between, e.g. " - "--image redis=7.4:8.10 (repeatable). NAME matches a source repo name; " - "its advisories are then counted against ITS OWN versions instead of " - "being left unclassified.") - a = ap.parse_args() - images = [] - if a.compose_to: - wins, note, app_changed = windows_from_compose(a.compose_to, a.compose_from, - include_primary=True) - if not wins: - print(f"### Advisory scan — {a.recipe}\n\n**No image versions changed between the two " - f"compose files, so this upgrade fixes no CVEs by definition.**\n\n_{note}_") - return 0 - print(f"_derived from compose diff ({note}):_", file=sys.stderr) - for n_, f_, t_ in wins: - print(f"_ {n_}: {f_} → {t_}_", file=sys.stderr) - # Only an actual app-service change defines the primary window. A sidecar-only PR must - # not be scanned as though its first sidecar were the application image. - if app_changed: - a.v_from, a.v_to = a.v_from or wins[0][1], a.v_to or wins[0][2] - images = list(wins[1:]) - else: - images = list(wins) - for spec in a.image: - name, _, rng = spec.partition('=') - vf, _, vt = rng.partition(':') - if name and vf and vt: - images.append((name, vf, vt)) - else: - print(f'ignoring malformed --image {spec!r} (expected NAME=FROM:TO)', file=sys.stderr) - rep = scan(a.recipe, a.v_from, a.v_to, a.registry, images) - if a.adjudicate: - rep["adjudication"] = [evidence_bundle(rep, c) - for c in needs_judgement(rep)[:MAX_ADJUDICATE]] - if a.json: - print(json.dumps(rep, indent=2)) - else: - print(markdown(rep)) - if a.adjudicate: - print(adjudication_block(rep)) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/cc-ci-plan/advisory-scan.py b/cc-ci-plan/advisory-scan.py new file mode 120000 index 0000000..293b1dd --- /dev/null +++ b/cc-ci-plan/advisory-scan.py @@ -0,0 +1 @@ +../scripts/cc-ci/advisory-scan.py \ No newline at end of file diff --git a/cc-ci-plan/agent-log.py b/cc-ci-plan/agent-log.py deleted file mode 100755 index 8def29d..0000000 --- a/cc-ci-plan/agent-log.py +++ /dev/null @@ -1,199 +0,0 @@ -#!/usr/bin/env python3 -"""Clean, greppable transcript logs for the cc-ci agents. - -Claude Code already writes a structured JSONL transcript of every session under -~/.claude/projects//.jsonl. This renders that into a readable, greppable -one-event-per-line log — WITHOUT touching the agent (read-only on a file it writes anyway, so no -slowdown and zero extra tokens). The raw `tmux pipe-pane` logs are TUI-escape soup; use these instead. - -Usage: - agent-log.py render print the clean transcript to stdout - agent-log.py tail [N] print the last N (default 40) rendered events - agent-log.py follow-all loop: keep .clean.log up to date for every agent (run in tmux) - -Agents: builder adversary upgrader assistant orchestrator -Output logs (follow-all): /srv/cc-ci/.cc-ci-logs/.clean.log - -Each line: `HH:MM:SS [kind] …` — kinds: user, asst (assistant text), tool:, result, think(skipped -by default). Long text/results are truncated (full detail stays in the JSONL); newlines collapsed to ⏎. -""" -import json, os, sys, time - -PROJ = "/home/loops/.claude/projects" -LOGDIR = "/srv/cc-ci/.cc-ci-logs" -MAXLEN = 800 # truncate any single rendered block to this many chars - -# agent -> (project-slug dir, signature substring in the first user/kickoff message) -AGENTS = { - "builder": ("-srv-cc-ci-orch-cc-ci", "cc-ci SUB-PHASE"), - "adversary": ("-srv-cc-ci-orch-cc-ci-adv", "Adversary agent"), - "upgrader": ("-srv-cc-ci-orch", "cc-ci UPGRADER"), - "assistant": ("-srv-cc-ci-orch", "cc-ci ASSISTANT"), - "orchestrator": ("-srv-cc-ci-orch", "cc-ci orchestrator"), -} - - -def _first_user_text(path, limit=4000): - """Read the start of a transcript; return the first user-message text (the kickoff signature).""" - try: - with open(path) as f: - for _ in range(60): - ln = f.readline() - if not ln: - break - try: - o = json.loads(ln) - except Exception: - continue - if o.get("type") == "user": - c = (o.get("message") or {}).get("content") - if isinstance(c, str): - return c[:limit] - if isinstance(c, list): - return " ".join(b.get("text", "") for b in c if isinstance(b, dict) and b.get("type") == "text")[:limit] - except FileNotFoundError: - return "" - return "" - - -def active_jsonl(agent): - """The agent's current transcript: newest *.jsonl in its slug dir whose kickoff matches the - signature (disambiguates the shared -srv-cc-ci-orch dir; tracks restarts → new uuid).""" - slug, sig = AGENTS[agent] - d = os.path.join(PROJ, slug) - try: - files = [os.path.join(d, f) for f in os.listdir(d) if f.endswith(".jsonl")] - except FileNotFoundError: - return None - files.sort(key=lambda p: os.path.getmtime(p), reverse=True) - for p in files: - if sig in _first_user_text(p): - return p - return None - - -def _clip(s): - s = " ".join(str(s).split()) if s else "" # collapse all whitespace/newlines - return s if len(s) <= MAXLEN else s[:MAXLEN] + " …[+%d]" % (len(s) - MAXLEN) - - -def render_line(o, show_think=False): - """Render one JSONL event to zero or more clean lines (list of strings).""" - t = o.get("type") - if t not in ("user", "assistant"): - return [] - ts = (o.get("timestamp") or "")[11:19] or "--:--:--" - m = o.get("message") or {} - c = m.get("content") - out = [] - if isinstance(c, str): - if c.strip(): - out.append(f"{ts} [user] {_clip(c)}") - return out - if not isinstance(c, list): - return out - for b in c: - if not isinstance(b, dict): - continue - bt = b.get("type") - if bt == "text": - txt = b.get("text", "") - if txt.strip(): - out.append(f"{ts} [{'asst' if t=='assistant' else 'user'}] {_clip(txt)}") - elif bt == "thinking": - if show_think: - out.append(f"{ts} [think] {_clip(b.get('thinking',''))}") - elif bt == "tool_use": - inp = b.get("input") or {} - brief = inp.get("command") or inp.get("file_path") or inp.get("path") or inp.get("prompt") or json.dumps(inp)[:200] - out.append(f"{ts} [tool:{b.get('name')}] {_clip(brief)}") - elif bt == "tool_result": - rc = b.get("content") - if isinstance(rc, list): - rc = " ".join(x.get("text", "") for x in rc if isinstance(x, dict)) - out.append(f"{ts} [result] {_clip(rc)}") - return out - - -def render_file(path, show_think=False): - lines = [] - with open(path) as f: - for ln in f: - try: - o = json.loads(ln) - except Exception: - continue - lines += render_line(o, show_think) - return lines - - -def cmd_render(agent, show_think=False): - p = active_jsonl(agent) - if not p: - print(f"(no transcript found for {agent})", file=sys.stderr); sys.exit(1) - print(f"# {agent} ← {p}") - for l in render_file(p, show_think): - print(l) - - -def cmd_tail(agent, n=40): - p = active_jsonl(agent) - if not p: - print(f"(no transcript found for {agent})", file=sys.stderr); sys.exit(1) - for l in render_file(p)[-n:]: - print(l) - - -def cmd_follow_all(): - """One cheap process: keep every agent's .clean.log current. Re-resolves the active - transcript each pass (handles restarts) and appends only newly-parsed events.""" - os.makedirs(LOGDIR, exist_ok=True) - state = {} # agent -> (path, byte_offset) - while True: - for agent in AGENTS: - p = active_jsonl(agent) - if not p: - continue - prev_path, off = state.get(agent, (None, 0)) - if p != prev_path: - off = 0 # new/restarted session → render from the top - try: - size = os.path.getsize(p) - if off > size: # file truncated/rotated - off = 0 - with open(p) as f: - f.seek(off) - chunk = f.read() - new_off = f.tell() - except FileNotFoundError: - continue - if chunk: - rendered = [] - for ln in chunk.splitlines(): - try: - o = json.loads(ln) - except Exception: - continue - rendered += render_line(o) - if rendered: - with open(os.path.join(LOGDIR, f"{agent}.clean.log"), "a") as out: - out.write("\n".join(rendered) + "\n") - state[agent] = (p, new_off) - time.sleep(5) - - -def main(): - a = sys.argv[1:] or ["follow-all"] - cmd = a[0] - if cmd == "render": - cmd_render(a[1], "--think" in a) - elif cmd == "tail": - cmd_tail(a[1], int(a[2]) if len(a) > 2 and a[2].isdigit() else 40) - elif cmd == "follow-all": - cmd_follow_all() - else: - print(__doc__); sys.exit(2) - - -if __name__ == "__main__": - main() diff --git a/cc-ci-plan/agent-log.py b/cc-ci-plan/agent-log.py new file mode 120000 index 0000000..010601c --- /dev/null +++ b/cc-ci-plan/agent-log.py @@ -0,0 +1 @@ +../scripts/cc-ci/agent-log.py \ No newline at end of file diff --git a/cc-ci-plan/agents.py b/cc-ci-plan/agents.py deleted file mode 100644 index 42ecbed..0000000 --- a/cc-ci-plan/agents.py +++ /dev/null @@ -1,850 +0,0 @@ -#!/usr/bin/env python3 -""" -cc-ci unified agent driver — one script, one config (agents.toml). - -Replaces the five bespoke launchers (launch.py / launch-orchestrator.py / launch-assistant.py -/ launch-upgrader.py / launch-report.py) and the ~15 scattered dotfiles. Every agent — loop -pair, orchestrator, assistant, one-shot tasks — is declared in agents.toml; the watchdog reads -the SAME file, so there is no env-vs-file drift. - -Usage: - agents.py up [name…] start enabled agents (or just the named ones); use-or-create - agents.py down [name…] stop agents (or all) - agents.py status one table: every agent — kind, backend, model, session, phase - agents.py watchdog the supervisor loop (reads agents.toml) - agents.py logs tail an agent's session log - agents.py phase [set N|next|show] inspect / move the loop phase - agents.py selftest backend activity-detector regression checks - agents.py migrate seed state/ from the legacy dotfiles (resume ids, phase idx) - -Options: - --config PATH config file (default: ') - - -def _mast(): - return ('
Co-op Cloud Recipe CI · Weekly Edition
' - '

The Recipe Report

') - - -def render(spec_path, out_path): - s = json.load(open(spec_path)) - kind = s.get("kind", "week") - title = KINDS.get(kind, KINDS["week"])[0] - gen = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") - sub = s.get("subtitle", ("Week of " if kind == "week" else "CVE check ") + s["date"]) - lead = s.get("lead", "") or "" - # Auto-link recipe-name mentions in the lead to their mirror repos. - gitea = _env().get("GITEA_URL", "git.autonomic.zone") - repo_url = {r["recipe"]: f"https://{gitea}/recipe-maintainers/{r['recipe']}" - for r in (s.get("table") or []) if r.get("recipe")} - if lead and "

" not in lead: - lead = "".join(f"

{_linkify_recipes(_esc(p.strip()), repo_url)}

" - for p in lead.split("\n\n") if p.strip()) - body = (_mast() + - f'' - f'
{lead}
') - # 1) the full wire — every recipe, in the agent's recommended priority order (CVEs first); CVEs column. - wire = ("The full wire — every recipe, in priority order" if kind == "week" - else "Advisory sweep — every recipe, worst first") - body += f'

{wire}

{_table(s.get("table"), repo_url)}' - # 2) addendum — special issues to look into (normal-size header); omitted entirely if there are none. - add = [a for a in (s.get("addendum") or []) if str(a).strip()] - if add: - body += ('

Addendum

    ' - + "".join(f"
  • {_linkify_recipes(_esc(b), repo_url)}
  • " for b in add) + "
") - # 3) security bulletin - if s.get("security"): - body += ('
Security Bulletin
' - '

🔒 Critical CVE upgrades

' + _stories(s["security"], repo_url) + "
") - # 4) what changed — a short section per recipe that has a PR - if s.get("changes"): - body += f'

What changed

{_changes(s.get("changes"), repo_url)}' - body += (f'') - open(out_path, "w").write(_page(f"{title} · " + s["date"], body)) - print("wrote", out_path) - - -def publish(html_path, date, kind="week"): - if kind not in KINDS: - print(f"unknown kind {kind!r}; expected one of {', '.join(KINDS)}"); sys.exit(2) - page = f"{kind}-{date}.html" - subprocess.run(["ssh", "cc-ci", f"cat > {HOST_REPORTS}/{page}"], input=open(html_path, "rb").read(), check=True) - # One index over BOTH families, newest first, each row labelled by its kind — an operator looking - # for "the latest security picture" should not have to know which skill produced which page. - entries = [] - for k in KINDS: - listing = subprocess.run(["ssh", "cc-ci", f"ls -1 {HOST_REPORTS}/{k}-*.html 2>/dev/null"], - capture_output=True, text=True).stdout.split() - for pth in listing: - d = os.path.basename(pth)[len(k) + 1:-5] - if re.fullmatch(r"\d{4}-\d{2}-\d{2}", d): - entries.append((d, k)) - lis = "\n".join( - f'
  • {KINDS[k][1].format(d=d)}{d}
  • ' - for d, k in sorted(set(entries), reverse=True)) - idx = _page("The Recipe Report — Archive", _mast() + - '' - f'
      {lis or "
    • No reports yet.
    • "}
    ') - subprocess.run(["ssh", "cc-ci", f"cat > {HOST_REPORTS}/index.html"], input=idx.encode(), check=True) - print(f"published https://report.ci.autonomic.zone/{page} (+ index)") - - -def main(): - a = sys.argv[1:] - cmd = a[0] if a else "survey" - today = datetime.now(timezone.utc).strftime("%Y-%m-%d") - if cmd == "survey": - survey(a[1] if len(a) > 1 else today) - elif cmd == "render": - render(a[1], a[2]) - elif cmd == "publish": - publish(a[1], a[2], a[3] if len(a) > 3 else "week") - else: - print(__doc__); sys.exit(2) - - -if __name__ == "__main__": - main() diff --git a/cc-ci-plan/recipe-report.py b/cc-ci-plan/recipe-report.py new file mode 120000 index 0000000..5cc09c8 --- /dev/null +++ b/cc-ci-plan/recipe-report.py @@ -0,0 +1 @@ +../scripts/cc-ci/recipe-report.py \ No newline at end of file diff --git a/cc-ci-plan/reconcile-upstream.sh b/cc-ci-plan/reconcile-upstream.sh deleted file mode 100755 index d4ff776..0000000 --- a/cc-ci-plan/reconcile-upstream.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env bash -# reconcile-upstream — sync recipe mirrors from TRUE upstream. Run this FIRST, always. -# ---------------------------------------------------------------------------------- -# Every recipe we maintain is a MIRROR of a coopcloud recipe. Work done against a stale -# mirror is wasted or wrong, in three ways we have actually hit: -# -# 1. A PR whose changes upstream ALREADY MERGED. mailu #6 (2024.06.57 + redis 8.10, -# two internet-facing Roundcube CVEs) sat open and was reported as the fix for -# those CVEs — while upstream had merged and released it as 3.1.3+2024.06.57. The -# work was done; only our mirror was behind. -# 2. A survey that reads the stale mirror and reports "no upgrades available", so a -# recipe silently drops out of the weekly run. -# 3. Reading the WRONG BRANCH. Several coopcloud recipes keep a stale `main` beside -# the real default `master` — gitea's `main` is at 1.24.2-rootless while `master` -# has 1.27.1-rootless plus the merged PRs. Reading `main` there says the recipe is -# three releases behind and missing two CVSS-9.8 RCE fixes, which reads exactly -# like a real finding. open-recipe-pr.sh resolves the default branch itself -# (main OR master) — never hand-pick one. -# -# This is deterministic: it force-syncs each mirror's `main` to upstream's default -# branch and closes any mirror PR whose changes are already upstream. No AI judgement. -# -# reconcile-upstream.sh ... # specific recipes -# reconcile-upstream.sh --all # every recipe in used-recipes.md -# -# Safe to run repeatedly; a mirror already in sync is a no-op. Recipe work lives in -# BRANCHES, never on mirror `main`, so force-syncing `main` discards nothing. -set -o errexit -o nounset -o pipefail - -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -ORCH="$(dirname "$HERE")" -SSH="${SSH:-cc-ci}" -RECONCILE="${RECONCILE:-$ORCH/.claude/skills/recipe-upgrade/open-recipe-pr.sh}" -USED_RECIPES="${USED_RECIPES:-$HERE/used-recipes.md}" - -[ -f "$RECONCILE" ] || { echo "ERROR: reconcile helper not found: $RECONCILE" >&2; exit 1; } -set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a -: "${GITEA_USERNAME:?}"; : "${GITEA_PASSWORD:?}"; : "${GITEA_URL:=git.autonomic.zone}" - -if [ "${1:-}" = "--all" ]; then - mapfile -t RECIPES < <(awk '!/^[[:space:]]*#/ && ($2=="weekly" || $2=="external") {print $1}' "$USED_RECIPES") -else - [ "$#" -gt 0 ] || { echo "usage: reconcile-upstream.sh ... | --all" >&2; exit 2; } - RECIPES=("$@") -fi - -synced=0; closed=0; failed=0 -for r in "${RECIPES[@]}"; do - echo "── $r" - if out="$(ssh "$SSH" "GITEA_USERNAME='$GITEA_USERNAME' GITEA_PASSWORD='$GITEA_PASSWORD' GITEA_URL='$GITEA_URL' bash -s $r --reconcile-only" < "$RECONCILE" 2>&1)"; then - printf '%s\n' "$out" | grep -E "Force-syncing|already in sync|closed PR|still open|✓" | sed 's/^/ /' || true - synced=$((synced + 1)) - closed=$((closed + $(printf '%s' "$out" | grep -c "closed PR" || true))) - else - printf '%s\n' "$out" | tail -3 | sed 's/^/ /' - echo " ✗ FAILED — do NOT proceed against this mirror until it reconciles" - failed=$((failed + 1)) - fi -done - -echo -echo "reconcile-upstream: ${synced} mirror(s) synced, ${closed} already-upstream PR(s) closed, ${failed} failed" -[ "$failed" -eq 0 ] diff --git a/cc-ci-plan/reconcile-upstream.sh b/cc-ci-plan/reconcile-upstream.sh new file mode 120000 index 0000000..810e5c9 --- /dev/null +++ b/cc-ci-plan/reconcile-upstream.sh @@ -0,0 +1 @@ +../scripts/cc-ci/reconcile-upstream.sh \ No newline at end of file diff --git a/cc-ci-plan/resolve-images.py b/cc-ci-plan/resolve-images.py deleted file mode 100644 index 223faeb..0000000 --- a/cc-ci-plan/resolve-images.py +++ /dev/null @@ -1,519 +0,0 @@ -#!/usr/bin/env python3 -"""resolve-images — what version is each of a recipe's images on, and what is newest? - -An abra-independent version resolver. `abra recipe upgrade` is the normal path, but it has a hard -failure mode: an image pinned with BOTH a tag and a digest makes it FATA and abandon the WHOLE -recipe — even images it already parsed. immich pins two that way: - - ghcr.io/immich-app/postgres:14-vectorchord0.4.3-pgvectors0.2.0@sha256:bcf6… - docker.io/valkey/valkey:9@sha256:3acc… - -so immich contributes NO version data at all and silently drops out of every survey. That is -indistinguishable from "up to date" unless a human notices the missing row — which is exactly how it -kept getting skipped, and why a CVE sweep reported it as unknown. - -This reads the compose files directly and queries the registries itself, so a digest pin is just a -digest pin. Output is JSON (default) or a table. - - resolve-images.py [--ssh HOST] [--recipe-dir DIR] [--table] [--only IMAGE] - -The cc-ci host has no python3, so `--ssh cc-ci` reads the compose files from that host's checkout -over ssh and does the resolving locally. That keeps the source of truth the SAME tree abra and CI -use, rather than a second copy that can drift. - -TAG SHAPES. Registries mix wildly different tag conventions in one repo, so "newest" is meaningless -without a shape. Each tag is reduced to a signature by replacing digit runs with '#': - - v3.1.0 -> v#.#.# - 1.27.1-rootless -> #.#.#-rootless - 8.10-alpine -> #.#-alpine - 14-vectorchord0.4.3-pgvectors0.2.0 -> #-vectorchord#.#.#-pgvectors#.#.# - -Only tags sharing the CURRENT pin's shape are candidates. That keeps `-alpine` on `-alpine`, and -stops a `latest`/`release`/`sha-…` tag from ever being proposed as an upgrade. - -TWO ANSWERS, NOT ONE. It reports `newest_same_shape` AND `newest_within_major` (same leading number). -For a plain app image they usually agree. For a compatibility-pinned sidecar they do not, and taking -the max would be wrong: immich's postgres tag encodes the pg major plus the vectorchord/pgvectors -versions that immich-server is built against, so jumping pg major because a newer tag exists breaks -the deployment. The caller picks; this tool refuses to guess and shows both. -""" - -from __future__ import annotations - -import argparse -import glob -import shlex -import subprocess -import gzip -import json -import os -import re -import sys -import time -import urllib.error -import urllib.parse -import urllib.request - -UA = "cc-ci-resolve-images (+https://git.autonomic.zone/recipe-maintainers/cc-ci)" -TIMEOUT = int(os.environ.get("RESOLVE_IMAGES_TIMEOUT", "45")) -RECIPE_DIR = os.environ.get("ABRA_RECIPE_DIR", os.path.expanduser("~/.abra/recipes")) -MAX_TAG_PAGES = int(os.environ.get("RESOLVE_IMAGES_MAX_PAGES", "40")) - -IMAGE_RE = re.compile(r"""^\s*image:\s*["']?([^"'\s]+)["']?\s*$""", re.M) - - -RETRIES = int(os.environ.get("RESOLVE_IMAGES_RETRIES", "4")) - - -def _fetch(url: str, headers: dict | None = None) -> bytes: - """GET with backoff on rate limits. - - Docker Hub throttles anonymous clients hard, and a sweep re-reads the same popular repos - (nginx, redis, postgres) for recipe after recipe. A 429 mid-sweep used to surface as - 'unresolved', which is indistinguishable from a real lookup failure — so retry, and let the - per-repo cache below remove most of the requests entirely.""" - h = {"User-Agent": UA, "Accept-Encoding": "gzip"} - h.update(headers or {}) - delay = 2.0 - for attempt in range(RETRIES): - try: - with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=TIMEOUT) as r: - raw = r.read() - if r.headers.get("Content-Encoding") == "gzip": - raw = gzip.decompress(raw) - return raw - except urllib.error.HTTPError as e: - if e.code in (429, 503) and attempt < RETRIES - 1: - time.sleep(delay) - delay *= 2 - continue - raise - raise RuntimeError("unreachable") - - -_HUB_JWT: list = [] - - -def _hub_auth() -> dict: - """Authenticated Docker Hub calls get a far higher rate limit than anonymous ones. - - Credentials come from /srv/cc-ci/.testenv (DOCKERHUB_USERNAME / DOCKERHUB_TOKEN), the same pair - the CI host already uses. Absent creds are fine — the sweep just runs anonymous and slower.""" - if _HUB_JWT: - return _HUB_JWT[0] - env = {} - try: - for ln in open(os.environ.get("CCCI_TESTENV", "/srv/cc-ci/.testenv")): - if "=" in ln and not ln.strip().startswith("#"): - k, v = ln.strip().split("=", 1) - env[k] = v.strip().strip("\"'") - except OSError: - pass - u = os.environ.get("DOCKERHUB_USERNAME") or env.get("DOCKERHUB_USERNAME") - t = os.environ.get("DOCKERHUB_TOKEN") or env.get("DOCKERHUB_TOKEN") - hdrs = {} - if u and t: - try: - body = json.dumps({"username": u, "password": t}).encode() - req = urllib.request.Request("https://hub.docker.com/v2/users/login", - data=body, method="POST", - headers={"Content-Type": "application/json", "User-Agent": UA}) - with urllib.request.urlopen(req, timeout=TIMEOUT) as r: - tokj = json.load(r).get("token") - if tokj: - hdrs = {"Authorization": f"JWT {tokj}"} - except Exception: # noqa: BLE001 — anonymous is a valid fallback - hdrs = {} - _HUB_JWT.append(hdrs) - return hdrs - - -def _json(url: str, headers: dict | None = None): - return json.loads(_fetch(url, headers)) - - -def shape(tag: str) -> str: - """Signature of a tag with every digit run replaced by '#'. See module docstring.""" - return re.sub(r"\d+", "#", tag) - - -def vkey(tag: str) -> tuple: - """Ordering key: every number in the tag, in order. '1.27.10' > '1.27.9'; text ignored.""" - return tuple(int(x) for x in re.findall(r"\d+", tag)) - - -def parse_ref(ref: str) -> dict: - """Split an image reference into registry / repo / tag / digest.""" - digest = None - if "@" in ref: - ref, _, digest = ref.partition("@") - host, repo, tag = "docker.io", ref, "latest" - # A leading component is a REGISTRY only when there is a path after it. Without the slash test, - # a bare `postgres:15.18` looks like host "postgres:15.18" because of the tag's colon — which - # silently sent every library image to a nonexistent registry. - if "/" in ref: - first = ref.split("/")[0] - if "." in first or ":" in first or first == "localhost": - host, _, repo = ref.partition("/") - if ":" in repo.split("/")[-1]: - repo, _, tag = repo.rpartition(":") - if host == "docker.io" and "/" not in repo: - repo = f"library/{repo}" # bare `redis` is really `library/redis` - return {"registry": host, "repo": repo, "tag": tag, "digest": digest} - - -HUB_RECENT_PAGES = int(os.environ.get("RESOLVE_IMAGES_HUB_PAGES", "40")) -_HUB_TRUNCATED: set[str] = set() - - -def _hub_tag_exists(repo: str, tag: str) -> bool: - try: - _json(f"https://hub.docker.com/v2/repositories/{repo}/tags/{tag}", _hub_auth()) - return True - except Exception: # noqa: BLE001 - return False - - -def _hub_tags(repo: str) -> list[str]: - """Recently-pushed tags, newest first. - - Popular Docker Hub repos carry many thousands of tags, so enumerate a bounded recent window. - A rebuilt old tag can displace a newer version from that window, so callers MUST treat a - truncated listing with no detected upgrade as unverified, not current. (ghcr offers no recency - ordering, which is why that path needs a different strategy.) - """ - tags, url = [], (f"https://hub.docker.com/v2/repositories/{repo}/tags" - f"?page_size=100&ordering=last_updated") - auth = _hub_auth() - for _ in range(HUB_RECENT_PAGES): - d = _json(url, auth) - tags += [r["name"] for r in d.get("results", [])] - url = d.get("next") - if not url: - break - if url: - _HUB_TRUNCATED.add(repo) - return tags - - -def _oci_bearer(host: str, repo: str) -> dict: - """Token for an OCI registry, discovered from its own auth challenge. - - Registries do NOT share a token endpoint. ghcr answers at /token?scope=…&service=ghcr.io, but - lscr.io and dock.mau.dev advertise different realms, and assuming ghcr's shape made both 401 — - which then read as "could not resolve" rather than "asked the wrong URL". The registry tells us - where to go in its WWW-Authenticate header; use that.""" - try: - urllib.request.urlopen( - urllib.request.Request(f"https://{host}/v2/{repo}/tags/list?n=1", - headers={"User-Agent": UA}), timeout=TIMEOUT) - return {} # no auth needed - except urllib.error.HTTPError as e: - if e.code != 401: - return {} - chal = e.headers.get("WWW-Authenticate", "") or "" - except Exception: # noqa: BLE001 - return {} - if not chal.lower().startswith("bearer"): - return {} - parts = dict(re.findall(r'(\w+)="([^"]*)"', chal)) - realm = parts.get("realm") - if not realm: - return {} - q = {"service": parts.get("service", host), "scope": parts.get("scope", f"repository:{repo}:pull")} - url = realm + ("&" if "?" in realm else "?") + urllib.parse.urlencode(q) - try: - tok = (_json(url) or {}).get("token") or (_json(url) or {}).get("access_token") - return {"Authorization": f"Bearer {tok}"} if tok else {} - except Exception: # noqa: BLE001 - return {} - - -def _oci_tags(host: str, repo: str) -> list[str]: - """Tags from any OCI/v2 registry, with challenge-derived auth and Link pagination. - - ghcr paginates hard — immich-server has >40,000 tags — and a truncated listing silently hides - the newest release line, so follow the cursor and let the caller's integrity check catch a read - that never reached the current pin.""" - hdrs = _oci_bearer(host, repo) - tags, url = [], f"https://{host}/v2/{repo}/tags/list?n=1000" - for _ in range(MAX_TAG_PAGES): - for attempt in range(RETRIES): - req = urllib.request.Request(url, headers={"User-Agent": UA, **hdrs}) - try: - with urllib.request.urlopen(req, timeout=TIMEOUT) as r: - tags += (json.load(r) or {}).get("tags") or [] - link = r.headers.get("Link", "") or "" - break - except urllib.error.HTTPError as e: - if e.code not in (429, 503) or attempt == RETRIES - 1: - raise - retry_after = e.headers.get("Retry-After") or "" - delay = min(int(retry_after) if retry_after.isdigit() else 2 ** (attempt + 1), 60) - time.sleep(delay) - m = re.search(r'<([^>]+)>;\s*rel="next"', link) - if not m: - break - nxt = m.group(1) - url = f"https://{host}{nxt}" if nxt.startswith("/") else nxt - else: - raise RuntimeError(f"tag listing truncated after {MAX_TAG_PAGES} pages") - return tags - - -def _gh_token() -> str | None: - tok = os.environ.get("GITHUB_TOKEN") - if tok: - return tok.strip() - try: - return open(os.environ.get("GITHUB_TOKEN_FILE", "/srv/cc-ci/.github-token")).read().strip() or None - except OSError: - return None - - -def github_release_tags(owner: str, repo: str, max_pages: int = 4) -> list[str]: - """Release tag names for a GitHub repo, newest first. - - FALLBACK for registries whose tag listing cannot be enumerated. ghcr has no ordering and no - server-side filter, and immich-machine-learning carries >40,000 tags — a full read is impractical - and a partial read silently hides the newest release line. The project's RELEASES are ordered, - small, and authoritative: container tags track them. (The GitHub Packages API would answer this - directly but needs a scoped token; this scan's token deliberately has none.) - """ - hdrs = {"Accept": "application/vnd.github+json"} - tok = _gh_token() - if tok: - hdrs["Authorization"] = f"Bearer {tok}" - out = [] - for page in range(1, max_pages + 1): - try: - rows = _json(f"https://api.github.com/repos/{owner}/{repo}/releases" - f"?per_page=100&page={page}", hdrs) - except Exception: # noqa: BLE001 - break - if not rows: - break - out += [r.get("tag_name") or "" for r in rows] - return [t for t in out if t] - - -def _release_fallback_repos(registry: str, repo: str) -> list[tuple[str, str]]: - """Candidate GitHub repos whose releases track this image's tags.""" - if "ghcr.io" not in registry: - return [] - parts = repo.split("/") - if len(parts) < 2: - return [] - owner, name = parts[0], parts[-1] - cands = [(owner, name)] - # ghcr.io/immich-app/immich-machine-learning is built from immich-app/immich. - if name.startswith(owner.split("-")[0]): - cands.append((owner, owner.split("-")[0])) - return cands - - -def _oci_tag_exists(host: str, repo: str, tag: str) -> bool: - """Verify a release candidate is actually published as an image manifest.""" - hdrs = {"User-Agent": UA, - "Accept": "application/vnd.oci.image.index.v1+json, " - "application/vnd.docker.distribution.manifest.list.v2+json, " - "application/vnd.oci.image.manifest.v1+json", - **_oci_bearer(host, repo)} - url = f"https://{host}/v2/{repo}/manifests/{urllib.parse.quote(tag, safe='')}" - try: - with urllib.request.urlopen(urllib.request.Request(url, headers=hdrs, method="HEAD"), - timeout=TIMEOUT) as response: - return response.status == 200 - except urllib.error.HTTPError as e: - if e.code == 404: - return False - raise - - -def _release_manifest_fallback(registry: str, repo: str, current: str) -> tuple[list[str], str] | None: - """For huge GHCR registries, use release tags only after checking actual manifests.""" - for owner, name in _release_fallback_repos(registry, repo): - releases = github_release_tags(owner, name) - if current not in releases: - continue # incomplete release window; it cannot establish a current baseline - candidates = sorted((tag for tag in set(releases) - if shape(tag) == shape(current) and vkey(tag) >= vkey(current)), - key=vkey, reverse=True) - for tag in candidates: - if _oci_tag_exists(registry, repo, tag): - return [current, tag], f"github-releases+registry-manifest:{owner}/{name}" - return None - - -_TAG_CACHE: dict[tuple[str, str], tuple[list[str], str | None]] = {} - - -def list_tags(registry: str, repo: str) -> tuple[list[str], str | None]: - if (registry, repo) in _TAG_CACHE: - return _TAG_CACHE[(registry, repo)] - res = _list_tags_uncached(registry, repo) - _TAG_CACHE[(registry, repo)] = res - return res - - -def _list_tags_uncached(registry: str, repo: str) -> tuple[list[str], str | None]: - try: - return (_hub_tags(repo) if registry in ("docker.io", "registry-1.docker.io") - else _oci_tags(registry, repo)), None - except urllib.error.HTTPError as e: - return [], f"HTTP {e.code}" - except Exception as e: # noqa: BLE001 - return [], f"{type(e).__name__}: {e}" - - -def resolve(ref: str) -> dict: - """Current pin -> newest same-shape tag, and newest within the current major.""" - if "${" in ref or "$(" in ref: - # The tag is a compose variable (ghost pins `ghost:${IMAGE_VERSION}-alpine`). Its real value - # lives in .env, not here. Report it as skipped, never as a failed lookup. - return {**parse_ref(ref), "ref": ref, "shape": None, "candidates": 0, - "newest_same_shape": None, "newest_within_major": None, - "upgrade_available": False, - "status": "skipped: templated ref (tag comes from a compose variable)"} - info = parse_ref(ref) - out = {**info, "ref": ref, "shape": shape(info["tag"]), "status": "ok", - "newest_same_shape": None, "newest_within_major": None, "candidates": 0, - "upgrade_available": False} - tags, err = list_tags(info["registry"], info["repo"]) - if err: - try: - fallback = (_release_manifest_fallback(info["registry"], info["repo"], info["tag"]) - if "tag listing truncated" in err else None) - except Exception as e: # noqa: BLE001 — a failed fallback must stay unresolved - out["status"] = f"error: registry {err}; release fallback {type(e).__name__}: {e}" - return out - if not fallback: - out["status"] = f"error: {err}" - return out - tags, out["source"] = fallback - out["tags_seen"] = len(set(tags)) - # INTEGRITY CHECK: the tag we are currently running MUST appear in the listing. If it does not, - # the listing is incomplete and any "newest" derived from it is a guess — ghcr paginates to tens - # of thousands of tags and a truncated read silently hides whole release lines. immich's - # machine-learning image is pinned v3.1.0, which EXISTS, yet a short read reported v1.134.0 as - # newest; without this check that becomes a confident, wrong answer. - if info["tag"] not in set(tags): - # Docker Hub: the window is recency-ordered, so the pin being outside it just means the pin - # is old — which is fine, because anything NEWER is necessarily inside the window. Confirm - # the pin genuinely exists (so a typo is still caught) and carry on. - if info["registry"] in ("docker.io", "registry-1.docker.io") and _hub_tag_exists(info["repo"], info["tag"]): - out["source"] = f"docker-hub:recent-{HUB_RECENT_PAGES * 100}" - tags = list(tags) + [info["tag"]] - else: - for owner, name in _release_fallback_repos(info["registry"], info["repo"]): - rel = github_release_tags(owner, name) - if info["tag"] in rel: - tags = rel - out["source"] = f"github-releases:{owner}/{name}" - out["tags_seen"] = len(set(rel)) - break - else: - out["status"] = ("error: tag listing incomplete — the current pin " - f"{info['tag']!r} is absent from {len(set(tags))} registry tags " - f"and from the project's GitHub releases") - return out - want, cur = out["shape"], vkey(info["tag"]) - same = [t for t in set(tags) if shape(t) == want and vkey(t)] - out["candidates"] = len(same) - if not same: - # A floating or unusual tag cannot prove that an image is current. Keep it visible to - # callers rather than letting an empty candidate set become a false UPTODATE verdict. - out["status"] = "unverifiable: no comparable numeric tags" - return out - newest = max(same, key=vkey) - out["newest_same_shape"] = newest - if cur: - within = [t for t in same if vkey(t)[:1] == cur[:1]] - if within: - out["newest_within_major"] = max(within, key=vkey) - out["upgrade_available"] = bool(cur and vkey(newest) > cur) - if (info["registry"] in ("docker.io", "registry-1.docker.io") - and info["repo"] in _HUB_TRUNCATED and not out["upgrade_available"]): - out["status"] = (f"unverifiable: Docker Hub listing truncated after " - f"{HUB_RECENT_PAGES * 100} recent tags") - return out - - -def compose_images_ssh(recipe: str, host: str, recipe_dir: str) -> list[str]: - """Same as compose_images, but the recipe tree lives on another host (cc-ci has no python3).""" - # NB: no shell-quoting of the directory — it may legitimately start with ~ or $HOME, and - # quoting it stops the remote shell expanding it, which yields an empty (and silent) result. - d = f"{recipe_dir}/{shlex.quote(recipe)}".replace("~", "$HOME") - cmd = (f'for f in {d}/compose*.yml; do case "$f" in *compose.ccci.yml) continue;; esac; ' - f'[ -f "$f" ] && {{ cat "$f"; echo; }}; done; exit 0') - out = subprocess.run(["ssh", host, cmd], capture_output=True, text=True, timeout=120) - if out.returncode != 0: - raise RuntimeError(f"ssh {host}: {(out.stderr.strip() or 'no output')[:200]}") - if not out.stdout.strip(): - raise RuntimeError(f"ssh {host}: no compose files found under {d}") - refs = [] - for m in IMAGE_RE.finditer(out.stdout): - if m.group(1) not in refs: - refs.append(m.group(1)) - return refs - - -def compose_images(recipe: str, recipe_dir: str) -> list[str]: - """Every `image:` ref in the recipe's own compose files (the cc-ci overlay is NOT the recipe).""" - refs, base = [], os.path.join(recipe_dir, recipe) - for path in sorted(glob.glob(os.path.join(base, "compose*.yml"))): - if os.path.basename(path) == "compose.ccci.yml": - continue - try: - for m in IMAGE_RE.finditer(open(path).read()): - if m.group(1) not in refs: - refs.append(m.group(1)) - except OSError: - continue - return refs - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("recipe") - ap.add_argument("--ssh", default=None, metavar="HOST", - help="read the recipe's compose files from HOST over ssh (e.g. --ssh cc-ci); " - "resolving still happens locally") - ap.add_argument("--recipe-dir", default=RECIPE_DIR) - ap.add_argument("--table", action="store_true", help="human-readable table instead of JSON") - ap.add_argument("--only", default=None, help="resolve just the images whose ref contains this") - a = ap.parse_args() - - rdir = a.recipe_dir if a.recipe_dir != RECIPE_DIR or not a.ssh else "~/.abra/recipes" - refs = (compose_images_ssh(a.recipe, a.ssh, rdir) if a.ssh - else compose_images(a.recipe, a.recipe_dir)) - if a.only: - refs = [r for r in refs if a.only in r] - results = [resolve(r) for r in refs] - report = { - "recipe": a.recipe, - "images": results, - "upgrades_available": [r["ref"] for r in results if r["upgrade_available"]], - "unresolved": [r["ref"] for r in results if r["status"].startswith(("error", "skipped", "unverifiable"))], - # The whole point: distinguish "checked, current" from "could not check". - "all_resolved": bool(results) and all(r["status"] == "ok" for r in results), - } - if not a.table: - print(json.dumps(report, indent=2)) - return 0 - print(f"{a.recipe} — {len(results)} images") - for r in results: - flag = "UPGRADE" if r["upgrade_available"] else ("UNKNOWN" if r["status"] != "ok" else "current") - print(f" [{flag:7}] {r['repo']}:{r['tag']}" + (" (digest-pinned)" if r["digest"] else "")) - print(f" shape={r['shape']} candidates={r['candidates']}" - f" newest_same_shape={r['newest_same_shape']}" - f" newest_within_major={r['newest_within_major']}") - if r["status"] != "ok": - print(f" status: {r['status']}") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/cc-ci-plan/resolve-images.py b/cc-ci-plan/resolve-images.py new file mode 120000 index 0000000..63abdc1 --- /dev/null +++ b/cc-ci-plan/resolve-images.py @@ -0,0 +1 @@ +../scripts/cc-ci/resolve-images.py \ No newline at end of file diff --git a/cc-ci-plan/task-consolidate-recipe-prs.md b/cc-ci-plan/task-consolidate-recipe-prs.md deleted file mode 100644 index 5151eb8..0000000 --- a/cc-ci-plan/task-consolidate-recipe-prs.md +++ /dev/null @@ -1,43 +0,0 @@ -# Assistant task — consolidate open recipe PRs (one open PR per recipe) - -**Dispatched:** 2026-06-02 by the orchestrator. **Owner:** the Assistant (one-shot). **Not** the -Builder/Adversary loops — they are busy on the regression phase; do not touch their clones. - -## Goal -Every recipe mirror should have **at most ONE open PR**. For any recipe with more than one open PR, -combine them into a single open PR (the union of their changes) and close the rest. - -## Steps - -1. **Survey.** Creds in `/srv/cc-ci/.testenv` (`GITEA_USERNAME`/`GITEA_PASSWORD`/`GITEA_URL`). For every - **recipe** mirror under the `recipe-maintainers` org, list its open PRs: - - `GET /api/v1/orgs/recipe-maintainers/repos?limit=100` - - `GET /api/v1/repos/recipe-maintainers//pulls?state=open` - Recipes = real recipe mirrors only — **exclude** infra repos: `cc-ci`, `cc-ci-orchestrator`, - `cc-ci-secrets`, `archived-*`. Build the list of recipes with **>1** open PR. - -2. **Consolidate** each such recipe into ONE open PR holding the union of the changes, then close the others: - - Work in a **fresh clone** of the mirror (e.g. under `/tmp`). **Never** use the loops' clones - (`/srv/cc-ci/cc-ci`, `/srv/cc-ci/cc-ci-adv`). - - Combine the open PR branches onto one branch (cherry-pick/merge). **Never force-push over unmerged - work** — preserve every change. Prefer **extending the lowest-numbered open PR** by pushing the - combined branch onto its head (the no-force "commit on top" pattern in - `/srv/cc-ci/.claude/skills/recipe-upgrade/open-recipe-pr.sh`). - - **Conflict policy:** two upgrade PRs to different versions → keep the **newest** version. An upgrade - PR + a different-purpose PR (e.g. a backup/restore fix) → include **both** changes. - - **Close** the now-redundant PRs with a comment: `Consolidated into # — one open PR per recipe.` - - **Re-test** the surviving consolidated PR by commenting `!testme` on it (real CI; results show in - the PR; iterate up to 3×). If a genuine pre-existing failure blocks it, leave an explanatory - comment — do **not** weaken/skip/delete any test. - -3. **Report & stop.** Summarise: which recipes had >1 open PR, what you consolidated, the surviving PR - URL per recipe, conflicts resolved, and any PR left red with an explanatory comment. Then go idle - (one-shot — do not loop). - -## Guardrails -- **NEVER merge any PR into `main`** — the operator merges. "Merge them together" = consolidate multiple - open PRs into ONE open PR, **not** merge to main. -- Only touch **recipe mirror** PRs. Do **not** touch cc-ci-repo PRs (build/test PRs). -- Recipes with 0 or 1 open PR: leave untouched. -- Known starting point (re-verify live — state may have changed): `custom-html` had 2 upgrade PRs - (#1 1.12.0, #2 1.13.0); `ghost` had #1 (backup fix) + #2 (upgrade). Survey fresh for the full set. diff --git a/cc-ci-plan/task-consolidate-recipe-prs.md b/cc-ci-plan/task-consolidate-recipe-prs.md new file mode 120000 index 0000000..e410fdf --- /dev/null +++ b/cc-ci-plan/task-consolidate-recipe-prs.md @@ -0,0 +1 @@ +../archive/plans/cc-ci-plan/task-consolidate-recipe-prs.md \ No newline at end of file diff --git a/cc-ci-plan/test-advisory-scan.py b/cc-ci-plan/test-advisory-scan.py deleted file mode 100755 index 3505cb0..0000000 --- a/cc-ci-plan/test-advisory-scan.py +++ /dev/null @@ -1,955 +0,0 @@ -#!/usr/bin/env python3 -"""Tests for advisory-scan.py. - -Two tiers: - - OFFLINE (default) — pure logic, fixtures injected in place of the network. Fast, deterministic, - no token, no rate limit. These encode every classification rule and every guarantee the CVE count - makes, including the specific production defects that motivated them. - - LIVE (--live) — re-derives the CVE counts published in the week-2026-08-07 report against the real - advisory APIs. Slow, needs network + ideally a GitHub token. Run before changing classification. - -Usage: - python3 test-advisory-scan.py # offline only - python3 test-advisory-scan.py --live # offline + historic report regressions -""" - -from __future__ import annotations - -import importlib.util -import io -import json -import os -import pathlib -import tempfile -import sys -import unittest -import unittest.mock - -HERE = pathlib.Path(__file__).resolve().parent -_spec = importlib.util.spec_from_file_location("advisory_scan", HERE / "advisory-scan.py") -A = importlib.util.module_from_spec(_spec) -_spec.loader.exec_module(A) - - -# ── fixture helpers ─────────────────────────────────────────────────────────────────────────────── - -def adv(cve, patched=None, published=None, severity="high", ghsa=None): - """One GitHub advisory row as github_advisories() would emit it.""" - return {"cve": cve, "ghsa": ghsa or f"GHSA-fake-{cve[-4:]}", "severity": severity, - "summary": f"summary for {cve}", "vulnerable_range": None, "patched": patched, - "url": None, "published_at": published} - - -def gh(owner_repo, advisories, status="ok"): - return {"source": f"github-advisories:{owner_repo}", "status": status, "advisories": advisories} - - -def vendor(url, cves=(), status="ok"): - return {"source": url, "status": status, "cves": list(cves), - "context": {c: f"...{c}..." for c in cves}} - - -def run_scan(gh_entries=(), vendor_entries=(), tag_dates=None, *, v_from=None, v_to=None, - images=None, recipe="fixture", urls=None, releases=None, image_sources=None): - """scan() with every network call replaced by fixtures. - - `releases` maps CVE id -> tags whose release notes name it (the third, release-note method).""" - tag_dates = tag_dates or {} - releases = releases or {} - urls = urls if urls is not None else ["https://github.com/app/app"] - with unittest.mock.patch.object(A, "registry_urls", lambda r, d: (list(urls), "/fake/reg.md")), \ - unittest.mock.patch.object(A, "github_advisories", lambda u: list(gh_entries)), \ - unittest.mock.patch.object(A, "vendor_pages", lambda u: list(vendor_entries)), \ - unittest.mock.patch.object(A, "registry_image_sources", lambda r, d: image_sources or {}), \ - unittest.mock.patch.object(A, "osv", lambda r, v: None), \ - unittest.mock.patch.object(A, "_tag_date", lambda o, r, v: tag_dates.get(v)), \ - unittest.mock.patch.object(A, "release_fix_versions", lambda src, cve: list(releases.get(cve, []))): - return A.scan(recipe, v_from, v_to, "/fake", images) - - -def parse_image_args(argv): - """Drive main()'s --image parsing exactly as the CLI does, returning the tuples scan() receives.""" - captured = {} - - def fake_scan(recipe, vf, vt, reg, images): - captured["images"] = images - return {"recipe": recipe, "from": vf, "to": vt, "registry": reg, "registry_urls": 0, - "sources": [], "cves": {}, "fixed_by_this_upgrade": [], "unclassified": [], - "sources_failed": [], "sources_benign": [], "count_known": True, - "cve_count_fixed": 0, "windows": {}, "classified_by": {}} - - err = io.StringIO() - with unittest.mock.patch.object(A, "scan", fake_scan), \ - unittest.mock.patch.object(sys, "argv", ["advisory-scan.py", *argv]), \ - unittest.mock.patch.object(sys, "stdout", io.StringIO()), \ - unittest.mock.patch.object(sys, "stderr", err): - A.main() - return captured["images"], err.getvalue() - - -# ── A. version ordering ─────────────────────────────────────────────────────────────────────────── - -class TestVersionKey(unittest.TestCase): - def test_strips_prefix_and_suffix(self): - self.assertEqual(A._vkey("v1.27.1"), (1, 27, 1)) - self.assertEqual(A._vkey("1.27.1-rootless"), (1, 27, 1)) - self.assertEqual(A._vkey("2024.06.55"), (2024, 6, 55)) - - def test_empty_and_none(self): - self.assertEqual(A._vkey(None), ()) - self.assertEqual(A._vkey(""), ()) - - def test_dotted_minor_is_numeric_not_lexical(self): - # The bug this guards: "8.10" must be NEWER than "8.2.3". String compare says otherwise. - self.assertGreater(A._vkey("8.10"), A._vkey("8.2.3")) - self.assertGreater(A._vkey("1.27.10"), A._vkey("1.27.9")) - - def test_shorter_prefix_orders_below_its_own_patch(self): - # 7.4 < 7.4.1, so a CVE patched in 7.4.1 IS fixed by moving off a bare 7.4 pin. - self.assertLess(A._vkey("7.4"), A._vkey("7.4.1")) - - -class TestWindowMembership(unittest.TestCase): - """(from, to] membership — exclusive lower, inclusive upper, compared zero-padded.""" - - def _in(self, f, t, c): - return A._within(A._vkey(f), A._vkey(t), A._vkey(c)) - - def test_bounds(self): - self.assertTrue(self._in("1.27.0", "1.27.1", "1.27.1")) # upper inclusive - self.assertFalse(self._in("1.27.0", "1.27.1", "1.27.0")) # lower exclusive - self.assertFalse(self._in("1.27.0", "1.27.1", "1.26.9")) - self.assertFalse(self._in("1.27.0", "1.27.1", "1.28.0")) - - def test_bare_major_upper_bound_includes_its_dot_zero(self): - # Regression: plain tuple order makes (18,) < (18,0), so a fix in 18.0 fell OUTSIDE a - # window ending at 18. Bare major tags are the norm for sidecars (postgres:18, redis:8). - self.assertTrue(self._in("17", "18", "18.0")) - self.assertTrue(self._in("7", "8", "8.0")) - self.assertTrue(self._in("7.4", "8.10", "8.0.4")) - - def test_bare_major_upper_bound_excludes_later_patches(self): - # Conservative on the other side: nothing proves which 18.x a floating tag resolved to. - self.assertFalse(self._in("17", "18", "18.5")) - - def test_bare_version_is_read_literally_as_dot_zero(self): - # from="8" means 8.0, so a fix in 8.0.4 is inside a window that ends at 9. - self.assertTrue(self._in("8", "9", "8.0.4")) - self.assertFalse(self._in("8", "9", "8.0")) # == the stated lower bound - - def test_prefix_lower_bound_still_counts_its_patches(self): - self.assertTrue(self._in("7.4", "8.10", "7.4.1")) - self.assertTrue(self._in("7.4", "8.10", "7.4.6")) - - def test_the_false_133_cve_stays_out(self): - self.assertFalse(self._in("7.4", "8.10", "6.0.11")) - - -# ── B. registry URL extraction ──────────────────────────────────────────────────────────────────── - -class TestRegistryUrls(unittest.TestCase): - def _write(self, tmp, text): - p = pathlib.Path(tmp) / "r.md" - p.write_text(text) - return A.registry_urls("r", tmp) - - def test_prose_ellipsis_is_not_a_security_source(self): - with tempfile.TemporaryDirectory() as directory: - urls, _ = self._write(directory, - "https://github.com/cryptpad/cryptpad and example `https://…` URLs " - "http://docspec:3000/conversion http://127.0.0.1:3000/health") - self.assertEqual(urls, ["https://github.com/cryptpad/cryptpad"]) - - def test_image_source_table_maps_monorepo_images(self): - mapping = A.registry_image_sources("lasuite-drive", str(HERE / "upstream")) - self.assertIn("github-advisories:suitenumerique/drive", mapping["drive-backend"]) - self.assertIn("github-advisories:CollaboraOnline/online", mapping["code"]) - - def test_common_database_cpes_follow_registry_images(self): - self.assertIn(("postgres", A.COMMON_IMAGE_CPES["postgres"]), - A.registry_cpes("immich", str(HERE / "upstream"))) - self.assertIn(("mariadb", A.COMMON_IMAGE_CPES["mariadb"]), - A.registry_cpes("gitea", str(HERE / "upstream"))) - self.assertIn(("rustdesk-server", "cpe:2.3:a:rustdesk:rustdesk_server:*:*:*:*:oss:*:*:*"), - A.registry_cpes("rustdesk-server", str(HERE / "upstream"))) - - def test_strips_trailing_markdown_punctuation(self): - # Production defect: a captured backtick 404'd the fetch and rendered n8n/immich as '?'. - import tempfile - with tempfile.TemporaryDirectory() as tmp: - urls, _ = self._write(tmp, "see `https://docs.n8n.io/release-notes/` and " - "**https://example.com/sec.html**, plus https://a.test/x.") - self.assertIn("https://docs.n8n.io/release-notes/", urls) - self.assertIn("https://example.com/sec.html", urls) - self.assertIn("https://a.test/x", urls) - self.assertFalse([u for u in urls if u.endswith(("`", "*", ".", ","))]) - - def test_dedupes_and_reports_missing_registry(self): - import tempfile - with tempfile.TemporaryDirectory() as tmp: - urls, path = self._write(tmp, "https://a.test/x https://a.test/x") - self.assertEqual(urls.count("https://a.test/x"), 1) - self.assertTrue(path.endswith("r.md")) - urls, path = A.registry_urls("does-not-exist", "/nonexistent-dir") - self.assertEqual((urls, path), ([], None)) - - -class TestNvdCompleteness(unittest.TestCase): - def test_truncated_results_are_not_a_clean_zero(self): - payload = json.dumps({"totalResults": 2, "vulnerabilities": [{"cve": {"id": "CVE-2026-0001"}}]}) - with unittest.mock.patch.object(A, "_fetch", return_value=payload): - row = A.nvd_advisories("cpe:2.3:a:example:server:*:*:*:*:*:*:*:*", "server") - self.assertEqual(row["status"], "error: NVD result set truncated") - self.assertEqual(row["advisories"], []) - - def test_database_backport_is_not_credited_again_on_major_upgrade(self): - ranges = [ - {"version": "*", "versionStartIncluding": "15.0", "versionEndExcluding": "15.14"}, - {"version": "*", "versionStartIncluding": "16.0", "versionEndExcluding": "16.5"}, - ] - self.assertIs(A._nvd_affects("15.13", ranges), True) - self.assertIs(A._nvd_affects("15.19", ranges), False) - self.assertIs(A._nvd_affects("18.6", ranges), False) - self.assertIsNone(A._nvd_affects("15-alpine", ranges)) - - -# ── C. --image argument parsing ─────────────────────────────────────────────────────────────────── - -class TestImageArgParsing(unittest.TestCase): - def test_single_and_repeated(self): - imgs, _ = parse_image_args(["r", "--image", "redis=7.4:8.10"]) - self.assertEqual(imgs, [("redis", "7.4", "8.10")]) - imgs, _ = parse_image_args(["r", "--image", "redis=7.4:8.10", "--image", "postgres=17:18"]) - self.assertEqual(imgs, [("redis", "7.4", "8.10"), ("postgres", "17", "18")]) - - def test_malformed_is_skipped_with_a_warning_not_a_crash(self): - # It is an ADDITIVE pre-step: one typo must not abort the upgrade's scan step. - for bad in ("redis=7.4", "redis", "=7.4:8.10", "redis=:8.10", "redis=7.4:"): - imgs, err = parse_image_args(["r", "--image", bad]) - self.assertEqual(imgs, [], f"{bad!r} should be rejected") - self.assertIn("malformed", err) - - def test_good_and_bad_mixed_keeps_the_good(self): - imgs, err = parse_image_args(["r", "--image", "redis=7.4:8.10", "--image", "nope"]) - self.assertEqual(imgs, [("redis", "7.4", "8.10")]) - self.assertIn("malformed", err) - - -# ── D. classification ───────────────────────────────────────────────────────────────────────────── - -class TestClassificationBoundaries(unittest.TestCase): - def _one(self, patched, v_from="1.27.0", v_to="1.27.1"): - rep = run_scan([gh("app/app", [adv("CVE-2026-0001", patched=patched)])], - v_from=v_from, v_to=v_to) - return rep - - def test_patched_at_upper_bound_counts(self): - self.assertEqual(self._one("1.27.1")["fixed_by_this_upgrade"], ["CVE-2026-0001"]) - - def test_patched_at_lower_bound_does_not_count(self): - # Already fixed in the version we were ON — this upgrade did not fix it. - rep = self._one("1.27.0") - self.assertEqual(rep["fixed_by_this_upgrade"], []) - self.assertEqual(rep["cve_count_fixed"], 0) - - def test_patched_below_and_above_window_do_not_count(self): - self.assertEqual(self._one("1.26.0")["fixed_by_this_upgrade"], []) - self.assertEqual(self._one("1.28.0")["fixed_by_this_upgrade"], []) - - def test_any_of_several_patched_lines_counts(self): - # n8n regression: one advisory patches several release lines; reading only the first - # dropped the line the deployment was on (CVE-2026-42231/42232 misclassified). - rep = self._one("1.123.32; 2.17.4; 2.18.1", v_from="2.17.0", v_to="2.17.4") - self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2026-0001"]) - - def test_no_patched_data_is_not_counted(self): - self.assertEqual(self._one(None)["fixed_by_this_upgrade"], []) - - -class TestPerImageWindows(unittest.TestCase): - """The false-133 family of defects: an image must only ever be judged by its OWN versions.""" - - APP = gh("discourse/discourse", [adv("CVE-APP-0001", patched="3.5.4", published="2026-03-01T00:00:00Z")]) - REDIS = gh("redis/redis", [ - adv("CVE-2021-21309", patched="6.0.11", published="2021-02-01T00:00:00Z"), - adv("CVE-2025-49844", patched="7.4.6; 8.0.4; 8.2.2", published="2025-10-01T00:00:00Z", - severity="critical"), - ]) - URLS = ["https://github.com/discourse/discourse", "https://github.com/redis/redis"] - - def test_sidecar_cve_is_not_judged_by_the_app_window(self): - # redis 6.0.11 sits numerically inside discourse 3.5.3 -> 2026.7.1. It must NOT count. - rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="2026.7.1", - tag_dates={"3.5.3": "2025-12-30T00:00:00Z", "2026.7.1": "2026-07-31T00:00:00Z"}, - urls=self.URLS) - self.assertNotIn("CVE-2021-21309", rep["fixed_by_this_upgrade"]) - self.assertIn("CVE-2021-21309", rep["unclassified"]) - - def test_unwindowed_image_is_unclassified_never_counted(self): - rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="3.5.4", urls=self.URLS) - self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-APP-0001"]) - for cve in ("CVE-2021-21309", "CVE-2025-49844"): - self.assertIn(cve, rep["unclassified"]) - - def test_sidecar_window_counts_only_what_that_bump_fixed(self): - rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="3.5.4", - images=[("redis", "7.4", "8.10")], urls=self.URLS) - self.assertIn("CVE-2025-49844", rep["fixed_by_this_upgrade"]) # patched 7.4.6, in window - self.assertNotIn("CVE-2021-21309", rep["fixed_by_this_upgrade"]) # patched 6.0.11, below it - self.assertEqual(rep["cve_count_fixed"], 2) # app 1 + redis 1 - - def test_count_is_the_union_across_images(self): - rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="3.5.4", - images=[("redis", "7.4", "8.10")], urls=self.URLS) - self.assertEqual(sorted(rep["fixed_by_this_upgrade"]), ["CVE-2025-49844", "CVE-APP-0001"]) - - def test_each_image_classified_independently(self): - # App crosses a scheme change (date method); redis does not (version method). Both resolve. - rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="2026.7.1", - images=[("redis", "7.4", "8.10")], urls=self.URLS, - tag_dates={"3.5.3": "2025-12-30T00:00:00Z", "2026.7.1": "2026-07-31T00:00:00Z"}) - methods = rep["classified_by"] - self.assertIn("publish date", methods["github-advisories:discourse/discourse"]) - self.assertEqual(methods["github-advisories:redis/redis"], "patched version ranges") - self.assertTrue(rep["count_known"]) - - def test_image_name_matches_as_substring(self): - rep = run_scan([self.APP, gh("discourse/discourse-postgres", [adv("CVE-PG-1", patched="18.0")])], - v_from="3.5.3", v_to="3.5.4", images=[("postgres", "17", "18")], - urls=["https://github.com/discourse/discourse", - "https://github.com/discourse/discourse-postgres"]) - self.assertIn("github-advisories:discourse/discourse-postgres", rep["windows"]) - self.assertIn("CVE-PG-1", rep["fixed_by_this_upgrade"]) - - def test_primary_cannot_be_stolen_by_a_loose_image_name(self): - rep = run_scan([self.APP, gh("discourse/discourse-postgres", [adv("CVE-PG-1", patched="18.0")])], - v_from="3.5.3", v_to="3.5.4", images=[("discourse", "1", "2")], - urls=["https://github.com/discourse/discourse", - "https://github.com/discourse/discourse-postgres"]) - self.assertEqual(rep["windows"]["github-advisories:discourse/discourse"], - {"from": "3.5.3", "to": "3.5.4"}) - - def test_unmatched_image_name_makes_count_unknown(self): - # A typo'd sidecar name must not silently turn its CVEs into a clean zero. - rep = run_scan([self.APP], v_from="3.5.3", v_to="3.5.4", - images=[("nosuchimage", "1", "2")], urls=self.URLS[:1]) - self.assertEqual(list(rep["windows"]), ["github-advisories:discourse/discourse"]) - self.assertFalse(rep["count_known"]) - self.assertEqual(rep["unmatched_image_windows"], ["nosuchimage"]) - self.assertIsNone(rep["cve_count_fixed"]) - - def test_registry_maps_image_to_differently_named_source(self): - rep = run_scan([self.APP, gh("suitenumerique/drive", [adv("CVE-DRIVE-1", patched="0.25.3")])], - v_from="3.5.3", v_to="3.5.4", images=[("drive-backend", "0.22.0", "0.25.3")], - urls=self.URLS, - image_sources={"drive-backend": {"github-advisories:suitenumerique/drive"}}) - self.assertEqual(rep.get("unmatched_image_windows"), None) - self.assertIn("CVE-DRIVE-1", rep["fixed_by_this_upgrade"]) - - def test_monorepo_images_share_identical_window(self): - source = "github-advisories:suitenumerique/drive" - rep = run_scan([gh("suitenumerique/drive", [adv("CVE-DRIVE-1", patched="0.25.3")])], - v_from="0.22.0", v_to="0.25.3", - images=[("drive-backend", "0.22.0", "0.25.3")], - image_sources={"drive-backend": {source}}) - self.assertTrue(rep["count_known"]) - self.assertEqual(rep.get("unmatched_image_windows"), None) - self.assertEqual(rep["cve_count_fixed"], 1) - - -class TestSchemeChangeDateFallback(unittest.TestCase): - DATES = {"3.5.3": "2025-12-30T00:00:00Z", "2026.7.1": "2026-07-31T00:00:00Z"} - - def _rep(self, advisories, dates=None): - return run_scan([gh("discourse/discourse", advisories)], v_from="3.5.3", v_to="2026.7.1", - tag_dates=self.DATES if dates is None else dates) - - def test_counts_advisories_published_inside_the_date_window(self): - rep = self._rep([adv("CVE-IN-1", published="2026-03-01T00:00:00Z"), - adv("CVE-OUT-1", published="2025-06-01T00:00:00Z"), - adv("CVE-OUT-2", published="2026-09-01T00:00:00Z")]) - self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-IN-1"]) - - def test_date_boundaries_match_the_version_rule(self): - # Exclusive lower, inclusive upper — same as 4a, so the two methods agree at the edges. - rep = self._rep([adv("CVE-LOWER", published=self.DATES["3.5.3"]), - adv("CVE-UPPER", published=self.DATES["2026.7.1"])]) - self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-UPPER"]) - - def test_advisory_without_a_publish_date_is_not_counted(self): - self.assertEqual(self._rep([adv("CVE-NODATE", published=None)])["fixed_by_this_upgrade"], []) - - def test_scheme_change_is_detected_not_version_compared(self): - rep = self._rep([adv("CVE-IN-1", patched="2026.1.0", published="2026-03-01T00:00:00Z")]) - self.assertIn("publish date", rep["classified_by"]["github-advisories:discourse/discourse"]) - self.assertIn("github-advisories:discourse/discourse", rep["date_window"]) - - def test_small_major_bump_still_uses_version_ranges(self): - rep = run_scan([gh("app/app", [adv("CVE-X", patched="3.0.0")])], v_from="2.9.0", v_to="3.0.0") - self.assertEqual(rep["classified_by"]["github-advisories:app/app"], "patched version ranges") - - -# ── E. count guarantees ─────────────────────────────────────────────────────────────────────────── - -class TestCountGuarantees(unittest.TestCase): - def test_unresolvable_window_yields_unknown_never_zero(self): - # Scheme change AND tag dates unresolvable -> must refuse to emit a number. - rep = run_scan([gh("app/app", [adv("CVE-1", published="2026-01-01T00:00:00Z")])], - v_from="3.5.3", v_to="2026.7.1", tag_dates={}) - self.assertIs(rep["cve_count_fixed"], None) - self.assertFalse(rep["count_known"]) - md = A.markdown(rep) - self.assertIn("UNKNOWN", md) - self.assertIn("NOT zero", md) - - def test_one_unresolvable_image_makes_the_whole_count_unknown(self): - # A partial number would understate a security figure, so it is suppressed entirely. - rep = run_scan([gh("app/app", [adv("CVE-APP", patched="1.1")]), - gh("redis/redis", [adv("CVE-REDIS", patched="8.0")])], - v_from="1.0", v_to="1.1", images=[("redis", "7.4", "9999.1")], - tag_dates={}, urls=["https://github.com/app/app", "https://github.com/redis/redis"]) - self.assertIs(rep["cve_count_fixed"], None) - self.assertFalse(rep["count_known"]) - - def test_genuine_zero_is_reported_as_zero(self): - rep = run_scan([gh("app/app", [adv("CVE-1", patched="9.9.9")])], v_from="1.0", v_to="1.1") - self.assertEqual(rep["cve_count_fixed"], 0) - self.assertTrue(rep["count_known"]) - self.assertIn("0 identified", A.markdown(rep)) - - def test_ghsa_without_cve_is_preserved_as_security_advisory(self): - entry = {"cve": None, "ghsa": "GHSA-aaaa-bbbb-cccc", "severity": "low", - "patched": "1.1", "summary": "security fix", "published_at": None} - rep = run_scan([gh("app/app", [entry])], v_from="1.0", v_to="1.1") - self.assertTrue(rep["count_known"]) - self.assertEqual(rep["cve_count_fixed"], 0) - self.assertEqual(rep["fixed_non_cve_advisories"], ["GHSA-aaaa-bbbb-cccc"]) - self.assertIn("use YES", A.markdown(rep)) - - def test_404_advisory_feed_is_benign_not_a_failure(self): - rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")]), - gh("side/car", [], status="no-advisories-published")], - v_from="1.0", v_to="1.1") - self.assertEqual(rep["sources_failed"], []) - self.assertIn("github-advisories:side/car", rep["sources_benign"]) - self.assertEqual(rep["cve_count_fixed"], 1) - - def test_template_url_is_benign_not_a_failure(self): - rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")])], - [vendor("https://x.test/changelog/v/", status="skipped: template URL")], - v_from="1.0", v_to="1.1") - self.assertEqual(rep["sources_failed"], []) - - def test_real_source_failure_is_surfaced(self): - rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")], status="error: HTTP 500")], - v_from="1.0", v_to="1.1") - self.assertIn("github-advisories:app/app", rep["sources_failed"]) - self.assertIn("FAILED", A.markdown(rep)) - self.assertFalse(rep["count_known"]) - - def test_only_404_feed_is_not_evidence_of_clean_scan(self): - rep = run_scan([gh("app/app", [], status="no-advisories-published")], - v_from="1.0", v_to="1.1") - self.assertTrue(rep["no_usable_sources"]) - self.assertFalse(rep["count_known"]) - - def test_no_window_given_classifies_nothing(self): - rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")])]) - self.assertEqual(rep["fixed_by_this_upgrade"], []) - self.assertIn("CVE-1", rep["unclassified"]) - - -class TestVendorOnlyCves(unittest.TestCase): - """The gitea case: CVEs named ONLY on a vendor page, absent from the GitHub advisory feed.""" - - def test_vendor_only_cve_is_recorded_and_surfaced(self): - rep = run_scan([gh("go-gitea/gitea", [])], - [vendor("https://blog.gitea.com/release-1.27.1/", ["CVE-2026-60004"])], - v_from="1.27.0", v_to="1.27.1") - self.assertIn("CVE-2026-60004", rep["cves"]) - self.assertIn("CVE-2026-60004", rep["unclassified"]) - - def test_vendor_only_cve_is_NOT_counted_but_IS_sent_for_judgement(self): - # It carries no version data, so no arithmetic can place it — the deterministic count must - # not include it. It must not be silently dropped either: pass 2 gets it with its evidence. - rep = run_scan([gh("go-gitea/gitea", [])], - [vendor("https://blog.gitea.com/release-1.27.1/", ["CVE-2026-60004"])], - v_from="1.27.0", v_to="1.27.1") - self.assertEqual(rep["fixed_by_this_upgrade"], []) - self.assertEqual(rep["cve_count_fixed"], 0) - self.assertIn("CVE-2026-60004", A.needs_judgement(rep)) - - def test_cve_in_both_vendor_and_advisory_feed_is_counted_once(self): - rep = run_scan([gh("go-gitea/gitea", [adv("CVE-2026-60004", patched="1.27.1")])], - [vendor("https://blog.gitea.com/x/", ["CVE-2026-60004"])], - v_from="1.27.0", v_to="1.27.1") - self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2026-60004"]) - self.assertEqual(rep["cve_count_fixed"], 1) - self.assertEqual(len(rep["cves"]["CVE-2026-60004"]["sources"]), 2) - - -class TestIndeterminateBucket(unittest.TestCase): - """An advisory with no knowable fix version is neither counted nor dismissed.""" - - def test_tbd_patched_is_indeterminate_not_excluded(self): - rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - self.assertEqual(rep["fixed_by_this_upgrade"], []) - self.assertIn("CVE-TBD", rep["indeterminate"]) - self.assertEqual(rep["cve_count_indeterminate"], 1) - - def test_placeholder_patched_is_indeterminate(self): - # "7.4.X" could be 7.4.1 — inside the window. Extracting a bare 7.4 and excluding it was - # how CVE-2024-46981 (high) went missing. - rep = run_scan([gh("redis/redis", [adv("CVE-X", patched="6.2.X, 7.2.X, 7.4.X")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - self.assertIn("CVE-X", rep["indeterminate"]) - - def test_real_versions_outside_the_window_are_decided_not_indeterminate(self): - rep = run_scan([gh("redis/redis", [adv("CVE-OLD", patched="6.0.11")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - self.assertEqual(rep["indeterminate"], []) - self.assertEqual(rep["cve_count_fixed"], 0) - - def test_indeterminate_is_surfaced_in_the_markdown_and_not_read_as_zero(self): - rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD", severity="critical")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - md = A.markdown(rep) - self.assertIn("could NOT be judged", md) - self.assertIn("must NOT be read as unaffected", md) - - -class TestReleaseNoteResolution(unittest.TestCase): - """Third method: a release whose notes NAME the CVE supplies the fix version the advisory lacks.""" - - def test_release_naming_the_cve_inside_the_window_counts_it(self): - rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], - releases={"CVE-TBD": ["6.2.19", "7.2.10", "7.4.5", "8.0.3"]}) - self.assertIn("CVE-TBD", rep["fixed_by_this_upgrade"]) - self.assertEqual(rep["indeterminate"], []) - self.assertEqual(rep["resolved_by_release_notes"]["CVE-TBD"], ["7.4.5", "8.0.3"]) - - def test_naming_releases_all_below_the_window_means_ALREADY_fixed(self): - # Every known fix predates the version we were already on, so this upgrade did not deliver - # it. That is a DECISION, not an unknown — mailu's redis 8.8.0 → 8.10.0 crosses 12 such - # advisories, and calling them "could not judge" overstates the uncertainty. - rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], - releases={"CVE-TBD": ["6.2.19"]}) - self.assertEqual(rep["fixed_by_this_upgrade"], []) - self.assertEqual(rep["indeterminate"], []) - self.assertIn("CVE-TBD", rep["already_fixed_before_upgrade"]) - self.assertIn("outside-window", rep["cves"]["CVE-TBD"]["classification"]) - - def test_naming_releases_only_ABOVE_the_window_stays_indeterminate(self): - # The fix landed after our target, so we are still exposed. Deliberately NOT decided as a - # tidy "not fixed": it is an open vulnerability and must stay visible to the operator. - rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], - releases={"CVE-TBD": ["9.0.0"]}) - self.assertEqual(rep["fixed_by_this_upgrade"], []) - self.assertIn("CVE-TBD", rep["indeterminate"]) - - def test_vendor_page_cve_on_the_same_repo_uses_release_notes(self): - # mailu announces its Roundcube CVEs only on github.com/Mailu/Mailu/releases. Requiring an - # advisory feed sent a deterministic case to pass 2; it is now decided in pass 1. - rep = run_scan([gh("Mailu/Mailu", [])], - [vendor("https://github.com/Mailu/Mailu/releases", ["CVE-2026-54432"])], - v_from="2024.06.55", v_to="2024.06.57", - urls=["https://github.com/Mailu/Mailu"], - releases={"CVE-2026-54432": ["2024.06.56"]}) - self.assertIn("CVE-2026-54432", rep["fixed_by_this_upgrade"]) - self.assertEqual(rep["cve_count_fixed"], 1) - - def test_release_evidence_is_recorded_for_audit(self): - rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], - releases={"CVE-TBD": ["7.4.5"]}) - e = rep["cves"]["CVE-TBD"] - self.assertEqual(e["fix_versions_from_release_notes"], ["7.4.5"]) - self.assertIn("named in release notes", e["classification"]) - - def test_it_does_not_override_a_version_range_decision(self): - # A CVE already counted by patched ranges is untouched; the method only rescues undecided. - rep = run_scan([gh("redis/redis", [adv("CVE-OK", patched="7.4.1")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], - releases={"CVE-OK": ["7.4.1"]}) - self.assertNotIn("CVE-OK", rep.get("resolved_by_release_notes") or {}) - - -class TestReleaseLineSemantics(unittest.TestCase): - """A fix inside the numeric window is not a fix on the branch you actually land on.""" - - def test_fix_later_on_the_targets_own_line_is_not_counted(self): - # ClickHouse fixed CVE-2023-48704 in 23.9.6.20 AND 23.10.5.20. Landing on 23.10.4.25 crosses - # the 23.9 fix numerically but is BELOW its own line's fix, so it does not have it. - rep = run_scan([gh("ClickHouse/ClickHouse", - [adv("CVE-2023-48704", patched="v23.10.5.20; v23.9.6.20; v23.8.8.20")])], - v_from="23.4.2.11", v_to="23.10.4.25", - urls=["https://github.com/ClickHouse/ClickHouse"]) - self.assertEqual(rep["fixed_by_this_upgrade"], []) - - def test_fix_earlier_on_the_targets_own_line_is_counted(self): - rep = run_scan([gh("ClickHouse/ClickHouse", - [adv("CVE-2023-47118", patched="v23.10.2.13; v23.8.6.16")])], - v_from="23.4.2.11", v_to="23.10.4.25", - urls=["https://github.com/ClickHouse/ClickHouse"]) - self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2023-47118"]) - - def test_fix_exactly_at_the_target_is_counted(self): - rep = run_scan([gh("ClickHouse/ClickHouse", - [adv("CVE-2023-48298", patched="v23.10.4.25; v23.9.5.29")])], - v_from="23.4.2.11", v_to="23.10.4.25", - urls=["https://github.com/ClickHouse/ClickHouse"]) - self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2023-48298"]) - - def test_no_fix_on_the_target_line_falls_back_to_the_window(self): - # redis fixes 7.4.6/8.0.4/8.2.2 with no 8.10.x entry; landing on 8.10 still has them, - # because nothing on the 8.10 line is named as a LATER fix. - rep = run_scan([gh("redis/redis", [adv("CVE-2025-49844", patched="7.4.6; 8.0.4; 8.2.2")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2025-49844"]) - - -class TestAlreadyFixedOnFromLine(unittest.TestCase): - """A fix that landed on the line we upgrade FROM was already ours before the upgrade.""" - - def test_backport_to_our_own_line_is_not_credited(self): - # mattermost patches every maintained line at once. 10.11.22 -> 10.12.4 crosses 10.12.1, but - # 10.11.22 is already past 10.11.4, so the deployment HAD the fix. Counting it credits the - # upgrade with work it did not do. - rep = run_scan([gh("mattermost/mattermost", - [adv("CVE-1", patched="10.11.4; 10.12.1; 10.5.12")])], - v_from="10.11.22", v_to="10.12.4", - urls=["https://github.com/mattermost/mattermost"]) - self.assertEqual(rep["fixed_by_this_upgrade"], []) - - def test_a_fix_ABOVE_our_position_on_the_same_line_still_counts(self): - rep = run_scan([gh("mattermost/mattermost", [adv("CVE-2", patched="10.11.30; 10.12.1")])], - v_from="10.11.22", v_to="10.12.4", - urls=["https://github.com/mattermost/mattermost"]) - self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2"]) - - def test_placeholders_never_feed_this_rule(self): - # "7.4.X" parses to a bare 7.4, which would read as "already fixed at 7.4" and silently drop - # a real fix — this is exactly how redis CVE-2024-46981 was lost when the rule was added. - rep = run_scan([gh("redis/redis", [adv("CVE-3", patched="6.2.X, 7.2.X, 7.4.X")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - self.assertIn("CVE-3", rep["indeterminate"]) - self.assertEqual(rep["fixed_by_this_upgrade"], []) - - -class TestChangelogAttribution(unittest.TestCase): - """Projects that publish no advisory feed still say which release fixed what — in their changelog.""" - - CHANGES = """ -Changes with nginx 1.31.3 11 Aug 2026 - *) Security: a flaw ... (CVE-2026-60005) - *) Security: another ... (CVE-2026-56434) - -Changes with nginx 1.31.2 04 Aug 2026 - *) Security: something ... (CVE-2026-48142) - -Changes with nginx 1.31.1 21 Jul 2026 - *) Security: older ... (CVE-2026-9256) - -Changes with nginx 1.20.0 01 Jan 2021 - *) Security: ancient ... (CVE-2013-2028) -""" - - def test_each_cve_is_attributed_to_the_release_that_fixed_it(self): - got = A._changelog_versions(self.CHANGES) - self.assertEqual(got["CVE-2026-60005"], "1.31.3") - self.assertEqual(got["CVE-2026-48142"], "1.31.2") - self.assertEqual(got["CVE-2026-9256"], "1.31.1") - self.assertEqual(got["CVE-2013-2028"], "1.20.0") - - def _scan(self, wfrom, wto): - # nginx publishes NO GitHub advisories — the feed is empty and the changelog is everything. - return run_scan( - [gh("nginx/nginx", [])], - [{"source": "https://nginx.org/en/CHANGES", "status": "ok", - "cves": sorted(A._changelog_versions(self.CHANGES)), - "context": {}, "fixed_in": A._changelog_versions(self.CHANGES)}], - images=[("nginx", wfrom, wto)], urls=["https://github.com/nginx/nginx"]) - - def test_window_counts_only_the_releases_it_crosses(self): - rep = self._scan("1.31.1", "1.31.3") # 1.31.1 is the FROM, so its CVE is already fixed - self.assertEqual(set(rep["fixed_by_this_upgrade"]), - {"CVE-2026-48142", "CVE-2026-56434", "CVE-2026-60005"}) - - def test_a_narrower_window_counts_fewer(self): - rep = self._scan("1.31.2", "1.31.3") - self.assertEqual(set(rep["fixed_by_this_upgrade"]), {"CVE-2026-56434", "CVE-2026-60005"}) - - def test_ancient_entries_are_not_swept_in(self): - # The changelog lists the project's whole history; only the crossed releases may count. - rep = self._scan("1.31.1", "1.31.3") - self.assertNotIn("CVE-2013-2028", rep["fixed_by_this_upgrade"]) - - def test_evidence_is_recorded(self): - rep = self._scan("1.31.1", "1.31.3") - self.assertEqual(rep["resolved_by_changelog"]["CVE-2026-60005"], "1.31.3") - - -class TestComposeDerivedWindows(unittest.TestCase): - """Windows read off a compose diff, so nobody has to remember which --image args an upgrade needs.""" - - OLD = """ -services: - app: - image: "plausible/analytics:v2.0.0" - db: - image: pgautoupgrade/pgautoupgrade:18-alpine - plausible_events_db: - image: clickhouse/clickhouse-server:23.4.2.11-alpine -volumes: - data: -""" - NEW = """ -services: - app: - image: "ghcr.io/plausible/community-edition:v3.2.1" - db: - image: pgautoupgrade/pgautoupgrade:18-alpine - plausible_events_db: - image: clickhouse/clickhouse-server:24.12-alpine -volumes: - data: -""" - - def _windows(self, old=None, new=None): - pages = {"to": new if new is not None else self.NEW, - "from": old if old is not None else self.OLD} - with unittest.mock.patch.object(A, "_fetch", lambda u, h=None: pages["to" if "to" in u else "from"]), \ - unittest.mock.patch.object(A, "_gitea_auth", lambda u: {}): - return A.windows_from_compose("http://x/to", "http://x/from")[0] - - def test_app_service_leads_and_sidecars_follow(self): - w = self._windows() - self.assertEqual(w[0], ("community-edition", "v2.0.0", "v3.2.1")) - self.assertIn(("clickhouse-server", "23.4.2.11-alpine", "24.12-alpine"), w) - - def test_unchanged_images_are_not_windows(self): - # pgautoupgrade is identical in both; inventing a window for it would be a false count. - self.assertNotIn("pgautoupgrade", [n for n, _, _ in self._windows()]) - - def test_a_changed_image_REPO_is_still_the_same_service(self): - # plausible/analytics -> ghcr.io/plausible/community-edition. Keyed by image repo this reads - # as one image vanishing and another appearing, and the app window is lost entirely. - w = self._windows() - self.assertTrue(any(n == "community-edition" and f == "v2.0.0" for n, f, _ in w)) - - def test_no_change_yields_no_windows(self): - self.assertEqual(self._windows(old=self.NEW, new=self.NEW), []) - - def test_lasuite_docs_pr_does_not_claim_preexisting_valkey_upgrade(self): - base = """services: - app: - image: lasuite/impress-frontend:v6.0.4 - yhub-valkey: - image: valkey/valkey:9.1.3-alpine - docspec: - image: ghcr.io/docspecio/api:3.0.2 -""" - head = base.replace("ghcr.io/docspecio/api:3.0.2", "ghcr.io/docspec/api:1.21.4") - windows = self._windows(old=base, new=head) - self.assertEqual(windows, [("api", "3.0.2", "1.21.4")]) - self.assertNotIn("valkey", [name for name, _, _ in windows]) - - captured = {} - - def fake_scan(recipe, v_from, v_to, registry, images): - captured.update(from_version=v_from, to_version=v_to, images=images) - return {"recipe": recipe, "from": v_from, "to": v_to, - "count_known": True, "cve_count_fixed": 0, "cves": {}, "sources": [], - "fixed_by_this_upgrade": [], "unclassified": [], "registry_urls": 0, - "sources_failed": [], "sources_benign": [], "windows": {}, - "classified_by": {}} - - with unittest.mock.patch.object(A, "windows_from_compose", - return_value=(windows, "pinned base", False)), \ - unittest.mock.patch.object(A, "scan", fake_scan), \ - unittest.mock.patch.object(sys, "argv", ["advisory-scan.py", "lasuite-docs", - "--compose-from", "base", "--compose-to", "head"]), \ - unittest.mock.patch.object(sys, "stdout", io.StringIO()), \ - unittest.mock.patch.object(sys, "stderr", io.StringIO()): - A.main() - self.assertIsNone(captured["from_version"]) - self.assertEqual(captured["images"], windows) - - def test_templated_tags_are_skipped(self): - new = self.NEW.replace('ghcr.io/plausible/community-edition:v3.2.1', 'ghost:${IMAGE_VERSION}') - self.assertNotIn("ghost", [n for n, _, _ in self._windows(new=new)]) - - -class TestImageNameMatching(unittest.TestCase): - """An image name and its advisory source rarely spell each other exactly.""" - - def test_matches_when_the_image_name_is_LONGER_than_the_source(self): - # clickhouse/clickhouse-server vs source ClickHouse/ClickHouse — one-directional matching - # dropped this window silently when the key came from a compose file. - rep = run_scan([gh("ClickHouse/ClickHouse", [adv("CVE-1", patched="23.10.2.13")])], - images=[("clickhouse-server", "23.4.2.11", "24.12")], - urls=["https://github.com/ClickHouse/ClickHouse"]) - self.assertIn("github-advisories:ClickHouse/ClickHouse", rep["windows"]) - self.assertEqual(rep["cve_count_fixed"], 1) - - def test_matches_when_the_image_name_is_SHORTER_than_the_source(self): - rep = run_scan([gh("redis/redis", [adv("CVE-2", patched="7.4.1")])], - images=[("redis", "7.4", "8.10")], urls=["https://github.com/redis/redis"]) - self.assertEqual(rep["cve_count_fixed"], 1) - - -class TestAdjudicationEvidenceAssembly(unittest.TestCase): - """Pass 2's JUDGEMENT is a model's and not testable; what IS testable is what it gets shown.""" - - def test_selects_indeterminate_and_vendor_only_cases(self): - rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], - [vendor("https://blog.test/sec", ["CVE-VENDOR"])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - todo = A.needs_judgement(rep) - self.assertIn("CVE-TBD", todo) - self.assertIn("CVE-VENDOR", todo) - - def test_does_not_re_ask_about_cases_pass_1_settled(self): - rep = run_scan([gh("redis/redis", [adv("CVE-OK", patched="7.4.1")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - self.assertNotIn("CVE-OK", A.needs_judgement(rep)) - - def test_evidence_bundle_carries_the_window_and_published_fields(self): - rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - with unittest.mock.patch.object(A, "advisory_text", lambda g, s=None: {"status": "skipped"}), \ - unittest.mock.patch.object(A, "release_fix_versions", lambda s, c: []): - ev = A.evidence_bundle(rep, "CVE-TBD") - self.assertEqual(ev["window"], {"from": "7.4", "to": "8.10"}) - self.assertEqual(ev["patched_as_published"], "TBD") - self.assertIn("no fix version", ev["why_undecided"]) - - def test_pass_1_decisions_are_included_for_review(self): - rep = run_scan([gh("redis/redis", [adv("CVE-OK", patched="7.4.1"), - adv("CVE-OLD", patched="6.0.11"), - adv("CVE-TBD", patched="TBD")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - with unittest.mock.patch.object(A, "advisory_text", lambda g, s=None: {"status": "skipped"}), \ - unittest.mock.patch.object(A, "release_fix_versions", lambda s, c: []): - block = A.adjudication_block(rep) - self.assertIn("Pass 1 decisions", block) - self.assertIn("CVE-OK", block) # counted - self.assertIn("CVE-OLD", block) # excluded as outside-window - self.assertIn("CVE-TBD", block) # needs judgement - - def test_truncation_is_announced_never_silent(self): - advs = [adv(f"CVE-2026-{1000+i}", patched="TBD") for i in range(30)] - rep = run_scan([gh("redis/redis", advs)], v_from="7.4", v_to="8.10", - urls=["https://github.com/redis/redis"]) - with unittest.mock.patch.object(A, "advisory_text", lambda g, s=None: {"status": "skipped"}), \ - unittest.mock.patch.object(A, "release_fix_versions", lambda s, c: []), \ - unittest.mock.patch.object(A, "MAX_ADJUDICATE", 5): - block = A.adjudication_block(rep) - self.assertIn("not shown", block) - self.assertIn("do not", block.lower()) - - -class TestMarkdownOutput(unittest.TestCase): - def test_lists_every_window_with_its_method(self): - rep = run_scan([gh("discourse/discourse", [adv("CVE-A", patched="3.5.4")]), - gh("redis/redis", [adv("CVE-B", patched="8.0")])], - v_from="3.5.3", v_to="3.5.4", images=[("redis", "7.4", "8.10")], - urls=["https://github.com/discourse/discourse", "https://github.com/redis/redis"]) - md = A.markdown(rep) - self.assertIn("discourse/discourse: 3.5.3 → 3.5.4", md) - self.assertIn("redis/redis: 7.4 → 8.10", md) - self.assertIn("**CVEs fixed by this upgrade: 2**", md) - - def test_severity_and_fixed_in_are_rendered(self): - rep = run_scan([gh("redis/redis", [adv("CVE-2025-49844", patched="7.4.6; 8.2.2", - severity="critical")])], - v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) - md = A.markdown(rep) - self.assertIn("critical", md) - self.assertIn("7.4.6", md) - - -# ── F. live regressions against published historic reports ──────────────────────────────────────── - -class TestHistoricReportNumbers(unittest.TestCase): - """Re-derive counts published in week-2026-08-07. Network + GitHub token; opt in with --live.""" - - REGISTRY = str(HERE / "upstream") - - @classmethod - def setUpClass(cls): - if not os.environ.get("ADVISORY_SCAN_LIVE"): - raise unittest.SkipTest("live tests: re-run with --live") - - def _count(self, recipe, v_from, v_to, images=None): - rep = A.scan(recipe, v_from, v_to, self.REGISTRY, images) - self.assertEqual(rep["sources_failed"], [], f"{recipe}: source failures make the count unsafe") - self.assertTrue(rep["count_known"], f"{recipe}: count came back UNKNOWN") - return rep - - def test_gitea_1_27_0_to_1_27_1_is_2(self): - rep = self._count("gitea", "1.27.0", "1.27.1") - self.assertEqual(rep["cve_count_fixed"], 2) - # Both CVSS-9.8 RCEs — the pair whose omission is why this tool exists. - self.assertEqual(set(rep["fixed_by_this_upgrade"]), {"CVE-2026-59774", "CVE-2026-60004"}) - - def test_discourse_app_only_is_123(self): - rep = self._count("discourse", "3.5.3", "2026.7.1") - self.assertEqual(rep["cve_count_fixed"], 123) - self.assertIn("publish date", rep["classified_by"]["github-advisories:discourse/discourse"]) - - def test_discourse_with_redis_sidecar_is_140(self): - # 123 app + 17 redis. Five redis advisories carry a usable patched_versions; the other - # twelve say "TBD" and are resolved from the release notes that name them. - rep = self._count("discourse", "3.5.3", "2026.7.1", [("redis", "7.4", "8.10")]) - self.assertEqual(rep["cve_count_fixed"], 140) - self.assertEqual(len(rep.get("resolved_by_release_notes") or {}), 12) - self.assertEqual(rep["cve_count_indeterminate"], 0) - # The five redis advisories that a sidecar-blind scan missed, incl. one critical. - for cve in ("CVE-2024-31227", "CVE-2024-31228", "CVE-2024-31449", - "CVE-2025-49844", "CVE-2025-62507"): - self.assertIn(cve, rep["fixed_by_this_upgrade"], f"{cve} missing from discourse+redis") - self.assertEqual(rep["cves"]["CVE-2025-49844"]["severity"], "critical") - - def test_discourse_redis_delta_is_exactly_seventeen(self): - app = self._count("discourse", "3.5.3", "2026.7.1") - both = self._count("discourse", "3.5.3", "2026.7.1", [("redis", "7.4", "8.10")]) - delta = set(both["fixed_by_this_upgrade"]) - set(app["fixed_by_this_upgrade"]) - self.assertEqual(len(delta), 17) - for cve in delta: - self.assertIn("redis", both["cves"][cve]["sources"][0]) - - def test_mailu_finds_the_roundcube_pair_without_an_agent(self): - # Published as 2 on 2026-08-07, but only because an agent read the release notes; the scan - # itself contributed 0. It now reaches 2 deterministically: the CVEs appear only on - # github.com/Mailu/Mailu/releases, and release 2024.06.56 (inside the window) names them. - rep = self._count("mailu", "2024.06.55", "2024.06.57", [("redis", "8.8.0", "8.10.0")]) - self.assertEqual(rep["cve_count_fixed"], 2) - self.assertEqual(set(rep["fixed_by_this_upgrade"]), {"CVE-2026-54432", "CVE-2026-54433"}) - # The redis bump fixes nothing new — every advisory it crosses was fixed at or before 8.6.3. - self.assertEqual(rep["cve_count_indeterminate"], 0) - - def test_keycloak_26_7_0_to_26_7_1_is_12(self): - # Was 7 while only the GHSA feed was consulted. keycloak lists five more CVEs in the 26.7.1 - # release notes' fixed-issues section that it never filed as advisories — the gitea pattern. - rep = self._count("keycloak", "26.7.0", "26.7.1") - self.assertEqual(rep["cve_count_fixed"], 12) - self.assertEqual(len(rep.get("resolved_by_release_notes") or {}), 5) - - -def _main(): - live = "--live" in sys.argv - if live: - sys.argv.remove("--live") - os.environ["ADVISORY_SCAN_LIVE"] = "1" - unittest.main(verbosity=2) - - -if __name__ == "__main__": - _main() diff --git a/cc-ci-plan/test-advisory-scan.py b/cc-ci-plan/test-advisory-scan.py new file mode 120000 index 0000000..5bfd0db --- /dev/null +++ b/cc-ci-plan/test-advisory-scan.py @@ -0,0 +1 @@ +../scripts/cc-ci/test-advisory-scan.py \ No newline at end of file diff --git a/cc-ci-plan/test-resolve-images.py b/cc-ci-plan/test-resolve-images.py deleted file mode 100644 index d43dd7a..0000000 --- a/cc-ci-plan/test-resolve-images.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python3 -"""Offline regressions for the weekly image survey's false-current cases.""" - -import importlib.util -import pathlib -import unittest -from unittest import mock - -HERE = pathlib.Path(__file__).resolve().parent -spec = importlib.util.spec_from_file_location("resolve_images", HERE / "resolve-images.py") -resolver = importlib.util.module_from_spec(spec) -spec.loader.exec_module(resolver) - - -class TestResolverCoverage(unittest.TestCase): - def test_cryptpad_calver_tag_is_found_independently_of_abra(self): - with mock.patch.object(resolver, "list_tags", return_value=( - ["version-2026.5.1", "version-2026.10.0", "opendesk-2026.08.04"], None)): - row = resolver.resolve("cryptpad/cryptpad:version-2026.5.1") - self.assertTrue(row["upgrade_available"]) - self.assertEqual(row["newest_same_shape"], "version-2026.10.0") - - def test_floating_and_templated_tags_cannot_prove_current(self): - with mock.patch.object(resolver, "list_tags", return_value=(["alpine", "1.2.3"], None)): - floating = resolver.resolve("atmoz/sftp:alpine") - templated = resolver.resolve("ghost:${IMAGE_VERSION}-alpine") - self.assertTrue(floating["status"].startswith("unverifiable:")) - self.assertTrue(templated["status"].startswith("skipped:")) - - def test_truncated_registry_listing_cannot_prove_current(self): - with mock.patch.object(resolver, "list_tags", return_value=(["1.2.3"], None)): - with mock.patch.object(resolver, "_HUB_TRUNCATED", {"library/example"}): - row = resolver.resolve("example:1.2.3") - self.assertTrue(row["status"].startswith("unverifiable:")) - - def test_huge_ghcr_listing_uses_only_published_release_manifests(self): - ref = "ghcr.io/immich-app/immich-machine-learning:v3.3.5" - with mock.patch.object(resolver, "list_tags", return_value=([], "RuntimeError: tag listing truncated")), \ - mock.patch.object(resolver, "github_release_tags", - return_value=["v3.3.6", "v3.3.5"]), \ - mock.patch.object(resolver, "_oci_tag_exists", side_effect=lambda h, r, t: t == "v3.3.5"): - row = resolver.resolve(ref) - self.assertEqual(row["status"], "ok") - self.assertFalse(row["upgrade_available"]) # release exists; image does not yet - self.assertIn("registry-manifest", row["source"]) - with mock.patch.object(resolver, "list_tags", return_value=([], "RuntimeError: tag listing truncated")), \ - mock.patch.object(resolver, "github_release_tags", - return_value=["v3.3.6", "v3.3.5"]), \ - mock.patch.object(resolver, "_oci_tag_exists", return_value=True): - upgraded = resolver.resolve(ref) - self.assertTrue(upgraded["upgrade_available"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/cc-ci-plan/test-resolve-images.py b/cc-ci-plan/test-resolve-images.py new file mode 120000 index 0000000..de69d88 --- /dev/null +++ b/cc-ci-plan/test-resolve-images.py @@ -0,0 +1 @@ +../scripts/cc-ci/test-resolve-images.py \ No newline at end of file diff --git a/scripts/cc-ci/advisory-scan.SPEC.md b/scripts/cc-ci/advisory-scan.SPEC.md new file mode 100644 index 0000000..577a37a --- /dev/null +++ b/scripts/cc-ci/advisory-scan.SPEC.md @@ -0,0 +1,391 @@ +# Advisory scan — specification + +What `cc-ci-plan/advisory-scan.py` does, step by step, and why each step exists. This documents the +implementation as it stands (2026-08-11); if you change the code, change this file in the same commit. +`cc-ci-plan/test-advisory-scan.py` is the executable half of this spec — every rule below is asserted +there. + +**Role.** A per-recipe CVE detector run as a **pre-step of `/recipe-upgrade`** (step 2a). It is +**strictly additive**: it never replaces the release-note reading the upgrade agent already does. The +CVE count reported for a recipe is the **union** of what the agent read and what this scan found; the +scan may never *lower* a count established by reading. + +**Why it exists.** gitea 1.27.1 fixed CVE-2026-60004 and CVE-2026-59774 (both CVSS 9.8). The weekly +report printed gitea's CVE count as `1`, then `none`. The upgrade agent had read the GitHub *release +notes*, which name neither — both were announced only in the vendor's blog security section — and the +report then derived security content from those notes plus model knowledge, which predates the CVEs. +Nothing in the pipeline queried an advisory source. This scan closes that hole. + +--- + +## Two passes + +| | Pass 1 — measure | Pass 2 — judge (`--adjudicate`) | +|---|---|---| +| Who | Pure Python, no model | The calling agent, a model | +| Does | Collects evidence and decides every case it can by arithmetic | Weighs the collected evidence on cases arithmetic cannot settle | +| Output | A count, or `UNKNOWN` | FIXED / NOT-FIXED / STILL-UNKNOWN per open case | +| Rule | Deterministic and reproducible | May only **raise** the count, never lower it | + +**Prefer pass 1.** Every case pass 1 decides is one that reproduces identically next week. Pass 2 exists +for evidence that is prose rather than data — a fallback, not a co-equal stage. When a class of case +keeps landing in pass 2, the fix is a new deterministic method in pass 1. §4c is exactly that: it moved +12 redis advisories out of pass 2 and into arithmetic. + +--- + +## Inputs + +``` +advisory-scan.py [--from ] [--to ] + [--image =:]... [--adjudicate] [--json] [--registry DIR] + +advisory-scan.py --compose-to [--compose-from ] # windows derived, not typed +``` + +| Input | Meaning | +|---|---| +| `` | Recipe name; selects `cc-ci-plan/upstream/.md` (the per-recipe URL registry) | +| `--from` / `--to` | The **primary app image's** version window being upgraded across | +| `--image NAME=FROM:TO` | A **sidecar image and the versions it moved between** (repeatable, all in ONE call). `NAME` is substring-matched against source repo names. Malformed values warn on stderr and are skipped. Without it that image's advisories stay unclassified. | +| `--compose-to URL` | **Derive every window by diffing this compose against its baseline**, instead of typing `--from/--to/--image`. Point it at a PR's `compose.yml`. | +| `--compose-from URL` | Baseline for the above. Default: the same repo's **default branch, resolved from the API** — never assumed to be `main`. | +| `--adjudicate` | Run pass 2: append the evidence dossier for judgement | +| `--registry` | Registry dir; also `CCCI_UPSTREAM_REGISTRY` | +| `GITHUB_TOKEN` / `GITHUB_TOKEN_FILE` | Read-only token; **rate limit only** (60/hr anonymous → 5000/hr). Default file `/srv/cc-ci/.github-token`, mode 600. Public advisories need **no scopes**. | + +Exit code is always 0 — this is informational. Failures are *reported*, never raised. + +For PR attribution, pin both compose URLs to commits: the PR head and its merge base with the +target branch. A previous release or warm canonical can include image changes already present +before the PR. A compose diff with only sidecar changes has no primary app window; every changed +sidecar is scanned under its own image name. + +--- + +# Pass 1 — deterministic + +## Step 1 — Collect source URLs from the registry + +Read `cc-ci-plan/upstream/.md` and extract every `http(s)://…` URL. + +**Trailing markdown punctuation is stripped** (`` ` `` `'` `"` `*` `.` `,` `;` `:` `>` `)`). The registry +is markdown, so URLs appear inside backticks and quotes; capturing the punctuation produced fetches of +`https://docs.n8n.io/release-notes/\`` which 404, and made immich and n8n render `?` for no real reason. + +> **Registry hygiene matters.** The scan can only look where the registry points. Two classes of defect +> have been found and fixed by running it: a **wrong URL** (`pgautoupgrade/pgautoupgrade`, which 404s — +> the repo is `pgautoupgrade/docker-pgautoupgrade`) and a **missing** one (gitea's CVEs are announced at +> `blog.gitea.com`, which the registry didn't list). When a vendor publishes security notes somewhere +> the registry lacks, add it. + +## Step 2 — Query the sources + +Three source classes, each recording **its own status** so *"checked, none found"* is never confused +with *"not checked"*. + +### 2a. GitHub Security Advisories — PRIMARY + +For every `github.com//` URL in the registry: +`GET /repos///security-advisories`. + +Captured per advisory: `cve_id`, `ghsa_id`, `severity`, `summary`, **`description`**, `published_at`, +and **all** `vulnerabilities[]` entries' `vulnerable_version_range` + `patched_versions` (joined `;`). + +- **All entries, not just the first.** An advisory carries one entry **per patched release line** — + n8n patches three (1.123.32, 2.17.4, 2.18.1). Reading only `vulnerabilities[0]` silently dropped the + line a deployment was actually on, and misclassified CVE-2026-42231/42232 as out-of-window. +- **Pagination via the `Link rel="next"` cursor**, to exhaustion (cap 20 hops). This endpoint returns + at most 100 rows **and ignores `?page=`** — it re-returns the same rows, which silently truncates busy + projects. discourse has 286 advisories; a single page cannot even cover one upgrade window. +- **The description is kept from this response.** It is already present here, and pass 2 needs the + prose; re-fetching it per advisory would cost one request each. +- **HTTP 404 ⇒ `no-advisories-published`** — a benign absence (many sidecar images publish none), **not** + a failure. Conflating the two pushed nearly every recipe to `?` and destroyed the signal. + +### 2b. Vendor release / security pages + +Every other registry URL is fetched, HTML-stripped, and scanned for `CVE-\d{4}-\d{4,7}`, keeping ±160 +characters of context per hit. + +URLs containing `<`, `>`, `{`, `}`, `VERSION`, or `vX.Y.Z` are **skipped as templates** — they are +human documentation (`…/changelog/v/`), not fetchable, and counting them as failures is wrong. + +This is the source that would have caught gitea: the vendor blog names both CVEs, the GitHub release +page names neither. + +**When the page is a changelog organised by release, each CVE is attributed to the release heading it +appears under** (`Changes with nginx 1.31.3`, `## v1.31.3`, …) and that becomes its fixed-in version. +Without this, a project that publishes no advisory feed can never contribute a CVE: + +> **nginx publishes NO GitHub security advisories.** Every nginx CVE we can see comes from +> `nginx.org/en/CHANGES`. Scraping ids out of it without attributing them to a release left them with +> no patched version, so they were never classifiable — and every nginx bump in the fleet reported +> **0** forever. nginx is a sidecar in most recipes. Measured: `1.31.1 → 1.31.3` fixes **six** CVEs +> (three in .2, three in .3); lasuite-docs#7 went 0 → 6 and lasuite-drive#6 went 0 → 3 on this alone. + +A changelog CVE is tied to a window by the **image name appearing in the page URL** (window `nginx` ↔ +`nginx.org/...`). A CVE found on a vendor page with no attributable release still has no version data, +so pass 1 cannot place it — it goes to pass 2 (§6). + +### 2c. NVD by CPE — the fallback for projects that publish nothing + +Declared per recipe in the registry as `nvd-cpe: = `. + +> **Why it exists.** Two recipes could not see CVEs *at all*: `mattermost-lts` (empty GitHub advisory +> feed, security bulletins rendered client-side so a text sweep finds nothing) and `mumble` (nothing +> published anywhere the registry points). Their scans returned `?` — nothing measured. NVD is +> CPE-indexed and carries structured ranges, so it answers where the vendor does not: mattermost +> 10.5.0 → 10.12.4 now scores **165**, and mumble finds `CVE-2025-71264` (fixed 1.6.870). + +Two range forms, both used: + +| NVD field | meaning | how it is judged | +|---|---|---| +| `versionEndExcluding X` | fixed in X exactly | a normal patched version (§4a) | +| `versionEndIncluding X` | affected **up to and including** X; fix version unpublished | fixed when the upgrade crosses X, i.e. `from ≤ X < to` | + +**NVD lags the vendor** — it had neither gitea CVSS-9.8 RCE at publication — so this is a fallback, +never a replacement for 2a/2b. Unauthenticated calls are rate-limited (~5/30s), hence the retry. + +### 2d. OSV.dev — supplementary + +Only when the recipe has an entry in `OSV_PACKAGES` (ecosystem + package) and a version is given. + +> **Measured, not assumed.** For the two gitea CVEs, OSV **404'd on both** and returned only Go +> *dependency* advisories for the package; NVD's API had them by neither CPE, CVE id, nor keyword. +> **Advisory databases lag the vendor**, which is why 2a and 2b lead and this is supplementary. + +## Step 3 — Union + +All findings merge into one CVE map: id → `{sources[], severity, ghsa, vulnerable_range, patched, +description, published_at, url, cvss, context}`. A CVE seen by several sources keeps them all. + +## Step 4 — Classify against the upgrade window + +Two invariants govern this step, both learned from a wrong answer in production. + +> **A. Every image is judged by its OWN versions.** The app repo uses `--from/--to`; each sidecar uses +> its own `--image NAME=FROM:TO`. **Pass them all in ONE invocation** — the count is a union across +> images, and the UNKNOWN guarantee in B only holds when a single run sees every one. An image with no +> window is **not** classified; its advisories are listed as unclassified so they stay visible without +> inflating the count. Each window is classified independently, so one may use version ranges while +> another falls back to dates. +> *Why:* discourse once reported **133**, of which **34 were redis CVEs** — including +> `CVE-2021-21309`, patched in redis 6.0.11 in 2021 — counted purely because 6.0.11 sits numerically +> inside discourse's `3.5.3 → 2026.7.1` range. The fix is not to ignore sidecars but to give each one +> the versions it actually moved through: with `--image redis=7.4:8.10`, discourse scores +> **140 = 123 (app, by date) + 17 (redis)**, and the redis seventeen include `CVE-2025-49844`, +> **critical**, invisible while sidecars went uncounted. +> +> **B. Never emit a number you cannot justify.** If no method can order a window, the count is +> `null` / `UNKNOWN`, never `0`. A `0` in a security column asserts safety. Equally, an advisory that +> cannot be judged is **indeterminate** (§4d) — never silently counted as "not fixed". + +### 3b. Deriving the windows from a compose diff (`--compose-to`) + +Typing `--from/--to/--image` by hand means someone has to remember that the recipe also bumped its +redis. That is how sidecar CVEs went uncounted for months. This mode reads the windows off the diff: + +1. Fetch both compose files (baseline = the repo's **default branch from the API**, since several + recipes keep a stale `main` beside a live `master`). +2. Parse `{service: (image-repo, tag)}` — keyed by **service, not image repo**, because an upgrade + may change the repo itself (plausible moved `plausible/analytics` → + `ghcr.io/plausible/community-edition`; keyed by repo that reads as one image vanishing and an + unrelated one appearing, losing the app window entirely). +3. Every service whose tag or repo changed becomes a window. The `app` service drives `--from/--to` + (coop-cloud convention: it is the recipe's primary image); the rest become `--image` windows. + Unchanged images produce no window — inventing one would be a false count. +4. The derived windows are printed to stderr before the scan, so the inputs are auditable. + +Image names are matched against advisory sources **both ways** — an image name is often longer than +its source repo (`clickhouse/clickhouse-server` vs `ClickHouse/ClickHouse`) and sometimes shorter +(`redis` vs `redis/redis`). + +Verified on plausible PR #5: from the compose URL alone it derives `v2.0.0 → v3.2.1` plus +`clickhouse-server 23.4.2.11-alpine → 24.12-alpine`, and reports **6** — identical to the +hand-specified args. + +`--from/--to/--image` remain available for finer-grained checks (scanning a window that is not a +literal compose diff, e.g. "what would the compatibility-safe target fix?"). + +### 4a. By patched version (preferred — exact) + +**A fix on the line you are upgrading FROM was already yours.** Projects that maintain several lines +patch them all at once: mattermost fixed `CVE-2025-11794` in 10.11.4, 10.12.1 *and* 10.5.12. An +upgrade 10.11.22 → 10.12.4 crosses 10.12.1, so a naive window test counts it — but 10.11.22 is +already past 10.11.4, so the deployment had the fix before the upgrade. Counting it credits the +upgrade with work it did not do. This check is **skipped for placeholder versions** (`7.4.X` parses +to a bare `7.4`, which would read as "already fixed at 7.4" and silently drop a real fix — exactly +how redis `CVE-2024-46981` was lost when the rule was first added). + + +`patched_versions` is a **range expression** (`">= 2.18.1"`), possibly several joined by `;`. Extract +every version-looking token; the advisory is **fixed-by-this-upgrade** if **any** patched version `p` +satisfies `from < p <= to` — exclusive lower (a fix already in the version you were on is not this +upgrade's doing), inclusive upper. + +**Comparison is zero-padded to equal length**, so `18` == `18.0` == `18.0.0` as semver means it. +Without padding, plain tuple order makes `(18,) < (18,0)`, i.e. a fix in 18.0 falls *outside* a window +ending at 18 — and bare major tags are the norm for sidecars (`postgres:18`, `redis:8-alpine`). Padding +is permissive at the lower bound and conservative at the upper: with `to = 18`, a fix in `18.5` is +**not** counted, because nothing proves which 18.x a floating tag resolved to. + +### 4b. By advisory publish date (fallback — temporal) + +Used **only** when 4a cannot be trusted: a **version-scheme change**, detected as the leading version +component jumping by ≥ `SCHEME_JUMP` (100) — e.g. semver `3.5.3` → calver `2026.7.1`. + +Version strings are unorderable across such a jump (`2025.12.2` compares "newer" than `3.5.3` while +shipping earlier), but **release dates always order**. So: + +1. Resolve `--from` and `--to` to **git tag dates** on that source (tries `v` then + ``; annotated tag → tagger date, else commit date). +2. An advisory counts as fixed when `date_from < published_at <= date_to` — the same exclusive/inclusive + boundaries as 4a, so the two methods agree at the edges. + +This reproduces, automatically, the hand count that established discourse `3.5.3` (2025-12-30) → +`2026.7.1` (2026-07-31) = **123 CVEs**. + +*Assumption:* the vendor publishes advisories at fix time (true for discourse). The count includes +**first-party plugin advisories** where the vendor files them on the same repo — which is why a +plugin-rich project scores far higher than a monolith, not a statement about relative security. + +### 4c. By release notes naming the CVE (rescue — for advisories with no fix version) + +Applied to advisories 4a/4b could not decide, **before** giving up on them. Fetch the source repo's +GitHub **releases** (cached per repo, 4 pages) and find every tag whose notes **name the CVE id**. If +any such tag falls inside the window by 4a's rule, the advisory is fixed by this upgrade, and the +naming tags are recorded in `fix_versions_from_release_notes` as the citation. + +> **Why this is not optional.** Vendors routinely publish an advisory with `patched_versions: "TBD"` +> and then name the CVE in the release notes of every branch that got the fix. **All 12** redis +> advisories crossed by discourse's redis bump are exactly this shape — `TBD`, or a placeholder like +> `7.4.X`, with an open-ended `vulnerable_version_range` (`All`, `>= 7.0.0`) — yet each is named in +> concrete releases (`CVE-2025-32023` → 6.2.19, 7.2.10, 7.4.5, 8.0.3, 8.2.0). Without this method +> discourse's redis contribution reads 5; with it, 17. Six of the twelve are high severity. + +### 4d. Otherwise — indeterminate, not excluded + +An advisory from a **windowed** source that none of 4a–4c could decide — no usable `patched_versions`, +an open-ended vulnerable range, and no release note naming it — is recorded as **indeterminate**. It is: + +- **not** added to the count (nothing justifies counting it), and +- **not** treated as unaffected (nothing justifies dismissing it either). + +It is listed prominently, the headline reads *"(at least — see undetermined below)"*, and it becomes an +input to pass 2. Silently excluding these is the same defect class as printing `0` for an unscanned +recipe, one level down. + +### 4e. Unorderable window + +If neither 4a nor 4b can order a window at all, `count_known = false`, `cve_count_fixed = null`, and the +headline reads **"CVEs fixed by this upgrade: UNKNOWN — the scan could NOT determine a count"** with an +explicit *"This is NOT zero"*. If **any** requested window is unorderable the whole count is suppressed; +a partial number would understate a security figure. + +## Step 5 — Output + +Markdown (default) for pasting into the per-recipe upgrade log, or `--json`. + +| Field | Meaning | +|---|---| +| `cve_count_fixed` | Union across all windows, or **`null`** if any window was unorderable | +| `count_known` | Distinguishes "counted zero" from "could not count" | +| `cve_count_indeterminate` / `indeterminate[]` | Judged by nothing; a **floor marker** on the count | +| `resolved_by_release_notes` | CVE → the tags that named it (4c citations) | +| `windows` | Every source classified, with its from/to | +| `classified_by` | **Per source**: which method decided it | +| `date_window` | **Per source**, when 4b was used | +| `fixed_by_this_upgrade[]` | CVE ids, with severity / GHSA / fixed-in per id | +| `unclassified[]` | Seen but not attributable (other images, or vendor-page-only) | +| `sources[]` / `sources_failed[]` / `sources_benign[]` | Per-source status; only genuine failures in `failed` | + +--- + +# Pass 2 — adjudication (`--adjudicate`) + +## Step 6 — What gets judged + +Two kinds of open case, both real gaps rather than noise: + +1. **Indeterminate** (§4d) — from an image *with* a window, but no fix version is knowable anywhere. +2. **Vendor-page-only** — a CVE seen only on a vendor security page, with no structured advisory + behind it. **gitea's two CVSS-9.8 RCEs are this shape.** They carry no version data, so no + arithmetic can place them, but the page prose usually states the fixed release. + +## Step 7 — The evidence dossier + +Pass 1 collects; pass 2 judges. Nothing in the dossier interprets — it assembles what was *measured*, +so the judgement is made against evidence rather than recollection. That distinction is the whole +point: the original failure was a report leaning on model knowledge that predated the CVEs, with no +source queried at all. + +Per open case: severity, CVSS, sources, its window, why it is undecided, `patched_versions` and +`vulnerable_version_range` **as published**, summary, full description, references, affected ranges +with `first_patched_version`, and **every release tag naming the CVE** — whether or not in window, since +the model may reason about branch lines the arithmetic deliberately will not. + +**Pass 2 also sees every decision pass 1 made** — a compact table of counted and excluded advisories +with the evidence behind each verdict. A deterministic verdict can still be wrong (a mis-parsed range, +a release note that mentions a CVE without fixing it), and only a reader with the evidence in front of +it can catch that. Silence means agreement. + +## Step 8 — The verdict contract + +For each open case: **FIXED** / **NOT-FIXED** / **STILL-UNKNOWN**, each with a one-line reason +**citing the evidence shown**. Every FIXED is added to the recipe's count — pass 1's number is a floor, +not a total. If the evidence does not settle it, **STILL-UNKNOWN**: do not infer from memory of the +project, and never record an undecided CVE as unaffected. + +**No silent caps.** `MAX_ADJUDICATE` (25) and `MAX_REVIEW_ROWS` (400) bound the output; whenever either +truncates, the block says how many were dropped and that the unshown remain undetermined. + +--- + +## How consumers must read it + +`/recipe-report` renders the `cve` column from the **union** of this scan and the agent's own reading: + +- a clean scan → its number, **including `0`**; +- **failed sources**, or `UNKNOWN` → **`?`**, never `none` — a blank reads as "clean", which is exactly + how two CVSS-9.8 gitea RCEs were published as `none`; +- **no upgrade this run** → `0`, not `?` — nothing an upgrade could have fixed; +- a count with **indeterminate advisories** → the number is a floor; say so in the notes; +- benign notes → never `?`. + +`?` must stay **rare**: it means *we tried and could not tell*, not *we did not look*. A rash of `?` is +a bug to raise in the report's Addendum, not a normal outcome — every instance so far traced to a defect +in this tool or stale registry data. + +## Testing + +`test-advisory-scan.py` — 58 offline tests (fixtures, no network) plus 6 live regressions against the +counts published in week-2026-08-07. **The offline tier covers pass 1 only, by design**: pass 2's +judgement is a model's and cannot be asserted deterministically. What *is* tested about pass 2 is the +part that stays deterministic — which cases it selects, and that truncation is always announced. + +``` +python3 test-advisory-scan.py # offline +python3 test-advisory-scan.py --live # + historic report numbers +``` + +`audit-advisory-scan.py` re-derives the counts with a **separate** semver implementation and its own +release fetch, then diffs against the scanner. Run it after changing classification; it is what caught +the 12 undercounted redis CVEs. + +## Known limits + +1. **Versions must be supplied per image.** An image with no `--image` is not counted — the scan will + not guess a version range it was not given. `/recipe-upgrade` passes one per image it bumped. +2. **Date-based counts are temporal**, not exact — they assume publish-at-fix-time. +3. **Registry-bound.** Unlisted vendor security pages are invisible; the scan cannot know what it was + never pointed at. +4. **`NAME` matching is substring-against-source-name**, so a short or generic name can attach to more + than one repo (`postgres` matches `discourse/discourse-postgres`). The primary source is claimed + first and cannot be stolen. A name matching **nothing** is silently ignored — a typo costs coverage + without warning. +5. **Release-note rescue (4c) trusts that naming implies fixing.** A release note that merely mentions a + CVE would be read as fixing it. Pass 2's review table exists partly to catch this. +6. **Rate limit** without a token is 60/hr — a full weekly sweep will exhaust it and degrade to failed + sources (visibly, but degraded). diff --git a/scripts/cc-ci/advisory-scan.py b/scripts/cc-ci/advisory-scan.py new file mode 100755 index 0000000..a38e407 --- /dev/null +++ b/scripts/cc-ci/advisory-scan.py @@ -0,0 +1,1437 @@ +#!/usr/bin/env python3 +"""Deterministic per-recipe CVE/advisory scan — an ADDITIVE pre-step for /recipe-upgrade. + +WHY THIS EXISTS (2026-08-10): gitea 1.27.1 fixed two CVSS-9.8 RCEs (CVE-2026-60004, +CVE-2026-59774). Our weekly report showed gitea's CVE count as "1", then "none". The upgrade +subagent had scanned the GitHub *release notes*, which mention neither; the two CVEs were announced +only in the vendor's blog security section. The report generator then derived security content from +those notes plus model knowledge — and the model's training predates the CVEs. Nothing in the +pipeline ever queried an advisory source, so a critical CVE that is newer than the model and absent +from the changelog was invisible by construction. + +WHAT IT DOES NOT DO: it does not replace or alter any existing security analysis. It is a strictly +ADDITIONAL evidence source whose findings are unioned into the CVE count. + +SOURCES (measured against the gitea case before being chosen): + 1. GitHub Security Advisories API — repos///security-advisories. PRIMARY: carries + CVE id, GHSA id, severity AND vulnerable/patched version ranges, so "fixed by THIS upgrade" is + computable rather than guessed. Found both gitea CVEs. Derived from the source-repo URLs the + per-recipe registry already records — no new per-recipe config needed. + 2. Vendor release/security pages — every URL in cc-ci-plan/upstream/.md, fetched and + regex-scanned for CVE ids. This is what would have caught gitea: the vendor blog names both, + while the GitHub releases page names neither. Add vendor security/announcement URLs to the + registry to widen this. + 3. OSV.dev — supplementary, best-effort, only when the recipe declares an ecosystem/package + mapping below. NOTE: for gitea, OSV returned only Go *dependency* advisories and 404'd on both + application CVEs; NVD's API had them neither by CPE, CVE id, nor keyword. Advisory databases + lag the vendor — which is exactly why (1) and (2) lead. + +Every source reports its own status, so "checked, none found" is never confused with "not checked". + +Usage: + advisory-scan.py [--from ] [--to ] [--json] [--registry DIR] + + --from/--to are the app versions being upgraded between (e.g. 1.26.2 -> 1.27.1). When given, each + advisory is classified fixed-by-this-upgrade / still-open / older. Without them everything known + is listed unclassified. Exits 0 even when sources fail (informational; failures are reported). +""" + +from __future__ import annotations + +import argparse +import gzip +import ipaddress +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +REGISTRY_DIR = os.environ.get("CCCI_UPSTREAM_REGISTRY", "/srv/cc-ci/cc-ci-plan/upstream") +UA = "cc-ci-advisory-scan (+https://git.autonomic.zone/recipe-maintainers/cc-ci)" +TIMEOUT = int(os.environ.get("ADVISORY_SCAN_TIMEOUT", "45")) +CVE_RE = re.compile(r"CVE-\d{4}-\d{4,7}") +# Leading-version-component jump that means the scheme changed (semver → calver). +SCHEME_JUMP = 100 +# A patched_versions field that names no usable version. GitHub carries these verbatim from the +# vendor: redis publishes "TBD" for 11 advisories and "6.2.X, 7.2.X, 7.4.X" for another, and their +# vulnerable_version_range is open-ended ("All", ">= 7.0.0"), so the fix version is NOT recoverable. +# Such an advisory must be reported as INDETERMINATE, never silently counted as "not fixed" — that +# would assert an upgrade did not fix something we simply cannot judge. +PLACEHOLDER_RE = re.compile(r"\bTBD\b|\bunknown\b|\bnone\b|\d+\.[Xx]\b|\?", re.I) + +# Optional OSV mappings: recipe -> (ecosystem, package). Supplementary only (see module docstring). +OSV_PACKAGES: dict[str, tuple[str, str]] = { + "gitea": ("Go", "code.gitea.io/gitea"), + "n8n": ("npm", "n8n"), +} + + +def _github_token() -> str | None: + """Read-only GitHub token, for the API rate limit ONLY (60/hr anonymous → 5000/hr with a token). + + Env `GITHUB_TOKEN` wins; otherwise the file at `GITHUB_TOKEN_FILE` (default + /srv/cc-ci/.github-token, chmod 600, never in git). Reading PUBLIC security advisories needs NO + scopes at all — create a classic PAT with every box unticked, or a fine-grained token limited to + "Public repositories: read". Do NOT grant repo/write scopes: this tool only ever GETs advisories. + A missing token is not an error — the scan simply runs anonymously and will report sources as + failed once the 60/hr limit bites, which is visible rather than silent. + """ + tok = os.environ.get("GITHUB_TOKEN") + if tok: + return tok.strip() + path = os.environ.get("GITHUB_TOKEN_FILE", "/srv/cc-ci/.github-token") + try: + with open(path) as f: + return f.read().strip() or None + except OSError: + return None + + +def _gh_paginate(url: str, hdrs: dict, max_pages: int = 20): + """Yield every row from a GitHub list endpoint, following Link rel=\"next\" cursors.""" + seen_keys = set() + for _ in range(max_pages): + req = urllib.request.Request(url, headers={"User-Agent": UA, **hdrs}) + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + rows = json.load(r) + link = r.headers.get("Link", "") or "" + fresh = 0 + for a in rows: + k = a.get("ghsa_id") or json.dumps(a, sort_keys=True)[:120] + if k not in seen_keys: + seen_keys.add(k); fresh += 1 + yield a + nxt = None + for part in link.split(","): + if 'rel="next"' in part: + nxt = part.split(";")[0].strip().strip("<>") + if not nxt or fresh == 0: + return + url = nxt + + +def _tag_date(owner: str, repo: str, version: str | None) -> str | None: + """Publish date of a release tag, for DATE-BASED classification (see classify_by_date). + + Version strings cannot be ordered across a scheme change (semver → calver), but tag dates + always can. Tries the common tag spellings; returns an ISO timestamp or None.""" + if not version: + return None + hdrs = {"Accept": "application/vnd.github+json"} + tok = _github_token() + if tok: + hdrs["Authorization"] = f"Bearer {tok}" + for tag in (f"v{version}", version): + try: + ref = json.loads(_fetch(f"https://api.github.com/repos/{owner}/{repo}/git/ref/tags/{tag}", hdrs)) + obj = ref.get("object", {}) + sha, typ = obj.get("sha"), obj.get("type") + if typ == "tag": + t = json.loads(_fetch(f"https://api.github.com/repos/{owner}/{repo}/git/tags/{sha}", hdrs)) + if t.get("tagger", {}).get("date"): + return t["tagger"]["date"] + sha = t.get("object", {}).get("sha") + c = json.loads(_fetch(f"https://api.github.com/repos/{owner}/{repo}/commits/{sha}", hdrs)) + return c["commit"]["committer"]["date"] + except Exception: # noqa: BLE001 — try the next spelling + continue + return None + + +def _fetch(url: str, headers: dict | None = None) -> str: + h = {"User-Agent": UA, "Accept-Encoding": "gzip"} + h.update(headers or {}) + with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=TIMEOUT) as r: + raw = r.read() + if r.headers.get("Content-Encoding") == "gzip": + raw = gzip.decompress(raw) + return raw.decode(errors="replace") + + +def _vkey(v: str | None) -> tuple: + """Loose version ordering key: leading integers of each dot-part ('1.27.1-rootless' -> (1,27,1)).""" + if not v: + return () + v = v.strip().lstrip("vV").split("+")[0] + out = [] + for part in re.split(r"[.\-_]", v): + m = re.match(r"^\d+", part) + if m: + out.append(int(m.group())) + elif out: + break + return tuple(out) + + +def _nvd_affects(version: str | None, ranges: list[dict]) -> bool | None: + """Whether NVD marks a concrete image version affected; None means tag lacks precision.""" + current = _vkey(version) + if not current: + return None + uncertain = False + for row in ranges: + exact = _vkey(row.get("version")) if row.get("version") not in (None, "*") else () + bounds = [(name, _vkey(row.get(name))) for name in ( + "versionStartIncluding", "versionStartExcluding", + "versionEndIncluding", "versionEndExcluding") if row.get(name)] + versions = ([exact] if exact else []) + [value for _, value in bounds] + if any(not value for value in versions): + uncertain = True + continue + if any(len(value) > len(current) and value[:len(current)] == current for value in versions): + uncertain = True # e.g. postgres:13-alpine does not say which 13.x patch is running + continue + def compare(other): + length = max(len(current), len(other)) + return (current + (0,) * (length - len(current))) > (other + (0,) * (length - len(other))) + if exact and current != exact: + continue + def outside(name, value): + if name == "versionStartExcluding": + return not compare(value) + if name == "versionStartIncluding": + return not compare(value) and current != value + if name == "versionEndIncluding": + return compare(value) + return compare(value) or current == value # versionEndExcluding + if any(outside(name, value) for name, value in bounds): + continue + return True + return None if uncertain else False + + +def _already_fixed_on_from_line(kf: tuple, cands: list[tuple]) -> bool: + """Was it ALREADY fixed on the line we are upgrading FROM? + + The mirror image of _superseded_on_target_line, and just as necessary. mattermost fixes each CVE + across several maintained lines at once — CVE-2025-11794 is patched in 10.11.4, 10.12.1 and + 10.5.12. Upgrading 10.11.22 -> 10.12.4 crosses 10.12.1, so a naive window test counts it; but + 10.11.22 is already past 10.11.4, so the deployment HAD the fix before the upgrade. Counting it + credits the upgrade with work it did not do.""" + if len(kf) < 2: + return False + line = kf[:2] + for c in cands: + if len(c) < 2 or c[:2] != line: + continue + n = max(len(kf), len(c)) + pad = lambda z: z + (0,) * (n - len(z)) + if pad(c) <= pad(kf): + return True + return False + + +def _superseded_on_target_line(kt: tuple, cands: list[tuple]) -> bool: + """Does a patched version on the TARGET's own release line sit ABOVE the target? + + Projects maintain several branches at once and backport per branch, so "some patched version is + inside the numeric window" is not the same as "the version we land on has the fix". ClickHouse + fixed CVE-2023-48704 in 23.9.6.20 AND 23.10.5.20; an upgrade landing on 23.10.4.25 crosses the + 23.9 fix numerically but is still BELOW its own line's fix, so it does NOT have it. When the + advisory names a fix on the target's own line and the target is older than it, that is proof of + absence and outranks any other candidate.""" + if len(kt) < 2: + return False + line = kt[:2] + return any(c[:2] == line and c > kt for c in cands if len(c) >= 2) + + +def _within(kf: tuple, kt: tuple, c: tuple) -> bool: + """Is patched-version `c` inside the window (kf, kt] — exclusive lower, inclusive upper? + + Compares ZERO-PADDED to equal length, so "18" == "18.0" == "18.0.0" the way semver means it. + Without the padding, plain tuple order says (18,) < (18,0), i.e. a CVE patched in 18.0 falls + OUTSIDE a window ending at 18 — and bare major tags are the norm for sidecars (postgres:18, + redis:8-alpine), so that silently dropped real fixes. Padding also keeps the upper bound + conservative: a fix in 18.5 is still outside a window ending at "18", because nothing proves + which 18.x a floating tag resolved to. + """ + n = max(len(kf), len(kt), len(c)) + pad = lambda t: t + (0,) * (n - len(t)) + return pad(kf) < pad(c) <= pad(kt) + + +def registry_urls(recipe: str, registry_dir: str) -> tuple[list[str], str | None]: + path = os.path.join(registry_dir, f"{recipe}.md") + try: + with open(path) as f: + text = f.read() + except OSError: + return [], None + urls = [] + for u in re.findall(r"https?://[^\s)|\]]+", text): + # The registry is MARKDOWN: urls appear inside `backticks`, 'quotes', **bold**, and at the + # end of sentences. Trailing punctuation captured into the url makes the fetch 404 and the + # recipe render '?' for no real reason — that is what put immich and n8n in the unknown + # column on 2026-08-07 (https://docs.n8n.io/release-notes/` ← note the backtick). + u = u.rstrip("`'\"*.,;:>)") + if "…" in u or "..." in u: + continue # prose placeholder, not a fetchable security source + host = urllib.parse.urlsplit(u).hostname + if not host or host == "localhost" or "." not in host: + continue # a container/loopback URL in operational notes, not a public advisory source + try: + if not ipaddress.ip_address(host).is_global: + continue + except ValueError: + pass + if u and u not in urls: + urls.append(u) + return urls, path + + +def github_advisories(urls: list[str]) -> list[dict]: + """Query GitHub Security Advisories for every github.com// in the registry.""" + seen, results = set(), [] + for u in urls: + m = re.match(r"https?://github\.com/([^/]+)/([^/#?]+)", u) + if not m: + continue + owner, repo = m.group(1), m.group(2).removesuffix(".git") + if (owner, repo) in seen: + continue + seen.add((owner, repo)) + api = f"https://api.github.com/repos/{owner}/{repo}/security-advisories?per_page=100" + hdrs = {"Accept": "application/vnd.github+json"} + tok = _github_token() + if tok: + hdrs["Authorization"] = f"Bearer {tok}" + entry = {"source": f"github-advisories:{owner}/{repo}", "status": "ok", "advisories": []} + try: + # PAGINATE. This endpoint caps at 100 per response and IGNORES ?page= — it returns the + # same rows again, which silently truncates busy projects (discourse has 286; a hand + # count on 2026-08-10 found 123 CVEs in one upgrade window that a single page missed). + # Follow the Link rel="next" cursor to exhaustion instead. + for a in _gh_paginate(api, hdrs): + # An advisory carries ONE ENTRY PER PATCHED RELEASE LINE. n8n patches three + # (1.123.32, 2.17.4, 2.18.1); reading only vulnerabilities[0] silently dropped the + # line our deployment is actually on, so CVE-2026-42231/42232 classified as + # out-of-window. Keep them ALL and let the classifier match any of them. + vulns = a.get("vulnerabilities") or [] + entry["advisories"].append( + { + "cve": a.get("cve_id"), + "ghsa": a.get("ghsa_id"), + "severity": a.get("severity"), + "summary": (a.get("summary") or "")[:200], + "vulnerable_range": "; ".join( + filter(None, (v.get("vulnerable_version_range") for v in vulns)) + ) or None, + "patched": "; ".join( + filter(None, (v.get("patched_versions") for v in vulns)) + ) or None, + "url": a.get("html_url"), + "published_at": a.get("published_at"), + # The list response ALREADY carries the prose. Keep it: the adjudication + # pass needs it, and re-fetching per advisory costs a request each. + "description": (a.get("description") or "")[:4000], + "cvss": ((a.get("cvss") or {}).get("vector_string")), + } + ) + except urllib.error.HTTPError as e: + # 404 = this repo simply publishes no security advisories (e.g. sidecar images like + # pgautoupgrade). That is a BENIGN ABSENCE, not a failed check — conflating the two + # would push nearly every recipe to "unknown" and make the ? signal meaningless again. + entry["status"] = "no-advisories-published" if e.code == 404 else f"error: HTTP {e.code}" + except Exception as e: # noqa: BLE001 — a genuinely dead source must be REPORTED, never silent + entry["status"] = f"error: {type(e).__name__}: {e}" + results.append(entry) + return results + + +# Release headings in a vendor changelog. nginx's CHANGES uses "Changes with nginx 1.31.3", most +# markdown changelogs use "## 1.31.3" / "## v1.31.3". +_HEADING_RE = re.compile( + r"^\s*(?:#{1,4}\s*)?(?:Changes with\s+\S+\s+|Version\s+|Release\s+)?v?(\d+\.\d+(?:\.\d+)*)\s*$" + r"|^\s*Changes with\s+\S+\s+(\d+\.\d+(?:\.\d+)*)", re.I) + + +def _changelog_versions(text: str) -> dict: + """{cve: version} for a changelog that is ORGANISED BY RELEASE. + + Why this exists: nginx publishes NO GitHub security advisories. Every nginx CVE we can see comes + from nginx.org/en/CHANGES, and scraping ids out of it without attributing them to a release + leaves them with no patched version — so they can never be classified, and an nginx bump reports + 0 CVEs forever. nginx 1.31.1 -> 1.31.3 in fact fixes SIX (three in .2, three in .3), and nginx is + a sidecar in most of the fleet, so that was a fleet-wide blind spot. + + Attributes each CVE to the nearest PRECEDING release heading — the release that fixed it. + """ + plain = re.sub(r"<[^>]+>", " ", text) + out, cur = {}, None + for line in plain.splitlines(): + m = _HEADING_RE.match(line) + if m: + cur = m.group(1) or m.group(2) + continue + if cur: + for cve in CVE_RE.findall(line): + out.setdefault(cve, cur) + return out + + +_BLOB_RE = re.compile(r"^https://github\.com/([^/]+)/([^/]+)/blob/(.+)$") + + +def _raw_if_blob(url: str) -> str: + """A GitHub *blob* URL is an HTML viewer, not the file. + + The registry pointed ONLYOFFICE's CHANGELOG.md at its blob page. Fetching that returns 636KB of + markup in which the release headings do not survive HTML-stripping, so 24 CVEs were visible and + NONE attributable to a release — the same shape of blind spot as nginx. The raw URL attributes + all 24. Normalising here fixes every registry entry at once, present and future.""" + m = _BLOB_RE.match(url) + return f"https://raw.githubusercontent.com/{m.group(1)}/{m.group(2)}/{m.group(3)}" if m else url + + +def vendor_pages(urls: list[str]) -> list[dict]: + """Fetch each registry URL and regex out CVE ids, with a little surrounding context.""" + out = [] + for u in urls: + if u.startswith("https://api.github.com"): + continue + if re.search(r"[<>{}]|\bVERSION\b|\bvX\.Y\.Z\b", u): + # Registry entries sometimes carry TEMPLATE urls for humans + # (…/changelog/v/). They are documentation, not fetchable — skipping them is + # correct; counting them as failures would wrongly mark the recipe's count unreliable. + out.append({"source": u, "status": "skipped: template URL (not fetchable)", "cves": [], "context": {}}) + continue + entry = {"source": u, "status": "ok", "cves": [], "context": {}, "fixed_in": {}} + try: + text = _fetch(_raw_if_blob(u)) + plain = re.sub(r"<[^>]+>", " ", text) + for cve in sorted(set(CVE_RE.findall(plain))): + entry["cves"].append(cve) + i = plain.find(cve) + entry["context"][cve] = re.sub(r"\s+", " ", plain[max(0, i - 160) : i + 200]).strip() + entry["fixed_in"] = _changelog_versions(text) + except Exception as e: # noqa: BLE001 + entry["status"] = f"error: {type(e).__name__}: {e}" + out.append(entry) + return out + + +NVD_API = "https://services.nvd.nist.gov/rest/json/cves/2.0" +NVD_CPE_RE = re.compile(r"^\s*[-*]?\s*nvd-cpe:\s*(\S+)\s*=\s*(cpe:2\.3:[^\s`]+)", re.M | re.I) +_NVD_CACHE: dict[str, dict] = {} +COMMON_IMAGE_CPES = { + "postgres": "cpe:2.3:a:postgresql:postgresql:*:*:*:*:*:*:*:*", + "mariadb": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", + "mysql": "cpe:2.3:a:oracle:mysql:*:*:*:*:*:*:*:*", +} + + +def registry_cpes(recipe: str, registry_dir: str) -> list[tuple[str, str]]: + """Explicit CPEs plus common database CPEs for images listed in the registry table.""" + path = os.path.join(registry_dir, f"{recipe}.md") + try: + text = open(path).read() + except OSError: + return [] + out = [(m.group(1), m.group(2)) for m in NVD_CPE_RE.finditer(text)] + explicit = {key for key, _ in out} + for line in text.splitlines(): + if not line.startswith("|"): + continue + cells = [cell.strip().strip("`") for cell in line.strip().strip("|").split("|")] + if len(cells) < 2: + continue + image = cells[1].split("/")[-1].lower() + if image in COMMON_IMAGE_CPES and image not in explicit: + out.append((image, COMMON_IMAGE_CPES[image])) + explicit.add(image) + return out + + +def registry_image_sources(recipe: str, registry_dir: str) -> dict[str, set[str]]: + """Map image repo basenames to GitHub advisory sources from the registry table.""" + path = os.path.join(registry_dir, f"{recipe}.md") + try: + lines = open(path).read().splitlines() + except OSError: + return {} + out: dict[str, set[str]] = {} + for line in lines: + if not line.startswith("|"): + continue + cells = [cell.strip().strip("`") for cell in line.strip().strip("|").split("|")] + if len(cells) < 3: + continue + image = cells[1].split("/")[-1].lower() + match = re.search(r"https?://github\.com/([^/\s|]+)/([^/\s|)]+)", cells[2]) + if not match or image in ("image", "---", ""): + continue + source = f"github-advisories:{match.group(1)}/{match.group(2).removesuffix('.git')}" + out.setdefault(image, set()).add(source) + return out + + +def nvd_advisories(cpe: str, key: str) -> dict: + """CVEs for a CPE from NVD, with the version data the classifier needs. + + THE FALLBACK FOR PROJECTS THAT PUBLISH NOTHING MACHINE-READABLE. mattermost's GitHub advisory + feed is empty and its security bulletins are client-side rendered; mumble publishes neither. Both + scanned as `?` — nothing measured — until here. NVD is CPE-indexed and carries structured ranges: + + versionEndExcluding X -> fixed in X exactly (a patched version) + versionEndIncluding X -> affected up to and INCLUDING X, fixed in some later release. The + exact fix version is unknown, but the upgrade fixes it whenever it + crosses X — recorded as `affected_max` and judged in the classifier. + + NVD LAGS the vendor (it had neither gitea CVSS-9.8 RCE at publication), so this is a fallback, + never a replacement for 2a/2b. Unauthenticated calls are rate-limited to ~5/30s, hence the retry. + """ + if cpe in _NVD_CACHE: + return {**_NVD_CACHE[cpe], "source": f"nvd:{key}"} + entry = {"source": f"nvd:{key}", "status": "ok", "advisories": []} + url = f"{NVD_API}?resultsPerPage=2000&virtualMatchString={urllib.parse.quote(cpe)}" + data = None + for attempt in range(3): + try: + data = json.loads(_fetch(url)) + break + except Exception as e: # noqa: BLE001 + if attempt == 2: + entry["status"] = f"error: {type(e).__name__}" + return entry + time.sleep(8) + vulnerabilities = (data or {}).get("vulnerabilities", []) + if (data or {}).get("totalResults", len(vulnerabilities)) > len(vulnerabilities): + entry["status"] = "error: NVD result set truncated" + return entry + for v in vulnerabilities: + c = v.get("cve") or {} + cid = c.get("id") + if not cid or c.get("vulnStatus") == "Rejected": + continue + fixed, affected_max, affected_ranges = set(), set(), [] + cpe_product = ":".join(cpe.split(":")[:5]) + ":" + cpe_edition = cpe.split(":")[9] if len(cpe.split(":")) > 9 else "*" + for cfg in c.get("configurations", []): + for node in cfg.get("nodes", []): + for m in node.get("cpeMatch", []): + criteria = m.get("criteria") or "" + if not m.get("vulnerable") or not criteria.startswith(cpe_product): + continue + edition = criteria.split(":")[9] if len(criteria.split(":")) > 9 else "*" + if cpe_edition != "*" and edition not in (cpe_edition, "*"): + continue + affected_ranges.append({k: m.get(k) for k in ( + "versionStartIncluding", "versionStartExcluding", + "versionEndIncluding", "versionEndExcluding") if m.get(k)}) + affected_ranges[-1]["version"] = criteria.split(":")[5] + if m.get("versionEndExcluding"): + fixed.add(m["versionEndExcluding"]) + elif m.get("versionEndIncluding"): + affected_max.add(m["versionEndIncluding"]) + sev = None + for mk in ("cvssMetricV31", "cvssMetricV30", "cvssMetricV2"): + got = (c.get("metrics") or {}).get(mk) or [] + if got: + sev = (got[0].get("cvssData") or {}).get("baseSeverity") + break + entry["advisories"].append({ + "cve": cid, "ghsa": None, "severity": (sev or "").lower() or None, + "summary": next((d.get("value") for d in c.get("descriptions", []) + if d.get("lang") == "en"), "")[:200], + "vulnerable_range": None, + "patched": "; ".join(sorted(fixed)) or None, + "affected_max": "; ".join(sorted(affected_max)) or None, + "affected_ranges": affected_ranges or None, + "url": f"https://nvd.nist.gov/vuln/detail/{cid}", + "published_at": c.get("published"), "description": None, "cvss": None, + }) + _NVD_CACHE[cpe] = entry + return entry + + +def osv(recipe: str, version: str | None) -> dict | None: + pkg = OSV_PACKAGES.get(recipe) + if not pkg or not version: + return None + eco, name = pkg + entry = {"source": f"osv:{eco}/{name}@{version}", "status": "ok", "cves": []} + try: + body = json.dumps({"package": {"name": name, "ecosystem": eco}, "version": version}).encode() + req = urllib.request.Request( + "https://api.osv.dev/v1/query", data=body, + headers={"Content-Type": "application/json", "User-Agent": UA}, method="POST", + ) + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + data = json.load(r) + ids = set() + for v in data.get("vulns", []): + for a in [v.get("id")] + (v.get("aliases") or []): + if a and a.startswith("CVE"): + ids.add(a) + entry["cves"] = sorted(ids) + except Exception as e: # noqa: BLE001 + entry["status"] = f"error: {type(e).__name__}: {e}" + return entry + + +_RELEASE_CACHE: dict[str, list[tuple[str, str]]] = {} + + +def _releases(owner: str, repo: str, max_pages: int = 4) -> list[tuple[str, str]]: + """[(tag, body)] for a repo's GitHub releases, cached per repo for the process.""" + key = f"{owner}/{repo}" + if key in _RELEASE_CACHE: + return _RELEASE_CACHE[key] + hdrs = {"Accept": "application/vnd.github+json"} + tok = _github_token() + if tok: + hdrs["Authorization"] = f"Bearer {tok}" + out: list[tuple[str, str]] = [] + try: + for rel in _gh_paginate( + f"https://api.github.com/repos/{owner}/{repo}/releases?per_page=100", hdrs, max_pages + ): + out.append((rel.get("tag_name") or "", + f"{rel.get('name') or ''}\n{rel.get('body') or ''}")) + except Exception: # noqa: BLE001 — best effort; absence just leaves advisories undetermined + pass + _RELEASE_CACHE[key] = out + return out + + +def _source_repo(source: str) -> tuple[str, str] | None: + """(owner, repo) for a source, whether it is an advisory feed or a vendor page on GitHub. + + A CVE that appears ONLY on a vendor page still deserves the release-note method when that page + lives on GitHub — mailu announces its Roundcube CVEs on github.com/Mailu/Mailu/releases and + nowhere structured, so requiring an advisory feed sent a deterministic case to pass 2.""" + if source.startswith("github-advisories:"): + owner, _, repo = source.split(":", 1)[1].partition("/") + return (owner, repo) if owner and repo else None + m = re.match(r"https?://github\.com/([^/]+)/([^/#?]+)", source) + return (m.group(1), m.group(2).removesuffix(".git")) if m else None + + +def release_fix_versions(source: str, cve: str) -> list[str]: + """Release tags whose notes NAME this CVE — a deterministic fix version when the advisory has none. + + Vendors routinely publish an advisory with `patched_versions: "TBD"` and then name the CVE in the + release notes of every branch that got the fix. redis does exactly this: all 12 of its advisories + that discourse's redis bump crosses carry TBD, yet each is named in concrete releases + (CVE-2025-32023 → 6.2.19, 7.2.10, 7.4.5, 8.0.3, 8.2.0). Ignoring that evidence undercounted + discourse by 12 CVEs, so this is checked BEFORE giving up on an advisory. + """ + ref = _source_repo(source) + if not ref: + return [] + return [tag for tag, body in _releases(*ref) if cve in body] + + +def advisory_text(ghsa: str, source: str | None = None) -> dict: + """Full text of one advisory, for the ADJUDICATION pass (see adjudication_block). + + The structured `patched_versions` field is often "TBD" while the prose description and the + linked references DO state where the fix landed. That prose is not machine-parseable in general + — which is the point: it is collected here for a MODEL to judge, not for a regex.""" + hdrs = {"Accept": "application/vnd.github+json"} + tok = _github_token() + if tok: + hdrs["Authorization"] = f"Bearer {tok}" + out = {"ghsa": ghsa, "status": "ok"} + # Repo-scoped FIRST. Many repository advisories are never mirrored into the global GitHub + # Advisory Database, so /advisories/ 404s for them (all 12 redis ones, for instance) + # while /repos///security-advisories/ returns the full record. + cands = [] + if source and source.startswith("github-advisories:"): + cands.append(f"https://api.github.com/repos/{source.split(':',1)[1]}/security-advisories/{ghsa}") + cands.append(f"https://api.github.com/advisories/{ghsa}") + try: + a, last = None, None + for u in cands: + try: + a = json.loads(_fetch(u, hdrs)); break + except Exception as ex: # noqa: BLE001 — try the next endpoint + last = ex + if a is None: + raise last or RuntimeError("no advisory endpoint responded") + out.update({ + "summary": a.get("summary"), + "description": (a.get("description") or "")[:4000], + "severity": a.get("severity"), + "published_at": a.get("published_at"), + "references": [r for r in (a.get("references") or [])][:12] or ( + [a.get("html_url")] if a.get("html_url") else []), + "cvss": (a.get("cvss") or {}).get("vector_string"), + "vulnerabilities": [ + {"package": (v.get("package") or {}).get("name"), + "vulnerable_version_range": v.get("vulnerable_version_range"), + "first_patched_version": v.get("first_patched_version")} + for v in (a.get("vulnerabilities") or []) + ], + }) + except Exception as e: # noqa: BLE001 + out["status"] = f"error: {type(e).__name__}: {e}" + return out + + +MAX_ADJUDICATE = int(os.environ.get("ADVISORY_SCAN_MAX_ADJUDICATE", "25")) +# Compact review rows for advisories pass 1 DID decide. Pass 2 sees these too, so a wrong +# deterministic verdict can be caught rather than inherited. +MAX_REVIEW_ROWS = int(os.environ.get("ADVISORY_SCAN_MAX_REVIEW", "400")) + + +def needs_judgement(rep: dict) -> list[str]: + """CVEs the deterministic pass could not decide — the input set for the adjudication pass. + + Two kinds, both real gaps rather than noise: + 1. INDETERMINATE — from an image WITH a window, but no fix version is knowable (advisory says + `TBD`/`7.4.X`, range is open-ended, and no release note names it). + 2. VENDOR-PAGE-ONLY — a CVE seen only on a vendor security page, with no structured advisory + behind it at all. gitea's two CVSS-9.8 RCEs are this shape. They carry no version data, so + no arithmetic can place them, but the page's prose usually states the fixed release. + """ + windows = rep.get("windows") or {} + out = list(rep.get("indeterminate") or []) + for cve in rep.get("unclassified") or []: + srcs = rep["cves"][cve]["sources"] + if not any(s.startswith("github-advisories:") for s in srcs) and cve not in out: + out.append(cve) + return sorted(out) + + +def evidence_bundle(rep: dict, cve: str) -> dict: + """EVERY deterministic signal held about one CVE, gathered for a model to weigh. + + Pass 1 collects; pass 2 judges. Nothing here interprets — it assembles what was measured, so the + judgement is made against evidence rather than recollection (the exact failure that let two + CVSS-9.8 gitea RCEs be published as "none": the report leaned on model knowledge that predated + them, and no source had been queried at all). + """ + e = rep["cves"][cve] + src = e["sources"][0] + windows = rep.get("windows") or {} + win = next((windows[s] for s in e["sources"] if s in windows), None) + ev = { + "cve": cve, + "severity": e.get("severity"), + "cvss": e.get("cvss"), + "sources": e["sources"], + "window": win, + "why_undecided": ("no fix version published and no release note names it" + if cve in (rep.get("indeterminate") or []) + else "seen only on a vendor page — no structured advisory, no version data"), + "patched_as_published": e.get("patched"), + "vulnerable_range_as_published": e.get("vulnerable_range"), + "summary": e.get("context"), + "description": e.get("description"), + "advisory_url": e.get("url"), + # Release tags NAMING this CVE, whether or not they fall in the window — the model may + # reason about branch lines the arithmetic deliberately would not. + "releases_naming_it": release_fix_versions(src, cve) if src.startswith("github-advisories:") else [], + "references": [], + } + if e.get("ghsa"): + t = advisory_text(e["ghsa"], src) + if t.get("status") == "ok": + ev["references"] = t.get("references") or [] + ev["description"] = t.get("description") or ev["description"] + ev["summary"] = t.get("summary") or ev["summary"] + ev["affected"] = t.get("vulnerabilities") or [] + else: + ev["detail_fetch"] = t.get("status") + return ev + + +def adjudication_block(rep: dict) -> str: + """SECOND PASS: present the collected evidence and ask for a judgement on each open case. + + This block decides nothing. The deterministic count stands as a FLOOR; a verdict here may only + ADD to it, matching the rule that this scan raises a count on evidence but never lowers one. + """ + todo = needs_judgement(rep) + if not todo: + return "" + shown, dropped = todo[:MAX_ADJUDICATE], max(0, len(todo) - MAX_ADJUDICATE) + L = ["", "---", "", + f"## Adjudication pass — {len(todo)} advisory/advisories need judgement", "", + "Pass 1 collected the evidence below deterministically and could NOT decide these cases. " + "Weigh the evidence and decide each one.", "", + "**For each: did the version move in its window fix it?** Answer **FIXED** / **NOT-FIXED** / " + "**STILL-UNKNOWN**, each with a one-line reason **citing the evidence shown** — a fixed " + "release named in the text, a branch line, an affected range. Add every FIXED to the " + "recipe's CVE count; the deterministic number is a floor, not a total. If the evidence does " + "not settle it, say STILL-UNKNOWN: do NOT infer from memory of the project, and never " + "record an undecided CVE as unaffected.", ""] + for src, win in (rep.get("windows") or {}).items(): + L.append(f"- window: `{src.split(':',1)[-1]}` {win['from']} → {win['to']}") + if dropped: + L += ["", f"⚠ Showing the first {MAX_ADJUDICATE} of {len(todo)}; **{dropped} not shown** " + f"(raise ADVISORY_SCAN_MAX_ADJUDICATE). The unshown remain undetermined — do not " + f"treat them as absent."] + L.append("") + for cve in shown: + ev = evidence_bundle(rep, cve) + L.append(f"### {cve} — {ev['severity'] or '?'}") + L.append(f"- undecided because: {ev['why_undecided']}") + L.append(f"- source: `{ev['sources'][0]}`" + + (f" · window {ev['window']['from']} → {ev['window']['to']}" if ev["window"] else + " · **no version window** for this image")) + L.append(f"- patched_versions as published: `{ev['patched_as_published']}`") + L.append(f"- vulnerable_range as published: `{ev['vulnerable_range_as_published']}`") + if ev["releases_naming_it"]: + L.append(f"- **releases naming this CVE**: {', '.join(ev['releases_naming_it'][:14])}") + for v in ev.get("affected") or []: + L.append(f"- affects `{v.get('package')}` {v.get('vulnerable_version_range')} — " + f"first_patched_version: {v.get('first_patched_version')}") + if ev["references"]: + L.append(f"- references: {', '.join(r.strip() for r in ev['references'][:6])}") + if ev.get("detail_fetch"): + L.append(f"- ⚠ detail fetch failed: {ev['detail_fetch']} (evidence below is from pass 1)") + if ev["summary"]: + L += ["", f"> {ev['summary']}"] + if ev["description"]: + L += ["", "```", (ev["description"] or "").strip()[:2000], "```"] + L.append("") + + # ── everything pass 1 DID decide, with the evidence behind each verdict ────────────────────── + # Pass 2 must see the whole picture, not only the leftovers: a deterministic verdict can still + # be wrong (a mis-parsed range, a release note that names a CVE without fixing it), and only a + # reader with the evidence in front of it can catch that. + decided = [] + for cve in rep.get("fixed_by_this_upgrade") or []: + e = rep["cves"][cve] + decided.append((cve, "COUNTED", e)) + for cve, e in sorted(rep.get("cves", {}).items()): + if e.get("classification") == "outside-window": + decided.append((cve, "excluded (outside window)", e)) + if decided: + shown_rows, dropped_rows = decided[:MAX_REVIEW_ROWS], max(0, len(decided) - MAX_REVIEW_ROWS) + L += ["---", "", + f"## Pass 1 decisions — {len(decided)} already judged deterministically", "", + "Review these too. If any verdict looks wrong given its evidence, say so and explain; " + "a correction here changes the count. Silence means you agree.", ""] + if dropped_rows: + L.append(f"⚠ Showing {MAX_REVIEW_ROWS} of {len(decided)}; **{dropped_rows} not shown** " + f"(raise ADVISORY_SCAN_MAX_REVIEW).") + L.append("") + L += ["| CVE | verdict | severity | patched as published | releases naming it | source |", + "|---|---|---|---|---|---|"] + for cve, verdict, e in shown_rows: + rel = e.get("fix_versions_from_release_notes") or [] + L.append(f"| {cve} | {verdict} | {e.get('severity') or '?'} | " + f"{(e.get('patched') or '—')[:60]} | {', '.join(rel[:5]) or '—'} | " + f"{e['sources'][0].split(':',1)[-1]} |") + L.append("") + return "\n".join(L) + + +def scan(recipe: str, v_from: str | None, v_to: str | None, registry_dir: str, + images: list[tuple[str, str, str]] | None = None) -> dict: + urls, reg_path = registry_urls(recipe, registry_dir) + report: dict = { + "recipe": recipe, + "from": v_from, + "to": v_to, + "registry": reg_path, + "registry_urls": len(urls), + "sources": [], + "cves": {}, + } + if reg_path is None: + report["sources"].append( + {"source": f"registry:{recipe}.md", "status": "error: registry file not found"} + ) + + def record(cve: str, src: str, **extra): + e = report["cves"].setdefault(cve, {"sources": [], "severity": None, "ghsa": None, + "vulnerable_range": None, "patched": None, + "context": None, "published_at": None, + "description": None, "url": None, "cvss": None, + "changelog_fixed_in": None, "affected_max": None, + "affected_ranges": None}) + if src not in e["sources"]: + e["sources"].append(src) + for k, v in extra.items(): + if v and not e.get(k): + e[k] = v + + for entry in github_advisories(urls): + report["sources"].append({"source": entry["source"], "status": entry["status"], + "found": len(entry.get("advisories", []))}) + for a in entry.get("advisories", []): + advisory_id = a.get("cve") or a.get("ghsa") + if advisory_id: + record(advisory_id, entry["source"], severity=a.get("severity"), ghsa=a.get("ghsa"), + vulnerable_range=a.get("vulnerable_range"), patched=a.get("patched"), + context=a.get("summary"), published_at=a.get("published_at"), + description=a.get("description"), url=a.get("url"), cvss=a.get("cvss")) + + for key, cpe in registry_cpes(recipe, registry_dir): + entry = nvd_advisories(cpe, key) + report["sources"].append({"source": entry["source"], "status": entry["status"], + "found": len(entry.get("advisories") or [])}) + for a in entry.get("advisories", []): + record(a["cve"], entry["source"], severity=a.get("severity"), + patched=a.get("patched"), affected_max=a.get("affected_max"), + affected_ranges=a.get("affected_ranges"), + context=a.get("summary"), published_at=a.get("published_at"), + url=a.get("url")) + + for entry in vendor_pages(urls): + report["sources"].append({"source": entry["source"], "status": entry["status"], + "found": len(entry.get("cves", []))}) + for cve in entry.get("cves", []): + record(cve, entry["source"], context=entry["context"].get(cve), + changelog_fixed_in=(entry.get("fixed_in") or {}).get(cve)) + + for version in filter(None, (v_from, v_to)): + o = osv(recipe, version) + if o: + report["sources"].append({"source": o["source"], "status": o["status"], + "found": len(o.get("cves", []))}) + for cve in o.get("cves", []): + record(cve, o["source"]) + + # Classify against the upgrade window when we know it: an advisory is "fixed by this upgrade" + # when its patched version is newer than `from` and no newer than `to`. + # + # TWO HARD-WON CONSTRAINTS (2026-08-10, discourse reported a false 133): + # a) The window belongs to ONE image. Advisories from OTHER repos in the registry (redis, + # postgres, nginx sidecars) must NOT be judged by it — redis CVE-2021-21309, patched in + # redis 6.0.11, scored as "fixed" because 6.0.11 sits numerically inside discourse's + # 3.5.3 → 2026.7.1 window. Only the PRIMARY app repo is classified; every other source is + # reported as unclassified so a human/agent still sees it but it never inflates the count. + # b) A version-SCHEME change (semver → calver, 3.5.3 → 2026.7.1) makes numeric ordering + # meaningless: 2025.12.2 compares "newer" than 3.5.3 while shipping earlier. When the + # leading component jumps by more than SCHEME_JUMP we refuse to classify and say so, + # rather than emitting a confident wrong number. + # ── Classification ──────────────────────────────────────────────────────────────────────── + # A recipe upgrades SEVERAL images (app + redis/postgres/nginx sidecars), each with its OWN + # version window. Judging every advisory by the app's window is how discourse once reported a + # false 133 (34 of them redis CVEs, incl. one patched in redis 6.0.11 in 2021). So each source + # is classified against ITS OWN window, and the count is the union across windows. + # + # --from/--to → the PRIMARY app repo (first github source in the registry) + # --image NAME=FROM:TO → any other source whose name contains NAME (repeatable), + # e.g. --image redis=7.4:8.10 + # + # A source with no window is not classified: its advisories are listed as unclassified so they + # stay visible without inflating the count. + gh_sources = [x["source"] for x in report["sources"] + if x["source"].startswith(("github-advisories:", "nvd:"))] + primary = gh_sources[0] if (gh_sources and (v_from or v_to)) else None + report["primary_source"] = primary + + windows = {} # source name -> (from, to) + window_key = {} # source name -> the image name it covers + if primary: + windows[primary] = (v_from, v_to) + window_key[primary] = primary.split("/")[-1] + # The app's window must also cover its NVD entry. NVD sources are keyed by IMAGE name + # (`mattermost-team-edition`) while the advisory feed is keyed by REPO (`mattermost/ + # mattermost`), so without this the fallback source that exists precisely because the feed + # is empty would itself go unwindowed — and mumble/mattermost would still report nothing. + pname = primary.split("/")[-1].lower() + for src in gh_sources: + if src.startswith("nvd:") and src not in windows: + k = src.split(":", 1)[1].lower() + if pname in k or k in pname: + windows[src] = (v_from, v_to) + window_key[src] = k + image_sources = registry_image_sources(recipe, registry_dir) + for key, wf, wt in (images or []): + matched = False + explicit = image_sources.get(key.lower(), set()) + for src in gh_sources: + # Match BOTH ways: an image name is often longer than its source repo + # (`clickhouse/clickhouse-server` vs source `ClickHouse/ClickHouse`) and sometimes + # shorter (`redis` vs `redis/redis`). One-directional matching silently dropped the + # clickhouse window when the key was derived from a compose file. + k, name = key.lower(), src.split("/")[-1].lower() + if src in explicit or k in src.lower() or name in k: + if src in windows: + matched |= windows[src] == (wf, wt) + continue # two images in one monorepo share a source and version window + windows[src] = (wf, wt) + window_key[src] = key + matched = True + if not matched: + report.setdefault("unmatched_image_windows", []).append(key) + report["windows"] = {k: {"from": f, "to": t} for k, (f, t) in windows.items()} + + def _classify_window(src, wf, wt): + """Return (fixed, method, date_window|None, unresolved, indeterminate) for one source. + + `indeterminate` = advisories from this source that the method COULD NOT JUDGE (no usable + patched version, or no publish date). They are neither counted nor dismissed.""" + if src.startswith("nvd:"): + got, undecidable = set(), set() + for advisory, evidence in report["cves"].items(): + if src not in evidence["sources"]: + continue + if not evidence.get("affected_ranges"): + undecidable.add(advisory) + continue + old = _nvd_affects(wf, evidence["affected_ranges"]) + new = _nvd_affects(wt, evidence["affected_ranges"]) + if old is True and new is False: + got.add(advisory) + elif old is None or (old is True and new is None): + undecidable.add(advisory) + return got, "NVD affected-version ranges", None, False, undecidable + kf, kt = _vkey(wf), _vkey(wt) + # A version-SCHEME change (semver 3.5.3 → calver 2026.7.1) makes numeric ordering + # meaningless: 2025.12.2 compares "newer" than 3.5.3 while shipping earlier. + scheme = bool(kf and kt and abs(kt[0] - kf[0]) >= SCHEME_JUMP) + if not scheme: + got, undecidable = set(), set() + for cve, e in report["cves"].items(): + if src not in e["sources"]: + continue + patched = e.get("patched") or "" + cands = [_vkey(t) for t in re.findall(r"\d+(?:\.\d+)*", patched)] + # NEVER on a placeholder: "7.4.X" parses to the bare 7.4, which then reads as + # "already fixed at 7.4" and silently drops a real fix (redis CVE-2024-46981). + # A placeholder means the fix version is unknown — that is the indeterminate path. + if (kf and kt and not PLACEHOLDER_RE.search(patched) + and _already_fixed_on_from_line(kf, cands)): + # already had it before the upgrade + e.setdefault("classification", "outside-window") + continue + if kf and kt and _superseded_on_target_line(kt, cands): + # The target's own line got the fix LATER than the target: not fixed here. + e.setdefault("classification", "outside-window") + continue + if kf and kt and any(_within(kf, kt, c) for c in cands): + got.add(cve) + elif kf and kt and e.get("affected_max"): + # NVD's `versionEndIncluding X`: affected up to and INCLUDING X, fixed in some + # later release. The exact fix version is unpublished, but the upgrade delivers + # it whenever it crosses X — i.e. from <= X < to. + for t in re.findall(r"\d+(?:\.\d+)*", e["affected_max"]): + x = _vkey(t) + n = max(len(kf), len(kt), len(x)) + pad = lambda z: z + (0,) * (n - len(z)) + if x and pad(kf) <= pad(x) < pad(kt): + got.add(cve) + break + elif not patched or PLACEHOLDER_RE.search(patched): + # No fix version published ("TBD") or only a placeholder ("7.4.X" — which could + # be 7.4.1, inside the window). We cannot say either way, so say so. + undecidable.add(cve) + return got, "patched version ranges", None, False, undecidable + # DATE FALLBACK: release DATES always order, even across a scheme change. Resolve both + # versions to git tag dates and count advisories PUBLISHED in that window — the method a + # hand count used to establish discourse 3.5.3 (2025-12-30) → 2026.7.1 (2026-07-31) = 123. + owner, _, repo = src.split(":", 1)[1].partition("/") + d_from, d_to = _tag_date(owner, repo, wf), _tag_date(owner, repo, wt) + if d_from and d_to and d_from < d_to: + got = {cve for cve, e in report["cves"].items() + if src in e["sources"] and e.get("published_at") + and d_from < e["published_at"] <= d_to} + undecidable = {cve for cve, e in report["cves"].items() + if src in e["sources"] and not e.get("published_at")} + return got, "advisory publish date (version scheme changed)", (d_from, d_to), False, undecidable + return set(), "unresolved", None, True, set() + + fixed_set, methods, date_windows, unresolved_any = set(), {}, {}, False + indeterminate: set = set() + for src, (wf, wt) in windows.items(): + got, method, dw, unresolved, undecidable = _classify_window(src, wf, wt) + indeterminate |= undecidable + methods[src] = method + if dw: + date_windows[src] = {"from": dw[0], "to": dw[1]} + if unresolved: + unresolved_any = True + for cve in got: + report["cves"][cve]["classification"] = f"fixed-by-this-upgrade ({method}) via {src}" + fixed_set.add(cve) + + # A CVE seen only in a vendor CHANGELOG has no advisory feed behind it, but the changelog says + # which release fixed it (see _changelog_versions). Tie it to a window by the image name + # appearing in the page URL — nginx's window is `nginx`, and its changelog is nginx.org/... . + # Without this, projects that publish no GitHub advisories (nginx being the big one) can never + # contribute a CVE, and every nginx bump in the fleet silently reports 0. + from_changelog = {} + for cve, e in report["cves"].items(): + if cve in fixed_set or not e.get("changelog_fixed_in"): + continue + for src, (wf, wt) in windows.items(): + key = (window_key.get(src) or "").lower() + if not key: + continue + if not any(key in s_.lower() for s_ in e["sources"] if s_.startswith("http")): + continue + kf, kt = _vkey(wf), _vkey(wt) + cand = _vkey(e["changelog_fixed_in"]) + if kf and kt and cand and _within(kf, kt, cand): + e["classification"] = (f"fixed-by-this-upgrade (named under {e['changelog_fixed_in']} " + f"in the vendor changelog) via {src}") + fixed_set.add(cve) + from_changelog[cve] = e["changelog_fixed_in"] + break + if from_changelog: + report["resolved_by_changelog"] = from_changelog + + unknown = [] + for cve, e in report["cves"].items(): + if cve in fixed_set: + continue + if not any(src in e["sources"] for src in windows): + e["classification"] = "unclassified: no versions given for this image" + unknown.append(cve) + else: + e.setdefault("classification", "outside-window") + if e["classification"] == "outside-window": + pass + else: + unknown.append(cve) + + report["classified_by"] = methods + if date_windows: + report["date_window"] = date_windows + # THIRD METHOD: before declaring an advisory undecidable, look for the CVE id in the project's + # own release notes. A tag that names it, inside the window, IS the fix version the advisory + # failed to publish. Deterministic and citable — not a judgement call. + # A window is keyed by advisory-feed source; map it to its repo so a vendor page on the SAME + # repo can be judged by the same window. + win_by_repo = {} + for wsrc, wv in windows.items(): + ref = _source_repo(wsrc) + if ref: + win_by_repo[ref] = wv + resolved_by_release, already_fixed = {}, set() + candidates = set(indeterminate) | { + c for c in unknown + if not any(s in windows for s in report["cves"][c]["sources"]) + and any(_source_repo(s) in win_by_repo for s in report["cves"][c]["sources"]) + } + for cve in sorted(candidates - fixed_set): + e = report["cves"][cve] + for src in e["sources"]: + ref = _source_repo(src) + if src not in windows and ref not in win_by_repo: + continue + wf, wt = windows[src] if src in windows else win_by_repo[ref] + kf, kt = _vkey(wf), _vkey(wt) + if not (kf and kt): + continue + naming = release_fix_versions(src, cve) + hits = [t for t in naming if _within(kf, kt, _vkey(t))] + if hits: + fixed_set.add(cve) + resolved_by_release[cve] = sorted(hits) + e["classification"] = (f"fixed-by-this-upgrade (named in release notes " + f"{', '.join(sorted(hits))}) via {src}") + e["fix_versions_from_release_notes"] = sorted(hits) + break + # Naming releases exist but ALL predate the version we were already on: the fix shipped + # before this upgrade, so the upgrade did not deliver it. That is a DECISION, not an + # unknown — mailu's redis 8.8.0 → 8.10.0 crosses 12 advisories all fixed by 8.6.3 or + # earlier, and reporting them as "could not judge" overstates the uncertainty. + if naming and all(_vkey(t) and not _within(kf, kt, _vkey(t)) for t in naming) \ + and max(_vkey(t) for t in naming if _vkey(t)) <= kf: + e["classification"] = ("outside-window: fixed in " + f"{', '.join(sorted(naming))}, all at or before {wf}") + e["fix_versions_from_release_notes"] = sorted(naming) + already_fixed.add(cve) + break + if resolved_by_release: + report["resolved_by_release_notes"] = resolved_by_release + + indeterminate -= fixed_set | already_fixed + if already_fixed: + report["already_fixed_before_upgrade"] = sorted(already_fixed) + for cve in indeterminate: + report["cves"][cve]["classification"] = "indeterminate: no fix version published" + unknown = [c for c in unknown if c not in fixed_set] + report["fixed_by_this_upgrade"] = sorted(fixed_set) + report["fixed_non_cve_advisories"] = sorted(x for x in fixed_set if not x.startswith("CVE-")) + report["indeterminate"] = sorted(indeterminate) + report["cve_count_indeterminate"] = len(indeterminate) + report["unclassified"] = sorted(unknown) + # NEVER report 0 for something we could not determine — a 0 asserts safety. If ANY requested + # window could not be ordered at all, the total is UNKNOWN rather than a partial number. + # A scan with NO usable source has not measured anything, so it must not report a number — + # least of all 0, which asserts safety. mumble had no cc-ci-plan/upstream/mumble.md at all and + # still produced "0 identified", which was then published as a clean 0 in a CVE report. + usable_sources = [s for s in report["sources"] if s["status"] == "ok"] + no_sources = not usable_sources + if no_sources: + report["no_usable_sources"] = True + report["sources_failed"] = [ + s["source"] + for s in report["sources"] + if not (s["status"] == "ok" or s["status"].startswith(("no-advisories-published", "skipped:"))) + ] + coverage_failed = bool(report.get("unmatched_image_windows")) or bool(v_from and not primary) + report["count_known"] = not unresolved_any and not no_sources and not coverage_failed and not report["sources_failed"] + report["cve_count_fixed"] = (sum(x.startswith("CVE-") for x in fixed_set) + if report["count_known"] else None) + report["cve_count_total_seen"] = sum(x.startswith("CVE-") for x in report["cves"]) + # Only GENUINE failures make a count unreliable. "no-advisories-published" (404: the repo has + # no advisory feed) and "skipped: template URL" are benign and must not degrade the verdict. + report["sources_benign"] = [ + s["source"] + for s in report["sources"] + if s["status"].startswith(("no-advisories-published", "skipped:")) + ] + return report + + +def markdown(rep: dict) -> str: + """Human/agent-readable block for pasting into the per-recipe upgrade log.""" + L = [f"### Advisory scan (deterministic pre-step) — {rep['recipe']} " + f"{rep.get('from') or '?'} → {rep.get('to') or '?'}"] + if not rep.get("count_known", True): + L.append("\n**CVEs fixed by this upgrade: UNKNOWN — the scan could NOT determine a count.**") + if rep.get("fixed_by_this_upgrade"): + L.append(f"\nAt least {len(rep['fixed_by_this_upgrade'])} fixed advisory/advisories were identified: " + + ", ".join(rep["fixed_by_this_upgrade"][:15])) + if rep.get("no_usable_sources"): + L.append("\n⚠ This is NOT zero. **No usable source was checked at all** — the registry " + "file `cc-ci-plan/upstream/.md` is missing or every source failed, so " + "nothing was measured. Render this recipe's cve cell as `?`, never `0`, and add " + "the registry file.") + else: + L.append("\n⚠ This is NOT zero. At least one version window or advisory source could " + "not be checked completely. Render this recipe's cve cell as `?`, never `0`.") + if rep.get("unmatched_image_windows"): + L.append("\n⚠ image windows with no matching advisory source: " + + ", ".join(rep["unmatched_image_windows"])) + if rep["unclassified"]: + L.append(f"\nAdvisories seen but unclassifiable ({len(rep['unclassified'])}) — includes " + f"other images in this recipe: " + ", ".join(rep["unclassified"][:12])) + if rep["sources_failed"]: + L.append(f"\n⚠ sources that FAILED: {', '.join(rep['sources_failed'])}") + L.append(f"\n_Sources checked: {len(rep['sources'])} ({rep['registry_urls']} registry URLs + " + f"advisory APIs). This scan is ADDITIVE — it does not replace the release-note " + f"reading in the upgrade step._") + return "\n".join(L) + ind = rep.get("cve_count_indeterminate") or 0 + fixed_cves = [x for x in rep["fixed_by_this_upgrade"] if x.startswith("CVE-")] + if fixed_cves: + floor = " (at least — see undetermined below)" if ind else "" + L.append(f"\n**CVEs fixed by this upgrade: {rep['cve_count_fixed']}**{floor}\n") + cb = rep.get("classified_by") or {} + if isinstance(cb, dict) and cb: + for src, method in cb.items(): + dw = (rep.get("date_window") or {}).get(src) + win = (rep.get("windows") or {}).get(src, {}) + span = f"{win.get('from')} → {win.get('to')}" + extra = (f" (dates {dw['from'][:10]} → {dw['to'][:10]})" if dw else "") + L.append(f"_{src.split(':',1)[-1]}: {span} — counted by {method}{extra}._") + L.append("") + L.append("| CVE | severity | fixed in | advisory | source |") + L.append("|---|---|---|---|---|") + for cve in fixed_cves: + e = rep["cves"][cve] + L.append(f"| {cve} | {e.get('severity') or '?'} | {e.get('patched') or '?'} | " + f"{e.get('ghsa') or '-'} | {e['sources'][0]} |") + else: + L.append("\n**CVEs fixed by this upgrade: 0 identified by the deterministic scan.**") + if rep.get("fixed_non_cve_advisories"): + L.append("\n**Security advisories fixed without CVE IDs: " + + str(len(rep["fixed_non_cve_advisories"])) + "** — " + + ", ".join(rep["fixed_non_cve_advisories"][:15]) + + ". In the report CVEs column, use YES when the CVE count is zero.") + if ind: + L.append(f"\n⚠ **{ind} advisory/advisories could NOT be judged** — the vendor published no fix " + f"version (GitHub carries `TBD` or a placeholder like `7.4.X`) and the vulnerable " + f"range is open-ended, so neither method can tell whether this upgrade fixed them. " + f"They are NOT included in the count above and must NOT be read as unaffected: " + + ", ".join(f"{c} ({rep['cves'][c].get('severity') or '?'})" + for c in rep["indeterminate"][:15]) + + (" …" if len(rep["indeterminate"]) > 15 else "") + + "\n\nRe-run with `--adjudicate` for the collected evidence on each, to judge.") + if rep["unclassified"]: + L.append(f"\nSeen but not version-classified ({len(rep['unclassified'])}) — includes advisories " + f"from OTHER images in this recipe (sidecars), which this window cannot judge: " + + ", ".join(rep["unclassified"][:12])) + if rep["sources_failed"]: + L.append(f"\n⚠ sources that FAILED (treat counts as incomplete): {', '.join(rep['sources_failed'])}") + L.append(f"\n_Sources checked: {len(rep['sources'])} " + f"({rep['registry_urls']} registry URLs + advisory APIs). This scan is ADDITIVE — it does " + f"not replace the release-note reading in the upgrade step._") + return "\n".join(L) + + +def _gitea_auth(url: str) -> dict: + """Basic auth for the private mirror, using public config plus .testenv. + + Sent as a HEADER, never embedded in the URL: in-URL credentials leak into shell history, process + lists and error messages, and urllib mis-parses a password containing a colon.""" + host = re.sub(r"^https?://", "", url).split("/")[0] + env = {} + for path in ( + "/srv/cc-ci/cc-ci/.env.public", + os.environ.get("CCCI_TESTENV", "/srv/cc-ci/.testenv"), + ): + try: + lines = open(path) + except OSError: + continue + for ln in lines: + if "=" in ln and not ln.strip().startswith("#"): + k, v = ln.strip().split("=", 1) + env[k] = v.strip().strip("\"'") + if host != env.get("GITEA_URL", "git.autonomic.zone"): + return {} + u, pw = env.get("GITEA_USERNAME"), env.get("GITEA_PASSWORD") + if not (u and pw): + return {} + import base64 as _b64 + return {"Authorization": "Basic " + _b64.b64encode(f"{u}:{pw}".encode()).decode()} + + +def _compose_images(url: str) -> dict[str, tuple[str, str]]: + """{service: (image-repo, tag)} for a compose file. + + Keyed by SERVICE, not by image repo, because an upgrade may change the repo itself: plausible + moved `plausible/analytics` -> `ghcr.io/plausible/community-edition`. Keyed by repo that reads + as one image vanishing and an unrelated one appearing, and the app's version window is lost — + which is exactly the upgrade most worth scanning.""" + txt = _fetch(url, _gitea_auth(url)) + out, svc = {}, None + in_services = False + for line in txt.splitlines(): + if re.match(r"^services:\s*$", line): + in_services = True + continue + if in_services and re.match(r"^\S", line): + in_services = False + if not in_services: + continue + m = re.match(r"^ (\S+):\s*$", line) + if m: + svc = m.group(1) + continue + m = re.match(r"^\s+image:\s*[\"']?([^\"'\s]+)", line) + if m and svc: + ref = m.group(1).split("@", 1)[0] + if "${" in ref or "$(" in ref: + continue + repo, _, tag = ref.rpartition(":") + if repo and tag: + out[svc] = (repo, tag) + return out + + +def _default_branch_compose(url: str) -> str | None: + """Same repo as `url`, but its DEFAULT branch — resolved from the API, never assumed. + + Several coopcloud recipes keep a stale `main` beside the real default `master` (gitea's `main` + is 1.24.2-rootless while `master` has 1.27.1-rootless), so guessing the branch produces a + confidently wrong baseline.""" + m = re.match(r"(https?://[^/]+)/([^/]+)/([^/]+)/(?:raw|src)/branch/[^/]+/(.*)$", url) + if not m: + return None + host, owner, repo, path = m.groups() + try: + meta = json.loads(_fetch(f"{host}/api/v1/repos/{owner}/{repo}", _gitea_auth(host))) + br = meta.get("default_branch") + except Exception: # noqa: BLE001 + return None + return f"{host}/{owner}/{repo}/raw/branch/{br}/{path}" if br else None + + +def windows_from_compose(to_url: str, from_url: str | None = None, + include_primary: bool = False) -> tuple: + """Derive the scan's version windows by DIFFING two compose files. + + This is the deterministic alternative to a human (or a model) deciding which `--image` args a + given upgrade needs. Point it at a PR's compose and it reads the windows straight off the diff: + every image whose tag changed becomes a window, every image that did not change is correctly + left out, and nothing depends on anyone remembering that the recipe also bumped its redis. + + Returns (windows, note) where windows is [(image-name, from, to)]. + """ + if from_url is None: + from_url = _default_branch_compose(to_url) + if not from_url: + raise SystemExit("could not resolve a baseline compose; pass --compose-from explicitly") + new, old = _compose_images(to_url), _compose_images(from_url) + app, others = None, [] + for svc, (repo, tag) in sorted(new.items()): + if svc not in old: + continue + prev_repo, prev_tag = old[svc] + if prev_tag == tag and prev_repo == repo: + continue + # The `app` service is the recipe's primary image by coop-cloud convention; its window drives + # --from/--to so the scan's primary advisory source is judged against it. Everything else is + # a sidecar window keyed by its image name. + if svc == "app": + app = (repo.split("/")[-1], prev_tag, tag) + else: + others.append((repo.split("/")[-1], prev_tag, tag)) + wins = ([app] if app else []) + others + result = (wins, f"baseline {from_url}") + return (*result, bool(app)) if include_primary else result + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("recipe") + ap.add_argument("--from", dest="v_from", default=None) + ap.add_argument("--to", dest="v_to", default=None) + ap.add_argument("--json", action="store_true", help="emit raw JSON instead of markdown") + ap.add_argument("--adjudicate", action="store_true", + help="SECOND PASS: for advisories the deterministic pass could not judge (no " + "fix version published), fetch their full text + references and append a " + "block for the agent to judge. Additive: it never changes the count above.") + ap.add_argument("--registry", default=REGISTRY_DIR) + ap.add_argument("--compose-to", default=None, metavar="URL", + help="derive the windows by DIFFING this compose against its baseline, instead " + "of passing --from/--to/--image by hand. Point it at a PR's compose.yml " + "(e.g. .../raw/branch//compose.yml).") + ap.add_argument("--compose-from", default=None, metavar="URL", + help="baseline compose for --compose-to. Default: the same repo's DEFAULT " + "branch, resolved from the API (never assumed to be `main`).") + ap.add_argument("--image", action="append", default=[], metavar="NAME=FROM:TO", + help="a sidecar image and the versions it moved between, e.g. " + "--image redis=7.4:8.10 (repeatable). NAME matches a source repo name; " + "its advisories are then counted against ITS OWN versions instead of " + "being left unclassified.") + a = ap.parse_args() + images = [] + if a.compose_to: + wins, note, app_changed = windows_from_compose(a.compose_to, a.compose_from, + include_primary=True) + if not wins: + print(f"### Advisory scan — {a.recipe}\n\n**No image versions changed between the two " + f"compose files, so this upgrade fixes no CVEs by definition.**\n\n_{note}_") + return 0 + print(f"_derived from compose diff ({note}):_", file=sys.stderr) + for n_, f_, t_ in wins: + print(f"_ {n_}: {f_} → {t_}_", file=sys.stderr) + # Only an actual app-service change defines the primary window. A sidecar-only PR must + # not be scanned as though its first sidecar were the application image. + if app_changed: + a.v_from, a.v_to = a.v_from or wins[0][1], a.v_to or wins[0][2] + images = list(wins[1:]) + else: + images = list(wins) + for spec in a.image: + name, _, rng = spec.partition('=') + vf, _, vt = rng.partition(':') + if name and vf and vt: + images.append((name, vf, vt)) + else: + print(f'ignoring malformed --image {spec!r} (expected NAME=FROM:TO)', file=sys.stderr) + rep = scan(a.recipe, a.v_from, a.v_to, a.registry, images) + if a.adjudicate: + rep["adjudication"] = [evidence_bundle(rep, c) + for c in needs_judgement(rep)[:MAX_ADJUDICATE]] + if a.json: + print(json.dumps(rep, indent=2)) + else: + print(markdown(rep)) + if a.adjudicate: + print(adjudication_block(rep)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/cc-ci/agent-log.py b/scripts/cc-ci/agent-log.py new file mode 100755 index 0000000..8def29d --- /dev/null +++ b/scripts/cc-ci/agent-log.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +"""Clean, greppable transcript logs for the cc-ci agents. + +Claude Code already writes a structured JSONL transcript of every session under +~/.claude/projects//.jsonl. This renders that into a readable, greppable +one-event-per-line log — WITHOUT touching the agent (read-only on a file it writes anyway, so no +slowdown and zero extra tokens). The raw `tmux pipe-pane` logs are TUI-escape soup; use these instead. + +Usage: + agent-log.py render print the clean transcript to stdout + agent-log.py tail [N] print the last N (default 40) rendered events + agent-log.py follow-all loop: keep .clean.log up to date for every agent (run in tmux) + +Agents: builder adversary upgrader assistant orchestrator +Output logs (follow-all): /srv/cc-ci/.cc-ci-logs/.clean.log + +Each line: `HH:MM:SS [kind] …` — kinds: user, asst (assistant text), tool:, result, think(skipped +by default). Long text/results are truncated (full detail stays in the JSONL); newlines collapsed to ⏎. +""" +import json, os, sys, time + +PROJ = "/home/loops/.claude/projects" +LOGDIR = "/srv/cc-ci/.cc-ci-logs" +MAXLEN = 800 # truncate any single rendered block to this many chars + +# agent -> (project-slug dir, signature substring in the first user/kickoff message) +AGENTS = { + "builder": ("-srv-cc-ci-orch-cc-ci", "cc-ci SUB-PHASE"), + "adversary": ("-srv-cc-ci-orch-cc-ci-adv", "Adversary agent"), + "upgrader": ("-srv-cc-ci-orch", "cc-ci UPGRADER"), + "assistant": ("-srv-cc-ci-orch", "cc-ci ASSISTANT"), + "orchestrator": ("-srv-cc-ci-orch", "cc-ci orchestrator"), +} + + +def _first_user_text(path, limit=4000): + """Read the start of a transcript; return the first user-message text (the kickoff signature).""" + try: + with open(path) as f: + for _ in range(60): + ln = f.readline() + if not ln: + break + try: + o = json.loads(ln) + except Exception: + continue + if o.get("type") == "user": + c = (o.get("message") or {}).get("content") + if isinstance(c, str): + return c[:limit] + if isinstance(c, list): + return " ".join(b.get("text", "") for b in c if isinstance(b, dict) and b.get("type") == "text")[:limit] + except FileNotFoundError: + return "" + return "" + + +def active_jsonl(agent): + """The agent's current transcript: newest *.jsonl in its slug dir whose kickoff matches the + signature (disambiguates the shared -srv-cc-ci-orch dir; tracks restarts → new uuid).""" + slug, sig = AGENTS[agent] + d = os.path.join(PROJ, slug) + try: + files = [os.path.join(d, f) for f in os.listdir(d) if f.endswith(".jsonl")] + except FileNotFoundError: + return None + files.sort(key=lambda p: os.path.getmtime(p), reverse=True) + for p in files: + if sig in _first_user_text(p): + return p + return None + + +def _clip(s): + s = " ".join(str(s).split()) if s else "" # collapse all whitespace/newlines + return s if len(s) <= MAXLEN else s[:MAXLEN] + " …[+%d]" % (len(s) - MAXLEN) + + +def render_line(o, show_think=False): + """Render one JSONL event to zero or more clean lines (list of strings).""" + t = o.get("type") + if t not in ("user", "assistant"): + return [] + ts = (o.get("timestamp") or "")[11:19] or "--:--:--" + m = o.get("message") or {} + c = m.get("content") + out = [] + if isinstance(c, str): + if c.strip(): + out.append(f"{ts} [user] {_clip(c)}") + return out + if not isinstance(c, list): + return out + for b in c: + if not isinstance(b, dict): + continue + bt = b.get("type") + if bt == "text": + txt = b.get("text", "") + if txt.strip(): + out.append(f"{ts} [{'asst' if t=='assistant' else 'user'}] {_clip(txt)}") + elif bt == "thinking": + if show_think: + out.append(f"{ts} [think] {_clip(b.get('thinking',''))}") + elif bt == "tool_use": + inp = b.get("input") or {} + brief = inp.get("command") or inp.get("file_path") or inp.get("path") or inp.get("prompt") or json.dumps(inp)[:200] + out.append(f"{ts} [tool:{b.get('name')}] {_clip(brief)}") + elif bt == "tool_result": + rc = b.get("content") + if isinstance(rc, list): + rc = " ".join(x.get("text", "") for x in rc if isinstance(x, dict)) + out.append(f"{ts} [result] {_clip(rc)}") + return out + + +def render_file(path, show_think=False): + lines = [] + with open(path) as f: + for ln in f: + try: + o = json.loads(ln) + except Exception: + continue + lines += render_line(o, show_think) + return lines + + +def cmd_render(agent, show_think=False): + p = active_jsonl(agent) + if not p: + print(f"(no transcript found for {agent})", file=sys.stderr); sys.exit(1) + print(f"# {agent} ← {p}") + for l in render_file(p, show_think): + print(l) + + +def cmd_tail(agent, n=40): + p = active_jsonl(agent) + if not p: + print(f"(no transcript found for {agent})", file=sys.stderr); sys.exit(1) + for l in render_file(p)[-n:]: + print(l) + + +def cmd_follow_all(): + """One cheap process: keep every agent's .clean.log current. Re-resolves the active + transcript each pass (handles restarts) and appends only newly-parsed events.""" + os.makedirs(LOGDIR, exist_ok=True) + state = {} # agent -> (path, byte_offset) + while True: + for agent in AGENTS: + p = active_jsonl(agent) + if not p: + continue + prev_path, off = state.get(agent, (None, 0)) + if p != prev_path: + off = 0 # new/restarted session → render from the top + try: + size = os.path.getsize(p) + if off > size: # file truncated/rotated + off = 0 + with open(p) as f: + f.seek(off) + chunk = f.read() + new_off = f.tell() + except FileNotFoundError: + continue + if chunk: + rendered = [] + for ln in chunk.splitlines(): + try: + o = json.loads(ln) + except Exception: + continue + rendered += render_line(o) + if rendered: + with open(os.path.join(LOGDIR, f"{agent}.clean.log"), "a") as out: + out.write("\n".join(rendered) + "\n") + state[agent] = (p, new_off) + time.sleep(5) + + +def main(): + a = sys.argv[1:] or ["follow-all"] + cmd = a[0] + if cmd == "render": + cmd_render(a[1], "--think" in a) + elif cmd == "tail": + cmd_tail(a[1], int(a[2]) if len(a) > 2 and a[2].isdigit() else 40) + elif cmd == "follow-all": + cmd_follow_all() + else: + print(__doc__); sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/scripts/cc-ci/agents.py b/scripts/cc-ci/agents.py new file mode 100644 index 0000000..42ecbed --- /dev/null +++ b/scripts/cc-ci/agents.py @@ -0,0 +1,850 @@ +#!/usr/bin/env python3 +""" +cc-ci unified agent driver — one script, one config (agents.toml). + +Replaces the five bespoke launchers (launch.py / launch-orchestrator.py / launch-assistant.py +/ launch-upgrader.py / launch-report.py) and the ~15 scattered dotfiles. Every agent — loop +pair, orchestrator, assistant, one-shot tasks — is declared in agents.toml; the watchdog reads +the SAME file, so there is no env-vs-file drift. + +Usage: + agents.py up [name…] start enabled agents (or just the named ones); use-or-create + agents.py down [name…] stop agents (or all) + agents.py status one table: every agent — kind, backend, model, session, phase + agents.py watchdog the supervisor loop (reads agents.toml) + agents.py logs tail an agent's session log + agents.py phase [set N|next|show] inspect / move the loop phase + agents.py selftest backend activity-detector regression checks + agents.py migrate seed state/ from the legacy dotfiles (resume ids, phase idx) + +Options: + --config PATH config file (default: ') + + +def _mast(): + return ('
    Co-op Cloud Recipe CI · Weekly Edition
    ' + '

    The Recipe Report

    ') + + +def render(spec_path, out_path): + s = json.load(open(spec_path)) + kind = s.get("kind", "week") + title = KINDS.get(kind, KINDS["week"])[0] + gen = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + sub = s.get("subtitle", ("Week of " if kind == "week" else "CVE check ") + s["date"]) + lead = s.get("lead", "") or "" + # Auto-link recipe-name mentions in the lead to their mirror repos. + gitea = _env().get("GITEA_URL", "git.autonomic.zone") + repo_url = {r["recipe"]: f"https://{gitea}/recipe-maintainers/{r['recipe']}" + for r in (s.get("table") or []) if r.get("recipe")} + if lead and "

    " not in lead: + lead = "".join(f"

    {_linkify_recipes(_esc(p.strip()), repo_url)}

    " + for p in lead.split("\n\n") if p.strip()) + body = (_mast() + + f'' + f'
    {lead}
    ') + # 1) the full wire — every recipe, in the agent's recommended priority order (CVEs first); CVEs column. + wire = ("The full wire — every recipe, in priority order" if kind == "week" + else "Advisory sweep — every recipe, worst first") + body += f'

    {wire}

    {_table(s.get("table"), repo_url)}' + # 2) addendum — special issues to look into (normal-size header); omitted entirely if there are none. + add = [a for a in (s.get("addendum") or []) if str(a).strip()] + if add: + body += ('

    Addendum

      ' + + "".join(f"
    • {_linkify_recipes(_esc(b), repo_url)}
    • " for b in add) + "
    ") + # 3) security bulletin + if s.get("security"): + body += ('
    Security Bulletin
    ' + '

    🔒 Critical CVE upgrades

    ' + _stories(s["security"], repo_url) + "
    ") + # 4) what changed — a short section per recipe that has a PR + if s.get("changes"): + body += f'

    What changed

    {_changes(s.get("changes"), repo_url)}' + body += (f'') + open(out_path, "w").write(_page(f"{title} · " + s["date"], body)) + print("wrote", out_path) + + +def publish(html_path, date, kind="week"): + if kind not in KINDS: + print(f"unknown kind {kind!r}; expected one of {', '.join(KINDS)}"); sys.exit(2) + page = f"{kind}-{date}.html" + subprocess.run(["ssh", "cc-ci", f"cat > {HOST_REPORTS}/{page}"], input=open(html_path, "rb").read(), check=True) + # One index over BOTH families, newest first, each row labelled by its kind — an operator looking + # for "the latest security picture" should not have to know which skill produced which page. + entries = [] + for k in KINDS: + listing = subprocess.run(["ssh", "cc-ci", f"ls -1 {HOST_REPORTS}/{k}-*.html 2>/dev/null"], + capture_output=True, text=True).stdout.split() + for pth in listing: + d = os.path.basename(pth)[len(k) + 1:-5] + if re.fullmatch(r"\d{4}-\d{2}-\d{2}", d): + entries.append((d, k)) + lis = "\n".join( + f'
  • {KINDS[k][1].format(d=d)}{d}
  • ' + for d, k in sorted(set(entries), reverse=True)) + idx = _page("The Recipe Report — Archive", _mast() + + '' + f'
      {lis or "
    • No reports yet.
    • "}
    ') + subprocess.run(["ssh", "cc-ci", f"cat > {HOST_REPORTS}/index.html"], input=idx.encode(), check=True) + print(f"published https://report.ci.autonomic.zone/{page} (+ index)") + + +def main(): + a = sys.argv[1:] + cmd = a[0] if a else "survey" + today = datetime.now(timezone.utc).strftime("%Y-%m-%d") + if cmd == "survey": + survey(a[1] if len(a) > 1 else today) + elif cmd == "render": + render(a[1], a[2]) + elif cmd == "publish": + publish(a[1], a[2], a[3] if len(a) > 3 else "week") + else: + print(__doc__); sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/scripts/cc-ci/reconcile-upstream.sh b/scripts/cc-ci/reconcile-upstream.sh new file mode 100755 index 0000000..d4ff776 --- /dev/null +++ b/scripts/cc-ci/reconcile-upstream.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# reconcile-upstream — sync recipe mirrors from TRUE upstream. Run this FIRST, always. +# ---------------------------------------------------------------------------------- +# Every recipe we maintain is a MIRROR of a coopcloud recipe. Work done against a stale +# mirror is wasted or wrong, in three ways we have actually hit: +# +# 1. A PR whose changes upstream ALREADY MERGED. mailu #6 (2024.06.57 + redis 8.10, +# two internet-facing Roundcube CVEs) sat open and was reported as the fix for +# those CVEs — while upstream had merged and released it as 3.1.3+2024.06.57. The +# work was done; only our mirror was behind. +# 2. A survey that reads the stale mirror and reports "no upgrades available", so a +# recipe silently drops out of the weekly run. +# 3. Reading the WRONG BRANCH. Several coopcloud recipes keep a stale `main` beside +# the real default `master` — gitea's `main` is at 1.24.2-rootless while `master` +# has 1.27.1-rootless plus the merged PRs. Reading `main` there says the recipe is +# three releases behind and missing two CVSS-9.8 RCE fixes, which reads exactly +# like a real finding. open-recipe-pr.sh resolves the default branch itself +# (main OR master) — never hand-pick one. +# +# This is deterministic: it force-syncs each mirror's `main` to upstream's default +# branch and closes any mirror PR whose changes are already upstream. No AI judgement. +# +# reconcile-upstream.sh ... # specific recipes +# reconcile-upstream.sh --all # every recipe in used-recipes.md +# +# Safe to run repeatedly; a mirror already in sync is a no-op. Recipe work lives in +# BRANCHES, never on mirror `main`, so force-syncing `main` discards nothing. +set -o errexit -o nounset -o pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ORCH="$(dirname "$HERE")" +SSH="${SSH:-cc-ci}" +RECONCILE="${RECONCILE:-$ORCH/.claude/skills/recipe-upgrade/open-recipe-pr.sh}" +USED_RECIPES="${USED_RECIPES:-$HERE/used-recipes.md}" + +[ -f "$RECONCILE" ] || { echo "ERROR: reconcile helper not found: $RECONCILE" >&2; exit 1; } +set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a +: "${GITEA_USERNAME:?}"; : "${GITEA_PASSWORD:?}"; : "${GITEA_URL:=git.autonomic.zone}" + +if [ "${1:-}" = "--all" ]; then + mapfile -t RECIPES < <(awk '!/^[[:space:]]*#/ && ($2=="weekly" || $2=="external") {print $1}' "$USED_RECIPES") +else + [ "$#" -gt 0 ] || { echo "usage: reconcile-upstream.sh ... | --all" >&2; exit 2; } + RECIPES=("$@") +fi + +synced=0; closed=0; failed=0 +for r in "${RECIPES[@]}"; do + echo "── $r" + if out="$(ssh "$SSH" "GITEA_USERNAME='$GITEA_USERNAME' GITEA_PASSWORD='$GITEA_PASSWORD' GITEA_URL='$GITEA_URL' bash -s $r --reconcile-only" < "$RECONCILE" 2>&1)"; then + printf '%s\n' "$out" | grep -E "Force-syncing|already in sync|closed PR|still open|✓" | sed 's/^/ /' || true + synced=$((synced + 1)) + closed=$((closed + $(printf '%s' "$out" | grep -c "closed PR" || true))) + else + printf '%s\n' "$out" | tail -3 | sed 's/^/ /' + echo " ✗ FAILED — do NOT proceed against this mirror until it reconciles" + failed=$((failed + 1)) + fi +done + +echo +echo "reconcile-upstream: ${synced} mirror(s) synced, ${closed} already-upstream PR(s) closed, ${failed} failed" +[ "$failed" -eq 0 ] diff --git a/scripts/cc-ci/resolve-images.py b/scripts/cc-ci/resolve-images.py new file mode 100644 index 0000000..223faeb --- /dev/null +++ b/scripts/cc-ci/resolve-images.py @@ -0,0 +1,519 @@ +#!/usr/bin/env python3 +"""resolve-images — what version is each of a recipe's images on, and what is newest? + +An abra-independent version resolver. `abra recipe upgrade` is the normal path, but it has a hard +failure mode: an image pinned with BOTH a tag and a digest makes it FATA and abandon the WHOLE +recipe — even images it already parsed. immich pins two that way: + + ghcr.io/immich-app/postgres:14-vectorchord0.4.3-pgvectors0.2.0@sha256:bcf6… + docker.io/valkey/valkey:9@sha256:3acc… + +so immich contributes NO version data at all and silently drops out of every survey. That is +indistinguishable from "up to date" unless a human notices the missing row — which is exactly how it +kept getting skipped, and why a CVE sweep reported it as unknown. + +This reads the compose files directly and queries the registries itself, so a digest pin is just a +digest pin. Output is JSON (default) or a table. + + resolve-images.py [--ssh HOST] [--recipe-dir DIR] [--table] [--only IMAGE] + +The cc-ci host has no python3, so `--ssh cc-ci` reads the compose files from that host's checkout +over ssh and does the resolving locally. That keeps the source of truth the SAME tree abra and CI +use, rather than a second copy that can drift. + +TAG SHAPES. Registries mix wildly different tag conventions in one repo, so "newest" is meaningless +without a shape. Each tag is reduced to a signature by replacing digit runs with '#': + + v3.1.0 -> v#.#.# + 1.27.1-rootless -> #.#.#-rootless + 8.10-alpine -> #.#-alpine + 14-vectorchord0.4.3-pgvectors0.2.0 -> #-vectorchord#.#.#-pgvectors#.#.# + +Only tags sharing the CURRENT pin's shape are candidates. That keeps `-alpine` on `-alpine`, and +stops a `latest`/`release`/`sha-…` tag from ever being proposed as an upgrade. + +TWO ANSWERS, NOT ONE. It reports `newest_same_shape` AND `newest_within_major` (same leading number). +For a plain app image they usually agree. For a compatibility-pinned sidecar they do not, and taking +the max would be wrong: immich's postgres tag encodes the pg major plus the vectorchord/pgvectors +versions that immich-server is built against, so jumping pg major because a newer tag exists breaks +the deployment. The caller picks; this tool refuses to guess and shows both. +""" + +from __future__ import annotations + +import argparse +import glob +import shlex +import subprocess +import gzip +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +UA = "cc-ci-resolve-images (+https://git.autonomic.zone/recipe-maintainers/cc-ci)" +TIMEOUT = int(os.environ.get("RESOLVE_IMAGES_TIMEOUT", "45")) +RECIPE_DIR = os.environ.get("ABRA_RECIPE_DIR", os.path.expanduser("~/.abra/recipes")) +MAX_TAG_PAGES = int(os.environ.get("RESOLVE_IMAGES_MAX_PAGES", "40")) + +IMAGE_RE = re.compile(r"""^\s*image:\s*["']?([^"'\s]+)["']?\s*$""", re.M) + + +RETRIES = int(os.environ.get("RESOLVE_IMAGES_RETRIES", "4")) + + +def _fetch(url: str, headers: dict | None = None) -> bytes: + """GET with backoff on rate limits. + + Docker Hub throttles anonymous clients hard, and a sweep re-reads the same popular repos + (nginx, redis, postgres) for recipe after recipe. A 429 mid-sweep used to surface as + 'unresolved', which is indistinguishable from a real lookup failure — so retry, and let the + per-repo cache below remove most of the requests entirely.""" + h = {"User-Agent": UA, "Accept-Encoding": "gzip"} + h.update(headers or {}) + delay = 2.0 + for attempt in range(RETRIES): + try: + with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=TIMEOUT) as r: + raw = r.read() + if r.headers.get("Content-Encoding") == "gzip": + raw = gzip.decompress(raw) + return raw + except urllib.error.HTTPError as e: + if e.code in (429, 503) and attempt < RETRIES - 1: + time.sleep(delay) + delay *= 2 + continue + raise + raise RuntimeError("unreachable") + + +_HUB_JWT: list = [] + + +def _hub_auth() -> dict: + """Authenticated Docker Hub calls get a far higher rate limit than anonymous ones. + + Credentials come from /srv/cc-ci/.testenv (DOCKERHUB_USERNAME / DOCKERHUB_TOKEN), the same pair + the CI host already uses. Absent creds are fine — the sweep just runs anonymous and slower.""" + if _HUB_JWT: + return _HUB_JWT[0] + env = {} + try: + for ln in open(os.environ.get("CCCI_TESTENV", "/srv/cc-ci/.testenv")): + if "=" in ln and not ln.strip().startswith("#"): + k, v = ln.strip().split("=", 1) + env[k] = v.strip().strip("\"'") + except OSError: + pass + u = os.environ.get("DOCKERHUB_USERNAME") or env.get("DOCKERHUB_USERNAME") + t = os.environ.get("DOCKERHUB_TOKEN") or env.get("DOCKERHUB_TOKEN") + hdrs = {} + if u and t: + try: + body = json.dumps({"username": u, "password": t}).encode() + req = urllib.request.Request("https://hub.docker.com/v2/users/login", + data=body, method="POST", + headers={"Content-Type": "application/json", "User-Agent": UA}) + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + tokj = json.load(r).get("token") + if tokj: + hdrs = {"Authorization": f"JWT {tokj}"} + except Exception: # noqa: BLE001 — anonymous is a valid fallback + hdrs = {} + _HUB_JWT.append(hdrs) + return hdrs + + +def _json(url: str, headers: dict | None = None): + return json.loads(_fetch(url, headers)) + + +def shape(tag: str) -> str: + """Signature of a tag with every digit run replaced by '#'. See module docstring.""" + return re.sub(r"\d+", "#", tag) + + +def vkey(tag: str) -> tuple: + """Ordering key: every number in the tag, in order. '1.27.10' > '1.27.9'; text ignored.""" + return tuple(int(x) for x in re.findall(r"\d+", tag)) + + +def parse_ref(ref: str) -> dict: + """Split an image reference into registry / repo / tag / digest.""" + digest = None + if "@" in ref: + ref, _, digest = ref.partition("@") + host, repo, tag = "docker.io", ref, "latest" + # A leading component is a REGISTRY only when there is a path after it. Without the slash test, + # a bare `postgres:15.18` looks like host "postgres:15.18" because of the tag's colon — which + # silently sent every library image to a nonexistent registry. + if "/" in ref: + first = ref.split("/")[0] + if "." in first or ":" in first or first == "localhost": + host, _, repo = ref.partition("/") + if ":" in repo.split("/")[-1]: + repo, _, tag = repo.rpartition(":") + if host == "docker.io" and "/" not in repo: + repo = f"library/{repo}" # bare `redis` is really `library/redis` + return {"registry": host, "repo": repo, "tag": tag, "digest": digest} + + +HUB_RECENT_PAGES = int(os.environ.get("RESOLVE_IMAGES_HUB_PAGES", "40")) +_HUB_TRUNCATED: set[str] = set() + + +def _hub_tag_exists(repo: str, tag: str) -> bool: + try: + _json(f"https://hub.docker.com/v2/repositories/{repo}/tags/{tag}", _hub_auth()) + return True + except Exception: # noqa: BLE001 + return False + + +def _hub_tags(repo: str) -> list[str]: + """Recently-pushed tags, newest first. + + Popular Docker Hub repos carry many thousands of tags, so enumerate a bounded recent window. + A rebuilt old tag can displace a newer version from that window, so callers MUST treat a + truncated listing with no detected upgrade as unverified, not current. (ghcr offers no recency + ordering, which is why that path needs a different strategy.) + """ + tags, url = [], (f"https://hub.docker.com/v2/repositories/{repo}/tags" + f"?page_size=100&ordering=last_updated") + auth = _hub_auth() + for _ in range(HUB_RECENT_PAGES): + d = _json(url, auth) + tags += [r["name"] for r in d.get("results", [])] + url = d.get("next") + if not url: + break + if url: + _HUB_TRUNCATED.add(repo) + return tags + + +def _oci_bearer(host: str, repo: str) -> dict: + """Token for an OCI registry, discovered from its own auth challenge. + + Registries do NOT share a token endpoint. ghcr answers at /token?scope=…&service=ghcr.io, but + lscr.io and dock.mau.dev advertise different realms, and assuming ghcr's shape made both 401 — + which then read as "could not resolve" rather than "asked the wrong URL". The registry tells us + where to go in its WWW-Authenticate header; use that.""" + try: + urllib.request.urlopen( + urllib.request.Request(f"https://{host}/v2/{repo}/tags/list?n=1", + headers={"User-Agent": UA}), timeout=TIMEOUT) + return {} # no auth needed + except urllib.error.HTTPError as e: + if e.code != 401: + return {} + chal = e.headers.get("WWW-Authenticate", "") or "" + except Exception: # noqa: BLE001 + return {} + if not chal.lower().startswith("bearer"): + return {} + parts = dict(re.findall(r'(\w+)="([^"]*)"', chal)) + realm = parts.get("realm") + if not realm: + return {} + q = {"service": parts.get("service", host), "scope": parts.get("scope", f"repository:{repo}:pull")} + url = realm + ("&" if "?" in realm else "?") + urllib.parse.urlencode(q) + try: + tok = (_json(url) or {}).get("token") or (_json(url) or {}).get("access_token") + return {"Authorization": f"Bearer {tok}"} if tok else {} + except Exception: # noqa: BLE001 + return {} + + +def _oci_tags(host: str, repo: str) -> list[str]: + """Tags from any OCI/v2 registry, with challenge-derived auth and Link pagination. + + ghcr paginates hard — immich-server has >40,000 tags — and a truncated listing silently hides + the newest release line, so follow the cursor and let the caller's integrity check catch a read + that never reached the current pin.""" + hdrs = _oci_bearer(host, repo) + tags, url = [], f"https://{host}/v2/{repo}/tags/list?n=1000" + for _ in range(MAX_TAG_PAGES): + for attempt in range(RETRIES): + req = urllib.request.Request(url, headers={"User-Agent": UA, **hdrs}) + try: + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + tags += (json.load(r) or {}).get("tags") or [] + link = r.headers.get("Link", "") or "" + break + except urllib.error.HTTPError as e: + if e.code not in (429, 503) or attempt == RETRIES - 1: + raise + retry_after = e.headers.get("Retry-After") or "" + delay = min(int(retry_after) if retry_after.isdigit() else 2 ** (attempt + 1), 60) + time.sleep(delay) + m = re.search(r'<([^>]+)>;\s*rel="next"', link) + if not m: + break + nxt = m.group(1) + url = f"https://{host}{nxt}" if nxt.startswith("/") else nxt + else: + raise RuntimeError(f"tag listing truncated after {MAX_TAG_PAGES} pages") + return tags + + +def _gh_token() -> str | None: + tok = os.environ.get("GITHUB_TOKEN") + if tok: + return tok.strip() + try: + return open(os.environ.get("GITHUB_TOKEN_FILE", "/srv/cc-ci/.github-token")).read().strip() or None + except OSError: + return None + + +def github_release_tags(owner: str, repo: str, max_pages: int = 4) -> list[str]: + """Release tag names for a GitHub repo, newest first. + + FALLBACK for registries whose tag listing cannot be enumerated. ghcr has no ordering and no + server-side filter, and immich-machine-learning carries >40,000 tags — a full read is impractical + and a partial read silently hides the newest release line. The project's RELEASES are ordered, + small, and authoritative: container tags track them. (The GitHub Packages API would answer this + directly but needs a scoped token; this scan's token deliberately has none.) + """ + hdrs = {"Accept": "application/vnd.github+json"} + tok = _gh_token() + if tok: + hdrs["Authorization"] = f"Bearer {tok}" + out = [] + for page in range(1, max_pages + 1): + try: + rows = _json(f"https://api.github.com/repos/{owner}/{repo}/releases" + f"?per_page=100&page={page}", hdrs) + except Exception: # noqa: BLE001 + break + if not rows: + break + out += [r.get("tag_name") or "" for r in rows] + return [t for t in out if t] + + +def _release_fallback_repos(registry: str, repo: str) -> list[tuple[str, str]]: + """Candidate GitHub repos whose releases track this image's tags.""" + if "ghcr.io" not in registry: + return [] + parts = repo.split("/") + if len(parts) < 2: + return [] + owner, name = parts[0], parts[-1] + cands = [(owner, name)] + # ghcr.io/immich-app/immich-machine-learning is built from immich-app/immich. + if name.startswith(owner.split("-")[0]): + cands.append((owner, owner.split("-")[0])) + return cands + + +def _oci_tag_exists(host: str, repo: str, tag: str) -> bool: + """Verify a release candidate is actually published as an image manifest.""" + hdrs = {"User-Agent": UA, + "Accept": "application/vnd.oci.image.index.v1+json, " + "application/vnd.docker.distribution.manifest.list.v2+json, " + "application/vnd.oci.image.manifest.v1+json", + **_oci_bearer(host, repo)} + url = f"https://{host}/v2/{repo}/manifests/{urllib.parse.quote(tag, safe='')}" + try: + with urllib.request.urlopen(urllib.request.Request(url, headers=hdrs, method="HEAD"), + timeout=TIMEOUT) as response: + return response.status == 200 + except urllib.error.HTTPError as e: + if e.code == 404: + return False + raise + + +def _release_manifest_fallback(registry: str, repo: str, current: str) -> tuple[list[str], str] | None: + """For huge GHCR registries, use release tags only after checking actual manifests.""" + for owner, name in _release_fallback_repos(registry, repo): + releases = github_release_tags(owner, name) + if current not in releases: + continue # incomplete release window; it cannot establish a current baseline + candidates = sorted((tag for tag in set(releases) + if shape(tag) == shape(current) and vkey(tag) >= vkey(current)), + key=vkey, reverse=True) + for tag in candidates: + if _oci_tag_exists(registry, repo, tag): + return [current, tag], f"github-releases+registry-manifest:{owner}/{name}" + return None + + +_TAG_CACHE: dict[tuple[str, str], tuple[list[str], str | None]] = {} + + +def list_tags(registry: str, repo: str) -> tuple[list[str], str | None]: + if (registry, repo) in _TAG_CACHE: + return _TAG_CACHE[(registry, repo)] + res = _list_tags_uncached(registry, repo) + _TAG_CACHE[(registry, repo)] = res + return res + + +def _list_tags_uncached(registry: str, repo: str) -> tuple[list[str], str | None]: + try: + return (_hub_tags(repo) if registry in ("docker.io", "registry-1.docker.io") + else _oci_tags(registry, repo)), None + except urllib.error.HTTPError as e: + return [], f"HTTP {e.code}" + except Exception as e: # noqa: BLE001 + return [], f"{type(e).__name__}: {e}" + + +def resolve(ref: str) -> dict: + """Current pin -> newest same-shape tag, and newest within the current major.""" + if "${" in ref or "$(" in ref: + # The tag is a compose variable (ghost pins `ghost:${IMAGE_VERSION}-alpine`). Its real value + # lives in .env, not here. Report it as skipped, never as a failed lookup. + return {**parse_ref(ref), "ref": ref, "shape": None, "candidates": 0, + "newest_same_shape": None, "newest_within_major": None, + "upgrade_available": False, + "status": "skipped: templated ref (tag comes from a compose variable)"} + info = parse_ref(ref) + out = {**info, "ref": ref, "shape": shape(info["tag"]), "status": "ok", + "newest_same_shape": None, "newest_within_major": None, "candidates": 0, + "upgrade_available": False} + tags, err = list_tags(info["registry"], info["repo"]) + if err: + try: + fallback = (_release_manifest_fallback(info["registry"], info["repo"], info["tag"]) + if "tag listing truncated" in err else None) + except Exception as e: # noqa: BLE001 — a failed fallback must stay unresolved + out["status"] = f"error: registry {err}; release fallback {type(e).__name__}: {e}" + return out + if not fallback: + out["status"] = f"error: {err}" + return out + tags, out["source"] = fallback + out["tags_seen"] = len(set(tags)) + # INTEGRITY CHECK: the tag we are currently running MUST appear in the listing. If it does not, + # the listing is incomplete and any "newest" derived from it is a guess — ghcr paginates to tens + # of thousands of tags and a truncated read silently hides whole release lines. immich's + # machine-learning image is pinned v3.1.0, which EXISTS, yet a short read reported v1.134.0 as + # newest; without this check that becomes a confident, wrong answer. + if info["tag"] not in set(tags): + # Docker Hub: the window is recency-ordered, so the pin being outside it just means the pin + # is old — which is fine, because anything NEWER is necessarily inside the window. Confirm + # the pin genuinely exists (so a typo is still caught) and carry on. + if info["registry"] in ("docker.io", "registry-1.docker.io") and _hub_tag_exists(info["repo"], info["tag"]): + out["source"] = f"docker-hub:recent-{HUB_RECENT_PAGES * 100}" + tags = list(tags) + [info["tag"]] + else: + for owner, name in _release_fallback_repos(info["registry"], info["repo"]): + rel = github_release_tags(owner, name) + if info["tag"] in rel: + tags = rel + out["source"] = f"github-releases:{owner}/{name}" + out["tags_seen"] = len(set(rel)) + break + else: + out["status"] = ("error: tag listing incomplete — the current pin " + f"{info['tag']!r} is absent from {len(set(tags))} registry tags " + f"and from the project's GitHub releases") + return out + want, cur = out["shape"], vkey(info["tag"]) + same = [t for t in set(tags) if shape(t) == want and vkey(t)] + out["candidates"] = len(same) + if not same: + # A floating or unusual tag cannot prove that an image is current. Keep it visible to + # callers rather than letting an empty candidate set become a false UPTODATE verdict. + out["status"] = "unverifiable: no comparable numeric tags" + return out + newest = max(same, key=vkey) + out["newest_same_shape"] = newest + if cur: + within = [t for t in same if vkey(t)[:1] == cur[:1]] + if within: + out["newest_within_major"] = max(within, key=vkey) + out["upgrade_available"] = bool(cur and vkey(newest) > cur) + if (info["registry"] in ("docker.io", "registry-1.docker.io") + and info["repo"] in _HUB_TRUNCATED and not out["upgrade_available"]): + out["status"] = (f"unverifiable: Docker Hub listing truncated after " + f"{HUB_RECENT_PAGES * 100} recent tags") + return out + + +def compose_images_ssh(recipe: str, host: str, recipe_dir: str) -> list[str]: + """Same as compose_images, but the recipe tree lives on another host (cc-ci has no python3).""" + # NB: no shell-quoting of the directory — it may legitimately start with ~ or $HOME, and + # quoting it stops the remote shell expanding it, which yields an empty (and silent) result. + d = f"{recipe_dir}/{shlex.quote(recipe)}".replace("~", "$HOME") + cmd = (f'for f in {d}/compose*.yml; do case "$f" in *compose.ccci.yml) continue;; esac; ' + f'[ -f "$f" ] && {{ cat "$f"; echo; }}; done; exit 0') + out = subprocess.run(["ssh", host, cmd], capture_output=True, text=True, timeout=120) + if out.returncode != 0: + raise RuntimeError(f"ssh {host}: {(out.stderr.strip() or 'no output')[:200]}") + if not out.stdout.strip(): + raise RuntimeError(f"ssh {host}: no compose files found under {d}") + refs = [] + for m in IMAGE_RE.finditer(out.stdout): + if m.group(1) not in refs: + refs.append(m.group(1)) + return refs + + +def compose_images(recipe: str, recipe_dir: str) -> list[str]: + """Every `image:` ref in the recipe's own compose files (the cc-ci overlay is NOT the recipe).""" + refs, base = [], os.path.join(recipe_dir, recipe) + for path in sorted(glob.glob(os.path.join(base, "compose*.yml"))): + if os.path.basename(path) == "compose.ccci.yml": + continue + try: + for m in IMAGE_RE.finditer(open(path).read()): + if m.group(1) not in refs: + refs.append(m.group(1)) + except OSError: + continue + return refs + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("recipe") + ap.add_argument("--ssh", default=None, metavar="HOST", + help="read the recipe's compose files from HOST over ssh (e.g. --ssh cc-ci); " + "resolving still happens locally") + ap.add_argument("--recipe-dir", default=RECIPE_DIR) + ap.add_argument("--table", action="store_true", help="human-readable table instead of JSON") + ap.add_argument("--only", default=None, help="resolve just the images whose ref contains this") + a = ap.parse_args() + + rdir = a.recipe_dir if a.recipe_dir != RECIPE_DIR or not a.ssh else "~/.abra/recipes" + refs = (compose_images_ssh(a.recipe, a.ssh, rdir) if a.ssh + else compose_images(a.recipe, a.recipe_dir)) + if a.only: + refs = [r for r in refs if a.only in r] + results = [resolve(r) for r in refs] + report = { + "recipe": a.recipe, + "images": results, + "upgrades_available": [r["ref"] for r in results if r["upgrade_available"]], + "unresolved": [r["ref"] for r in results if r["status"].startswith(("error", "skipped", "unverifiable"))], + # The whole point: distinguish "checked, current" from "could not check". + "all_resolved": bool(results) and all(r["status"] == "ok" for r in results), + } + if not a.table: + print(json.dumps(report, indent=2)) + return 0 + print(f"{a.recipe} — {len(results)} images") + for r in results: + flag = "UPGRADE" if r["upgrade_available"] else ("UNKNOWN" if r["status"] != "ok" else "current") + print(f" [{flag:7}] {r['repo']}:{r['tag']}" + (" (digest-pinned)" if r["digest"] else "")) + print(f" shape={r['shape']} candidates={r['candidates']}" + f" newest_same_shape={r['newest_same_shape']}" + f" newest_within_major={r['newest_within_major']}") + if r["status"] != "ok": + print(f" status: {r['status']}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/cc-ci/test-advisory-scan.py b/scripts/cc-ci/test-advisory-scan.py new file mode 100755 index 0000000..3505cb0 --- /dev/null +++ b/scripts/cc-ci/test-advisory-scan.py @@ -0,0 +1,955 @@ +#!/usr/bin/env python3 +"""Tests for advisory-scan.py. + +Two tiers: + + OFFLINE (default) — pure logic, fixtures injected in place of the network. Fast, deterministic, + no token, no rate limit. These encode every classification rule and every guarantee the CVE count + makes, including the specific production defects that motivated them. + + LIVE (--live) — re-derives the CVE counts published in the week-2026-08-07 report against the real + advisory APIs. Slow, needs network + ideally a GitHub token. Run before changing classification. + +Usage: + python3 test-advisory-scan.py # offline only + python3 test-advisory-scan.py --live # offline + historic report regressions +""" + +from __future__ import annotations + +import importlib.util +import io +import json +import os +import pathlib +import tempfile +import sys +import unittest +import unittest.mock + +HERE = pathlib.Path(__file__).resolve().parent +_spec = importlib.util.spec_from_file_location("advisory_scan", HERE / "advisory-scan.py") +A = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(A) + + +# ── fixture helpers ─────────────────────────────────────────────────────────────────────────────── + +def adv(cve, patched=None, published=None, severity="high", ghsa=None): + """One GitHub advisory row as github_advisories() would emit it.""" + return {"cve": cve, "ghsa": ghsa or f"GHSA-fake-{cve[-4:]}", "severity": severity, + "summary": f"summary for {cve}", "vulnerable_range": None, "patched": patched, + "url": None, "published_at": published} + + +def gh(owner_repo, advisories, status="ok"): + return {"source": f"github-advisories:{owner_repo}", "status": status, "advisories": advisories} + + +def vendor(url, cves=(), status="ok"): + return {"source": url, "status": status, "cves": list(cves), + "context": {c: f"...{c}..." for c in cves}} + + +def run_scan(gh_entries=(), vendor_entries=(), tag_dates=None, *, v_from=None, v_to=None, + images=None, recipe="fixture", urls=None, releases=None, image_sources=None): + """scan() with every network call replaced by fixtures. + + `releases` maps CVE id -> tags whose release notes name it (the third, release-note method).""" + tag_dates = tag_dates or {} + releases = releases or {} + urls = urls if urls is not None else ["https://github.com/app/app"] + with unittest.mock.patch.object(A, "registry_urls", lambda r, d: (list(urls), "/fake/reg.md")), \ + unittest.mock.patch.object(A, "github_advisories", lambda u: list(gh_entries)), \ + unittest.mock.patch.object(A, "vendor_pages", lambda u: list(vendor_entries)), \ + unittest.mock.patch.object(A, "registry_image_sources", lambda r, d: image_sources or {}), \ + unittest.mock.patch.object(A, "osv", lambda r, v: None), \ + unittest.mock.patch.object(A, "_tag_date", lambda o, r, v: tag_dates.get(v)), \ + unittest.mock.patch.object(A, "release_fix_versions", lambda src, cve: list(releases.get(cve, []))): + return A.scan(recipe, v_from, v_to, "/fake", images) + + +def parse_image_args(argv): + """Drive main()'s --image parsing exactly as the CLI does, returning the tuples scan() receives.""" + captured = {} + + def fake_scan(recipe, vf, vt, reg, images): + captured["images"] = images + return {"recipe": recipe, "from": vf, "to": vt, "registry": reg, "registry_urls": 0, + "sources": [], "cves": {}, "fixed_by_this_upgrade": [], "unclassified": [], + "sources_failed": [], "sources_benign": [], "count_known": True, + "cve_count_fixed": 0, "windows": {}, "classified_by": {}} + + err = io.StringIO() + with unittest.mock.patch.object(A, "scan", fake_scan), \ + unittest.mock.patch.object(sys, "argv", ["advisory-scan.py", *argv]), \ + unittest.mock.patch.object(sys, "stdout", io.StringIO()), \ + unittest.mock.patch.object(sys, "stderr", err): + A.main() + return captured["images"], err.getvalue() + + +# ── A. version ordering ─────────────────────────────────────────────────────────────────────────── + +class TestVersionKey(unittest.TestCase): + def test_strips_prefix_and_suffix(self): + self.assertEqual(A._vkey("v1.27.1"), (1, 27, 1)) + self.assertEqual(A._vkey("1.27.1-rootless"), (1, 27, 1)) + self.assertEqual(A._vkey("2024.06.55"), (2024, 6, 55)) + + def test_empty_and_none(self): + self.assertEqual(A._vkey(None), ()) + self.assertEqual(A._vkey(""), ()) + + def test_dotted_minor_is_numeric_not_lexical(self): + # The bug this guards: "8.10" must be NEWER than "8.2.3". String compare says otherwise. + self.assertGreater(A._vkey("8.10"), A._vkey("8.2.3")) + self.assertGreater(A._vkey("1.27.10"), A._vkey("1.27.9")) + + def test_shorter_prefix_orders_below_its_own_patch(self): + # 7.4 < 7.4.1, so a CVE patched in 7.4.1 IS fixed by moving off a bare 7.4 pin. + self.assertLess(A._vkey("7.4"), A._vkey("7.4.1")) + + +class TestWindowMembership(unittest.TestCase): + """(from, to] membership — exclusive lower, inclusive upper, compared zero-padded.""" + + def _in(self, f, t, c): + return A._within(A._vkey(f), A._vkey(t), A._vkey(c)) + + def test_bounds(self): + self.assertTrue(self._in("1.27.0", "1.27.1", "1.27.1")) # upper inclusive + self.assertFalse(self._in("1.27.0", "1.27.1", "1.27.0")) # lower exclusive + self.assertFalse(self._in("1.27.0", "1.27.1", "1.26.9")) + self.assertFalse(self._in("1.27.0", "1.27.1", "1.28.0")) + + def test_bare_major_upper_bound_includes_its_dot_zero(self): + # Regression: plain tuple order makes (18,) < (18,0), so a fix in 18.0 fell OUTSIDE a + # window ending at 18. Bare major tags are the norm for sidecars (postgres:18, redis:8). + self.assertTrue(self._in("17", "18", "18.0")) + self.assertTrue(self._in("7", "8", "8.0")) + self.assertTrue(self._in("7.4", "8.10", "8.0.4")) + + def test_bare_major_upper_bound_excludes_later_patches(self): + # Conservative on the other side: nothing proves which 18.x a floating tag resolved to. + self.assertFalse(self._in("17", "18", "18.5")) + + def test_bare_version_is_read_literally_as_dot_zero(self): + # from="8" means 8.0, so a fix in 8.0.4 is inside a window that ends at 9. + self.assertTrue(self._in("8", "9", "8.0.4")) + self.assertFalse(self._in("8", "9", "8.0")) # == the stated lower bound + + def test_prefix_lower_bound_still_counts_its_patches(self): + self.assertTrue(self._in("7.4", "8.10", "7.4.1")) + self.assertTrue(self._in("7.4", "8.10", "7.4.6")) + + def test_the_false_133_cve_stays_out(self): + self.assertFalse(self._in("7.4", "8.10", "6.0.11")) + + +# ── B. registry URL extraction ──────────────────────────────────────────────────────────────────── + +class TestRegistryUrls(unittest.TestCase): + def _write(self, tmp, text): + p = pathlib.Path(tmp) / "r.md" + p.write_text(text) + return A.registry_urls("r", tmp) + + def test_prose_ellipsis_is_not_a_security_source(self): + with tempfile.TemporaryDirectory() as directory: + urls, _ = self._write(directory, + "https://github.com/cryptpad/cryptpad and example `https://…` URLs " + "http://docspec:3000/conversion http://127.0.0.1:3000/health") + self.assertEqual(urls, ["https://github.com/cryptpad/cryptpad"]) + + def test_image_source_table_maps_monorepo_images(self): + mapping = A.registry_image_sources("lasuite-drive", str(HERE / "upstream")) + self.assertIn("github-advisories:suitenumerique/drive", mapping["drive-backend"]) + self.assertIn("github-advisories:CollaboraOnline/online", mapping["code"]) + + def test_common_database_cpes_follow_registry_images(self): + self.assertIn(("postgres", A.COMMON_IMAGE_CPES["postgres"]), + A.registry_cpes("immich", str(HERE / "upstream"))) + self.assertIn(("mariadb", A.COMMON_IMAGE_CPES["mariadb"]), + A.registry_cpes("gitea", str(HERE / "upstream"))) + self.assertIn(("rustdesk-server", "cpe:2.3:a:rustdesk:rustdesk_server:*:*:*:*:oss:*:*:*"), + A.registry_cpes("rustdesk-server", str(HERE / "upstream"))) + + def test_strips_trailing_markdown_punctuation(self): + # Production defect: a captured backtick 404'd the fetch and rendered n8n/immich as '?'. + import tempfile + with tempfile.TemporaryDirectory() as tmp: + urls, _ = self._write(tmp, "see `https://docs.n8n.io/release-notes/` and " + "**https://example.com/sec.html**, plus https://a.test/x.") + self.assertIn("https://docs.n8n.io/release-notes/", urls) + self.assertIn("https://example.com/sec.html", urls) + self.assertIn("https://a.test/x", urls) + self.assertFalse([u for u in urls if u.endswith(("`", "*", ".", ","))]) + + def test_dedupes_and_reports_missing_registry(self): + import tempfile + with tempfile.TemporaryDirectory() as tmp: + urls, path = self._write(tmp, "https://a.test/x https://a.test/x") + self.assertEqual(urls.count("https://a.test/x"), 1) + self.assertTrue(path.endswith("r.md")) + urls, path = A.registry_urls("does-not-exist", "/nonexistent-dir") + self.assertEqual((urls, path), ([], None)) + + +class TestNvdCompleteness(unittest.TestCase): + def test_truncated_results_are_not_a_clean_zero(self): + payload = json.dumps({"totalResults": 2, "vulnerabilities": [{"cve": {"id": "CVE-2026-0001"}}]}) + with unittest.mock.patch.object(A, "_fetch", return_value=payload): + row = A.nvd_advisories("cpe:2.3:a:example:server:*:*:*:*:*:*:*:*", "server") + self.assertEqual(row["status"], "error: NVD result set truncated") + self.assertEqual(row["advisories"], []) + + def test_database_backport_is_not_credited_again_on_major_upgrade(self): + ranges = [ + {"version": "*", "versionStartIncluding": "15.0", "versionEndExcluding": "15.14"}, + {"version": "*", "versionStartIncluding": "16.0", "versionEndExcluding": "16.5"}, + ] + self.assertIs(A._nvd_affects("15.13", ranges), True) + self.assertIs(A._nvd_affects("15.19", ranges), False) + self.assertIs(A._nvd_affects("18.6", ranges), False) + self.assertIsNone(A._nvd_affects("15-alpine", ranges)) + + +# ── C. --image argument parsing ─────────────────────────────────────────────────────────────────── + +class TestImageArgParsing(unittest.TestCase): + def test_single_and_repeated(self): + imgs, _ = parse_image_args(["r", "--image", "redis=7.4:8.10"]) + self.assertEqual(imgs, [("redis", "7.4", "8.10")]) + imgs, _ = parse_image_args(["r", "--image", "redis=7.4:8.10", "--image", "postgres=17:18"]) + self.assertEqual(imgs, [("redis", "7.4", "8.10"), ("postgres", "17", "18")]) + + def test_malformed_is_skipped_with_a_warning_not_a_crash(self): + # It is an ADDITIVE pre-step: one typo must not abort the upgrade's scan step. + for bad in ("redis=7.4", "redis", "=7.4:8.10", "redis=:8.10", "redis=7.4:"): + imgs, err = parse_image_args(["r", "--image", bad]) + self.assertEqual(imgs, [], f"{bad!r} should be rejected") + self.assertIn("malformed", err) + + def test_good_and_bad_mixed_keeps_the_good(self): + imgs, err = parse_image_args(["r", "--image", "redis=7.4:8.10", "--image", "nope"]) + self.assertEqual(imgs, [("redis", "7.4", "8.10")]) + self.assertIn("malformed", err) + + +# ── D. classification ───────────────────────────────────────────────────────────────────────────── + +class TestClassificationBoundaries(unittest.TestCase): + def _one(self, patched, v_from="1.27.0", v_to="1.27.1"): + rep = run_scan([gh("app/app", [adv("CVE-2026-0001", patched=patched)])], + v_from=v_from, v_to=v_to) + return rep + + def test_patched_at_upper_bound_counts(self): + self.assertEqual(self._one("1.27.1")["fixed_by_this_upgrade"], ["CVE-2026-0001"]) + + def test_patched_at_lower_bound_does_not_count(self): + # Already fixed in the version we were ON — this upgrade did not fix it. + rep = self._one("1.27.0") + self.assertEqual(rep["fixed_by_this_upgrade"], []) + self.assertEqual(rep["cve_count_fixed"], 0) + + def test_patched_below_and_above_window_do_not_count(self): + self.assertEqual(self._one("1.26.0")["fixed_by_this_upgrade"], []) + self.assertEqual(self._one("1.28.0")["fixed_by_this_upgrade"], []) + + def test_any_of_several_patched_lines_counts(self): + # n8n regression: one advisory patches several release lines; reading only the first + # dropped the line the deployment was on (CVE-2026-42231/42232 misclassified). + rep = self._one("1.123.32; 2.17.4; 2.18.1", v_from="2.17.0", v_to="2.17.4") + self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2026-0001"]) + + def test_no_patched_data_is_not_counted(self): + self.assertEqual(self._one(None)["fixed_by_this_upgrade"], []) + + +class TestPerImageWindows(unittest.TestCase): + """The false-133 family of defects: an image must only ever be judged by its OWN versions.""" + + APP = gh("discourse/discourse", [adv("CVE-APP-0001", patched="3.5.4", published="2026-03-01T00:00:00Z")]) + REDIS = gh("redis/redis", [ + adv("CVE-2021-21309", patched="6.0.11", published="2021-02-01T00:00:00Z"), + adv("CVE-2025-49844", patched="7.4.6; 8.0.4; 8.2.2", published="2025-10-01T00:00:00Z", + severity="critical"), + ]) + URLS = ["https://github.com/discourse/discourse", "https://github.com/redis/redis"] + + def test_sidecar_cve_is_not_judged_by_the_app_window(self): + # redis 6.0.11 sits numerically inside discourse 3.5.3 -> 2026.7.1. It must NOT count. + rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="2026.7.1", + tag_dates={"3.5.3": "2025-12-30T00:00:00Z", "2026.7.1": "2026-07-31T00:00:00Z"}, + urls=self.URLS) + self.assertNotIn("CVE-2021-21309", rep["fixed_by_this_upgrade"]) + self.assertIn("CVE-2021-21309", rep["unclassified"]) + + def test_unwindowed_image_is_unclassified_never_counted(self): + rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="3.5.4", urls=self.URLS) + self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-APP-0001"]) + for cve in ("CVE-2021-21309", "CVE-2025-49844"): + self.assertIn(cve, rep["unclassified"]) + + def test_sidecar_window_counts_only_what_that_bump_fixed(self): + rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="3.5.4", + images=[("redis", "7.4", "8.10")], urls=self.URLS) + self.assertIn("CVE-2025-49844", rep["fixed_by_this_upgrade"]) # patched 7.4.6, in window + self.assertNotIn("CVE-2021-21309", rep["fixed_by_this_upgrade"]) # patched 6.0.11, below it + self.assertEqual(rep["cve_count_fixed"], 2) # app 1 + redis 1 + + def test_count_is_the_union_across_images(self): + rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="3.5.4", + images=[("redis", "7.4", "8.10")], urls=self.URLS) + self.assertEqual(sorted(rep["fixed_by_this_upgrade"]), ["CVE-2025-49844", "CVE-APP-0001"]) + + def test_each_image_classified_independently(self): + # App crosses a scheme change (date method); redis does not (version method). Both resolve. + rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="2026.7.1", + images=[("redis", "7.4", "8.10")], urls=self.URLS, + tag_dates={"3.5.3": "2025-12-30T00:00:00Z", "2026.7.1": "2026-07-31T00:00:00Z"}) + methods = rep["classified_by"] + self.assertIn("publish date", methods["github-advisories:discourse/discourse"]) + self.assertEqual(methods["github-advisories:redis/redis"], "patched version ranges") + self.assertTrue(rep["count_known"]) + + def test_image_name_matches_as_substring(self): + rep = run_scan([self.APP, gh("discourse/discourse-postgres", [adv("CVE-PG-1", patched="18.0")])], + v_from="3.5.3", v_to="3.5.4", images=[("postgres", "17", "18")], + urls=["https://github.com/discourse/discourse", + "https://github.com/discourse/discourse-postgres"]) + self.assertIn("github-advisories:discourse/discourse-postgres", rep["windows"]) + self.assertIn("CVE-PG-1", rep["fixed_by_this_upgrade"]) + + def test_primary_cannot_be_stolen_by_a_loose_image_name(self): + rep = run_scan([self.APP, gh("discourse/discourse-postgres", [adv("CVE-PG-1", patched="18.0")])], + v_from="3.5.3", v_to="3.5.4", images=[("discourse", "1", "2")], + urls=["https://github.com/discourse/discourse", + "https://github.com/discourse/discourse-postgres"]) + self.assertEqual(rep["windows"]["github-advisories:discourse/discourse"], + {"from": "3.5.3", "to": "3.5.4"}) + + def test_unmatched_image_name_makes_count_unknown(self): + # A typo'd sidecar name must not silently turn its CVEs into a clean zero. + rep = run_scan([self.APP], v_from="3.5.3", v_to="3.5.4", + images=[("nosuchimage", "1", "2")], urls=self.URLS[:1]) + self.assertEqual(list(rep["windows"]), ["github-advisories:discourse/discourse"]) + self.assertFalse(rep["count_known"]) + self.assertEqual(rep["unmatched_image_windows"], ["nosuchimage"]) + self.assertIsNone(rep["cve_count_fixed"]) + + def test_registry_maps_image_to_differently_named_source(self): + rep = run_scan([self.APP, gh("suitenumerique/drive", [adv("CVE-DRIVE-1", patched="0.25.3")])], + v_from="3.5.3", v_to="3.5.4", images=[("drive-backend", "0.22.0", "0.25.3")], + urls=self.URLS, + image_sources={"drive-backend": {"github-advisories:suitenumerique/drive"}}) + self.assertEqual(rep.get("unmatched_image_windows"), None) + self.assertIn("CVE-DRIVE-1", rep["fixed_by_this_upgrade"]) + + def test_monorepo_images_share_identical_window(self): + source = "github-advisories:suitenumerique/drive" + rep = run_scan([gh("suitenumerique/drive", [adv("CVE-DRIVE-1", patched="0.25.3")])], + v_from="0.22.0", v_to="0.25.3", + images=[("drive-backend", "0.22.0", "0.25.3")], + image_sources={"drive-backend": {source}}) + self.assertTrue(rep["count_known"]) + self.assertEqual(rep.get("unmatched_image_windows"), None) + self.assertEqual(rep["cve_count_fixed"], 1) + + +class TestSchemeChangeDateFallback(unittest.TestCase): + DATES = {"3.5.3": "2025-12-30T00:00:00Z", "2026.7.1": "2026-07-31T00:00:00Z"} + + def _rep(self, advisories, dates=None): + return run_scan([gh("discourse/discourse", advisories)], v_from="3.5.3", v_to="2026.7.1", + tag_dates=self.DATES if dates is None else dates) + + def test_counts_advisories_published_inside_the_date_window(self): + rep = self._rep([adv("CVE-IN-1", published="2026-03-01T00:00:00Z"), + adv("CVE-OUT-1", published="2025-06-01T00:00:00Z"), + adv("CVE-OUT-2", published="2026-09-01T00:00:00Z")]) + self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-IN-1"]) + + def test_date_boundaries_match_the_version_rule(self): + # Exclusive lower, inclusive upper — same as 4a, so the two methods agree at the edges. + rep = self._rep([adv("CVE-LOWER", published=self.DATES["3.5.3"]), + adv("CVE-UPPER", published=self.DATES["2026.7.1"])]) + self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-UPPER"]) + + def test_advisory_without_a_publish_date_is_not_counted(self): + self.assertEqual(self._rep([adv("CVE-NODATE", published=None)])["fixed_by_this_upgrade"], []) + + def test_scheme_change_is_detected_not_version_compared(self): + rep = self._rep([adv("CVE-IN-1", patched="2026.1.0", published="2026-03-01T00:00:00Z")]) + self.assertIn("publish date", rep["classified_by"]["github-advisories:discourse/discourse"]) + self.assertIn("github-advisories:discourse/discourse", rep["date_window"]) + + def test_small_major_bump_still_uses_version_ranges(self): + rep = run_scan([gh("app/app", [adv("CVE-X", patched="3.0.0")])], v_from="2.9.0", v_to="3.0.0") + self.assertEqual(rep["classified_by"]["github-advisories:app/app"], "patched version ranges") + + +# ── E. count guarantees ─────────────────────────────────────────────────────────────────────────── + +class TestCountGuarantees(unittest.TestCase): + def test_unresolvable_window_yields_unknown_never_zero(self): + # Scheme change AND tag dates unresolvable -> must refuse to emit a number. + rep = run_scan([gh("app/app", [adv("CVE-1", published="2026-01-01T00:00:00Z")])], + v_from="3.5.3", v_to="2026.7.1", tag_dates={}) + self.assertIs(rep["cve_count_fixed"], None) + self.assertFalse(rep["count_known"]) + md = A.markdown(rep) + self.assertIn("UNKNOWN", md) + self.assertIn("NOT zero", md) + + def test_one_unresolvable_image_makes_the_whole_count_unknown(self): + # A partial number would understate a security figure, so it is suppressed entirely. + rep = run_scan([gh("app/app", [adv("CVE-APP", patched="1.1")]), + gh("redis/redis", [adv("CVE-REDIS", patched="8.0")])], + v_from="1.0", v_to="1.1", images=[("redis", "7.4", "9999.1")], + tag_dates={}, urls=["https://github.com/app/app", "https://github.com/redis/redis"]) + self.assertIs(rep["cve_count_fixed"], None) + self.assertFalse(rep["count_known"]) + + def test_genuine_zero_is_reported_as_zero(self): + rep = run_scan([gh("app/app", [adv("CVE-1", patched="9.9.9")])], v_from="1.0", v_to="1.1") + self.assertEqual(rep["cve_count_fixed"], 0) + self.assertTrue(rep["count_known"]) + self.assertIn("0 identified", A.markdown(rep)) + + def test_ghsa_without_cve_is_preserved_as_security_advisory(self): + entry = {"cve": None, "ghsa": "GHSA-aaaa-bbbb-cccc", "severity": "low", + "patched": "1.1", "summary": "security fix", "published_at": None} + rep = run_scan([gh("app/app", [entry])], v_from="1.0", v_to="1.1") + self.assertTrue(rep["count_known"]) + self.assertEqual(rep["cve_count_fixed"], 0) + self.assertEqual(rep["fixed_non_cve_advisories"], ["GHSA-aaaa-bbbb-cccc"]) + self.assertIn("use YES", A.markdown(rep)) + + def test_404_advisory_feed_is_benign_not_a_failure(self): + rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")]), + gh("side/car", [], status="no-advisories-published")], + v_from="1.0", v_to="1.1") + self.assertEqual(rep["sources_failed"], []) + self.assertIn("github-advisories:side/car", rep["sources_benign"]) + self.assertEqual(rep["cve_count_fixed"], 1) + + def test_template_url_is_benign_not_a_failure(self): + rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")])], + [vendor("https://x.test/changelog/v/", status="skipped: template URL")], + v_from="1.0", v_to="1.1") + self.assertEqual(rep["sources_failed"], []) + + def test_real_source_failure_is_surfaced(self): + rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")], status="error: HTTP 500")], + v_from="1.0", v_to="1.1") + self.assertIn("github-advisories:app/app", rep["sources_failed"]) + self.assertIn("FAILED", A.markdown(rep)) + self.assertFalse(rep["count_known"]) + + def test_only_404_feed_is_not_evidence_of_clean_scan(self): + rep = run_scan([gh("app/app", [], status="no-advisories-published")], + v_from="1.0", v_to="1.1") + self.assertTrue(rep["no_usable_sources"]) + self.assertFalse(rep["count_known"]) + + def test_no_window_given_classifies_nothing(self): + rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")])]) + self.assertEqual(rep["fixed_by_this_upgrade"], []) + self.assertIn("CVE-1", rep["unclassified"]) + + +class TestVendorOnlyCves(unittest.TestCase): + """The gitea case: CVEs named ONLY on a vendor page, absent from the GitHub advisory feed.""" + + def test_vendor_only_cve_is_recorded_and_surfaced(self): + rep = run_scan([gh("go-gitea/gitea", [])], + [vendor("https://blog.gitea.com/release-1.27.1/", ["CVE-2026-60004"])], + v_from="1.27.0", v_to="1.27.1") + self.assertIn("CVE-2026-60004", rep["cves"]) + self.assertIn("CVE-2026-60004", rep["unclassified"]) + + def test_vendor_only_cve_is_NOT_counted_but_IS_sent_for_judgement(self): + # It carries no version data, so no arithmetic can place it — the deterministic count must + # not include it. It must not be silently dropped either: pass 2 gets it with its evidence. + rep = run_scan([gh("go-gitea/gitea", [])], + [vendor("https://blog.gitea.com/release-1.27.1/", ["CVE-2026-60004"])], + v_from="1.27.0", v_to="1.27.1") + self.assertEqual(rep["fixed_by_this_upgrade"], []) + self.assertEqual(rep["cve_count_fixed"], 0) + self.assertIn("CVE-2026-60004", A.needs_judgement(rep)) + + def test_cve_in_both_vendor_and_advisory_feed_is_counted_once(self): + rep = run_scan([gh("go-gitea/gitea", [adv("CVE-2026-60004", patched="1.27.1")])], + [vendor("https://blog.gitea.com/x/", ["CVE-2026-60004"])], + v_from="1.27.0", v_to="1.27.1") + self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2026-60004"]) + self.assertEqual(rep["cve_count_fixed"], 1) + self.assertEqual(len(rep["cves"]["CVE-2026-60004"]["sources"]), 2) + + +class TestIndeterminateBucket(unittest.TestCase): + """An advisory with no knowable fix version is neither counted nor dismissed.""" + + def test_tbd_patched_is_indeterminate_not_excluded(self): + rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + self.assertEqual(rep["fixed_by_this_upgrade"], []) + self.assertIn("CVE-TBD", rep["indeterminate"]) + self.assertEqual(rep["cve_count_indeterminate"], 1) + + def test_placeholder_patched_is_indeterminate(self): + # "7.4.X" could be 7.4.1 — inside the window. Extracting a bare 7.4 and excluding it was + # how CVE-2024-46981 (high) went missing. + rep = run_scan([gh("redis/redis", [adv("CVE-X", patched="6.2.X, 7.2.X, 7.4.X")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + self.assertIn("CVE-X", rep["indeterminate"]) + + def test_real_versions_outside_the_window_are_decided_not_indeterminate(self): + rep = run_scan([gh("redis/redis", [adv("CVE-OLD", patched="6.0.11")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + self.assertEqual(rep["indeterminate"], []) + self.assertEqual(rep["cve_count_fixed"], 0) + + def test_indeterminate_is_surfaced_in_the_markdown_and_not_read_as_zero(self): + rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD", severity="critical")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + md = A.markdown(rep) + self.assertIn("could NOT be judged", md) + self.assertIn("must NOT be read as unaffected", md) + + +class TestReleaseNoteResolution(unittest.TestCase): + """Third method: a release whose notes NAME the CVE supplies the fix version the advisory lacks.""" + + def test_release_naming_the_cve_inside_the_window_counts_it(self): + rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], + releases={"CVE-TBD": ["6.2.19", "7.2.10", "7.4.5", "8.0.3"]}) + self.assertIn("CVE-TBD", rep["fixed_by_this_upgrade"]) + self.assertEqual(rep["indeterminate"], []) + self.assertEqual(rep["resolved_by_release_notes"]["CVE-TBD"], ["7.4.5", "8.0.3"]) + + def test_naming_releases_all_below_the_window_means_ALREADY_fixed(self): + # Every known fix predates the version we were already on, so this upgrade did not deliver + # it. That is a DECISION, not an unknown — mailu's redis 8.8.0 → 8.10.0 crosses 12 such + # advisories, and calling them "could not judge" overstates the uncertainty. + rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], + releases={"CVE-TBD": ["6.2.19"]}) + self.assertEqual(rep["fixed_by_this_upgrade"], []) + self.assertEqual(rep["indeterminate"], []) + self.assertIn("CVE-TBD", rep["already_fixed_before_upgrade"]) + self.assertIn("outside-window", rep["cves"]["CVE-TBD"]["classification"]) + + def test_naming_releases_only_ABOVE_the_window_stays_indeterminate(self): + # The fix landed after our target, so we are still exposed. Deliberately NOT decided as a + # tidy "not fixed": it is an open vulnerability and must stay visible to the operator. + rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], + releases={"CVE-TBD": ["9.0.0"]}) + self.assertEqual(rep["fixed_by_this_upgrade"], []) + self.assertIn("CVE-TBD", rep["indeterminate"]) + + def test_vendor_page_cve_on_the_same_repo_uses_release_notes(self): + # mailu announces its Roundcube CVEs only on github.com/Mailu/Mailu/releases. Requiring an + # advisory feed sent a deterministic case to pass 2; it is now decided in pass 1. + rep = run_scan([gh("Mailu/Mailu", [])], + [vendor("https://github.com/Mailu/Mailu/releases", ["CVE-2026-54432"])], + v_from="2024.06.55", v_to="2024.06.57", + urls=["https://github.com/Mailu/Mailu"], + releases={"CVE-2026-54432": ["2024.06.56"]}) + self.assertIn("CVE-2026-54432", rep["fixed_by_this_upgrade"]) + self.assertEqual(rep["cve_count_fixed"], 1) + + def test_release_evidence_is_recorded_for_audit(self): + rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], + releases={"CVE-TBD": ["7.4.5"]}) + e = rep["cves"]["CVE-TBD"] + self.assertEqual(e["fix_versions_from_release_notes"], ["7.4.5"]) + self.assertIn("named in release notes", e["classification"]) + + def test_it_does_not_override_a_version_range_decision(self): + # A CVE already counted by patched ranges is untouched; the method only rescues undecided. + rep = run_scan([gh("redis/redis", [adv("CVE-OK", patched="7.4.1")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"], + releases={"CVE-OK": ["7.4.1"]}) + self.assertNotIn("CVE-OK", rep.get("resolved_by_release_notes") or {}) + + +class TestReleaseLineSemantics(unittest.TestCase): + """A fix inside the numeric window is not a fix on the branch you actually land on.""" + + def test_fix_later_on_the_targets_own_line_is_not_counted(self): + # ClickHouse fixed CVE-2023-48704 in 23.9.6.20 AND 23.10.5.20. Landing on 23.10.4.25 crosses + # the 23.9 fix numerically but is BELOW its own line's fix, so it does not have it. + rep = run_scan([gh("ClickHouse/ClickHouse", + [adv("CVE-2023-48704", patched="v23.10.5.20; v23.9.6.20; v23.8.8.20")])], + v_from="23.4.2.11", v_to="23.10.4.25", + urls=["https://github.com/ClickHouse/ClickHouse"]) + self.assertEqual(rep["fixed_by_this_upgrade"], []) + + def test_fix_earlier_on_the_targets_own_line_is_counted(self): + rep = run_scan([gh("ClickHouse/ClickHouse", + [adv("CVE-2023-47118", patched="v23.10.2.13; v23.8.6.16")])], + v_from="23.4.2.11", v_to="23.10.4.25", + urls=["https://github.com/ClickHouse/ClickHouse"]) + self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2023-47118"]) + + def test_fix_exactly_at_the_target_is_counted(self): + rep = run_scan([gh("ClickHouse/ClickHouse", + [adv("CVE-2023-48298", patched="v23.10.4.25; v23.9.5.29")])], + v_from="23.4.2.11", v_to="23.10.4.25", + urls=["https://github.com/ClickHouse/ClickHouse"]) + self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2023-48298"]) + + def test_no_fix_on_the_target_line_falls_back_to_the_window(self): + # redis fixes 7.4.6/8.0.4/8.2.2 with no 8.10.x entry; landing on 8.10 still has them, + # because nothing on the 8.10 line is named as a LATER fix. + rep = run_scan([gh("redis/redis", [adv("CVE-2025-49844", patched="7.4.6; 8.0.4; 8.2.2")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2025-49844"]) + + +class TestAlreadyFixedOnFromLine(unittest.TestCase): + """A fix that landed on the line we upgrade FROM was already ours before the upgrade.""" + + def test_backport_to_our_own_line_is_not_credited(self): + # mattermost patches every maintained line at once. 10.11.22 -> 10.12.4 crosses 10.12.1, but + # 10.11.22 is already past 10.11.4, so the deployment HAD the fix. Counting it credits the + # upgrade with work it did not do. + rep = run_scan([gh("mattermost/mattermost", + [adv("CVE-1", patched="10.11.4; 10.12.1; 10.5.12")])], + v_from="10.11.22", v_to="10.12.4", + urls=["https://github.com/mattermost/mattermost"]) + self.assertEqual(rep["fixed_by_this_upgrade"], []) + + def test_a_fix_ABOVE_our_position_on_the_same_line_still_counts(self): + rep = run_scan([gh("mattermost/mattermost", [adv("CVE-2", patched="10.11.30; 10.12.1")])], + v_from="10.11.22", v_to="10.12.4", + urls=["https://github.com/mattermost/mattermost"]) + self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2"]) + + def test_placeholders_never_feed_this_rule(self): + # "7.4.X" parses to a bare 7.4, which would read as "already fixed at 7.4" and silently drop + # a real fix — this is exactly how redis CVE-2024-46981 was lost when the rule was added. + rep = run_scan([gh("redis/redis", [adv("CVE-3", patched="6.2.X, 7.2.X, 7.4.X")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + self.assertIn("CVE-3", rep["indeterminate"]) + self.assertEqual(rep["fixed_by_this_upgrade"], []) + + +class TestChangelogAttribution(unittest.TestCase): + """Projects that publish no advisory feed still say which release fixed what — in their changelog.""" + + CHANGES = """ +Changes with nginx 1.31.3 11 Aug 2026 + *) Security: a flaw ... (CVE-2026-60005) + *) Security: another ... (CVE-2026-56434) + +Changes with nginx 1.31.2 04 Aug 2026 + *) Security: something ... (CVE-2026-48142) + +Changes with nginx 1.31.1 21 Jul 2026 + *) Security: older ... (CVE-2026-9256) + +Changes with nginx 1.20.0 01 Jan 2021 + *) Security: ancient ... (CVE-2013-2028) +""" + + def test_each_cve_is_attributed_to_the_release_that_fixed_it(self): + got = A._changelog_versions(self.CHANGES) + self.assertEqual(got["CVE-2026-60005"], "1.31.3") + self.assertEqual(got["CVE-2026-48142"], "1.31.2") + self.assertEqual(got["CVE-2026-9256"], "1.31.1") + self.assertEqual(got["CVE-2013-2028"], "1.20.0") + + def _scan(self, wfrom, wto): + # nginx publishes NO GitHub advisories — the feed is empty and the changelog is everything. + return run_scan( + [gh("nginx/nginx", [])], + [{"source": "https://nginx.org/en/CHANGES", "status": "ok", + "cves": sorted(A._changelog_versions(self.CHANGES)), + "context": {}, "fixed_in": A._changelog_versions(self.CHANGES)}], + images=[("nginx", wfrom, wto)], urls=["https://github.com/nginx/nginx"]) + + def test_window_counts_only_the_releases_it_crosses(self): + rep = self._scan("1.31.1", "1.31.3") # 1.31.1 is the FROM, so its CVE is already fixed + self.assertEqual(set(rep["fixed_by_this_upgrade"]), + {"CVE-2026-48142", "CVE-2026-56434", "CVE-2026-60005"}) + + def test_a_narrower_window_counts_fewer(self): + rep = self._scan("1.31.2", "1.31.3") + self.assertEqual(set(rep["fixed_by_this_upgrade"]), {"CVE-2026-56434", "CVE-2026-60005"}) + + def test_ancient_entries_are_not_swept_in(self): + # The changelog lists the project's whole history; only the crossed releases may count. + rep = self._scan("1.31.1", "1.31.3") + self.assertNotIn("CVE-2013-2028", rep["fixed_by_this_upgrade"]) + + def test_evidence_is_recorded(self): + rep = self._scan("1.31.1", "1.31.3") + self.assertEqual(rep["resolved_by_changelog"]["CVE-2026-60005"], "1.31.3") + + +class TestComposeDerivedWindows(unittest.TestCase): + """Windows read off a compose diff, so nobody has to remember which --image args an upgrade needs.""" + + OLD = """ +services: + app: + image: "plausible/analytics:v2.0.0" + db: + image: pgautoupgrade/pgautoupgrade:18-alpine + plausible_events_db: + image: clickhouse/clickhouse-server:23.4.2.11-alpine +volumes: + data: +""" + NEW = """ +services: + app: + image: "ghcr.io/plausible/community-edition:v3.2.1" + db: + image: pgautoupgrade/pgautoupgrade:18-alpine + plausible_events_db: + image: clickhouse/clickhouse-server:24.12-alpine +volumes: + data: +""" + + def _windows(self, old=None, new=None): + pages = {"to": new if new is not None else self.NEW, + "from": old if old is not None else self.OLD} + with unittest.mock.patch.object(A, "_fetch", lambda u, h=None: pages["to" if "to" in u else "from"]), \ + unittest.mock.patch.object(A, "_gitea_auth", lambda u: {}): + return A.windows_from_compose("http://x/to", "http://x/from")[0] + + def test_app_service_leads_and_sidecars_follow(self): + w = self._windows() + self.assertEqual(w[0], ("community-edition", "v2.0.0", "v3.2.1")) + self.assertIn(("clickhouse-server", "23.4.2.11-alpine", "24.12-alpine"), w) + + def test_unchanged_images_are_not_windows(self): + # pgautoupgrade is identical in both; inventing a window for it would be a false count. + self.assertNotIn("pgautoupgrade", [n for n, _, _ in self._windows()]) + + def test_a_changed_image_REPO_is_still_the_same_service(self): + # plausible/analytics -> ghcr.io/plausible/community-edition. Keyed by image repo this reads + # as one image vanishing and another appearing, and the app window is lost entirely. + w = self._windows() + self.assertTrue(any(n == "community-edition" and f == "v2.0.0" for n, f, _ in w)) + + def test_no_change_yields_no_windows(self): + self.assertEqual(self._windows(old=self.NEW, new=self.NEW), []) + + def test_lasuite_docs_pr_does_not_claim_preexisting_valkey_upgrade(self): + base = """services: + app: + image: lasuite/impress-frontend:v6.0.4 + yhub-valkey: + image: valkey/valkey:9.1.3-alpine + docspec: + image: ghcr.io/docspecio/api:3.0.2 +""" + head = base.replace("ghcr.io/docspecio/api:3.0.2", "ghcr.io/docspec/api:1.21.4") + windows = self._windows(old=base, new=head) + self.assertEqual(windows, [("api", "3.0.2", "1.21.4")]) + self.assertNotIn("valkey", [name for name, _, _ in windows]) + + captured = {} + + def fake_scan(recipe, v_from, v_to, registry, images): + captured.update(from_version=v_from, to_version=v_to, images=images) + return {"recipe": recipe, "from": v_from, "to": v_to, + "count_known": True, "cve_count_fixed": 0, "cves": {}, "sources": [], + "fixed_by_this_upgrade": [], "unclassified": [], "registry_urls": 0, + "sources_failed": [], "sources_benign": [], "windows": {}, + "classified_by": {}} + + with unittest.mock.patch.object(A, "windows_from_compose", + return_value=(windows, "pinned base", False)), \ + unittest.mock.patch.object(A, "scan", fake_scan), \ + unittest.mock.patch.object(sys, "argv", ["advisory-scan.py", "lasuite-docs", + "--compose-from", "base", "--compose-to", "head"]), \ + unittest.mock.patch.object(sys, "stdout", io.StringIO()), \ + unittest.mock.patch.object(sys, "stderr", io.StringIO()): + A.main() + self.assertIsNone(captured["from_version"]) + self.assertEqual(captured["images"], windows) + + def test_templated_tags_are_skipped(self): + new = self.NEW.replace('ghcr.io/plausible/community-edition:v3.2.1', 'ghost:${IMAGE_VERSION}') + self.assertNotIn("ghost", [n for n, _, _ in self._windows(new=new)]) + + +class TestImageNameMatching(unittest.TestCase): + """An image name and its advisory source rarely spell each other exactly.""" + + def test_matches_when_the_image_name_is_LONGER_than_the_source(self): + # clickhouse/clickhouse-server vs source ClickHouse/ClickHouse — one-directional matching + # dropped this window silently when the key came from a compose file. + rep = run_scan([gh("ClickHouse/ClickHouse", [adv("CVE-1", patched="23.10.2.13")])], + images=[("clickhouse-server", "23.4.2.11", "24.12")], + urls=["https://github.com/ClickHouse/ClickHouse"]) + self.assertIn("github-advisories:ClickHouse/ClickHouse", rep["windows"]) + self.assertEqual(rep["cve_count_fixed"], 1) + + def test_matches_when_the_image_name_is_SHORTER_than_the_source(self): + rep = run_scan([gh("redis/redis", [adv("CVE-2", patched="7.4.1")])], + images=[("redis", "7.4", "8.10")], urls=["https://github.com/redis/redis"]) + self.assertEqual(rep["cve_count_fixed"], 1) + + +class TestAdjudicationEvidenceAssembly(unittest.TestCase): + """Pass 2's JUDGEMENT is a model's and not testable; what IS testable is what it gets shown.""" + + def test_selects_indeterminate_and_vendor_only_cases(self): + rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], + [vendor("https://blog.test/sec", ["CVE-VENDOR"])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + todo = A.needs_judgement(rep) + self.assertIn("CVE-TBD", todo) + self.assertIn("CVE-VENDOR", todo) + + def test_does_not_re_ask_about_cases_pass_1_settled(self): + rep = run_scan([gh("redis/redis", [adv("CVE-OK", patched="7.4.1")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + self.assertNotIn("CVE-OK", A.needs_judgement(rep)) + + def test_evidence_bundle_carries_the_window_and_published_fields(self): + rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + with unittest.mock.patch.object(A, "advisory_text", lambda g, s=None: {"status": "skipped"}), \ + unittest.mock.patch.object(A, "release_fix_versions", lambda s, c: []): + ev = A.evidence_bundle(rep, "CVE-TBD") + self.assertEqual(ev["window"], {"from": "7.4", "to": "8.10"}) + self.assertEqual(ev["patched_as_published"], "TBD") + self.assertIn("no fix version", ev["why_undecided"]) + + def test_pass_1_decisions_are_included_for_review(self): + rep = run_scan([gh("redis/redis", [adv("CVE-OK", patched="7.4.1"), + adv("CVE-OLD", patched="6.0.11"), + adv("CVE-TBD", patched="TBD")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + with unittest.mock.patch.object(A, "advisory_text", lambda g, s=None: {"status": "skipped"}), \ + unittest.mock.patch.object(A, "release_fix_versions", lambda s, c: []): + block = A.adjudication_block(rep) + self.assertIn("Pass 1 decisions", block) + self.assertIn("CVE-OK", block) # counted + self.assertIn("CVE-OLD", block) # excluded as outside-window + self.assertIn("CVE-TBD", block) # needs judgement + + def test_truncation_is_announced_never_silent(self): + advs = [adv(f"CVE-2026-{1000+i}", patched="TBD") for i in range(30)] + rep = run_scan([gh("redis/redis", advs)], v_from="7.4", v_to="8.10", + urls=["https://github.com/redis/redis"]) + with unittest.mock.patch.object(A, "advisory_text", lambda g, s=None: {"status": "skipped"}), \ + unittest.mock.patch.object(A, "release_fix_versions", lambda s, c: []), \ + unittest.mock.patch.object(A, "MAX_ADJUDICATE", 5): + block = A.adjudication_block(rep) + self.assertIn("not shown", block) + self.assertIn("do not", block.lower()) + + +class TestMarkdownOutput(unittest.TestCase): + def test_lists_every_window_with_its_method(self): + rep = run_scan([gh("discourse/discourse", [adv("CVE-A", patched="3.5.4")]), + gh("redis/redis", [adv("CVE-B", patched="8.0")])], + v_from="3.5.3", v_to="3.5.4", images=[("redis", "7.4", "8.10")], + urls=["https://github.com/discourse/discourse", "https://github.com/redis/redis"]) + md = A.markdown(rep) + self.assertIn("discourse/discourse: 3.5.3 → 3.5.4", md) + self.assertIn("redis/redis: 7.4 → 8.10", md) + self.assertIn("**CVEs fixed by this upgrade: 2**", md) + + def test_severity_and_fixed_in_are_rendered(self): + rep = run_scan([gh("redis/redis", [adv("CVE-2025-49844", patched="7.4.6; 8.2.2", + severity="critical")])], + v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"]) + md = A.markdown(rep) + self.assertIn("critical", md) + self.assertIn("7.4.6", md) + + +# ── F. live regressions against published historic reports ──────────────────────────────────────── + +class TestHistoricReportNumbers(unittest.TestCase): + """Re-derive counts published in week-2026-08-07. Network + GitHub token; opt in with --live.""" + + REGISTRY = str(HERE / "upstream") + + @classmethod + def setUpClass(cls): + if not os.environ.get("ADVISORY_SCAN_LIVE"): + raise unittest.SkipTest("live tests: re-run with --live") + + def _count(self, recipe, v_from, v_to, images=None): + rep = A.scan(recipe, v_from, v_to, self.REGISTRY, images) + self.assertEqual(rep["sources_failed"], [], f"{recipe}: source failures make the count unsafe") + self.assertTrue(rep["count_known"], f"{recipe}: count came back UNKNOWN") + return rep + + def test_gitea_1_27_0_to_1_27_1_is_2(self): + rep = self._count("gitea", "1.27.0", "1.27.1") + self.assertEqual(rep["cve_count_fixed"], 2) + # Both CVSS-9.8 RCEs — the pair whose omission is why this tool exists. + self.assertEqual(set(rep["fixed_by_this_upgrade"]), {"CVE-2026-59774", "CVE-2026-60004"}) + + def test_discourse_app_only_is_123(self): + rep = self._count("discourse", "3.5.3", "2026.7.1") + self.assertEqual(rep["cve_count_fixed"], 123) + self.assertIn("publish date", rep["classified_by"]["github-advisories:discourse/discourse"]) + + def test_discourse_with_redis_sidecar_is_140(self): + # 123 app + 17 redis. Five redis advisories carry a usable patched_versions; the other + # twelve say "TBD" and are resolved from the release notes that name them. + rep = self._count("discourse", "3.5.3", "2026.7.1", [("redis", "7.4", "8.10")]) + self.assertEqual(rep["cve_count_fixed"], 140) + self.assertEqual(len(rep.get("resolved_by_release_notes") or {}), 12) + self.assertEqual(rep["cve_count_indeterminate"], 0) + # The five redis advisories that a sidecar-blind scan missed, incl. one critical. + for cve in ("CVE-2024-31227", "CVE-2024-31228", "CVE-2024-31449", + "CVE-2025-49844", "CVE-2025-62507"): + self.assertIn(cve, rep["fixed_by_this_upgrade"], f"{cve} missing from discourse+redis") + self.assertEqual(rep["cves"]["CVE-2025-49844"]["severity"], "critical") + + def test_discourse_redis_delta_is_exactly_seventeen(self): + app = self._count("discourse", "3.5.3", "2026.7.1") + both = self._count("discourse", "3.5.3", "2026.7.1", [("redis", "7.4", "8.10")]) + delta = set(both["fixed_by_this_upgrade"]) - set(app["fixed_by_this_upgrade"]) + self.assertEqual(len(delta), 17) + for cve in delta: + self.assertIn("redis", both["cves"][cve]["sources"][0]) + + def test_mailu_finds_the_roundcube_pair_without_an_agent(self): + # Published as 2 on 2026-08-07, but only because an agent read the release notes; the scan + # itself contributed 0. It now reaches 2 deterministically: the CVEs appear only on + # github.com/Mailu/Mailu/releases, and release 2024.06.56 (inside the window) names them. + rep = self._count("mailu", "2024.06.55", "2024.06.57", [("redis", "8.8.0", "8.10.0")]) + self.assertEqual(rep["cve_count_fixed"], 2) + self.assertEqual(set(rep["fixed_by_this_upgrade"]), {"CVE-2026-54432", "CVE-2026-54433"}) + # The redis bump fixes nothing new — every advisory it crosses was fixed at or before 8.6.3. + self.assertEqual(rep["cve_count_indeterminate"], 0) + + def test_keycloak_26_7_0_to_26_7_1_is_12(self): + # Was 7 while only the GHSA feed was consulted. keycloak lists five more CVEs in the 26.7.1 + # release notes' fixed-issues section that it never filed as advisories — the gitea pattern. + rep = self._count("keycloak", "26.7.0", "26.7.1") + self.assertEqual(rep["cve_count_fixed"], 12) + self.assertEqual(len(rep.get("resolved_by_release_notes") or {}), 5) + + +def _main(): + live = "--live" in sys.argv + if live: + sys.argv.remove("--live") + os.environ["ADVISORY_SCAN_LIVE"] = "1" + unittest.main(verbosity=2) + + +if __name__ == "__main__": + _main() diff --git a/scripts/cc-ci/test-resolve-images.py b/scripts/cc-ci/test-resolve-images.py new file mode 100644 index 0000000..d43dd7a --- /dev/null +++ b/scripts/cc-ci/test-resolve-images.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Offline regressions for the weekly image survey's false-current cases.""" + +import importlib.util +import pathlib +import unittest +from unittest import mock + +HERE = pathlib.Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location("resolve_images", HERE / "resolve-images.py") +resolver = importlib.util.module_from_spec(spec) +spec.loader.exec_module(resolver) + + +class TestResolverCoverage(unittest.TestCase): + def test_cryptpad_calver_tag_is_found_independently_of_abra(self): + with mock.patch.object(resolver, "list_tags", return_value=( + ["version-2026.5.1", "version-2026.10.0", "opendesk-2026.08.04"], None)): + row = resolver.resolve("cryptpad/cryptpad:version-2026.5.1") + self.assertTrue(row["upgrade_available"]) + self.assertEqual(row["newest_same_shape"], "version-2026.10.0") + + def test_floating_and_templated_tags_cannot_prove_current(self): + with mock.patch.object(resolver, "list_tags", return_value=(["alpine", "1.2.3"], None)): + floating = resolver.resolve("atmoz/sftp:alpine") + templated = resolver.resolve("ghost:${IMAGE_VERSION}-alpine") + self.assertTrue(floating["status"].startswith("unverifiable:")) + self.assertTrue(templated["status"].startswith("skipped:")) + + def test_truncated_registry_listing_cannot_prove_current(self): + with mock.patch.object(resolver, "list_tags", return_value=(["1.2.3"], None)): + with mock.patch.object(resolver, "_HUB_TRUNCATED", {"library/example"}): + row = resolver.resolve("example:1.2.3") + self.assertTrue(row["status"].startswith("unverifiable:")) + + def test_huge_ghcr_listing_uses_only_published_release_manifests(self): + ref = "ghcr.io/immich-app/immich-machine-learning:v3.3.5" + with mock.patch.object(resolver, "list_tags", return_value=([], "RuntimeError: tag listing truncated")), \ + mock.patch.object(resolver, "github_release_tags", + return_value=["v3.3.6", "v3.3.5"]), \ + mock.patch.object(resolver, "_oci_tag_exists", side_effect=lambda h, r, t: t == "v3.3.5"): + row = resolver.resolve(ref) + self.assertEqual(row["status"], "ok") + self.assertFalse(row["upgrade_available"]) # release exists; image does not yet + self.assertIn("registry-manifest", row["source"]) + with mock.patch.object(resolver, "list_tags", return_value=([], "RuntimeError: tag listing truncated")), \ + mock.patch.object(resolver, "github_release_tags", + return_value=["v3.3.6", "v3.3.5"]), \ + mock.patch.object(resolver, "_oci_tag_exists", return_value=True): + upgraded = resolver.resolve(ref) + self.assertTrue(upgraded["upgrade_available"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/cc-ci/upstream b/scripts/cc-ci/upstream new file mode 120000 index 0000000..3ce1281 --- /dev/null +++ b/scripts/cc-ci/upstream @@ -0,0 +1 @@ +../../cc-ci-plan/upstream \ No newline at end of file diff --git a/scripts/cc-ci/used-recipes.md b/scripts/cc-ci/used-recipes.md new file mode 120000 index 0000000..1b01100 --- /dev/null +++ b/scripts/cc-ci/used-recipes.md @@ -0,0 +1 @@ +../../cc-ci-plan/used-recipes.md \ No newline at end of file From 7d1de8865757c6ddc9fe2adf9a1d5209a73eb5fb Mon Sep 17 00:00:00 2001 From: notplants <@notplants> Date: Mon, 23 Nov 2026 20:11:51 +0000 Subject: [PATCH 2/2] Point Nix at relocated CI scripts and remove legacy plan paths --- AGENTS.md | 3 +- README.md | 11 ++--- archive/README.md | 4 +- cc-ci-plan/README.md | 1 - cc-ci-plan/adversary-verify-pr6.md | 1 - cc-ci-plan/advisory-scan.SPEC.md | 1 - cc-ci-plan/advisory-scan.py | 1 - cc-ci-plan/agent-log.py | 1 - cc-ci-plan/agents.py | 1 - cc-ci-plan/agents.toml | 1 - cc-ci-plan/ai-progress-monitor-prompt.txt | 1 - cc-ci-plan/audit-advisory-scan.py | 1 - cc-ci-plan/audit-sources.py | 1 - cc-ci-plan/brief.md | 1 - .../concurrency-restructure-full-plan.md | 1 - cc-ci-plan/concurrency-restructure-plan.md | 1 - cc-ci-plan/kickoff.md | 1 - cc-ci-plan/launch-assistant.py | 1 - cc-ci-plan/launch-assistant.sh | 1 - cc-ci-plan/launch-opencode.sh | 1 - cc-ci-plan/launch-orchestrator.py | 1 - cc-ci-plan/launch-orchestrator.sh | 1 - cc-ci-plan/launch-report.py | 1 - cc-ci-plan/launch-supervisor.py | 1 - cc-ci-plan/launch-upgrader.py | 1 - cc-ci-plan/launch-upgrader.sh | 1 - cc-ci-plan/launch.py | 1 - cc-ci-plan/launch.sh | 1 - cc-ci-plan/load-env.sh | 1 - cc-ci-plan/msg-loop.sh | 1 - cc-ci-plan/orchestration.md | 1 - cc-ci-plan/orchestrator-opencode-restart.txt | 1 - cc-ci-plan/overnight-run.sh | 1 - .../phase6-phase7-summary-2026-06-01.md | 1 - cc-ci-plan/plan-cc-ci-combined-host.md | 1 - .../plan-ccci-compose-overlay-policy.md | 1 - ...plan-domain-migration-ci-autonomic-zone.md | 1 - cc-ci-plan/plan-ghostpr-debug-fix.md | 1 - .../plan-lasuite-drive-oidc-robustness.md | 1 - cc-ci-plan/plan-lasuite-drive-recipe-pr.md | 1 - cc-ci-plan/plan-mirror-enroll-all-recipes.md | 1 - cc-ci-plan/plan-overnight-run.md | 1 - cc-ci-plan/plan-phase-bsky-fix.md | 1 - .../plan-phase-canon-canonical-sweep.md | 1 - .../plan-phase-cf48-opus-cfold-review.md | 1 - .../plan-phase-cf55-gpt55-cfold-review.md | 1 - cc-ci-plan/plan-phase-cfold-custom-folder.md | 1 - cc-ci-plan/plan-phase-dash-recipe-history.md | 1 - cc-ci-plan/plan-phase-drone-enroll.md | 1 - .../plan-phase-dstamp-discourse-drift.md | 1 - cc-ci-plan/plan-phase-ghost-reeval.md | 1 - cc-ci-plan/plan-phase-gtea-gitea-fulltests.md | 1 - cc-ci-plan/plan-phase-kuma-monitor.md | 1 - cc-ci-plan/plan-phase-lvl5-lint-rung.md | 1 - cc-ci-plan/plan-phase-mailu-backup.md | 1 - .../plan-phase-nixenv-shared-runtime-env.md | 1 - .../plan-phase-prevb-previous-dynamic-base.md | 1 - ...n-phase-pvcheck-post-proxy-verification.md | 1 - cc-ci-plan/plan-phase-pvfix-swarm-proxy.md | 1 - .../plan-phase-pxgate-proxy-healthgate.md | 1 - .../plan-phase-redfix-canon-sweep-failures.md | 1 - .../plan-phase-regall-recipe-regression.md | 1 - .../plan-phase-samever-older-base-fallback.md | 1 - .../plan-phase-settings-ci-server-config.md | 1 - cc-ci-plan/plan-phase-shot-screenshots.md | 1 - cc-ci-plan/plan-phase1b-review-lint.md | 1 - .../plan-phase1c-full-reproducibility.md | 1 - cc-ci-plan/plan-phase1d-generic-test-suite.md | 1 - .../plan-phase1e-harness-corrections.md | 1 - cc-ci-plan/plan-phase2-recipe-tests.md | 1 - cc-ci-plan/plan-phase2b-test-performance.md | 1 - cc-ci-plan/plan-phase2pc-image-cache.md | 1 - .../plan-phase2w-warm-canonical-quick.md | 1 - cc-ci-plan/plan-phase3-results-ux.md | 1 - ...plan-phase4-final-review-polish-cleanup.md | 1 - cc-ci-plan/plan-phase5-verify-upgrade-flow.md | 1 - .../plan-phase6-reconcile-all-mirrors.md | 1 - .../plan-phase7-upgrade-three-recipes.md | 1 - cc-ci-plan/plan-prepull-images.md | 1 - cc-ci-plan/plan-proxy-vip-exhaustion-fix.md | 1 - cc-ci-plan/plan-recipe-report-skill.md | 1 - cc-ci-plan/plan-report-pr-status-column.md | 1 - cc-ci-plan/plan-server-regression-canaries.md | 1 - cc-ci-plan/plan-sso-dep-testing.md | 1 - cc-ci-plan/plan.md | 1 - cc-ci-plan/pr-survey.py | 1 - cc-ci-plan/prompts | 1 - cc-ci-plan/reboot-log.sh | 1 - .../recipe-custom-restructure-full-plan.md | 1 - cc-ci-plan/recipe-report.py | 1 - cc-ci-plan/reconcile-upstream.sh | 1 - cc-ci-plan/resolve-images.py | 1 - cc-ci-plan/systemd/cc-ci-loops.service | 1 - cc-ci-plan/task-consolidate-recipe-prs.md | 1 - cc-ci-plan/test-advisory-scan.py | 1 - cc-ci-plan/test-e2e-testme-acceptance.md | 1 - cc-ci-plan/test-resolve-images.py | 1 - {cc-ci-plan => data/cc-ci}/JOURNAL.md | 0 {cc-ci-plan => data/cc-ci}/REBOOTS.md | 0 {cc-ci-plan => data/cc-ci}/upstream/README.md | 6 +-- .../cc-ci}/upstream/bluesky-pds.md | 0 .../cc-ci}/upstream/cryptpad.md | 0 .../cc-ci}/upstream/custom-html-tiny.md | 0 .../cc-ci}/upstream/custom-html.md | 0 .../cc-ci}/upstream/discourse.md | 0 {cc-ci-plan => data/cc-ci}/upstream/drone.md | 0 {cc-ci-plan => data/cc-ci}/upstream/ghost.md | 0 {cc-ci-plan => data/cc-ci}/upstream/gitea.md | 0 .../cc-ci}/upstream/hedgedoc.md | 0 {cc-ci-plan => data/cc-ci}/upstream/immich.md | 0 .../cc-ci}/upstream/keycloak.md | 0 .../cc-ci}/upstream/lasuite-docs.md | 0 .../cc-ci}/upstream/lasuite-drive.md | 0 .../cc-ci}/upstream/lasuite-meet.md | 0 {cc-ci-plan => data/cc-ci}/upstream/mailu.md | 0 .../cc-ci}/upstream/matrix-synapse.md | 0 .../cc-ci}/upstream/mattermost-lts.md | 0 {cc-ci-plan => data/cc-ci}/upstream/mumble.md | 0 {cc-ci-plan => data/cc-ci}/upstream/n8n.md | 0 .../cc-ci}/upstream/plausible.md | 0 .../cc-ci}/upstream/rustdesk-server.md | 0 .../cc-ci}/upstream/uptime-kuma.md | 0 .../cc-ci}/upstream/wordpress.md | 0 {cc-ci-plan => data/cc-ci}/used-recipes.md | 0 docs/host-provisioning-and-migration.md | 4 +- nix/modules/cc-ci.nix | 49 ++++++------------- scripts/cc-ci/advisory-scan.SPEC.md | 8 +-- scripts/cc-ci/advisory-scan.py | 8 +-- scripts/cc-ci/agents.py | 6 +-- scripts/cc-ci/agents.toml | 6 +-- scripts/cc-ci/audit-advisory-scan.py | 4 +- scripts/cc-ci/audit-sources.py | 6 +-- scripts/cc-ci/launch-assistant.py | 4 +- scripts/cc-ci/launch-report.py | 4 +- scripts/cc-ci/launch-supervisor.py | 6 +-- scripts/cc-ci/launch-upgrader.py | 6 +-- scripts/cc-ci/pr-survey.py | 2 +- scripts/cc-ci/reboot-log.sh | 2 +- scripts/cc-ci/reconcile-upstream.sh | 2 +- scripts/cc-ci/test-advisory-scan.py | 10 ++-- scripts/cc-ci/upstream | 1 - scripts/cc-ci/used-recipes.md | 1 - scripts/recovery/README.md | 2 +- 143 files changed, 64 insertions(+), 185 deletions(-) delete mode 120000 cc-ci-plan/README.md delete mode 120000 cc-ci-plan/adversary-verify-pr6.md delete mode 120000 cc-ci-plan/advisory-scan.SPEC.md delete mode 120000 cc-ci-plan/advisory-scan.py delete mode 120000 cc-ci-plan/agent-log.py delete mode 120000 cc-ci-plan/agents.py delete mode 120000 cc-ci-plan/agents.toml delete mode 120000 cc-ci-plan/ai-progress-monitor-prompt.txt delete mode 120000 cc-ci-plan/audit-advisory-scan.py delete mode 120000 cc-ci-plan/audit-sources.py delete mode 120000 cc-ci-plan/brief.md delete mode 120000 cc-ci-plan/concurrency-restructure-full-plan.md delete mode 120000 cc-ci-plan/concurrency-restructure-plan.md delete mode 120000 cc-ci-plan/kickoff.md delete mode 120000 cc-ci-plan/launch-assistant.py delete mode 120000 cc-ci-plan/launch-assistant.sh delete mode 120000 cc-ci-plan/launch-opencode.sh delete mode 120000 cc-ci-plan/launch-orchestrator.py delete mode 120000 cc-ci-plan/launch-orchestrator.sh delete mode 120000 cc-ci-plan/launch-report.py delete mode 120000 cc-ci-plan/launch-supervisor.py delete mode 120000 cc-ci-plan/launch-upgrader.py delete mode 120000 cc-ci-plan/launch-upgrader.sh delete mode 120000 cc-ci-plan/launch.py delete mode 120000 cc-ci-plan/launch.sh delete mode 120000 cc-ci-plan/load-env.sh delete mode 120000 cc-ci-plan/msg-loop.sh delete mode 120000 cc-ci-plan/orchestration.md delete mode 120000 cc-ci-plan/orchestrator-opencode-restart.txt delete mode 120000 cc-ci-plan/overnight-run.sh delete mode 120000 cc-ci-plan/phase6-phase7-summary-2026-06-01.md delete mode 120000 cc-ci-plan/plan-cc-ci-combined-host.md delete mode 120000 cc-ci-plan/plan-ccci-compose-overlay-policy.md delete mode 120000 cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md delete mode 120000 cc-ci-plan/plan-ghostpr-debug-fix.md delete mode 120000 cc-ci-plan/plan-lasuite-drive-oidc-robustness.md delete mode 120000 cc-ci-plan/plan-lasuite-drive-recipe-pr.md delete mode 120000 cc-ci-plan/plan-mirror-enroll-all-recipes.md delete mode 120000 cc-ci-plan/plan-overnight-run.md delete mode 120000 cc-ci-plan/plan-phase-bsky-fix.md delete mode 120000 cc-ci-plan/plan-phase-canon-canonical-sweep.md delete mode 120000 cc-ci-plan/plan-phase-cf48-opus-cfold-review.md delete mode 120000 cc-ci-plan/plan-phase-cf55-gpt55-cfold-review.md delete mode 120000 cc-ci-plan/plan-phase-cfold-custom-folder.md delete mode 120000 cc-ci-plan/plan-phase-dash-recipe-history.md delete mode 120000 cc-ci-plan/plan-phase-drone-enroll.md delete mode 120000 cc-ci-plan/plan-phase-dstamp-discourse-drift.md delete mode 120000 cc-ci-plan/plan-phase-ghost-reeval.md delete mode 120000 cc-ci-plan/plan-phase-gtea-gitea-fulltests.md delete mode 120000 cc-ci-plan/plan-phase-kuma-monitor.md delete mode 120000 cc-ci-plan/plan-phase-lvl5-lint-rung.md delete mode 120000 cc-ci-plan/plan-phase-mailu-backup.md delete mode 120000 cc-ci-plan/plan-phase-nixenv-shared-runtime-env.md delete mode 120000 cc-ci-plan/plan-phase-prevb-previous-dynamic-base.md delete mode 120000 cc-ci-plan/plan-phase-pvcheck-post-proxy-verification.md delete mode 120000 cc-ci-plan/plan-phase-pvfix-swarm-proxy.md delete mode 120000 cc-ci-plan/plan-phase-pxgate-proxy-healthgate.md delete mode 120000 cc-ci-plan/plan-phase-redfix-canon-sweep-failures.md delete mode 120000 cc-ci-plan/plan-phase-regall-recipe-regression.md delete mode 120000 cc-ci-plan/plan-phase-samever-older-base-fallback.md delete mode 120000 cc-ci-plan/plan-phase-settings-ci-server-config.md delete mode 120000 cc-ci-plan/plan-phase-shot-screenshots.md delete mode 120000 cc-ci-plan/plan-phase1b-review-lint.md delete mode 120000 cc-ci-plan/plan-phase1c-full-reproducibility.md delete mode 120000 cc-ci-plan/plan-phase1d-generic-test-suite.md delete mode 120000 cc-ci-plan/plan-phase1e-harness-corrections.md delete mode 120000 cc-ci-plan/plan-phase2-recipe-tests.md delete mode 120000 cc-ci-plan/plan-phase2b-test-performance.md delete mode 120000 cc-ci-plan/plan-phase2pc-image-cache.md delete mode 120000 cc-ci-plan/plan-phase2w-warm-canonical-quick.md delete mode 120000 cc-ci-plan/plan-phase3-results-ux.md delete mode 120000 cc-ci-plan/plan-phase4-final-review-polish-cleanup.md delete mode 120000 cc-ci-plan/plan-phase5-verify-upgrade-flow.md delete mode 120000 cc-ci-plan/plan-phase6-reconcile-all-mirrors.md delete mode 120000 cc-ci-plan/plan-phase7-upgrade-three-recipes.md delete mode 120000 cc-ci-plan/plan-prepull-images.md delete mode 120000 cc-ci-plan/plan-proxy-vip-exhaustion-fix.md delete mode 120000 cc-ci-plan/plan-recipe-report-skill.md delete mode 120000 cc-ci-plan/plan-report-pr-status-column.md delete mode 120000 cc-ci-plan/plan-server-regression-canaries.md delete mode 120000 cc-ci-plan/plan-sso-dep-testing.md delete mode 120000 cc-ci-plan/plan.md delete mode 120000 cc-ci-plan/pr-survey.py delete mode 120000 cc-ci-plan/prompts delete mode 120000 cc-ci-plan/reboot-log.sh delete mode 120000 cc-ci-plan/recipe-custom-restructure-full-plan.md delete mode 120000 cc-ci-plan/recipe-report.py delete mode 120000 cc-ci-plan/reconcile-upstream.sh delete mode 120000 cc-ci-plan/resolve-images.py delete mode 120000 cc-ci-plan/systemd/cc-ci-loops.service delete mode 120000 cc-ci-plan/task-consolidate-recipe-prs.md delete mode 120000 cc-ci-plan/test-advisory-scan.py delete mode 120000 cc-ci-plan/test-e2e-testme-acceptance.md delete mode 120000 cc-ci-plan/test-resolve-images.py rename {cc-ci-plan => data/cc-ci}/JOURNAL.md (100%) rename {cc-ci-plan => data/cc-ci}/REBOOTS.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/README.md (90%) rename {cc-ci-plan => data/cc-ci}/upstream/bluesky-pds.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/cryptpad.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/custom-html-tiny.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/custom-html.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/discourse.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/drone.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/ghost.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/gitea.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/hedgedoc.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/immich.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/keycloak.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/lasuite-docs.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/lasuite-drive.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/lasuite-meet.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/mailu.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/matrix-synapse.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/mattermost-lts.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/mumble.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/n8n.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/plausible.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/rustdesk-server.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/uptime-kuma.md (100%) rename {cc-ci-plan => data/cc-ci}/upstream/wordpress.md (100%) rename {cc-ci-plan => data/cc-ci}/used-recipes.md (100%) delete mode 120000 scripts/cc-ci/upstream delete mode 120000 scripts/cc-ci/used-recipes.md diff --git a/AGENTS.md b/AGENTS.md index 1f037c5..6a87e55 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,8 +3,7 @@ This repository declares the combined cc-ci NixOS host and runs its operator steering session, weekly recipe upgrader, report, and host updater. The Builder/Adversary phase build is finished. Its plans, prompts, and launch implementation are under -`archive/original-build/`; compatibility links remain at old paths because the -unchanged Nix `cc-ci-loops` service still calls `cc-ci-plan/launch.sh` on boot. +`archive/original-build/`; the legacy Nix `cc-ci-loops` service only records reboots. Do not restart the completed Builder/Adversary loops. Start with `README.md` for current operations and `archive/README.md` for history. diff --git a/README.md b/README.md index 54fbb3f..16377b4 100644 --- a/README.md +++ b/README.md @@ -9,16 +9,13 @@ the [cc-ci repository](https://git.autonomic.zone/recipe-maintainers/cc-ci). |---|---| | Combined host and timers | `flake.nix`, `nix/hosts/cc-ci/`, `nix/modules/` | | Operator session, weekly upgrade and report launchers | `scripts/cc-ci/agents.py`, `scripts/cc-ci/launch-{upgrader,report,supervisor}.py` | -| Recipe inventory, upstream notes, reporting tools | `cc-ci-plan/used-recipes.md`, `cc-ci-plan/upstream/`, `scripts/cc-ci/recipe-report.py` | +| Recipe inventory, upstream notes, reporting tools | `data/cc-ci/used-recipes.md`, `data/cc-ci/upstream/`, `scripts/cc-ci/recipe-report.py` | | Host provisioning and migration | [`docs/host-provisioning-and-migration.md`](docs/host-provisioning-and-migration.md) | | Original Builder/Adversary build | [`archive/original-build/`](archive/original-build/README.md) | -Secrets and runtime state are gitignored. The completed two-loop build and remaining historical plans are -archived. Active executables live under `scripts/cc-ci/`; the old -`cc-ci-plan/` paths remain as compatibility links for unchanged Nix units. +Secrets and runtime state are gitignored. The completed two-loop build and historical plans are archived. Active executables live under `scripts/cc-ci/`; Nix units now call the new script paths directly. No Builder or Adversary session should be running. The Nix -`cc-ci-loops` unit still invokes a compatibility launcher on boot and exits -when it sees the completed phase state. Its Nix behavior is unchanged. +`cc-ci-loops` unit only records the boot ID; it does not launch retired loops. ## Host updates and recovery @@ -48,7 +45,7 @@ when it sees the completed phase state. Its Nix behavior is unchanged. The cc-ci orchestrator on this host is an **opencode agent** (`scripts/cc-ci/agents.toml`: backend `opencode`, model configured in `scripts/cc-ci/agents.toml`), launched on boot by `cc-ci-orchestrator.service` -via the compatibility path `cc-ci-plan/agents.py up orchestrator` into tmux session `cc-ci-orchestrator`, attached to +via `scripts/cc-ci/agents.py up orchestrator` into tmux session `cc-ci-orchestrator`, attached to the shared opencode web server. Steer it from the web UI, **https://oc.ci.commoninternet.net** (basic auth, user `oc`), where the weekly upgrader's and report's sessions show up too. There is no Claude Code on this host: Claude sessions run on the notplants-orchestrator box and diff --git a/archive/README.md b/archive/README.md index 64064fb..b05d529 100644 --- a/archive/README.md +++ b/archive/README.md @@ -1,9 +1,9 @@ # archive/ — how cc-ci and its orchestrator were built and moved, before the combined host -Historical record. Original-build compatibility launch files are linked from `cc-ci-plan/`; the Nix unit reads those paths but the completed loops do not run. It was moved out of the live +Historical record. Original-build launch files live under `original-build/cc-ci-plan/`; the completed loops do not run. It was moved out of the live tree on 2026-09-07 when the CI server and the orchestrator were consolidated onto one Hetzner host (`nixosConfigurations.cc-ci` in `../flake.nix`; deploy guide in `../README.md`; the plan -that did it is `../cc-ci-plan/plan-cc-ci-combined-host.md`). +that did it is `original-build/cc-ci-plan/plan-cc-ci-combined-host.md`). | path | what it was | |---|---| diff --git a/cc-ci-plan/README.md b/cc-ci-plan/README.md deleted file mode 120000 index d3af5e4..0000000 --- a/cc-ci-plan/README.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/README.md \ No newline at end of file diff --git a/cc-ci-plan/adversary-verify-pr6.md b/cc-ci-plan/adversary-verify-pr6.md deleted file mode 120000 index 35acbdc..0000000 --- a/cc-ci-plan/adversary-verify-pr6.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/adversary-verify-pr6.md \ No newline at end of file diff --git a/cc-ci-plan/advisory-scan.SPEC.md b/cc-ci-plan/advisory-scan.SPEC.md deleted file mode 120000 index e5dc1d8..0000000 --- a/cc-ci-plan/advisory-scan.SPEC.md +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/advisory-scan.SPEC.md \ No newline at end of file diff --git a/cc-ci-plan/advisory-scan.py b/cc-ci-plan/advisory-scan.py deleted file mode 120000 index 293b1dd..0000000 --- a/cc-ci-plan/advisory-scan.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/advisory-scan.py \ No newline at end of file diff --git a/cc-ci-plan/agent-log.py b/cc-ci-plan/agent-log.py deleted file mode 120000 index 010601c..0000000 --- a/cc-ci-plan/agent-log.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/agent-log.py \ No newline at end of file diff --git a/cc-ci-plan/agents.py b/cc-ci-plan/agents.py deleted file mode 120000 index d3cb9de..0000000 --- a/cc-ci-plan/agents.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/agents.py \ No newline at end of file diff --git a/cc-ci-plan/agents.toml b/cc-ci-plan/agents.toml deleted file mode 120000 index ae8fd50..0000000 --- a/cc-ci-plan/agents.toml +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/agents.toml \ No newline at end of file diff --git a/cc-ci-plan/ai-progress-monitor-prompt.txt b/cc-ci-plan/ai-progress-monitor-prompt.txt deleted file mode 120000 index d4ea1d1..0000000 --- a/cc-ci-plan/ai-progress-monitor-prompt.txt +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/ai-progress-monitor-prompt.txt \ No newline at end of file diff --git a/cc-ci-plan/audit-advisory-scan.py b/cc-ci-plan/audit-advisory-scan.py deleted file mode 120000 index 4f1a060..0000000 --- a/cc-ci-plan/audit-advisory-scan.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/audit-advisory-scan.py \ No newline at end of file diff --git a/cc-ci-plan/audit-sources.py b/cc-ci-plan/audit-sources.py deleted file mode 120000 index 482336f..0000000 --- a/cc-ci-plan/audit-sources.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/audit-sources.py \ No newline at end of file diff --git a/cc-ci-plan/brief.md b/cc-ci-plan/brief.md deleted file mode 120000 index 4e46322..0000000 --- a/cc-ci-plan/brief.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/brief.md \ No newline at end of file diff --git a/cc-ci-plan/concurrency-restructure-full-plan.md b/cc-ci-plan/concurrency-restructure-full-plan.md deleted file mode 120000 index 505779f..0000000 --- a/cc-ci-plan/concurrency-restructure-full-plan.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/concurrency-restructure-full-plan.md \ No newline at end of file diff --git a/cc-ci-plan/concurrency-restructure-plan.md b/cc-ci-plan/concurrency-restructure-plan.md deleted file mode 120000 index 3f8cd9a..0000000 --- a/cc-ci-plan/concurrency-restructure-plan.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/concurrency-restructure-plan.md \ No newline at end of file diff --git a/cc-ci-plan/kickoff.md b/cc-ci-plan/kickoff.md deleted file mode 120000 index 14d7795..0000000 --- a/cc-ci-plan/kickoff.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/kickoff.md \ No newline at end of file diff --git a/cc-ci-plan/launch-assistant.py b/cc-ci-plan/launch-assistant.py deleted file mode 120000 index 5916988..0000000 --- a/cc-ci-plan/launch-assistant.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/launch-assistant.py \ No newline at end of file diff --git a/cc-ci-plan/launch-assistant.sh b/cc-ci-plan/launch-assistant.sh deleted file mode 120000 index 641d8c6..0000000 --- a/cc-ci-plan/launch-assistant.sh +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/launch-assistant.sh \ No newline at end of file diff --git a/cc-ci-plan/launch-opencode.sh b/cc-ci-plan/launch-opencode.sh deleted file mode 120000 index 9add75e..0000000 --- a/cc-ci-plan/launch-opencode.sh +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/launch-opencode.sh \ No newline at end of file diff --git a/cc-ci-plan/launch-orchestrator.py b/cc-ci-plan/launch-orchestrator.py deleted file mode 120000 index 2ed173b..0000000 --- a/cc-ci-plan/launch-orchestrator.py +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/launch-orchestrator.py \ No newline at end of file diff --git a/cc-ci-plan/launch-orchestrator.sh b/cc-ci-plan/launch-orchestrator.sh deleted file mode 120000 index bf1b923..0000000 --- a/cc-ci-plan/launch-orchestrator.sh +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/launch-orchestrator.sh \ No newline at end of file diff --git a/cc-ci-plan/launch-report.py b/cc-ci-plan/launch-report.py deleted file mode 120000 index 1d89828..0000000 --- a/cc-ci-plan/launch-report.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/launch-report.py \ No newline at end of file diff --git a/cc-ci-plan/launch-supervisor.py b/cc-ci-plan/launch-supervisor.py deleted file mode 120000 index 0630f12..0000000 --- a/cc-ci-plan/launch-supervisor.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/launch-supervisor.py \ No newline at end of file diff --git a/cc-ci-plan/launch-upgrader.py b/cc-ci-plan/launch-upgrader.py deleted file mode 120000 index e1592e2..0000000 --- a/cc-ci-plan/launch-upgrader.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/launch-upgrader.py \ No newline at end of file diff --git a/cc-ci-plan/launch-upgrader.sh b/cc-ci-plan/launch-upgrader.sh deleted file mode 120000 index c3523d9..0000000 --- a/cc-ci-plan/launch-upgrader.sh +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/launch-upgrader.sh \ No newline at end of file diff --git a/cc-ci-plan/launch.py b/cc-ci-plan/launch.py deleted file mode 120000 index c9bda77..0000000 --- a/cc-ci-plan/launch.py +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/launch.py \ No newline at end of file diff --git a/cc-ci-plan/launch.sh b/cc-ci-plan/launch.sh deleted file mode 120000 index 72edfd1..0000000 --- a/cc-ci-plan/launch.sh +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/launch.sh \ No newline at end of file diff --git a/cc-ci-plan/load-env.sh b/cc-ci-plan/load-env.sh deleted file mode 120000 index caaca98..0000000 --- a/cc-ci-plan/load-env.sh +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/load-env.sh \ No newline at end of file diff --git a/cc-ci-plan/msg-loop.sh b/cc-ci-plan/msg-loop.sh deleted file mode 120000 index 9959c76..0000000 --- a/cc-ci-plan/msg-loop.sh +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/msg-loop.sh \ No newline at end of file diff --git a/cc-ci-plan/orchestration.md b/cc-ci-plan/orchestration.md deleted file mode 120000 index 250fd20..0000000 --- a/cc-ci-plan/orchestration.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/orchestration.md \ No newline at end of file diff --git a/cc-ci-plan/orchestrator-opencode-restart.txt b/cc-ci-plan/orchestrator-opencode-restart.txt deleted file mode 120000 index 3ebdff8..0000000 --- a/cc-ci-plan/orchestrator-opencode-restart.txt +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/orchestrator-opencode-restart.txt \ No newline at end of file diff --git a/cc-ci-plan/overnight-run.sh b/cc-ci-plan/overnight-run.sh deleted file mode 120000 index d3d0b24..0000000 --- a/cc-ci-plan/overnight-run.sh +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/overnight-run.sh \ No newline at end of file diff --git a/cc-ci-plan/phase6-phase7-summary-2026-06-01.md b/cc-ci-plan/phase6-phase7-summary-2026-06-01.md deleted file mode 120000 index 710b4b5..0000000 --- a/cc-ci-plan/phase6-phase7-summary-2026-06-01.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/phase6-phase7-summary-2026-06-01.md \ No newline at end of file diff --git a/cc-ci-plan/plan-cc-ci-combined-host.md b/cc-ci-plan/plan-cc-ci-combined-host.md deleted file mode 120000 index 75acd63..0000000 --- a/cc-ci-plan/plan-cc-ci-combined-host.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-cc-ci-combined-host.md \ No newline at end of file diff --git a/cc-ci-plan/plan-ccci-compose-overlay-policy.md b/cc-ci-plan/plan-ccci-compose-overlay-policy.md deleted file mode 120000 index 1ca0141..0000000 --- a/cc-ci-plan/plan-ccci-compose-overlay-policy.md +++ /dev/null @@ -1 +0,0 @@ -../archive/plans/cc-ci-plan/plan-ccci-compose-overlay-policy.md \ No newline at end of file diff --git a/cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md b/cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md deleted file mode 120000 index 0fa3b92..0000000 --- a/cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md +++ /dev/null @@ -1 +0,0 @@ -../archive/plans/cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md \ No newline at end of file diff --git a/cc-ci-plan/plan-ghostpr-debug-fix.md b/cc-ci-plan/plan-ghostpr-debug-fix.md deleted file mode 120000 index e644016..0000000 --- a/cc-ci-plan/plan-ghostpr-debug-fix.md +++ /dev/null @@ -1 +0,0 @@ -../archive/plans/cc-ci-plan/plan-ghostpr-debug-fix.md \ No newline at end of file diff --git a/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md b/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md deleted file mode 120000 index 2f9e458..0000000 --- a/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md +++ /dev/null @@ -1 +0,0 @@ -../archive/plans/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md \ No newline at end of file diff --git a/cc-ci-plan/plan-lasuite-drive-recipe-pr.md b/cc-ci-plan/plan-lasuite-drive-recipe-pr.md deleted file mode 120000 index 307643b..0000000 --- a/cc-ci-plan/plan-lasuite-drive-recipe-pr.md +++ /dev/null @@ -1 +0,0 @@ -../archive/plans/cc-ci-plan/plan-lasuite-drive-recipe-pr.md \ No newline at end of file diff --git a/cc-ci-plan/plan-mirror-enroll-all-recipes.md b/cc-ci-plan/plan-mirror-enroll-all-recipes.md deleted file mode 120000 index b7e8cd8..0000000 --- a/cc-ci-plan/plan-mirror-enroll-all-recipes.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-mirror-enroll-all-recipes.md \ No newline at end of file diff --git a/cc-ci-plan/plan-overnight-run.md b/cc-ci-plan/plan-overnight-run.md deleted file mode 120000 index 62a4f09..0000000 --- a/cc-ci-plan/plan-overnight-run.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-overnight-run.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-bsky-fix.md b/cc-ci-plan/plan-phase-bsky-fix.md deleted file mode 120000 index e17d835..0000000 --- a/cc-ci-plan/plan-phase-bsky-fix.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-bsky-fix.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-canon-canonical-sweep.md b/cc-ci-plan/plan-phase-canon-canonical-sweep.md deleted file mode 120000 index 55befa3..0000000 --- a/cc-ci-plan/plan-phase-canon-canonical-sweep.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-canon-canonical-sweep.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-cf48-opus-cfold-review.md b/cc-ci-plan/plan-phase-cf48-opus-cfold-review.md deleted file mode 120000 index b8ad082..0000000 --- a/cc-ci-plan/plan-phase-cf48-opus-cfold-review.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-cf48-opus-cfold-review.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-cf55-gpt55-cfold-review.md b/cc-ci-plan/plan-phase-cf55-gpt55-cfold-review.md deleted file mode 120000 index 4691c01..0000000 --- a/cc-ci-plan/plan-phase-cf55-gpt55-cfold-review.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-cf55-gpt55-cfold-review.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-cfold-custom-folder.md b/cc-ci-plan/plan-phase-cfold-custom-folder.md deleted file mode 120000 index 7d211ef..0000000 --- a/cc-ci-plan/plan-phase-cfold-custom-folder.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-cfold-custom-folder.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-dash-recipe-history.md b/cc-ci-plan/plan-phase-dash-recipe-history.md deleted file mode 120000 index 30db515..0000000 --- a/cc-ci-plan/plan-phase-dash-recipe-history.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-dash-recipe-history.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-drone-enroll.md b/cc-ci-plan/plan-phase-drone-enroll.md deleted file mode 120000 index c0b0413..0000000 --- a/cc-ci-plan/plan-phase-drone-enroll.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-drone-enroll.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-dstamp-discourse-drift.md b/cc-ci-plan/plan-phase-dstamp-discourse-drift.md deleted file mode 120000 index d2040aa..0000000 --- a/cc-ci-plan/plan-phase-dstamp-discourse-drift.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-dstamp-discourse-drift.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-ghost-reeval.md b/cc-ci-plan/plan-phase-ghost-reeval.md deleted file mode 120000 index 7415dca..0000000 --- a/cc-ci-plan/plan-phase-ghost-reeval.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-ghost-reeval.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-gtea-gitea-fulltests.md b/cc-ci-plan/plan-phase-gtea-gitea-fulltests.md deleted file mode 120000 index 0b23c81..0000000 --- a/cc-ci-plan/plan-phase-gtea-gitea-fulltests.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-gtea-gitea-fulltests.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-kuma-monitor.md b/cc-ci-plan/plan-phase-kuma-monitor.md deleted file mode 120000 index 2192730..0000000 --- a/cc-ci-plan/plan-phase-kuma-monitor.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-kuma-monitor.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-lvl5-lint-rung.md b/cc-ci-plan/plan-phase-lvl5-lint-rung.md deleted file mode 120000 index 59574bf..0000000 --- a/cc-ci-plan/plan-phase-lvl5-lint-rung.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-lvl5-lint-rung.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-mailu-backup.md b/cc-ci-plan/plan-phase-mailu-backup.md deleted file mode 120000 index 0ee246c..0000000 --- a/cc-ci-plan/plan-phase-mailu-backup.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-mailu-backup.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-nixenv-shared-runtime-env.md b/cc-ci-plan/plan-phase-nixenv-shared-runtime-env.md deleted file mode 120000 index 12fee75..0000000 --- a/cc-ci-plan/plan-phase-nixenv-shared-runtime-env.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-nixenv-shared-runtime-env.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-prevb-previous-dynamic-base.md b/cc-ci-plan/plan-phase-prevb-previous-dynamic-base.md deleted file mode 120000 index 3b5b767..0000000 --- a/cc-ci-plan/plan-phase-prevb-previous-dynamic-base.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-prevb-previous-dynamic-base.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-pvcheck-post-proxy-verification.md b/cc-ci-plan/plan-phase-pvcheck-post-proxy-verification.md deleted file mode 120000 index 9d91722..0000000 --- a/cc-ci-plan/plan-phase-pvcheck-post-proxy-verification.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-pvcheck-post-proxy-verification.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-pvfix-swarm-proxy.md b/cc-ci-plan/plan-phase-pvfix-swarm-proxy.md deleted file mode 120000 index 0a4f14a..0000000 --- a/cc-ci-plan/plan-phase-pvfix-swarm-proxy.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-pvfix-swarm-proxy.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-pxgate-proxy-healthgate.md b/cc-ci-plan/plan-phase-pxgate-proxy-healthgate.md deleted file mode 120000 index a7d694e..0000000 --- a/cc-ci-plan/plan-phase-pxgate-proxy-healthgate.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-pxgate-proxy-healthgate.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-redfix-canon-sweep-failures.md b/cc-ci-plan/plan-phase-redfix-canon-sweep-failures.md deleted file mode 120000 index 7e260df..0000000 --- a/cc-ci-plan/plan-phase-redfix-canon-sweep-failures.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-redfix-canon-sweep-failures.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-regall-recipe-regression.md b/cc-ci-plan/plan-phase-regall-recipe-regression.md deleted file mode 120000 index ab530c2..0000000 --- a/cc-ci-plan/plan-phase-regall-recipe-regression.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-regall-recipe-regression.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-samever-older-base-fallback.md b/cc-ci-plan/plan-phase-samever-older-base-fallback.md deleted file mode 120000 index a2f6159..0000000 --- a/cc-ci-plan/plan-phase-samever-older-base-fallback.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-samever-older-base-fallback.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-settings-ci-server-config.md b/cc-ci-plan/plan-phase-settings-ci-server-config.md deleted file mode 120000 index 4a32b35..0000000 --- a/cc-ci-plan/plan-phase-settings-ci-server-config.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-settings-ci-server-config.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase-shot-screenshots.md b/cc-ci-plan/plan-phase-shot-screenshots.md deleted file mode 120000 index c6fd7d3..0000000 --- a/cc-ci-plan/plan-phase-shot-screenshots.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase-shot-screenshots.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase1b-review-lint.md b/cc-ci-plan/plan-phase1b-review-lint.md deleted file mode 120000 index 5b83044..0000000 --- a/cc-ci-plan/plan-phase1b-review-lint.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase1b-review-lint.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase1c-full-reproducibility.md b/cc-ci-plan/plan-phase1c-full-reproducibility.md deleted file mode 120000 index 00e169b..0000000 --- a/cc-ci-plan/plan-phase1c-full-reproducibility.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase1c-full-reproducibility.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase1d-generic-test-suite.md b/cc-ci-plan/plan-phase1d-generic-test-suite.md deleted file mode 120000 index 4cd3b9b..0000000 --- a/cc-ci-plan/plan-phase1d-generic-test-suite.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase1d-generic-test-suite.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase1e-harness-corrections.md b/cc-ci-plan/plan-phase1e-harness-corrections.md deleted file mode 120000 index c62251e..0000000 --- a/cc-ci-plan/plan-phase1e-harness-corrections.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase1e-harness-corrections.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase2-recipe-tests.md b/cc-ci-plan/plan-phase2-recipe-tests.md deleted file mode 120000 index 401a1c6..0000000 --- a/cc-ci-plan/plan-phase2-recipe-tests.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase2-recipe-tests.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase2b-test-performance.md b/cc-ci-plan/plan-phase2b-test-performance.md deleted file mode 120000 index 893a889..0000000 --- a/cc-ci-plan/plan-phase2b-test-performance.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase2b-test-performance.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase2pc-image-cache.md b/cc-ci-plan/plan-phase2pc-image-cache.md deleted file mode 120000 index 1241e0e..0000000 --- a/cc-ci-plan/plan-phase2pc-image-cache.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase2pc-image-cache.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase2w-warm-canonical-quick.md b/cc-ci-plan/plan-phase2w-warm-canonical-quick.md deleted file mode 120000 index e36dc26..0000000 --- a/cc-ci-plan/plan-phase2w-warm-canonical-quick.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase2w-warm-canonical-quick.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase3-results-ux.md b/cc-ci-plan/plan-phase3-results-ux.md deleted file mode 120000 index 89d8df0..0000000 --- a/cc-ci-plan/plan-phase3-results-ux.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase3-results-ux.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase4-final-review-polish-cleanup.md b/cc-ci-plan/plan-phase4-final-review-polish-cleanup.md deleted file mode 120000 index f721645..0000000 --- a/cc-ci-plan/plan-phase4-final-review-polish-cleanup.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase4-final-review-polish-cleanup.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase5-verify-upgrade-flow.md b/cc-ci-plan/plan-phase5-verify-upgrade-flow.md deleted file mode 120000 index 98c6118..0000000 --- a/cc-ci-plan/plan-phase5-verify-upgrade-flow.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase5-verify-upgrade-flow.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase6-reconcile-all-mirrors.md b/cc-ci-plan/plan-phase6-reconcile-all-mirrors.md deleted file mode 120000 index 6fb5f6f..0000000 --- a/cc-ci-plan/plan-phase6-reconcile-all-mirrors.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase6-reconcile-all-mirrors.md \ No newline at end of file diff --git a/cc-ci-plan/plan-phase7-upgrade-three-recipes.md b/cc-ci-plan/plan-phase7-upgrade-three-recipes.md deleted file mode 120000 index 5c32afb..0000000 --- a/cc-ci-plan/plan-phase7-upgrade-three-recipes.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-phase7-upgrade-three-recipes.md \ No newline at end of file diff --git a/cc-ci-plan/plan-prepull-images.md b/cc-ci-plan/plan-prepull-images.md deleted file mode 120000 index 7d8b6ee..0000000 --- a/cc-ci-plan/plan-prepull-images.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-prepull-images.md \ No newline at end of file diff --git a/cc-ci-plan/plan-proxy-vip-exhaustion-fix.md b/cc-ci-plan/plan-proxy-vip-exhaustion-fix.md deleted file mode 120000 index dfbc632..0000000 --- a/cc-ci-plan/plan-proxy-vip-exhaustion-fix.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-proxy-vip-exhaustion-fix.md \ No newline at end of file diff --git a/cc-ci-plan/plan-recipe-report-skill.md b/cc-ci-plan/plan-recipe-report-skill.md deleted file mode 120000 index 56359c5..0000000 --- a/cc-ci-plan/plan-recipe-report-skill.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-recipe-report-skill.md \ No newline at end of file diff --git a/cc-ci-plan/plan-report-pr-status-column.md b/cc-ci-plan/plan-report-pr-status-column.md deleted file mode 120000 index 962c5b0..0000000 --- a/cc-ci-plan/plan-report-pr-status-column.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-report-pr-status-column.md \ No newline at end of file diff --git a/cc-ci-plan/plan-server-regression-canaries.md b/cc-ci-plan/plan-server-regression-canaries.md deleted file mode 120000 index b191b8d..0000000 --- a/cc-ci-plan/plan-server-regression-canaries.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan-server-regression-canaries.md \ No newline at end of file diff --git a/cc-ci-plan/plan-sso-dep-testing.md b/cc-ci-plan/plan-sso-dep-testing.md deleted file mode 120000 index b97190a..0000000 --- a/cc-ci-plan/plan-sso-dep-testing.md +++ /dev/null @@ -1 +0,0 @@ -../archive/plans/cc-ci-plan/plan-sso-dep-testing.md \ No newline at end of file diff --git a/cc-ci-plan/plan.md b/cc-ci-plan/plan.md deleted file mode 120000 index 537e7c9..0000000 --- a/cc-ci-plan/plan.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/plan.md \ No newline at end of file diff --git a/cc-ci-plan/pr-survey.py b/cc-ci-plan/pr-survey.py deleted file mode 120000 index e338726..0000000 --- a/cc-ci-plan/pr-survey.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/pr-survey.py \ No newline at end of file diff --git a/cc-ci-plan/prompts b/cc-ci-plan/prompts deleted file mode 120000 index b8aad19..0000000 --- a/cc-ci-plan/prompts +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/prompts \ No newline at end of file diff --git a/cc-ci-plan/reboot-log.sh b/cc-ci-plan/reboot-log.sh deleted file mode 120000 index babc589..0000000 --- a/cc-ci-plan/reboot-log.sh +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/reboot-log.sh \ No newline at end of file diff --git a/cc-ci-plan/recipe-custom-restructure-full-plan.md b/cc-ci-plan/recipe-custom-restructure-full-plan.md deleted file mode 120000 index 11aba61..0000000 --- a/cc-ci-plan/recipe-custom-restructure-full-plan.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/recipe-custom-restructure-full-plan.md \ No newline at end of file diff --git a/cc-ci-plan/recipe-report.py b/cc-ci-plan/recipe-report.py deleted file mode 120000 index 5cc09c8..0000000 --- a/cc-ci-plan/recipe-report.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/recipe-report.py \ No newline at end of file diff --git a/cc-ci-plan/reconcile-upstream.sh b/cc-ci-plan/reconcile-upstream.sh deleted file mode 120000 index 810e5c9..0000000 --- a/cc-ci-plan/reconcile-upstream.sh +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/reconcile-upstream.sh \ No newline at end of file diff --git a/cc-ci-plan/resolve-images.py b/cc-ci-plan/resolve-images.py deleted file mode 120000 index 63abdc1..0000000 --- a/cc-ci-plan/resolve-images.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/resolve-images.py \ No newline at end of file diff --git a/cc-ci-plan/systemd/cc-ci-loops.service b/cc-ci-plan/systemd/cc-ci-loops.service deleted file mode 120000 index 89f383c..0000000 --- a/cc-ci-plan/systemd/cc-ci-loops.service +++ /dev/null @@ -1 +0,0 @@ -../../archive/original-build/cc-ci-plan/systemd/cc-ci-loops.service \ No newline at end of file diff --git a/cc-ci-plan/task-consolidate-recipe-prs.md b/cc-ci-plan/task-consolidate-recipe-prs.md deleted file mode 120000 index e410fdf..0000000 --- a/cc-ci-plan/task-consolidate-recipe-prs.md +++ /dev/null @@ -1 +0,0 @@ -../archive/plans/cc-ci-plan/task-consolidate-recipe-prs.md \ No newline at end of file diff --git a/cc-ci-plan/test-advisory-scan.py b/cc-ci-plan/test-advisory-scan.py deleted file mode 120000 index 5bfd0db..0000000 --- a/cc-ci-plan/test-advisory-scan.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/test-advisory-scan.py \ No newline at end of file diff --git a/cc-ci-plan/test-e2e-testme-acceptance.md b/cc-ci-plan/test-e2e-testme-acceptance.md deleted file mode 120000 index 8ab49c9..0000000 --- a/cc-ci-plan/test-e2e-testme-acceptance.md +++ /dev/null @@ -1 +0,0 @@ -../archive/original-build/cc-ci-plan/test-e2e-testme-acceptance.md \ No newline at end of file diff --git a/cc-ci-plan/test-resolve-images.py b/cc-ci-plan/test-resolve-images.py deleted file mode 120000 index de69d88..0000000 --- a/cc-ci-plan/test-resolve-images.py +++ /dev/null @@ -1 +0,0 @@ -../scripts/cc-ci/test-resolve-images.py \ No newline at end of file diff --git a/cc-ci-plan/JOURNAL.md b/data/cc-ci/JOURNAL.md similarity index 100% rename from cc-ci-plan/JOURNAL.md rename to data/cc-ci/JOURNAL.md diff --git a/cc-ci-plan/REBOOTS.md b/data/cc-ci/REBOOTS.md similarity index 100% rename from cc-ci-plan/REBOOTS.md rename to data/cc-ci/REBOOTS.md diff --git a/cc-ci-plan/upstream/README.md b/data/cc-ci/upstream/README.md similarity index 90% rename from cc-ci-plan/upstream/README.md rename to data/cc-ci/upstream/README.md index 2e08698..3e6ac73 100644 --- a/cc-ci-plan/upstream/README.md +++ b/data/cc-ci/upstream/README.md @@ -2,15 +2,15 @@ Per-recipe maps of **where each image's release notes / changelog live**. This is the cc-ci analog of recipe-maintainer's `recipe-info//upstream.md`: the `/recipe-upgrade` skill reads -`cc-ci-plan/upstream/.md` so it doesn't have to rediscover the upstream source for every image +`data/cc-ci/upstream/.md` so it doesn't have to rediscover the upstream source for every image on every weekly run — discover once, persist, reuse. ## How `/recipe-upgrade` uses it (step 1) -1. Read `cc-ci-plan/upstream/.md`. +1. Read `data/cc-ci/upstream/.md`. 2. If it's **missing**, or an image in the recipe's `compose.yml` **isn't covered** (new/renamed service), discover the upstream project + releases page for each uncovered image (WebSearch the image → its GitHub/source repo → its releases/changelog page), then **write/update** this file and - commit it (`git -C /srv/cc-ci-orch add cc-ci-plan/upstream/.md && commit && push`). + commit it (`git -C /srv/cc-ci-orch add data/cc-ci/upstream/.md && commit && push`). 3. Fetch the release notes **from these URLs** between the current → target version of each service. ## Format (one file per recipe) diff --git a/cc-ci-plan/upstream/bluesky-pds.md b/data/cc-ci/upstream/bluesky-pds.md similarity index 100% rename from cc-ci-plan/upstream/bluesky-pds.md rename to data/cc-ci/upstream/bluesky-pds.md diff --git a/cc-ci-plan/upstream/cryptpad.md b/data/cc-ci/upstream/cryptpad.md similarity index 100% rename from cc-ci-plan/upstream/cryptpad.md rename to data/cc-ci/upstream/cryptpad.md diff --git a/cc-ci-plan/upstream/custom-html-tiny.md b/data/cc-ci/upstream/custom-html-tiny.md similarity index 100% rename from cc-ci-plan/upstream/custom-html-tiny.md rename to data/cc-ci/upstream/custom-html-tiny.md diff --git a/cc-ci-plan/upstream/custom-html.md b/data/cc-ci/upstream/custom-html.md similarity index 100% rename from cc-ci-plan/upstream/custom-html.md rename to data/cc-ci/upstream/custom-html.md diff --git a/cc-ci-plan/upstream/discourse.md b/data/cc-ci/upstream/discourse.md similarity index 100% rename from cc-ci-plan/upstream/discourse.md rename to data/cc-ci/upstream/discourse.md diff --git a/cc-ci-plan/upstream/drone.md b/data/cc-ci/upstream/drone.md similarity index 100% rename from cc-ci-plan/upstream/drone.md rename to data/cc-ci/upstream/drone.md diff --git a/cc-ci-plan/upstream/ghost.md b/data/cc-ci/upstream/ghost.md similarity index 100% rename from cc-ci-plan/upstream/ghost.md rename to data/cc-ci/upstream/ghost.md diff --git a/cc-ci-plan/upstream/gitea.md b/data/cc-ci/upstream/gitea.md similarity index 100% rename from cc-ci-plan/upstream/gitea.md rename to data/cc-ci/upstream/gitea.md diff --git a/cc-ci-plan/upstream/hedgedoc.md b/data/cc-ci/upstream/hedgedoc.md similarity index 100% rename from cc-ci-plan/upstream/hedgedoc.md rename to data/cc-ci/upstream/hedgedoc.md diff --git a/cc-ci-plan/upstream/immich.md b/data/cc-ci/upstream/immich.md similarity index 100% rename from cc-ci-plan/upstream/immich.md rename to data/cc-ci/upstream/immich.md diff --git a/cc-ci-plan/upstream/keycloak.md b/data/cc-ci/upstream/keycloak.md similarity index 100% rename from cc-ci-plan/upstream/keycloak.md rename to data/cc-ci/upstream/keycloak.md diff --git a/cc-ci-plan/upstream/lasuite-docs.md b/data/cc-ci/upstream/lasuite-docs.md similarity index 100% rename from cc-ci-plan/upstream/lasuite-docs.md rename to data/cc-ci/upstream/lasuite-docs.md diff --git a/cc-ci-plan/upstream/lasuite-drive.md b/data/cc-ci/upstream/lasuite-drive.md similarity index 100% rename from cc-ci-plan/upstream/lasuite-drive.md rename to data/cc-ci/upstream/lasuite-drive.md diff --git a/cc-ci-plan/upstream/lasuite-meet.md b/data/cc-ci/upstream/lasuite-meet.md similarity index 100% rename from cc-ci-plan/upstream/lasuite-meet.md rename to data/cc-ci/upstream/lasuite-meet.md diff --git a/cc-ci-plan/upstream/mailu.md b/data/cc-ci/upstream/mailu.md similarity index 100% rename from cc-ci-plan/upstream/mailu.md rename to data/cc-ci/upstream/mailu.md diff --git a/cc-ci-plan/upstream/matrix-synapse.md b/data/cc-ci/upstream/matrix-synapse.md similarity index 100% rename from cc-ci-plan/upstream/matrix-synapse.md rename to data/cc-ci/upstream/matrix-synapse.md diff --git a/cc-ci-plan/upstream/mattermost-lts.md b/data/cc-ci/upstream/mattermost-lts.md similarity index 100% rename from cc-ci-plan/upstream/mattermost-lts.md rename to data/cc-ci/upstream/mattermost-lts.md diff --git a/cc-ci-plan/upstream/mumble.md b/data/cc-ci/upstream/mumble.md similarity index 100% rename from cc-ci-plan/upstream/mumble.md rename to data/cc-ci/upstream/mumble.md diff --git a/cc-ci-plan/upstream/n8n.md b/data/cc-ci/upstream/n8n.md similarity index 100% rename from cc-ci-plan/upstream/n8n.md rename to data/cc-ci/upstream/n8n.md diff --git a/cc-ci-plan/upstream/plausible.md b/data/cc-ci/upstream/plausible.md similarity index 100% rename from cc-ci-plan/upstream/plausible.md rename to data/cc-ci/upstream/plausible.md diff --git a/cc-ci-plan/upstream/rustdesk-server.md b/data/cc-ci/upstream/rustdesk-server.md similarity index 100% rename from cc-ci-plan/upstream/rustdesk-server.md rename to data/cc-ci/upstream/rustdesk-server.md diff --git a/cc-ci-plan/upstream/uptime-kuma.md b/data/cc-ci/upstream/uptime-kuma.md similarity index 100% rename from cc-ci-plan/upstream/uptime-kuma.md rename to data/cc-ci/upstream/uptime-kuma.md diff --git a/cc-ci-plan/upstream/wordpress.md b/data/cc-ci/upstream/wordpress.md similarity index 100% rename from cc-ci-plan/upstream/wordpress.md rename to data/cc-ci/upstream/wordpress.md diff --git a/cc-ci-plan/used-recipes.md b/data/cc-ci/used-recipes.md similarity index 100% rename from cc-ci-plan/used-recipes.md rename to data/cc-ci/used-recipes.md diff --git a/docs/host-provisioning-and-migration.md b/docs/host-provisioning-and-migration.md index a412607..0499bdd 100644 --- a/docs/host-provisioning-and-migration.md +++ b/docs/host-provisioning-and-migration.md @@ -299,7 +299,7 @@ stopped on the new host while its directory is copied: | `/var/lib/ci-certs` | the copy traefik is handed | then `systemctl restart cc-ci-acme-traefik-handoff` | | `/root/.abra` | abra's per-app env files for the deployed stacks | | | Drone data volume `/var/lib/docker/volumes/drone_ci_commoninternet_net_data` | Drone's DB: the Gitea OAuth grant, repo activation, build history | `docker service scale drone_ci_commoninternet_net_app=0` on the new host, copy, scale back to 1. Otherwise run `scripts/bootstrap-drone-oauth.sh` (cc-ci repo) with the bot password and re-activate repos | -| `/srv/cc-ci-orch/.cc-ci-logs`, `/srv/cc-ci-orch/cc-ci-plan/upstream/`, `cc-ci-plan/REBOOTS.md`, `cc-ci-plan/JOURNAL.md` | orchestrator history, the upgrader's per-recipe release-note registry | as loops; do the final sync after stopping the orchestrator on the old host | +| `/srv/cc-ci-orch/.cc-ci-logs`, `/srv/cc-ci-orch/data/cc-ci/upstream/`, `data/cc-ci/REBOOTS.md`, `data/cc-ci/JOURNAL.md` | orchestrator history, the upgrader's per-recipe release-note registry | as loops; do the final sync after stopping the orchestrator on the old host | ## 7. Cutover and verification @@ -319,7 +319,7 @@ stopped on the new host while its directory is copied: `systemctl unmask cc-ci-upgrade-all.timer cc-ci-upgrade-supervisor.timer && systemctl start` both. 4. End to end: post `!testme` on an open recipe PR and watch it turn green on the new Drone; open `https://ci.commoninternet.net` and `https://report.ci.commoninternet.net`. -5. The orchestrator: as loops on the new host `cd /srv/cc-ci-orch && python3 cc-ci-plan/agents.py up orchestrator` +5. The orchestrator: as loops on the new host `cd /srv/cc-ci-orch && python3 scripts/cc-ci/agents.py up orchestrator` (or just `systemctl restart cc-ci-orchestrator`), attach with `sudo -iu loops tmux attach -t cc-ci-orchestrator` or use the opencode web UI. Check its status and the host journal after startup. 6. Keep the old host as a cold standby for a week, then delete it (and its tailnet node — the diff --git a/nix/modules/cc-ci.nix b/nix/modules/cc-ci.nix index 91355e0..03e1d2c 100644 --- a/nix/modules/cc-ci.nix +++ b/nix/modules/cc-ci.nix @@ -1,6 +1,5 @@ # cc-ci.nix — the cc-ci operator session and weekly-upgrade/hourly-supervisor timers. -# The Builder/Adversary loop unit below is a compatibility path for the completed -# original build. Its plans and launcher live under archive/original-build/. +# The Builder/Adversary build is archived; its old unit name only records reboots. # # Exported from this repo's flake as `nixosModules.cc-ci-orchestrator` (and, for the host that # used to import it under the old name, `nixosModules.cc-ci`). Split out of the shared agent @@ -14,47 +13,27 @@ # those are host concerns, provided by nix/modules/orchestrator-host.nix, not by this module. { config, pkgs, lib, ... }: { - # Legacy Builder/Adversary boot unit. The phase build is complete; launch.sh - # checks its DONE state and exits without starting those sessions. Keep this - # declaration and path unchanged while the compatibility unit remains enabled. + # Keep the historical unit name for its boot-id-gated reboot record. + # The Builder/Adversary phase loops are complete and never launched. systemd.services.cc-ci-loops = { - description = "cc-ci Builder/Adversary loops + watchdog (launch.sh start)"; - wantedBy = [ "multi-user.target" ]; # enabled after workspace staged (Hetzner cutover) - after = [ "network-online.target" "opencode-install.service" ]; + description = "cc-ci reboot record (legacy unit name)"; + wantedBy = [ "multi-user.target" ]; + after = [ "network-online.target" ]; wants = [ "network-online.target" ]; serviceConfig = { - # KillMode=process: this unit only LAUNCHES the tmux server, it does not own it. With the - # default (control-group) systemd kills every leftover process in the cgroup when the unit - # stops — and since one tmux server hosts every agent session on this host, a rebuild that - # merely touched this unit wiped all of them (operator 2026-08-01). Only the (already - # exited) main process is killed now; `systemctl stop` therefore does NOT tear down agents. - KillMode = "process"; Type = "oneshot"; RemainAfterExit = true; User = "loops"; Group = "users"; - WorkingDirectory = "/srv/cc-ci/cc-ci"; - # Append one line to REBOOTS.md per genuine reboot (boot_id-gated; not on manual restart). - ExecStartPre = "${pkgs.bash}/bin/bash /srv/cc-ci/cc-ci-plan/reboot-log.sh"; + WorkingDirectory = "/srv/cc-ci-orch"; + ExecStart = "${pkgs.bash}/bin/bash /srv/cc-ci/scripts/cc-ci/reboot-log.sh"; }; - # The loops backend is persisted in .cc-ci-logs/.loop-backend (opencode on the cc-ci host — - # no Claude there since 2026-09-07). The archived build phases are DONE; - # on boot the compatibility launcher only confirms completion and exits. - environment = { RESUME_PHASE = "1"; HOME = "/home/loops"; }; - path = [ pkgs.bash pkgs.tmux pkgs.git pkgs.python3 pkgs.openssh pkgs.nettools ]; - script = '' - # Put the standalone opencode binary on PATH. On a cold boot this is the env the tmux - # server (and thus every agent session) inherits. - export PATH="/home/loops/.local/bin:$PATH" - [ -x /srv/cc-ci/cc-ci-plan/launch.sh ] && /srv/cc-ci/cc-ci-plan/launch.sh start || \ - echo "workspace not staged yet — skipping loop start" - ''; }; # cc-ci-orchestrator supervisor — the operator's steering session. Same shape as # lichen-orchestrator / project-orchestrator above: this unit only LAUNCHES the orchestrator's - # tmux session via the agent-orchestrator harness (cc-ci-plan/agents.py); it does not own the + # tmux session via the agent-orchestrator harness (scripts/cc-ci/agents.py); it does not own the # session or the tmux server. This is the current operator steering agent, # separate from the retired Builder/Adversary loops. Its backend/model are - # declared in cc-ci-plan/agents.toml; it attaches to the shared + # declared in scripts/cc-ci/agents.toml; it attaches to the shared # opencode web server — opencode-web.service in orchestrator-host.nix — and steered from its # web UI; no Claude on this host, operator 2026-09-07). The harness watchdog (started by # `agents.py up`) keeps it alive: heal-only (no stall reboots — a persistent supervisor must not @@ -78,8 +57,8 @@ export PATH="/home/loops/.local/bin:$PATH" proj="/srv/cc-ci-orch" echo "$(cat /proc/sys/kernel/random/boot_id) boot $(date -u +%FT%TZ) — cc-ci-orchestrator up" \ - >> "$proj/cc-ci-plan/.ao-boot.log" 2>/dev/null || true - cd "$proj" && python3 cc-ci-plan/agents.py up orchestrator || echo "cc-ci orchestrator agents.py up failed" + >> "$proj/scripts/cc-ci/.ao-boot.log" 2>/dev/null || true + cd "$proj" && python3 scripts/cc-ci/agents.py up orchestrator || echo "cc-ci orchestrator agents.py up failed" ''; }; @@ -109,7 +88,7 @@ path = [ pkgs.bash pkgs.tmux pkgs.git pkgs.python3 pkgs.openssh pkgs.nettools ]; script = '' export PATH="/home/loops/.local/bin:$PATH" - python3 /srv/cc-ci/cc-ci-plan/launch-upgrader.py start >> /srv/cc-ci/.cc-ci-logs/upgrader-cron.log 2>&1 + python3 /srv/cc-ci/scripts/cc-ci/launch-upgrader.py start >> /srv/cc-ci/.cc-ci-logs/upgrader-cron.log 2>&1 ''; }; @@ -146,7 +125,7 @@ path = [ pkgs.bash pkgs.tmux pkgs.git pkgs.python3 pkgs.openssh pkgs.nettools ]; script = '' export PATH="/home/loops/.local/bin:$PATH" - python3 /srv/cc-ci/cc-ci-plan/launch-supervisor.py check >> /srv/cc-ci/.cc-ci-logs/supervisor-cron.log 2>&1 + python3 /srv/cc-ci/scripts/cc-ci/launch-supervisor.py check >> /srv/cc-ci/.cc-ci-logs/supervisor-cron.log 2>&1 ''; }; diff --git a/scripts/cc-ci/advisory-scan.SPEC.md b/scripts/cc-ci/advisory-scan.SPEC.md index 577a37a..98d1bbc 100644 --- a/scripts/cc-ci/advisory-scan.SPEC.md +++ b/scripts/cc-ci/advisory-scan.SPEC.md @@ -1,8 +1,8 @@ # Advisory scan — specification -What `cc-ci-plan/advisory-scan.py` does, step by step, and why each step exists. This documents the +What `scripts/cc-ci/advisory-scan.py` does, step by step, and why each step exists. This documents the implementation as it stands (2026-08-11); if you change the code, change this file in the same commit. -`cc-ci-plan/test-advisory-scan.py` is the executable half of this spec — every rule below is asserted +`scripts/cc-ci/test-advisory-scan.py` is the executable half of this spec — every rule below is asserted there. **Role.** A per-recipe CVE detector run as a **pre-step of `/recipe-upgrade`** (step 2a). It is @@ -45,7 +45,7 @@ advisory-scan.py --compose-to [--compose-from ] # windows | Input | Meaning | |---|---| -| `` | Recipe name; selects `cc-ci-plan/upstream/.md` (the per-recipe URL registry) | +| `` | Recipe name; selects `data/cc-ci/upstream/.md` (the per-recipe URL registry) | | `--from` / `--to` | The **primary app image's** version window being upgraded across | | `--image NAME=FROM:TO` | A **sidecar image and the versions it moved between** (repeatable, all in ONE call). `NAME` is substring-matched against source repo names. Malformed values warn on stderr and are skipped. Without it that image's advisories stay unclassified. | | `--compose-to URL` | **Derive every window by diffing this compose against its baseline**, instead of typing `--from/--to/--image`. Point it at a PR's `compose.yml`. | @@ -67,7 +67,7 @@ sidecar is scanned under its own image name. ## Step 1 — Collect source URLs from the registry -Read `cc-ci-plan/upstream/.md` and extract every `http(s)://…` URL. +Read `data/cc-ci/upstream/.md` and extract every `http(s)://…` URL. **Trailing markdown punctuation is stripped** (`` ` `` `'` `"` `*` `.` `,` `;` `:` `>` `)`). The registry is markdown, so URLs appear inside backticks and quotes; capturing the punctuation produced fetches of diff --git a/scripts/cc-ci/advisory-scan.py b/scripts/cc-ci/advisory-scan.py index a38e407..3a4fe79 100755 --- a/scripts/cc-ci/advisory-scan.py +++ b/scripts/cc-ci/advisory-scan.py @@ -17,7 +17,7 @@ SOURCES (measured against the gitea case before being chosen): CVE id, GHSA id, severity AND vulnerable/patched version ranges, so "fixed by THIS upgrade" is computable rather than guessed. Found both gitea CVEs. Derived from the source-repo URLs the per-recipe registry already records — no new per-recipe config needed. - 2. Vendor release/security pages — every URL in cc-ci-plan/upstream/.md, fetched and + 2. Vendor release/security pages — every URL in data/cc-ci/upstream/.md, fetched and regex-scanned for CVE ids. This is what would have caught gitea: the vendor blog names both, while the GitHub releases page names neither. Add vendor security/announcement URLs to the registry to widen this. @@ -50,7 +50,7 @@ import urllib.error import urllib.parse import urllib.request -REGISTRY_DIR = os.environ.get("CCCI_UPSTREAM_REGISTRY", "/srv/cc-ci/cc-ci-plan/upstream") +REGISTRY_DIR = os.environ.get("CCCI_UPSTREAM_REGISTRY", "/srv/cc-ci/data/cc-ci/upstream") UA = "cc-ci-advisory-scan (+https://git.autonomic.zone/recipe-maintainers/cc-ci)" TIMEOUT = int(os.environ.get("ADVISORY_SCAN_TIMEOUT", "45")) CVE_RE = re.compile(r"CVE-\d{4}-\d{4,7}") @@ -1154,7 +1154,7 @@ def scan(recipe: str, v_from: str | None, v_to: str | None, registry_dir: str, # NEVER report 0 for something we could not determine — a 0 asserts safety. If ANY requested # window could not be ordered at all, the total is UNKNOWN rather than a partial number. # A scan with NO usable source has not measured anything, so it must not report a number — - # least of all 0, which asserts safety. mumble had no cc-ci-plan/upstream/mumble.md at all and + # least of all 0, which asserts safety. mumble had no data/cc-ci/upstream/mumble.md at all and # still produced "0 identified", which was then published as a clean 0 in a CVE report. usable_sources = [s for s in report["sources"] if s["status"] == "ok"] no_sources = not usable_sources @@ -1191,7 +1191,7 @@ def markdown(rep: dict) -> str: + ", ".join(rep["fixed_by_this_upgrade"][:15])) if rep.get("no_usable_sources"): L.append("\n⚠ This is NOT zero. **No usable source was checked at all** — the registry " - "file `cc-ci-plan/upstream/.md` is missing or every source failed, so " + "file `data/cc-ci/upstream/.md` is missing or every source failed, so " "nothing was measured. Render this recipe's cve cell as `?`, never `0`, and add " "the registry file.") else: diff --git a/scripts/cc-ci/agents.py b/scripts/cc-ci/agents.py index 42ecbed..5cc4fb7 100644 --- a/scripts/cc-ci/agents.py +++ b/scripts/cc-ci/agents.py @@ -46,7 +46,7 @@ def load_config(path): "backends": raw.get("backend", {}), "defaults": defaults, "loop": raw.get("loop", {}), - "plan_dir": str(SCRIPT_DIR), + "plan_dir": str(SCRIPT_DIR.parent.parent / "archive/original-build/cc-ci-plan"), "log_dir": defaults.get("log_dir", "/srv/cc-ci/.cc-ci-logs"), "session_prefix": defaults.get("session_prefix", "cc-ci-"), } @@ -210,9 +210,9 @@ def build_loop_kickoff(cfg, agent): pid, plan, status = ph["id"], ph["plan"], ph["status"] preamble = ( f"*** cc-ci SUB-PHASE {pid} ***\n" - f"SINGLE SOURCE OF TRUTH for THIS phase: /srv/cc-ci/cc-ci-plan/{plan} — read it in full " + f"SINGLE SOURCE OF TRUTH for THIS phase: /srv/cc-ci/scripts/cc-ci/{plan} — read it in full " f"now; it defines this phase's mission and Definition of Done.\n" - f"The general loop protocol still applies and lives in /srv/cc-ci/cc-ci-plan/plan.md " + f"The general loop protocol still applies and lives in /srv/cc-ci/archive/original-build/cc-ci-plan/plan.md " f"(§6.1 coordination, §7 pacing, §9 guardrails) — read those sections too.\n" f"Track loop state in PHASE-NAMESPACED files UNDER machine-docs/ in your repo clone " f"(create the dir if missing): machine-docs/{status}, machine-docs/BACKLOG-{pid}.md, " diff --git a/scripts/cc-ci/agents.toml b/scripts/cc-ci/agents.toml index 9dfc227..7ada7ca 100644 --- a/scripts/cc-ci/agents.toml +++ b/scripts/cc-ci/agents.toml @@ -34,7 +34,7 @@ supports_resume = false prompt_delivery = "ping" # send after the TUI connects connect_delay = 12 submit_key = "C-m" -preamble = "set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a" +preamble = "set -a; . /srv/cc-ci/scripts/cc-ci/load-env.sh; set +a" stall_idle = 900 active_re = "esc interrupt|thinking|inferring|running tool|tool call|preparing patch|reading|searching" limit_re = "spend limit|usage limit|limit reached|reached your .*limit|out of (credits|tokens)" @@ -72,7 +72,7 @@ resume = true watch = "none" enabled = false prompt = """ -You are the cc-ci ASSISTANT. Read cc-ci-plan/JOURNAL.md for context, then wait for a specific \ +You are the cc-ci ASSISTANT. Read data/cc-ci/JOURNAL.md for context, then wait for a specific \ plan/task from the orchestrator or operator. Work autonomously until the assigned task is \ complete, report the result, and then wait for the next assignment.""" @@ -101,5 +101,5 @@ You generate the public weekly "Recipe Report". Run the /recipe-report skill now # Non-AI helper services (started by `up`, not AI sessions) [[service]] name = "cleanlogs" # tmux session: cc-ci-cleanlogs -command = "python3 cc-ci-plan/agent-log.py follow-all" +command = "python3 scripts/cc-ci/agent-log.py follow-all" dir = "/srv/cc-ci-orch" diff --git a/scripts/cc-ci/audit-advisory-scan.py b/scripts/cc-ci/audit-advisory-scan.py index 10c76ed..6da749f 100755 --- a/scripts/cc-ci/audit-advisory-scan.py +++ b/scripts/cc-ci/audit-advisory-scan.py @@ -7,9 +7,9 @@ Anything the two disagree on is a miscategorization in one of them. """ import importlib.util, json, re, sys -spec = importlib.util.spec_from_file_location("A", "/srv/cc-ci-orch/cc-ci-plan/advisory-scan.py") +spec = importlib.util.spec_from_file_location("A", "/srv/cc-ci-orch/scripts/cc-ci/advisory-scan.py") A = importlib.util.module_from_spec(spec); spec.loader.exec_module(A) -REG = "/srv/cc-ci-orch/cc-ci-plan/upstream" +REG = "/srv/cc-ci-orch/data/cc-ci/upstream" def sv(s): diff --git a/scripts/cc-ci/audit-sources.py b/scripts/cc-ci/audit-sources.py index 4b8afd3..480c71a 100755 --- a/scripts/cc-ci/audit-sources.py +++ b/scripts/cc-ci/audit-sources.py @@ -47,8 +47,8 @@ _aspec = importlib.util.spec_from_file_location("advisory_scan", os.path.join(HE A = importlib.util.module_from_spec(_aspec) _aspec.loader.exec_module(A) -REGISTRY_DIR = os.environ.get("CCCI_UPSTREAM_REGISTRY", os.path.join(HERE, "upstream")) -USED_RECIPES = os.path.join(HERE, "used-recipes.md") +REGISTRY_DIR = os.environ.get("CCCI_UPSTREAM_REGISTRY", os.path.join(HERE, "../../data/cc-ci/upstream")) +USED_RECIPES = os.path.join(HERE, "../../data/cc-ci/used-recipes.md") DEPRECATION_RE = re.compile( r"\b(deprecat|no longer maintain|unmaintained|superseded|moved to|migrated to|" r"has moved|discontinued|end.of.life|archived)\b", re.I) @@ -194,7 +194,7 @@ def audit_recipe(recipe: str, ssh: str | None, quiet_days: int) -> dict: pass if reg_path is None: out["findings"].append({"level": "warn", "what": "no upstream registry file", - "detail": f"cc-ci-plan/upstream/{recipe}.md is missing — the advisory " + "detail": f"data/cc-ci/upstream/{recipe}.md is missing — the advisory " f"scan has nowhere to look"}) seen = set() for u in urls: diff --git a/scripts/cc-ci/launch-assistant.py b/scripts/cc-ci/launch-assistant.py index 01ae2d9..7ff2598 100644 --- a/scripts/cc-ci/launch-assistant.py +++ b/scripts/cc-ci/launch-assistant.py @@ -37,7 +37,7 @@ REMOTE_CONTROL = os.environ.get("REMOTE_CONTROL", "1") == "1" DEFAULT_ID = "9db267a4-9b9e-4818-8197-0a42dba443ea" ID_FILE = os.environ.get("ASSISTANT_ID_FILE", f"{LOG_DIR}/.assistant-session-id") STARTUP_PROMPT = os.environ.get("ASSISTANT_STARTUP_PROMPT", ( - "You are the cc-ci ASSISTANT. Read cc-ci-plan/JOURNAL.md for context, then wait for a " + "You are the cc-ci ASSISTANT. Read data/cc-ci/JOURNAL.md for context, then wait for a " "specific plan/task from the orchestrator or operator. Work autonomously until the assigned " "task is complete, report the result, and then wait for the next assignment." )) @@ -112,7 +112,7 @@ def start(mode="resume"): if not Path(OPENCODE_BIN).exists(): die(f"opencode not found at {OPENCODE_BIN}") cmd = ( - f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; " + f"set -a; . /srv/cc-ci/scripts/cc-ci/load-env.sh; set +a; " f"NO_COLOR=1 {OPENCODE_BIN} attach {OPENCODE_SERVER} --dir {WORKDIR}" ) log(f"starting {SESSION} (backend=opencode, model={LOOP_MODEL or 'default'})") diff --git a/scripts/cc-ci/launch-report.py b/scripts/cc-ci/launch-report.py index 649f76c..66164d2 100755 --- a/scripts/cc-ci/launch-report.py +++ b/scripts/cc-ci/launch-report.py @@ -112,7 +112,7 @@ def start(mode, date): cwd = "/srv/cc-ci-orch/cc-ci" share_flag = "--share" if OPENCODE_SHARE else "" cmd = ( - f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; " + f"set -a; . /srv/cc-ci/scripts/cc-ci/load-env.sh; set +a; " f"{OPENCODE_BIN} run {model_flag} {share_flag} --attach '{OPENCODE_SERVER}' " f"--title '{SESSION}' --dir {cwd} \"$(cat '{kf}')\"" ) @@ -134,7 +134,7 @@ def start(mode, date): # runs under the tmux server (survives the systemd oneshot like the run sessions). if os.environ.get("REPORT_WATCHDOG", "1") == "1": import shlex - LU = "/srv/cc-ci/cc-ci-plan/launch-upgrader.py" + LU = "/srv/cc-ci/scripts/cc-ci/launch-upgrader.py" rf = Path(LOG_DIR) / f".kickoff-{SESSION}-resume.txt" rf.write_text( "The opencode usage limit has reset (or the report stalled). CONTINUE generating and " diff --git a/scripts/cc-ci/launch-supervisor.py b/scripts/cc-ci/launch-supervisor.py index e14357b..3d4af3d 100644 --- a/scripts/cc-ci/launch-supervisor.py +++ b/scripts/cc-ci/launch-supervisor.py @@ -80,12 +80,12 @@ DO THIS, in order — stop as soon as the run is healthy again: `GET /session/{sid}/message`) and the open recipe PRs to see which enrolled recipes already have a PR this week and which remain. Do NOT redo any recipe that already has a PR. 3. DRIVE TO COMPLETION. Prefer to RESUME the existing run (context preserved) once the environment - is healthy: `python3 {WORKDIR}/cc-ci-plan/launch-upgrader.py resume`. Then CONFIRM it actually + is healthy: `python3 {WORKDIR}/scripts/cc-ci/launch-upgrader.py resume`. Then CONFIRM it actually restarted and is progressing (a fresh `opencode run … -s {sid} --continue` proc + the session advancing). If the session is truly gone/unresumable, drive the remaining recipes yourself the /upgrade-all way (per-recipe /recipe-upgrade DEFAULT-mode subagents, !testme verify), then make sure the weekly summary is written to {WORKDIR}/.cc-ci-logs/upgrades/ and launch the public - report: `python3 {WORKDIR}/cc-ci-plan/launch-report.py fresh`. + report: `python3 {WORKDIR}/scripts/cc-ci/launch-report.py fresh`. 4. If on inspection the run is actually FINE (progressing) or already COMPLETE, do NOTHING. 5. Print `SUPERVISOR DONE` and go idle. Do NOT loop. @@ -107,7 +107,7 @@ def spawn_supervisor(sid, reason): kf = Path(LOG_DIR) / f".kickoff-{SUP_SESSION}.txt" kf.write_text(build_kickoff(sid, reason)) share = "--share" if OPENCODE_SHARE else "" - cmd = (f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; {OPENCODE_BIN} run --model '{MODEL}' {share} " + cmd = (f"set -a; . /srv/cc-ci/scripts/cc-ci/load-env.sh; set +a; {OPENCODE_BIN} run --model '{MODEL}' {share} " f"--attach '{OPENCODE_SERVER}' --title '{SUP_SESSION}' --dir {WORKDIR} \"$(cat '{kf}')\"") _sh(["tmux", "new-session", "-d", "-s", SUP_SESSION, "-c", WORKDIR, cmd]) _sh(["tmux", "pipe-pane", "-o", "-t", SUP_SESSION, f"cat >> '{LOG_DIR}/{SUP_SESSION}.log'"]) diff --git a/scripts/cc-ci/launch-upgrader.py b/scripts/cc-ci/launch-upgrader.py index d065ec3..963c731 100644 --- a/scripts/cc-ci/launch-upgrader.py +++ b/scripts/cc-ci/launch-upgrader.py @@ -220,7 +220,7 @@ def start(mode="use-or-create"): # so they must come AFTER `run` (a global `opencode --model X run` is ignored). share_flag = "--share" if OPENCODE_SHARE else "" cmd = ( - f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; " + f"set -a; . /srv/cc-ci/scripts/cc-ci/load-env.sh; set +a; " f"{OPENCODE_BIN} run {model_flag} {share_flag} --attach '{OPENCODE_SERVER}' " f"--title '{SESSION}' \"$(cat '{kf}')\"" ) @@ -522,10 +522,10 @@ def resume(reason="manual"): "!testme, open/extend the recipe PR (NEVER merge, NEVER weaken a test), <= DRONE_RUNNER_CAPACITY " "concurrent. immich has a tag+digest image abra can't parse — do the upstream-direct cross-check " "(recipe-upgrade SKILL §1), don't silently skip it. When all remaining recipes are done: " - "write+push the weekly summary, then `python3 /srv/cc-ci/cc-ci-plan/launch-report.py fresh`, print " + "write+push the weekly summary, then `python3 /srv/cc-ci/scripts/cc-ci/launch-report.py fresh`, print " "'" + DONE_MARKER + "', and go idle.") share = "--share" if OPENCODE_SHARE else "" - cmd = (f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; {OPENCODE_BIN} run -s {sid} --continue " + cmd = (f"set -a; . /srv/cc-ci/scripts/cc-ci/load-env.sh; set +a; {OPENCODE_BIN} run -s {sid} --continue " f"--model '{MODEL}' {share} --attach '{OPENCODE_SERVER}' --dir '{WORKDIR}' \"$(cat '{kf}')\"") subprocess.run(["tmux", "new-session", "-d", "-s", SESSION, "-c", WORKDIR, cmd]) subprocess.run(["tmux", "pipe-pane", "-o", "-t", SESSION, f"cat >> '{LOG_FILE}'"]) diff --git a/scripts/cc-ci/pr-survey.py b/scripts/cc-ci/pr-survey.py index 355d244..1c6c8ce 100755 --- a/scripts/cc-ci/pr-survey.py +++ b/scripts/cc-ci/pr-survey.py @@ -38,7 +38,7 @@ import urllib.request from datetime import datetime, timezone HERE = os.path.dirname(os.path.abspath(__file__)) -USED_RECIPES = os.path.join(HERE, "used-recipes.md") +USED_RECIPES = os.path.join(HERE, "../../data/cc-ci/used-recipes.md") TESTENV = os.environ.get("CCCI_TESTENV", "/srv/cc-ci/.testenv") PUBLIC_ENV = "/srv/cc-ci/cc-ci/.env.public" NS = "recipe-maintainers" diff --git a/scripts/cc-ci/reboot-log.sh b/scripts/cc-ci/reboot-log.sh index aadebf0..9e2d5e9 100755 --- a/scripts/cc-ci/reboot-log.sh +++ b/scripts/cc-ci/reboot-log.sh @@ -4,7 +4,7 @@ # only logs when the current boot_id differs from the last one we recorded. set -u -REBOOTS="/srv/cc-ci/cc-ci-plan/REBOOTS.md" +REBOOTS="/srv/cc-ci/data/cc-ci/REBOOTS.md" LAST_BOOT_FILE="/srv/cc-ci/.cc-ci-logs/.last-boot-id" PHASE_IDX_FILE="/srv/cc-ci/.cc-ci-logs/.phase-idx" diff --git a/scripts/cc-ci/reconcile-upstream.sh b/scripts/cc-ci/reconcile-upstream.sh index d4ff776..c505630 100755 --- a/scripts/cc-ci/reconcile-upstream.sh +++ b/scripts/cc-ci/reconcile-upstream.sh @@ -34,7 +34,7 @@ RECONCILE="${RECONCILE:-$ORCH/.claude/skills/recipe-upgrade/open-recipe-pr.sh}" USED_RECIPES="${USED_RECIPES:-$HERE/used-recipes.md}" [ -f "$RECONCILE" ] || { echo "ERROR: reconcile helper not found: $RECONCILE" >&2; exit 1; } -set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a +set -a; . /srv/cc-ci/scripts/cc-ci/load-env.sh; set +a : "${GITEA_USERNAME:?}"; : "${GITEA_PASSWORD:?}"; : "${GITEA_URL:=git.autonomic.zone}" if [ "${1:-}" = "--all" ]; then diff --git a/scripts/cc-ci/test-advisory-scan.py b/scripts/cc-ci/test-advisory-scan.py index 3505cb0..9baa190 100755 --- a/scripts/cc-ci/test-advisory-scan.py +++ b/scripts/cc-ci/test-advisory-scan.py @@ -163,17 +163,17 @@ class TestRegistryUrls(unittest.TestCase): self.assertEqual(urls, ["https://github.com/cryptpad/cryptpad"]) def test_image_source_table_maps_monorepo_images(self): - mapping = A.registry_image_sources("lasuite-drive", str(HERE / "upstream")) + mapping = A.registry_image_sources("lasuite-drive", str(HERE / "../../data/cc-ci/upstream")) self.assertIn("github-advisories:suitenumerique/drive", mapping["drive-backend"]) self.assertIn("github-advisories:CollaboraOnline/online", mapping["code"]) def test_common_database_cpes_follow_registry_images(self): self.assertIn(("postgres", A.COMMON_IMAGE_CPES["postgres"]), - A.registry_cpes("immich", str(HERE / "upstream"))) + A.registry_cpes("immich", str(HERE / "../../data/cc-ci/upstream"))) self.assertIn(("mariadb", A.COMMON_IMAGE_CPES["mariadb"]), - A.registry_cpes("gitea", str(HERE / "upstream"))) + A.registry_cpes("gitea", str(HERE / "../../data/cc-ci/upstream"))) self.assertIn(("rustdesk-server", "cpe:2.3:a:rustdesk:rustdesk_server:*:*:*:*:oss:*:*:*"), - A.registry_cpes("rustdesk-server", str(HERE / "upstream"))) + A.registry_cpes("rustdesk-server", str(HERE / "../../data/cc-ci/upstream"))) def test_strips_trailing_markdown_punctuation(self): # Production defect: a captured backtick 404'd the fetch and rendered n8n/immich as '?'. @@ -880,7 +880,7 @@ class TestMarkdownOutput(unittest.TestCase): class TestHistoricReportNumbers(unittest.TestCase): """Re-derive counts published in week-2026-08-07. Network + GitHub token; opt in with --live.""" - REGISTRY = str(HERE / "upstream") + REGISTRY = str(HERE / "../../data/cc-ci/upstream") @classmethod def setUpClass(cls): diff --git a/scripts/cc-ci/upstream b/scripts/cc-ci/upstream deleted file mode 120000 index 3ce1281..0000000 --- a/scripts/cc-ci/upstream +++ /dev/null @@ -1 +0,0 @@ -../../cc-ci-plan/upstream \ No newline at end of file diff --git a/scripts/cc-ci/used-recipes.md b/scripts/cc-ci/used-recipes.md deleted file mode 120000 index 1b01100..0000000 --- a/scripts/cc-ci/used-recipes.md +++ /dev/null @@ -1 +0,0 @@ -../../cc-ci-plan/used-recipes.md \ No newline at end of file diff --git a/scripts/recovery/README.md b/scripts/recovery/README.md index 1e75b47..fb9e0c0 100644 --- a/scripts/recovery/README.md +++ b/scripts/recovery/README.md @@ -31,7 +31,7 @@ rotation). shifts indices and a stale override points at the wrong generation. - Journal of the failed boot: `journalctl -D /mnt/var/log/journal --list-boots` / `-b `. 5. `rescue-off` → `poweroff` → `poweron` → verify → write the incident up in - `cc-ci-plan/JOURNAL.md` and (if server) `.cc-ci-logs/`. + `data/cc-ci/JOURNAL.md` and (if server) `.cc-ci-logs/`. **Prevention:** `nixos-rebuild test` before `switch`, always (see AGENTS.md / the update skills) — `test` leaves the bootloader alone, so a power-cycle recovers by itself.