Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(kill-switch): make the platform-wide stop engageable, and give it a product surface (#1534)
Beenu Arora1f86648d9912
diff --git a/.github/workflows/kill-switch-live.yml b/.github/workflows/kill-switch-live.ymlnew file mode 100644index 000000000..c1ff7b650--- /dev/null+++ b/.github/workflows/kill-switch-live.yml@@ -0,0 +1,118 @@+# The kill switch, against real Postgres as the runtime role.+#+# Why this is a live job rather than part of the general Python suite:+# the whole subject is what a row-level security policy does to the role the+# services actually connect as. `061_runtime_app_role.sql` makes `aisoc_app`+# NOSUPERUSER NOBYPASSRLS and both tables are FORCE ROW LEVEL SECURITY, so+# the defect these suites pin — a global row no session could write — is+# invisible to every other role. Seeding it as the migration owner succeeds+# and proves nothing, which is precisely the workaround that hid it.+#+# No `paths:` filter. An emergency stop must grade every pull request, not+# only ones that touch a named path: the ways this breaks are a policy edit+# in some other migration, a dependency sweep moving the global routes onto+# a tenant-scoped session, and a permission rename — none of which are under+# the paths anyone would think to list.+name: Kill switch (live)++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:++concurrency:+ group: kill-switch-live-${{ github.ref }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.sha }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ kill-switch-live:+ name: The platform-wide stop can be engaged, and stops closure+ runs-on: ubuntu-latest+ timeout-minutes: 20++ env:+ # The runtime role, not the owner. POSTGRES_USER (aisoc) is a superuser+ # and ignores every policy even under FORCE ROW LEVEL SECURITY; the+ # suites refuse to run against a role that can bypass, rather than+ # passing for the wrong reason.+ ISOLATION_KILL_SWITCH_DSN: postgresql+asyncpg://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc+ PGPASSWORD: aisoc_ci_only+ ENVIRONMENT: test+ SECRET_KEY: ci-kill-switch-signing-secret-at-least-32-chars+ OTEL_SDK_DISABLED: "true"++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - name: Start PostgreSQL with registry fallback+ uses: ./.github/actions/start-postgres+ with:+ password: aisoc_ci_only++ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6+ with:+ python-version: "3.11"++ - name: Apply every migration, in order+ run: |+ set -euo pipefail+ for f in services/api/migrations/*.sql; do+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"+ done++ - name: Give the runtime role its password+ run: |+ set -euo pipefail+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "ALTER ROLE aisoc_app WITH LOGIN PASSWORD 'aisoc_app_ci_only';"+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "GRANT USAGE ON SCHEMA public TO aisoc_app;"++ # Asserted rather than assumed. If this role could bypass a policy,+ # every suite below would pass against the pre-fix tree.+ - name: The runtime role cannot walk past a policy+ run: |+ set -euo pipefail+ bad=$(psql -h localhost -U aisoc -d aisoc -tAc \+ "SELECT count(*) FROM pg_roles WHERE rolname = 'aisoc_app' AND (rolsuper OR rolbypassrls)")+ if [ "$bad" != "0" ]; then+ echo "FAIL: aisoc_app holds SUPERUSER or BYPASSRLS, so these suites would verify nothing."+ exit 1+ fi+ echo "OK: aisoc_app is subject to row-level security."++ - name: Install api from its lockfile+ working-directory: services/api+ run: |+ set -euo pipefail+ python -m pip install --quiet --upgrade pip "poetry==2.4.1"+ poetry config virtualenvs.create false+ poetry install --no-root --no-interaction+ python -m pip install --quiet pytest pytest-asyncio++ - name: The global row is writable by the runtime role, and nothing else is+ working-directory: services/api+ run: python -m pytest ../../tests/isolation/test_kill_switch_global_live.py -v --tb=short -rs++ - name: The platform-wide stop is reachable through the product+ working-directory: services/api+ run: python -m pytest ../../tests/isolation/test_kill_switch_endpoint_live.py -v --tb=short -rs++ # `services/agents` ships a different package also called `app`, so+ # importing one shadows the other. The closure reader lives in that one,+ # and it is installed after the API legs have run for that reason.+ - name: Install agents from its lockfile+ working-directory: services/agents+ run: |+ set -euo pipefail+ poetry config virtualenvs.create false+ poetry install --no-root --no-interaction+ python -m pip install --quiet pytest pytest-asyncio++ - name: An engaged platform switch actually stops automatic closure+ working-directory: services/agents+ run: python -m pytest ../../tests/isolation/test_kill_switch_closure_live.py -v --tb=short -rsdiff --git a/ROADMAP.md b/ROADMAP.mdindex 8b165f137..9c5aadc41 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **321 rows — 317 GATED / 4 PARTIAL / 0 NO GATE**. Four rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **322 rows — 318 GATED / 4 PARTIAL / 0 NO GATE**. Four rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 39b05568d..6cc551782 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 317 rows+The last row is the one worth reading first. It is the honest index: 318 rows`GATED`, 4 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is whydiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 607bf0e9f..1b2a9f86c 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -329,11 +329,12 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| An adversary-in-the-middle session replay is detected on the session, not on the user | `services/fusion/app/data/windowed_ruleset.json` (`wd-aitm-*`); depth plan 7.3 | `ci.yml :: python-test` (fusion, `test_aitm_session_rules.py` — 20 cases driving the **real** `WindowedDetectionEngine`, the real matcher and the **shipped** ruleset loaded off disk rather than a hand-made rule list: the replay fires all four rules, the negative twin fires none of them, a single event fires nothing, two sessions for one user do not complete each other, an event with no session id is not grouped at all, the sequence does not fire without its MFA stage or in the wrong order, and one tenant's sign-in cannot complete another's replay) + `ci.yml` connectors matrix (`test_aitm_session_fields_reach_detection.py` — 18 cases driving the real `OktaConnector.normalize()` and `AzureEntraConnector.normalize()` over hand-authored vendor payloads, including that `mfa_satisfied` is three-valued and that a Graph `correlationId` does not stand in for a missing `sessionId`) + `ci.yml :: python-lint` (`check_windowed_translation.py` — the ceiling of 0 windowed rules selecting on a computed field, which is what forced the connector hoist rather than a rule naming a field nothing emits; `export_windowed_ruleset.py --check` for drift between the authored list and the artefact the engine loads) | core | GATED | The two halves live in different interpreters because `services/connectors` and `services/fusion` both name their package `app`; the connector test pins the payload the engine test transcribes, so a connector change that drops a field reds the connector test rather than silently passing the engine one || No two database migrations claim the same number, so a chain applies in one order on a fresh install and on an upgrade alike | `services/api/app/scripts/run_migrations.py` (orders by filename, records applied by filename); `scripts/check_migration_numbering.py` | `migration-numbering.yml :: migration-numbering` (no `paths:` filter on either trigger, so it grades every pull request and every push to a protected branch — the collision is a property of a *pair* of files and the second half can arrive from somebody else's merge, so a filter scoped to the migrations directory would miss exactly the case that bites. Discovers all 6 numbered chains structurally rather than from a list, which is what finds `services/osquery-tls/app/db/versions` under its non-conventional `script_location`. Proven against the real defect: a worktree holding both `121_fusion_alert_outbox.sql` and PR 1525's `121_closure_authorization_default_deny.sql` exits 1 naming both, and the same tree with the new-duplicate arm disabled reports a confident OK. The 13 historical collisions already on main are frozen by file set, checked in both directions so a stale exemption and a third file joining an old pair each fail | core | GATED | — || A query credited as tenant-scoped is one whose `tenant_id` constrains the rows read or written, not one that merely mentions the column | `scripts/check_tenant_query_predicates.py` (`_tenant_predicate_in_sql`) | `isolation.yml :: Tenant query predicates` (the credit is decided by the clause the token sits in, so a `RETURNING` list, a `SELECT` projection, an `ORDER BY`, a `GROUP BY`, an UPDATE `SET` and a SQL comment all stop counting, while `WHERE`, join `ON`, `USING`, `HAVING`, an INSERT column list and an `ON CONFLICT` target still do. Both code paths were fixed, not one: `_names` collects string constants, so the statement's own SQL came back round and a second bare-token test re-granted the credit on 14 of the 17 statements the first fix had demoted. 36 self-test cases written per SQL *clause* rather than per instance found, including the padding-free fragment branch and a control that an appended fragment naming the column without comparing it still fails. Proven both ways on the live tree: with its ratchet entry removed the real `UPDATE … RETURNING id, tenant_id` outbox claim is flagged, and reverting the detector to the bare-token match stops it being flagged | core | GATED | — |+| The platform-wide kill switch can actually be engaged, and an engaged one stops automatic closure | `docs/remediation/kill-switch-reachability.md`; `services/api/migrations/123_kill_switch_global_engageable.sql`; parity 2.2 | `kill-switch-live.yml :: The platform-wide stop can be engaged, and stops closure` (real Postgres, every migration applied, driven as the NOSUPERUSER NOBYPASSRLS `aisoc_app` role because the migration owner is a superuser and ignores policies even under FORCE ROW LEVEL SECURITY — the job fails if the DSN resolves to a role that can bypass, and the suite refuses to run against one, because seeding the global row as the owner is the workaround that hid this for 45 migrations. 25 cases across three suites: the global row is writable by an unbound session and by nothing else, a tenant cannot write the global row or another tenant's row or another tenant's audit row, an unbound session cannot write into any tenant, the real routes write the row end to end through the real ASGI app, a tenant_admin and an analyst are both refused 403 while the tenant switch still works for them, and `resolve_closure_policy` refuses a 0.99 verdict against a 0.50 bar with source=kill_switch for a tenant that engaged nothing itself) + `ci.yml :: Python — Tests` (api `test_kill_switch.py`, the global routes resolve their handler, require `platform_kill_switch:write` read off the resolved dependency tree rather than the handler source, and take the unbound session) | core | GATED | Before this the global row had no writer at all: every write in the endpoint module bound the caller's tenant, so no endpoint, console control, CLI or script could set `tenant_id IS NULL`, while two readers consulted it on every alert. **There is still no console control for the kill switch in either scope** — both are API-only. **An engaged switch stops closure and not dispatch**: `services/actions`, playbook dispatch and the MCP write surface contain no reference to it, contrary to the module docstring, which is recorded as a separate defect rather than fixed here |## Summary-- Total: 321-- GATED: 317+- Total: 322+- GATED: 318- PARTIAL: 4- NO GATE: 0diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 33bdec9cd..2de81fae7 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -11669,6 +11669,78 @@ paths:$ref: '#/components/schemas/HTTPValidationError'security:- HTTPBearer: []+ /api/v1/kill-switch/global/engage:+ post:+ tags:+ - autonomy+ summary: Freeze autonomous closure and action dispatch for every tenant+ description: 'Stop autonomous closure and dispatch across the whole deployment.+++ One row, upserted. The conflict target is the expression index++ `aisoc_kill_switch_global_idx ON aisoc_kill_switch ((TRUE)) WHERE tenant_id++ IS NULL`, which is what keeps the global switch a singleton rather than a++ pile of rows a reader would have to reconcile at 3am.'+ operationId: engage_global_api_v1_kill_switch_global_engage_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/EngageRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/KillSwitchState'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/kill-switch/global/release:+ post:+ tags:+ - autonomy+ summary: Resume autonomous closure and action dispatch across every tenant+ description: 'Release the platform-wide stop.+++ A tenant that engaged its own switch keeps it: the two scopes are++ independent and neither needs the other''s agreement, so releasing globally++ must not silently resume a tenant that asked to stay stopped.'+ operationId: release_global_api_v1_kill_switch_global_release_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ReleaseRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/KillSwitchState'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []/api/v1/ledger/{run_id}/publish/preview:post:tags:diff --git a/docs/remediation/kill-switch-reachability.md b/docs/remediation/kill-switch-reachability.mdnew file mode 100644index 000000000..4d764594b--- /dev/null+++ b/docs/remediation/kill-switch-reachability.md@@ -0,0 +1,382 @@+# The platform-wide kill switch could not be engaged++The kill switch is the control an operator reaches for when the agent is+doing something they did not expect. It has two scopes: a per-tenant row and+a global one that stops autonomous closure and action dispatch across the+whole deployment.++**The per-tenant switch worked. The global one had never been engageable by+anything, on any deployment, since it shipped in migration 078.** A stop+control that cannot be reached is worse than no stop control, because people+believe it is there.++This note records what was verified, what the defect turned out to be once+investigated, the fix, and the operator procedure.++## What was reported, and what was actually wrong++A sibling lane reported one half: the row-level security policy on+`aisoc_kill_switch` carries `WITH CHECK (tenant_id = current_tenant_id())`,+which makes the global row uninsertable by the runtime role.++That is true. Investigation found it was **the smaller half**.++| | Reported | Verified |+| --- | --- | --- |+| The RLS policy refuses the global row | yes | yes, for every session the runtime role can open |+| Any endpoint, console control, CLI or script could engage it | not assessed | **no writer existed anywhere in the tree** |+| The per-tenant switch | not assessed | works, and is unaffected |++So the fix had to be two things. Repairing the policy alone would have left+a correct policy over a row nothing writes, which this repository treats as+not existing.++### 1. The policy refused the global row++`078_closure_policy_and_kill_switch.sql` creates the table with a nullable+`tenant_id`, where `NULL` is the global row, and this policy:++```sql+USING (tenant_id IS NULL OR tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)+WITH CHECK (tenant_id = current_tenant_id())+```++`current_tenant_id()` returns `NULL` for an unset or empty setting+(`002_rls.sql`). Judged by that `WITH CHECK`, the global row is:++- `NULL = NULL` on a session with no tenant bound, which is `NULL`;+- `NULL = '<uuid>'` on a session with one bound, which is also `NULL`.++A `WITH CHECK` that does not evaluate to true refuses the row, so **both**+cases fail. The table's own comment says the global row "is written by the+platform operator through a session with no tenant set" — the one case the+check rejects.++Verified against `postgres:16` with all 136 migrations applied, connected as+the `NOSUPERUSER NOBYPASSRLS` `aisoc_app` runtime role. This matters: the+migration owner is a superuser and ignores policies even under `FORCE ROW+LEVEL SECURITY`, so seeding the row as the owner succeeds and proves+nothing. That is precisely the workaround that hid this.++```+######## PROOF 1: global INSERT as aisoc_app, NO tenant bound ########+ERROR: new row violates row-level security policy for table "aisoc_kill_switch"++######## PROOF 2: global INSERT as aisoc_app, WITH tenant A bound ########+SET+ERROR: new row violates row-level security policy for table "aisoc_kill_switch"++######## CONTROL: per-tenant INSERT as aisoc_app, tenant A bound ########+SET+INSERT 0 1+```++The live policy and role attributes, read from the catalogue rather than+from the migration text:++```+polname | tenant_isolation+using_expr | ((tenant_id IS NULL) OR (tenant_id = current_tenant_id()) OR (current_tenant_id() IS NULL))+with_check | (tenant_id = current_tenant_id())++ rolname | rolsuper | rolbypassrls | rolcanlogin+-----------+----------+--------------+-------------+ aisoc | t | t | t+ aisoc_app | f | f | t++ relname | relrowsecurity | relforcerowsecurity+-------------------------+----------------+---------------------+ aisoc_kill_switch | t | t+ aisoc_kill_switch_audit | t | t+```++`aisoc_kill_switch_audit` carries the same strict check, so even a switch+that could be thrown would have failed on its audit row.++### 2. Nothing could write the global row++Every write to the table in the repository bound the caller's own tenant:++```+services/api/app/api/v1/endpoints/kill_switch.py:129 INSERT INTO aisoc_kill_switch ... VALUES (:id, :t, ...)+services/api/app/api/v1/endpoints/kill_switch.py:144 INSERT INTO aisoc_kill_switch_audit ... VALUES (:id, :t, ...)+services/api/app/api/v1/endpoints/kill_switch.py:178 UPDATE aisoc_kill_switch ... WHERE tenant_id = :t+services/api/app/api/v1/endpoints/kill_switch.py:201 INSERT INTO aisoc_kill_switch_audit ... VALUES (:id, :t, ...)+```++`:t` is `user.tenant_id` at all four sites. There was no fifth writer: no+console control (`apps/web` contains no kill-switch component at all), no+CLI, no script. The published route table confirmed the surface was three+operations, none of them global:++```+GET /api/v1/kill-switch+POST /api/v1/kill-switch/engage+POST /api/v1/kill-switch/release+```++Meanwhile **two readers consult the global row**: the `GET` above, and+`kill_switch_engaged` in `services/agents/app/closure/policy.py`, which the+closure resolver calls first and separately on every alert.++A reader over a table nothing writes is a shape `AGENTS.md` calls out by+name. Here it was wearing the label of an emergency stop.++### 3. The per-tenant switch was fine++It had already been repaired — the routes take `TenantDBSession`, so they+bind `app.current_tenant_id` and satisfy the strict check (the sibling of+GHSA-898c-wxrw-hx6c, pinned by `test_rls_write_sessions.py`). The per-tenant+assertions and all four negative properties passed **before** the fix as+well as after, which is how the fix is known not to have regressed them.++## The fix++### The policy expresses the distinction rather than dropping the check++Dropping `WITH CHECK` would make the table writable and tenant isolation+decorative. A global row is legitimately not tenant-scoped, so+`123_kill_switch_global_engageable.sql` says so:++```sql+WITH CHECK (+ tenant_id = current_tenant_id()+ OR (tenant_id IS NULL AND current_tenant_id() IS NULL)+)+```++Read over the two things a session can be, this says "you may write exactly+the row that is yours":++| session | row | decision |+| --- | --- | --- |+| unbound | global | **allowed** — the platform operator's own row |+| unbound | a tenant's | refused — `NULL OR FALSE` is `NULL` |+| tenant A | global | refused — a tenant cannot freeze everyone |+| tenant A | A's own | allowed — unchanged from 078 |+| tenant A | tenant B's | refused — unchanged from 078 |++Four of those five are unchanged. The only new capability is the first.+`aisoc_kill_switch_audit` gets the same policy for the same reason.++### The surface++`POST /api/v1/kill-switch/global/engage` and `.../global/release`.++Both take the **unbound** `DBSession`, which is the inverse of the tenant+routes and load-bearing rather than an oversight: migration 123 admits the+global row only when `current_tenant_id()` is `NULL`, so a tenant-scoped+session is precisely the one that cannot write it. Because moving a+kill-switch route onto `TenantDBSession` is the repair the *tenant* routes+needed, `test_they_run_on_an_unbound_session` asserts the resolved+dependency so a future sweep cannot silently undo this.++Authorization is a new permission, `platform_kill_switch:write`, **not**+`settings:write`. A tenant administrator holds `settings:write`, and this+switch stops every *other* tenant on the deployment. No tenant-scoped role+is granted the new one; only the wildcard roles hold it, which is the+decision `workload_identities:*` already records for the same reason.+Migration 123 seeds it into the permission catalogue, because `092` has+already run everywhere and a new permission reaches an existing deployment+only through a new file.++Reading stays available to any authenticated user: a platform-wide stop a+tenant cannot see reads to them as an unexplained outage.++## The evidence++Three steps, in order, all executed against `postgres:16` with all 136+migrations applied and the application connected as `aisoc_app`.++### Step 1 — the test fails on the unfixed tree++```+tests/isolation/test_kill_switch_global_live.py+FAILED ...::test_an_unbound_session_can_engage_the_global_switch+FAILED ...::test_the_global_switch_can_be_released_again+FAILED ...::test_the_global_audit_row_can_be_written+FAILED ...::TestBothScopesAreVisibleToTheTenant::test_a_tenant_reads_the_global_switch+4 failed, 7 passed++ asyncpg.exceptions.InsufficientPrivilegeError: new row violates row-level+ security policy for table "aisoc_kill_switch"++services/api/tests/test_kill_switch.py+9 failed, 11 passed # the global routes answer 404+```++The 7 that pass are the per-tenant cases and the four negative properties.++### Step 2 — the fix++```+tests/isolation/test_kill_switch_global_live.py 11 passed+tests/isolation/test_kill_switch_endpoint_live.py 10 passed+tests/isolation/test_kill_switch_closure_live.py 4 passed+services/api/tests/test_kill_switch.py 20 passed+services/api tests/ 4974 passed, 164 skipped+```++The negative properties are asserted, not assumed. Engaging the global+switch does **not** widen anything:++- a tenant-bound session cannot write the global row;+- a tenant cannot write another tenant's row, or another tenant's audit row;+- an unbound session cannot write any tenant's row;+- one tenant cannot read another tenant's switch.++Through the product, a `tenant_admin` and an `infosec` analyst both receive+**403** on the global route and the global row stays absent, while the+`tenant_admin` can still stop their own tenant.++And the closure path observes it — which is what makes the control a+control. With the global switch engaged, `resolve_closure_policy` refuses a+confidence of 0.99 against a 0.50 bar with `source="kill_switch"`, for a+tenant that engaged nothing itself; releasing it resumes closure.++### Step 3 — negative controls++Three, each reverting one thing and leaving the rest in place.++**A. Policy reverted to 078, code intact.**++```+test_kill_switch_global_live.py 4 failed, 7 passed (identical signature to step 1)+test_kill_switch_endpoint_live.py 4 failed, 6 passed (the route 500s on the write)+```++The authorization cases still passed, which is what isolates this control to+the policy.++**B. Endpoint reverted, policy intact.**++```+services/api/tests/test_kill_switch.py 9 failed, 11 passed (identical signature to step 1)+test_kill_switch_endpoint_live.py 8 failed, 2 passed (404 on every global route)+```++**C. Policy reverted, closure suite.**++```+test_kill_switch_closure_live.py 4 failed+ asyncpg.exceptions.InsufficientPrivilegeError: new row violates row-level+ security policy for table "aisoc_kill_switch"+```++Restoring each returned every suite to green.++### Gates++```+scripts/check_rls_policy_shape.py OK — 160 surviving policies over 159 tables; 159 FORCEd+scripts/check_route_authz.py OK — 318 state-changing routes, 297 authorize,+ 21 identity-only (ceiling 21), 0 discarded+ruff format --check . 2614 files already formatted+ruff check services/ scripts/ tests/ tools/ All checks passed+scripts/check_mypy_baseline.py OK — no tree got worse (964 findings, 20 trees)+```++`kill-switch-live.yml` runs all three live suites on every pull request with+no `paths:` filter, and fails the job if the DSN resolves to a role holding+`SUPERUSER` or `BYPASSRLS` — a suite that cannot see a policy would+otherwise report the pre-fix tree healthy.++## Operator procedure++### Engaging the platform-wide stop++Requires `platform_kill_switch:write`, which only a wildcard role holds. The+reason is mandatory and must be at least 8 characters: the next operator has+to be able to tell a deliberate freeze from a forgotten test.++```bash+curl -sS -X POST https://<your-console>/api/v1/kill-switch/global/engage \+ -H "Authorization: Bearer $TOKEN" \+ -H 'Content-Type: application/json' \+ -d '{"reason": "triage agent closing alerts it should not have"}'+```++It takes effect within one poll of the closure cache, whose TTL is 10+seconds by default (`AISOC_CLOSURE_POLICY_TTL_SECONDS`). No restart and no+deploy.++Confirm from any authenticated account:++```bash+curl -sS https://<your-console>/api/v1/kill-switch -H "Authorization: Bearer $TOKEN"+# {"engaged": true, "scope": "global", "reason": "...", "engaged_by": "...", ...}+```++### Releasing it++```bash+curl -sS -X POST https://<your-console>/api/v1/kill-switch/global/release \+ -H "Authorization: Bearer $TOKEN" \+ -H 'Content-Type: application/json' \+ -d '{"reason": "root cause fixed, resuming"}'+```++Releasing when nothing is engaged answers **404** rather than reporting+success, because an operator who believes they released a stop that was not+there stops looking for the one that is.++A tenant that engaged its own switch keeps it: the two scopes are+independent and neither needs the other's agreement.++### The per-tenant switch++Unchanged. `POST /api/v1/kill-switch/engage` and `/release`, requiring+`settings:write`, acting on the caller's own tenant only. A tenant cannot+release a global switch; it is told so with a **409** rather than given a+success that changes nothing.++### Every change is audited++Both scopes write to `aisoc_kill_switch_audit` with the actor, the reason+and the scope (`global` or `tenant`).++## Still unreachable, and other limits++Stated rather than implied.++- **There is no console control for the kill switch, in either scope.**+ `apps/web` contains no kill-switch component; the per-tenant switch has+ been API-only since 078 and the global one now matches it. Engaging either+ means an API call or something that makes one. That is a real gap in+ first-run usability and is out of scope here.+- **`platform_kill_switch:write` is held only by the wildcard roles**+ (`platform_admin`, `admin`). There is no narrower role that can throw the+ platform switch without also holding everything else. Giving the stop its+ own grantable role is a product decision, not a defect.+- **The switch stops closure and dispatch, not ingestion.** Events keep+ arriving, detections keep firing and alerts keep being raised; what stops+ is automatic closure and action dispatch. An operator expecting silence+ will not get it.+- **`AISOC_CLOSURE_POLICY_TTL_SECONDS` is per process.** A deployment that+ raises it raises the delay before a stop takes effect, on every replica+ independently. The default of 10 seconds is what the measured behaviour+ above assumes.+- **No multi-replica test.** The suites drive one application process. The+ switch is a database row read by every replica, so there is no per-replica+ state to diverge, but that is an argument rather than a measurement.+- **Only closure honours the switch. Three of the four paths the docstring+ names do not consult it at all.** `endpoints/kill_switch.py` opens by+ saying the switch is "checked first and separately by everything that+ acts: closure in the triage worker, the actions dispatcher, playbook+ dispatch and the MCP write tools". Closure is real and is proven above:+ `auto_triage_agent.py` calls `closure_policy.decide(...)` on the+ production triage path, and that resolver checks the switch before+ anything else. The other three are not: `services/actions` contains no+ reference to `aisoc_kill_switch`, to `kill_switch_engaged` or to+ `app.closure` in any form, and neither does playbook dispatch or the MCP+ write surface.++ So **an engaged kill switch stops automatic closure and does not stop+ action dispatch.** That is a second, separate defect of the same family as+ this one, found while verifying this note rather than reported. It is not+ fixed here: the dispatcher is `services/actions`, the fix belongs with the+ governance chokepoint rather than beside an RLS policy, and the module+ that would carry the shared reader is owned by another in-flight change.+ Recorded so the docstring's claim is not read as a description of the+ current state — which is the exact trap `AGENTS.md` warns about, a+ docstring describing an intent rather than what the tree does.diff --git a/services/api/app/api/v1/endpoints/kill_switch.py b/services/api/app/api/v1/endpoints/kill_switch.pyindex 441ae40d0..dba6b487b 100644--- a/services/api/app/api/v1/endpoints/kill_switch.py+++ b/services/api/app/api/v1/endpoints/kill_switch.py@@ -44,6 +44,14 @@ logger = logging.getLogger(__name__)router = APIRouter(prefix="/kill-switch", tags=["autonomy"])+#: Deployment-wide authority, so deliberately **not** ``settings:write``.+#: A tenant administrator holds that one, and the platform switch stops every+#: other tenant on the deployment too. No tenant-scoped role in+#: ``ROLE_PERMISSIONS`` is granted this; only the wildcard roles hold it, which+#: is the same decision ``workload_identities:*`` records for the same reason.+#: Migration 123 seeds it into the permission catalog.+PLATFORM_KILL_SWITCH_PERMISSION = "platform_kill_switch:write"+class KillSwitchState(BaseModel):engaged: bool@@ -211,3 +219,126 @@ async def release(_sanitize(body.reason),)return KillSwitchState(engaged=False)+++# ── The platform-wide switch ────────────────────────────────────────────────+#+# These two are the surface that did not exist. The table has carried a global+# row since 078 and two readers consult it — the GET above and+# `kill_switch_engaged` in services/agents, on every alert — but every write in+# this module bound the caller's own tenant, so no endpoint, console control,+# CLI or script could set `tenant_id IS NULL`. The platform-wide stop was+# readable, documented, and reachable only from a psql prompt; and migration+# 078's WITH CHECK refused it even there for the role the services connect as.+#+# Both routes take the **unbound** `DBSession`, which is the inverse of the two+# tenant routes above and is load-bearing rather than an oversight: migration+# 123 admits the global row only when `current_tenant_id()` IS NULL, so a+# tenant-scoped session is precisely the one that cannot write it. Moving these+# onto `TenantDBSession` — the repair the tenant routes needed — would break the+# global switch again, so `test_they_run_on_an_unbound_session` asserts the+# resolved dependency rather than leaving it to a comment.+++ "/global/engage",+ response_model=KillSwitchState,+ status_code=status.HTTP_200_OK,+ summary="Freeze autonomous closure and action dispatch for every tenant",+)+async def engage_global(+ body: EngageRequest,+ db: DBSession,+ user: Annotated[AuthUser, Depends(require_permission(PLATFORM_KILL_SWITCH_PERMISSION))],+) -> KillSwitchState:+ """Stop autonomous closure and dispatch across the whole deployment.++ One row, upserted. The conflict target is the expression index+ `aisoc_kill_switch_global_idx ON aisoc_kill_switch ((TRUE)) WHERE tenant_id+ IS NULL`, which is what keeps the global switch a singleton rather than a+ pile of rows a reader would have to reconcile at 3am.+ """+ actor = getattr(user, "email", None) or str(getattr(user, "user_id", "unknown"))+ now = datetime.now(UTC)++ await db.execute(+ text("""+ INSERT INTO aisoc_kill_switch+ (id, tenant_id, engaged, reason, engaged_by, engaged_at, updated_at)+ VALUES (:id, NULL, TRUE, :reason, :actor, :now, :now)+ ON CONFLICT ((TRUE)) WHERE tenant_id IS NULL+ DO UPDATE SET engaged = TRUE,+ reason = EXCLUDED.reason,+ engaged_by = EXCLUDED.engaged_by,+ engaged_at = EXCLUDED.engaged_at,+ released_by = NULL,+ released_at = NULL,+ updated_at = EXCLUDED.updated_at+ """).bindparams(id=uuid.uuid4(), reason=body.reason, actor=actor, now=now)+ )+ await db.execute(+ text("""+ INSERT INTO aisoc_kill_switch_audit (id, tenant_id, action, reason, actor, scope)+ VALUES (:id, NULL, 'engage', :reason, :actor, 'global')+ """).bindparams(id=uuid.uuid4(), reason=body.reason, actor=actor)+ )+ await db.commit()++ logger.warning(+ "kill_switch.engaged scope=global actor=%s reason=%s",+ _sanitize(actor, 64),+ _sanitize(body.reason),+ )+ return KillSwitchState(engaged=True, scope="global", reason=body.reason, engaged_by=actor, engaged_at=now)+++ "/global/release",+ response_model=KillSwitchState,+ summary="Resume autonomous closure and action dispatch across every tenant",+)+async def release_global(+ body: ReleaseRequest,+ db: DBSession,+ user: Annotated[AuthUser, Depends(require_permission(PLATFORM_KILL_SWITCH_PERMISSION))],+) -> KillSwitchState:+ """Release the platform-wide stop.++ A tenant that engaged its own switch keeps it: the two scopes are+ independent and neither needs the other's agreement, so releasing globally+ must not silently resume a tenant that asked to stay stopped.+ """+ actor = getattr(user, "email", None) or str(getattr(user, "user_id", "unknown"))+ now = datetime.now(UTC)++ result = await db.execute(+ text("""+ UPDATE aisoc_kill_switch+ SET engaged = FALSE, released_by = :actor, released_at = :now, updated_at = :now+ WHERE tenant_id IS NULL AND engaged = TRUE+ RETURNING id+ """).bindparams(actor=actor, now=now)+ )+ if result.first() is None:+ # Saying so beats reporting success over a switch that was never+ # engaged: an operator who believes they released a stop that is not+ # there stops looking for the one that is.+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail="No platform-wide kill switch is engaged.",+ )++ await db.execute(+ text("""+ INSERT INTO aisoc_kill_switch_audit (id, tenant_id, action, reason, actor, scope)+ VALUES (:id, NULL, 'release', :reason, :actor, 'global')+ """).bindparams(id=uuid.uuid4(), reason=body.reason, actor=actor)+ )+ await db.commit()++ logger.warning(+ "kill_switch.released scope=global actor=%s reason=%s",+ _sanitize(actor, 64),+ _sanitize(body.reason),+ )+ return KillSwitchState(engaged=False)diff --git a/services/api/app/core/rbac_catalog.py b/services/api/app/core/rbac_catalog.pyindex 134a9e05b..ac2d47c15 100644--- a/services/api/app/core/rbac_catalog.py+++ b/services/api/app/core/rbac_catalog.py@@ -99,6 +99,12 @@ PERMISSIONS: Final[tuple[tuple[str, str, str], ...]] = (("plugins:read", "View plugins", "plugins"),("plugins:admin", "Administer plugins", "plugins"),("plugins:execute", "Execute plugins", "plugins"),+ # The platform-wide stop over autonomous closure and action dispatch.+ # Deployment-wide authority, so no tenant-scoped role is granted it: the+ # switch freezes every *other* tenant too, and `settings:write` — which a+ # tenant administrator holds — would have handed that reach to all of+ # them. Seeded by migration 123; see `endpoints/kill_switch.py`.+ ("platform_kill_switch:write", "Engage or release the platform-wide kill switch", "system"),("*", "Every permission (wildcard; admin role)", "system"),)diff --git a/services/api/migrations/123_kill_switch_global_engageable.sql b/services/api/migrations/123_kill_switch_global_engageable.sqlnew file mode 100644index 000000000..f08d94497--- /dev/null+++ b/services/api/migrations/123_kill_switch_global_engageable.sql@@ -0,0 +1,96 @@+-- The platform-wide kill switch can be engaged by the runtime role.+--+-- What was wrong+-- --------------+-- 078 created `aisoc_kill_switch` with a global row (`tenant_id IS NULL`)+-- and the policy+--+-- USING (tenant_id IS NULL OR tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)+-- WITH CHECK (tenant_id = current_tenant_id())+--+-- and its own comment says the global row "is written by the platform+-- operator through a session with no tenant set". That is the one case the+-- check rejects. `current_tenant_id()` returns NULL for an unset or empty+-- setting, so the global row is judged `NULL = NULL` on an unbound session+-- and `NULL = '<uuid>'` on a bound one. Both are NULL, and a WITH CHECK+-- that does not evaluate to true refuses the row.+--+-- The effect was a stop button with two readers — `GET /kill-switch` and+-- `kill_switch_engaged` in services/agents, which consults it on every+-- alert — and no session that could ever have written it. Reproduced+-- against postgres:16 with this chain applied, connected as the+-- NOSUPERUSER NOBYPASSRLS `aisoc_app` role:+--+-- INSERT INTO aisoc_kill_switch (tenant_id, ...) VALUES (NULL, ...);+-- ERROR: new row violates row-level security policy for table "aisoc_kill_switch"+--+-- unbound and bound alike, while the same INSERT for the session's own+-- tenant returned INSERT 0 1. The per-tenant half has always worked; only+-- the platform-wide half was unreachable.+--+-- The shape of the fix+-- --------------------+-- Dropping WITH CHECK would make the table writable and tenant isolation+-- decorative — an unbound worker could then write into any tenant. A global+-- row is legitimately not tenant-scoped, so the policy expresses that+-- distinction instead:+--+-- WITH CHECK (tenant_id = current_tenant_id()+-- OR (tenant_id IS NULL AND current_tenant_id() IS NULL))+--+-- Read as a truth table over the two things a session can be, this says+-- "you may write exactly the row that is yours":+--+-- session row decision+-- --------- ------------ ------------------------------------------+-- unbound global allowed — the platform operator's own row+-- unbound a tenant's refused — NULL OR FALSE is NULL+-- tenant A global refused — a tenant cannot freeze everyone+-- tenant A A's own allowed — unchanged from 078+-- tenant A tenant B's refused — unchanged from 078+--+-- Three of those five were already refused by 078 and stay refused. The+-- only behaviour that changes is the first: an unbound session gains the+-- global row and nothing else. In particular a tenant still cannot write+-- the global row, so this does not hand any tenant administrator a switch+-- that stops every other tenant on the deployment.+--+-- `aisoc_kill_switch_audit` carries the same strict check and the same fix.+-- Without it a switch that could be thrown would still have failed on its+-- audit row, and an emergency stop nobody can account for afterwards is a+-- different defect rather than a smaller one.+--+-- The USING clauses are re-stated unchanged. They already admit the global+-- row to every session, which is deliberate: a platform-wide stop a tenant+-- cannot see reads to them as an unexplained outage.++DROP POLICY IF EXISTS tenant_isolation ON aisoc_kill_switch;+CREATE POLICY tenant_isolation ON aisoc_kill_switch+ USING (tenant_id IS NULL OR tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)+ WITH CHECK (+ tenant_id = current_tenant_id()+ OR (tenant_id IS NULL AND current_tenant_id() IS NULL)+ );++DROP POLICY IF EXISTS tenant_isolation ON aisoc_kill_switch_audit;+CREATE POLICY tenant_isolation ON aisoc_kill_switch_audit+ USING (tenant_id IS NULL OR tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)+ WITH CHECK (+ tenant_id = current_tenant_id()+ OR (tenant_id IS NULL AND current_tenant_id() IS NULL)+ );++-- ── The permission that gates the routes ────────────────────────────────+--+-- Engaging the platform-wide stop is deployment-wide authority, so it is+-- not `settings:write`: a tenant administrator holds that one, and this+-- switch stops every *other* tenant too. It is seeded here rather than only+-- declared in `app/core/rbac_catalog.py` because 092 has already run on+-- every deployment and the runner tracks applied files, so a new permission+-- reaches an existing catalog only through a new migration. Same reasoning+-- as `workload_identities:*`: no tenant-scoped role is granted it, and only+-- the wildcard roles hold it.++INSERT INTO permissions (name, description, category) VALUES+ ('platform_kill_switch:write', 'Engage or release the platform-wide kill switch', 'system')+ON CONFLICT (name) DO NOTHING;diff --git a/services/api/tests/test_kill_switch.py b/services/api/tests/test_kill_switch.pyindex 2656c4f58..bcfb5b864 100644--- a/services/api/tests/test_kill_switch.py+++ b/services/api/tests/test_kill_switch.py@@ -13,9 +13,18 @@ import inspectimport pytestfrom app.api.v1.endpoints import kill_switch+from app.core.rbac_catalog import PERMISSIONS+from app.core.security import ROLE_PERMISSIONS+from app.db.database import get_dbfrom app.main import appfrom fastapi.testclient import TestClient+#: The permission the platform-wide routes require. Read from the module so+#: the test cannot keep passing against a renamed constant, and defaulted so+#: that a tree without the surface fails each assertion with its own reason+#: rather than aborting collection and taking the rest of this file with it.+PLATFORM_KILL_SWITCH = getattr(kill_switch, "PLATFORM_KILL_SWITCH_PERMISSION", "<no platform kill-switch permission is declared>")+#: One client for the module. Resolution is by **sending a request**, not#: by walking `app.routes`: that is not the route table and what it holds#: changes with the FastAPI minor, which made the sibling compliance file@@ -39,6 +48,41 @@ def _handler_for(path: str, method: str = "GET") -> str | None:return operation.get("operationId", "").split("_api_v1_")[0] or None+def _route_object(path: str, method: str):+ """The router's own route, for assertions about the dependency tree.++ Taken off ``kill_switch.router`` rather than ``app.routes``: what the+ latter holds changes with the FastAPI minor, and a gate that enumerated it+ once compared zero pairs and reported success.+ """+ for route in kill_switch.router.routes:+ if route.path == path and method in set(getattr(route, "methods", set())):+ return route+ raise AssertionError(f"no route {method} {path}")+++def _required_permissions(route) -> set[str]:+ """Every permission the route's dependency tree actually resolves.++ ``require_permission`` returns a closure, so the permission it enforces+ lives in that closure's cells rather than anywhere readable from the+ route. Walking the resolved tree is what makes this an assertion about+ enforcement instead of about spelling.+ """+ found: set[str] = set()++ def walk(dependant) -> None:+ call = dependant.call+ closure = getattr(call, "__closure__", None) or ()+ if getattr(call, "__name__", "") == "_check":+ found.update(cell.cell_contents for cell in closure if isinstance(cell.cell_contents, str))+ for sub in dependant.dependencies:+ walk(sub)++ walk(route.dependant)+ return found++class TestTheRoutesExist:@pytest.mark.parametrize(("path", "method", "handler"),@@ -96,6 +140,81 @@ class TestItIsAudited:assert len(kill_switch._sanitize("x" * 5000)) <= 200+class TestThePlatformSwitchHasASurface:+ """The global switch had two readers and no writer.++ Every write in this module bound ``t=user.tenant_id``, so the only scope+ any caller could reach was their own tenant, while ``GET /kill-switch``+ and ``services/agents`` ``kill_switch_engaged`` both consult the global+ row on every alert. A reader over a table nothing writes is not a+ control, and this one was labelled an emergency stop.+ """++ @pytest.mark.parametrize(+ ("path", "handler"),+ [+ ("/api/v1/kill-switch/global/engage", "engage_global"),+ ("/api/v1/kill-switch/global/release", "release_global"),+ ],+ )+ def test_the_global_routes_exist(self, path: str, handler: str) -> None:+ assert _reaches_a_route(path, "POST"), f"POST {path} answers 404, so the platform-wide stop has no product surface"+ assert _handler_for(path, "POST") == handler++ @pytest.mark.parametrize("verb", ["engage", "release"])+ def test_they_require_the_platform_permission(self, verb: str) -> None:+ """Not ``settings:write``. A tenant administrator holds that, and the+ global switch stops every *other* tenant on the deployment too.++ Read off the **resolved** dependency tree rather than the handler's+ source. A substring assertion would pass on+ ``Annotated[Any, require_permission(...)]`` with no ``Depends()``,+ which FastAPI silently drops — that exact shape left eleven routes+ reading as gated while enforcing nothing.+ """+ required = _required_permissions(_route_object(f"/kill-switch/global/{verb}", "POST"))+ assert PLATFORM_KILL_SWITCH in required, (+ f"{verb}_global resolves {sorted(required) or 'no permission check'}, not {PLATFORM_KILL_SWITCH}, "+ "so it is reachable by a principal whose authority stops at their own tenant"+ )++ def test_no_tenant_scoped_role_holds_it(self) -> None:+ """The permission is the authorization. If a tenant role held it,+ requiring it would be theatre."""+ holders = [role for role, perms in ROLE_PERMISSIONS.items() if PLATFORM_KILL_SWITCH in perms]+ assert holders == [], (+ f"{PLATFORM_KILL_SWITCH} is granted to {holders}, which are tenant-scoped roles. "+ "Only the wildcard roles may freeze the whole deployment."+ )+ wildcard = [role for role, perms in ROLE_PERMISSIONS.items() if "*" in perms]+ assert wildcard, "no role holds the wildcard, so nobody could ever engage the platform switch"++ def test_it_is_in_the_seeded_catalog(self) -> None:+ """A permission absent from the catalog renders blank on the Roles+ screen and cannot be granted to a custom role."""+ assert PLATFORM_KILL_SWITCH in {name for name, _d, _c in PERMISSIONS}++ @pytest.mark.parametrize("name", ["engage_global", "release_global"])+ def test_they_run_on_an_unbound_session(self, name: str) -> None:+ """The inverse of the tenant routes, and load-bearing rather than an+ oversight: the global row is admitted by ``WITH CHECK`` only when+ ``current_tenant_id()`` is NULL, so a tenant-scoped session is exactly+ the one that cannot write it.++ Asserted on the resolved dependency so it cannot drift into+ ``get_tenant_db`` the way the tenant routes once drifted out of it.+ """+ route = _route_object("/kill-switch/global/" + name.split("_")[0], "POST")+ db = next((d.call for d in route.dependant.dependencies if d.name == "db"), None)+ assert db is get_db, f"{name} must take the unbound session; a tenant-bound one cannot write the global row"++ @pytest.mark.parametrize("name", ["engage_global", "release_global"])+ def test_both_transitions_are_audited_as_global(self, name: str) -> None:+ source = inspect.getsource(getattr(kill_switch, name))+ assert "aisoc_kill_switch_audit" in source, f"{name} writes no audit row"+ assert "'global'" in source, f"{name} does not record the scope as global"++class TestReleasingAGlobalSwitch:def test_a_tenant_cannot_release_the_platform_switch(self) -> None:"""And is told so, rather than getting a success that changesdiff --git a/tests/isolation/test_kill_switch_closure_live.py b/tests/isolation/test_kill_switch_closure_live.pynew file mode 100644index 000000000..36b589086--- /dev/null+++ b/tests/isolation/test_kill_switch_closure_live.py@@ -0,0 +1,164 @@+"""An engaged platform switch actually stops automatic closure.++Why this exists separately+--------------------------+``test_kill_switch_global_live.py`` proves the row can be written and+``test_kill_switch_endpoint_live.py`` proves a product surface writes it.+Neither proves the thing the switch is *for*. This repository treats a+control nothing consults as not existing, and the global row spent its whole+life in exactly that state — readable, documented, and written by nothing —+so asserting that the reader honours it is the half that makes the other two+worth having.++This runs against ``services/agents``, whose ``app`` package owns+``closure.policy``. ``services/api`` ships a different package by the same+name, so importing one shadows the other; the live workflow runs this leg+from ``services/agents`` for that reason, exactly as+``test_closure_grant_live.py`` does.++No ``importorskip`` on ``app.closure.policy``. A skip in a job whose purpose+is to run this live is indistinguishable from a pass, and that shape has+shipped here before.+"""++from __future__ import annotations++import os+import uuid++import pytest+import pytest_asyncio++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_KILL_SWITCH_DSN", "").strip(),+ reason="ISOLATION_KILL_SWITCH_DSN is not set; this suite needs a live Postgres",+ ),+]++#: Well above any configured threshold, so a verdict that is refused here was+#: refused by the switch rather than by confidence.+CERTAIN = 0.99+++def _dsn() -> str:+ value = os.environ.get("ISOLATION_KILL_SWITCH_DSN", "").strip()+ if not value:+ pytest.skip("ISOLATION_KILL_SWITCH_DSN is not set")+ return value.replace("postgresql+asyncpg://", "postgresql://")+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def pool():+ asyncpg = pytest.importorskip("asyncpg")+ created = await asyncpg.create_pool(_dsn(), min_size=1, max_size=4)+ yield created+ await created.close()+++@pytest_asyncio.fixture(loop_scope="module", autouse=True)+async def _clean(pool):+ """Clear the singleton global row, and drop the resolver's cache.++ The cache is a 10-second TTL keyed per tenant, so without this a test+ that engages the switch would still be answered from the state the+ previous test left behind.+ """+ from app.closure.policy import reset_cache++ reset_cache()+ yield+ async with pool.acquire() as conn:+ await conn.execute("DELETE FROM aisoc_kill_switch WHERE tenant_id IS NULL")+ reset_cache()+++async def _tenant(pool) -> str:+ tenant_id = str(uuid.uuid4())+ async with pool.acquire() as conn:+ await conn.execute(+ "INSERT INTO tenants (id, name, slug) VALUES ($1::uuid, $2, $3)",+ tenant_id,+ "ks-closure",+ f"ksc-{tenant_id[:8]}",+ )+ return tenant_id+++async def _engage_globally(pool, reason: str) -> None:+ async with pool.acquire() as conn:+ await conn.execute(+ """+ INSERT INTO aisoc_kill_switch (tenant_id, engaged, reason, engaged_by)+ VALUES (NULL, TRUE, $1, 'operator')+ ON CONFLICT ((TRUE)) WHERE tenant_id IS NULL+ DO UPDATE SET engaged = TRUE, reason = EXCLUDED.reason, released_by = NULL, released_at = NULL+ """,+ reason,+ )+++class TestTheClosurePathObservesTheGlobalSwitch:+ async def test_an_engaged_global_switch_refuses_closure(self, pool) -> None:+ """The reader is `services/agents` `kill_switch_engaged`, which the+ closure resolver calls first and separately from the policy."""+ from app.closure.policy import kill_switch_engaged, reset_cache++ tenant_id = await _tenant(pool)+ await _engage_globally(pool, "platform-wide stop")+ reset_cache()++ engaged, why = await kill_switch_engaged(pool, tenant_id)++ assert engaged is True, "the closure path did not observe an engaged platform kill switch"+ assert "global" in why, f"the reason does not name the scope an operator has to go and release: {why!r}"++ async def test_it_refuses_a_verdict_the_threshold_would_have_closed(self, pool) -> None:+ """Through `resolve_closure_policy`, which is what the triage path+ calls. A confidence of 0.99 against a 0.50 bar closes on any other+ day, so the refusal is attributable to the switch alone."""+ from app.closure.policy import reset_cache, resolve_closure_policy++ tenant_id = await _tenant(pool)+ await _engage_globally(pool, "platform-wide stop")+ reset_cache()++ decision = await resolve_closure_policy(pool, tenant_id=tenant_id, alert_class=None, confidence=CERTAIN, default_threshold=0.50)++ assert decision.allowed is False+ assert decision.source == "kill_switch", f"refused for the wrong reason: {decision.source} / {decision.reason}"++ async def test_a_tenant_that_engaged_nothing_is_still_stopped(self, pool) -> None:+ """The global switch is the platform operator's and does not need any+ tenant's agreement. A stop that only covered tenants who had opted in+ would not be a platform-wide stop."""+ from app.closure.policy import kill_switch_engaged, reset_cache++ first = await _tenant(pool)+ second = await _tenant(pool)+ await _engage_globally(pool, "platform-wide stop")+ reset_cache()++ assert (await kill_switch_engaged(pool, first))[0] is True+ assert (await kill_switch_engaged(pool, second))[0] is True++ async def test_releasing_it_resumes_closure(self, pool) -> None:+ """The negative control for this file. Without it, a reader that+ returned True unconditionally would satisfy every assertion above."""+ from app.closure.policy import kill_switch_engaged, reset_cache, resolve_closure_policy++ tenant_id = await _tenant(pool)+ await _engage_globally(pool, "platform-wide stop")+ reset_cache()+ assert (await kill_switch_engaged(pool, tenant_id))[0] is True++ async with pool.acquire() as conn:+ await conn.execute("UPDATE aisoc_kill_switch SET engaged = FALSE WHERE tenant_id IS NULL")+ reset_cache()++ engaged, _why = await kill_switch_engaged(pool, tenant_id)+ decision = await resolve_closure_policy(pool, tenant_id=tenant_id, alert_class=None, confidence=CERTAIN, default_threshold=0.50)++ assert engaged is False, "closure stayed frozen after the switch was released"+ assert decision.allowed is True, f"closure did not resume after release: {decision.reason}"diff --git a/tests/isolation/test_kill_switch_endpoint_live.py b/tests/isolation/test_kill_switch_endpoint_live.pynew file mode 100644index 000000000..5c038bf81--- /dev/null+++ b/tests/isolation/test_kill_switch_endpoint_live.py@@ -0,0 +1,287 @@+"""The platform-wide kill switch is reachable through the product.++``test_kill_switch_global_live.py`` proves the row-level security policy+admits the global row. That is necessary and not sufficient: before this+change there was no caller at all. Every write in+``services/api/app/api/v1/endpoints/kill_switch.py`` bound+``t=user.tenant_id``, so the only scope any principal could reach was their+own tenant, while two readers consulted the global row on every alert. A+control nothing can reach is not a control, so this drives the real routes.++What this exercises that a unit test cannot+-------------------------------------------+The real ASGI application with its real authentication dependencies, a real+sign-in, and a real Postgres the app connects to as the runtime role. The+defect class this repository keeps finding is a double more capable than the+real thing — a session that answers any query, a fake that never reaches the+transport. Here the interesting question is specifically whether the handler's+session can write a row the policy judges, which only a real connection as a+real role can answer.++The authorization half is the point, not a detail. ``settings:write`` was the+obvious permission to reuse and would have been wrong: a tenant administrator+holds it, and the platform switch freezes every *other* tenant on the+deployment too. :class:`TestOnlyThePlatformOperatorMayEngageIt` is what holds+that line.+"""++from __future__ import annotations++import os+import uuid+from collections.abc import AsyncIterator+from typing import TYPE_CHECKING++import pytest+import pytest_asyncio++if TYPE_CHECKING:+ # Import-time only. A module-scope import of httpx or SQLAlchemy takes the+ # offline collection job down with it, which once cost 241 unrelated+ # tests; the fixtures import them for real.+ import httpx+ from sqlalchemy.ext.asyncio import AsyncSession++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_KILL_SWITCH_DSN", "").strip(),+ reason="ISOLATION_KILL_SWITCH_DSN is not set; this suite needs a live Postgres",+ ),+]++# Named for what it is: as `PASSWORD` the secret scanner reads the literal as+# a credential, and a `.gitleaksignore` entry is fingerprinted on the line+# number, so any later edit to this file would reopen the finding.+TEST_PASSPHRASE = "correct-horse-battery-staple-42"++#: Long enough to satisfy the mandatory-reason floor on both request models.+REASON = "the agent was closing alerts it should not have"+++def _dsn() -> str:+ value = os.environ.get("ISOLATION_KILL_SWITCH_DSN", "").strip()+ if not value:+ pytest.skip("ISOLATION_KILL_SWITCH_DSN is not set")+ return value+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def app_client() -> AsyncIterator[httpx.AsyncClient]:+ pytest.importorskip("httpx")+ os.environ["DATABASE_URL"] = _dsn()+ # Not "development": that is in AUTH_BYPASS_ENVIRONMENTS, so an+ # uncredentialed request would resolve to a demo admin — inside the one+ # suite whose subject is which principal may throw the switch.+ os.environ["ENVIRONMENT"] = "test"++ import httpx+ from app.main import create_application++ transport = httpx.ASGITransport(app=create_application())+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ yield client+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def db() -> AsyncIterator[AsyncSession]:+ pytest.importorskip("asyncpg")+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++ engine = create_async_engine(_dsn(), future=True)+ maker = async_sessionmaker(engine, expire_on_commit=False)+ async with maker() as session:+ yield session+ await engine.dispose()+++@pytest_asyncio.fixture(loop_scope="module", autouse=True)+async def _clear_the_global_switch(db: AsyncSession) -> AsyncIterator[None]:+ """The global row is a singleton, so one test's switch is the next test's+ starting state."""+ import sqlalchemy++ yield+ await db.rollback()+ await db.execute(sqlalchemy.text("DELETE FROM aisoc_kill_switch WHERE tenant_id IS NULL"))+ await db.commit()+++async def _user(session: AsyncSession, *, role: str) -> dict:+ """A real user row with a real bcrypt hash, in its own tenant."""+ import sqlalchemy+ from app.core.security import get_password_hash++ await session.rollback()+ tenant_id = uuid.uuid4()+ await session.execute(+ sqlalchemy.text("INSERT INTO tenants (id, name, slug) VALUES (:i, :n, :s)"),+ {"i": tenant_id, "n": f"ks-{tenant_id.hex[:8]}", "s": f"ks-{tenant_id.hex[:8]}"},+ )+ user_id = uuid.uuid4()+ email = f"u-{user_id.hex[:10]}@example.com"+ await session.execute(+ sqlalchemy.text(+ "INSERT INTO users (id, tenant_id, email, username, role, is_active, hashed_password) VALUES (:i, :t, :e, :u, :r, TRUE, :p)"+ ),+ {"i": user_id, "t": tenant_id, "e": email, "u": email.split("@")[0], "r": role, "p": get_password_hash(TEST_PASSPHRASE)},+ )+ await session.commit()+ return {"id": user_id, "tenant_id": tenant_id, "email": email, "role": role}+++async def _bearer(client: httpx.AsyncClient, user: dict) -> dict[str, str]:+ response = await client.post("/api/v1/auth/login", json={"email": user["email"], "password": TEST_PASSPHRASE})+ assert response.status_code == 200, response.text+ return {"Authorization": f"Bearer {response.json()['access_token']}"}+++async def _global_row(db: AsyncSession):+ import sqlalchemy++ await db.rollback()+ return (+ await db.execute(sqlalchemy.text("SELECT engaged, reason, engaged_by, released_by FROM aisoc_kill_switch WHERE tenant_id IS NULL"))+ ).first()+++class TestThePlatformOperatorCanThrowIt:+ async def test_engaging_writes_the_global_row(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ """The whole point, end to end. Against the pre-fix tree this is a+ 404: the route did not exist."""+ operator = await _user(db, role="admin")+ headers = await _bearer(app_client, operator)++ response = await app_client.post("/api/v1/kill-switch/global/engage", json={"reason": REASON}, headers=headers)++ assert response.status_code == 200, response.text+ assert response.json()["engaged"] is True+ assert response.json()["scope"] == "global"++ row = await _global_row(db)+ assert row is not None, "the endpoint reported success and wrote no global row"+ assert row.engaged is True+ assert row.reason == REASON+ assert row.engaged_by == operator["email"]++ async def test_engaging_is_audited_as_global(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ """An emergency stop nobody can account for afterwards is its own+ defect. The audit table carries the same strict check as the switch,+ so this would have failed even once the switch itself worked."""+ import sqlalchemy++ operator = await _user(db, role="admin")+ headers = await _bearer(app_client, operator)++ await app_client.post("/api/v1/kill-switch/global/engage", json={"reason": REASON}, headers=headers)++ await db.rollback()+ rows = (+ await db.execute(+ sqlalchemy.text(+ "SELECT actor, action FROM aisoc_kill_switch_audit WHERE tenant_id IS NULL AND scope = 'global' AND actor = :a"+ ),+ {"a": operator["email"]},+ )+ ).fetchall()+ assert [r.action for r in rows] == ["engage"]++ async def test_releasing_clears_it(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ operator = await _user(db, role="admin")+ headers = await _bearer(app_client, operator)+ await app_client.post("/api/v1/kill-switch/global/engage", json={"reason": REASON}, headers=headers)++ response = await app_client.post(+ "/api/v1/kill-switch/global/release", json={"reason": "the agent is behaving again"}, headers=headers+ )++ assert response.status_code == 200, response.text+ row = await _global_row(db)+ assert row.engaged is False+ assert row.released_by == operator["email"]++ async def test_releasing_a_switch_nobody_engaged_is_a_404(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ """Rather than a success that changed nothing. An operator who+ believes they released a stop that was not there stops looking for+ the one that is."""+ operator = await _user(db, role="admin")+ headers = await _bearer(app_client, operator)++ response = await app_client.post("/api/v1/kill-switch/global/release", json={"reason": "nothing is engaged"}, headers=headers)++ assert response.status_code == 404, response.text++ async def test_a_reason_is_mandatory(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ """A switch with no reason is one nobody can safely disengage."""+ operator = await _user(db, role="admin")+ headers = await _bearer(app_client, operator)++ response = await app_client.post("/api/v1/kill-switch/global/engage", json={"reason": "x"}, headers=headers)++ assert response.status_code == 422, response.text+ assert await _global_row(db) is None+++class TestOnlyThePlatformOperatorMayEngageIt:+ """The authorization property. ``settings:write`` would have been the+ convenient permission and the wrong one."""++ async def test_a_tenant_admin_is_refused(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ """A tenant administrator holds ``settings:write`` and can stop their+ own tenant. Letting that reach the global switch would let any+ customer freeze every other customer on the deployment."""+ tenant_admin = await _user(db, role="tenant_admin")+ headers = await _bearer(app_client, tenant_admin)++ response = await app_client.post("/api/v1/kill-switch/global/engage", json={"reason": REASON}, headers=headers)++ assert response.status_code == 403, response.text+ assert await _global_row(db) is None, "a refused request still wrote the global row"++ async def test_an_analyst_is_refused(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ analyst = await _user(db, role="infosec")+ headers = await _bearer(app_client, analyst)++ response = await app_client.post("/api/v1/kill-switch/global/engage", json={"reason": REASON}, headers=headers)++ assert response.status_code == 403, response.text++ async def test_an_unauthenticated_caller_is_refused(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ response = await app_client.post("/api/v1/kill-switch/global/engage", json={"reason": REASON})++ assert response.status_code in (401, 403), response.text+ assert await _global_row(db) is None++ async def test_a_tenant_admin_can_still_stop_their_own_tenant(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ """The working half, through the product rather than through SQL. A+ fix that locked the platform switch down by breaking this would have+ traded one unreachable stop for another."""+ tenant_admin = await _user(db, role="tenant_admin")+ headers = await _bearer(app_client, tenant_admin)++ response = await app_client.post("/api/v1/kill-switch/engage", json={"reason": REASON}, headers=headers)++ assert response.status_code == 200, response.text+ assert response.json()["scope"] == "tenant"+++class TestATenantSeesThePlatformStop:+ """A platform-wide stop a tenant cannot see reads to them as an+ unexplained outage, so the read is deliberately not behind a permission."""++ async def test_an_analyst_reads_the_global_switch(self, app_client: httpx.AsyncClient, db: AsyncSession) -> None:+ operator = await _user(db, role="admin")+ await app_client.post(+ "/api/v1/kill-switch/global/engage",+ json={"reason": REASON},+ headers=await _bearer(app_client, operator),+ )+ analyst = await _user(db, role="infosec")++ response = await app_client.get("/api/v1/kill-switch", headers=await _bearer(app_client, analyst))++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["engaged"] is True+ assert body["scope"] == "global"+ assert body["reason"] == REASONdiff --git a/tests/isolation/test_kill_switch_global_live.py b/tests/isolation/test_kill_switch_global_live.pynew file mode 100644index 000000000..b13fb64b4--- /dev/null+++ b/tests/isolation/test_kill_switch_global_live.py@@ -0,0 +1,351 @@+"""The platform-wide kill switch can actually be engaged.++What was wrong+--------------+``078_closure_policy_and_kill_switch.sql`` gives ``aisoc_kill_switch`` the+policy::++ USING (tenant_id IS NULL OR tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)+ WITH CHECK (tenant_id = current_tenant_id())++The global row is the one with ``tenant_id IS NULL``. Judged by that+``WITH CHECK`` it is unwritable by **every** session the runtime role can+open, and the two cases fail for different reasons that both land on the+same refusal:++* no tenant bound — ``NULL = NULL`` is ``NULL``, and a ``WITH CHECK`` that+ does not evaluate to true refuses the row;+* a tenant bound — ``NULL = '<uuid>'`` is ``NULL``, same refusal.++So the ``USING`` clause lets every tenant *read* a global stop that no+session could ever have written. The table's own comment says the global row+"is written by the platform operator through a session with no tenant set",+which is the one case the check rejects.++The half that was not reported+------------------------------+The policy is only half of it. Before the fix, **no code in the tree wrote+the global row at all** — every write in ``kill_switch.py`` binds+``t=user.tenant_id``, so the only reachable scope was the caller's own+tenant. There was no endpoint, console control, CLI or script that could set+``tenant_id IS NULL``, while two readers (the endpoint's ``GET`` and+``services/agents`` ``kill_switch_engaged``) consult it on every alert. A+reader over a table nothing writes is the shape ``AGENTS.md`` calls out, and+here it was wearing the label of an emergency stop.++Why this suite connects as ``aisoc_app``+----------------------------------------+Because the defect is invisible from any other role. ``061_runtime_app_role``+makes ``aisoc_app`` ``NOSUPERUSER NOBYPASSRLS``, and both tables are ``FORCE+ROW LEVEL SECURITY``; a superuser ignores policies entirely, so seeding the+global row as the migration role succeeds and proves nothing. That is+precisely the workaround that hid this, so :func:`_refuse_a_vacuous_run`+fails the suite rather than skipping when the DSN resolves to a role that can+walk past a policy.++Against the pre-fix tree every assertion in+:class:`TestTheGlobalSwitchIsEngageable` fails with+``new row violates row-level security policy for table "aisoc_kill_switch"``.+"""++from __future__ import annotations++import os+import uuid++import pytest+import pytest_asyncio++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_KILL_SWITCH_DSN", "").strip(),+ reason="ISOLATION_KILL_SWITCH_DSN is not set; this suite needs a live Postgres",+ ),+]++#: The sentinel an unbound session carries. ``current_tenant_id()`` maps both+#: an unset and an empty setting to NULL, so clearing is how a connection+#: becomes the platform operator rather than a tenant.+_UNBOUND = ""+++def _dsn() -> str:+ value = os.environ.get("ISOLATION_KILL_SWITCH_DSN", "").strip()+ if not value:+ pytest.skip("ISOLATION_KILL_SWITCH_DSN is not set")+ return value.replace("postgresql+asyncpg://", "postgresql://")+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def pool():+ asyncpg = pytest.importorskip("asyncpg")+ created = await asyncpg.create_pool(_dsn(), min_size=1, max_size=4)+ yield created+ await created.close()+++@pytest_asyncio.fixture(scope="module", loop_scope="module", autouse=True)+async def _refuse_a_vacuous_run(pool) -> None:+ """A role that bypasses RLS would pass every assertion below.++ This suite's whole subject is what a policy does to the runtime role. Run+ as the owner or a superuser it is not a weaker test, it is a test of+ nothing, and it would have reported the pre-fix tree healthy.+ """+ async with pool.acquire() as conn:+ row = await conn.fetchrow("SELECT current_user AS who, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user")+ forced = await conn.fetchval(+ "SELECT bool_and(relforcerowsecurity) FROM pg_class WHERE relname IN ('aisoc_kill_switch', 'aisoc_kill_switch_audit')"+ )++ assert not row["rolsuper"], (+ f"connected as {row['who']}, which is a SUPERUSER and ignores every row-level security "+ "policy. Point ISOLATION_KILL_SWITCH_DSN at the aisoc_app runtime role."+ )+ assert not row["rolbypassrls"], f"connected as {row['who']}, which holds BYPASSRLS, so no policy below is in force"+ assert forced is True, (+ "aisoc_kill_switch / aisoc_kill_switch_audit are not FORCE ROW LEVEL SECURITY, so the table owner "+ "walks past the policy and this suite cannot see what a tenant session sees"+ )+++async def _tenant(pool) -> str:+ """A tenant row, created on an unbound connection.++ ``tenants`` is not the table under test and creating one needs no tenant+ context, so this deliberately does not go through the bound path.+ """+ tenant_id = str(uuid.uuid4())+ async with pool.acquire() as conn:+ await _bind(conn, _UNBOUND)+ await conn.execute(+ "INSERT INTO tenants (id, name, slug) VALUES ($1::uuid, $2, $3)",+ tenant_id,+ "kill-switch",+ f"ks-{tenant_id[:8]}",+ )+ return tenant_id+++async def _bind(conn, tenant_id: str) -> None:+ """Bind, or clear with ``_UNBOUND``. Session scope, not ``SET LOCAL``:+ these connections run statements outside an explicit transaction."""+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, false)", tenant_id)+++async def _engage(conn, tenant_id: str | None, *, reason: str, actor: str = "operator") -> None:+ """Engage, upserting on whichever of the two unique indexes applies.++ The global index is ``ON aisoc_kill_switch ((TRUE)) WHERE tenant_id IS+ NULL``, so its conflict target is the expression rather than the column.+ """+ if tenant_id is None:+ await conn.execute(+ """+ INSERT INTO aisoc_kill_switch (tenant_id, engaged, reason, engaged_by)+ VALUES (NULL, TRUE, $1, $2)+ ON CONFLICT ((TRUE)) WHERE tenant_id IS NULL+ DO UPDATE SET engaged = TRUE, reason = EXCLUDED.reason, engaged_by = EXCLUDED.engaged_by,+ released_by = NULL, released_at = NULL+ """,+ reason,+ actor,+ )+ return+ await conn.execute(+ """+ INSERT INTO aisoc_kill_switch (tenant_id, engaged, reason, engaged_by)+ VALUES ($1::uuid, TRUE, $2, $3)+ ON CONFLICT (tenant_id) WHERE tenant_id IS NOT NULL+ DO UPDATE SET engaged = TRUE, reason = EXCLUDED.reason, engaged_by = EXCLUDED.engaged_by,+ released_by = NULL, released_at = NULL+ """,+ tenant_id,+ reason,+ actor,+ )+++async def _audit(conn, tenant_id: str | None, *, scope: str, action: str = "engage") -> None:+ await conn.execute(+ """+ INSERT INTO aisoc_kill_switch_audit (tenant_id, action, reason, actor, scope)+ VALUES ($1::uuid, $2, 'because the agent was doing something unexpected', 'operator', $3)+ """,+ tenant_id,+ action,+ scope,+ )+++@pytest_asyncio.fixture(loop_scope="module", autouse=True)+async def _clean(pool):+ """The global row is a singleton, so one test's switch is the next+ test's starting state unless it is cleared."""+ yield+ async with pool.acquire() as conn:+ await _bind(conn, _UNBOUND)+ await conn.execute("DELETE FROM aisoc_kill_switch WHERE tenant_id IS NULL")+++class TestTheGlobalSwitchIsEngageable:+ """The reported defect. Every assertion here fails on the pre-fix tree."""++ async def test_an_unbound_session_can_engage_the_global_switch(self, pool) -> None:+ async with pool.acquire() as conn:+ await _bind(conn, _UNBOUND)++ await _engage(conn, None, reason="platform-wide stop at 3am")++ state = await conn.fetchrow("SELECT engaged, reason FROM aisoc_kill_switch WHERE tenant_id IS NULL")++ assert state is not None, "the global kill switch row does not exist after engaging it"+ assert state["engaged"] is True+ assert state["reason"] == "platform-wide stop at 3am"++ async def test_the_global_switch_can_be_released_again(self, pool) -> None:+ """A stop that cannot be released is its own outage."""+ async with pool.acquire() as conn:+ await _bind(conn, _UNBOUND)+ await _engage(conn, None, reason="platform-wide stop at 3am")++ released = await conn.fetchval(+ """+ UPDATE aisoc_kill_switch+ SET engaged = FALSE, released_by = 'operator', released_at = NOW()+ WHERE tenant_id IS NULL AND engaged = TRUE+ RETURNING id+ """+ )++ assert released is not None, "the global kill switch could not be released by the runtime role"++ async def test_the_global_audit_row_can_be_written(self, pool) -> None:+ """``aisoc_kill_switch_audit`` carries the same strict check, so a+ switch that could be thrown would still have 500'd on its audit row —+ and an unaudited emergency stop is one nobody can account for."""+ async with pool.acquire() as conn:+ await _bind(conn, _UNBOUND)++ await _audit(conn, None, scope="global")++ written = await conn.fetchval("SELECT count(*) FROM aisoc_kill_switch_audit WHERE tenant_id IS NULL AND scope = 'global'")++ assert written >= 1, "the global kill switch cannot write its audit row"+++class TestTheTenantSwitchStillWorks:+ """The working half. A fix for the global row that regressed this would+ have traded one unreachable stop for another."""++ async def test_a_tenant_bound_session_engages_its_own_row(self, pool) -> None:+ tenant_id = await _tenant(pool)+ async with pool.acquire() as conn:+ await _bind(conn, tenant_id)++ await _engage(conn, tenant_id, reason="this tenant only", actor="analyst")++ state = await conn.fetchrow("SELECT engaged FROM aisoc_kill_switch WHERE tenant_id = $1::uuid", tenant_id)++ assert state is not None and state["engaged"] is True++ async def test_a_tenant_bound_session_writes_its_own_audit_row(self, pool) -> None:+ tenant_id = await _tenant(pool)+ async with pool.acquire() as conn:+ await _bind(conn, tenant_id)++ await _audit(conn, tenant_id, scope="tenant")++ written = await conn.fetchval("SELECT count(*) FROM aisoc_kill_switch_audit WHERE tenant_id = $1::uuid", tenant_id)++ assert written == 1+++class TestEngagingGloballyWidensNothing:+ """The negative property. Making the global row writable must not make+ any session able to write a row that is not its own."""++ async def test_a_tenant_cannot_write_the_global_row(self, pool) -> None:+ """Otherwise any tenant administrator could freeze every other+ tenant on the deployment."""+ asyncpg = pytest.importorskip("asyncpg")+ tenant_id = await _tenant(pool)++ async with pool.acquire() as conn:+ await _bind(conn, tenant_id)++ with pytest.raises(asyncpg.exceptions.InsufficientPrivilegeError):+ await _engage(conn, None, reason="freezing the whole platform from one tenant")++ async def test_a_tenant_cannot_write_another_tenants_row(self, pool) -> None:+ asyncpg = pytest.importorskip("asyncpg")+ mine = await _tenant(pool)+ theirs = await _tenant(pool)++ async with pool.acquire() as conn:+ await _bind(conn, mine)++ with pytest.raises(asyncpg.exceptions.InsufficientPrivilegeError):+ await _engage(conn, theirs, reason="stopping somebody else's tenant")++ async def test_a_tenant_cannot_write_another_tenants_audit_row(self, pool) -> None:+ """A forged audit row is how a real action gets attributed to the+ wrong operator."""+ asyncpg = pytest.importorskip("asyncpg")+ mine = await _tenant(pool)+ theirs = await _tenant(pool)++ async with pool.acquire() as conn:+ await _bind(conn, mine)++ with pytest.raises(asyncpg.exceptions.InsufficientPrivilegeError):+ await _audit(conn, theirs, scope="tenant")++ async def test_an_unbound_session_cannot_write_a_tenants_row(self, pool) -> None:+ """The platform operator's session owns the global row and nothing+ else. Without this the fix would be 'drop the check', which would let+ any unbound worker write into any tenant."""+ asyncpg = pytest.importorskip("asyncpg")+ tenant_id = await _tenant(pool)++ async with pool.acquire() as conn:+ await _bind(conn, _UNBOUND)++ with pytest.raises(asyncpg.exceptions.InsufficientPrivilegeError):+ await _engage(conn, tenant_id, reason="writing into a tenant from an unbound session")+++class TestBothScopesAreVisibleToTheTenant:+ """A platform-wide stop a tenant cannot see reads to them as an+ unexplained outage, which is why ``USING`` admits the global row."""++ async def test_a_tenant_reads_the_global_switch(self, pool) -> None:+ tenant_id = await _tenant(pool)++ async with pool.acquire() as conn:+ await _bind(conn, _UNBOUND)+ await _engage(conn, None, reason="platform maintenance")++ async with pool.acquire() as conn:+ await _bind(conn, tenant_id)+ seen = await conn.fetch(+ "SELECT tenant_id, reason FROM aisoc_kill_switch WHERE engaged = TRUE AND (tenant_id IS NULL OR tenant_id = $1::uuid)",+ tenant_id,+ )++ assert [r["reason"] for r in seen] == ["platform maintenance"]++ async def test_a_tenant_does_not_read_another_tenants_switch(self, pool) -> None:+ mine = await _tenant(pool)+ theirs = await _tenant(pool)++ async with pool.acquire() as conn:+ await _bind(conn, theirs)+ await _engage(conn, theirs, reason="their own stop", actor="their-analyst")++ async with pool.acquire() as conn:+ await _bind(conn, mine)+ seen = await conn.fetch("SELECT tenant_id FROM aisoc_kill_switch WHERE engaged = TRUE")++ assert [r["tenant_id"] for r in seen] == [], "one tenant can see another tenant's kill switch"