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
Four alembic chains that migrated as the role the policies apply to (#827)
Beenu Arora118b41d85844
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymlindex 28657c0c1..775a654d8 100644--- a/.github/workflows/integration.yml+++ b/.github/workflows/integration.yml@@ -377,26 +377,77 @@ jobs:- name: Runtime DB role cannot bypass RLS (live)run: python scripts/check_runtime_db_role.py --dsn "$DATABASE_URL" --owner-dsn "$DATABASE_MIGRATION_URL"- # The UEBA package layout (app/ dir) isn't wheel-buildable; alembic's- # env.py only needs `app.models.ueba` importable, so run in-place with+ # These four service layouts (app/ dir) aren't wheel-buildable; each+ # env.py only needs its own `app.*` importable, so run in-place with# PYTHONPATH instead of pip-installing the service.- name: Install alembic- run: pip install --quiet alembic+ run: pip install --quiet alembic "sqlalchemy[asyncio]" asyncpg pydantic pydantic-settings- - name: UEBA alembic round-trip (upgrade → downgrade → upgrade)- working-directory: services/ueba+ # Four chains, each in its own database, and each applied with **only**+ # its migration variable in the environment — no DATABASE_URL at all.+ #+ # That is deliberate and is the behavioural half of a static check.+ # `scripts/check_runtime_db_role.py` can read which variables an env.py+ # *names*; it cannot run the file, so an env.py naming a migration+ # credential it never reads would pass there. Here it cannot: with no+ # runtime variable set, a chain that ignores its migration variable+ # falls back to the hard-coded localhost default and fails to connect.+ - name: Alembic round-trips as the owner only (upgrade → downgrade → upgrade)env:- PYTHONPATH: .- # Dedicated database so the SQL-runner schema above is untouched.- # aisoc-db-role: owner — alembic applies DDL and reads DATABASE_URL by its own convention- DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_ci_secret@localhost:5432/ueba_ci+ PGPASSWORD: aisoc_ci_secretrun: |set -euo pipefail- PGPASSWORD=aisoc_ci_secret psql -h localhost -U aisoc -d aisoc -c "CREATE DATABASE ueba_ci"- alembic upgrade head- alembic downgrade base- alembic upgrade head- echo "alembic round-trip clean"+ for db in ueba_ci honeytokens_ci purple_team_ci osquery_tls_ci; do+ psql -h localhost -U aisoc -d aisoc -c "CREATE DATABASE $db"+ done+ # aisoc-db-role: owner — alembic applies DDL; these are the owner's, and no runtime DSN is set here+ owner=postgresql+asyncpg://aisoc:aisoc_ci_secret@localhost:5432+ round_trip () {+ echo "── $1 ($2)"+ ( cd "services/$1" \+ && env -u DATABASE_URL PYTHONPATH=. "$2=$owner/$3" sh -euc \+ 'alembic upgrade head && alembic downgrade base && alembic upgrade head' )+ }+ round_trip ueba UEBA_DATABASE_MIGRATION_URL ueba_ci+ round_trip honeytokens HONEYTOKEN_DATABASE_MIGRATION_URL honeytokens_ci+ round_trip purple-team PURPLE_TEAM_DATABASE_MIGRATION_URL purple_team_ci+ round_trip osquery-tls AISOC_OSQUERY_TLS_DATABASE_MIGRATION_URL osquery_tls_ci+ echo "alembic round-trips clean"++ # The four chains share one database in the default deployment, and used+ # to share one `alembic_version` table with it — so the second chain to+ # run believed it was already at head. Measured before the fix: after+ # ueba reached 0002, honeytokens ran zero migrations and purple-team+ # failed applying RLS to tables that were never created, leaving two+ # services with no tenant policies and nothing saying so.+ #+ # The assertion is on the tables, not on the exit status: every chain+ # "succeeded" while that was true.+ - name: Four chains, one database (per-chain version tables)+ env:+ PGPASSWORD: aisoc_ci_secret+ run: |+ set -euo pipefail+ psql -h localhost -U aisoc -d aisoc -c "CREATE DATABASE shared_ci"+ # aisoc-db-role: owner — the four chains apply DDL here; no runtime DSN is set+ shared=postgresql+asyncpg://aisoc:aisoc_ci_secret@localhost:5432/shared_ci+ for pair in "ueba:UEBA_DATABASE_MIGRATION_URL" \+ "honeytokens:HONEYTOKEN_DATABASE_MIGRATION_URL" \+ "purple-team:PURPLE_TEAM_DATABASE_MIGRATION_URL" \+ "osquery-tls:AISOC_OSQUERY_TLS_DATABASE_MIGRATION_URL"; do+ ( cd "services/${pair%%:*}" && env -u DATABASE_URL PYTHONPATH=. "${pair##*:}=$shared" alembic upgrade head )+ done+ missing=0+ for t in ueba_anomalies honeytokens honeytoken_triggers \+ purple_team_executions purple_team_detection_drift_snapshots \+ osquery_node fim_event; do+ if [ "$(psql -h localhost -U aisoc -d shared_ci -tAc "SELECT to_regclass('public.$t') IS NOT NULL")" != "t" ]; then+ echo "::error::$t was not created — a chain believed itself at head over a sibling's version row"+ missing=$((missing + 1))+ fi+ done+ [ "$missing" -eq 0 ] || exit 1+ echo "all four chains applied to one database"# ── Disaster recovery: an untested backup is not a backup ─────────────────backup-restore:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex df34adb3e..2d3354795 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -920,6 +920,73 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **The four services that run their own alembic chain now migrate as the+ owner and serve as the runtime role, and three of them were not reached by+ the role switch at all.** `honeytokens`, `osquery-tls`, `purple-team` and+ `ueba` manage their own schema, and each applied it as whatever DSN the+ operator supplied — so their migration and runtime credentials were the same+ one, and pointing such a service at the owner turned off row-level security+ for the twelve tables those chains own with nothing objecting. Each+ `env.py` now reads `<SERVICE>_DATABASE_MIGRATION_URL`, then+ `DATABASE_MIGRATION_URL`, and only then falls back to the runtime DSN with a+ warning on stderr naming what will break.++ Three things were found while wiring it, each measured rather than inferred:++ - **`DATABASE_URL` was inert on three of the four.** `docker-compose.yml`+ sets it on every service, but `honeytokens`, `purple-team` and+ `osquery-tls` declare `env_prefix` in their settings, so the name they+ read is `HONEYTOKEN_DATABASE_URL` and the compose entry did nothing: each+ fell back to a default naming the **owner**. Both spellings now resolve,+ unprefixed first, the convention `services/ueba` and `services/fusion`+ already used. Operator note: on a deployment that sets both to *different*+ databases, the unprefixed one now wins.+ - **The four chains shared one `alembic_version` table** — they share one+ database in the default deployment and number their revisions identically.+ Following `apps/docs/docs/quickstart.md` against `postgres:16`: after+ `ueba` reached `0002`, `honeytokens alembic upgrade head` ran **zero**+ migrations and `purple-team` failed applying its RLS revision to tables+ that had never been created, so two services had no tables and no policies+ and every command reported success. Each chain now keeps its own version+ table and adopts an existing deployment's recorded version on the next+ upgrade — only when that chain's own tables are already present, so it+ cannot claim a sibling's row.+ - **The runtime role had no grant on those tables.**+ `061_runtime_app_role.sql` grants over `ALL TABLES` as they stood and sets+ `ALTER DEFAULT PRIVILEGES` for the role that issued it; nothing orders the+ chains against it, and a deployment applying them under different owners+ gets neither. Each chain now grants `SELECT, INSERT, UPDATE, DELETE` on its+ own tables, guarded so it is a notice rather than a failure where the role+ does not exist.++ Verified live on `postgres:16` with all four chains applied and two tenants+ seeded: bound to one tenant the runtime role sees one row of two in+ `ueba_entity_baselines`, `honeytokens` and `osquery_node`; unbound it sees+ both, which is the fail-open arm the cross-tenant sweeps depend on; a+ cross-tenant insert is refused by the policy; `CREATE TABLE` is refused with+ `permission denied for schema public`; `ALTER TABLE … NO FORCE ROW LEVEL+ SECURITY` with `must be owner of table`; and `SET LOCAL row_security = off`+ raises rather than doing nothing. None of the four chains creates a view, so+ the `security_invoker` hazard does not arise there, and none of the four+ services issues DDL outside its chain.++- **`approval_timers` is in a migration and carries a policy.**+ `services/slack-bot`'s `PostgresTimerStore` created it at startup with+ `CREATE TABLE IF NOT EXISTS`, outside every chain in the repository — so+ `060_rls_coverage.sql` never saw it, it had no `tenant_id` for a policy to+ filter on, and it decides whether a pending containment auto-rejects. Under+ the DML-only runtime role the DDL itself fails, because Postgres checks the+ schema ACL before the existence test, and `main.py` caught that into a+ warning and fell back to the non-durable store: durable approval timers+ would have quietly stopped being durable. `062_approval_timers.sql` adds the+ table, a `tenant_id`, and the canonical policy; the store probes with+ `to_regclass` and refuses with the migration's name rather than creating+ anything, carries the tenant in every statement, and binds+ `app.current_tenant_id` on each pooled connection so the policy engages too.+ A deployment already carrying the runtime-created table converges on the+ same shape, with its existing rows defaulting to an empty `tenant_id` that+ the migration says how to backfill.+- **The services no longer connect to Postgres as a superuser, so the 92row-level-security policies added below now actually filter.** The previousentry closed the coverage gap and measured, in the same breath, that none of@@ -1364,6 +1431,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **Two more gates were exempt from the empty-corpus rule only by accident.**+ `check_route_auth.py` and `check_tenant_query_predicates.py` did not exit 0+ over an empty tree, but neither had a corpus floor: each happened to fail+ first on its own stale-exemption ratchet, because every entry stopped+ matching at once. That is a true statement about the wrong thing, and it+ disappears the moment somebody empties the table. Both now refuse the+ corpus itself, ahead of every output mode including `--inventory`, which CI+ runs as its own step — a green step printing `TOTAL 0` is the same defect+ one level out. The route gates share one floor, in+ `check_route_tenant_scope.py`, because they share one collector; the+ predicate gate refuses each of the three ways its scan can empty+ separately, since files, tenant-scoped tables and statements reaching zero+ are three different losses and the middle one is the quiet one. Proven both+ ways: with every exemption table emptied the floor is still what refuses,+ and the real repository is unaffected.++ `check_route_auth.py` now imports its scanner as a module rather than by+ name. It took `REPO_ROOT` and `SERVICES_DIR` by value at import time, so the+ shared self-test rebinding them would have left this gate scanning the real+ checkout while believing it was pointed at an empty one — a self-test that+ proves nothing, which is the shape the whole exercise is about.++- **`check_gate_contract.py` can now ask "the directory exists and is empty",+ not only "the repository is not there".** Its scratch tree omitted+ `services/` and `detections/` entirely, so a gate opening with+ `if not X.is_dir(): return 2` refused it for a reason that says nothing+ about its corpus — and the way a corpus is actually lost is a renamed+ package or a glob that stopped matching, neither of which removes the+ directory. A second **skeleton** shape creates them empty and every check is+ probed against both. The cost was measured rather than assumed before+ committing to it: 64 of the 71 checks already refused the skeleton, and of+ the five that did not, three were defects now fixed and two were already+ recorded exceptions. The exception table is keyed by shape and has five+ entries. Probe runtime went from ~8 s to ~16 s.+- **`check_route_tenant_scope.py` reported OK having scanned zero routes.** Itrefused a tree with no `services/` directory, which is not how a scan losesits corpus: a renamed package, a changed decorator spelling or a walk thatdiff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.mdindex 7b711e695..6e355f33b 100644--- a/apps/docs/docs/deployment/env-vars.md+++ b/apps/docs/docs/deployment/env-vars.md@@ -124,7 +124,43 @@ even under `FORCE ROW LEVEL SECURITY`. See| Variable | Default | Description ||----------|---------|-------------|| `DATABASE_URL` | `postgresql+asyncpg://aisoc_app:aisoc_app_dev_secret@localhost:5432/aisoc` | Async Postgres DSN for the **runtime** role. DML only. |-| `DATABASE_MIGRATION_URL` | unset → falls back to `DATABASE_URL` | Async Postgres DSN for the **owner**. Used only by `python -m app.scripts.run_migrations`, which needs DDL. |+| `DATABASE_MIGRATION_URL` | unset → falls back to `DATABASE_URL` | Async Postgres DSN for the **owner**. Read by `python -m app.scripts.run_migrations` and by the four alembic chains below, all of which need DDL. |++#### The four services that manage their own schema++`honeytokens`, `osquery-tls`, `purple-team` and `ueba` run their own alembic+chain rather than the API's SQL runner, and until now each applied it as+whatever DSN the operator supplied — so their migration and runtime+credentials were the same one. Pointing such a service at the owner turned off+row-level security for the twelve tables those chains own, and nothing+objected.++Each now reads a migration credential first and falls back to the runtime one+with a warning on stderr:++| Service | Migration DSN (owner) | Runtime DSN |+|---------|-----------------------|-------------|+| `honeytokens` | `HONEYTOKEN_DATABASE_MIGRATION_URL`, then `DATABASE_MIGRATION_URL` | `DATABASE_URL`, then `HONEYTOKEN_DATABASE_URL` |+| `osquery-tls` | `AISOC_OSQUERY_TLS_DATABASE_MIGRATION_URL`, then `DATABASE_MIGRATION_URL` | `DATABASE_URL`, then `AISOC_OSQUERY_TLS_DATABASE_URL` |+| `purple-team` | `PURPLE_TEAM_DATABASE_MIGRATION_URL`, then `DATABASE_MIGRATION_URL` | `DATABASE_URL`, then `PURPLE_TEAM_DATABASE_URL` |+| `ueba` | `UEBA_DATABASE_MIGRATION_URL`, then `DATABASE_MIGRATION_URL` | `DATABASE_URL`, then `UEBA_DATABASE_URL` |++Two things changed alongside, both of which an operator can observe:++- **The unprefixed `DATABASE_URL` now reaches all four.** `honeytokens`,+ `purple-team` and `osquery-tls` previously read only their prefixed+ spelling, while `docker-compose.yml` set the unprefixed one — so the+ variable was inert and each fell back to a default naming the *owner*. The+ prefixed spelling still works; the unprefixed one wins when both are set.+- **Each chain keeps its own alembic version table** (`alembic_version_ueba`+ and so on). They share one database in the default deployment and used to+ share one `alembic_version`, so the second chain to run believed it was+ already at head — measured: after `ueba` reached `0002`, `honeytokens+ alembic upgrade head` ran zero migrations and `purple-team` failed applying+ its RLS revision to tables that had never been created. An existing+ deployment is adopted automatically on the next `alembic upgrade`: the+ recorded version is copied into the per-chain table when, and only when,+ that chain's own tables are already present.| `AISOC_APP_DB_PASSWORD` | `aisoc_app_dev_secret` in compose; unset elsewhere | Password applied to the runtime role, by the postgres init hook on a fresh volume and by the migration runner on every run. Unset leaves the role's credential alone. || `DATABASE_POOL_SIZE` | `20` | SQLAlchemy pool size || `DATABASE_MAX_OVERFLOW` | `10` | SQLAlchemy max overflow |@@ -285,7 +321,7 @@ The table below shows the canonical (unprefixed) name first and the legacy alias| `HOST` | `UEBA_HOST` | `0.0.0.0` | HTTP listener interface || `PORT` | `UEBA_PORT` | `8004` | HTTP listener port |-`services/ueba/alembic/env.py` follows the same rule: it reads `DATABASE_URL` first and falls back to `UEBA_DATABASE_URL`, so `alembic upgrade head` and the running service always see the same DSN.+`services/ueba/alembic/env.py` no longer follows the same rule, deliberately. It reads `UEBA_DATABASE_MIGRATION_URL`, then `DATABASE_MIGRATION_URL`, and only then falls back to the runtime DSN — because `alembic upgrade` issues DDL and the runtime role holds none. See [The four services that manage their own schema](#the-four-services-that-manage-their-own-schema).---diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.mdindex 3da82d2c1..7da7a5eb9 100644--- a/apps/docs/docs/operations/security.md+++ b/apps/docs/docs/operations/security.md@@ -183,6 +183,16 @@ Every service runs as the scoped runtime role. Nothing needs a cross-tenant cred| retention purge / hunt scheduler / tenant deletion (in-process in `api`) | runtime, unbound | Cross-tenant by design, and now assert that no tenant is bound before sweeping. || migration runner, `alembic`, `scripts/backup.sh` | owner | DDL, and a dump that has to read and rewrite tables the runtime role cannot. |+#### The four services that apply their own chain++`honeytokens`, `osquery-tls`, `purple-team` and `ueba` manage their own schema through alembic, and the row above only holds because each now resolves a *migration* credential separately from its runtime one. Until it did, both came from the same variable: an operator pointing such a service at the owner lost row-level security on the twelve tables those chains own, and the deployment surface still read as compliant.++Set both per service — see [the table in Env vars](../deployment/env-vars#the-four-services-that-manage-their-own-schema). Leaving the migration variable unset still works and prints a warning on stderr naming what will happen; under the DML-only role the first `CREATE TABLE` fails with `permission denied for schema public`.++Each chain also grants the runtime role `SELECT, INSERT, UPDATE, DELETE` on its own tables rather than relying on `061_runtime_app_role.sql` having run first. Nothing orders the chains against each other, and `ALTER DEFAULT PRIVILEGES` is recorded against the role that issued it — so a deployment that applies the API chain and a service chain under different owners, or points a service at its own database, would otherwise get a service that starts, connects, and answers every query with `permission denied`.++Verified against `postgres:16` with all four chains applied and two tenants seeded: bound to one tenant the runtime role sees one row of two in `ueba_entity_baselines`, `honeytokens` and `osquery_node`; unbound it sees both, which is the fail-open arm the sweeps depend on; a cross-tenant insert is refused by the policy; `CREATE TABLE` is refused with `permission denied for schema public`; and `ALTER TABLE … NO FORCE ROW LEVEL SECURITY` with `must be owner of table`.+The `users` table is excluded from RLS deliberately — it would create a chicken-and-egg problem during authentication, and platform-admin user administration is cross-tenant by design. Tenant filtering on `users` is enforced at the application layer through `get_current_user()`.### The tenant comes from the credential, never from the requestdiff --git a/apps/docs/docs/quickstart.md b/apps/docs/docs/quickstart.mdindex 66ae4997b..ada71ad25 100644--- a/apps/docs/docs/quickstart.md+++ b/apps/docs/docs/quickstart.md@@ -148,6 +148,14 @@ docker compose exec honeytokens alembic upgrade headdocker compose exec purple-team alembic upgrade head```+Each of those four runs as the **owner**, not as the role the service serves+requests with: `docker-compose.yml` sets `DATABASE_MIGRATION_URL` alongside+`DATABASE_URL` for all four, and their `alembic/env.py` prefers it. The+runtime role holds no `CREATE` on schema public, by design — that is what+stops it turning row-level security off — so a chain applied as the runtime+credential fails on the first `CREATE TABLE`. See+[Env vars → the four services that manage their own schema](deployment/env-vars#the-four-services-that-manage-their-own-schema).+The `api` migrations include[`008_investigation_ledger.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/008_investigation_ledger.sql)(replayable agent decision log) anddiff --git a/docker-compose.yml b/docker-compose.ymlindex c68b41217..8293437e7 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -555,7 +555,13 @@ services:profiles:- osqueryenvironment:+ # Two roles, the same split the api service uses. This service manages+ # its own schema through alembic, so it needs the owner to apply DDL and+ # must not serve requests as it. The marker on the second line below is+ # what tells scripts/check_runtime_db_role.py the owner is deliberate.DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc+ # aisoc-db-role: owner — alembic applies this service's chain; the runtime role holds no DDL+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisocAISOC_OSQUERY_TLS_ENROLL_SECRET: ${AISOC_OSQUERY_TLS_ENROLL_SECRET:-change-me-in-production}# The ingest service is registered as `ingest-worker` in this compose# file; the previous `http://ingest:8080` would not resolve via DNS.@@ -695,7 +701,13 @@ services:ports:- "127.0.0.1:8007:8004"environment:+ # Two roles, the same split the api service uses. This service manages+ # its own schema through alembic, so it needs the owner to apply DDL and+ # must not serve requests as it. The marker on the second line below is+ # what tells scripts/check_runtime_db_role.py the owner is deliberate.DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc+ # aisoc-db-role: owner — alembic applies this service's chain; the runtime role holds no DDL+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/8KAFKA_BOOTSTRAP_SERVERS: kafka:29092CLICKHOUSE_URL: http://aisoc:clickhouse_dev_secret@clickhouse:8123/aisoc@@ -727,7 +739,13 @@ services:ports:- "127.0.0.1:8008:8005"environment:+ # Two roles, the same split the api service uses. This service manages+ # its own schema through alembic, so it needs the owner to apply DDL and+ # must not serve requests as it. The marker on the second line below is+ # what tells scripts/check_runtime_db_role.py the owner is deliberate.DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc+ # aisoc-db-role: owner — alembic applies this service's chain; the runtime role holds no DDL+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/9KAFKA_BOOTSTRAP_SERVERS: kafka:29092CORE_API_URL: http://api:8000@@ -756,7 +774,13 @@ services:ports:- "127.0.0.1:8006:8006"environment:+ # Two roles, the same split the api service uses. This service manages+ # its own schema through alembic, so it needs the owner to apply DDL and+ # must not serve requests as it. The marker on the second line below is+ # what tells scripts/check_runtime_db_role.py the owner is deliberate.DATABASE_URL: postgresql+asyncpg://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc+ # aisoc-db-role: owner — alembic applies this service's chain; the runtime role holds no DDL+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/10CORE_API_URL: http://api:8000ATTCK_DATA_PATH: /app/data/enterprise-attack.jsondiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 9d4e3becb..7328835f4 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -129,8 +129,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| No route lets its caller name the tenant it reads; a tenant parameter is intersected with the caller's scope | (implied by multi-tenant); `tests/isolation/README.md` | `isolation.yml :: route-scope` (`scripts/check_route_tenant_scope.py` — an AST pass over all routes under `services/`, failing in **both** directions: a route taking a tenant identifier with no auth dependency, and a route accepting one without passing it through a scope intersection. Request-body models are read too, since a `tenant_id` on a POST body is the same hole as a query parameter. `--self-test` injects a violation of each kind, asserts two clean controls pass, and strips the verifier the one conditional exemption names to prove a stale exemption is dropped; the root comes from `git rev-parse` and the scan prints how many routes across how many files it opened) + `tests/isolation/test_route_tenant_scope.py` (the vendored HS256 verifier rejects `alg: none`, a refresh token, a wrong key and an expired token; an empty scope refuses rather than widening; and a two-tenant replay seeds A and B through the real `EntityRiskEngine`, asserts both genuinely hold rows, then asserts an anonymous caller, an undeclared service token and a console session for B are each refused A's entity-risk queue) + `sync_vendored_tenant_scope.py --check` (six copies byte-identical but for `SERVICE_NAME`) | GATED | `services/mesh` is exempt by design (Ed25519 + k-anonymity; a bearer token would break federation rather than secure it) and three MSSP routes that *define* a scope rather than read within one are exempt with the constraint that stands in for the intersection named per row || Every route authenticates, or is public for a reason that is itself checked | (implied by multi-tenant + RBAC); `apps/docs/docs/operations/security.md` | `isolation.yml :: route-scope` (`scripts/check_route_auth.py` — default-deny over all 601 routes under `services/`, reusing the same AST collector as the tenant-scope gate so the two cannot drift. A route without an auth dependency must appear in one of three tables, each carrying its reason: a probe module, a named public route, or an **in-band credential** route whose entry names the verifier and lapses the moment the handler stops calling it. Fails in both directions — an unexplained route fails, and an exemption that no longer matches an unauthenticated route fails as stale, so the tables shrink as routes are secured. `--self-test` injects an unauthenticated mutating route, asserts router-level and module-local `Annotated[..., Depends(...)]` auth are both recognised, and strips a live in-band entry to prove a stale one is dropped) + `tests/isolation/test_route_auth_default_deny.py` (the real agents routers over ASGI: an anonymous caller is refused on all seven previously-open routes including playbook create/execute/delete, a valid console session still gets a non-empty response, a service token declaring no tenant is 403, and forged / expired / `alg: none` / refresh tokens are each refused) | GATED | `services/mesh` stays exempt by design (Ed25519 + k-anonymity; a bearer token would break federation rather than secure it), recorded as a service-level entry whose reason the inventory prints || Every query on a tenant-scoped table filters on a tenant, however the row was addressed | (implied by multi-tenant) | `isolation.yml :: route-scope` (`scripts/check_tenant_query_predicates.py` — the predicate question the parameter gate structurally cannot ask, since a route matching on an id takes no tenant. Both the tenant-scoped ORM models and the tenant-scoped tables are derived from the tree (the model's `tenant_id` column, the migrations' DDL) rather than listed, so a new migration cannot slip past. Scoping is recognised structurally through five shapes — inline `.where()`, a `filters` list, a variable binding, a later `q = q.where(...)`, a join, and a helper that takes the statement and returns it filtered — plus a predicate on the authenticated principal's own identity, a key an **enforcing** guard already validated against the caller's tenant, and an RLS context bound on the connection where the table carries a policy. "Enforcing" is decided structurally: a guard whose result is tested in a branch that only logs demonstrably continues on failure and earns no credit, a guard whose callee raises does, and a callee this module cannot resolve is refused rather than guessed — the previous rule guessed yes, so a fail-soft guard written inline was indistinguishable from one that 404s. The session is excluded from the validated set by what it is used as (the receiver of a call), since `db` reaches every raw statement's name set and was crediting queries keyed on something else entirely. Raw SQL is parsed too, with docstrings excluded so prose about a query is not read as one. Undecidable cases sit on a **shrink-only ratchet**: each entry carries a reason, an entry whose statement is now scoped fails as stale, and `MAX_RATCHET` is asserted against the table's length so growth needs a number raised in the diff) + `tests/isolation/test_route_auth_default_deny.py` (two tenants seeded against a real database, both asserted to hold rows before either absence is asserted, then tenant B naming tenant A's `query_id` gets nothing back) | GATED | 32 ratcheted exceptions remain, each with its reason — credential lookups that *establish* a tenant, deliberately cross-tenant MSSP portfolio reads, background workers that have no caller, and two SQL-fragment builders whose only caller appends the predicate. The two ledger writes that were ratcheted as "scoped by an RLS context" are gone: the rule now recognises that shape structurally, and re-checking it found the mechanism did not work — the agents service was setting `app.tenant_id`, which no policy reads |-| Every tenant-scoped table carries an RLS policy, and a policy that cannot engage says so rather than reading as protection | `apps/docs/docs/operations/security.md` (multi-tenant isolation) | `integration.yml :: migrations` (`tests/isolation/test_postgres_rls.py::test_every_tenant_table_is_protected_or_named` — both directions: a tenant-scoped table with no policy fails unless it is one of the named exclusions, and an exclusion that no longer describes an unprotected table fails as stale; `FORCE` is required on every one, since without it the table owner, which is the application, walks past the policy. `test_no_policy_reads_a_session_variable_nothing_sets` closes the bug class that made seven existing policies inert — four keyed on a GUC no code path sets, two raising `unrecognized configuration parameter` on an unbound session. `test_superuser_bypasses_rls_which_is_why_the_probe_role_exists` measures the shipped role's bypass so the coverage figure is never read as a live guarantee) + `check_tenant_query_predicates.py --inventory` (coverage derived from the migration text of all five schema chains, not one) | GATED | 92 of 95; the three left are named, not rounded away — `users` is excluded so authentication can resolve a principal before a tenant exists, and `case_tasks` / `case_timeline` are ORM models no migration creates, asserted still absent (both re-confirmed against a live `postgres:16` with the full chain applied: `users` is the only tenant-scoped table without a policy, and neither ORM table has a `CREATE TABLE` anywhere in the chain). The policies are no longer inert: `061_runtime_app_role.sql` moved every deployment surface onto a role with neither attribute, and the row below gates it |-| The role the services connect as is subject to row-level security, and the cross-tenant workers still see every tenant | `apps/docs/docs/operations/security.md` (the role the services connect as) | `isolation.yml` (`scripts/check_runtime_db_role.py` — fails when a runtime DSN connects as the role that surface provisions as the database superuser. Structural: the privileged role is read out of `POSTGRES_USER` / `db_username` in the tree, not matched against a name, so renaming it changes nothing and a fourteenth service with a copied DSN still fails. Both directions — a *migration* DSN that is **not** the owner fails too, since the runtime role holds no DDL and that deploy dies on the first `CREATE TABLE`; a surface containing a Postgres URL that the parser could not read fails as a blind spot rather than passing; and an `aisoc-db-role: owner` exemption left behind after its DSN moved fails as stale. Thirteen classifier fixtures run *before* every scan, and a run that matched no surface exits non-zero) + `integration.yml :: migrations` (`--dsn`, which reads `pg_roles` and `pg_class` on a live database and catches `rolsuper`, `rolbypassrls`, ownership of a covered object, a view without `security_invoker`, and a role still accepting the password `002_rls.sql` shipped) | GATED | The parser's own blind spot was found by enumerating what it **credited**: `infra/terraform/main.tf` declares `db_username = var.db_username` and interpolates `${var.db_username}`, and the naive compare read those as two roles — so the one surface handing the RDS master user to every service was recorded as compliant. A managed Postgres still needs the operator to create the role's login; the compose stacks and CI do it themselves |+| Every tenant-scoped table carries an RLS policy, and a policy that cannot engage says so rather than reading as protection | `apps/docs/docs/operations/security.md` (multi-tenant isolation) | `integration.yml :: migrations` (`tests/isolation/test_postgres_rls.py::test_every_tenant_table_is_protected_or_named` — both directions: a tenant-scoped table with no policy fails unless it is one of the named exclusions, and an exclusion that no longer describes an unprotected table fails as stale; `FORCE` is required on every one, since without it the table owner, which is the application, walks past the policy. `test_no_policy_reads_a_session_variable_nothing_sets` closes the bug class that made seven existing policies inert — four keyed on a GUC no code path sets, two raising `unrecognized configuration parameter` on an unbound session. `test_superuser_bypasses_rls_which_is_why_the_probe_role_exists` measures the shipped role's bypass so the coverage figure is never read as a live guarantee) + `check_tenant_query_predicates.py --inventory` (coverage derived from the migration text of all five schema chains, not one) | GATED | 93 of 96 — `approval_timers` joined the count in `062_approval_timers.sql`, having previously been created at runtime by `services/slack-bot`'s `PostgresTimerStore` and so covered by no chain, no policy and no `tenant_id`, on a table that decides whether a pending containment auto-rejects. The three left are named, not rounded away — `users` is excluded so authentication can resolve a principal before a tenant exists, and `case_tasks` / `case_timeline` are ORM models no migration creates, asserted still absent (both re-confirmed against a live `postgres:16` with the full chain applied: `users` is the only tenant-scoped table without a policy, and neither ORM table has a `CREATE TABLE` anywhere in the chain). The policies are no longer inert: `061_runtime_app_role.sql` moved every deployment surface onto a role with neither attribute, and the row below gates it |+| The role the services connect as is subject to row-level security, and the cross-tenant workers still see every tenant | `apps/docs/docs/operations/security.md` (the role the services connect as) | `isolation.yml` (`scripts/check_runtime_db_role.py` — fails when a runtime DSN connects as the role that surface provisions as the database superuser. Structural: the privileged role is read out of `POSTGRES_USER` / `db_username` in the tree, not matched against a name, so renaming it changes nothing and a fourteenth service with a copied DSN still fails. Both directions — a *migration* DSN that is **not** the owner fails too, since the runtime role holds no DDL and that deploy dies on the first `CREATE TABLE`; a surface containing a Postgres URL that the parser could not read fails as a blind spot rather than passing; and an `aisoc-db-role: owner` exemption left behind after its DSN moved fails as stale. Thirteen classifier fixtures run *before* every scan, and a run that matched no surface exits non-zero. Two directions were added once the four alembic services were modelled the same way: **which credential applies each chain**, discovered from every `alembic.ini`'s `script_location` rather than from a list of four paths, failing when a chain names no `*DATABASE_MIGRATION_URL` at all, when it names one no deployment surface sets, or when its `env.py` cannot be read; and **a DSN handed to a service that cannot read the variable**, resolved from the compose `build.context` to the service's own source plus its pydantic `env_prefix`. Against `origin/main` the extended gate produces seven findings where it previously printed OK) + `integration.yml :: migrations` (`--dsn`, which reads `pg_roles` and `pg_class` on a live database and catches `rolsuper`, `rolbypassrls`, ownership of a covered object, a view without `security_invoker`, and a role still accepting the password `002_rls.sql` shipped) | GATED | The parser's own blind spot was found by enumerating what it **credited**: `infra/terraform/main.tf` declares `db_username = var.db_username` and interpolates `${var.db_username}`, and the naive compare read those as two roles — so the one surface handing the RDS master user to every service was recorded as compliant. The same method found the next one: `docker-compose.yml` set `DATABASE_URL=aisoc_app` on `honeytokens`, `purple-team` and `osquery-tls` and the gate credited all three, while each read only its prefixed spelling and fell back to a default naming the *owner* — a role switch that reached none of them behind a compliant-looking surface. A docstring mentioning ``DATABASE_URL`` in prose credited a fourth until the reader was narrowed to non-docstring literals. A managed Postgres still needs the operator to create the role's login; the compose stacks and CI do it themselves || A cross-tenant worker that stops seeing data says so instead of reporting success | `apps/docs/docs/operations/security.md` (a session that never bound a tenant) | `isolation.yml` (`scripts/check_rls_policy_shape.py` — every surviving policy in all five schema chains must carry the `OR current_tenant_id() IS NULL` arm, because ingest, fusion, the retention purge and the schedulers read on a session that binds no tenant and would otherwise see zero rows and report success. Replays the chain in order so a definition a later migration repaired is not reported, which is what lets the seven broken policies stay in the tree as history instead of being silenced by an ignore list. Both directions: a policy reading a GUC nothing sets, or omitting `missing_ok`, fails from the other side; a schema file that enables RLS but yields no policy fails as a blind spot; `ENABLE` without `FORCE`, and `ENABLE` with no policy, both fail) + `services/api/tests/test_retention_worker.py` (the sweep refuses, and issues no delete, on a session that has a tenant bound) | GATED | Two blind spots in this parser were found by counting what it credited rather than what it flagged: the four alembic chains build SQL by implicit string concatenation with no `;` so none of their twelve tables parsed, and the first fix then read each revision's `downgrade()` too, so create and drop cancelled and the policy count did not move. The static set is a deliberate **superset** of the live one — two policies in `002` sit behind an `IF EXISTS` a text replay cannot evaluate — which is the safe direction || Documentation and marketing name no competitor product, while vendors AiSOC integrates with stay named | AGENTS.md (naming rule); docs portal + benchmark comparison tables | `competitor-names.yml` (`scripts/check_competitor_names.py` — an explicit name list plus a path allow-list for integration surfaces, both checked in both directions: a dead pattern, a stale allow entry that no longer excuses anything, and a drifted comparison-table marker each fail rather than reporting a clean tree; the scan prints the absolute root and file count so it cannot report on a tree it never read) + `tests/test_competitor_names_gate.py` (42 cases, including `Torq` asserted as a competitor in prose *and* left untouched across its connector module, manifest, docs page and tests) | GATED | the name list is AI-SOC/SOAR rivals; vendors that are purely integration targets are deliberately absent from it and are instead held out of the pinned comparison-table regions, which are checked against a wider vendor list || The published playbook schema describes the engine that runs playbooks | concepts/playbooks.md (step table + `x-aisoc-execution`); `schemas/playbook.schema.json` | `ci.yml` P2 job (`scripts/check_playbook_schema_parity.py --self-test` — compares the schema enum, the `StepType` enum, the engine's `_HANDLERS` table, the `x-aisoc-execution` map, `bounds.py` and the pack validator's trigger list, **every pair in both directions**; refuses to run on a tree missing its marker files instead of printing OK about files it never opened, and names the root, schema, step counts and playbook count it inspected) + `scripts/lint_playbooks.py` (every `*.playbook.json` in the tree, not the two it used to scan while reporting "2/2 passed") + `tests/test_playbook_schema_parity_gate.py` (18 cases; drift injected in each direction and the gate asserted to name it) | GATED | the `governed` execution class is compared against `engine.RESPONSE_STEP_TYPES` in both directions, and the published `StepType` union in `packages/types` against the engine's, because that file had drifted into a fourth 28-member vocabulary nothing imported. `approval` is the one remaining unimplemented type and the schema says so |@@ -142,7 +142,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Every `ActionType` resolves a capability contract, so the confidence matrix is never skipped | concepts/live-actions.md (the one alias, and when it goes) | `ci.yml` actions job (`scripts/check_action_contract.py` directions 7 and 8 — every `ActionType` must resolve a contract by name or alias, and every alias must key a real `ActionType`, point at a real contract, not shadow a capability of the same name, and describe a bridge some adapter actually implements) + `test_approval_gate_wiring.py` (`notify_slack` at 10% confidence was approved for auto-execution and now requires an analyst; the alias is asserted unable to *lower* a requirement) | GATED | one alias entry (`notify_slack` -> `notify`), with its retirement condition recorded: it goes when `ActionType` does || Every check this matrix names is actually run by CI | this matrix (each row names a gate) | `ci.yml` (`scripts/check_gate_coverage.py` — resolves the whole graph rather than reading workflow names: workflows, `make` recipes they invoke, the pytest suites they collect and the scripts those reach, so a check wired only through a test still counts. Both directions — a check no workflow reaches, and a workflow step naming a `scripts/` path that does not exist. `--self-test` runs first and asserts the resolver discriminates rather than returning "reached" for everything, and the corpus counts are printed so it cannot report on a tree it never opened) | GATED | the ratchet for a deliberately-unwired check is empty; it may shrink, never grow || What counts as a check is decided by what a script does, not what it is named | `scripts/check_gate_coverage.py` (the inventory it reports on) | `ci.yml` (three structural signals, all read from the tree: a declared verdict flag, an exit status derived from findings the script accumulates, and a workflow job whose output another job branches on. The first two are intrinsic, so an uncalled gate is still inventoried and the `SCRIPT -> WORKFLOW` direction is not vacuous. The classifier is also checked in reverse — a script CI runs with `--check` that the classifier does not inventory fails as `classifier-blind-spot`) + `tests/test_gate_coverage_classifier.py` (10 cases, including a gate planted under a name no convention would reveal, and a generator that aborts on an empty read asserted *not* to be a check) | GATED | - |-| No check reports OK over a repository with no content | every row above (a gate that credits an empty tree proves nothing about a full one) | `ci.yml :: python-test` (`scripts/check_gate_contract.py` — runs all 69 inventoried checks the way a workflow runs each one, inside a git repository holding only `scripts/`, and requires a non-zero exit. A run that failed for a reason the empty tree did not cause — an argparse usage error, or an import of a module the repository does not supply — is INCONCLUSIVE and fails rather than counting as a refusal, so the gate cannot credit a failure it did not cause. Exceptions are recorded with the disposition they are excused for and checked in both directions: an entry naming nothing, and an entry whose gate has started behaving differently, both fail) + `tests/test_gate_contract.py` (41 cases) | GATED | 4 recorded exceptions; the probe cannot pose the question to a gate whose only input is a path named on the command line, or one that lives inside `scripts/` |+| No check reports OK over a repository with no content | every row above (a gate that credits an empty tree proves nothing about a full one) | `ci.yml :: python-test` (`scripts/check_gate_contract.py` — runs all 69 inventoried checks the way a workflow runs each one, inside a git repository holding only `scripts/`, and requires a non-zero exit. Two tree shapes, because they are two questions: **bare** omits the directories a gate judges, **skeleton** creates them empty. The second is the one that happens — a renamed package, a glob that stopped matching — and a gate opening with `if not X.is_dir(): return 2` answers the first for a reason that says nothing about its corpus. Measured before it was added: 64 of 71 checks already refused the skeleton, so the exception list stayed readable rather than doubling. A run that failed for a reason the empty tree did not cause — an argparse usage error, or an import of a module the repository does not supply — is INCONCLUSIVE and fails rather than counting as a refusal, so the gate cannot credit a failure it did not cause. Exceptions are recorded with the disposition they are excused for and checked in both directions: an entry naming nothing, and an entry whose gate has started behaving differently, both fail) + `tests/test_gate_contract.py` (45 cases) | GATED | 5 recorded exceptions, keyed by tree shape; the probe cannot pose the question to a gate whose only input is a path named on the command line, or one that lives inside `scripts/`. One entry exists because its dispositions legitimately differ: `check_logger_kwargs.py` scans every Python file in the repository, so against a skeleton it has a real corpus in `scripts/` and correctly finds nothing wrong || Every check resolves its root from git and carries a `--self-test` | `scripts/` (the gates themselves) | `ci.yml :: python-test` (`scripts/check_gate_contract.py` — a check that derives a repository root from `__file__` without consulting git fails as `root-from-file`, and one that declares no `--self-test` fails as `no-self-test`. Both read from the syntax tree: the first spelling matched `repo_root` anywhere in the text and `check_gate_coverage.py` emits it as a JSON key, so a non-compliant gate read as compliant on the strength of a dictionary key in its own output. Both exception lists are empty — all 69 comply — and an entry added to either must carry a reason) | GATED | - |## Summarydiff --git a/scripts/check_gate_contract.py b/scripts/check_gate_contract.pyindex 21b6fcec4..8dfd5682a 100644--- a/scripts/check_gate_contract.py+++ b/scripts/check_gate_contract.py@@ -105,7 +105,10 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))import check_gate_coverage as coverage # noqa: E402from gate_toolkit import ( # noqa: E402+ BARE,SELF_TEST_FLAG,+ SKELETON,+ TREE_SHAPES,VERDICT_FLAG_PREFERENCE,repo_root,run_in_scratch_tree,@@ -118,42 +121,76 @@ from gate_toolkit import ( # noqa: E402# so does an entry whose reason has stopped being true.# --------------------------------------------------------------------------+#: Every shape, when a script behaves the same against all of them.+ANY_SHAPE = "*"+#: Checks the empty-tree question cannot be put to, each recorded with the#: disposition it is expected to produce. Recording the disposition and not#: just the name is what makes the entry falsifiable: an exception written#: because argparse refused the arguments does not quietly go on covering the#: gate on the day it starts exiting 0 instead.-EMPTY_TREE_EXCEPTIONS: dict[str, tuple[str, str]] = {- "wet_eval_check.py": (- "passed",- "Reads two environment variables and no repository content at all. Its exit status is 0 by "- "design so a fork with no secrets does not look like a broken build; the verdict is the JSON "- "status file that wet-eval.yml branches on, which is why check_gate_coverage classifies it "- "from the job graph rather than from anything intrinsic. There is no tree for it to credit, "- "so its --self-test checks the verdict it does render: should_run across present, absent, "- "partial and dry-run secrets.",- ),- "security_audit.py": (- "passed",- "Three of its four arms — pnpm, python, go — now refuse a tree with no manifests in it. The "- "fourth, validate-ignores, has scripts/security_audit_ignores.txt as its entire subject, and "- "scripts/ is the one directory the scratch tree has to keep for the gate to be runnable at "- "all. So the probe cannot pose the question for that arm; the missing-policy-file case is "- "covered instead by test_validate_ignores_refuses_a_missing_policy_file.",- ),- "openapi_diff.py": (- "inconclusive",- "Both specifications are named on the command line and one of them is a checkout of main that "- "openapi-breaking.yml writes outside the repository, so it discovers nothing from the tree and "- "there is no empty-tree verdict to render. Run with no arguments it refuses at argparse, before "- "any file is opened.",- ),- "wet_eval_update_benchmark.py": (- "inconclusive",- "Same shape: --wet-block names a report the weekly workflow produces outside the checkout, so "- "the only replayable invocation would be testing the argument list rather than the tree. "- "Required arguments mean argparse refuses a bare run before it reads anything.",- ),+#:+#: Keyed ``script -> shape -> (disposition, reason)``. ``ANY_SHAPE`` covers+#: every shape and is what most entries use; a named shape overrides it. The+#: indirection earns its keep exactly once — ``check_logger_kwargs.py``+#: refuses the bare tree and legitimately passes the skeleton — and writing+#: both shapes out for the other four would have duplicated four paragraphs+#: to express "no change".+EMPTY_TREE_EXCEPTIONS: dict[str, dict[str, tuple[str, str]]] = {+ "wet_eval_check.py": {+ ANY_SHAPE: (+ "passed",+ "Reads two environment variables and no repository content at all. Its exit status is 0 by "+ "design so a fork with no secrets does not look like a broken build; the verdict is the JSON "+ "status file that wet-eval.yml branches on, which is why check_gate_coverage classifies it "+ "from the job graph rather than from anything intrinsic. There is no tree for it to credit, "+ "so its --self-test checks the verdict it does render: should_run across present, absent, "+ "partial and dry-run secrets.",+ )+ },+ "security_audit.py": {+ ANY_SHAPE: (+ "passed",+ "Three of its four arms — pnpm, python, go — now refuse a tree with no manifests in it. The "+ "fourth, validate-ignores, has scripts/security_audit_ignores.txt as its entire subject, and "+ "scripts/ is the one directory the scratch tree has to keep for the gate to be runnable at "+ "all. So the probe cannot pose the question for that arm; the missing-policy-file case is "+ "covered instead by test_validate_ignores_refuses_a_missing_policy_file.",+ )+ },+ "openapi_diff.py": {+ ANY_SHAPE: (+ "inconclusive",+ "Both specifications are named on the command line and one of them is a checkout of main that "+ "openapi-breaking.yml writes outside the repository, so it discovers nothing from the tree and "+ "there is no empty-tree verdict to render. Run with no arguments it refuses at argparse, before "+ "any file is opened.",+ )+ },+ "wet_eval_update_benchmark.py": {+ ANY_SHAPE: (+ "inconclusive",+ "Same shape: --wet-block names a report the weekly workflow produces outside the checkout, so "+ "the only replayable invocation would be testing the argument list rather than the tree. "+ "Required arguments mean argparse refuses a bare run before it reads anything.",+ )+ },+ "check_logger_kwargs.py": {+ BARE: (+ "refused",+ "No services/ directory at all, which it refuses outright before scanning. Recorded rather "+ "than left implicit because the skeleton entry below only makes sense next to it.",+ ),+ SKELETON: (+ "passed",+ "Its corpus is every Python file in the repository, not one directory — scripts/ is in scope "+ "and the scratch tree keeps it, so against a skeleton it classifies real stdlib loggers in "+ "real files and correctly finds none misused. That is a pass over a corpus it genuinely has, "+ "not a credit for a tree it never opened, and its own floor proves the difference: it exits 1 "+ "when it classifies zero stdlib calls. Measured, not assumed — 64 of the 71 checks refuse the "+ "skeleton and this is the only one whose disposition differs between the two shapes.",+ ),+ },}#: Checks that derive a root from ``__file__`` and do not consult git. Empty:@@ -337,10 +374,11 @@ def classify(status: int | None, output: str, supplied: frozenset[str]) -> tuple@dataclassclass Run:- """One invocation of one gate inside the scratch tree."""+ """One invocation of one gate inside one scratch tree."""args: list[str]source: str+ shape: strdisposition: strwhy: strevidence: str = ""@@ -353,26 +391,31 @@ class Probe:script: strruns: list[Run] = field(default_factory=list)- @property- def disposition(self) -> str:- """The worst thing any invocation did.+ def disposition_for(self, shape: str) -> str:+ """The worst thing any invocation did against ``shape``.Worst, not first: a script CI runs four ways is four gates wearing onename, and excusing the set because the first one refused is how asubcommand that credits an empty tree stays hidden behind a siblingthat does not."""- seen = {run.disposition for run in self.runs}+ seen = {run.disposition for run in self.runs if run.shape == shape}if PASSED in seen:return PASSEDif REFUSED in seen:return REFUSEDreturn INCONCLUSIVE+ def why_for(self, shape: str) -> str:+ worst = self.disposition_for(shape)+ return next(+ (run.why for run in self.runs if run.shape == shape and run.disposition == worst),+ "no invocation was attempted",+ )+@property- def why(self) -> str:- worst = self.disposition- return next((run.why for run in self.runs if run.disposition == worst), "no invocation was attempted")+ def shapes(self) -> list[str]:+ return [shape for shape in TREE_SHAPES if any(run.shape == shape for run in self.runs)]def probe(surface: coverage.Surface, checks: dict[str, dict[str, str]], root: Path, *, only: str | None = None) -> list[Probe]:@@ -382,31 +425,35 @@ def probe(surface: coverage.Surface, checks: dict[str, dict[str, str]], root: Parelies on. Its own declared flags are the fallback, used only when nothingCI does can be replayed — a step whose arguments name an artefact builtoutside the checkout tests the argument list rather than the tree.++ Two tree shapes, because they are two questions. ``BARE`` asks what a gate+ does when the thing it judges is not there; ``SKELETON`` asks what it does+ when the directory is there and holds nothing. The second is the one that+ happens — a renamed package, a changed glob — and a gate opening with+ ``if not X.is_dir(): return 2`` answers the first for a reason that says+ nothing about its corpus."""supplied = importable_names(root)- results: list[Probe] = []- with scratch_tree(root / "scripts") as tree:- for script in sorted(checks):- if only and script != only:- continue- result = Probe(script=script)- for args in ci_invocations(surface, script, checks[script]):- result.runs.append(_run_one(script, args, tree, supplied, "the workflow that runs it"))- if result.disposition == INCONCLUSIVE:- for args in declared_invocations(checks[script]):- run = _run_one(script, args, tree, supplied, "its own declared verdict flag")- result.runs.append(run)- if run.disposition != INCONCLUSIVE:- break- results.append(result)- return results---def _run_one(script: str, args: Sequence[str], tree: Path, supplied: frozenset[str], source: str) -> Run:+ results: dict[str, Probe] = {script: Probe(script=script) for script in sorted(checks) if not only or script == only}+ for shape in TREE_SHAPES:+ with scratch_tree(root / "scripts", shape=shape) as tree:+ for script, result in results.items():+ for args in ci_invocations(surface, script, checks[script]):+ result.runs.append(_run_one(script, args, tree, supplied, "the workflow that runs it", shape))+ if result.disposition_for(shape) == INCONCLUSIVE:+ for args in declared_invocations(checks[script]):+ run = _run_one(script, args, tree, supplied, "its own declared verdict flag", shape)+ result.runs.append(run)+ if run.disposition != INCONCLUSIVE:+ break+ return list(results.values())+++def _run_one(script: str, args: Sequence[str], tree: Path, supplied: frozenset[str], source: str, shape: str) -> Run:status, output = run_in_scratch_tree(script, args, tree=tree)_reset(tree)disposition, why = classify(status, output, supplied)- return Run(args=list(args), source=source, disposition=disposition, why=why, evidence=_tail(output))+ return Run(args=list(args), source=source, shape=shape, disposition=disposition, why=why, evidence=_tail(output))def _reset(tree: Path) -> None:@@ -498,12 +545,20 @@ def _declares_self_test(tree: ast.Module) -> bool:# --------------------------------------------------------------------------# Verdict# --------------------------------------------------------------------------+def _expected(accepted: dict[str, dict[str, tuple[str, str]]], script: str, shape: str) -> tuple[str, str] | None:+ """The recorded exception for this script and shape, if there is one."""+ per_shape = accepted.get(script)+ if per_shape is None:+ return None+ return per_shape.get(shape) or per_shape.get(ANY_SHAPE)++def evaluate(checks: dict[str, dict[str, str]],probes: dict[str, Probe],properties: dict[str, dict[str, bool]],*,- accepted: dict[str, tuple[str, str]],+ accepted: dict[str, dict[str, tuple[str, str]]],no_git_root: dict[str, str],no_self_test: dict[str, str],) -> list[tuple[str, str]]:@@ -512,39 +567,42 @@ def evaluate(for script in sorted(checks):result = probes.get(script)- excused, expected = script in accepted, (accepted.get(script) or ("", ""))[0]if result is None:failures.append(("not-probed", f"{script} is a check and the probe produced no result for it"))continue- if excused and result.disposition != expected:- failures.append(- (- "exception-stale",- f"{script} is excused on the strength of a {expected!r} disposition and now reports "- f"{result.disposition!r} ({result.why}). Either the reason has stopped being true and "- "the entry should go, or it is covering something it was never written for.",+ for shape in result.shapes:+ exception = _expected(accepted, script, shape)+ disposition, why = result.disposition_for(shape), result.why_for(shape)+ if exception is not None and disposition != exception[0]:+ failures.append(+ (+ "exception-stale",+ f"{script} is excused against the {shape} tree on the strength of a "+ f"{exception[0]!r} disposition and now reports {disposition!r} ({why}). Either the "+ "reason has stopped being true and the entry should go, or it is covering "+ "something it was never written for.",+ ))- )- elif result.disposition == INCONCLUSIVE and not excused:- failures.append(- (- "inconclusive",- f"{script}: {result.why}. The probe did not exercise the gate, so a non-zero exit is "- "not evidence it refuses an empty tree — install the dependency in the job, or record "- "an exception saying why the question cannot be asked.",+ elif exception is None and disposition == INCONCLUSIVE:+ failures.append(+ (+ "inconclusive",+ f"{script} against the {shape} tree: {why}. The probe did not exercise the gate, so "+ "a non-zero exit is not evidence it refuses an empty tree — install the dependency "+ "in the job, or record an exception saying why the question cannot be asked.",+ ))- )- elif result.disposition == PASSED and not excused:- offending = [" ".join(r.args) or "(no arguments)" for r in result.runs if r.disposition == PASSED]- failures.append(- (- "passes-over-empty-tree",- f"{script} {', '.join(offending)} exited 0 inside a repository holding no content. "- "Found nothing and scanned nothing print the same word: this gate credits a tree it "- "never opened. Make it fail closed on an empty read, or record why the exit status is "- "not its verdict.",+ elif exception is None and disposition == PASSED:+ offending = [" ".join(r.args) or "(no arguments)" for r in result.runs if r.shape == shape and r.disposition == PASSED]+ failures.append(+ (+ "passes-over-empty-tree",+ f"{script} {', '.join(offending)} exited 0 inside a {shape} repository holding no "+ "content. Found nothing and scanned nothing print the same word: this gate credits "+ "a tree it never opened. Make it fail closed on an empty read, or record why the "+ "exit status is not its verdict.",+ ))- )static = properties.get(script, {})needs_git = static.get("derives_root_from_file") and not static.get("consults_git_for_root")@@ -570,8 +628,9 @@ def evaluate(if static.get("declares_self_test") and script in no_self_test:failures.append(("ratchet-stale", f"{script} is on NO_SELF_TEST but now declares {SELF_TEST_FLAG}; remove the entry"))+ flattened = {name: " ".join(reason for _disposition, reason in per_shape.values()) for name, per_shape in accepted.items()}reasons: dict[str, dict[str, str]] = {- "EMPTY_TREE_EXCEPTIONS": {name: reason for name, (_disposition, reason) in accepted.items()},+ "EMPTY_TREE_EXCEPTIONS": flattened,"NO_GIT_ROOT": no_git_root,"NO_SELF_TEST": no_self_test,}@@ -587,8 +646,9 @@ def evaluate(def _exception_summary() -> str:counts: dict[str, int] = {}- for disposition, _reason in EMPTY_TREE_EXCEPTIONS.values():- counts[disposition] = counts.get(disposition, 0) + 1+ for per_shape in EMPTY_TREE_EXCEPTIONS.values():+ for disposition, _reason in per_shape.values():+ counts[disposition] = counts.get(disposition, 0) + 1return ", ".join(f"{count} {name}" for name, count in sorted(counts.items())) or "none"@@ -651,14 +711,16 @@ def main(argv: list[str] | None = None) -> int:)return 1 if failures else 0- counts = {name: sum(1 for p in probes.values() if p.disposition == name) for name in (REFUSED, PASSED, INCONCLUSIVE)}runs = sum(len(p.runs) for p in probes.values())print(f"repo root {root}")print(f"inventory check_gate_coverage.py ({len(checks)} checks, {len(probes)} probed over {runs} invocations)")- print("scratch tree a git repository holding only scripts/ — no services, detections, apps, docs or workflows")- print(f"dispositions {counts[REFUSED]} refused, {counts[PASSED]} exited 0, {counts[INCONCLUSIVE]} inconclusive")+ print("scratch trees bare — a git repository holding only scripts/: services, detections, apps, docs, workflows absent")+ print(" skeleton — the same, with those directories present and empty")+ for shape in TREE_SHAPES:+ counts = {name: sum(1 for p in probes.values() if p.disposition_for(shape) == name) for name in (REFUSED, PASSED, INCONCLUSIVE)}+ print(f" {shape:<14} {counts[REFUSED]} refused, {counts[PASSED]} exited 0, {counts[INCONCLUSIVE]} inconclusive")print(- f"exceptions {len(EMPTY_TREE_EXCEPTIONS)} recorded ({_exception_summary()}), "+ f"exceptions {len(EMPTY_TREE_EXCEPTIONS)} scripts recorded ({_exception_summary()}), "f"{len(NO_GIT_ROOT)} without a git root, {len(NO_SELF_TEST)} without a self-test")print()@@ -668,9 +730,9 @@ def main(argv: list[str] | None = None) -> int:for name in sorted(probes):for run in probes[name].runs:mark = {REFUSED: "refused ", PASSED: "EXITED 0", INCONCLUSIVE: "UNKNOWN "}[run.disposition]- print(f" {mark} {name:{width}} {' '.join(run.args) or '(no arguments)'} [{run.source}]")+ print(f" {mark} {run.shape:<9} {name:{width}} {' '.join(run.args) or '(no arguments)'} [{run.source}]")if run.evidence:- print(f" {'':{width}} {run.evidence}")+ print(f" {'':9} {'':{width}} {run.evidence}")print()if failures:@@ -678,8 +740,9 @@ def main(argv: list[str] | None = None) -> int:for code, detail in failures:print(f" [{code}] {detail}")return 1- print(f"OK — {len(checks) - len(EMPTY_TREE_EXCEPTIONS)} of {len(checks)} checks refuse a repository with no content;")- print(f" the other {len(EMPTY_TREE_EXCEPTIONS)} are recorded exceptions, each with the disposition it is excused for.")+ print(f"OK — {len(checks) - len(EMPTY_TREE_EXCEPTIONS)} of {len(checks)} checks refuse both a repository with no content")+ print(" and one whose directories are present and empty;")+ print(f" the other {len(EMPTY_TREE_EXCEPTIONS)} are recorded exceptions, each with the disposition it is excused for per shape.")return 0@@ -690,8 +753,10 @@ def self_test() -> int:"""Inject each defect this gate exists to catch and require it to be caught."""checks = {"check_real.py": {"verdict-flag": "--check"}}- def result(*dispositions: str) -> dict[str, Probe]:- runs = [Run(args=["--check"], source="test", disposition=d, why=f"exited on {d}") for d in dispositions]+ def result(*dispositions: str, shape: str = BARE, also: dict[str, str] | None = None) -> dict[str, Probe]:+ runs = [Run(args=["--check"], source="test", shape=shape, disposition=d, why=f"exited on {d}") for d in dispositions]+ for other_shape, disposition in (also or {}).items():+ runs.append(Run(args=["--check"], source="test", shape=other_shape, disposition=disposition, why="exited"))return {"check_real.py": Probe(script="check_real.py", runs=runs)}good = result(REFUSED)@@ -734,22 +799,43 @@ def self_test() -> int:("an accepted empty-tree pass that has started refusing — a stale exception","exception-stale",- run(good, accepted={"check_real.py": (PASSED, "recorded reason")}),+ run(good, accepted={"check_real.py": {ANY_SHAPE: (PASSED, "recorded reason")}}),),("an exception written for an inconclusive probe now covering an outright pass","exception-stale",- run(result(PASSED), accepted={"check_real.py": (INCONCLUSIVE, "recorded reason")}),+ run(result(PASSED), accepted={"check_real.py": {ANY_SHAPE: (INCONCLUSIVE, "recorded reason")}}),),("an exception naming a check that is not in the tree","ratchet-names-nothing",- run(good, accepted={"check_ghost.py": (PASSED, "recorded reason")}),+ run(good, accepted={"check_ghost.py": {ANY_SHAPE: (PASSED, "recorded reason")}}),),("an exception with no reason given","ratchet-unexplained",- run(good, accepted={"check_real.py": (REFUSED, " ")}),+ run(good, accepted={"check_real.py": {ANY_SHAPE: (REFUSED, " ")}}),+ ),+ (+ "a gate that refuses the bare tree and credits the skeleton — the shape the second tree exists for",+ "passes-over-empty-tree",+ run(result(REFUSED, also={SKELETON: PASSED})),+ ),+ (+ "an ANY_SHAPE exemption cannot quietly cover a shape it was not written for",+ "exception-stale",+ run(+ result(REFUSED, also={SKELETON: PASSED}),+ accepted={"check_real.py": {ANY_SHAPE: (REFUSED, "recorded reason")}},+ ),+ ),+ (+ "a per-shape exemption covers only the shape it names",+ "passes-over-empty-tree",+ run(+ result(PASSED, also={SKELETON: PASSED}),+ accepted={"check_real.py": {SKELETON: (PASSED, "recorded reason")}},+ ),),("a gate rooting itself at __file__ with no git resolution",@@ -836,8 +922,8 @@ def self_test() -> int:print(f" {'PASS' if correct else 'FAIL'} REPLAY: {replay_label}")print(f" expected {replay_want} got {replayed}")- # And the scratch tree itself, because every result above is only as good- # as the claim that the tree really has nothing in it.+ # And the scratch trees themselves, because every result above is only as+ # good as the claim that each tree really is the shape it says it is.with scratch_tree() as tree:present = sorted(p.name for p in tree.iterdir() if p.name != ".git")toplevel = subprocess.run( # noqa: S603@@ -846,15 +932,31 @@ def self_test() -> int:isolated = Path(toplevel.stdout.strip() or "/nowhere").resolve() == tree.resolve()bare = present == ["scripts"]ok &= bare and isolated- print(f" {'PASS' if bare else 'FAIL'} TREE: the scratch repository holds scripts/ and nothing else")+ print(f" {'PASS' if bare else 'FAIL'} TREE(bare): the scratch repository holds scripts/ and nothing else")print(f" contents {present}")- print(f" {'PASS' if isolated else 'FAIL'} TREE: git inside it resolves to itself, not to the real checkout")+ print(f" {'PASS' if isolated else 'FAIL'} TREE(bare): git inside it resolves to itself, not to the real checkout")++ # The skeleton has to differ from the bare tree in exactly one way: the+ # directories exist and hold nothing. A skeleton that accidentally copied+ # content would turn every probe into a scan of real files, and one whose+ # directories vanished under `git clean` between probes would silently be+ # the bare tree wearing a second name.+ with scratch_tree(shape=SKELETON) as tree:+ _reset(tree)+ dirs = sorted(p.name for p in tree.iterdir() if p.is_dir() and p.name != ".git")+ services = tree / "services"+ empty = services.is_dir() and [p.name for p in services.iterdir()] == [".gitkeep"]+ has_dirs = "services" in dirs and "detections" in dirs+ ok &= empty and has_dirs+ print(f" {'PASS' if has_dirs else 'FAIL'} TREE(skeleton): the directories a gate judges are present")+ print(f" contents {dirs}")+ print(f" {'PASS' if empty else 'FAIL'} TREE(skeleton): and still empty after a reset between probes")print()if not ok:print("self-test FAILED: this gate did not catch drift it claims to catch")return 1- print(f"self-test OK: {len(cases)} injected defects and {len(reader) + len(chooser) + len(replay) + 2} component assertions")+ print(f"self-test OK: {len(cases)} injected defects and {len(reader) + len(chooser) + len(replay) + 4} component assertions")return 0diff --git a/scripts/check_route_auth.py b/scripts/check_route_auth.pyindex d29e60af1..c1a0cc8ac 100644--- a/scripts/check_route_auth.py+++ b/scripts/check_route_auth.py@@ -68,12 +68,14 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))# One parser, two questions. A second route scanner would drift from this one# the first time either learned something the other did not — which is how the# `ExecuteUser` alias came to be reported as an unauthenticated playbook-run.-from check_route_tenant_scope import ( # noqa: E402- REPO_ROOT,- SERVICES_DIR,- Route,- collect_routes,-)+#+# Imported as a module rather than by name on purpose. `REPO_ROOT` and+# `SERVICES_DIR` are module state that the shared empty-corpus self-test+# rebinds to a scratch tree; a from-import would copy the originals at import+# time, so this gate would go on scanning the real checkout while believing it+# was pointed at an empty one — a self-test that proves nothing, which is the+# shape this whole exercise is about.+import check_route_tenant_scope as route_scan # noqa: E402#: Public by design at the service level. ``mesh`` federates between#: independent deployments over Ed25519 signatures and k-anonymity: peers@@ -209,16 +211,16 @@ IN_BAND_CREDENTIAL_ROUTES: dict[str, tuple[str, str]] = {}-def _module_exempt(route: Route) -> str | None:+def _module_exempt(route: route_scan.Route) -> str | None:for suffix, reason in PUBLIC_MODULES.items():if route.path.endswith(suffix):return reasonreturn None-def classify(routes: list[Route]) -> tuple[list[Route], list[str]]:+def classify(routes: list[route_scan.Route]) -> tuple[list[route_scan.Route], list[str]]:"""Return (unexplained unauthenticated routes, stale exemption keys)."""- unexplained: list[Route] = []+ unexplained: list[route_scan.Route] = []matched: set[str] = set()for route in routes:@@ -245,7 +247,7 @@ def classify(routes: list[Route]) -> tuple[list[Route], list[str]]:return unexplained, stale-def _verifier_in_module(route: Route, verifier: str) -> bool:+def _verifier_in_module(route: route_scan.Route, verifier: str) -> bool:"""Whether the handler's module references the verifier.Some in-band checks live one call frame away — Bolt's@@ -255,23 +257,23 @@ def _verifier_in_module(route: Route, verifier: str) -> bool:is the looser test, so it is used as a fallback: the point is thatdeleting the verification entirely still trips the gate."""- path = REPO_ROOT / route.path+ path = route_scan.REPO_ROOT / route.pathif not path.is_file():return Falsereturn verifier in path.read_text(encoding="utf-8", errors="ignore")-def _print_inventory(routes: list[Route]) -> None:- print(f"Route authentication inventory — scanned {SERVICES_DIR}")+def _print_inventory(routes: list[route_scan.Route]) -> None:+ print(f"Route authentication inventory — scanned {route_scan.SERVICES_DIR}")print(f"{'service':<14}{'routes':>8}{'authed':>8}{'public':>8}{'in-band':>9}{'open':>6} reason for the public ones")print("-" * 104)total = [0, 0, 0, 0, 0]for svc in sorted({r.service for r in routes}):rows = [r for r in routes if r.service == svc]authed = [r for r in rows if r.has_auth]- public: list[Route] = []- inband: list[Route] = []- open_: list[Route] = []+ public: list[route_scan.Route] = []+ inband: list[route_scan.Route] = []+ open_: list[route_scan.Route] = []for r in rows:if r.has_auth:continue@@ -352,7 +354,7 @@ def _self_test() -> int:target = root / "services" / "probe" / "app"target.mkdir(parents=True, exist_ok=True)(target / "routes.py").write_text(source, encoding="utf-8")- routes = collect_routes(root=root)+ routes = route_scan.collect_routes(root=root)open_, _stale = classify(routes)ok = len(open_) == want and len(routes) > 0if not ok:@@ -360,6 +362,16 @@ def _self_test() -> int:print(f" [{'PASS' if ok else 'FAIL'}] {label}: {len(open_)} open, want {want} (scanned {len(routes)} routes)")failures += _self_test_stale_exemption()++ # A scan that found no routes must not report on them. This gate did not+ # exit 0 over an empty tree before, but only because the stale-exemption+ # ratchet fired first: every entry in the two tables stopped matching, so+ # the failure said "51 exemptions no longer describe an unauthenticated+ # route" — a true statement about the wrong thing, and one that goes away+ # the moment somebody empties the tables. The floor has to be the corpus+ # itself.+ failures += route_scan.self_test_empty_corpus("empty corpus", lambda: main([]))+if failures:print(f"\nself-test FAILED: {failures} case(s) did not behave as specified", file=sys.stderr)return 1@@ -378,7 +390,7 @@ def _self_test_stale_exemption() -> int:A claim nobody re-tests is indistinguishable from a comment."""failures = 0- routes = collect_routes()+ routes = route_scan.collect_routes()by_key = {f"{r.path}::{r.function}": r for r in routes}for key, (verifier, _reason) in IN_BAND_CREDENTIAL_ROUTES.items():@@ -387,7 +399,7 @@ def _self_test_stale_exemption() -> int:print(f" [FAIL] in-band exemption names a route that does not exist: {key}")failures += 1continue- path = REPO_ROOT / route.path+ path = route_scan.REPO_ROOT / route.pathsource = path.read_text(encoding="utf-8", errors="ignore")if verifier not in source:print(f" [FAIL] in-band exemption for {route.function}() names {verifier}(), which {route.path} never mentions")@@ -422,17 +434,32 @@ def main(argv: list[str] | None = None) -> int:if args.self_test:return _self_test()- if not SERVICES_DIR.is_dir():- print(f"ERROR: no services/ directory under {REPO_ROOT} — refusing to report a result for a tree I did not open.", file=sys.stderr)+ if not route_scan.SERVICES_DIR.is_dir():+ print(+ f"ERROR: no services/ directory under {route_scan.REPO_ROOT} — refusing to report a result for a tree I did not open.",+ file=sys.stderr,+ )+ return 2++ routes = route_scan.collect_routes()++ # Before any output mode, and before the exemption ratchet: zero routes is+ # not zero open routes. Shared with check_route_tenant_scope, which owns+ # the collector — one corpus, one floor. Ahead of `--inventory` too,+ # because CI runs it as its own step and a green step printing `TOTAL 0`+ # is the same defect one level out.+ refusal = route_scan.empty_corpus_refusal(routes, route_scan.SERVICES_DIR)+ if refusal is not None:+ print(f"check_route_auth: scanned 0 routes under {route_scan.SERVICES_DIR}")+ print(f"\nFAIL: {refusal}", file=sys.stderr)return 2- routes = collect_routes()unexplained, stale = classify(routes)files = len({r.path for r in routes})authed = sum(1 for r in routes if r.has_auth)print(- f"check_route_auth: scanned {len(routes)} routes across {files} files under {SERVICES_DIR}; "+ f"check_route_auth: scanned {len(routes)} routes across {files} files under {route_scan.SERVICES_DIR}; "f"{authed} authenticated, {len(routes) - authed} public "f"({len(PUBLIC_ROUTES)} named routes, {len(IN_BAND_CREDENTIAL_ROUTES)} verified in-band, "f"{len(PUBLIC_MODULES)} probe module, {len(EXEMPT_SERVICES)} exempt service)"diff --git a/scripts/check_route_tenant_scope.py b/scripts/check_route_tenant_scope.pyindex 9968a98fa..bc951988a 100644--- a/scripts/check_route_tenant_scope.py+++ b/scripts/check_route_tenant_scope.py@@ -48,6 +48,7 @@ import osimport subprocessimport sysimport tempfile+from collections.abc import Callablefrom dataclasses import asdict, dataclass, fieldfrom pathlib import Path@@ -509,6 +510,57 @@ def find_violations(routes: list[Route]) -> tuple[list[Route], list[Route]]:return unauthenticated, unintersected+def empty_corpus_refusal(routes: list[Route], services_dir: Path) -> str | None:+ """Why a scan that found no routes must not render a verdict, or ``None``.++ Shared with ``check_route_auth.py``, which imports this scanner. One+ corpus, one floor: two copies would be two floors, and the second one+ written is the one that gets the condition subtly wrong.++ The directory-missing guard in each ``main()`` is not this case. A corpus+ is lost by a renamed package, a changed decorator spelling or a walk that+ stops descending — none of which removes ``services/``, and all of which+ leave the gate with nothing to look at and a clean verdict to print. This+ gate did exactly that: ``scanned 0 routes across 0 files`` on one line and+ ``OK: every route taking a tenant identifier authenticates`` on the next,+ which is the sentence CI shows on a real pass.+ """+ if routes:+ return None+ return (+ f"no routes found under {services_dir}. Zero routes scanned is not zero routes "+ "unscoped — either the walk, SERVICES_DIR or the decorator patterns have stopped "+ "describing where the routes are."+ )+++def self_test_empty_corpus(label: str, run: Callable[[], int]) -> int:+ """Run a route gate against a ``services/`` tree with no routes; require a refusal.++ ``run`` is the gate's own ``main``, called with the module-level roots+ rebound to a scratch tree. Rebinding is done here rather than in each+ gate because ``check_route_auth`` imports the names *from* this module:+ a gate that rebound its own copy would leave the collector pointed at the+ real checkout and prove nothing. Returns 0 on success, 1 on failure.+ """+ global REPO_ROOT, SERVICES_DIR # noqa: PLW0603 - the scanned root is module state+ original_root, original_services = REPO_ROOT, SERVICES_DIR+ with tempfile.TemporaryDirectory(prefix="route_corpus_empty_") as tmp:+ root = Path(tmp)+ (root / "services" / "api" / "app").mkdir(parents=True)+ (root / "services" / "api" / "app" / "nothing.py").write_text("VALUE = 1\n", encoding="utf-8")+ REPO_ROOT, SERVICES_DIR = root, root / "services"+ try:+ status = run()+ finally:+ REPO_ROOT, SERVICES_DIR = original_root, original_services+ if status != 0:+ print(f" [PASS] {label}: a services/ tree with no routes exits {status} rather than reporting it clean")+ return 0+ print(f" [FAIL] {label}: reported OK having scanned zero routes")+ return 1++def _print_inventory(routes: list[Route]) -> None:services = sorted({r.service for r in routes})print(f"Route inventory — scanned {SERVICES_DIR}")@@ -613,7 +665,7 @@ async def queue(user: AuthUser, tenant_id: UUID):# printed "scanned 0 routes across 0 files" and then "OK: every route# taking a tenant identifier authenticates" against a services/ directory# with nothing in it — the clean verdict CI shows on a real pass.- failures += _self_test_empty_corpus()+ failures += self_test_empty_corpus("empty corpus", lambda: main([]))if failures:print(f"\nself-test FAILED: {failures} case(s) did not behave as specified", file=sys.stderr)@@ -625,32 +677,6 @@ async def queue(user: AuthUser, tenant_id: UUID):return 0-def _self_test_empty_corpus() -> int:- """Point the scan at a services/ directory with no routes and require a refusal.-- The directory-missing guard is not this case. A corpus is lost by a- renamed package, a changed decorator spelling or a walk that stops- descending — none of which removes ``services/``, and all of which leave- the gate with nothing to look at and a clean verdict to print.- """- global REPO_ROOT, SERVICES_DIR # noqa: PLW0603 - the scanned root is module state- original_root, original_services = REPO_ROOT, SERVICES_DIR- with tempfile.TemporaryDirectory(prefix="route_scope_empty_") as tmp:- root = Path(tmp)- (root / "services" / "api" / "app").mkdir(parents=True)- (root / "services" / "api" / "app" / "nothing.py").write_text("VALUE = 1\n", encoding="utf-8")- REPO_ROOT, SERVICES_DIR = root, root / "services"- try:- status = main([])- finally:- REPO_ROOT, SERVICES_DIR = original_root, original_services- if status != 0:- print(f" [PASS] empty corpus: a services/ tree with no routes exits {status} rather than reporting it clean")- return 0- print(" [FAIL] empty corpus: reported OK having scanned zero routes")- return 1--def _self_test_stale_exemption() -> int:"""Assert IN_BAND_CREDENTIAL_ROUTES stops exempting once its verifier is gone.@@ -703,6 +729,20 @@ def main(argv: list[str] | None = None) -> int:routes = collect_routes()+ # Before any output mode. Naming the count was half the fix; see+ # empty_corpus_refusal() for why the directory check above is not this+ # case, and for the two-line output that made it invisible.+ #+ # Ahead of `--inventory` as well as the default, because CI runs the+ # inventory as its own step: a green step printing `TOTAL 0 0 0 0 0` is+ # the same defect one level out, and it survived the first fix because+ # only the default path was given a floor.+ refusal = empty_corpus_refusal(routes, SERVICES_DIR)+ if refusal is not None:+ print(f"check_route_tenant_scope: scanned 0 routes across 0 files under {SERVICES_DIR}")+ print(f"\nFAIL: {refusal}", file=sys.stderr)+ return 2+if args.json:print(json.dumps([asdict(r) for r in routes], indent=2))return 0@@ -718,23 +758,6 @@ def main(argv: list[str] | None = None) -> int:files = len({r.path for r in routes})print(f"check_route_tenant_scope: scanned {len(routes)} routes across {files} files under {SERVICES_DIR}")- # And refuse when it opened nothing. Naming the count was half the fix:- # against a tree with a services/ directory and no routes in it, this- # printed "scanned 0 routes across 0 files" and then "OK: every route- # taking a tenant identifier authenticates" — a clean verdict on an empty- # set, in the same sentence CI shows when the real scan passes. The- # directory check above only catches services/ being absent altogether,- # which is not how a scan loses its corpus: a renamed package, a changed- # decorator spelling or a broken walk all leave the directory in place.- if not routes:- print(- f"\nFAIL: no routes found under {SERVICES_DIR}. Zero routes scanned is not zero routes "- "unscoped — either the walk, SERVICES_DIR or the decorator patterns have stopped "- "describing where the routes are.",- file=sys.stderr,- )- return 2-if unauthenticated:print(f"\nFAIL: {len(unauthenticated)} route(s) take a tenant identifier with no auth dependency.", file=sys.stderr)print(" The tenant is whatever the caller typed. Derive it from the authenticated principal.", file=sys.stderr)diff --git a/scripts/check_runtime_db_role.py b/scripts/check_runtime_db_role.pyindex 134250ae6..778516c01 100644--- a/scripts/check_runtime_db_role.py+++ b/scripts/check_runtime_db_role.py@@ -87,6 +87,7 @@ Usagefrom __future__ import annotationsimport argparse+import astimport asyncioimport reimport sys@@ -123,7 +124,17 @@ SURFACE_GLOBS: tuple[str, ...] = (#: Environment variable names whose value is a DSN the *migration/DDL* path#: uses. These are the ones that are *supposed* to be the owner.-MIGRATION_VARS = frozenset({"DATABASE_MIGRATION_URL", "AISOC_DATABASE_MIGRATION_URL"})+#:+#: A suffix rather than a set of names. The set held two spellings and the four+#: services that manage their own alembic chain each need a third+#: (``UEBA_DATABASE_MIGRATION_URL`` and friends), so a set would have to grow+#: by one entry per service — a list pretending to be a rule. Anything ending+#: in ``DATABASE_MIGRATION_URL`` is a migration DSN whatever prefixes it.+MIGRATION_VAR_SUFFIX = "DATABASE_MIGRATION_URL"+++def is_migration_var(name: str) -> bool:+ return name.upper().endswith(MIGRATION_VAR_SUFFIX)#: Some DSNs must be the owner and cannot say so in their variable name, because#: the tool reading them chose the name: alembic and the SQL runner both read@@ -199,6 +210,14 @@ class Inspected:ignored_dsns: list[tuple[str, str, str]] = field(default_factory=list)#: DSNs the surface declared as the owner's on purpose, with the reason.exempted: list[tuple[str, str, str, str]] = field(default_factory=list)+ #: Alembic chains found, and the credentials each environment names.+ entrypoints: list[EntryPoint] = field(default_factory=list)+ #: (surface, service, service_dir, var) pairs whose variable the service+ #: was shown to be able to read.+ readable_bindings: list[ServiceBinding] = field(default_factory=list)+ #: Services carrying a DSN whose build context is not in this tree, so+ #: there is no source to ask. Recorded, not credited.+ unmapped_bindings: list[tuple[str, str]] = field(default_factory=list)# ---------------------------------------------------------------------------@@ -347,7 +366,7 @@ def classify(surface: str, text: str, inspected: Inspected, known_superusers: sefor dsn in usable:var, role = dsn.var, _canonical_role(dsn.role)- is_migration = var.upper() in MIGRATION_VARS or dsn.owner_reason is not None+ is_migration = is_migration_var(var) or dsn.owner_reason is not Nonebucket = inspected.migration_dsns if is_migration else inspected.runtime_dsnsbucket.append((surface, var, role))if dsn.owner_reason is not None:@@ -386,6 +405,282 @@ def classify(surface: str, text: str, inspected: Inspected, known_superusers: sereturn findings+# ---------------------------------------------------------------------------+# Where the DDL comes from: the alembic chains+# ---------------------------------------------------------------------------+# The scan above reads deployment surfaces, and a deployment surface only says+# which DSN is handed to a service. It cannot say which of them the service+# uses to apply DDL — and four services in this tree (honeytokens, osquery-tls,+# purple-team, ueba) manage their own schema through alembic and, until this+# gate learned to look, read the *runtime* variable to do it. Their migration+# and runtime credentials were therefore the same one, so an operator pointing+# them at the owner lost row-level security on twelve tables with nothing to+# object.+#+# Discovery is by alembic's own convention rather than by a list of four paths:+# an alembic chain is configured by an ``alembic.ini`` whose ``script_location``+# names the directory holding ``env.py``. Add a fifth chain and it is picked up+# by being an alembic chain.++#: Variable names an environment file may read for a DSN. Matched on shape, not+#: against a vocabulary, because every service spells its own prefix.+_ENV_NAME_RE = re.compile(r"^[A-Z][A-Z0-9_]*$")+_DSN_VAR_HINT = ("DATABASE", "_DSN", "POSTGRES")++_SCRIPT_LOCATION_RE = re.compile(r"^\s*script_location\s*=\s*(?P<loc>\S+)", re.M)+++@dataclass+class EntryPoint:+ """One alembic chain and the credentials its environment names."""++ ini: str+ env_py: str | None+ migration_vars: list[str]+ runtime_vars: list[str]+++def _env_var_literals(source: str) -> list[str]:+ """Environment-variable-shaped string literals in a Python source file.++ Deliberately loose, and loose in the direction that produces *findings*+ rather than suppressing them: this is used to ask whether an environment+ names a migration credential at all, and the failure that actually+ happened was naming none.++ What it cannot prove is that the file *reads* what it names — that needs+ the file to run. ``.github/workflows/integration.yml`` closes that half+ behaviourally: it applies each chain with only the migration variable in+ the environment, so an ``env.py`` naming one it never reads fails there.+ """+ out: list[str] = []+ try:+ tree = ast.parse(source)+ except SyntaxError:+ return out+ for node in ast.walk(tree):+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ value = node.value+ if _ENV_NAME_RE.match(value) and any(hint in value for hint in _DSN_VAR_HINT) and value not in out:+ out.append(value)+ return out+++def collect_entrypoints(root: Path) -> list[EntryPoint]:+ points: list[EntryPoint] = []+ for ini in sorted(root.rglob("alembic.ini")):+ rel = ini.relative_to(root).as_posix()+ if any(part in rel for part in ("node_modules/", "plans/", ".venv/")):+ continue+ location = _SCRIPT_LOCATION_RE.search(ini.read_text(encoding="utf-8", errors="ignore"))+ env_py = (ini.parent / location.group("loc") / "env.py") if location else None+ if env_py is None or not env_py.is_file():+ points.append(EntryPoint(ini=rel, env_py=None, migration_vars=[], runtime_vars=[]))+ continue+ names = _env_var_literals(env_py.read_text(encoding="utf-8", errors="ignore"))+ points.append(+ EntryPoint(+ ini=rel,+ env_py=env_py.relative_to(root).as_posix(),+ migration_vars=[n for n in names if is_migration_var(n)],+ runtime_vars=[n for n in names if not is_migration_var(n)],+ )+ )+ return points+++def classify_entrypoints(points: list[EntryPoint], configured: set[str]) -> list[Finding]:+ """Both directions over the chains that apply DDL.++ ``configured`` is every variable name any deployment surface assigns, so+ the reverse direction can tell a real split from one that exists only in+ the code.+ """+ findings: list[Finding] = []+ for point in points:+ if point.env_py is None:+ findings.append(+ Finding(+ point.ini,+ "declares an alembic chain whose script_location has no env.py the gate could read, "+ "so nothing can be said about which credential applies this chain",+ )+ )+ continue+ if not (point.migration_vars or point.runtime_vars):+ findings.append(+ Finding(+ point.env_py,+ "is an alembic environment from which no database variable could be read — the gate "+ "cannot vouch for it. Silence from a scanner and compliance look identical.",+ )+ )+ continue+ if not point.migration_vars:+ findings.append(+ Finding(+ point.env_py,+ f"applies DDL as {', '.join(point.runtime_vars)}, which is what the service connects as. "+ f"Read a *DATABASE_MIGRATION_URL first: the runtime role deliberately holds no CREATE, and "+ "an operator who points this at the owner instead loses row-level security on every table "+ "this chain owns.",+ )+ )+ continue+ if not any(name in configured for name in point.migration_vars):+ findings.append(+ Finding(+ point.env_py,+ f"names {', '.join(point.migration_vars)} and no deployment surface sets any of them, so "+ "every operator gets the runtime-credential fallback. The split exists in the code and "+ "not in the deployment.",+ )+ )+ return findings+++# ---------------------------------------------------------------------------+# A DSN handed to a service that cannot read it+# ---------------------------------------------------------------------------+# The reverse of everything above, and the shape that hid three of these four+# services from this gate entirely. ``docker-compose.yml`` set+# ``DATABASE_URL=aisoc_app`` on honeytokens, purple-team and osquery-tls and+# the gate credited all three — but each declares ``env_prefix`` in its+# pydantic settings, so the variable it actually reads is+# ``HONEYTOKEN_DATABASE_URL``. The compose entry was inert: the services fell+# back to a default naming the *owner*, and the role switch reached none of+# them. Found by enumerating what the gate credited rather than what it flagged.++_COMPOSE_SERVICE_RE = re.compile(r"^ (?P<name>[a-z0-9][\w.-]*):\s*$")+_BUILD_CONTEXT_RE = re.compile(r"context:\s*[.\s/]*services/(?P<dir>[\w.-]+)\s*$")+#: A whole quoted token that is exactly an identifier. Backticks are in the+#: set for Go raw strings and JS template literals; for Python the AST is used+#: instead, because reStructuredText prose is full of ``DATABASE_URL`` and a+#: docstring mentioning a variable is not a service reading it — that single+#: over-credit hid one of the three inert DSNs behind a comment.+_LITERAL_RE = re.compile(r"""["'`]([A-Za-z_][A-Za-z0-9_]*)["'`]""")+_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")++#: Never consulted when asking what a service can read. A test that sets a+#: variable is not the program reading it — ``services/osquery-tls`` has+#: ``os.environ.setdefault("DATABASE_URL", …)`` in its conftest and reads the+#: name nowhere else, which is precisely the case this direction exists for.+_NOT_THE_PROGRAM = ("/tests/", "/test_", "/node_modules/", "/.venv/")++_SOURCE_SUFFIXES = frozenset({".py", ".go", ".ts", ".js", ".mjs"})+++@dataclass+class ServiceBinding:+ surface: str+ service: str+ service_dir: str+ var: str+++def readable_env_names(service_dir: Path) -> set[str]:+ """Environment names this service's own source can resolve.++ Two sources, because one alone misses a whole language or a whole+ framework:++ * every quoted identifier in its source — which covers ``os.environ.get``,+ Go's ``getEnv("DATABASE_DSN", "")``, ``process.env["X"]`` and pydantic's+ ``AliasChoices`` without needing a parser per language;+ * for each ``BaseSettings`` class, ``env_prefix`` + field name, because+ that name appears nowhere in the source at all. Omitting this half is+ what made the check report every service as fine.+ """+ names: set[str] = set()+ for path in service_dir.rglob("*"):+ if not path.is_file() or path.suffix not in _SOURCE_SUFFIXES:+ continue+ posix = path.as_posix()+ if any(fragment in posix for fragment in _NOT_THE_PROGRAM):+ continue+ text = path.read_text(encoding="utf-8", errors="ignore")+ names |= {m.group(1) for m in re.finditer(r"process\.env\.([A-Za-z_]\w*)", text)}+ if path.suffix != ".py":+ names |= set(_LITERAL_RE.findall(text))+ continue+ try:+ tree = ast.parse(text)+ except SyntaxError:+ names |= set(_LITERAL_RE.findall(text))+ continue+ docstrings = {+ id(node.body[0].value)+ for node in ast.walk(tree)+ if isinstance(node, ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef)+ and getattr(node, "body", None)+ and isinstance(node.body[0], ast.Expr)+ and isinstance(node.body[0].value, ast.Constant)+ and isinstance(node.body[0].value.value, str)+ }+ names |= {+ node.value+ for node in ast.walk(tree)+ if isinstance(node, ast.Constant)+ and isinstance(node.value, str)+ and id(node) not in docstrings+ and _IDENTIFIER_RE.match(node.value)+ }+ for node in ast.walk(tree):+ if not isinstance(node, ast.ClassDef):+ continue+ bases = {b.id if isinstance(b, ast.Name) else getattr(b, "attr", "") for b in node.bases}+ if "BaseSettings" not in bases:+ continue+ prefix = ""+ for stmt in node.body:+ if isinstance(stmt, ast.Assign) and any(getattr(t, "id", "") == "model_config" for t in stmt.targets):+ for kw in getattr(stmt.value, "keywords", []):+ if kw.arg == "env_prefix" and isinstance(kw.value, ast.Constant):+ prefix = str(kw.value.value)+ for stmt in node.body:+ if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):+ names.add(f"{prefix}{stmt.target.id}")+ return {name.upper() for name in names}+++def collect_service_bindings(surface: str, text: str) -> tuple[list[ServiceBinding], list[str]]:+ """DSN variables a compose surface sets on a service it builds from this tree.++ Returns ``(bindings, unmapped)``; ``unmapped`` names services carrying a+ DSN whose build context is not a directory under ``services/``, which the+ caller records rather than credits.+ """+ bindings: list[ServiceBinding] = []+ unmapped: list[str] = []+ contexts: dict[str, str] = {}+ service: str | None = None+ for line in text.splitlines():+ match = _COMPOSE_SERVICE_RE.match(line)+ if match:+ service = match.group("name")+ continue+ ctx = _BUILD_CONTEXT_RE.search(line)+ if ctx and service:+ contexts[service] = ctx.group("dir")++ service = None+ for raw in text.splitlines():+ match = _COMPOSE_SERVICE_RE.match(raw)+ if match:+ service = match.group("name")+ continue+ if service is None or not _SCHEME_HINT_RE.search(raw):+ continue+ assign = _ASSIGN_RE.match(_expand_default(raw))+ if assign is None or assign.group("key") in {"context", "image", "value"}:+ continue+ if service not in contexts:+ unmapped.append(f"{service}: {assign.group('key')}")+ continue+ bindings.append(ServiceBinding(surface, service, contexts[service], assign.group("key")))+ return bindings, unmapped++# ---------------------------------------------------------------------------# Self-test — runs before the scan, not behind a flag# ---------------------------------------------------------------------------@@ -570,6 +865,9 @@ def self_test() -> list[str]:expected = "accept" if should_pass else "reject"failures.append(f"{label}: classifier {verdict}, expected it to {expected}")+ failures.extend(_self_test_entrypoints())+ failures.extend(_self_test_readable_names())+# The empty-input rule, asserted rather than assumed: a run that inspected# nothing must not be able to report OK.if not _empty_input_findings(Inspected()):@@ -577,6 +875,127 @@ def self_test() -> list[str]:populated = Inspected(surfaces=["x"], runtime_dsns=[("x", "DATABASE_URL", "r")])if _empty_input_findings(populated):failures.append("a populated scan was reported as empty — the empty-input rule is over-tight")+ if not _empty_entrypoint_findings(Inspected(surfaces=["x"])):+ failures.append("a scan that found no alembic chain produced no finding — that direction can go quiet unnoticed")+ if _empty_entrypoint_findings(Inspected(entrypoints=[EntryPoint("a.ini", "env.py", ["X_DATABASE_MIGRATION_URL"], [])])):+ failures.append("a scan that found a chain was reported as empty — the chain empty-input rule is over-tight")+ return failures+++#: ``(label, entry point, variables the deployment sets, should pass)``.+_ENTRYPOINT_FIXTURES: tuple[tuple[str, EntryPoint, set[str], bool], ...] = (+ (+ "a chain reading a migration credential the deployment sets",+ EntryPoint("svc/alembic.ini", "svc/alembic/env.py", ["SVC_DATABASE_MIGRATION_URL"], ["DATABASE_URL"]),+ {"SVC_DATABASE_MIGRATION_URL", "DATABASE_URL"},+ True,+ ),+ (+ "a chain applying DDL as the runtime credential — the state all four were in",+ EntryPoint("svc/alembic.ini", "svc/alembic/env.py", [], ["DATABASE_URL", "SVC_DATABASE_URL"]),+ {"DATABASE_URL"},+ False,+ ),+ (+ "a split that exists in the code and in no deployment surface",+ EntryPoint("svc/alembic.ini", "svc/alembic/env.py", ["SVC_DATABASE_MIGRATION_URL"], ["DATABASE_URL"]),+ {"DATABASE_URL"},+ False,+ ),+ (+ "an alembic.ini whose env.py the gate could not read is a blind spot, not a pass",+ EntryPoint("svc/alembic.ini", None, [], []),+ {"DATABASE_URL"},+ False,+ ),+ (+ "an env.py naming no database variable at all is a blind spot too",+ EntryPoint("svc/alembic.ini", "svc/alembic/env.py", [], []),+ {"DATABASE_URL"},+ False,+ ),+ (+ "the unprefixed spelling counts — the rule is the suffix, not a vocabulary",+ EntryPoint("svc/alembic.ini", "svc/alembic/env.py", ["DATABASE_MIGRATION_URL"], ["DATABASE_URL"]),+ {"DATABASE_MIGRATION_URL"},+ True,+ ),+)+++def _self_test_entrypoints() -> list[str]:+ failures: list[str] = []+ for label, point, configured, should_pass in _ENTRYPOINT_FIXTURES:+ found = classify_entrypoints([point], configured)+ if (not found) is not should_pass:+ verdict = "accepted" if not found else f"rejected ({found[0].detail[:70]}…)"+ failures.append(f"entry point — {label}: {verdict}, expected it to {'accept' if should_pass else 'reject'}")++ # And the literal reader, which is what turns a file into an EntryPoint.+ source = (+ 'MIGRATION_URL_VARS = ("SVC_DATABASE_MIGRATION_URL", "DATABASE_MIGRATION_URL")\n'+ 'X = os.environ.get("DATABASE_URL")\n'+ 'Y = "not an env name"\n'+ )+ names = _env_var_literals(source)+ if names != ["SVC_DATABASE_MIGRATION_URL", "DATABASE_MIGRATION_URL", "DATABASE_URL"]:+ failures.append(f"the env-name reader returned {names}, which is not what that source names")+ return failures+++def _self_test_readable_names() -> list[str]:+ """A pydantic ``env_prefix`` makes the readable name appear nowhere in the source.++ This is the assertion that would have failed before the prefix half was+ added, while the gate reported every service as fine.+ """+ import tempfile # noqa: PLC0415 — self-test only++ failures: list[str] = []+ prefixed = (+ "from pydantic_settings import BaseSettings, SettingsConfigDict\n"+ "class Settings(BaseSettings):\n"+ ' model_config = SettingsConfigDict(env_prefix="SVC_")\n'+ ' database_url: str = "postgresql://a:b@c/d"\n'+ )+ with tempfile.TemporaryDirectory(prefix="db-role-readable-") as tmp:+ svc = Path(tmp) / "svc" / "app"+ svc.mkdir(parents=True)+ (svc / "config.py").write_text(prefixed, encoding="utf-8")+ (svc / "conftest_like").mkdir()+ tests = Path(tmp) / "svc" / "tests"+ tests.mkdir()+ (tests / "conftest.py").write_text('os.environ.setdefault("DATABASE_URL", "x")\n', encoding="utf-8")+ names = readable_env_names(Path(tmp) / "svc")+ if "SVC_DATABASE_URL" not in names:+ failures.append("env_prefix + field did not yield SVC_DATABASE_URL, so a prefixed service reads as unreachable")+ if "DATABASE_URL" in names:+ failures.append("a name only a test file mentions was credited; a conftest setting a variable is not the program reading it")++ # Both directions: a service that genuinely reads the unprefixed name.+ unprefixed = 'import os\nDSN = os.environ.get("DATABASE_URL", "")\n'+ with tempfile.TemporaryDirectory(prefix="db-role-readable-") as tmp:+ svc = Path(tmp) / "svc" / "app"+ svc.mkdir(parents=True)+ (svc / "db.py").write_text(unprefixed, encoding="utf-8")+ names = readable_env_names(Path(tmp) / "svc")+ if "DATABASE_URL" not in names:+ failures.append("a direct os.environ.get('DATABASE_URL') was not credited, which would be a false finding")++ # And the compose side: the binding has to be attributed to the right service.+ compose = (+ "services:\n"+ " api:\n"+ " build:\n"+ " context: ./services/api\n"+ " environment:\n"+ " DATABASE_URL: postgresql+asyncpg://r:p@postgres:5432/aisoc\n"+ " postgres:\n"+ " image: postgres:16\n"+ )+ bindings, unmapped = collect_service_bindings("docker-compose.yml", compose)+ if [(b.service, b.service_dir, b.var) for b in bindings] != [("api", "api", "DATABASE_URL")] or unmapped:+ failures.append(f"compose binding parse returned {[(b.service, b.service_dir, b.var) for b in bindings]}, unmapped={unmapped}")return failures@@ -604,6 +1023,26 @@ def _empty_input_findings(inspected: Inspected) -> list[Finding]:return out+def _empty_entrypoint_findings(inspected: Inspected) -> list[Finding]:+ """The same rule, for the direction that reads the alembic chains.++ Kept separate from the surface rule so a run that found surfaces and no+ chains still fails. Folding the two into one condition is how a direction+ goes quiet without anybody noticing: the gate would print OK on the+ strength of the half that still worked.+ """+ if inspected.entrypoints:+ return []+ return [+ Finding(+ "<root>",+ "no alembic.ini was found, so the question of which credential applies each chain was "+ "never put. Four services in this tree manage their own schema; a scan that finds none "+ "has stopped looking rather than found nothing to look at.",+ )+ ]++# ---------------------------------------------------------------------------# Live mode# ---------------------------------------------------------------------------@@ -772,7 +1211,39 @@ def main(argv: list[str] | None = None) -> int:for rel, text in surfaces:findings.extend(classify(rel, text, inspected, known))+ # Which credential applies each chain, and whether the deployment sets it.+ configured: set[str] = set()+ for _rel, text in surfaces:+ for line in text.splitlines():+ assign = _ASSIGN_RE.match(line)+ if assign:+ configured.add(assign.group("key").upper())+ inspected.entrypoints = collect_entrypoints(root)+ findings.extend(classify_entrypoints(inspected.entrypoints, configured))++ # And the reverse: a DSN handed to a service that cannot read the name.+ readable_cache: dict[str, set[str]] = {}+ for rel, text in surfaces:+ bindings, unmapped = collect_service_bindings(rel, text)+ inspected.unmapped_bindings.extend((rel, item) for item in unmapped)+ for binding in bindings:+ if binding.service_dir not in readable_cache:+ readable_cache[binding.service_dir] = readable_env_names(root / "services" / binding.service_dir)+ if binding.var.upper() in readable_cache[binding.service_dir]:+ inspected.readable_bindings.append(binding)+ continue+ findings.append(+ Finding(+ rel,+ f"sets {binding.var} on {binding.service}, and services/{binding.service_dir} reads no such "+ "variable — so the DSN is inert and the service falls back to whatever its own default names. "+ "A role switch that never reaches the service is the bypass wearing a compliant-looking "+ "deployment surface.",+ )+ )+findings.extend(_empty_input_findings(inspected))+ findings.extend(_empty_entrypoint_findings(inspected))print(f"check_runtime_db_role: scanned {len(inspected.surfaces)} deployment surfaces under {root}")print(f" roles this deployment provisions as privileged: {sorted(known) or '<none found>'}")@@ -792,6 +1263,18 @@ def main(argv: list[str] | None = None) -> int:for surface, var, role in inspected.ignored_dsns:print(f" {surface}: {var} as {role!r}")+ print(f" {len(inspected.entrypoints)} alembic chain(s), and the credential each applies DDL as:")+ for point in inspected.entrypoints:+ applies = ", ".join(point.migration_vars) if point.migration_vars else f"<runtime: {', '.join(point.runtime_vars) or 'none'}>"+ print(f" {point.env_py or point.ini}: {applies}")+ print(f" {len(inspected.readable_bindings)} DSN variable(s) confirmed readable by the service they are set on:")+ for binding in inspected.readable_bindings:+ print(f" {binding.surface}: {binding.var} on {binding.service} → services/{binding.service_dir}")+ if inspected.unmapped_bindings:+ print(f" {len(inspected.unmapped_bindings)} DSN(s) on services built outside this tree, so there is no source to ask:")+ for surface, item in inspected.unmapped_bindings:+ print(f" {surface}: {item}")+if args.dsn:findings.extend(asyncio.run(_live_findings(args.dsn, args.owner_dsn)))print(f" live target: {_redact(args.dsn)}")diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.pyindex b3264102d..573a8aad6 100644--- a/scripts/check_tenant_query_predicates.py+++ b/scripts/check_tenant_query_predicates.py@@ -1324,14 +1324,67 @@ def _self_test() -> int:failures += _self_test_stale_ratchet()failures += _self_test_ratchet_ceiling()+ failures += _self_test_empty_corpus()if failures:print(f"\nself-test FAILED: {failures} case(s) did not behave as specified", file=sys.stderr)return 1- print("\nself-test passed: drift detected in both directions, ten controls clear, and a stale ratchet entry is dropped.")+ print(+ "\nself-test passed: drift detected in both directions, ten controls clear, a stale ratchet "+ "entry is dropped, and each of the three ways the corpus can empty is refused."+ )return 0+#: ``(label, what to put in the scratch tree)``. Each leaves ``services/`` in+#: place and empties one of the three things the gate counts.+_EMPTY_CORPUS_CASES: tuple[tuple[str, dict[str, str], str | None], ...] = (+ ("no Python at all under services/", {}, None),+ ("Python but no tenant-scoped table anywhere", {"r.py": "VALUE = 1\n"}, None),+ (+ "a tenant-scoped table declared and no statement touching one",+ {"r.py": "VALUE = 1\n"},+ "CREATE TABLE IF NOT EXISTS widgets (\n id UUID PRIMARY KEY,\n tenant_id UUID NOT NULL\n);",+ ),+)+++def _self_test_empty_corpus() -> int:+ """Each of the three ways this scan can end up with nothing must refuse.++ Not one case: the gate counts files, tables and statements, and any of+ them reaching zero means a different part of it stopped working. A single+ ``if not findings`` would have covered none of them — zero findings is+ what a clean tree looks like.++ The controls at the end are as important as the cases: an over-tight+ floor that fires on the real repository would be "fixed" by deleting it.+ """+ global REPO_ROOT, SERVICES_DIR # noqa: PLW0603 - the scanned root is module state+ original_root, original_services = REPO_ROOT, SERVICES_DIR+ failures = 0+ for label, sources, migration in _EMPTY_CORPUS_CASES:+ with tempfile.TemporaryDirectory(prefix="predicates_empty_") as tmp:+ root = Path(tmp)+ (root / "services" / "probe" / "app").mkdir(parents=True)+ for name, src in sources.items():+ (root / "services" / "probe" / "app" / name).write_text(src, encoding="utf-8")+ if migration is not None:+ (root / "services" / "probe" / "migrations").mkdir(parents=True)+ (root / "services" / "probe" / "migrations" / "001.sql").write_text(migration, encoding="utf-8")+ REPO_ROOT, SERVICES_DIR = root, root / "services"+ try:+ status = main([])+ finally:+ REPO_ROOT, SERVICES_DIR = original_root, original_services+ if status != 0:+ print(f" [PASS] empty corpus — {label}: exits {status} rather than reporting it clean")+ else:+ print(f" [FAIL] empty corpus — {label}: reported OK having judged nothing")+ failures += 1+ return failures++def _self_test_stale_ratchet() -> int:"""Strip a live ratchet entry's justification and assert it stops protecting.@@ -1396,6 +1449,49 @@ def main(argv: list[str] | None = None) -> int:result = scan()findings, inv, files, statements = result.findings, result.inventory, result.files, result.statements+ # Name what was scanned, before any output mode. A gate that prints OK+ # without saying what it opened cannot be told apart from one that opened+ # nothing.+ print(+ f"check_tenant_query_predicates: scanned {files} files under {SERVICES_DIR}; "+ f"{statements} statements touch {len(inv.tables)} tenant-scoped tables "+ f"({len(inv.tables) - len(inv.tables & inv.rls_tables)} of them with no RLS policy)"+ )++ # And refuse when any of the three things it counts is zero. This gate did+ # not exit 0 over an empty tree before, but only because every ratchet+ # entry went stale at once and that check happens to run first — a true+ # statement about the wrong thing, and one that disappears the moment the+ # ratchet is emptied. The floor has to be the corpus.+ #+ # Three conditions rather than one, because they are three different+ # losses and rolling them together would let the interesting one hide+ # behind the obvious one. The middle is the dangerous case: the inventory+ # is derived from migration DDL and model classes, so a changed glob or a+ # renamed base class empties it silently while the walk still opens+ # hundreds of files and the gate still prints OK.+ #+ # Ahead of `--inventory` as well as the default, because CI runs the+ # inventory as its own step and the coverage figures it prints are quoted+ # elsewhere; all-zero and green is the worst of both.+ for count, detail in (+ (files, f"no Python file was read under {SERVICES_DIR} — the walk found nothing to scan"),+ (+ len(inv.tables),+ "no tenant-scoped table was discovered. The inventory comes from migration DDL and mapped "+ "models; zero of them means the schema globs or the model detection stopped matching, and "+ "every statement below would be judged against an empty set",+ ),+ (+ statements,+ f"{files} files were read and not one statement touched a tenant-scoped table. Found nothing "+ "and scanned nothing print the same word",+ ),+ ):+ if count == 0:+ print(f"\nFAIL: {detail}.", file=sys.stderr)+ return 2+if args.json:print(json.dumps([asdict(f) for f in findings], indent=2))return 0@@ -1405,14 +1501,6 @@ def main(argv: list[str] | None = None) -> int:return 0unratcheted, stale = partition(findings)-- # Name what was scanned. A gate that prints OK without saying what it- # opened cannot be told apart from one that opened nothing.- print(- f"check_tenant_query_predicates: scanned {files} files under {SERVICES_DIR}; "- f"{statements} statements touch {len(inv.tables)} tenant-scoped tables "- f"({len(inv.tables) - len(inv.tables & inv.rls_tables)} of them with no RLS policy)"- )if result.rls_scoped:print(f" {result.rls_scoped} statement(s) are scoped by an RLS context on the connection rather than by a "diff --git a/scripts/gate_toolkit.py b/scripts/gate_toolkit.pyindex 6716954bc..521be9653 100644--- a/scripts/gate_toolkit.py+++ b/scripts/gate_toolkit.py@@ -47,7 +47,10 @@ from contextlib import contextmanagerfrom pathlib import Path__all__ = [+ "BARE","SELF_TEST_FLAG",+ "SKELETON",+ "TREE_SHAPES","VERDICT_FLAG_PREFERENCE","verdict_args","repo_root",@@ -115,8 +118,40 @@ def repo_root(start: Path | None = None) -> Path:return fallback+#: The two shapes a gate can be pointed at when it has nothing to judge.+#:+#: ``BARE`` the directories a gate renders a verdict about are *absent*.+#: ``SKELETON`` they are *present and empty*.+#:+#: They are different questions and a gate can answer them differently. The+#: shape that actually recurs here is the second: ``check_grafana_dashboards``+#: failed on an empty dashboards directory and passed on a missing one, and+#: ``check_route_tenant_scope`` printed ``scanned 0 routes across 0 files``+#: followed by a clean verdict against a ``services/`` directory that existed+#: and held nothing. A gate whose first act is ``if not X.is_dir(): return 2``+#: refuses BARE for a reason that says nothing about its corpus.+BARE = "bare"+SKELETON = "skeleton"+TREE_SHAPES = (BARE, SKELETON)++#: Directories the skeleton creates empty. Every top-level directory any gate+#: in this tree renders a verdict about; a gate whose subject is missing from+#: this list sees BARE twice and the second shape buys nothing for it.+_SKELETON_DIRS = (+ "services",+ "detections",+ "apps",+ "packages",+ "plugins",+ "docs",+ "infra",+ "marketplace",+ ".github/workflows",+)++@contextmanager-def scratch_tree(source: Path | None = None) -> Iterator[Path]:+def scratch_tree(source: Path | None = None, *, shape: str = BARE) -> Iterator[Path]:"""A git repository holding this repository's ``scripts/`` and nothing else.Not an empty directory: the gate under test has to be *runnable*, which@@ -126,17 +161,32 @@ def scratch_tree(source: Path | None = None) -> Iterator[Path]:pointed here has nothing to inspect, so anything other than a refusal isa result it invented.+ ``shape=SKELETON`` creates those directories instead of omitting them,+ each empty. That distinguishes "the tree is not there" from "the corpus+ is gone", which is the failure that actually happens: a renamed package,+ a changed decorator spelling, a glob that stopped matching. None of them+ removes ``services/``.+It is a real git repository with a commit, because a gate that resolvesits root through ``git rev-parse`` must land *here* and not walk out intothe checkout the scratch directory happens to sit inside."""+ if shape not in TREE_SHAPES:+ raise ValueError(f"unknown scratch tree shape {shape!r}; expected one of {TREE_SHAPES}")scripts = (source or Path(__file__).resolve().parent).resolve()if not scripts.is_dir():raise FileNotFoundError(f"no scripts directory to copy from: {scripts}")- tmp = Path(tempfile.mkdtemp(prefix="aisoc-empty-tree-"))+ tmp = Path(tempfile.mkdtemp(prefix=f"aisoc-{shape}-tree-"))try:shutil.copytree(scripts, tmp / "scripts")+ if shape == SKELETON:+ for rel in _SKELETON_DIRS:+ (tmp / rel).mkdir(parents=True, exist_ok=True)+ # git does not track a directory, only files in it, and a gate+ # resolving its root through git must still find the directory+ # after `git clean -qxfd` between probes.+ (tmp / rel / ".gitkeep").write_text("", encoding="utf-8")git = ["git", "-c", "user.name=gate", "-c", "user.email=gate@invalid", "-c", "commit.gpgsign=false"]for argv in (["init", "-q", "-b", "main"], ["add", "-A"], ["commit", "-qm", "scratch"]):subprocess.run(git + argv, cwd=tmp, check=True, capture_output=True) # noqa: S603@@ -173,9 +223,9 @@ def run_in_scratch_tree(return done.returncode, (done.stdout or "") + (done.stderr or "")-def refuses_an_empty_tree(script: str, args: Sequence[str] = ()) -> tuple[bool, str]:+def refuses_an_empty_tree(script: str, args: Sequence[str] = (), *, shape: str = BARE) -> tuple[bool, str]:"""Whether ``script`` declines to render a verdict about a tree with no content."""- with scratch_tree() as tree:+ with scratch_tree(shape=shape) as tree:status, output = run_in_scratch_tree(script, args, tree=tree)if status is None:return False, outputdiff --git a/services/api/migrations/062_approval_timers.sql b/services/api/migrations/062_approval_timers.sqlnew file mode 100644index 000000000..f251a357d--- /dev/null+++ b/services/api/migrations/062_approval_timers.sql@@ -0,0 +1,92 @@+-- The one table application code created at runtime, brought into the chain.+--+-- What it is+-- ----------+-- `services/slack-bot` arms a timer for every action that needs approval, so+-- a forgotten Approve/Deny terminates on its configured safe default instead+-- of leaving a containment in `awaiting_approval` forever.+-- `PostgresTimerStore` makes those timers survive a bot restart — and it+-- created its own table on startup with `CREATE TABLE IF NOT EXISTS`, outside+-- every migration chain in the repository.+--+-- Why that was not harmless+-- -------------------------+-- Three things follow from a table no migration knows about, and the third is+-- the one that matters:+--+-- * `060_rls_coverage.sql` gave a policy to every tenant-scoped table *in+-- the chain*. This one was not in it, so it had none — and it gates+-- response actions. An approval timer names an action id and a safe+-- default; reading or deleting another tenant's row is the difference+-- between a containment that auto-rejects and one that does not.+-- * it carried no `tenant_id` at all, so no policy could have been written+-- for it even if somebody had looked.+-- * `061_runtime_app_role.sql` took `CREATE` on schema public away from the+-- runtime role, and Postgres checks the schema ACL *before* the existence+-- test — so `CREATE TABLE IF NOT EXISTS` raises `permission denied for+-- schema public` even when the table is already there. The store's+-- `create()` would have failed at startup on a correctly-configured+-- deployment, and `main.py` catches that into a `logger.warning` and+-- falls back to the in-memory store. Durable approval timers would have+-- silently stopped being durable.+--+-- It was reachable only by an operator who set `DATABASE_URL` on the+-- slack-bot service, which the default compose does not — which is why it+-- survived this long, not why it was safe.+--+-- Shape+-- -----+-- Mirrors `PostgresTimerStore`'s columns, plus `tenant_id`. `TEXT` rather than+-- `uuid` to match `aisoc_action_records` (055), the table this one is keyed+-- against: both hold ids minted by `services/actions`, and the policy below+-- casts exactly the way 060 does for that table.+--+-- `fire_at` stays a DOUBLE PRECISION epoch rather than becoming a TIMESTAMPTZ.+-- The scheduler compares it against `time.time()` and re-arms with the+-- difference; converting here would move that arithmetic into two places.++CREATE TABLE IF NOT EXISTS approval_timers (+ action_id TEXT PRIMARY KEY,+ tenant_id TEXT NOT NULL DEFAULT '',+ fire_at DOUBLE PRECISION NOT NULL,+ safe_default TEXT NOT NULL DEFAULT 'rejected',+ case_id TEXT NOT NULL DEFAULT '',+ channel TEXT,+ approver_id TEXT NOT NULL DEFAULT 'scheduler',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- A deployment that already ran the store's own DDL has the table without the+-- column. Added separately so this migration converges on the same shape from+-- both starting points.+--+-- Rows already in such a table get `tenant_id = ''`, which matches no bound+-- tenant — so the bot will not recover those timers after the upgrade. That+-- is stated rather than guessed around: this migration cannot know which+-- tenant they belong to, and inventing one would re-arm an auto-reject+-- against the wrong estate. Backfill before restarting the bot:+-- UPDATE approval_timers SET tenant_id = '<your AISOC_DEFAULT_TENANT_ID>'+-- WHERE tenant_id = '';+ALTER TABLE approval_timers ADD COLUMN IF NOT EXISTS tenant_id TEXT NOT NULL DEFAULT '';++-- The only query beyond primary key is recovery's "every pending timer for+-- this tenant", which runs once per bot start.+CREATE INDEX IF NOT EXISTS ix_approval_timers_tenant+ ON approval_timers (tenant_id);++-- Same shape as every other policy in this schema, and for the same reason:+-- the `IS NULL` arm keeps a connection that binds no tenant working, because+-- a worker that silently sees zero rows is worse than the bypass the role+-- split closes. `scripts/check_rls_policy_shape.py` fails if it is dropped.+ALTER TABLE approval_timers ENABLE ROW LEVEL SECURITY;+-- FORCE, or the owner — the role that runs this chain — walks straight past.+ALTER TABLE approval_timers FORCE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS approval_timers_tenant ON approval_timers;+CREATE POLICY approval_timers_tenant ON approval_timers+ USING (tenant_id = current_tenant_id()::text OR current_tenant_id() IS NULL);++-- No GRANT here. 061 runs before this migration and as the same owner, so its+-- `ALTER DEFAULT PRIVILEGES … GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES+-- TO aisoc_app` covers a table created afterwards. That is the mechanism the+-- four alembic chains cannot rely on — nothing orders them against 061 — which+-- is why they carry an explicit grant and this does not.diff --git a/services/honeytokens/alembic/env.py b/services/honeytokens/alembic/env.pyindex f85e84b64..b8d41012e 100644--- a/services/honeytokens/alembic/env.py+++ b/services/honeytokens/alembic/env.py@@ -1,11 +1,37 @@-"""Alembic migration environment for Honeytokens service."""+"""Alembic migration environment for Honeytokens service.++Which credential applies the chain+----------------------------------+Alembic issues DDL, and ``services/api/migrations/061_runtime_app_role.sql``+deliberately left the runtime role without any: ``aisoc_app`` holds ``USAGE``+on schema public and not ``CREATE``, precisely so it cannot+``ALTER TABLE … NO FORCE ROW LEVEL SECURITY`` and switch off the policies+``0002_tenant_rls`` installs. A service that migrates and serves under one+credential has not split those roles at all, whatever the deployment surface+says.++So the migration credential is read first and the runtime one is only a+fallback. The fallback stays — a deployment that has not split the roles+behaves exactly as it did before — but it is announced, because both ways of+getting this wrong are otherwise silent:++* point this at the runtime role and ``alembic upgrade`` dies on the first+ ``CREATE TABLE`` with ``permission denied for schema public``;+* point the *service* at the owner and every policy in this chain stops+ filtering, with nothing in any log to say so.++``scripts/check_runtime_db_role.py`` is what keeps the deployment surfaces+honest about which variable carries which role.+"""from __future__ import annotationsimport asyncioimport os+import sysfrom logging.config import fileConfig+import sqlalchemy as safrom alembic import contextfrom app.models.honeytoken import Basefrom sqlalchemy.ext.asyncio import create_async_engine@@ -17,10 +43,106 @@ if config.config_file_name is not None:target_metadata = Base.metadata-DATABASE_URL = os.environ.get(- "HONEYTOKEN_DATABASE_URL",- "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc",-)+#: Owner credentials, most specific first. Any variable ending in+#: ``DATABASE_MIGRATION_URL`` is recognised as a migration DSN by the gate.+MIGRATION_URL_VARS = ("HONEYTOKEN_DATABASE_MIGRATION_URL", "DATABASE_MIGRATION_URL")++#: Runtime credentials. Same order the service's own settings resolve them in,+#: so the fallback below lands on exactly what the service connects as.+RUNTIME_URL_VARS = ("DATABASE_URL", "HONEYTOKEN_DATABASE_URL")++DEFAULT_URL = "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc"+++def _first_env(names: tuple[str, ...]) -> str:+ for name in names:+ value = os.environ.get(name, "").strip()+ if value:+ return value+ return ""+++def _resolve_dsn() -> str:+ migration = _first_env(MIGRATION_URL_VARS)+ if migration:+ return migration+ print(+ "alembic: none of "+ + ", ".join(MIGRATION_URL_VARS)+ + " is set, so this chain is being applied as the runtime credential. That works only "+ "while the two are the same role; under the DML-only runtime role the first CREATE TABLE "+ "fails with 'permission denied for schema public'.",+ file=sys.stderr,+ )+ return _first_env(RUNTIME_URL_VARS) or DEFAULT_URL+++DATABASE_URL = _resolve_dsn()+++#: Alembic's default version table is ``alembic_version``, and four services in+#: this repository run their own chain against **one** database — compose gives+#: ueba, honeytokens, purple-team and osquery-tls the same ``aisoc``. They also+#: number their revisions identically (``0001``, ``0002``, …), so the shared+#: table made the second chain to run believe it was already at head.+#:+#: Measured against ``postgres:16`` on the sequence ``apps/docs/docs/quickstart.md``+#: prints: after ``ueba`` reached ``0002``, ``honeytokens alembic upgrade head``+#: ran **zero** migrations and ``purple-team`` failed applying its RLS revision+#: to tables that had never been created. Two services' tenant policies did not+#: exist in the default deployment and nothing said so.+VERSION_TABLE = "alembic_version_honeytokens"++#: The table those chains shared. Read once, never written: see+#: :func:`_adopt_legacy_version`.+LEGACY_VERSION_TABLE = "alembic_version"+++def _adopt_legacy_version(connection) -> None: # type: ignore[no-untyped-def]+ """Carry a version recorded in the shared table into this chain's own.++ Without this, moving to a per-chain version table reads to alembic as a+ database that has never been migrated, and the first ``CREATE TABLE``+ fails because the table is already there.++ Three conditions, all required, so the adoption cannot claim a revision+ belonging to a sibling chain:++ * this chain has no version table yet;+ * at least one table **this chain maps** already exists, which is the only+ evidence that this chain — rather than a sibling — is what the shared+ row records;+ * the recorded id is a revision in this chain's own script directory.++ The shared table is left alone. A sibling that has not adopted yet still+ needs it, and once every chain has, it is inert rather than wrong.++ ``CREATE TABLE IF NOT EXISTS`` appears below and is reached only after the+ probe says the table is absent. Postgres checks the schema ACL *before* the+ existence test, so the statement raises ``permission denied for schema+ public`` on a role without ``CREATE`` even when the table is already there+ — the trap that took two stores in ``services/agents`` down to a+ ``logger.debug``. Here the whole function runs on the **migration**+ connection, but the probe-first order costs nothing and keeps the shape+ right if that ever stops being true.+ """+ inspector = sa.inspect(connection)+ if inspector.has_table(VERSION_TABLE) or not inspector.has_table(LEGACY_VERSION_TABLE):+ return+ if not any(inspector.has_table(name) for name in target_metadata.tables):+ return+ recorded = connection.execute(sa.text(f"SELECT version_num FROM {LEGACY_VERSION_TABLE}")).scalar() # noqa: S608+ if recorded is None or recorded not in {rev.revision for rev in context.script.walk_revisions()}:+ return+ connection.execute(+ sa.text(+ f"CREATE TABLE IF NOT EXISTS {VERSION_TABLE} (" # noqa: S608+ f"version_num VARCHAR(32) NOT NULL, "+ f"CONSTRAINT {VERSION_TABLE}_pkc PRIMARY KEY (version_num))"+ )+ )+ connection.execute(sa.text(f"INSERT INTO {VERSION_TABLE} (version_num) VALUES (:v)"), {"v": recorded}) # noqa: S608+ print(f"alembic: adopted {recorded!r} from {LEGACY_VERSION_TABLE} into {VERSION_TABLE}", file=sys.stderr)def run_migrations_offline() -> None:@@ -29,14 +151,22 @@ def run_migrations_offline() -> None:target_metadata=target_metadata,literal_binds=True,dialect_opts={"paramstyle": "named"},+ version_table=VERSION_TABLE,)with context.begin_transaction():context.run_migrations()def do_run_migrations(connection): # type: ignore[no-untyped-def]- context.configure(connection=connection, target_metadata=target_metadata)+ context.configure(connection=connection, target_metadata=target_metadata, version_table=VERSION_TABLE)with context.begin_transaction():+ # Inside ``begin_transaction()``, not before it. Alembic's+ # ``begin_transaction`` is a no-op when the connection is *already* in a+ # transaction, and in SQLAlchemy 2.0 any execute on a plain ``connect()``+ # starts one implicitly — so probing the schema first left the whole+ # upgrade inside a transaction nobody committed. Measured: the chain+ # printed every "Running upgrade" line and the database came back empty.+ _adopt_legacy_version(connection)context.run_migrations()diff --git a/services/honeytokens/alembic/versions/0003_runtime_role_grants.py b/services/honeytokens/alembic/versions/0003_runtime_role_grants.pynew file mode 100644index 000000000..1a0c9821c--- /dev/null+++ b/services/honeytokens/alembic/versions/0003_runtime_role_grants.py@@ -0,0 +1,116 @@+"""Give the runtime role DML on the honeytoken tables, and nothing more.++Revision ID: 0003+Revises: 0002+Create Date: 2026-09-24++Companion to ``services/api/migrations/061_runtime_app_role.sql``, which split+one superuser credential into an owner that applies DDL and ``aisoc_app``, the+DML-only role every service's ``DATABASE_URL`` points at. That migration+granted ``aisoc_app`` on ``ALL TABLES IN SCHEMA public`` as they stood when it+ran, and set ``ALTER DEFAULT PRIVILEGES`` for objects the *same* role creates+afterwards.++Neither clause reaches this chain reliably:++* nothing orders the two chains against each other, so this service's tables+ may not exist when 061's ``ALL TABLES`` grant runs;+* ``ALTER DEFAULT PRIVILEGES`` is recorded against the role that issued it, so+ a deployment applying the API chain and this one under different owners — or+ pointing this service at its own database, which ``HONEYTOKEN_DATABASE_URL`` exists+ to allow — gets no default privilege here at all.++The observable failure is a service that starts, connects, and answers every+query with ``permission denied for table honeytoken_triggers``. So the chain grants+what its own tables need rather than depending on another chain having run.++Grants, not ownership: an owner can ``ALTER TABLE … NO FORCE ROW LEVEL+SECURITY``, which is the bypass 061 exists to close. ``aisoc_app`` therefore+gets ``SELECT, INSERT, UPDATE, DELETE`` and not ``TRUNCATE``, ``REFERENCES`` or+``TRIGGER``.++The role name is a literal because it has to match 061, the compose stack and+every deployment surface, and a role interpolated into DDL from an environment+variable is an injection site with no upside. A deployment using a different+runtime role issues the equivalent grant itself; the guard below makes this+revision a notice rather than a failure there.+"""++from __future__ import annotations++from alembic import op # type: ignore[attr-defined] # re-exported at runtime, absent from the stub++revision = "0003"+down_revision = "0002"+branch_labels = None+depends_on = None++# Spelled out one table at a time rather than derived from the mapped+# metadata: a grant covering whatever happens to be mapped today is not+# reviewable, and this list is the reviewable part of the change.+TABLES = ("honeytokens", "honeytoken_triggers")++RUNTIME_ROLE = "aisoc_app"+++def _statement(action: str, tables: tuple[str, ...], role: str) -> str:+ """``GRANT``/``REVOKE`` over these tables and the sequences they own.++ Sequences are included because ``nextval`` needs ``USAGE`` and ``currval``+ needs ``SELECT``, and a grant on the table alone carries neither — the+ first ``BIGSERIAL`` anybody adds to this chain would fail at insert time+ with a message about a sequence nobody went looking for.+ """+ array = "ARRAY[" + ", ".join(f"'{t}'" for t in tables) + "]"+ if action == "GRANT":+ clause = (+ "format('GRANT %s ON %s TO " + role + "', "+ "CASE obj.kind WHEN 'S' THEN 'USAGE, SELECT' ELSE 'SELECT, INSERT, UPDATE, DELETE' END, obj.ref)"+ )+ notice = (+ f"RAISE NOTICE 'role {role} does not exist; skipping runtime grants. Apply "+ f"services/api/migrations/061_runtime_app_role.sql, or grant your own runtime role "+ f"DML on these tables by hand.';"+ )+ else:+ clause = "format('REVOKE ALL ON %s FROM " + role + "', obj.ref)"+ notice = ""+ return f"""+DO $$+DECLARE+ obj record;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '{role}') THEN+ {notice}+ RETURN;+ END IF;+ FOR obj IN+ SELECT c.oid::regclass::text AS ref, c.relkind AS kind+ FROM pg_class c+ WHERE pg_table_is_visible(c.oid)+ AND (+ (c.relkind IN ('r', 'p') AND c.relname = ANY ({array}))+ -- Only sequences. An index carries the same 'a' dependency on its+ -- table, and GRANT on one raises `"ix_…" is an index` — which the+ -- live round-trip caught and a review of the statement did not.+ OR (c.relkind = 'S' AND c.oid IN (+ SELECT d.objid+ FROM pg_depend d+ JOIN pg_class t ON t.oid = d.refobjid+ WHERE d.deptype = 'a' AND t.relname = ANY ({array})+ ))+ )+ LOOP+ EXECUTE {clause};+ END LOOP;+END+$$;+"""+++def upgrade() -> None:+ op.execute(_statement("GRANT", TABLES, RUNTIME_ROLE))+++def downgrade() -> None:+ op.execute(_statement("REVOKE", TABLES, RUNTIME_ROLE))diff --git a/services/honeytokens/app/core/config.py b/services/honeytokens/app/core/config.pyindex e0df3f3db..c7e525047 100644--- a/services/honeytokens/app/core/config.py+++ b/services/honeytokens/app/core/config.py@@ -1,11 +1,31 @@+from pydantic import AliasChoices, Fieldfrom pydantic_settings import BaseSettings, SettingsConfigDictclass Settings(BaseSettings):- model_config = SettingsConfigDict(env_prefix="HONEYTOKEN_", env_file=".env", extra="ignore")-- # Database- database_url: str = "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc"+ model_config = SettingsConfigDict(+ env_prefix="HONEYTOKEN_",+ env_file=".env",+ populate_by_name=True,+ extra="ignore",+ )++ # Database.+ #+ # ``env_prefix`` means every other field here is read as+ # ``HONEYTOKEN_<FIELD>``, and this one used to be as well — while+ # ``docker-compose.yml`` set plain ``DATABASE_URL`` on this service, as it+ # does for every other. The variable was therefore inert: the service fell+ # back to the default below, which names the *owner* role, so pointing the+ # deployment at the DML-only runtime role changed nothing here.+ #+ # Both spellings now resolve, unprefixed first, the same convention+ # ``services/ueba`` and ``services/fusion`` already use. The alias replaces+ # the prefix for this field only; the rest of the settings are untouched.+ database_url: str = Field(+ default="postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc",+ validation_alias=AliasChoices("DATABASE_URL", "HONEYTOKEN_DATABASE_URL"),+ )# Webhook alerting. ``alert_webhook_secret`` previously defaulted to the# literal string ``"changeme"`` — anyone running this service with thediff --git a/services/honeytokens/tests/test_settings_env.py b/services/honeytokens/tests/test_settings_env.pynew file mode 100644index 000000000..651cbd570--- /dev/null+++ b/services/honeytokens/tests/test_settings_env.py@@ -0,0 +1,62 @@+"""``DATABASE_URL`` reaches this service, not just its compose block.++Every other field here is read as ``HONEYTOKEN_<FIELD>`` because the settings+declare ``env_prefix``. ``database_url`` used to be too — while+``docker-compose.yml`` set plain ``DATABASE_URL`` on the service, as it does on+every other. The variable was inert, so the switch to the DML-only runtime+role never reached this service at all and the default, which names the+*owner*, was what it connected as.++Both spellings are asserted, and so is the precedence between them, because+"accepts the new name" and "still accepts the old one" are different promises+and a deployment relies on both.+"""++from __future__ import annotations++import os++import pytest++[email protected](autouse=True)+def _clean_env(monkeypatch):+ for key in list(os.environ):+ if key.startswith("HONEYTOKEN_") or key == "DATABASE_URL":+ monkeypatch.delenv(key, raising=False)+++def test_unprefixed_env_var(monkeypatch):+ monkeypatch.setenv("DATABASE_URL", "postgresql+asyncpg://aisoc_app:pw@db:5432/aisoc")+ from app.core.config import Settings++ assert Settings().database_url == "postgresql+asyncpg://aisoc_app:pw@db:5432/aisoc"+++def test_prefixed_env_var_still_works(monkeypatch):+ monkeypatch.setenv("HONEYTOKEN_DATABASE_URL", "postgresql+asyncpg://legacy:pw@db:5432/legacy")+ from app.core.config import Settings++ assert Settings().database_url == "postgresql+asyncpg://legacy:pw@db:5432/legacy"+++def test_unprefixed_takes_precedence(monkeypatch):+ monkeypatch.setenv("DATABASE_URL", "postgresql+asyncpg://winner:pw@db:5432/win")+ monkeypatch.setenv("HONEYTOKEN_DATABASE_URL", "postgresql+asyncpg://loser:pw@db:5432/lose")+ from app.core.config import Settings++ assert Settings().database_url == "postgresql+asyncpg://winner:pw@db:5432/win"+++def test_falls_back_to_default():+ from app.core.config import Settings++ assert "localhost" in Settings().database_url+++def test_other_fields_keep_their_prefix(monkeypatch):+ """The alias covers one field. Widening it silently would be its own bug."""+ monkeypatch.setenv("HONEYTOKEN_TOKEN_TTL_DAYS", "7")+ from app.core.config import Settings++ assert Settings().token_ttl_days == 7diff --git a/services/osquery-tls/app/core/config.py b/services/osquery-tls/app/core/config.pyindex 5303f5570..26b1431ee 100644--- a/services/osquery-tls/app/core/config.py+++ b/services/osquery-tls/app/core/config.py@@ -6,6 +6,7 @@ All settings are read from environment variables prefixed withfrom __future__ import annotations+from pydantic import AliasChoices, Fieldfrom pydantic_settings import BaseSettings, SettingsConfigDict@@ -13,12 +14,27 @@ class Settings(BaseSettings):model_config = SettingsConfigDict(env_prefix="AISOC_OSQUERY_TLS_",env_file=".env",+ populate_by_name=True,extra="ignore",)# --- Database -------------------------------------------------------# Reuses the main API Postgres; all tables live in the `osquery_tls` schema.- database_url: str = "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc"+ #+ # ``env_prefix`` means every other field here is read as+ # ``AISOC_OSQUERY_TLS_<FIELD>``, and this one used to be as well — while+ # ``docker-compose.yml`` set plain ``DATABASE_URL`` on this service, as it+ # does for every other. The variable was therefore inert: the service fell+ # back to the default below, which names the *owner* role, so pointing the+ # deployment at the DML-only runtime role changed nothing here.+ #+ # Both spellings now resolve, unprefixed first, the same convention+ # ``services/ueba`` and ``services/fusion`` already use. The alias replaces+ # the prefix for this field only; the rest of the settings are untouched.+ database_url: str = Field(+ default="postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc",+ validation_alias=AliasChoices("DATABASE_URL", "AISOC_OSQUERY_TLS_DATABASE_URL"),+ )# --- Ingest service -------------------------------------------------# Where normalised osquery rows are forwarded to.diff --git a/services/osquery-tls/app/db/env.py b/services/osquery-tls/app/db/env.pyindex cef7f7c81..32b2a400c 100644--- a/services/osquery-tls/app/db/env.py+++ b/services/osquery-tls/app/db/env.py@@ -1,13 +1,38 @@"""Alembic migration environment for the osquery-tls service.Supports async migrations via asyncio run_sync().++Which credential applies the chain+----------------------------------+Alembic issues DDL, and ``services/api/migrations/061_runtime_app_role.sql``+deliberately left the runtime role without any: ``aisoc_app`` holds ``USAGE``+on schema public and not ``CREATE``, precisely so it cannot+``ALTER TABLE … NO FORCE ROW LEVEL SECURITY`` and switch off the policies+``004_tenant_rls`` installs. A service that migrates and serves under one+credential has not split those roles at all, whatever the deployment surface+says.++So the migration credential is read first and ``settings.database_url`` — what+the service itself connects as — is only a fallback. The fallback stays, but+it is announced, because both ways of getting this wrong are otherwise silent:++* point this at the runtime role and ``alembic upgrade`` dies on the first+ ``CREATE TABLE`` with ``permission denied for schema public``;+* point the *service* at the owner and every policy in this chain stops+ filtering, with nothing in any log to say so.++``scripts/check_runtime_db_role.py`` is what keeps the deployment surfaces+honest about which variable carries which role."""from __future__ import annotationsimport asyncio+import os+import sysfrom logging.config import fileConfig+import sqlalchemy as safrom alembic import contextfrom sqlalchemy import poolfrom sqlalchemy.ext.asyncio import create_async_engine@@ -19,8 +44,31 @@ from app.db.base import Base# Explicitly reference the import so static analysis tools don't flag it as unused._ = _models+#: Owner credentials, most specific first. Any variable ending in+#: ``DATABASE_MIGRATION_URL`` is recognised as a migration DSN by the gate.+MIGRATION_URL_VARS = ("AISOC_OSQUERY_TLS_DATABASE_MIGRATION_URL", "DATABASE_MIGRATION_URL")+++def _resolve_dsn() -> str:+ for name in MIGRATION_URL_VARS:+ value = os.environ.get(name, "").strip()+ if value:+ return value+ print(+ "alembic: none of "+ + ", ".join(MIGRATION_URL_VARS)+ + " is set, so this chain is being applied as the runtime credential. That works only "+ "while the two are the same role; under the DML-only runtime role the first CREATE TABLE "+ "fails with 'permission denied for schema public'.",+ file=sys.stderr,+ )+ return settings.database_url+++DATABASE_URL = _resolve_dsn()+config = context.config-config.set_main_option("sqlalchemy.url", settings.database_url)+config.set_main_option("sqlalchemy.url", DATABASE_URL)if config.config_file_name is not None:fileConfig(config.config_file_name)@@ -28,6 +76,71 @@ if config.config_file_name is not None:target_metadata = Base.metadata+#: Alembic's default version table is ``alembic_version``, and four services in+#: this repository run their own chain against **one** database — compose gives+#: ueba, honeytokens, purple-team and osquery-tls the same ``aisoc``. They also+#: number their revisions identically (``0001``, ``0002``, …), so the shared+#: table made the second chain to run believe it was already at head.+#:+#: Measured against ``postgres:16`` on the sequence ``apps/docs/docs/quickstart.md``+#: prints: after ``ueba`` reached ``0002``, ``honeytokens alembic upgrade head``+#: ran **zero** migrations and ``purple-team`` failed applying its RLS revision+#: to tables that had never been created. Two services' tenant policies did not+#: exist in the default deployment and nothing said so.+VERSION_TABLE = "alembic_version_osquery_tls"++#: The table those chains shared. Read once, never written: see+#: :func:`_adopt_legacy_version`.+LEGACY_VERSION_TABLE = "alembic_version"+++def _adopt_legacy_version(connection) -> None: # type: ignore[no-untyped-def]+ """Carry a version recorded in the shared table into this chain's own.++ Without this, moving to a per-chain version table reads to alembic as a+ database that has never been migrated, and the first ``CREATE TABLE``+ fails because the table is already there.++ Three conditions, all required, so the adoption cannot claim a revision+ belonging to a sibling chain:++ * this chain has no version table yet;+ * at least one table **this chain maps** already exists, which is the only+ evidence that this chain — rather than a sibling — is what the shared+ row records;+ * the recorded id is a revision in this chain's own script directory.++ The shared table is left alone. A sibling that has not adopted yet still+ needs it, and once every chain has, it is inert rather than wrong.++ ``CREATE TABLE IF NOT EXISTS`` appears below and is reached only after the+ probe says the table is absent. Postgres checks the schema ACL *before* the+ existence test, so the statement raises ``permission denied for schema+ public`` on a role without ``CREATE`` even when the table is already there+ — the trap that took two stores in ``services/agents`` down to a+ ``logger.debug``. Here the whole function runs on the **migration**+ connection, but the probe-first order costs nothing and keeps the shape+ right if that ever stops being true.+ """+ inspector = sa.inspect(connection)+ if inspector.has_table(VERSION_TABLE) or not inspector.has_table(LEGACY_VERSION_TABLE):+ return+ if not any(inspector.has_table(name) for name in target_metadata.tables):+ return+ recorded = connection.execute(sa.text(f"SELECT version_num FROM {LEGACY_VERSION_TABLE}")).scalar() # noqa: S608+ if recorded is None or recorded not in {rev.revision for rev in context.script.walk_revisions()}:+ return+ connection.execute(+ sa.text(+ f"CREATE TABLE IF NOT EXISTS {VERSION_TABLE} (" # noqa: S608+ f"version_num VARCHAR(32) NOT NULL, "+ f"CONSTRAINT {VERSION_TABLE}_pkc PRIMARY KEY (version_num))"+ )+ )+ connection.execute(sa.text(f"INSERT INTO {VERSION_TABLE} (version_num) VALUES (:v)"), {"v": recorded}) # noqa: S608+ print(f"alembic: adopted {recorded!r} from {LEGACY_VERSION_TABLE} into {VERSION_TABLE}", file=sys.stderr)++def run_migrations_offline() -> None:url = config.get_main_option("sqlalchemy.url")context.configure(@@ -35,20 +148,32 @@ def run_migrations_offline() -> None:target_metadata=target_metadata,literal_binds=True,dialect_opts={"paramstyle": "named"},+ version_table=VERSION_TABLE,)with context.begin_transaction():context.run_migrations()def do_run_migrations(connection):- context.configure(connection=connection, target_metadata=target_metadata)+ context.configure(connection=connection, target_metadata=target_metadata, version_table=VERSION_TABLE)with context.begin_transaction():+ # Inside ``begin_transaction()``, not before it. Alembic's+ # ``begin_transaction`` is a no-op when the connection is *already* in a+ # transaction, and in SQLAlchemy 2.0 any execute on a plain ``connect()``+ # starts one implicitly — so probing the schema first left the whole+ # upgrade inside a transaction nobody committed. Measured: the chain+ # printed every "Running upgrade" line and the database came back empty.+ _adopt_legacy_version(connection)context.run_migrations()async def run_async_migrations() -> None:- engine = create_async_engine(settings.database_url, poolclass=pool.NullPool)- async with engine.connect() as connection:+ engine = create_async_engine(DATABASE_URL, poolclass=pool.NullPool)+ # ``begin()`` rather than ``connect()``: the three sibling chains all use it,+ # and it is what commits. On a bare ``connect()`` the outer transaction is+ # rolled back at close unless something inside commits, which makes a+ # successful-looking upgrade a no-op.+ async with engine.begin() as connection:await connection.run_sync(do_run_migrations)await engine.dispose()diff --git a/services/osquery-tls/app/db/versions/005_runtime_role_grants.py b/services/osquery-tls/app/db/versions/005_runtime_role_grants.pynew file mode 100644index 000000000..3599f681f--- /dev/null+++ b/services/osquery-tls/app/db/versions/005_runtime_role_grants.py@@ -0,0 +1,121 @@+"""Give the runtime role DML on the osquery-TLS tables, and nothing more.++Revision ID: 005+Revises: 004+Create Date: 2026-09-24++Companion to ``services/api/migrations/061_runtime_app_role.sql``, which split+one superuser credential into an owner that applies DDL and ``aisoc_app``, the+DML-only role every service's ``DATABASE_URL`` points at. That migration+granted ``aisoc_app`` on ``ALL TABLES IN SCHEMA public`` as they stood when it+ran, and set ``ALTER DEFAULT PRIVILEGES`` for objects the *same* role creates+afterwards.++Neither clause reaches this chain reliably:++* nothing orders the two chains against each other, so this service's tables+ may not exist when 061's ``ALL TABLES`` grant runs;+* ``ALTER DEFAULT PRIVILEGES`` is recorded against the role that issued it, so+ a deployment applying the API chain and this one under different owners — or+ pointing this service at its own database, which ``AISOC_OSQUERY_TLS_DATABASE_URL`` exists+ to allow — gets no default privilege here at all.++The observable failure is a service that starts, connects, and answers every+query with ``permission denied for table osquery_node``. So the chain grants+what its own tables need rather than depending on another chain having run.++Grants, not ownership: an owner can ``ALTER TABLE … NO FORCE ROW LEVEL+SECURITY``, which is the bypass 061 exists to close. ``aisoc_app`` therefore+gets ``SELECT, INSERT, UPDATE, DELETE`` and not ``TRUNCATE``, ``REFERENCES`` or+``TRIGGER``.++The role name is a literal because it has to match 061, the compose stack and+every deployment surface, and a role interpolated into DDL from an environment+variable is an injection site with no upside. A deployment using a different+runtime role issues the equivalent grant itself; the guard below makes this+revision a notice rather than a failure there.+"""++from __future__ import annotations++from alembic import op # type: ignore[attr-defined] # re-exported at runtime, absent from the stub++revision = "005"+down_revision = "004"+branch_labels = None+depends_on = None++# Spelled out one table at a time rather than derived from the mapped+# metadata: a grant covering whatever happens to be mapped today is not+# reviewable, and this list is the reviewable part of the change.+TABLES = (+ "osquery_node",+ "osquery_pack_assignment",+ "osquery_distributed_query",+ "fim_event",+)++RUNTIME_ROLE = "aisoc_app"+++def _statement(action: str, tables: tuple[str, ...], role: str) -> str:+ """``GRANT``/``REVOKE`` over these tables and the sequences they own.++ Sequences are included because ``nextval`` needs ``USAGE`` and ``currval``+ needs ``SELECT``, and a grant on the table alone carries neither — the+ first ``BIGSERIAL`` anybody adds to this chain would fail at insert time+ with a message about a sequence nobody went looking for.+ """+ array = "ARRAY[" + ", ".join(f"'{t}'" for t in tables) + "]"+ if action == "GRANT":+ clause = (+ "format('GRANT %s ON %s TO " + role + "', "+ "CASE obj.kind WHEN 'S' THEN 'USAGE, SELECT' ELSE 'SELECT, INSERT, UPDATE, DELETE' END, obj.ref)"+ )+ notice = (+ f"RAISE NOTICE 'role {role} does not exist; skipping runtime grants. Apply "+ f"services/api/migrations/061_runtime_app_role.sql, or grant your own runtime role "+ f"DML on these tables by hand.';"+ )+ else:+ clause = "format('REVOKE ALL ON %s FROM " + role + "', obj.ref)"+ notice = ""+ return f"""+DO $$+DECLARE+ obj record;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '{role}') THEN+ {notice}+ RETURN;+ END IF;+ FOR obj IN+ SELECT c.oid::regclass::text AS ref, c.relkind AS kind+ FROM pg_class c+ WHERE pg_table_is_visible(c.oid)+ AND (+ (c.relkind IN ('r', 'p') AND c.relname = ANY ({array}))+ -- Only sequences. An index carries the same 'a' dependency on its+ -- table, and GRANT on one raises `"ix_…" is an index` — which the+ -- live round-trip caught and a review of the statement did not.+ OR (c.relkind = 'S' AND c.oid IN (+ SELECT d.objid+ FROM pg_depend d+ JOIN pg_class t ON t.oid = d.refobjid+ WHERE d.deptype = 'a' AND t.relname = ANY ({array})+ ))+ )+ LOOP+ EXECUTE {clause};+ END LOOP;+END+$$;+"""+++def upgrade() -> None:+ op.execute(_statement("GRANT", TABLES, RUNTIME_ROLE))+++def downgrade() -> None:+ op.execute(_statement("REVOKE", TABLES, RUNTIME_ROLE))diff --git a/services/osquery-tls/tests/test_settings_env.py b/services/osquery-tls/tests/test_settings_env.pynew file mode 100644index 000000000..bc5db827b--- /dev/null+++ b/services/osquery-tls/tests/test_settings_env.py@@ -0,0 +1,62 @@+"""``DATABASE_URL`` reaches this service, not just its compose block.++Every other field here is read as ``AISOC_OSQUERY_TLS_<FIELD>`` because the settings+declare ``env_prefix``. ``database_url`` used to be too — while+``docker-compose.yml`` set plain ``DATABASE_URL`` on the service, as it does on+every other. The variable was inert, so the switch to the DML-only runtime+role never reached this service at all and the default, which names the+*owner*, was what it connected as.++Both spellings are asserted, and so is the precedence between them, because+"accepts the new name" and "still accepts the old one" are different promises+and a deployment relies on both.+"""++from __future__ import annotations++import os++import pytest++[email protected](autouse=True)+def _clean_env(monkeypatch):+ for key in list(os.environ):+ if key.startswith("AISOC_OSQUERY_TLS_") or key == "DATABASE_URL":+ monkeypatch.delenv(key, raising=False)+++def test_unprefixed_env_var(monkeypatch):+ monkeypatch.setenv("DATABASE_URL", "postgresql+asyncpg://aisoc_app:pw@db:5432/aisoc")+ from app.core.config import Settings++ assert Settings().database_url == "postgresql+asyncpg://aisoc_app:pw@db:5432/aisoc"+++def test_prefixed_env_var_still_works(monkeypatch):+ monkeypatch.setenv("AISOC_OSQUERY_TLS_DATABASE_URL", "postgresql+asyncpg://legacy:pw@db:5432/legacy")+ from app.core.config import Settings++ assert Settings().database_url == "postgresql+asyncpg://legacy:pw@db:5432/legacy"+++def test_unprefixed_takes_precedence(monkeypatch):+ monkeypatch.setenv("DATABASE_URL", "postgresql+asyncpg://winner:pw@db:5432/win")+ monkeypatch.setenv("AISOC_OSQUERY_TLS_DATABASE_URL", "postgresql+asyncpg://loser:pw@db:5432/lose")+ from app.core.config import Settings++ assert Settings().database_url == "postgresql+asyncpg://winner:pw@db:5432/win"+++def test_falls_back_to_default():+ from app.core.config import Settings++ assert "localhost" in Settings().database_url+++def test_other_fields_keep_their_prefix(monkeypatch):+ """The alias covers one field. Widening it silently would be its own bug."""+ monkeypatch.setenv("AISOC_OSQUERY_TLS_INGEST_URL", "http://ingest.test:8080")+ from app.core.config import Settings++ assert Settings().ingest_url == "http://ingest.test:8080"diff --git a/services/purple-team/alembic/env.py b/services/purple-team/alembic/env.pyindex 74a894b1b..be505bc8e 100644--- a/services/purple-team/alembic/env.py+++ b/services/purple-team/alembic/env.py@@ -1,11 +1,37 @@-"""Alembic migration environment for Purple Team service."""+"""Alembic migration environment for Purple Team service.++Which credential applies the chain+----------------------------------+Alembic issues DDL, and ``services/api/migrations/061_runtime_app_role.sql``+deliberately left the runtime role without any: ``aisoc_app`` holds ``USAGE``+on schema public and not ``CREATE``, precisely so it cannot+``ALTER TABLE … NO FORCE ROW LEVEL SECURITY`` and switch off the policies+``0003_tenant_rls`` installs. A service that migrates and serves under one+credential has not split those roles at all, whatever the deployment surface+says.++So the migration credential is read first and the runtime one is only a+fallback. The fallback stays — a deployment that has not split the roles+behaves exactly as it did before — but it is announced, because both ways of+getting this wrong are otherwise silent:++* point this at the runtime role and ``alembic upgrade`` dies on the first+ ``CREATE TABLE`` with ``permission denied for schema public``;+* point the *service* at the owner and every policy in this chain stops+ filtering, with nothing in any log to say so.++``scripts/check_runtime_db_role.py`` is what keeps the deployment surfaces+honest about which variable carries which role.+"""from __future__ import annotationsimport asyncioimport os+import sysfrom logging.config import fileConfig+import sqlalchemy as safrom alembic import contextfrom app.models.purple_team import Basefrom sqlalchemy.ext.asyncio import create_async_engine@@ -17,10 +43,106 @@ if config.config_file_name is not None:target_metadata = Base.metadata-DATABASE_URL = os.environ.get(- "PURPLE_TEAM_DATABASE_URL",- "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc",-)+#: Owner credentials, most specific first. Any variable ending in+#: ``DATABASE_MIGRATION_URL`` is recognised as a migration DSN by the gate.+MIGRATION_URL_VARS = ("PURPLE_TEAM_DATABASE_MIGRATION_URL", "DATABASE_MIGRATION_URL")++#: Runtime credentials. Same order the service's own settings resolve them in,+#: so the fallback below lands on exactly what the service connects as.+RUNTIME_URL_VARS = ("DATABASE_URL", "PURPLE_TEAM_DATABASE_URL")++DEFAULT_URL = "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc"+++def _first_env(names: tuple[str, ...]) -> str:+ for name in names:+ value = os.environ.get(name, "").strip()+ if value:+ return value+ return ""+++def _resolve_dsn() -> str:+ migration = _first_env(MIGRATION_URL_VARS)+ if migration:+ return migration+ print(+ "alembic: none of "+ + ", ".join(MIGRATION_URL_VARS)+ + " is set, so this chain is being applied as the runtime credential. That works only "+ "while the two are the same role; under the DML-only runtime role the first CREATE TABLE "+ "fails with 'permission denied for schema public'.",+ file=sys.stderr,+ )+ return _first_env(RUNTIME_URL_VARS) or DEFAULT_URL+++DATABASE_URL = _resolve_dsn()+++#: Alembic's default version table is ``alembic_version``, and four services in+#: this repository run their own chain against **one** database — compose gives+#: ueba, honeytokens, purple-team and osquery-tls the same ``aisoc``. They also+#: number their revisions identically (``0001``, ``0002``, …), so the shared+#: table made the second chain to run believe it was already at head.+#:+#: Measured against ``postgres:16`` on the sequence ``apps/docs/docs/quickstart.md``+#: prints: after ``ueba`` reached ``0002``, ``honeytokens alembic upgrade head``+#: ran **zero** migrations and ``purple-team`` failed applying its RLS revision+#: to tables that had never been created. Two services' tenant policies did not+#: exist in the default deployment and nothing said so.+VERSION_TABLE = "alembic_version_purple_team"++#: The table those chains shared. Read once, never written: see+#: :func:`_adopt_legacy_version`.+LEGACY_VERSION_TABLE = "alembic_version"+++def _adopt_legacy_version(connection) -> None: # type: ignore[no-untyped-def]+ """Carry a version recorded in the shared table into this chain's own.++ Without this, moving to a per-chain version table reads to alembic as a+ database that has never been migrated, and the first ``CREATE TABLE``+ fails because the table is already there.++ Three conditions, all required, so the adoption cannot claim a revision+ belonging to a sibling chain:++ * this chain has no version table yet;+ * at least one table **this chain maps** already exists, which is the only+ evidence that this chain — rather than a sibling — is what the shared+ row records;+ * the recorded id is a revision in this chain's own script directory.++ The shared table is left alone. A sibling that has not adopted yet still+ needs it, and once every chain has, it is inert rather than wrong.++ ``CREATE TABLE IF NOT EXISTS`` appears below and is reached only after the+ probe says the table is absent. Postgres checks the schema ACL *before* the+ existence test, so the statement raises ``permission denied for schema+ public`` on a role without ``CREATE`` even when the table is already there+ — the trap that took two stores in ``services/agents`` down to a+ ``logger.debug``. Here the whole function runs on the **migration**+ connection, but the probe-first order costs nothing and keeps the shape+ right if that ever stops being true.+ """+ inspector = sa.inspect(connection)+ if inspector.has_table(VERSION_TABLE) or not inspector.has_table(LEGACY_VERSION_TABLE):+ return+ if not any(inspector.has_table(name) for name in target_metadata.tables):+ return+ recorded = connection.execute(sa.text(f"SELECT version_num FROM {LEGACY_VERSION_TABLE}")).scalar() # noqa: S608+ if recorded is None or recorded not in {rev.revision for rev in context.script.walk_revisions()}:+ return+ connection.execute(+ sa.text(+ f"CREATE TABLE IF NOT EXISTS {VERSION_TABLE} (" # noqa: S608+ f"version_num VARCHAR(32) NOT NULL, "+ f"CONSTRAINT {VERSION_TABLE}_pkc PRIMARY KEY (version_num))"+ )+ )+ connection.execute(sa.text(f"INSERT INTO {VERSION_TABLE} (version_num) VALUES (:v)"), {"v": recorded}) # noqa: S608+ print(f"alembic: adopted {recorded!r} from {LEGACY_VERSION_TABLE} into {VERSION_TABLE}", file=sys.stderr)def run_migrations_offline() -> None:@@ -29,14 +151,22 @@ def run_migrations_offline() -> None:target_metadata=target_metadata,literal_binds=True,dialect_opts={"paramstyle": "named"},+ version_table=VERSION_TABLE,)with context.begin_transaction():context.run_migrations()def do_run_migrations(connection): # type: ignore[no-untyped-def]- context.configure(connection=connection, target_metadata=target_metadata)+ context.configure(connection=connection, target_metadata=target_metadata, version_table=VERSION_TABLE)with context.begin_transaction():+ # Inside ``begin_transaction()``, not before it. Alembic's+ # ``begin_transaction`` is a no-op when the connection is *already* in a+ # transaction, and in SQLAlchemy 2.0 any execute on a plain ``connect()``+ # starts one implicitly — so probing the schema first left the whole+ # upgrade inside a transaction nobody committed. Measured: the chain+ # printed every "Running upgrade" line and the database came back empty.+ _adopt_legacy_version(connection)context.run_migrations()diff --git a/services/purple-team/alembic/versions/0004_runtime_role_grants.py b/services/purple-team/alembic/versions/0004_runtime_role_grants.pynew file mode 100644index 000000000..1fc70d0c2--- /dev/null+++ b/services/purple-team/alembic/versions/0004_runtime_role_grants.py@@ -0,0 +1,121 @@+"""Give the runtime role DML on the purple-team tables, and nothing more.++Revision ID: 0004+Revises: 0003+Create Date: 2026-09-24++Companion to ``services/api/migrations/061_runtime_app_role.sql``, which split+one superuser credential into an owner that applies DDL and ``aisoc_app``, the+DML-only role every service's ``DATABASE_URL`` points at. That migration+granted ``aisoc_app`` on ``ALL TABLES IN SCHEMA public`` as they stood when it+ran, and set ``ALTER DEFAULT PRIVILEGES`` for objects the *same* role creates+afterwards.++Neither clause reaches this chain reliably:++* nothing orders the two chains against each other, so this service's tables+ may not exist when 061's ``ALL TABLES`` grant runs;+* ``ALTER DEFAULT PRIVILEGES`` is recorded against the role that issued it, so+ a deployment applying the API chain and this one under different owners — or+ pointing this service at its own database, which ``PURPLE_TEAM_DATABASE_URL`` exists+ to allow — gets no default privilege here at all.++The observable failure is a service that starts, connects, and answers every+query with ``permission denied for table purple_team_executions``. So the chain grants+what its own tables need rather than depending on another chain having run.++Grants, not ownership: an owner can ``ALTER TABLE … NO FORCE ROW LEVEL+SECURITY``, which is the bypass 061 exists to close. ``aisoc_app`` therefore+gets ``SELECT, INSERT, UPDATE, DELETE`` and not ``TRUNCATE``, ``REFERENCES`` or+``TRIGGER``.++The role name is a literal because it has to match 061, the compose stack and+every deployment surface, and a role interpolated into DDL from an environment+variable is an injection site with no upside. A deployment using a different+runtime role issues the equivalent grant itself; the guard below makes this+revision a notice rather than a failure there.+"""++from __future__ import annotations++from alembic import op # type: ignore[attr-defined] # re-exported at runtime, absent from the stub++revision = "0004"+down_revision = "0003"+branch_labels = None+depends_on = None++# Spelled out one table at a time rather than derived from the mapped+# metadata: a grant covering whatever happens to be mapped today is not+# reviewable, and this list is the reviewable part of the change.+TABLES = (+ "purple_team_atomic_tests",+ "purple_team_executions",+ "purple_team_tabletop_sessions",+ "purple_team_detection_drift_snapshots",+)++RUNTIME_ROLE = "aisoc_app"+++def _statement(action: str, tables: tuple[str, ...], role: str) -> str:+ """``GRANT``/``REVOKE`` over these tables and the sequences they own.++ Sequences are included because ``nextval`` needs ``USAGE`` and ``currval``+ needs ``SELECT``, and a grant on the table alone carries neither — the+ first ``BIGSERIAL`` anybody adds to this chain would fail at insert time+ with a message about a sequence nobody went looking for.+ """+ array = "ARRAY[" + ", ".join(f"'{t}'" for t in tables) + "]"+ if action == "GRANT":+ clause = (+ "format('GRANT %s ON %s TO " + role + "', "+ "CASE obj.kind WHEN 'S' THEN 'USAGE, SELECT' ELSE 'SELECT, INSERT, UPDATE, DELETE' END, obj.ref)"+ )+ notice = (+ f"RAISE NOTICE 'role {role} does not exist; skipping runtime grants. Apply "+ f"services/api/migrations/061_runtime_app_role.sql, or grant your own runtime role "+ f"DML on these tables by hand.';"+ )+ else:+ clause = "format('REVOKE ALL ON %s FROM " + role + "', obj.ref)"+ notice = ""+ return f"""+DO $$+DECLARE+ obj record;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '{role}') THEN+ {notice}+ RETURN;+ END IF;+ FOR obj IN+ SELECT c.oid::regclass::text AS ref, c.relkind AS kind+ FROM pg_class c+ WHERE pg_table_is_visible(c.oid)+ AND (+ (c.relkind IN ('r', 'p') AND c.relname = ANY ({array}))+ -- Only sequences. An index carries the same 'a' dependency on its+ -- table, and GRANT on one raises `"ix_…" is an index` — which the+ -- live round-trip caught and a review of the statement did not.+ OR (c.relkind = 'S' AND c.oid IN (+ SELECT d.objid+ FROM pg_depend d+ JOIN pg_class t ON t.oid = d.refobjid+ WHERE d.deptype = 'a' AND t.relname = ANY ({array})+ ))+ )+ LOOP+ EXECUTE {clause};+ END LOOP;+END+$$;+"""+++def upgrade() -> None:+ op.execute(_statement("GRANT", TABLES, RUNTIME_ROLE))+++def downgrade() -> None:+ op.execute(_statement("REVOKE", TABLES, RUNTIME_ROLE))diff --git a/services/purple-team/app/core/config.py b/services/purple-team/app/core/config.pyindex 5cef99099..31a746e94 100644--- a/services/purple-team/app/core/config.py+++ b/services/purple-team/app/core/config.py@@ -2,14 +2,34 @@from __future__ import annotations+from pydantic import AliasChoices, Fieldfrom pydantic_settings import BaseSettings, SettingsConfigDictclass Settings(BaseSettings):- model_config = SettingsConfigDict(env_prefix="PURPLE_TEAM_", env_file=".env", extra="ignore")-- # Database- database_url: str = "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc"+ model_config = SettingsConfigDict(+ env_prefix="PURPLE_TEAM_",+ env_file=".env",+ populate_by_name=True,+ extra="ignore",+ )++ # Database.+ #+ # ``env_prefix`` means every other field here is read as+ # ``PURPLE_TEAM_<FIELD>``, and this one used to be as well — while+ # ``docker-compose.yml`` set plain ``DATABASE_URL`` on this service, as it+ # does for every other. The variable was therefore inert: the service fell+ # back to the default below, which names the *owner* role, so pointing the+ # deployment at the DML-only runtime role changed nothing here.+ #+ # Both spellings now resolve, unprefixed first, the same convention+ # ``services/ueba`` and ``services/fusion`` already use. The alias replaces+ # the prefix for this field only; the rest of the settings are untouched.+ database_url: str = Field(+ default="postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc",+ validation_alias=AliasChoices("DATABASE_URL", "PURPLE_TEAM_DATABASE_URL"),+ )# Caldera integrationcaldera_url: str = "http://localhost:8888"diff --git a/services/purple-team/tests/test_settings_env.py b/services/purple-team/tests/test_settings_env.pynew file mode 100644index 000000000..4ff8323a7--- /dev/null+++ b/services/purple-team/tests/test_settings_env.py@@ -0,0 +1,62 @@+"""``DATABASE_URL`` reaches this service, not just its compose block.++Every other field here is read as ``PURPLE_TEAM_<FIELD>`` because the settings+declare ``env_prefix``. ``database_url`` used to be too — while+``docker-compose.yml`` set plain ``DATABASE_URL`` on the service, as it does on+every other. The variable was inert, so the switch to the DML-only runtime+role never reached this service at all and the default, which names the+*owner*, was what it connected as.++Both spellings are asserted, and so is the precedence between them, because+"accepts the new name" and "still accepts the old one" are different promises+and a deployment relies on both.+"""++from __future__ import annotations++import os++import pytest++[email protected](autouse=True)+def _clean_env(monkeypatch):+ for key in list(os.environ):+ if key.startswith("PURPLE_TEAM_") or key == "DATABASE_URL":+ monkeypatch.delenv(key, raising=False)+++def test_unprefixed_env_var(monkeypatch):+ monkeypatch.setenv("DATABASE_URL", "postgresql+asyncpg://aisoc_app:pw@db:5432/aisoc")+ from app.core.config import Settings++ assert Settings().database_url == "postgresql+asyncpg://aisoc_app:pw@db:5432/aisoc"+++def test_prefixed_env_var_still_works(monkeypatch):+ monkeypatch.setenv("PURPLE_TEAM_DATABASE_URL", "postgresql+asyncpg://legacy:pw@db:5432/legacy")+ from app.core.config import Settings++ assert Settings().database_url == "postgresql+asyncpg://legacy:pw@db:5432/legacy"+++def test_unprefixed_takes_precedence(monkeypatch):+ monkeypatch.setenv("DATABASE_URL", "postgresql+asyncpg://winner:pw@db:5432/win")+ monkeypatch.setenv("PURPLE_TEAM_DATABASE_URL", "postgresql+asyncpg://loser:pw@db:5432/lose")+ from app.core.config import Settings++ assert Settings().database_url == "postgresql+asyncpg://winner:pw@db:5432/win"+++def test_falls_back_to_default():+ from app.core.config import Settings++ assert "localhost" in Settings().database_url+++def test_other_fields_keep_their_prefix(monkeypatch):+ """The alias covers one field. Widening it silently would be its own bug."""+ monkeypatch.setenv("PURPLE_TEAM_DRIFT_SNAPSHOT_INTERVAL_SECONDS", "7")+ from app.core.config import Settings++ assert Settings().drift_snapshot_interval_seconds == 7diff --git a/services/slack-bot/app/main.py b/services/slack-bot/app/main.pyindex 0550b4955..c1b3f4b9b 100644--- a/services/slack-bot/app/main.py+++ b/services/slack-bot/app/main.py@@ -261,10 +261,18 @@ async def _lifespan(app: FastAPI) -> AsyncIterator[None]:timer_store = Nonedsn = os.getenv("DATABASE_URL", "").strip()if dsn:- try:- from app.services.timer_store import PostgresTimerStore # noqa: PLC0415+ from app.services.timer_store import MissingApprovalTimersTable, PostgresTimerStore # noqa: PLC0415- timer_store = await PostgresTimerStore.create(dsn)+ try:+ timer_store = await PostgresTimerStore.create(dsn, get_settings().AISOC_DEFAULT_TENANT_ID)+ except MissingApprovalTimersTable as exc:+ # Distinguished from a transient database problem and logged at+ # error: the deployment asked for durable approval timers, they+ # are not durable, and the remedy is a migration rather than a+ # retry. Still non-fatal — the in-memory fallback is the pre-B3+ # behaviour, not a broken bot.+ logger.error("approval_timer_store.schema_missing", error=str(exc))+ timer_store = Noneexcept Exception as exc: # noqa: BLE001 — durable store is best-effortlogger.warning("approval_timer_store.init_failed", error=str(exc))timer_store = Nonediff --git a/services/slack-bot/app/services/timer_store.py b/services/slack-bot/app/services/timer_store.pyindex a91cce6ce..29904150b 100644--- a/services/slack-bot/app/services/timer_store.py+++ b/services/slack-bot/app/services/timer_store.py@@ -37,6 +37,12 @@ class TimerRecord:case_id: str = ""channel: str | None = Noneapprover_id: str = "scheduler"+ #: The tenant the action belongs to. v1 maps one Slack workspace to one+ #: AiSOC tenant, so it comes from ``AISOC_DEFAULT_TENANT_ID`` rather than+ #: from the card — but it is carried on the record, not assumed by the+ #: store, because the row is what a policy filters on and a timer decides+ #: whether a containment auto-rejects.+ tenant_id: str = ""@runtime_checkable@@ -69,42 +75,74 @@ class InMemoryTimerStore:return list(self._rows.values())-_CREATE_SQL = """-CREATE TABLE IF NOT EXISTS approval_timers (- action_id TEXT PRIMARY KEY,- fire_at DOUBLE PRECISION NOT NULL,- safe_default TEXT NOT NULL DEFAULT 'rejected',- case_id TEXT NOT NULL DEFAULT '',- channel TEXT,- approver_id TEXT NOT NULL DEFAULT 'scheduler',- created_at TIMESTAMPTZ NOT NULL DEFAULT now()-)-"""+class MissingApprovalTimersTable(RuntimeError):+ """``approval_timers`` is absent, and this store will not create it."""+++class PostgresTimerStore:+ """asyncpg-backed durable store. Fail-soft: DB errors are logged, not raised.++ Two properties this class deliberately does **not** have any more.+ It does not create its own table. ``approval_timers`` lives in+ ``services/api/migrations/062_approval_timers.sql``; before that it existed+ in no migration anywhere, so it had no row-level-security policy while+ every other tenant-scoped table in the schema did — on a table that decides+ whether a pending containment auto-rejects. Runtime DDL is also how the+ store would have broken silently: ``061_runtime_app_role.sql`` takes+ ``CREATE`` on schema public away from the runtime role, Postgres checks the+ schema ACL *before* the existence test, and ``main.py`` turns the resulting+ error into a warning and falls back to the non-durable store. A probe that+ says "apply the migration" is a failure somebody can act on.-class PostgresTimerStore: # pragma: no cover — thin asyncpg wrapper, exercised by the live service- """asyncpg-backed durable store. Fail-soft: DB errors are logged, not raised."""+ It does not read rows it cannot attribute. Every statement carries+ ``tenant_id``, so the store does not depend on the policy alone — and each+ connection binds ``app.current_tenant_id`` so the policy engages as well.+ One control in the query, one in the database.+ """- def __init__(self, pool: Any) -> None:+ def __init__(self, pool: Any, tenant_id: str) -> None:self._pool = pool+ self._tenant_id = tenant_id@classmethod- async def create(cls, dsn: str) -> PostgresTimerStore:+ async def create(cls, dsn: str, tenant_id: str) -> PostgresTimerStore:import asyncpg # noqa: PLC0415- pool = await asyncpg.create_pool(dsn.replace("postgresql+asyncpg://", "postgresql://", 1), min_size=1, max_size=2)+ async def _bind_tenant(conn: Any) -> None:+ # Not SET LOCAL: there is no surrounding transaction, and the+ # binding is meant to last for the pooled connection. The pool is+ # this process's and this process serves one tenant.+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, false)", tenant_id)++ pool = await asyncpg.create_pool(+ dsn.replace("postgresql+asyncpg://", "postgresql://", 1),+ min_size=1,+ max_size=2,+ init=_bind_tenant,+ )async with pool.acquire() as conn:- await conn.execute(_CREATE_SQL)- return cls(pool)+ present = await conn.fetchval("SELECT to_regclass('public.approval_timers')")+ if present is None:+ await pool.close()+ raise MissingApprovalTimersTable(+ "approval_timers does not exist. Apply the API migration chain "+ "(062_approval_timers.sql) with the owner credential; this service holds DML only "+ "and will not create the table at runtime."+ )+ return cls(pool, tenant_id)async def put(self, record: TimerRecord) -> None:try:async with self._pool.acquire() as conn:await conn.execute(- """INSERT INTO approval_timers (action_id, fire_at, safe_default, case_id, channel, approver_id)- VALUES ($1,$2,$3,$4,$5,$6)- ON CONFLICT (action_id) DO UPDATE SET fire_at=$2, safe_default=$3""",+ """INSERT INTO approval_timers+ (action_id, tenant_id, fire_at, safe_default, case_id, channel, approver_id)+ VALUES ($1,$2,$3,$4,$5,$6,$7)+ ON CONFLICT (action_id) DO UPDATE SET fire_at=$3, safe_default=$4+ WHERE approval_timers.tenant_id = $2""",record.action_id,+ record.tenant_id or self._tenant_id,record.fire_at_epoch,record.safe_default,record.case_id,@@ -117,14 +155,23 @@ class PostgresTimerStore: # pragma: no cover — thin asyncpg wrapper, exerciseasync def delete(self, action_id: str) -> None:try:async with self._pool.acquire() as conn:- await conn.execute("DELETE FROM approval_timers WHERE action_id=$1", action_id)+ await conn.execute(+ "DELETE FROM approval_timers WHERE action_id=$1 AND tenant_id=$2",+ action_id,+ self._tenant_id,+ )except Exception as exc: # noqa: BLE001log.warning("timer_store.delete_failed", action_id=action_id, error=str(exc))async def list_pending(self) -> list[TimerRecord]:try:async with self._pool.acquire() as conn:- rows = await conn.fetch("SELECT action_id, fire_at, safe_default, case_id, channel, approver_id FROM approval_timers")+ rows = await conn.fetch(+ """SELECT action_id, tenant_id, fire_at, safe_default, case_id, channel, approver_id+ FROM approval_timers+ WHERE tenant_id = $1""",+ self._tenant_id,+ )return [TimerRecord(action_id=r["action_id"],@@ -133,6 +180,7 @@ class PostgresTimerStore: # pragma: no cover — thin asyncpg wrapper, exercisecase_id=r["case_id"],channel=r["channel"],approver_id=r["approver_id"],+ tenant_id=r["tenant_id"],)for r in rows]diff --git a/services/slack-bot/tests/test_timer_store_postgres.py b/services/slack-bot/tests/test_timer_store_postgres.pynew file mode 100644index 000000000..0947871d1--- /dev/null+++ b/services/slack-bot/tests/test_timer_store_postgres.py@@ -0,0 +1,191 @@+"""``PostgresTimerStore`` does not create its own table, and scopes every row.++``approval_timers`` was in no migration anywhere: the store created it at+startup with ``CREATE TABLE IF NOT EXISTS``. Two consequences, and the tests+below pin both.++* It had no row-level-security policy, because ``060_rls_coverage.sql`` gave+ one to every tenant-scoped table *in the chain* and this table was outside+ it — on a table that decides whether a pending containment auto-rejects. It+ also had no ``tenant_id`` for a policy to filter on.+* Under the DML-only runtime role the DDL itself fails: Postgres checks the+ schema ACL before the existence test, so ``CREATE TABLE IF NOT EXISTS``+ raises ``permission denied for schema public`` even when the table is there.+ ``main.py`` caught that into a log line and fell back to the in-memory+ store, so "durable approval timers" would have quietly stopped being+ durable.++These drive a recording double rather than a live database: what is being+asserted is the statements the store issues, which is exactly what a policy+and a missing migration turn on. The live half is+``tests/isolation/test_postgres_rls.py``.+"""++from __future__ import annotations++import pytest+from app.services.timer_store import MissingApprovalTimersTable, PostgresTimerStore, TimerRecord++TENANT = "11111111-1111-1111-1111-111111111111"+OTHER = "22222222-2222-2222-2222-222222222222"+++class _Conn:+ def __init__(self, rows: list[dict] | None = None) -> None:+ self.statements: list[tuple[str, tuple]] = []+ self._rows = rows or []++ async def execute(self, sql, *args):+ self.statements.append((sql, args))++ async def fetch(self, sql, *args):+ self.statements.append((sql, args))+ return self._rows++ async def fetchval(self, sql, *args):+ self.statements.append((sql, args))+ return "approval_timers"+++class _Acquire:+ def __init__(self, conn: _Conn) -> None:+ self._conn = conn++ async def __aenter__(self) -> _Conn:+ return self._conn++ async def __aexit__(self, *exc) -> None:+ return None+++class _Pool:+ def __init__(self, conn: _Conn) -> None:+ self._conn = conn++ def acquire(self) -> _Acquire:+ return _Acquire(self._conn)+++def _sql(conn: _Conn) -> str:+ return " ".join(sql for sql, _ in conn.statements)+++async def test_put_carries_the_tenant():+ conn = _Conn()+ store = PostgresTimerStore(_Pool(conn), TENANT)+ await store.put(TimerRecord(action_id="a1", fire_at_epoch=1.0, safe_default="rejected"))+ sql, args = conn.statements[0]+ assert "tenant_id" in sql+ assert TENANT in args+++async def test_delete_is_scoped_to_the_tenant():+ conn = _Conn()+ store = PostgresTimerStore(_Pool(conn), TENANT)+ await store.delete("a1")+ sql, args = conn.statements[0]+ assert "tenant_id=$2" in sql.replace(" ", "")+ assert args == ("a1", TENANT)+++async def test_list_pending_is_scoped_to_the_tenant():+ conn = _Conn(+ rows=[+ {+ "action_id": "a1",+ "tenant_id": TENANT,+ "fire_at": 1.0,+ "safe_default": "rejected",+ "case_id": "c1",+ "channel": None,+ "approver_id": "scheduler",+ }+ ]+ )+ store = PostgresTimerStore(_Pool(conn), TENANT)+ records = await store.list_pending()+ sql, args = conn.statements[0]+ assert "WHERE tenant_id = $1" in sql+ assert args == (TENANT,)+ assert records[0].tenant_id == TENANT+++async def test_a_record_naming_another_tenant_does_not_override_the_store():+ """The store's tenant wins. A record is data; the connection is the scope."""+ conn = _Conn()+ store = PostgresTimerStore(_Pool(conn), TENANT)+ await store.put(TimerRecord(action_id="a1", fire_at_epoch=1.0, safe_default="rejected", tenant_id=""))+ _sql_text, args = conn.statements[0]+ assert TENANT in args+ assert OTHER not in args+++def test_the_store_issues_no_ddl():+ """A grep over the module, because the failure was DDL on a startup path.++ Asserted against the source rather than against a call log: the point is+ that no code path can create the table, not that one particular path did+ not this time.+ """+ import inspect # noqa: PLC0415++ from app.services import timer_store # noqa: PLC0415++ source = inspect.getsource(timer_store)+ body = source.split('"""', 2)[-1] # drop the module docstring, which names the SQL+ for statement in ("CREATE TABLE", "CREATE INDEX", "ALTER TABLE"):+ assert statement not in body, f"{statement} is back in timer_store.py; it belongs in a migration"+++async def test_create_refuses_when_the_table_is_absent(monkeypatch):+ """An absent table is an error naming the migration, not a silent fallback."""++ class _AbsentConn(_Conn):+ async def fetchval(self, sql, *args):+ return None++ closed: list[bool] = []++ class _ClosablePool(_Pool):+ async def close(self) -> None:+ closed.append(True)++ class _FakeAsyncpg:+ @staticmethod+ async def create_pool(*_args, **_kwargs):+ return _ClosablePool(_AbsentConn())++ monkeypatch.setitem(__import__("sys").modules, "asyncpg", _FakeAsyncpg)++ with pytest.raises(MissingApprovalTimersTable) as caught:+ await PostgresTimerStore.create("postgresql+asyncpg://u:p@h/db", TENANT)+ assert "062_approval_timers.sql" in str(caught.value)+ assert closed, "the pool was left open after refusing"+++async def test_create_binds_the_rls_context_on_every_connection(monkeypatch):+ """The policy only engages on a connection that bound a tenant."""+ captured: dict[str, object] = {}++ class _FakeAsyncpg:+ @staticmethod+ async def create_pool(*_args, **kwargs):+ captured["init"] = kwargs.get("init")+ return _Pool(_Conn())++ monkeypatch.setitem(__import__("sys").modules, "asyncpg", _FakeAsyncpg)+ await PostgresTimerStore.create("postgresql+asyncpg://u:p@h/db", TENANT)++ init = captured["init"]+ assert init is not None, "connections are pooled without binding a tenant, so the policy never engages"+ conn = _Conn()+ await init(conn) # type: ignore[operator]+ sql, args = conn.statements[0]+ assert "app.current_tenant_id" in sql+ assert TENANT in argsdiff --git a/services/ueba/alembic/env.py b/services/ueba/alembic/env.pyindex 0aa9714d8..b7318aeda 100644--- a/services/ueba/alembic/env.py+++ b/services/ueba/alembic/env.py@@ -1,11 +1,37 @@-"""Alembic migration environment for UEBA service."""+"""Alembic migration environment for UEBA service.++Which credential applies the chain+----------------------------------+Alembic issues DDL, and ``services/api/migrations/061_runtime_app_role.sql``+deliberately left the runtime role without any: ``aisoc_app`` holds ``USAGE``+on schema public and not ``CREATE``, precisely so it cannot+``ALTER TABLE … NO FORCE ROW LEVEL SECURITY`` and switch off the policies+``0002_tenant_rls`` installs. A service that migrates and serves under one+credential has not split those roles at all, whatever the deployment surface+says.++So the migration credential is read first and the runtime one is only a+fallback. The fallback stays — a deployment that has not split the roles+behaves exactly as it did before — but it is announced, because both ways of+getting this wrong are otherwise silent:++* point this at the runtime role and ``alembic upgrade`` dies on the first+ ``CREATE TABLE`` with ``permission denied for schema public``;+* point the *service* at the owner and every policy in this chain stops+ filtering, with nothing in any log to say so.++``scripts/check_runtime_db_role.py`` is what keeps the deployment surfaces+honest about which variable carries which role.+"""from __future__ import annotationsimport asyncioimport os+import sysfrom logging.config import fileConfig+import sqlalchemy as safrom alembic import contextfrom app.models.ueba import Basefrom sqlalchemy.ext.asyncio import create_async_engine@@ -17,10 +43,106 @@ if config.config_file_name is not None:target_metadata = Base.metadata-DATABASE_URL = os.environ.get("DATABASE_URL") or os.environ.get(- "UEBA_DATABASE_URL",- "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc",-)+#: Owner credentials, most specific first. Any variable ending in+#: ``DATABASE_MIGRATION_URL`` is recognised as a migration DSN by the gate.+MIGRATION_URL_VARS = ("UEBA_DATABASE_MIGRATION_URL", "DATABASE_MIGRATION_URL")++#: Runtime credentials. Same order the service's own settings resolve them in,+#: so the fallback below lands on exactly what the service connects as.+RUNTIME_URL_VARS = ("DATABASE_URL", "UEBA_DATABASE_URL")++DEFAULT_URL = "postgresql+asyncpg://aisoc:aisoc@localhost:5432/aisoc"+++def _first_env(names: tuple[str, ...]) -> str:+ for name in names:+ value = os.environ.get(name, "").strip()+ if value:+ return value+ return ""+++def _resolve_dsn() -> str:+ migration = _first_env(MIGRATION_URL_VARS)+ if migration:+ return migration+ print(+ "alembic: none of "+ + ", ".join(MIGRATION_URL_VARS)+ + " is set, so this chain is being applied as the runtime credential. That works only "+ "while the two are the same role; under the DML-only runtime role the first CREATE TABLE "+ "fails with 'permission denied for schema public'.",+ file=sys.stderr,+ )+ return _first_env(RUNTIME_URL_VARS) or DEFAULT_URL+++DATABASE_URL = _resolve_dsn()+++#: Alembic's default version table is ``alembic_version``, and four services in+#: this repository run their own chain against **one** database — compose gives+#: ueba, honeytokens, purple-team and osquery-tls the same ``aisoc``. They also+#: number their revisions identically (``0001``, ``0002``, …), so the shared+#: table made the second chain to run believe it was already at head.+#:+#: Measured against ``postgres:16`` on the sequence ``apps/docs/docs/quickstart.md``+#: prints: after ``ueba`` reached ``0002``, ``honeytokens alembic upgrade head``+#: ran **zero** migrations and ``purple-team`` failed applying its RLS revision+#: to tables that had never been created. Two services' tenant policies did not+#: exist in the default deployment and nothing said so.+VERSION_TABLE = "alembic_version_ueba"++#: The table those chains shared. Read once, never written: see+#: :func:`_adopt_legacy_version`.+LEGACY_VERSION_TABLE = "alembic_version"+++def _adopt_legacy_version(connection) -> None: # type: ignore[no-untyped-def]+ """Carry a version recorded in the shared table into this chain's own.++ Without this, moving to a per-chain version table reads to alembic as a+ database that has never been migrated, and the first ``CREATE TABLE``+ fails because the table is already there.++ Three conditions, all required, so the adoption cannot claim a revision+ belonging to a sibling chain:++ * this chain has no version table yet;+ * at least one table **this chain maps** already exists, which is the only+ evidence that this chain — rather than a sibling — is what the shared+ row records;+ * the recorded id is a revision in this chain's own script directory.++ The shared table is left alone. A sibling that has not adopted yet still+ needs it, and once every chain has, it is inert rather than wrong.++ ``CREATE TABLE IF NOT EXISTS`` appears below and is reached only after the+ probe says the table is absent. Postgres checks the schema ACL *before* the+ existence test, so the statement raises ``permission denied for schema+ public`` on a role without ``CREATE`` even when the table is already there+ — the trap that took two stores in ``services/agents`` down to a+ ``logger.debug``. Here the whole function runs on the **migration**+ connection, but the probe-first order costs nothing and keeps the shape+ right if that ever stops being true.+ """+ inspector = sa.inspect(connection)+ if inspector.has_table(VERSION_TABLE) or not inspector.has_table(LEGACY_VERSION_TABLE):+ return+ if not any(inspector.has_table(name) for name in target_metadata.tables):+ return+ recorded = connection.execute(sa.text(f"SELECT version_num FROM {LEGACY_VERSION_TABLE}")).scalar() # noqa: S608+ if recorded is None or recorded not in {rev.revision for rev in context.script.walk_revisions()}:+ return+ connection.execute(+ sa.text(+ f"CREATE TABLE IF NOT EXISTS {VERSION_TABLE} (" # noqa: S608+ f"version_num VARCHAR(32) NOT NULL, "+ f"CONSTRAINT {VERSION_TABLE}_pkc PRIMARY KEY (version_num))"+ )+ )+ connection.execute(sa.text(f"INSERT INTO {VERSION_TABLE} (version_num) VALUES (:v)"), {"v": recorded}) # noqa: S608+ print(f"alembic: adopted {recorded!r} from {LEGACY_VERSION_TABLE} into {VERSION_TABLE}", file=sys.stderr)def run_migrations_offline() -> None:@@ -29,14 +151,22 @@ def run_migrations_offline() -> None:target_metadata=target_metadata,literal_binds=True,dialect_opts={"paramstyle": "named"},+ version_table=VERSION_TABLE,)with context.begin_transaction():context.run_migrations()def do_run_migrations(connection): # type: ignore[no-untyped-def]- context.configure(connection=connection, target_metadata=target_metadata)+ context.configure(connection=connection, target_metadata=target_metadata, version_table=VERSION_TABLE)with context.begin_transaction():+ # Inside ``begin_transaction()``, not before it. Alembic's+ # ``begin_transaction`` is a no-op when the connection is *already* in a+ # transaction, and in SQLAlchemy 2.0 any execute on a plain ``connect()``+ # starts one implicitly — so probing the schema first left the whole+ # upgrade inside a transaction nobody committed. Measured: the chain+ # printed every "Running upgrade" line and the database came back empty.+ _adopt_legacy_version(connection)context.run_migrations()diff --git a/services/ueba/alembic/versions/0003_runtime_role_grants.py b/services/ueba/alembic/versions/0003_runtime_role_grants.pynew file mode 100644index 000000000..87acccc80--- /dev/null+++ b/services/ueba/alembic/versions/0003_runtime_role_grants.py@@ -0,0 +1,116 @@+"""Give the runtime role DML on the UEBA tables, and nothing more.++Revision ID: 0003+Revises: 0002+Create Date: 2026-09-24++Companion to ``services/api/migrations/061_runtime_app_role.sql``, which split+one superuser credential into an owner that applies DDL and ``aisoc_app``, the+DML-only role every service's ``DATABASE_URL`` points at. That migration+granted ``aisoc_app`` on ``ALL TABLES IN SCHEMA public`` as they stood when it+ran, and set ``ALTER DEFAULT PRIVILEGES`` for objects the *same* role creates+afterwards.++Neither clause reaches this chain reliably:++* nothing orders the two chains against each other, so this service's tables+ may not exist when 061's ``ALL TABLES`` grant runs;+* ``ALTER DEFAULT PRIVILEGES`` is recorded against the role that issued it, so+ a deployment applying the API chain and this one under different owners — or+ pointing this service at its own database, which ``UEBA_DATABASE_URL`` exists+ to allow — gets no default privilege here at all.++The observable failure is a service that starts, connects, and answers every+query with ``permission denied for table ueba_anomalies``. So the chain grants+what its own tables need rather than depending on another chain having run.++Grants, not ownership: an owner can ``ALTER TABLE … NO FORCE ROW LEVEL+SECURITY``, which is the bypass 061 exists to close. ``aisoc_app`` therefore+gets ``SELECT, INSERT, UPDATE, DELETE`` and not ``TRUNCATE``, ``REFERENCES`` or+``TRIGGER``.++The role name is a literal because it has to match 061, the compose stack and+every deployment surface, and a role interpolated into DDL from an environment+variable is an injection site with no upside. A deployment using a different+runtime role issues the equivalent grant itself; the guard below makes this+revision a notice rather than a failure there.+"""++from __future__ import annotations++from alembic import op # type: ignore[attr-defined] # re-exported at runtime, absent from the stub++revision = "0003"+down_revision = "0002"+branch_labels = None+depends_on = None++# Spelled out one table at a time rather than derived from the mapped+# metadata: a grant covering whatever happens to be mapped today is not+# reviewable, and this list is the reviewable part of the change.+TABLES = ("ueba_entity_baselines", "ueba_anomalies", "ueba_peer_groups")++RUNTIME_ROLE = "aisoc_app"+++def _statement(action: str, tables: tuple[str, ...], role: str) -> str:+ """``GRANT``/``REVOKE`` over these tables and the sequences they own.++ Sequences are included because ``nextval`` needs ``USAGE`` and ``currval``+ needs ``SELECT``, and a grant on the table alone carries neither — the+ first ``BIGSERIAL`` anybody adds to this chain would fail at insert time+ with a message about a sequence nobody went looking for.+ """+ array = "ARRAY[" + ", ".join(f"'{t}'" for t in tables) + "]"+ if action == "GRANT":+ clause = (+ "format('GRANT %s ON %s TO " + role + "', "+ "CASE obj.kind WHEN 'S' THEN 'USAGE, SELECT' ELSE 'SELECT, INSERT, UPDATE, DELETE' END, obj.ref)"+ )+ notice = (+ f"RAISE NOTICE 'role {role} does not exist; skipping runtime grants. Apply "+ f"services/api/migrations/061_runtime_app_role.sql, or grant your own runtime role "+ f"DML on these tables by hand.';"+ )+ else:+ clause = "format('REVOKE ALL ON %s FROM " + role + "', obj.ref)"+ notice = ""+ return f"""+DO $$+DECLARE+ obj record;+BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '{role}') THEN+ {notice}+ RETURN;+ END IF;+ FOR obj IN+ SELECT c.oid::regclass::text AS ref, c.relkind AS kind+ FROM pg_class c+ WHERE pg_table_is_visible(c.oid)+ AND (+ (c.relkind IN ('r', 'p') AND c.relname = ANY ({array}))+ -- Only sequences. An index carries the same 'a' dependency on its+ -- table, and GRANT on one raises `"ix_…" is an index` — which the+ -- live round-trip caught and a review of the statement did not.+ OR (c.relkind = 'S' AND c.oid IN (+ SELECT d.objid+ FROM pg_depend d+ JOIN pg_class t ON t.oid = d.refobjid+ WHERE d.deptype = 'a' AND t.relname = ANY ({array})+ ))+ )+ LOOP+ EXECUTE {clause};+ END LOOP;+END+$$;+"""+++def upgrade() -> None:+ op.execute(_statement("GRANT", TABLES, RUNTIME_ROLE))+++def downgrade() -> None:+ op.execute(_statement("REVOKE", TABLES, RUNTIME_ROLE))diff --git a/tests/test_gate_contract.py b/tests/test_gate_contract.pyindex e64843a81..a3f4f74b7 100644--- a/tests/test_gate_contract.py+++ b/tests/test_gate_contract.py@@ -231,8 +231,8 @@ def test_a_gate_in_the_scratch_tree_resolves_the_scratch_tree():# ── The verdict ──────────────────────────────────────────────────────────────-def _probe(*dispositions: str) -> dict[str, cgc.Probe]:- runs = [cgc.Run(args=["--check"], source="test", disposition=d, why=d) for d in dispositions]+def _probe(*dispositions: str, shape: str = gate_toolkit.BARE) -> dict[str, cgc.Probe]:+ runs = [cgc.Run(args=["--check"], source="test", shape=shape, disposition=d, why=d) for d in dispositions]return {"check_x.py": cgc.Probe(script="check_x.py", runs=runs)}@@ -264,7 +264,7 @@ def test_the_worst_invocation_decides_not_the_first():def test_an_exception_is_checked_against_the_disposition_it_was_written_for():- excused = {"check_x.py": (cgc.INCONCLUSIVE, "its inputs are named on the command line")}+ excused = {"check_x.py": {cgc.ANY_SHAPE: (cgc.INCONCLUSIVE, "its inputs are named on the command line")}}assert not _codes(_probe(cgc.INCONCLUSIVE), accepted=excused)assert "exception-stale" in _codes(_probe(cgc.PASSED), accepted=excused)@@ -272,11 +272,11 @@ def test_an_exception_is_checked_against_the_disposition_it_was_written_for():def test_an_exception_naming_nothing_fails():- assert "ratchet-names-nothing" in _codes(_probe(cgc.REFUSED), accepted={"check_gone.py": (cgc.PASSED, "reason")})+ assert "ratchet-names-nothing" in _codes(_probe(cgc.REFUSED), accepted={"check_gone.py": {cgc.ANY_SHAPE: (cgc.PASSED, "reason")}})def test_an_exception_with_no_reason_fails():- assert "ratchet-unexplained" in _codes(_probe(cgc.REFUSED), accepted={"check_x.py": (cgc.REFUSED, " ")})+ assert "ratchet-unexplained" in _codes(_probe(cgc.REFUSED), accepted={"check_x.py": {cgc.ANY_SHAPE: (cgc.REFUSED, " ")}})# ── The real tree ────────────────────────────────────────────────────────────@@ -292,9 +292,36 @@ def test_every_recorded_exception_names_a_check_that_exists():def test_every_recorded_exception_carries_a_disposition_the_gate_understands():- for name, (disposition, reason) in cgc.EMPTY_TREE_EXCEPTIONS.items():- assert disposition in {cgc.PASSED, cgc.REFUSED, cgc.INCONCLUSIVE}, name- assert len(reason.split()) >= 10, f"{name}: a one-line reason is not a justification"+ for name, per_shape in cgc.EMPTY_TREE_EXCEPTIONS.items():+ assert per_shape, f"{name} is listed with no shape at all"+ for shape, (disposition, reason) in per_shape.items():+ assert shape == cgc.ANY_SHAPE or shape in gate_toolkit.TREE_SHAPES, f"{name}: unknown tree shape {shape!r}"+ assert disposition in {cgc.PASSED, cgc.REFUSED, cgc.INCONCLUSIVE}, name+ assert len(reason.split()) >= 10, f"{name}[{shape}]: a one-line reason is not a justification"+++def test_a_shape_specific_exemption_does_not_cover_the_other_shape():+ """The reason the second tree shape is worth having, asserted rather than assumed.++ A gate can refuse a missing directory for a reason that says nothing+ about its corpus and then credit the same directory when it exists and is+ empty. An exemption written for one shape must not silently carry over.+ """+ excused = {"check_x.py": {gate_toolkit.SKELETON: (cgc.PASSED, "its corpus is not the directory in question at all")}}+ both = _probe(cgc.PASSED)+ both["check_x.py"].runs.append(+ cgc.Run(args=["--check"], source="test", shape=gate_toolkit.SKELETON, disposition=cgc.PASSED, why="exited 0")+ )+ assert "passes-over-empty-tree" in _codes(both, accepted=excused)+++def test_the_skeleton_tree_has_the_directories_the_bare_one_omits():+ with gate_toolkit.scratch_tree(shape=gate_toolkit.SKELETON) as tree:+ assert (tree / "services").is_dir()+ assert (tree / "detections").is_dir()+ assert [p.name for p in (tree / "services").iterdir()] == [".gitkeep"]+ with gate_toolkit.scratch_tree(shape=gate_toolkit.BARE) as tree:+ assert not (tree / "services").exists()def test_the_self_test_catches_every_defect_it_claims_to():