From 39c89f098d8ede49f7d051cfde03714dda9ed638 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:44:47 -0600 Subject: [PATCH 1/5] Auth: a pending session with no factor ends no sessions under require_mfa Under [security].require_mfa a session on an account with no enrolled factor is MFA-pending. It is now confined like any other pending session: it reaches enrolment and sign-out, and is refused elsewhere, the session-terminate routes included, with a refusal naming enrolment. - AuthService: session_terminate, save_ends_own_sessions and revoke_all_sessions are refused to every pending session, the account's factors aside, so no re-proof (password or IdP) mints them. The enrolment actions keep the first-enrolment carve-out. - JSON: the MFA refusal keeps 403 + X-MFA-Required and its leading text; for a pending session with no factor the detail names enrolment. - Console: the reauth-only action gate sends such a session to /ui/account?m=enroll_first instead of /ui/reauth. - Docs: SECURITY.md and CONFIGURATION.md; changelog fragment. - Seam: the console gate body moved the seam digest; re-derived with --write and the console accepted seam set by hand. - Tests: two old tests that pinned the no-factor terminate inverted. Every other path keeps main's result: a session that owes no factor (require_mfa off, or out of scope) and one with a factor are unchanged. Not built: #3941 item 2 (the route-set / revoke-set race). BACKLOG #1149 (ASVS 7.5.2) Proposed PR title: Auth: a pending session with no factor ends no sessions under require_mfa (BACKLOG #1149) Proposed banner: PARTIAL -- engine closes ground 2 (no-factor pending session refused session-ending grants and terminates, refusal names enrolment). Left: #3941 item 2 decision; 7.5.2 re-score (vault record work). --- ...actor-pending-ends-no-sessions.security.md | 9 + docs/CONFIGURATION.md | 2 +- docs/SECURITY.md | 28 +-- messagefoundry/api/_ui_seam.py | 7 +- messagefoundry/api/security.py | 46 ++++- messagefoundry/auth/service.py | 52 ++++-- messagefoundry_webconsole/__init__.py | 2 +- messagefoundry_webconsole/_auth.py | 8 +- .../tests/test_ui_mfa_gate.py | 75 +++++++- tests/golden/webconsole_seam.snapshot | 12 +- tests/test_api_auth.py | 15 +- tests/test_derived_gate_decision_audit.py | 4 + tests/test_mfa_access_gate.py | 169 +++++++++++++++++- .../test_session_token_at_elevation_sites.py | 12 +- 14 files changed, 373 insertions(+), 68 deletions(-) create mode 100644 changelog.d/1149-no-factor-pending-ends-no-sessions.security.md diff --git a/changelog.d/1149-no-factor-pending-ends-no-sessions.security.md b/changelog.d/1149-no-factor-pending-ends-no-sessions.security.md new file mode 100644 index 0000000000..3248a2f010 --- /dev/null +++ b/changelog.d/1149-no-factor-pending-ends-no-sessions.security.md @@ -0,0 +1,9 @@ +- **A pending session on an account with no second factor no longer ends sessions.** Under + `[security].require_mfa`, such a session is MFA-pending, and it is now treated like any other + pending session: it reaches enrolment and sign-out, and the self-service terminate routes + (`DELETE /me/sessions`, `DELETE /me/sessions/{session_id}` and their console twins) refuse it. + No password re-proof mints it a `session_terminate`, `save_ends_own_sessions` or + `revoke_all_sessions` grant, so none can be carried through its first enrolment. The JSON refusal + keeps `403` + `X-MFA-Required` and its detail now names enrolment; the console sends the session + to `/ui/account?m=enroll_first`. The enrolment that binds the first factor satisfies the session, + and ending sessions then works as before. (`BACKLOG #1149`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 263925f27d..3e1461ba2a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3586,7 +3586,7 @@ and a PHI weakening under **strict enforcement** (`enforcement = enforce`, the d | `external_link_interstitial` | bool | `true` | **`[BUILT]` (ASVS 3.7.3):** show the "you are leaving this site" page at all. Setting it `false` means the console navigates off-site with **no notification and no cancel** — that is the control itself, so this is a posture decision rather than a convenience one, and `serve` prints a warning naming it at every start. The federated sign-in leg is affected: with the interstitial on and the IdP outside `organization_domains`, `GET /ui/oidc/start` renders the page and the flow is minted only on confirm (`POST`), which also closes the standing hole where any external page could begin a sign-in by linking to the start leg. Env: `MEFOR_SECURITY_EXTERNAL_LINK_INTERSTITIAL` | | `external_link_allowlist` | list[str] | `[]` | **`[BUILT]` (ASVS 3.7.3) — WARNING: THE AUDITED ESCAPE, AND IT LOWERS SECURITY.** Destinations listed here are navigated to with **no notification and no cancel**, which is precisely what the requirement asks for. It exists for legitimate high-volume external destinations an operator does not want to declare as their own domain. Same entry rule as `organization_domains`, the IPv4 exception included, and the same label-boundary matching. Non-empty makes `serve` print a warning **naming every entry individually** — never a count, because "3 destinations exempted" is the shape of message that lets an entry nobody intended sit in a list for a year. **Prefer `organization_domains`**: declaring a domain you control is a statement about scope; allowlisting one you do not is a waiver. Env: `MEFOR_SECURITY_EXTERNAL_LINK_ALLOWLIST` | | `require_sign_in` | | | **→ REMOVED** (vault BACKLOG #2719). Sign-in is always required, on every bind. Setting this key is refused at load, from the file or as `MEFOR_SECURITY_REQUIRE_SIGN_IN`, whatever its value. The loopback mode it used to allow named no person in the audit trail and could not repair an account. If every Administrator signs in through an outside service, keep a local Administrator ([SECURITY.md](SECURITY.md#keep-a-local-administrator)). | -| `require_mfa` | bool | `true` | second factor (native TOTP or a WebAuthn passkey), enforced as an **access gate** since ASVS 6.3.3 — an MFA-pending session is refused on *every* authorized route with `403` + `X-MFA-Required: 1`, and a browser session is redirected to `/ui/mfa`. **The enrolment path is a deliberate exemption, not a re-route:** `/ui/mfa` itself and the account/enrolment routes (`GET /ui/account`, the password and factor-enrolment routes) are declared `allow_mfa_pending=True` ([`messagefoundry_webconsole/_auth.py`](../messagefoundry_webconsole/_auth.py), `routes/account.py`), so a user with **no** factor enrolled is not stranded — send them to **`/ui/account`** to enrol. A local account that `require_mfa` and `require_mfa_scope` cover enrols **TOTP or a discoverable passkey first**, a factor with a way past the sign-in lock (ADR 0197 Amendment A, wave 2). Until it holds one, `POST /me/password` refuses with `enrol an authenticator app first` (403; a pending session that holds a passkey gets `X-MFA-Required` first), the console's password page redirects to `/ui/account?m=enroll_first`, and a passkey registration whose client reports it is not discoverable is refused. A directory account may enrol TOTP or a passkey. Say "redirected to", not "confined to": `/ui/mfa` renders a code field only once TOTP is enrolled and a passkey button only once WebAuthn is, so a zero-factor user who is told they cannot leave that page is looking at a page with no form. | +| `require_mfa` | bool | `true` | second factor (native TOTP or a WebAuthn passkey), enforced as an **access gate** since ASVS 6.3.3 — an MFA-pending session is refused on *every* authorized route with `403` + `X-MFA-Required: 1`, and a browser session is redirected to `/ui/mfa`. **The enrolment path is a deliberate exemption, not a re-route:** `/ui/mfa` itself and the account/enrolment routes (`GET /ui/account`, the password and factor-enrolment routes) are declared `allow_mfa_pending=True` ([`messagefoundry_webconsole/_auth.py`](../messagefoundry_webconsole/_auth.py), `routes/account.py`), so a user with **no** factor enrolled is not stranded — send them to **`/ui/account`** to enrol. Such a user is MFA-pending too, so it cannot end sessions before it enrols: the terminate routes (`DELETE /me/sessions` and `DELETE /me/sessions/{session_id}`, and the console's twins) refuse it, the JSON refusal's detail naming enrolment and the console redirecting to `/ui/account?m=enroll_first`, and the enrolment that binds its first factor satisfies the session (BACKLOG #1149). The access gate's own `403` names enrolment to such a session too. A local account that `require_mfa` and `require_mfa_scope` cover enrols **TOTP or a discoverable passkey first**, a factor with a way past the sign-in lock (ADR 0197 Amendment A, wave 2). Until it holds one, `POST /me/password` refuses with `enrol an authenticator app first` (403; a pending session that holds a passkey gets `X-MFA-Required` first), the console's password page redirects to `/ui/account?m=enroll_first`, and a passkey registration whose client reports it is not discoverable is refused. A directory account may enrol TOTP or a passkey. Say "redirected to", not "confined to": `/ui/mfa` renders a code field only once TOTP is enrolled and a passkey button only once WebAuthn is, so a zero-factor user who is told they cannot leave that page is looking at a page with no form. | | `require_mfa_scope` | `"administrators"` \| `"every_local_account"` | `"every_local_account"` | **Which accounts must ENROL a factor** when `require_mfa` is on (ASVS 6.3.3). An account that has already enrolled one must satisfy it while it keeps one, under either value (an OIDC sign-in meets it while `[auth].oidc_require_mfa_claim` is on, the default) — this dial only decides who is required to enrol in the first place. `administrators` restores the pre-6.3.3 posture and is reported as a **loosening** on `GET /security/posture` (advisory, not a refusal: refusing to boot on it would break every existing deployment on upgrade). **The `every_local_account` value is wider than its name** (BACKLOG #1144): directory (AD/Kerberos) identities used to be out of scope under either value, and they are not any more — the directory legs assert no strength the engine can read, so a Kerberos session mints MFA-pending and its holder enrols an engine factor. The value's spelling is stale; renaming a `Literal` reaches the settings model, this table and the tests that pin both, which is its own coherent change rather than a rider on a security fix. **Operator note:** under the default a non-interactive **bearer-token service account** becomes MFA-pending and cannot enrol unattended. Two settings answer it, each with a limit. **Set this to `administrators`**, which frees only a **local** account that does not hold the Administrator role: the Administrator role stays in scope under either value, and a directory session that proved no factor stays MFA-pending under both. Or **set `require_mfa = false`**, which frees any account that has not enrolled a factor, whatever its role; on an exposed instance under `enforcement = enforce`, `serve` then refuses to start unless `allow_single_factor_admin_when_exposed` is set (see that row). An account that has enrolled a factor still owes it either way while it keeps one, with the same OIDC exception. With `require_mfa` off, or for an account `require_mfa_scope` leaves out (under `administrators`, any account without the Administrator role, directory ones included), the holder may remove its last factor. Under `administrators` with `require_mfa` on, a directory account that does so is still not single-factor: its next Kerberos session stays MFA-pending until it enrols again. Making it an AD principal is **no longer** an escape, and mTLS is not one either: a cert-identity is exempt from the MFA gate but is admitted on exactly one route (`GET /service/identity`), so it cannot carry a working service account (see the [`[api]`](#api) `tls_client_cert_identities` row). Env: `MEFOR_SECURITY_REQUIRE_MFA_SCOPE` | | `sign_out_after_idle_minutes` | int | `30` | session idle timeout; `1` to `525600` (a year), refused at load outside that (BACKLOG #5772) | | `max_session_hours` | int | `12` | session absolute lifetime; `1` to `8760` (a year), refused at load outside that (BACKLOG #5772) | diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 683b84c934..5679585980 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -4070,10 +4070,12 @@ The complete set, as enumerated in the [route map](#route--permission-map-engine Ordinary reads — listing users, the AD maps, the audit log, a single message — are **not** step-up gated. Four routes take the *password-only* variant (`require_reauth_only[_action]`), deliberately **without** the MFA gate so a required-but-unenrolled user cannot deadlock: `POST /me/mfa/enroll`, -`POST /me/mfa/confirm`, `DELETE /me/sessions/{session_id}`, `DELETE /me/sessions`. The skip serves -an account with no factor only: a pending session on an account that has one gets `403` + -`X-MFA-Required` on all four (BACKLOG #1951; see the "Binding a NEW second factor, or ending -sessions" row). +`POST /me/mfa/confirm`, `DELETE /me/sessions/{session_id}`, `DELETE /me/sessions`. On the two +enrolment routes the skip serves an account with no factor only: a pending session on an account +that has one gets `403` + `X-MFA-Required` there (BACKLOG #1951). On the two terminate routes it +serves no pending session: one on an account that has a factor gets the same `403`, and so does one +on an account with no factor that `[security].require_mfa` covers, whose detail names enrolment as +the next step (BACKLOG #1149). See the "Binding a NEW second factor, or ending sessions" row. This re-proves a credential of the session's account (secondary verification): the local password, the directory password by a live re-bind, or for an `oidc` session a fresh IdP sign-in. With **WP-14 native TOTP MFA** built, the step-up @@ -5034,7 +5036,7 @@ slack. | First-seen sign-in address — sign-in owes a second factor, or any directory sign-in | as the row above | as the row above | **LOG** — the same audit row and notice. A directory sign-in that owes nothing more also records the address, so the next one from it is not reported again; nothing else changes. **Under the shipped `require_mfa` a Kerberos sign-in always owes a factor**, and so does an OIDC one while `oidc_require_mfa_claim` is off. Such a sign-in records nothing; the factor leg that finishes it records the address instead: a TOTP or recovery code, a passkey, or a factor enrolment, under the conditions in the row above. So on this leg, as on the local one, every sign-in is unjudged (`no_baseline`) until one finishes, and a sign-in abandoned at the factor prompt records nothing. Under the same default no directory step-up records an address (see the row above). Such a session is born without step-up freshness anyway. A later proof stamps the window, for example a TOTP or recovery code, a user-verified passkey, or a step-up. On an OIDC session only the IdP step-up does (BACKLOG #2142). A Kerberos or password session steps up with the account password; an `oidc` session steps up at the IdP. Under the shipped `require_mfa` scope (`every_local_account`) this is the path every password-only local sign-in takes. A combined sign-in (password and a TOTP code or a passkey assertion in one request) owes nothing more, so it takes the row above instead and is seeded from any address. **Never** refuses the login (BACKLOG #288) | on | (no knob) | | Credential recency | age of `session.reauth_at` | `now − reauth_at > step_up_max_age_seconds`, or `reauth_at is None` | **DENY** 403 + `X-Step-Up-Required: 1` (console: 303 → `/ui/reauth`; an `oidc` session's JSON refusal names the IdP leg, see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753)) | 300 s | `[auth].step_up_max_age_seconds` | | Action-bound step-up grant | a single-use grant minted only by a successful step-up, on the **monotonic** clock: `reauth(purpose=…)` for the password or re-bind leg (`POST /me/reauth`, `POST /ui/reauth`), and `complete_oidc_step_up` for an `oidc` session's IdP leg, for the action the operator started from. Never by a sign-in or by `verify_mfa` | no unconsumed grant for this route's action | **DENY** 403 + `X-Step-Up-Required` + `X-Step-Up-Action: `; opting out falls back to the session window — **except on a factor bind or a session terminate**, see the row below | on | `[auth].require_action_step_up` | -| Binding a NEW second factor, ending sessions, or changing the password | the session's MFA state × the account's existing factors | the action binds a factor (`mfa_enroll`, `mfa_confirm`, `webauthn_enroll`), ends sessions (`session_terminate`, BACKLOG #1951) or changes the password (`POST /me/password` and `/ui/account/password`, BACKLOG #1954) **and** the session has not satisfied its second factor **and** the account already holds one of either kind | **DENY** — the existing factor must be proven first (`POST /auth/mfa-verify`, `/ui/mfa`, or the code/passkey leg of `/ui/reauth`); the password routes answer 403 + `X-MFA-Required` (console: 303 → `/ui/mfa`, except a covered local account whose passkeys are not discoverable and which has no TOTP, which the console sends to the enrolment page). This refusal never reaches an account with **no** factor, which has nothing to prove: it enrols its first factor and ends its own sessions from a password-only session, which is what the MFA gate's exemptions are for. Two other rules still bind it. Under `[security].require_mfa` a covered local account's first factor must be TOTP or a discoverable passkey: a passkey whose client reports it is not discoverable is refused at the registration finish, and the password change is refused with `enrol an authenticator app first` until such a factor exists (`FactorEnrolmentRequired`, ADR 0197 Amendment A; console: a 303 to the enrolment page). And a must-change session cannot end its sessions at all, because the must-change confinement does not admit those routes. With the requirement off, such an account changes its password as before. The passkey registration **finish** asks the same rule again (`finish_webauthn_registration`, BACKLOG #3014), because its console route rides the action-less gate: a ceremony staged before the account gained a factor is refused with **400** `this account already has a second factor`, its ceremony ended, audited `auth.mfa_denied`. Both enrolment legs, this finish and the TOTP confirm (`confirm_mfa_enrollment`, whose first ask is its route's gate), ask it once more after the login-to-MFA floor and a directory account's directory lookup. A factor bound on another session during either is refused with a 400 `this account already has a second factor`, audited `auth.mfa_denied`. The TOTP confirm refuses this way only for a passkey, before it spends a step or mints a recovery code; a TOTP enabled meanwhile is left to its enable's compare-and-set, which ends the session (BACKLOG #2224). On the passkey finish the insert is conditional too: the store asks the same rule inside the insert's own transaction, so a factor bound on another session after that second ask is refused there, with the same 400 and the same `auth.mfa_denied` row, no passkey stored and the session not stamped (BACKLOG #3690 item 1). The server backends lock the account row for that check, as every factor write there does, and the session row after it. SQLite holds its one writer lock instead, which no other writer in the process passes; a write from another process that commits between the check and the insert fails the finish with an error, storing nothing, rather than the 400. The rule is the same one: a session already stamped MFA-verified, including one a sign-in that owed nothing minted stamped, is not refused. The TOTP confirm is still read-then-act: a factor bound after its second ask, for example while it hashes its recovery codes, is not caught (BACKLOG #3061) | on | **no knob** — `require_action_step_up` does not reach it, deliberately | +| Binding a NEW second factor, ending sessions, or changing the password | the session's MFA state × the account's existing factors | the action binds a factor (`mfa_enroll`, `mfa_confirm`, `webauthn_enroll`), ends sessions (`session_terminate`, BACKLOG #1951) or changes the password (`POST /me/password` and `/ui/account/password`, BACKLOG #1954) **and** the session has not satisfied its second factor **and** the account already holds one of either kind | **DENY** — the existing factor must be proven first (`POST /auth/mfa-verify`, `/ui/mfa`, or the code/passkey leg of `/ui/reauth`); the password routes answer 403 + `X-MFA-Required` (console: 303 → `/ui/mfa`, except a covered local account whose passkeys are not discoverable and which has no TOTP, which the console sends to the enrolment page). The factor-binding and password refusals do not reach an account with **no** factor, which has nothing to prove: it enrols its first factor from a password-only session, which is what the MFA gate's exemptions are for. Ending sessions is different (BACKLOG #1149, ASVS 7.5.2): `session_terminate`, `save_ends_own_sessions` and `revoke_all_sessions` are refused to a pending session on an account with no factor too, which under `[security].require_mfa` is MFA-pending. No step-up mints it those grants, the JSON terminate routes answer 403 + `X-MFA-Required` with a detail naming enrolment, and the console sends it to the enrolment page. The enrolment that binds its first factor satisfies the session, and the terminate then works. Two other rules still bind such an account. Under `[security].require_mfa` a covered local account's first factor must be TOTP or a discoverable passkey: a passkey whose client reports it is not discoverable is refused at the registration finish, and the password change is refused with `enrol an authenticator app first` until such a factor exists (`FactorEnrolmentRequired`, ADR 0197 Amendment A; console: a 303 to the enrolment page). And a must-change session cannot end its sessions at all, because the must-change confinement does not admit those routes. With the requirement off, such an account changes its password as before. The passkey registration **finish** asks the same rule again (`finish_webauthn_registration`, BACKLOG #3014), because its console route rides the action-less gate: a ceremony staged before the account gained a factor is refused with **400** `this account already has a second factor`, its ceremony ended, audited `auth.mfa_denied`. Both enrolment legs, this finish and the TOTP confirm (`confirm_mfa_enrollment`, whose first ask is its route's gate), ask it once more after the login-to-MFA floor and a directory account's directory lookup. A factor bound on another session during either is refused with a 400 `this account already has a second factor`, audited `auth.mfa_denied`. The TOTP confirm refuses this way only for a passkey, before it spends a step or mints a recovery code; a TOTP enabled meanwhile is left to its enable's compare-and-set, which ends the session (BACKLOG #2224). On the passkey finish the insert is conditional too: the store asks the same rule inside the insert's own transaction, so a factor bound on another session after that second ask is refused there, with the same 400 and the same `auth.mfa_denied` row, no passkey stored and the session not stamped (BACKLOG #3690 item 1). The server backends lock the account row for that check, as every factor write there does, and the session row after it. SQLite holds its one writer lock instead, which no other writer in the process passes; a write from another process that commits between the check and the insert fails the finish with an error, storing nothing, rather than the 400. The rule is the same one: a session already stamped MFA-verified, including one a sign-in that owed nothing minted stamped, is not refused. The TOTP confirm is still read-then-act: a factor bound after its second ask, for example while it hashes its recovery codes, is not caught (BACKLOG #3061) | on | **no knob** — `require_action_step_up` does not reach it, deliberately | | MFA state | `session.mfa_verified_at` × factor enrollment × account roles | the rule is **provider-blind** (BACKLOG #1144 — an AD account used to be exempt here, on a delegation the directory never asserted): enrolled → always required, whatever the scope says; un-enrolled → required when the knob is on **and** the scope covers the account — **`every_local_account` by default**, i.e. every account despite the value's narrower name, or the Administrator role only under `administrators`. A directory session that was minted without an engine-verified factor stays MFA-pending while the knob is on, whatever the scope (`AuthService._unverified_session_owes_factor`, the one provider-keyed step) | **DENY** 403 + `X-MFA-Required: 1` on **every** authorized route — an **access gate**, not only a step-up gate; the console twin is a 303 to `/ui/mfa`, with the account and factor-enrolment routes exempt so an un-enrolled user is not stranded. An earlier revision of this row said Administrator-only and step-up-boundary-only; both were wrong | on; scope `every_local_account` | `[security].require_mfa`, `[security].require_mfa_scope` (the `[auth]` spellings are rejected at load) | | Identity provider — local credential rotation | `identity.auth_provider` | the provider is AD (the credential is the directory's, not the engine's) | **DENY** `POST /me/password` with **400**. Whether the step-up goes to the IdP depends on how the **session** was minted (see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753)): an `oidc` session steps up at the IdP and is never asked for a password. Otherwise this attribute picks the leg: for an AD identity, a **live directory re-bind** instead of a local hash compare. Both legs refuse a disabled AD account, because the directory lookup each one runs finds no enabled entry. So a disabled AD account cannot refresh its window **by a step-up**. Nor can it with an engine TOTP or recovery code once the directory reports it disabled: `verify_mfa` asks the directory first, by the row's directory id, and refuses an account the directory does not confirm (BACKLOG #2023) or a row with no directory id (BACKLOG #2027). Its passkey cannot clear the MFA gate either, because the passkey leg asks the same (BACKLOG #2239); see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753). The provider does **not** exempt the identity from the engine MFA gate (see the MFA state row): a directory session minted without an engine-verified factor (every Kerberos session, and an OIDC one while `oidc_require_mfa_claim` is off) is refused while `[security].require_mfa` is on, whatever the scope, and with it off is refused only once the account has enrolled a factor. The gate does not fire once the session is MFA-verified: at mint, for an OIDC sign-in whose signed `amr`/`acr` passed the claim gate, or later, once the holder proves the engine factor | n/a | `[auth].ad_enabled` | | Authentication ambience | how the session was minted | every directory sign-in -- Kerberos by `GET /ui/sso` or `POST /auth/negotiate`, and the OIDC callback -- mints with `seed_reauth=False`, decided inside `_complete_ad_login` rather than by the caller (BACKLOG #1144 step 5) | **CHALLENGE** — the session is born **without** step-up freshness, so a sensitive action forces an explicit credential step-up. A Kerberos session skips it when its holder has already proved a TOTP or recovery code at the MFA gate, which stamps a window, or a user-verified passkey, which does too (see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753)). An OIDC session never does: a code meets its pending factor but opens no window, so its step-up is always the IdP leg (BACKLOG #2142, ADR 0142 Amendment F, a seat decision under owner delegation 2026-10-08, not an owner ruling) (the *second* signal in this table whose action is a challenge rather than a hard decision) | n/a | (by design) | @@ -6443,17 +6445,21 @@ Users and admins can see and revoke individual sessions (ASVS 7.5.2 / 7.4.5): - **`DELETE /users/{id}/sessions`** (`users:manage`) — admin force-sign-out of a user (offboarding / suspected compromise). -The two self-service terminates are **re-proof-only** step-ups deliberately, with no second-factor -gate: such a gate would deadlock an MFA-required-but-unenrolled operator out of revoking their own -sessions. The re-proof is the session's own step-up leg: the password or directory re-bind, or for +The two self-service terminates are **re-proof-only** step-ups, with no second-factor gate in front +of the re-proof. Neither is open to an MFA-pending session (below), so an operator with no factor +under `[security].require_mfa` enrols first, and the enrolment that binds the factor satisfies the +session. The re-proof is the session's own step-up leg: the password or directory re-bind, or for an `oidc` session the IdP leg, which the console twins (`POST /ui/account/sessions/{session_id}/revoke` and `POST /ui/account/sessions/revoke-others`) reach through `/ui/reauth`. The JSON routes have no federated leg, so while `[auth].require_action_step_up` is on (the default) a bearer client holding -an `oidc` session cannot pass them. The no-gate -carve-out serves only an account with **no** factor. A pending session on an account that has one +an `oidc` session cannot pass them. A pending session on an account that has a factor must prove it first, at `POST /auth/mfa-verify`, `POST /ui/mfa` or the code/passkey leg of `/ui/reauth` (an `oidc` session's `/ui/reauth` sends it to `/ui/mfa`). Until it does, no step-up mints a `session_terminate` grant for it, and both terminate routes refuse -it with `X-MFA-Required` (ASVS 6.3.3, BACKLOG #1951). +it with `X-MFA-Required` (ASVS 6.3.3, BACKLOG #1951). A pending session on an account with **no** +factor, which `[security].require_mfa` covers, is refused the same way (BACKLOG #1149, ASVS 7.5.2): +no step-up mints it a `session_terminate`, `save_ends_own_sessions` or `revoke_all_sessions` grant, +the JSON terminate routes answer `403` + `X-MFA-Required` with a detail that names enrolment, and +the console twins send it to `/ui/account?m=enroll_first`. It may still reach enrolment and sign-out. Changing the password also ends every session, and it follows the same rule (BACKLOG #1954). A pending session on an account with a factor gets `403` + `X-MFA-Required` from `POST /me/password`, diff --git a/messagefoundry/api/_ui_seam.py b/messagefoundry/api/_ui_seam.py index b06ae3de4a..732954e204 100644 --- a/messagefoundry/api/_ui_seam.py +++ b/messagefoundry/api/_ui_seam.py @@ -967,12 +967,17 @@ #: ``0cb66e183386b7c8`` to ``10cd6745cb708c1a``, and over the merge with BACKLOG #5646 above, from #: ``7c3240bbbaf0605a`` to ``a888b8fed812bbe6``. #: +#: BACKLOG #1149: the console's reauth-only action gate sends a pending session with no factor to +#: enrolment when a session-ending action refuses it. The snapshot hashes that gate's body, so the +#: digest moved. No engine surface changed. Re-derived with ``--write``, from +#: ``a888b8fed812bbe6`` to ``28c252796d4fd6c4``. +#: #: The digest below covers the surface DISCOVERED from the console's own imports and uses, which is #: strictly larger than the five hand-maintained tuples it replaced -- those had drifted, and the #: proof is that commit 40a4d5d9 added a REQUIRED ``UploadedFileList.scope`` field the console renders #: unconditionally while touching no seam file at all. Regenerate with #: ``python scripts/webconsole_seam_snapshot.py --write``; never hand-edit it to silence a gate. -ENGINE_UI_SEAM: str = "a888b8fed812bbe6" +ENGINE_UI_SEAM: str = "28c252796d4fd6c4" @dataclass(frozen=True, slots=True) diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 45d12d14d6..a5899fcffd 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -49,7 +49,7 @@ from messagefoundry.audit_write import AUDIT_WRITE_DEFECTS from messagefoundry.auth import AuthProvider, Identity, Permission, Role from messagefoundry.auth.notifications import deadline_utc as deadline_utc # re-export -from messagefoundry.auth.service import AuthService, LoginOutcome +from messagefoundry.auth.service import STEP_UP_ACTION_MFA_ENROLL, AuthService, LoginOutcome from messagefoundry.config.tls_policy import HopDisposition from messagefoundry.controlchars import scrub_log_argument @@ -185,12 +185,13 @@ def alert_directory_administrator_granted(state: Any, outcome: LoginOutcome, *, # Deliberately NOT exempt: GET /me/sessions and GET /me/security-events. A pending session has proven # ONE factor, which is exactly the attacker-holds-the-password case; handing it the victim's session # inventory and client-IP history is reconnaissance. ASVS 7.5.2 self-service is a POST-authentication -# clause, and neither route is on any deadlock-escape path (revocation still works: POST /me/reauth -# then DELETE /me/sessions, both reachable). +# clause, and neither route is on any deadlock-escape path. # -# That revocation path serves an account with NO factor, which has nothing to prove at -# /auth/mfa-verify. An account that HAS one proves it first before that path works (BACKLOG #1951; -# see AuthService._PENDING_REFUSED_ACTIONS). /me/password is limited the same way (#1954). +# Ending sessions is not open to a pending session either. An account that HAS a factor proves it +# first (BACKLOG #1951); one with NO factor that require_mfa covers enrols first, and the confirm +# that binds the factor satisfies the session (BACKLOG #1149). The terminate routes ride +# require_reauth_only_action, so AuthService._PENDING_REFUSED_ACTIONS is what refuses them. +# /me/password is limited for an account that has a factor (#1954). _MFA_EXEMPT_ROUTES: frozenset[tuple[str, str]] = frozenset( { ("POST", "/auth/logout"), @@ -1612,15 +1613,40 @@ async def _mfa_refusal(request: Request, auth: AuthService, identity: Identity) Writes its ``auth.mfa_denied`` row first, whichever gate refuses (BACKLOG #1197). It is a plain :class:`HTTPException`, not a :class:`_GateRefusal`, so :func:`_recorded_decision` writes - no second row for it.""" + no second row for it. + + A pending session on an account that holds NO factor (``require_mfa`` covers it) has nothing to + prove at ``/auth/mfa-verify``, so its detail names enrolment instead (BACKLOG #1149). The + detail keeps the same leading text and the header stays, so a client that matches either + still reads an MFA refusal.""" await auth.audit_mfa_denied(identity, request.url.path, client=client_ip(request)) return HTTPException( status.HTTP_403_FORBIDDEN, - "multi-factor verification required; POST /auth/mfa-verify then retry", + _MFA_ENROL_FIRST_DETAIL + if await _pending_holds_no_factor(auth, bearer_token(request)) + else "multi-factor verification required; POST /auth/mfa-verify then retry", headers={"X-MFA-Required": "1"}, ) +#: The 403 detail for a pending session whose account holds no factor (BACKLOG #1149). +_MFA_ENROL_FIRST_DETAIL = ( + "multi-factor verification required; no second factor is enrolled, so enrol one first" + " (POST /me/reauth with purpose mfa_enroll, POST /me/mfa/enroll, POST /me/mfa/confirm)," + " then retry" +) + + +async def _pending_holds_no_factor(auth: AuthService, token: str | None) -> bool: + """Whether a session already known to be MFA-pending is on an account with no factor. + + Asks the ``mfa_enroll`` factor-binding refusal, which is True for a pending session exactly + when its account holds a factor, and fails closed (True) on a session or account it cannot + find. So a False here means a found, pending session with no factor; the unknown case keeps + the verify wording. No new service member, so the console's seam does not move.""" + return not await auth.factor_binding_is_blocked(token, STEP_UP_ACTION_MFA_ENROLL) + + async def refuse_from_new_address(request: Request) -> None: """Refuse a request whose session was last verified from another host (vault BACKLOG #2620). @@ -2268,7 +2294,9 @@ def require_reauth_only_action( Carries the same ``mfa_gate=False`` opt-out as :func:`require_reauth_only`, for the same reason; the session-terminate routes use it too. A pending session on an account that HAS a factor is - still refused (see ``AuthService._PENDING_REFUSED_ACTIONS``), with ``X-MFA-Required`` and not + still refused (see ``AuthService._PENDING_REFUSED_ACTIONS``), and on the terminate routes so + is one with no factor (BACKLOG #1149), whose detail names enrolment. Both get + ``X-MFA-Required`` and not a step-up header: a password re-proof mints it nothing, so pointing it at ``POST /me/reauth`` would loop a client that already typed the right password (BACKLOG #1951).""" diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 692c4e0fc4..8c8d77193a 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -16465,7 +16465,8 @@ def reauth_detail(*, interrupted: bool = False, clear_id: str | None = None) -> # and notice are written at the clear, above. return elevation - #: The step-up actions a pending session may NOT be granted once its account HAS a factor. Every + #: The step-up actions a pending session may NOT be granted once its account HAS a factor (and, + #: for the session-ending ones below, even when it has none). Every #: one of them rides a ``*_reauth_only_action`` gate (``mfa_gate=False``), which exists so an #: account with no factor is not locked out of it. For an account that already has one: #: @@ -16489,6 +16490,12 @@ def reauth_detail(*, interrupted: bool = False, clear_id: str | None = None) -> #: password re-proof from an MFA-pending session does not count as authenticating again, so #: ``POST /me/reauth`` and ``/ui/reauth`` mint that session no grant for it. #: ``revoke_all_sessions`` (BACKLOG #2614) is listed for the same reason. + #: + #: The three session-ending actions in :data:`_PENDING_SESSION_ENDING_ACTIONS` are refused to + #: EVERY pending session, the account's factors aside (BACKLOG #1149, ASVS 7.5.2). Under + #: ``require_mfa`` a session on an account with no factor is MFA-pending, so it is confined like + #: any other pending session: it enrols first, and the confirm that binds its first factor + #: satisfies the session. Only the enrolment actions keep the first-enrolment carve-out. _PENDING_REFUSED_ACTIONS = frozenset( { STEP_UP_ACTION_MFA_ENROLL, @@ -16500,6 +16507,16 @@ def reauth_detail(*, interrupted: bool = False, clear_id: str | None = None) -> } ) + #: The actions of :data:`_PENDING_REFUSED_ACTIONS` that end sessions. Refused to a pending + #: session whether or not its account holds a factor (BACKLOG #1149). + _PENDING_SESSION_ENDING_ACTIONS = frozenset( + { + STEP_UP_ACTION_SESSION_TERMINATE, + STEP_UP_ACTION_SAVE_ENDS_OWN_SESSIONS, + STEP_UP_ACTION_REVOKE_ALL_SESSIONS, + } + ) + async def _factor_binding_is_blocked(self, token: str | None, purpose: str) -> bool: """Whether a step-up grant for ``purpose`` must be REFUSED for this session (ASVS 6.3.3). @@ -16515,34 +16532,47 @@ async def _factor_binding_is_blocked(self, token: str | None, purpose: str) -> b So: if the session has not satisfied its second factor and the account already has one, the existing factor must be proven first (``POST /auth/mfa-verify``). First enrolment is - untouched: an account with NO factor still enrols, and ends sessions, from a password-only - session, which is exactly the deadlock carve-out. Disable/delete actions are NOT listed: - they run behind ``require_step_up_action``, which keeps its own ``mfa_satisfied`` check. + untouched: an account with NO factor still enrols from a password-only session, which is + exactly the deadlock carve-out. It no longer ends sessions from one: the session-ending + actions are refused to every pending session (BACKLOG #1149), so such an account enrols + first, and the enrolment that binds its first factor satisfies the session. Disable/delete + actions are NOT listed: they run behind ``require_step_up_action``, which keeps its own + ``mfa_satisfied`` check. """ if purpose not in self._PENDING_REFUSED_ACTIONS: return False - return await self._owes_enrolled_factor(token) + return await self._owes_enrolled_factor( + token, any_pending=purpose in self._PENDING_SESSION_ENDING_ACTIONS + ) async def _factor_binding_is_blocked_hash(self, token_hash: str, purpose: str) -> bool: """:meth:`_factor_binding_is_blocked` keyed on the session's hash (see :meth:`_elevated_hash`).""" if purpose not in self._PENDING_REFUSED_ACTIONS: return False - return await self._owes_enrolled_factor_hash(token_hash) + return await self._owes_enrolled_factor_hash( + token_hash, any_pending=purpose in self._PENDING_SESSION_ENDING_ACTIONS + ) - async def _owes_enrolled_factor(self, token: str | None, *, local_only: bool = False) -> bool: + async def _owes_enrolled_factor( + self, token: str | None, *, local_only: bool = False, any_pending: bool = False + ) -> bool: """Whether the session is MFA-pending on an account that already HAS a second factor. Fails closed (True) when the session or its user cannot be found. ``local_only`` answers False for a directory account, whose password the engine does not hold. It names AD rather than excluding everything that is not LOCAL: ``_build_identity`` maps an unrecognized - provider back to LOCAL, so the password handler treats that row as local and changes it.""" + provider back to LOCAL, so the password handler treats that row as local and changes it. + ``any_pending`` drops the "HAS a factor" half: True for every pending session, including + one on an account with no factor that ``require_mfa`` covers (BACKLOG #1149).""" if not token: return True # no session to act on, so fail closed (as below) - return await self._owes_enrolled_factor_hash(hash_token(token), local_only=local_only) + return await self._owes_enrolled_factor_hash( + hash_token(token), local_only=local_only, any_pending=any_pending + ) async def _owes_enrolled_factor_hash( - self, token_hash: str, *, local_only: bool = False + self, token_hash: str, *, local_only: bool = False, any_pending: bool = False ) -> bool: """:meth:`_owes_enrolled_factor` keyed on the session's hash (see :meth:`_elevated_hash`).""" session = await self._load_session(token_hash) @@ -16551,7 +16581,7 @@ async def _owes_enrolled_factor_hash( satisfied, user = await self._session_satisfaction(session) if satisfied: return False - if user is None: + if user is None or any_pending: return True if local_only and user.auth_provider == AuthProvider.AD.value: return False diff --git a/messagefoundry_webconsole/__init__.py b/messagefoundry_webconsole/__init__.py index 8b9d18a845..9979d6b1b2 100644 --- a/messagefoundry_webconsole/__init__.py +++ b/messagefoundry_webconsole/__init__.py @@ -44,7 +44,7 @@ # If cross-seam support is ever genuinely wanted, re-widen this set AND add the CI matrix that # installs the MIN and MAX supported engine builds — the claim and its test land together, or not # at all. -SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"a888b8fed812bbe6"}) +SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"28c252796d4fd6c4"}) #: The vendored static assets shipped in THIS wheel (mounted at /ui/static by :func:`mount_ui`). STATIC_DIR = Path(__file__).parent / "static" diff --git a/messagefoundry_webconsole/_auth.py b/messagefoundry_webconsole/_auth.py index b53a5b52f8..1274612005 100644 --- a/messagefoundry_webconsole/_auth.py +++ b/messagefoundry_webconsole/_auth.py @@ -34,7 +34,7 @@ record_ws_gate, ) from messagefoundry.auth import Identity, Permission -from messagefoundry.auth.service import AuthService +from messagefoundry.auth.service import STEP_UP_ACTION_MFA_ENROLL, AuthService from messagefoundry.auth.tokens import hash_token from messagefoundry.auth.webauthn import configured_rp_id @@ -2182,6 +2182,12 @@ async def refuse_pending( # The JSON twin's rule: a refused request still records the new-IP signal. Only on this # branch, because a request let through records it once, later in the base. await auth.flag_new_client_ip(token, client_ip(request), path=request.url.path) + # BACKLOG #1149: a session-ending action is refused to a pending session on an account with + # NO factor too. It has nothing to give /ui/reauth, which would mint it nothing, so it is + # sent to enrol. The mfa_enroll refusal is True exactly when the account holds a factor (and + # on an unknown session), the JSON plane's _pending_holds_no_factor reading. + if not await auth.factor_binding_is_blocked(token, STEP_UP_ACTION_MFA_ENROLL): + return HTTPException(status.HTTP_303_SEE_OTHER, headers={"Location": ENROL_FIRST_PAGE}) return _reauth_redirect(request, continuation(request)) # allow_mfa_pending: a genuine exemption, not a re-route. It serves an account with NO factor, diff --git a/packaging/messagefoundry-webconsole/tests/test_ui_mfa_gate.py b/packaging/messagefoundry-webconsole/tests/test_ui_mfa_gate.py index 657b31c712..d34d272715 100644 --- a/packaging/messagefoundry-webconsole/tests/test_ui_mfa_gate.py +++ b/packaging/messagefoundry-webconsole/tests/test_ui_mfa_gate.py @@ -697,15 +697,68 @@ async def test_a_session_that_proved_its_code_at_reauth_can_end_sessions( assert await service.identity_for_token(other.token) is None -async def test_an_account_with_no_factor_still_ends_sessions_from_a_pending_session( +@pytest.mark.parametrize("action_step_up", (True, False), ids=("enforced", "opted-out")) +async def test_a_pending_session_with_no_factor_is_sent_to_enrol_not_to_end_sessions( + engine: Engine, monkeypatch: pytest.MonkeyPatch, action_step_up: bool +) -> None: + """RED when: ``session_terminate`` is refused only to a pending session that HAS a factor, or + the console's refusal sends a no-factor session to ``/ui/reauth`` instead of to enrolment. + + BACKLOG #1149 (ASVS 7.5.2). Under ``require_mfa`` a session on an account with no factor is + MFA-pending. It may reach enrolment and sign-out, and nothing that ends sessions: its next step + is to enrol, and the enrolment satisfies it. The step-up state is planted directly, so the + route is refused for being pending, not for want of a proof: ``enforced`` plants the single-use + grant, ``opted-out`` stamps the window, which is that branch's whole gate. + """ + from messagefoundry.auth.service import STEP_UP_ACTION_SESSION_TERMINATE + + service = await _service( + engine, admin_write_min_interval_seconds=0, require_action_step_up=action_step_up + ) + await _add(service, "op", Role.OPERATOR) + other = await service.login("op", PW) + assert other.ok and other.token is not None + + async with _client(engine, service) as c: + assert (await _login(c)).status_code == 303 + tok = c.cookies.get("mf_session") + assert tok is not None and await service.mfa_satisfied(tok) is False + calls = _spy_admin_write(service, monkeypatch) + for path in (f"/ui/account/sessions/{hash_token(other.token)}/revoke", _REVOKE_OTHERS): + if action_step_up: + service._grant_action_step_up(hash_token(tok), STEP_UP_ACTION_SESSION_TERMINATE) + else: + await service.store.mark_session_reauthed(hash_token(tok)) + assert await service.has_recent_step_up(tok) is True # the positive control + r = await c.post(path, headers=SAME_ORIGIN) + assert r.status_code == 303 + assert r.headers["location"] == _ENROL_FIRST, ( + f"{path} from a pending session with no factor was not sent to enrol" + ) + # The page it lands on names enrolment as the next step. + page = await c.get(_ENROL_FIRST) + assert page.status_code == 200 and "enroll an authenticator" in page.text + + assert await service.identity_for_token(other.token) is not None + assert calls == [], f"a refused pending session was charged: {calls}" + # Refused as a pending session, so audited like every other MFA refusal. + denied = [ + a["detail"] or "" + for a in await engine.store.list_audit() + if a["action"] == "auth.mfa_denied" + ] + assert sum("/ui/account/sessions/" in d for d in denied) == 2 + + +async def test_a_no_factor_session_without_require_mfa_still_ends_sessions( engine: Engine, ) -> None: - """RED when: the refusal over-reaches and blocks the un-enrolled case too. + """The control for the test above. RED when: the refusal reaches a session that owes no factor. - A fresh account is pending under the default ``require_mfa`` and has no code to give. The - password-only re-proof is its only way to end a session it does not recognise. + With ``require_mfa`` off an account with no factor is not pending, so the password re-proof at + ``/ui/reauth`` ends its other sessions as it did before BACKLOG #1149. """ - service = await _service(engine, admin_write_min_interval_seconds=0) + service = await _service(engine, admin_write_min_interval_seconds=0, require_mfa=False) await _add(service, "op", Role.OPERATOR) other = await service.login("op", PW) assert other.ok and other.token is not None @@ -713,8 +766,7 @@ async def test_an_account_with_no_factor_still_ends_sessions_from_a_pending_sess async with _client(engine, service) as c: assert (await _login(c)).status_code == 303 tok = c.cookies.get("mf_session") - assert tok is not None and await service.mfa_satisfied(tok) is False - # The click, refused for want of a fresh proof; it issues the continuation (#2764). + assert tok is not None and await service.mfa_satisfied(tok) is True refused = await c.post(_REVOKE_OTHERS, headers=SAME_ORIGIN) assert refused.headers["location"] == f"/ui/reauth?next={_REVOKE_OTHERS}" minted = await c.post( @@ -1252,7 +1304,12 @@ async def counting_form_pairs(request: Request) -> list[tuple[str, str]]: #: The password page is not among them any more: under require_mfa an account with no TOTP is sent #: to enrol before it may rotate (ADR 0197 Amendment A), which #: ``test_a_must_change_account_with_no_factor_enrols_before_it_rotates`` pins. -_NO_FACTOR_PASSING_POSTS = tuple(p for p in _PENDING_REFUSED_POSTS if p.id != "password") +#: The two session-terminate posts are not among them either: under require_mfa a pending session +#: with no factor is sent to enrol before it may end sessions (BACKLOG #1149), which +#: ``test_a_pending_session_with_no_factor_is_sent_to_enrol_not_to_end_sessions`` pins. +_NO_FACTOR_PASSING_POSTS = tuple( + p for p in _PENDING_REFUSED_POSTS if p.id not in ("password", "revoke-one", "revoke-others") +) @pytest.mark.parametrize(("path", "refused_to"), _NO_FACTOR_PASSING_POSTS) @@ -1262,7 +1319,7 @@ async def test_a_pending_session_with_no_factor_is_charged_and_not_refused( """RED when: the early refusal over-reaches to an account with no factor. That account is pending under the default ``require_mfa`` with nothing to prove, and these - routes are how it enrols, rotates and ends sessions. It passes the gate, so it pays the budget + routes are how it enrols. It passes the gate, so it pays the budget like any other write, and it leaves no ``auth.mfa_denied`` row. """ service = await _service(engine) diff --git a/tests/golden/webconsole_seam.snapshot b/tests/golden/webconsole_seam.snapshot index ca37482f26..b00f29278a 100644 --- a/tests/golden/webconsole_seam.snapshot +++ b/tests/golden/webconsole_seam.snapshot @@ -7,7 +7,7 @@ # by hand (BACKLOG #1220) - so a newly rendered DTO is covered with nobody editing a list. ## ENGINE_UI_SEAM -a888b8fed812bbe6 +28c252796d4fd6c4 ## dataclass messagefoundry.api._ui_seam.UiDeps engine_seam @@ -396,14 +396,14 @@ GET /ui/account/password: gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=True; mfa_refusal=None; new_address_check=True; pending_refusal=messagefoundry_webconsole.routes.account:register.._factor_first#ffcbbbf8ddf0(); permissions=[]; phi=False; step_up_new_address=None) GET /ui/account/notify-address: gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=True; allow_must_change=False; mfa_refusal=None; new_address_check=True; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=None) + messagefoundry_webconsole._service:_service#2c4a90234a30() POST /ui/account/notify-address: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=True; allow_must_change=False; mfa_refusal=None; new_address_check=True; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=None) -POST /ui/account/mfa/enroll: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='mfa_enroll'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#cdf81f13a06b(action='mfa_enroll'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) +POST /ui/account/mfa/enroll: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='mfa_enroll'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='mfa_enroll'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) GET /ui/account/mfa/confirm: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only..dependency#96b0e4ba44a5(base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) -POST /ui/account/mfa/verify: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='mfa_confirm'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#cdf81f13a06b(action='mfa_confirm'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())); before_spend=messagefoundry_webconsole.routes.account:_no_code_posted#3c6ad8b48c50(); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())) +POST /ui/account/mfa/verify: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='mfa_confirm'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='mfa_confirm'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())); before_spend=messagefoundry_webconsole.routes.account:_no_code_posted#3c6ad8b48c50(); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())) POST /ui/account/mfa/disable: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_step_up_action..dependency#e542e585d39b(action='mfa_disable'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=messagefoundry_webconsole._auth:_reauth_refusal..refuse#27c64e277eed(continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); new_address_check=False; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None); repeat=None; spend=True) GET /ui/account/sessions: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=True; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=None) -POST /ui/account/sessions/{session_id}/revoke: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='session_terminate'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#cdf81f13a06b(action='session_terminate'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) -POST /ui/account/sessions/revoke-others: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='session_terminate'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#cdf81f13a06b(action='session_terminate'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) -POST /ui/account/webauthn/enroll: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='webauthn_enroll'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#cdf81f13a06b(action='webauthn_enroll'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) +POST /ui/account/sessions/{session_id}/revoke: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='session_terminate'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='session_terminate'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) +POST /ui/account/sessions/revoke-others: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='session_terminate'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='session_terminate'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) +POST /ui/account/webauthn/enroll: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='webauthn_enroll'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='webauthn_enroll'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) POST /ui/account/webauthn/verify: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only..dependency#96b0e4ba44a5(base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#2bdf9126e7dd())); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#2bdf9126e7dd())) POST /ui/account/webauthn/{credential_id_hash}/delete: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_step_up_action..dependency#e542e585d39b(action='webauthn_delete'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=messagefoundry_webconsole._auth:_reauth_refusal..refuse#27c64e277eed(continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); new_address_check=False; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None); repeat=None; spend=True) GET /ui/audit: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=True; pending_refusal=None; permissions=[audit:read]; phi=False; step_up_new_address=None) diff --git a/tests/test_api_auth.py b/tests/test_api_auth.py index 47c30b1707..a2cc383985 100644 --- a/tests/test_api_auth.py +++ b/tests/test_api_auth.py @@ -2493,9 +2493,11 @@ async def test_revoke_other_sessions_requires_reauth_when_stale(engine: Engine) assert (await c.get("/auth/me", headers=_auth(t2))).status_code == 200 # current kept -async def test_revoke_no_mfa_user_gate_is_password_only(engine: Engine) -> None: - # TRAP guard: even a require_mfa session that has NOT enrolled a factor gets a password-only gate - # on terminate (X-Step-Up-Required, never X-MFA-Required) — never deadlocked out of revoking. +async def test_revoke_no_mfa_user_is_sent_to_enrol(engine: Engine) -> None: + # BACKLOG #1149 (ASVS 7.5.2): a require_mfa session that has NOT enrolled a factor is + # MFA-pending, so the terminate routes refuse it with X-MFA-Required and a detail naming + # enrolment, before and after a password re-proof. It is not deadlocked: enrolment stays open, + # and tests/test_mfa_access_gate.py pins that it terminates once enrolled. service = await _service(engine, AuthSettings(require_mfa=True, login_rate_limit_enabled=False)) await _add(service, "u", Role.VIEWER) async with _client(engine, service) as c: @@ -2503,11 +2505,12 @@ async def test_revoke_no_mfa_user_gate_is_password_only(engine: Engine) -> None: await service.store.mark_session_reauthed(hash_token(t), now=0.0) stale = await c.delete("/me/sessions", headers=_auth(t)) assert stale.status_code == 403 - assert stale.headers.get("X-Step-Up-Required") == "1" - assert stale.headers.get("X-MFA-Required") is None # NOT the MFA gate + assert stale.headers.get("X-MFA-Required") == "1" + assert stale.headers.get("X-Step-Up-Required") is None + assert "enrol one first" in stale.json()["detail"] _r, t = await _reauth(c, t, purpose="session_terminate") assert _r.status_code == 200 - assert (await c.delete("/me/sessions", headers=_auth(t))).status_code == 200 + assert (await c.delete("/me/sessions", headers=_auth(t))).status_code == 403 async def test_revoke_ownership_404_survives_reauth(engine: Engine) -> None: diff --git a/tests/test_derived_gate_decision_audit.py b/tests/test_derived_gate_decision_audit.py index e99abd1580..8e22879c16 100644 --- a/tests/test_derived_gate_decision_audit.py +++ b/tests/test_derived_gate_decision_audit.py @@ -366,6 +366,10 @@ async def audit_mfa_denied(self, *_: object, **__: object) -> None: async def audit_gate_refused(self, *_: object, **__: object) -> None: self.calls.append(_REFUSED) + async def factor_binding_is_blocked(self, *_: object, **__: object) -> bool: + # _mfa_refusal asks it to word its detail (BACKLOG #1149); it writes no row. + return True + def _post_request() -> Request: app = FastAPI() diff --git a/tests/test_mfa_access_gate.py b/tests/test_mfa_access_gate.py index e6560d4255..c8cce09116 100644 --- a/tests/test_mfa_access_gate.py +++ b/tests/test_mfa_access_gate.py @@ -583,24 +583,179 @@ async def test_a_session_that_proved_its_second_factor_can_end_sessions( assert await service.identity_for_token(tok) is not None -async def test_an_account_with_no_factor_still_ends_sessions_from_a_pending_session( +_ENROL_NAMED = "enrol one first" + + +@pytest.mark.parametrize("action_step_up", (True, False), ids=("enforced", "opted-out")) +async def test_a_pending_session_with_no_factor_cannot_end_sessions( + engine: Engine, action_step_up: bool +) -> None: + """RED when: ``session_terminate`` is refused only to a pending session that HAS a factor. + + BACKLOG #1149 (ASVS 7.5.2). Under the default ``require_mfa`` a session on an account with no + factor is MFA-pending. It may reach enrolment and sign-out, and is refused elsewhere, the + terminate routes included, with a refusal that names enrolment. Before this the password + re-proof below minted it a ``session_terminate`` grant and the terminate ran. + + The ``opted-out`` arm is the one the route-side refusal carries alone: there a re-auth refreshes + the session window, which is the whole gate. The ``enforced`` arm also pins the mint-side + refusal: the re-auth leaves no grant behind for a later request to spend. + """ + service = await _service( + engine, + AuthSettings( + login_rate_limit_enabled=False, + mfa_verify_min_elapsed_seconds=0, + require_action_step_up=action_step_up, + ), + ) + await _add(service, "fresh", Role.VIEWER) + other = await service.login("fresh", PW) + assert other.ok and other.token is not None + + async with _client(engine, service) as c: + tok = await _login(c, "fresh") + assert await service.mfa_satisfied(tok) is False # pending, with nothing to prove + + for path in (f"/me/sessions/{hash_token(other.token)}", "/me/sessions"): + tok = await _reauth_to_terminate(c, tok) + assert await service.has_recent_step_up(tok) is True # the positive control + ended = await c.delete(path, headers=_auth(tok)) + assert ended.status_code == 403, ( + f"DELETE {path} from an MFA-pending session with no factor succeeded" + ) + assert ended.headers.get("X-MFA-Required") == "1" + assert "X-Step-Up-Required" not in ended.headers + assert _ENROL_NAMED in ended.json()["detail"], ended.json() + if action_step_up: + assert ( + await service.has_action_step_up(tok, STEP_UP_ACTION_SESSION_TERMINATE) is False + ), "the re-auth minted a session_terminate grant for a pending session" + + assert await service.identity_for_token(other.token) is not None + + audit = await engine.store.list_audit() + reauths = [json.loads(a["detail"]) for a in audit if a["action"] == "auth.reauth"] + assert [r["grant_refused"] for r in reauths] == [True, True] + denied = [a["detail"] or "" for a in audit if a["action"] == "auth.mfa_denied"] + assert any("/me/sessions" in d for d in denied) + + +@pytest.mark.parametrize("purpose", ("save_ends_own_sessions", "revoke_all_sessions")) +async def test_a_pending_session_with_no_factor_is_minted_no_session_ending_grant( + engine: Engine, purpose: str +) -> None: + """RED when: a password re-proof from a pending session with no factor mints a grant for an + action that ends sessions. + + BACKLOG #1149, the vault's residual (g): such a session minted a ``save_ends_own_sessions`` + grant, carried it through its first enrolment, which satisfies the session, and spent it on a + save that ended its own sessions. The grant must not exist to carry. + """ + service = await _service(engine) + await _add(service, "fresh", Role.VIEWER) + + async with _client(engine, service) as c: + tok = await _login(c, "fresh") + r = await c.post( + "/me/reauth", json={"password": PW, "purpose": purpose}, headers=_auth(tok) + ) + assert r.status_code == 200 # a genuine password proof, re-keyed either way + tok = str(r.json()["token"]) + assert await service.has_recent_step_up(tok) is True # the positive control + assert await service.holds_action_step_up(tok, purpose) is False + + +async def test_a_no_factor_session_ends_sessions_once_it_has_enrolled( + engine: Engine, monkeypatch: pytest.MonkeyPatch +) -> None: + """RED when: the refusal outlives enrolment. The way out the refusal names must work. + + Enrolment is reachable from the pending session, the confirm that binds the first factor + satisfies the session, and the terminate then runs on a fresh password proof. + """ + service = await _service(engine) + await _add(service, "fresh", Role.VIEWER) + other = await service.login("fresh", PW) + assert other.ok and other.token is not None + t0 = 1_000_000.0 + pin_totp_clock(monkeypatch, t0) + + async with _client(engine, service) as c: + tok = await _login(c, "fresh") + r = await c.post( + "/me/reauth", json={"password": PW, "purpose": "mfa_enroll"}, headers=_auth(tok) + ) + assert r.status_code == 200 + tok = str(r.json()["token"]) + enrolled = await c.post("/me/mfa/enroll", headers=_auth(tok)) + assert enrolled.status_code == 200, enrolled.text + secret = str(enrolled.json()["secret"]) + r = await c.post( + "/me/reauth", json={"password": PW, "purpose": "mfa_confirm"}, headers=_auth(tok) + ) + assert r.status_code == 200 + tok = str(r.json()["token"]) + confirmed = await c.post( + "/me/mfa/confirm", json={"code": totp.totp(secret, now=t0)}, headers=_auth(tok) + ) + assert confirmed.status_code == 200, confirmed.text + tok = str(confirmed.json()["token"]) + assert await service.mfa_satisfied(tok) is True + + tok = await _reauth_to_terminate(c, tok) + r = await c.delete("/me/sessions", headers=_auth(tok)) + assert r.status_code == 200, r.text + assert await service.identity_for_token(other.token) is None + + +async def test_the_access_gate_names_enrolment_to_a_pending_session_with_no_factor( engine: Engine, ) -> None: - """RED when: the refusal over-reaches and blocks the un-enrolled case too. + """RED when: the 6.3.3 refusal tells a session with no factor to verify one. - This is the path the comment on ``_MFA_EXEMPT_ROUTES`` keeps on purpose. An account with no - factor is pending under the default ``require_mfa``, and it has nothing to prove at - ``/auth/mfa-verify``. A password re-proof is the only way it can end a session it does not - recognise. Pinned beside the refusal so a fix for one cannot silently break the other. + It has nothing to give ``/auth/mfa-verify``, so the refusal names enrolment (BACKLOG #1149). + The control: a pending session on an account that HAS a factor keeps the verify wording. """ service = await _service(engine) await _add(service, "fresh", Role.VIEWER) + await _add(service, "vic", Role.VIEWER) + await _add_passkey(service, "vic") + + async with _client(engine, service) as c: + fresh = await c.get("/messages", headers=_auth(await _login(c, "fresh"))) + enrolled = await c.get("/messages", headers=_auth(await _login(c, "vic"))) + for r in (fresh, enrolled): + assert r.status_code == 403 + assert r.headers.get("X-MFA-Required") == "1" + assert r.json()["detail"].startswith("multi-factor verification required") + assert _ENROL_NAMED in fresh.json()["detail"] + assert enrolled.json()["detail"] == ( + "multi-factor verification required; POST /auth/mfa-verify then retry" + ) + + +async def test_a_no_factor_session_without_require_mfa_still_ends_sessions( + engine: Engine, +) -> None: + """The control for the refusals above. RED when: they reach a session that owes no factor. + + With ``require_mfa`` off an account with no factor is not pending, so a password re-proof ends + its other sessions as it did before BACKLOG #1149. + """ + service = await _service( + engine, + AuthSettings( + require_mfa=False, mfa_verify_min_elapsed_seconds=0, login_rate_limit_enabled=False + ), + ) + await _add(service, "fresh", Role.VIEWER) other = await service.login("fresh", PW) assert other.ok and other.token is not None async with _client(engine, service) as c: tok = await _login(c, "fresh") - assert (await c.get("/messages", headers=_auth(tok))).status_code == 403 # pending + assert await service.mfa_satisfied(tok) is True tok = await _reauth_to_terminate(c, tok) r = await c.delete("/me/sessions", headers=_auth(tok)) assert r.status_code == 200 diff --git a/tests/test_session_token_at_elevation_sites.py b/tests/test_session_token_at_elevation_sites.py index 08f074756c..dea59ec26f 100644 --- a/tests/test_session_token_at_elevation_sites.py +++ b/tests/test_session_token_at_elevation_sites.py @@ -36,7 +36,7 @@ from messagefoundry.auth import totp from messagefoundry.auth.identity import Identity -from messagefoundry.auth.service import STEP_UP_ACTION_SESSION_TERMINATE, AuthService +from messagefoundry.auth.service import STEP_UP_ACTION_MFA_ENROLL, AuthService from messagefoundry.config.settings import AuthSettings from messagefoundry.store.store import MessageStore from tests._admin_account import ADMIN_USERNAME, login_admin @@ -243,7 +243,9 @@ async def test_the_step_up_reauth_elevates_the_token_in_place() -> None: The account holds NO factor on purpose. ``_factor_binding_is_blocked`` would correctly refuse this purpose (and every factor-binding one) to a pending session whose account already has a - factor (BACKLOG #1951), and that refusal would hide the grant this asserts. + factor (BACKLOG #1951), and that refusal would hide the grant this asserts. The purpose is + ``mfa_enroll`` rather than ``session_terminate`` because a session-ending grant is refused to + every pending session, this one included (BACKLOG #1149). """ store, service = await _service() try: @@ -260,7 +262,7 @@ async def test_the_step_up_reauth_elevates_the_token_in_place() -> None: password, token=token, client="10.0.0.7", - purpose=STEP_UP_ACTION_SESSION_TERMINATE, + purpose=STEP_UP_ACTION_MFA_ENROLL, ) assert elevation.ok is True fresh = elevation.token @@ -274,10 +276,10 @@ async def test_the_step_up_reauth_elevates_the_token_in_place() -> None: "stamp landed before the rotation, since it is rowcount-blind" ) # has_action_step_up is single-use, so this both proves the key and spends the grant. - assert await service.has_action_step_up(fresh, STEP_UP_ACTION_SESSION_TERMINATE) is True, ( + assert await service.has_action_step_up(fresh, STEP_UP_ACTION_MFA_ENROLL) is True, ( "...and the action-bound grant was re-keyed onto the new token, not stranded on the old" ) - assert await service.has_action_step_up(token, STEP_UP_ACTION_SESSION_TERMINATE) is False, ( + assert await service.has_action_step_up(token, STEP_UP_ACTION_MFA_ENROLL) is False, ( "...and is NOT reachable on the retired one" ) finally: From 34cf98f0af7a1355730d45f3c9b06767922d922b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:19:17 -0600 Subject: [PATCH 2/5] Auth: review round 1 for the no-factor pending refusal - The JSON refusal's wording read keeps the 403 on a store fault (verify wording), as _step_up_refusal's does; a test pins it. - The enrol-first detail says each enrolment step has its own step-up. - _PENDING_REFUSED_ACTIONS is built from _PENDING_SESSION_ENDING_ACTIONS. - Stale comments beside the terminate gates, on both planes, and the SECURITY.md gate-table and decision-table cells now state the rule. - CONFIGURATION.md links to SECURITY.md rather than restating it. BACKLOG #1149 --- docs/CONFIGURATION.md | 2 +- docs/SECURITY.md | 8 ++-- messagefoundry/api/auth_routes.py | 5 ++- messagefoundry/api/security.py | 27 ++++++++++--- messagefoundry/auth/service.py | 43 +++++++++++---------- messagefoundry_webconsole/_auth.py | 12 +++--- messagefoundry_webconsole/pages/account.py | 6 +-- messagefoundry_webconsole/routes/account.py | 8 ++-- tests/test_mfa_access_gate.py | 22 +++++++++++ 9 files changed, 87 insertions(+), 46 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3e1461ba2a..bc5b3693b8 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3586,7 +3586,7 @@ and a PHI weakening under **strict enforcement** (`enforcement = enforce`, the d | `external_link_interstitial` | bool | `true` | **`[BUILT]` (ASVS 3.7.3):** show the "you are leaving this site" page at all. Setting it `false` means the console navigates off-site with **no notification and no cancel** — that is the control itself, so this is a posture decision rather than a convenience one, and `serve` prints a warning naming it at every start. The federated sign-in leg is affected: with the interstitial on and the IdP outside `organization_domains`, `GET /ui/oidc/start` renders the page and the flow is minted only on confirm (`POST`), which also closes the standing hole where any external page could begin a sign-in by linking to the start leg. Env: `MEFOR_SECURITY_EXTERNAL_LINK_INTERSTITIAL` | | `external_link_allowlist` | list[str] | `[]` | **`[BUILT]` (ASVS 3.7.3) — WARNING: THE AUDITED ESCAPE, AND IT LOWERS SECURITY.** Destinations listed here are navigated to with **no notification and no cancel**, which is precisely what the requirement asks for. It exists for legitimate high-volume external destinations an operator does not want to declare as their own domain. Same entry rule as `organization_domains`, the IPv4 exception included, and the same label-boundary matching. Non-empty makes `serve` print a warning **naming every entry individually** — never a count, because "3 destinations exempted" is the shape of message that lets an entry nobody intended sit in a list for a year. **Prefer `organization_domains`**: declaring a domain you control is a statement about scope; allowlisting one you do not is a waiver. Env: `MEFOR_SECURITY_EXTERNAL_LINK_ALLOWLIST` | | `require_sign_in` | | | **→ REMOVED** (vault BACKLOG #2719). Sign-in is always required, on every bind. Setting this key is refused at load, from the file or as `MEFOR_SECURITY_REQUIRE_SIGN_IN`, whatever its value. The loopback mode it used to allow named no person in the audit trail and could not repair an account. If every Administrator signs in through an outside service, keep a local Administrator ([SECURITY.md](SECURITY.md#keep-a-local-administrator)). | -| `require_mfa` | bool | `true` | second factor (native TOTP or a WebAuthn passkey), enforced as an **access gate** since ASVS 6.3.3 — an MFA-pending session is refused on *every* authorized route with `403` + `X-MFA-Required: 1`, and a browser session is redirected to `/ui/mfa`. **The enrolment path is a deliberate exemption, not a re-route:** `/ui/mfa` itself and the account/enrolment routes (`GET /ui/account`, the password and factor-enrolment routes) are declared `allow_mfa_pending=True` ([`messagefoundry_webconsole/_auth.py`](../messagefoundry_webconsole/_auth.py), `routes/account.py`), so a user with **no** factor enrolled is not stranded — send them to **`/ui/account`** to enrol. Such a user is MFA-pending too, so it cannot end sessions before it enrols: the terminate routes (`DELETE /me/sessions` and `DELETE /me/sessions/{session_id}`, and the console's twins) refuse it, the JSON refusal's detail naming enrolment and the console redirecting to `/ui/account?m=enroll_first`, and the enrolment that binds its first factor satisfies the session (BACKLOG #1149). The access gate's own `403` names enrolment to such a session too. A local account that `require_mfa` and `require_mfa_scope` cover enrols **TOTP or a discoverable passkey first**, a factor with a way past the sign-in lock (ADR 0197 Amendment A, wave 2). Until it holds one, `POST /me/password` refuses with `enrol an authenticator app first` (403; a pending session that holds a passkey gets `X-MFA-Required` first), the console's password page redirects to `/ui/account?m=enroll_first`, and a passkey registration whose client reports it is not discoverable is refused. A directory account may enrol TOTP or a passkey. Say "redirected to", not "confined to": `/ui/mfa` renders a code field only once TOTP is enrolled and a passkey button only once WebAuthn is, so a zero-factor user who is told they cannot leave that page is looking at a page with no form. | +| `require_mfa` | bool | `true` | second factor (native TOTP or a WebAuthn passkey), enforced as an **access gate** since ASVS 6.3.3 — an MFA-pending session is refused on *every* authorized route with `403` + `X-MFA-Required: 1`, and a browser session is redirected to `/ui/mfa`. **The enrolment path is a deliberate exemption, not a re-route:** `/ui/mfa` itself and the account/enrolment routes (`GET /ui/account`, the password and factor-enrolment routes) are declared `allow_mfa_pending=True` ([`messagefoundry_webconsole/_auth.py`](../messagefoundry_webconsole/_auth.py), `routes/account.py`), so a user with **no** factor enrolled is not stranded — send them to **`/ui/account`** to enrol. Such a user is MFA-pending too, so it cannot end sessions before it enrols (BACKLOG #1149); [SECURITY.md](SECURITY.md), under the self-service session routes, says what it is told. A local account that `require_mfa` and `require_mfa_scope` cover enrols **TOTP or a discoverable passkey first**, a factor with a way past the sign-in lock (ADR 0197 Amendment A, wave 2). Until it holds one, `POST /me/password` refuses with `enrol an authenticator app first` (403; a pending session that holds a passkey gets `X-MFA-Required` first), the console's password page redirects to `/ui/account?m=enroll_first`, and a passkey registration whose client reports it is not discoverable is refused. A directory account may enrol TOTP or a passkey. Say "redirected to", not "confined to": `/ui/mfa` renders a code field only once TOTP is enrolled and a passkey button only once WebAuthn is, so a zero-factor user who is told they cannot leave that page is looking at a page with no form. | | `require_mfa_scope` | `"administrators"` \| `"every_local_account"` | `"every_local_account"` | **Which accounts must ENROL a factor** when `require_mfa` is on (ASVS 6.3.3). An account that has already enrolled one must satisfy it while it keeps one, under either value (an OIDC sign-in meets it while `[auth].oidc_require_mfa_claim` is on, the default) — this dial only decides who is required to enrol in the first place. `administrators` restores the pre-6.3.3 posture and is reported as a **loosening** on `GET /security/posture` (advisory, not a refusal: refusing to boot on it would break every existing deployment on upgrade). **The `every_local_account` value is wider than its name** (BACKLOG #1144): directory (AD/Kerberos) identities used to be out of scope under either value, and they are not any more — the directory legs assert no strength the engine can read, so a Kerberos session mints MFA-pending and its holder enrols an engine factor. The value's spelling is stale; renaming a `Literal` reaches the settings model, this table and the tests that pin both, which is its own coherent change rather than a rider on a security fix. **Operator note:** under the default a non-interactive **bearer-token service account** becomes MFA-pending and cannot enrol unattended. Two settings answer it, each with a limit. **Set this to `administrators`**, which frees only a **local** account that does not hold the Administrator role: the Administrator role stays in scope under either value, and a directory session that proved no factor stays MFA-pending under both. Or **set `require_mfa = false`**, which frees any account that has not enrolled a factor, whatever its role; on an exposed instance under `enforcement = enforce`, `serve` then refuses to start unless `allow_single_factor_admin_when_exposed` is set (see that row). An account that has enrolled a factor still owes it either way while it keeps one, with the same OIDC exception. With `require_mfa` off, or for an account `require_mfa_scope` leaves out (under `administrators`, any account without the Administrator role, directory ones included), the holder may remove its last factor. Under `administrators` with `require_mfa` on, a directory account that does so is still not single-factor: its next Kerberos session stays MFA-pending until it enrols again. Making it an AD principal is **no longer** an escape, and mTLS is not one either: a cert-identity is exempt from the MFA gate but is admitted on exactly one route (`GET /service/identity`), so it cannot carry a working service account (see the [`[api]`](#api) `tls_client_cert_identities` row). Env: `MEFOR_SECURITY_REQUIRE_MFA_SCOPE` | | `sign_out_after_idle_minutes` | int | `30` | session idle timeout; `1` to `525600` (a year), refused at load outside that (BACKLOG #5772) | | `max_session_hours` | int | `12` | session absolute lifetime; `1` to `8760` (a year), refused at load outside that (BACKLOG #5772) | diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 5679585980..07ace476fb 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1453,7 +1453,7 @@ apply. What each **adds** over plain `require()`: | `require_phi_read` | 8 | the ADR 0092 PHI-read hop refusal (`enforce_phi_read_hop`) **before** any identity work, then the **new-client-IP** refusal (403 + `X-Step-Up-Required: 1`, vault BACKLOG #2620), then the per-actor PHI-read budget, 429 + a `Retry-After` naming the actor's wait (the whole window while the global count is spent) | | `require_step_up` | 23 | the same non-GET pacing, then the **MFA gate** (403 + `X-MFA-Required: 1`), the **new-client-IP** signal, and the credential-recency window (403 + `X-Step-Up-Required: 1`) | | `require_step_up_action` | 20 | the same non-GET pacing (BACKLOG #1148), the **MFA gate**, then a **single-use, action-bound** step-up grant, minted on this plane only by `POST /me/reauth` (403 + `X-Step-Up-Action: `; the password leg of `POST /ui/reauth` and the IdP leg mint it for a cookie session). Promoting a route here no longer drops the pacing floor. Since vault BACKLOG #2625 it also gates the injection and bulk-export set (see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753)) | -| `require_reauth_only_action` | 4 | password step-up **without** the MFA gate — deadlock avoidance on the MFA-enrollment lanes, and on session terminate (ASVS 7.5.2), where the grant is action-bound so a login-seeded window does not unlock it. `require_reauth_only` still exists and still backs the `/ui` twin, but BACKLOG #1149 moved the last JSON route off it, so it no longer appears in this walk | +| `require_reauth_only_action` | 4 | password step-up **without** the MFA gate — deadlock avoidance on the MFA-enrollment lanes. Session terminate (ASVS 7.5.2) rides it too, though no pending session passes there (BACKLOG #1149), and its grant is action-bound so a login-seeded window does not unlock it. `require_reauth_only` still exists and still backs the `/ui` twin, but BACKLOG #1149 moved the last JSON route off it, so it no longer appears in this walk | | `require_service_cert` | 1 | cert-only authentication (a bearer token gets 401), and a **PHI fence** that raises at *app construction* if asked to gate `messages:view_summary` / `messages:view_raw` | `optional_identity` (2 routes) never raises, so a tokenless client is answered. @@ -4068,8 +4068,8 @@ The complete set, as enumerated in the [route map](#route--permission-map-engine each charges the per-actor **PHI-read** budget explicitly instead. Ordinary reads — listing users, the AD maps, the audit log, a single message — are **not** step-up -gated. Four routes take the *password-only* variant (`require_reauth_only[_action]`), deliberately -**without** the MFA gate so a required-but-unenrolled user cannot deadlock: `POST /me/mfa/enroll`, +gated. Four routes take the *password-only* variant (`require_reauth_only[_action]`), **without** +the MFA gate, so a required-but-unenrolled user can reach enrolment: `POST /me/mfa/enroll`, `POST /me/mfa/confirm`, `DELETE /me/sessions/{session_id}`, `DELETE /me/sessions`. On the two enrolment routes the skip serves an account with no factor only: a pending session on an account that has one gets `403` + `X-MFA-Required` there (BACKLOG #1951). On the two terminate routes it @@ -5036,7 +5036,7 @@ slack. | First-seen sign-in address — sign-in owes a second factor, or any directory sign-in | as the row above | as the row above | **LOG** — the same audit row and notice. A directory sign-in that owes nothing more also records the address, so the next one from it is not reported again; nothing else changes. **Under the shipped `require_mfa` a Kerberos sign-in always owes a factor**, and so does an OIDC one while `oidc_require_mfa_claim` is off. Such a sign-in records nothing; the factor leg that finishes it records the address instead: a TOTP or recovery code, a passkey, or a factor enrolment, under the conditions in the row above. So on this leg, as on the local one, every sign-in is unjudged (`no_baseline`) until one finishes, and a sign-in abandoned at the factor prompt records nothing. Under the same default no directory step-up records an address (see the row above). Such a session is born without step-up freshness anyway. A later proof stamps the window, for example a TOTP or recovery code, a user-verified passkey, or a step-up. On an OIDC session only the IdP step-up does (BACKLOG #2142). A Kerberos or password session steps up with the account password; an `oidc` session steps up at the IdP. Under the shipped `require_mfa` scope (`every_local_account`) this is the path every password-only local sign-in takes. A combined sign-in (password and a TOTP code or a passkey assertion in one request) owes nothing more, so it takes the row above instead and is seeded from any address. **Never** refuses the login (BACKLOG #288) | on | (no knob) | | Credential recency | age of `session.reauth_at` | `now − reauth_at > step_up_max_age_seconds`, or `reauth_at is None` | **DENY** 403 + `X-Step-Up-Required: 1` (console: 303 → `/ui/reauth`; an `oidc` session's JSON refusal names the IdP leg, see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753)) | 300 s | `[auth].step_up_max_age_seconds` | | Action-bound step-up grant | a single-use grant minted only by a successful step-up, on the **monotonic** clock: `reauth(purpose=…)` for the password or re-bind leg (`POST /me/reauth`, `POST /ui/reauth`), and `complete_oidc_step_up` for an `oidc` session's IdP leg, for the action the operator started from. Never by a sign-in or by `verify_mfa` | no unconsumed grant for this route's action | **DENY** 403 + `X-Step-Up-Required` + `X-Step-Up-Action: `; opting out falls back to the session window — **except on a factor bind or a session terminate**, see the row below | on | `[auth].require_action_step_up` | -| Binding a NEW second factor, ending sessions, or changing the password | the session's MFA state × the account's existing factors | the action binds a factor (`mfa_enroll`, `mfa_confirm`, `webauthn_enroll`), ends sessions (`session_terminate`, BACKLOG #1951) or changes the password (`POST /me/password` and `/ui/account/password`, BACKLOG #1954) **and** the session has not satisfied its second factor **and** the account already holds one of either kind | **DENY** — the existing factor must be proven first (`POST /auth/mfa-verify`, `/ui/mfa`, or the code/passkey leg of `/ui/reauth`); the password routes answer 403 + `X-MFA-Required` (console: 303 → `/ui/mfa`, except a covered local account whose passkeys are not discoverable and which has no TOTP, which the console sends to the enrolment page). The factor-binding and password refusals do not reach an account with **no** factor, which has nothing to prove: it enrols its first factor from a password-only session, which is what the MFA gate's exemptions are for. Ending sessions is different (BACKLOG #1149, ASVS 7.5.2): `session_terminate`, `save_ends_own_sessions` and `revoke_all_sessions` are refused to a pending session on an account with no factor too, which under `[security].require_mfa` is MFA-pending. No step-up mints it those grants, the JSON terminate routes answer 403 + `X-MFA-Required` with a detail naming enrolment, and the console sends it to the enrolment page. The enrolment that binds its first factor satisfies the session, and the terminate then works. Two other rules still bind such an account. Under `[security].require_mfa` a covered local account's first factor must be TOTP or a discoverable passkey: a passkey whose client reports it is not discoverable is refused at the registration finish, and the password change is refused with `enrol an authenticator app first` until such a factor exists (`FactorEnrolmentRequired`, ADR 0197 Amendment A; console: a 303 to the enrolment page). And a must-change session cannot end its sessions at all, because the must-change confinement does not admit those routes. With the requirement off, such an account changes its password as before. The passkey registration **finish** asks the same rule again (`finish_webauthn_registration`, BACKLOG #3014), because its console route rides the action-less gate: a ceremony staged before the account gained a factor is refused with **400** `this account already has a second factor`, its ceremony ended, audited `auth.mfa_denied`. Both enrolment legs, this finish and the TOTP confirm (`confirm_mfa_enrollment`, whose first ask is its route's gate), ask it once more after the login-to-MFA floor and a directory account's directory lookup. A factor bound on another session during either is refused with a 400 `this account already has a second factor`, audited `auth.mfa_denied`. The TOTP confirm refuses this way only for a passkey, before it spends a step or mints a recovery code; a TOTP enabled meanwhile is left to its enable's compare-and-set, which ends the session (BACKLOG #2224). On the passkey finish the insert is conditional too: the store asks the same rule inside the insert's own transaction, so a factor bound on another session after that second ask is refused there, with the same 400 and the same `auth.mfa_denied` row, no passkey stored and the session not stamped (BACKLOG #3690 item 1). The server backends lock the account row for that check, as every factor write there does, and the session row after it. SQLite holds its one writer lock instead, which no other writer in the process passes; a write from another process that commits between the check and the insert fails the finish with an error, storing nothing, rather than the 400. The rule is the same one: a session already stamped MFA-verified, including one a sign-in that owed nothing minted stamped, is not refused. The TOTP confirm is still read-then-act: a factor bound after its second ask, for example while it hashes its recovery codes, is not caught (BACKLOG #3061) | on | **no knob** — `require_action_step_up` does not reach it, deliberately | +| Binding a NEW second factor, ending sessions, or changing the password | the session's MFA state × the account's existing factors | the action binds a factor (`mfa_enroll`, `mfa_confirm`, `webauthn_enroll`), ends sessions (`session_terminate`, BACKLOG #1951) or changes the password (`POST /me/password` and `/ui/account/password`, BACKLOG #1954) **and** the session has not satisfied its second factor **and**, except for the session-ending actions, the account already holds one of either kind. The session-ending actions (`session_terminate`, `save_ends_own_sessions`, `revoke_all_sessions`) are refused to every pending session, including one with no factor under `[security].require_mfa` (BACKLOG #1149) | **DENY** — the existing factor must be proven first (`POST /auth/mfa-verify`, `/ui/mfa`, or the code/passkey leg of `/ui/reauth`); the password routes answer 403 + `X-MFA-Required` (console: 303 → `/ui/mfa`, except a covered local account whose passkeys are not discoverable and which has no TOTP, which the console sends to the enrolment page). The factor-binding and password refusals do not reach an account with **no** factor, which has nothing to prove: it enrols its first factor from a password-only session, which is what the MFA gate's exemptions are for. Ending sessions is different (BACKLOG #1149, ASVS 7.5.2): `session_terminate`, `save_ends_own_sessions` and `revoke_all_sessions` are refused to a pending session on an account with no factor too, which under `[security].require_mfa` is MFA-pending. No step-up mints it those grants, the JSON terminate routes answer 403 + `X-MFA-Required` with a detail naming enrolment, and the console sends it to the enrolment page. The enrolment that binds its first factor satisfies the session, and the terminate then works. Two other rules still bind such an account. Under `[security].require_mfa` a covered local account's first factor must be TOTP or a discoverable passkey: a passkey whose client reports it is not discoverable is refused at the registration finish, and the password change is refused with `enrol an authenticator app first` until such a factor exists (`FactorEnrolmentRequired`, ADR 0197 Amendment A; console: a 303 to the enrolment page). And a must-change session cannot end its sessions at all, because the must-change confinement does not admit those routes. With the requirement off, such an account changes its password as before. The passkey registration **finish** asks the same rule again (`finish_webauthn_registration`, BACKLOG #3014), because its console route rides the action-less gate: a ceremony staged before the account gained a factor is refused with **400** `this account already has a second factor`, its ceremony ended, audited `auth.mfa_denied`. Both enrolment legs, this finish and the TOTP confirm (`confirm_mfa_enrollment`, whose first ask is its route's gate), ask it once more after the login-to-MFA floor and a directory account's directory lookup. A factor bound on another session during either is refused with a 400 `this account already has a second factor`, audited `auth.mfa_denied`. The TOTP confirm refuses this way only for a passkey, before it spends a step or mints a recovery code; a TOTP enabled meanwhile is left to its enable's compare-and-set, which ends the session (BACKLOG #2224). On the passkey finish the insert is conditional too: the store asks the same rule inside the insert's own transaction, so a factor bound on another session after that second ask is refused there, with the same 400 and the same `auth.mfa_denied` row, no passkey stored and the session not stamped (BACKLOG #3690 item 1). The server backends lock the account row for that check, as every factor write there does, and the session row after it. SQLite holds its one writer lock instead, which no other writer in the process passes; a write from another process that commits between the check and the insert fails the finish with an error, storing nothing, rather than the 400. The rule is the same one: a session already stamped MFA-verified, including one a sign-in that owed nothing minted stamped, is not refused. The TOTP confirm is still read-then-act: a factor bound after its second ask, for example while it hashes its recovery codes, is not caught (BACKLOG #3061) | on | **no knob** — `require_action_step_up` does not reach it, deliberately | | MFA state | `session.mfa_verified_at` × factor enrollment × account roles | the rule is **provider-blind** (BACKLOG #1144 — an AD account used to be exempt here, on a delegation the directory never asserted): enrolled → always required, whatever the scope says; un-enrolled → required when the knob is on **and** the scope covers the account — **`every_local_account` by default**, i.e. every account despite the value's narrower name, or the Administrator role only under `administrators`. A directory session that was minted without an engine-verified factor stays MFA-pending while the knob is on, whatever the scope (`AuthService._unverified_session_owes_factor`, the one provider-keyed step) | **DENY** 403 + `X-MFA-Required: 1` on **every** authorized route — an **access gate**, not only a step-up gate; the console twin is a 303 to `/ui/mfa`, with the account and factor-enrolment routes exempt so an un-enrolled user is not stranded. An earlier revision of this row said Administrator-only and step-up-boundary-only; both were wrong | on; scope `every_local_account` | `[security].require_mfa`, `[security].require_mfa_scope` (the `[auth]` spellings are rejected at load) | | Identity provider — local credential rotation | `identity.auth_provider` | the provider is AD (the credential is the directory's, not the engine's) | **DENY** `POST /me/password` with **400**. Whether the step-up goes to the IdP depends on how the **session** was minted (see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753)): an `oidc` session steps up at the IdP and is never asked for a password. Otherwise this attribute picks the leg: for an AD identity, a **live directory re-bind** instead of a local hash compare. Both legs refuse a disabled AD account, because the directory lookup each one runs finds no enabled entry. So a disabled AD account cannot refresh its window **by a step-up**. Nor can it with an engine TOTP or recovery code once the directory reports it disabled: `verify_mfa` asks the directory first, by the row's directory id, and refuses an account the directory does not confirm (BACKLOG #2023) or a row with no directory id (BACKLOG #2027). Its passkey cannot clear the MFA gate either, because the passkey leg asks the same (BACKLOG #2239); see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753). The provider does **not** exempt the identity from the engine MFA gate (see the MFA state row): a directory session minted without an engine-verified factor (every Kerberos session, and an OIDC one while `oidc_require_mfa_claim` is off) is refused while `[security].require_mfa` is on, whatever the scope, and with it off is refused only once the account has enrolled a factor. The gate does not fire once the session is MFA-verified: at mint, for an OIDC sign-in whose signed `amr`/`acr` passed the claim gate, or later, once the holder proves the engine factor | n/a | `[auth].ad_enabled` | | Authentication ambience | how the session was minted | every directory sign-in -- Kerberos by `GET /ui/sso` or `POST /auth/negotiate`, and the OIDC callback -- mints with `seed_reauth=False`, decided inside `_complete_ad_login` rather than by the caller (BACKLOG #1144 step 5) | **CHALLENGE** — the session is born **without** step-up freshness, so a sensitive action forces an explicit credential step-up. A Kerberos session skips it when its holder has already proved a TOTP or recovery code at the MFA gate, which stamps a window, or a user-verified passkey, which does too (see [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753)). An OIDC session never does: a code meets its pending factor but opens no window, so its step-up is always the IdP leg (BACKLOG #2142, ADR 0142 Amendment F, a seat decision under owner delegation 2026-10-08, not an owner ruling) (the *second* signal in this table whose action is a challenge rather than a hard decision) | n/a | (by design) | diff --git a/messagefoundry/api/auth_routes.py b/messagefoundry/api/auth_routes.py index eaf29244b2..f8dea36d2f 100644 --- a/messagefoundry/api/auth_routes.py +++ b/messagefoundry/api/auth_routes.py @@ -1279,8 +1279,9 @@ async def revoke_my_session( service: AuthService = Depends(_service), # 7.5.2 (ASVS): terminating a session needs a fresh PASSWORD re-proof BOUND TO THIS ACTION # (BACKLOG #1149) — single-use, so the login-seeded window no longer satisfies it. Still the - # reauth-only family and NOT the MFA gate: a no-factor user must remain able to revoke; a - # pending session on an account WITH a factor is refused (#1951). The gate runs before the + # reauth-only family and NOT the MFA gate, but no pending session passes it: one on an + # account WITH a factor is refused (#1951), and so is one with NO factor that require_mfa + # covers, which is told to enrol (#1149). The gate runs before the # body and 403s identically for owned AND foreign ids, so it leaks no ownership. identity: Identity = Depends(require_reauth_only_action(STEP_UP_ACTION_SESSION_TERMINATE)), ) -> SimpleMessage: diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index a5899fcffd..b8d3b993b4 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -209,8 +209,9 @@ def alert_directory_administrator_granted(state: Any, outcome: LoginOutcome, *, # out of the two gates that run first, so neither can deadlock behind this one. # # THE ``mfa_gate=False`` ROUTES ARE EXEMPT TOO, and they are not listed. Those are the reauth-only -# factories (TOTP enrolment and confirm, session termination): the escapes an account under -# ``require_mfa`` with no factor needs. Keying on the flag rather than on a copy of their paths is +# factories (TOTP enrolment and confirm, session termination). Enrolment is the escape an account +# under ``require_mfa`` with no factor needs; termination refuses such a pending session (BACKLOG +# #1149). Keying on the flag rather than on a copy of their paths is # what keeps this plane and the console's (which exempts every ``allow_mfa_pending`` route) the same. # # /me/notify-email is deliberately NOT in the MFA set above. A session still owing its factor has @@ -1632,8 +1633,7 @@ async def _mfa_refusal(request: Request, auth: AuthService, identity: Identity) #: The 403 detail for a pending session whose account holds no factor (BACKLOG #1149). _MFA_ENROL_FIRST_DETAIL = ( "multi-factor verification required; no second factor is enrolled, so enrol one first" - " (POST /me/reauth with purpose mfa_enroll, POST /me/mfa/enroll, POST /me/mfa/confirm)," - " then retry" + " (POST /me/mfa/enroll, then POST /me/mfa/confirm, each behind its own step-up), then retry" ) @@ -1643,8 +1643,23 @@ async def _pending_holds_no_factor(auth: AuthService, token: str | None) -> bool Asks the ``mfa_enroll`` factor-binding refusal, which is True for a pending session exactly when its account holds a factor, and fails closed (True) on a session or account it cannot find. So a False here means a found, pending session with no factor; the unknown case keeps - the verify wording. No new service member, so the console's seam does not move.""" - return not await auth.factor_binding_is_blocked(token, STEP_UP_ACTION_MFA_ENROLL) + the verify wording. + + The read only picks the wording, and the gate has already refused, so a store fault keeps the + 403 and its ``X-MFA-Required`` with the verify wording rather than becoming a 500, as + :func:`_step_up_refusal`'s wording read does (vault BACKLOG #3145 item 6).""" + try: + return not await auth.factor_binding_is_blocked(token, STEP_UP_ACTION_MFA_ENROLL) + except AUDIT_WRITE_DEFECTS: + raise + except store_call_errors() as exc: + log.warning( + "an MFA refusal could not read whether the account holds a factor (%s); it answers" + " with the verify wording", + type(exc).__name__, + exc_info=True, + ) + return False async def refuse_from_new_address(request: Request) -> None: diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 8c8d77193a..4bcd60d423 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -16465,10 +16465,21 @@ def reauth_detail(*, interrupted: bool = False, clear_id: str | None = None) -> # and notice are written at the clear, above. return elevation + #: The actions of :data:`_PENDING_REFUSED_ACTIONS` that end sessions. Refused to a pending + #: session whether or not its account holds a factor (BACKLOG #1149). Part of that set by + #: construction, so an action added here is refused. + _PENDING_SESSION_ENDING_ACTIONS = frozenset( + { + STEP_UP_ACTION_SESSION_TERMINATE, + STEP_UP_ACTION_SAVE_ENDS_OWN_SESSIONS, + STEP_UP_ACTION_REVOKE_ALL_SESSIONS, + } + ) + #: The step-up actions a pending session may NOT be granted once its account HAS a factor (and, - #: for the session-ending ones below, even when it has none). Every + #: for the session-ending ones above, even when it has none). Every #: one of them rides a ``*_reauth_only_action`` gate (``mfa_gate=False``), which exists so an - #: account with no factor is not locked out of it. For an account that already has one: + #: account with no factor is not locked out of enrolment. For an account that already has one: #: #: - binding a new factor (``mfa_enroll``, ``mfa_confirm``, ``webauthn_enroll``) is a promotion #: path, because both ceremonies mark the session MFA-satisfied on success; @@ -16496,25 +16507,15 @@ def reauth_detail(*, interrupted: bool = False, clear_id: str | None = None) -> #: ``require_mfa`` a session on an account with no factor is MFA-pending, so it is confined like #: any other pending session: it enrols first, and the confirm that binds its first factor #: satisfies the session. Only the enrolment actions keep the first-enrolment carve-out. - _PENDING_REFUSED_ACTIONS = frozenset( - { - STEP_UP_ACTION_MFA_ENROLL, - STEP_UP_ACTION_MFA_CONFIRM, - STEP_UP_ACTION_WEBAUTHN_ENROLL, - STEP_UP_ACTION_SESSION_TERMINATE, - STEP_UP_ACTION_SAVE_ENDS_OWN_SESSIONS, - STEP_UP_ACTION_REVOKE_ALL_SESSIONS, - } - ) - - #: The actions of :data:`_PENDING_REFUSED_ACTIONS` that end sessions. Refused to a pending - #: session whether or not its account holds a factor (BACKLOG #1149). - _PENDING_SESSION_ENDING_ACTIONS = frozenset( - { - STEP_UP_ACTION_SESSION_TERMINATE, - STEP_UP_ACTION_SAVE_ENDS_OWN_SESSIONS, - STEP_UP_ACTION_REVOKE_ALL_SESSIONS, - } + _PENDING_REFUSED_ACTIONS = ( + frozenset( + { + STEP_UP_ACTION_MFA_ENROLL, + STEP_UP_ACTION_MFA_CONFIRM, + STEP_UP_ACTION_WEBAUTHN_ENROLL, + } + ) + | _PENDING_SESSION_ENDING_ACTIONS ) async def _factor_binding_is_blocked(self, token: str | None, purpose: str) -> bool: diff --git a/messagefoundry_webconsole/_auth.py b/messagefoundry_webconsole/_auth.py index 1274612005..6f90f0c5fe 100644 --- a/messagefoundry_webconsole/_auth.py +++ b/messagefoundry_webconsole/_auth.py @@ -534,7 +534,8 @@ def require_ui( must reach (enrollment, the confinement page, the account pages). ``pending_refusal`` is for a route that passes ``allow_mfa_pending`` for an account with NO factor - and must still refuse a pending session on an account that HAS one. It runs where the 6.3.3 gate + and must still refuse some pending sessions, at least one on an account that HAS a factor. It + runs where the 6.3.3 gate runs, so the refusal comes before the permission loop and before either budget is charged (BACKLOG #1973). Checked later, the refused request had already spent the user's admin-write budget, so a password holder could throttle the real user by being refused in a loop. On a @@ -2172,7 +2173,8 @@ def require_ui_reauth_only_action( async def refuse_pending( request: Request, auth: AuthService, _identity: Identity ) -> HTTPException | None: - # A pending session on an account that HAS a factor (see _PENDING_REFUSED_ACTIONS). Run by + # A pending session on an account that HAS a factor (see _PENDING_REFUSED_ACTIONS), or on a + # session-ending action any pending session (BACKLOG #1149). Run by # the base, so it is refused before the admin-write charge (BACKLOG #1973), and audited there # like require_ui's own MFA refusal and like the JSON twin; /ui/reauth then asks for the # code before the password. @@ -2191,9 +2193,9 @@ async def refuse_pending( return _reauth_redirect(request, continuation(request)) # allow_mfa_pending: a genuine exemption, not a re-route. It serves an account with NO factor, - # which can never satisfy a gate standing in front of the route that enrolls it, or that ends - # a session it does not recognise. An account that HAS a factor is refused by refuse_pending - # (#1951), inside the base so that the refusal spends no budget (#1973). + # which can never satisfy a gate standing in front of the route that enrolls it. An account + # that HAS a factor is refused by refuse_pending (#1951), and so is any pending session on a + # session-ending action (#1149), inside the base so that the refusal spends no budget (#1973). base = require_ui( *permissions, allow_mfa_pending=True, diff --git a/messagefoundry_webconsole/pages/account.py b/messagefoundry_webconsole/pages/account.py index 75777134e8..a40bfdc1e2 100644 --- a/messagefoundry_webconsole/pages/account.py +++ b/messagefoundry_webconsole/pages/account.py @@ -812,9 +812,9 @@ def sessions_page(sessions: Sequence[Mapping[str, object]], *, notice: str | Non **Revoking one's OWN sessions is step-up gated** (ASVS 7.5.2, BACKLOG #1149): both terminate POSTs take ``require_ui_reauth_only_action(STEP_UP_ACTION_SESSION_TERMINATE)``, so the cookie alone does not carry them — ``/ui/reauth`` mints a single-use grant bound to that action and each - terminate consumes one. It is the password-only family on purpose: the full step-up would - deadlock an MFA-required-but-unenrolled operator out of revoking their own sessions. An operator - who HAS a factor proves it first (BACKLOG #1951). + terminate consumes one. It is the password-only family, but no pending session passes it: an + operator who HAS a factor proves it first (BACKLOG #1951), and one with no factor under + ``require_mfa`` is sent to enrol first (BACKLOG #1149). *This docstring previously said "no step-up", which stopped being true when that gate landed. A stale absence claim beside a control is worse than silence: it reads as a licence to remove diff --git a/messagefoundry_webconsole/routes/account.py b/messagefoundry_webconsole/routes/account.py index 1a78088474..5acf915697 100644 --- a/messagefoundry_webconsole/routes/account.py +++ b/messagefoundry_webconsole/routes/account.py @@ -166,8 +166,8 @@ async def _no_code_posted(request: Request) -> bool: # --- L6b: self-service session TERMINATE (ASVS 7.5.2) — password re-proof before revoke --- # Both terminate POSTs are body-less (all params in the PATH), so they register as auto_retry # continuations /ui/reauth may re-POST after a stale-window re-auth. step_up=False (password- -# only, mirrors require_ui_reauth_only): a required-but-unenrolled MFA session must still be -# able to revoke — require_ui_step_up would deadlock it (WP-14). permission=None (self-scoped). +# only, mirrors require_ui_reauth_only). A pending session does not pass the gate, with a factor +# (#1951) or without one under require_mfa, which is sent to enrol (#1149). permission=None. # The two patterns do not overlap: the per-session pattern requires two more segments after # sessions/ (/revoke), so /ui/account/sessions/revoke-others (one segment) matches only itself. # BACKLOG #1149 (ASVS 7.5.2): both now carry an action= tag, the same treatment the factor lanes got @@ -739,8 +739,8 @@ async def ui_mfa_disable( # --- L6b: self-service session management (#75 parity — desktop sessions.py twin) --- # LISTING one's OWN sessions is plain cookie-authenticated self-service (require_ui). TERMINATING # one (revoke one / revoke-others) additionally requires a fresh PASSWORD re-proof - # (require_ui_reauth_only_action — ASVS 7.5.2), NOT the full MFA step-up: a no-factor user must - # still be able to revoke, and require_ui_step_up would deadlock them (WP-14). BACKLOG #1149 + # (require_ui_reauth_only_action — ASVS 7.5.2), NOT the full MFA step-up. No pending session + # passes it: one with no factor under require_mfa is sent to enrol first. BACKLOG #1149 # CORRECTED THE SENTENCE THAT STOOD HERE: it read "a fresh login seeds the step-up window, so an # immediate post-login revoke is unaffected", which was true of the code and was the defect -- # 7.5.2 wants an authentication event AFTER the one that established the session. The proof is diff --git a/tests/test_mfa_access_gate.py b/tests/test_mfa_access_gate.py index c8cce09116..a1ee2aba71 100644 --- a/tests/test_mfa_access_gate.py +++ b/tests/test_mfa_access_gate.py @@ -735,6 +735,28 @@ async def test_the_access_gate_names_enrolment_to_a_pending_session_with_no_fact ) +async def test_a_store_fault_on_the_wording_read_keeps_the_mfa_refusal( + engine: Engine, monkeypatch: pytest.MonkeyPatch +) -> None: + """RED when: the read that picks the refusal's wording is unguarded, so a store fault there + turns the 403 + ``X-MFA-Required`` into a 500. The fault answers with the verify wording.""" + service = await _service(engine) + await _add(service, "fresh", Role.VIEWER) + + async def broken(*_: object, **__: object) -> bool: + raise OSError("synthetic store fault") + + async with _client(engine, service) as c: + tok = await _login(c, "fresh") + monkeypatch.setattr(service, "factor_binding_is_blocked", broken) + r = await c.get("/messages", headers=_auth(tok)) + assert r.status_code == 403 + assert r.headers.get("X-MFA-Required") == "1" + assert r.json()["detail"] == ( + "multi-factor verification required; POST /auth/mfa-verify then retry" + ) + + async def test_a_no_factor_session_without_require_mfa_still_ends_sessions( engine: Engine, ) -> None: From db3d07dec869ab65ff1b4c2586966cc3232a3152 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:57:34 -0600 Subject: [PATCH 3/5] Auth: review round 2 for the no-factor pending refusal - Three console tests that used a no-factor pending session to reach /ui/reauth for another purpose run with require_mfa off. - The console asks the factor read again only on a session-ending action. - SECURITY.md: the IdP step-up grant refusal states the new rule. - Comment fixes: the refused-actions set, the wording helper's return. - Console CHANGELOG entry; the seam digest re-derived again. BACKLOG #1149 Proposed PR title: Auth: a pending session with no factor ends no sessions under require_mfa (BACKLOG #1149) --- docs/SECURITY.md | 7 ++++--- messagefoundry/api/_ui_seam.py | 4 ++-- messagefoundry/api/security.py | 5 +++-- messagefoundry/auth/service.py | 7 ++++--- messagefoundry_webconsole/__init__.py | 2 +- messagefoundry_webconsole/_auth.py | 16 ++++++++++++++-- packaging/messagefoundry-webconsole/CHANGELOG.md | 4 ++++ .../tests/test_ui_credential_bounds.py | 8 +++++--- .../tests/test_webui_bulk.py | 7 +++++-- tests/golden/webconsole_seam.snapshot | 12 ++++++------ 10 files changed, 48 insertions(+), 24 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 07ace476fb..146f405bb3 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -5768,8 +5768,9 @@ token claim**. There is no new `auth_provider` value: a federated login resolves It then elevates through the same path as the password leg: `reauth_at` is stamped, the session is rotated (ASVS 7.2.4) and keeps its `mfa_verified_at`, and a single-use action grant is minted for the action the operator started from, when that action takes one and the session is not - refused it (a pending session on an account with a factor, for a factor-binding or session-terminate action, or a save that ends the caller's own sessions (BACKLOG #3401), - or the bulk session revoke (BACKLOG #2614), as on the password leg). Every outcome + refused it (a pending session on an account with a factor, for a factor-binding action; any pending + session, factor or not, for a session terminate, a save that ends the caller's own sessions (BACKLOG + #3401) or the bulk session revoke (BACKLOG #2614), BACKLOG #1149; as on the password leg). Every outcome that `complete_oidc_step_up` or `abandon_oidc_step_up` decides writes an `auth.reauth` row with `mech=oidc`, and a refusal carries a closed-set `reason` (`step_up_not_fresh`, `step_up_idp_auth_time_not_later`, `step_up_idp_auth_time_missing`, `step_up_subject_mismatch`, `flow_purpose_mismatch`, a claims-ladder slug, and others). @@ -6936,7 +6937,7 @@ list, which admits any certificate its CA ever signed. | **Local** (argon2id) | **password** (argon2id) **plus an engine second factor** — RFC 6238 TOTP, single-use recovery codes, or a WebAuthn/FIDO2 passkey. That factor is an **access gate, not merely a step-up boundary**: an MFA-pending session is refused on *every* authorized route with `X-MFA-Required: 1`, and a browser session is **redirected** to `/ui/mfa` — *not* confined to it, as an earlier revision of this cell said, because the account and factor-enrolment routes are declared MFA-pending-exempt, so a user with no factor yet enrols at `/ui/account`. It binds any local account that has enrolled a factor, plus every account `[security].require_mfa_scope` covers — **`every_local_account` by default** (`[security].require_mfa` defaults **on**; both keys are rejected under `[auth]` and fail the start). Set the scope to `administrators` for the earlier, narrower posture, in which a non-admin, un-enrolled local session is **password-only end to end**. Caveat: a passkey is asserted at `user_verification=preferred`, so for a passkey-only account the second factor may be **device possession alone** | **per-account lockout** (5/15 min) on **two counters** (ADR 0197). The **sign-in** counter is fed by wrong passwords **and** by the step-up re-auth and password-change re-proofs, which it does not refuse; those are capped per session instead (BACKLOG #1138). The **second-step** counter is fed by wrong TOTP/recovery codes and by a **combined sign-in** (password and TOTP code in one request) that gets exactly one factor right. The sign-in lock refuses a password-only sign-in but **not** a combined one on an account with TOTP enrolled, nor a **combined passkey sign-in** (password and a discoverable-passkey assertion in one request, ADR 0197 Amendment A wave 2) on an account holding a discoverable passkey; the second-step lock refuses all of them, and the second step. The second-step lock doubles per cycle up to `lockout_max_minutes` on every local account, and the sign-in lock does so on a local account with a TOTP enrolled unless the engine KNOWS this release refuses that enrolment (at least a marker it refuses, BACKLOG #3422, a key under 160 bits, BACKLOG #5340, or no secret): a TOTP it cannot judge, as [WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068) says, still escalates. It does so too on a local account holding a discoverable passkey under the configured relying party (BACKLOG #3937). Every other lock keeps `lockout_minutes`. A local account whose enrolment is known to be refused, and that holds no such passkey, keeps it for serial failures only: a race listed under [WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068) escalates that account by the plain enabled-TOTP rule (BACKLOG #3422). While the credential in force is engine-generated, sign-in failures arm no lock, and under `require_mfa` the holder enrols TOTP or a discoverable passkey before replacing it (ADR 0197 Amendment A) + breach/context policy + the per-IP **and** global sign-in window | the only sign-in whose **first** factor feeds the engine lockout; the TOTP/recovery leg feeds it on **any** account that enrolled a code, directory accounts included. Its passkey is phishing-resistant, but not Local's alone: a directory account can enrol one too (BACKLOG #1144) | | **AD** (LDAP simple-bind over LDAPS) — **step-up re-authentication only; the sign-in was retired** | password, verified by a bind **as the user** against the DC. It no longer mints a session: `POST /auth/login` with `provider=ad` is refused and audited, and the bind survives only at `POST /me/reauth` and the console's `POST /ui/reauth`, where it re-proves a session **Kerberos** minted. An `oidc` session never reaches the bind: `reauth()` refuses it before any verify and it steps up at the IdP (the OIDC row). The one other session it can reach is a row written before `sessions.auth_mechanism` existed, which reads NULL and takes this leg for an AD account. So this row carries no MFA grant of its own — the session's MFA state was decided at its own sign-in. The delegated-directory relaxation it used to carry is **retired** (BACKLOG #1144): no pathway grants MFA satisfaction on a directory assertion the engine cannot read | the **directory's** lockout/complexity policy; engine-side, a **per-actor** step-up budget, **not** the sign-in limiter — the bind is post-session, so an unauthenticated flood cannot reach it — plus the **engine** per-account lockout, which a rejected re-bind feeds (BACKLOG #1138), and a per-session cap: the session whose re-binds reach `lockout_threshold` rejections is revoked, so it sends the DC at most that many counted ones. A re-bind the DC ends with an outage code, at least busy or unavailable, is charged to neither the lockout nor the cap; *Why the lock does not refuse a live session's re-proofs* below lists the codes, the other re-binds the engine does not count, and what bounds them (BACKLOG #3169). `[auth].login_rate_limit_enabled=false` removes the per-actor budget too, because that flag builds neither limiter; it is one of the settings that turn the budget off, and the same section links their list. The lockout feed and the per-session cap survive it, so the flag does not strip counted re-binds bare. The engine lock sets the engine's own row and is enforced at the Kerberos and OIDC sign-ins, not at the re-bind. It never writes a lock to the directory account, but each rejected re-bind still reaches the DC, so the domain's own lockout policy can lock the domain account too | password strength + lockout are the AD domain's responsibility. LDAPS is required: a plain `ldap://` bind is refused at every posture, with no escape (vault BACKLOG #3533; until then the removed `[auth].ad_allow_insecure_ldap` released it under `[security].enforcement = warn`), and `ad_tls_verify=false` is refused at startup, with no escape (vault BACKLOG #3230; until then the `MEFOR_ALLOW_INSECURE_TLS` dev escape released it) | | **Kerberos / SPNEGO** | domain ticket **plus an engine second factor**. No `amr`-equivalent evidence reaches the engine, so the ticket proves nothing about directory-side factor strength and the session is issued **MFA-pending** (BACKLOG #1144). It used to be issued **MFA-satisfied** under a delegated-directory relaxation, which cleared every engine MFA gate on zero engine-readable evidence; that grant is retired. While `[security].require_mfa` is on, an un-satisfied directory session reaches only the MFA-pending-exempt routes, and its holder enrols a TOTP or a passkey on the same routes a local account uses. **The account's first engine factor binds only with a single-use issued enrolment code** ([ADR 0207](adr/0207-a-single-use-enrolment-code-for-a-directory-account-s-first-engine-factor.md), [Directory-account enrolment codes](#directory-account-enrolment-codes-adr-0207)), with `require_mfa` on or off, so the directory password alone binds nothing. Set `require_mfa = false` for the earlier single-factor posture | the **domain's** controls; engine-side, the sign-in window on the token-bearing leg (`[auth].login_rate_limit_enabled`, default on — **off leaves the ticket leg with no engine-side control at all**; the RFC 4559 challenge leg is deliberately unthrottled either way). An enrolled engine TOTP or recovery code still feeds the per-account lockout, and a locked account row refuses this sign-in (BACKLOG #1638) | experimental, off by default, **single-leg — no mutual authentication**, channel binding deliberately un-enforced. Both legs (`GET /ui/sso` and the JSON `POST /auth/negotiate`) mint with no step-up window, so a sensitive action forces a step-up unless a TOTP or recovery code, or a user-verified passkey, proved at the MFA gate has already stamped one. That step-up is the **AD** row's directory re-bind, at `POST /me/reauth` or `POST /ui/reauth`. **Refuses an account that holds a federated binding** (vault BACKLOG #2609): that account signs in through the OIDC row, and [Federated sign-in](#federated-sign-in-oidc-browser-only--adr-0142) has the limits | -| **OIDC federation** (browser only, hybrid AD-backed) | IdP-asserted, gated on a **signature-verified** `amr`/`acr` claim (`[auth].oidc_require_mfa_claim` defaults **on**) — an assertion, not a proof | no engine credential to guess on the federated leg, so that leg feeds no per-account lockout, though a lock another leg set on the account row refuses this sign-in (BACKLOG #1638); both legs (`POST /ui/oidc/start`, `GET /ui/oidc/callback`) charge the sign-in window, and so does `GET /ui/oidc/start` when its interstitial is skipped (see the [Route → limiter map](#route--limiter-map)) (`[auth].login_rate_limit_enabled`, default on — **off leaves the federated leg with no engine-side control at all**, though the bounded pending-flow cache still caps concurrent start legs), plus the IdP's own lockout. The **step-up leg** checks no engine credential either, so a refused IdP step-up feeds no lockout and no per-session re-proof cap, and neither account lock refuses it. Its start, `POST /ui/reauth/oidc`, and the IdP's return to `GET /ui/oidc/callback` both draw the per-actor ceremony limiter, the return under a key of its own for the user the staged flow names (BACKLOG #3374) | hybrid-only: a federated principal with no on-prem AD object is refused. Roles come from LDAP, never from a token claim. When `[auth].oidc_username_strip_domain` is on (default), the claim's UPN suffix must match `oidc_allowed_username_domains` (or `[auth].ad_domain`); with stripping **off** the claim is used verbatim and no suffix check applies. Either way the claim selects no account: the bound (issuer, sub) pair does (ADR 0184). The session's absolute lifetime is capped at the verified `id_token.exp` and at `auth_time + [auth].oidc_max_age_seconds`; minted with no step-up window. **Its step-up goes back to the IdP and never to a password** (BACKLOG #296, ADR 0142 Amendment B). `POST /ui/reauth/oidc` sends the browser to the IdP with `max_age=0` and `prompt=login`, and `complete_oidc_step_up` checks the answer before it elevates the session. Among its checks, the verified (issuer, sub) pair must still be the account's, and the new `auth_time` must be no earlier than the moment the flow was staged, less `oidc_clock_skew_seconds`, and later than the IdP `auth_time` the session holds (BACKLOG #2143). The full list, in order, is under [Federated sign-in](#federated-sign-in-oidc-browser-only--adr-0142). It then stamps `reauth_at`, rotates the session, and mints the action-bound grant when the action the operator started from takes one and the session is not refused it (a pending session on an account with a factor, for a factor-binding or session-terminate action, a save that ends the caller's own sessions (BACKLOG #3401), or ending every session (BACKLOG #2614)). Console only: `POST /me/reauth` refuses an `oidc` session, and the JSON plane has no federated step-up | +| **OIDC federation** (browser only, hybrid AD-backed) | IdP-asserted, gated on a **signature-verified** `amr`/`acr` claim (`[auth].oidc_require_mfa_claim` defaults **on**) — an assertion, not a proof | no engine credential to guess on the federated leg, so that leg feeds no per-account lockout, though a lock another leg set on the account row refuses this sign-in (BACKLOG #1638); both legs (`POST /ui/oidc/start`, `GET /ui/oidc/callback`) charge the sign-in window, and so does `GET /ui/oidc/start` when its interstitial is skipped (see the [Route → limiter map](#route--limiter-map)) (`[auth].login_rate_limit_enabled`, default on — **off leaves the federated leg with no engine-side control at all**, though the bounded pending-flow cache still caps concurrent start legs), plus the IdP's own lockout. The **step-up leg** checks no engine credential either, so a refused IdP step-up feeds no lockout and no per-session re-proof cap, and neither account lock refuses it. Its start, `POST /ui/reauth/oidc`, and the IdP's return to `GET /ui/oidc/callback` both draw the per-actor ceremony limiter, the return under a key of its own for the user the staged flow names (BACKLOG #3374) | hybrid-only: a federated principal with no on-prem AD object is refused. Roles come from LDAP, never from a token claim. When `[auth].oidc_username_strip_domain` is on (default), the claim's UPN suffix must match `oidc_allowed_username_domains` (or `[auth].ad_domain`); with stripping **off** the claim is used verbatim and no suffix check applies. Either way the claim selects no account: the bound (issuer, sub) pair does (ADR 0184). The session's absolute lifetime is capped at the verified `id_token.exp` and at `auth_time + [auth].oidc_max_age_seconds`; minted with no step-up window. **Its step-up goes back to the IdP and never to a password** (BACKLOG #296, ADR 0142 Amendment B). `POST /ui/reauth/oidc` sends the browser to the IdP with `max_age=0` and `prompt=login`, and `complete_oidc_step_up` checks the answer before it elevates the session. Among its checks, the verified (issuer, sub) pair must still be the account's, and the new `auth_time` must be no earlier than the moment the flow was staged, less `oidc_clock_skew_seconds`, and later than the IdP `auth_time` the session holds (BACKLOG #2143). The full list, in order, is under [Federated sign-in](#federated-sign-in-oidc-browser-only--adr-0142). It then stamps `reauth_at`, rotates the session, and mints the action-bound grant when the action the operator started from takes one and the session is not refused it (a pending session on an account with a factor, for a factor-binding action; any pending session, factor or not, for a session terminate, a save that ends the caller's own sessions (BACKLOG #3401), or ending every session (BACKLOG #2614), BACKLOG #1149). Console only: `POST /me/reauth` refuses an `oidc` session, and the JSON plane has no federated step-up | | **mTLS service identity** (non-interactive, ADR 0083) | a **verified** client certificate mapped through a deny-by-default, name-space-qualified allow-list (`CN:` / `SAN::`) | **not applicable** — no guessable secret and no lockout; admission requires a chain verifying to the pinned client CA plus a listed qualified name | no session, no MFA, no step-up — which is why it is **PHI-fenced**: `require_service_cert` raises at **app construction** if asked to gate a PHI-view permission. One route only (`GET /service/identity`); every success is audited `service_cert_auth` | | **HTTP intake authentication** (non-interactive, ingest plane, ADR 0154 D6) | per inbound `Http()` connection, `intake_auth` picks one of `none`, `api_key`, `bearer` or `mtls_subject`. **The default is `none`: no credential is checked, so any peer the network rules admit may submit.** `api_key` and `bearer` compare a shared secret (`intake_api_key`, `env()` only, with an `intake_api_key_next` rotation slot) in constant time; `mtls_subject` maps a client certificate already verified against `tls_ca_file` through the qualified `intake_client_subjects` allow-list, keyed by the loaded CA whose key signed the certificate | **per-peer and global failed-attempt budgets** (defaults `intake_auth_rate_limit` 10/min, `intake_auth_rate_limit_global` 60/min, then `429`; see Table B); a successful attempt never spends budget, and a peer that authenticated inside the window is exempt from the global one. **No per-account lockout** — there is no account | authorises *submitting* only: no session, no MFA, no step-up, no read. Under `api_key` / `bearer` a missing or wrong credential gets `401` before any body byte is read, or `400` if it sends the credential header twice (Table B). Under `mtls_subject` a peer with no certificate from `tls_ca_file` fails the TLS handshake and is never seen by the engine, and a verified certificate whose subject is not listed under the loaded CA that signed it gets `403`. The refusals the engine sees are audited `intake.auth_failed` / `intake.auth_subject_denied` / `intake.auth_rate_limited`. Off loopback, a listener with no effective peer control is refused at start under `[security].enforcement = enforce` (Table B) | | **MLLP intake authentication** (non-interactive, ingest plane, BACKLOG #4907) | per inbound `MLLP()` connection, `tls_client_subjects` maps a client certificate already verified against `tls_ca_file` through a qualified (`CN:` / `SAN::`) allow-list, keyed by the loaded CA whose key signed the certificate, through the matcher `mtls_subject` uses. **The default is unset: no subject is checked, so any certificate `tls_ca_file` verifies is admitted as any sender.** It needs `tls` and `tls_ca_file` | **per-peer and global failed-attempt budgets** at the `Http()` defaults (10/min per address, 60/min in all), with no setting of its own to change or turn them off. The per-address budget is read before the certificate is compared, and an address that has spent it is closed unread; the global one is read only once the compare has refused, so a listed sender never spends budget and is never closed by the global one. **No per-account lockout** — there is no account | authorises *submitting* only: no session, no MFA, no step-up, no read. A peer with no certificate from `tls_ca_file` fails the TLS handshake before the `tls_client_subjects` allowlist is read, leaving only the throttled `tls_handshake_failed` connection event (Table B). A verified certificate whose names are not listed under the loaded CA that signed it has each message of its first read recorded as an `ERROR` row, then answered `AR` on an HL7 v2 inbound that acknowledges, and the connection closes. The refusals are audited `intake.auth_subject_denied` / `intake.auth_rate_limited`, and the listener refuses TLS renegotiation. [CONNECTIONS.md](CONNECTIONS.md#expected-senders-tls_client_subjects) states the design (Table B) | diff --git a/messagefoundry/api/_ui_seam.py b/messagefoundry/api/_ui_seam.py index 732954e204..d6088cc9fc 100644 --- a/messagefoundry/api/_ui_seam.py +++ b/messagefoundry/api/_ui_seam.py @@ -970,14 +970,14 @@ #: BACKLOG #1149: the console's reauth-only action gate sends a pending session with no factor to #: enrolment when a session-ending action refuses it. The snapshot hashes that gate's body, so the #: digest moved. No engine surface changed. Re-derived with ``--write``, from -#: ``a888b8fed812bbe6`` to ``28c252796d4fd6c4``. +#: ``a888b8fed812bbe6`` to ``c5417861cbb1bd67``. #: #: The digest below covers the surface DISCOVERED from the console's own imports and uses, which is #: strictly larger than the five hand-maintained tuples it replaced -- those had drifted, and the #: proof is that commit 40a4d5d9 added a REQUIRED ``UploadedFileList.scope`` field the console renders #: unconditionally while touching no seam file at all. Regenerate with #: ``python scripts/webconsole_seam_snapshot.py --write``; never hand-edit it to silence a gate. -ENGINE_UI_SEAM: str = "28c252796d4fd6c4" +ENGINE_UI_SEAM: str = "c5417861cbb1bd67" @dataclass(frozen=True, slots=True) diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index b8d3b993b4..63d335f187 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1642,8 +1642,9 @@ async def _pending_holds_no_factor(auth: AuthService, token: str | None) -> bool Asks the ``mfa_enroll`` factor-binding refusal, which is True for a pending session exactly when its account holds a factor, and fails closed (True) on a session or account it cannot - find. So a False here means a found, pending session with no factor; the unknown case keeps - the verify wording. + find. So this returns True only for a found, pending session with no factor; the unknown case + keeps the verify wording. A session satisfied between the gate's read and this one also reads + True, a wording slip on a refusal already decided. The read only picks the wording, and the gate has already refused, so a store fault keeps the 403 and its ``X-MFA-Required`` with the verify wording rather than becoming a 500, as diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 4bcd60d423..450d39383e 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -16477,9 +16477,10 @@ def reauth_detail(*, interrupted: bool = False, clear_id: str | None = None) -> ) #: The step-up actions a pending session may NOT be granted once its account HAS a factor (and, - #: for the session-ending ones above, even when it has none). Every - #: one of them rides a ``*_reauth_only_action`` gate (``mfa_gate=False``), which exists so an - #: account with no factor is not locked out of enrolment. For an account that already has one: + #: for the session-ending ones above, even when it has none). At least the enrolment actions + #: and ``session_terminate`` ride a ``*_reauth_only_action`` gate (``mfa_gate=False``), which + #: exists so an account with no factor is not locked out of enrolment. For an account that + #: already has one: #: #: - binding a new factor (``mfa_enroll``, ``mfa_confirm``, ``webauthn_enroll``) is a promotion #: path, because both ceremonies mark the session MFA-satisfied on success; diff --git a/messagefoundry_webconsole/__init__.py b/messagefoundry_webconsole/__init__.py index 9979d6b1b2..e40b6dcfc2 100644 --- a/messagefoundry_webconsole/__init__.py +++ b/messagefoundry_webconsole/__init__.py @@ -44,7 +44,7 @@ # If cross-seam support is ever genuinely wanted, re-widen this set AND add the CI matrix that # installs the MIN and MAX supported engine builds — the claim and its test land together, or not # at all. -SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"28c252796d4fd6c4"}) +SUPPORTED_ENGINE_SEAMS: frozenset[str] = frozenset({"c5417861cbb1bd67"}) #: The vendored static assets shipped in THIS wheel (mounted at /ui/static by :func:`mount_ui`). STATIC_DIR = Path(__file__).parent / "static" diff --git a/messagefoundry_webconsole/_auth.py b/messagefoundry_webconsole/_auth.py index 6f90f0c5fe..4f1a947152 100644 --- a/messagefoundry_webconsole/_auth.py +++ b/messagefoundry_webconsole/_auth.py @@ -34,7 +34,11 @@ record_ws_gate, ) from messagefoundry.auth import Identity, Permission -from messagefoundry.auth.service import STEP_UP_ACTION_MFA_ENROLL, AuthService +from messagefoundry.auth.service import ( + STEP_UP_ACTION_MFA_ENROLL, + STEP_UP_ACTION_SESSION_TERMINATE, + AuthService, +) from messagefoundry.auth.tokens import hash_token from messagefoundry.auth.webauthn import configured_rp_id @@ -2150,6 +2154,12 @@ async def spend_ui_action_step_up( return spend +#: The reauth-only actions that end sessions, the one place a pending session with no factor is +#: refused on this gate and so sent to enrol (BACKLOG #1149). The other reauth-only actions bind a +#: factor, and an account with no factor may take them. +_SESSION_ENDING_UI_ACTIONS = frozenset({STEP_UP_ACTION_SESSION_TERMINATE}) + + def require_ui_reauth_only_action( action: str, *permissions: Permission, @@ -2188,7 +2198,9 @@ async def refuse_pending( # NO factor too. It has nothing to give /ui/reauth, which would mint it nothing, so it is # sent to enrol. The mfa_enroll refusal is True exactly when the account holds a factor (and # on an unknown session), the JSON plane's _pending_holds_no_factor reading. - if not await auth.factor_binding_is_blocked(token, STEP_UP_ACTION_MFA_ENROLL): + if action in _SESSION_ENDING_UI_ACTIONS and not await auth.factor_binding_is_blocked( + token, STEP_UP_ACTION_MFA_ENROLL + ): return HTTPException(status.HTTP_303_SEE_OTHER, headers={"Location": ENROL_FIRST_PAGE}) return _reauth_redirect(request, continuation(request)) diff --git a/packaging/messagefoundry-webconsole/CHANGELOG.md b/packaging/messagefoundry-webconsole/CHANGELOG.md index 53233cf881..4faf9dd4ae 100644 --- a/packaging/messagefoundry-webconsole/CHANGELOG.md +++ b/packaging/messagefoundry-webconsole/CHANGELOG.md @@ -81,6 +81,10 @@ this line.** ### Security +- **A pending session with no second factor is sent to enrol before it can end sessions.** Under + `[security].require_mfa`, the two session-terminate POSTs refuse such a session and redirect it + to `/ui/account?m=enroll_first`, where it was sent to `/ui/reauth`; the enrolment that binds its + first factor satisfies the session. The supported engine seam moved with it. (`BACKLOG #1149`) - **A step-up request refused for a new client address spends no budget.** The step-up gates (`require_ui_step_up` and its action, re-auth-only and own-sessions variants) asked the new-address question after their `require_ui` base had already charged the admin-write budget, diff --git a/packaging/messagefoundry-webconsole/tests/test_ui_credential_bounds.py b/packaging/messagefoundry-webconsole/tests/test_ui_credential_bounds.py index 5c9671caab..43a48eff6e 100644 --- a/packaging/messagefoundry-webconsole/tests/test_ui_credential_bounds.py +++ b/packaging/messagefoundry-webconsole/tests/test_ui_credential_bounds.py @@ -36,7 +36,7 @@ _REVOKE_OTHERS = "/ui/account/sessions/revoke-others" -async def _service(engine: Engine) -> AuthService: +async def _service(engine: Engine, *, require_mfa: bool = True) -> AuthService: service = AuthService( engine.store, AuthSettings( @@ -45,6 +45,7 @@ async def _service(engine: Engine) -> AuthService: admin_write_min_interval_seconds=0, # One slot keeps the enrolment and the recovery-code walk to one argon2 hash each. mfa_recovery_code_count=1, + require_mfa=require_mfa, ), ) await service.initialize() @@ -304,8 +305,9 @@ async def test_an_oversized_step_up_password_never_reaches_reauth( """RED when: ui_reauth's password leg stops checking the password's length before reauth. An account with no factor goes straight to the password leg, which is the one a directory - account's step-up would bind with.""" - service = await _service(engine) + account's step-up would bind with. ``require_mfa`` is off: under it this session is + MFA-pending, and the terminate it starts from sends it to enrol instead (BACKLOG #1149).""" + service = await _service(engine, require_mfa=False) await _add(service) calls = _spy(monkeypatch, service, "reauth") async with ui_client(engine, service) as c: diff --git a/packaging/messagefoundry-webconsole/tests/test_webui_bulk.py b/packaging/messagefoundry-webconsole/tests/test_webui_bulk.py index c439dfc3b7..cd7e14e697 100644 --- a/packaging/messagefoundry-webconsole/tests/test_webui_bulk.py +++ b/packaging/messagefoundry-webconsole/tests/test_webui_bulk.py @@ -59,7 +59,9 @@ async def test_revoke_one_stale_bounces_to_reauth(engine: Engine) -> None: # through the GRANT minted below, which _grant_action_step_up deadlines at # now + step_up_max_age_seconds, i.e. already expired. The mint is the CONTROL, not setup: drop # it and the POST bounces for want of ANY grant, which it does under any window (BACKLOG #1851). - service = AuthService(engine.store, AuthSettings(step_up_max_age_seconds=-1)) + # require_mfa off: under it this no-factor session is MFA-pending and is sent to enrol before + # any window is read (BACKLOG #1149), so the window would not be what refuses. + service = AuthService(engine.store, AuthSettings(step_up_max_age_seconds=-1, require_mfa=False)) await service.initialize() await _add(service, "op", Role.OPERATOR) other = await service.login("op", PW) # the target 2nd session @@ -90,7 +92,8 @@ async def test_revoke_others_stale_bounces_to_reauth(engine: Engine) -> None: # The revoke-others twin of the per-session test above, and the same correction applies: the # negative window bites through the ADR 0077 GRANT's TTL, not through has_recent_step_up, so the # _mint_action below is what puts the window under test (BACKLOG #1851). Reasoning: that twin. - service = AuthService(engine.store, AuthSettings(step_up_max_age_seconds=-1)) + # require_mfa off, for the reason the twin above gives (BACKLOG #1149). + service = AuthService(engine.store, AuthSettings(step_up_max_age_seconds=-1, require_mfa=False)) await service.initialize() await _add(service, "op", Role.OPERATOR) await service.login("op", PW) # a 2nd session diff --git a/tests/golden/webconsole_seam.snapshot b/tests/golden/webconsole_seam.snapshot index b00f29278a..a5c05611b1 100644 --- a/tests/golden/webconsole_seam.snapshot +++ b/tests/golden/webconsole_seam.snapshot @@ -7,7 +7,7 @@ # by hand (BACKLOG #1220) - so a newly rendered DTO is covered with nobody editing a list. ## ENGINE_UI_SEAM -28c252796d4fd6c4 +c5417861cbb1bd67 ## dataclass messagefoundry.api._ui_seam.UiDeps engine_seam @@ -396,14 +396,14 @@ GET /ui/account/password: gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=True; mfa_refusal=None; new_address_check=True; pending_refusal=messagefoundry_webconsole.routes.account:register.._factor_first#ffcbbbf8ddf0(); permissions=[]; phi=False; step_up_new_address=None) GET /ui/account/notify-address: gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=True; allow_must_change=False; mfa_refusal=None; new_address_check=True; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=None) + messagefoundry_webconsole._service:_service#2c4a90234a30() POST /ui/account/notify-address: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=True; allow_must_change=False; mfa_refusal=None; new_address_check=True; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=None) -POST /ui/account/mfa/enroll: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='mfa_enroll'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='mfa_enroll'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) +POST /ui/account/mfa/enroll: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='mfa_enroll'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#3f4f7e54eac8(action='mfa_enroll'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) GET /ui/account/mfa/confirm: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only..dependency#96b0e4ba44a5(base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) -POST /ui/account/mfa/verify: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='mfa_confirm'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='mfa_confirm'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())); before_spend=messagefoundry_webconsole.routes.account:_no_code_posted#3c6ad8b48c50(); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())) +POST /ui/account/mfa/verify: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='mfa_confirm'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#3f4f7e54eac8(action='mfa_confirm'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())); before_spend=messagefoundry_webconsole.routes.account:_no_code_posted#3c6ad8b48c50(); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#ca1183b81534())) POST /ui/account/mfa/disable: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_step_up_action..dependency#e542e585d39b(action='mfa_disable'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=messagefoundry_webconsole._auth:_reauth_refusal..refuse#27c64e277eed(continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); new_address_check=False; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None); repeat=None; spend=True) GET /ui/account/sessions: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=True; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=None) -POST /ui/account/sessions/{session_id}/revoke: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='session_terminate'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='session_terminate'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) -POST /ui/account/sessions/revoke-others: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='session_terminate'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='session_terminate'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) -POST /ui/account/webauthn/enroll: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='webauthn_enroll'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#66be6e6a23fa(action='webauthn_enroll'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) +POST /ui/account/sessions/{session_id}/revoke: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='session_terminate'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#3f4f7e54eac8(action='session_terminate'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) +POST /ui/account/sessions/revoke-others: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='session_terminate'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#3f4f7e54eac8(action='session_terminate'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) +POST /ui/account/webauthn/enroll: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only_action..dependency#9e6ef5d526e2(action='webauthn_enroll'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=messagefoundry_webconsole._auth:require_ui_reauth_only_action..refuse_pending#3f4f7e54eac8(action='webauthn_enroll'; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); before_spend=None; continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)) POST /ui/account/webauthn/verify: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_reauth_only..dependency#96b0e4ba44a5(base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=True; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=False; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#2bdf9126e7dd())); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=messagefoundry_webconsole.routes.account:register..#2bdf9126e7dd())) POST /ui/account/webauthn/{credential_id_hash}/delete: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui_step_up_action..dependency#e542e585d39b(action='webauthn_delete'; base=gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=messagefoundry_webconsole._auth:_reauth_refusal..refuse#27c64e277eed(continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); new_address_check=False; pending_refusal=None; permissions=[]; phi=False; step_up_new_address=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None)); continuation=messagefoundry_webconsole._auth:_step_up_continuation..continuation#58ffab073086(reauth_next=None); repeat=None; spend=True) GET /ui/audit: messagefoundry_webconsole._service:_service#2c4a90234a30() + gate messagefoundry_webconsole._auth:require_ui..dependency#e7a997e44876(activity=True; allow_mfa_pending=False; allow_missing_notify_email=False; allow_must_change=False; mfa_refusal=None; new_address_check=True; pending_refusal=None; permissions=[audit:read]; phi=False; step_up_new_address=None) From 768ba1f7e7100f410b8a137caf647407f2487983 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:32:28 -0600 Subject: [PATCH 4/5] Auth: close review findings 1-5 on the no-factor pending refusal - The wording read also catches the sealed-read set and TransitSealUnavailableError, so a seal or Transit fault keeps the 403. - /ui/reauth sends a pending session with no factor to enrol for a session-ending action instead of a password form that mints nothing. - SECURITY.md: the password-only routes paragraph, the incident-response revoke note and the session-termination paragraph state the new rule, "at least" where the list is open, and that a local password holder can enrol first: the refusal adds a step, not a bar. - ADR 0077 and ADR 0207: dated amendment notes, accepted text kept. - Changelog: the terminate routes used to send X-Step-Up-Required to this session and now send X-MFA-Required. BACKLOG #1149 Proposed PR title: Auth: a pending session with no factor ends no sessions under require_mfa (BACKLOG #1149) --- ...actor-pending-ends-no-sessions.security.md | 15 ++++--- docs/SECURITY.md | 19 ++++++--- docs/adr/0077-action-bound-step-up.md | 12 ++++++ ...directory-account-s-first-engine-factor.md | 10 +++++ messagefoundry/api/security.py | 7 +++- messagefoundry_webconsole/routes/account.py | 3 +- messagefoundry_webconsole/routes/core.py | 42 ++++++++++++++++--- .../tests/test_webui_bulk.py | 25 ++++++++--- tests/test_mfa_access_gate.py | 20 +++++++-- 9 files changed, 125 insertions(+), 28 deletions(-) diff --git a/changelog.d/1149-no-factor-pending-ends-no-sessions.security.md b/changelog.d/1149-no-factor-pending-ends-no-sessions.security.md index 3248a2f010..745cdd79da 100644 --- a/changelog.d/1149-no-factor-pending-ends-no-sessions.security.md +++ b/changelog.d/1149-no-factor-pending-ends-no-sessions.security.md @@ -1,9 +1,14 @@ - **A pending session on an account with no second factor no longer ends sessions.** Under `[security].require_mfa`, such a session is MFA-pending, and it is now treated like any other - pending session: it reaches enrolment and sign-out, and the self-service terminate routes + pending session: it reaches at least enrolment and sign-out, and the self-service terminate routes (`DELETE /me/sessions`, `DELETE /me/sessions/{session_id}` and their console twins) refuse it. No password re-proof mints it a `session_terminate`, `save_ends_own_sessions` or - `revoke_all_sessions` grant, so none can be carried through its first enrolment. The JSON refusal - keeps `403` + `X-MFA-Required` and its detail now names enrolment; the console sends the session - to `/ui/account?m=enroll_first`. The enrolment that binds the first factor satisfies the session, - and ending sessions then works as before. (`BACKLOG #1149`) + `revoke_all_sessions` grant, so none can be carried through its first enrolment. The terminate + routes used to answer such a session `403` + `X-Step-Up-Required` until it re-proved its password; + they now answer `403` + `X-MFA-Required` whatever it proves, with a detail that names enrolment, + and the access gate's own refusal names enrolment to it too. A client that prompts for a code on + `X-MFA-Required` will prompt for one this session does not have. The console sends the session to + `/ui/account?m=enroll_first`, from the terminate POSTs and from `/ui/reauth`. The enrolment that + binds the first factor satisfies the session, and ending sessions then works as before, so for a + local account a password holder can still enrol a factor of its own and then end sessions: this + adds a step, not a bar. (`BACKLOG #1149`) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 146f405bb3..f581ee95b5 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -4069,9 +4069,9 @@ The complete set, as enumerated in the [route map](#route--permission-map-engine Ordinary reads — listing users, the AD maps, the audit log, a single message — are **not** step-up gated. Four routes take the *password-only* variant (`require_reauth_only[_action]`), **without** -the MFA gate, so a required-but-unenrolled user can reach enrolment: `POST /me/mfa/enroll`, -`POST /me/mfa/confirm`, `DELETE /me/sessions/{session_id}`, `DELETE /me/sessions`. On the two -enrolment routes the skip serves an account with no factor only: a pending session on an account +the MFA gate: `POST /me/mfa/enroll`, `POST /me/mfa/confirm`, `DELETE /me/sessions/{session_id}`, +`DELETE /me/sessions`. On the two enrolment routes the skip is what lets a required-but-unenrolled +user reach enrolment, and it serves an account with no factor only: a pending session on an account that has one gets `403` + `X-MFA-Required` there (BACKLOG #1951). On the two terminate routes it serves no pending session: one on an account that has a factor gets the same `403`, and so does one on an account with no factor that `[security].require_mfa` covers, whose detail names enrolment as @@ -6416,7 +6416,11 @@ engine bounds its own sessions with short caps, and the reconciler carries direc route). For your own sessions, Sign out ends the current one. `DELETE /me/sessions` ends the others, but asks for a fresh step-up first. With `[auth].require_action_step_up` on (the default), a Kerberos session can give that step-up only by password. So a Kerberos session on a - passwordless or smartcard-only account cannot end its other sessions this way; + passwordless or smartcard-only account cannot end its other sessions this way. Under + `[security].require_mfa` a Kerberos session that has proven no engine factor is MFA-pending, + and `DELETE /me/sessions` refuses it whatever it proves until it enrols one, which for a + directory account needs an administrator-issued enrolment code (ADR 0207, BACKLOG #1149). Until + then an administrator ends those sessions with `DELETE /users/{user_id}/sessions`; - end sessions in bulk with `DELETE /sessions`, which keeps the caller's current session only when the revoke re-stamps it and otherwise ends it too, or from the host with `messagefoundry admin-revoke-sessions`, which keeps none (BACKLOG #2614). What these and the @@ -6460,7 +6464,12 @@ it with `X-MFA-Required` (ASVS 6.3.3, BACKLOG #1951). A pending session on an ac factor, which `[security].require_mfa` covers, is refused the same way (BACKLOG #1149, ASVS 7.5.2): no step-up mints it a `session_terminate`, `save_ends_own_sessions` or `revoke_all_sessions` grant, the JSON terminate routes answer `403` + `X-MFA-Required` with a detail that names enrolment, and -the console twins send it to `/ui/account?m=enroll_first`. It may still reach enrolment and sign-out. +the console twins send it to `/ui/account?m=enroll_first`, as does `/ui/reauth` when asked to +re-prove for a terminate. It may still reach at least enrolment and sign-out; `_MFA_EXEMPT_ROUTES` +in `api/security.py` holds the JSON routes a pending session reaches. This refusal adds a step, +not a bar, against a holder of a local account's password alone: that holder may enrol a factor of +its own first, which satisfies the session, and then end sessions. A directory account's first +enrolment needs an administrator-issued enrolment code (ADR 0207), so there it holds. Changing the password also ends every session, and it follows the same rule (BACKLOG #1954). A pending session on an account with a factor gets `403` + `X-MFA-Required` from `POST /me/password`, diff --git a/docs/adr/0077-action-bound-step-up.md b/docs/adr/0077-action-bound-step-up.md index 695d484388..3a0e8d41cd 100644 --- a/docs/adr/0077-action-bound-step-up.md +++ b/docs/adr/0077-action-bound-step-up.md @@ -267,3 +267,15 @@ It changes no route's gate. The bullet's route list is the 2026-07-10 state: the amendment moved `PATCH /users/{user_id}` to an action-bound grant. At least the admin password reset, admin MFA reset and federated-identity routes have moved since. `api/auth_routes.py` is the authority on which gate each route uses today. + +## Amendment (2026-11-24, BACKLOG #1149 — ASVS 7.5.2): no pending session terminates + +The 2026-07-17 amendment above says the terminate routes stay password-only "so a no-factor user +can still revoke". That no longer holds under `[security].require_mfa`. A session on an account +with no factor that the requirement covers is MFA-pending, and `session_terminate`, +`save_ends_own_sessions` and `revoke_all_sessions` are refused to every pending session, whether +or not the account holds a factor: no step-up mints those grants, the JSON terminate routes answer +`403` + `X-MFA-Required` with a detail naming enrolment, and the console sends the session to +enrolment. The routes keep their password-only, action-bound gate. The text above is kept as it +was accepted; this note governs where they differ. `docs/SECURITY.md`, under *Session inventory & +targeted revocation*, states the current rule. diff --git a/docs/adr/0207-a-single-use-enrolment-code-for-a-directory-account-s-first-engine-factor.md b/docs/adr/0207-a-single-use-enrolment-code-for-a-directory-account-s-first-engine-factor.md index 09a9630fa2..19eef6bcee 100644 --- a/docs/adr/0207-a-single-use-enrolment-code-for-a-directory-account-s-first-engine-factor.md +++ b/docs/adr/0207-a-single-use-enrolment-code-for-a-directory-account-s-first-engine-factor.md @@ -1069,3 +1069,13 @@ default `require_mfa` the floor already refused those actions, so only the off p THEN THE SYSTEM SHALL leave TOTP off and spend nothing in that ceremony. Where that factor was bound by a path that asks no code, the code stays unspent. → `tests/test_directory_enrolment_code.py` + +## Amendment (2026-11-24, BACKLOG #1149): session termination is refused to every factorless pending session + +This ADR refuses session termination to a factorless directory session and says the route +comments claiming "a no-factor user must remain able to revoke" no longer hold for that session +class. BACKLOG #1149 widened the refusal: under `[security].require_mfa` every MFA-pending session +is refused `session_terminate`, `save_ends_own_sessions` and `revoke_all_sessions`, local or +directory, factor or not, and those comments and the `docs/SECURITY.md` passages this ADR lists +were changed with it. At least the route rows for the terminate routes in `docs/SECURITY.md` still +read only "password-only step-up". The text above is kept as it was accepted. diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 63d335f187..716cab4a37 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -61,6 +61,7 @@ from messagefoundry.pipeline.cert_expiry import peer_cert_expiry from messagefoundry.redaction import safe_exc from messagefoundry.store.base import sealed_read_errors, store_call_errors +from messagefoundry.store.row_seal import TransitSealUnavailableError from messagefoundry.store.store import UserRecord log = logging.getLogger(__name__) @@ -1646,14 +1647,16 @@ async def _pending_holds_no_factor(auth: AuthService, token: str | None) -> bool keeps the verify wording. A session satisfied between the gate's read and this one also reads True, a wording slip on a refusal already decided. - The read only picks the wording, and the gate has already refused, so a store fault keeps the + The read only picks the wording, and the gate has already refused, so a store, seal or Transit + fault (at least the sealed-read set and ``TransitSealUnavailableError``) keeps the 403 and its ``X-MFA-Required`` with the verify wording rather than becoming a 500, as :func:`_step_up_refusal`'s wording read does (vault BACKLOG #3145 item 6).""" + faults: tuple[type[Exception], ...] = (*sealed_read_errors(), TransitSealUnavailableError) try: return not await auth.factor_binding_is_blocked(token, STEP_UP_ACTION_MFA_ENROLL) except AUDIT_WRITE_DEFECTS: raise - except store_call_errors() as exc: + except faults as exc: log.warning( "an MFA refusal could not read whether the account holds a factor (%s); it answers" " with the verify wording", diff --git a/messagefoundry_webconsole/routes/account.py b/messagefoundry_webconsole/routes/account.py index 5acf915697..ccbe4ff267 100644 --- a/messagefoundry_webconsole/routes/account.py +++ b/messagefoundry_webconsole/routes/account.py @@ -167,7 +167,8 @@ async def _no_code_posted(request: Request) -> bool: # Both terminate POSTs are body-less (all params in the PATH), so they register as auto_retry # continuations /ui/reauth may re-POST after a stale-window re-auth. step_up=False (password- # only, mirrors require_ui_reauth_only). A pending session does not pass the gate, with a factor -# (#1951) or without one under require_mfa, which is sent to enrol (#1149). permission=None. +# (#1951) or without one under require_mfa, which is sent to enrol (#1149); /ui/reauth sends it +# to enrol too, keyed on the action rather than on step_up. permission=None. # The two patterns do not overlap: the per-session pattern requires two more segments after # sessions/ (/revoke), so /ui/account/sessions/revoke-others (one segment) matches only itself. # BACKLOG #1149 (ASVS 7.5.2): both now carry an action= tag, the same treatment the factor lanes got diff --git a/messagefoundry_webconsole/routes/core.py b/messagefoundry_webconsole/routes/core.py index cc3fa6a79f..c48b8f3abd 100644 --- a/messagefoundry_webconsole/routes/core.py +++ b/messagefoundry_webconsole/routes/core.py @@ -60,6 +60,7 @@ from .. import pages from .._auth import ( _REAUTH_NEXT_MAX, + _SESSION_ENDING_UI_ACTIONS, CLEAR_SITE_DATA_HEADER, CLEAR_SITE_DATA_VALUE, ENROL_FIRST_PAGE, @@ -262,7 +263,9 @@ def _refusal_error(elevation: Elevation, fallback: str) -> str: return fallback -def _enrol_before_step_up(mfa: MfaStatus, *, satisfied: bool, step_up: bool) -> bool: +def _enrol_before_step_up( + mfa: MfaStatus, *, satisfied: bool, step_up: bool, ends_sessions: bool = False +) -> bool: """Whether the password ``/ui/reauth`` sends this session to enrol instead of rendering its form. True for a full-step-up action when the account holds no factor of EITHER kind (ADR 0068 @@ -270,8 +273,16 @@ def _enrol_before_step_up(mfa: MfaStatus, *, satisfied: bool, step_up: bool) -> deadlock guard: such a session can never pass the step-up, so the form would loop straight back (BACKLOG #3116). The account-rule half (``mfa.required``) is policy, not a deadlock: it sends a required-but-unenrolled account to enrol even when a stamp leaves its session satisfied. ``AuthService._unverified_session_owes_factor`` says when a session owes a factor - the account rule does not. Enrolment itself is ``step_up=False``, so it never bounces here.""" - if not step_up or mfa.enabled or mfa.webauthn_enrolled: + the account rule does not. Enrolment itself is ``step_up=False``, so it never bounces here. + + ``ends_sessions`` is a session-ending action (BACKLOG #1149). It is ``step_up=False``, but a + pending session with no factor is refused it, and a re-proof would mint it nothing, so that + session too is sent to enrol rather than shown a form.""" + if mfa.enabled or mfa.webauthn_enrolled: + return False + if ends_sessions and not satisfied: + return True + if not step_up: return False return mfa.required or not satisfied @@ -2068,9 +2079,23 @@ async def ui_reauth_form( # the IdP, so this page renders NO password field at all. Decided by the SESSION's # mechanism, not the account: a Kerberos session keeps the password form below. # Ahead of the enroll-first bounce; _reauth_idp_page says why. - return await _reauth_idp_page(auth, token, mfa, next_, action.step_up, continues) + # A session-ending action counts as a full step-up here, for the reason + # _enrol_before_step_up gives (BACKLOG #1149). + return await _reauth_idp_page( + auth, + token, + mfa, + next_, + action.step_up or action.action in _SESSION_ENDING_UI_ACTIONS, + continues, + ) satisfied = await auth.mfa_satisfied(token) - if _enrol_before_step_up(mfa, satisfied=satisfied, step_up=action.step_up): + if _enrol_before_step_up( + mfa, + satisfied=satisfied, + step_up=action.step_up, + ends_sessions=action.action in _SESSION_ENDING_UI_ACTIONS, + ): return RedirectResponse(ENROL_FIRST_PAGE, status_code=303) # The rendering splits BY FACTOR (decision 1(b)): the TOTP code field renders iff # TOTP is enrolled (a required-but-unenrolled account can never produce a code — @@ -2121,7 +2146,12 @@ async def ui_reauth(request: Request) -> Response: # continues_after_reauth is asked of `token` at each use, not once here: the code leg below # rotates it and re-keys the issued continuation onto the new token. satisfied = await auth.mfa_satisfied(token) - if _enrol_before_step_up(mfa, satisfied=satisfied, step_up=action.step_up): + if _enrol_before_step_up( + mfa, + satisfied=satisfied, + step_up=action.step_up, + ends_sessions=action.action in _SESSION_ENDING_UI_ACTIONS, + ): # Checked BEFORE the rate limiter so a correct password isn't burned into a 429 (the # review's silent-loop finding). test_ui_mfa_gate.py pins the order for the session half # with the budget denied. diff --git a/packaging/messagefoundry-webconsole/tests/test_webui_bulk.py b/packaging/messagefoundry-webconsole/tests/test_webui_bulk.py index cd7e14e697..16729486ee 100644 --- a/packaging/messagefoundry-webconsole/tests/test_webui_bulk.py +++ b/packaging/messagefoundry-webconsole/tests/test_webui_bulk.py @@ -116,7 +116,8 @@ async def test_revoke_others_stale_bounces_to_reauth(engine: Engine) -> None: def test_session_terminate_actions_registered_password_only() -> None: # Both terminate POSTs are registered auto_retry continuations (so /ui/reauth can re-POST them), - # step_up=False (password-only) so a no-factor session is never deadlocked out of revoking. + # step_up=False (password-only). A pending session with no factor is still sent to enrol by + # /ui/reauth (BACKLOG #1149), which keys on the action rather than on this flag. from messagefoundry_webconsole import is_safe_ui_action, lookup_ui_action assert is_safe_ui_action("/ui/account/sessions/revoke-others") is True @@ -129,13 +130,27 @@ def test_session_terminate_actions_registered_password_only() -> None: assert is_safe_ui_action("/ui/account/sessions/revoke-others/extra") is False # extra segment -async def test_revoke_reauth_only_no_mfa_deadlock(engine: Engine) -> None: - # A require_mfa but UNENROLLED cookie session under a stale window: GET /ui/reauth?next= - # renders the PASSWORD reauth form (200), NOT the enroll_first divert — the step_up=False - # registration keeps a no-factor user out of the enroll-loop so they can still revoke. +async def test_revoke_reauth_sends_a_no_factor_pending_session_to_enrol(engine: Engine) -> None: + # BACKLOG #1149: a require_mfa but UNENROLLED cookie session is MFA-pending, and a terminate is + # refused to it whatever it proves, so GET /ui/reauth?next= sends it to enrol rather + # than rendering a password form whose re-proof would mint nothing. It is not deadlocked: the + # enrolment it is sent to satisfies the session, after which the terminate works. service = AuthService(engine.store, AuthSettings(require_mfa=True, step_up_max_age_seconds=-1)) await service.initialize() await _add(service, "op", Role.OPERATOR) + async with _client(engine, service) as c: + await _cookie_login(c, "op") + r = await c.get("/ui/reauth", params={"next": "/ui/account/sessions/revoke-others"}) + assert r.status_code == 303 + assert r.headers["location"] == "/ui/account?m=enroll_first" + + +async def test_revoke_reauth_stays_password_only_when_no_factor_is_owed(engine: Engine) -> None: + # The control for the test above: with require_mfa off the same no-factor session owes nothing, + # so /ui/reauth renders the PASSWORD form (200, no code field), as before BACKLOG #1149. + service = AuthService(engine.store, AuthSettings(require_mfa=False, step_up_max_age_seconds=-1)) + await service.initialize() + await _add(service, "op", Role.OPERATOR) async with _client(engine, service) as c: await _cookie_login(c, "op") r = await c.get("/ui/reauth", params={"next": "/ui/account/sessions/revoke-others"}) diff --git a/tests/test_mfa_access_gate.py b/tests/test_mfa_access_gate.py index a1ee2aba71..79b9a29893 100644 --- a/tests/test_mfa_access_gate.py +++ b/tests/test_mfa_access_gate.py @@ -41,6 +41,8 @@ from messagefoundry.config.settings import AuthSettings, EgressSettings from messagefoundry.pipeline import Engine from messagefoundry.store import MessageStore +from messagefoundry.store.crypto import CipherError +from messagefoundry.store.row_seal import TransitSealUnavailableError from messagefoundry.store.store import WebAuthnCredential from tests._admin_account import create_admin, create_local_user_chosen from tests._enrolment_code import enrolment_code_for @@ -735,16 +737,26 @@ async def test_the_access_gate_names_enrolment_to_a_pending_session_with_no_fact ) +@pytest.mark.parametrize( + "fault", + ( + OSError("synthetic store fault"), + TransitSealUnavailableError(), + CipherError("synthetic undecryptable row"), + ), + ids=("store", "transit", "cipher"), +) async def test_a_store_fault_on_the_wording_read_keeps_the_mfa_refusal( - engine: Engine, monkeypatch: pytest.MonkeyPatch + engine: Engine, monkeypatch: pytest.MonkeyPatch, fault: Exception ) -> None: - """RED when: the read that picks the refusal's wording is unguarded, so a store fault there - turns the 403 + ``X-MFA-Required`` into a 500. The fault answers with the verify wording.""" + """RED when: the read that picks the refusal's wording lets a store, seal or Transit fault + through, so the 403 + ``X-MFA-Required`` becomes a 500. The fault answers with the verify + wording.""" service = await _service(engine) await _add(service, "fresh", Role.VIEWER) async def broken(*_: object, **__: object) -> bool: - raise OSError("synthetic store fault") + raise fault async with _client(engine, service) as c: tok = await _login(c, "fresh") From 7e91397ce2759ce98ac3412b130d50b9660a516e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:50:05 -0600 Subject: [PATCH 5/5] Docs: text fixes from the last review round on the no-factor pending refusal The pending-session reach names the mfa_gate=False routes too; the Kerberos revoke note splits the factor and no-factor cases; the ADR 0077 note states the wording per case; the wording-read docstring names the faults it catches. BACKLOG #1149 --- docs/SECURITY.md | 11 +++++++---- docs/adr/0077-action-bound-step-up.md | 11 ++++++----- messagefoundry/api/security.py | 9 +++++---- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index f581ee95b5..5e70ad47f5 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -6418,8 +6418,10 @@ engine bounds its own sessions with short caps, and the reconciler carries direc default), a Kerberos session can give that step-up only by password. So a Kerberos session on a passwordless or smartcard-only account cannot end its other sessions this way. Under `[security].require_mfa` a Kerberos session that has proven no engine factor is MFA-pending, - and `DELETE /me/sessions` refuses it whatever it proves until it enrols one, which for a - directory account needs an administrator-issued enrolment code (ADR 0207, BACKLOG #1149). Until + and `DELETE /me/sessions` refuses it whatever password it proves. On an account that holds an + engine factor it proves that factor at `POST /auth/mfa-verify` first; on one with no factor it + enrols one, which for a directory account needs an administrator-issued enrolment code + (ADR 0207, BACKLOG #1149). Until then an administrator ends those sessions with `DELETE /users/{user_id}/sessions`; - end sessions in bulk with `DELETE /sessions`, which keeps the caller's current session only when the revoke re-stamps it and otherwise ends it too, or from the host with @@ -6465,8 +6467,9 @@ factor, which `[security].require_mfa` covers, is refused the same way (BACKLOG no step-up mints it a `session_terminate`, `save_ends_own_sessions` or `revoke_all_sessions` grant, the JSON terminate routes answer `403` + `X-MFA-Required` with a detail that names enrolment, and the console twins send it to `/ui/account?m=enroll_first`, as does `/ui/reauth` when asked to -re-prove for a terminate. It may still reach at least enrolment and sign-out; `_MFA_EXEMPT_ROUTES` -in `api/security.py` holds the JSON routes a pending session reaches. This refusal adds a step, +re-prove for a terminate. It may still reach at least enrolment and sign-out. On the JSON plane +a pending session reaches at least the routes in `_MFA_EXEMPT_ROUTES` in `api/security.py` and +the routes whose gate passes `mfa_gate=False`; enrolment is one of the latter. This refusal adds a step, not a bar, against a holder of a local account's password alone: that holder may enrol a factor of its own first, which satisfies the session, and then end sessions. A directory account's first enrolment needs an administrator-issued enrolment code (ADR 0207), so there it holds. diff --git a/docs/adr/0077-action-bound-step-up.md b/docs/adr/0077-action-bound-step-up.md index 3a0e8d41cd..ec9d59b2c6 100644 --- a/docs/adr/0077-action-bound-step-up.md +++ b/docs/adr/0077-action-bound-step-up.md @@ -270,12 +270,13 @@ authority on which gate each route uses today. ## Amendment (2026-11-24, BACKLOG #1149 — ASVS 7.5.2): no pending session terminates -The 2026-07-17 amendment above says the terminate routes stay password-only "so a no-factor user -can still revoke". That no longer holds under `[security].require_mfa`. A session on an account +The first 2026-07-17 amendment above (ASVS 7.5.2) says the terminate routes stay password-only "so +a no-factor user can still revoke". That no longer holds under `[security].require_mfa`. A session on an account with no factor that the requirement covers is MFA-pending, and `session_terminate`, `save_ends_own_sessions` and `revoke_all_sessions` are refused to every pending session, whether -or not the account holds a factor: no step-up mints those grants, the JSON terminate routes answer -`403` + `X-MFA-Required` with a detail naming enrolment, and the console sends the session to -enrolment. The routes keep their password-only, action-bound gate. The text above is kept as it +or not the account holds a factor: no step-up mints those grants, and the JSON terminate routes +answer `403` + `X-MFA-Required`. For a session with no factor the detail names enrolment and the +console sends it to enrolment; one that holds a factor keeps the verify wording and is sent to +prove that factor. The routes keep their password-only, action-bound gate. The text above is kept as it was accepted; this note governs where they differ. `docs/SECURITY.md`, under *Session inventory & targeted revocation*, states the current rule. diff --git a/messagefoundry/api/security.py b/messagefoundry/api/security.py index 716cab4a37..c59a5f3ad8 100644 --- a/messagefoundry/api/security.py +++ b/messagefoundry/api/security.py @@ -1647,10 +1647,11 @@ async def _pending_holds_no_factor(auth: AuthService, token: str | None) -> bool keeps the verify wording. A session satisfied between the gate's read and this one also reads True, a wording slip on a refusal already decided. - The read only picks the wording, and the gate has already refused, so a store, seal or Transit - fault (at least the sealed-read set and ``TransitSealUnavailableError``) keeps the - 403 and its ``X-MFA-Required`` with the verify wording rather than becoming a 500, as - :func:`_step_up_refusal`'s wording read does (vault BACKLOG #3145 item 6).""" + The read only picks the wording, and the gate has already refused, so the faults caught here + (the sealed-read set and ``TransitSealUnavailableError``) keep the 403 and its + ``X-MFA-Required`` with the verify wording rather than becoming a 500, the rule + :func:`_step_up_refusal`'s wording read follows for store faults (vault BACKLOG #3145 item 6). + ``TransitSealUnverifiableError`` is not in the set.""" faults: tuple[type[Exception], ...] = (*sealed_read_errors(), TransitSealUnavailableError) try: return not await auth.factor_binding_is_blocked(token, STEP_UP_ACTION_MFA_ENROLL)