From aa3b0b0495c9e4d2ccbe0fb90c7facb73fd6c11c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:17:52 -0600 Subject: [PATCH 1/3] Session lineage: stamp and measure the window on the store's own clock ASVS 7.2.4 arm (ii). A link's retired_at was the elevating process's time.time() and the window was measured from the signing-in process's, so a forward step of the signing-in clock, or skew between engine hosts, dropped a link inside the real window and left the rotated session live. Every backend now stamps retired_at from the database clock in the link INSERT, and the lineage read and the reaper purge measure the window back from that same clock (SQLite julianday('now'), Postgres statement_timestamp(), SQL Server SYSUTCDATETIME()). The store API takes a window length (lineage_seconds) instead of an instant (lineage_since); rotate_session takes no now. The sign-out asks for its 5 s plus the time since its proof. Residual, stated in SECURITY.md and ADR 0210 Amendment B: a step of the store's own clock still moves the window (on SQLite, the clock of the host holding the file). Tests: a 425 s-class forward step of the signing-in process no longer drops a link (SQLite, service and logout); the store contract now checks the window and purge ignore the caller's now on all three backends; tests that aged a link by patching time.time now age it in the store. BACKLOG #4276 --- docs/SECURITY.md | 20 ++++-- ...ows-a-time-bounded-retired-hash-lineage.md | 18 +++++ docs/adr/README.md | 2 +- messagefoundry/api/app.py | 6 +- messagefoundry/auth/service.py | 28 +++++--- messagefoundry/store/base.py | 28 ++++---- messagefoundry/store/postgres.py | 44 ++++++------ messagefoundry/store/session_lineage.py | 23 +++++-- messagefoundry/store/sqlserver.py | 42 +++++++----- messagefoundry/store/store.py | 55 +++++++++------ .../tests/test_ui_logout_affordance.py | 15 ++-- tests/_logout_rows.py | 12 ++++ tests/_session_rotation_contract.py | 48 +++++++------ tests/test_session_sql_placeholders.py | 2 +- tests/test_session_supersession.py | 50 +++++++++++--- tests/test_session_supersession_lineage.py | 68 ++++++++++++++++--- 16 files changed, 326 insertions(+), 135 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 683b84c934..ddc326ee48 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -6580,8 +6580,11 @@ as before this change: - a sign-in that runs past the bound, which a slow identity provider or directory can cause, since their timeouts bound each call and not the whole sign-in; - more than 32 elevations on one session inside the bound; -- a wall clock that stepped between the elevation and the sign-in, which moves the bound by the - size of the step, in either direction. +- a step of the store's own clock between the elevation and the sign-in, which moves the bound by + the size of the step, in either direction. The store stamps each link and measures the bound on + that one clock (vault BACKLOG #4276): the database server's on PostgreSQL and SQL Server, and + on SQLite the clock of the host that holds the database file. So a step of an engine process's + clock, or skew between engine hosts that share the store, does not move the bound. **A retired token authenticates nothing.** No session read, the validator included, consults the links; only a revoke follows them, at a sign-in's supersession or at a sign-out (below). For the @@ -6591,23 +6594,26 @@ it can only end a session, never open or extend one. Whoever held that token bef could already end the session with `POST /auth/logout`; the link lets them do it for the length of the bound after the elevation too, through a sign-in whose first credential passes; with MFA required, the supersession runs when the password-only session is minted, before the second factor, -so a password alone is enough. A wall -clock that stepped forward at the elevation, or back before the sign-in, lengthens that time by the -step; the reaper's clock-step guard covers its own purge, not this. The links are not under the session integrity seal (BACKLOG #2592): a forged link can only direct a +so a password alone is enough. A store +clock that stepped back between the elevation and the sign-in lengthens that time by the step; the +reaper's clock-step guard reads the engine's clock, and covers neither this nor the purge of links, +which the store measures on its own clock. The links are not under the session integrity seal (BACKLOG #2592): a forged link can only direct a revoke, and a revoke needs no key on any backend. **A sign-out follows the links too, for far less time (BACKLOG #3715).** An elevation in another tab can re-key the session while a sign-out is in flight, and the sign-out then ends the session under its new token, in the same transaction as the revoke. `POST /auth/logout` follows links written up to 5 seconds before its request arrived; the slack covers a link stamped before its -rotation commits, and clocks that differ between engine processes. Its sign-in check proved the +rotation commits. The store measures that window back from its own clock, which stamps the link +too, as the bound plus the time since the request arrived on the engine's clock, so clocks that +differ between engine processes do not move it. Its sign-in check proved the token live after the request arrived, so any link from it was written after that proof, and the route gains no reach. `/ui/logout` carries no credential, so it follows links written up to 5 seconds before the call. **That is a separate power, credential-free and end-only:** for 5 seconds after an elevation, anyone who presents the RETIRED token to `/ui/logout` ends the session it became, with no sign-in. It cannot open or extend a session. At least these cases stay open, and the session lives on under its new token: an elevation older than the bound, more than 32 -elevations in a row inside it, and a wall clock that stepped between the elevation and the +elevations in a row inside it, and a step of the store's own clock between the elevation and the sign-out, which moves the bound by the step. The `auth.logout` row names the session's owner as actor, its `outcome` is `revoked`, and a `presented` field holds the hash that was presented. The `outcome` is `lapsed` instead when the session's own clock checks fail at the diff --git a/docs/adr/0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md b/docs/adr/0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md index 7e39636ee6..e5ff93c19e 100644 --- a/docs/adr/0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md +++ b/docs/adr/0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md @@ -124,3 +124,21 @@ proves nothing and measures it from the call, so a retired token gains a SECOND one under Consequences: for 5 seconds after an elevation, presented to `/ui/logout` with no credential, it ends the session it became. It still cannot open or extend one. `docs/SECURITY.md` states both powers. `revoke_own_session` still follows no link. + +## Amendment B (2026-11-24): the store's own clock stamps and measures the window + +Vault BACKLOG #4276, ASVS 7.2.4 arm (ii). Under Decision 3 and the stated limits above, the link was +stamped with the elevating process's `time.time()` and the window measured from the signing-in +process's, so a forward step of the signing-in process's clock, or a sign-in host whose clock ran +ahead of the elevating one, dropped a link inside the real window. Now every backend stamps +`retired_at` from the database's own clock in the link's INSERT, and the walk's lineage read and +the reaper's purge measure the window back from that same clock: SQLite's `julianday('now')`, +Postgres `statement_timestamp()`, SQL Server `SYSUTCDATETIME()`. Decision 3's bound is now a +length, `lineage_seconds`, not an instant, `lineage_since`, and `rotate_session` takes no `now`. +The sign-out asks for its 5 seconds plus the time since its proof on the engine's clock: two +readings of one process's clock, never compared with a stamp. + +What this closes: a step of an engine process's clock, and skew between engine hosts sharing one +store, no longer move the window. What stays: a step of the store's own clock between the elevation +and the sign-in still moves it by the step. On SQLite that is the clock of the host that holds the +database file. `docs/SECURITY.md` states both. diff --git a/docs/adr/README.md b/docs/adr/README.md index 095683fed3..5b2b4ad5e0 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -232,7 +232,7 @@ what is withheld and what you can request. | [0207](0207-a-single-use-enrolment-code-for-a-directory-account-s-first-engine-factor.md) | **A single-use enrolment code for a directory account's first engine factor** (vault BACKLOG #2609, closing item 2; the decision ADR 0142 Amendment C left open) -- a directory account's first engine factor is bound only with a single-use enrolment code an Administrator issues and hands over out of band. Required at the step that binds and stamps (`confirm_mfa_enrollment`, `finish_webauthn_registration`) when the account is `ad`, holds no engine factor, and the session is not stamped MFA-verified: so every Kerberos session and a federated one with the claim gate off, never a claim-gated federated one. That step also refuses an account that now holds a factor. That re-check (both checks on the passkey leg; on the TOTP leg, a passkey, with a TOTP enabled meanwhile left to the compare-and-set), the TOTP enable bound to the verified secret, and the passkey finish route's per-actor attempt budget have since shipped (BACKLOG #3014, #3025, #3061). Amendment A (2026-10-27) adds: once owner ruling A5 removes the directory re-bind, the code is a factorless directory session's re-proof at the binding step, the enrolment begins and the TOTP confirm form are admitted with no grant, and every other step-up action stays refused until a factor exists; the code is read after the directory re-lookup, and on the TOTP leg is spent in the enable's own conditional write, after the stamp, rather than before it; the host command refuses a SQLite store an engine holds, a file that is not a store, and a store the probe cannot check; and the issuing Administrator is told when a code is spent. Disabling the account clears an outstanding code, and every refused code gets one client-facing reply. The handover is the control, so it must leave the directory: an Administrator checks who is asking and never replies through the account's own mail or chat. The rule reads no session mechanism and no `kerberos_enabled`, and holds with `require_mfa` on or off. At least 128 bits, stored as its SHA-256 digest, one per account, 24 hours, spent by one conditional write (before the credential write on the passkey leg, in the enable's write on the TOTP leg). Issued by an Administrator behind step-up, never for the caller's own account, also by an MFA reset of a directory account, and, for a site where no Administrator can issue one, by a host command on `admin-unlock`'s gate, which is not BACKLOG #2711's outage recovery. Rejected: password only, a TOTP-on-directory-password shortcut, an emailed link, a short Argon2 code, gating on the mechanism | **Accepted (2026-10-27)**; Amended (A, 2026-10-27) -- accepted by the batch 447 Manager under the Owner's delegation of 2026-10-27 (CLAUDE.md section 5, owner ruling 2026-10-22), after two adversarial reviews; that delegation record is the owner's ruling. Proposed (2026-10-05), doc-only, drafted on the owner's direction. The code with `require_mfa` off is answered yes (Amendment A). Open: a fixed lifetime, a code from an MFA reset, and the host command's reach. Severity conditional per CLAUDE.md section 0 | | [0208](0208-a-theia-desktop-app-gives-interface-analysts-a-simpler-steps-only-editor.md) | **A Theia desktop app gives interface analysts a simpler Steps-only editor** (owner rulings and Manager decisions of 2026-10-07; rewrites the uncommitted 2026-10-02 hosted-Theia drafts after two four-lens reviews) -- two Electron builds sharing one native Theia Steps extension: an analyst build capped at the Steps level, and a developer build that is a full IDE with a Steps / Split / Code switch and no per-user limits. The purpose is a simpler interface, not enforcement. The analyst build signs in to the engine, clears every session gate, proves the session on a non-exempt route at start-up and before each save, and turns on editing only for `code:steps` (new, advisory, read by the editor only) or `code:edit`. That role check is the primary control and a guardrail: the developer build, VS Code and any other tool are outside it. An optional repository check classifies a change as Steps-only by comparing `code` rows, every control header and each typed row's full statement against base, and passes anything else only with a `code:edit` reviewer's approval of the head commit; it holds against a deliberate change only when run from a definition the change cannot edit. Analyst Test takes a generator spec and never passes `--show-phi`. Review R1 is a precondition answered by the R1 fix and a typed-only `lens rewrite` mode the analyst build always sets; both landed in PR 2155 (2026-10-08). Analyst is a built-in role. The analyst build drops three ADR 0076 guardrails (Amendment G). Hosting is deferred to its own ADR. Rejected: a filtered `@theia/plugin-ext` analyst build, per-user limits in the developer build, VS Code for analysts, a Steps editor in the web console. Spec: [`docs/design/theia-analyst-editor.md`](../design/theia-analyst-editor.md) | **Proposed (2026-10-07)** -- doc-only, no editor code. Merging records it as Proposed and accepts nothing; Accepted needs the owner. Licence AGPL-3.0-or-later (owner ruling). Open: spikes S-1 to S-4 (S-1 is met except its Test and language-server legs, measured on a browser target; S-2 is met on the browser build and on Electron, spike S-2b; S-4's classifier half is met by a prototype and its base-ref workflow half is untested), the start-up probe route (an implementation detail), and the differences ADR 0076 Amendment G, G.7, records between PR 2155's lens code and its rules | | [0209](0209-mllp-and-tcp-deliveries-refuse-a-payload-holding-more-than-one-msh.md) | **MLLP and TCP deliveries refuse a payload holding more than one MSH** (vault BACKLOG #2858; the outbound decision ADR 0206 rule 5 deferred) -- an MLLP or TCP delivery refuses a payload that opens with `MSH` and holds a second `MSH` line, CR or LF line ends alike, as `NegativeAckError(permanent=True)` with code `multiple-messages` and content-free text. The check sits in `check_frame_bytes`, so a live send, each batch member (judged as stored) and a shadow outbound give one answer; the ingress guard's reading moves to `parsing/split.py`, beside the delivery's, and a test holds the two to one answer. No batch-sender opt-out: ADR 0082's `BHS` envelope is the batch path and is never read, nor is an X12 relay or any payload not led by `MSH`. HTTP and File outbounds are out of scope. Rejected: a declared batch sender, splitting into N frames, refusing on every outbound, a `check_frame`-only check | **Accepted (2026-10-17, on build)** -- decision delegated by the owner under the driver rule and taken by the batch 265 Manager; the owner may overrule at review. Built with the change. Severity conditional per CLAUDE.md section 0 | -| [0210](0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md) | **Session supersession follows a time-bounded retired-hash lineage** (vault BACKLOG #3028; extends #2146, engine PR 2028) -- each session rotation writes a `session_lineage` link (retired hash, successor hash, `retired_at`) in its own transaction, on SQLite, Postgres and SQL Server. The login supersession follows those links over any number of hops (at most 32) to the live end and revokes it in the same transaction, for `oidc_flow_ttl_seconds` plus 120 seconds after each rotation; the session reaper purges older links. No session read consults the table, so a retired hash authenticates nothing; a test pins the readers per backend. The links are unsealed, because a forged one can only direct a revoke, which needs no key. One shared walk, so #3029 can reuse it. Rejected: a `previous_hash` column, a revoked tombstone row, a per-sign-in start-time bound. Open: an elevation older than the window, such as a second holder's, is not followed. Amendment A (2026-10-28, BACKLOG #3715): the sign-out follows them too, for 5 seconds, which gives a retired token a second, credential-free end-only power on `/ui/logout` | **Accepted (2026-10-17, on build)** -- design set by the batch 257 Manager's brief; the owner may overrule at review. Severity conditional per CLAUDE.md section 0 | +| [0210](0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md) | **Session supersession follows a time-bounded retired-hash lineage** (vault BACKLOG #3028; extends #2146, engine PR 2028) -- each session rotation writes a `session_lineage` link (retired hash, successor hash, `retired_at`) in its own transaction, on SQLite, Postgres and SQL Server. The login supersession follows those links over any number of hops (at most 32) to the live end and revokes it in the same transaction, for `oidc_flow_ttl_seconds` plus 120 seconds after each rotation; the session reaper purges older links. No session read consults the table, so a retired hash authenticates nothing; a test pins the readers per backend. The links are unsealed, because a forged one can only direct a revoke, which needs no key. One shared walk, so #3029 can reuse it. Rejected: a `previous_hash` column, a revoked tombstone row, a per-sign-in start-time bound. Open: an elevation older than the window, such as a second holder's, is not followed. Amendment A (2026-10-28, BACKLOG #3715): the sign-out follows them too, for 5 seconds, which gives a retired token a second, credential-free end-only power on `/ui/logout`. Amendment B (2026-11-24, vault BACKLOG #4276): the database's own clock stamps each link and measures the window, so an engine clock step or skew between engine hosts no longer moves it; a step of the store's own clock still does | **Accepted (2026-10-17, on build)** -- design set by the batch 257 Manager's brief; the owner may overrule at review. Severity conditional per CLAUDE.md section 0 | | [0211](0211-afk-autonomy-controls-decision-log-kill-switch-tripwires-digest.md) | **AFK-autonomy controls: decision log, kill switch, tripwires, digest** (docs/AUTONOMY-PLAN.md section 4, wave 1) -- the decision log is one private vault issue per UTC day with one comment per record, spooled locally first so a network failure loses nothing and the tripwire hook logs offline; the record schema (class, predicates with evidence, recommendation, alternatives, undo path, stated confidence, reviewed, outcome). The kill switch is the repository variable `MEFOR_AFK_KILL`, read over REST and fail-safe: only `off` is OFF, and a SessionStart banner shows ON. A non-blocking tripwire hook in the shell-guard dispatcher records `--no-verify`, force pushes, ref deletions, `reset --hard`, `-Force` on remove.ps1 or claim.ps1, `-AllowOrphanedAllocations` and a write to the kill switch; it does not stop the act, so section 4.4 is not met, and the other section 4.4 tripwires are rules only. Who rates and who sets the switch are rules only: every seat holds one identity. A private daily digest carries a blind sample with the recommendation hidden, owner ratings, and per seat and class the trailing-60 disagreement and 14-day reversal rate. Rejected: a JSONL file in the vault, a local file alone | **Accepted (2026-10-21, on build)** -- the owner approved the plan on 2026-10-21; storage, schema and the enforcement split are this build's design, and the owner may overrule at review. **Amended 2026-10-22:** the `-Banner` hook also tells non-Special sessions to load driver and empower while the switch reads OFF; the ON banner does not. Open: the owner or Lander sets `MEFOR_AFK_KILL` to `off`; until then every session reads ON | | [0212](0212-enterworktree-safety-check.md) | **EnterWorktree safety check** (owner request in session, 2026-10-21) -- a PreToolUse hook on `EnterWorktree` runs the read-only `scripts/worktree/enter-check.ps1` and shows its verdict in the owner's permission prompt: `ask` with a reason starting `enter-check: SAFE` or `enter-check: UNSAFE` and the first reasons. It never allows and never denies, and annotates only a prompt the harness shows anyway (ADR section 2 says where); on the local OFF file or any fault it returns no decision. SAFE needs six checks to pass, listed in the ADR: in short, a session's own scratchpad worktree, at an untouched commit of the remote's `main`, entered from outside any primary. Auto-allow is deferred until the allow comes from an installed copy outside session-writable trees: the hook and check run from the session's own tree, and the reviews found at least twelve SAFE-when-unsafe paths, at least ten still open, those found listed in the ADR. Silence per machine with the OFF file, or permanently by removing the settings entry. Rejected: allowing `.claude/worktrees/`, `-like` matching, a list of protected paths, a fail-open check, `allow` on SAFE, `deny` on UNSAFE | **Accepted (2026-10-21, on build; advisory 2026-10-22)** -- the owner asked for it in session; the Manager set the design and, after the third review pass, made the hook advisory (class B); the owner may overrule at review | | [0213](0213-seal-the-secret-rotation-fingerprint-as-a-store-cipher-cell.md) | **Seal the secret-rotation fingerprint as a store-cipher cell** (vault BACKLOG #3472, #3247 item 1) -- each non-DEK `secret_rotation_meta.fingerprint` becomes a store-cipher cell holding a per-row random HMAC key, the value's MAC and the row's class id, AAD-bound to its row and stored behind the `sealed-hmac-sha256-32` tag. `rotate-key`'s `reencrypt_to_active` re-seals it on all three backends, so a store key rotation no longer moves every fingerprint and no start needs the retired key. A cell the engine cannot read, and every pre-#3472 row, keeps its dates: an old row never resets a clock. `vault_transit` stays off (#3473). Supersedes the #2242 re-key rule and removes the DEK-derived fingerprint key. Rejected: carrying retired fingerprint keys forward (A, the fallback), a random per-store key, recomputing in `rotate-key`, a non-rotating derivation | **Accepted (2026-10-26)** -- owner ruling 2026-10-26, in session (batch 343 Manager), option "S: seal as cipher cell"; built with the change | diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index b4bff70fae..73c464db26 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -12236,8 +12236,10 @@ async def _session_reaper( ``_SESSION_REAP_INTERVAL``, until the task is cancelled. With ``idle_seconds`` given, idle-expired rows go too (BACKLOG #2096); the lifespan passes the idle timeout the validator uses. With ``lineage_seconds`` given, session lineage links older than that go too (vault - BACKLOG #3028); the lifespan passes the window the supersession follows them for. Purging as of - the earlier instant below only keeps a link longer, never shortens that window. + BACKLOG #3028); the lifespan passes the window the supersession follows them for. The store + measures that age on its own clock, the one the supersession measures its window on (vault + BACKLOG #4276), never from the ``now`` passed below, so the guard below does not cover the + links and need not: the purge drops only a link the supersession would no longer follow. **The reaper skips a pass when the wall clock has jumped forward (BACKLOG #2283).** The purge judges expiry and idleness by the wall clock, and its deletes cannot be undone. Run just after diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 692c4e0fc4..aa894a94ae 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -13540,7 +13540,7 @@ async def _report_ended_session(self, ref: str) -> None: ) async def _supersede_session( - self, token_hash: str, *, now: float, lineage_since: float | None = None + self, token_hash: str, *, now: float, lineage_seconds: float | None = None ) -> SessionRecord | _EndedUnread | None: """The store's ``supersede_session``. A row it ended that then did not parse (BACKLOG #5505) is reported, as :meth:`_session_seal_failed` reports one, and answered as @@ -13549,7 +13549,7 @@ async def _supersede_session( fault in that report is logged, not raised, for the same reason.""" try: return await self._store.supersede_session( - token_hash, now=now, lineage_since=lineage_since + token_hash, now=now, lineage_seconds=lineage_seconds ) except RevokedRowSealError as exc: try: @@ -14672,8 +14672,10 @@ async def logout( transaction as the revoke. There is no read before the revoke: a read through :meth:`_load_session` ends and reports a row whose seal fails, so the revoke would then record ``nothing_to_revoke`` for a session this call ended. Links retired up to - :data:`_LOGOUT_LINEAGE_SECONDS` before ``proven_at`` are followed. The slack covers a link - stamped before its rotation commits, and clocks that differ between engine processes. + :data:`_LOGOUT_LINEAGE_SECONDS` before ``proven_at`` are followed. The store measures that + window back from its own clock, which also stamps every link (vault BACKLOG #4276), so it + asks for the bound plus the time since ``proven_at`` on this process's clock. The slack + covers a link stamped before its rotation commits. ``proven_at`` has no default, so every caller states what it proved. ``POST /auth/logout`` passes the moment its request arrived. Its gate proved the token live after that, so any @@ -14725,8 +14727,13 @@ async def logout( return "nothing_to_revoke" presented = hash_token(token) before = time.time() - since = (before if proven_at is None else proven_at) - _LOGOUT_LINEAGE_SECONDS - ended = await self._supersede_session(presented, now=before, lineage_since=since) + # A length back from the store's own clock (vault BACKLOG #4276): the bound, plus the time + # since the proof. That time is two readings of this process's clock, never compared with a + # link's stamp; a step backward between them is read as no time at all. + elapsed = 0.0 if proven_at is None else max(0.0, before - proven_at) + ended = await self._supersede_session( + presented, now=before, lineage_seconds=_LOGOUT_LINEAGE_SECONDS + elapsed + ) if isinstance(ended, SessionRecord): self._forget_reproof_counts((ended.token_hash,)) if ended is None: @@ -15012,7 +15019,10 @@ async def _supersede_session_hash(self, prior_hash: str, *, client: str | None) federated leg the presented hash was read at the start leg, before the identity provider's round trip. The presented hash then names no session. The store follows the lineage links each rotation wrote to the session's live end and revokes that, in the same transaction. - Only links retired within :attr:`supersession_lineage_seconds` of now are followed. This and + Only links retired within :attr:`supersession_lineage_seconds` of now, on the store's own + clock, are followed: the store stamps each link and measures the window on that one clock + (vault BACKLOG #4276), so this process's clock, and skew between engine hosts, do not move + the bound. A step of the store's own clock still does. This and :meth:`logout` are the only places a retired hash leads anywhere, and it leads only to an end. An elevation that finished longer ago than that, such as one a second holder of the token completed @@ -15021,8 +15031,10 @@ async def _supersede_session_hash(self, prior_hash: str, *, client: str | None) followed, the hash that was presented. """ before = time.time() + # The window is a length, measured back from the store's own clock (vault BACKLOG #4276), + # so a step of this process's clock cannot drop a link inside it. prior = await self._supersede_session( - prior_hash, now=before, lineage_since=before - self.supersession_lineage_seconds + prior_hash, now=before, lineage_seconds=self.supersession_lineage_seconds ) if isinstance(prior, SessionRecord): self._forget_reproof_counts((prior.token_hash,)) diff --git a/messagefoundry/store/base.py b/messagefoundry/store/base.py index c00ad0c9c2..90901fc2eb 100644 --- a/messagefoundry/store/base.py +++ b/messagefoundry/store/base.py @@ -3516,9 +3516,7 @@ async def list_sessions( async def touch_session(self, token_hash: str, *, now: float | None = None) -> None: ... - async def rotate_session( - self, token_hash: str, *, new_token_hash: str, now: float | None = None - ) -> bool: + async def rotate_session(self, token_hash: str, *, new_token_hash: str) -> bool: """Re-key a live session to ``new_token_hash``, in place (ASVS 7.2.4). A pure re-key: every other column — ``user_id``, ``created_at``, ``expires_at``, ``client``, @@ -3542,8 +3540,9 @@ async def rotate_session( so it must be able to fail closed if the session died underneath it. **A re-key that lands also records a lineage link, in the SAME transaction** (vault BACKLOG - #3028, ADR 0210): ``token_hash`` retired, replaced by ``new_token_hash``, stamped with - ``now`` or, when that is ``None``, the time the re-key landed, after any wait. The + #3028, ADR 0210): ``token_hash`` retired, replaced by ``new_token_hash``, stamped with the + DATABASE's own clock when the link's statement runs, after any wait, and never with an + engine process's clock (vault BACKLOG #4276; ``store/session_lineage.py`` says why). The session row itself carries nothing of its old hash, so the old hash still resolves to nothing. The link's one reader is :meth:`supersede_session`; ``store/session_lineage.py`` says why it is unsealed. A re-key that did not land writes no link. @@ -3600,7 +3599,7 @@ async def mark_session_mfa_verified( async def revoke_session(self, token_hash: str, *, now: float | None = None) -> None: ... async def supersede_session( - self, token_hash: str, *, now: float, lineage_since: float | None = None + self, token_hash: str, *, now: float, lineage_seconds: float | None = None ) -> SessionRecord | None: """Revoke the unrevoked session ``token_hash`` names, or the one it became, and return its row as revoked. @@ -3617,16 +3616,19 @@ async def supersede_session( first, the row is revoked and the rotation's ``revoked_at IS NULL`` guard refuses it, so the rotation fails closed. - **A rotation that committed FIRST is followed, when ``lineage_since`` is given (vault + **A rotation that committed FIRST is followed, when ``lineage_seconds`` is given (vault BACKLOG #3028, ADR 0210).** The presented hash then names no row, so the revoke steps along the links :meth:`rotate_session` wrote, up to ``LINEAGE_MAX_HOPS`` of them, and ends the - live end, inside one transaction. A link retired before ``lineage_since`` is not followed, - so a retired hash leads anywhere only for a bounded time; the caller chooses the bound, - because the store reads no settings. On Postgres and SQL Server a rotation can still commit + live end, inside one transaction. A link retired more than ``lineage_seconds`` before the + database's own clock, read in the walk's own statement, is not followed, so a retired hash + leads anywhere only for a bounded time; the caller chooses the bound, because the store + reads no settings. The stamp and the test read one clock, the database's, so neither an + engine process's clock step nor skew between engine hosts moves the bound (vault BACKLOG + #4276). ``now`` stamps only the revoke. On Postgres and SQL Server a rotation can still commit between two steps; it costs the walk one more step, never the revoke, because each step revokes before it reads a link. ``store/session_lineage.py`` says why that order is the control. With - ``lineage_since`` left ``None`` no link is followed, and a rotation that committed first + ``lineage_seconds`` left ``None`` no link is followed, and a rotation that committed first leaves this returning ``None``, as before. The lineage lookup lives here and nowhere else: no session READ follows a link, so a retired hash authenticates nothing. @@ -3781,7 +3783,9 @@ async def purge_expired_sessions( validator refuses them on presentation, so keeping them only grows the table. With ``lineage_seconds`` given, session lineage links retired more than that long before - ``now`` are deleted too (vault BACKLOG #3028). The supersession no longer follows them, so + the database's own clock are deleted too (vault BACKLOG #3028), never measured from + ``now``: the supersession measures its window on that clock (vault BACKLOG #4276), so the + two agree whichever engine process runs the purge. The supersession no longer follows them, so keeping them only grows the table. They are not counted in the return. The idle variant scans the table, because its ``OR`` reaches past the expiry index, and that diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index 1bfddad0f1..a47d70392b 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -1630,15 +1630,20 @@ def _pg_session_cap_keep_sql(split_mfa_pending: bool) -> str: " client=$6, reauth_at=$7, mfa_verified_at=$8, auth_mechanism=$9, idp_auth_time=$10," " user_epoch=$11, global_epoch=$12, seal=$13 WHERE token_hash=$14 AND seal=$15" ) -# Vault BACKLOG #3028: store.py's three session lineage statements respelled for `$n`. store.py says +# Vault BACKLOG #3028: store.py's three session lineage statements respelled for `$n`, stamping and +# measuring `retired_at` on this server's clock, `_PG_EPOCH_NOW` (vault BACKLOG #4276). store.py says # which method runs each, and that no other statement names the table. _PG_SESSION_LINEAGE_INSERT: Final = ( - "INSERT INTO session_lineage (retired_hash, successor_hash, retired_at) VALUES ($1,$2,$3)" + "INSERT INTO session_lineage (retired_hash, successor_hash, retired_at)" + f" VALUES ($1,$2,{_PG_EPOCH_NOW})" ) _PG_SESSION_LINEAGE_SUCCESSOR: Final = ( - "SELECT successor_hash FROM session_lineage WHERE retired_hash=$1 AND retired_at >= $2" + "SELECT successor_hash FROM session_lineage WHERE retired_hash=$1" + f" AND retired_at >= {_PG_EPOCH_NOW} - $2::double precision" +) +_PG_SESSION_LINEAGE_PURGE: Final = ( + f"DELETE FROM session_lineage WHERE retired_at < {_PG_EPOCH_NOW} - $1::double precision" ) -_PG_SESSION_LINEAGE_PURGE: Final = "DELETE FROM session_lineage WHERE retired_at < $1" #: The whole-account session sweep: revoke and blank the seal (BACKLOG #2592). Each caller raises #: the account's session epoch in the same transaction. _PG_REVOKE_USER_SESSIONS_SQL: Final = ( @@ -12259,25 +12264,21 @@ async def mark_session_mfa_verified( written = await self._write_session(conn, token_hash, stamp) return written is not None and stamp.anchored - async def rotate_session( - self, token_hash: str, *, new_token_hash: str, now: float | None = None - ) -> bool: + async def rotate_session(self, token_hash: str, *, new_token_hash: str) -> bool: """Re-key a live session in place (ASVS 7.2.4). See :meth:`AuthStore.rotate_session`. The token hash is sealed, so the re-key goes through :meth:`_write_session` (BACKLOG #2592). The lineage link goes in the same transaction, only when the re-key landed (vault - BACKLOG #3028), its time read once the re-key has landed, after any wait for the borrow - or the row lock. The answer is read after the transaction has committed. The borrow is - :meth:`_after_commit_txn`'s, for the reason it gives.""" + BACKLOG #3028), its time this server's clock when the link's own statement runs (vault + BACKLOG #4276), after any wait for the borrow or the row lock. The answer is read after + the transaction has committed. The borrow is :meth:`_after_commit_txn`'s, for the reason + it gives.""" async with self._after_commit_txn() as conn: rotated = await self._write_session( conn, token_hash, lambda s: replace(s, token_hash=new_token_hash) ) if rotated is not None: - retired_at = time.time() if now is None else now - await conn.execute( - _PG_SESSION_LINEAGE_INSERT, token_hash, new_token_hash, retired_at - ) + await conn.execute(_PG_SESSION_LINEAGE_INSERT, token_hash, new_token_hash) return rotated is not None async def revoke_session(self, token_hash: str, *, now: float | None = None) -> None: @@ -12289,7 +12290,7 @@ async def revoke_session(self, token_hash: str, *, now: float | None = None) -> ) async def supersede_session( - self, token_hash: str, *, now: float, lineage_since: float | None = None + self, token_hash: str, *, now: float, lineage_seconds: float | None = None ) -> SessionRecord | None: """Revoke and return, one statement per step, in one transaction (BACKLOG #2146, vault BACKLOG #3028). See :meth:`AuthStore.supersede_session`. @@ -12308,13 +12309,16 @@ async def _revoke(h: str) -> SessionRecord | None: ) return SessionRecord.from_mapping(dict(d)) if d else None - async def _successor(h: str, since: float) -> str | None: - found = await conn.fetchval(_PG_SESSION_LINEAGE_SUCCESSOR, h, since) + async def _successor(h: str, seconds: float) -> str | None: + found = await conn.fetchval(_PG_SESSION_LINEAGE_SUCCESSOR, h, float(seconds)) return None if found is None else str(found) try: return await revoke_through_lineage( - token_hash, lineage_since=lineage_since, revoke=_revoke, successor=_successor + token_hash, + lineage_seconds=lineage_seconds, + revoke=_revoke, + successor=_successor, ) except RowSealError as exc: # BACKLOG #5505: only the read-back refused the row, so the block exits cleanly @@ -12530,7 +12534,9 @@ async def purge_expired_sessions( float(idle_seconds), ) if lineage_seconds is not None: - await self._execute(_PG_SESSION_LINEAGE_PURGE, now - float(lineage_seconds)) + # Measured back from this server's clock, as the supersession measures its window, + # never from ``now`` (vault BACKLOG #4276). + await self._execute(_PG_SESSION_LINEAGE_PURGE, float(lineage_seconds)) return purged # --- retention / purge + maintenance (PHI.md §8) ------------------------- diff --git a/messagefoundry/store/session_lineage.py b/messagefoundry/store/session_lineage.py index 8b3e3f84a8..8f62b68577 100644 --- a/messagefoundry/store/session_lineage.py +++ b/messagefoundry/store/session_lineage.py @@ -7,6 +7,15 @@ retired hash, the hash that replaced it, and when. This module holds the one walk over those rows that every backend shares, so the three cannot disagree on how far it goes. +**"When" is the store's own clock, never an engine process's (vault BACKLOG #4276).** A link's +``retired_at`` is stamped from the database's clock inside the rotation's own statement, and the +window a walk follows links for is measured back from the database's clock inside the walk's own +statements. So the stamp and the test read ONE clock, whichever engine process elevated and +whichever signs in. A forward step of an engine process's clock, or skew between engine hosts that +share the store, no longer drops a link inside the window. A step of the store's own clock between +the rotation and the walk still moves the window by the size of the step. On SQLite that clock is +the clock of the host that holds the database file, which every engine shard opens. + **A retired hash authenticates nothing.** No session read consults this table: ``get_session``, ``list_sessions`` and the service's session loader read ``sessions`` only. The one reader is the revoke below, so the only thing a retired hash can lead to is the END of the session it became. @@ -33,14 +42,15 @@ #: Revoke the unrevoked row that hash names and return it as revoked, or ``None`` when none did. type Revoke = Callable[[str], Awaitable[SessionRecord | None]] -#: The hash that replaced this one, by a link retired at or after ``since``, or ``None``. +#: The hash that replaced this one, by a link retired no more than ``seconds`` before the store's +#: own clock at the lookup, or ``None``. type Successor = Callable[[str, float], Awaitable[str | None]] async def revoke_through_lineage( token_hash: str, *, - lineage_since: float | None, + lineage_seconds: float | None, revoke: Revoke, successor: Successor, ) -> SessionRecord | None: @@ -55,17 +65,18 @@ async def revoke_through_lineage( COMMITTED a rotation can commit between two steps. Reading the whole chain first and revoking its end afterwards would aim the revoke at a hash such a rotation had already retired. - ``lineage_since`` is the oldest ``retired_at`` a followed link may carry. ``None`` follows no - link at all, which is the plain revoke of the hash given (BACKLOG #2146's behaviour). + ``lineage_seconds`` is how long before the store's own clock, read at each lookup, a followed + link may have been retired. ``None`` follows no link at all, which is the plain revoke of the + hash given (BACKLOG #2146's behaviour). Returns the row it revoked, whose ``token_hash`` is the hash it ended under, or ``None`` when the walk reached a hash with no unrevoked row and no live link, or ran out of hops.""" current = token_hash for hop in range(LINEAGE_MAX_HOPS + 1): ended = await revoke(current) - if ended is not None or lineage_since is None or hop == LINEAGE_MAX_HOPS: + if ended is not None or lineage_seconds is None or hop == LINEAGE_MAX_HOPS: return ended - following = await successor(current, lineage_since) + following = await successor(current, lineage_seconds) if following is None: return None current = following diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 0e590a8091..076de3756b 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -232,9 +232,6 @@ _SESSION_CAP_ORDER_SQL, _SESSION_CAP_RANK_NOT_AHEAD_SQL, _SESSION_INSERT, - _SESSION_LINEAGE_INSERT, - _SESSION_LINEAGE_PURGE, - _SESSION_LINEAGE_SUCCESSOR, _SESSION_LIVE_SQL, _SESSION_NOT_AHEAD_SQL, _SQL_ADMIN_GUARD_HOLDERS, @@ -491,6 +488,20 @@ "(CAST(DATEDIFF_BIG(MICROSECOND, CAST('1970-01-01' AS DATETIME2), SYSUTCDATETIME()) AS FLOAT)" " / 1000000.0)" ) +# Vault BACKLOG #3028, ADR 0210: store.py's three session lineage statements, respelled to stamp and +# measure `retired_at` on this server's clock (vault BACKLOG #4276). store.py says which method runs +# each, and that no other statement names the table. Each names the clock once, as above. +_MSSQL_SESSION_LINEAGE_INSERT: Final = ( + "INSERT INTO session_lineage (retired_hash, successor_hash, retired_at)" + f" VALUES (?,?,{_MSSQL_EPOCH_NOW})" +) +_MSSQL_SESSION_LINEAGE_SUCCESSOR: Final = ( + "SELECT successor_hash FROM session_lineage WHERE retired_hash=?" + f" AND retired_at >= {_MSSQL_EPOCH_NOW} - ?" +) +_MSSQL_SESSION_LINEAGE_PURGE: Final = ( + f"DELETE FROM session_lineage WHERE retired_at < {_MSSQL_EPOCH_NOW} - ?" +) # BACKLOG #1169: rows per batch for the `attachment_chunk` at-rest migration. Every OTHER cipher pass # batches 500 because its rows are kilobyte-shaped; one attachment_chunk row is a whole # DETACH_CHUNK_BYTES (1 MiB) slice, ~1.33 MiB once base64+GCM sealed. 16 keeps a batch near 21 MiB, @@ -17749,17 +17760,16 @@ async def mark_session_mfa_verified( written = await self._write_session_txn(token_hash, stamp) return written is not None and stamp.anchored - async def rotate_session( - self, token_hash: str, *, new_token_hash: str, now: float | None = None - ) -> bool: + async def rotate_session(self, token_hash: str, *, new_token_hash: str) -> bool: """Re-key a live session in place (ASVS 7.2.4). See :meth:`AuthStore.rotate_session`. The token hash is sealed, so the re-key goes through :meth:`_write_session` (BACKLOG #2592), whose write reads an ``OUTPUT`` rowset and never ``cursor.rowcount`` (BACKLOG #2283). ``token_hash`` is ``NVARCHAR(64)`` and a hex digest is exactly 64 chars, so the clustered-PK row move is width-safe. The lineage link goes in the same transaction, only - when the re-key landed (vault BACKLOG #3028), its time read then, after any wait for the - borrow or the row lock. The borrow is :meth:`_acquire_after_commit`'s, for the reason it + when the re-key landed (vault BACKLOG #3028), its time this server's clock when the link's + own statement runs (vault BACKLOG #4276), after any wait for the borrow or the row lock. + The borrow is :meth:`_acquire_after_commit`'s, for the reason it gives (BACKLOG #3023). LOCK ORDER (BACKLOG #4974). The re-key takes its account's ``users`` row under ``UPDLOCK, @@ -17784,8 +17794,7 @@ async def rotate_session( which are raced and which are not.""" async def _link(cur: Any) -> None: - retired_at = time.time() if now is None else now - await cur.execute(_SESSION_LINEAGE_INSERT, (token_hash, new_token_hash, retired_at)) + await cur.execute(_MSSQL_SESSION_LINEAGE_INSERT, (token_hash, new_token_hash)) rotated = await self._write_session_txn( token_hash, @@ -17803,7 +17812,7 @@ async def revoke_session(self, token_hash: str, *, now: float | None = None) -> ) async def supersede_session( - self, token_hash: str, *, now: float, lineage_since: float | None = None + self, token_hash: str, *, now: float, lineage_seconds: float | None = None ) -> SessionRecord | None: """Revoke and return, one statement per step, in one transaction (BACKLOG #2146, vault BACKLOG #3028). See :meth:`AuthStore.supersede_session`. @@ -17823,8 +17832,8 @@ async def _revoke(h: str) -> SessionRecord | None: rows = await self._fetch_dicts(cur) return SessionRecord.from_mapping(rows[0]) if rows else None - async def _successor(h: str, since: float) -> str | None: - await cur.execute(_SESSION_LINEAGE_SUCCESSOR, (h, since)) + async def _successor(h: str, seconds: float) -> str | None: + await cur.execute(_MSSQL_SESSION_LINEAGE_SUCCESSOR, (h, float(seconds))) rows = await cur.fetchall() return str(rows[0][0]) if rows else None @@ -17833,7 +17842,7 @@ async def _successor(h: str, since: float) -> str | None: try: ended = await revoke_through_lineage( token_hash, - lineage_since=lineage_since, + lineage_seconds=lineage_seconds, revoke=_revoke, successor=_successor, ) @@ -18124,8 +18133,9 @@ async def purge_expired_sessions( purged = await self._execute(sql, params) if lineage_seconds is not None: # Its own statement and transaction, as on Postgres: a link is table hygiene, and the - # supersession stops following one at its window whether or not this has run. - await self._execute(_SESSION_LINEAGE_PURGE, (now - float(lineage_seconds),)) + # supersession stops following one at its window whether or not this has run. Measured + # back from this server's clock, as the supersession measures (vault BACKLOG #4276). + await self._execute(_MSSQL_SESSION_LINEAGE_PURGE, (float(lineage_seconds),)) return purged async def stats(self) -> dict[str, int]: diff --git a/messagefoundry/store/store.py b/messagefoundry/store/store.py index 38dc19eb79..61d1814b3e 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -1660,17 +1660,27 @@ def stamped_connection_event(ev: ConnectionEventWrite) -> ConnectionEventWrite: ) -# Vault BACKLOG #3028, ADR 0210: the session lineage's three statements, in `?` form for SQLite and -# SQL Server; postgres.py respells them for `$n`. The INSERT runs only inside rotate_session's own -# transaction, the SELECT only inside supersede_session's, and the DELETE only from the session -# purge. No other statement names the table: a retired hash must authenticate nothing. +# Vault BACKLOG #4276: the database's own clock as epoch seconds, the unit `session_lineage.retired_at` +# holds. SQLite reads the host clock through its VFS, not through Python's `time.time`, and holds +# 'now' fixed for the whole of one statement. postgres.py and sqlserver.py have their own copies. +_SQLITE_EPOCH_NOW: Final = "((julianday('now') - 2440587.5) * 86400.0)" +# Vault BACKLOG #3028, ADR 0210: the session lineage's three statements; postgres.py and sqlserver.py +# respell them. The INSERT runs only inside rotate_session's own transaction, the SELECT only inside +# supersede_session's, and the DELETE only from the session purge. No other statement names the +# table: a retired hash must authenticate nothing. Each stamps or measures `retired_at` on the +# database's clock, never a parameter from an engine process (vault BACKLOG #4276, +# store/session_lineage.py), so the window is one clock's reading on every engine shard. _SESSION_LINEAGE_INSERT: Final = ( - "INSERT INTO session_lineage (retired_hash, successor_hash, retired_at) VALUES (?,?,?)" + "INSERT INTO session_lineage (retired_hash, successor_hash, retired_at)" + f" VALUES (?,?,{_SQLITE_EPOCH_NOW})" ) _SESSION_LINEAGE_SUCCESSOR: Final = ( - "SELECT successor_hash FROM session_lineage WHERE retired_hash=? AND retired_at >= ?" + "SELECT successor_hash FROM session_lineage WHERE retired_hash=?" + f" AND retired_at >= {_SQLITE_EPOCH_NOW} - ?" +) +_SESSION_LINEAGE_PURGE: Final = ( + f"DELETE FROM session_lineage WHERE retired_at < {_SQLITE_EPOCH_NOW} - ?" ) -_SESSION_LINEAGE_PURGE: Final = "DELETE FROM session_lineage WHERE retired_at < ?" def session_reseal_params(new: SessionRecord, old: SessionRecord) -> tuple[object, ...]: @@ -22426,26 +22436,22 @@ async def mark_session_mfa_verified( await self._commit() return written is not None and stamp.anchored - async def rotate_session( - self, token_hash: str, *, new_token_hash: str, now: float | None = None - ) -> bool: + async def rotate_session(self, token_hash: str, *, new_token_hash: str) -> bool: """Re-key a live session in place (ASVS 7.2.4). See :meth:`AuthStore.rotate_session`. ``token_hash`` is the PK, so this is a key update: the row keeps every other column and the old hash stops resolving in the same transaction. The token hash is sealed, so the re-key re-seals (BACKLOG #2592). Reports whether a row was re-keyed so the caller can fail closed when the session was revoked out from under it. The lineage link is written in the same - transaction, and only when the re-key landed (vault BACKLOG #3028). Its time is read once - the re-key has landed, so a wait for the lock cannot age the link before it exists.""" + transaction, and only when the re-key landed (vault BACKLOG #3028). Its time is the + database's clock when the link's own statement runs (vault BACKLOG #4276), after the re-key + has landed, so a wait for the lock cannot age the link before it exists.""" async with _writer_txn(self._db, self._lock): rotated = await self._write_session( token_hash, lambda s: replace(s, token_hash=new_token_hash) ) if rotated is not None: - retired_at = time.time() if now is None else now - await self._db.execute( - _SESSION_LINEAGE_INSERT, (token_hash, new_token_hash, retired_at) - ) + await self._db.execute(_SESSION_LINEAGE_INSERT, (token_hash, new_token_hash)) await self._commit() return rotated is not None @@ -22459,10 +22465,10 @@ async def revoke_session(self, token_hash: str, *, now: float | None = None) -> await self._commit() async def supersede_session( - self, token_hash: str, *, now: float, lineage_since: float | None = None + self, token_hash: str, *, now: float, lineage_seconds: float | None = None ) -> SessionRecord | None: """Revoke, then read the row back in the SAME transaction (BACKLOG #2146), following the - session lineage when ``lineage_since`` is given (vault BACKLOG #3028). See + session lineage when ``lineage_seconds`` is given (vault BACKLOG #3028). See :meth:`AuthStore.supersede_session`. Two statements per step rather than one ``UPDATE ... RETURNING``, because ``RETURNING`` @@ -22482,8 +22488,8 @@ async def _revoke(h: str) -> SessionRecord | None: row = await cur.fetchone() return SessionRecord.from_mapping(dict(row)) if row else None - async def _successor(h: str, since: float) -> str | None: - cur = await self._db.execute(_SESSION_LINEAGE_SUCCESSOR, (h, since)) + async def _successor(h: str, seconds: float) -> str | None: + cur = await self._db.execute(_SESSION_LINEAGE_SUCCESSOR, (h, float(seconds))) row = await cur.fetchone() return str(row[0]) if row else None @@ -22491,7 +22497,10 @@ async def _successor(h: str, since: float) -> str | None: async with _writer_guard(self._db, self._lock): try: ended = await revoke_through_lineage( - token_hash, lineage_since=lineage_since, revoke=_revoke, successor=_successor + token_hash, + lineage_seconds=lineage_seconds, + revoke=_revoke, + successor=_successor, ) except RowSealError as exc: # BACKLOG #5505: only the read-back refused the row; its revoke still commits. @@ -22808,7 +22817,9 @@ async def purge_expired_sessions( ) purged = cur.rowcount if cur.rowcount is not None else 0 if lineage_seconds is not None: - await self._db.execute(_SESSION_LINEAGE_PURGE, (now - float(lineage_seconds),)) + # Measured back from the database's clock, as the supersession measures its window, + # never from ``now`` (vault BACKLOG #4276). + await self._db.execute(_SESSION_LINEAGE_PURGE, (float(lineage_seconds),)) await self._commit() return purged diff --git a/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py b/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py index 535701fff2..d9959edac4 100644 --- a/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py +++ b/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py @@ -40,7 +40,12 @@ from messagefoundry.store.store import MessageStore from messagefoundry_webconsole import pages from messagefoundry_webconsole._html import minimal_nav -from tests._logout_rows import logout_details, logout_rows, temp_password_expired_rows +from tests._logout_rows import ( + age_session_links, + logout_details, + logout_rows, + temp_password_expired_rows, +) PW = "a-strong-test-passphrase" # >=15, no app/vendor terms — satisfies the ASVS policy (WP-3) @@ -347,16 +352,16 @@ async def test_ui_logout_with_a_cookie_an_elevation_just_retired_ends_its_succes async def test_ui_logout_with_a_cookie_retired_past_the_window_ends_nothing( - engine: Engine, monkeypatch: pytest.MonkeyPatch + engine: Engine, ) -> None: """The control for the test above, one second past the 5-second window. This route carries no credential, so a retired cookie leads nowhere after that: nothing is revoked, the row says - ``nothing_to_revoke`` and has no owner to name.""" + ``nothing_to_revoke`` and has no owner to name. The link is aged on the store's clock, the one + the window is measured on (vault BACKLOG #4276); patching ``time`` would not age it.""" service, old = await _signed_in_operator(engine) successor = await service._rotate_session_token(old) assert successor is not None - rotated_at = time.time() - monkeypatch.setattr(time, "time", lambda: rotated_at + _LOGOUT_LINEAGE_SECONDS + 1.0) + await age_session_links(engine.store, _LOGOUT_LINEAGE_SECONDS + 1.0) out = await _sign_out_with(engine, service, old) assert out.status_code == 303 assert await service.identity_for_token(successor, activity=False) is not None diff --git a/tests/_logout_rows.py b/tests/_logout_rows.py index 7660a332da..71ccd5d4a5 100644 --- a/tests/_logout_rows.py +++ b/tests/_logout_rows.py @@ -24,6 +24,18 @@ async def logout_rows( ] +async def age_session_links(store: Any, seconds: float) -> None: + """Move every ``session_lineage`` link of a SQLite ``MessageStore`` ``seconds`` into the past. + + The store stamps a link and measures the window a revoke follows it for on the DATABASE's + clock, not on ``time.time`` (vault BACKLOG #4276), so patching ``time`` no longer ages a link. + This is how a test puts a link past a window instead.""" + await store._db.execute( + "UPDATE session_lineage SET retired_at = retired_at - ?", (float(seconds),) + ) + await store._db.commit() + + async def temp_password_expired_rows(store: Any) -> list[tuple[object, object, object]]: """Each ``auth.temp_password_expired`` row, newest first, as its actor, client address and whole ``detail``: the row a sign-out writes when it ends a session whose temporary credential diff --git a/tests/_session_rotation_contract.py b/tests/_session_rotation_contract.py index 5a4438553f..5ae9464881 100644 --- a/tests/_session_rotation_contract.py +++ b/tests/_session_rotation_contract.py @@ -245,6 +245,11 @@ async def assert_session_lineage_contract(store: Any, *, user_id: str = "lin-u1" ``rotate_session`` links the hash it retired to its successor in its own transaction, and ``supersede_session`` follows those links, inside a window its caller names, to the live end. A retired hash still resolves to nothing, and the reaper's purge drops links past the window. + + The window is a LENGTH, measured back from the database's own clock, which also stamps every + link (vault BACKLOG #4276). So a test cannot age a link by passing an old ``now``; a window + below zero, which ends after the database's present, stands in for a link past it, and a + ``now`` far from the present shows the window does not read it. """ now = time.time() await store.create_user( @@ -263,52 +268,57 @@ async def assert_session_lineage_contract(store: Any, *, user_id: str = "lin-u1" # --- two rotations: a -> b -> c, and neither retired hash resolves ------------------------- a, b, c = _h(), _h(), _h() await store.create_session(token_hash=a, user_id=user_id, expires_at=expires, now=now) - assert await store.rotate_session(a, new_token_hash=b, now=now) is True - assert await store.rotate_session(b, new_token_hash=c, now=now + 1) is True + assert await store.rotate_session(a, new_token_hash=b) is True + assert await store.rotate_session(b, new_token_hash=c) is True assert await store.get_session(a) is None, "a retired hash must resolve to nothing" assert await store.get_session(b) is None, "a retired hash must resolve to nothing" # --- no window: the plain revoke of the hash given, as before ------------------------------ assert await store.supersede_session(a, now=now + 2) is None - # --- a window that starts after the first link: that link is not followed ------------------- - assert await store.supersede_session(a, now=now + 2, lineage_since=now + 0.5) is None + # --- a window that ends after both links: neither is followed ------------------------------- + assert await store.supersede_session(a, now=now + 2, lineage_seconds=-60) is None live = await store.get_session(c) assert live is not None and live.revoked_at is None, "a link past the window was followed" - # --- inside the window: followed over both hops, and the live end is what ends -------------- - ended = await store.supersede_session(a, now=now + 3, lineage_since=now - 10) + # --- inside the window: followed over both hops, and the live end is what ends. The revoke's + # `now` is far ahead of the database's clock, as a signing-in process whose clock stepped + # forward would pass, and the window does not read it (vault BACKLOG #4276) ----------------- + ahead = now + 5000 + ended = await store.supersede_session(a, now=ahead, lineage_seconds=60) assert ended is not None, "the supersession did not follow the lineage to the live end" - assert ended.token_hash == c and ended.user_id == user_id and ended.revoked_at == now + 3 + assert ended.token_hash == c and ended.user_id == user_id and ended.revoked_at == ahead stored = await store.get_session(c) - assert stored is not None and stored.revoked_at == now + 3, "the revoke was not persisted" + assert stored is not None and stored.revoked_at == ahead, "the revoke was not persisted" # The chain now ends at a revoked row, so a second supersession ends nothing. - assert await store.supersede_session(a, now=now + 4, lineage_since=now - 10) is None + assert await store.supersede_session(a, now=now + 4, lineage_seconds=60) is None # From the middle of the chain, too. - assert await store.supersede_session(b, now=now + 4, lineage_since=now - 10) is None + assert await store.supersede_session(b, now=now + 4, lineage_seconds=60) is None # --- a rotation that did not land writes no link ------------------------------------------- d = _h() - assert await store.rotate_session(c, new_token_hash=d, now=now + 5) is False + assert await store.rotate_session(c, new_token_hash=d) is False await store.create_session(token_hash=d, user_id=user_id, expires_at=expires, now=now) - assert await store.supersede_session(c, now=now + 6, lineage_since=now - 10) is None, ( + assert await store.supersede_session(c, now=now + 6, lineage_seconds=60) is None, ( "a refused rotation linked its hash to a session it never became" ) kept = await store.get_session(d) assert kept is not None and kept.revoked_at is None - # --- the purge drops links past the window and keeps the rest ------------------------------ + # --- the purge measures on the database's clock: a `now` ahead of it drops no live link, and a + # window that ends after the database's present drops every link --------------------------- old, old_next, fresh, fresh_next = _h(), _h(), _h(), _h() await store.create_session(token_hash=old, user_id=user_id, expires_at=expires, now=now) await store.create_session(token_hash=fresh, user_id=user_id, expires_at=expires, now=now) - assert await store.rotate_session(old, new_token_hash=old_next, now=now - 1000) is True - assert await store.rotate_session(fresh, new_token_hash=fresh_next, now=now) is True + assert await store.rotate_session(old, new_token_hash=old_next) is True + assert await store.rotate_session(fresh, new_token_hash=fresh_next) is True await store.purge_expired_sessions(now=now) # no window: every link stays - await store.purge_expired_sessions(now=now, lineage_seconds=100) - assert await store.supersede_session(old, now=now, lineage_since=now - 10_000) is None, ( + await store.purge_expired_sessions(now=ahead, lineage_seconds=600) + swept = await store.supersede_session(fresh, now=now + 7, lineage_seconds=60) + assert swept is not None and swept.token_hash == fresh_next, "the purge dropped a live link" + await store.purge_expired_sessions(now=now, lineage_seconds=-60) + assert await store.supersede_session(old, now=now, lineage_seconds=10_000) is None, ( "a link past the purge window survived the purge" ) survivor = await store.get_session(old_next) assert survivor is not None and survivor.revoked_at is None - swept = await store.supersede_session(fresh, now=now + 7, lineage_since=now - 10) - assert swept is not None and swept.token_hash == fresh_next, "the purge dropped a live link" diff --git a/tests/test_session_sql_placeholders.py b/tests/test_session_sql_placeholders.py index f128ff86de..820d7bf868 100644 --- a/tests/test_session_sql_placeholders.py +++ b/tests/test_session_sql_placeholders.py @@ -61,7 +61,7 @@ "supersede_session": lambda s: s.supersede_session(_HASH, now=_NOW), # Vault BACKLOG #3028: nothing is revoked, so the walk reads the lineage once and stops. "supersede_session_lineage": lambda s: s.supersede_session( - _HASH, now=_NOW, lineage_since=_NOW - 360 + _HASH, now=_NOW, lineage_seconds=360 ), "revoke_user_sessions": lambda s: s.revoke_user_sessions("u", now=_NOW, audit=no_audit_row), "revoke_user_sessions_except": lambda s: s.revoke_user_sessions( diff --git a/tests/test_session_supersession.py b/tests/test_session_supersession.py index b258e9d041..b5f78ecd6b 100644 --- a/tests/test_session_supersession.py +++ b/tests/test_session_supersession.py @@ -41,6 +41,7 @@ from messagefoundry.store.store import MessageStore from tests._admin_account import create_local_user_chosen from tests._logout_rows import ( + age_session_links, logout_details, logout_entries, logout_rows, @@ -263,13 +264,13 @@ def _stepping() -> float: return base + reads[0] * 0.001 async def _touched_first( - token_hash: str, *, now: float, lineage_since: float | None = None + token_hash: str, *, now: float, lineage_seconds: float | None = None ) -> object: touched = time.time() assert touched > now, "the stepping clock did not separate the touch from the revoke stamp" await store.touch_session(token_hash, now=touched) touches.append(token_hash) - return await real_supersede(token_hash, now=now, lineage_since=lineage_since) + return await real_supersede(token_hash, now=now, lineage_seconds=lineage_seconds) monkeypatch.setattr(store, "supersede_session", _touched_first) monkeypatch.setattr(time, "time", _stepping) @@ -301,10 +302,10 @@ async def test_a_session_live_when_the_revoke_began_is_audited_though_it_lapsed_ # password hash cannot eat the margin on a slow runner. clock = {"now": record.last_used_at + 30 * 60 - 2.0} # 2 seconds of idle time left - async def _slow(token_hash: str, *, now: float, lineage_since: float | None = None) -> object: + async def _slow(token_hash: str, *, now: float, lineage_seconds: float | None = None) -> object: if token_hash == prior_hash: clock["now"] += 4.0 # the call returns 2 seconds past the idle limit - return await real_supersede(token_hash, now=now, lineage_since=lineage_since) + return await real_supersede(token_hash, now=now, lineage_seconds=lineage_seconds) monkeypatch.setattr(time, "time", lambda: clock["now"]) monkeypatch.setattr(store, "supersede_session", _slow) @@ -581,21 +582,52 @@ async def test_a_lapsed_session_is_recorded_as_lapsed_and_names_its_owner( async def test_a_logout_follows_no_rotation_older_than_its_bound_before_proven_at( - store: MessageStore, monkeypatch: pytest.MonkeyPatch + store: MessageStore, ) -> None: # BACKLOG #3715. POST /auth/logout passes the moment its request arrived as proven_at, and a - # link retired more than _LOGOUT_LINEAGE_SECONDS before that is not followed. The clock steps - # past the bound, so the rotation lands strictly before it. + # link retired more than _LOGOUT_LINEAGE_SECONDS before that is not followed. The link is aged + # past the bound on the store's clock, which is the one the window is measured on (vault + # BACKLOG #4276), so the rotation lands strictly before it. service = await _service(store, session_idle_timeout_minutes=30) token = await _token(service) successor = await _rotated(service, token) - real = time.time - monkeypatch.setattr(time, "time", lambda: real() + _LOGOUT_LINEAGE_SECONDS + 1.0) + await age_session_links(store, _LOGOUT_LINEAGE_SECONDS + 1.0) outcome = await service.logout(token, client=None, actor="op", proven_at=time.time()) assert outcome == "nothing_to_revoke" assert await _live(service, successor), "a link older than the bound was followed" +async def test_a_logout_follows_a_link_retired_after_an_earlier_proof( + store: MessageStore, +) -> None: + # Vault BACKLOG #4276. The window is a length back from the store's clock: the bound plus the + # time since proven_at. A link 6 seconds old is past the bound alone, and inside it once the + # proof is 10 seconds old, as a link written after that proof would be. + service = await _service(store, session_idle_timeout_minutes=30) + token = await _token(service) + successor = await _rotated(service, token) + await age_session_links(store, _LOGOUT_LINEAGE_SECONDS + 1.0) + proven = time.time() - (_LOGOUT_LINEAGE_SECONDS + 5.0) + outcome = await service.logout(token, client=None, actor="op", proven_at=proven) + assert outcome == "revoked" + assert not await _live(service, successor) + + +async def test_a_logout_after_a_forward_step_of_this_process_clock_still_follows_the_link( + store: MessageStore, monkeypatch: pytest.MonkeyPatch +) -> None: + # Vault BACKLOG #4276. The process clock jumps past the bound after the rotation. The link's + # stamp and the window are both the store's clock, so the step drops nothing. + service = await _service(store, session_idle_timeout_minutes=30) + token = await _token(service) + successor = await _rotated(service, token) + real = time.time + monkeypatch.setattr(time, "time", lambda: real() + _LOGOUT_LINEAGE_SECONDS + 60.0) + outcome = await service.logout(token, client=None, actor="op", proven_at=time.time()) + assert outcome == "revoked" + assert not await _live(service, successor), "a forward step of the process clock dropped a link" + + async def test_a_logout_ends_the_session_a_rotation_in_flight_re_keyed( store: MessageStore, ) -> None: diff --git a/tests/test_session_supersession_lineage.py b/tests/test_session_supersession_lineage.py index 73334a26eb..9b52988a96 100644 --- a/tests/test_session_supersession_lineage.py +++ b/tests/test_session_supersession_lineage.py @@ -34,6 +34,7 @@ from messagefoundry.store.session_lineage import LINEAGE_MAX_HOPS, revoke_through_lineage from messagefoundry.store.store import MessageStore, SessionRecord from tests._ast_sites import code_names, code_strings, parse_source +from tests._logout_rows import age_session_links from tests.test_session_supersession import ( PW, _live, @@ -149,20 +150,71 @@ async def test_the_link_is_followed_over_several_elevations(store: MessageStore) assert not await _live(service, end), "the chain was not followed to its live end" -async def test_a_link_older_than_the_window_is_not_followed( +async def test_a_link_older_than_the_window_is_not_followed(store: MessageStore) -> None: + # The link is aged on the store's clock, the one the window is measured on (vault BACKLOG + # #4276); patching `time` would no longer age it, as the next test shows. + service = await _service(store, session_idle_timeout_minutes=240) + window = service.supersession_lineage_seconds + assert window >= service.oidc_flow_ttl_seconds, "the window must outlast the longest sign-in" + prior = await _token(service) + rotated = await _elevate(service, prior) + await age_session_links(store, window + 5) + assert await _live(service, rotated) + await _token(service, supersedes=prior) + assert await _live(service, rotated), "a link past its window ended a session" + assert await _superseded(store) == [] + + +async def test_a_forward_step_of_the_signing_in_process_clock_does_not_drop_a_link( store: MessageStore, monkeypatch: pytest.MonkeyPatch ) -> None: + # Vault BACKLOG #4276, ASVS 7.2.4 arm (ii). The 2026-10-26 pass moved `time.time` forward 425 + # seconds after one elevation, and a sign-in presenting the older token then left the rotated + # session live: the link was stamped and judged on this process's clock. Both now read the + # store's clock, so the same step, past the whole window, drops nothing. service = await _service(store, session_idle_timeout_minutes=240) window = service.supersession_lineage_seconds - assert window >= service.oidc_flow_ttl_seconds, "the window must outlast the longest sign-in" prior = await _token(service) rotated = await _elevate(service, prior) real = time.time monkeypatch.setattr(time, "time", lambda: real() + window + 5) assert await _live(service, rotated) await _token(service, supersedes=prior) - assert await _live(service, rotated), "a link past its window ended a session" - assert await _superseded(store) == [] + assert not await _live(service, rotated), ( + "a forward step of the signing-in process's clock dropped a link inside the window" + ) + assert await _superseded(store) == [ + { + "scope": "superseded", + "session": hash_token(rotated)[:12], + "presented": hash_token(prior)[:12], + "actor": "op", + } + ] + + +async def test_the_link_is_stamped_on_the_store_clock_and_the_purge_measures_on_it( + store: MessageStore, tmp_path: Path +) -> None: + # Vault BACKLOG #4276. An elevating process whose clock runs an hour ahead stamps nothing + # ahead: the stamp is the database's. And the purge measures a link's age on that clock too, so + # a reaper whose `now` runs ahead keeps a link the supersession would still follow. + service = await _service(store, session_idle_timeout_minutes=240) + prior = await _token(service) + real = time.time + skew = 3600.0 + with pytest.MonkeyPatch.context() as mp: + mp.setattr(time, "time", lambda: real() + skew) + rotated = await _elevate(service, prior) + with closing(sqlite3.connect(tmp_path / "lineage.db")) as db: + (stamp,) = db.execute("SELECT retired_at FROM session_lineage").fetchone() + assert abs(float(stamp) - real()) < 60, f"the link was stamped {stamp - real():.0f}s off" + await store.purge_expired_sessions( + now=real() + skew, lineage_seconds=service.supersession_lineage_seconds + ) + assert _links(tmp_path / "lineage.db") == [(hash_token(prior), hash_token(rotated))] + await store.purge_expired_sessions(now=real(), lineage_seconds=-60.0) + assert _links(tmp_path / "lineage.db") == [], "a window that ends after now kept a link" def _links(path: Path) -> list[tuple[str, str]]: @@ -258,7 +310,7 @@ def test_the_service_follows_the_lineage_from_the_supersession_and_sign_out_alon if isinstance(node, ast.AsyncFunctionDef | ast.FunctionDef): for call in ast.walk(node): if isinstance(call, ast.Call) and any( - k.arg == "lineage_since" for k in call.keywords + k.arg == "lineage_seconds" for k in call.keywords ): passing.add(node.name) assert passing == {"_supersede_session_hash", "logout", "_supersede_session"} @@ -383,7 +435,7 @@ async def _successor(h: str, since: float) -> str | None: return found ended = await revoke_through_lineage( - "a", lineage_since=0.0, revoke=_revoke, successor=_successor + "a", lineage_seconds=0.0, revoke=_revoke, successor=_successor ) assert ended is not None and ended.token_hash == "c" assert calls == ["revoke a", "follow a", "revoke b", "follow b", "revoke c"] @@ -400,10 +452,10 @@ async def _revoke(h: str) -> SessionRecord | None: return _revoke reach = await revoke_through_lineage( - "0", lineage_since=0.0, revoke=_revoke_only(LINEAGE_MAX_HOPS), successor=_successor + "0", lineage_seconds=0.0, revoke=_revoke_only(LINEAGE_MAX_HOPS), successor=_successor ) assert reach is not None and reach.token_hash == str(LINEAGE_MAX_HOPS) past = await revoke_through_lineage( - "0", lineage_since=0.0, revoke=_revoke_only(LINEAGE_MAX_HOPS + 1), successor=_successor + "0", lineage_seconds=0.0, revoke=_revoke_only(LINEAGE_MAX_HOPS + 1), successor=_successor ) assert past is None, "the walk followed more links than its bound" From 2d9827fdeb20796c498c38f89a2cbdf07f49d2df Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:06:10 -0600 Subject: [PATCH 2/3] Session lineage: keep waits and steps from shortening the window Review round 1 of the store-clock change. - The walk adds back, on the monotonic clock, the time a store call spent waiting before each lookup, so a lock, connection or row-lock wait no longer shortens the window the caller asked for. - POST /auth/logout reads proven_at on the monotonic clock, and the sign-out measures the time since it on the same clock. - The reaper asks the purge for the window plus its step tolerance, restoring the margin the store-clock purge had dropped. - SECURITY.md, ADR 0210 Amendment B and the docstrings no longer claim an engine clock step is closed on SQLite: there the store's clock is the engine host's. - The store contract now places one window between two real link ages on every backend; the SQLite aging helper moved beside it. BACKLOG #4276 --- docs/SECURITY.md | 19 ++++--- ...ows-a-time-bounded-retired-hash-lineage.md | 19 ++++--- docs/adr/README.md | 2 +- messagefoundry/api/app.py | 16 ++++-- messagefoundry/api/auth_routes.py | 8 +-- messagefoundry/auth/service.py | 20 ++++---- messagefoundry/store/base.py | 7 +-- messagefoundry/store/postgres.py | 2 + messagefoundry/store/session_lineage.py | 35 +++++++++---- messagefoundry/store/sqlserver.py | 2 + messagefoundry/store/store.py | 2 + .../tests/test_ui_logout_affordance.py | 14 +++--- tests/_logout_rows.py | 12 ----- tests/_session_rotation_contract.py | 50 +++++++++++++++++-- tests/test_api_auth.py | 28 ++++++++--- tests/test_session_supersession.py | 18 ++++--- tests/test_session_supersession_lineage.py | 50 ++++++++++++++++--- 17 files changed, 212 insertions(+), 92 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index ddc326ee48..e9b108ce81 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -6582,9 +6582,10 @@ as before this change: - more than 32 elevations on one session inside the bound; - a step of the store's own clock between the elevation and the sign-in, which moves the bound by the size of the step, in either direction. The store stamps each link and measures the bound on - that one clock (vault BACKLOG #4276): the database server's on PostgreSQL and SQL Server, and - on SQLite the clock of the host that holds the database file. So a step of an engine process's - clock, or skew between engine hosts that share the store, does not move the bound. + that one clock (vault BACKLOG #4276). On PostgreSQL and SQL Server it is the database server's, + so a step of an engine host's clock, or skew between engine hosts that share the store, does not + move the bound there. **On SQLite it is the engine host's own clock**, which SQLite reads and on + which every engine shard runs, so on SQLite a step of that host's clock still moves the bound. **A retired token authenticates nothing.** No session read, the validator included, consults the links; only a revoke follows them, at a sign-in's supersession or at a sign-out (below). For the @@ -6596,8 +6597,10 @@ the bound after the elevation too, through a sign-in whose first credential pass required, the supersession runs when the password-only session is minted, before the second factor, so a password alone is enough. A store clock that stepped back between the elevation and the sign-in lengthens that time by the step; the -reaper's clock-step guard reads the engine's clock, and covers neither this nor the purge of links, -which the store measures on its own clock. The links are not under the session integrity seal (BACKLOG #2592): a forged link can only direct a +reaper's clock-step guard reads the engine's clock and does not cover this. The reaper deletes a link +only once it is older than the bound plus that guard's step tolerance on the store's clock, so a +forward step of the store's clock smaller than the tolerance cannot delete a link the sign-in would +still follow. The links are not under the session integrity seal (BACKLOG #2592): a forged link can only direct a revoke, and a revoke needs no key on any backend. **A sign-out follows the links too, for far less time (BACKLOG #3715).** An elevation in another @@ -6605,8 +6608,8 @@ tab can re-key the session while a sign-out is in flight, and the sign-out then under its new token, in the same transaction as the revoke. `POST /auth/logout` follows links written up to 5 seconds before its request arrived; the slack covers a link stamped before its rotation commits. The store measures that window back from its own clock, which stamps the link -too, as the bound plus the time since the request arrived on the engine's clock, so clocks that -differ between engine processes do not move it. Its sign-in check proved the +too, as the bound plus the time since the request arrived on the engine's monotonic clock, so on +PostgreSQL and SQL Server clocks that differ between engine hosts do not move it. Its sign-in check proved the token live after the request arrived, so any link from it was written after that proof, and the route gains no reach. `/ui/logout` carries no credential, so it follows links written up to 5 seconds before the call. **That is a separate power, credential-free and end-only:** for 5 seconds @@ -6614,7 +6617,7 @@ after an elevation, anyone who presents the RETIRED token to `/ui/logout` ends t became, with no sign-in. It cannot open or extend a session. At least these cases stay open, and the session lives on under its new token: an elevation older than the bound, more than 32 elevations in a row inside it, and a step of the store's own clock between the elevation and the -sign-out, which moves the bound by the step. The `auth.logout` row names the +sign-out, which moves the bound by the step; on SQLite that clock is the engine host's. The `auth.logout` row names the session's owner as actor, its `outcome` is `revoked`, and a `presented` field holds the hash that was presented. The `outcome` is `lapsed` instead when the session's own clock checks fail at the revoke, or when the session passes them but the owner's admin-issued temporary credential is past diff --git a/docs/adr/0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md b/docs/adr/0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md index e5ff93c19e..fcf64f2a83 100644 --- a/docs/adr/0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md +++ b/docs/adr/0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md @@ -135,10 +135,15 @@ ahead of the elevating one, dropped a link inside the real window. Now every bac the reaper's purge measure the window back from that same clock: SQLite's `julianday('now')`, Postgres `statement_timestamp()`, SQL Server `SYSUTCDATETIME()`. Decision 3's bound is now a length, `lineage_seconds`, not an instant, `lineage_since`, and `rotate_session` takes no `now`. -The sign-out asks for its 5 seconds plus the time since its proof on the engine's clock: two -readings of one process's clock, never compared with a stamp. - -What this closes: a step of an engine process's clock, and skew between engine hosts sharing one -store, no longer move the window. What stays: a step of the store's own clock between the elevation -and the sign-in still moves it by the step. On SQLite that is the clock of the host that holds the -database file. `docs/SECURITY.md` states both. +The sign-out asks for its 5 seconds plus the time since its proof, on the engine's monotonic clock. +Each store adds back, on the monotonic clock, the time its own call spent waiting before a lookup, +so no lock, connection or row wait shortens the window. The reaper asks the purge for the window +plus its step tolerance, so a forward step of the store's clock under that tolerance cannot delete +a link the supersession would still follow. + +What this closes: on PostgreSQL and SQL Server, a step of an engine host's clock, and skew between +engine hosts sharing one store, no longer move the window. What stays: a step of the store's own +clock between the elevation and the sign-in still moves it by the step. On SQLite that clock is the +engine host's own, since SQLite reads the host clock and every engine shard runs on the host that +holds the file, so on SQLite this change leaves a real host clock step where it was. +`docs/SECURITY.md` states both. diff --git a/docs/adr/README.md b/docs/adr/README.md index 5b2b4ad5e0..c01f0fa98c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -232,7 +232,7 @@ what is withheld and what you can request. | [0207](0207-a-single-use-enrolment-code-for-a-directory-account-s-first-engine-factor.md) | **A single-use enrolment code for a directory account's first engine factor** (vault BACKLOG #2609, closing item 2; the decision ADR 0142 Amendment C left open) -- a directory account's first engine factor is bound only with a single-use enrolment code an Administrator issues and hands over out of band. Required at the step that binds and stamps (`confirm_mfa_enrollment`, `finish_webauthn_registration`) when the account is `ad`, holds no engine factor, and the session is not stamped MFA-verified: so every Kerberos session and a federated one with the claim gate off, never a claim-gated federated one. That step also refuses an account that now holds a factor. That re-check (both checks on the passkey leg; on the TOTP leg, a passkey, with a TOTP enabled meanwhile left to the compare-and-set), the TOTP enable bound to the verified secret, and the passkey finish route's per-actor attempt budget have since shipped (BACKLOG #3014, #3025, #3061). Amendment A (2026-10-27) adds: once owner ruling A5 removes the directory re-bind, the code is a factorless directory session's re-proof at the binding step, the enrolment begins and the TOTP confirm form are admitted with no grant, and every other step-up action stays refused until a factor exists; the code is read after the directory re-lookup, and on the TOTP leg is spent in the enable's own conditional write, after the stamp, rather than before it; the host command refuses a SQLite store an engine holds, a file that is not a store, and a store the probe cannot check; and the issuing Administrator is told when a code is spent. Disabling the account clears an outstanding code, and every refused code gets one client-facing reply. The handover is the control, so it must leave the directory: an Administrator checks who is asking and never replies through the account's own mail or chat. The rule reads no session mechanism and no `kerberos_enabled`, and holds with `require_mfa` on or off. At least 128 bits, stored as its SHA-256 digest, one per account, 24 hours, spent by one conditional write (before the credential write on the passkey leg, in the enable's write on the TOTP leg). Issued by an Administrator behind step-up, never for the caller's own account, also by an MFA reset of a directory account, and, for a site where no Administrator can issue one, by a host command on `admin-unlock`'s gate, which is not BACKLOG #2711's outage recovery. Rejected: password only, a TOTP-on-directory-password shortcut, an emailed link, a short Argon2 code, gating on the mechanism | **Accepted (2026-10-27)**; Amended (A, 2026-10-27) -- accepted by the batch 447 Manager under the Owner's delegation of 2026-10-27 (CLAUDE.md section 5, owner ruling 2026-10-22), after two adversarial reviews; that delegation record is the owner's ruling. Proposed (2026-10-05), doc-only, drafted on the owner's direction. The code with `require_mfa` off is answered yes (Amendment A). Open: a fixed lifetime, a code from an MFA reset, and the host command's reach. Severity conditional per CLAUDE.md section 0 | | [0208](0208-a-theia-desktop-app-gives-interface-analysts-a-simpler-steps-only-editor.md) | **A Theia desktop app gives interface analysts a simpler Steps-only editor** (owner rulings and Manager decisions of 2026-10-07; rewrites the uncommitted 2026-10-02 hosted-Theia drafts after two four-lens reviews) -- two Electron builds sharing one native Theia Steps extension: an analyst build capped at the Steps level, and a developer build that is a full IDE with a Steps / Split / Code switch and no per-user limits. The purpose is a simpler interface, not enforcement. The analyst build signs in to the engine, clears every session gate, proves the session on a non-exempt route at start-up and before each save, and turns on editing only for `code:steps` (new, advisory, read by the editor only) or `code:edit`. That role check is the primary control and a guardrail: the developer build, VS Code and any other tool are outside it. An optional repository check classifies a change as Steps-only by comparing `code` rows, every control header and each typed row's full statement against base, and passes anything else only with a `code:edit` reviewer's approval of the head commit; it holds against a deliberate change only when run from a definition the change cannot edit. Analyst Test takes a generator spec and never passes `--show-phi`. Review R1 is a precondition answered by the R1 fix and a typed-only `lens rewrite` mode the analyst build always sets; both landed in PR 2155 (2026-10-08). Analyst is a built-in role. The analyst build drops three ADR 0076 guardrails (Amendment G). Hosting is deferred to its own ADR. Rejected: a filtered `@theia/plugin-ext` analyst build, per-user limits in the developer build, VS Code for analysts, a Steps editor in the web console. Spec: [`docs/design/theia-analyst-editor.md`](../design/theia-analyst-editor.md) | **Proposed (2026-10-07)** -- doc-only, no editor code. Merging records it as Proposed and accepts nothing; Accepted needs the owner. Licence AGPL-3.0-or-later (owner ruling). Open: spikes S-1 to S-4 (S-1 is met except its Test and language-server legs, measured on a browser target; S-2 is met on the browser build and on Electron, spike S-2b; S-4's classifier half is met by a prototype and its base-ref workflow half is untested), the start-up probe route (an implementation detail), and the differences ADR 0076 Amendment G, G.7, records between PR 2155's lens code and its rules | | [0209](0209-mllp-and-tcp-deliveries-refuse-a-payload-holding-more-than-one-msh.md) | **MLLP and TCP deliveries refuse a payload holding more than one MSH** (vault BACKLOG #2858; the outbound decision ADR 0206 rule 5 deferred) -- an MLLP or TCP delivery refuses a payload that opens with `MSH` and holds a second `MSH` line, CR or LF line ends alike, as `NegativeAckError(permanent=True)` with code `multiple-messages` and content-free text. The check sits in `check_frame_bytes`, so a live send, each batch member (judged as stored) and a shadow outbound give one answer; the ingress guard's reading moves to `parsing/split.py`, beside the delivery's, and a test holds the two to one answer. No batch-sender opt-out: ADR 0082's `BHS` envelope is the batch path and is never read, nor is an X12 relay or any payload not led by `MSH`. HTTP and File outbounds are out of scope. Rejected: a declared batch sender, splitting into N frames, refusing on every outbound, a `check_frame`-only check | **Accepted (2026-10-17, on build)** -- decision delegated by the owner under the driver rule and taken by the batch 265 Manager; the owner may overrule at review. Built with the change. Severity conditional per CLAUDE.md section 0 | -| [0210](0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md) | **Session supersession follows a time-bounded retired-hash lineage** (vault BACKLOG #3028; extends #2146, engine PR 2028) -- each session rotation writes a `session_lineage` link (retired hash, successor hash, `retired_at`) in its own transaction, on SQLite, Postgres and SQL Server. The login supersession follows those links over any number of hops (at most 32) to the live end and revokes it in the same transaction, for `oidc_flow_ttl_seconds` plus 120 seconds after each rotation; the session reaper purges older links. No session read consults the table, so a retired hash authenticates nothing; a test pins the readers per backend. The links are unsealed, because a forged one can only direct a revoke, which needs no key. One shared walk, so #3029 can reuse it. Rejected: a `previous_hash` column, a revoked tombstone row, a per-sign-in start-time bound. Open: an elevation older than the window, such as a second holder's, is not followed. Amendment A (2026-10-28, BACKLOG #3715): the sign-out follows them too, for 5 seconds, which gives a retired token a second, credential-free end-only power on `/ui/logout`. Amendment B (2026-11-24, vault BACKLOG #4276): the database's own clock stamps each link and measures the window, so an engine clock step or skew between engine hosts no longer moves it; a step of the store's own clock still does | **Accepted (2026-10-17, on build)** -- design set by the batch 257 Manager's brief; the owner may overrule at review. Severity conditional per CLAUDE.md section 0 | +| [0210](0210-session-supersession-follows-a-time-bounded-retired-hash-lineage.md) | **Session supersession follows a time-bounded retired-hash lineage** (vault BACKLOG #3028; extends #2146, engine PR 2028) -- each session rotation writes a `session_lineage` link (retired hash, successor hash, `retired_at`) in its own transaction, on SQLite, Postgres and SQL Server. The login supersession follows those links over any number of hops (at most 32) to the live end and revokes it in the same transaction, for `oidc_flow_ttl_seconds` plus 120 seconds after each rotation; the session reaper purges older links. No session read consults the table, so a retired hash authenticates nothing; a test pins the readers per backend. The links are unsealed, because a forged one can only direct a revoke, which needs no key. One shared walk, so #3029 can reuse it. Rejected: a `previous_hash` column, a revoked tombstone row, a per-sign-in start-time bound. Open: an elevation older than the window, such as a second holder's, is not followed. Amendment A (2026-10-28, BACKLOG #3715): the sign-out follows them too, for 5 seconds, which gives a retired token a second, credential-free end-only power on `/ui/logout`. Amendment B (2026-11-24, vault BACKLOG #4276): the database's own clock stamps each link and measures the window, so on PostgreSQL and SQL Server an engine host's clock step or skew between engine hosts no longer moves it; a step of the store's own clock still does, and on SQLite that is the engine host's clock | **Accepted (2026-10-17, on build)** -- design set by the batch 257 Manager's brief; the owner may overrule at review. Severity conditional per CLAUDE.md section 0 | | [0211](0211-afk-autonomy-controls-decision-log-kill-switch-tripwires-digest.md) | **AFK-autonomy controls: decision log, kill switch, tripwires, digest** (docs/AUTONOMY-PLAN.md section 4, wave 1) -- the decision log is one private vault issue per UTC day with one comment per record, spooled locally first so a network failure loses nothing and the tripwire hook logs offline; the record schema (class, predicates with evidence, recommendation, alternatives, undo path, stated confidence, reviewed, outcome). The kill switch is the repository variable `MEFOR_AFK_KILL`, read over REST and fail-safe: only `off` is OFF, and a SessionStart banner shows ON. A non-blocking tripwire hook in the shell-guard dispatcher records `--no-verify`, force pushes, ref deletions, `reset --hard`, `-Force` on remove.ps1 or claim.ps1, `-AllowOrphanedAllocations` and a write to the kill switch; it does not stop the act, so section 4.4 is not met, and the other section 4.4 tripwires are rules only. Who rates and who sets the switch are rules only: every seat holds one identity. A private daily digest carries a blind sample with the recommendation hidden, owner ratings, and per seat and class the trailing-60 disagreement and 14-day reversal rate. Rejected: a JSONL file in the vault, a local file alone | **Accepted (2026-10-21, on build)** -- the owner approved the plan on 2026-10-21; storage, schema and the enforcement split are this build's design, and the owner may overrule at review. **Amended 2026-10-22:** the `-Banner` hook also tells non-Special sessions to load driver and empower while the switch reads OFF; the ON banner does not. Open: the owner or Lander sets `MEFOR_AFK_KILL` to `off`; until then every session reads ON | | [0212](0212-enterworktree-safety-check.md) | **EnterWorktree safety check** (owner request in session, 2026-10-21) -- a PreToolUse hook on `EnterWorktree` runs the read-only `scripts/worktree/enter-check.ps1` and shows its verdict in the owner's permission prompt: `ask` with a reason starting `enter-check: SAFE` or `enter-check: UNSAFE` and the first reasons. It never allows and never denies, and annotates only a prompt the harness shows anyway (ADR section 2 says where); on the local OFF file or any fault it returns no decision. SAFE needs six checks to pass, listed in the ADR: in short, a session's own scratchpad worktree, at an untouched commit of the remote's `main`, entered from outside any primary. Auto-allow is deferred until the allow comes from an installed copy outside session-writable trees: the hook and check run from the session's own tree, and the reviews found at least twelve SAFE-when-unsafe paths, at least ten still open, those found listed in the ADR. Silence per machine with the OFF file, or permanently by removing the settings entry. Rejected: allowing `.claude/worktrees/`, `-like` matching, a list of protected paths, a fail-open check, `allow` on SAFE, `deny` on UNSAFE | **Accepted (2026-10-21, on build; advisory 2026-10-22)** -- the owner asked for it in session; the Manager set the design and, after the third review pass, made the hook advisory (class B); the owner may overrule at review | | [0213](0213-seal-the-secret-rotation-fingerprint-as-a-store-cipher-cell.md) | **Seal the secret-rotation fingerprint as a store-cipher cell** (vault BACKLOG #3472, #3247 item 1) -- each non-DEK `secret_rotation_meta.fingerprint` becomes a store-cipher cell holding a per-row random HMAC key, the value's MAC and the row's class id, AAD-bound to its row and stored behind the `sealed-hmac-sha256-32` tag. `rotate-key`'s `reencrypt_to_active` re-seals it on all three backends, so a store key rotation no longer moves every fingerprint and no start needs the retired key. A cell the engine cannot read, and every pre-#3472 row, keeps its dates: an old row never resets a clock. `vault_transit` stays off (#3473). Supersedes the #2242 re-key rule and removes the DEK-derived fingerprint key. Rejected: carrying retired fingerprint keys forward (A, the fallback), a random per-store key, recomputing in `rotate-key`, a non-rotating derivation | **Accepted (2026-10-26)** -- owner ruling 2026-10-26, in session (batch 343 Manager), option "S: seal as cipher cell"; built with the change | diff --git a/messagefoundry/api/app.py b/messagefoundry/api/app.py index 73c464db26..2d11a6bbdc 100644 --- a/messagefoundry/api/app.py +++ b/messagefoundry/api/app.py @@ -12237,9 +12237,13 @@ async def _session_reaper( idle-expired rows go too (BACKLOG #2096); the lifespan passes the idle timeout the validator uses. With ``lineage_seconds`` given, session lineage links older than that go too (vault BACKLOG #3028); the lifespan passes the window the supersession follows them for. The store - measures that age on its own clock, the one the supersession measures its window on (vault - BACKLOG #4276), never from the ``now`` passed below, so the guard below does not cover the - links and need not: the purge drops only a link the supersession would no longer follow. + measures a link's age on its own clock, the one the supersession measures its window on (vault + BACKLOG #4276), never from the ``now`` passed below. So the reaper asks for that window plus + ``_SESSION_REAP_STEP_TOLERANCE``: a forward step of the store's clock no larger than that, which + the guard below lets through, or cannot see at all when the store's clock is a database + server's, then cannot make the purge delete a link the supersession would follow once the clock + is set right. A larger step of a database server's clock still can. + The cost is that a link waits that much longer to go, and the supersession ignores it meanwhile. **The reaper skips a pass when the wall clock has jumped forward (BACKLOG #2283).** The purge judges expiry and idleness by the wall clock, and its deletes cannot be undone. Run just after @@ -12300,7 +12304,11 @@ def _clocks() -> tuple[float, float]: await store.purge_expired_sessions( now=now - _SESSION_REAP_STEP_TOLERANCE, idle_seconds=idle_seconds, - lineage_seconds=lineage_seconds, + lineage_seconds=( + None + if lineage_seconds is None + else lineage_seconds + _SESSION_REAP_STEP_TOLERANCE + ), ) except asyncio.CancelledError: raise diff --git a/messagefoundry/api/auth_routes.py b/messagefoundry/api/auth_routes.py index eaf29244b2..0ae4564acd 100644 --- a/messagefoundry/api/auth_routes.py +++ b/messagefoundry/api/auth_routes.py @@ -299,9 +299,11 @@ async def _service(request: Request) -> AuthService: async def _arrival() -> float: - """The wall-clock moment a route's dependencies began to be solved, for ``POST /auth/logout`` - (BACKLOG #3715). Wall clock, because the store stamps a lineage link with ``time.time()``.""" - return time.time() + """The moment a route's dependencies began to be solved, for ``POST /auth/logout`` (BACKLOG + #3715), on the monotonic clock. The sign-out measures only the time since it, and the store + measures the window on its own clock (vault BACKLOG #4276), so a wall-clock step between the + two readings must not move it.""" + return time.monotonic() def _current_user(identity: Identity) -> CurrentUser: diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index aa894a94ae..2cb6e68c29 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -14674,11 +14674,12 @@ async def logout( record ``nothing_to_revoke`` for a session this call ended. Links retired up to :data:`_LOGOUT_LINEAGE_SECONDS` before ``proven_at`` are followed. The store measures that window back from its own clock, which also stamps every link (vault BACKLOG #4276), so it - asks for the bound plus the time since ``proven_at`` on this process's clock. The slack - covers a link stamped before its rotation commits. + asks for the bound plus the time since ``proven_at``, and adds any wait of its own. The + slack covers a link stamped before its rotation commits. - ``proven_at`` has no default, so every caller states what it proved. ``POST /auth/logout`` - passes the moment its request arrived. Its gate proved the token live after that, so any + ``proven_at`` has no default, so every caller states what it proved. It is a + :func:`time.monotonic` reading, never a wall-clock one, so no clock step moves the window. + ``POST /auth/logout`` passes the moment its request arrived. Its gate proved the token live after that, so any link from it was committed after that proof, and the route gains no reach: the caller could sign that session out anyway. ``/ui/logout`` proves nothing about the token and passes ``None``, and the bound is measured from the call. For those seconds a holder of a RETIRED @@ -14728,9 +14729,9 @@ async def logout( presented = hash_token(token) before = time.time() # A length back from the store's own clock (vault BACKLOG #4276): the bound, plus the time - # since the proof. That time is two readings of this process's clock, never compared with a - # link's stamp; a step backward between them is read as no time at all. - elapsed = 0.0 if proven_at is None else max(0.0, before - proven_at) + # since the proof, on the monotonic clock `proven_at` was read on, so no wall-clock step + # moves it. The store adds any wait of its own, so the window starts where it did. + elapsed = 0.0 if proven_at is None else max(0.0, time.monotonic() - proven_at) ended = await self._supersede_session( presented, now=before, lineage_seconds=_LOGOUT_LINEAGE_SECONDS + elapsed ) @@ -15021,8 +15022,9 @@ async def _supersede_session_hash(self, prior_hash: str, *, client: str | None) each rotation wrote to the session's live end and revokes that, in the same transaction. Only links retired within :attr:`supersession_lineage_seconds` of now, on the store's own clock, are followed: the store stamps each link and measures the window on that one clock - (vault BACKLOG #4276), so this process's clock, and skew between engine hosts, do not move - the bound. A step of the store's own clock still does. This and + (vault BACKLOG #4276). On a server store this process's clock, and skew between engine + hosts, do not move the bound. A step of the store's own clock still does, and on SQLite + that is this host's clock. This and :meth:`logout` are the only places a retired hash leads anywhere, and it leads only to an end. An elevation that finished longer ago than that, such as one a second holder of the token completed diff --git a/messagefoundry/store/base.py b/messagefoundry/store/base.py index 90901fc2eb..6d989fe1de 100644 --- a/messagefoundry/store/base.py +++ b/messagefoundry/store/base.py @@ -3622,9 +3622,10 @@ async def supersede_session( live end, inside one transaction. A link retired more than ``lineage_seconds`` before the database's own clock, read in the walk's own statement, is not followed, so a retired hash leads anywhere only for a bounded time; the caller chooses the bound, because the store - reads no settings. The stamp and the test read one clock, the database's, so neither an - engine process's clock step nor skew between engine hosts moves the bound (vault BACKLOG - #4276). ``now`` stamps only the revoke. On Postgres and SQL Server a rotation can still commit + reads no settings. The stamp and the test read one clock, the database's (vault BACKLOG + #4276), so on a server store neither an engine host's clock step nor skew between engine + hosts moves the bound; on SQLite the database's clock is the engine host's. Time the call + spends waiting is added back to the window, so no wait shortens it. ``now`` stamps only the revoke. On Postgres and SQL Server a rotation can still commit between two steps; it costs the walk one more step, never the revoke, because each step revokes before it reads a link. ``store/session_lineage.py`` says why that order is the control. With diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index a47d70392b..d59b61f6ea 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -12298,6 +12298,7 @@ async def supersede_session( Each step's ``UPDATE ... RETURNING`` locks the row it ends. Under READ COMMITTED each statement reads what has committed when it starts, so a rotation that commits while the walk runs is seen by the next step's lineage read. The borrow stays bounded, as it was.""" + started = time.monotonic() # before the borrow, so its wait cannot shorten the window async with self._timed_acquire(record=False) as conn, conn.transaction(): async def _revoke(h: str) -> SessionRecord | None: @@ -12317,6 +12318,7 @@ async def _successor(h: str, seconds: float) -> str | None: return await revoke_through_lineage( token_hash, lineage_seconds=lineage_seconds, + started=started, revoke=_revoke, successor=_successor, ) diff --git a/messagefoundry/store/session_lineage.py b/messagefoundry/store/session_lineage.py index 8f62b68577..84f1de3088 100644 --- a/messagefoundry/store/session_lineage.py +++ b/messagefoundry/store/session_lineage.py @@ -7,14 +7,21 @@ retired hash, the hash that replaced it, and when. This module holds the one walk over those rows that every backend shares, so the three cannot disagree on how far it goes. -**"When" is the store's own clock, never an engine process's (vault BACKLOG #4276).** A link's -``retired_at`` is stamped from the database's clock inside the rotation's own statement, and the -window a walk follows links for is measured back from the database's clock inside the walk's own -statements. So the stamp and the test read ONE clock, whichever engine process elevated and -whichever signs in. A forward step of an engine process's clock, or skew between engine hosts that -share the store, no longer drops a link inside the window. A step of the store's own clock between -the rotation and the walk still moves the window by the size of the step. On SQLite that clock is -the clock of the host that holds the database file, which every engine shard opens. +**"When" is the store's own clock, never a reading an engine process passes in (vault BACKLOG +#4276).** A link's ``retired_at`` is stamped from the database's clock inside the rotation's own +statement, and the window a walk follows links for is measured back from the database's clock inside +the walk's own statements. So the stamp and the test read ONE clock, whichever engine process +elevated and whichever signs in. On PostgreSQL and SQL Server that clock is the database server's, +so a clock step on an engine host, or skew between engine hosts that share the store, no longer +drops a link inside the window. A step of the store's own clock between the rotation and the walk +still moves the window by the size of the step. **On SQLite the store's clock IS the engine host's +clock:** SQLite reads the host clock, and every engine shard runs on the host that holds the +database file. So on SQLite a step of that host's clock still moves the window, as it did before. + +The time a store call spends waiting, for its lock, a connection or a row lock, or between the hops +of one walk, is added back to the window on the engine's monotonic clock (the walk's +``started``). So the window starts where it did when the caller measured it from a fixed +instant, before the wait, and no wait shortens it. **A retired hash authenticates nothing.** No session read consults this table: ``get_session``, ``list_sessions`` and the service's session loader read ``sessions`` only. The one reader is the @@ -28,6 +35,7 @@ from __future__ import annotations +import time from collections.abc import Awaitable, Callable from typing import TYPE_CHECKING, Final @@ -51,6 +59,7 @@ async def revoke_through_lineage( token_hash: str, *, lineage_seconds: float | None, + started: float, revoke: Revoke, successor: Successor, ) -> SessionRecord | None: @@ -66,8 +75,11 @@ async def revoke_through_lineage( its end afterwards would aim the revoke at a hash such a rotation had already retired. ``lineage_seconds`` is how long before the store's own clock, read at each lookup, a followed - link may have been retired. ``None`` follows no link at all, which is the plain revoke of the - hash given (BACKLOG #2146's behaviour). + link may have been retired, as of ``started``. ``None`` follows no link at all, which is the + plain revoke of the hash given (BACKLOG #2146's behaviour). ``started`` is a + :func:`time.monotonic` reading taken when the store call began, before any wait; each lookup + asks for ``lineage_seconds`` plus the time since then, so no wait inside the call shortens the + window. Returns the row it revoked, whose ``token_hash`` is the hash it ended under, or ``None`` when the walk reached a hash with no unrevoked row and no live link, or ran out of hops.""" @@ -76,7 +88,8 @@ async def revoke_through_lineage( ended = await revoke(current) if ended is not None or lineage_seconds is None or hop == LINEAGE_MAX_HOPS: return ended - following = await successor(current, lineage_seconds) + waited = max(0.0, time.monotonic() - started) + following = await successor(current, lineage_seconds + waited) if following is None: return None current = following diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index 076de3756b..c4742582a9 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -17821,6 +17821,7 @@ async def supersede_session( which a session-wide ``SET NOCOUNT ON`` cannot hide (BACKLOG #2283). Each statement reads what has committed when it runs, so a rotation that commits while the walk runs is seen by the next step's lineage read. Committed as a durable write, never as a READ.""" + started = time.monotonic() # before the borrow, so its wait cannot shorten the window async with self._acquire() as conn, self._cursor(conn) as cur: async def _revoke(h: str) -> SessionRecord | None: @@ -17843,6 +17844,7 @@ async def _successor(h: str, seconds: float) -> str | None: ended = await revoke_through_lineage( token_hash, lineage_seconds=lineage_seconds, + started=started, revoke=_revoke, successor=_successor, ) diff --git a/messagefoundry/store/store.py b/messagefoundry/store/store.py index 61d1814b3e..640f36b154 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -22476,6 +22476,7 @@ async def supersede_session( unit: the writer lock orders them against every in-process writer, ``rotate_session`` included. The first ``UPDATE`` takes SQLite's write lock even when it matches no row, and holds it until the commit, so no other process can re-key a row while the walk runs.""" + started = time.monotonic() # before the lock, so its wait cannot shorten the window async def _revoke(h: str) -> SessionRecord | None: cur = await self._db.execute( @@ -22499,6 +22500,7 @@ async def _successor(h: str, seconds: float) -> str | None: ended = await revoke_through_lineage( token_hash, lineage_seconds=lineage_seconds, + started=started, revoke=_revoke, successor=_successor, ) diff --git a/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py b/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py index d9959edac4..8ed4897448 100644 --- a/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py +++ b/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py @@ -41,11 +41,11 @@ from messagefoundry_webconsole import pages from messagefoundry_webconsole._html import minimal_nav from tests._logout_rows import ( - age_session_links, logout_details, logout_rows, temp_password_expired_rows, ) +from tests._session_rotation_contract import age_sqlite_session_links PW = "a-strong-test-passphrase" # >=15, no app/vendor terms — satisfies the ASVS policy (WP-3) @@ -326,18 +326,18 @@ async def _sign_out_with(engine: Engine, service: AuthService, cookie: str) -> h async def test_ui_logout_with_a_cookie_an_elevation_just_retired_ends_its_successor( - engine: Engine, monkeypatch: pytest.MonkeyPatch + engine: Engine, ) -> None: """BACKLOG #3715, #3749 item 3. An elevation in another tab re-keys the session while this tab's sign-out is in flight, so the cookie it sends names no session. Within 5 seconds of the elevation the sign-out follows the link, ends the session under its new token, and the - row names the owner, where it used to keep a NULL actor and leave the session live. The clock - is FROZEN 2 seconds inside the bound, read after the rotation, so runner speed cannot move it.""" + row names the owner, where it used to keep a NULL actor and leave the session live. The link + is aged 3 seconds on the store's clock, the one the window is measured on (vault BACKLOG + #4276), so it sits 2 seconds inside the bound less the time the sign-out itself takes.""" service, old = await _signed_in_operator(engine) successor = await service._rotate_session_token(old) assert successor is not None, "the rotation failed closed, so the race was not driven" - rotated_at = time.time() - monkeypatch.setattr(time, "time", lambda: rotated_at + _LOGOUT_LINEAGE_SECONDS - 2.0) + await age_sqlite_session_links(engine.store, _LOGOUT_LINEAGE_SECONDS - 2.0) out = await _sign_out_with(engine, service, old) assert out.status_code == 303 assert await service.identity_for_token(successor, activity=False) is None @@ -361,7 +361,7 @@ async def test_ui_logout_with_a_cookie_retired_past_the_window_ends_nothing( service, old = await _signed_in_operator(engine) successor = await service._rotate_session_token(old) assert successor is not None - await age_session_links(engine.store, _LOGOUT_LINEAGE_SECONDS + 1.0) + await age_sqlite_session_links(engine.store, _LOGOUT_LINEAGE_SECONDS + 1.0) out = await _sign_out_with(engine, service, old) assert out.status_code == 303 assert await service.identity_for_token(successor, activity=False) is not None diff --git a/tests/_logout_rows.py b/tests/_logout_rows.py index 71ccd5d4a5..7660a332da 100644 --- a/tests/_logout_rows.py +++ b/tests/_logout_rows.py @@ -24,18 +24,6 @@ async def logout_rows( ] -async def age_session_links(store: Any, seconds: float) -> None: - """Move every ``session_lineage`` link of a SQLite ``MessageStore`` ``seconds`` into the past. - - The store stamps a link and measures the window a revoke follows it for on the DATABASE's - clock, not on ``time.time`` (vault BACKLOG #4276), so patching ``time`` no longer ages a link. - This is how a test puts a link past a window instead.""" - await store._db.execute( - "UPDATE session_lineage SET retired_at = retired_at - ?", (float(seconds),) - ) - await store._db.commit() - - async def temp_password_expired_rows(store: Any) -> list[tuple[object, object, object]]: """Each ``auth.temp_password_expired`` row, newest first, as its actor, client address and whole ``detail``: the row a sign-out writes when it ends a session whose temporary credential diff --git a/tests/_session_rotation_contract.py b/tests/_session_rotation_contract.py index 5ae9464881..4a1124079c 100644 --- a/tests/_session_rotation_contract.py +++ b/tests/_session_rotation_contract.py @@ -25,10 +25,14 @@ from __future__ import annotations +import asyncio import secrets import time from typing import Any +#: Real seconds between two lineage links in the contract, so a window can fall between their ages. +_LINK_GAP_SECONDS = 2.0 + def _h() -> str: """A 64-char hex token hash — the exact shape ``hash_token`` produces, and the width SQL @@ -36,6 +40,20 @@ def _h() -> str: return secrets.token_hex(32) +async def age_sqlite_session_links(store: Any, seconds: float) -> None: + """Move every ``session_lineage`` link of a SQLite ``MessageStore`` ``seconds`` into the past. + SQLite only: it writes through the store's own connection, ``store._db``. + + The store stamps a link and measures the window a revoke follows it for on the DATABASE's + clock, not on ``time.time`` (vault BACKLOG #4276), so patching ``time`` no longer ages a link. + This is how a SQLite test puts a link past a window instead. The backend-neutral contract + below ages links by waiting instead.""" + await store._db.execute( + "UPDATE session_lineage SET retired_at = retired_at - ?", (float(seconds),) + ) + await store._db.commit() + + async def _count_sessions(store: Any, user_id: str) -> int: """Every session row for ``user_id``, revoked ones INCLUDED. @@ -305,20 +323,44 @@ async def assert_session_lineage_contract(store: Any, *, user_id: str = "lin-u1" kept = await store.get_session(d) assert kept is not None and kept.revoked_at is None - # --- the purge measures on the database's clock: a `now` ahead of it drops no live link, and a - # window that ends after the database's present drops every link --------------------------- + # --- one window between two links' ages follows and keeps the younger only ----------------- old, old_next, fresh, fresh_next = _h(), _h(), _h(), _h() await store.create_session(token_hash=old, user_id=user_id, expires_at=expires, now=now) await store.create_session(token_hash=fresh, user_id=user_id, expires_at=expires, now=now) assert await store.rotate_session(old, new_token_hash=old_next) is True + # Real time between the two links, so one window can sit between their ages on the database's + # clock: this is what shows each backend stamps and measures in the same unit and epoch. + await asyncio.sleep(_LINK_GAP_SECONDS) + fresh_from = time.monotonic() assert await store.rotate_session(fresh, new_token_hash=fresh_next) is True await store.purge_expired_sessions(now=now) # no window: every link stays + + def _between() -> float: + # Older than the fresh link by a margin, younger than the old one by about as much. + return (time.monotonic() - fresh_from) + _LINK_GAP_SECONDS / 2 + + assert await store.supersede_session(old, now=now, lineage_seconds=_between()) is None, ( + "a window shorter than a link's age followed it" + ) + await store.purge_expired_sessions(now=now, lineage_seconds=_between()) + assert await store.supersede_session(old, now=now, lineage_seconds=10_000) is None, ( + "a purge kept a link older than its window" + ) + old_live = await store.get_session(old_next) + assert old_live is not None and old_live.revoked_at is None + + # --- a `now` far ahead of the database's clock leaves a live link alone --------------------- await store.purge_expired_sessions(now=ahead, lineage_seconds=600) swept = await store.supersede_session(fresh, now=now + 7, lineage_seconds=60) assert swept is not None and swept.token_hash == fresh_next, "the purge dropped a live link" + + # --- a window that ends after the database's present drops every link ---------------------- + last, last_next = _h(), _h() + await store.create_session(token_hash=last, user_id=user_id, expires_at=expires, now=now) + assert await store.rotate_session(last, new_token_hash=last_next) is True await store.purge_expired_sessions(now=now, lineage_seconds=-60) - assert await store.supersede_session(old, now=now, lineage_seconds=10_000) is None, ( + assert await store.supersede_session(last, now=now, lineage_seconds=10_000) is None, ( "a link past the purge window survived the purge" ) - survivor = await store.get_session(old_next) + survivor = await store.get_session(last_next) assert survivor is not None and survivor.revoked_at is None diff --git a/tests/test_api_auth.py b/tests/test_api_auth.py index 47c30b1707..60564bfe36 100644 --- a/tests/test_api_auth.py +++ b/tests/test_api_auth.py @@ -680,21 +680,33 @@ async def test_logout_passes_a_proven_at_read_before_its_gate( engine: Engine, monkeypatch: pytest.MonkeyPatch ) -> None: """BACKLOG #3715. ``POST /auth/logout`` passes a ``proven_at`` read during the request and - before its gate reads the session; ``AuthService.logout`` says why. The clock ticks on every - read, so "before" is a strict order. ``proven_at=None`` fails here.""" + before its gate reads the session; ``AuthService.logout`` says why. It is a monotonic reading + (vault BACKLOG #4276), so the route's ``time.monotonic`` is replaced by a clock that ticks on + every read, which makes "before" a strict order; the event loop's own clock is left alone. + ``proven_at=None`` fails here.""" + from messagefoundry.api import auth_routes + service = await _service(engine) await _add(service, "u", Role.VIEWER) async with _client(engine, service) as c: token = (await _login(c, "u")).json()["token"] - start = time.time() + start = time.monotonic() ticks = iter(range(1, 10**9)) - monkeypatch.setattr(time, "time", lambda: start + next(ticks) * 0.001) + + def _tick() -> float: + return start + next(ticks) * 0.001 + + class _RouteTime: + def __getattr__(self, name: str) -> Any: + return _tick if name == "monotonic" else getattr(time, name) + + monkeypatch.setattr(auth_routes, "time", _RouteTime()) gate_reads: list[float] = [] real_get_session = engine.store.get_session async def _timed_get_session(*args: Any, **kwargs: Any) -> Any: - gate_reads.append(time.time()) + gate_reads.append(_tick()) return await real_get_session(*args, **kwargs) monkeypatch.setattr(engine.store, "get_session", _timed_get_session) @@ -707,7 +719,7 @@ async def _spy_logout(token: str | None, **kwargs: Any) -> Any: monkeypatch.setattr(service, "logout", _spy_logout) async with _client(engine, service) as c: - sent = time.time() + sent = _tick() assert (await c.post("/auth/logout", headers=_auth(token))).status_code == 200 assert gate_reads, "the gate never read the session, so this measured nothing" assert len(proven) == 1 @@ -715,7 +727,7 @@ async def _spy_logout(token: str | None, **kwargs: Any) -> Any: "the route passed no proven_at, so it took the credential-free bound" ) assert sent < proven[0] < gate_reads[0], ( - "proven_at is not a wall-clock read taken during this request, before the gate" + "proven_at is not a monotonic read taken during this request, before the gate" ) @@ -3598,7 +3610,7 @@ async def test_a_logout_whose_credential_lapsed_after_its_gate_records_lapsed( assert await service.identity_for_token(outcome.token) is not None await _move_deadline_to(engine, ned_id, time.time() - 1) ended = await service.logout( - outcome.token, actor="ned", client="192.0.2.7", proven_at=time.time() + outcome.token, actor="ned", client="192.0.2.7", proven_at=time.monotonic() ) assert ended == "lapsed" assert await logout_rows(engine.store) == [("ned", "192.0.2.7", "lapsed")] diff --git a/tests/test_session_supersession.py b/tests/test_session_supersession.py index b5f78ecd6b..b6b0b8139d 100644 --- a/tests/test_session_supersession.py +++ b/tests/test_session_supersession.py @@ -41,7 +41,6 @@ from messagefoundry.store.store import MessageStore from tests._admin_account import create_local_user_chosen from tests._logout_rows import ( - age_session_links, logout_details, logout_entries, logout_rows, @@ -50,6 +49,7 @@ ) from tests._session_cap_contract import _revoked from tests._session_race import rotate_after_first_call +from tests._session_rotation_contract import age_sqlite_session_links PW = "a-strong-test-passphrase" # >=15, no app/vendor terms -- satisfies the ASVS policy (WP-3) @@ -591,8 +591,8 @@ async def test_a_logout_follows_no_rotation_older_than_its_bound_before_proven_a service = await _service(store, session_idle_timeout_minutes=30) token = await _token(service) successor = await _rotated(service, token) - await age_session_links(store, _LOGOUT_LINEAGE_SECONDS + 1.0) - outcome = await service.logout(token, client=None, actor="op", proven_at=time.time()) + await age_sqlite_session_links(store, _LOGOUT_LINEAGE_SECONDS + 1.0) + outcome = await service.logout(token, client=None, actor="op", proven_at=time.monotonic()) assert outcome == "nothing_to_revoke" assert await _live(service, successor), "a link older than the bound was followed" @@ -606,8 +606,8 @@ async def test_a_logout_follows_a_link_retired_after_an_earlier_proof( service = await _service(store, session_idle_timeout_minutes=30) token = await _token(service) successor = await _rotated(service, token) - await age_session_links(store, _LOGOUT_LINEAGE_SECONDS + 1.0) - proven = time.time() - (_LOGOUT_LINEAGE_SECONDS + 5.0) + await age_sqlite_session_links(store, _LOGOUT_LINEAGE_SECONDS + 1.0) + proven = time.monotonic() - (_LOGOUT_LINEAGE_SECONDS + 5.0) outcome = await service.logout(token, client=None, actor="op", proven_at=proven) assert outcome == "revoked" assert not await _live(service, successor) @@ -617,13 +617,15 @@ async def test_a_logout_after_a_forward_step_of_this_process_clock_still_follows store: MessageStore, monkeypatch: pytest.MonkeyPatch ) -> None: # Vault BACKLOG #4276. The process clock jumps past the bound after the rotation. The link's - # stamp and the window are both the store's clock, so the step drops nothing. + # stamp and the window are both the store's clock, so the step drops nothing. The patch moves + # Python's clock and not SQLite's, so this models an engine whose clock differs from its store's + # (a server store); on SQLite a real host step moves both, which this does not cover. service = await _service(store, session_idle_timeout_minutes=30) token = await _token(service) successor = await _rotated(service, token) real = time.time monkeypatch.setattr(time, "time", lambda: real() + _LOGOUT_LINEAGE_SECONDS + 60.0) - outcome = await service.logout(token, client=None, actor="op", proven_at=time.time()) + outcome = await service.logout(token, client=None, actor="op", proven_at=time.monotonic()) assert outcome == "revoked" assert not await _live(service, successor), "a forward step of the process clock dropped a link" @@ -635,7 +637,7 @@ async def test_a_logout_ends_the_session_a_rotation_in_flight_re_keyed( # ends its successor, and the row names both hashes. service = await _service(store, session_idle_timeout_minutes=30) token = await _token(service) - proven = time.time() + proven = time.monotonic() successor = await _rotated(service, token) outcome = await service.logout(token, client=None, actor="op", proven_at=proven) assert outcome == "revoked" diff --git a/tests/test_session_supersession_lineage.py b/tests/test_session_supersession_lineage.py index 9b52988a96..f7671f5e3c 100644 --- a/tests/test_session_supersession_lineage.py +++ b/tests/test_session_supersession_lineage.py @@ -34,7 +34,7 @@ from messagefoundry.store.session_lineage import LINEAGE_MAX_HOPS, revoke_through_lineage from messagefoundry.store.store import MessageStore, SessionRecord from tests._ast_sites import code_names, code_strings, parse_source -from tests._logout_rows import age_session_links +from tests._session_rotation_contract import age_sqlite_session_links from tests.test_session_supersession import ( PW, _live, @@ -158,7 +158,7 @@ async def test_a_link_older_than_the_window_is_not_followed(store: MessageStore) assert window >= service.oidc_flow_ttl_seconds, "the window must outlast the longest sign-in" prior = await _token(service) rotated = await _elevate(service, prior) - await age_session_links(store, window + 5) + await age_sqlite_session_links(store, window + 5) assert await _live(service, rotated) await _token(service, supersedes=prior) assert await _live(service, rotated), "a link past its window ended a session" @@ -171,7 +171,10 @@ async def test_a_forward_step_of_the_signing_in_process_clock_does_not_drop_a_li # Vault BACKLOG #4276, ASVS 7.2.4 arm (ii). The 2026-10-26 pass moved `time.time` forward 425 # seconds after one elevation, and a sign-in presenting the older token then left the rotated # session live: the link was stamped and judged on this process's clock. Both now read the - # store's clock, so the same step, past the whole window, drops nothing. + # store's clock, so the same step, past the whole window, drops nothing. The patch moves only + # Python's clock, not SQLite's, so it models an engine process whose clock differs from the + # store's, as an engine host over a PostgreSQL or SQL Server store can. On SQLite a real step + # of the host's clock moves the store's clock too, and this does not show that case closed. service = await _service(store, session_idle_timeout_minutes=240) window = service.supersession_lineage_seconds prior = await _token(service) @@ -372,7 +375,9 @@ async def purge_expired_sessions( finally: task.cancel() await asyncio.gather(task, return_exceptions=True) - assert seen[0] == 420.0 + # Plus the step tolerance: the store measures the age on its own clock, which the reaper's + # step guard does not read (vault BACKLOG #4276). + assert seen[0] == 420.0 + api_app._SESSION_REAP_STEP_TOLERANCE def test_the_lifespan_hands_the_reaper_the_supersession_window() -> None: @@ -435,7 +440,7 @@ async def _successor(h: str, since: float) -> str | None: return found ended = await revoke_through_lineage( - "a", lineage_seconds=0.0, revoke=_revoke, successor=_successor + "a", lineage_seconds=0.0, started=time.monotonic(), revoke=_revoke, successor=_successor ) assert ended is not None and ended.token_hash == "c" assert calls == ["revoke a", "follow a", "revoke b", "follow b", "revoke c"] @@ -452,10 +457,41 @@ async def _revoke(h: str) -> SessionRecord | None: return _revoke reach = await revoke_through_lineage( - "0", lineage_seconds=0.0, revoke=_revoke_only(LINEAGE_MAX_HOPS), successor=_successor + "0", + lineage_seconds=0.0, + started=time.monotonic(), + revoke=_revoke_only(LINEAGE_MAX_HOPS), + successor=_successor, ) assert reach is not None and reach.token_hash == str(LINEAGE_MAX_HOPS) past = await revoke_through_lineage( - "0", lineage_seconds=0.0, revoke=_revoke_only(LINEAGE_MAX_HOPS + 1), successor=_successor + "0", + lineage_seconds=0.0, + started=time.monotonic(), + revoke=_revoke_only(LINEAGE_MAX_HOPS + 1), + successor=_successor, ) assert past is None, "the walk followed more links than its bound" + + +async def test_the_walk_adds_the_time_since_the_store_call_began_to_the_window() -> None: + # Vault BACKLOG #4276. The store measures the window at each lookup, after any wait for its + # lock, a connection or a row lock. The walk adds the time since the call began back, so the + # window starts where a fixed instant read at the call would have started it. + asked: list[float] = [] + + async def _revoke(h: str) -> SessionRecord | None: + return None + + async def _successor(h: str, seconds: float) -> str | None: + asked.append(seconds) + return None + + await revoke_through_lineage( + "a", + lineage_seconds=5.0, + started=time.monotonic() - 30.0, + revoke=_revoke, + successor=_successor, + ) + assert len(asked) == 1 and 35.0 <= asked[0] < 40.0, asked From 2d785e2ba455ed225a08e199a8c7024b6a1ea1cf Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:37:54 -0600 Subject: [PATCH 3/3] Session lineage: state the database-clock purge residual, refuse a wall-clock proof time Review round 2. - SECURITY.md names the new residual: on a server store, a forward step of the database clock larger than the reaper's step tolerance lets a purge delete links still inside the bound. - logout refuses a proven_at ahead of the monotonic clock, the shape of a wall-clock reading, rather than silently narrowing the window. - supersession_lineage_seconds says the purge keeps links for the window plus the step tolerance. - The SQLite aging helper takes the store's writer lock; the positive /ui/logout test keeps a 4 s margin; the store docstrings point to store/session_lineage.py instead of restating the residual; the redundant float() coercions are gone. BACKLOG #4276 --- docs/SECURITY.md | 7 ++++++- messagefoundry/auth/service.py | 15 ++++++++++----- messagefoundry/store/base.py | 6 ++---- messagefoundry/store/postgres.py | 2 +- messagefoundry/store/sqlserver.py | 2 +- messagefoundry/store/store.py | 2 +- .../tests/test_ui_logout_affordance.py | 7 ++++--- tests/_session_rotation_contract.py | 9 +++++---- tests/test_session_supersession.py | 10 ++++++++++ 9 files changed, 40 insertions(+), 20 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index e9b108ce81..16139a32cc 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -6585,7 +6585,12 @@ as before this change: that one clock (vault BACKLOG #4276). On PostgreSQL and SQL Server it is the database server's, so a step of an engine host's clock, or skew between engine hosts that share the store, does not move the bound there. **On SQLite it is the engine host's own clock**, which SQLite reads and on - which every engine shard runs, so on SQLite a step of that host's clock still moves the bound. + which every engine shard runs, so on SQLite a step of that host's clock still moves the bound; +- on PostgreSQL and SQL Server, a forward step of the database server's clock larger than the + session reaper's step tolerance (`_SESSION_REAP_STEP_TOLERANCE`, 600 seconds) while a reaper + pass runs. The reaper's step guard reads only the engine's clock, so it cannot see that step, and + the purge then deletes links still inside the bound. The deletion stands after the clock is set + right. **A retired token authenticates nothing.** No session read, the validator included, consults the links; only a revoke follows them, at a sign-in's supersession or at a sign-out (below). For the diff --git a/messagefoundry/auth/service.py b/messagefoundry/auth/service.py index 2cb6e68c29..70b3725ce2 100644 --- a/messagefoundry/auth/service.py +++ b/messagefoundry/auth/service.py @@ -7211,7 +7211,8 @@ def oidc_flow_ttl_seconds(self) -> int: def supersession_lineage_seconds(self) -> float: """How long a retired session hash still leads a sign-in's supersession to the session it became (vault BACKLOG #3028, ADR 0210), in seconds. The session reaper purges links older - than this. + than this plus its step tolerance, on the store's clock (vault BACKLOG #4276; the reaper + says why). It must outlast the longest sign-in a rotation can race, because the presented hash is read at the START of the sign-in and the supersession runs at its end. The longest is the @@ -14731,7 +14732,12 @@ async def logout( # A length back from the store's own clock (vault BACKLOG #4276): the bound, plus the time # since the proof, on the monotonic clock `proven_at` was read on, so no wall-clock step # moves it. The store adds any wait of its own, so the window starts where it did. - elapsed = 0.0 if proven_at is None else max(0.0, time.monotonic() - proven_at) + ticks = time.monotonic() + if proven_at is not None and proven_at > ticks: + # A wall-clock reading, as this argument was before vault BACKLOG #4276, is far ahead + # of the monotonic clock and would silently narrow the window to the bare bound. + raise ValueError("proven_at must be a time.monotonic() reading from this process") + elapsed = 0.0 if proven_at is None else ticks - proven_at ended = await self._supersede_session( presented, now=before, lineage_seconds=_LOGOUT_LINEAGE_SECONDS + elapsed ) @@ -15022,9 +15028,8 @@ async def _supersede_session_hash(self, prior_hash: str, *, client: str | None) each rotation wrote to the session's live end and revokes that, in the same transaction. Only links retired within :attr:`supersession_lineage_seconds` of now, on the store's own clock, are followed: the store stamps each link and measures the window on that one clock - (vault BACKLOG #4276). On a server store this process's clock, and skew between engine - hosts, do not move the bound. A step of the store's own clock still does, and on SQLite - that is this host's clock. This and + (vault BACKLOG #4276); ADR 0210 Amendment B says which clock steps that leaves moving the + bound. This and :meth:`logout` are the only places a retired hash leads anywhere, and it leads only to an end. An elevation that finished longer ago than that, such as one a second holder of the token completed diff --git a/messagefoundry/store/base.py b/messagefoundry/store/base.py index 6d989fe1de..b7166b907c 100644 --- a/messagefoundry/store/base.py +++ b/messagefoundry/store/base.py @@ -3622,10 +3622,8 @@ async def supersede_session( live end, inside one transaction. A link retired more than ``lineage_seconds`` before the database's own clock, read in the walk's own statement, is not followed, so a retired hash leads anywhere only for a bounded time; the caller chooses the bound, because the store - reads no settings. The stamp and the test read one clock, the database's (vault BACKLOG - #4276), so on a server store neither an engine host's clock step nor skew between engine - hosts moves the bound; on SQLite the database's clock is the engine host's. Time the call - spends waiting is added back to the window, so no wait shortens it. ``now`` stamps only the revoke. On Postgres and SQL Server a rotation can still commit + reads no settings. The stamp and the test both read the database's clock (vault BACKLOG + #4276); ``store/session_lineage.py`` says what that closes and what it leaves open. ``now`` stamps only the revoke. On Postgres and SQL Server a rotation can still commit between two steps; it costs the walk one more step, never the revoke, because each step revokes before it reads a link. ``store/session_lineage.py`` says why that order is the control. With diff --git a/messagefoundry/store/postgres.py b/messagefoundry/store/postgres.py index d59b61f6ea..72eb2087d9 100644 --- a/messagefoundry/store/postgres.py +++ b/messagefoundry/store/postgres.py @@ -12311,7 +12311,7 @@ async def _revoke(h: str) -> SessionRecord | None: return SessionRecord.from_mapping(dict(d)) if d else None async def _successor(h: str, seconds: float) -> str | None: - found = await conn.fetchval(_PG_SESSION_LINEAGE_SUCCESSOR, h, float(seconds)) + found = await conn.fetchval(_PG_SESSION_LINEAGE_SUCCESSOR, h, seconds) return None if found is None else str(found) try: diff --git a/messagefoundry/store/sqlserver.py b/messagefoundry/store/sqlserver.py index c4742582a9..2148a2ccfe 100644 --- a/messagefoundry/store/sqlserver.py +++ b/messagefoundry/store/sqlserver.py @@ -17834,7 +17834,7 @@ async def _revoke(h: str) -> SessionRecord | None: return SessionRecord.from_mapping(rows[0]) if rows else None async def _successor(h: str, seconds: float) -> str | None: - await cur.execute(_MSSQL_SESSION_LINEAGE_SUCCESSOR, (h, float(seconds))) + await cur.execute(_MSSQL_SESSION_LINEAGE_SUCCESSOR, (h, seconds)) rows = await cur.fetchall() return str(rows[0][0]) if rows else None diff --git a/messagefoundry/store/store.py b/messagefoundry/store/store.py index 640f36b154..5f9249b146 100644 --- a/messagefoundry/store/store.py +++ b/messagefoundry/store/store.py @@ -22490,7 +22490,7 @@ async def _revoke(h: str) -> SessionRecord | None: return SessionRecord.from_mapping(dict(row)) if row else None async def _successor(h: str, seconds: float) -> str | None: - cur = await self._db.execute(_SESSION_LINEAGE_SUCCESSOR, (h, float(seconds))) + cur = await self._db.execute(_SESSION_LINEAGE_SUCCESSOR, (h, seconds)) row = await cur.fetchone() return str(row[0]) if row else None diff --git a/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py b/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py index 8ed4897448..c44ee56592 100644 --- a/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py +++ b/packaging/messagefoundry-webconsole/tests/test_ui_logout_affordance.py @@ -332,12 +332,13 @@ async def test_ui_logout_with_a_cookie_an_elevation_just_retired_ends_its_succes tab's sign-out is in flight, so the cookie it sends names no session. Within 5 seconds of the elevation the sign-out follows the link, ends the session under its new token, and the row names the owner, where it used to keep a NULL actor and leave the session live. The link - is aged 3 seconds on the store's clock, the one the window is measured on (vault BACKLOG - #4276), so it sits 2 seconds inside the bound less the time the sign-out itself takes.""" + is aged 1 second on the store's clock, the one the window is measured on (vault BACKLOG + #4276), so it sits 4 seconds inside the bound less the time the sign-out request takes before + its store call; real time, unlike the frozen clock this used, so the margin is kept wide.""" service, old = await _signed_in_operator(engine) successor = await service._rotate_session_token(old) assert successor is not None, "the rotation failed closed, so the race was not driven" - await age_sqlite_session_links(engine.store, _LOGOUT_LINEAGE_SECONDS - 2.0) + await age_sqlite_session_links(engine.store, _LOGOUT_LINEAGE_SECONDS - 4.0) out = await _sign_out_with(engine, service, old) assert out.status_code == 303 assert await service.identity_for_token(successor, activity=False) is None diff --git a/tests/_session_rotation_contract.py b/tests/_session_rotation_contract.py index 4a1124079c..26c4f883ee 100644 --- a/tests/_session_rotation_contract.py +++ b/tests/_session_rotation_contract.py @@ -48,10 +48,11 @@ async def age_sqlite_session_links(store: Any, seconds: float) -> None: clock, not on ``time.time`` (vault BACKLOG #4276), so patching ``time`` no longer ages a link. This is how a SQLite test puts a link past a window instead. The backend-neutral contract below ages links by waiting instead.""" - await store._db.execute( - "UPDATE session_lineage SET retired_at = retired_at - ?", (float(seconds),) - ) - await store._db.commit() + async with store._lock: # the store's writer lock, as its own writes take it + await store._db.execute( + "UPDATE session_lineage SET retired_at = retired_at - ?", (float(seconds),) + ) + await store._db.commit() async def _count_sessions(store: Any, user_id: str) -> int: diff --git a/tests/test_session_supersession.py b/tests/test_session_supersession.py index b6b0b8139d..b4cd9b9c67 100644 --- a/tests/test_session_supersession.py +++ b/tests/test_session_supersession.py @@ -613,6 +613,16 @@ async def test_a_logout_follows_a_link_retired_after_an_earlier_proof( assert not await _live(service, successor) +async def test_a_logout_refuses_a_wall_clock_proven_at(store: MessageStore) -> None: + # Vault BACKLOG #4276. proven_at is a monotonic reading now. A wall-clock one, which this + # argument took before, would narrow the window silently, so it is refused before any revoke. + service = await _service(store, session_idle_timeout_minutes=30) + token = await _token(service) + with pytest.raises(ValueError, match="monotonic"): + await service.logout(token, client=None, actor="op", proven_at=time.time()) + assert await _live(service, token), "the refused sign-out ended the session anyway" + + async def test_a_logout_after_a_forward_step_of_this_process_clock_still_follows_the_link( store: MessageStore, monkeypatch: pytest.MonkeyPatch ) -> None: