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(api): make autonomy grant revocation reachable (#917)
Beenu Arorafa23ce5b714f
diff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.ymlindex b2f9f9962..dd6d5a5c1 100644--- a/.github/workflows/isolation.yml+++ b/.github/workflows/isolation.yml@@ -22,6 +22,7 @@ on:- "services/**"- "scripts/check_route_tenant_scope.py"- "scripts/check_route_auth.py"+ - "scripts/check_route_shadowing.py"- "scripts/check_tenant_query_predicates.py"- "scripts/sync_vendored_tenant_scope.py"# The runtime-DB-role gate reads these, so a change to any of them has@@ -40,6 +41,7 @@ on:- "services/**"- "scripts/check_route_tenant_scope.py"- "scripts/check_route_auth.py"+ - "scripts/check_route_shadowing.py"- "scripts/check_tenant_query_predicates.py"- "scripts/sync_vendored_tenant_scope.py"# The runtime-DB-role gate reads these, so a change to any of them has@@ -147,6 +149,18 @@ jobs:- name: Every route authenticates or records why it is publicrun: python scripts/check_route_auth.py+ # A route can authenticate perfectly and still never run. `DELETE+ # /autonomy-policy/grants` sat behind `DELETE /{action}` from the day it+ # shipped, so an operator could earn an autonomy grant and had no+ # working path to hand it back. This is the breadth half of that check;+ # the fidelity half builds the app and sends a request for every+ # published operation (services/api/tests/test_route_shadowing.py).+ - name: Route-shadowing gate self-test (the defect, and four near misses)+ run: python scripts/check_route_shadowing.py --self-test++ - name: No literal route is unreachable behind a parameterised one+ run: python scripts/check_route_shadowing.py+# The predicate question, which the parameter gate structurally cannot# ask: a route that matches on an id takes no tenant, which is exactly# why it was missing the filter.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b2eeddaa9..ce4b39829 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -632,6 +632,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0on the wrong side of the train/test split and leak the answer into its ownevaluation.+### Fixed++- **An operator could earn an autonomy grant and had no working way to hand it+ back.** `DELETE /api/v1/autonomy-policy/grants` has been unreachable since it+ shipped. `DELETE /{action}` is declared several hundred lines earlier in the+ same router, FastAPI matches in registration order, and so the request was+ taken by the threshold-reset handler with `action="grants"`. It answered 204,+ so the caller was told the revocation had happened. What actually happened was+ a `DELETE` against `aisoc_autonomy_thresholds`: the wrong table, no audit row,+ and a capability the tenant still held. A capability outside the shared+ vocabulary was accepted the same way, because the request never reached the+ validator that would have refused it.++ `{action}` is now constrained by a path convertor that excludes this router's+ literal sub-resources. A convertor takes part in matching, so+ `/autonomy-policy/grants` no longer matches `/{action}` at all and the literal+ route is reached wherever either one is declared. Ordering the declarations+ would have fixed the symptom while leaving the constraint written nowhere+ except the order of the file; the two routes are deliberately left in the+ order that failed, so the tests prove the constraint rather than the ordering.+ FastAPI's `Path(pattern=...)` cannot do this: it is validation applied after a+ route has already matched, so a reserved name would answer 422 rather than+ falling through, and pydantic's regex engine rejects look-around outright. No+ published path changed.++- **The gate written for this exact bug class had never seen a route.**+ `test_route_shadowing.py` read `app.routes` and filtered for `APIRoute`. On+ the FastAPI version these services pin, `include_router` does not put routes+ there: it appends a single `_IncludedRouter`, and the only `APIRoute`s in the+ list are the handful of docs and probe routes the app was born with. Filtering+ yielded zero routes, so the check compared zero pairs, found zero problems and+ reported success, over an app serving 456 operations.++ The corpus now comes from `app.openapi()`, and reachability is decided by+ sending a request for every published operation and reading back which route+ Starlette matched, which is the app as deployed rather than an internal list+ whose meaning changed underneath. It refuses a corpus below a floor rather+ than reporting an empty app clean, and it is proven against the defect: run+ on the pre-fix tree it names `DELETE /api/v1/autonomy-policy/grants` as+ answered by `reset_action_threshold`.++### Added++- **`scripts/check_route_shadowing.py`**, the breadth half of the same+ question. The runtime check needs a service's whole driver stack importable+ and so can only speak for one service; this is one AST pass over `services/`+ covering all thirteen, 628 routes in 138 files. It is the weaker instrument+ and says so in its own output: it pairs routes within a module and router,+ and a parameter carrying a convertor is counted and named as deferred to the+ runtime check rather than being judged or silently dropped. Routes whose path+ is not a string literal are counted too, because the first draft of the fix+ used a shared constant and the gate went on printing OK while skipping the+ very pair it exists for.+## [11.2.0] — 2026-09-26### Addeddiff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.mdindex 7c71af38d..cc321e119 100644--- a/GAP_CLOSURE_PROGRESS.md+++ b/GAP_CLOSURE_PROGRESS.md@@ -288,7 +288,7 @@ window on a second run, and a hosted model may legitimately differ.- [x] **2.1 Shadow mode**, per tenant and per alert class. Shipped in [#906](https://github.com/beenuar/AiSOC/pull/906), and its second closure path in [#912](https://github.com/beenuar/AiSOC/pull/912), which closes D15. The seam is Phase 1.2's: `FusedAlertTriageWorker` already routes every write through the `TriageWriter` port, so shadow mode is a wrapper around the tenant's live sink rather than a second code path. Chosen per alert, not per worker, because the class is not known until the alert is in hand; the constructor sinks are untouched, which is what keeps the Phase 1.2 AST test true. Migration **066** adds `aisoc_shadow_mode` and `aisoc_shadow_decisions`. Analyst closures now arrive from both routes the plan names: a bounded sweep over alerts closed in this console, and a scheduled sweep over each measuring tenant's own SIEM on the five Phase 1.1 readers unchanged. See D9 for the one property everything else rests on, and D15 for what the second path cost.- [x] **2.2 Rolling agreement** per alert class, rule, source and model, on the operations dashboard and the autonomy scorecard. Shipped in [#906](https://github.com/beenuar/AiSOC/pull/906). The metrics are Phase 1.3's and "uses the Phase 1 metrics" is now a gate rather than a sentence: `check_replay_contract_parity.py` went from three trees to four and compares `GRADED_DISPOSITIONS`, `ABSTENTION_VERDICTS`, `MALICIOUS` and `UNLABELED` in both directions, proven capable of failing by drifting each collection in turn. Agreement is computed over *answered* decisions only so abstaining cannot inflate it, malicious recall counts an abstention as a miss, a rate with no denominator reads "not measured", and every rate travels with its count. Matrix 156 rows to 159, GATED 148 to 151.-- [x] **2.3 Promotion gate**, with automatic demotion on drift and every transition written to the hash-chained audit log. Shipped in [#908](https://github.com/beenuar/AiSOC/pull/908). Migration **067** adds `aisoc_autonomy_grants`. The gate is pure and lives in the vendored rules module so `services/actions` enforces the same arithmetic at dispatch that `services/api` decides on at promotion time. Wired into all three modules the plan names: `unified_autonomy.unified_decision` gained an `earned_grant` argument that can only widen the reversible MEDIUM-blast branch, `tenant_policy.TenantPolicy` carries the earned verbs and never issues one, and `autonomy_policy.py` gained `GET`/`POST`/`DELETE /grants`. The dispatcher was also wired, because `unified_decision` turned out to have no production caller at all (see D12). The "Done when" runs against a real Postgres in `integration.yml`. See D13 for why the ceiling stops at L3.+- [x] **2.3 Promotion gate**, with automatic demotion on drift and every transition written to the hash-chained audit log. Shipped in [#908](https://github.com/beenuar/AiSOC/pull/908). Migration **067** adds `aisoc_autonomy_grants`. The gate is pure and lives in the vendored rules module so `services/actions` enforces the same arithmetic at dispatch that `services/api` decides on at promotion time. Wired into all three modules the plan names: `unified_autonomy.unified_decision` gained an `earned_grant` argument that can only widen the reversible MEDIUM-blast branch, `tenant_policy.TenantPolicy` carries the earned verbs and never issues one, and `autonomy_policy.py` gained `GET`/`POST`/`DELETE /grants`. One of those three was never reachable: `DELETE /{action}` is declared several hundred lines earlier in the same router and FastAPI matches in registration order, so every revocation request was taken by the threshold-reset handler, answered 204 and deleted a row from `aisoc_autonomy_thresholds`. A tenant could earn a grant and had no working way to hand it back, which is this phase's safety control failing one way. Fixed by constraining `{action}` with a path convertor that excludes the router's literal sub-resources, so the exclusion sits in the matching regex rather than in the order of the file. The gate written for this bug class had never seen a route (it read `app.routes`, which `include_router` does not populate on the pinned FastAPI); it now takes its corpus from `app.openapi()` and decides reachability by sending a request, refuses an empty corpus, and is joined by `check_route_shadowing.py` across all thirteen services. Matrix 173 rows to 175, GATED 165 to 167. The dispatcher was also wired, because `unified_decision` turned out to have no production caller at all (see D12). The "Done when" runs against a real Postgres in `integration.yml`. See D13 for why the ceiling stops at L3.**Done when:** on recorded data, a test tenant cannot enable auto-close for aclass with 20 shadow decisions, can once the thresholds are met, and is demoteddiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 5a0ed039c..5796d435f 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -184,6 +184,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| The sweep is bounded work against a customer's API: it keeps a watermark, honours rate limits and never re-reads a window forever | `apps/docs/docs/operations/shadow-mode.md` (What it does to your SIEM); `services/api/migrations/068_shadow_reconcile_state.sql` | `ci.yml` api job (`test_shadow_reconcile_sweep.py::TestRateLimitingAndTheWatermark` - the watermark advances to the latest closure actually seen rather than to the end of the window asked for, so a vendor that indexes late does not have findings stepped over; an **empty** window still advances it, minus the overlap, so quiet hours are not re-read forever; a window is capped so a connector blocked for a month catches up in steps rather than asking for the month in one search; a first pass starts when measurement started rather than at the beginning of the vendor's retention; the per-connector floor and the per-tick cap are both asserted to withhold a poll; and a `Retry-After` is stored and honoured. `test_a_transient_failure_leaves_the_watermark_alone` asserts a failure cannot look like progress) | GATED | Every limit is asserted against the sweep's own decision to poll. Whether the defaults are the *right* numbers for a given SIEM is a judgement: they are configurable and the docs table publishes each one beside what it bounds || The API scores a replay with the grader the benchmark package ships, not a second copy of it | `services/api/app/_vendor/aisoc_benchmark/VENDORED.md` | `ci.yml :: vendored-sync` (`scripts/sync_vendored_benchmark.py --check` — every module of `packages/aisoc-benchmark/aisoc_benchmark/` must be byte-identical in `services/api/app/_vendor/aisoc_benchmark/`, checked in **both** directions so a module present only in the mirror fails too, and refusing to report a clean mirror when the source directory yields no modules) | GATED | A mirror rather than an import, because the `aisoc-core-api` image is built with `./services/api` as its context and nothing under `packages/` exists at runtime. Same constraint that produced `_vendor/narrative.py` and `_vendor/nl_query/`. A second grader would eventually disagree with the first about what "hallucination rate" means while both kept calling themselves the same number || The published count of services each compose profile starts is what the compose file starts | README L130-132 (profile table); `apps/docs/docs/architecture.md`; `apps/docs/docs/quickstart.md`; `docs/audit/REPOSITORY_REALITY.md`; [ADR-0007](../decisions/0007-connectors-and-actions-in-core.md) | `ci.yml` gates job (`scripts/check_profile_service_counts.py`: ten published figures across four documents are compared against the profile membership parsed out of `docker-compose.yml`, with compose's "a service in no profile is in every profile" semantic implemented rather than assumed, and one-shot containers counted separately from long-running ones because "long-running services" is the figure the documents publish. Fails in **both** directions: a count that disagrees, and a watched figure that has vanished from a document, so deleting the claim fails as a stale entry rather than passing because nothing matched. Also asserts `actions` is reachable from the `chatops` profile, since `slack-bot` depends on it and compose refuses to render a file whose dependency is outside the profile being started, which is the specific state ADR-0007 created by putting `actions` in no profile at all. Proven able to fail by re-staling the README's core figure to 14) | GATED | The counts are gated; the **memory** figures in ADR-0007 are point-in-time measurements on one machine and no gate can re-measure them in CI. They are published with the host, the engine version and the date, and the ~8 GB README figure is deliberately left unmoved because 124.8 MiB does not move a number published to one significant figure |+| An operator can hand an earned autonomy grant back | `apps/docs/docs/operations/shadow-mode.md` (earning autonomy); `services/api/app/api/v1/endpoints/autonomy_policy.py` | `ci.yml` api job (`test_autonomy_grant_revocation.py`, which drives the real route over ASGI and asserts on what the database was told, because the handler that used to answer this request also returned 204: a revocation issues `UPDATE aisoc_autonomy_grants` and must touch `aisoc_autonomy_thresholds` not at all, it is audited as `autonomy:revoked` rather than as a demotion, a revocation matching no standing grant answers 404 rather than succeeding silently, a capability outside the shared vocabulary is refused, and resetting a threshold still reaches the reset. Proven against the pre-fix tree, where four of the six fail) | GATED | Gated against a recording session rather than a live Postgres. The grant lifecycle itself is covered against real Postgres by the Phase 2.3 rows above; what this row adds is that the route carrying it is reachable at all |+| Every route the app publishes is the route that answers for it | (implied by every route-level claim in this table); `services/api/tests/test_route_shadowing.py` | `ci.yml` api job (`test_route_shadowing.py`, where the corpus is `app.openapi()` and reachability is decided by *sending a request* for all 456 published operations and reading back which route Starlette matched, never by reading `app.routes`: on the FastAPI version these services pin, `include_router` does not populate it, so the previous version of this gate filtered an effectively empty list, compared zero pairs and reported success over the whole app. It refuses a corpus below a floor rather than calling an empty app clean, and it is proven able to fail both against a synthetic app carrying the defect and against the pre-fix tree, where it names `DELETE /api/v1/autonomy-policy/grants` as answered by `reset_action_threshold`) + `isolation.yml :: route-scope` (`check_route_shadowing.py`, one AST pass over all thirteen services and 628 routes, with a `--self-test` covering the shipped defect and four near misses) | GATED | The runtime half speaks for `services/api` alone, since it needs that service's driver stack importable. The other twelve are covered by the static pass, which is the weaker instrument and reports as much: it pairs routes within a module and router, so two modules mounted on one prefix are out of its reach, and it counts rather than judges a convertor-constrained parameter and a path that is not a string literal |## Summarydiff --git a/scripts/check_route_shadowing.py b/scripts/check_route_shadowing.pynew file mode 100644index 000000000..5ce2b0a3c--- /dev/null+++ b/scripts/check_route_shadowing.py@@ -0,0 +1,290 @@+#!/usr/bin/env python3+"""No literal route may be unreachable behind an earlier parameterised one.++FastAPI matches in registration order. ``DELETE /{action}`` declared before+``DELETE /grants`` takes every request for ``/grants`` with ``action="grants"``,+so the literal handler never runs. Both routes exist, both look correct where+they are written, and they are usually hundreds of lines apart.++This has shipped twice. ``GET /api/v1/assets/vulnerabilities`` went first, and+``DELETE /api/v1/autonomy-policy/grants`` went the same way: an operator could+earn an autonomy grant and had no working path to hand it back, which is a+safety control failing in the one direction that matters.++Why this is a second gate rather than the only one+--------------------------------------------------+``services/api/tests/test_route_shadowing.py`` decides reachability the honest+way: it builds the app, takes the inventory from ``app.openapi()``, sends a+request for every published operation and reads back which route Starlette+matched. Nothing approximates anything. But that needs the service's whole+driver stack importable, so it can only ever speak for one service at a time,+and twelve others were covered by nothing at all.++This gate is the breadth half: one AST pass over ``services/``, no imports, so+every service is read in one run. It is the weaker instrument of the two and+says so in its own output rather than implying otherwise:++* it pairs routes within a module and router, because that is where+ registration order is legible statically. Two modules included under one+ prefix can shadow each other and this will not see it.+* a parameter carrying a path convertor is *not* judged here. A convertor+ takes part in matching and can be exactly what makes the literal reachable+ (it is, in ``autonomy_policy``), and whether it does is a question about a+ compiled regex this pass never sees. Those pairs are counted and named on+ every run, so deferring them stays visible instead of turning into silence.++It shares ``check_route_tenant_scope``'s collector for the same reason+``check_route_auth`` does: one corpus and one floor, so a third scanner cannot+drift from the first two.+"""++from __future__ import annotations++import argparse+import sys+import tempfile+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++# Imported as a module, never by name: `REPO_ROOT` and `SERVICES_DIR` are+# module state the shared empty-corpus self-test rebinds to a scratch tree,+# and a from-import would copy the originals and go on scanning the real+# checkout while believing it was pointed at an empty one.+import check_route_tenant_scope as route_scan # noqa: E402++#: Convertors that constrain nothing a literal segment could not satisfy. A+#: parameter carrying one of these swallows a sibling literal exactly as a+#: bare `{param}` does, so it is judged rather than deferred.+UNCONSTRAINING_CONVERTORS = frozenset({"", "str", "path"})+++def _segments(path: str) -> list[str]:+ return [s for s in path.split("/") if s]+++def _is_param(segment: str) -> bool:+ return segment.startswith("{") and segment.endswith("}")+++def _convertor(segment: str) -> str:+ """The convertor named on a path parameter, or ``""`` for a bare one."""+ inner = segment[1:-1]+ return inner.split(":", 1)[1].strip() if ":" in inner else ""+++def shadows(earlier: str, later: str) -> tuple[bool, bool]:+ """Whether ``earlier`` captures ``later``, and whether that is decidable here.++ Returns ``(captures, decidable)``. A parameter carrying a custom convertor+ makes the pair undecidable statically: the convertor is part of the+ matching regex and may well be the reason the literal is reachable.+ """+ a, b = _segments(earlier), _segments(later)+ if len(a) != len(b):+ return False, True++ captures = False+ decidable = True+ for seg_a, seg_b in zip(a, b, strict=True):+ if seg_a == seg_b:+ continue+ if _is_param(seg_a) and not _is_param(seg_b):+ captures = True+ if _convertor(seg_a) not in UNCONSTRAINING_CONVERTORS:+ decidable = False+ continue+ return False, True+ return captures, decidable+++def unresolved_paths(routes: list[route_scan.Route]) -> list[str]:+ """Routes whose path this pass could not read, and so never judged.++ A decorator handed a variable rather than a string literal is invisible+ here. That is not hypothetical: the fix this gate was written alongside+ used a shared constant at first, and the gate went on printing OK while+ silently skipping the very pair it exists for. Naming them costs one line+ and makes the blind spot countable.+ """+ return sorted(f"{r.path}:{r.lineno} {r.function}()" for r in routes if not r.path_is_literal)+++def find_shadowed(routes: list[route_scan.Route]) -> tuple[list[str], list[str]]:+ """Every unreachable route, and every pair left to the runtime check."""+ groups: dict[tuple[str, str, str], list[route_scan.Route]] = {}+ for route in routes:+ # A route with no resolvable router object cannot be ordered against+ # anything, so it forms its own group and is compared with nothing.+ for router in route.router_objs or [f"?{route.lineno}"]:+ groups.setdefault((route.service, route.path, router), []).append(route)++ unreachable: list[str] = []+ deferred: list[str] = []+ for (_service, path, _router), group in sorted(groups.items()):+ group.sort(key=lambda r: r.lineno)+ for index, later in enumerate(group):+ for earlier in group[:index]:+ shared = sorted(set(earlier.methods) & set(later.methods))+ if not shared:+ continue+ captures, decidable = shadows(earlier.route_path, later.route_path)+ if not captures:+ continue+ where = f"{path}:{later.lineno} {[m.upper() for m in shared]} {later.route_path}"+ if decidable:+ unreachable.append(+ f"{where} is unreachable: {earlier.route_path} is registered first "+ f"(line {earlier.lineno}, {earlier.function}) and will match it. "+ "Constrain the parameter with a path convertor, or give the literal a path it cannot collide with."+ )+ else:+ deferred.append(f"{where} is guarded by a convertor on {earlier.route_path} (line {earlier.lineno})")+ return unreachable, deferred+++# ── self-test ──────────────────────────────────────────────────────────────++_SHADOWED = """+from fastapi import APIRouter+router = APIRouter(prefix="/autonomy-policy")+[email protected]("/{action}")+async def reset(action: str) -> None:+ return None+[email protected]("/grants")+async def revoke() -> None:+ return None+"""++_CONSTRAINED = _SHADOWED.replace("/{action}", "/{action:autonomy_action}")++_CLEAN = """+from fastapi import APIRouter+router = APIRouter(prefix="/autonomy-policy")+[email protected]("/grants")+async def revoke() -> None:+ return None+[email protected]("/{action}")+async def reset(action: str) -> None:+ return None+"""++_TWO_ROUTERS = """+from fastapi import APIRouter+router = APIRouter(prefix="/policy")+other = APIRouter(prefix="/elsewhere")+[email protected]("/{action}")+async def reset(action: str) -> None:+ return None+[email protected]("/grants")+async def revoke() -> None:+ return None+"""+++def _scan_source(source: str) -> tuple[list[str], list[str]]:+ """Run the gate over a scratch ``services/`` tree holding one module."""+ global_root, global_services = route_scan.REPO_ROOT, route_scan.SERVICES_DIR+ with tempfile.TemporaryDirectory(prefix="route_shadow_") as tmp:+ root = Path(tmp)+ module = root / "services" / "api" / "app" / "endpoints.py"+ module.parent.mkdir(parents=True)+ module.write_text(source, encoding="utf-8")+ route_scan.REPO_ROOT, route_scan.SERVICES_DIR = root, root / "services"+ try:+ return find_shadowed(route_scan.collect_routes())+ finally:+ route_scan.REPO_ROOT, route_scan.SERVICES_DIR = global_root, global_services+++def _self_test() -> int:+ """A gate nobody has seen fail is indistinguishable from one that cannot.++ Each case is the real defect or a near miss of it, so a refactor that+ quietly breaks detection shows up here rather than in an incident.+ """+ failures = 0++ cases: list[tuple[str, str, bool, bool]] = [+ ("the shipped defect: DELETE /grants behind DELETE /{action}", _SHADOWED, True, False),+ ("a bare parameter is judged, not deferred", _SHADOWED, True, False),+ ("the literal declared first is reachable", _CLEAN, False, False),+ ("a convertor on the parameter is deferred, not called clean or broken", _CONSTRAINED, False, True),+ ("routes on two different routers are not paired", _TWO_ROUTERS, False, False),+ ]+ for label, source, expect_unreachable, expect_deferred in cases:+ unreachable, deferred = _scan_source(source)+ ok = bool(unreachable) is expect_unreachable and bool(deferred) is expect_deferred+ failures += not ok+ print(f" [{'PASS' if ok else 'FAIL'}] {label}")+ if not ok:+ print(f" unreachable={unreachable} deferred={deferred}")++ failures += route_scan.self_test_empty_corpus("check_route_shadowing", lambda: main([]))++ print()+ if failures:+ print(f"check_route_shadowing: self-test FAILED ({failures} case(s))")+ return 1+ print("check_route_shadowing: self-test OK")+ return 0+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--self-test", action="store_true", help="prove the gate detects the defect it exists for")+ args = parser.parse_args(argv)++ if args.self_test:+ return _self_test()++ if not route_scan.SERVICES_DIR.is_dir():+ print(+ f"ERROR: no services/ directory under {route_scan.REPO_ROOT}, so there is no tree to report a result for.",+ file=sys.stderr,+ )+ return 2++ routes = route_scan.collect_routes()++ # Zero routes scanned is not zero routes shadowed. Shared with the gate+ # that owns the collector, so there is one floor rather than two.+ refusal = route_scan.empty_corpus_refusal(routes, route_scan.SERVICES_DIR)+ if refusal is not None:+ print(f"check_route_shadowing: scanned 0 routes under {route_scan.SERVICES_DIR}")+ print(f"\nFAIL: {refusal}", file=sys.stderr)+ return 2++ unreachable, deferred = find_shadowed(routes)+ unreadable = unresolved_paths(routes)++ files = len({r.path for r in routes})+ services = len({r.service for r in routes})+ print(+ f"check_route_shadowing: scanned {len(routes)} routes across {files} files "+ f"in {services} services under {route_scan.SERVICES_DIR}; "+ f"{len(deferred)} deferred to the runtime check, {len(unreadable)} path(s) not statically readable"+ )+ for line in deferred:+ print(f" deferred to the runtime check: {line}")+ for line in unreadable:+ print(f" path not a string literal, not judged here: {line}")++ if unreachable:+ print(f"\nFAIL: {len(unreachable)} unreachable route(s):", file=sys.stderr)+ for line in unreachable:+ print(f" {line}", file=sys.stderr)+ return 1++ print(f"OK: no literal route is shadowed by an earlier parameterised one ({len(deferred)} deferred to the runtime check).")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/check_route_tenant_scope.py b/scripts/check_route_tenant_scope.pyindex bc951988a..7b9429e26 100644--- a/scripts/check_route_tenant_scope.py+++ b/scripts/check_route_tenant_scope.py@@ -230,6 +230,14 @@ class Route:function: strmethods: list[str]route_path: str+ #: The router object the decorator hung off. Registration order only+ #: matters between routes on the *same* router, so the shadowing gate+ #: needs this to avoid pairing two routers that share a module.+ router_objs: list[str] = field(default_factory=list)+ #: False when a decorator was handed a variable instead of a literal, so+ #: ``route_path`` is empty because nothing could be read rather than+ #: because the route sits at a collection root.+ path_is_literal: bool = Truetenant_params: list[str] = field(default_factory=list)auth_deps: list[str] = field(default_factory=list)scope_calls: list[str] = field(default_factory=list)@@ -279,8 +287,13 @@ def _annotation_names(annotation: ast.expr | None) -> set[str]:return _names_in(annotation)-def _decorator_route_info(dec: ast.expr) -> tuple[str, str, str] | None:- """Return (router_object, method, route_path) for a route decorator."""+def _decorator_route_info(dec: ast.expr) -> tuple[str, str, str | None] | None:+ """Return (router_object, method, route_path) for a route decorator.++ ``route_path`` is ``None`` when the decorator was handed something other+ than a string literal, so a caller can tell "no path here to read" from+ "the path is the empty string".+ """if not isinstance(dec, ast.Call):return Nonefunc = dec.func@@ -289,7 +302,11 @@ def _decorator_route_info(dec: ast.expr) -> tuple[str, str, str] | None:if not isinstance(func.value, ast.Name):return Nonerouter_obj = func.value.id- route_path = ""+ # `None` rather than `""`: a decorator handed a variable and one handed+ # the empty string (a collection root, `@router.get("")`) are different+ # facts, and a reader that conflates them either skips 45 real routes or+ # reports them all as unreadable.+ route_path: str | None = Noneif dec.args and isinstance(dec.args[0], ast.Constant) and isinstance(dec.args[0].value, str):route_path = dec.args[0].valuereturn router_obj, func.attr, route_path@@ -397,7 +414,8 @@ def _scan_tree(tree: ast.AST, *, service: str, rel_path: str) -> list[Route]:continuemethods: list[str] = []- route_path = ""+ route_path: str | None = None+ path_is_literal = Truerouter_objs: set[str] = set()decorator_auth: set[str] = set()@@ -408,7 +426,10 @@ def _scan_tree(tree: ast.AST, *, service: str, rel_path: str) -> list[Route]:router_obj, method, path = inforouter_objs.add(router_obj)methods.append(method)- route_path = route_path or path+ if path is None:+ path_is_literal = False+ elif route_path is None:+ route_path = path# dependencies=[...] declared on the route decorator itselfassert isinstance(dec, ast.Call)for kw in dec.keywords:@@ -455,7 +476,9 @@ def _scan_tree(tree: ast.AST, *, service: str, rel_path: str) -> list[Route]:lineno=node.lineno,function=node.name,methods=sorted(set(methods)),- route_path=route_path,+ route_path=route_path or "",+ path_is_literal=path_is_literal,+ router_objs=sorted(router_objs),tenant_params=tenant_params,auth_deps=sorted(auth_deps),scope_calls=scope_calls,diff --git a/services/api/app/api/v1/endpoints/autonomy_policy.py b/services/api/app/api/v1/endpoints/autonomy_policy.pyindex a9a41bd01..9ce77dcde 100644--- a/services/api/app/api/v1/endpoints/autonomy_policy.py+++ b/services/api/app/api/v1/endpoints/autonomy_policy.py@@ -19,12 +19,14 @@ role — see ``services/api/app/core/security.py``).from __future__ import annotations+import refrom datetime import UTC, datetimeimport structlogfrom fastapi import APIRouter, HTTPException, Query, Request, statusfrom pydantic import BaseModel, Field, model_validatorfrom sqlalchemy import text+from starlette.convertors import Convertor, register_url_convertorfrom app._vendor.autonomy_evidence_rules import PromotionThresholdsfrom app.api.v1.deps import AuthUser, DBSession@@ -48,6 +50,66 @@ logger = structlog.get_logger()router = APIRouter(prefix="/autonomy-policy", tags=["autonomy-policy"])+# ---------------------------------------------------------------------------+# `{action}` sits at this router's root, so it competes with every literal+# sub-resource the router has. `DELETE /grants` lost that competition: FastAPI+# matches in registration order, `DELETE /{action}` is declared several hundred+# lines earlier, and so the revocation handler was unreachable. An operator+# could earn an autonomy grant and not hand it back, which is a safety control+# failing in the one direction that matters.+#+# Ordering the literals first would fix the symptom, but the constraint would+# live nowhere except the order of the file and the next edit could silently+# undo it. Constraining the parameter instead puts the exclusion in the route's+# own matching regex, which is what Starlette compares a request against:+# `/autonomy-policy/grants` no longer matches `/{action}` at all, so the+# literal route is reached wherever either one is declared.+#+# FastAPI's `Path(pattern=...)` cannot do this. It is validation applied after+# a route has already matched, so a reserved name would answer 422 instead of+# falling through, and pydantic's regex engine rejects look-around outright.+# Only a path convertor takes part in matching.+#+# The reserved set has to stay in step with the literals the router actually+# serves; `test_route_shadowing.py` asserts that against the running app rather+# than leaving it to be remembered here.+# ---------------------------------------------------------------------------++#: Literal sub-resources of this router. Not action names.+RESERVED_SEGMENTS = ("agreement", "grants", "shadow-mode")++#: Same shape `upsert_action_threshold` enforces on the body of an action name.+_MAX_ACTION_LEN = 100++#: The two routes that take an action spell this out rather than sharing a+#: constant, because a decorator given a variable is a path no static reader+#: can resolve, and `check_route_shadowing.py` would skip the pair silently.+#: Drift is not a risk: Starlette raises on an unknown convertor at import.+ACTION_CONVERTOR_NAME = "autonomy_action"+++class _ActionNameConvertor(Convertor):+ """An action name: alphanumeric and underscores, and never a sub-resource.++ Built from `RESERVED_SEGMENTS` rather than written out, so the tuple above+ and the regex here cannot come to disagree.+ """++ regex = r"(?!(?:{})\Z)[A-Za-z0-9_]{{1,{}}}".format(+ "|".join(re.escape(segment) for segment in RESERVED_SEGMENTS),+ _MAX_ACTION_LEN,+ )++ def convert(self, value: str) -> str:+ return value++ def to_string(self, value: str) -> str:+ return value+++register_url_convertor(ACTION_CONVERTOR_NAME, _ActionNameConvertor())++# ---------------------------------------------------------------------------# Hard-coded reference policy (kept in sync with# services/agents/app/policy/guardrails.py::_DEFAULT_THRESHOLDS).@@ -319,7 +381,7 @@ async def get_autonomy_policy(return AutonomyPolicyResponse(tenant_id=str(user.tenant_id), actions=actions)[email protected]("/{action}", response_model=ThresholdUpdateResponse)[email protected]("/{action:autonomy_action}", response_model=ThresholdUpdateResponse)async def upsert_action_threshold(action: str,payload: ThresholdUpdateRequest,@@ -445,7 +507,7 @@ async def upsert_action_threshold()[email protected]("/{action}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)[email protected]("/{action:autonomy_action}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)async def reset_action_threshold(action: str,user: AuthUser,diff --git a/services/api/tests/test_autonomy_grant_revocation.py b/services/api/tests/test_autonomy_grant_revocation.pynew file mode 100644index 000000000..46b612c1c--- /dev/null+++ b/services/api/tests/test_autonomy_grant_revocation.py@@ -0,0 +1,195 @@+"""An operator can hand an earned autonomy grant back.++``DELETE /api/v1/autonomy-policy/grants`` was unreachable from the day it+shipped. ``DELETE /{action}`` is declared several hundred lines earlier in the+same router, FastAPI matches in registration order, and so the request was+taken by the threshold-reset handler with ``action="grants"``. The revocation+never ran, and the caller got a 204 saying it had: a safety control that only+worked in the direction that hands autonomy *out*.++The damage is what makes the two handlers easy to tell apart, and this drives+the real route rather than the handler function so that it can tell them+apart. A revocation issues ``UPDATE aisoc_autonomy_grants``; the reset issues+``DELETE FROM aisoc_autonomy_thresholds``. Before the fix this request quietly+did the second one, so a test that asserted only on the status code would have+passed against the defect.+"""++from __future__ import annotations++import uuid+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++TENANT_ID = uuid.UUID("11111111-1111-4111-8111-111111111111")+USER_ID = uuid.UUID("22222222-2222-4222-8222-222222222222")++GRANT_QUERY = {"scope_kind": "action_verb", "scope_key": "close_alert", "capability": "auto_close"}+++class _Result:+ """Enough of a SQLAlchemy result for the statements this route issues."""++ def __init__(self, rowcount: int = 1) -> None:+ self.rowcount = rowcount++ def mappings(self) -> _Result:+ return self++ def all(self) -> list:+ return []++ def first(self) -> None:+ return None++ def scalar_one_or_none(self) -> None:+ return None+++class _RecordingSession:+ """Records what the route told the database, which is the evidence here."""++ def __init__(self, *, rowcount: int = 1) -> None:+ self.statements: list[tuple[str, dict]] = []+ self.added: list[Any] = []+ self._rowcount = rowcount+ self.committed = 0++ async def execute(self, statement: Any, params: dict | None = None) -> _Result:+ self.statements.append((str(statement), params or {}))+ return _Result(rowcount=self._rowcount)++ def add(self, instance: Any) -> None:+ self.added.append(instance)++ async def flush(self) -> None:+ return None++ async def commit(self) -> None:+ self.committed += 1++ async def rollback(self) -> None:+ return None++ def sql_touching(self, table: str) -> list[str]:+ return [sql for sql, _ in self.statements if table in sql]++ def audit_actions(self) -> list[str]:+ return [getattr(row, "action", "") for row in self.added]+++class _Principal:+ """The authenticated caller. The tenant comes from here, never the request."""++ def __init__(self) -> None:+ self.tenant_id = TENANT_ID+ self.user_id = USER_ID+ self.email = "[email protected]"++ async def require_permission_db(self, permission: str, db: Any) -> None:+ assert permission == "settings:write"+++def session() -> _RecordingSession:+ return _RecordingSession()+++def client(session: _RecordingSession) -> TestClient:+ autonomy_policy = pytest.importorskip("app.api.v1.endpoints.autonomy_policy")+ deps = pytest.importorskip("app.api.v1.deps")+ rls = pytest.importorskip("app.db.rls")++ app = FastAPI()+ app.include_router(autonomy_policy.router, prefix="/api/v1")+ app.dependency_overrides[deps.get_current_user] = _Principal+ app.dependency_overrides[rls.get_tenant_db] = lambda: session+ app.dependency_overrides[deps.get_db] = lambda: session+ return TestClient(app, raise_server_exceptions=False)+++def test_revoking_a_grant_reaches_the_revocation(client: TestClient, session: _RecordingSession) -> None:+ """The regression. Asserted on what the database was told, because the+ handler that used to answer this request also returned 204."""+ response = client.request("DELETE", "/api/v1/autonomy-policy/grants", params=GRANT_QUERY)++ assert response.status_code == 204, response.text+ revocations = session.sql_touching("aisoc_autonomy_grants")+ assert revocations, (+ f"no statement touched aisoc_autonomy_grants; the request was answered by something other than the revocation: {session.statements}"+ )+ assert "UPDATE aisoc_autonomy_grants" in revocations[0]+ assert session.committed == 1+++def test_the_revocation_is_audited_as_a_revocation(client: TestClient, session: _RecordingSession) -> None:+ """A human stopping and the evidence stopping them are different events.++ One word for both would make "was this taken away because the numbers+ slipped" unanswerable from the log, which is the reason the service keeps+ a separate audit action for it.+ """+ autonomy_grants = pytest.importorskip("app.services.autonomy_grants")++ client.request("DELETE", "/api/v1/autonomy-policy/grants", params=GRANT_QUERY)++ assert autonomy_grants.AUDIT_REVOKED in session.audit_actions()+++def test_revoking_a_grant_does_not_reset_a_threshold(client: TestClient, session: _RecordingSession) -> None:+ """What the defect actually did, named so it cannot come back unnoticed.++ ``action="grants"`` deleted the tenant's threshold override for an action+ called "grants". Harmless only because no such action exists; the point is+ that the request reached the wrong table entirely.+ """+ client.request("DELETE", "/api/v1/autonomy-policy/grants", params=GRANT_QUERY)++ assert session.sql_touching("aisoc_autonomy_thresholds") == []+++def test_resetting_a_threshold_still_works(client: TestClient, session: _RecordingSession) -> None:+ """The parameterised route keeps its own traffic.++ Constraining ``{action}`` narrows it to names that are not sub-resources,+ and nothing else.+ """+ response = client.request("DELETE", "/api/v1/autonomy-policy/close_alert")++ assert response.status_code == 204, response.text+ assert session.sql_touching("aisoc_autonomy_thresholds")+ assert session.sql_touching("aisoc_autonomy_grants") == []+++def test_revoking_a_grant_nobody_holds_is_a_404(session: _RecordingSession) -> None:+ """A revocation that matched no standing grant is not a silent success."""+ autonomy_policy = pytest.importorskip("app.api.v1.endpoints.autonomy_policy")+ deps = pytest.importorskip("app.api.v1.deps")+ rls = pytest.importorskip("app.db.rls")++ empty = _RecordingSession(rowcount=0)+ app = FastAPI()+ app.include_router(autonomy_policy.router, prefix="/api/v1")+ app.dependency_overrides[deps.get_current_user] = _Principal+ app.dependency_overrides[rls.get_tenant_db] = lambda: empty++ response = TestClient(app, raise_server_exceptions=False).request("DELETE", "/api/v1/autonomy-policy/grants", params=GRANT_QUERY)++ assert response.status_code == 404+ assert empty.committed == 0+++def test_a_scope_outside_the_vocabulary_is_refused(client: TestClient, session: _RecordingSession) -> None:+ """A capability no code path consults must not be revocable either."""+ response = client.request(+ "DELETE",+ "/api/v1/autonomy-policy/grants",+ params={**GRANT_QUERY, "capability": "auto_everything"},+ )++ assert response.status_code == 422+ assert session.sql_touching("aisoc_autonomy_grants") == []diff --git a/services/api/tests/test_route_shadowing.py b/services/api/tests/test_route_shadowing.pyindex 432cf56db..0240d64d5 100644--- a/services/api/tests/test_route_shadowing.py+++ b/services/api/tests/test_route_shadowing.py@@ -1,90 +1,270 @@-"""No literal route may be shadowed by an earlier parameterised route.+"""Every route the app publishes must be the route that answers for it.-FastAPI matches routes in registration order. If ``GET /{asset_id}`` is-registered before ``GET /vulnerabilities``, then a request for-``/assets/vulnerabilities`` is matched by the first route, fails to parse-"vulnerabilities" as a UUID, and returns 422 — the literal handler is simply-unreachable, and nothing in CI noticed because both routes exist and both have-tests that call them directly.+FastAPI matches in registration order. If ``DELETE /{action}`` is registered+before ``DELETE /grants``, a request for ``/autonomy-policy/grants`` is taken+by the first route with ``action="grants"`` and the revocation handler is+simply unreachable. Nothing in review catches it: the two declarations sit+hundreds of lines apart and each is correct on its own.-That is exactly what had happened to ``GET /api/v1/assets/vulnerabilities``.+That is not hypothetical here. ``DELETE /api/v1/autonomy-policy/grants`` was+unreachable from the day it shipped, so an operator could earn an autonomy+grant and had no way to hand it back: a safety control that failed in the one+direction that matters. ``GET /api/v1/assets/vulnerabilities`` had gone the+same way earlier.-This is a generic structural check rather than a test of one endpoint, because-the failure mode is easy to reintroduce and invisible in review: the two route-declarations are usually tens of lines apart and each looks correct on its own.+Why the previous version of this file never saw either+------------------------------------------------------+It read ``app.routes`` and filtered for ``APIRoute``. On the FastAPI version+these services pin, ``include_router`` does not put routes there: it appends a+single ``_IncludedRouter`` object, and the only ``APIRoute``\\ s the list holds+are the handful of docs and probe routes the app was born with. Filtering that+list yields **zero** routes, so the check compared zero pairs, found zero+problems and reported success, over an app serving 456 operations. Run against+a newer FastAPI it failed, and the failure was real; that disagreement is the+only reason anyone looked.++So the corpus comes from ``app.openapi()``, which is what the deployed app+publishes, and reachability is decided by **sending a request** and reading+back which route Starlette matched. Both of those reflect the served app+rather than an internal list whose meaning changed under us. The same lesson+is recorded on the shadow-reconcile route test in ``services/actions``.++And because "found nothing" and "scanned nothing" print the same word, the+check refuses a corpus smaller than :data:`MINIMUM_PUBLISHED_OPERATIONS`+rather than reporting an empty app clean. That is the rule+``scripts/gate_toolkit.py`` applies to every gate under ``scripts/``; it+applies here for the same reason."""from __future__ import annotations+import re+from collections.abc import Iterator+from typing import Any+import pytest-from fastapi.routing import APIRoute+from fastapi import APIRouter, FastAPI+from fastapi.testclient import TestClient+#: The floor the corpus has to clear before any verdict is rendered. The app+#: publishes several hundred operations; the failure this guards against is+#: the corpus collapsing to the seven docs and probe routes, which is exactly+#: what happened when the inventory came from ``app.routes``. A floor cannot+#: be a target, so it sits well under the real count and is only ever tripped+#: by a collapse.+MINIMUM_PUBLISHED_OPERATIONS = 200-#: A path segment that is a literal, not a ``{param}`` placeholder.-def _segments(path: str) -> list[str]:- return [s for s in path.split("/") if s]+#: Verbs worth probing. ``head``/``options``/``trace`` are answered by+#: Starlette itself rather than by a declared handler.+PROBED_METHODS = ("get", "put", "post", "delete", "patch")+_PARAM = re.compile(r"\{[^}]+\}")-def _is_param(segment: str) -> bool:- return segment.startswith("{") and segment.endswith("}")+class EmptyRouteCorpus(RuntimeError):+ """Raised when there is not enough of an app to render a verdict about."""-def _shadows(earlier: str, later: str) -> bool:- """True if a request for ``later`` would be captured by ``earlier``.- Only meaningful when the two have the same segment count and every- differing segment in ``earlier`` is a parameter.+def _shape(path: str) -> tuple[str, ...]:+ """A path reduced to which segments are literal and which are parameters.++ Compared rather than the path itself because the route object reports its+ own path without whatever prefix it was included under, so the strings+ never match even when the routes do.+ """+ return tuple("{}" if s.startswith("{") and s.endswith("}") else s for s in path.split("/") if s)+++def _probe_url(path: str) -> str:+ """A concrete URL for a published path, with parameters filled in.++ The filler is alphanumeric, which satisfies every path convertor in this+ tree including the one guarding ``{action}``.+ """+ counter = 0++ def fill(_: re.Match[str]) -> str:+ nonlocal counter+ counter += 1+ return f"aisocprobe{counter}"++ return _PARAM.sub(fill, path)+++class _RouteRecorder:+ """ASGI wrapper that remembers which route Starlette matched.++ ``scope`` is one dict all the way down, so the route the router records on+ it is visible again once the call returns. Routing happens before+ authentication, so a 401 still answers the only question being asked.++ ``finally``, because a handler that raises would otherwise leave the route+ unrecorded and read as unreachable."""- a, b = _segments(earlier), _segments(later)- if len(a) != len(b):- return False- saw_param_over_literal = False- for seg_a, seg_b in zip(a, b, strict=True):- if seg_a == seg_b:- continue- if _is_param(seg_a) and not _is_param(seg_b):- saw_param_over_literal = True- continue- return False- return saw_param_over_literal+ def __init__(self, app: Any) -> None:+ self.app = app+ self.route: Any = None-def test_no_literal_route_is_shadowed_by_an_earlier_parameterised_route():- # Importing the app pulls the full driver stack (neo4j, clickhouse, ...).- # CI installs those; a bare checkout may not, and the helper tests below- # still give useful signal there.- app = pytest.importorskip("app.main", reason="full app dependencies not installed").app- routes = [r for r in app.routes if isinstance(r, APIRoute)]+ async def __call__(self, scope: dict, receive: Any, send: Any) -> None:+ self.route = None+ try:+ await self.app(scope, receive, send)+ finally:+ self.route = scope.get("route")+++def _published_operations(app: FastAPI) -> list[tuple[str, str]]:+ return [(method, path) for path, operations in app.openapi()["paths"].items() for method in operations if method in PROBED_METHODS]+++def unreachable_routes(app: FastAPI, *, minimum: int = MINIMUM_PUBLISHED_OPERATIONS) -> list[str]:+ """Every published operation that a *different* route answers for.++ Raises :class:`EmptyRouteCorpus` rather than returning ``[]`` when the app+ publishes less than ``minimum`` operations.+ """+ operations = _published_operations(app)+ if len(operations) < minimum:+ raise EmptyRouteCorpus(+ f"{len(operations)} published operation(s) is below the floor of {minimum}: "+ "refusing to report an app this small as clean, because a corpus that "+ "collapsed and a corpus with no problems are the same empty list."+ )++ recorder = _RouteRecorder(app)+ # Redirects are not followed: a handler that answers 302 would otherwise+ # have the *followed* request's route recorded over its own.+ client = TestClient(recorder, raise_server_exceptions=False, follow_redirects=False)problems: list[str] = []- for i, later in enumerate(routes):- for earlier in routes[:i]:- shared_methods = earlier.methods & later.methods- if not shared_methods:- continue- if _shadows(earlier.path, later.path):- problems.append(- f"{sorted(shared_methods)} {later.path} is unreachable: "- f"{earlier.path} is registered first and will match it. "- f"Move the literal route above the parameterised one."- )-- assert not problems, "shadowed routes found:\n " + "\n ".join(problems)--- ("earlier", "later", "expected"),- [- ("/assets/{asset_id}", "/assets/vulnerabilities", True),- ("/hunts/{hunt_id}", "/hunts/runs", True),- # Different arity cannot shadow.- ("/assets/{asset_id}", "/assets/{asset_id}/vulnerabilities", False),- # Literal-before-literal is fine.- ("/assets/summary", "/assets/vulnerabilities", False),- # A parameter in the *later* path is not shadowed by a literal.- ("/assets/vulnerabilities", "/assets/{asset_id}", False),- ],-)-def test_shadow_detection_itself(earlier: str, later: str, expected: bool):- """The helper has to be right or the gate above is worthless."""- assert _shadows(earlier, later) is expected+ for method, path in operations:+ response = client.request(method.upper(), _probe_url(path))+ matched = recorder.route+ if matched is None:+ problems.append(f"{method.upper()} {path} is published but no route matched it (status {response.status_code})")+ continue+ served = _shape(getattr(matched, "path_format", ""))+ # The matched route carries no mount prefix, so compare the tail.+ declared_tail = _shape(path)[-len(served) :] if served else ()+ if served != declared_tail:+ problems.append(+ f"{method.upper()} {path} is unreachable: it is answered by "+ f"/{'/'.join(served)} ({matched.name}), which is registered first and matches it"+ )+ return problems+++# ── the gate ───────────────────────────────────────────────────────────────++[email protected](scope="module")+def deployed_app() -> FastAPI:+ # CI installs the full driver stack; a bare checkout may not, and the+ # synthetic cases below still give signal there.+ return pytest.importorskip("app.main", reason="full app dependencies not installed").app+++def test_no_route_the_app_publishes_is_unreachable(deployed_app: FastAPI) -> None:+ problems = unreachable_routes(deployed_app)+ assert not problems, "unreachable routes found:\n " + "\n ".join(problems)+++def test_the_corpus_is_the_deployed_app_rather_than_a_handful_of_probes(deployed_app: FastAPI) -> None:+ """The regression that made the previous gate vacuous.++ Reading ``app.routes`` here yields the docs and probe routes alone. If the+ inventory ever collapses back to that, this fails instead of the gate+ above quietly passing over nothing.+ """+ assert len(_published_operations(deployed_app)) >= MINIMUM_PUBLISHED_OPERATIONS+++# ── the gate has to be able to fail ────────────────────────────────────────+++def _synthetic(*, shadowed: bool) -> FastAPI:+ """The real defect, reduced: a collection behind a sibling parameter."""+ router = APIRouter(prefix="/autonomy-policy")++ if shadowed:++ @router.delete("/{action}")+ async def reset(action: str) -> dict:+ return {"action": action}++ else:++ @router.delete("/{action:autonomy_action}")+ async def reset(action: str) -> dict: # type: ignore[misc]+ return {"action": action}++ @router.delete("/grants")+ async def revoke() -> dict:+ return {"revoked": True}++ app = FastAPI()+ app.include_router(router, prefix="/api/v1")+ return app++[email protected](scope="module", autouse=True)+def _convertor_registered() -> Iterator[None]:+ # Registering the convertor is a side effect of importing the endpoint+ # module, which the synthetic control below relies on without wanting the+ # rest of the app.+ pytest.importorskip("app.api.v1.endpoints.autonomy_policy", reason="api package not importable")+ yield+++def test_the_check_reports_a_shadowed_route() -> None:+ """A gate only demonstrates something if it can fail.++ Proven against the defect as it shipped: the parameterised route first,+ the collection after it.+ """+ problems = unreachable_routes(_synthetic(shadowed=True), minimum=1)+ assert len(problems) == 1, problems+ assert "DELETE /api/v1/autonomy-policy/grants is unreachable" in problems[0]+ assert "reset" in problems[0]+++def test_the_check_passes_a_route_the_parameter_no_longer_swallows() -> None:+ """The control, with the declarations in the same order as the failing case.++ Only the constraint on the parameter differs, so a pass here is the+ constraint working rather than the ordering having been changed.+ """+ assert unreachable_routes(_synthetic(shadowed=False), minimum=1) == []+++def test_the_check_refuses_an_app_with_nothing_in_it() -> None:+ with pytest.raises(EmptyRouteCorpus):+ unreachable_routes(FastAPI())+++# ── the exclusion list cannot go stale ─────────────────────────────────────+++def test_every_literal_sub_resource_of_the_autonomy_router_is_reserved() -> None:+ """The reserved set is what keeps ``{action}`` off its siblings.++ Derived from the router as it is actually served rather than read back+ from the tuple it was built from, so a sub-resource added later and not+ reserved fails here instead of becoming the next unreachable route.+ """+ autonomy_policy = pytest.importorskip("app.api.v1.endpoints.autonomy_policy")++ app = FastAPI()+ app.include_router(autonomy_policy.router)+ prefix_depth = len(_shape(autonomy_policy.router.prefix))++ literals = {+ segments[prefix_depth]+ for path in app.openapi()["paths"]+ if len(segments := _shape(path)) > prefix_depth and segments[prefix_depth] != "{}"+ }+ unreserved = literals - set(autonomy_policy.RESERVED_SEGMENTS)+ assert not unreserved, (+ f"sub-resource(s) {sorted(unreserved)} sit beside {{action}} but are not in RESERVED_SEGMENTS, so {{action}} can swallow them"+ )