Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(8.1): WebAuthn as a console second factor, and MFA enforced per role
Beenu Arora2f63ce0f0dc9
diff --git a/services/api/app/api/v1/endpoints/auth.py b/services/api/app/api/v1/endpoints/auth.pyindex 327035f69..3b0a383fa 100644--- a/services/api/app/api/v1/endpoints/auth.py+++ b/services/api/app/api/v1/endpoints/auth.py@@ -139,7 +139,7 @@ async def login(request: LoginRequest, http_request: Request, db: DBSession) -># rather than by widening the 200 body: `access_token` and# `refresh_token` are required fields of `TokenResponse`, and making# either optional is a break for every generated client.- challenge = await mfa_challenge_for(db, user_id=user.id, tenant_id=user.tenant_id)+ challenge = await mfa_challenge_for(db, user_id=user.id, tenant_id=user.tenant_id, role=user.role)if challenge is not None:return JSONResponse(status_code=status.HTTP_202_ACCEPTED, content=challenge)@@ -161,27 +161,46 @@ async def login(request: LoginRequest, http_request: Request, db: DBSession) ->)-async def mfa_challenge_for(db: Any, *, user_id: uuid.UUID, tenant_id: uuid.UUID) -> dict[str, Any] | None:+async def mfa_challenge_for(+ db: Any,+ *,+ user_id: uuid.UUID,+ tenant_id: uuid.UUID,+ role: str | None = None,+) -> dict[str, Any] | None:"""What this account still owes before a session is issued, or `None`.Two cases and they are not the same thing. An enrolled user owes a- code. A user in an enforcing tenant who has never enrolled owes an- enrolment — refusing them instead would lock out every unenrolled user- the moment an administrator turns the policy on, which is the whole- tenant at once.+ proof. A user the policy covers who has never enrolled owes an+ enrolment — refusing them instead would lock out every unenrolled+ user the moment an administrator turns the policy on, which is the+ whole tenant at once.++ `role` is how depth 8.1's per-role enforcement arrives. It defaults to+ `None`, which `mfa_required_for` answers from the tenant-wide switch+ alone, so a caller that has not been taught about roles enforces+ exactly what it enforced before rather than silently enforcing less.A failure to read either table is **not** treated as "no MFA". Thatwould fail open at the one place in the product where open is worst."""- from app.api.v1.endpoints.mfa import has_confirmed_factor, mint_challenge, tenant_requires_totp+ from app.api.v1.endpoints.mfa import has_confirmed_factor, has_webauthn_factor, mfa_required_for, mint_challengeif await has_confirmed_factor(db, user_id):+ # Only the methods this account can actually use. Offering+ # `webauthn` to somebody with no authenticator sends them to a+ # browser prompt that cannot succeed, and offering `totp` to+ # somebody whose only factor is a security key asks for a code+ # from an app they never set up.+ methods = ["totp", "recovery_code"] if await _has_totp(db, user_id) else []+ if await has_webauthn_factor(db, user_id):+ methods.append("webauthn")return {"mfa_required": True,"mfa_token": mint_challenge(user_id=user_id, tenant_id=tenant_id, purpose="verify"),- "methods": ["totp", "recovery_code"],+ "methods": methods,}- if await tenant_requires_totp(db, tenant_id):+ if await mfa_required_for(db, tenant_id, role):return {"mfa_enrollment_required": True,"mfa_token": mint_challenge(user_id=user_id, tenant_id=tenant_id, purpose="enroll"),@@ -189,6 +208,13 @@ async def mfa_challenge_for(db: Any, *, user_id: uuid.UUID, tenant_id: uuid.UUIDreturn None+async def _has_totp(db: Any, user_id: uuid.UUID) -> bool:+ from app.api.v1.endpoints.mfa import enrolment_row++ row = await enrolment_row(db, user_id)+ return bool(row and row["confirmed_at"])++def settings_dict() -> dict[str, str]:"""The SSO-related environment, read live so an operator can flip theflag without a redeploy. Anything unset reads as its safe default."""diff --git a/services/api/app/api/v1/endpoints/mfa.py b/services/api/app/api/v1/endpoints/mfa.pyindex b36b04896..75e30e53d 100644--- a/services/api/app/api/v1/endpoints/mfa.py+++ b/services/api/app/api/v1/endpoints/mfa.py@@ -69,7 +69,7 @@ from sqlalchemy import textfrom app.api.v1.deps import AuthUser, DBSession, bearer_scheme, get_current_user, require_permissionfrom app.core.config import settings-from app.core.security import create_access_token, create_refresh_token+from app.core.security import ROLE_PERMISSIONS, create_access_token, create_refresh_tokenfrom app.db.rls import set_rls_contextfrom app.security.credential_vault import CredentialVaultError, get_vaultfrom app.services import mfa as totp@@ -147,18 +147,53 @@ async def enrolment_row(db: Any, user_id: uuid.UUID) -> dict[str, Any] | None:return dict(row) if row else None+async def has_webauthn_factor(db: Any, user_id: uuid.UUID) -> bool:+ """Whether this user holds an unrevoked WebAuthn credential.++ Any credential counts, not only one enrolled from the console. Both+ the registration and the authentication path in `passkeys.py` pass+ `require_user_verification=True`, so every row in that table is a+ possession factor that has also verified its holder — which is what a+ second factor is. Insisting on a console-enrolled one would make a+ user who already carries a verified authenticator enrol the same+ device twice, and leave two sign-count high-water marks for one+ authenticator, splitting the clone-detection control in half.+ """+ count = (+ await db.execute(+ text(+ "SELECT count(*) FROM passkey_credentials WHERE user_id = :u AND revoked_at IS NULL"+ ).bindparams(u=user_id)+ )+ ).scalar()+ return bool(count)++async def has_confirmed_factor(db: Any, user_id: uuid.UUID) -> bool:+ """Whether this account can satisfy a challenge with anything at all.++ TOTP **or** WebAuthn. Before depth 8.1 this read the TOTP table alone,+ so a user whose only factor was a passkey counted as unenrolled: an+ enforcing tenant answered them `mfa_enrollment_required` and made them+ add a TOTP secret beside an authenticator that was already stronger.+ """row = await enrolment_row(db, user_id)- return bool(row and row["confirmed_at"])+ if row and row["confirmed_at"]:+ return True+ return await has_webauthn_factor(db, user_id)async def tenant_requires_totp(db: Any, tenant_id: uuid.UUID) -> bool:- """Whether this tenant has asked for a second factor.+ """Whether this tenant requires a second factor of **everybody**.**Absence of a row means no.** No migration writes one: a backfill of arow per tenant would change the meaning of every predicate that countsrows in that table, and this repository has already shipped azero-permission administrator on a fresh install that way.++ Kept under its original name because `auth.py`, the console and three+ tests call it. It is one of the two inputs to `mfa_required_for`,+ which is what callers deciding a sign-in should use."""row = ((await db.execute(text("SELECT require_totp FROM aisoc_tenant_mfa_policy WHERE tenant_id = :t").bindparams(t=tenant_id)))@@ -168,6 +203,44 @@ async def tenant_requires_totp(db: Any, tenant_id: uuid.UUID) -> bool:return bool(row and row["require_totp"])+async def roles_requiring_mfa(db: Any, tenant_id: uuid.UUID) -> set[str]:+ """The roles this tenant enforces a second factor for.++ Absence of a row means not required, for the same reason as above.+ """+ rows = (+ (+ await db.execute(+ text(+ "SELECT role FROM aisoc_tenant_mfa_role_policy WHERE tenant_id = :t AND require_mfa IS TRUE"+ ).bindparams(t=tenant_id)+ )+ )+ .mappings()+ .all()+ )+ return {str(row["role"]) for row in rows}+++async def mfa_required_for(db: Any, tenant_id: uuid.UUID, role: str | None) -> bool:+ """Whether *role* in *tenant* must hold a second factor.++ The tenant-wide switch **or** a row for this role. A deployment that+ wants a factor from its administrators and not from every viewer sets+ the second without the first; one that wants it from everybody sets+ the first and the role rows are then irrelevant.++ `role` of `None` is answered by the tenant-wide switch alone. It is+ not treated as "no role, so no requirement": a principal whose role+ could not be read is the case where failing open is worst.+ """+ if await tenant_requires_totp(db, tenant_id):+ return True+ if not role:+ return False+ return role in await roles_requiring_mfa(db, tenant_id)++def _decrypt_secret(stored: str) -> str:try:return get_vault().decrypt(stored)@@ -307,6 +380,21 @@ class ResetRequest(BaseModel):class MfaPolicy(BaseModel):require_totp: bool+ # Roles this tenant enforces a factor for, over and above the+ # tenant-wide switch. Defaulted so every existing client — and the+ # three tests that construct this model with one argument — keeps+ # working against a body that names no roles.+ require_for_roles: list[str] = Field(default_factory=list)+++class WebAuthnChallengeRequest(BaseModel):+ mfa_token: str+++class WebAuthnVerifyRequest(BaseModel):+ mfa_token: str+ challenge: str+ credential: dict[str, Any]# ─── Routes ───────────────────────────────────────────────────────────────────@@ -444,6 +532,84 @@ async def verify(body: VerifyRequest, db: DBSession, request: Request) -> Sessioraise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="That code is not valid.")+# ─── WebAuthn as the second factor ────────────────────────────────────────────+#+# The credentials, the challenge store and the verification live in+# `passkeys.py`, which the responder app has used since migration `009`.+# This re-uses all three rather than growing a second implementation: a+# second WebAuthn verifier in one tree is two things that can disagree+# about whether a signature is valid.+#+# What is different here is only *what the assertion buys*. In+# `passkeys.py` it is a whole sign-in; here it discharges a challenge that+# `POST /auth/login` already issued against a verified password, and the+# session is minted by this module's `_issue_session` from the user row —+# never from anything the assertion carried.++[email protected]("/webauthn/challenge")+async def webauthn_challenge(body: WebAuthnChallengeRequest, db: DBSession) -> dict[str, Any]:+ """Assertion options for a user part-way through a sign-in.++ The user is taken from the signed `mfa_token`, never from the body:+ an endpoint that let a caller name whose credentials to list would+ answer "does this address hold a passkey" to anybody who asked.+ """+ from app.api.v1.endpoints.passkeys import webauthn_second_factor_options # noqa: PLC0415++ payload = read_challenge(body.mfa_token, expect_purpose="verify")+ user_id = uuid.UUID(str(payload["sub"]))+ tenant_id = uuid.UUID(str(payload["tenant_id"]))+ options = await webauthn_second_factor_options(db, user_id=user_id, tenant_id=tenant_id)+ if options is None:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="No security key or passkey is enrolled for this account. Use your authenticator app or a recovery code.",+ )+ return options++[email protected]("/webauthn/verify", response_model=SessionTokens)+async def webauthn_verify(body: WebAuthnVerifyRequest, db: DBSession, request: Request) -> SessionTokens:+ """Complete a sign-in with a security key or passkey.++ The credential must belong to the user the challenge names. Without+ that check anybody holding **any** enrolled authenticator could+ discharge **anybody's** challenge, which is the whole control.+ """+ from app.api.v1.endpoints.passkeys import verify_second_factor_assertion # noqa: PLC0415++ payload = read_challenge(body.mfa_token, expect_purpose="verify")+ user_id = uuid.UUID(str(payload["sub"]))+ tenant_id = uuid.UUID(str(payload["tenant_id"]))++ device = await verify_second_factor_assertion(+ db,+ user_id=user_id,+ challenge=body.challenge,+ credential=body.credential,+ )+ if device is None:+ logger.warning("mfa.webauthn_failed user=%s source=%s", _sanitize(user_id), _sanitize(client_ip(request), 64))+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="That security key could not be verified.")++ await set_rls_context(db, tenant_id)+ await emit_audit(+ db=db,+ tenant_id=tenant_id,+ actor_id=user_id,+ actor_email=None,+ api_key_prefix=None,+ action="mfa.verified",+ resource="user",+ resource_id=str(user_id),+ changes={"method": "webauthn", "device_name": device, "source_ip": client_ip(request)},+ request=request,+ )+ await db.commit()+ return SessionTokens(**await _issue_session(db, user_id, tenant_id))++async def _consume_recovery_code(db: Any, *, user_id: uuid.UUID, tenant_id: uuid.UUID, code: str, request: Request) -> bool:"""Spend one unused recovery code, or report that none matched.@@ -653,7 +819,10 @@ async def _forget(db: Any, *, user_id: uuid.UUID, tenant_id: uuid.UUID) -> None:async def get_policy(current_user: AuthUser, db: DBSession) -> MfaPolicy:"""Readable by any member: a user is entitled to know what their owntenant requires of them."""- return MfaPolicy(require_totp=await tenant_requires_totp(db, current_user.tenant_id))+ return MfaPolicy(+ require_totp=await tenant_requires_totp(db, current_user.tenant_id),+ require_for_roles=sorted(await roles_requiring_mfa(db, current_user.tenant_id)),+ )@router.put("/policy", response_model=MfaPolicy)@@ -668,7 +837,21 @@ async def put_policy(The tenant is the caller's, never a parameter. A row is written onlywhen an administrator asks for one, so a tenant that has never visitedthis endpoint has no row and is not enforced.++ `require_for_roles` names roles that must hold a factor even when the+ tenant-wide switch is off. Every name is checked against+ `ROLE_PERMISSIONS` before it is stored: a typo would otherwise be+ accepted, match nobody's role, and leave an administrator looking at+ a policy page that says a role is enforced while it is not — the+ quiet direction, and the one worth refusing loudly."""+ unknown = sorted(set(body.require_for_roles) - set(ROLE_PERMISSIONS))+ if unknown:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=f"No such role: {', '.join(unknown)}. A policy naming a role nobody holds enforces nothing.",+ )+await set_rls_context(db, current_user.tenant_id)await db.execute(text("""@@ -678,6 +861,22 @@ async def put_policy(SET require_totp = EXCLUDED.require_totp, updated_by = EXCLUDED.updated_by, updated_at = now()""").bindparams(t=current_user.tenant_id, r=body.require_totp, u=current_user.user_id))++ # The whole role set is replaced rather than merged, so clearing a+ # role from the console actually clears it. A merge would make the+ # page able to add a requirement and never able to remove one.+ requested = sorted(set(body.require_for_roles))+ await db.execute(+ text("DELETE FROM aisoc_tenant_mfa_role_policy WHERE tenant_id = :t").bindparams(t=current_user.tenant_id)+ )+ for role_name in requested:+ await db.execute(+ text("""+ INSERT INTO aisoc_tenant_mfa_role_policy (tenant_id, role, require_mfa, updated_by, updated_at)+ VALUES (:t, :r, TRUE, :u, now())+ """).bindparams(t=current_user.tenant_id, r=role_name, u=current_user.user_id)+ )+await emit_audit(db=db,tenant_id=current_user.tenant_id,@@ -687,8 +886,8 @@ async def put_policy(action="mfa.policy_changed",resource="tenant",resource_id=str(current_user.tenant_id),- changes={"require_totp": body.require_totp},+ changes={"require_totp": body.require_totp, "require_for_roles": requested},request=request,)await db.commit()- return MfaPolicy(require_totp=body.require_totp)+ return MfaPolicy(require_totp=body.require_totp, require_for_roles=requested)diff --git a/services/api/app/api/v1/endpoints/passkeys.py b/services/api/app/api/v1/endpoints/passkeys.pyindex 0e3fa068d..558a061e3 100644--- a/services/api/app/api/v1/endpoints/passkeys.py+++ b/services/api/app/api/v1/endpoints/passkeys.py@@ -306,6 +306,127 @@ async def passkey_register_finish(# --------------------------------------------------------------------------- #+# --------------------------------------------------------------------------- #+# Second-factor use, for the desktop console+# --------------------------------------------------------------------------- #+#+# Depth 8.1. These two are the only WebAuthn code the console MFA path+# calls, and they live here rather than in `mfa.py` so there is exactly+# one verifier in the tree. Two implementations of+# `verify_authentication_response` is two things that can come to+# different conclusions about one signature, and the one that is wrong is+# not necessarily the one that gets fixed.+#+# They are plain functions rather than routes: the routes are in `mfa.py`+# because the thing they guard is a console sign-in, not a passkey.+++async def webauthn_second_factor_options(db: Any, *, user_id: uuid.UUID, tenant_id: uuid.UUID) -> dict[str, Any] | None:+ """Assertion options restricted to *user_id*'s own credentials.++ Returns `None` when the user holds none, so the caller can say so+ rather than offering a challenge no authenticator can answer.++ `allow_credentials` is never empty-and-therefore-discoverable here.+ That is the difference from `passkey_authenticate_begin`, where a+ discoverable assertion is the point: this discharges a challenge for+ one known person, so any other authenticator must simply not be+ offered.+ """+ webauthn, _ = _import_webauthn()++ cred_rows = (+ (+ await db.execute(+ select(PasskeyCredential).where(+ PasskeyCredential.user_id == user_id,+ PasskeyCredential.revoked_at.is_(None),+ )+ )+ )+ .scalars()+ .all()+ )+ if not cred_rows:+ return None++ options = webauthn.generate_authentication_options(+ rp_id=settings.PASSKEY_RP_ID,+ allow_credentials=[+ {"id": _b64url_decode(c.credential_id), "type": "public-key", "transports": c.transports or None}+ for c in cred_rows+ ],+ )+ encoded_challenge = await _store_challenge(+ db,+ purpose="authenticate",+ challenge=options.challenge,+ user_id=user_id,+ tenant_id=tenant_id,+ )+ return {"publicKey": json.loads(webauthn.options_to_json(options)), "challenge": encoded_challenge}+++async def verify_second_factor_assertion(+ db: Any,+ *,+ user_id: uuid.UUID,+ challenge: str,+ credential: dict[str, Any],+) -> str | None:+ """Verify an assertion **and** that it came from *user_id*'s own key.++ Returns the credential's device name on success and `None` on any+ failure, so a caller cannot mistake a falsy result for a pass.++ The `user_id` predicate on the credential lookup is the control.+ Without it, an attacker who has verified a password for one account+ could discharge its challenge with their own enrolled authenticator —+ the signature would be perfectly valid and belong to somebody else.+ """+ webauthn, _ = _import_webauthn()++ raw_credential_id = credential.get("id") or credential.get("rawId")+ if not isinstance(raw_credential_id, str):+ return None++ await _consume_challenge(db, encoded=challenge, purpose="authenticate")++ cred_row = (+ await db.execute(+ select(PasskeyCredential).where(+ PasskeyCredential.credential_id == raw_credential_id,+ PasskeyCredential.user_id == user_id,+ PasskeyCredential.revoked_at.is_(None),+ )+ )+ ).scalar_one_or_none()+ if cred_row is None:+ return None++ try:+ verified = webauthn.verify_authentication_response(+ credential=credential,+ expected_challenge=_b64url_decode(challenge),+ expected_rp_id=settings.PASSKEY_RP_ID,+ expected_origin=settings.PASSKEY_RP_ORIGINS,+ credential_public_key=_b64url_decode(cred_row.public_key),+ credential_current_sign_count=cred_row.sign_count,+ # Not negotiable, and the reason this credential counts as a+ # *second* factor at all: without user verification an+ # assertion proves possession of a device and nothing about+ # who is holding it.+ require_user_verification=True,+ )+ except Exception as exc: # noqa: BLE001 - any verification failure is a refusal+ logger.warning("mfa.webauthn_verification_failed: %s", exc)+ return None++ cred_row.sign_count = int(verified.new_sign_count)+ cred_row.last_used_at = _now()+ return str(cred_row.device_name)++@router.post("/authenticate/begin")async def passkey_authenticate_begin(body: AuthenticateBeginRequest,diff --git a/services/api/app/auth/oidc.py b/services/api/app/auth/oidc.pyindex 7911e087e..3d06cdf50 100644--- a/services/api/app/auth/oidc.py+++ b/services/api/app/auth/oidc.py@@ -441,6 +441,11 @@ async def oidc_callback(email_verified=_claim_is_true(merged.get("email_verified")),name=merged.get("name"),groups=groups,+ # RFC 8176 `amr`. Where the provider states it already+ # performed multi-factor authentication, the console does not+ # ask the same person for the same assurance twice. A provider+ # that says nothing has not said yes.+ authn_methods=[str(m) for m in (merged.get("amr") or []) if m],)except SsoProvisioningError as exc:# A specific reason, not a generic failure. "No SSO connection is@@ -457,9 +462,14 @@ async def oidc_callback(target = state_data.get("redirect", "/")safe_target = _safe_redirect(target)redirect_url = f"/login?next={quote(safe_target, safe='')}"- separator = "&" if "#" in redirect_url else "#"+ # `_session_fragment` answers with a challenge rather than a session+ # when the tenant's policy requires a second factor of the role this+ # sign-in resolved to. Shared with the SAML callback so the two doors+ # cannot disagree about one policy.+ from app.auth.saml import _session_fragment # noqa: PLC0415+response = RedirectResponse(- url=f"{redirect_url}{separator}access_token={session['access_token']}&refresh_token={session['refresh_token']}",+ url=f"{redirect_url}{_session_fragment(session)}",status_code=302,)response.delete_cookie("oidc_state")diff --git a/services/api/app/auth/saml.py b/services/api/app/auth/saml.pyindex 989cb993a..1783f5bb6 100644--- a/services/api/app/auth/saml.py+++ b/services/api/app/auth/saml.py@@ -297,7 +297,7 @@ async def saml_acs(request: Request, db: DBSession) -> Response:# 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"{redirect_url}#access_token={session['access_token']}&refresh_token={session['refresh_token']}"),+ url=f"{redirect_url}{_session_fragment(session)}",status_code=302,)@@ -381,6 +381,28 @@ def _first(lst: list[str]) -> str:return lst[0] if lst else ""+def _session_fragment(session: dict[str, Any]) -> str:+ """The URL fragment a completed callback lands on.++ Two outcomes, and the difference is whether a session exists at all.+ When the tenant's policy requires a second factor of this role and+ the provider did not assert one, `complete_sso_login` returns a+ challenge and **no tokens** — so there is nothing to put in the+ fragment but the challenge, and the console's sign-in page asks for+ the factor before anybody is signed in.++ Reading `access_token` unconditionally, as this did before depth 8.1,+ would raise `KeyError` inside the handler on exactly the deployments+ that enforce MFA. Shared with the OIDC callback so the two cannot+ answer differently.+ """+ if session.get("mfa_required") or session.get("mfa_enrollment_required"):+ methods = ",".join(str(m) for m in (session.get("methods") or []))+ key = "mfa_required" if session.get("mfa_required") else "mfa_enrollment_required"+ return f"#{key}=1&mfa_token={quote(str(session['mfa_token']), safe='')}&methods={quote(methods, safe='')}"+ return f"#access_token={session['access_token']}&refresh_token={session['refresh_token']}"++async def _build_saml_request(request: Request) -> dict[str, Any]:"""Convert FastAPI request to the dict expected by python3-saml."""body = await request.body()diff --git a/services/api/app/auth/sso_provisioning.py b/services/api/app/auth/sso_provisioning.pyindex 69ae74f6a..2cc9484f6 100644--- a/services/api/app/auth/sso_provisioning.py+++ b/services/api/app/auth/sso_provisioning.py@@ -434,6 +434,55 @@ async def provision_user(return {"id": user_id, "email": email, "role": role, "created": True, "previous_role": None}+# Authentication-method values that mean "the identity provider already+# performed multi-factor authentication". OIDC sends them in `amr`+# (RFC 8176); SAML sends an `AuthnContextClassRef`, and the two spellings+# below are the ones in the SAML 2.0 authentication context specification+# that denote more than one factor.+#+# Deliberately short. `pwd`, `sms` and `tel` are **not** here: a password+# is the factor the console already has, and a one-time code over SMS or a+# phone call is the factor every published guidance tells an operator to+# stop relying on. An allowlist that grows by accident is a policy that+# turns itself off.+MULTI_FACTOR_AUTHN_METHODS: frozenset[str] = frozenset(+ {+ "mfa",+ "otp",+ "hwk",+ "swk",+ "urn:oasis:names:tc:SAML:2.0:ac:classes:MobileTwoFactorContract",+ "urn:oasis:names:tc:SAML:2.0:ac:classes:TimeSyncToken",+ "urn:oasis:names:tc:SAML:2.0:ac:classes:SmartcardPKI",+ }+)+++def idp_asserted_multi_factor(authn_methods: list[str] | None) -> bool:+ """Whether the assertion states the provider performed MFA itself.++ `None` and `[]` both mean "did not say", which is not the same as+ "did not" — and is treated the same way, because the console cannot+ tell the difference and the safe reading of silence is that no second+ factor has been proved.+ """+ return any(str(method).strip() in MULTI_FACTOR_AUTHN_METHODS for method in (authn_methods or []))+++async def _second_factor_challenge(+ db: AsyncSession, *, tenant_id: Any, user_id: Any, role: str+) -> dict[str, Any] | None:+ """The challenge this SSO sign-in still owes, or `None`.++ Delegates to the same two helpers `POST /auth/login` uses, so the+ password door and the SSO door cannot come to different conclusions+ about one policy. A reimplementation here is how they would drift.+ """+ from app.api.v1.endpoints.auth import mfa_challenge_for # noqa: PLC0415++ return await mfa_challenge_for(db, user_id=user_id, tenant_id=tenant_id, role=role)++async def complete_sso_login(db: AsyncSession,*,@@ -444,10 +493,29 @@ async def complete_sso_login(email_verified: bool | None,name: str | None = None,groups: list[str] | None = None,+ authn_methods: list[str] | None = None,) -> dict[str, Any]:"""The whole path: assertion to a token the API actually verifies.- Returns `{access_token, refresh_token, role, user_id, tenant_id}`.+ Returns `{access_token, refresh_token, role, user_id, tenant_id}` —+ **or**, when the tenant's MFA policy covers the role this sign-in+ resolved to and the identity provider did not say it performed+ multi-factor authentication, `{mfa_required, mfa_token, methods,+ role, user_id, tenant_id}` and no session at all.++ Depth 8.1. Before it, the policy was consulted by `POST /auth/login`+ and by nothing else, so a tenant that required a second factor of its+ administrators got one from anybody who typed a password and from+ nobody who arrived through SSO. Callers must handle the challenge+ shape; the two in this repository redirect to the console's+ second-factor page carrying `mfa_token` in the URL fragment.++ `authn_methods` is what the assertion said about how the user+ authenticated — OIDC's `amr`, or the SAML `AuthnContextClassRef`.+ Where the provider states it already performed multi-factor+ authentication, asking for a second one is asking the same person for+ the same assurance twice. Absence means not evidenced, never+ satisfied."""if not email:raise SsoProvisioningError("the assertion carried no email, so no local user can be named")@@ -557,6 +625,27 @@ async def complete_sso_login(await db.rollback()logger.warning("sso.login_audit_failed error=%s", _sanitize(audit_exc))+ # Depth 8.1. The second factor, if this tenant requires one of this+ # role and the provider did not already supply one.+ #+ # Checked *after* provisioning on purpose: the account and its+ # identity binding are the record of who signed in, and they are+ # correct whether or not a session is issued. Checking first would+ # mean a user covered by the policy never gets an account, so the+ # administrator enforcing the policy cannot see them to help them.+ if not idp_asserted_multi_factor(authn_methods):+ challenge = await _second_factor_challenge(+ db, tenant_id=connection["tenant_id"], user_id=user["id"], role=role+ )+ if challenge is not None:+ return {+ **challenge,+ "role": role,+ "user_id": str(user["id"]),+ "tenant_id": str(connection["tenant_id"]),+ "provisioned": user["created"],+ }+claims = {"sub": str(user["id"]),"tenant_id": str(connection["tenant_id"]),