Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(web): require a credential on every console API call (#1069)
Beenu Arora03e923f33491
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 974e5a48d..9ce70e3d8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -361,6 +361,22 @@ jobs:run: python scripts/check_mock_data_gated.py --self-test- name: Verify sample data is gated behind demo moderun: python scripts/check_mock_data_gated.py+ # Sixty-one console calls reached an API with no Authorization header,+ # and every one of them worked: an uncredentialed request resolved to a+ # demo administrator in a development-class environment, which is how+ # the quick start ran. Closing that turns each into a 401, so the+ # console side needs a gate of its own — nothing here looked at a+ # request header before, only at server-side route decorators.+ #+ # Self-test first. Three blind spots in its own first draft are pinned+ # as cases: a generic type argument hid both real SWR sites, a+ # multi-line arrow fetcher was truncated at the first newline, and an+ # inline fetcher whose URL is the SWR key has no API path at the call+ # site to match on at all.+ - name: Console credential gate — self-test+ run: python3 scripts/check_console_auth_headers.py --self-test+ - name: Verify every console API call carries a credential+ run: python3 scripts/check_console_auth_headers.py# Sending a customer file to a third party is a disclosure, and for the# first commercial provider wired here it is a disclosure to the public# internet: a stored report carries `visibility: "public"` anddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex a3537c15d..df42aa6f4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0Worth recording separately: `main` was green at `079fdb69` while every open pull request was red on this, because the advisories were published after `main` last ran. A stale-green default branch hiding a breaker that reds the whole queue is a shape this repository has hit before.+- **Every console call to an AiSOC API now carries a credential. Sixty-one did not.** The gap: `apps/web` reached API routes through bare `fetch(url)` and through two single-argument SWR fetchers that take no options, so the request went out with no `Authorization` header. Those calls worked, which is what hid them — an uncredentialed request resolves to a demo administrator whenever the API runs in a development-class environment, and that is how the quick start and the documented single-host deployment run.++ How it was measured: `scripts/check_console_auth_headers.py`, which parses each `fetch(` and `useSWR(` call in `apps/web/src` and asks whether the credential is visible on the same expression. Against the commit before the fix it reports 61 findings across 21 files; after, 33 API calls across 311 files all carry one, with a single allowlisted exception (the public `/r/<slug>` replay permalink, which is unauthenticated by design). A hand-written grep for `fetch('/api/v1` finds only 27 of the 61: it cannot see a template-literal URL behind a base variable, the six call sites inside `api.ts` itself, or any of the 16 `useSWR` keys whose fetcher is anonymous by construction.++ Two near-misses are now findings rather than passes, because neither authenticates: `X-Tenant-Id` on its own is a caller-supplied claim, not an identity, and five `api.ts` call sites sent exactly that and no token; and `credentials: 'include'` sends cookies, while the API verifies a bearer token and the SSO cookie it sets is read by nothing.++ The fix routes everything through one credentialed path — `apiHeaders()`, `apiRequest()`, `authedFetcher()` and `apiFetch()` in `apps/web/src/lib/api.ts` — and deletes `apps/web/src/lib/fetcher.ts` and `jsonFetcher` outright. Three hand-rolled copies of the localStorage token block collapse into the helper, which also fixes a tenant-switcher bug they shared: all three pinned `X-Tenant-Id` to the build-time `TENANT_ID` rather than resolving `getActiveTenantId()` at call time, so switching tenant did not reach them.++ The server-side prefetch in `apps/web/src/app/(app)/cases/page.tsx` was removed rather than credentialed. It sent a build-time tenant id and no token, so it served one fixed tenant's cases to whoever loaded the page; a server render has no session to borrow, so there was no authenticated version of that call to keep. The `initialCases` prop it fed went with it, along with the two assertions in `CasesViewSsr.test.tsx` that only described it — the two covering the demo gate remain, since that is the direction with a production path.++ The gate that keeps it closed is wired into `ci.yml` beside the sample-data gate, and runs `--self-test` first. Three blind spots in its own first draft are pinned as cases, each of which had made it silently miss real findings: a generic type argument (`useSWR<Role[]>(...)`) hid both settings SWR sites, a multi-line arrow fetcher was truncated at the first newline so nine calls on the honeytokens and purple-team pages read as "imported, judged elsewhere", and an inline fetcher whose URL is the SWR key has no API path at the call site to match on at all.+## [14.0.0] - 2026-09-29### BREAKINGdiff --git a/PARITY_PROGRESS.md b/PARITY_PROGRESS.mdnew file mode 100644index 000000000..f7f817405--- /dev/null+++ b/PARITY_PROGRESS.md@@ -0,0 +1,209 @@+# Parity plan progress++Mirrors [`plans/aisoc_parity_plan.plan.md`](plans/aisoc_parity_plan.plan.md),+which is the source of truth and is not edited. Modelled on+[`GAP_CLOSURE_PROGRESS.md`](GAP_CLOSURE_PROGRESS.md).++The plan was captured against `v14.0.0` (commit `079fdb6`). `origin/main` was+at `079fdb69` with **zero commits since the tag** when work started, so every+path, line reference and number the plan cites was checked against the tree it+describes rather than a moved one. Where they disagree, the disagreement is a+Deviation below and the tree wins.++Its precondition — "ask the maintainer once whether the private security batch+has been merged and released" — was answered: it had not been, and it is being+worked first. Progress on it is in+[`SECURITY_BATCH_PROGRESS.md`](SECURITY_BATCH_PROGRESS.md).++## Pre-existing state, captured before any code was written++See the same section of `SECURITY_BATCH_PROGRESS.md`; both plans started from+one measurement of the untouched tree. In short: 77 of 84 gates pass, the seven+that do not are six argument or token refusals plus one environmental mypy+finding, and the console suite is 816 tests green with a clean type-check.++Numbers re-derived at the start, to be used instead of the plan's:++- **CORE is 17 compose services**, being those with no `profiles:` key, which+ is what `make up` starts. 16 if one-shot `ollama-pull` is excluded. See D3.+- Claim matrix: **241 rows, 241 GATED, 0 PARTIAL, 0 NO GATE**.+- `scripts/` holds 183 `.py` files, 84 of them named `check_*.py`.+- Next migration number: **076**. Next ADR: **0009**.+- Ratchets: `MAX_UNAUTHORIZED = 28`, tenant-predicate exceptions 35.+- `README.md` is at its 250-line cap, so Phase 1 links rather than adds.++## Deviations: where the plan and the tree disagree++### D1. Phase 11 of the gap-closure plan already shipped++The plan's 1.2 says "the gap-closure tracker still marks file analysis as+blocked, although v12.0.0 shipped the sandbox providers". Confirmed, and the+scope is all three sub-items, not one: `GAP_CLOSURE_PROGRESS.md:469-475` marks+Phase 11 and 11.1 through 11.3 as `[!]` blocked, while the tree carries+`services/api/app/services/sandbox/base.py` plus the CAPEv2, mock and+MalwareAnalyzer providers, the upload policy with migration+`064_sandbox_upload_policy.sql` and `scripts/check_sandbox_upload_policy.py`,+the enrichment and agent-tool wiring, and six routes at+`endpoints/sandbox.py:171-263`.++### D2. Two of the four gates Phase 1.4 asks for already exist in part++`scripts/check_route_shadowing.py` exists, and it cannot catch the duplicate+`get_investigation` pair that 1.3 names. Its own docstring says so at line 27:+"Two modules included under one prefix can shadow each other and this will not+see it." Two independent reasons, both worth knowing before extending it: it+groups by `(service, path, router)` and the two paths differ before mounting+(`/investigations/{run_id}` against `/api/v1/investigations/{run_id}`, because+the prefix comes from an app-level `include_router` the AST pass cannot see),+and `shadows()` only sets `captures=True` when a parameter segment faces a+literal one, so identical paths compare equal and report nothing.++A console route-contract gate also exists in narrow form.+`scripts/check_ledger_replay_contract.py` pins `CLIENT_OBJECT = "ledgerApi"`+against `ROUTER_PREFIX_DEFAULT = "/investigations"`, with a bidirectional+server-only allowlist. It is a working pattern to widen, not a greenfield+build. `scripts/check_sdk_surface.py` is SDK-only as the plan says.++### D3. There is no `core` profile, so the CORE count has no single source++Plan item 1.2 says to "take the real count from `docker compose config` for the+CORE profile". There is no `core` profile in `docker-compose.yml`, so that+command cannot answer the question. CORE is the set of services declaring no+profile, which is 17 of the 32 declared: actions, agents, api, connectors,+fusion, ingest-worker, kafka, litellm, ollama, ollama-pull, postgres, qdrant,+realtime, redis, threatintel, web, zookeeper.++Four places in the tree disagree with each other about it: `install.sh:784`+says 10 while naming 9 on the next line, `walkthrough.mdx:80` says fifteen,+`Makefile:157` says fifteen, and `scripts/generate_slo_alerts.py:5` says 17. So+1.2 needs one derivation the others read from, not four string edits.++### D4. Three counts in 1.1 and 1.2 are wrong in different directions++- **Playbooks are 62, not 50.** `playbooks/README.md:13` says 50 and its tree+ enumerates 9 directories summing to 50; the tree holds 62+ `*.playbook.json` across 21 directories, which is what+ `marketplace/index.json` already publishes as `playbook_packs: 62`.+- **ATT&CK coverage over executable rules only is 387 technique ids**, or 168+ unique base techniques. The published 493 (`marketplace/index.json:540`) is+ the union over all 7,155 marketplace items with sub-techniques counted+ separately; detections-only is 491.+- **The 68-hunt library is a true number.** 68 YAML hunts exist. Only the+ "hunting agent" half of that README row is unbacked, so 1.1 narrows the row+ rather than the count.++### D5. A count in `marketplace/index.json` disagrees with its own data++Neither document raises this. `stats.executable` reads **2767** while the item+flags say `executable: true` on exactly **2603** and `false` on 4388. A+headline number and the data under it, in one file, disagreeing by 164. Folded+into 1.1's coverage row since both are published from the same generator.++### D6. Compliance is 5 frameworks and 24 controls, and 87 controls are unread++Plan item 1.1 narrows the six-framework claim "to the 24 controls across 5+frameworks the API maps", which is right:+`services/api/app/api/v1/endpoints/compliance.py:66-101` maps SOC2 7, PCI-DSS+5, HIPAA 4, ISO27001 4, NIST-CSF 4, with DORA absent. Two things to know while+doing it: a second, smaller mapping in+`services/api/app/services/compliance_mapping.py:16-29` holds 12 controls+across 2 frameworks, and the richer+`services/api/compliance_frameworks/*.yaml` (87 controls across five+frameworks, DORA included) is **loaded by nothing** — zero `.py` references.+PDF export does not exist in either module.++### D7. Two claims in 1.1 are already partly retracted++- **MSSP ARR is gone.** `apps/web/src/components/mssp/MSSPDashboardView.tsx:8`+ records the removal of the fabricated ARR, risk and headcount strip, and+ `MSSPDashboardView.test.tsx:276` asserts `queryByText(/ARR/)` is null. Only+ `apps/docs/docs/intro.md:61` still advertises it, so that row is a doc edit.+- **Shift handoff, EASM and team analytics all exist as real code.** The+ intro.md row removes four items of which three have implementations, so it+ narrows rather than deletes.++### D8. The memory overclaim is narrower than written++Plan item 1.1 narrows the landing-page claim "to the reason-coded memory that+exists". All three tiers do exist as code+(`services/agents/app/memory/{session,working,institutional,manager}.py`); what+does not exist is **pgvector** — no reference in `institutional.py`, no+migration creating the extension, and the only mention is a hedged docstring at+`memory/__init__.py:8`. `MemoryManager` also has no production caller, which is+a reachability finding for 1.4 rather than a claim edit.++## Phase 1: Make every claim true on the default path++- [ ] **1.1** Retract or narrow the overclaims+- [ ] **1.2** Clear the documentation drift+- [ ] **1.3** Repair the broken console paths+- [ ] **1.4** Make the gates path-aware++## Phase 2: Govern and protect alert closure++- [ ] **2.1** Per-tenant, per-class closure policy+- [ ] **2.2** Kill switch+- [ ] **2.3** Learn only from humans — the urgent half ships as security S10+- [ ] **2.4** Pseudonymize before hosted egress+- [ ] **2.5** One model path for every LLM call+- [ ] **2.6** Enforced budgets++## Phase 3: Prove verdict quality on the default install++- [ ] **3.1** Give the default install evidence+- [ ] **3.2** Accuracy on the shipped model+- [ ] **3.3** Behavioural injection suite+- [ ] **3.4** Before-and-after measurement+- [ ] **3.5** QA sampling of auto-closed alerts+- [ ] **3.6** A grounded copilot+- [ ] **3.7** Evidence bundles++## Phase 4: Enterprise identity and the operator console++- [ ] **4.1** SSO end to end+- [ ] **4.2** Console MFA+- [ ] **4.3** Custom roles everywhere — ships as security S13+- [ ] **4.4** Audit log for tenant admins+- [ ] **4.5** Operator pages+- [ ] **4.6** Internationalisation+- [ ] **4.7** Accessibility on core views++## Phase 5: Close the response and detection loop++- [ ] **5.1** Alert-triggered playbooks+- [ ] **5.2** Approval as a durable pause+- [ ] **5.3** Steps that do something+- [ ] **5.4** Tenant tuning inside fusion+- [ ] **5.5** Rules that can fire+- [ ] **5.6** Case depth+- [ ] **5.7** Delivery++## Phase 6: Agent parity, then platform depth++- [ ] **6.1** Hunting+- [ ] **6.2** Detection engineering+- [ ] **6.3** Custom agents+- [ ] **6.4** Phishing operations+- [ ] **6.5** Semantic memory with provenance+- [ ] **6.6** MCP over the network+- [ ] **6.7** Agent identity and AI-agent baselines+- [ ] **6.8** Deployment completeness+- [ ] **6.9** Scale+- [ ] **6.10** Collection and standards++## Maintainer-only items++- [ ] Fund a hosted-model key so 3.2 and 3.3 can report hosted results+- [ ] Sign at least one design partner willing to replay closed alerts+- [ ] Publish the npm and PyPI packages and the MCP server package+- [ ] Commission an external penetration test, and SOC 2 or ISO 27001 for the+ hosted service+- [ ] Add a second maintainer with merge rights+- [ ] Decide when to cut the planned major, and the cadence of the stable+ channel++## Notes for the next session++The security batch comes first and is tracked separately. Phase 1 starts once+it has landed and been released, because several of its items assume those+fixes exist.diff --git a/ROADMAP.md b/ROADMAP.mdindex 16b894e57..35d113119 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **241 rows — 241 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **242 rows — 242 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/SECURITY_BATCH_PROGRESS.md b/SECURITY_BATCH_PROGRESS.mdnew file mode 100644index 000000000..c0dacfe61--- /dev/null+++ b/SECURITY_BATCH_PROGRESS.md@@ -0,0 +1,190 @@+# Security batch progress++Thirteen defects found by reading the code at `v14.0.0` (commit `079fdb6`). None+had been exercised against a running deployment, so every item starts with a+reproduction that fails on the untouched tree for the stated reason.++Two of the thirteen are also items in+[`plans/aisoc_parity_plan.plan.md`](plans/aisoc_parity_plan.plan.md). They are+done once, here, and the parity tracker points at this file rather than+repeating the work.++## D0. This batch is public, by the maintainer's decision++The source brief specified coordinated disclosure: a local branch pushed+nowhere, a tracker under `.private/`, and advisory drafts handed over in chat+for the maintainer to publish before any code became visible.++The maintainer chose the opposite: ordinary public pull requests, merged and+released as they land, with advisories filed afterwards against the release.+The reasoning is that this is a self-hosted product whose defaults are readable+by anyone who opens `.env.example`, so the fix reaching self-hosters sooner is+worth more than the delay buying secrecy that the repository does not really+have.++What that changes, and what it does not:++- No `.private/` directory. This file is the tracker and it is committed.+- Commit messages stay neutral and carry no exploit detail, payloads or+ advisory wording. That costs nothing, keeps the history readable, and leaves+ the option of filing advisories against these commits later.+- Advisory drafts are still produced for every defect: reproduction, root+ cause, affected versions, a suggested CVSS v3.1 vector, and whether the fix+ is breaking.+- S1 and S13 both break callers, so this batch lands as a major.++## Pre-existing state, captured before any code was written++Measured on `origin/main` at `079fdb69` with the working tree stashed, so the+numbers describe the untouched tree.++### Gates: 77 of 84 pass++The seven that do not, and why none is a defect in the tree:++| Gate | Exit | Reason |+|---|---|---|+| `check_attribution.py` | 2 | Refuses to scan without `--all`, `--diff-base`, `--commits` or `--text-file`. |+| `check_container_egress.py` | 2 | Refuses without `--service`: "a probe that covers nothing must not report clean". |+| `check_published_secrets.py` | 2 | Refuses without `--check-env`, `--check` or `--list-guarded`. |+| `check_codeql_alerts.py` | 2 | Needs `GITHUB_TOKEN` with `security-events: read`. Refuses rather than reporting clean about alerts it never read. |+| `check_main_run_cancellations.py` | 2 | Needs a token for the Actions API, same refusal. |+| `check_required_check_substance.py` | 2 | Needs a token for the Actions API, same refusal. |+| `check_mypy_baseline.py` | 1 | Environmental, see D14. |++Six of the seven are the gate contract working: they decline to render a+verdict about a corpus they could not read. Only `check_mypy_baseline` reports+a finding, and it does not reproduce in CI.++### Console suite++`apps/web`: 79 files, 816 tests, zero failures. `npx tsc --noEmit` clean.+`npx eslint .` reports 0 errors and 76 warnings, all pre-existing.++## Deviations: where the brief and the tree disagree++### D1. S1c is 61 call sites, not 27++The brief names `RBACView.tsx` and "any other header-less call you find".+Counting by hand with a grep for `fetch('/api/v1` gives 27. The gate written+for the item finds **61** across 21 files, and the extra 34 are not noise:++- template-literal URLs behind a base variable, which the grep pattern cannot+ see: `fetch(\`${API}/api/v1/honeytokens/${id}\`)` on the honeytokens and+ purple-team pages (9 calls);+- six calls inside `apps/web/src/lib/api.ts` itself, five of which sent+ `X-Tenant-Id` and no token, which reads like an identity and is not one;+- sixteen `useSWR` sites whose fetcher is a single-argument function and+ therefore anonymous by construction.++### D2. `require_permission_db` has 27 call sites, not 31++All 27 are in-body `await <principal>.require_permission_db(...)`; there are+**zero** as a `Depends`. They live in four modules only: `autonomy_policy.py`+(9), `tenant_skills.py` (9), `business_context.py` (5), `mcp_servers.py` (4).+The static figure in the brief is exact: 272, being 256 `Depends` plus 16+direct calls.++### D3. S3's "no authorization decision" is narrower than written++All four routes in `services/api/app/api/v1/endpoints/shifts.py` do take+`current_user: AuthUser`, so they authenticate. What is absent is any+`require_permission(...)` and any tenant scoping, so the finding is+cross-tenant read and write of one shared in-process list by any authenticated+principal. The effect stands; the mechanism in the brief does not.++### D4. S7's audit-read restriction is not a wildcard check++`services/api/app/api/v1/endpoints/audit.py` contains no `"*"` comparison.+Both read routes use `Depends(require_permission("audit_log:read"))`. The+outcome the brief describes holds and is stronger than stated: `audit_log:read`+appears in **no** role's permission list in `ROLE_PERMISSIONS`, so only the two+roles holding `["*"]` can read the log. A `tenant_admin` gets 403 because the+permission is unreachable, not because a wildcard was demanded.++### D5. The production compose file already exists and nothing selects it++S1's fix is not "write a production compose". `docker-compose.prod.yml` sets+`ENVIRONMENT: production` and `AISOC_DEV_MODE: 0` as literals on all six Python+services. But `Makefile:102` (`up:`) and `Makefile:142` (`up-full:`) never pass+`-f docker-compose.prod.yml`, and `install.sh` and `install.ps1` contain zero+occurrences of either variable. The file is correct and unreachable from every+documented path.++### D6. `realtime`'s push routes are worse than written++The brief says the tenant comes "from a header or query parameter with no+credential". `services/realtime/src/push.ts:92` reads `x-tenant-id`, falls back+to the `tenant_id` query parameter, and then falls back to the literal string+`'default'`. The three `POST /v1/push/*` routes carry only a rate limiter.++### D7. Ten services default `AISOC_DEV_MODE=1`, and `api` is not one of them++`docker-compose.yml` sets `AISOC_DEV_MODE: ${AISOC_DEV_MODE:-1}` on fusion,+agents, osquery-tls, actions, connectors, threatintel, ueba, honeytokens,+purple-team and slack-bot. The API service has no `AISOC_DEV_MODE` at all; it+reaches the same bypass through `ENVIRONMENT: ${ENVIRONMENT:-development}` and+`AUTH_BYPASS_ENVIRONMENTS`.++### D14. `check_mypy_baseline` fails locally and passes in CI++Locally it reports `(unmanaged)/scripts/run_evals.py: 15 index finding(s),+baseline records 13`. CI is green at the same commit (28 success, 2 skipped on+`079fdb69`), and the local mypy is 2.3.1, which is what `ci.yml:234` pins.++The gate deliberately removes two sources of variance with+`--no-site-packages --no-incremental`, documented at `ci.yml:272`. It does not+pin the interpreter, and this machine runs Python 3.12.6 against CI's 3.11.+Recorded as environmental rather than fixed, and worth noting as a gap in a+gate whose whole purpose is reproducibility.++## S1. Anonymous admin in the documented deployment++Reproduced and confirmed live on `origin/main`. The crux is byte-identical, not+merely similar: `dev_auth.py:29` `DEMO_TENANT_ID` and `bootstrap_admin.py:59`+`DEFAULT_TENANT_ID` are both `00000000-0000-0000-0000-000000000001`, so the+anonymous principal is an `admin` in the same tenant the real operator is+bootstrapped into.++- [x] **S1c** Console credential on every call ([#1069](https://github.com/beenuar/AiSOC/pull/1069))+- [ ] **S1** Production-class defaults on every documented path+- [ ] **S1b** The nine vendored shims, slack-bot and realtime push++## S2 to S13++- [ ] **S2** Copilot conversations and saved hunt searches are tenant-scoped+- [ ] **S3** Fabricated shared shift state+- [ ] **S4** STIX and TAXII demo data served outside demo mode+- [ ] **S5** Login throttling and lockout+- [ ] **S6** SSO stub identities deleted+- [ ] **S7** Audit blind spots+- [ ] **S8** Tenant isolation beyond query predicates+- [ ] **S9** State-changing routes with no authorization decision+- [ ] **S10** Attacker-controlled alert text can close and then silence alerts+- [ ] **S11** Plaintext service traffic+- [ ] **S12** Default Caldera API key+- [ ] **S13** A custom role cannot restrict a user below their built-in role++## Maintainer actions++- [ ] Check whether the managed instance runs with a dev-class `ENVIRONMENT`+ or serves more than one real tenant. If it does, assess exposure for S1+ to S4 and rotate anything those routes could reach. (Named neutrally on+ purpose: `scripts/check_hosted_hostname.py` keeps the managed hostname+ out of this repository, and a tracker is not a reason to exempt it.)+- [ ] Reserve the PyPI and npm names the packages will use (`aisoc` on PyPI+ belongs to an unrelated project).+- [ ] File the advisories against the release once the batch has landed.++### D8. Two documents publish the claim-matrix row count in prose++`ROADMAP.md` and `apps/docs/docs/compliance/evidence-pack.md` both state the+figure, and `scripts/check_readme_figures.py` compares them against the live+table. So every PR that adds a claim row moves three files, not one. The gate+caught it on the first attempt here, which is what it is for.++## Notes for the next session++The batch order is dependency-driven, not severity-driven. S1c had to land+before S1 because closing the anonymous path turns 61 console calls into 401s,+and the console had to be able to authenticate first.diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex dce0e95d5..b62132f97 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 241 rows+The last row is the one worth reading first. It is the honest index: 242 rows`GATED`, 0 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is whydiff --git a/apps/web/src/app/(app)/admin/tenants/page.tsx b/apps/web/src/app/(app)/admin/tenants/page.tsxindex ce6ed3d25..b6d4163e7 100644--- a/apps/web/src/app/(app)/admin/tenants/page.tsx+++ b/apps/web/src/app/(app)/admin/tenants/page.tsx@@ -19,6 +19,7 @@import { useCallback, useEffect, useMemo, useState } from 'react';import Link from 'next/link';+import { apiFetch } from '@/lib/api';// ---------------------------------------------------------------------------// Wire types — mirror services/api/app/api/v1/endpoints/tenant_provision.py@@ -62,7 +63,7 @@ export default function AdminTenantsPage() {if (trimmed) params.set('q', trimmed);if (managedOnly) params.set('managed_only', 'true');const qs = params.toString();- const response = await fetch(+ const response = await apiFetch(`/api/v1/admin/tenants${qs ? `?${qs}` : ''}`,{ method: 'GET', cache: 'no-store' },);diff --git a/apps/web/src/app/(app)/admin/waitlist/page.tsx b/apps/web/src/app/(app)/admin/waitlist/page.tsxindex 6cb93bec1..bf708895e 100644--- a/apps/web/src/app/(app)/admin/waitlist/page.tsx+++ b/apps/web/src/app/(app)/admin/waitlist/page.tsx@@ -25,6 +25,7 @@*/import { useCallback, useEffect, useMemo, useState } from 'react';+import { apiFetch } from '@/lib/api';// ---------------------------------------------------------------------------// Wire types — mirror services/api/app/api/v1/endpoints/waitlist.py@@ -90,7 +91,7 @@ export default function AdminWaitlistPage() {setError(null);try {const qs = statusFilter === 'all' ? '' : `?status_filter=${statusFilter}`;- const response = await fetch(`/api/v1/waitlist/entries${qs}`, {+ const response = await apiFetch(`/api/v1/waitlist/entries${qs}`, {method: 'GET',cache: 'no-store',});@@ -118,7 +119,7 @@ export default function AdminWaitlistPage() {) => {setBusyRow(entryId);try {- const response = await fetch(`/api/v1/waitlist/entries/${entryId}`, {+ const response = await apiFetch(`/api/v1/waitlist/entries/${entryId}`, {method: 'PATCH',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ status: nextStatus }),@@ -139,7 +140,7 @@ export default function AdminWaitlistPage() {setBusyRow(entryId);setError(null);try {- const response = await fetch('/api/v1/admin/tenants/provision', {+ const response = await apiFetch('/api/v1/admin/tenants/provision', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ waitlist_entry_id: entryId, seed_demo: true }),diff --git a/apps/web/src/app/(app)/cases/page.tsx b/apps/web/src/app/(app)/cases/page.tsxindex 78a97d649..3073dadea 100644--- a/apps/web/src/app/(app)/cases/page.tsx+++ b/apps/web/src/app/(app)/cases/page.tsx@@ -1,8 +1,4 @@import { CasesView } from '@/components/cases/CasesView';-import {- normalizeCasesResponse,- type CasesResponse,-} from '@/lib/api';export const metadata = {title: 'Cases',@@ -15,41 +11,19 @@ export const dynamic = 'force-dynamic';export const revalidate = 0;export const fetchCache = 'force-no-store';-const DEFAULT_TENANT_ID = '00000000-0000-0000-0000-000000000001';--function resolveServerApiBase(): string {- // Prefer the in-cluster mesh URL when running on Fly so SSR doesn't depend- // on public DNS or TLS. Fall back to the public API base for local dev.- const internal = process.env.API_URL?.trim();- if (internal) return internal.replace(/\/+$/, '');- const publicBase = process.env.NEXT_PUBLIC_API_URL?.trim();- if (publicBase) return publicBase.replace(/\/+$/, '');- return '';-}--async function loadInitialCases(): Promise<CasesResponse | null> {- const base = resolveServerApiBase();- if (!base) return null;- const tenantId =- process.env.NEXT_PUBLIC_TENANT_ID?.trim() || DEFAULT_TENANT_ID;- try {- const res = await fetch(`${base}/api/v1/cases`, {- headers: {- Accept: 'application/json',- 'X-Tenant-Id': tenantId,- },- cache: 'no-store',- next: { revalidate: 0 },- });- if (!res.ok) return null;- const raw = await res.json();- return normalizeCasesResponse(raw);- } catch {- return null;- }-}--export default async function CasesPage() {- const initialCases = await loadInitialCases();- return <CasesView initialCases={initialCases ?? undefined} />;+// There is no server-side prefetch here on purpose.+//+// This page used to fetch `/api/v1/cases` during the server render, sending+// `X-Tenant-Id` from a build-time environment variable and no credential at+// all. It returned data because the API resolved an uncredentialed request to+// a demo administrator in a development-class environment, and the tenant it+// read was whichever one the image was built for rather than the one the+// signed-in analyst belongs to.+//+// A server render has no session to borrow: the bearer token lives in the+// browser. So the prefetch cannot be made correct, only removed. `CasesView`+// loads through the credentialed client on mount, which is the only place the+// caller's own identity and tenant are known.+export default function CasesPage() {+ return <CasesView />;}diff --git a/apps/web/src/app/(app)/honeytokens/page.tsx b/apps/web/src/app/(app)/honeytokens/page.tsxindex 19616d9b5..8016c8286 100644--- a/apps/web/src/app/(app)/honeytokens/page.tsx+++ b/apps/web/src/app/(app)/honeytokens/page.tsx@@ -3,6 +3,7 @@import { useState } from "react";import useSWR, { mutate } from "swr";import { useTenantId } from "@/components/layout/TenantProvider";+import { apiHeaders } from '@/lib/api';// Same-origin by default — Next.js rewrites proxy `/api/v1/honeytokens/*`// to the honeytokens service. Override with `NEXT_PUBLIC_HONEYTOKENS_URL`@@ -18,7 +19,7 @@ const API = process.env.NEXT_PUBLIC_HONEYTOKENS_URL ?? "";// the console's `X-Tenant-Id` header uses.const fetcher = (url: string) =>- fetch(url).then((r) => {+ fetch(url, { headers: apiHeaders() }).then((r) => {if (!r.ok) throw new Error(`HTTP ${r.status}`);return r.json();});@@ -139,7 +140,7 @@ function CreateTokenModal({try {const res = await fetch(`${API}/api/v1/honeytokens`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: apiHeaders(),body: JSON.stringify({tenant_id: tenantId,name,@@ -325,13 +326,13 @@ export default function HoneytokensPage() {};const revoke = async (id: string) => {- await fetch(`${API}/api/v1/honeytokens/${id}/revoke`, { method: "PATCH" });+ await fetch(`${API}/api/v1/honeytokens/${id}/revoke`, { method: "PATCH", headers: apiHeaders() });refresh();};const remove = async (id: string) => {if (!confirm("Delete this honeytoken?")) return;- await fetch(`${API}/api/v1/honeytokens/${id}`, { method: "DELETE" });+ await fetch(`${API}/api/v1/honeytokens/${id}`, { method: "DELETE", headers: apiHeaders() });refresh();};diff --git a/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx b/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsxindex 79b52d615..fdab1464b 100644--- a/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx+++ b/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx@@ -38,7 +38,7 @@ import useSWR from 'swr';import cytoscape, { type Core, type ElementDefinition } from 'cytoscape';import fcose from 'cytoscape-fcose';import { clsx } from 'clsx';-import { safeFetcher } from '@/lib/fetcher';+import { authedFetcher } from '@/lib/api';import { demoFallback } from '@/lib/demoFallback';import { describeApiFailure } from '@/lib/failure';@@ -284,7 +284,7 @@ function countDenyActions(decisions: Decision[]): number {}function isScaffold501(error: unknown): boolean {- // safeFetcher throws `HTTP 501 …` strings on coverage=scaffold providers.+ // authedFetcher throws ApiError with the status on coverage=scaffold providers.return error instanceof Error && error.message.startsWith('HTTP 501');}@@ -352,7 +352,7 @@ export function EffectivePermissionsView() {const { data: providerInfo } = useSWR<{ providers: ProviderInfo[] }>('/api/v1/identity/effective-permissions/providers',- safeFetcher,+ authedFetcher,{ fallbackData: demoFallback({ providers: DEMO_PROVIDERS }) },);const providers = providerInfo?.providers ?? DEMO_PROVIDERS;@@ -365,7 +365,7 @@ export function EffectivePermissionsView() {: null;const { data, error, isLoading, mutate } = useSWR<ResolverResult>(apiUrl,- safeFetcher,+ authedFetcher,{fallbackData:provider === 'aws' && !isScaffoldProvider ? demoFallback(DEMO_RESULT) : undefined,diff --git a/apps/web/src/app/(app)/purple-team/page.tsx b/apps/web/src/app/(app)/purple-team/page.tsxindex 7fe6fcfc4..e542f1c10 100644--- a/apps/web/src/app/(app)/purple-team/page.tsx+++ b/apps/web/src/app/(app)/purple-team/page.tsx@@ -4,6 +4,7 @@ import { useState } from 'react'import useSWR from 'swr'import { demoFallback } from '@/lib/demoFallback';import { useTenantId } from '@/components/layout/TenantProvider';+import { apiHeaders } from '@/lib/api';// Same-origin by default — Next.js rewrites proxy `/api/v1/purple-team/*` to// the purple-team service. Override with `NEXT_PUBLIC_PURPLE_TEAM_API` for@@ -122,7 +123,7 @@ interface TabletopSession {// below is `null`-gated on it so no request is issued against a guess.const fetcher = (url: string) =>- fetch(url).then((r) => {+ fetch(url, { headers: apiHeaders() }).then((r) => {if (!r.ok) throw new Error(`HTTP ${r.status}`)return r.json()})@@ -243,7 +244,7 @@ function CoverageHeatmap() {try {const res = await fetch(`${API}/api/v1/purple-team/drift/snapshot?tenant_id=${tenantId}&trigger=manual`,- { method: 'POST' }+ { method: 'POST', headers: apiHeaders() })if (!res.ok) throw new Error(`HTTP ${res.status}`)await mutateDrift()@@ -588,7 +589,7 @@ function TabletopPanel() {if (!tenantId) returnawait fetch(`${API}/api/v1/purple-team/tabletop`, {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: apiHeaders(),body: JSON.stringify({tenant_id: tenantId,name: form.name,@@ -604,19 +605,19 @@ function TabletopPanel() {async function addFinding(sessionId: string) {await fetch(`${API}/api/v1/purple-team/tabletop/${sessionId}/findings`, {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: apiHeaders(),body: JSON.stringify({ finding: newFinding, severity: newFindingSeverity }),})setNewFinding('')mutate()- const res = await fetch(`${API}/api/v1/purple-team/tabletop/${sessionId}`)+ const res = await fetch(`${API}/api/v1/purple-team/tabletop/${sessionId}`, { headers: apiHeaders() })if (!res.ok) returnconst updated = await res.json()setSelectedSession(updated)}async function completeSession(sessionId: string) {- await fetch(`${API}/api/v1/purple-team/tabletop/${sessionId}/complete`, { method: 'PATCH' })+ await fetch(`${API}/api/v1/purple-team/tabletop/${sessionId}/complete`, { method: 'PATCH', headers: apiHeaders() })mutate()}@@ -803,7 +804,7 @@ function ReportDetectionModal({async function save() {await fetch(`${API}/api/v1/purple-team/executions/${execution.id}/detection`, {method: 'PATCH',- headers: { 'Content-Type': 'application/json' },+ headers: apiHeaders(),body: JSON.stringify({execution_id: execution.id,detected,diff --git a/apps/web/src/app/(app)/settings/business-context/client.ts b/apps/web/src/app/(app)/settings/business-context/client.tsindex e329b45ae..9e3ed2863 100644--- a/apps/web/src/app/(app)/settings/business-context/client.ts+++ b/apps/web/src/app/(app)/settings/business-context/client.ts@@ -1,3 +1,4 @@+import { apiFetch } from '@/lib/api';/*** Business Context settings — typed fetch client.*@@ -18,7 +19,6 @@ const TENANT_ID =* Honour ``NEXT_PUBLIC_API_URL`` if set so this works in local debugging* configurations that bypass the proxy.*/-const API_BASE = process.env.NEXT_PUBLIC_API_URL || "";// ---------------------------------------------------------------------------// Wire types — kept in sync with the FastAPI response_model classes.@@ -111,7 +111,7 @@ async function asJson<T>(resp: Response): Promise<T> {/** ``GET /api/v1/business-context/rules`` — load the saved rule set. */export async function loadRules(): Promise<RulesEnvelope> {- const resp = await fetch(`${API_BASE}/api/v1/business-context/rules`, {+ const resp = await apiFetch(`/api/v1/business-context/rules`, {method: "GET",headers: authHeaders(),credentials: "include",@@ -121,7 +121,7 @@ export async function loadRules(): Promise<RulesEnvelope> {/** ``POST /api/v1/business-context/rules`` — replace the whole rule set. */export async function saveRules(yaml: string): Promise<RulesEnvelope> {- const resp = await fetch(`${API_BASE}/api/v1/business-context/rules`, {+ const resp = await apiFetch(`/api/v1/business-context/rules`, {method: "POST",headers: authHeaders(),credentials: "include",@@ -135,8 +135,8 @@ export async function previewRules(yaml: string,alerts: Record<string, unknown>[] = [],): Promise<PreviewResponse> {- const resp = await fetch(- `${API_BASE}/api/v1/business-context/rules/preview`,+ const resp = await apiFetch(+ `/api/v1/business-context/rules/preview`,{method: "POST",headers: authHeaders(),diff --git a/apps/web/src/components/audit/AuditLogView.test.tsx b/apps/web/src/components/audit/AuditLogView.test.tsxindex 5a8135271..0e6647bda 100644--- a/apps/web/src/components/audit/AuditLogView.test.tsx+++ b/apps/web/src/components/audit/AuditLogView.test.tsx@@ -46,6 +46,10 @@ vi.mock('@/lib/api', () => ({exportCsv: exportCsvMock,exportHtml: exportHtmlMock,},+ // The view's SWR fetcher. It used to be a module-local arrow that called+ // `fetch(url, { credentials: 'include' })`, i.e. no credential the API+ // reads; SWR itself is mocked below, so this only has to exist.+ authedFetcher: vi.fn(),}));const toastSuccess = vi.hoisted(() => vi.fn());diff --git a/apps/web/src/components/audit/AuditLogView.tsx b/apps/web/src/components/audit/AuditLogView.tsxindex d1fc9c86d..85d010b32 100644--- a/apps/web/src/components/audit/AuditLogView.tsx+++ b/apps/web/src/components/audit/AuditLogView.tsx@@ -5,7 +5,7 @@ import useSWR from 'swr';import toast from 'react-hot-toast';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';import { ErrorState } from '@/components/ui/ErrorState';-import { auditApi, ApiError, type AuditExportFilters } from '@/lib/api';+import { ApiError, auditApi, authedFetcher, type AuditExportFilters } from '@/lib/api';import { demoFallback } from '@/lib/demoFallback';interface AuditEvent {@@ -29,13 +29,6 @@ interface AuditListResponse {total_pages: number;}-const fetcher = async (url: string) => {- const r = await fetch(url, { credentials: 'include' });- if (!r.ok) throw new Error(`HTTP ${r.status}`);- const text = await r.text();- try { return JSON.parse(text); } catch { throw new Error('Invalid JSON'); }-};-const MOCK_AUDIT: AuditListResponse = {items: [{ id: '1', tenant_id: 't1', actor_id: 'u1', actor_email: '[email protected]', actor_ip: '10.0.1.12', action: 'cases:create', resource: 'case', resource_id: 'c-0001abcd', changes: { title: 'Suspicious lateral movement' }, created_at: new Date(Date.now() - 300_000).toISOString() },@@ -87,7 +80,7 @@ export function AuditLogView() {const { data: raw, error, isLoading } = useSWR<AuditListResponse>(`/api/v1/audit?${params}`,- fetcher,+ authedFetcher,{refreshInterval: 30_000,fallbackData: demoFallback(MOCK_AUDIT),diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsxindex a59e6e687..5c13f5be3 100644--- a/apps/web/src/components/cases/CaseWorkspace.tsx+++ b/apps/web/src/components/cases/CaseWorkspace.tsx@@ -24,19 +24,7 @@ import useSWR from 'swr';import { clsx } from 'clsx';import { format, formatDistanceToNow } from 'date-fns';import toast from 'react-hot-toast';-import {- casesApi,- graphApi,- realtimeApi,- type AttackChainTimeline,- type AttackChainWindow,- type Case,- type CaseAttackPath,- type CaseSeverity,- type CaseStatus,- type CaseTask,- type CaseTimelineEvent,-} from '@/lib/api';+import { apiFetch, type AttackChainTimeline, type AttackChainWindow, type Case, type CaseAttackPath, casesApi, type CaseSeverity, type CaseStatus, type CaseTask, type CaseTimelineEvent, graphApi, realtimeApi } from '@/lib/api';import { Skeleton } from '@/components/ui/Skeleton';import { ErrorState } from '@/components/ui/ErrorState';import { EmptyState } from '@/components/ui/EmptyState';@@ -406,7 +394,7 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {setInvestigating(false);toast.success('Investigation complete — report ready');// Fetch the Markdown report- fetch(`/api/v1/cases/${caseId}/investigations/${runId}/report.md`)+ apiFetch(`/api/v1/cases/${caseId}/investigations/${runId}/report.md`).then((r) => r.ok ? r.text() : '').then((md) => { if (md) setReportMd(md); }).catch(() => { /* best-effort */ });@@ -462,7 +450,7 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {if (inv.status === 'completed') {toast.success('Investigation complete — report ready');try {- const resp = await fetch(`/api/v1/cases/${caseId}/investigations/${result.run_id}/report.md`);+ const resp = await apiFetch(`/api/v1/cases/${caseId}/investigations/${result.run_id}/report.md`);if (resp.ok) setReportMd(await resp.text());} catch { /* best-effort */ }} else {diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsxindex 934635582..769e74cab 100644--- a/apps/web/src/components/cases/CasesView.tsx+++ b/apps/web/src/components/cases/CasesView.tsx@@ -139,28 +139,19 @@ function CaseCard({ c }: { c: Case }) {type FilterStatus = Case['status'] | 'all';-interface CasesViewProps {- /**- * Optional pre-fetched cases from a Server Component. When provided, these- * are rendered on first paint (no flash of mock data) and SWR revalidates- * in the background. When omitted (e.g. dev/local without API access),- * deterministic mock data is used so the layout stays stable for SSR.- */- initialCases?: CasesResponse;-}--export function CasesView({ initialCases }: CasesViewProps = {}) {+export function CasesView() {const [statusFilter, setStatusFilter] = useState<FilterStatus>('all');const [severityFilter, setSeverityFilter] = useState<Case['severity'] | 'all'>('all');const [search, setSearch] = useState('');- // Real server-rendered cases are not sample data, and the gate that- // withholds one must not withhold the other. Folding both into a single- // `fallback` and passing that through `demoFallback` returned `undefined`- // outside the hosted demo *regardless of whether SSR data was supplied* —- // so the server fetch in `cases/page.tsx` was made, awaited and discarded- // on every non-demo deployment, which is the flash of empty content the- // prop exists to prevent.+ // This view took an `initialCases` prop fed by a server-side fetch in+ // `cases/page.tsx`. That fetch sent no credential and a build-time tenant+ // id, so it returned one fixed tenant's cases to whoever loaded the page,+ // and it only returned anything at all because an uncredentialed request+ // resolved to a demo administrator. A server render has no session to+ // borrow, so it was removed rather than repaired; the list now loads+ // through the credentialed client on mount, under the caller's own+ // identity.const sampleCases = demoFallback<CasesResponse>({cases: MOCK_CASES,total: MOCK_CASES.length,@@ -172,10 +163,7 @@ export function CasesView({ initialCases }: CasesViewProps = {}) {['cases', statusFilter, severityFilter],() => casesApi.list({ status: statusFilter !== 'all' ? statusFilter : undefined }),{- fallbackData: initialCases ?? sampleCases,- // Supplying `fallbackData` is enough to stop SWR revalidating on mount,- // which would turn the SSR snapshot into what the view permanently- // shows rather than its first paint.+ fallbackData: sampleCases,revalidateOnMount: true,});diff --git a/apps/web/src/components/cases/CasesViewSsr.test.tsx b/apps/web/src/components/cases/CasesViewSsr.test.tsxindex 8dc7ef4fa..2c1cf2f6f 100644--- a/apps/web/src/components/cases/CasesViewSsr.test.tsx+++ b/apps/web/src/components/cases/CasesViewSsr.test.tsx@@ -1,15 +1,19 @@/**- * The server fetch in `cases/page.tsx` must survive into the first paint.+ * The fabricated case list stays withheld outside the hosted demo.*- * `initialCases` is documented as server-rendered data that avoids a flash of- * mock content. It was folded into the same `fallback` object as `MOCK_CASES`- * and the whole thing passed through `demoFallback(fallback)` — which returns- * `undefined` outside the hosted demo *regardless of whether real SSR data- * was supplied*. So on every non-demo deployment the server round-trip was- * made, awaited, and then discarded.+ * This file used to assert that an `initialCases` prop, fed by a server-side+ * fetch in `cases/page.tsx`, survived into the first paint. That fetch sent+ * no credential and a build-time tenant id, so it served one fixed tenant's+ * cases to whoever loaded the page and only returned anything because an+ * uncredentialed request resolved to a demo administrator. It was removed,+ * and with it the prop: a server render has no session to borrow, so there+ * was no authenticated version of that call to keep.*- * Real SSR data is not sample data, and the gate that withholds one must not- * withhold the other.+ * What still matters, and is what this file now covers, is the direction that+ * has a production path: `demoFallback` must hand SWR the sample list inside+ * the hosted demo and nothing at all outside it. Folding real data and sample+ * data into one object and passing the pair through `demoFallback` is how+ * that gate got confused once already.*/import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';@@ -53,28 +57,8 @@ vi.mock('@/components/saved-views/SavedViewsBar', () => ({import { CasesView } from './CasesView';-const SSR_CASES: CasesResponse = {- cases: [- {- id: 'case-ssr-1',- title: 'Server-rendered case from the API',- status: 'open',- severity: 'high',- alertCount: 2,- createdAt: '2026-05-06T09:00:00Z',- updatedAt: '2026-05-06T09:30:00Z',- tags: [],- },- ],- total: 1,- page: 1,- pageSize: 1,-} as CasesResponse;--/** Titles only `MOCK_CASES` carries. */const FABRICATED_TITLES = ['Ransomware incident on finance workstations',- 'Suspected APT lateral movement campaign','Cryptominer on dev server cluster',];@@ -89,14 +73,8 @@ afterEach(() => {__setDemoModeForTests(null);});-describe('server-rendered cases are not discarded outside demo mode', () => {- it('renders the SSR payload on first paint', () => {- render(<CasesView initialCases={SSR_CASES} />);-- expect(screen.getByText('Server-rendered case from the API')).toBeTruthy();- });-- it('still withholds the fabricated list when no SSR data was supplied', () => {+describe('the fabricated case list is withheld outside demo mode', () => {+ it('renders none of the sample titles', () => {render(<CasesView />);for (const title of FABRICATED_TITLES) {@@ -107,16 +85,16 @@ describe('server-rendered cases are not discarded outside demo mode', () => {}});- it('never hands the fabricated list to SWR as real SSR data', () => {- render(<CasesView initialCases={SSR_CASES} />);+ it('hands SWR no fallback at all, rather than a fabricated one', () => {+ render(<CasesView />);- const supplied = [...swrFallbacks.values()].find(Boolean) as CasesResponse | undefined;- expect(supplied?.cases?.[0]?.title).toBe('Server-rendered case from the API');+ const supplied = [...swrFallbacks.values()] as (CasesResponse | undefined)[];+ expect(supplied.every((value) => value === undefined)).toBe(true);});});describe('the hosted demo is still populated', () => {- it('shows the sample list when the build is the demo and there is no SSR data', () => {+ it('shows the sample list when the build is the demo', () => {__setDemoModeForTests(true);render(<CasesView />);diff --git a/apps/web/src/components/compliance/ComplianceHeatmap.tsx b/apps/web/src/components/compliance/ComplianceHeatmap.tsxindex 22e6ca890..96b8a4c60 100644--- a/apps/web/src/components/compliance/ComplianceHeatmap.tsx+++ b/apps/web/src/components/compliance/ComplianceHeatmap.tsx@@ -1,6 +1,7 @@'use client';import useSWR from 'swr';+import { authedFetcher } from '@/lib/api';interface HeatmapCell {category: string;@@ -41,11 +42,6 @@ function intensityClass(count: number, max: number): string {return 'opacity-100';}-const fetcher = (url: string) =>- fetch(url).then((r) => {- if (!r.ok) throw new Error(`HTTP ${r.status}`);- return r.json();- });interface Props {framework: string;@@ -54,7 +50,7 @@ interface Props {export function ComplianceHeatmap({ framework }: Props) {const { data, error, isLoading } = useSWR<HeatmapData>(`/api/v1/compliance/${framework}/heatmap`,- fetcher,+ authedFetcher,{ refreshInterval: 60_000 });diff --git a/apps/web/src/components/compliance/FrameworkView.tsx b/apps/web/src/components/compliance/FrameworkView.tsxindex 2b7173123..ab210074d 100644--- a/apps/web/src/components/compliance/FrameworkView.tsx+++ b/apps/web/src/components/compliance/FrameworkView.tsx@@ -4,6 +4,7 @@ import useSWR, { mutate } from 'swr';import { useState } from 'react';import { ComplianceHeatmap } from './ComplianceHeatmap';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';+import { apiFetch } from '@/lib/api';interface Evidence {id: string;@@ -82,7 +83,7 @@ export function FrameworkView({ framework }: Props) {async function handleCollect() {setCollecting(true);try {- const res = await fetch(`/api/v1/compliance/${framework}/collect`, {+ const res = await apiFetch(`/api/v1/compliance/${framework}/collect`, {method: 'POST',});if (!res.ok) throw new Error(`HTTP ${res.status}`);@@ -96,7 +97,7 @@ export function FrameworkView({ framework }: Props) {async function handleExport() {setExporting(true);try {- const res = await fetch(`/api/v1/compliance/${framework}/export`);+ const res = await apiFetch(`/api/v1/compliance/${framework}/export`);if (!res.ok) throw new Error(`HTTP ${res.status}`);const exportData = await res.json();diff --git a/apps/web/src/components/compliance/SOC2View.tsx b/apps/web/src/components/compliance/SOC2View.tsxindex 980c5b666..798c8277b 100644--- a/apps/web/src/components/compliance/SOC2View.tsx+++ b/apps/web/src/components/compliance/SOC2View.tsx@@ -2,6 +2,7 @@import { useState } from 'react';import useSWR from 'swr';+import { apiFetch, authedFetcher } from '@/lib/api';interface ControlOut {id: string;@@ -42,11 +43,6 @@ interface SOC2Response {controls: ControlWithEvidence[];}-const fetcher = (url: string) =>- fetch(url, { credentials: 'include' }).then((r) => {- if (!r.ok) throw new Error('Failed to fetch');- return r.json();- });const STATUS_STYLES: Record<string, string> = {collected: 'bg-green-100 text-green-800 border-green-200',@@ -92,14 +88,14 @@ export function SOC2View() {const { data, error, isLoading, mutate } = useSWR<SOC2Response>('/api/v1/compliance/soc2',- fetcher,+ authedFetcher,{ revalidateOnFocus: false });const handleCollect = async () => {setCollecting(true);try {- await fetch('/api/v1/compliance/soc2/collect', {+ await apiFetch('/api/v1/compliance/soc2/collect', {method: 'POST',credentials: 'include',});@@ -112,7 +108,7 @@ export function SOC2View() {const handleExport = async () => {setExporting(true);try {- const res = await fetch('/api/v1/compliance/soc2/export', { credentials: 'include' });+ const res = await apiFetch('/api/v1/compliance/soc2/export', { credentials: 'include' });if (!res.ok) throw new Error(`HTTP ${res.status}`);const json = await res.json();// Generate a printable HTML page for PDF exportdiff --git a/apps/web/src/components/detections/DetectionCatalog.tsx b/apps/web/src/components/detections/DetectionCatalog.tsxindex c36fb96ed..7723b1a7c 100644--- a/apps/web/src/components/detections/DetectionCatalog.tsx+++ b/apps/web/src/components/detections/DetectionCatalog.tsx@@ -3,6 +3,7 @@import { useState, useEffect } from 'react';import clsx from 'clsx';import { canUseDemoData } from '@/lib/demoFallback';+import { apiFetch } from '@/lib/api';// ── Types ─────────────────────────────────────────────────────────────────────@@ -95,7 +96,7 @@ function DetectionCard({ rule }: { rule: DetectionRule }) {e.stopPropagation();setInstalling(true);try {- await fetch(`/api/v1/community/detections/${rule.id}/install`, { method: 'POST' });+ await apiFetch(`/api/v1/community/detections/${rule.id}/install`, { method: 'POST' });setInstalled(true);} catch {// ignore@@ -111,7 +112,7 @@ function DetectionCard({ rule }: { rule: DetectionRule }) {}setLoadingDetail(true);try {- const res = await fetch(`/api/v1/community/detections/${rule.id}`);+ const res = await apiFetch(`/api/v1/community/detections/${rule.id}`);if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);const data = await res.json();setDetail(data.sigma_yaml ?? 'No content available');@@ -241,7 +242,7 @@ export function DetectionCatalog() {if (product !== 'all') params.set('logsource_product', product);if (level !== 'all') params.set('level', level);- const res = await fetch(`/api/v1/community/detections?${params}`);+ const res = await apiFetch(`/api/v1/community/detections?${params}`);if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);const data: DetectionListResponse = await res.json();setRules(data.items ?? []);diff --git a/apps/web/src/components/marketplace/MarketplaceView.test.tsx b/apps/web/src/components/marketplace/MarketplaceView.test.tsxindex 2b71af7af..19ee9ba9c 100644--- a/apps/web/src/components/marketplace/MarketplaceView.test.tsx+++ b/apps/web/src/components/marketplace/MarketplaceView.test.tsx@@ -59,6 +59,7 @@ beforeEach(() => {afterEach(() => {vi.restoreAllMocks();+ window.localStorage.clear();});describe('MarketplaceView install flow', () => {@@ -72,12 +73,16 @@ describe('MarketplaceView install flow', () => {expect(screen.getByRole('button', { name: /^install$/i })).toBeInTheDocument();});- it('POSTs to /api/v1/marketplace/install when the user clicks Install', async () => {+ it('POSTs to /api/v1/marketplace/install with the caller credential', async () => {const fetchMock = vi.fn(async (): Promise<Response> =>new Response(JSON.stringify({ ok: true }), { status: 200 }),);vi.stubGlobal('fetch', fetchMock);+ // The install used to go out as a bare `fetch` with `credentials:+ // 'include'`, which sends cookies the API does not read. It succeeded+ // only where an uncredentialed request resolved to a demo administrator.+ window.localStorage.setItem('aisoc.responder.accessToken', 'test-token');render(<MarketplaceView />);@@ -88,8 +93,10 @@ describe('MarketplaceView install flow', () => {'/api/v1/marketplace/install',expect.objectContaining({method: 'POST',- headers: { 'Content-Type': 'application/json' },- credentials: 'include',+ headers: expect.objectContaining({+ 'Content-Type': 'application/json',+ Authorization: 'Bearer test-token',+ }),}),);});diff --git a/apps/web/src/components/marketplace/MarketplaceView.tsx b/apps/web/src/components/marketplace/MarketplaceView.tsxindex b52d9328e..bcd6713e9 100644--- a/apps/web/src/components/marketplace/MarketplaceView.tsx+++ b/apps/web/src/components/marketplace/MarketplaceView.tsx@@ -6,7 +6,7 @@ import clsx from 'clsx';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';import { ErrorState } from '@/components/ui/ErrorState';import { formatTagLabel } from './tagLabel';-import { AUTH_TOKEN_KEY } from '@/lib/api';+import { apiFetch, AUTH_TOKEN_KEY } from '@/lib/api';// ── Types ────────────────────────────────────────────────────────────────────@@ -596,7 +596,7 @@ export function MarketplaceView() {return next;});try {- const res = await fetch('/api/v1/marketplace/install', {+ const res = await apiFetch('/api/v1/marketplace/install', {method: 'POST',headers: { 'Content-Type': 'application/json', ...authHeaders() },credentials: 'include',diff --git a/apps/web/src/components/playbooks/DraftFromPromptDialog.tsx b/apps/web/src/components/playbooks/DraftFromPromptDialog.tsxindex d3ad8d636..ac63a2dc0 100644--- a/apps/web/src/components/playbooks/DraftFromPromptDialog.tsx+++ b/apps/web/src/components/playbooks/DraftFromPromptDialog.tsx@@ -33,6 +33,7 @@import React, { useCallback, useEffect, useRef, useState } from 'react';import { useRouter } from 'next/navigation';import type { Playbook } from './types';+import { apiFetch } from '@/lib/api';const SUGGESTIONS: { label: string; prompt: string }[] = [{@@ -95,7 +96,7 @@ export function DraftFromPromptDialog({ open, onClose }: DraftFromPromptDialogPrsetBusy(true);setError(null);try {- const resp = await fetch('/api/v1/playbooks/draft-from-nl', {+ const resp = await apiFetch('/api/v1/playbooks/draft-from-nl', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ prompt: trimmed, allow_llm: true }),diff --git a/apps/web/src/components/playbooks/PlaybookEditor.tsx b/apps/web/src/components/playbooks/PlaybookEditor.tsxindex 80cfe5954..da4cc8c3f 100644--- a/apps/web/src/components/playbooks/PlaybookEditor.tsx+++ b/apps/web/src/components/playbooks/PlaybookEditor.tsx@@ -27,6 +27,7 @@ import { STEP_TYPE_META } from './stepColors';import { AUTHORABLE_STEP_TYPES, defaultParamsFor } from './stepSchemas';import { ContextualActions } from '@/components/copilot/ContextualActions';import { useHistoryState } from '@/hooks/useHistoryState';+import { apiFetch, authedFetcher } from '@/lib/api';/*** What the palette offers. Derived from the registry, and filtered on@@ -53,11 +54,6 @@ function makeNewStep(type: StepType): PlaybookStep {};}-const fetcher = (url: string) =>- fetch(url).then((r) => {- if (!r.ok) throw new Error('Failed to fetch');- return r.json();- });/* ───────────────────────────── Trigger editor ───────────────────────────── */@@ -112,7 +108,7 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {const { data: remote, isLoading } = useSWR<Playbook>(!isNew ? `/api/v1/playbooks/${playbookId}` : null,- fetcher,+ authedFetcher,);const [playbook, history] = useHistoryState<Playbook>(EMPTY_PLAYBOOK);@@ -274,7 +270,7 @@ export function PlaybookEditor({ playbookId }: PlaybookEditorProps) {setRunning(true);setRunResult(null);try {- const res = await fetch(`/api/v1/playbooks/${playbook.id}/run`, {+ const res = await apiFetch(`/api/v1/playbooks/${playbook.id}/run`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ context: {}, dry_run: true }),diff --git a/apps/web/src/components/playbooks/PlaybooksView.tsx b/apps/web/src/components/playbooks/PlaybooksView.tsxindex 526e6dc7c..a8e159b62 100644--- a/apps/web/src/components/playbooks/PlaybooksView.tsx+++ b/apps/web/src/components/playbooks/PlaybooksView.tsx@@ -24,7 +24,8 @@ import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar';import { DraftFromPromptDialog } from './DraftFromPromptDialog';import { demoFallback } from '@/lib/demoFallback';import { FailureBanner } from '@/components/ui/FailureBanner';-import { describeApiFailure, jsonFetcher } from '@/lib/failure';+import { describeApiFailure } from '@/lib/failure';+import { apiFetch, authedFetcher } from '@/lib/api';/** Filter snapshot stored by the backend as a saved-view preset. */type PlaybookFilterSnapshot = PlaybookGalleryFilters;@@ -41,7 +42,6 @@ const DEFAULT_PLAYBOOK_FILTERS: PlaybookFilterSnapshot = {// Was `throw new Error('Failed to fetch')` — the status was discarded// entirely, so neither banner below it could say anything more specific than// "unavailable", and both guessed at a cause.-const fetcher = jsonFetcher;/* ─────────────────────────── Run History Tab ─────────────────────────── */@@ -56,7 +56,7 @@ const STATUS_BADGE: Record<string, string> = {function RunHistoryTab() {const { data, isLoading, error, mutate } = useSWR<PlaybookRun[]>('/api/v1/playbooks/runs?limit=100',- fetcher,+ authedFetcher,{ refreshInterval: 10000 });if (isLoading) return <div className="py-10 text-center text-gray-600 text-sm">Loading run history…</div>;@@ -151,7 +151,7 @@ function CommunityPlaybooksTab() {try {const params = new URLSearchParams({ page: String(p), page_size: String(PAGE_SIZE), sort_by: sort });if (q) params.set('search', q);- const res = await fetch(`/api/v1/community/playbooks?${params}`);+ const res = await apiFetch(`/api/v1/community/playbooks?${params}`);if (!res.ok) throw new Error(`HTTP ${res.status}`);const data = await res.json();setItems(data.items ?? []);@@ -176,7 +176,7 @@ function CommunityPlaybooksTab() {setSubmitResult('Invalid JSON. Please fix and retry.');return;}- const res = await fetch('/api/v1/community/playbooks/submit', {+ const res = await apiFetch('/api/v1/community/playbooks/submit', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),@@ -349,7 +349,7 @@ function CommunityPlaybookCard({ playbook }: { playbook: CommunityPlaybook }) {const handleInstall = async () => {setInstalling(true);try {- await fetch(`/api/v1/community/playbooks/${playbook.id}/install`, { method: 'POST' });+ await apiFetch(`/api/v1/community/playbooks/${playbook.id}/install`, { method: 'POST' });setInstalled(true);} catch { /* ignore */ } finally {setInstalling(false);@@ -422,7 +422,7 @@ const MOCK_PLAYBOOKS: Playbook[] = [export function PlaybooksView() {const [tab, setTab] = useState<'playbooks' | 'runs' | 'community'>('playbooks');- const { data, isLoading, error, mutate } = useSWR<Playbook[]>('/api/v1/playbooks', fetcher, {+ const { data, isLoading, error, mutate } = useSWR<Playbook[]>('/api/v1/playbooks', authedFetcher, {refreshInterval: 30000,fallbackData: demoFallback(MOCK_PLAYBOOKS),});diff --git a/apps/web/src/components/playbooks/packHelpers.ts b/apps/web/src/components/playbooks/packHelpers.tsindex a9964de74..5abe4c67b 100644--- a/apps/web/src/components/playbooks/packHelpers.ts+++ b/apps/web/src/components/playbooks/packHelpers.ts@@ -24,6 +24,7 @@*/import type { Playbook, StepType } from './types';+import { apiFetch } from '@/lib/api';const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -383,7 +384,7 @@ export async function forkPlaybook(opts?: { author?: string },): Promise<Playbook> {const body = buildForkBody(original, opts);- const res = await fetch('/api/v1/playbooks', {+ const res = await apiFetch('/api/v1/playbooks', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),diff --git a/apps/web/src/components/playbooks/rowActions.tsx b/apps/web/src/components/playbooks/rowActions.tsxindex 403e9da07..b29b218fc 100644--- a/apps/web/src/components/playbooks/rowActions.tsx+++ b/apps/web/src/components/playbooks/rowActions.tsx@@ -11,6 +11,7 @@import React, { useState } from 'react';import { mutate } from 'swr';import type { Playbook } from './types';+import { apiFetch } from '@/lib/api';/** Small toggle that flips Playbook.enabled via PUT /api/v1/playbooks/<id>. */export function EnabledToggle({ playbook }: { playbook: Playbook }) {@@ -18,7 +19,7 @@ export function EnabledToggle({ playbook }: { playbook: Playbook }) {async function toggle() {setLoading(true);try {- await fetch(`/api/v1/playbooks/${playbook.id}`, {+ await apiFetch(`/api/v1/playbooks/${playbook.id}`, {method: 'PUT',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ enabled: !playbook.enabled }),@@ -54,7 +55,7 @@ export function RunButton({ playbook }: { playbook: Playbook }) {async function run() {setStatus('running');try {- const res = await fetch(`/api/v1/playbooks/${playbook.id}/run`, {+ const res = await apiFetch(`/api/v1/playbooks/${playbook.id}/run`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ context: {}, dry_run: true }),@@ -89,6 +90,6 @@ export function RunButton({ playbook }: { playbook: Playbook }) {/** Delete a playbook (used only for user-created playbooks, not shipped packs). */export async function deletePlaybook(id: string) {if (!confirm('Delete this playbook?')) return;- await fetch(`/api/v1/playbooks/${id}`, { method: 'DELETE' });+ await apiFetch(`/api/v1/playbooks/${id}`, { method: 'DELETE' });await mutate('/api/v1/playbooks');}diff --git a/apps/web/src/components/settings/RBACView.tsx b/apps/web/src/components/settings/RBACView.tsxindex 27b1b3b2e..947eabd08 100644--- a/apps/web/src/components/settings/RBACView.tsx+++ b/apps/web/src/components/settings/RBACView.tsx@@ -5,7 +5,8 @@ import useSWR, { mutate } from 'swr';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';import { demoFallback } from '@/lib/demoFallback';import { FailureBanner } from '@/components/ui/FailureBanner';-import { describeApiFailure, jsonFetcher } from '@/lib/failure';+import { describeApiFailure } from '@/lib/failure';+import { apiFetch, authedFetcher } from '@/lib/api';interface Permission {id: string;@@ -25,7 +26,6 @@ interface Role {// Throws `ApiError`, so the banner below can tell a 403 (this operator cannot// read roles) from a 500 (the API is broken) from a 422 (the console is).-const fetcher = jsonFetcher;const CATEGORY_COLORS: Record<string, string> = {cases: 'bg-blue-500/20 text-blue-300',@@ -257,10 +257,10 @@ export function RBACView() {data: roles,error: rolesError,mutate: reloadRoles,- } = useSWR<Role[]>('/api/v1/rbac/roles', fetcher, {+ } = useSWR<Role[]>('/api/v1/rbac/roles', authedFetcher, {fallbackData: demoFallback(MOCK_ROLES),});- const { data: permissions } = useSWR<Permission[]>('/api/v1/rbac/permissions', fetcher, {+ const { data: permissions } = useSWR<Permission[]>('/api/v1/rbac/permissions', authedFetcher, {fallbackData: demoFallback(MOCK_PERMISSIONS),});@@ -269,7 +269,7 @@ export function RBACView() {const handleDelete = async (role: Role) => {if (!confirm(`Delete role "${role.name}"?`)) return;- await fetch(`/api/v1/rbac/roles/${role.id}`, { method: 'DELETE' });+ await apiFetch(`/api/v1/rbac/roles/${role.id}`, { method: 'DELETE' });mutate('/api/v1/rbac/roles');};diff --git a/apps/web/src/components/sla/SLADashboard.tsx b/apps/web/src/components/sla/SLADashboard.tsxindex 29f08c14e..10f731572 100644--- a/apps/web/src/components/sla/SLADashboard.tsx+++ b/apps/web/src/components/sla/SLADashboard.tsx@@ -3,17 +3,7 @@import { useState } from 'react';import useSWR, { mutate } from 'swr';import { demoFallback } from '@/lib/demoFallback';--const fetcher = async (url: string) => {- const r = await fetch(url);- if (!r.ok) throw new Error(`HTTP ${r.status}`);- const text = await r.text();- try {- return JSON.parse(text);- } catch {- throw new Error('Invalid JSON');- }-};+import { apiFetch, authedFetcher } from '@/lib/api';interface SeverityMetrics {total: number;@@ -130,7 +120,7 @@ function EditConfigModal({const save = async () => {setSaving(true);- await fetch(`/api/v1/sla/config/${config.severity}`, {+ await apiFetch(`/api/v1/sla/config/${config.severity}`, {method: 'PUT',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ mttd_target: mttd, mttr_target: mttr, mttc_target: mttc }),@@ -202,7 +192,7 @@ function EditKpiBarModal({setErr(null);setSaving(true);try {- const res = await fetch('/api/v1/sla/kpi-targets', {+ const res = await apiFetch('/api/v1/sla/kpi-targets', {method: 'PUT',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -440,7 +430,7 @@ export function SLADashboard() {const { data: rawMetrics, error: metricsError, mutate: refetchMetrics } = useSWR<SLAMetrics>(`/api/v1/sla/metrics?days=${days}`,- fetcher,+ authedFetcher,{refreshInterval: 60_000,fallbackData: demoFallback(MOCK_SLA_METRICS),@@ -461,7 +451,7 @@ export function SLADashboard() {// and a 42.5m MTTR rendered in both, on every deployment, identically.const metrics = isValidMetrics ? rawMetrics : undefined;- const { data: configs } = useSWR<SLAConfig[]>('/api/v1/sla/config', fetcher, {+ const { data: configs } = useSWR<SLAConfig[]>('/api/v1/sla/config', authedFetcher, {fallbackData: demoFallback(MOCK_SLA_CONFIGS),shouldRetryOnError: false,errorRetryCount: 0,diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex a0bfb9ba5..3e681e39e 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -154,6 +154,40 @@ export class ApiError extends Error {}}+/**+ * The headers every console call to an AiSOC API must carry.+ *+ * Exported because not every call can go through {@link apiRequest}: the+ * NDJSON and SSE endpoints need the raw `Response` so the caller can read+ * `response.body`. Those five call sites used to build their own header+ * object, and every one of them sent `X-Tenant-Id` and no token — which+ * reads like an identity and is not one. The API authenticates a bearer+ * token; a tenant header is a caller-supplied claim.+ *+ * `X-Tenant-Id` resolves at call time so the tenant switcher applies to the+ * very next request without a page reload.+ */+export function apiHeaders(extra?: HeadersInit): Record<string, string> {+ const headers: Record<string, string> = {+ 'Content-Type': 'application/json',+ 'X-Tenant-Id': getActiveTenantId(),+ ...(extra as Record<string, string> | undefined),+ };++ if (typeof window !== 'undefined') {+ try {+ if (!headers.Authorization && !headers.authorization) {+ const token = window.localStorage.getItem(AUTH_TOKEN_KEY);+ if (token) headers.Authorization = `Bearer ${token}`;+ }+ } catch {+ /* localStorage unavailable; ignore */+ }+ }++ return headers;+}+async function request<T>(path: string, options: FetchOptions = {}): Promise<T> {const { params, baseUrl, ...fetchOptions } = options;@@ -169,32 +203,7 @@ async function request<T>(path: string, options: FetchOptions = {}): Promise<T>if (qs) url += `?${qs}`;}- const headers: HeadersInit = {- 'Content-Type': 'application/json',- // Resolve at call-time so the tenant switcher takes effect on the very- // next fetch (no full page reload needed).- 'X-Tenant-Id': getActiveTenantId(),- ...fetchOptions.headers,- };-- // Mobile responder PWA auth: if a passkey-issued JWT is present in- // localStorage, attach it as a Bearer token. The desktop console relies on- // cookies set by the API gateway, so this is purely additive.- if (typeof window !== 'undefined') {- try {- const existing =- (headers as Record<string, string>).Authorization ??- (headers as Record<string, string>).authorization;- if (!existing) {- const token = window.localStorage.getItem('aisoc.responder.accessToken');- if (token) {- (headers as Record<string, string>).Authorization = `Bearer ${token}`;- }- }- } catch {- /* localStorage unavailable; ignore */- }- }+ const headers = apiHeaders(fetchOptions.headers);let response: Response;try {@@ -222,10 +231,61 @@ async function request<T>(path: string, options: FetchOptions = {}): Promise<T>if (response.status === 204) return {} as T;// Some endpoints (the agent stream, NDJSON) might not be JSON. Callers that- // need streams should use fetch() directly. Here we assume JSON.+ // need streams should use fetch() with apiHeaders(). Here we assume JSON.return (await response.json()) as T;}+/**+ * The credentialed JSON client, for calls with no typed wrapper yet.+ *+ * Sixty-one console call sites reached the API with no `Authorization`+ * header, forty-five of them through a bare `fetch(url)`. They worked only+ * because the API resolved a credential-free request to a demo administrator+ * in a development-class environment. Prefer a typed namespace below when one+ * covers the route; reach for this when none does, rather than for `fetch`.+ *+ * `scripts/check_console_auth_headers.py` keeps the class closed.+ */+export async function apiRequest<T>(path: string, options: FetchOptions = {}): Promise<T> {+ return request<T>(path, options);+}++/**+ * SWR fetcher that carries a credential.+ *+ * SWR calls a fetcher as `f(key)`, so a fetcher has nowhere to put options+ * and every single-argument fetcher in this console was anonymous by+ * construction. This one routes through {@link request}, so it also throws+ * {@link ApiError} with the status intact, which `describeApiFailure` needs+ * to tell a console bug from an outage.+ */+export async function authedFetcher<T>(url: string): Promise<T> {+ return request<T>(url);+}++/**+ * A credentialed `fetch` that returns the raw `Response`.+ *+ * For the endpoints whose body is not JSON: NDJSON streams, SSE, PDF and+ * Markdown downloads. Identical to `fetch` except that the credential and+ * tenant headers are not optional.+ */+export async function apiFetch(path: string, options: FetchOptions = {}): Promise<Response> {+ const { params, baseUrl, ...fetchOptions } = options;+ let url = `${baseUrl ?? API_BASE}${path}`;+ if (params) {+ const searchParams = new URLSearchParams();+ Object.entries(params).forEach(([key, value]) => {+ if (value !== undefined && value !== null && value !== '') {+ searchParams.set(key, String(value));+ }+ });+ const qs = searchParams.toString();+ if (qs) url += `?${qs}`;+ }+ return fetch(url, { ...fetchOptions, headers: apiHeaders(fetchOptions.headers), cache: 'no-store' });+}+// ─── Auth ────────────────────────────────────────────────────────────────────export const AUTH_TOKEN_KEY = 'aisoc.responder.accessToken';@@ -328,14 +388,9 @@ export const authApi = {/** Merge user preferences on the server (theme, layout, etc.). */async updateUserPreferences(preferences: Record<string, unknown>): Promise<AuthUser> {- const token = typeof window !== 'undefined'- ? window.localStorage.getItem(AUTH_TOKEN_KEY)- : null;- const headers: Record<string, string> = { 'Content-Type': 'application/json' };- if (token) headers['Authorization'] = `Bearer ${token}`;const response = await fetch(`${API_BASE}/api/v1/auth/me/preferences`, {method: 'PATCH',- headers,+ headers: apiHeaders(),body: JSON.stringify({ preferences }),});if (!response.ok) throw new Error('Failed to update preferences');@@ -1815,7 +1870,7 @@ export const casesApi = {/** Trigger a browser download of the PDF report. */downloadReportPdf: async (caseId: string, runId: string): Promise<void> => {const resp = await fetch(`${API_BASE}/api/v1/cases/${caseId}/investigations/${runId}/report.pdf`, {- headers: { 'X-Tenant-Id': TENANT_ID },+ headers: apiHeaders(),});if (!resp.ok) {const err = await resp.text().catch(() => resp.statusText);@@ -1853,18 +1908,7 @@ export const casesApi = {* report surfaces behave consistently in the PWA.*/openAutoSummaryHtml: async (caseId: string): Promise<void> => {- const headers: Record<string, string> = {- Accept: 'text/html',- 'X-Tenant-Id': TENANT_ID,- };- if (typeof window !== 'undefined') {- try {- const token = window.localStorage.getItem(AUTH_TOKEN_KEY);- if (token) headers.Authorization = `Bearer ${token}`;- } catch {- /* localStorage unavailable; ignore */- }- }+ const headers = apiHeaders({ Accept: 'text/html' });const url = `${API_BASE}/api/v1/cases/${caseId}/summary?format=html`;const response = await fetch(url, { headers, cache: 'no-store' });@@ -3186,10 +3230,7 @@ export const agentsApi = {streamInvestigation: (alertId: string, signal?: AbortSignal) =>fetch(`${AGENTS_BASE}/api/v1/agents/investigate/stream`, {method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-Tenant-Id': TENANT_ID,- },+ headers: apiHeaders(),body: JSON.stringify({ alertId }),signal,}),@@ -3207,14 +3248,11 @@ export const agentsApi = {) =>fetch(`${AGENTS_BASE}/api/v1/explain`, {method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-Tenant-Id': TENANT_ID,- },+ headers: apiHeaders(),body: JSON.stringify({alert: payload.alert,alert_id: payload.alertId,- tenant_id: TENANT_ID,+ tenant_id: getActiveTenantId(),}),signal,}),@@ -4666,10 +4704,7 @@ export const copilotApi = {streamChat: (req: CopilotChatRequest, signal?: AbortSignal) =>fetch(`${API_BASE}/api/v1/copilot/chat/stream`, {method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-Tenant-Id': TENANT_ID,- },+ headers: apiHeaders(),body: JSON.stringify(req),signal,}),@@ -4778,10 +4813,7 @@ export const contextualApi = {stream: (req: ContextualActionRequest, signal?: AbortSignal) =>fetch(`${AGENTS_BASE}/api/v1/contextual/action/stream`, {method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-Tenant-Id': TENANT_ID,- },+ headers: apiHeaders(),body: JSON.stringify(req),signal,}),@@ -5665,18 +5697,7 @@ export const reportsApi = {if (params.period_start) search.set('period_start', params.period_start);if (params.period_end) search.set('period_end', params.period_end);- const headers: Record<string, string> = {- Accept: 'text/html',- 'X-Tenant-Id': TENANT_ID,- };- if (typeof window !== 'undefined') {- try {- const token = window.localStorage.getItem(AUTH_TOKEN_KEY);- if (token) headers.Authorization = `Bearer ${token}`;- } catch {- /* localStorage unavailable; ignore */- }- }+ const headers = apiHeaders({ Accept: 'text/html' });const url = `${API_BASE}/api/v1/reports/digest/weekly?${search.toString()}`;const response = await fetch(url, { headers, cache: 'no-store' });@@ -5915,18 +5936,7 @@ function buildAuditExportSearch(}function buildAuditExportHeaders(accept: string): Record<string, string> {- const headers: Record<string, string> = {- Accept: accept,- 'X-Tenant-Id': TENANT_ID,- };- if (typeof window !== 'undefined') {- try {- const token = window.localStorage.getItem(AUTH_TOKEN_KEY);- if (token) headers.Authorization = `Bearer ${token}`;- } catch {- /* localStorage unavailable; ignore */- }- }+ const headers = apiHeaders({ Accept: accept });return headers;}diff --git a/apps/web/src/lib/failure.test.ts b/apps/web/src/lib/failure.test.tsindex 694bd9cfe..0a991c327 100644--- a/apps/web/src/lib/failure.test.ts+++ b/apps/web/src/lib/failure.test.ts@@ -24,7 +24,7 @@ describe('statusOf', () => {it('parses the status out of the legacy fetchers that only threw a string', () => {// `RBACView` and `PlaybooksView` threw `new Error('HTTP 404')`, and- // `safeFetcher` throws `HTTP 501 Not Implemented — …`. Downgrading those+ // `authedFetcher` throws `ApiError` carrying status 501. Downgrading those// to "unrecognised" would lose the only signal that distinguishes a// console bug from an outage.expect(statusOf(new Error('HTTP 404'))).toBe(404);diff --git a/apps/web/src/lib/failure.ts b/apps/web/src/lib/failure.tsindex dcec6c9c1..b0ff87b31 100644--- a/apps/web/src/lib/failure.ts+++ b/apps/web/src/lib/failure.ts@@ -109,27 +109,3 @@ export function describeApiFailure(error: unknown, subject: FailureSubject): strconst detail = error instanceof Error ? error.message : String(error ?? 'unknown error');return `Could not load the ${what}: ${detail}. ${unknownNotEmpty(what)}`;}--/**- * `fetch` wrapper that throws {@link ApiError} rather than a bare `Error`.- *- * The per-view fetchers this replaces threw `new Error('HTTP 404')`, which- * carried the status in prose only. Callers therefore could not distinguish a- * console bug from an outage without parsing a message, and none of them did —- * they all printed "unreachable".- */-export async function jsonFetcher<T>(url: string): Promise<T> {- let response: Response;- try {- response = await fetch(url);- } catch (err) {- // Status 0 is the transport failing: DNS, TLS, CORS, offline. This is the- // only case where "unreachable" is the honest word.- throw new ApiError(err instanceof Error ? err.message : 'Network request failed', 0, '');- }- if (!response.ok) {- const body = await response.text().catch(() => '');- throw new ApiError(`HTTP ${response.status}`, response.status, body);- }- return (await response.json()) as T;-}diff --git a/apps/web/src/lib/fetcher.ts b/apps/web/src/lib/fetcher.tsdeleted file mode 100644index 09f7ba345..000000000--- a/apps/web/src/lib/fetcher.ts+++ /dev/null@@ -1,8 +0,0 @@-export async function safeFetcher<T = unknown>(url: string): Promise<T> {- const r = await fetch(url);- if (!r.ok) {- const body = await r.text().catch(() => '');- throw new Error(`HTTP ${r.status} ${r.statusText} — ${body.slice(0, 120)}`);- }- return r.json();-}diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 1abe3d16e..ecaed61fa 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -249,10 +249,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| A bind parameter in a raw SQL statement carries the name the handler binds, so the route reaches a connection rather than 500ing on `ArgumentError` | `scripts/check_text_bind_casts.py` (module docstring); the four dead handlers it names | `isolation.yml :: route-scope` (`check_text_bind_casts.py` — an AST pass over every `text()` literal under `services/`, refusing `:name::type` because SQLAlchemy's bind-parameter regex backtracks one character rather than skipping the cast, so `:payload::jsonb` declares `payloa` and the matching `.bindparams()` raises. `--self-test` asserts five things: the injected `:payload::jsonb` is reported, a `::` cast in a *concatenated* statement is reported too, the correct `CAST(:name AS type)` spelling is not, an ARN literal outside a `text()` call is not, and a tree with no Python under `services/` is refused rather than called clean) | GATED | Scoped to statements the AST can see as `text()` arguments, including concatenated ones. A statement whose SQL arrives at runtime from outside the module — a fragment read from a file or assembled by a helper the pass does not follow — is not covered, and the fix everywhere is the standard `CAST(:name AS type)` spelling || Every CI job that grades a service installs what that service's image ships, so CI cannot run a different engine than production | `scripts/check_ci_install_parity.py` (module docstring); `RELEASES.md` | `reproducible-builds.yml :: pin-agreement` (`check_ci_install_parity.py` — for every job running a service's *whole* pytest suite, three directions: a runtime dependency guarded by `except ImportError` that CI does not install, so CI grades the fallback and the image grades the real path; a package CI installs that none of the job's services declares; and a version range disjoint from, wider than, or unbounded against the intersection of what those services declare. 16 self-test cases inject each direction, two controls must not fire, and two refusals cover a tree with nothing to compare. It reported 210 divergences against the commit before it landed) | GATED | The three whole-suite jobs derive their install list from the manifests through `service_requirements.py`, which re-resolves inside the declared ranges rather than installing the locked set — so CI can land on a different patch release than the image. Narrower than a hand-written list, and stated in the script's docstring. Closing it means installing from the lock in CI, at the cost of the pip wheel cache the matrix was built around || A published Helm chart version names one chart forever | `apps/docs/docs/deployment/kubernetes.md` (The chart's version); `infra/helm/aisoc/Chart.yaml` | `helm.yml :: version` + `release.yml :: chart-publish` (`check_chart_version.py` — four checks that need no network: `appVersion` moved while the chart's own `version` did not, any tracked chart file moved with no version bump (with Chart.yaml's own `version:` masked, so the bump cannot justify itself), a version that moved backward, and one chart version declared at two release tags with differing content. Plus one that asks GHCR: the version about to be pushed already exists holding content this tree does not. The registry comparison is on **unpacked files**, because `helm package` is not byte-reproducible — `Chart.yaml` is compared parsed since helm re-serialises it, and the tracked subchart `.tgz` are expanded the way helm expands them, a mapping measured exact against the published 5.9.2 at 146 files. On a release it runs with `--require-network`, before `helm push`, because the push overwrites silently and there is no after. 16 self-test cases, and the gate refuses a checkout with no tags rather than concluding no release ever declared a version) | GATED | **Proven against the pre-fix tree**: at `2db6ce73` (the v13.0.0 release commit) it exits 1 naming `appversion-moved-alone` — `v12.3.2` -> `v13.0.0` with `version` held at 5.9.2 — and exits 0 at `9d3225c6` after the bump to 6.0.0. **Two things it deliberately does not decide.** Whether a bump is the right *size*: nothing in a diff knows if a renamed `values.yaml` key breaks somebody's values file, so the gate enforces forward, never how far. And the overwrite that already happened: republishing replaced the bytes, so the registry's 5.9.2 and the tree that overwrote it are now byte-identical — measured, 146 files, zero differences — which is why the retro-detection reads git rather than the registry, and why the pre-fix proof runs through the baseline check. `5.9.2` and `5.2.0` are recorded in `KNOWN_COLLISIONS` as unrepairable, checked in both directions so an entry that stops being detectable fails |+| Every console call to an AiSOC API carries a credential | `apps/web/src/lib/api.ts` (the credentialed client); `SECURITY.md` (authentication) | `ci.yml :: Python — Lint & Type-check` (`check_console_auth_headers.py` — parses every `fetch(` and `useSWR(` call under `apps/web/src` and requires the credential to be visible on the same expression, so hiding it behind a local `const headers` a few lines up does not count. `X-Tenant-Id` alone and `credentials: 'include'` are both findings, because neither authenticates against a bearer-token API. 15 self-test cases, of which three pin blind spots in the gate's own first draft — a generic type argument hid both real SWR sites, a multi-line arrow fetcher was truncated at the first newline, and an inline fetcher whose URL is the SWR key has no API path at the call site — and four are controls that must not fire. It refuses a tree with no console sources, and separately refuses one where the console makes no API call at all, since a broken matcher and a console that stopped calling the API print the same clean line) | GATED | **Proven against the pre-fix tree**: 61 findings across 21 files at `079fdb69` (45 bare fetches, 16 SWR fetchers), 0 after. One allowlisted exception, the public `/r/<slug>` replay permalink, which is unauthenticated by design and is kept safe by `replay_redaction.py` rather than by a header; the allowlist may only shrink and a stale entry fails the gate. One limit stated rather than implied: the gate reads the console, so it proves the credential is sent, not that the server requires it — `check_route_auth.py` and `check_route_authz.py` are the other half |## Summary-- GATED: 241+- GATED: 242- PARTIAL: 0- NO GATE: 0 (**every claim is backed by a failing test, and none is now a named deferral either.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The last two PARTIAL rows closed with `scripts/check_live_agent_floor.py` and a floor derived from ten runs across two environments, not by relabelling. Recount with `scripts/check_claim_gate_matrix.py` rather than trusting these three numbers: they move weekly, and a count copied into prose goes stale in silence.)diff --git a/plans/aisoc_parity_plan.plan.md b/plans/aisoc_parity_plan.plan.mdnew file mode 100644index 000000000..3598f5a18--- /dev/null+++ b/plans/aisoc_parity_plan.plan.md@@ -0,0 +1,370 @@+# AiSOC parity plan++> **Status**: Locked plan. Implement as specified, do not edit.+> **Captured**: 2026-09-30, against v14.0.0 (commit `079fdb6`).+> **Tracking**: `PARITY_PROGRESS.md` mirrors progress; this file is the source of truth.+> **Relationship**: `plans/aisoc_gap_closure_plan.plan.md` stays locked. Where this plan says "implement gap-closure Phase N as specified", that plan's text governs and this one only adds to it.++### Why this plan exists++A capability review at v14.0.0 compared AiSOC with commercial AI SOC platforms and with SIEM, SOAR and XDR suites. It used the criteria buyers now rank highest: proven verdict accuracy on their own alerts (including false negatives), replayable evidence, governed autonomy, integration coverage and time to value, data control, and the security of the agent itself. AiSOC already owns the mechanisms for the top three: replay evaluation over a customer's closed SIEM alerts, the Investigation Ledger, and capability contracts with dry-run defaults. It also leads on checkable claims. It loses evaluations on four things:++1. **No measured result.** No verdict accuracy, false-positive rate or false-negative rate has been measured on the shipped default model (`llama3.2:3b`) or on any hosted model. The only live floor is groundedness over 10 synthetic incidents on `qwen2.5:0.5b`.+2. **Built but dark.** A large share of the product does not run in the default install:+ - the event lake, entity graph, UEBA and enrichment sit in the `full` profile;+ - tenant tuning never reaches the streaming engine;+ - playbooks never trigger from alerts, and their approval step is unimplemented;+ - earned `auto_close` grants and the console's closure thresholds have no reader;+ - the pseudonymizer is on no LLM path;+ - the hunting agent has no caller.+3. **Docs ahead of code.** Twelve documented capabilities go beyond what the code does.+4. **Missing enterprise gates and 2026 agent table stakes.** SSO does not complete a sign-in. The console has no MFA. Custom roles are honoured at 31 permission checks while about 272 read a static role map. There is no hunting, detection-engineering, custom-agent or phishing-operations agent on the default path, no semantic memory, and the MCP server is stdio-only and deployed by nothing.++The common root cause is that the gates certify functions rather than call paths: a claim row can pass on a unit test of a module nothing imports. This plan therefore makes the gates path-aware first. It then wires, governs and measures what already exists, and only then expands.++Refer to commercial products only neutrally, using the phrases in `scripts/competitor_names.toml`. `scripts/check_competitor_names.py` scans every tracked file, including plan files. Nothing scans PR text or commit messages for competitor names, so check those by hand.++### Rules for every phase++- **Inherited rules.** Every rule in "Rules for every phase" of `plans/aisoc_gap_closure_plan.plan.md` applies here verbatim: claims and gates, tenancy and auth, migrations, LLM calls, state-changing actions, outbound traffic, no fabricated data, CORE footprint, vendor tests, hygiene, eval re-grading, docs and house style.+- **Reproduce before fixing.** Each dark, broken or overclaimed item starts with a test, gate or script that fails on the current tree for the reason stated here. If it does not fail, record a Deviation and move on. Do not "fix" what you cannot reproduce.+- **Path-aware proof.**+ - A claim row this plan adds or touches must be gated by a test that drives the production call path: the worker, route or consumer that actually runs in the deployment, not a unit test of an isolated function.+ - Each such row names the profile it holds in (`core` or `full`).+- **Shipped means default-reachable.** A capability counts as shipped only if it runs under `make up` (CORE), or its claim row says `full` and a gate exercises it there. Opt-in flags are fine; flags that nothing reads are not.+- **Retract first, rebuild later.** Phase 1 narrows or removes each overclaim. A claim comes back only with the PR that makes it true, together with its gate.+- **Authorization.**+ - New routes authenticate (`check_route_auth.py`), and every state-changing route authorizes with an existing permission (`check_route_authz.py`).+ - Never write `Annotated[Any, require_permission(...)]` without `Depends`.+ - When a change lowers the number of routes with no authorization decision, lower `MAX_UNAUTHORIZED` in the same PR.+ - Role and scope grants go through `app.core.role_grants`.+- **Tenancy.**+ - The tenant comes from the credential (`user.tenant_id`, `TenantDBSession`). Any `tenant_id` input goes through `scoped_tenant_or_403`.+ - New tables follow `services/api/migrations/069_mcp_servers.sql`: a `tenant_id` NOT NULL foreign key, `ENABLE` and `FORCE ROW LEVEL SECURITY`, the policy shape `check_rls_policy_shape.py` requires, and explicit grants to `aisoc_app` in a guarded `DO` block.+ - Route modules hold no process-global mutable state.+- **Breaking changes.** Accumulate them under `[Unreleased]` with `### BREAKING`, for one planned major. Do not tag, bump `VERSION` or cut releases; the maintainer does that.+- **Numbers drift.** Re-derive these at build time; never copy them from this plan:+ - the next migration number (076 at capture, with duplicate prefixes present);+ - the next ADR number in `docs/decisions/` (0009 at capture);+ - README length (250 lines against a 250-line cap, so link rather than add);+ - ratchet ceilings (route authz 28 and tenant-predicate exceptions 35 at capture).+- **Stale guidance to ignore.**+ - CONTRIBUTING says Python 3.12, but CI and every image use 3.11.+ - CONTRIBUTING shows a four-tier severity sample, but five tiers are required: `info | low | medium | high | critical`.+ - CONTRIBUTING describes hand-written connector docs, but they are generated.+ - Toolchain: Python 3.11, Node 22, pnpm 8.15.1 with `--frozen-lockfile`, and Go as pinned in each `go.mod`.+- **House style everywhere.**+ - No em dashes in code comments, docs, commit messages or PR bodies. Nothing in CI catches this, so check yourself.+ - Conventional Commits with a scope; `!` plus a `BREAKING CHANGE:` footer when breaking; DCO sign-off (`git commit -s`).+ - No tool or assistant attribution in commits, trailers, PR bodies, code or docs.+- **Local checks before every push.**+ - `python3 scripts/check_attribution.py --commits origin/main..HEAD`.+ - These scripts under `scripts/`: `check_competitor_names.py`, `check_gate_coverage.py`, `check_gate_contract.py`, `check_test_discovery.py`, `check_route_auth.py`, `check_route_authz.py`, `check_route_tenant_scope.py`, `check_tenant_query_predicates.py`, `check_rls_policy_shape.py`, `check_orm_migration_parity.py --check` (without `--check` it only advises and always exits 0), `check_claim_gate_matrix.py`, `check_release_policy.py`, `check_comment_paths.py` and `check_mypy_baseline.py`.+ - `ruff format --check .` and `ruff check services/ scripts/ tests/ tools/`.+ - `pytest` from each touched service directory.+ - `make up && make smoke` for anything on the event path.++### Phase 1: Make every claim true on the default path++**Goal:** nothing a buyer reads in the README, docs, trust pages, roadmap or console is contradicted by a proof of value, and the gates would have caught every item in this phase.++**1.1 Retract or narrow the overclaims.** Edit each claim to match what the code does today, and add a tracker line naming the sub-item that will restore it.++| Claim | Where | Action | Restored by |+|---|---|---|---|+| "Hunting agent + 68-hunt library" ready in `full` | `README.md` maturity table | Narrow to what runs | 6.1 |+| Hosted mode pseudonymizes PII before LLM egress by default; matrix row 19, "no data exfiltration" | `docs/trust/data-flows.md`; `docs/audit/CLAIM_TO_GATE_MATRIX.md` row 19 | Retract the default-on statement; re-gate row 19 on a call-path test or downgrade it | 2.4 |+| Session, working and "institutional (PostgreSQL + pgvector, permanent)" memory | `apps/web/src/components/landing/Features.tsx` | Narrow to the reason-coded memory that exists | 6.5 |+| An `auto_close` grant lets the agent close alerts of that class without a human | `apps/docs/docs/operations/shadow-mode.md` | State that grants are recorded but not yet enforced | 2.1 |+| SAML 2.0 and OIDC for major IdPs, IdP group-to-role mapping, `SAML_IDP_METADATA_URL`, TOTP with backup codes and per-role enforcement | `ROADMAP.md`; `apps/docs/docs/operations/security.md` | Move to planned | 4.1, 4.2 |+| SOC 2 Type II evidence dashboard with PDF export; automated evidence across six frameworks including DORA | `ROADMAP.md`; `apps/docs/docs/intro.md` | Narrow to the 24 controls across 5 frameworks the API maps | 1.3 |+| Shift handoff dashboard, EASM risk scoring, MSSP executive dashboard with ARR, team analytics and gamification | `apps/docs/docs/intro.md` | Remove | None |+| "WCAG AA full accessibility pass" | `ROADMAP.md` | Narrow to the components axe covers | 4.7 |+| EU residency via per-tenant routing, `events_dist`, active-active regions, RPO and RTO targets | `docs/operations/multi-region.md` | Label as a design, not implemented | None |+| GCP KMS and Vault Transit "implement the same protocol" | `services/api/app/security/envelope_cipher.py` docstring | Correct to the backends `get_vault` accepts | None |+| Tenant skills are authored "in YAML in the console editor" | `GAP_CLOSURE_PROGRESS.md` | Correct the tracker line | 6.3 |+| ATT&CK coverage of 493 unique techniques | `marketplace/index.json` and the console coverage matrix | Report executable-rule tag coverage only, labelled as tag coverage | 5.5 |++**1.2 Clear the documentation drift.** Where a count is generated, fix the generator, not its output.+- The `playbooks/` README still says 50 playbooks.+- The hunt scheduler's docstring says default-on while its config says off.+- The detection engine's docstring says rules are indexed by product, but it evaluates the whole corpus.+- The auto-triage docstring names a `/triage/stats` route that does not exist.+- `install.sh` prints "Starting the 10-service CORE stack", and `apps/docs/docs/deployment/walkthrough.mdx` says `make up` starts fifteen CORE services. Take the real count from `docker compose config` for the CORE profile.+- The ClickHouse schema comment says "hot tier - 30 days" over a 90-day TTL.+- The upgrade guide covers only v3 to v4; add at least v10 to v14.+- The gap-closure tracker still marks file analysis as blocked, although v12.0.0 shipped the sandbox providers.+- CONTRIBUTING lists Python 3.12 and a four-tier severity sample.++**1.3 Repair the broken console paths.**+- The `/compliance/[framework]` and `/compliance/soc2` pages call routes that do not exist. The calls come from `FrameworkView.tsx`, `ComplianceHeatmap.tsx` and `SOC2View.tsx` in `apps/web/src/components/compliance/`: seven calls to four route shapes, namely `GET /compliance/{framework}` and, under it, `POST .../collect`, `GET .../export` and `GET .../heatmap`.+ - The existing routes (`services/api/app/api/v1/endpoints/compliance.py`) key frameworks as `SOC2`, `PCI-DSS`, `HIPAA`, `ISO27001` and `NIST-CSF`, not the console's slugs.+ - Point the pages at the existing routes with a slug mapping, or build the missing routes with real rows.+ - Never render a placeholder outside demo mode.+- The `/honeytokens` and `/purple-team` pages (`apps/web/src/app/(app)/honeytokens/page.tsx` and `apps/web/src/app/(app)/purple-team/page.tsx`) have no proxy rewrite and send no credentials. Add rewrites in `apps/web/next.config.js` and move the calls onto the typed `request()` client.+- The case page requests a Markdown report from a route that does not exist. Add the `report.md` route (authenticated, authorized and tenant-scoped) or remove the pane.+- `services/agents/app/main.py` registers two handlers for `GET /api/v1/investigations/{run_id}`. The one registered first reads a different store, so console status polling returns 404. Give each handler a distinct path and update the caller.+- Seven functions in the web API client target routes that do not exist and have no callers. Delete them.++**1.4 Make the gates path-aware.** Each new gate follows the gate contract: it uses `gate_toolkit`, has a `--self-test` that injects a violation, fails closed on an empty tree, prints what it scanned, and is wired into a workflow.+- Add `scripts/check_module_reachability.py`. Every module under `services/*/app` and each package's source tree must have a production importer, an entry point, or an allowlist entry with a written reason. The allowlist may only shrink.+- Extend `scripts/check_route_shadowing.py` to catch identical method and path pairs registered by different routers in one app.+- Extend the mock-data and demo-state gates to Python route modules, covering module-level lists or dicts of sample data reachable outside demo mode. Also check that route modules hold no process-global mutable containers. Skip either check if the tree already has it.+- Extend `scripts/check_claim_gate_matrix.py` so every row declares a profile (`core` or `full`) and names its gate test. Fail a row whose gate test imports a module the reachability gate reports as unreachable.+- Add a console route-contract gate so every `fetch()` or `request()` path in `apps/web/src` resolves to a backend route or a Next.js rewrite. None exists at capture: `scripts/check_ledger_replay_contract.py` covers only the ledger routes, and `scripts/check_sdk_surface.py` covers only the SDKs.++**Done when:**+- Every row in 1.1 is narrowed or retracted, with a tracker pointer.+- The console makes no call to a missing route, and a gate enforces it.+- The reachability gate reports zero unexplained modules.+- In `--self-test`, a deliberately orphaned module, a duplicate route pair, a Python demo list and an unprofiled claim row each fail their gate.++### Phase 2: Govern and protect alert closure++**Goal:** the path that closes alerts without a human obeys per-tenant policy, can be stopped instantly, learns only from humans, and never sends unredacted customer data to a hosted model.++**2.1 Per-tenant, per-class closure policy.** Today three things are wrong:+- closure uses one process-wide threshold (`AISOC_AUTO_CLOSE_THRESHOLD`, default 0.85, in `services/agents/app/agents/auto_triage_agent.py`);+- the only grant reader selects `auto_execute` on action verbs (`services/actions/app/services/tenant_policy.py`);+- the console's per-action thresholds are read only by an unused module (`services/agents/app/policy/guardrails.py`).++To fix it:+- Add a tenant-scoped closure policy table with, per alert class, an enabled flag, a threshold and an earned-grant reference. Make the fused-alert worker (`services/agents/app/workers/fused_alert_consumer.py`) read it together with the evidence-gated `auto_close` grants from shadow mode.+- Keep the global env threshold as the fallback, so the change is additive.+- Wire the console threshold editor to the new table. Delete or wire the unused guardrails path; the reachability gate decides which.++**2.2 Kill switch.** Add a database-backed switch, global and per tenant. The triage worker (closure), the actions dispatcher, playbook dispatch and the MCP write tools all check it before acting.+- Provide a console control and an API behind a dedicated permission, audited, with a reason field.+- Tripping the switch stops closure and dispatch within one poll interval, without a restart.+- Add a claim row gated by an end-to-end test.++**2.3 Learn only from humans.** Outcome priors that suppress repeat alerts (`services/agents/app/memory/outcomes.py`) must come from analyst dispositions.+- Write a human-authored prior whenever an analyst disposes an alert.+- Make the suppression lookup read those priors and the analyst override keys (`override:v2:`, `services/api/app/services/override_learning.py`).+- Stop AI-only priors from suppressing anything without analyst corroboration.+- Every prior carries its author, source alert, scope and expiry.++**2.4 Pseudonymize before hosted egress.**+- Route every hosted-model call through the reversible pseudonymizer (`services/agents/app/privacy/redactor.py`) at the LLM contract layer (`services/agents/app/llm/contract.py` and its API equivalent).+- Add a per-tenant setting: on by default for hosted providers, off for local ones. Re-identify the values in the response.+- Add a call-path gate that fails if any hosted call site bypasses the contract, and re-gate claim row 19 on it.++**2.5 One model path for every LLM call.**+- Per-tenant BYOK today wraps only the triage call and explain. Extend it to escalation, copilot, contextual actions, NL query, NL-to-detection and playbook drafting.+- Some API-service features call a hosted provider directly with an OpenAI key: `services/api/app/api/v1/endpoints/nl_query.py`, `detection_loop.py` (which hardcodes a hosted model id) and the ATT&CK embeddings. Move them onto `aisoc-<role>` gateway aliases (`services/api/app/services/model_aliases.py`, `infra/litellm/config.yaml`, `services/agents/app/llm/model_pins.py`), so they work on the local model in CORE and in air-gap mode.++**2.6 Enforced budgets.**+- Replace the per-process, in-memory budget governor (`services/agents/app/core/cost_governor.py`) with a spend window stored in Postgres and shared across replicas and restarts.+- Enforce per-alert token caps and runner tool-call budgets inside the loop (`services/agents/app/graph/runner.py`), not after it.+- An over-budget investigation ends in a labelled "budget exhausted" state that routes to a human, never in a verdict.++**Done when:**+- On recorded data, a tenant with auto-close disabled for a class sees no closure for that class, while another tenant's closures continue.+- The kill switch halts closure and a pending dispatch in an end-to-end test.+- An AI-only prior never suppresses an alert.+- A test that inspects outbound payloads to a mocked hosted provider finds no raw hostname, username, IP, domain or email from the evidence.+- Every LLM call site resolves through a gateway alias, and a gate enforces it.+- A budget breach mid-loop stops the loop.++### Phase 3: Prove verdict quality on the default install++**Goal:** publish verdict accuracy, malicious recall, false-negative counts and injection flip rates for the model AiSOC ships, measured through the production path, with "not measured" everywhere else.++**3.1 Give the default install evidence.** On CORE the investigation agent mostly receives "could not check", because the lake, graph and enrichment run in `full` (`services/agents/app/tools/customer_tools.py`).+- Match the indicators on fused alerts against the tenant's IOC store inside fusion (`services/fusion/app/services/alert_enricher.py`), with IOC expiry and decay.+- Make federated search (`services/connectors/app/federated/`, `services/api/app/api/v1/endpoints/federated.py`) and the configured vendor read verbs default evidence tools whenever a matching connector is enabled.+- Write an ADR (next number) deciding whether a lean event store joins CORE. Measure its memory against CORE's 8 GB budget before deciding, and implement only what the ADR accepts.++**3.2 Accuracy on the shipped model.**+- Point the live-agent eval (`services/agents/tests/eval_data/live_agent_floor.json` and its workflow) at the shipped default model as well as `qwen2.5:0.5b`.+- Report, through `packages/aisoc-benchmark` on labelled replay sets: verdict accuracy, per-class precision and recall, malicious recall with a confidence interval, and false-negative counts. Label synthetic sets as synthetic.+- Publish the results in `apps/docs/docs/benchmark.md` with the model id, dataset, date and commit. Hosted models read "not measured" until the maintainer funds a key.++**3.3 Behavioural injection suite.**+- Implement log-field injection families: instructions planted in usernames, command lines, URLs, email subjects, file paths and process names, plus persona hijack, fake analyst notes and fake tool output.+- Run them as a behavioural suite through the production triage path, reporting verdict flip rate and unsafe-action rate per family next to the existing guard catch rates.+- Fail CI if the flip rate regresses past a recorded floor.++**3.4 Before-and-after measurement.** Implement gap-closure tracker item 6.4 as specified.++**3.5 QA sampling of auto-closed alerts.**+- Send a tenant-configurable sample of auto-closed alerts (default 5 percent) to an analyst review queue.+- Reviewers score each on an open five-part rubric: evidence gathered, reasoning, verdict, response and report quality.+- Disagreements feed 2.3 and appear on the operations dashboard as measured closure accuracy.++**3.6 A grounded copilot.** Give the copilot (`services/agents/app/api/copilot.py`):+- the read tools the investigation agent has;+- the page context the console already sends;+- tenant-scoped persistence;+- citations to ledger entries for every factual claim. An answer with no citation is labelled uncited.++**3.7 Evidence bundles.**+- Export each investigation as a signed, replayable bundle holding the alert, evidence, tool calls, prompts by hash, model id, verdict, confidence, cost provenance and approvals.+- Map agent activity to the OCSF version the tree targets: the `ai_agent` object (added in OCSF 1.9.0), the `ai_operation` profile (added in 1.8.0), and the record-integrity profile for tamper evidence. Check each against the published schema before using it.+- Reports cite the ledger entry behind each finding.++**Done when:**+- `benchmark.md` shows measured accuracy, malicious recall, false-negative counts and flip rates for the shipped model, each with its dataset, date and commit, and "not measured" for anything not run.+- A CORE install investigating a recorded alert, with one mocked SIEM connector, reaches at least two evidence pivots.+- An evidence bundle round-trips through replay byte for byte.++### Phase 4: Enterprise identity and the operator console++**Goal:** an enterprise or MSSP security review passes on identity, access and audit, and operators never need the API for day-to-day administration.++**4.1 SSO end to end.** Today `services/api/app/auth/saml.py` and `oidc.py` put a token in a cookie the API never reads, and it names no local user, tenant or role.+- Declare `python3-saml` as a dependency in every install path.+- Provision users just in time, with tenant binding and IdP group-to-role mapping through `app.core.role_grants`.+- Issue the same bearer token the API already verifies.+- Accept IdP metadata by URL and by file.+- Add an end-to-end CI test against a containerised test IdP (for example Keycloak) for both OIDC and SAML.++**4.2 Console MFA.** Add TOTP with backup codes and WebAuthn for console sign-in, reusing the passkey code in `services/api/app/api/v1/endpoints/passkeys.py`. Support enforcement per role and per tenant, and recovery by an admin with an audit record.++**4.3 Custom roles everywhere.** `require_permission` reads a static map of built-in roles at about 272 call sites (256 dependencies and 16 direct calls), while database custom roles are consulted at 31 (`services/api/app/api/v1/deps.py`).+- Make every check consult the database role model, with a cache that is invalidated on change.+- This changes behaviour, so record it under `### BREAKING`.+- If the security batch already did this, record a Deviation and add only the console role-assignment UI.++**4.4 Audit log for tenant admins.**+- A console audit view scoped to the tenant, with filters and CSV and JSON export.+- An enforced retention job driven by the stored retention setting.+- Export to a configured destination.++**4.5 Operator pages.**+- Console pages for branding, SCIM tokens, retention, organisation members and grants, rule packs and delegations, all of which are API-only today.+- Opt-in enforcement of per-tenant limits, with a clear over-limit state. `services/api/app/services/entitlements.py` reports headroom but enforces nothing.++**4.6 Internationalisation.** Implement gap-closure 13.4 as specified.++**4.7 Accessibility on core views.** Extend axe coverage (`apps/web/src/test/a11y.test.tsx`) to the queue, alert list, case workspace, investigation rail and settings, and fix what it finds. Only then restore an accessibility claim, naming the views covered.++**Done when:**+- A CI test signs in through OIDC and through SAML, lands in the right tenant with the mapped role, and calls an authorized route.+- MFA is enforced for a role that requires it.+- A custom role grants and denies access at a route that used the static map.+- A tenant admin reads and exports their own audit log and cannot read another tenant's.++### Phase 5: Close the response and detection loop++**Goal:** the detections a tenant tunes are the detections that run, and playbooks run from alerts, with human approval wherever the contract requires it.++**5.1 Alert-triggered playbooks.** `find_matching()` (`services/agents/app/playbook/store.py`) has no production caller today. Call it from the fused-alert path behind a setting that ships off. A playbook first runs in preview, with its plan and simulated steps shown on the alert, and then goes live per tenant and per playbook.++**5.2 Approval as a durable pause.** The `approval` step (`services/agents/app/playbook/engine.py`) always fails today, and eight playbooks abort there. Implement it as a persisted pause that:+- resumes from `/approvals/{id}/decide`;+- survives restarts;+- expires with a recorded outcome;+- appears in Slack, the responder app and email approvals.++**5.3 Steps that do something.**+- Resolve `${...}` placeholders in `http` steps from connector instances and the vault, through the SSRF guard. Today 69 such steps are rejected.+- Make `notify` deliver through the configured Slack, Teams, email and PagerDuty destinations. Today 61 such steps deliver nothing.+- Fix or remove the osquery step.+- Ship the 62 pack playbooks and the YAML hunts in the agents image, gated by an image-content check.++**5.4 Tenant tuning inside fusion.** Fusion loads static JSON and never reads tenant tuning (`services/fusion/app/services/detection_engine.py`, `services/api/app/services/rule_tuning.py`), and marketplace install only sets an in-memory flag (`services/api/app/api/v1/endpoints/marketplace.py`).+- Load per-tenant suppressions, thresholds, disables, custom rules and MSSP rule packs into fusion as versioned overlays with hot reload.+- Make marketplace install write rows that fusion reads.+- A tuning change applies to that tenant only and is recorded with its author and reason.++**5.5 Rules that can fire.** 133 of the 833 native rules depend on inputs that do not exist (`scripts/check_detection_fields.py`): a windowed evaluator (74 rules), identity enrichment (24), per-tenant allowlists (15), fields nothing emits (8), first-seen enrichment (8), behavioural baselines (2) and other inputs (6).+- Build the missing inputs where that is cheap; quarantine the rest with a reason, and shrink the ratchet.+- Recompute ATT&CK coverage from executable rules only.++**5.6 Case depth.**+- Alert and case merge. The merge columns in `services/api/app/models/alert.py` have no writer.+- Bulk triage, in both the route and the UI.+- An SLA breach worker that escalates.+- Escalation routing to a tier, queue or on-call schedule. Today "escalate" only raises severity one step (`services/api/app/api/v1/endpoints/alerts.py`).+- Tenant custom fields on cases.+- Per-analyst workload metrics.++**5.7 Delivery.**+- A report scheduler that reads the stored cron and delivers. `services/api/app/api/v1/endpoints/reports.py` leaves generated reports pending.+- SMTP delivery for reports and digests.+- The email-approval sender wired up (`services/api/app/services/email_approval.py`).+- Proactive Teams approval cards. `services/teams-bot` already has the card builder and callback handler; deploy it in compose and post the cards.+- Outbound event webhooks with HMAC signatures, retries and a dead-letter view.++**Done when:**+- A matching alert starts a playbook in preview, which pauses for approval, resumes on the decision and verifies its action.+- A tenant suppression changes fusion output for that tenant only.+- A scheduled report arrives at a mock SMTP server.+- An outbound webhook is signed and retried.++### Phase 6: Agent parity, then platform depth++**Goal:** the agent capabilities buyers treat as table stakes in 2026 run in the default install. Then the platform gains the depth an overlay needs at scale.++**6.1 Hunting.**+- Wire the NL hunting agent (`services/agents/app/hunt/agent.py`) into the console and the MCP server. Today only its test imports it.+- Run the YAML hunt library against federated search or the event store instead of synthetic JSONL (`services/agents/app/hunt/scheduler.py`). Scheduled hunts create alerts through fusion.+- Keep the closed query schema: the model never writes query text.++**6.2 Detection engineering.** Implement gap-closure Phase 9 as specified:+- coverage gaps per tenant;+- drafted rules as governed DRAFT proposals, with fixtures, synthetic events and a backtest through replay;+- nothing promoted without approval.++**6.3 Custom agents.** Implement gap-closure Phase 7 as specified. Add console editors for agent definitions, tenant skills and MCP server registrations, which are API-only today. Each editor has validation, a dry run, and version history with rollback.++**6.4 Phishing operations.** Implement gap-closure Phase 10 as specified:+- reported-phish mailbox intake;+- purge and retract verbs with capability contracts;+- a blast radius scaled by recipient count;+- campaign grouping.++**6.5 Semantic memory with provenance.**+- Add vector recall on Qdrant, which already runs in CORE, for past cases, runbooks and institutional memory. Today `services/api/app/api/v1/endpoints/knowledge_base.py` uses full-text search and tag overlap.+- Every memory item carries an author, source, scope, expiry and state (in use, conflict, not in use). Conflicting items surface for analyst review before use.+- Replay shows the accuracy delta.++**6.6 MCP over the network.** The MCP server (`services/mcp/src/server.ts`) is stdio-only and deployed by nothing. Change that so that it:+- runs over streamable HTTP;+- is deployed in compose and Helm;+- authenticates with scoped API keys;+- enables tools per tenant;+- writes an audit row for every call, reads included;+- marks destructive tools as requiring approval.++**6.7 Agent identity and AI-agent baselines.**+- Give each internal agent its own identity, with short-lived credentials and least-privilege tool scopes, visible in the audit log.+- Then use the AI-agent runtime telemetry that `packages/aisoc-ai-sdk` already emits to build a per-agent behavioural baseline, with anomaly alerts for customers' own AI agents.++**6.8 Deployment completeness.**+- Helm renders and installs every CORE service. Today the chart omits connectors, actions, threat intel, the LLM gateway, Ollama and Qdrant (`infra/helm/aisoc/values.yaml`).+- Restore covers every component that backup covers (`scripts/restore.sh`).+- The connector scheduler uses leader election.+- One run on a managed cloud Kubernetes service is recorded in `docs/perf/`.++**6.9 Scale.**+- Index detection rules by log source, so fusion stops running every rule against every event.+- Concurrent triage consumers, with ordering kept per entity.+- Lag-based autoscaling hints.+- Benchmarks on cloud hardware, with results in `docs/perf/results/` and honest "not an SLO" labels.++**6.10 Collection and standards.**+- A syslog listener (RFC 5424, RFC 3164, CEF and LEEF) in `services/ingest`.+- S3 and queue-based ingestion, for example CloudTrail from S3 and SQS instead of `LookupEvents`.+- An OTLP logs receiver.+- A Kafka input.+- OCSF normalization beyond the five classes ingest emits today.+- Sigma correlation rule types in fusion.+- A real TAXII 2.1 server backed by the tenant IOC store.++**Done when:**+- The locked gap-closure plan's "Done when" criteria for Phases 7, 9 and 10 are met.+- Hunting is reachable from the console and from MCP on CORE.+- MCP over HTTP is deployed, with an audit row per tool call.+- `helm install` brings up all of CORE on kind and on one managed cluster.+- A syslog source reaches an alert through `make smoke`.++### Maintainer-only items (record as [!], do not attempt)++- Fund a hosted-model key so that 3.2 and 3.3 can report hosted results.+- Sign at least one design partner willing to replay closed alerts.+- Publish the npm and PyPI packages and the MCP server package (the names need reserving first).+- Commission an external penetration test, and SOC 2 or ISO 27001 for the hosted service.+- Add a second maintainer with merge rights.+- Decide when to cut the planned major, and the cadence of the stable channel.diff --git a/scripts/check_console_auth_headers.py b/scripts/check_console_auth_headers.pynew file mode 100644index 000000000..d07a11b43--- /dev/null+++ b/scripts/check_console_auth_headers.py@@ -0,0 +1,674 @@+#!/usr/bin/env python3+"""Every console call to an AiSOC API carries a credential.++Why this exists+---------------+The console reached 61 API call sites across 21 files through bare+``fetch(url)`` and through single-argument SWR fetchers that take no options+at all, so the request went out with no ``Authorization`` header. Those calls+worked, which is the whole problem: the API resolved a credential-free request+to a demo administrator whenever it ran in a development-class environment,+and that is how the quick start and the documented single-host deployment ran.+Closing the anonymous path turns every one of them into a 401, so the console+had to move onto the credentialed client in the same change.++Nothing would have caught the drift. ``check_ledger_replay_contract`` holds+one client object against one router and says nothing about headers;+``check_route_auth`` and ``check_route_authz`` look at the server. The console+side had no gate at all, and a header is exactly the kind of thing a new+component omits by copying the component beside it.++What counts as a credential+---------------------------+An ``Authorization`` header, and nothing else. Two near-misses deserve+naming because both were present in the tree and neither authenticates:++``X-Tenant-Id``+ A caller-supplied tenant claim. Five call sites in ``api.ts`` sent it and+ no token, which reads like an identity and is not one.++``credentials: 'include'``+ Sends cookies. The API verifies a bearer token; the SSO cookie it sets is+ read by nothing. A cookie-only call is anonymous to this backend.++Scope+-----+Browser code under ``apps/web/src``. Server components are in scope and+allowlisted individually rather than exempted as a class: a server render has+no session to borrow, so a call made there is either genuinely public or a+call that cannot succeed, and both deserve a written reason.+"""++from __future__ import annotations++import argparse+import pathlib+import sys+import tempfile+from dataclasses import dataclass++# `scripts/` is on sys.path when this file is run as a program, but not when a+# test loads it by path with importlib. gate_toolkit sits beside it either way.+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))++from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402++#: Where the console lives, relative to the repository root.+CONSOLE_ROOT = "apps/web/src"++#: Path fragments that mark a URL as an AiSOC API call. `/api/v1` covers the+#: core API and every service the Next rewrites proxy; `/v1/inbox` is the+#: ingest webhook, which authenticates by token in the path.+API_MARKERS = ("/api/v1/", "/v1/inbox/")++#: Suffixes whose calls are not shipped to a browser.+EXEMPT_SUFFIXES = (".test.ts", ".test.tsx", ".spec.ts", ".spec.tsx", ".stories.tsx")++#: What counts as a credential at a call site, matched case-insensitively.+#:+#: Either the header spelled out, or a call to the one helper that attaches+#: it. Recognising the helper matters: hiding the header behind a local+#: `const headers = {...}` a few lines up is how the preferences call ended up+#: with a token and no tenant header, and the fix for that shape is to route+#: it through the helper rather than to make the gate chase variables. So the+#: rule a reviewer can state is "show the credential, or call the thing whose+#: job is attaching it, on the same expression as the fetch".+CREDENTIAL_MARKERS = ("authorization", "apiheaders(")++#: Fetchers that attach a credential themselves, so a bare reference to one as+#: an SWR fetcher is fine. Keep in step with `apps/web/src/lib/api.ts`.+AUTHED_FETCHERS = frozenset({"authedFetcher", "apiRequest", "apiFetch", "request"})++#: Single-argument fetchers that cannot attach a credential, by construction:+#: SWR calls them as `f(key)` and they take no options. A bare reference to+#: one against an API key is a finding even though no `fetch(` is in sight.+#: Both named here were retired; the names stay so that re-introducing the+#: shape is a failure rather than a silent regression.+UNAUTHED_FETCHERS = frozenset({"jsonFetcher", "safeFetcher"})+++#: Calls that legitimately carry no credential, keyed by (path, url fragment)+#: with the reason. This may only shrink: `--check` reports an entry whose+#: call has gone, so a fixed site cannot leave its excuse behind.+ALLOWED_UNCREDENTIALED: dict[tuple[str, str], str] = {+ (+ "lib/replay.ts",+ "/api/v1/r/",+ ): (+ "The public replay permalink. Unauthenticated by design: /r/<slug> is "+ "the surface a reader opens from a blog post, and the redaction pass in "+ "services/api/app/services/replay_redaction.py is what makes it safe to serve."+ ),+}+++@dataclass(frozen=True)+class Finding:+ """One console call that reaches an API without a credential."""++ rel_path: str+ line: int+ url: str+ kind: str+ detail: str++ def render(self) -> str:+ return f"{self.rel_path}:{self.line} [{self.kind}] {self.url}\n {self.detail}"+++@dataclass(frozen=True)+class Report:+ findings: list[Finding]+ files_scanned: int+ calls_scanned: int+ stale_allowlist: list[str]+++def _sources(root: pathlib.Path) -> list[pathlib.Path]:+ console = root / CONSOLE_ROOT+ if not console.is_dir():+ return []+ return sorted(p for p in console.rglob("*.ts*") if p.suffix in (".ts", ".tsx") and not p.name.endswith(EXEMPT_SUFFIXES))+++def _call_arguments(text: str, open_paren: int) -> tuple[str, int] | None:+ """The text between the parentheses of a call, and the index after it.++ Written by hand rather than with a regex because the first argument is+ usually a template literal, and `${...}` puts braces and quotes inside a+ string that a naive matcher would treat as structure. Tracks quote state+ and template-substitution depth so `fetch(`${A}/api/v1/x`, { ... })` is+ read as two arguments rather than five.+ """+ if open_paren >= len(text) or text[open_paren] != "(":+ return None+ depth = 0+ index = open_paren+ quote: str | None = None+ # One entry per `${` we are inside, so a nested template closes correctly.+ substitutions: list[int] = []+ while index < len(text):+ char = text[index]+ if quote is not None:+ if char == "\\":+ index += 2+ continue+ if quote == "`" and char == "$" and text[index : index + 2] == "${":+ substitutions.append(depth)+ quote = None+ depth += 1+ index += 2+ continue+ if char == quote:+ quote = None+ index += 1+ continue+ if char in "'\"`":+ quote = char+ index += 1+ continue+ if char in "([{":+ depth += 1+ elif char in ")]}":+ depth -= 1+ if substitutions and depth == substitutions[-1]:+ substitutions.pop()+ quote = "`"+ index += 1+ continue+ if depth == 0:+ return text[open_paren + 1 : index], index + 1+ index += 1+ return None+++def _split_top_level(argument_text: str) -> list[str]:+ """Split a call's arguments on commas that are not nested or quoted."""+ parts: list[str] = []+ depth = 0+ quote: str | None = None+ substitutions: list[int] = []+ start = 0+ index = 0+ while index < len(argument_text):+ char = argument_text[index]+ if quote is not None:+ if char == "\\":+ index += 2+ continue+ if quote == "`" and argument_text[index : index + 2] == "${":+ substitutions.append(depth)+ quote = None+ depth += 1+ index += 2+ continue+ if char == quote:+ quote = None+ index += 1+ continue+ if char in "'\"`":+ quote = char+ elif char in "([{":+ depth += 1+ elif char in ")]}":+ depth -= 1+ if substitutions and depth == substitutions[-1]:+ substitutions.pop()+ quote = "`"+ elif char == "," and depth == 0:+ parts.append(argument_text[start:index])+ start = index + 1+ index += 1+ parts.append(argument_text[start:])+ return [part.strip() for part in parts]+++def _api_path_in(text: str) -> str | None:+ """The API path a URL expression names, if it names one."""+ for marker in API_MARKERS:+ if marker in text:+ # Report from the marker so the finding reads as a route rather+ # than as whatever base-URL expression happens to precede it.+ tail = text[text.index(marker) :]+ for terminator in ("`", "'", '"', "?"):+ if terminator in tail:+ tail = tail[: tail.index(terminator)]+ return tail.strip()+ return None+++def _line_of(text: str, index: int) -> int:+ return text.count("\n", 0, index) + 1+++def _skip_generic(text: str, index: int) -> int:+ """Past a `<...>` type argument list, if one starts at `index`.++ `useSWR<Role[]>('/api/v1/rbac/roles', fetcher)` is a call, and a matcher+ that only skips whitespace between the name and `(` does not see it. Both+ SWR sites in the settings console carried a generic, so the rule that was+ meant to catch an unauthenticated fetcher matched nothing at all.++ Only a balanced `<...>` immediately followed by `(` counts, so a genuine+ comparison such as `a < b && c > (d)` is left alone.+ """+ if index >= len(text) or text[index] != "<":+ return index+ depth = 0+ cursor = index+ while cursor < len(text):+ char = text[cursor]+ if char == "<":+ depth += 1+ elif char == ">":+ depth -= 1+ if depth == 0:+ after = cursor + 1+ while after < len(text) and text[after] in " \t\n":+ after += 1+ return after if after < len(text) and text[after] == "(" else index+ elif char in ";{}\n" and depth:+ return index+ cursor += 1+ return index+++def _find_call_sites(source: str, callee: str) -> list[tuple[int, str, list[str]]]:+ """Every `callee(...)` in `source`, as (offset, raw arguments, split)."""+ sites: list[tuple[int, str, list[str]]] = []+ needle = callee+ cursor = 0+ while True:+ found = source.find(needle, cursor)+ if found < 0:+ return sites+ cursor = found + len(needle)+ # Reject `myFetch(` and `.fetch(` style matches: only a call whose+ # name starts at a word boundary is this callee.+ before = source[found - 1] if found else " "+ if before.isalnum() or before in "_$.":+ continue+ after = found + len(needle)+ while after < len(source) and source[after] in " \t\n":+ after += 1+ after = _skip_generic(source, after)+ parsed = _call_arguments(source, after)+ if parsed is None:+ continue+ raw, _ = parsed+ sites.append((found, raw, _split_top_level(raw)))+++def _carries_credential(options_text: str) -> bool:+ lowered = options_text.lower()+ return any(marker in lowered for marker in CREDENTIAL_MARKERS)+++def _definition_of(source: str, name: str) -> str | None:+ """The text of a `const name = ...` or `function name(...)` in this file.++ SWR takes a fetcher by name, so judging the call means reading what the+ name is bound to. Three bindings occur in this console and they answer+ differently: an alias of an imported fetcher, an inline arrow that calls+ `fetch(url)` on the SWR key, and a name imported from another module.+ Only the first two can be decided here.+ """+ for opener in (f"const {name} = ", f"let {name} = ", f"function {name}("):+ found = source.find(opener)+ if found < 0:+ continue+ start = found + len(opener)+ depth = 0+ cursor = start+ while cursor < len(source):+ char = source[cursor]+ if char in "([{":+ depth += 1+ elif char in ")]}":+ depth -= 1+ if depth < 0:+ break+ elif char == ";" and depth == 0:+ break+ elif char == "\n" and depth == 0 and _statement_ends_at(source, start, cursor):+ break+ cursor += 1+ return source[start:cursor]+ return None+++#: Tokens that mean a statement continues on the next line, so a newline at+#: brace depth zero is not the end of the definition. Both fetchers on the+#: honeytokens and purple-team pages are written as+#: `const fetcher = (url: string) =>\n fetch(url).then(...)`, and stopping at+#: the first newline read the definition as the bare signature `(url: string)+#: =>`. That has no `fetch(` in it, so the gate concluded "imported from+#: elsewhere, judged where defined" and skipped nine real findings while+#: printing a clean line for them.+_CONTINUES = ("=>", "=", "&&", "||", "?", ":", ",", "+", "(", "[", "{", ".", "await", "return")+++def _statement_ends_at(source: str, start: int, cursor: int) -> bool:+ text = source[start:cursor].rstrip()+ if not text:+ return False+ return not any(text.endswith(token) for token in _CONTINUES)+++def _fetcher_is_credentialed(source: str, fetcher: str) -> bool | None:+ """Whether a named SWR fetcher attaches a credential. None means unknown."""+ if fetcher in AUTHED_FETCHERS:+ return True+ if fetcher in UNAUTHED_FETCHERS:+ return False+ definition = _definition_of(source, fetcher)+ if definition is None:+ # Imported from another module; judged where it is defined.+ return None+ stripped = definition.strip().rstrip(";")+ if stripped in AUTHED_FETCHERS:+ return True+ if stripped in UNAUTHED_FETCHERS:+ return False+ if _carries_credential(definition):+ return True+ if "fetch(" in definition:+ # An inline fetcher that calls fetch() on the SWR key with no header.+ # The fetch() scanner cannot see this one: its URL is the parameter,+ # so there is no API path at the call site to match on.+ return False+ return None+++def _allowlist_reason(rel_path: str, url: str) -> str | None:+ for (path, fragment), reason in ALLOWED_UNCREDENTIALED.items():+ if path == rel_path and fragment in url:+ return reason+ return None+++def inspect(root: pathlib.Path) -> Report:+ findings: list[Finding] = []+ calls = 0+ files = _sources(root)+ used_allowlist: set[tuple[str, str]] = set()++ for path in files:+ rel = path.relative_to(root / CONSOLE_ROOT).as_posix()+ source = path.read_text(encoding="utf-8", errors="replace")++ for offset, _raw, parts in _find_call_sites(source, "fetch"):+ url = _api_path_in(parts[0] if parts else "")+ if url is None:+ continue+ calls += 1+ options = ",".join(parts[1:])+ if _carries_credential(options):+ continue+ reason = _allowlist_reason(rel, url)+ if reason is not None:+ for key in ALLOWED_UNCREDENTIALED:+ if key[0] == rel and key[1] in url:+ used_allowlist.add(key)+ continue+ findings.append(+ Finding(+ rel,+ _line_of(source, offset),+ url,+ "bare-fetch",+ "fetch() with no Authorization header. Use apiRequest() from @/lib/api.",+ )+ )++ for offset, _raw, parts in _find_call_sites(source, "useSWR"):+ if len(parts) < 2:+ continue+ url = _api_path_in(parts[0])+ if url is None:+ continue+ calls += 1+ fetcher = parts[1].strip()+ if "=>" in fetcher or fetcher.startswith("function"):+ # An inline arrow is judged on what it does, not its name.+ if _carries_credential(fetcher) or "fetch(" not in fetcher:+ continue+ elif fetcher.isidentifier():+ credentialed = _fetcher_is_credentialed(source, fetcher)+ if credentialed is not False:+ continue+ else:+ continue+ reason = _allowlist_reason(rel, url)+ if reason is not None:+ continue+ findings.append(+ Finding(+ rel,+ _line_of(source, offset),+ url,+ "swr-fetcher",+ f"useSWR keyed on an API path with `{fetcher}`, which sends no credential. Use authedFetcher from @/lib/api.",+ )+ )++ stale = [f"{path} :: {fragment}" for (path, fragment) in ALLOWED_UNCREDENTIALED if (path, fragment) not in used_allowlist]+ return Report(findings, len(files), calls, stale)+++def _verdict(report: Report) -> int:+ if report.files_scanned == 0:+ print(+ f"check_console_auth_headers: no console sources under {CONSOLE_ROOT} — refusing to report a tree with nothing in it as clean",+ file=sys.stderr,+ )+ return 2+ if report.calls_scanned == 0:+ print(+ "check_console_auth_headers: scanned "+ f"{report.files_scanned} file(s) and found no API call at all. "+ "Either the console stopped calling the API or the matcher broke; "+ "both need a human.",+ file=sys.stderr,+ )+ return 2++ if report.stale_allowlist:+ print("check_console_auth_headers: allowlist entries whose call is gone:", file=sys.stderr)+ for entry in report.stale_allowlist:+ print(f" {entry}", file=sys.stderr)+ print("Remove them; the allowlist may only shrink.", file=sys.stderr)+ return 1++ if report.findings:+ print(+ f"check_console_auth_headers: {len(report.findings)} console call(s) reach an API with no credential:",+ file=sys.stderr,+ )+ for finding in report.findings:+ print(f" {finding.render()}", file=sys.stderr)+ return 1++ print(+ f"check_console_auth_headers: OK — {report.calls_scanned} API call(s) across "+ f"{report.files_scanned} console file(s) all carry a credential "+ f"({len(ALLOWED_UNCREDENTIALED)} allowlisted as public)."+ )+ return 0+++# ── Self-test ───────────────────────────────────────────────────────────────+++@dataclass(frozen=True)+class Case:+ """One self-test case: source, and the finding kind that must account for it.++ `expect` names the kind rather than asking "did anything fire", so a bare+ fetch cannot pass on the strength of the SWR rule catching the same line.+ `expect=None` means the case must produce nothing.+ """++ description: str+ source: str+ expect: str | None+ suffix: str = ".tsx"+ name: str = "View"+++def self_test_cases() -> tuple[Case, ...]:+ return (+ Case(+ "a bare fetch to an API path, the shape that shipped",+ "export async function go() {\n await fetch('/api/v1/rbac/roles/abc', { method: 'DELETE' });\n}\n",+ "bare-fetch",+ ),+ Case(+ "a template-literal URL behind a base variable",+ "const API = process.env.NEXT_PUBLIC_HONEYTOKENS_URL ?? '';\n"+ "export async function go() {\n"+ " await fetch(`${API}/api/v1/honeytokens/x/revoke`, { method: 'PATCH' });\n}\n",+ "bare-fetch",+ ),+ Case(+ "X-Tenant-Id alone, which reads like an identity and is not one",+ "export async function go() {\n"+ " await fetch('/api/v1/cases/1/investigations/2/report.pdf', {\n"+ " headers: { 'X-Tenant-Id': t },\n });\n}\n",+ "bare-fetch",+ ),+ Case(+ "credentials: 'include', which sends cookies the API never reads",+ "export async function go() {\n await fetch('/api/v1/compliance/soc2/export', { credentials: 'include' });\n}\n",+ "bare-fetch",+ ),+ Case(+ "a local alias of an unauthenticated fetcher used by SWR",+ "import { jsonFetcher } from '@/lib/failure';\n"+ "const fetcher = jsonFetcher;\n"+ "export function V() {\n"+ " const { data } = useSWR('/api/v1/rbac/roles', fetcher);\n"+ " return <b>{data}</b>;\n}\n",+ "swr-fetcher",+ name="Aliased",+ ),+ Case(+ "the same alias behind a generic, which hid both real SWR sites",+ "import { jsonFetcher } from '@/lib/failure';\n"+ "const fetcher = jsonFetcher;\n"+ "export function V() {\n"+ " const { data } = useSWR<Role[]>('/api/v1/rbac/roles', fetcher, { x: 1 });\n"+ " return <b>{data}</b>;\n}\n",+ "swr-fetcher",+ name="Generic",+ ),+ Case(+ "an inline fetcher whose URL is the SWR key, invisible to fetch() scanning",+ "const fetcher = async (url: string) => {\n"+ " const r = await fetch(url);\n return r.json();\n};\n"+ "export function V() {\n"+ " const { data } = useSWR<Row[]>('/api/v1/sla/config', fetcher);\n"+ " return <b>{data}</b>;\n}\n",+ "swr-fetcher",+ name="Inline",+ ),+ # ── and the directions it must not fire in ──────────────────────────+ Case(+ "a credentialed fetch",+ "export async function go() {\n"+ " await fetch('/api/v1/playbooks/1/run', {\n"+ " method: 'POST',\n headers: { Authorization: `Bearer ${t}` },\n });\n}\n",+ None,+ ),+ Case(+ "the authenticated client, which attaches the header itself",+ "import { apiRequest, authedFetcher } from '@/lib/api';\n"+ "export function V() {\n"+ " const { data } = useSWR('/api/v1/rbac/roles', authedFetcher);\n"+ " void apiRequest('/api/v1/playbooks', { method: 'POST' });\n"+ " return <b>{data}</b>;\n}\n",+ None,+ ),+ Case(+ "a multi-line arrow fetcher, truncated at the newline by a first pass",+ "const fetcher = (url: string) =>\n"+ " fetch(url).then((r) => {\n"+ " if (!r.ok) throw new Error(`HTTP ${r.status}`)\n"+ " return r.json()\n"+ " })\n"+ "export function V() {\n"+ " const { data } = useSWR<Row[]>(t ? `${API}/api/v1/purple-team/coverage?x=1` : null, fetcher)\n"+ " return <b>{data}</b>;\n}\n",+ "swr-fetcher",+ name="MultiLine",+ ),+ Case(+ "the header helper, which is the credentialed path",+ "import { apiHeaders } from '@/lib/api';\n"+ "export async function go() {\n"+ " await fetch('/api/v1/auth/me/preferences', {\n"+ " method: 'PATCH',\n headers: apiHeaders(),\n });\n}\n",+ None,+ ),+ Case(+ "a fetch to something that is not an AiSOC API",+ "export async function go() {\n await fetch('https://cdn.example.com/logo.svg');\n}\n",+ None,+ ),+ Case(+ "a template literal whose substitution contains braces and a quote",+ "export async function go() {\n"+ " await fetch(`/api/v1/x/${encodeURIComponent(o['k'])}`, {\n"+ " headers: { Authorization: `Bearer ${t}` },\n });\n}\n",+ None,+ ),+ )+++def _case_results(tmp: pathlib.Path) -> list[tuple[str, bool]]:+ results: list[tuple[str, bool]] = []+ for index, case in enumerate(self_test_cases()):+ tree = tmp / f"case{index}"+ console = tree / CONSOLE_ROOT+ console.mkdir(parents=True)+ (console / f"{case.name}{case.suffix}").write_text(case.source, encoding="utf-8")+ report = inspect(tree)+ kinds = {finding.kind for finding in report.findings}+ if case.expect is None:+ passed = not report.findings+ detail = f"expected nothing, got {sorted(kinds)}" if not passed else ""+ else:+ passed = case.expect in kinds+ detail = f"expected {case.expect}, got {sorted(kinds)}" if not passed else ""+ results.append((f"{case.description}{f' — {detail}' if detail else ''}", passed))+ return results+++def _corpus_result(root: pathlib.Path) -> tuple[str, bool]:+ """A console whose calls all vanished must fail, not pass."""+ report = inspect(root)+ return (+ f"counts what it scanned ({report.calls_scanned} API calls in {report.files_scanned} files)",+ report.calls_scanned > 0 and report.files_scanned > 0,+ )+++def self_test() -> int:+ with tempfile.TemporaryDirectory(prefix="aisoc-console-auth-") as tmp:+ extra = _case_results(pathlib.Path(tmp))+ extra.append(_corpus_result(repo_root()))+ return self_test_main(pathlib.Path(__file__).name, ["--check"], extra)+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--check", action="store_true", help="render a verdict (default)")+ parser.add_argument(SELF_TEST_FLAG, action="store_true", dest="self_test")+ args = parser.parse_args()+ if args.self_test:+ return self_test()+ return _verdict(inspect(repo_root()))+++if __name__ == "__main__":+ raise SystemExit(main())