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.

fix(sso): SAML trust comes from the connection, not the environment (fix pass 4.1) (#1192)

Beenu Arora857d6065d820
diff --git a/.github/workflows/sso-live.yml b/.github/workflows/sso-live.yml
new file mode 100644
index 000000000..368396eb2
--- /dev/null
+++ b/.github/workflows/sso-live.yml
@@ -0,0 +1,232 @@
+# SSO completes a sign-in — through the real app, against real providers.
+#
+# Why this exists
+# ---------------
+# `services/api/tests/test_sso_provisioning.py` asserts the *shape* of the
+# provisioning path: that the tenant is not an argument, that a group cannot
+# confer `admin`, that the token is signed with the key the API verifies
+# with. All true, and none of it answers whether anybody can sign in.
+#
+# Nothing drove either handler end to end, which is how fix-pass 4.1's
+# defect survived: `_saml_settings()` read its IdP trust anchor from
+# `SAML_IDP_*` while `aisoc_sso_connections.metadata_url` and
+# `.metadata_xml` — written by `POST /sso-connections`, returned by
+# `GET /sso-connections` — were read by nothing. On a stock install the
+# 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.
+name: SSO (live)
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ workflow_dispatch:
+
+# Per commit on push and per pull request on a PR. Keying on `github.ref`
+# makes a push to `main` cancel the run before it, which is how required
+# checks end up ungraded on the commits that matter most.
+concurrency:
+ group: sso-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:
+ sso-live:
+ name: SAML and OIDC sign in through the real app
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+
+ services:
+ postgres:
+ image: 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
+ # path 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 suite whose point is that the principal comes from
+ # the assertion.
+ ENVIRONMENT: test
+ OTEL_SDK_DISABLED: "true"
+
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+
+ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6
+ with:
+ python-version: "3.11"
+
+ # 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 python3-saml links against
+ run: sudo apt-get update -qq && sudo apt-get install -y -qq libxmlsec1-dev pkg-config
+
+ - 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: Refuse to continue without the SAML stack
+ run: |
+ python -c "import onelogin.saml2.auth" \
+ || { echo "python3-saml did not import; this suite would skip rather than grade."; 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;"
+
+ - name: A signed assertion and a real id_token sign somebody in
+ working-directory: services/api
+ env:
+ ISOLATION_SSO_DSN: ${{ env.SSO_DSN }}
+ DATABASE_URL: ${{ env.SSO_DSN }}
+ run: python -m pytest ../../tests/isolation/test_sso_live.py -v --tb=short
+
+ # The negative control.
+ #
+ # Putting the IdP trust anchor back where 4.1 found it — the
+ # environment — must make the suite go red. Without this, "alice
+ # signed in" would pass equally well against a deployment that was
+ # still ignoring the connection the operator configured, because the
+ # environment in that suite happens to name an IdP it does not hold
+ # the key for only by construction.
+ #
+ # Measured on the fix commit: two tests fail,
+ # `test_login_redirects_to_the_sso_url_in_the_connection_metadata`
+ # and `test_an_assertion_signed_by_the_connections_key_signs_someone_in`.
+ - name: The suite fails when SAML trust goes back to the environment
+ working-directory: services/api
+ env:
+ ISOLATION_SSO_DSN: ${{ env.SSO_DSN }}
+ DATABASE_URL: ${{ env.SSO_DSN }}
+ run: |
+ cp app/auth/saml.py /tmp/saml.bak
+ python - <<'PY'
+ import pathlib, sys
+ p = pathlib.Path("app/auth/saml.py")
+ s = p.read_text()
+ needle = " idp, connection_issuer = await _resolve_idp(db, issuer=claimed_issuer)"
+ if needle not in s:
+ print("negative control could not find the connection lookup to remove; it has "
+ "been reshaped and this control is no longer proving anything")
+ sys.exit(1)
+ s = s.replace(needle, " idp, connection_issuer = environment_idp_settings(), (claimed_issuer or '')", 1)
+ p.write_text(s)
+ PY
+ if python -m pytest ../../tests/isolation/test_sso_live.py -q >/dev/null 2>&1; then
+ cp /tmp/saml.bak app/auth/saml.py
+ echo "FAIL: the suite passed with SAML trust read from the environment."
+ exit 1
+ fi
+ cp /tmp/saml.bak app/auth/saml.py
+ echo "OK: reverting to environment-sourced SAML trust makes the suite fail, as it must."
+ python -m pytest ../../tests/isolation/test_sso_live.py -q
+
+ # ───────────────────────────────────────────────────────────────────────
+ # The containerised identity provider.
+ #
+ # 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.
+ #
+ # 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.
+ # ───────────────────────────────────────────────────────────────────────
+ keycloak-oidc:
+ name: A real Keycloak id_token verifies (unproven — see workflow header)
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+
+ 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. Digest-pinned, resolved from quay's own tag API at
+ # the time this file was written.
+ - 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://localhost: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
+
+ # The whole api lockfile, because the probe imports
+ # `app.auth.oidc` — the production verifier — and that module's
+ # import chain reaches `app.api.v1.deps`. A hand-curated pip list
+ # here would mean the probe runs against software nobody ships,
+ # which is the anti-pattern this repository already removed from its
+ # images.
+ - 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
+
+ # One script for both halves so a bootstrap that half-succeeded
+ # cannot leave the verification step reading a realm that is not
+ # there and reporting it as a verification failure.
+ - name: Bootstrap a realm, then verify a real id_token through the API's own code
+ env:
+ ENVIRONMENT: test
+ OTEL_SDK_DISABLED: "true"
+ run: python3 scripts/ci/keycloak_oidc_probe.py
diff --git a/FIX_PASS_PROGRESS.md b/FIX_PASS_PROGRESS.md
index d3ecfd7a5..087fc8581 100644
--- a/FIX_PASS_PROGRESS.md
+++ b/FIX_PASS_PROGRESS.md
@@ -101,7 +101,8 @@ conditional `numpy` pins collide into an unresolvable install. Parse with
## Wave 4: Enterprise identity, white-label and metering
-- [ ] **4.1** SSO completes in the console
+- [~] **4.1** SSO completes in the console
+ - Two of the three defects did **not** reproduce: the console fragment consumer (`authApi.completeSsoHandoff`) and the login-screen SSO entry both landed in v17.1.0. Neither was covered by a test, so six now pin them. The third reproduced exactly as written — `_saml_settings()` read its IdP trust anchor from `SAML_IDP_*` while the connection's own `metadata_url` / `metadata_xml` were read by nothing, so a SAML login redirected to the environment's IdP and a correctly signed assertion came back `invalid_response`. Fixed in `app/auth/saml_metadata.py`; the ACS also now lands on `/login?next=` with both tokens, because the old RelayState redirect lost the fragment to the console's own auth guard. Driven end to end against real Postgres and a real signed assertion in `sso-live.yml`. **Still `[~]`**: the containerised-IdP leg (`sso-live.yml :: keycloak-oidc`) has never been observed to pass — no container runtime would start where it was written — so the claim row is PARTIAL, not GATED.
- [ ] **4.2** Console MFA
- [ ] **4.3** White-label reaches every surface it claims
- [ ] **4.4** Metering counts what happened
diff --git a/ROADMAP.md b/ROADMAP.md
index a68f8926b..0e6c456d9 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **290 rows — 290 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **290 rows — 289 GATED / 1 PARTIAL / 0 NO GATE**. The one PARTIAL is "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).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index e3827c2c0..b8f26262e 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: 290 rows
-`GATED`, 0 `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: 289 rows
+`GATED`, 1 `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/apps/docs/docs/operations/enterprise-sso.md b/apps/docs/docs/operations/enterprise-sso.md
index ac252ee53..fc4b17911 100644
--- a/apps/docs/docs/operations/enterprise-sso.md
+++ b/apps/docs/docs/operations/enterprise-sso.md
@@ -147,6 +147,57 @@ unredeemed.
routes are live; configure the connection with either `metadata_url`
or `metadata_xml`.
+### The trust anchor is the connection, not the environment
+
+Until v17.2.0 it was neither: `SAML_IDP_ENTITY_ID`, `SAML_IDP_SSO_URL`
+and `SAML_IDP_CERT` decided which identity provider the deployment
+trusted, and the `metadata_url` / `metadata_xml` you set on a connection
+were stored, returned by `GET /sso-connections`, and read by nothing. A
+stock install sets none of those variables, so the trust anchor was
+empty and every assertion was refused — with the console showing a
+connection that looked configured.
+
+Now the connection decides. `metadata_xml` wins over `metadata_url`,
+because a document you pasted is your explicit statement of the trust
+material and should not be silently replaced by whatever a URL serves
+today. A `metadata_url` is fetched by the API through the same SSRF
+guard outbound playbook steps use, and cached for ten minutes per
+replica so an IdP outage does not sit in front of every sign-in.
+
+The `SAML_IDP_*` variables still work as a fallback, so a deployment
+configured before this change keeps working. A connection wins whenever
+one resolves.
+
+:::note More than one identity provider
+`/auth/saml/login` with no `?issuer=` resolves the single enabled SAML
+connection. With several configured it refuses rather than picking one,
+so link each provider's button to
+`/auth/saml/login?issuer=<entity id>`.
+:::
+
+### Why reading the assertion's `Issuer` is not a hole
+
+`/auth/saml/acs` reads `<saml:Issuer>` out of the POSTed response before
+anything has been verified, and uses it to choose which connection's
+certificate to verify against.
+
+That looks like the thing this feature refuses to do everywhere else,
+and it is not. The asserted issuer selects a **trust anchor**; it does
+not confer trust. An assertion naming an issuer whose private key the
+sender does not hold fails signature verification and authenticates
+nobody. The tenant still comes from the connection row — and the entity
+id handed to provisioning is the one the *connection* declares, not the
+one the assertion claimed.
+
+### Where the callback lands
+
+On `/login?next=…`, with the access and refresh tokens in the fragment —
+the same place the OIDC callback lands, and for the same reason. It used
+to redirect straight to the RelayState destination, whose auth guard
+rebuilds its bounce target from `pathname + search` and therefore
+**drops the fragment**, taking the only copy of the token with it. The
+fragment consumer lives on `/login`.
+
## Checking it works
```bash
diff --git a/apps/web/src/lib/sso-handoff.test.ts b/apps/web/src/lib/sso-handoff.test.ts
new file mode 100644
index 000000000..963b77890
--- /dev/null
+++ b/apps/web/src/lib/sso-handoff.test.ts
@@ -0,0 +1,126 @@
+/**
+ * The console's end of an SSO round trip.
+ *
+ * Fix pass 4.1 names three defects. Two of them — "no console code reads
+ * the fragment" and "the login page offers only email and password" —
+ * were fixed in v17.1.0 and were covered by no test, which is how a
+ * handler whose only caller is one `useEffect` quietly stops being called.
+ *
+ * These assertions exist so that stays true, and they are written against
+ * the real `completeSsoHandoff` rather than a mock of it: the behaviour
+ * under test is "what this function does to `window`", and a double
+ * cannot have that.
+ *
+ * Why the fragment at all: a query string reaches the server, the access
+ * log and the `Referer` header. A fragment does not. The cost is that the
+ * only copy of the token lives in `window.location.hash` until this runs,
+ * which is why `handleUnauthorized` — which rebuilds its redirect from
+ * `pathname + search` — must never be allowed to fire first. Both SSO
+ * callbacks therefore land on `/login`, where this consumer lives.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AUTH_REFRESH_KEY, AUTH_TOKEN_KEY, AUTH_USER_KEY, authApi } from './api';
+
+const USER = {
+ id: 'cf0a5e32-3d7a-4f54-9f4a-6f6b6a4f6d21',
+ email: '[email protected]',
+ role: 'infosec',
+ tenant_id: '2a2f1a7c-5a3f-4c37-9f35-1d6b6fbb9c41',
+};
+
+function landOn(hash: string): void {
+ window.history.replaceState(null, '', `/login?next=%2Falerts${hash}`);
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ landOn('');
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('completeSsoHandoff', () => {
+ it('reads the session out of the fragment and stores it', async () => {
+ landOn('#access_token=at-123&refresh_token=rt-456');
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response(JSON.stringify(USER), { status: 200 })),
+ );
+
+ await expect(authApi.completeSsoHandoff()).resolves.toBe(true);
+
+ expect(window.localStorage.getItem(AUTH_TOKEN_KEY)).toBe('at-123');
+ expect(window.localStorage.getItem(AUTH_REFRESH_KEY)).toBe('rt-456');
+ expect(JSON.parse(window.localStorage.getItem(AUTH_USER_KEY) ?? '{}').email).toBe(USER.email);
+ });
+
+ it('clears the fragment, so the token is not left in the address bar', async () => {
+ landOn('#access_token=at-123&refresh_token=rt-456');
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response(JSON.stringify(USER), { status: 200 })),
+ );
+
+ await authApi.completeSsoHandoff();
+
+ expect(window.location.hash).toBe('');
+ // The `?next=` the callback set has to survive: it is where the page
+ // routes to once the session is stored.
+ expect(window.location.search).toBe('?next=%2Falerts');
+ });
+
+ it('presents the token as a bearer credential to /auth/me', async () => {
+ landOn('#access_token=at-123&refresh_token=rt-456');
+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>
+ new Response(JSON.stringify(USER), { status: 200 }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ await authApi.completeSsoHandoff();
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(String(url)).toContain('/api/v1/auth/me');
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer at-123');
+ });
+
+ it('stores nothing when the API rejects the token', async () => {
+ landOn('#access_token=forged&refresh_token=forged');
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('{}', { status: 401 })),
+ );
+
+ await expect(authApi.completeSsoHandoff()).resolves.toBe(false);
+ expect(window.localStorage.getItem(AUTH_TOKEN_KEY)).toBeNull();
+ });
+
+ it('does nothing at all when there is no fragment', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+
+ await expect(authApi.completeSsoHandoff()).resolves.toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('ssoStatus', () => {
+ it('reads as "no SSO" when the endpoint is unreachable', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new Error('connection refused');
+ }),
+ );
+
+ // A status outage must not take the password form down with it, and
+ // it must not render an SSO button that cannot work.
+ await expect(authApi.ssoStatus()).resolves.toMatchObject({
+ sso_enabled: false,
+ local_login_enabled: true,
+ });
+ });
+});
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 2a00cd705..d443aa5ea 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -273,7 +273,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`) | 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`. **Limit**: no containerised-IdP test yet, so this is gated against the provisioning path rather than against a real Okta, Entra or Keycloak |
+| 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 |
| 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 |
@@ -302,8 +302,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
- Total: 290
-- GATED: 290
-- PARTIAL: 0
+- GATED: 289
+- PARTIAL: 1
- NO GATE: 0
Counts come from `scripts/check_claim_gate_matrix.py`, which is also the gate. Recompute
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index a4b21af72..04c357660 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -17517,7 +17517,14 @@ paths:
tags:
- auth-saml
summary: Saml Login
- description: Initiate SAML SSO — redirect to IdP.
+ description: 'Initiate SAML SSO — redirect to the IdP this connection names.
+
+
+ `issuer` is optional and the console does not send one: a deployment
+
+ with a single enabled SAML connection has an unambiguous answer. It
+
+ exists so a deployment with several can link one button per provider.'
operationId: saml_login_auth_saml_login_get
parameters:
- name: redirect
@@ -17527,6 +17534,14 @@ paths:
type: string
default: /
title: Redirect
+ - name: issuer
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Issuer
responses:
'200':
description: Successful Response
@@ -17570,14 +17585,38 @@ paths:
tags:
- auth-saml
summary: Saml Logout
- description: Initiate SAML SLO.
+ description: 'Initiate SAML SLO, at the SingleLogoutService the connection names.
+
+
+ Resolved the same way `/login` is. A deployment whose IdP comes from a
+
+ connection has no `SAML_IDP_SLO_URL`, so this used to build a logout
+
+ request against an empty endpoint and 500 on the way out of a session.
+
+ An SLO that cannot be initiated is a local logout, not an error.'
operationId: saml_logout_auth_saml_logout_get
+ parameters:
+ - name: issuer
+ in: query
+ required: false
+ schema:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Issuer
responses:
'200':
description: Successful Response
content:
application/json:
schema: {}
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/auth/oidc/login:
get:
tags:
diff --git a/scripts/ci/keycloak_oidc_probe.py b/scripts/ci/keycloak_oidc_probe.py
new file mode 100644
index 000000000..f4b059983
--- /dev/null
+++ b/scripts/ci/keycloak_oidc_probe.py
@@ -0,0 +1,171 @@
+#!/usr/bin/env python3
+"""Verify a real Keycloak `id_token` with the API's own verification code.
+
+Fix pass 4.1. Driven by `.github/workflows/sso-live.yml`.
+
+Read the caveat before citing this
+-----------------------------------
+This does **not** prove "a user signed in through Keycloak". There is no
+browser here, so the authorization hop — redirect, consent, callback — is
+not exercised; `tests/isolation/test_sso_live.py` covers that against a
+provider this repository controls.
+
+What it does prove is the half a self-authored provider cannot: that
+`app.auth.oidc._verify_id_token` accepts a token minted by a real identity
+provider, resolved through that provider's real discovery document and
+real JWKS, with a real `kid`. Every defect of the "our fake was more
+capable than the vendor" family lives in that gap.
+
+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.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import sys
+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"
+
+# `services/api` is the import root for `app.*`.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "services" / "api"))
+
+
+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,
+ "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)
+
+
+def issue_id_token(client_secret: str) -> str:
+ response = httpx.post(
+ f"{KEYCLOAK}/realms/{REALM}/protocol/openid-connect/token",
+ data={
+ "grant_type": "password",
+ "client_id": CLIENT_ID,
+ "client_secret": client_secret,
+ "username": USERNAME,
+ "password": PASSWORD,
+ "scope": "openid email profile",
+ },
+ timeout=30,
+ )
+ if not response.is_success:
+ # Keycloak's own `error_description` names the cause — a disabled
+ # grant, a bad secret, a user who cannot log in. Raising
+ # `HTTPStatusError` instead would print the URL and the status and
+ # leave an operator guessing, which is the diagnostic failure this
+ # repository keeps rediscovering.
+ raise SystemExit(f"Keycloak refused the token request: {response.status_code} {response.text[:500]}")
+ token = response.json().get("id_token")
+ if not token:
+ raise SystemExit("Keycloak returned no id_token; the client is not configured for the openid scope")
+ return str(token)
+
+
+async def main() -> int:
+ client_secret = bootstrap()
+ id_token = issue_id_token(client_secret)
+ issuer = f"{KEYCLOAK}/realms/{REALM}"
+
+ os.environ["OIDC_CLIENT_ID"] = CLIENT_ID
+ from app.auth.oidc import _discover, _IdTokenInvalid, _verify_id_token # noqa: PLC0415
+
+ provider = await _discover(issuer)
+ for key in ("jwks_uri", "token_endpoint", "authorization_endpoint"):
+ if not provider.get(key):
+ raise SystemExit(f"Keycloak's discovery document declares no {key}")
+
+ claims = await _verify_id_token(id_token, issuer=issuer, provider=provider)
+ if claims.get("email") != EMAIL:
+ raise SystemExit(f"verified a token for {claims.get('email')!r}, expected {EMAIL!r}")
+ print(f"OK: a real Keycloak id_token verified against its published JWKS (sub={claims.get('sub')})")
+
+ # The negative control. Same token, an audience this deployment is not
+ # configured for: a verifier that checked nothing would have passed
+ # above for the wrong reason.
+ os.environ["OIDC_CLIENT_ID"] = "some-other-client"
+ try:
+ await _verify_id_token(id_token, issuer=issuer, provider=provider)
+ except _IdTokenInvalid:
+ print("OK: the same token is refused when it names another audience.")
+ return 0
+ print("FAIL: an id_token minted for a different client was accepted.")
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(asyncio.run(main()))
diff --git a/services/api/app/auth/saml.py b/services/api/app/auth/saml.py
index 663e76cc0..989cb993a 100644
--- a/services/api/app/auth/saml.py
+++ b/services/api/app/auth/saml.py
@@ -11,15 +11,29 @@ Dependencies (optional):
- python3-saml (onelogin/python3-saml) if available
- Refuses with 501 when not installed, rather than inventing an identity
+Where the identity provider comes from (fix pass 4.1)
+-----------------------------------------------------
+The **connection row**, not the environment. `aisoc_sso_connections`
+carries `metadata_url` and `metadata_xml` per connection; both were
+written by `POST /sso-connections` and read by nothing, so an
+administrator could configure an IdP in the console and the deployment
+would go on trusting whatever `SAML_IDP_*` said — which on a stock install
+is nothing, so every assertion was refused. See
+`app/auth/saml_metadata.py`.
+
+The `SAML_IDP_*` variables below remain as a fallback for deployments that
+configured SAML before connections were readable. A connection wins over
+them whenever one resolves.
+
Configuration (env vars):
- SAML_IDP_ENTITY_ID IdP Entity ID (issuer)
- SAML_IDP_SSO_URL IdP SSO redirect URL
- SAML_IDP_SLO_URL IdP SLO URL (optional)
- SAML_IDP_CERT IdP X.509 certificate (PEM, single line base64 or multi-line)
SAML_SP_ENTITY_ID SP Entity ID (defaults to ACS URL)
SAML_SP_ACS_URL Assertion Consumer Service URL
SAML_SP_PRIVATE_KEY SP private key PEM (optional, for signed requests)
SAML_SP_CERT SP certificate PEM (optional)
+ SAML_IDP_ENTITY_ID Fallback IdP Entity ID (issuer)
+ SAML_IDP_SSO_URL Fallback IdP SSO redirect URL
+ SAML_IDP_SLO_URL Fallback IdP SLO URL (optional)
+ SAML_IDP_CERT Fallback IdP X.509 certificate (PEM or single-line base64)
JWT_SECRET Secret used to sign issued JWTs
JWT_ALGORITHM HS256 (default)
JWT_EXPIRE_MINUTES Token lifetime (default: 480 = 8h)
@@ -32,12 +46,21 @@ import os
import re
from datetime import UTC, datetime, timedelta
from typing import Any
+from urllib.parse import quote
import jwt as _jwt
from fastapi import APIRouter, HTTPException, Request, status
from fastapi.responses import RedirectResponse, Response
from app.api.v1.deps import DBSession
+from app.auth.saml_metadata import (
+ SamlTrustError,
+ environment_idp_is_configured,
+ environment_idp_settings,
+ idp_settings_for_connection,
+ issuer_from_saml_response,
+ resolve_saml_connection,
+)
from app.auth.sso_provisioning import SsoProvisioningError, complete_sso_login
logger = logging.getLogger(__name__)
@@ -88,17 +111,19 @@ def _issue_jwt(claims: dict[str, Any]) -> str:
# ─── SAML settings builder ────────────────────────────────────────────────────
-def _saml_settings() -> dict[str, Any]:
+def _saml_settings(idp: dict[str, Any] | None = None) -> dict[str, Any]:
+ """The python3-saml settings for this service provider.
+
+ The SP half is deployment-wide: one service, one ACS URL, one
+ certificate. The **IdP half is per connection** and is passed in —
+ `idp=None` falls back to `SAML_IDP_*`, which is how a pre-4.1
+ deployment was configured and the only thing that used to be possible.
+ """
sp_acs = os.getenv("SAML_SP_ACS_URL", "http://localhost:8000/auth/saml/acs")
sp_entity = os.getenv("SAML_SP_ENTITY_ID", sp_acs)
sp_key = os.getenv("SAML_SP_PRIVATE_KEY", "")
sp_cert = os.getenv("SAML_SP_CERT", "")
- idp_entity = os.getenv("SAML_IDP_ENTITY_ID", "")
- idp_sso = os.getenv("SAML_IDP_SSO_URL", "")
- idp_slo = os.getenv("SAML_IDP_SLO_URL", "")
- idp_cert = os.getenv("SAML_IDP_CERT", "").replace("\\n", "\n")
-
return {
"strict": True,
"debug": os.getenv("SAML_DEBUG", "false").lower() == "true",
@@ -115,49 +140,63 @@ def _saml_settings() -> dict[str, Any]:
"privateKey": sp_key,
"x509cert": sp_cert,
},
- "idp": {
- "entityId": idp_entity,
- "singleSignOnService": {
- "url": idp_sso,
- "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
- },
- "singleLogoutService": {
- "url": idp_slo,
- "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
- },
- "x509cert": idp_cert,
- },
+ "idp": idp if idp is not None else environment_idp_settings(),
}
-# ─── Routes ───────────────────────────────────────────────────────────────────
+async def _resolve_idp(db: DBSession, *, issuer: str | None) -> tuple[dict[str, Any], str]:
+ """The IdP settings block and the issuer that keys its connection.
+ Returns `(idp_settings, issuer)`. The issuer returned is the one the
+ **connection** declares, never the one an assertion claimed: the
+ assertion's issuer only selected which connection to look at, and
+ `complete_sso_login` resolves the tenant from the row this returns the
+ key of.
+ """
+ connection = await resolve_saml_connection(db, issuer=issuer)
+ if connection is not None:
+ return await idp_settings_for_connection(connection), str(connection["issuer"])
-def _idp_entity_id() -> str:
- """The IdP entity id, which keys the SSO connection row.
+ if environment_idp_is_configured():
+ env = environment_idp_settings()
+ logger.info("saml.trust_from_environment no connection row matched; using SAML_IDP_* ")
+ return env, str(env["entityId"])
- Read from the configured settings rather than from the assertion: the
- assertion is the thing being authenticated and cannot be the thing that
- decides which tenant it provisions into.
- """
- try:
- settings_dict = _saml_settings()
- idp = settings_dict.get("idp") or {}
- return str(idp.get("entityId") or os.getenv("SAML_IDP_ENTITY_ID", "") or "")
- except Exception: # noqa: BLE001
- return os.getenv("SAML_IDP_ENTITY_ID", "")
+ raise SamlTrustError(
+ "no enabled SAML connection is configured for this deployment. Create one with "
+ "POST /api/v1/sso-connections carrying the identity provider's metadata_url or metadata_xml."
+ )
+
+
+# ─── Routes ───────────────────────────────────────────────────────────────────
@router.get("/login")
-async def saml_login(request: Request, redirect: str = "/") -> Response:
- """Initiate SAML SSO — redirect to IdP."""
+async def saml_login(request: Request, db: DBSession, redirect: str = "/", issuer: str | None = None) -> Response:
+ """Initiate SAML SSO — redirect to the IdP this connection names.
+
+ `issuer` is optional and the console does not send one: a deployment
+ with a single enabled SAML connection has an unambiguous answer. It
+ exists so a deployment with several can link one button per provider.
+ """
+ from app.auth.oidc import _require_sso_enabled # noqa: PLC0415
+
+ _require_sso_enabled()
try:
from onelogin.saml2.auth import OneLogin_Saml2_Auth # type: ignore[import]
+ idp, _issuer = await _resolve_idp(db, issuer=issuer)
req = await _build_saml_request(request)
- auth = OneLogin_Saml2_Auth(req, _saml_settings())
+ auth = OneLogin_Saml2_Auth(req, _saml_settings(idp))
login_url: str = auth.login(return_to=redirect)
return RedirectResponse(url=login_url)
+ except SamlTrustError as exc:
+ # A configuration problem, named. "SAML error: Invalid dict
+ # settings: idp_sso_url_invalid" sent an operator to read
+ # python3-saml's source; this sends them to the connection they
+ # thought they had configured.
+ logger.warning("saml.login_unconfigured reason=%s", str(exc).replace("\r", "").replace("\n", " ")[:300])
+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
except ImportError as exc:
# 501, not a page that looks like a login. This branch used to render
# a stub and the one below it used to mint a token, and since
@@ -183,7 +222,14 @@ async def saml_acs(request: Request, db: DBSession) -> Response:
from onelogin.saml2.auth import OneLogin_Saml2_Auth # type: ignore[import]
req = await _build_saml_request(request)
- auth = OneLogin_Saml2_Auth(req, _saml_settings())
+ # The issuer the response names picks which connection's
+ # certificate to verify against. It confers nothing: an assertion
+ # naming an issuer whose private key the sender does not hold fails
+ # `process_response()` two lines below, and the tenant comes from
+ # the connection row either way.
+ claimed_issuer = issuer_from_saml_response(str(req.get("post_data", {}).get("SAMLResponse") or ""))
+ idp, connection_issuer = await _resolve_idp(db, issuer=claimed_issuer)
+ auth = OneLogin_Saml2_Auth(req, _saml_settings(idp))
auth.process_response()
errors = auth.get_errors()
@@ -209,10 +255,13 @@ async def saml_acs(request: Request, db: DBSession) -> Response:
session = await complete_sso_login(
db,
provider="saml",
- # The IdP entity id, which is what the connection is keyed
- # on. The tenant comes from that row, never from the
- # assertion.
- issuer=_idp_entity_id(),
+ # The entity id the *connection* declares, not the one the
+ # assertion claimed. They are equal on the path that got
+ # here — the signature verified against that connection's
+ # certificate — and passing the connection's value means a
+ # future change to selection cannot turn the assertion into
+ # the thing that chooses the tenant.
+ issuer=connection_issuer,
email=str(_first(attrs.get("email") or attrs.get(email_claim, [name_id]))),
subject=str(name_id or ""),
name=_first(attrs.get("displayName") or attrs.get(name_claim, [])),
@@ -229,12 +278,32 @@ async def saml_acs(request: Request, db: DBSession) -> Response:
except SsoProvisioningError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
+ # Land on the login page, not on the RelayState destination, and
+ # carry the refresh token too. Both halves were defects:
+ #
+ # `handleUnauthorized` in `apps/web/src/lib/api.ts` builds its
+ # bounce target from `pathname + search`, so an auth guard on
+ # `/alerts` redirects to `/login?next=/alerts` and **drops the
+ # fragment** — taking the only copy of the token with it. The OIDC
+ # callback already lands on /login for exactly this reason; this
+ # one did not, so a SAML sign-in could not complete in the console
+ # however valid the assertion.
+ #
+ # And the console's fragment consumer persists `refresh_token`
+ # alongside the access token; omitting it logged the user out
+ # silently when the access token expired.
relay_state = _safe_redirect(str((await request.form()).get("RelayState", "/")))
- separator = "&" if "#" in relay_state else "#"
+ redirect_url = f"/login?next={quote(relay_state, safe='')}"
# In the fragment, which browsers do not send to the server and
# which does not land in an access log or a Referer header.
- return RedirectResponse(url=f"{relay_state}{separator}access_token={session['access_token']}", status_code=302)
-
+ return RedirectResponse(
+ url=(f"{redirect_url}#access_token={session['access_token']}&refresh_token={session['refresh_token']}"),
+ status_code=302,
+ )
+
+ except SamlTrustError as exc:
+ logger.warning("saml.acs_unconfigured reason=%s", str(exc).replace("\r", "").replace("\n", " ")[:300])
+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)) from exc
except ImportError as exc:
# This issued a signed session for a principal called
# `stub-saml-user` that no identity provider had ever seen, from an
@@ -272,22 +341,36 @@ async def saml_metadata() -> Response:
@router.get("/logout")
-async def saml_logout(request: Request) -> Response:
- """Initiate SAML SLO."""
+async def saml_logout(request: Request, db: DBSession, issuer: str | None = None) -> Response:
+ """Initiate SAML SLO, at the SingleLogoutService the connection names.
+
+ Resolved the same way `/login` is. A deployment whose IdP comes from a
+ connection has no `SAML_IDP_SLO_URL`, so this used to build a logout
+ request against an empty endpoint and 500 on the way out of a session.
+ An SLO that cannot be initiated is a local logout, not an error.
+ """
try:
from onelogin.saml2.auth import OneLogin_Saml2_Auth # type: ignore[import]
+ idp, _issuer = await _resolve_idp(db, issuer=issuer)
req = await _build_saml_request(request)
- auth = OneLogin_Saml2_Auth(req, _saml_settings())
+ auth = OneLogin_Saml2_Auth(req, _saml_settings(idp))
name_id = request.cookies.get("saml_name_id", "")
logout_url: str = auth.logout(name_id=name_id)
response = RedirectResponse(url=logout_url)
response.delete_cookie("aisoc_token")
response.delete_cookie("saml_name_id")
return response
- except ImportError:
+ except Exception: # noqa: BLE001
+ # Every failure here ends the same way, so they are not
+ # distinguished: python3-saml missing, no connection configured, or
+ # an IdP that publishes no SingleLogoutService. The session is
+ # already being discarded locally, and refusing to do that because
+ # the provider cannot be told would leave the user signed in.
+ logger.info("saml.slo_unavailable falling back to local logout")
response = RedirectResponse(url="/login")
response.delete_cookie("aisoc_token")
+ response.delete_cookie("saml_name_id")
return response
diff --git a/services/api/app/auth/saml_metadata.py b/services/api/app/auth/saml_metadata.py
new file mode 100644
index 000000000..e21a6dd2a
--- /dev/null
+++ b/services/api/app/auth/saml_metadata.py
@@ -0,0 +1,277 @@
+"""Where a SAML deployment's trust in an identity provider comes from.
+
+Fix pass 4.1.
+
+The defect
+----------
+`_saml_settings()` built the `idp` block from `SAML_IDP_ENTITY_ID`,
+`SAML_IDP_SSO_URL` and `SAML_IDP_CERT` — process-wide environment
+variables — while `aisoc_sso_connections.metadata_url` and `.metadata_xml`
+were written by `POST /sso-connections`, returned by `GET /sso-connections`
+and read by nothing. So an administrator could configure a connection in
+the console, watch it come back from the API, and have the deployment go on
+trusting whatever the environment said. On a deployment that sets no SAML
+environment at all — the default, and what `.env.example` ships — the IdP
+block is empty, so every assertion is refused and the console reports a
+configuration that is doing nothing.
+
+It also capped the deployment at exactly one identity provider, which the
+connection table was designed not to be: the unique index is on
+`(provider, issuer)` precisely so several tenants can each bring their own.
+
+Selecting a connection by the issuer an assertion names
+--------------------------------------------------------
+`/acs` reads the `<saml:Issuer>` out of the POSTed response *before*
+anything has been verified, and uses it to pick which connection's
+certificate to verify against. That is safe, and the reason is worth
+stating because it looks like the thing this feature refuses to do
+everywhere else:
+
+the asserted issuer selects a **trust anchor**, it does not confer trust.
+An assertion naming an issuer whose private key the sender does not hold
+fails signature verification and authenticates nobody. The tenant still
+comes from the connection row an administrator configured, never from the
+assertion — that property is unchanged and is what
+`complete_sso_login` enforces.
+
+A `metadata_url` is fetched by this service from an address a tenant
+administrator supplied, which is the shape `_vendor/ssrf_guard.py` exists
+for, so the fetch goes through it and the response is size-capped.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import logging
+import os
+import time
+from typing import Any
+
+import httpx
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app._vendor.ssrf_guard import SSRFError, validate_outbound_url
+
+logger = logging.getLogger(__name__)
+
+#: A metadata document is a handful of kilobytes. The cap is here because
+#: the URL is operator-supplied and the response is not: a redirect to
+#: something enormous should fail rather than be streamed into memory.
+_MAX_METADATA_BYTES = 2 * 1024 * 1024
+
+#: IdP metadata is public, idempotent and changes when a certificate rolls.
+#: Re-fetching it on every sign-in would put the identity provider's
+#: availability in front of every login, so it is cached per replica.
+_METADATA_TTL_SECONDS = 600
+_metadata_cache: dict[str, tuple[float, str]] = {}
+
+
+def _sanitize(value: object, limit: int = 160) -> str:
+ return str(value).replace("\r", "").replace("\n", " ")[:limit]
+
+
+class SamlTrustError(Exception):
+ """No usable IdP trust material could be assembled for this sign-in."""
+
+
+def parse_idp_metadata(xml: str, *, entity_id: str | None = None) -> dict[str, Any]:
+ """The `idp` settings block a SAML metadata document declares.
+
+ Delegates to `python3-saml`'s own parser rather than reading the XML
+ here: it already resolves bindings, picks the `IDPSSODescriptor` and
+ collects multiple signing certificates into `x509certMulti`, and it
+ parses with `forbid_dtd=True, forbid_entities=True`, so a metadata
+ document cannot carry an external-entity reference.
+ """
+ from onelogin.saml2.idp_metadata_parser import OneLogin_Saml2_IdPMetadataParser # noqa: PLC0415
+
+ try:
+ parsed = OneLogin_Saml2_IdPMetadataParser.parse(xml, entity_id=entity_id)
+ except Exception as exc: # noqa: BLE001 - any parse failure is a refusal
+ raise SamlTrustError(f"the IdP metadata could not be parsed: {exc}") from exc
+
+ idp = dict((parsed or {}).get("idp") or {})
+ if not idp.get("entityId"):
+ raise SamlTrustError("the IdP metadata declares no entityID")
+ if not (idp.get("singleSignOnService") or {}).get("url"):
+ raise SamlTrustError("the IdP metadata declares no HTTP-Redirect SingleSignOnService")
+ if not (idp.get("x509cert") or idp.get("x509certMulti")):
+ # Without a certificate there is nothing to verify a signature
+ # against, and `strict` mode would refuse every assertion later with
+ # a message about the response rather than about the configuration.
+ raise SamlTrustError("the IdP metadata publishes no signing certificate")
+ return idp
+
+
+async def fetch_idp_metadata(url: str) -> str:
+ """Fetch a metadata document over HTTP, through the SSRF guard.
+
+ The URL is supplied by a tenant administrator through
+ `POST /sso-connections`, and this service fetches it, so it is exactly
+ the shape the guard exists for: a loopback or link-local target would
+ make the SSO configuration form a reader of this host's own metadata
+ service.
+ """
+ cached = _metadata_cache.get(url)
+ if cached and (time.monotonic() - cached[0]) < _METADATA_TTL_SECONDS:
+ return cached[1]
+
+ try:
+ validate_outbound_url(url)
+ except SSRFError as exc:
+ raise SamlTrustError(f"the connection's metadata_url is not allowed: {exc}") from exc
+
+ try:
+ async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client:
+ response = await client.get(url, headers={"Accept": "application/samlmetadata+xml, application/xml"})
+ response.raise_for_status()
+ if len(response.content) > _MAX_METADATA_BYTES:
+ raise SamlTrustError("the metadata document at the connection's metadata_url is implausibly large")
+ body = response.text
+ except SamlTrustError:
+ raise
+ except Exception as exc: # noqa: BLE001
+ raise SamlTrustError(f"the connection's metadata_url could not be fetched: {exc}") from exc
+
+ _metadata_cache[url] = (time.monotonic(), body)
+ return body
+
+
+async def idp_settings_for_connection(connection: dict[str, Any]) -> dict[str, Any]:
+ """The `idp` block this connection's own configuration declares.
+
+ `metadata_xml` wins over `metadata_url`: a document pasted into the
+ console is the operator's explicit statement of the trust material,
+ and should not be silently replaced by whatever a URL serves today.
+ """
+ xml = (connection.get("metadata_xml") or "").strip()
+ if not xml:
+ url = (connection.get("metadata_url") or "").strip()
+ if not url:
+ raise SamlTrustError(
+ "this SAML connection carries neither metadata_xml nor metadata_url, so there is "
+ "no identity provider to trust. Add one with PUT /api/v1/sso-connections/{id}."
+ )
+ xml = await fetch_idp_metadata(url)
+ # The connection's `issuer` is the entity id an administrator claimed.
+ # Passing it through means a federation document describing several
+ # providers resolves to the one this connection is for.
+ return parse_idp_metadata(xml, entity_id=(connection.get("issuer") or None) or None)
+
+
+async def resolve_saml_connection(db: AsyncSession, *, issuer: str | None = None) -> dict[str, Any] | None:
+ """The enabled SAML connection for *issuer*, or the only one there is.
+
+ `issuer` is `None` on `/login`, which the console links to without one:
+ a deployment with a single SAML connection has an unambiguous answer
+ and should not make an operator paste an entity id into a login link.
+ 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.
+ """
+ try:
+ rows = (
+ (
+ await db.execute(
+ text("""
+ 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)
+ ORDER BY created_at
+ LIMIT 2
+ """).bindparams(i=issuer)
+ )
+ )
+ .mappings()
+ .all()
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("saml.connection_lookup_failed error=%s", _sanitize(exc))
+ return None
+
+ if not rows:
+ return None
+ if len(rows) > 1:
+ logger.warning(
+ "saml.ambiguous_connection count>1 issuer=%s - link the login button to /auth/saml/login?issuer=<entity id>",
+ _sanitize(issuer or "<unset>"),
+ )
+ return None
+ return dict(rows[0])
+
+
+def issuer_from_saml_response(saml_response_b64: str) -> str | None:
+ """The `<Issuer>` an unverified SAML response names.
+
+ A **lookup key only**, and the distinction is the whole security
+ argument: it selects which connection's certificate the signature is
+ then checked against, and an assertion naming an issuer whose key the
+ sender does not hold fails that check. Nothing here is trusted; it
+ decides what to distrust it against.
+ """
+ try:
+ raw = base64.b64decode(saml_response_b64, validate=False)
+ except (binascii.Error, ValueError):
+ return None
+
+ from onelogin.saml2.xml_utils import OneLogin_Saml2_XML # noqa: PLC0415
+
+ try:
+ tree = OneLogin_Saml2_XML.to_etree(raw)
+ except Exception: # noqa: BLE001 - a response we cannot parse names no issuer
+ return None
+
+ namespaces = {
+ "samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
+ "saml": "urn:oasis:names:tc:SAML:2.0:assertion",
+ }
+ # The response-level Issuer first, then the assertion's: a provider may
+ # sign only the assertion and omit the outer element.
+ for path in ("/samlp:Response/saml:Issuer", "/samlp:Response/saml:Assertion/saml:Issuer"):
+ found = tree.xpath(path, namespaces=namespaces)
+ if found and (found[0].text or "").strip():
+ return str(found[0].text).strip()
+ return None
+
+
+def environment_idp_settings() -> dict[str, Any]:
+ """The pre-4.1 environment-variable IdP block.
+
+ Kept as a fallback so a deployment that configured SAML through the
+ environment before connections were readable keeps working across the
+ upgrade. It is not the path a new deployment takes, and
+ `saml_trust_source()` reports which one answered so an operator can
+ tell.
+ """
+ return {
+ "entityId": os.getenv("SAML_IDP_ENTITY_ID", ""),
+ "singleSignOnService": {
+ "url": os.getenv("SAML_IDP_SSO_URL", ""),
+ "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
+ },
+ "singleLogoutService": {
+ "url": os.getenv("SAML_IDP_SLO_URL", ""),
+ "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
+ },
+ "x509cert": os.getenv("SAML_IDP_CERT", "").replace("\\n", "\n"),
+ }
+
+
+def environment_idp_is_configured() -> bool:
+ env = environment_idp_settings()
+ return bool(env["entityId"] and env["singleSignOnService"]["url"] and env["x509cert"])
+
+
+__all__ = [
+ "SamlTrustError",
+ "environment_idp_is_configured",
+ "environment_idp_settings",
+ "fetch_idp_metadata",
+ "idp_settings_for_connection",
+ "issuer_from_saml_response",
+ "parse_idp_metadata",
+ "resolve_saml_connection",
+]
diff --git a/services/api/tests/test_saml_connection_metadata.py b/services/api/tests/test_saml_connection_metadata.py
new file mode 100644
index 000000000..d7aa25dee
--- /dev/null
+++ b/services/api/tests/test_saml_connection_metadata.py
@@ -0,0 +1,188 @@
+"""SAML trust comes from the connection row, not from the process environment.
+
+Fix pass 4.1.
+
+The defect
+----------
+`_saml_settings()` built the `idp` block from `SAML_IDP_ENTITY_ID`,
+`SAML_IDP_SSO_URL` and `SAML_IDP_CERT`, while
+`aisoc_sso_connections.metadata_url` and `.metadata_xml` — written by
+`POST /sso-connections` and returned by `GET /sso-connections` — were read
+nowhere. A stock install sets none of those variables, so the IdP block was
+empty and every assertion was refused while the console showed a configured
+connection.
+
+This file is the offline half, so the module is graded by the job that runs
+on every pull request. `tests/isolation/test_sso_live.py` is the half that
+proves a real signed assertion actually signs somebody in, and it needs
+Postgres and the whole application; the redirect targets and the token the
+console receives are asserted there, against the real routes, rather than
+by reading the handler's source here.
+"""
+
+from __future__ import annotations
+
+import base64
+import inspect
+
+import pytest
+from app.auth import saml
+from app.auth.saml_metadata import (
+ SamlTrustError,
+ environment_idp_is_configured,
+ issuer_from_saml_response,
+ parse_idp_metadata,
+)
+
+CERT = (
+ "MIIDBzCCAe+gAwIBAgIUKavXqjNUj2n6MqmhKoZappnTk5gwDQYJKoZIhvcNAQELBQAwEzERMA8GA1UEAwwIaWRwLnRlc3Qw"
+ "HhcNMjYxMDA3MTEwNjQ5WhcNMjYxMDA5MTEwNjQ5WjATMREwDwYDVQQDDAhpZHAudGVzdA=="
+)
+
+_KEY_DESCRIPTOR = f""" <md:KeyDescriptor use="signing">
+ <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
+ <ds:X509Data><ds:X509Certificate>{CERT}</ds:X509Certificate></ds:X509Data>
+ </ds:KeyInfo>
+ </md:KeyDescriptor>
+"""
+
+_SSO_SERVICE = """ <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
+ Location="https://idp.example/sso"/>
+"""
+
+
+def _metadata(*, key_descriptor: bool = True) -> str:
+ """IdP metadata, with or without a published signing certificate.
+
+ Assembled from parts so the no-certificate case is still *well-formed*
+ XML. Deleting a slice of a string would also test that the parser
+ rejects broken markup, which is not the property under test.
+ """
+ return (
+ '<?xml version="1.0"?>\n'
+ '<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"\n'
+ ' entityID="https://idp.example/metadata">\n'
+ ' <md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">\n'
+ + (_KEY_DESCRIPTOR if key_descriptor else "")
+ + _SSO_SERVICE
+ + " </md:IDPSSODescriptor>\n"
+ "</md:EntityDescriptor>"
+ )
+
+
+class TestParsingMetadata:
+ def test_it_yields_the_entity_id_sso_url_and_certificate(self) -> None:
+ idp = parse_idp_metadata(_metadata())
+ assert idp["entityId"] == "https://idp.example/metadata"
+ assert idp["singleSignOnService"]["url"] == "https://idp.example/sso"
+ assert idp["x509cert"].startswith("MIIDBzCC")
+
+ def test_metadata_with_no_certificate_is_refused(self) -> None:
+ """Rather than accepted and left to fail later as `invalid_response`.
+
+ With no certificate there is nothing to verify a signature against,
+ and `strict` mode would then refuse every assertion with a message
+ about the *response* instead of about the configuration — so the
+ operator reads "the IdP sent something wrong" and goes looking in
+ the wrong place.
+ """
+ with pytest.raises(SamlTrustError, match="no signing certificate"):
+ parse_idp_metadata(_metadata(key_descriptor=False))
+
+ def test_an_external_entity_reference_is_refused(self) -> None:
+ """A metadata document is operator-supplied and parsed by this
+ service, so XXE is in scope. `python3-saml` parses with
+ `forbid_dtd=True, forbid_entities=True`; this pins that the path
+ taken here is that one, and not a looser parser added later."""
+ hostile = (
+ '<?xml version="1.0"?>\n'
+ '<!DOCTYPE r [<!ENTITY xxe SYSTEM "file:///etc/hostname">]>\n'
+ '<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" entityID="&xxe;">\n'
+ "</md:EntityDescriptor>"
+ )
+ with pytest.raises(SamlTrustError):
+ parse_idp_metadata(hostile)
+
+
+class TestSelectingAConnectionByTheAssertedIssuer:
+ """The issuer an unverified response names is a **lookup key**: it picks
+ which certificate to verify against, and an assertion naming an issuer
+ whose private key the sender does not hold fails that check."""
+
+ def test_it_reads_the_response_level_issuer(self) -> None:
+ xml = (
+ '<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" '
+ 'xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">'
+ "<saml:Issuer>https://idp.example/metadata</saml:Issuer></samlp:Response>"
+ )
+ assert issuer_from_saml_response(base64.b64encode(xml.encode()).decode()) == "https://idp.example/metadata"
+
+ def test_it_falls_back_to_the_assertions_issuer(self) -> None:
+ """A provider may sign only the assertion and omit the outer element."""
+ xml = (
+ '<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" '
+ 'xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">'
+ "<saml:Assertion><saml:Issuer>https://inner.example/idp</saml:Issuer></saml:Assertion>"
+ "</samlp:Response>"
+ )
+ assert issuer_from_saml_response(base64.b64encode(xml.encode()).decode()) == "https://inner.example/idp"
+
+ @pytest.mark.parametrize("payload", ["", "not-base64-!!!", base64.b64encode(b"<not-saml/>").decode()])
+ def test_an_unparseable_response_names_no_issuer(self, payload: str) -> None:
+ """`None`, never a guess. `resolve_saml_connection` then falls back
+ to the single configured connection, and a guess there would pick an
+ arbitrary identity provider for somebody's sign-in."""
+ assert issuer_from_saml_response(payload) is None
+
+
+class TestTheSettingsBuilder:
+ def test_the_idp_block_is_whatever_the_caller_resolved(self) -> None:
+ idp = {"entityId": "https://from-the-connection/idp"}
+ assert saml._saml_settings(idp)["idp"] is idp
+
+ def test_it_falls_back_to_the_environment_only_when_given_nothing(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Kept so a deployment that configured SAML before connections were
+ readable survives the upgrade. It is not the path a new deployment
+ takes."""
+ monkeypatch.setenv("SAML_IDP_ENTITY_ID", "https://legacy.example/idp")
+ monkeypatch.setenv("SAML_IDP_SSO_URL", "https://legacy.example/sso")
+ monkeypatch.setenv("SAML_IDP_CERT", CERT)
+ assert environment_idp_is_configured() is True
+ assert saml._saml_settings()["idp"]["entityId"] == "https://legacy.example/idp"
+
+ def test_an_environment_with_no_certificate_does_not_count_as_configured(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The stock install. Counting it as configured is what would let
+ `_resolve_idp` answer with an empty trust anchor instead of saying
+ no connection exists."""
+ monkeypatch.setenv("SAML_IDP_ENTITY_ID", "https://legacy.example/idp")
+ monkeypatch.setenv("SAML_IDP_SSO_URL", "https://legacy.example/sso")
+ monkeypatch.setenv("SAML_IDP_CERT", "")
+ assert environment_idp_is_configured() is False
+
+
+class TestTheTenantStillDoesNotComeFromTheAssertion:
+ """4.1 adds a read of the asserted issuer, which is the one place this
+ feature could grow the hole it was built to avoid.
+
+ Structural rather than behavioural on purpose, and it is the same
+ reasoning `test_sso_provisioning.py` uses: the live suite can show that
+ *today* the two issuers are equal — the signature verified against that
+ connection's certificate, so they must be — and therefore cannot
+ distinguish a handler that passes the connection's value from one that
+ passes the assertion's. Only the code can.
+ """
+
+ def test_the_acs_passes_the_connections_issuer_to_provisioning(self) -> None:
+ source = inspect.getsource(saml.saml_acs)
+ assert "issuer=connection_issuer" in source, (
+ "the ACS hands `complete_sso_login` something other than the issuer the connection declares"
+ )
+ assert "_resolve_idp(db, issuer=claimed_issuer)" in source
+ # `claimed_issuer` may reach `_resolve_idp` and nothing else.
+ after_call = source.split("complete_sso_login(", 1)[-1]
+ assert "claimed_issuer" not in after_call
+
+ def test_complete_sso_login_still_takes_no_tenant(self) -> None:
+ from app.auth.sso_provisioning import complete_sso_login
+
+ assert "tenant_id" not in inspect.signature(complete_sso_login).parameters
diff --git a/tests/isolation/test_sso_live.py b/tests/isolation/test_sso_live.py
new file mode 100644
index 000000000..02a021d43
--- /dev/null
+++ b/tests/isolation/test_sso_live.py
@@ -0,0 +1,728 @@
+"""SSO completes a sign-in, through the real app, against a real identity provider.
+
+Fix pass 4.1.
+
+Why this suite exists
+---------------------
+`services/api/tests/test_sso_provisioning.py` asserts the shape of the
+provisioning path — that the tenant is not an argument, that a group cannot
+confer `admin`, that the token is signed with the key the API verifies
+with. All of that is true and none of it answers the question a buyer
+asks: *can somebody actually sign in?*
+
+Nothing in the repository ever drove either handler end to end. The OIDC
+callback was never run against a provider that publishes a JWKS, and the
+SAML ACS was never handed an assertion signed by a key the deployment
+trusts. So two different kinds of defect were invisible:
+
+**The one this suite was written to reproduce.** `_saml_settings()` builds
+the IdP trust anchor from `SAML_IDP_ENTITY_ID`, `SAML_IDP_SSO_URL` and
+`SAML_IDP_CERT` — process-wide environment variables — while
+`aisoc_sso_connections.metadata_url` and `.metadata_xml` are written by
+`POST /sso-connections` and read by nothing. An administrator configures a
+connection in the console, the deployment keeps trusting whatever the
+environment says, and on a deployment that sets no SAML environment at all
+(the default) the IdP block is empty and every assertion is refused.
+
+**The one that would have survived any amount of unit testing**: a
+provider-shaped detail like a `kid` the JWKS client cannot resolve, or an
+`Audience` the SP rejects, only shows up when a real signature meets a real
+verifier.
+
+What is real here and what is not
+----------------------------------
+Real: a 2048-bit RSA IdP keypair, IdP metadata carrying its certificate, a
+SAML Response signed with `xmlsec` through `python3-saml`'s own signer, and
+the full `OneLogin_Saml2_Auth.process_response()` verification path. Real
+Postgres with every migration applied, the application built by
+`create_application()`, and a token the API's own verifier accepts.
+
+Not real: the identity provider is not a containerised Keycloak. It is a
+keypair and a metadata document, which is exactly the trust material a
+deployment configures, but it does not exercise a vendor's own quirks.
+`.github/workflows/sso-live.yml` runs the containerised leg.
+
+The negative control
+--------------------
+`test_an_assertion_signed_by_an_untrusted_key_is_refused` is what stops the
+positive assertions passing for the wrong reason: a handler that skipped
+signature verification entirely would satisfy "alice signed in".
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import tempfile
+import threading
+import uuid
+from datetime import UTC, datetime, timedelta
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+import pytest_asyncio
+
+# One event loop for the module, and one application built in it: a loop
+# per test closes the pool the previous app still holds and every later
+# test dies with "Event loop is closed", which is a message about the
+# harness that says nothing about the code.
+#
+# Skipped as a *module* rather than only in a fixture. The offline
+# isolation job collects this directory with no Postgres running, and a
+# fixture-only skip lets any test that does not take the fixture run
+# anyway and fail there — a harness failure reported against a capability.
+pytestmark = [
+ pytest.mark.asyncio(loop_scope="module"),
+ pytest.mark.skipif(
+ not os.environ.get("ISOLATION_SSO_DSN", "").strip(),
+ reason="ISOLATION_SSO_DSN is not set; this suite needs a live Postgres",
+ ),
+]
+
+# python3-saml validates the SP URLs against its own URL regex, which
+# rejects a single-label host like `testserver`. The client below is
+# given the same origin so the assertion's `Destination` matches.
+SP_ORIGIN = "http://sp.aisoc-ci.test"
+ACS_URL = f"{SP_ORIGIN}/auth/saml/acs"
+IDP_ENTITY_ID = "https://idp.aisoc-ci.test/metadata"
+IDP_SSO_URL = "https://idp.aisoc-ci.test/sso"
+IDP_SLO_URL = "https://idp.aisoc-ci.test/slo"
+
+
+# ─── A real identity provider's trust material ───────────────────────────────
+
+
+class _Idp:
+ """An RSA keypair, the metadata that publishes it, and a signer.
+
+ Deliberately not a mock. The certificate in the metadata is the same
+ one the private key below signs with, so a verifier that checks the
+ signature against the metadata will accept these assertions and reject
+ anything else — which is the whole property under test.
+ """
+
+ def __init__(self, *, entity_id: str | None = None, sso_url: str = IDP_SSO_URL) -> None:
+ # Unique by default. `aisoc_sso_connections` is uniquely indexed on
+ # `(provider, issuer)` deployment-wide, so a fixed entity id makes
+ # the suite collide with its own previous run on a database that
+ # outlives one invocation — which is every CI service container
+ # reused across jobs, and every developer's local Postgres.
+ self.entity_id = entity_id or f"{IDP_ENTITY_ID}/{uuid.uuid4().hex}"
+ self.sso_url = sso_url
+ directory = Path(tempfile.mkdtemp(prefix="aisoc-idp-"))
+ key_path, crt_path = directory / "idp.key", directory / "idp.crt"
+ subprocess.run(
+ [
+ "openssl",
+ "req",
+ "-x509",
+ "-newkey",
+ "rsa:2048",
+ "-nodes",
+ "-keyout",
+ str(key_path),
+ "-out",
+ str(crt_path),
+ "-days",
+ "2",
+ "-subj",
+ "/CN=aisoc-ci-idp",
+ ],
+ check=True,
+ capture_output=True,
+ )
+ self.key_pem = key_path.read_text()
+ self.cert_pem = crt_path.read_text()
+ self.cert_b64 = "".join(line for line in self.cert_pem.splitlines() if "CERTIFICATE" not in line)
+
+ @property
+ def metadata_xml(self) -> str:
+ return (
+ '<?xml version="1.0"?>\n'
+ '<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" '
+ f'entityID="{self.entity_id}">\n'
+ ' <md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">\n'
+ ' <md:KeyDescriptor use="signing">\n'
+ ' <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">\n'
+ f" <ds:X509Data><ds:X509Certificate>{self.cert_b64}</ds:X509Certificate></ds:X509Data>\n"
+ " </ds:KeyInfo>\n"
+ " </md:KeyDescriptor>\n"
+ ' <md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" '
+ f'Location="{IDP_SLO_URL}"/>\n'
+ ' <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" '
+ f'Location="{self.sso_url}"/>\n'
+ " </md:IDPSSODescriptor>\n"
+ "</md:EntityDescriptor>"
+ )
+
+ def signed_response(self, *, email: str, groups: tuple[str, ...] = (), audience: str = ACS_URL) -> str:
+ from onelogin.saml2.constants import OneLogin_Saml2_Constants as Const
+ from onelogin.saml2.utils import OneLogin_Saml2_Utils as Utils
+
+ now = datetime.now(UTC)
+ response_id, assertion_id = "_" + uuid.uuid4().hex, "_" + uuid.uuid4().hex
+ issued = now.strftime("%Y-%m-%dT%H:%M:%SZ")
+ not_before = (now - timedelta(minutes=5)).strftime("%Y-%m-%dT%H:%M:%SZ")
+ not_after = (now + timedelta(minutes=5)).strftime("%Y-%m-%dT%H:%M:%SZ")
+ attributes = "".join(
+ '<saml:Attribute Name="groups" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">'
+ f'<saml:AttributeValue xsi:type="xs:string">{group}</saml:AttributeValue></saml:Attribute>'
+ for group in groups
+ )
+ xml = f"""<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
+ xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
+ ID="{response_id}" Version="2.0" IssueInstant="{issued}" Destination="{ACS_URL}">
+ <saml:Issuer>{self.entity_id}</saml:Issuer>
+ <samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>
+ <saml:Assertion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ ID="{assertion_id}" Version="2.0" IssueInstant="{issued}">
+ <saml:Issuer>{self.entity_id}</saml:Issuer>
+ <saml:Subject>
+ <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{email}</saml:NameID>
+ <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
+ <saml:SubjectConfirmationData NotOnOrAfter="{not_after}" Recipient="{ACS_URL}"/>
+ </saml:SubjectConfirmation>
+ </saml:Subject>
+ <saml:Conditions NotBefore="{not_before}" NotOnOrAfter="{not_after}">
+ <saml:AudienceRestriction><saml:Audience>{audience}</saml:Audience></saml:AudienceRestriction>
+ </saml:Conditions>
+ <saml:AuthnStatement AuthnInstant="{issued}" SessionIndex="{assertion_id}">
+ <saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef></saml:AuthnContext>
+ </saml:AuthnStatement>
+ <saml:AttributeStatement>
+ <saml:Attribute Name="email" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
+ <saml:AttributeValue xsi:type="xs:string">{email}</saml:AttributeValue>
+ </saml:Attribute>{attributes}
+ </saml:AttributeStatement>
+ </saml:Assertion>
+</samlp:Response>"""
+ signed = Utils.add_sign(
+ xml,
+ self.key_pem,
+ self.cert_pem,
+ sign_algorithm=Const.RSA_SHA256,
+ digest_algorithm=Const.SHA256,
+ )
+ if isinstance(signed, bytes):
+ signed = signed.decode()
+ return base64.b64encode(signed.encode()).decode()
+
+
+# ─── A real OpenID Connect provider, on a real socket ────────────────────────
+
+
+_HEADER_UNSAFE = re.compile(r"[^A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%-]")
+
+
+def _header_safe(value: str) -> str:
+ """A URL fragment safe to place in a response header.
+
+ Reconstructed from allowed characters rather than checked, so neither a
+ reader nor a taint tracker has to reason about what survived.
+ """
+ return _HEADER_UNSAFE.sub("", value)
+
+
+class _OidcProvider:
+ """Discovery, JWKS, authorization, token and userinfo over real HTTP.
+
+ Not a mock and not a monkeypatch: the API's own `_discover()` fetches
+ the discovery document over TCP, its `PyJWKClient` fetches the JWKS and
+ resolves the signing key by `kid`, and the `id_token` below is a real
+ RS256 JWT. So the verification this exercises — signature, `iss`,
+ `aud`, `exp` and the `nonce` replay check — is the production path with
+ nothing stubbed.
+
+ What it is not is a containerised Keycloak;
+ `.github/workflows/sso-live.yml` runs that leg.
+ """
+
+ client_id = "aisoc-ci"
+ client_secret = "aisoc-ci-secret"
+
+ def __init__(self) -> None:
+ from cryptography.hazmat.primitives.asymmetric import rsa
+
+ self._key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ #: Never published in the JWKS. Signing with it under the same
+ #: `kid` is how the negative control forges a token: the verifier
+ #: resolves the real key and the signature does not check out.
+ self._rogue_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ self.sign_with_rogue_key = False
+ self.kid = uuid.uuid4().hex
+ #: code -> the nonce the authorization request carried, so `/token`
+ #: can mint an id_token that survives the callback's replay check.
+ self._codes: dict[str, dict[str, str]] = {}
+ self.subject = f"sub-{uuid.uuid4().hex[:10]}"
+ self.email = f"bob-{uuid.uuid4().hex[:8]}@example.com"
+ self.groups: list[str] = []
+
+ provider = self
+
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *_args: object) -> None: # keep pytest output readable
+ return
+
+ def _send(self, status: int, body: bytes, content_type: str = "application/json") -> None:
+ self.send_response(status)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler's contract
+ path = urlsplit(self.path).path
+ query = parse_qs(urlsplit(self.path).query)
+ if path == "/.well-known/openid-configuration":
+ self._send(200, json.dumps(provider.discovery).encode())
+ elif path == "/jwks.json":
+ self._send(200, json.dumps(provider.jwks).encode())
+ elif path == "/authorize":
+ code = uuid.uuid4().hex
+ provider._codes[code] = {"nonce": (query.get("nonce") or [""])[0]}
+ # Rebuilt from an allow-list rather than interpolated. A
+ # `Location` assembled from the query string is response
+ # splitting even in a fixture, and a provider that lets a
+ # crafted `redirect_uri` inject a header is not modelling
+ # a real one.
+ target = _header_safe((query.get("redirect_uri") or [""])[0])
+ state = _header_safe((query.get("state") or [""])[0])
+ self.send_response(302)
+ self.send_header("Location", f"{target}?code={code}&state={state}")
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+ elif path == "/userinfo":
+ self._send(200, json.dumps(provider.claims(nonce=None)).encode())
+ else:
+ self._send(404, b"{}")
+
+ def do_POST(self) -> None: # noqa: N802
+ length = int(self.headers.get("Content-Length") or 0)
+ form = parse_qs(self.rfile.read(length).decode())
+ if urlsplit(self.path).path != "/token":
+ self._send(404, b"{}")
+ return
+ code = (form.get("code") or [""])[0]
+ entry = provider._codes.pop(code, None)
+ if entry is None:
+ self._send(400, json.dumps({"error": "invalid_grant"}).encode())
+ return
+ self._send(
+ 200,
+ json.dumps(
+ {
+ "access_token": "opaque-" + uuid.uuid4().hex,
+ "token_type": "Bearer",
+ "expires_in": 300,
+ "id_token": provider.id_token(nonce=entry["nonce"]),
+ }
+ ).encode(),
+ )
+
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.issuer = f"http://127.0.0.1:{self._server.server_address[1]}"
+ self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
+ self._thread.start()
+
+ def close(self) -> None:
+ self._server.shutdown()
+ self._server.server_close()
+
+ @property
+ def discovery(self) -> dict:
+ return {
+ "issuer": self.issuer,
+ "authorization_endpoint": f"{self.issuer}/authorize",
+ "token_endpoint": f"{self.issuer}/token",
+ "userinfo_endpoint": f"{self.issuer}/userinfo",
+ "jwks_uri": f"{self.issuer}/jwks.json",
+ "id_token_signing_alg_values_supported": ["RS256"],
+ }
+
+ @property
+ def jwks(self) -> dict:
+ from cryptography.hazmat.primitives.asymmetric import rsa
+
+ numbers: rsa.RSAPublicNumbers = self._key.public_key().public_numbers()
+
+ def b64(value: int) -> str:
+ raw = value.to_bytes((value.bit_length() + 7) // 8, "big")
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+
+ return {"keys": [{"kty": "RSA", "use": "sig", "alg": "RS256", "kid": self.kid, "n": b64(numbers.n), "e": b64(numbers.e)}]}
+
+ def claims(self, *, nonce: str | None) -> dict:
+ now = datetime.now(UTC)
+ claims = {
+ "iss": self.issuer,
+ "sub": self.subject,
+ "aud": self.client_id,
+ "email": self.email,
+ "email_verified": True,
+ "name": "Bob Example",
+ "iat": int(now.timestamp()),
+ "exp": int((now + timedelta(minutes=5)).timestamp()),
+ }
+ if self.groups:
+ claims["groups"] = self.groups
+ if nonce:
+ claims["nonce"] = nonce
+ return claims
+
+ def id_token(self, *, nonce: str) -> str:
+ import jwt
+ from cryptography.hazmat.primitives import serialization
+
+ key = self._rogue_key if self.sign_with_rogue_key else self._key
+ pem = key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ )
+ return jwt.encode(self.claims(nonce=nonce), pem, algorithm="RS256", headers={"kid": self.kid})
+
+
+# ─── Harness ──────────────────────────────────────────────────────────────────
+
+
+def _dsn() -> str:
+ value = os.environ.get("ISOLATION_SSO_DSN", "").strip()
+ if not value:
+ pytest.skip("ISOLATION_SSO_DSN is not set; this suite needs a live Postgres")
+ return value
+
+
+@pytest_asyncio.fixture(scope="module", loop_scope="module")
+async def app_client():
+ """The real application, against real Postgres.
+
+ `ENVIRONMENT=test` and not `development`: `development` is in
+ `AUTH_BYPASS_ENVIRONMENTS`, so an uncredentialed request resolves to a
+ demo administrator — inside the one suite whose point is that the
+ principal comes from the assertion.
+
+ The SAML environment variables are set to an IdP this suite does *not*
+ hold the key for. That is the reproduce condition: if the handler reads
+ its trust anchor from the environment rather than from the connection,
+ every assertion below is refused.
+ """
+ pytest.importorskip("httpx")
+ os.environ["DATABASE_URL"] = _dsn()
+ os.environ["ENVIRONMENT"] = "test"
+ os.environ["SSO_ENABLED"] = "true"
+ os.environ["SAML_SP_ACS_URL"] = ACS_URL
+ 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"] = ""
+
+ import httpx
+ from app.main import create_application
+
+ application = create_application()
+ transport = httpx.ASGITransport(app=application)
+ async with httpx.AsyncClient(transport=transport, base_url=SP_ORIGIN) as client:
+ yield client
+
+
+@pytest_asyncio.fixture(scope="module", loop_scope="module")
+async def db():
+ 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")
+async def idp() -> _Idp:
+ """One identity provider per test, so the deployment-wide unique index
+ on `(provider, issuer)` cannot make one test's row collide with
+ another's."""
+ return _Idp()
+
+
+async def _tenant(session) -> uuid.UUID: # noqa: ANN001
+ import sqlalchemy
+
+ # The session is module-scoped, so an earlier failure leaves its
+ # transaction aborted and every later statement reports that instead of
+ # its own error. Start clean.
+ 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"sso-{tenant_id.hex[:8]}", "s": f"sso-{tenant_id.hex[:8]}"},
+ )
+ await session.commit()
+ return tenant_id
+
+
+async def _saml_connection(session, *, idp: _Idp, by_url: str | None = None) -> dict: # noqa: ANN001
+ """An enabled SAML connection carrying the IdP's own metadata.
+
+ This is the row the console writes and that nothing read.
+ """
+ import sqlalchemy
+
+ tenant_id = await _tenant(session)
+ connection_id = uuid.uuid4()
+ # The table's `WITH CHECK` has no null escape: a tenant configures its
+ # own connection, so the write is bound even though the *read* on the
+ # callback path is not (resolving the row is what decides the tenant).
+ # The fixture therefore has to bind, exactly as the console's session
+ # does.
+ 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
+ (id, tenant_id, provider, issuer, display_name, enabled,
+ group_role_mapping, default_role, metadata_url, metadata_xml)
+ VALUES (:id, :t, 'saml', :iss, 'CI IdP', TRUE,
+ CAST(:map AS jsonb), 'viewer', :url, :xml)
+ """
+ ),
+ {
+ "id": connection_id,
+ "t": tenant_id,
+ "iss": idp.entity_id,
+ "map": '{"soc-analysts": "infosec"}',
+ "url": by_url,
+ "xml": None if by_url else idp.metadata_xml,
+ },
+ )
+ await session.commit()
+ return {"id": connection_id, "tenant_id": tenant_id}
+
+
+# ─── The reproduce ────────────────────────────────────────────────────────────
+
+
+class TestSamlTrustComesFromTheConnection:
+ """Fix pass 4.1: `metadata_url` and `metadata_xml` are written by
+ `POST /sso-connections` and read by nothing."""
+
+ async def test_login_redirects_to_the_sso_url_in_the_connection_metadata(self, app_client, db, idp) -> None: # noqa: ANN001
+ """The environment names a different IdP, so a pass here can only
+ come from the connection row."""
+ connection = await _saml_connection(db, idp=idp)
+
+ response = await app_client.get(
+ "/auth/saml/login",
+ params={"issuer": idp.entity_id, "redirect": "/alerts"},
+ follow_redirects=False,
+ )
+
+ assert response.status_code in (302, 303, 307), response.text
+ location = response.headers["location"]
+ assert location.startswith(idp.sso_url), (
+ f"redirected to {location!r}, which is not the SingleSignOnService the connection's "
+ f"metadata declares. Connection {connection['id']} carries it and the handler ignored it."
+ )
+
+ async def test_an_assertion_signed_by_the_connections_key_signs_someone_in(self, app_client, db, idp) -> None: # noqa: ANN001
+ """End to end: a signed assertion in, a token the API verifies out,
+ a real user row in the connection's tenant."""
+ import sqlalchemy
+
+ connection = await _saml_connection(db, idp=idp)
+ email = f"alice-{uuid.uuid4().hex[:8]}@example.com"
+
+ response = await app_client.post(
+ "/auth/saml/acs",
+ data={
+ "SAMLResponse": idp.signed_response(email=email, groups=("soc-analysts",)),
+ "RelayState": "/alerts",
+ },
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 302, response.text
+ location = response.headers["location"]
+ # On `/login`, not on the RelayState destination. `handleUnauthorized`
+ # in the console builds its bounce target from `pathname + search`, so
+ # an auth guard on `/alerts` would redirect to `/login?next=/alerts`
+ # and drop the fragment — taking the only copy of the token with it.
+ assert location.startswith("/login?next="), location
+ assert "#access_token=" in location, location
+ # The console's fragment consumer persists both.
+ assert "refresh_token=" in location, location
+
+ token = location.split("access_token=", 1)[1].split("&", 1)[0]
+ me = await app_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})
+ assert me.status_code == 200, me.text
+ body = me.json()
+ assert body["email"] == email
+ # The tenant is the connection's, never the assertion's.
+ assert body["tenant_id"] == str(connection["tenant_id"])
+ # `soc-analysts` maps to `infosec` on this connection.
+ assert body["role"] == "infosec"
+
+ row = (
+ (
+ await db.execute(
+ sqlalchemy.text("SELECT tenant_id, role FROM users WHERE lower(email) = lower(:e)"),
+ {"e": email},
+ )
+ )
+ .mappings()
+ .first()
+ )
+ assert row is not None, "the sign-in returned a token for a user that was never written"
+ assert row["tenant_id"] == connection["tenant_id"]
+
+ async def test_an_assertion_signed_by_an_untrusted_key_is_refused(self, app_client, db, idp) -> None: # noqa: ANN001
+ """The negative control.
+
+ A second keypair, claiming the *same* issuer as the configured
+ connection. Only the signature distinguishes them, so a handler
+ that resolved the connection and then skipped verification would
+ pass every test above and fail this one.
+ """
+ await _saml_connection(db, idp=idp)
+ impostor = _Idp() # same entity id, different private key
+ email = f"mallory-{uuid.uuid4().hex[:8]}@example.com"
+
+ response = await app_client.post(
+ "/auth/saml/acs",
+ data={"SAMLResponse": impostor.signed_response(email=email), "RelayState": "/"},
+ follow_redirects=False,
+ )
+
+ assert response.status_code >= 400, (
+ f"an assertion signed by a key the connection does not trust was accepted "
+ f"({response.status_code}); location={response.headers.get('location')!r}"
+ )
+ assert "access_token=" not in str(response.headers.get("location", ""))
+
+
+# ─── OIDC, end to end against a provider that really signs ───────────────────
+
+
+@pytest_asyncio.fixture(loop_scope="module")
+async def oidc():
+ provider = _OidcProvider()
+ os.environ["OIDC_ISSUER"] = provider.issuer
+ os.environ["OIDC_CLIENT_ID"] = provider.client_id
+ os.environ["OIDC_CLIENT_SECRET"] = provider.client_secret
+ os.environ["OIDC_REDIRECT_URI"] = f"{SP_ORIGIN}/auth/oidc/callback"
+ # `_discover` and `PyJWKClient` both cache per issuer for the lifetime
+ # of the process, and each test gets a provider on a fresh port, so a
+ # stale entry would serve the previous test's keys.
+ from app.auth import oidc as oidc_module
+
+ oidc_module._provider_cache.clear()
+ oidc_module._jwks_clients.clear()
+ try:
+ yield provider
+ finally:
+ provider.close()
+
+
+async def _oidc_connection(session, *, issuer: str, mapping: str = "{}") -> dict: # noqa: ANN001
+ import sqlalchemy
+
+ tenant_id = await _tenant(session)
+ connection_id = uuid.uuid4()
+ 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
+ (id, tenant_id, provider, issuer, display_name, enabled,
+ group_role_mapping, default_role)
+ VALUES (:id, :t, 'oidc', :iss, 'CI OIDC', TRUE, CAST(:map AS jsonb), 'viewer')
+ """
+ ),
+ {"id": connection_id, "t": tenant_id, "iss": issuer, "map": mapping},
+ )
+ await session.commit()
+ return {"id": connection_id, "tenant_id": tenant_id}
+
+
+class TestOidcCompletesASignIn:
+ """The claim row's own words: *SSO completes a sign-in, into the right
+ tenant with the mapped role.* Nothing drove this against a provider
+ that publishes a JWKS until now."""
+
+ async def test_the_whole_authorization_code_flow(self, app_client, db, oidc) -> None: # noqa: ANN001
+ import httpx
+
+ oidc.groups = ["soc-analysts"]
+ connection = await _oidc_connection(db, issuer=oidc.issuer, mapping='{"soc-analysts": "infosec"}')
+
+ start = await app_client.get("/auth/oidc/login", params={"redirect": "/alerts"}, follow_redirects=False)
+ assert start.status_code in (302, 307), start.text
+ authorize_url = start.headers["location"]
+ assert authorize_url.startswith(f"{oidc.issuer}/authorize"), authorize_url
+
+ # The browser's hop. Done with a plain client because this URL is
+ # the provider's, not the application's.
+ async with httpx.AsyncClient(follow_redirects=False) as browser:
+ bounced = await browser.get(authorize_url)
+ assert bounced.status_code == 302, bounced.text
+ returned = parse_qs(urlsplit(bounced.headers["location"]).query)
+
+ callback = await app_client.get(
+ "/auth/oidc/callback",
+ params={"code": returned["code"][0], "state": returned["state"][0]},
+ follow_redirects=False,
+ )
+ assert callback.status_code == 302, callback.text
+ location = callback.headers["location"]
+ assert location.startswith("/login?next="), location
+ assert "#access_token=" in location and "refresh_token=" in location
+
+ token = location.split("access_token=", 1)[1].split("&", 1)[0]
+ me = await app_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"})
+ assert me.status_code == 200, me.text
+ assert me.json()["email"] == oidc.email
+ assert me.json()["tenant_id"] == str(connection["tenant_id"])
+ assert me.json()["role"] == "infosec"
+
+ async def test_an_id_token_signed_by_another_key_is_refused(self, app_client, db, oidc) -> None: # noqa: ANN001
+ """The OIDC negative control.
+
+ The same issuer, the same `kid`, a private key that is not the one
+ the JWKS publishes. Only the signature distinguishes this token
+ from the one above, so a callback that decoded the `id_token`
+ without verifying — which is what this handler used to do, under a
+ comment saying to use JWKS in production — would pass the previous
+ test and fail this one.
+ """
+ import httpx
+
+ await _oidc_connection(db, issuer=oidc.issuer)
+ oidc.sign_with_rogue_key = True
+
+ start = await app_client.get("/auth/oidc/login", params={"redirect": "/"}, follow_redirects=False)
+ async with httpx.AsyncClient(follow_redirects=False) as browser:
+ bounced = await browser.get(start.headers["location"])
+ returned = parse_qs(urlsplit(bounced.headers["location"]).query)
+
+ callback = await app_client.get(
+ "/auth/oidc/callback",
+ params={"code": returned["code"][0], "state": returned["state"][0]},
+ follow_redirects=False,
+ )
+ assert callback.status_code == 401, (
+ f"an id_token signed by a key outside the provider's published JWKS was accepted ({callback.status_code})"
+ )
+ assert "access_token=" not in str(callback.headers.get("location", ""))