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(security): two reported advisories — WebSocket auth and SSO account binding (#1122)

Beenu Arora709ea6c4e4a2
diff --git a/.github/workflows/agent-auth-live.yml b/.github/workflows/agent-auth-live.yml
index 88b48585a..c8014a742 100644
--- a/.github/workflows/agent-auth-live.yml
+++ b/.github/workflows/agent-auth-live.yml
@@ -150,6 +150,18 @@ jobs:
ISOLATION_KEV_DSN: ${{ env.LIVE_DSN }}
run: python -m pytest ../../tests/isolation/test_kev_exposure_has_data_live.py -v --tb=short -rs
+ - name: A revoked session cannot hold the graph WebSocket open
+ working-directory: services/api
+ env:
+ ISOLATION_WS_AUTH_DSN: ${{ env.LIVE_DSN }}
+ run: python -m pytest ../../tests/isolation/test_graph_ws_revocation_live.py -v --tb=short -rs
+
+ - name: An unverified email claim cannot take over an account
+ working-directory: services/api
+ env:
+ ISOLATION_SSO_DSN: ${{ env.LIVE_DSN }}
+ run: python -m pytest ../../tests/isolation/test_sso_account_binding_live.py -v --tb=short -rs
+
- name: No suite may report success having skipped
run: |
set -euo pipefail
@@ -158,4 +170,4 @@ jobs:
exit 1
fi
echo "LIVE_DSN was set, and the cross-service step sets ISOLATION_CROSS_SERVICE,"
- echo "so none of the five suites took its skip path."
+ echo "so none of the seven suites took its skip path."
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7eb892f26..da0c01f24 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,57 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security
+
+- **A revoked session kept the graph WebSocket open** ([GHSA-25fh-rxp8-67j8]).
+ `_authenticate_ws` resolved its JWT by hand, under a docstring claiming *"we
+ reuse the same helpers `get_current_user` uses so the auth contract is
+ identical"*. It did not: no session-revocation check against
+ `users.sessions_revoked_at`, and no `resolve_permissions`. So a
+ de-provisioned principal kept a live subscription to the tenant graph stream
+ for the remaining lifetime of its access token while the **same token** was
+ answered `401 Session revoked` over HTTP, and `require_permission` fell back
+ to the static role map because `resolved_permissions` was `None` -- where a
+ wildcard role passes unconditionally. Both paths now call one
+ `resolve_jwt_principal`; two implementations of one security contract
+ diverge, and the only question is when.
+- **An unverified email claim could take over any account in the tenant**
+ ([GHSA-qjjc-q2h2-56cg]). `provision_user` selected the local account with
+ `WHERE tenant_id = :t AND lower(email) = lower(:e)`, and the word
+ `email_verified` appeared **nowhere** in the OIDC path. An attacker able to
+ authenticate to the tenant's configured provider with an account carrying a
+ victim's unverified address received a token minted for the victim's local
+ id -- and with database-backed RBAC the API then resolved the *victim's*
+ `user_roles`, so a low-privilege group mapping did not contain it.
+
+ Matching on email was deliberate and stays, because an organisation moving
+ identity provider keeps its addresses and would otherwise get a second
+ account per person. It is now guarded on both sides: an existing account can
+ only be claimed when the provider affirmatively asserts `email_verified`
+ (absent reads as unverified -- OIDC makes the claim optional, and "did not
+ say" is not "said yes"), and the subject is bound to the account it signs in
+ as, per connection, in `aisoc_sso_identities` (migration 089). A second
+ subject presenting a bound account's address is refused even with a verified
+ email. An IdP migration is a new connection, so bindings start empty and
+ everyone re-claims their own account on first sign-in -- exactly the
+ behaviour the email match existed to provide. SAML passes verified: the
+ assertion is signed, and the signature is the assurance OIDC uses the claim
+ to provide.
+
+ The identity binding also has to set the tenant context before it writes.
+ A sign-in callback has no authenticated principal, so the session it arrives
+ on carries none, and the new table's `WITH CHECK` has no
+ `current_tenant_id() IS NULL` escape -- deliberately, because an unscoped
+ session that can insert any `tenant_id` is not a control. `complete_sso_login`
+ sets it from the connection, which is the only thing that decides the tenant
+ on this path. Without it the binding is refused under the DML-only
+ `aisoc_app` role and SSO login fails outright; CI found that because it runs
+ as that role, and a local database connected as the owner cannot, since RLS
+ does not apply to the owner at all.
+
+[GHSA-25fh-rxp8-67j8]: https://github.com/beenuar/AiSOC/security/advisories/GHSA-25fh-rxp8-67j8
+[GHSA-qjjc-q2h2-56cg]: https://github.com/beenuar/AiSOC/security/advisories/GHSA-qjjc-q2h2-56cg
+
### BREAKING
- **`POST /api/v1/detection-loop/suggest`, `GET /api/v1/detection-loop/suggestions`
diff --git a/scripts/check_one_permission_model.py b/scripts/check_one_permission_model.py
index 52d41a834..12f5a93ed 100644
--- a/scripts/check_one_permission_model.py
+++ b/scripts/check_one_permission_model.py
@@ -121,14 +121,33 @@ def inspect(root: pathlib.Path) -> Report:
report.findings.append("the require_permission factory is gone")
# 2. authentication resolves one
+ #
+ # Followed through one hop of delegation, because the property is "the
+ # authenticated principal carries a resolved set" and not "this particular
+ # function contains this particular call". `get_current_user` used to
+ # inline the whole JWT path; it now hands off to `resolve_jwt_principal`,
+ # which the WebSocket upgrade also uses -- and the reason it does is that
+ # the WebSocket had its *own* copy which resolved no permissions at all
+ # (GHSA-25fh-rxp8-67j8). A gate keyed on the function name would have
+ # reported that refactor as a regression while the thing it guards got
+ # stronger, which is the shape that gets a gate deleted.
auth = _function(deps, "get_current_user")
if auth is None:
report.findings.append("get_current_user is gone")
- elif "resolve_permissions" not in _calls(auth):
- report.findings.append(
- "get_current_user does not call `resolve_permissions`, so no principal ever carries "
- "a database-backed set and the static map is the only model again"
- )
+ else:
+ resolvers = [auth]
+ for name in sorted(_calls(auth)):
+ if name == "get_current_user":
+ continue
+ delegate = _function(deps, name)
+ if delegate is not None:
+ resolvers.append(delegate)
+ if not any("resolve_permissions" in _calls(fn) for fn in resolvers):
+ report.findings.append(
+ "no function on the authentication path calls `resolve_permissions`, so no "
+ "principal ever carries a database-backed set and the static map is the only "
+ "model again"
+ )
# 3. every RBAC write invalidates
rbac = _tree(root, RBAC_ROUTES)
diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.py
index c21f5ad42..048bebb99 100644
--- a/scripts/check_tenant_query_predicates.py
+++ b/scripts/check_tenant_query_predicates.py
@@ -199,7 +199,14 @@ RATCHET: dict[str, str] = {
"services/api/app/api/v1/endpoints/auth.py::refresh_token::User": (
"refresh presents a signed token, not a tenant; the row it names assigns one"
),
- "services/api/app/api/v1/deps.py::get_current_user::User": "bearer-token subject lookup; runs before any tenant exists on the request",
+ # One entry where there were two. The bearer-token subject lookup was
+ # inlined in `get_current_user` *and* copied into `_authenticate_ws`;
+ # that copy skipped the session-revocation check and database RBAC
+ # (GHSA-25fh-rxp8-67j8), so the two are now one function and this is
+ # its one exemption.
+ "services/api/app/api/v1/deps.py::resolve_jwt_principal::User": (
+ "bearer-token subject lookup; runs before any tenant exists on the request"
+ ),
"services/api/app/api/v1/deps.py::_resolve_api_key::ApiKey": (
"API-key hash lookup; the key row is the credential that carries the tenant"
),
@@ -207,9 +214,6 @@ RATCHET: dict[str, str] = {
"SCIM bearer-token digest lookup; the token row is what assigns the tenant, "
"and RFC 7643 defines no tenant attribute a caller could have supplied"
),
- "services/api/app/api/v1/endpoints/graph_ws.py::_authenticate_ws::User": (
- "websocket ticket verification, same pre-auth shape as get_current_user"
- ),
"services/api/app/api/v1/endpoints/passkeys.py::_consume_challenge::PasskeyChallenge": (
"single-use WebAuthn challenge, matched on its own high-entropy value"
),
diff --git a/services/api/app/api/v1/deps.py b/services/api/app/api/v1/deps.py
index 5f7401ac4..e6ee1bc9a 100644
--- a/services/api/app/api/v1/deps.py
+++ b/services/api/app/api/v1/deps.py
@@ -414,6 +414,28 @@ async def get_current_user(
return service_principal
# --- JWT path ---
+ return await resolve_jwt_principal(token, db)
+
+
+async def resolve_jwt_principal(token: str, db: AsyncSession) -> CurrentUser:
+ """Turn an access token into the principal the API acts for.
+
+ **The one place a JWT becomes a principal.** It was inlined in
+ `get_current_user`, and `graph_ws.py` resolved its own copy by hand for the
+ WebSocket upgrade -- under a docstring claiming "we reuse the same helpers
+ `get_current_user` uses so the auth contract is identical". It did not: the
+ copy checked neither session revocation nor database RBAC, so a
+ de-provisioned principal kept a live subscription to the tenant graph
+ stream while the same token was answered 401 over HTTP
+ (GHSA-25fh-rxp8-67j8).
+
+ Two implementations of one security contract diverge, and the question is
+ only when. So there is one, and both callers use it.
+
+ Raises `HTTPException(401)` on every rejection; the WebSocket caller
+ translates that into a close frame, because an upgrade response cannot
+ carry `WWW-Authenticate`.
+ """
try:
payload = decode_token(token)
user_id: str = payload.get("sub") # type: ignore[assignment]
@@ -426,8 +448,16 @@ async def get_current_user(
detail="Could not validate credentials",
) from e
+ try:
+ subject_uuid = uuid.UUID(user_id)
+ except ValueError as exc:
+ # A `sub` that is not a UUID used to raise `ValueError` out of this
+ # function and become a 500. It is a malformed credential, which is a
+ # 401.
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") from exc
+
result = await db.execute(
- select(User).where(User.id == uuid.UUID(user_id), User.is_active == True) # noqa: E712
+ select(User).where(User.id == subject_uuid, User.is_active == True) # noqa: E712
)
user = result.scalar_one_or_none()
if user is None:
diff --git a/services/api/app/api/v1/endpoints/graph_ws.py b/services/api/app/api/v1/endpoints/graph_ws.py
index 29a8dc07b..e51c5d080 100644
--- a/services/api/app/api/v1/endpoints/graph_ws.py
+++ b/services/api/app/api/v1/endpoints/graph_ws.py
@@ -59,11 +59,9 @@ from fastapi import (
WebSocketDisconnect,
status,
)
-from jwt import PyJWTError
-from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from app.api.v1.deps import CurrentUser, _resolve_api_key
+from app.api.v1.deps import CurrentUser, _resolve_api_key, resolve_jwt_principal
from app.api.v1.dev_auth import (
DEMO_TENANT_ID,
DEMO_USER_EMAIL,
@@ -71,9 +69,7 @@ from app.api.v1.dev_auth import (
DEMO_USER_ROLE,
is_dev_mode,
)
-from app.core.security import decode_token
from app.db.database import get_db
-from app.models.tenant import User
logger = logging.getLogger(__name__)
@@ -136,33 +132,30 @@ async def _authenticate_ws(
)
return None
- # JWT path
+ # JWT path.
+ #
+ # Delegated, not reimplemented. This block used to decode the token, load
+ # the user and build a `CurrentUser` by hand, which skipped the two things
+ # the HTTP dependency does after that: the session-revocation check against
+ # `users.sessions_revoked_at`, and `resolve_permissions`. So a
+ # de-provisioned principal kept a live subscription to the tenant graph
+ # stream for the remaining lifetime of its access token while the same
+ # token was answered `401 Session revoked` over HTTP, and
+ # `require_permission` below fell back to the static role map because
+ # `resolved_permissions` was `None` -- where a wildcard role passes
+ # unconditionally (GHSA-25fh-rxp8-67j8).
+ #
+ # The upgrade response cannot carry `WWW-Authenticate`, which is the only
+ # reason this is not a plain `Depends`, so the 401 is translated into a
+ # close frame here and nowhere else.
try:
- payload = decode_token(token)
- except PyJWTError:
- await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="invalid token")
- return None
- sub = payload.get("sub")
- token_type = payload.get("type", "access")
- if not sub or token_type != "access":
- await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="invalid token")
- return None
- try:
- user_uuid = uuid.UUID(sub)
- except ValueError:
- await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="invalid subject")
- return None
- result = await db.execute(select(User).where(User.id == user_uuid, User.is_active.is_(True)))
- user = result.scalar_one_or_none()
- if user is None:
- await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="user not found")
+ return await resolve_jwt_principal(token, db)
+ except HTTPException as exc:
+ await websocket.close(
+ code=status.WS_1008_POLICY_VIOLATION,
+ reason=str(exc.detail)[:120],
+ )
return None
- return CurrentUser(
- user_id=user.id,
- tenant_id=user.tenant_id,
- role=user.role,
- email=user.email,
- )
@router.websocket("/stream")
diff --git a/services/api/app/auth/oidc.py b/services/api/app/auth/oidc.py
index 8b0e23a18..e8a012e4b 100644
--- a/services/api/app/auth/oidc.py
+++ b/services/api/app/auth/oidc.py
@@ -416,6 +416,13 @@ async def oidc_callback(
issuer=issuer,
email=str(merged.get("email") or ""),
subject=str(merged.get("sub") or ""),
+ # OIDC makes `email_verified` optional, and it arrives as a bool
+ # from most providers and the string "true" from a few. Anything
+ # that is not an affirmative is passed through as not-verified:
+ # "the provider did not say" is not "the provider said yes", and
+ # treating absence as consent is the whole of
+ # GHSA-qjjc-q2h2-56cg.
+ email_verified=_claim_is_true(merged.get("email_verified")),
name=merged.get("name"),
groups=groups,
)
@@ -435,6 +442,21 @@ async def oidc_callback(
return response
+def _claim_is_true(value: Any) -> bool:
+ """Whether a provider affirmatively asserted a boolean claim.
+
+ Returns `False` for `None`, for a missing claim, and for any string that
+ is not an affirmative. There is deliberately no "unknown" third state: the
+ only question the caller asks is "may this claim select an existing
+ account", and the answer to that for an unasserted claim is no.
+ """
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ return value.strip().lower() in {"true", "1", "yes"}
+ return False
+
+
def _claim_groups(claims: dict[str, Any]) -> list[str]:
"""Group names from whichever claim this IdP uses.
diff --git a/services/api/app/auth/saml.py b/services/api/app/auth/saml.py
index 869819995..a3fc77a0a 100644
--- a/services/api/app/auth/saml.py
+++ b/services/api/app/auth/saml.py
@@ -214,6 +214,14 @@ async def saml_acs(request: Request, db: DBSession) -> Response:
subject=str(name_id or ""),
name=_first(attrs.get("displayName") or attrs.get(name_claim, [])),
groups=groups,
+ # A SAML assertion is signed by the identity provider, and the
+ # address it asserts *is* the provider's statement about the
+ # user -- there is no separate `email_verified` claim to
+ # consult, and the signature is the assurance OIDC uses that
+ # claim to provide. Stated here rather than defaulted inside
+ # `complete_sso_login`, so a reader of either caller can see
+ # which assurance applies.
+ email_verified=True,
)
except SsoProvisioningError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
diff --git a/services/api/app/auth/sso_provisioning.py b/services/api/app/auth/sso_provisioning.py
index 0d801dcae..7e63e5716 100644
--- a/services/api/app/auth/sso_provisioning.py
+++ b/services/api/app/auth/sso_provisioning.py
@@ -46,6 +46,7 @@ from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.security import create_access_token, create_refresh_token
+from app.db.rls import set_rls_context
logger = logging.getLogger(__name__)
@@ -110,7 +111,9 @@ async def resolve_connection(db: AsyncSession, *, provider: str, issuer: str) ->
(
await db.execute(
text("""
- SELECT tenant_id, group_role_mapping, default_role, enabled
+ -- `id` is what an identity binding is keyed on, so the
+ -- connection has to carry it: see `_bind_subject`.
+ SELECT id, tenant_id, group_role_mapping, default_role, enabled
FROM aisoc_sso_connections
WHERE provider = :p AND issuer = :i AND enabled = TRUE
LIMIT 1
@@ -126,23 +129,122 @@ async def resolve_connection(db: AsyncSession, *, provider: str, issuer: str) ->
return dict(row) if row else None
+async def _bind_subject(
+ db: AsyncSession,
+ *,
+ tenant_id: Any,
+ connection_id: Any,
+ subject: str,
+ user_id: Any,
+ email: str,
+ provider: str,
+) -> None:
+ """Record that this subject owns this account, on this connection.
+
+ Idempotent on `(connection_id, subject)`: a re-bind of the same pair is a
+ repeat sign-in, which only moves `last_seen_at`. A *different* account for
+ the same pair is refused by the unique index rather than silently
+ repointing the binding, because quietly moving an identity from one account
+ to another is the thing this table exists to prevent.
+ """
+ await db.execute(
+ text(
+ """
+ INSERT INTO aisoc_sso_identities
+ (tenant_id, connection_id, subject, user_id, bound_email, provider)
+ VALUES (:t, :c, :s, :u, :e, :p)
+ ON CONFLICT (connection_id, subject) DO UPDATE
+ SET last_seen_at = now()
+ WHERE aisoc_sso_identities.user_id = EXCLUDED.user_id
+ """
+ ).bindparams(t=tenant_id, c=connection_id, s=subject, u=user_id, e=email, p=provider)
+ )
+ logger.info(
+ "sso.identity_bound email=%s provider=%s subject=%s",
+ _sanitize(email, 80),
+ _sanitize(provider, 20),
+ _sanitize(subject, 64),
+ )
+
+
async def provision_user(
db: AsyncSession,
*,
tenant_id: Any,
+ connection_id: Any,
email: str,
name: str | None,
role: str,
provider: str,
subject: str,
+ email_verified: bool | None,
) -> dict[str, Any]:
"""Find or create the local user this assertion names.
- Matching is on `(tenant_id, email)`. Not on the IdP subject, even
- though that is the stable identifier, because an organisation that
- moves from one IdP to another keeps its email addresses and would
- otherwise get a second account for every person.
+ Three steps, in order, and the order is the security property.
+
+ **1. The subject, if this connection has seen it.** `sub` is the stable
+ identifier, so a bound account survives its owner changing email address at
+ the provider.
+
+ **2. The email, but only if the provider says it verified it.** This used
+ to be the only step, with no `email_verified` requirement anywhere in the
+ OIDC path -- so an attacker who could authenticate to the tenant's
+ configured provider with an account carrying a victim's *unverified*
+ address received a token minted for the victim's local id, and with
+ database-backed RBAC the API resolved the victim's `user_roles`
+ (GHSA-qjjc-q2h2-56cg). A claim that is absent or false is treated as
+ unverified, because OIDC makes `email_verified` optional and "the provider
+ did not say" is not "the provider said yes".
+
+ Matching on email at all is deliberate and stays: an organisation that
+ moves from one identity provider to another keeps its email addresses and
+ would otherwise get a second account for every person. The binding is per
+ **connection**, so a migration starts with none and everyone re-claims
+ their own account on first sign-in -- which is exactly that behaviour.
+
+ **3. Create.** Nobody owns this address yet.
+
+ `email_verified` is `True` for SAML: the assertion is signed by the
+ identity provider, and the address it asserts *is* the provider's
+ statement about the user. There is no separate claim to consult.
"""
+ # ── 1. Already bound on this connection? ──────────────────────────────
+ bound = (
+ (
+ await db.execute(
+ text(
+ "SELECT i.user_id, u.email, u.role, u.is_active "
+ "FROM aisoc_sso_identities i JOIN users u ON u.id = i.user_id "
+ "WHERE i.connection_id = :c AND i.subject = :s AND i.tenant_id = :t "
+ "LIMIT 1"
+ ).bindparams(c=connection_id, s=subject, t=tenant_id)
+ )
+ )
+ .mappings()
+ .first()
+ )
+ if bound:
+ if not bound["is_active"]:
+ raise SsoProvisioningError(f"account {bound['email']} is deactivated")
+ await db.execute(
+ # Tenant-scoped even though `(connection_id, subject)` is unique:
+ # how a row was addressed is irrelevant to what the statement can
+ # reach, and a write that carries its own predicate stays correct
+ # after whatever edit comes next.
+ text(
+ "UPDATE aisoc_sso_identities SET last_seen_at = :now WHERE tenant_id = :t AND connection_id = :c AND subject = :s"
+ ).bindparams(now=datetime.now(UTC), t=tenant_id, c=connection_id, s=subject)
+ )
+ if bound["role"] != role:
+ await db.execute(
+ text("UPDATE users SET role = :r, updated_at = :now WHERE id = :id").bindparams(
+ r=role, now=datetime.now(UTC), id=bound["user_id"]
+ )
+ )
+ return {"id": bound["user_id"], "email": bound["email"], "role": role, "created": False}
+
+ # ── 2. Claim by verified email ────────────────────────────────────────
existing = (
(
await db.execute(
@@ -156,11 +258,65 @@ async def provision_user(
)
if existing:
+ if email_verified is not True:
+ # The whole of GHSA-qjjc-q2h2-56cg in one branch. Refused before
+ # anything is written, because the role refresh below runs on the
+ # way to the return and a rejected sign-in must not have touched
+ # the victim's row.
+ logger.warning(
+ "sso.unverified_email_claim_refused email=%s provider=%s subject=%s",
+ _sanitize(email, 80),
+ _sanitize(provider, 20),
+ _sanitize(subject, 64),
+ )
+ raise SsoProvisioningError(
+ f"the provider did not assert that {email} is verified, so it cannot be used to "
+ "sign in as an existing account. Configure the identity provider to send "
+ "`email_verified: true`, or have the account's owner sign in first."
+ )
if not existing["is_active"]:
# A deactivated account must not be revived by signing in.
# Deactivation is how an operator removes access, and SSO
# re-creating it on the next sign-in would make that useless.
raise SsoProvisioningError(f"account {email} is deactivated")
+
+ # Somebody else on this connection may already own it. The unique
+ # index on `(connection_id, user_id)` would catch this on insert, but
+ # a clear refusal beats a constraint violation an operator has to
+ # decode.
+ claimed = (
+ (
+ await db.execute(
+ text("SELECT subject FROM aisoc_sso_identities WHERE connection_id = :c AND user_id = :u LIMIT 1").bindparams(
+ c=connection_id, u=existing["id"]
+ )
+ )
+ )
+ .mappings()
+ .first()
+ )
+ if claimed and claimed["subject"] != subject:
+ logger.warning(
+ "sso.account_already_bound email=%s provider=%s presented=%s",
+ _sanitize(email, 80),
+ _sanitize(provider, 20),
+ _sanitize(subject, 64),
+ )
+ raise SsoProvisioningError(
+ f"account {email} is already bound to a different identity on this SSO "
+ "connection. An administrator must unbind it before another subject can claim it."
+ )
+
+ await _bind_subject(
+ db,
+ tenant_id=tenant_id,
+ connection_id=connection_id,
+ subject=subject,
+ user_id=existing["id"],
+ email=email,
+ provider=provider,
+ )
+
# The role is refreshed from the IdP on every sign-in, so removing
# someone from a group takes effect at their next login rather than
# requiring a second manual step.
@@ -202,6 +358,19 @@ async def provision_user(
now=now,
)
)
+ # Bound immediately. An account created by this sign-in belongs to the
+ # subject that created it, so the next sign-in takes step 1 above rather
+ # than re-claiming by email -- and nobody else can claim it at all.
+ await _bind_subject(
+ db,
+ tenant_id=tenant_id,
+ connection_id=connection_id,
+ subject=subject,
+ user_id=user_id,
+ email=email,
+ provider=provider,
+ )
+
logger.info(
"sso.user_provisioned email=%s role=%s provider=%s",
_sanitize(email, 80),
@@ -218,6 +387,7 @@ async def complete_sso_login(
issuer: str,
email: str,
subject: str,
+ email_verified: bool | None,
name: str | None = None,
groups: list[str] | None = None,
) -> dict[str, Any]:
@@ -227,6 +397,14 @@ async def complete_sso_login(
"""
if not email:
raise SsoProvisioningError("the assertion carried no email, so no local user can be named")
+ if not subject:
+ # Checked here, with the email, because both are argument validation
+ # and neither needs the database. Without a subject there is nothing to
+ # bind, so an account could only ever be selected by address -- the
+ # shape GHSA-qjjc-q2h2-56cg describes. Both providers always send one:
+ # OIDC `sub` is mandatory and a SAML assertion with no NameID is
+ # malformed.
+ raise SsoProvisioningError("the assertion carried no subject, so the account it names cannot be bound to an identity")
connection = await resolve_connection(db, provider=provider, issuer=issuer)
if connection is None:
@@ -249,14 +427,29 @@ async def complete_sso_login(
if role not in ASSIGNABLE_ROLES:
role = DEFAULT_ROLE
+ # The tenant is known now, and not before: a sign-in callback has no
+ # authenticated principal, so the session it arrives on carries no RLS
+ # context and `current_tenant_id()` is NULL.
+ #
+ # `aisoc_sso_identities` is tenant-scoped with the standard policy, whose
+ # `WITH CHECK` has no null escape -- deliberately, since an unscoped
+ # session that could insert any `tenant_id` is not a control. So the
+ # context is set here, from the connection, which is also the only thing
+ # that decides the tenant on this path. Without it the identity binding
+ # would be refused on every deployment running as the DML-only `aisoc_app`
+ # role, which is every deployment: SSO login would fail outright.
+ await set_rls_context(db, connection["tenant_id"])
+
user = await provision_user(
db,
tenant_id=connection["tenant_id"],
+ connection_id=connection["id"],
email=email,
name=name,
role=role,
provider=provider,
subject=subject,
+ email_verified=email_verified,
)
await db.commit()
diff --git a/services/api/migrations/089_sso_identity_binding.sql b/services/api/migrations/089_sso_identity_binding.sql
new file mode 100644
index 000000000..6a9607db3
--- /dev/null
+++ b/services/api/migrations/089_sso_identity_binding.sql
@@ -0,0 +1,83 @@
+-- Bind an identity-provider subject to the local account it signs in as.
+--
+-- GHSA-qjjc-q2h2-56cg. `provision_user` selected the local account with
+-- `WHERE tenant_id = :t AND lower(email) = lower(:e)`, and nothing in the OIDC
+-- path required `email_verified` -- the word appeared nowhere in `oidc.py` or
+-- `sso_provisioning.py`. So an attacker able to authenticate to the tenant's
+-- configured identity provider with an account carrying a victim's unverified
+-- email received an access token minted for the victim's local id, and with
+-- database-backed RBAC the API then resolved the *victim's* `user_roles`.
+--
+-- Why the binding is per connection, not per tenant
+-- -------------------------------------------------
+-- `provision_user`'s docstring explains why matching was on email at all, and
+-- the reason is good: an organisation that moves from one identity provider to
+-- another keeps its email addresses and would otherwise get a second account
+-- for every person. Binding on `(connection_id, subject)` keeps that true. An
+-- IdP migration is a new connection, so its bindings start empty and everyone
+-- re-claims their own account by verified email on first sign-in. Within one
+-- connection a second subject presenting a bound account's address is either a
+-- provider recycling addresses or an attacker, and neither should win quietly.
+--
+-- `subject` is text and not a uuid: OIDC says `sub` is a case-sensitive string
+-- up to 255 ASCII characters, and SAML NameIDs are routinely longer and are
+-- not uuids either.
+
+CREATE TABLE IF NOT EXISTS aisoc_sso_identities (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+
+ -- The SSO connection this subject was asserted by. Not a foreign key to
+ -- `aisoc_sso_connections` on purpose: deleting a connection must not
+ -- silently drop the bindings that record who claimed which account, and an
+ -- operator who re-creates a connection gets a new id and therefore a clean
+ -- re-claim, which is the migration path above.
+ connection_id UUID NOT NULL,
+
+ subject TEXT NOT NULL,
+
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+
+ -- What the provider asserted at bind time, kept for an auditor asking how
+ -- this account came to be claimed.
+ bound_email TEXT NOT NULL,
+ provider TEXT NOT NULL,
+
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- One subject per connection, and one account per subject.
+CREATE UNIQUE INDEX IF NOT EXISTS aisoc_sso_identities_subject
+ ON aisoc_sso_identities (connection_id, subject);
+
+-- And the other direction: one account may be claimed by at most one subject
+-- on a given connection. Without this, two subjects could each bind to the
+-- same user and both would resolve -- which is the vulnerability wearing a
+-- different hat.
+CREATE UNIQUE INDEX IF NOT EXISTS aisoc_sso_identities_account
+ ON aisoc_sso_identities (connection_id, user_id);
+
+CREATE INDEX IF NOT EXISTS aisoc_sso_identities_tenant
+ ON aisoc_sso_identities (tenant_id);
+
+COMMENT ON TABLE aisoc_sso_identities IS
+ 'Binds an IdP subject to the local account it signs in as, per SSO connection. '
+ 'Closes GHSA-qjjc-q2h2-56cg: before this, an unverified email claim could select '
+ 'any existing account in the tenant.';
+
+DO $$
+BEGIN
+ EXECUTE 'ALTER TABLE aisoc_sso_identities ENABLE ROW LEVEL SECURITY';
+ EXECUTE 'ALTER TABLE aisoc_sso_identities FORCE ROW LEVEL SECURITY';
+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON aisoc_sso_identities';
+ EXECUTE
+ 'CREATE POLICY tenant_isolation ON aisoc_sso_identities '
+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '
+ 'WITH CHECK (tenant_id = current_tenant_id())';
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_sso_identities TO aisoc_app';
+ END IF;
+END
+$$;
diff --git a/services/api/tests/test_graph_ws_auth_matches_http.py b/services/api/tests/test_graph_ws_auth_matches_http.py
new file mode 100644
index 000000000..a1bb1bc51
--- /dev/null
+++ b/services/api/tests/test_graph_ws_auth_matches_http.py
@@ -0,0 +1,127 @@
+"""The WebSocket auth contract is the HTTP one, not a weaker copy of it.
+
+GHSA-25fh-rxp8-67j8. Reported through private vulnerability reporting.
+
+What was wrong
+--------------
+`_authenticate_ws` in `graph_ws.py` resolved a JWT by hand: decode, check the
+type, load the user, build a `CurrentUser`. Its docstring said *"We reuse the
+same helpers `get_current_user` uses so the auth contract is identical."* It
+did not, in two ways that matter:
+
+* **No revocation check.** `get_current_user` calls `token_is_revoked` against
+ `users.sessions_revoked_at`, so a token minted before a session revocation is
+ refused with `401 Session revoked`. The WebSocket path never looked, so a
+ de-provisioned principal kept a live subscription to the tenant graph stream
+ for the remaining lifetime of its access token -- while the *same token* was
+ being refused over HTTP.
+
+* **No database RBAC.** `get_current_user` calls `resolve_permissions` and puts
+ the result in `resolved_permissions`. The hand-built principal left it
+ `None`, so `require_permission("graph:read")` fell back to the static
+ `ROLE_PERMISSIONS` map. A wildcard role passes that unconditionally, which
+ means a database-backed grant revocation had no effect on this surface
+ either.
+
+The reporter's proof of concept is the shape worth keeping: `GET
+/api/v1/graph/overview` answers 401, and `GET /api/v1/graph_ws/stream?token=`
+with the *same token* answers 101 and keeps streaming.
+
+What this file asserts
+----------------------
+That the two paths cannot diverge again: the WebSocket resolver delegates to
+the same function the HTTP dependency uses, rather than reimplementing it. A
+test that merely checked "a revoked token is refused" would pass against a
+second hand-rolled copy that happens to call `token_is_revoked` today and stops
+calling it after the next edit.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+GRAPH_WS = REPO_ROOT / "services" / "api" / "app" / "api" / "v1" / "endpoints" / "graph_ws.py"
+
+
+def _authenticate_ws_calls() -> set[str]:
+ """Every function `_authenticate_ws` calls, by name."""
+ tree = ast.parse(GRAPH_WS.read_text(encoding="utf-8"))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "_authenticate_ws":
+ names: set[str] = set()
+ for call in ast.walk(node):
+ if isinstance(call, ast.Call):
+ func = call.func
+ if isinstance(func, ast.Name):
+ names.add(func.id)
+ elif isinstance(func, ast.Attribute):
+ names.add(func.attr)
+ return names
+ raise AssertionError("graph_ws.py no longer defines _authenticate_ws")
+
+
+class TestTheSocketDoesNotReimplementAuthentication:
+ def test_it_delegates_to_the_shared_resolver(self) -> None:
+ """The durable property. Two implementations of one security contract
+ drift, and this one drifted silently for the whole time it shipped."""
+ calls = _authenticate_ws_calls()
+
+ assert "resolve_jwt_principal" in calls, (
+ "_authenticate_ws still resolves the JWT itself. The HTTP dependency and the "
+ "WebSocket must share one resolver, or the next edit to one leaves the other behind"
+ )
+
+ def test_it_no_longer_builds_a_principal_by_hand_on_the_jwt_path(self) -> None:
+ """A hand-built `CurrentUser` is how `resolved_permissions` became
+ `None`, which is what demoted the permission check to the static role
+ map."""
+ source = GRAPH_WS.read_text(encoding="utf-8")
+ tree = ast.parse(source)
+
+ built = 0
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.AsyncFunctionDef) and node.name == "_authenticate_ws"):
+ continue
+ for call in ast.walk(node):
+ if not isinstance(call, ast.Call):
+ continue
+ if isinstance(call.func, ast.Name) and call.func.id == "CurrentUser":
+ built += 1
+
+ # One remains, and only one: the dev-mode demo principal, which is
+ # gated by `is_dev_mode()` and carries no real identity.
+ assert built <= 1, f"{built} hand-built CurrentUser(...) calls remain in _authenticate_ws"
+
+
+class TestTheSharedResolverEnforcesBothChecks:
+ def test_the_resolver_checks_revocation(self) -> None:
+ from app.api.v1 import deps
+
+ source = inspect.getsource(deps.resolve_jwt_principal)
+
+ assert "token_is_revoked" in source, "the shared resolver does not check session revocation"
+
+ def test_the_resolver_resolves_database_permissions(self) -> None:
+ from app.api.v1 import deps
+
+ source = inspect.getsource(deps.resolve_jwt_principal)
+
+ assert "resolve_permissions" in source, (
+ "the shared resolver does not load database RBAC, so require_permission falls back "
+ "to the static role map and a wildcard role passes unconditionally"
+ )
+
+ def test_the_http_dependency_uses_the_same_resolver(self) -> None:
+ """The negative control on the refactor: if `get_current_user` stopped
+ using it, this test would still pass on the WebSocket side while the
+ two had silently diverged again -- in the other direction."""
+ from app.api.v1 import deps
+
+ source = inspect.getsource(deps.get_current_user)
+
+ assert "resolve_jwt_principal" in source, (
+ "get_current_user no longer uses the shared resolver, so HTTP and WebSocket have diverged again"
+ )
diff --git a/services/api/tests/test_sso_provisioning.py b/services/api/tests/test_sso_provisioning.py
index 0bba99013..b1267f4c2 100644
--- a/services/api/tests/test_sso_provisioning.py
+++ b/services/api/tests/test_sso_provisioning.py
@@ -207,4 +207,40 @@ class TestRefusals:
issuer="https://idp.example",
email="",
subject="s",
+ # Verified, so the refusal under test is unambiguously the
+ # missing email and not the claim added by GHSA-qjjc-q2h2-56cg.
+ email_verified=True,
)
+
+ async def test_no_subject_raises_rather_than_matching_on_email_alone(self) -> None:
+ """Without a subject there is nothing to bind, so an account could only
+ be selected by address -- the shape GHSA-qjjc-q2h2-56cg describes.
+
+ Both providers always send one: OIDC `sub` is mandatory and a SAML
+ assertion with no NameID is malformed, so this is a refusal for a case
+ that should not arise rather than a limitation.
+ """
+ with pytest.raises(SsoProvisioningError, match="no subject"):
+ await sso_provisioning.complete_sso_login(
+ None, # type: ignore[arg-type]
+ provider="oidc",
+ issuer="https://idp.example",
+ subject="",
+ email_verified=True,
+ )
+
+
+class TestTheVerifiedEmailClaim:
+ """GHSA-qjjc-q2h2-56cg: only an affirmative assertion counts."""
+
+ @pytest.mark.parametrize("value", [True, "true", "True", "1", "yes"])
+ def test_an_affirmative_claim_is_read_as_verified(self, value: object) -> None:
+ assert oidc._claim_is_true(value) is True
+
+ @pytest.mark.parametrize("value", [None, False, "false", "", "no", 0, "maybe", [], {}])
+ def test_everything_else_is_not(self, value: object) -> None:
+ """Including absence. OIDC makes the claim optional, so "the provider
+ did not say" must not read as "the provider said yes"."""
+ assert oidc._claim_is_true(value) is False
diff --git a/tests/isolation/test_graph_ws_revocation_live.py b/tests/isolation/test_graph_ws_revocation_live.py
new file mode 100644
index 000000000..72031f7d5
--- /dev/null
+++ b/tests/isolation/test_graph_ws_revocation_live.py
@@ -0,0 +1,242 @@
+"""A revoked session cannot hold the graph WebSocket open. Real Postgres.
+
+GHSA-25fh-rxp8-67j8.
+
+The reporter's proof of concept, executed
+----------------------------------------
+Preconditions: an account whose `users.sessions_revoked_at` is set, and an
+unexpired access token minted before that moment.
+
+1. The HTTP dependency answers **401 Session revoked**.
+2. The WebSocket resolver answered **101 Switching Protocols** and kept
+ streaming.
+
+Step 2 is the vulnerability, and the two steps use the same token. The test
+below drives both resolvers against the same real row, which is the only way to
+show that they now agree -- a source-reading test can show that the WebSocket
+*calls* the shared function, and this shows what the shared function does with
+a revoked principal.
+
+Why this needs a live database
+------------------------------
+`token_is_revoked` compares the token's `iat` against a timestamp column, and
+`resolve_permissions` reads `user_roles`. A fake session that answers any query
+returns a user for both, which is precisely the double that let the original
+defect ship: the offline suite could not tell a working revocation check from
+an absent one.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+from datetime import UTC, datetime, timedelta
+
+import pytest
+import pytest_asyncio
+
+pytestmark = [
+ pytest.mark.asyncio(loop_scope="module"),
+ pytest.mark.skipif(
+ not os.environ.get("ISOLATION_WS_AUTH_DSN", "").strip(),
+ reason="ISOLATION_WS_AUTH_DSN is not set; this suite needs a live Postgres",
+ ),
+]
+
+
+def _dsn() -> str:
+ value = os.environ.get("ISOLATION_WS_AUTH_DSN", "").strip()
+ if not value:
+ pytest.skip("ISOLATION_WS_AUTH_DSN is not set")
+ if value.startswith("postgresql://"):
+ return value.replace("postgresql://", "postgresql+asyncpg://", 1)
+ return value
+
+
+@pytest_asyncio.fixture(scope="module", loop_scope="module")
+async def engine():
+ from sqlalchemy.ext.asyncio import create_async_engine
+
+ eng = create_async_engine(_dsn())
+ try:
+ yield eng
+ finally:
+ await eng.dispose()
+
+
+@pytest_asyncio.fixture(loop_scope="module")
+async def revoked_admin(engine):
+ """An active admin, a token minted for it, and *then* a revocation.
+
+ The sequence is the real one and runs in that order: `create_access_token`
+ stamps `iat` as now, so the token is minted first and the revocation
+ recorded a moment later, exactly as a de-provisioning does.
+
+ `is_active` stays true on purpose. The point of the revocation column is
+ that it ends a session *without* relying on the active flag, and a
+ deactivated user would be refused by a check that was never at fault.
+ """
+ from app.core.security import create_access_token
+ from sqlalchemy import text
+
+ tenant = uuid.uuid4()
+ user = uuid.uuid4()
+ slug = f"wsrev-{tenant.hex[:8]}"
+
+ async with engine.begin() as conn:
+ await conn.execute(
+ text("INSERT INTO tenants (id, name, slug) VALUES (:id, :n, :s)"),
+ {"id": tenant, "n": slug, "s": slug},
+ )
+ await conn.execute(
+ text(
+ """
+ INSERT INTO users (id, tenant_id, email, username, hashed_password,
+ role, is_active)
+ VALUES (:id, :t, :e, :e, 'x', 'admin', true)
+ """
+ ),
+ {"id": user, "t": tenant, "e": f"{slug}@example.test"},
+ )
+
+ token = create_access_token({"sub": str(user), "tenant_id": str(tenant), "role": "admin", "email": f"{slug}@example.test"})
+
+ # Then the de-provisioning. A minute later, so the comparison is not
+ # decided by `iat`'s one-second resolution.
+ async with engine.begin() as conn:
+ await conn.execute(
+ text("UPDATE users SET sessions_revoked_at = :r WHERE id = :id"),
+ {"r": datetime.now(UTC) + timedelta(minutes=1), "id": user},
+ )
+
+ try:
+ yield {"tenant_id": tenant, "user_id": user, "token": token}
+ finally:
+ async with engine.begin() as conn:
+ await conn.execute(text("DELETE FROM users WHERE id = :id"), {"id": user})
+ await conn.execute(text("DELETE FROM tenants WHERE id = :id"), {"id": tenant})
+
+
+class TestTheRevokedTokenIsRefusedOnBothSurfaces:
+ async def test_the_shared_resolver_refuses_it(self, engine, revoked_admin) -> None:
+ from app.api.v1.deps import resolve_jwt_principal
+ from fastapi import HTTPException
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ token = revoked_admin["token"]
+
+ async with AsyncSession(engine) as session:
+ with pytest.raises(HTTPException) as caught:
+ await resolve_jwt_principal(token, session)
+
+ assert caught.value.status_code == 401
+ assert "revoked" in str(caught.value.detail).lower(), caught.value.detail
+
+ async def test_the_websocket_closes_rather_than_streaming(self, engine, revoked_admin) -> None:
+ """The vulnerability itself: this used to return a principal and the
+ stream stayed open."""
+ from app.api.v1.endpoints.graph_ws import _authenticate_ws
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ closed: dict[str, object] = {}
+
+ class _Socket:
+ async def close(self, code: int, reason: str = "") -> None:
+ closed["code"] = code
+ closed["reason"] = reason
+
+ token = revoked_admin["token"]
+
+ async with AsyncSession(engine) as session:
+ principal = await _authenticate_ws(_Socket(), token, session)
+
+ assert principal is None, "the websocket accepted a revoked session"
+ assert closed.get("code") == 1008, closed
+ assert "revoked" in str(closed.get("reason", "")).lower(), closed
+
+
+class TestAValidSessionStillWorks:
+ """The negative control. A resolver that refused everything would pass
+ every test above and take the product down."""
+
+ @pytest_asyncio.fixture(loop_scope="module")
+ async def live_admin(self, engine):
+ from sqlalchemy import text
+
+ tenant = uuid.uuid4()
+ user = uuid.uuid4()
+ slug = f"wsok-{tenant.hex[:8]}"
+ async with engine.begin() as conn:
+ await conn.execute(
+ text("INSERT INTO tenants (id, name, slug) VALUES (:id, :n, :s)"),
+ {"id": tenant, "n": slug, "s": slug},
+ )
+ await conn.execute(
+ text(
+ """
+ INSERT INTO users (id, tenant_id, email, username, hashed_password,
+ role, is_active)
+ VALUES (:id, :t, :e, :e, 'x', 'admin', true)
+ """
+ ),
+ {"id": user, "t": tenant, "e": f"{slug}@example.test"},
+ )
+ try:
+ yield {"tenant_id": tenant, "user_id": user}
+ finally:
+ async with engine.begin() as conn:
+ await conn.execute(text("DELETE FROM users WHERE id = :id"), {"id": user})
+ await conn.execute(text("DELETE FROM tenants WHERE id = :id"), {"id": tenant})
+
+ async def test_an_unrevoked_session_opens_the_socket(self, engine, live_admin) -> None:
+ from app.api.v1.endpoints.graph_ws import _authenticate_ws
+ from app.core.security import create_access_token
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ class _Socket:
+ async def close(self, code: int, reason: str = "") -> None:
+ raise AssertionError(f"closed a valid session: {code} {reason}")
+
+ token = create_access_token(
+ {
+ "sub": str(live_admin["user_id"]),
+ "tenant_id": str(live_admin["tenant_id"]),
+ "role": "admin",
+ "email": "[email protected]",
+ }
+ )
+
+ async with AsyncSession(engine) as session:
+ principal = await _authenticate_ws(_Socket(), token, session)
+
+ assert principal is not None
+ assert principal.user_id == live_admin["user_id"]
+
+ async def test_the_principal_carries_database_permissions(self, engine, live_admin) -> None:
+ """The second half of the advisory: `resolved_permissions` was `None`,
+ so `require_permission` fell back to the static role map and a wildcard
+ role passed unconditionally."""
+ from app.api.v1.endpoints.graph_ws import _authenticate_ws
+ from app.core.security import create_access_token
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ class _Socket:
+ async def close(self, code: int, reason: str = "") -> None:
+ raise AssertionError(f"closed a valid session: {code} {reason}")
+
+ token = create_access_token(
+ {
+ "sub": str(live_admin["user_id"]),
+ "tenant_id": str(live_admin["tenant_id"]),
+ "role": "admin",
+ "email": "[email protected]",
+ }
+ )
+
+ async with AsyncSession(engine) as session:
+ principal = await _authenticate_ws(_Socket(), token, session)
+
+ assert principal is not None
+ assert principal.resolved_permissions is not None, (
+ "the websocket principal still carries no database permissions, so require_permission falls back to the static role map"
+ )
diff --git a/tests/isolation/test_sso_account_binding_live.py b/tests/isolation/test_sso_account_binding_live.py
new file mode 100644
index 000000000..cf030e6d9
--- /dev/null
+++ b/tests/isolation/test_sso_account_binding_live.py
@@ -0,0 +1,364 @@
+"""An unverified email claim cannot take over an existing account.
+
+GHSA-qjjc-q2h2-56cg. Reported through private vulnerability reporting.
+
+What was wrong
+--------------
+`provision_user` selected the local account with
+`WHERE tenant_id = :t AND lower(email) = lower(:e)`, and nothing in the OIDC
+path required `email_verified`. The word `email_verified` appeared **nowhere**
+in `oidc.py` or `sso_provisioning.py`.
+
+So an attacker who can authenticate to the tenant's configured identity
+provider with an account whose *unverified* email matches an existing AiSOC
+user receives an access token minted for that existing user's local id. With
+database-backed RBAC the API then resolves that local user's `user_roles`, so a
+low-privilege group mapping does not contain the damage: the attacker gets the
+victim's permissions, not their own.
+
+`provision_user` already accepted a `subject` parameter and never used it for
+matching. Its docstring explains why, and the reason is good:
+
+ Matching is on `(tenant_id, email)`. Not on the IdP subject, even though
+ that is the stable identifier, because an organisation that moves from one
+ IdP to another keeps its email addresses and would otherwise get a second
+ account for every person.
+
+The fix has to keep that true. It does, by binding the subject **per
+connection**: an IdP migration is a new connection, so bindings do not carry
+over and everyone re-claims their account by verified email on first sign-in --
+exactly the behaviour the docstring describes. Within one connection, a second
+subject presenting a bound account's email is an attack and is refused.
+
+What this file asserts
+----------------------
+Real Postgres with every migration applied, driving `provision_user` directly:
+
+* an unverified claim cannot select an existing account;
+* a verified claim can, and binds;
+* once bound, a different subject on the same connection is refused even with
+ a verified email;
+* the bound subject still resolves after the email changes at the IdP;
+* a new connection re-claims by verified email, so IdP migration still works.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+
+import pytest
+import pytest_asyncio
+
+pytestmark = [
+ pytest.mark.asyncio(loop_scope="module"),
+ pytest.mark.skipif(
+ not os.environ.get("ISOLATION_SSO_DSN", "").strip(),
+ reason="ISOLATION_SSO_DSN is not set; this suite needs a live Postgres",
+ ),
+]
+
+
+def _dsn() -> str:
+ value = os.environ.get("ISOLATION_SSO_DSN", "").strip()
+ if not value:
+ pytest.skip("ISOLATION_SSO_DSN is not set")
+ if value.startswith("postgresql://"):
+ return value.replace("postgresql://", "postgresql+asyncpg://", 1)
+ return value
+
+
+@pytest_asyncio.fixture(scope="module", loop_scope="module")
+async def engine():
+ from sqlalchemy.ext.asyncio import create_async_engine
+
+ eng = create_async_engine(_dsn())
+ try:
+ yield eng
+ finally:
+ await eng.dispose()
+
+
+@pytest_asyncio.fixture(loop_scope="module")
+async def tenant_with_victim(engine):
+ """A tenant, a privileged victim account, and two SSO connection ids."""
+ from sqlalchemy import text
+
+ tenant = uuid.uuid4()
+ victim = uuid.uuid4()
+ connection_a = uuid.uuid4()
+ connection_b = uuid.uuid4()
+ slug = f"sso-{tenant.hex[:8]}"
+ victim_email = f"victim-{tenant.hex[:8]}@example.test"
+
+ async with engine.begin() as conn:
+ await conn.execute(
+ text("INSERT INTO tenants (id, name, slug) VALUES (:id, :n, :s)"),
+ {"id": tenant, "n": slug, "s": slug},
+ )
+ await conn.execute(
+ text(
+ """
+ INSERT INTO users (id, tenant_id, email, username, hashed_password, role, is_active)
+ VALUES (:id, :t, :e, :e, 'x', 'tenant_admin', true)
+ """
+ ),
+ {"id": victim, "t": tenant, "e": victim_email},
+ )
+ try:
+ yield {
+ "tenant_id": tenant,
+ "victim_id": victim,
+ "victim_email": victim_email,
+ "connection_a": connection_a,
+ "connection_b": connection_b,
+ }
+ finally:
+ async with engine.begin() as conn:
+ await conn.execute(text("DELETE FROM aisoc_sso_identities WHERE tenant_id = :t"), {"t": tenant})
+ await conn.execute(text("DELETE FROM users WHERE tenant_id = :t"), {"t": tenant})
+ await conn.execute(text("DELETE FROM tenants WHERE id = :id"), {"id": tenant})
+
+
+async def _provision(engine, *, fixture, subject: str, email: str, verified: bool | None, connection=None):
+ """Call `provision_user` the way `complete_sso_login` does.
+
+ Including the RLS context. A sign-in callback has no authenticated
+ principal, so the session it arrives on carries none, and
+ `aisoc_sso_identities` is tenant-scoped with a `WITH CHECK` that has no
+ null escape -- an unscoped session that could insert any `tenant_id` is not
+ a control. `complete_sso_login` sets it from the connection once the tenant
+ is known, and `TestTheCallbackSetsTheTenantContext` below pins that; this
+ helper mirrors it so these tests exercise the same conditions.
+
+ The fixtures run as the owner because they create tenants and users, which
+ is DDL-adjacent setup. The calls under test run through the application's
+ own session, which in CI is the DML-only `aisoc_app` role -- and that is
+ the role that found this: under the owner, RLS does not apply at all and
+ every one of these passed while SSO login would have been refused on every
+ real deployment.
+ """
+ from app.auth.sso_provisioning import provision_user
+ from app.db.rls import set_rls_context
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ async with AsyncSession(engine) as session:
+ await set_rls_context(session, fixture["tenant_id"])
+ result = await provision_user(
+ session,
+ tenant_id=fixture["tenant_id"],
+ connection_id=connection or fixture["connection_a"],
+ email=email,
+ name="Someone",
+ role="analyst",
+ provider="oidc",
+ subject=subject,
+ email_verified=verified,
+ )
+ await session.commit()
+ return result
+
+
+class TestAnUnverifiedClaimCannotTakeOverAnAccount:
+ async def test_it_is_refused(self, engine, tenant_with_victim) -> None:
+ """The vulnerability. This used to return the victim's user id."""
+ from app.auth.sso_provisioning import SsoProvisioningError
+
+ with pytest.raises(SsoProvisioningError) as caught:
+ await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="attacker-subject",
+ email=tenant_with_victim["victim_email"],
+ verified=False,
+ )
+
+ assert "verif" in str(caught.value).lower(), caught.value
+
+ async def test_an_absent_claim_is_treated_as_unverified(self, engine, tenant_with_victim) -> None:
+ """OIDC makes `email_verified` optional, so absent must mean "not
+ asserted" rather than "fine". Failing open on a missing claim is the
+ same hole with an extra step."""
+ from app.auth.sso_provisioning import SsoProvisioningError
+
+ with pytest.raises(SsoProvisioningError):
+ await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="attacker-subject",
+ email=tenant_with_victim["victim_email"],
+ verified=None,
+ )
+
+ async def test_the_victims_account_is_untouched(self, engine, tenant_with_victim) -> None:
+ """A refusal that had already rewritten the row would be worse than
+ the original defect: the role refresh runs before the return."""
+ from app.auth.sso_provisioning import SsoProvisioningError
+ from sqlalchemy import text
+
+ with pytest.raises(SsoProvisioningError):
+ await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="attacker-subject",
+ email=tenant_with_victim["victim_email"],
+ verified=False,
+ )
+
+ async with engine.connect() as conn:
+ role = (await conn.execute(text("SELECT role FROM users WHERE id = :id"), {"id": tenant_with_victim["victim_id"]})).scalar_one()
+
+ assert role == "tenant_admin", f"the refused sign-in rewrote the victim's role to {role!r}"
+
+
+class TestAVerifiedClaimStillWorks:
+ """The negative control. A guard that refused everything would pass every
+ test above and make SSO unusable."""
+
+ async def test_a_verified_claim_matches_the_existing_account(self, engine, tenant_with_victim) -> None:
+ result = await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="victim-subject",
+ email=tenant_with_victim["victim_email"],
+ verified=True,
+ )
+
+ assert result["id"] == tenant_with_victim["victim_id"]
+ assert result["created"] is False
+
+ async def test_it_binds_the_subject(self, engine, tenant_with_victim) -> None:
+ from sqlalchemy import text
+
+ await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="victim-subject",
+ email=tenant_with_victim["victim_email"],
+ verified=True,
+ )
+
+ async with engine.connect() as conn:
+ bound = (
+ await conn.execute(
+ text("SELECT user_id FROM aisoc_sso_identities WHERE connection_id = :c AND subject = :s"),
+ {"c": tenant_with_victim["connection_a"], "s": "victim-subject"},
+ )
+ ).scalar_one_or_none()
+
+ assert bound == tenant_with_victim["victim_id"]
+
+
+class TestOnceBoundTheSubjectIsTheIdentity:
+ async def test_a_second_subject_cannot_claim_a_bound_account(self, engine, tenant_with_victim) -> None:
+ """Even with a *verified* email. Once this connection has said which
+ subject owns the account, a different one presenting the same address
+ is either a provider that recycles addresses or an attacker, and
+ neither should silently win."""
+ from app.auth.sso_provisioning import SsoProvisioningError
+
+ await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="victim-subject",
+ email=tenant_with_victim["victim_email"],
+ verified=True,
+ )
+
+ with pytest.raises(SsoProvisioningError) as caught:
+ await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="attacker-subject",
+ email=tenant_with_victim["victim_email"],
+ verified=True,
+ )
+
+ assert "already" in str(caught.value).lower() or "bound" in str(caught.value).lower()
+
+ async def test_the_binding_survives_an_email_change(self, engine, tenant_with_victim) -> None:
+ """The reason to bind the subject at all: it is the stable identifier,
+ so somebody who marries and changes address keeps their account and
+ their history."""
+ await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="victim-subject",
+ email=tenant_with_victim["victim_email"],
+ verified=True,
+ )
+
+ renamed = await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="victim-subject",
+ email=f"new-{tenant_with_victim['victim_email']}",
+ verified=True,
+ )
+
+ assert renamed["id"] == tenant_with_victim["victim_id"]
+
+
+class TestIdpMigrationStillWorks:
+ async def test_a_new_connection_re_claims_by_verified_email(self, engine, tenant_with_victim) -> None:
+ """The behaviour `provision_user`'s docstring promises, and the reason
+ matching is on email in the first place: an organisation moving IdP
+ keeps its addresses and must not get a second account per person.
+
+ A new connection means new subjects, so bindings do not carry over --
+ and each person re-claims their own account on first sign-in.
+ """
+ await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="victim-subject",
+ email=tenant_with_victim["victim_email"],
+ verified=True,
+ )
+
+ migrated = await _provision(
+ engine,
+ fixture=tenant_with_victim,
+ subject="entirely-different-subject-at-the-new-idp",
+ email=tenant_with_victim["victim_email"],
+ verified=True,
+ connection=tenant_with_victim["connection_b"],
+ )
+
+ assert migrated["id"] == tenant_with_victim["victim_id"], (
+ "an IdP migration created a second account, which is what matching on email exists to prevent"
+ )
+ assert migrated["created"] is False
+
+
+class TestTheCallbackSetsTheTenantContext:
+ """The defect CI found that a permissive local database could not.
+
+ `aisoc_sso_identities` is tenant-scoped, and its `WITH CHECK` has no
+ `current_tenant_id() IS NULL` escape -- on purpose, because a session with
+ no tenant context that can insert any `tenant_id` is not an isolation
+ control. A sign-in callback carries no principal and therefore no context,
+ so without this the identity binding is refused on every deployment running
+ as the DML-only `aisoc_app` role, which is every deployment: SSO login
+ would have failed outright.
+
+ Read as source because driving `complete_sso_login` needs a configured
+ connection row, a signed assertion and token minting; what has to be
+ pinned is narrow and structural -- that the context is set, and set
+ *before* the provisioning call rather than after it.
+ """
+
+ def test_the_context_is_set_from_the_connection(self) -> None:
+ import inspect
+
+ from app.auth import sso_provisioning
+
+ source = inspect.getsource(sso_provisioning.complete_sso_login)
+
+ assert "set_rls_context" in source, (
+ "complete_sso_login does not set the tenant context, so the identity binding "
+ "is refused under the DML-only role and SSO login fails"
+ )
+ assert source.index("set_rls_context") < source.index("provision_user("), (
+ "the context is set after provisioning, which is too late for the insert it guards"
+ )