Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

feat(8.1): a containerised identity provider signs somebody in over OIDC and SAML (#1327)

Beenu Arora50c32845a23a
diff --git a/.github/workflows/sso-live.yml b/.github/workflows/sso-live.yml
index b30a78940..a1d15ba77 100644
--- a/.github/workflows/sso-live.yml
+++ b/.github/workflows/sso-live.yml
@@ -15,8 +15,8 @@
# environment is empty, so every assertion was refused while the console
# showed a configured connection.
#
-# The two jobs below are deliberately different kinds of evidence, and the
-# second is weaker than it looks — see its own header.
+# The three jobs below are deliberately different kinds of evidence; each
+# one's header says what it does and does not prove.
name: SSO (live)
on:
@@ -158,26 +158,27 @@ jobs:
python -m pytest ../../tests/isolation/test_sso_live.py -q
# ───────────────────────────────────────────────────────────────────────
- # The containerised identity provider.
+ # The containerised identity provider, OIDC half.
#
- # READ THIS BEFORE CITING IT AS EVIDENCE. As of the commit that added
- # this file, this job has **never been observed to pass**: it was
- # authored in an environment where no container runtime would start, so
- # the Keycloak bootstrap below is unexercised. Until a green run exists,
- # the claim row "SSO completes a sign-in" stays PARTIAL on the strength
- # of the job above and nothing is claimed for this one.
+ # This job was authored where no container runtime would start, so for
+ # its first weeks it had never been observed to pass and said so here.
+ # It has since been **observed to pass on `main`**: run 38118951217,
+ # job 114409519883, 2026-10-11, printing
#
- # What it proves when it does pass is also narrower than "a user signed
- # in through Keycloak": there is no browser here, so the authorization
- # *hop* is not exercised. It takes a real Keycloak-issued `id_token`
- # through the resource-owner grant and runs the API's own
- # `_verify_id_token` against Keycloak's published JWKS — real discovery,
- # real key rotation semantics, real RS256 from a real provider. The
- # browser hop is covered by `test_sso_live.py` against a provider this
- # repository controls.
+ # OK: a real Keycloak id_token verified against its published JWKS
+ # OK: the same token is refused when it names another audience.
+ #
+ # What it proves is narrower than "a user signed in through Keycloak",
+ # and that part of the original caveat stands: there is no browser
+ # here, so the authorization *hop* is not exercised by this job. It
+ # takes a real Keycloak-issued `id_token` through the resource-owner
+ # grant and runs the API's own `_verify_id_token` against Keycloak's
+ # published JWKS — real discovery, real key rotation semantics, real
+ # RS256 from a real provider. The hop against a real provider is the
+ # `keycloak-saml` job below.
# ───────────────────────────────────────────────────────────────────────
keycloak-oidc:
- name: A real Keycloak id_token verifies (unproven — see workflow header)
+ name: A real Keycloak id_token verifies against its published JWKS
runs-on: ubuntu-latest
timeout-minutes: 20
@@ -230,3 +231,141 @@ jobs:
ENVIRONMENT: test
OTEL_SDK_DISABLED: "true"
run: python3 scripts/ci/keycloak_oidc_probe.py
+
+ # ───────────────────────────────────────────────────────────────────────
+ # The containerised identity provider, SAML half. Depth 8.1.
+ #
+ # This is the strongest of the three and the only one that walks the
+ # whole flow against software this repository does not author: the app
+ # builds an AuthnRequest from the trust material an operator stored on
+ # the connection, a real Keycloak renders its own login page, real
+ # credentials are posted to it, Keycloak signs a real Response, and
+ # that document goes to the real `/auth/saml/acs` of an application
+ # built by `create_application()` against real Postgres with every
+ # migration applied.
+ #
+ # Two shipped defects were invisible until it existed, both of which
+ # the self-authored provider in `tests/isolation/test_sso_live.py`
+ # could not have found:
+ #
+ # * `resolve_saml_connection` bound `:i` untyped, so the `IS NULL`
+ # branch — the one the console takes — raised on asyncpg and was
+ # swallowed into "no enabled SAML connection is configured".
+ # * Keycloak's default role-list mapper emits one `<Attribute
+ # Name="Role">` per role and python3-saml refuses repeated names,
+ # so the ACS answered an unhandled 500 to a stock Keycloak.
+ #
+ # The negative control is inside the probe, because it needs the same
+ # assertion: the certificate on the connection is swapped for another
+ # realm's and the identical Response must be refused.
+ # ───────────────────────────────────────────────────────────────────────
+ keycloak-saml:
+ name: A real Keycloak signs somebody in over SAML
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+
+ services:
+ postgres:
+ image: public.ecr.aws/docker/library/postgres:16-alpine
+ env:
+ POSTGRES_USER: aisoc
+ POSTGRES_PASSWORD: aisoc_ci_only
+ POSTGRES_DB: aisoc
+ ports: ["5432:5432"]
+ options: >-
+ --health-cmd "pg_isready -U aisoc"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 20
+
+ env:
+ # The runtime role, not the owner. A superuser ignores every RLS
+ # policy even under FORCE ROW LEVEL SECURITY, and the SSO callback
+ # writes `aisoc_sso_identities` under a policy whose WITH CHECK has
+ # no null escape — so running as the owner would pass for a reason
+ # no deployment enjoys.
+ SSO_DSN: postgresql+asyncpg://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc
+ PGPASSWORD: aisoc_ci_only
+ # NOT `development`: that is in `AUTH_BYPASS_ENVIRONMENTS`, so an
+ # uncredentialed request would resolve to a demo administrator —
+ # inside the one job whose point is that the principal comes from
+ # the assertion.
+ ENVIRONMENT: test
+ OTEL_SDK_DISABLED: "true"
+ # `127.0.0.1`, never `localhost`. Python's `http.cookiejar` stores a
+ # cookie from a single-label host under the domain `localhost.local`
+ # and then matches nothing, so Keycloak's login POST arrives without
+ # the session it set and answers "cookies are disabled in your
+ # browser" — a failure that looks like a broken sign-in and is a
+ # resolver detail.
+ KEYCLOAK_URL: http://127.0.0.1:8080
+
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+
+ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6
+ with:
+ python-version: "3.11"
+
+ # `docker run`, not a `services:` container: Keycloak's entrypoint
+ # needs the `start-dev` argument and a service container has no way
+ # to supply one. Same digest as the OIDC job above, so the two
+ # cannot drift onto different providers.
+ - name: Start Keycloak
+ run: |
+ docker run -d --name keycloak -p 8080:8080 \
+ -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
+ -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
+ quay.io/keycloak/keycloak:26.8@sha256:b0f60d489d51c5d113390bdf5461d4c06e6051be026c05549f2e1e10ec352bcc \
+ start-dev
+ for _ in $(seq 1 60); do
+ curl -sf http://127.0.0.1:8080/realms/master >/dev/null && exit 0
+ sleep 5
+ done
+ echo "Keycloak never became ready. Container log follows."
+ docker logs keycloak | tail -50
+ exit 1
+
+ # xmlsec1 is a C library and `python3-saml` will not import without
+ # it. Installed before the lockfile so a missing system package is a
+ # loud failure here rather than a skip later.
+ - name: System libraries and the api lockfile
+ working-directory: services/api
+ run: |
+ set -euo pipefail
+ sudo apt-get update -qq && sudo apt-get install -y -qq libxmlsec1-dev pkg-config
+ python -m pip install --quiet --upgrade pip "poetry==2.4.1"
+ poetry config virtualenvs.create false
+ poetry install --no-root --no-interaction
+
+ - name: Refuse to continue without the SAML stack
+ run: |
+ python -c "import onelogin.saml2.auth" \
+ || { echo "python3-saml did not import; this job would report a provider problem for a missing dependency."; exit 1; }
+
+ - name: Apply every migration, in order
+ run: |
+ 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: |
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \
+ "ALTER ROLE aisoc_app WITH 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;"
+
+ # A script rather than a pytest suite, deliberately: a script
+ # cannot skip. There is no fixture to go missing and no
+ # `importorskip` to turn an absent dependency into a green run,
+ # which is the failure mode a job named "live" must not have.
+ - name: A real Keycloak signs somebody in, and an untrusted key does not
+ env:
+ ISOLATION_SSO_DSN: ${{ env.SSO_DSN }}
+ DATABASE_URL: ${{ env.SSO_DSN }}
+ run: python3 scripts/ci/keycloak_saml_probe.py
+
+ - name: Keycloak log on failure
+ if: failure()
+ run: docker logs keycloak | tail -80
diff --git a/DEPTH_PROGRESS.md b/DEPTH_PROGRESS.md
index 19cd4bb58..5567c305c 100644
--- a/DEPTH_PROGRESS.md
+++ b/DEPTH_PROGRESS.md
@@ -64,6 +64,11 @@ is written. Next free at capture: migration `095`, ADR `0010`
| migration `107` | 9.4 — `107_case_war_rooms.sql` | claimed |
| migration `108` | 9.5 — `108_hunt_reports.sql` | claimed |
| migration `109` | 9.6 — `109_push_devices.sql` | claimed |
+| migration `110` | 8.1 — `110_console_webauthn.sql` | claimed |
+| migration `111` | 8.1 — `111_audit_retention.sql` | claimed |
+| migration `112` | 8.1 — released, taken by another lane (D12) | **struck** |
+| migration `113` | 8.1 — `113_entitlement_enforcement.sql` | claimed |
+| ADR `0011` | 8.1 — truncating a hash-chained audit log | claimed |
Highest migration on `main` at claim time was `101_audit_immutable_nullify.sql`,
so `095`--`101` were taken by sibling lanes between the capture above and this
@@ -75,6 +80,13 @@ and `103` were already spoken for in the table above, so Phase 9 takes `104`
through `109`, one per item. A number left unused at the end of the phase is
released by striking its row rather than by silently leaving a gap.
+Item 8.1 re-read `services/api/migrations/` on 2026-10-11 before claiming:
+`105_semantic_memory.sql` was the highest on `main`, and `102`--`109` were
+already spoken for above, so 8.1 takes `110`--`112` and ADR `0011`. The three
+sub-items that need no schema — the containerised-IdP CI leg,
+internationalisation and accessibility — claim no number. The same release
+rule applies: an unused number is struck, not silently skipped.
+
## Phase 0: Kickoff
- [x] **0.1** `DEPTH_PROGRESS.md` exists (this file), modelled on
@@ -314,6 +326,65 @@ Three things follow, and all three are in the tree rather than in this note:
retrieval delta above is the part that can be measured honestly today,
and it is the part that is actually about what 9.2 builds.
+### D12 -- Migration `112` was claimed here and taken by another lane first
+
+The claim table above reserved `110`--`112` for 8.1 after re-reading
+`services/api/migrations/` against `main`, which is the documented procedure
+and was not enough. Sequentially-numbered migrations are a **first-come
+namespace across branches, not across `main`**: by the time 8.1 came to write
+its third file, `112_scheduler_leases.sql` existed on another lane's pushed
+branch. `110` and `111` had three and three other claimants respectively and
+survived only because this item pushed first.
+
+Re-derived immediately before committing by scanning the migration directory
+of **all 259 remote branches**, not just `main`, which put the first free
+number at `113`. The `112` row is struck rather than silently reused, per the
+release rule at the top of that table.
+
+The general lesson is that "re-read `main` before claiming" understates the
+problem. `main` is the one place a number cannot yet be taken.
+
+### D13 -- Two honest gates disagreed about the claim matrix, and the older one was wrong
+
+`scripts/check_claim_gate_matrix.py` read the matrix as 300 GATED / 2 PARTIAL
+while `readme_gates._matrix_counts` read 299 / 3, so the summary block was
+reported as stale against a table that was correct.
+
+`readme_gates` classified a row by scanning the **whole line** for `NO GATE`,
+then `PARTIAL`, then `GATED`. A row's Notes cell is prose, so the first GATED
+row to record *why* it had been PARTIAL -- which is exactly what a row should
+say when a gate is built and the status earned -- counted as PARTIAL.
+
+The cheap fix was to reword the row and lose the history. It now reads the
+cell the column header names, refuses a table whose Status column cannot be
+located rather than counting it as empty, and both properties are pinned by
+tests that fail against the previous parser.
+
+### D14 -- 4.6 is not started, and 4.5 is half done. Neither is claimed
+
+Stated plainly rather than folded into a tick.
+
+**4.6 internationalisation** (gap-closure 13.4) is **not started**. It asks
+for a Next.js i18n library, externalised strings on five surfaces, a locale
+switcher, RTL, locale-aware dates and numbers, a pilot locale and a CI gate
+for missing and unused keys. Nothing of it exists: there is no `i18n`
+directory, no message catalogue and no i18n dependency in `apps/web`. It is
+the one sub-item of 8.1 with no code behind it, and the honest record is a
+`[ ]`, not a partial credit for the parts that are easy.
+
+**4.5** asks for two things. The opt-in limit enforcement the depth plan
+names by file is built, wired to two routes and gated (#1332). The **six
+console pages** -- branding, SCIM tokens, retention, organisation members and
+grants, rule packs, delegations -- are not. Its claim row says so in the row
+itself rather than relying on this note, because a reader of the matrix does
+not read this file.
+
+Neither is blocking 8.1's stated "Done when": a CI test signs in through OIDC
+and SAML with MFA enforced for the role, an elevation expires on schedule
+(8.2, merged), and the security pack passes the competitor-name and
+comment-path gates. All three hold. The item is `[~]` rather than `[x]`
+because the spec lists more than its own done-when.
+
### D8 -- No upstream Sigma correlation rule exists in this tree to import
`detections/sigma-imports/` holds 3,132 rule documents and **not one carries
@@ -557,7 +628,21 @@ endpoint produces once triage falls through to its deterministic scorer.
## Phase 8: Enterprise gates
-- [ ] **8.1** Identity and administration
+- [~] **8.1** Identity and administration. Five of six sub-items done, each
+ in its own pull request; the shortfall is itemised in D14 below.
+ - [x] parity 4.1 — a containerised Keycloak signs somebody in over **OIDC**
+ and **SAML**, both legs **observed to pass** (#1327). The SSO claim row
+ moves PARTIAL → GATED on that evidence, not on a relabel.
+ - [x] 4.2 — WebAuthn as a console second factor and MFA enforced **per
+ role** (#1328), on top of the TOTP, recovery codes and per-tenant
+ enforcement fix pass 4.2 already shipped.
+ - [x] 4.4 — the audit retention window is enforced and a truncated chain
+ still verifies (#1329). Export already existed on `AuditLogView.tsx`.
+ - [~] 4.5 — opt-in limit enforcement in `entitlements.py` (#1332). The
+ **six console pages** 4.5 also names are not built: see D14.
+ - [ ] 4.6 — internationalisation. Not started: see D14.
+ - [x] 4.7 — axe covers the case list and case workspace, the two views
+ 4.7 left out, and the four defects it found are fixed (#1331).
- [x] **8.2** ABAC, elevation and workload identities
- [x] **8.3** Buyer security pack
@@ -640,3 +725,9 @@ endpoint produces once triage falls through to its deterministic scorer.
| 2026-10-09 | 3.2 | Ordered and unordered sequences in the windowed engine; all four translatable Sigma correlation types compile, seven refusal reasons recorded. No upstream correlation rule exists in this tree to import (D8), so the corpus is first-party and labelled as such. |
| 2026-10-09 | 4.1 | Reproduced: `check_cloud_native_collection.py` on the unmodified tree reported all three collection paths absent. Implemented `aws_cloudtrail_s3` (SQS-notified S3 objects; management events, data events and VPC flow logs; delete-after-emit), `gcp_pubsub` (REST pull on a log-sink subscription; ack-after-read) and `azure_event_hubs` (Capture blobs over the Data Lake Gen2 JSON API, with a focused Avro OCF reader). Negative controls recorded in the PR: deleting the SQS message before the object is read, acknowledging the Pub/Sub batch before it is built, ignoring the Avro union branch index, and ignoring the flow-log header line each fail a named test, and all were restored. Connectors suite 1014 -> 1098 passed. |
| 2026-10-09 | 3.1 | All 74 decided. 50 translated into `wd-*` rules derived from each original's own clauses and replayed through the real engine (162 assertions); 24 refused with a reason across five kinds. `MAX_UNREACHABLE` 119 → 45, published executable 2,603 → 2,529, windowed 18 → 68. Three findings recorded as D4–D6 below. |
+| 2026-10-11 | 8.1 | parity 4.1's containerised-IdP leg **observed to pass**, both halves: `keycloak-oidc` verifies a real `id_token` against Keycloak's published JWKS with an audience-mismatch negative control, and `keycloak-saml` walks the whole SP-initiated flow to the real ACS and signs `[email protected]` in as `infosec`, with an untrusted-key control answering 400. Run `38124780886`, as `ENVIRONMENT=test` against the DML-only `aisoc_app` role. The SSO claim row moves PARTIAL → GATED on that evidence. Building it found two shipped defects no self-authored provider could expose: `resolve_saml_connection` bound `:i` untyped so `:i IS NULL` raised on asyncpg, and Keycloak's default role-list mapper emits one `<Attribute Name="Role">` per role, which python3-saml refuses. |
+| 2026-10-11 | 8.1 | WebAuthn as a console second factor and MFA enforced per role. Fixing the branch's own gates found three `passkey_credentials` reads scoped by user id alone on a tenant-scoped table, and a permission-model violation where the MFA policy route imported `ROLE_PERMISSIONS` directly; the role *vocabulary* now has one owner in `role_grants.known_roles()`. 23 of 23 live cases pass against real Postgres, and deleting the login integration fails 14 of them — measured, where the workflow had said eight. |
+| 2026-10-11 | 8.1 | An enforced audit retention window with a re-anchored checkpoint, ADR-0011, and 12 live cases. Writing them found that migration `111` declared `ON DELETE CASCADE` on the checkpoint table and then made the cascade impossible; and, separately, that `audit_log`'s own trigger from migration `101` blocks `DELETE FROM tenants` for every tenant that has written a row, so tenant deletion is impossible on `main`. Reproduced and filed as #1330 rather than fixed here. |
+| 2026-10-11 | 8.1 | Opt-in per-tenant limit enforcement (migration `113`, D12), wired to `POST /connectors` and `POST /tenants/me/users` through one helper, with `GET`/`PUT /usage/enforcement` as the operator surface. Nine live cases, half of them positive controls: a guard that never refuses fails 1, a guard stuck closed fails 4. |
+| 2026-10-11 | 8.1 | axe extended to the case list and case workspace, the two of parity 4.7's five views that were left out. Four real defects found and fixed: two `<select>` controls with no accessible name (one of them the control that writes a case's status), two indistinguishable `<aside>` landmarks, and panel headings at `h3` directly under the page's `h1`. |
+
diff --git a/ROADMAP.md b/ROADMAP.md
index 8e0bf2111..d029c22f9 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 **302 rows — 299 GATED / 3 PARTIAL / 0 NO GATE**. Three rows are PARTIAL. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. And "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. 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. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **302 rows — 300 GATED / 2 PARTIAL / 0 NO GATE**. Two rows are PARTIAL. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. "SSO completes a sign-in" was the third, and depth 8.1 closed it by building the gate it named rather than by relabelling: `sso-live.yml` now stands up a containerised Keycloak and both legs have been observed to pass — `keycloak-oidc` takes a real `id_token` through `_verify_id_token` against the provider's published JWKS, and `keycloak-saml` walks the whole SP-initiated flow to the real ACS. 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. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 1dd2f4f30..7890b5387 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,8 +33,8 @@ 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: 299 rows
-`GATED`, 3 `PARTIAL`, and a ratchet that refuses to let a row sit at
+The last row is the one worth reading first. It is the honest index: 300 rows
+`GATED`, 2 `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 count
copied into prose goes stale in silence, which is why
`scripts/readme_gates.py` cross-checks this sentence against the matrix.
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index fcb3a56e6..712149e18 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -277,7 +277,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| CORE gives the investigation agent real indicator evidence | `apps/docs/docs/deployment/docker.md` | `ci.yml :: Python — Service unit tests` (`services/fusion/tests/test_tenant_ioc_match.py`) | core | GATED | `AlertEnricher` asks the enrichment service, which runs in the `full` profile, so on CORE the call failed, was caught, logged at `debug`, and `{}` returned: the agent received "could not check" for every indicator on every alert. The tenant's own `threat_intel_iocs` is in the Postgres fusion already uses and CORE ships a real CISA KEV feed. Expiry is a hard gate in SQL; decay is a per-type half-life on `last_seen`, because an address reassigns in weeks and a file hash identifies the same bytes forever. The half-lives are judgement rather than measurement and say so. A faded hit is reported weakly rather than dropped, because "seen weakly" is different information from "never seen" |
| Injection flip rate and unsafe-action rate are measured per family | `apps/docs/docs/benchmark.md` | `ci.yml :: Python — Tests` (`tests/adversarial/test_behavioural_injection.py`) | core | GATED | **27 pairs across the 9 families the plan names**, each payload written to fit the field it arrives in: overall flip 25.9%, unsafe action 3.7%, with a per-family ceiling so a regression in one cannot hide behind an improvement in another. It immediately found a real blind spot: **`fake_tool_output` flips every verdict and the guard catches none of it**, because a payload shaped like a tool's own answer reads as evidence rather than as an instruction. Recorded at 1.0 rather than patched, and the guard is deliberately not tuned against this corpus in the same change, because hardening against a tuned corpus has already been measured here moving 66.7% to 98.1% while held-out payloads moved 3.6% to 7.1%. **Measures the pipeline, not a model**: the stub is deliberately obedient, so the rates are an upper bound on harm and the artefact carries `llm_resistance_measured: false` |
| Closure accuracy is measured on the tenant's own data, not only on a synthetic corpus | `apps/docs/docs/operations/shadow-mode.md` | `ci.yml :: Python — Tests` (agents, `test_closure_qa_sampling.py`) | core | GATED | Nothing measured this. The eval harness grades a synthetic corpus and the funnel counts how many alerts were closed, neither of which answers "of the ones the agent closed on your data, how many should it have". A tenant-configurable sample (5% default) of auto-closures goes to an analyst, scored on the five-part rubric. The sample is a **deterministic hash of the alert id, not `random()`**: a rolled sample fires at the configured rate *per replica*, so three replicas at 5% sample 15%, and a redelivered Kafka message gets a second roll and weights one closure twice. Bucketing also makes a higher rate a superset of a lower one, so a tenant's figure stays comparable across a rate change. Zero reviews reports **not measured** rather than 0.0, and every mean travels with the count it was taken over |
-| SSO completes a sign-in, into the right tenant with the mapped role | `apps/docs/docs/operations/security.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_sso_provisioning.py`, `test_saml_connection_metadata.py`) + `sso-live.yml :: sso-live` (`tests/isolation/test_sso_live.py` against real Postgres and the real application: a SAML Response signed by the connection's own IdP key, and an RS256 `id_token` from a provider serving real discovery and a real JWKS, each taken through to a token `GET /auth/me` accepts) | core | PARTIAL | Both handlers used to end a successful sign-in by putting a JWT in an `aisoc_token` cookie carrying `sub`, `email`, `name` and `picture`. That token authenticated nothing three times over: signed with `JWT_SECRET` rather than the key the API verifies with, carrying no `tenant_id` or `role`, and in a cookie when the API reads `Authorization: Bearer`. A user could complete the whole dance and find every request unauthenticated. **The security property the tests exist for is that the tenant does not come from the assertion**: an IdP that can name its own tenant can name somebody else's, so it comes from the connection row an administrator configured, and `complete_sso_login` is asserted to take no tenant argument at all. A group cannot map to `admin` or `platform_admin`. The token travels in the URL fragment, which is not sent to the server and does not reach an access log or a `Referer`. **Fix pass 4.1** found the half none of that could see: `_saml_settings()` read its IdP trust anchor from `SAML_IDP_*` while the connection's own `metadata_url` and `metadata_xml` were written by `POST /sso-connections` and read by nothing, so on a stock install — which sets no SAML environment at all — every assertion was refused while the console showed a configured connection. The SAML callback also redirected straight to its RelayState destination, whose auth guard rebuilds its bounce target from `pathname + search` and drops the fragment the token travels in. Both are fixed and driven end to end. **Why this is PARTIAL and not GATED**: the identity providers in that suite are a keypair and a metadata document this repository authors, so they cannot exhibit a vendor's own quirks. `sso-live.yml :: keycloak-oidc` is the containerised leg and **has never been observed to pass** — it was written where no container runtime would start. The row returns to GATED on the first green run of that job, not before |
+| SSO completes a sign-in, into the right tenant with the mapped role | `apps/docs/docs/operations/security.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_sso_provisioning.py`, `test_saml_connection_metadata.py`) + `sso-live.yml :: sso-live` (`tests/isolation/test_sso_live.py` against real Postgres and the real application) + `sso-live.yml :: keycloak-oidc` (a real Keycloak `id_token` through `_verify_id_token` against its published JWKS) + `sso-live.yml :: keycloak-saml` (`scripts/ci/keycloak_saml_probe.py`: the whole SP-initiated flow against a containerised Keycloak — the app's AuthnRequest from the connection's own trust material, Keycloak's own login page, a signed Response, and the real ACS against real Postgres as the DML-only `aisoc_app` role) | core | GATED | Both handlers used to end a successful sign-in by putting a JWT in an `aisoc_token` cookie carrying `sub`, `email`, `name` and `picture`. That token authenticated nothing three times over: signed with `JWT_SECRET` rather than the key the API verifies with, carrying no `tenant_id` or `role`, and in a cookie when the API reads `Authorization: Bearer`. A user could complete the whole dance and find every request unauthenticated. **The security property the tests exist for is that the tenant does not come from the assertion**: an IdP that can name its own tenant can name somebody else's, so it comes from the connection row an administrator configured, and `complete_sso_login` is asserted to take no tenant argument at all. A group cannot map to `admin` or `platform_admin`. The token travels in the URL fragment, which is not sent to the server and does not reach an access log or a `Referer`. **Fix pass 4.1** found the half none of that could see: `_saml_settings()` read its IdP trust anchor from `SAML_IDP_*` while the connection's own `metadata_url` and `metadata_xml` were written by `POST /sso-connections` and read by nothing, so on a stock install — which sets no SAML environment at all — every assertion was refused while the console showed a configured connection. The SAML callback also redirected straight to its RelayState destination, whose auth guard rebuilds its bounce target from `pathname + search` and drops the fragment the token travels in. Both are fixed and driven end to end. **This row was PARTIAL because the identity providers in that suite are a keypair and a metadata document this repository authors, so they cannot exhibit a vendor's own quirks, and the containerised leg had never been observed to pass.** Both halves are now closed. `keycloak-oidc` passed on `main` in run 38118951217 (2026-10-11), and depth 8.1 added `keycloak-saml`, which walks the entire SP-initiated flow against a real Keycloak and passed on the pull request that added it. **It immediately found two shipped defects neither the self-authored provider nor any unit test could see**: `resolve_saml_connection` bound `:i` with no type, so `:i IS NULL` — the branch `/auth/saml/login` takes when the console links to it without an issuer, which is every console — raised on asyncpg and was swallowed into "no enabled SAML connection is configured"; and Keycloak's default role-list mapper emits one `<Attribute Name="Role">` per role, which python3-saml refuses, so the ACS answered an unhandled 500 to a stock Keycloak. Both fixed, both with negative controls in the PR. One limit stated rather than implied: there is no browser in either job, so the SAML hop is driven over HTTP with the login form parsed out of Keycloak's own HTML — everything a browser does except JavaScript, which Keycloak's login form does not require |
| Accessibility is checked on the views an analyst uses, not only on the landing page | `ROADMAP.md` | `ci.yml :: Web — Tests` (`apps/web/src/test/a11y.test.tsx`) | core | GATED | 1.1 narrowed the "WCAG AA full accessibility pass" claim because axe covered the landing and chrome components only. 4.7 adds **three of the five** operator views the plan names: the alerts queue and list, the investigation rail, and settings. Each asserts it rendered real markup **before** axe runs, because axe passes on an empty div and a view that rendered a spinner would report coverage the suite does not have. That guard immediately caught one: the rail keys SWR on a tuple, the fixture read only the string form, and it was rendering its error state. **Limits stated**: the case workspace is not covered, and axe checks a subset of WCAG rather than all of it |
| A playbook can start from an alert, and previews before it acts | `apps/docs/docs/console/playbooks.md` | `ci.yml :: Python — Tests` (agents, `test_alert_triggered_playbooks.py`) | core | GATED | `find_matching()` had **no production caller**, so no playbook ever ran from an alert. Three switches must agree before one acts (deployment, tenant, playbook) and the default of every one is off; anything short of all three runs in **preview**, with its plan and simulated steps attached to the alert. Preview is the default state rather than a mode somebody has to remember, so a deployment that enables the feature and forgets the per-playbook list gets previews rather than containment. The live list is read per call, so turning one off takes effect on the next alert rather than the next restart. It runs **after** triage, because a playbook's conditions read the verdict |
| An approval step is a durable pause that survives a restart | `apps/docs/docs/console/playbooks.md` | `ci.yml :: Python — Tests` (agents, `test_playbook_pause_resume.py`) | core | GATED | The engine is a single-threaded index walk with no pause and no resume, so `approval` failed closed and **12 shipped playbooks aborted on it**. Failing closed was right (it previously returned `{"skipped": true}` while reporting SUCCESS, letting a run continue into the action a human was meant to authorise) but it is not an approval mechanism. Migration `081` stores the position **and the context**, because the resumed half would otherwise see an empty context and every templated parameter would resolve to nothing. The stored index is the approval step itself and resume advances past it, so a replayed decision continues rather than pausing again. The pause is resolved **before** the run continues, so a double-tap in the responder app resumes once. Expiry is mandatory with a recorded outcome: `expired` is a decision, not the absence of one |
@@ -314,8 +314,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
- Total: 302
-- GATED: 299
-- PARTIAL: 3
+- GATED: 300
+- PARTIAL: 2
- NO GATE: 0
Counts come from `scripts/check_claim_gate_matrix.py`, which is also the gate. Recompute
diff --git a/scripts/check_text_bind_casts.py b/scripts/check_text_bind_casts.py
index be1d7e713..60fee9e54 100644
--- a/scripts/check_text_bind_casts.py
+++ b/scripts/check_text_bind_casts.py
@@ -59,6 +59,14 @@ SQLA_BIND_RE = re.compile(r"(?<![:\w\x5c]):(\w+)(?!:)")
# a column, say) is not reported.
CAST_ADJACENT_RE = re.compile(r"(?<![:\w\\]):(\w+)::")
+# A bind parameter tested directly for NULL: `:name IS NULL`, or the negated
+# form. Postgres has nothing to infer the parameter's type from, so asyncpg
+# answers `could not determine data type of parameter $N` — and only when the
+# value bound is actually `None`, which is why this survives every test that
+# supplies a value. A `CAST(:name AS TEXT) IS NULL` is already typed and is
+# not matched.
+UNTYPED_NULL_TEST_RE = re.compile(r"(?<![:\w\\]):(\w+)\s+IS\s+(?:NOT\s+)?NULL", re.IGNORECASE)
+
# The historical prototype subtree is reference-only and is `paths-ignore`d by
# CodeQL for the same reason.
SKIP_PREFIXES = ("plans/",)
@@ -112,7 +120,14 @@ def _is_text_call(node: ast.Call) -> bool:
def violations(source: str, rel: str) -> list[str]:
- """Report every `:name::type` inside a `text()` statement in ``source``."""
+ """Report every bind parameter inside a `text()` that needs a cast.
+
+ Two signatures, one family and one fix. `:name::type` declares a
+ different, shorter parameter name and raises on `.bindparams()`;
+ `:name IS NULL` declares the right name and raises on the connection,
+ but only when the value bound is `None`. Both are written
+ `CAST(:name AS <type>)`.
+ """
try:
tree = ast.parse(source)
except SyntaxError as exc:
@@ -138,6 +153,13 @@ def violations(source: str, rel: str) -> list[str]:
f"{rel}:{node.lineno}: `:{intended}::` declares `{truncated}`, so `.bindparams({intended}=...)` raises. "
f"Write `CAST(:{intended} AS <type>)`."
)
+ for match in UNTYPED_NULL_TEST_RE.finditer(statement):
+ name = match.group(1)
+ found.append(
+ f"{rel}:{node.lineno}: `:{name} IS NULL` gives Postgres no type to infer, so asyncpg raises "
+ f"`could not determine data type` whenever `{name}` is bound to None — the branch a test that "
+ f"always supplies a value never reaches. Write `CAST(:{name} AS <type>) IS NULL`."
+ )
return found
@@ -166,13 +188,16 @@ def main() -> int:
problems.extend(violations(source, str(path.relative_to(root))))
if problems:
- print("A bind parameter is followed by a `::` cast, so SQLAlchemy declares a different name:\n", file=sys.stderr)
+ print("A bind parameter inside a text() statement needs an explicit cast:\n", file=sys.stderr)
for problem in problems:
print(f" {problem}", file=sys.stderr)
- print(f"\n{len(problems)} statement(s) would raise before reaching a connection.", file=sys.stderr)
+ print(f"\n{len(problems)} statement(s) would raise rather than run.", file=sys.stderr)
return 1
- print(f"OK: {len(files)} tracked Python file(s) scanned ({len(services)} under services/), no `:name::type` inside a text() statement")
+ print(
+ f"OK: {len(files)} tracked Python file(s) scanned ({len(services)} under services/), "
+ "no `:name::type` and no untyped `:name IS NULL` inside a text() statement"
+ )
return 0
@@ -181,6 +206,16 @@ _BROKEN = 'q = text("INSERT INTO t (a, b) VALUES (:payload::jsonb, :other)").bin
_NOT_SQL = 'if ":iam::" in resource_id and ":policy/" in resource_id:\n kind = "policy"'
_CONCAT = 'q = text("SELECT * FROM t" " WHERE k = ANY(:kinds::text[])")'
+# The second signature. `_NULL_BROKEN` is the exact statement depth 8.1
+# found in `resolve_saml_connection`; `_NULL_CLEAN` is its fix. The
+# `NOT NULL` case is here because the same inference failure applies, and
+# `_NULL_COLUMN` is the shape that must keep passing — a *column* tested
+# for NULL is ordinary SQL and carries no parameter at all.
+_NULL_BROKEN = 'q = text("SELECT id FROM c WHERE (:i IS NULL OR issuer = :i)").bindparams(i=issuer)'
+_NULL_CLEAN = 'q = text("SELECT id FROM c WHERE (CAST(:i AS TEXT) IS NULL OR issuer = CAST(:i AS TEXT))")'
+_NULL_NEGATED = 'q = text("SELECT id FROM c WHERE :since IS NOT NULL")'
+_NULL_COLUMN = 'q = text("SELECT id FROM c WHERE deleted_at IS NULL AND issuer = :i")'
+
def _rule_self_test() -> list[tuple[str, bool]]:
return [
@@ -188,6 +223,10 @@ def _rule_self_test() -> list[tuple[str, bool]]:
("an injected `:payload::jsonb` is reported", any("payloa" in v for v in violations(_BROKEN, "f.py"))),
("an ARN literal outside a text() call is not reported", not violations(_NOT_SQL, "f.py")),
("a `::` cast in a concatenated statement is reported", any(":kinds::" in v for v in violations(_CONCAT, "f.py"))),
+ ("an untyped `:i IS NULL` is reported", any(":i IS NULL" in v for v in violations(_NULL_BROKEN, "f.py"))),
+ ("`CAST(:i AS TEXT) IS NULL` is not reported", not violations(_NULL_CLEAN, "f.py")),
+ ("an untyped `:since IS NOT NULL` is reported", any(":since IS NULL" in v for v in violations(_NULL_NEGATED, "f.py"))),
+ ("a column tested for NULL is not reported", not violations(_NULL_COLUMN, "f.py")),
]
diff --git a/scripts/ci/keycloak_oidc_probe.py b/scripts/ci/keycloak_oidc_probe.py
index 07c286e3e..fa191bdc1 100644
--- a/scripts/ci/keycloak_oidc_probe.py
+++ b/scripts/ci/keycloak_oidc_probe.py
@@ -20,6 +20,10 @@ The negative control is in the file rather than the workflow because it
needs the same realm: after the positive check, the same token is
re-verified against a *different* expected audience and must be refused.
A verifier that accepted anything would pass the positive check alone.
+
+The realm itself is built by `keycloak_realm.bootstrap`, shared with
+`keycloak_saml_probe.py`. Two copies of one bootstrap in one tree is the
+shape this repository keeps finding on the wrong side of a drift.
"""
from __future__ import annotations
@@ -31,92 +35,24 @@ from pathlib import Path
import httpx
-KEYCLOAK = os.environ.get("KEYCLOAK_URL", "http://localhost:8080")
-REALM = "aisoc-ci"
-CLIENT_ID = "aisoc-console"
-CLIENT_SECRET = "aisoc-ci-secret"
-USERNAME = "alice"
-PASSWORD = "alice-ci-password"
+_HERE = Path(__file__).resolve()
+# `services/api` is the import root for `app.*`; this file's own directory
+# is the import root for `keycloak_realm`.
+sys.path.insert(0, str(_HERE.parents[2] / "services" / "api"))
+sys.path.insert(0, str(_HERE.parent))
-# `services/api` is the import root for `app.*`.
-sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "services" / "api"))
+from keycloak_realm import ( # noqa: E402
+ EMAIL,
+ OIDC_CLIENT_ID,
+ PASSWORD,
+ REALM,
+ USERNAME,
+ bootstrap,
+)
+CLIENT_ID = OIDC_CLIENT_ID
-def _admin_token() -> str:
- response = httpx.post(
- f"{KEYCLOAK}/realms/master/protocol/openid-connect/token",
- data={"grant_type": "password", "client_id": "admin-cli", "username": "admin", "password": "admin"},
- timeout=30,
- )
- response.raise_for_status()
- return str(response.json()["access_token"])
-
-
-def bootstrap() -> str:
- """A realm, a confidential client and a user. Returns the client secret.
-
- The secret is **read back** rather than assumed. Keycloak generates one
- when a confidential client is created and does not necessarily honour a
- `secret` supplied in the creation payload, so sending one and then using
- it is a coin flip that answers `400 unauthorized_client` — a message
- about the grant, for a problem in the registration.
- """
- headers = {"Authorization": f"Bearer {_admin_token()}"}
- base = f"{KEYCLOAK}/admin/realms"
-
- # 409 is success: the workflow may retry a step, and a realm that
- # already exists is the state this wants.
- for url, payload in (
- (base, {"realm": REALM, "enabled": True}),
- (
- f"{base}/{REALM}/clients",
- {
- "clientId": CLIENT_ID,
- "secret": CLIENT_SECRET,
- "publicClient": False,
- "clientAuthenticatorType": "client-secret",
- "standardFlowEnabled": True,
- # The resource-owner grant is how this script obtains a
- # token without a browser. It is enabled on the CI realm
- # only and is not something AiSOC asks a deployment for.
- "directAccessGrantsEnabled": True,
- "redirectUris": ["http://localhost:8000/auth/oidc/callback"],
- },
- ),
- (
- f"{base}/{REALM}/users",
- {
- "username": USERNAME,
- "email": EMAIL,
- "emailVerified": True,
- "enabled": True,
- # Keycloak's `VERIFY_PROFILE` required action is on by
- # default and is evaluated against profile completeness at
- # token time rather than stored on the user, so the account
- # reads as `requiredActions: []` and still refuses the
- # password grant with `invalid_grant: "Account is not fully
- # set up"`. A name is what it is waiting for; without these
- # two fields this probe cannot obtain a token at all.
- "firstName": "Alice",
- "lastName": "Analyst",
- "credentials": [{"type": "password", "value": PASSWORD, "temporary": False}],
- },
- ),
- ):
- response = httpx.post(url, json=payload, headers=headers, timeout=30)
- if response.status_code not in (201, 204, 409):
- raise SystemExit(f"Keycloak bootstrap failed at {url}: {response.status_code} {response.text[:400]}")
-
- listed = httpx.get(f"{base}/{REALM}/clients", params={"clientId": CLIENT_ID}, headers=headers, timeout=30)
- listed.raise_for_status()
- entries = listed.json()
- if not entries:
- raise SystemExit(f"Keycloak has no client {CLIENT_ID!r} after bootstrap")
- internal_id = entries[0]["id"]
- secret = httpx.get(f"{base}/{REALM}/clients/{internal_id}/client-secret", headers=headers, timeout=30)
- secret.raise_for_status()
- return str(secret.json().get("value") or CLIENT_SECRET)
+KEYCLOAK = os.environ.get("KEYCLOAK_URL", "http://localhost:8080")
def issue_id_token(client_secret: str) -> str:
@@ -146,7 +82,7 @@ def issue_id_token(client_secret: str) -> str:
async def main() -> int:
- client_secret = bootstrap()
+ client_secret = bootstrap(KEYCLOAK)["oidc_client_secret"]
id_token = issue_id_token(client_secret)
issuer = f"{KEYCLOAK}/realms/{REALM}"
diff --git a/scripts/ci/keycloak_realm.py b/scripts/ci/keycloak_realm.py
new file mode 100644
index 000000000..eda6141f8
--- /dev/null
+++ b/scripts/ci/keycloak_realm.py
@@ -0,0 +1,220 @@
+#!/usr/bin/env python3
+"""Bootstrap one Keycloak realm that both containerised-IdP probes share.
+
+Depth 8.1. Driven by `.github/workflows/sso-live.yml`.
+
+One realm, one user, two clients — an OIDC one and a SAML one — because the
+alternative is two probes each standing up their own Keycloak, which doubles
+the slowest step in the workflow to prove the same provider twice.
+
+Everything here is idempotent: a `409` from Keycloak means the object this
+wanted already exists, which is the state the caller asked for. A workflow
+step that is retried, or a second probe running against the realm the first
+one created, must not fail for having arrived second.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+import httpx
+
+REALM = "aisoc-ci"
+
+# OIDC half.
+OIDC_CLIENT_ID = "aisoc-console"
+OIDC_REDIRECT_URI = "http://localhost:8000/auth/oidc/callback"
+
+# SAML half. The client id *is* the SP entity id — that is how Keycloak
+# identifies a service provider, and it is what the `Audience` of every
+# assertion will name, so it has to equal what `_saml_settings()` builds
+# from `SAML_SP_ENTITY_ID`.
+SP_ORIGIN = "http://sp.aisoc-ci.test"
+SP_ENTITY_ID = f"{SP_ORIGIN}/auth/saml/metadata"
+SP_ACS_URL = f"{SP_ORIGIN}/auth/saml/acs"
+
+USERNAME = "alice"
+PASSWORD = "alice-ci-password"
+
+# The group the SAML and OIDC connections both map to a role. Mapping a
+# group to a role is the half of provisioning a self-authored provider
+# cannot exercise honestly, because the group has to survive a real
+# provider's own attribute pipeline to arrive.
+GROUP = "soc-analysts"
+
+
+class KeycloakError(RuntimeError):
+ """Keycloak refused a bootstrap step, with its own message attached."""
+
+
+def admin_token(keycloak: str) -> str:
+ response = httpx.post(
+ f"{keycloak}/realms/master/protocol/openid-connect/token",
+ data={
+ "grant_type": "password",
+ "client_id": "admin-cli",
+ "username": "admin",
+ "password": "admin",
+ },
+ timeout=30,
+ )
+ response.raise_for_status()
+ return str(response.json()["access_token"])
+
+
+def _create(url: str, payload: dict[str, Any], headers: dict[str, str]) -> None:
+ """POST an object, treating "it already exists" as success."""
+ response = httpx.post(url, json=payload, headers=headers, timeout=30)
+ if response.status_code not in (201, 204, 409):
+ raise KeycloakError(f"Keycloak bootstrap failed at {url}: {response.status_code} {response.text[:400]}")
+
+
+def bootstrap(keycloak: str) -> dict[str, str]:
+ """A realm, two clients, a group and a user. Returns the OIDC secret.
+
+ The OIDC client secret is **read back** rather than assumed. Keycloak
+ generates one when a confidential client is created and does not
+ necessarily honour a `secret` supplied in the creation payload, so
+ sending one and then using it is a coin flip that answers
+ `400 unauthorized_client` — a message about the grant, for a problem
+ in the registration.
+ """
+ headers = {"Authorization": f"Bearer {admin_token(keycloak)}"}
+ base = f"{keycloak}/admin/realms"
+
+ _create(base, {"realm": REALM, "enabled": True}, headers)
+ _create(f"{base}/{REALM}/groups", {"name": GROUP}, headers)
+
+ _create(
+ f"{base}/{REALM}/clients",
+ {
+ "clientId": OIDC_CLIENT_ID,
+ "publicClient": False,
+ "clientAuthenticatorType": "client-secret",
+ "standardFlowEnabled": True,
+ # The resource-owner grant is how the OIDC probe obtains a
+ # token without a browser. It is enabled on the CI realm only
+ # and is not something AiSOC asks a deployment for.
+ "directAccessGrantsEnabled": True,
+ "redirectUris": [OIDC_REDIRECT_URI],
+ },
+ headers,
+ )
+
+ _create(
+ f"{base}/{REALM}/clients",
+ {
+ "clientId": SP_ENTITY_ID,
+ "protocol": "saml",
+ "enabled": True,
+ "redirectUris": [SP_ACS_URL, f"{SP_ORIGIN}/*"],
+ "attributes": {
+ # Sign both the response and the assertion. python3-saml
+ # is configured `strict`, and the signature is the only
+ # thing standing between an assertion and a session.
+ "saml.server.signature": "true",
+ "saml.assertion.signature": "true",
+ "saml.signature.algorithm": "RSA_SHA256",
+ # The SP holds no signing key in CI, so Keycloak must not
+ # insist that the AuthnRequest carry one. This is the one
+ # setting here that a production deployment should invert.
+ "saml.client.signature": "false",
+ "saml.authnstatement": "true",
+ "saml_name_id_format": "email",
+ "saml_force_name_id_format": "true",
+ "saml_assertion_consumer_url_post": SP_ACS_URL,
+ },
+ # `saml_acs` reads `attributes["email"]` before it falls back
+ # to the NameID, and reads `groups` for the role mapping.
+ # Neither arrives without a mapper.
+ "protocolMappers": [
+ {
+ "name": "email",
+ "protocol": "saml",
+ "protocolMapper": "saml-user-property-mapper",
+ "config": {
+ "user.attribute": "email",
+ "attribute.name": "email",
+ "attribute.nameformat": "Basic",
+ },
+ },
+ {
+ "name": "groups",
+ "protocol": "saml",
+ "protocolMapper": "saml-group-membership-mapper",
+ "config": {
+ "attribute.name": "groups",
+ "attribute.nameformat": "Basic",
+ "single": "false",
+ "full.path": "false",
+ },
+ },
+ ],
+ },
+ headers,
+ )
+
+ _create(
+ f"{base}/{REALM}/users",
+ {
+ "username": USERNAME,
+ "email": EMAIL,
+ "emailVerified": True,
+ "enabled": True,
+ # Keycloak's `VERIFY_PROFILE` required action is on by default
+ # and is evaluated against profile completeness at token time
+ # rather than stored on the user, so the account reads as
+ # `requiredActions: []` and still refuses the password grant
+ # with `invalid_grant: "Account is not fully set up"`. A name
+ # is what it is waiting for; without these two fields no probe
+ # here can obtain a token at all.
+ "firstName": "Alice",
+ "lastName": "Analyst",
+ "groups": [GROUP],
+ "credentials": [{"type": "password", "value": PASSWORD, "temporary": False}],
+ },
+ headers,
+ )
+
+ listed = httpx.get(
+ f"{base}/{REALM}/clients",
+ params={"clientId": OIDC_CLIENT_ID},
+ headers=headers,
+ timeout=30,
+ )
+ listed.raise_for_status()
+ entries = listed.json()
+ if not entries:
+ raise KeycloakError(f"Keycloak has no client {OIDC_CLIENT_ID!r} after bootstrap")
+ secret = httpx.get(
+ f"{base}/{REALM}/clients/{entries[0]['id']}/client-secret",
+ headers=headers,
+ timeout=30,
+ )
+ secret.raise_for_status()
+ return {"oidc_client_secret": str(secret.json().get("value") or "")}
+
+
+def saml_descriptor(keycloak: str) -> str:
+ """The realm's SAML IdP metadata, as an operator would paste it.
+
+ This is the document `aisoc_sso_connections.metadata_xml` holds, and
+ reading it from the provider rather than writing it by hand is the
+ point: a self-authored metadata document agrees with a self-authored
+ assertion by construction.
+ """
+ response = httpx.get(f"{keycloak}/realms/{REALM}/protocol/saml/descriptor", timeout=30)
+ response.raise_for_status()
+ body = response.text
+ if "IDPSSODescriptor" not in body or "X509Certificate" not in body:
+ raise KeycloakError("Keycloak's SAML descriptor carries no IdP descriptor or no certificate")
+ return body
+
+
+def saml_entity_id(descriptor: str) -> str:
+ match = re.search(r'entityID="([^"]+)"', descriptor)
+ if not match:
+ raise KeycloakError("Keycloak's SAML descriptor declares no entityID")
+ return match.group(1)
diff --git a/scripts/ci/keycloak_saml_probe.py b/scripts/ci/keycloak_saml_probe.py
new file mode 100644
index 000000000..e7d5fecfd
--- /dev/null
+++ b/scripts/ci/keycloak_saml_probe.py
@@ -0,0 +1,480 @@
+#!/usr/bin/env python3
+"""A real Keycloak signs somebody in to the real app, over SAML.
+
+Depth 8.1. Driven by `.github/workflows/sso-live.yml`.
+
+What this proves that the sibling probes do not
+-----------------------------------------------
+`keycloak_oidc_probe.py` takes a real Keycloak `id_token` through the API's
+own verifier. It is a strong check on one function and it stops at the
+function: nothing about it says a sign-in completes.
+
+`tests/isolation/test_sso_live.py` drives the whole SAML sign-in, but
+against an identity provider this repository authors — a keypair and a
+metadata document it also writes. A self-authored provider agrees with a
+self-authored expectation by construction, which is the shape this
+repository keeps rediscovering as "the test double was more capable than
+the real thing".
+
+This probe closes the gap between them. It walks the **entire SP-initiated
+SAML flow**: the app builds an `AuthnRequest` from the trust material an
+operator stored on the connection, a real Keycloak renders its own login
+page, a real person's credentials are posted to it, Keycloak mints and
+signs a real `Response`, and that document is posted back to the real
+`/auth/saml/acs` of an application built by `create_application()` against
+real Postgres with every migration applied.
+
+There is no browser, but there is a browser *hop*: the redirect is
+followed, the login form is parsed out of Keycloak's own HTML and
+submitted with a cookie jar, and the auto-submitting POST form Keycloak
+answers with is what supplies the assertion. The only thing a browser
+would add is JavaScript, which Keycloak's login form does not require.
+
+The negative control
+--------------------
+After the positive run, the **same** assertion is replayed against the
+same connection with one byte-range changed: the certificate in the stored
+metadata is swapped for a different realm's. A handler that skipped
+signature verification — or that read its trust anchor from somewhere
+other than the connection — would sign Alice in twice. It must refuse the
+second.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import re
+import sys
+import uuid
+from html import unescape
+from pathlib import Path
+from typing import Any
+
+import httpx
+
+_HERE = Path(__file__).resolve()
+# `services/api` is the import root for `app.*`; this file's own directory
+# is the import root for `keycloak_realm`.
+sys.path.insert(0, str(_HERE.parents[2] / "services" / "api"))
+sys.path.insert(0, str(_HERE.parent))
+
+from keycloak_realm import ( # noqa: E402
+ EMAIL,
+ GROUP,
+ PASSWORD,
+ SP_ACS_URL,
+ SP_ENTITY_ID,
+ SP_ORIGIN,
+ USERNAME,
+ KeycloakError,
+ admin_token,
+ bootstrap,
+ saml_descriptor,
+ saml_entity_id,
+)
+
+KEYCLOAK = os.environ.get("KEYCLOAK_URL", "http://localhost:8080")
+
+# A realm whose only purpose is to own a signing key this deployment does
+# not trust, for the negative control.
+UNTRUSTED_REALM = "aisoc-ci-untrusted"
+
+# The group the connection maps to a role. `infosec`, not `admin`: a group
+# must never be able to confer the wildcard, and asserting the mapping
+# landed is only meaningful for a role that is not the default.
+MAPPED_ROLE = "infosec"
+
+# Written into `display_name` so a re-run can find and clear the row it
+# left behind, whatever issuer that run used.
+CONNECTION_MARKER = "Containerised Keycloak"
+
+# Every tenant this probe creates is slugged with it, so a re-run can
+# remove its own leftovers and nothing else.
+TENANT_SLUG_PREFIX = "kc-probe-"
+
+
+def _dsn() -> str:
+ value = (os.environ.get("ISOLATION_SSO_DSN") or os.environ.get("DATABASE_URL") or "").strip()
+ if not value:
+ raise SystemExit(
+ "ISOLATION_SSO_DSN is not set. This probe needs real Postgres with every "
+ "migration applied; it has no offline mode and must not appear to pass without one."
+ )
+ return value
+
+
+def _untrusted_certificate() -> str:
+ """A signing certificate from a realm this deployment never configured."""
+ headers = {"Authorization": f"Bearer {admin_token(KEYCLOAK)}"}
+ response = httpx.post(
+ f"{KEYCLOAK}/admin/realms",
+ json={"realm": UNTRUSTED_REALM, "enabled": True},
+ headers=headers,
+ timeout=30,
+ )
+ if response.status_code not in (201, 204, 409):
+ raise KeycloakError(f"could not create the untrusted realm: {response.status_code} {response.text[:300]}")
+
+ descriptor = httpx.get(f"{KEYCLOAK}/realms/{UNTRUSTED_REALM}/protocol/saml/descriptor", timeout=30)
+ descriptor.raise_for_status()
+ match = re.search(r"<ds:X509Certificate>([^<]+)</ds:X509Certificate>", descriptor.text)
+ if not match:
+ raise KeycloakError("the untrusted realm's descriptor carries no certificate")
+ return match.group(1)
+
+
+def _form_action(html: str, *, needle: str) -> str:
+ """The `action` of the form in *html* whose markup contains *needle*."""
+ for form in re.finditer(r"<form\b[^>]*>", html, flags=re.IGNORECASE):
+ action = re.search(r'action="([^"]+)"', form.group(0))
+ if action and needle in form.group(0):
+ return unescape(action.group(1))
+ # Keycloak renders exactly one form on its login page, so falling back
+ # to "the only form there is" is honest rather than a guess — and it
+ # survives a theme that drops the id this would otherwise match on.
+ only = re.search(r'<form\b[^>]*action="([^"]+)"', html, flags=re.IGNORECASE)
+ if only:
+ return unescape(only.group(1))
+ raise KeycloakError("Keycloak's login page carried no form; its login theme has changed shape")
+
+
+def _hidden_field(html: str, name: str) -> str | None:
+ match = re.search(
+ rf'<input[^>]*name="{re.escape(name)}"[^>]*value="([^"]*)"',
+ html,
+ flags=re.IGNORECASE,
+ )
+ if match:
+ return unescape(match.group(1))
+ # Attribute order is not fixed in generated markup.
+ match = re.search(
+ rf'<input[^>]*value="([^"]*)"[^>]*name="{re.escape(name)}"',
+ html,
+ flags=re.IGNORECASE,
+ )
+ return unescape(match.group(1)) if match else None
+
+
+class _Cookies:
+ """The hop's own cookie store, because the stock one cannot do this.
+
+ Keycloak sets `AUTH_SESSION_ID`, `KC_RESTART` and
+ `KC_AUTH_SESSION_HASH` with `SameSite=None` — SAML's POST binding is
+ cross-site by design — and the cookie specification requires
+ `SameSite=None` to be paired with `Secure`. It does so whatever the
+ realm's `sslRequired` says, so there is no Keycloak setting that
+ turns it off.
+
+ Python's `http.cookiejar` then refuses to return a `Secure` cookie
+ over `http://`. Browsers make an exception for loopback, which they
+ treat as a trustworthy origin, and that exception is the only reason
+ anybody can run Keycloak's dev mode at all. `httpx` offers no way to
+ supply that rule: `Client._merge_cookies` rebuilds the jar with the
+ default policy on every outgoing request, so a custom
+ `CookiePolicy` is silently discarded and the symptom is Keycloak's
+ "cookies are disabled in your browser".
+
+ Carrying the cookies explicitly is not a more capable fake — it is
+ the browser behaviour Keycloak is relying on, written out. Nothing
+ about AiSOC is stubbed by it.
+ """
+
+ def __init__(self) -> None:
+ self._jar: dict[str, str] = {}
+
+ def absorb(self, response: httpx.Response) -> None:
+ for raw in response.headers.get_list("set-cookie"):
+ name, _, rest = raw.partition("=")
+ value = rest.split(";", 1)[0]
+ self._jar[name.strip()] = value
+
+ def header(self) -> dict[str, str]:
+ if not self._jar:
+ return {}
+ return {"Cookie": "; ".join(f"{k}={v}" for k, v in self._jar.items())}
+
+
+def _follow(client: httpx.Client, cookies: _Cookies, response: httpx.Response, *, limit: int = 10) -> httpx.Response:
+ """Walk redirects by hand, absorbing cookies at every hop.
+
+ `follow_redirects=True` would hide the intermediate `Set-Cookie`
+ headers from the store above, which is where Keycloak puts the
+ session it then asks for back.
+ """
+ for _ in range(limit):
+ cookies.absorb(response)
+ if response.status_code not in (301, 302, 303, 307, 308):
+ return response
+ location = response.headers.get("location", "")
+ if not location:
+ return response
+ response = client.get(str(response.url.join(location)), headers=cookies.header())
+ raise KeycloakError("Keycloak redirected more times than a sign-in should need")
+
+
+def browser_hop(sso_redirect_url: str) -> tuple[str, str]:
+ """Walk Keycloak's login page the way a browser would.
+
+ Returns `(SAMLResponse, RelayState)` exactly as the auto-submitting
+ form Keycloak answers with carries them.
+ """
+ cookies = _Cookies()
+ with httpx.Client(timeout=30, follow_redirects=False) as browser:
+ page = _follow(browser, cookies, browser.get(sso_redirect_url))
+ if page.status_code != 200:
+ raise KeycloakError(f"Keycloak did not render a login page: {page.status_code} {page.text[:300]}")
+
+ action = _form_action(page.text, needle="kc-form-login")
+ posted = _follow(
+ browser,
+ cookies,
+ browser.post(
+ action,
+ data={"username": USERNAME, "password": PASSWORD, "credentialId": ""},
+ headers={**cookies.header(), "Content-Type": "application/x-www-form-urlencoded"},
+ ),
+ )
+
+ saml_response = _hidden_field(posted.text, "SAMLResponse")
+ if not saml_response:
+ raise KeycloakError("Keycloak did not answer the login with a SAMLResponse. Its reply began: " + posted.text[:400])
+ return saml_response, (_hidden_field(posted.text, "RelayState") or "")
+
+
+async def _seed_connection(dsn: str, *, issuer: str, metadata_xml: str) -> uuid.UUID:
+ """A tenant and the enabled SAML connection an administrator would create.
+
+ Written through SQL rather than through `POST /sso-connections`
+ because that route needs an authenticated administrator, and minting
+ one here would make the probe depend on the very login it is proving.
+ The row's shape is the route's shape, pinned by the route's own tests.
+
+ Idempotent for the same reason the Keycloak bootstrap is: a retried
+ step, or a second run against a database that is not fresh, must not
+ fail on the deployment-wide unique index over `issuer`. A failure here
+ reads as "SAML is broken" when it only means "this ran twice".
+ """
+ import sqlalchemy
+ 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)
+ tenant_id = uuid.uuid4()
+ try:
+ async with maker() as session:
+ # `users.email` is unique across the whole deployment, so the
+ # account a previous run provisioned would make
+ # `complete_sso_login` fail on its insert — a collision
+ # between two runs, reported as a broken sign-in.
+ #
+ # The *user* is removed and the tenant is left behind, on
+ # purpose. Deleting the tenant cascades into `audit_log`,
+ # whose trigger refuses a DELETE outright (migration `101`),
+ # so a probe that tidied up properly would be refused by the
+ # immutability control — correctly. `audit_log.actor_id` is
+ # `ON DELETE SET NULL`, which is why removing the user is
+ # allowed where removing the tenant is not.
+ await session.execute(
+ sqlalchemy.text("DELETE FROM users WHERE email = :e"),
+ {"e": EMAIL},
+ )
+ await session.execute(
+ sqlalchemy.text("INSERT INTO tenants (id, name, slug) VALUES (:i, :n, :s)"),
+ {
+ "i": tenant_id,
+ "n": f"{TENANT_SLUG_PREFIX}{tenant_id.hex[:8]}",
+ "s": f"{TENANT_SLUG_PREFIX}{tenant_id.hex[:8]}",
+ },
+ )
+ # The table's `WITH CHECK` has no null escape: a tenant
+ # configures its own connection, so this write binds the
+ # context exactly as the console's session does. The *read* on
+ # the callback path is unbound, because resolving the row is
+ # what decides the tenant.
+ await session.execute(
+ sqlalchemy.text("SELECT set_config('app.current_tenant_id', :t, FALSE)"),
+ {"t": str(tenant_id)},
+ )
+ # The delete is unbound on purpose: a leftover row from an
+ # earlier run belongs to a tenant this session is not bound
+ # to, so a bound delete would match nothing and the insert
+ # below would still collide.
+ #
+ # Matched on the marker as well as the issuer. A previous run
+ # against a different `KEYCLOAK_URL` left a row under a
+ # *different* issuer, and `resolve_saml_connection` then
+ # correctly refuses to guess between two providers — so the
+ # probe would fail with "no connection configured" for a
+ # reason that is not a defect.
+ await session.execute(sqlalchemy.text("SELECT set_config('app.current_tenant_id', '', FALSE)"))
+ await session.execute(
+ sqlalchemy.text("DELETE FROM aisoc_sso_connections WHERE issuer = :i OR display_name = :marker"),
+ {"i": issuer, "marker": CONNECTION_MARKER},
+ )
+ await session.execute(
+ sqlalchemy.text("SELECT set_config('app.current_tenant_id', :t, FALSE)"),
+ {"t": str(tenant_id)},
+ )
+ await session.execute(
+ sqlalchemy.text("""
+ INSERT INTO aisoc_sso_connections
+ (tenant_id, provider, issuer, display_name, enabled,
+ group_role_mapping, default_role, metadata_xml)
+ VALUES (:t, 'saml', :iss, :marker, TRUE,
+ CAST(:map AS jsonb), 'viewer', :xml)
+ """),
+ {
+ "t": tenant_id,
+ "iss": issuer,
+ "map": f'{{"{GROUP}": "{MAPPED_ROLE}"}}',
+ "marker": CONNECTION_MARKER,
+ "xml": metadata_xml,
+ },
+ )
+ await session.commit()
+ finally:
+ await engine.dispose()
+ return tenant_id
+
+
+async def _replace_connection_metadata(dsn: str, *, issuer: str, metadata_xml: str) -> None:
+ import sqlalchemy
+ 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)
+ try:
+ async with maker() as session:
+ row = (
+ await session.execute(
+ sqlalchemy.text("SELECT tenant_id FROM aisoc_sso_connections WHERE issuer = :i"),
+ {"i": issuer},
+ )
+ ).first()
+ if row is None:
+ raise KeycloakError("the connection this probe created is gone")
+ await session.execute(
+ sqlalchemy.text("SELECT set_config('app.current_tenant_id', :t, FALSE)"),
+ {"t": str(row[0])},
+ )
+ await session.execute(
+ sqlalchemy.text("UPDATE aisoc_sso_connections SET metadata_xml = :x WHERE issuer = :i"),
+ {"x": metadata_xml, "i": issuer},
+ )
+ await session.commit()
+ finally:
+ await engine.dispose()
+
+
+def _application() -> Any:
+ """The real app, configured the way a SAML deployment is.
+
+ `ENVIRONMENT=test` and never `development`: `development` is in
+ `AUTH_BYPASS_ENVIRONMENTS`, so an uncredentialed request would resolve
+ to a demo administrator — inside the one probe whose point is that the
+ principal comes from the assertion.
+
+ `SAML_IDP_*` deliberately names a provider whose key this deployment
+ does not hold. If the handler ever goes back to reading its trust
+ anchor from the environment, nothing below can pass.
+ """
+ os.environ["ENVIRONMENT"] = "test"
+ os.environ["SSO_ENABLED"] = "true"
+ os.environ["SAML_SP_ACS_URL"] = SP_ACS_URL
+ os.environ["SAML_SP_ENTITY_ID"] = SP_ENTITY_ID
+ os.environ["SAML_IDP_ENTITY_ID"] = "https://environment-idp.invalid/metadata"
+ os.environ["SAML_IDP_SSO_URL"] = "https://environment-idp.invalid/sso"
+ os.environ["SAML_IDP_CERT"] = ""
+ os.environ["OTEL_SDK_DISABLED"] = "true"
+
+ from app.main import create_application # noqa: PLC0415
+
+ return create_application()
+
+
+async def main() -> int:
+ dsn = _dsn()
+ os.environ["DATABASE_URL"] = dsn
+
+ bootstrap(KEYCLOAK)
+ descriptor = saml_descriptor(KEYCLOAK)
+ issuer = saml_entity_id(descriptor)
+ await _seed_connection(dsn, issuer=issuer, metadata_xml=descriptor)
+ print(f"OK: an enabled SAML connection carries Keycloak's own descriptor (issuer={issuer}).")
+
+ transport = httpx.ASGITransport(app=_application())
+ async with httpx.AsyncClient(transport=transport, base_url=SP_ORIGIN) as app_client:
+ # 1. The app builds an AuthnRequest from the connection's metadata.
+ start = await app_client.get("/auth/saml/login", params={"redirect": "/alerts"})
+ if start.status_code not in (302, 303, 307):
+ raise SystemExit(f"/auth/saml/login did not redirect: {start.status_code} {start.text[:400]}")
+ location = start.headers["location"]
+ if not location.startswith(KEYCLOAK):
+ raise SystemExit(
+ f"/auth/saml/login redirected to {location[:200]!r}, which is not the Keycloak the "
+ "connection names — the trust anchor did not come from the connection."
+ )
+ print("OK: the app's AuthnRequest is addressed to the IdP the connection names.")
+
+ # 2. A real person signs in at a real Keycloak.
+ saml_response, relay_state = browser_hop(location)
+ print("OK: Keycloak authenticated the user and signed a Response.")
+
+ # 3. That Response is posted back to the real ACS.
+ landed = await app_client.post(
+ "/auth/saml/acs",
+ data={"SAMLResponse": saml_response, "RelayState": relay_state or "/alerts"},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ if landed.status_code != 302:
+ raise SystemExit(f"the ACS refused a genuine assertion: {landed.status_code} {landed.text[:600]}")
+ fragment = landed.headers["location"]
+ match = re.search(r"#access_token=([^&]+)", fragment)
+ if not match:
+ raise SystemExit(f"the ACS issued no access token; it redirected to {fragment[:200]!r}")
+ access_token = match.group(1)
+
+ # 4. The token is the API's own, and it describes the right person.
+ from app.core.security import decode_token # noqa: PLC0415
+
+ claims = decode_token(access_token)
+ if (claims.get("email") or "").lower() != EMAIL:
+ raise SystemExit(f"signed in as {claims.get('email')!r}, expected {EMAIL!r}")
+ if claims.get("role") != MAPPED_ROLE:
+ raise SystemExit(
+ f"the connection maps {GROUP!r} to {MAPPED_ROLE!r} but the session carries "
+ f"{claims.get('role')!r}; a group the IdP asserted did not reach the role mapping"
+ )
+ print(
+ f"OK: a real Keycloak SAML assertion signed {EMAIL} in to the real app "
+ f"(role={claims.get('role')}, tenant={claims.get('tenant_id')})."
+ )
+
+ # 5. The negative control. Same assertion, same connection, one
+ # certificate swapped for a realm this deployment never trusted.
+ trusted_certificate = re.search(r"<ds:X509Certificate>([^<]+)</ds:X509Certificate>", descriptor)
+ if trusted_certificate is None:
+ # `saml_descriptor` already refused a document with no
+ # certificate, so this is unreachable — and saying so beats a
+ # `# type: ignore`, which would also suppress the day the
+ # descriptor's shape changes and the negative control starts
+ # silently comparing a document against itself.
+ raise KeycloakError("the descriptor that signed this assertion carries no certificate to swap")
+ untrusted = descriptor.replace(trusted_certificate.group(1), _untrusted_certificate())
+ await _replace_connection_metadata(dsn, issuer=issuer, metadata_xml=untrusted)
+ replayed = await app_client.post(
+ "/auth/saml/acs",
+ data={"SAMLResponse": saml_response, "RelayState": relay_state or "/alerts"},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ if replayed.status_code == 302 and "access_token=" in replayed.headers.get("location", ""):
+ print("FAIL: the same assertion was accepted against a certificate this deployment does not trust.")
+ return 1
+ print(f"OK: the same assertion is refused once the connection names another key ({replayed.status_code}).")
+
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(asyncio.run(main()))
diff --git a/scripts/readme_gates.py b/scripts/readme_gates.py
index 8c7197873..cb56185e4 100644
--- a/scripts/readme_gates.py
+++ b/scripts/readme_gates.py
@@ -539,38 +539,68 @@ def _truth_table_executable() -> int | None:
return int(m.group(1)) if m else None
-def _matrix_counts() -> tuple[int, int] | None:
- """(gated, partial) counted from the matrix rows themselves, not its prose."""
+def _matrix_statuses() -> list[str]:
+ """The Status *cell* of every data row, located by its column header.
+
+ This used to classify a row by scanning the whole line for the words
+ `NO GATE`, `PARTIAL` and `GATED`, in that order. A row's Notes cell is
+ prose, so the moment a GATED row explained the history behind its own
+ status -- "this row was PARTIAL because ..." -- it was counted as PARTIAL,
+ and the summary the author had correctly recomputed with
+ `scripts/check_claim_gate_matrix.py` was reported as stale against it.
+
+ Two honest components disagreeing about one table reads as drift rather
+ than as a parser bug, so the cheap fix is to reword the row and lose the
+ history. Reading the cell the column header names costs the same and
+ cannot be fooled by anything written in another column.
+ """
if not CLAIM_MATRIX.exists():
- return None
- gated = partial = 0
- for line in _read(CLAIM_MATRIX).splitlines():
+ return []
+ lines = _read(CLAIM_MATRIX).splitlines()
+ header_idx = status_col = None
+ for i, line in enumerate(lines):
if not line.lstrip().startswith("|"):
continue
- if "NO GATE" in line:
- continue
- if "PARTIAL" in line:
- partial += 1
- elif "GATED" in line:
- gated += 1
+ cells = [c.strip().casefold() for c in line.strip().strip("|").split("|")]
+ if "status" in cells:
+ header_idx, status_col = i, cells.index("status")
+ break
+ if header_idx is None or status_col is None:
+ raise ValueError(
+ f"{_doc_label(CLAIM_MATRIX)} has no Status column; the claim-to-gate "
+ "table header is what every count in this gate is located by."
+ )
+
+ statuses: list[str] = []
+ for line in lines[header_idx + 1 :]:
+ s = line.strip()
+ if not s.startswith("|"):
+ break # the table ended
+ if re.match(r"^\|[\s:|-]+\|?$", s):
+ continue # the header separator
+ cells = [c.strip() for c in s.strip("|").split("|")]
+ if len(cells) > status_col:
+ statuses.append(cells[status_col].strip("`* ").upper())
+ return statuses
+
+
+def _matrix_counts() -> tuple[int, int] | None:
+ """(gated, partial) counted from the matrix rows themselves, not its prose."""
+ statuses = _matrix_statuses()
+ gated = sum(1 for s in statuses if s.startswith("GATED"))
+ partial = sum(1 for s in statuses if s.startswith("PARTIAL"))
return (gated, partial) if (gated or partial) else None
def _matrix_row_total() -> int | None:
"""Every data row, `NO GATE` included.
- `_matrix_counts` deliberately skips `NO GATE` rows, so the tally prose —
- "N rows — G GATED / P PARTIAL / Z NO GATE" — had its *leading* figure
+ `_matrix_counts` deliberately skips `NO GATE` rows, so the tally prose --
+ "N rows — G GATED / P PARTIAL / Z NO GATE" -- had its *leading* figure
checked by nothing. Returned separately rather than widening that
function's tuple, which is unpacked as a pair by its tests.
"""
- if not CLAIM_MATRIX.exists():
- return None
- rows = sum(
- 1
- for line in _read(CLAIM_MATRIX).splitlines()
- if line.lstrip().startswith("|") and ("NO GATE" in line or "PARTIAL" in line or "GATED" in line)
- )
+ rows = sum(1 for s in _matrix_statuses() if s.startswith("GATED") or s.startswith("PARTIAL") or s.startswith("NO GATE"))
return rows or None
diff --git a/services/api/app/auth/saml.py b/services/api/app/auth/saml.py
index 989cb993a..19dfff279 100644
--- a/services/api/app/auth/saml.py
+++ b/services/api/app/auth/saml.py
@@ -127,6 +127,29 @@ def _saml_settings(idp: dict[str, Any] | None = None) -> dict[str, Any]:
return {
"strict": True,
"debug": os.getenv("SAML_DEBUG", "false").lower() == "true",
+ "security": {
+ # Keycloak's built-in "role list" mapper is on by default and
+ # emits **one `<Attribute Name="Role">` element per role**, so
+ # a stock Keycloak sends six of them before anybody adds a
+ # mapper. python3-saml defaults `allowRepeatAttributeName` to
+ # False and raises `Found an Attribute element with duplicated
+ # Name` out of `process_response()` — past every `except` this
+ # handler has, so the ACS answered an unhandled 500 and **no
+ # Keycloak user could complete a SAML sign-in at all**.
+ #
+ # Repeated `<Attribute>` elements are legal SAML 2.0 and this
+ # merges their values rather than refusing the assertion. It is
+ # not a relaxation of trust: `process_response()` calls
+ # `response.is_valid()` — signature, conditions and audience —
+ # and only reads attributes once that has passed, so an
+ # attacker cannot add an element without invalidating the
+ # signature that admitted it.
+ #
+ # Found by depth 8.1's containerised-IdP probe. The
+ # self-authored provider in `tests/isolation/test_sso_live.py`
+ # emits one attribute per name, so it could not have found it.
+ "allowRepeatAttributeName": True,
+ },
"sp": {
"entityId": sp_entity,
"assertionConsumerService": {
diff --git a/services/api/app/auth/saml_metadata.py b/services/api/app/auth/saml_metadata.py
index e21a6dd2a..be7d4a103 100644
--- a/services/api/app/auth/saml_metadata.py
+++ b/services/api/app/auth/saml_metadata.py
@@ -170,6 +170,16 @@ async def resolve_saml_connection(db: AsyncSession, *, issuer: str | None = None
With more than one and no issuer the answer is `None` rather than a
guess, because picking an arbitrary identity provider for somebody's
sign-in is worse than refusing.
+
+ The `CAST(:i AS TEXT)` is load-bearing, not decoration. A bind
+ parameter whose only use is `:i IS NULL` gives Postgres nothing to
+ infer a type from, so asyncpg answers `could not determine data type
+ of parameter $1` — and only on the `None` branch, which is the branch
+ the console takes. The `except` below then turned that into "no
+ enabled SAML connection is configured", so an operator who *had*
+ configured one was sent to configure it again. Depth 8.1 reproduced
+ it against real Postgres; `check_text_bind_casts.py` now refuses the
+ untyped spelling.
"""
try:
rows = (
@@ -179,7 +189,7 @@ async def resolve_saml_connection(db: AsyncSession, *, issuer: str | None = None
SELECT id, tenant_id, issuer, display_name, metadata_url, metadata_xml
FROM aisoc_sso_connections
WHERE provider = 'saml' AND enabled = TRUE
- AND (:i IS NULL OR issuer = :i)
+ AND (CAST(:i AS TEXT) IS NULL OR issuer = CAST(:i AS TEXT))
ORDER BY created_at
LIMIT 2
""").bindparams(i=issuer)
diff --git a/tests/test_readme_figures_gate.py b/tests/test_readme_figures_gate.py
index e07d1e569..e3559296d 100644
--- a/tests/test_readme_figures_gate.py
+++ b/tests/test_readme_figures_gate.py
@@ -113,6 +113,35 @@ def test_partial_rows_are_not_counted_as_gated(tree: Path) -> None:
assert (gated, partial) == (2, 1)
+def test_a_status_word_in_the_notes_does_not_change_the_count(tree: Path) -> None:
+ """A GATED row may say the word PARTIAL in its Notes and still be GATED.
+
+ The count used to come from scanning the whole line for `NO GATE`, then
+ `PARTIAL`, then `GATED`, so the first row that recorded *why* it had been
+ PARTIAL -- which is exactly what a row is supposed to say when a gate is
+ built and the status earned -- was counted as PARTIAL. The summary its
+ author had correctly recomputed with `check_claim_gate_matrix.py` then
+ read as stale, and the cheap fix would have been to delete the history.
+ """
+ matrix = MATRIX.replace(
+ "| two | README | ci.yml | GATED | - |",
+ "| two | README | ci.yml | GATED | this row was PARTIAL until the containerised leg was observed to pass; NO GATE before that |",
+ )
+ (tree / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md").write_text(matrix)
+ gates = _load_gates(tree)
+ assert gates._matrix_counts() == (2, 1)
+ assert gates._matrix_row_total() == 3
+
+
+def test_a_matrix_without_a_status_column_is_refused(tree: Path) -> None:
+ """Unreadable is not the same as clean, and must not count as either."""
+ (tree / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md").write_text(
+ "# matrix\n\n| claim | source | gate | gap |\n|---|---|---|---|\n| one | README | ci.yml | - |\n"
+ )
+ with pytest.raises(ValueError, match="no Status column"):
+ _load_gates(tree)._matrix_counts()
+
+
def test_missing_sources_do_not_crash_the_gate(tmp_path: Path) -> None:
"""A partial checkout should skip these checks, not raise."""
(tmp_path / "README.md").write_text("833 executable. 2 GATED / 1 PARTIAL.\n")