packages feed

shomei-postgres 0.3.0.0 → 0.4.0.0

raw patch · 14 files changed

+646/−155 lines, 14 filesdep ~shomei-coredep ~shomei-migrationsdep ~shomei-postgresPVP ok

version bump matches the API change (PVP)

Dependency ranges changed: shomei-core, shomei-migrations, shomei-postgres

API changes (from Hackage documentation)

+ Shomei.Session.Authentication.Guard.Postgres: checkAuthentication :: UserId -> AuthenticationGuard -> UTCTime -> Transaction (Either AuthError ())
+ Shomei.Session.Authentication.Guard.Postgres: lockAuthenticationUser :: UserId -> Transaction (Maybe (Text, Int64))
+ Shomei.Session.Authentication.Guard.Postgres: lockUserStmt :: Statement UUID (Maybe (Text, Int64))

Files

CHANGELOG.md view
@@ -4,6 +4,14 @@ [PVP](https://pvp.haskell.org/) and is versioned independently of the other Shōmei packages. +## 0.4.0.0 — 2026-11-25++- **Breaking:** require the Shōmei 0.4 API series.++- Revoking all of a user's sessions also revokes the delegated sessions in which that user is the actor. Revoking a service account revokes, in the same statement, its live machine sessions and the delegated sessions its backing user is subject or actor of.++- **Breaking:** recovery and generation-aware writers serialize on the user row in bounded transactions; refresh and code exchange coordinate with reset. Factor/session deletion and winner-only audit roll back together. Recovery-code replacement is now an explicit transaction.+ ## 0.3.0.0 — 2026-11-05  - **Breaking:** internal dependency bounds follow the 0.3 API series; migration dependencies require `shomei-migrations ^>=0.2.0.1`.
shomei-postgres.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: shomei-postgres-version: 0.3.0.0+version: 0.4.0.0 synopsis:   PostgreSQL adapters for Shōmei's store/publisher/signing-key ports @@ -81,6 +81,7 @@     Shomei.Persistence.Pool.Postgres     Shomei.Persistence.Transaction.Postgres     Shomei.ServiceAccount.Postgres+    Shomei.Session.Authentication.Guard.Postgres     Shomei.Session.LoginAttempt.Postgres     Shomei.Session.Postgres     Shomei.Session.RefreshToken.Postgres@@ -100,7 +101,7 @@     hasql >=1.10 && <1.11,     hasql-transaction >=1.2.1 && <1.3,     ram >=0.22 && <0.23,-    shomei-core ^>=0.3.0.0,+    shomei-core ^>=0.4.0.0,     stm >=2.5 && <2.6,     text >=2.0 && <2.2,     time >=1.12 && <1.15,@@ -118,6 +119,7 @@     -with-rtsopts=-N    build-depends:+    aeson >=2.1 && <2.3,     base >=4.18 && <5,     bytestring >=0.11 && <0.13,     containers >=0.6 && <0.9,@@ -127,9 +129,9 @@     hasql >=1.10 && <1.11,     hasql-transaction >=1.2.1 && <1.3,     ram >=0.22 && <0.23,-    shomei-core ^>=0.3.0.0,-    shomei-migrations:test-support ^>=0.2.0.1,-    shomei-postgres ^>=0.3.0.0,+    shomei-core ^>=0.4.0.0,+    shomei-migrations:test-support ^>=0.2.0.2,+    shomei-postgres ^>=0.4.0.0,     tasty >=1.4 && <1.6,     tasty-hunit >=0.10 && <0.11,     text >=2.0 && <2.2,
src/Shomei/Account/User/Postgres.hs view
@@ -28,7 +28,7 @@  type InsertUserRow = (UUID, Text, Maybe Text, Maybe Text, Text, UTCTime, UTCTime) -type UserRow = (UUID, Text, Maybe Text, Maybe Text, Text, Maybe UTCTime, UTCTime, UTCTime)+type UserRow = (UUID, Text, Maybe Text, Maybe Text, Text, Maybe UTCTime, UTCTime, UTCTime, Int64)  runUserStorePostgres ::   (Database :> es, IOE :> es, Error AuthError :> es, Clock :> es) =>@@ -98,11 +98,12 @@       status = UserActive,       emailVerifiedAt = Nothing,       createdAt = ts,-      updatedAt = ts+      updatedAt = ts,+      authenticationGeneration = 0     }  rebuildUser :: UserRow -> Either Text User-rebuildUser (uid, lid, e, dn, st, verified, c, u) = do+rebuildUser (uid, lid, e, dn, st, verified, c, u, generation) = do   loginId <- loginIdFromDb lid   email <- maybeEmailFromDb e   status <- userStatusFromText st@@ -115,12 +116,13 @@         status = status,         emailVerifiedAt = verified,         createdAt = c,-        updatedAt = u+        updatedAt = u,+        authenticationGeneration = generation       }  userRowDecoder :: D.Row UserRow userRowDecoder =-  (,,,,,,,)+  (,,,,,,,,)     <$> D.column (D.nonNullable D.uuid)     <*> D.column (D.nonNullable D.text)     <*> D.column (D.nullable D.text)@@ -129,6 +131,7 @@     <*> D.column (D.nullable D.timestamptz)     <*> D.column (D.nonNullable D.timestamptz)     <*> D.column (D.nonNullable D.timestamptz)+    <*> D.column (D.nonNullable D.int8)  insertUserStmt :: Statement InsertUserRow () insertUserStmt =@@ -153,7 +156,7 @@ findUserByIdStmt =   preparable     """-    SELECT user_id, login_id, email, display_name, status, email_verified_at, created_at, updated_at+    SELECT user_id, login_id, email, display_name, status, email_verified_at, created_at, updated_at, authentication_generation     FROM shomei.shomei_users     WHERE user_id = $1     """@@ -164,7 +167,7 @@ findUserByLoginIdStmt =   preparable     """-    SELECT user_id, login_id, email, display_name, status, email_verified_at, created_at, updated_at+    SELECT user_id, login_id, email, display_name, status, email_verified_at, created_at, updated_at, authentication_generation     FROM shomei.shomei_users     WHERE login_id = $1     """@@ -175,7 +178,7 @@ findUserByEmailStmt =   preparable     """-    SELECT user_id, login_id, email, display_name, status, email_verified_at, created_at, updated_at+    SELECT user_id, login_id, email, display_name, status, email_verified_at, created_at, updated_at, authentication_generation     FROM shomei.shomei_users     WHERE email = $1     """@@ -233,7 +236,7 @@ listUsersStmt =   preparable     """-    SELECT user_id, login_id, email, display_name, status, email_verified_at, created_at, updated_at+    SELECT user_id, login_id, email, display_name, status, email_verified_at, created_at, updated_at, authentication_generation     FROM shomei.shomei_users     WHERE ($1::text        IS NULL OR status = $1)       AND ($2::timestamptz IS NULL OR (created_at, user_id) < ($2, $3))
src/Shomei/Mfa/RecoveryCode/Postgres.hs view
@@ -24,24 +24,30 @@ import Shomei.Id (recoveryCodeIdToUUID, userIdToUUID) import Shomei.Mfa.RecoveryCode.Store (RecoveryCodeStore (..)) import Shomei.Mfa.Totp.Domain (NewRecoveryCode (..))-import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runSession)+import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runSession, runTransaction)+import Shomei.Persistence.Transaction.Postgres qualified as Tx import Shomei.Prelude+import Shomei.Session.Authentication.Guard.Postgres (checkAuthentication)  runRecoveryCodeStorePostgres ::   (Database :> es, IOE :> es, Error AuthError :> es) =>   Eff (RecoveryCodeStore : es) a ->   Eff es a runRecoveryCodeStorePostgres = interpret_ \case-  ReplaceRecoveryCodes uid newCodes -> do+  ReplaceRecoveryCodes uid guard ts newCodes -> do     let uidU = userIdToUUID uid         rows =           [ (recoveryCodeIdToUUID nc.recoveryCodeId, uidU, nc.codeHash, nc.createdAt)           | nc <- newCodes           ]-    res <- runSession do-      Session.statement uidU deleteForUserStmt-      mapM_ (`Session.statement` insertStmt) rows-    either dbFail (const (pure ())) res+    res <- runTransaction do+      checked <- checkAuthentication uid guard ts+      case checked of+        Left err -> pure (Left err)+        Right () -> do+          Tx.statement uidU deleteForUserStmt+          Right <$> mapM_ (`Tx.statement` insertStmt) rows+    either dbFail pure res   ConsumeRecoveryCode uid h t -> do     res <- runSession (Session.statement (userIdToUUID uid, h, t) consumeStmt)     either dbFail (pure . isJust) res
src/Shomei/Mfa/Totp/Postgres.hs view
@@ -62,9 +62,12 @@ import Shomei.Mfa.Totp.Domain (NewTotpCredential (..), TotpCredential (..)) import Shomei.Mfa.Totp.Store (TotpCredentialStore (..)) import Shomei.Persistence.Codec.Postgres (tshow)-import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runSession)+import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runSession, runTransaction) import Shomei.Persistence.Pool.Postgres qualified as Pool+import Shomei.Persistence.Transaction.Postgres qualified as Bounded import Shomei.Prelude+import Shomei.Session.Authentication.Guard (AuthenticationGuard (..))+import Shomei.Session.Authentication.Guard.Postgres (checkAuthentication)  -- | The AES-256-GCM key that encrypts stored TOTP secrets. Abstract: no 'Show', no JSON, so a -- leak is a type error rather than a review question. 32 bytes, held as 'BA.ScrubbedBytes'.@@ -139,7 +142,7 @@  -- | The stored row, column order matching @shomei_totp_credentials@: -- @(totp_credential_id, user_id, secret_enc, last_used_counter, confirmed_at, created_at)@.-type TotpRow = (UUID, UUID, ByteString, Maybe Int64, Maybe UTCTime, UTCTime, Int16)+type TotpRow = (UUID, UUID, ByteString, Maybe Int64, Maybe UTCTime, UTCTime, Int16, Maybe Int64)  runTotpCredentialStorePostgres ::   (Database :> es, IOE :> es, Error AuthError :> es) =>@@ -147,31 +150,49 @@   Eff (TotpCredentialStore : es) a ->   Eff es a runTotpCredentialStorePostgres key = interpret_ \case-  UpsertTotpEnrollment NewTotpCredential {totpCredentialId, userId, secret = TotpSecret raw, createdAt} -> do+  UpsertTotpEnrollment proofState NewTotpCredential {totpCredentialId, userId, secret = TotpSecret raw, createdAt} -> do     enc <- liftIO (encryptSecret key (totpCredentialIdToUUID totpCredentialId) (userIdToUUID userId) raw)-    let params = (totpCredentialIdToUUID totpCredentialId, userIdToUUID userId, enc, createdAt)-    res <- runSession (Session.statement params upsertStmt)-    either dbFail (const (pure ())) res+    let params = (totpCredentialIdToUUID totpCredentialId, userIdToUUID userId, enc, createdAt, proofState.generation)+    res <- runTransaction do+      checked <- checkAuthentication userId proofState createdAt+      case checked of+        Left err -> pure (Left err)+        Right () -> Right <$> Bounded.statement params upsertStmt+    outcome <- either dbFail pure res     pure-      TotpCredential-        { totpCredentialId,-          userId,-          secret = TotpSecret raw,-          lastUsedCounter = Nothing,-          confirmedAt = Nothing,-          createdAt-        }+      ( TotpCredential+          { authenticationGeneration = Just proofState.generation,+            totpCredentialId,+            userId,+            secret = TotpSecret raw,+            lastUsedCounter = Nothing,+            confirmedAt = Nothing,+            createdAt+          }+          <$ outcome+      )   FindTotpByUser uid -> do     res <- runSession (Session.statement (userIdToUUID uid) findByUserStmt)     row <- either dbFail pure res     traverse rebuild row-  ConfirmTotp tcid t -> do-    res <- runSession (Session.statement (totpCredentialIdToUUID tcid, t) confirmStmt)-    either dbFail (const (pure ())) res+  ConfirmTotp uid proofState tcid t -> do+    res <- runTransaction do+      checked <- checkAuthentication uid proofState t+      case checked of+        Left err -> pure (Left err)+        Right () -> Right <$> Bounded.statement (totpCredentialIdToUUID tcid, t) confirmStmt+    either dbFail pure res   SetTotpLastUsedCounter tcid c -> do     res <- runSession (Session.statement (totpCredentialIdToUUID tcid, c) setCounterStmt)     accepted <- either dbFail pure res     pure (isJust accepted)+  RemoveTotpCredential uid proofState tcid ts -> do+    res <- runTransaction do+      checked <- checkAuthentication uid proofState ts+      case checked of+        Left err -> pure (Left err)+        Right () -> Right <$> Bounded.statement (totpCredentialIdToUUID tcid, userIdToUUID uid) deleteCredentialStmt+    either dbFail pure res   DeleteTotpByUser uid -> do     res <- runSession (Session.statement (userIdToUUID uid) deleteByUserStmt)     either dbFail (const (pure ())) res@@ -180,11 +201,12 @@     rebuild row = either (throwError . InternalAuthError) pure (rebuildCredential key row)  rebuildCredential :: TotpEncryptionKey -> TotpRow -> Either Text TotpCredential-rebuildCredential key (tcid, uid, enc, lastUsed, confirmed, created, version) = do+rebuildCredential key (tcid, uid, enc, lastUsed, confirmed, created, version, generation) = do   raw <- decryptSecret key tcid uid version enc   pure     TotpCredential-      { totpCredentialId = totpCredentialIdFromUUID tcid,+      { authenticationGeneration = generation,+        totpCredentialId = totpCredentialIdFromUUID tcid,         userId = userIdFromUUID uid,         secret = TotpSecret raw,         lastUsedCounter = lastUsed,@@ -194,7 +216,7 @@  totpRowDecoder :: D.Row TotpRow totpRowDecoder =-  (,,,,,,)+  (,,,,,,,)     <$> D.column (D.nonNullable D.uuid)     <*> D.column (D.nonNullable D.uuid)     <*> D.column (D.nonNullable D.bytea)@@ -202,33 +224,36 @@     <*> D.column (D.nullable D.timestamptz)     <*> D.column (D.nonNullable D.timestamptz)     <*> D.column (D.nonNullable D.int2)+    <*> D.column (D.nullable D.int8)  selectCols :: Text-selectCols = "totp_credential_id, user_id, secret_enc, last_used_counter, confirmed_at, created_at, envelope_version"+selectCols = "totp_credential_id, user_id, secret_enc, last_used_counter, confirmed_at, created_at, envelope_version, authentication_generation"  -- | Insert, or replace an existing (unconfirmed) enrollment for the user: on a @user_id@ -- conflict the id and secret are swapped in and the counter/confirmation are reset to NULL. The -- workflow refuses to reach here when a /confirmed/ credential exists.-upsertStmt :: Statement (UUID, UUID, ByteString, UTCTime) ()+upsertStmt :: Statement (UUID, UUID, ByteString, UTCTime, Int64) () upsertStmt =   preparable     """     INSERT INTO shomei.shomei_totp_credentials-      (totp_credential_id, user_id, secret_enc, last_used_counter, confirmed_at, created_at, envelope_version)-    VALUES ($1, $2, $3, NULL, NULL, $4, 1)+      (totp_credential_id, user_id, secret_enc, last_used_counter, confirmed_at, created_at, envelope_version, authentication_generation)+    VALUES ($1, $2, $3, NULL, NULL, $4, 1, $5)     ON CONFLICT (user_id) DO UPDATE     SET totp_credential_id = EXCLUDED.totp_credential_id,         secret_enc = EXCLUDED.secret_enc,         envelope_version = 1,+        authentication_generation = EXCLUDED.authentication_generation,         last_used_counter = NULL,         confirmed_at = NULL,         created_at = EXCLUDED.created_at     """-    ( contrazip4+    ( contrazip5         (E.param (E.nonNullable E.uuid))         (E.param (E.nonNullable E.uuid))         (E.param (E.nonNullable E.bytea))         (E.param (E.nonNullable E.timestamptz))+        (E.param (E.nonNullable E.int8))     )     D.noResult @@ -328,3 +353,10 @@     "UPDATE shomei.shomei_totp_credentials SET secret_enc = $4, envelope_version = 1 WHERE totp_credential_id = $1 AND user_id = $2 AND secret_enc = $3 AND envelope_version = $5 RETURNING totp_credential_id"     (contrazip5 (E.param (E.nonNullable E.uuid)) (E.param (E.nonNullable E.uuid)) (E.param (E.nonNullable E.bytea)) (E.param (E.nonNullable E.bytea)) (E.param (E.nonNullable E.int2)))     (D.rowMaybe (D.column (D.nonNullable D.uuid)))++deleteCredentialStmt :: Statement (UUID, UUID) ()+deleteCredentialStmt =+  preparable+    "DELETE FROM shomei.shomei_totp_credentials WHERE totp_credential_id = $1 AND user_id = $2"+    (contrazip2 (E.param (E.nonNullable E.uuid)) (E.param (E.nonNullable E.uuid)))+    D.noResult
src/Shomei/OAuth/AuthorizationCode/Postgres.hs view
@@ -4,8 +4,9 @@   ) where -import Contravariant.Extras (contrazip10, contrazip2)+import Contravariant.Extras (contrazip11, contrazip2) import Data.Aeson (Result (..), Value)+import Data.Int (Int64) import Data.Set qualified as Set import Data.Text qualified as Text import Data.UUID (UUID)@@ -20,28 +21,41 @@ import Shomei.Id (sessionIdFromUUID, sessionIdToUUID, userIdFromUUID, userIdToUUID) import Shomei.OAuth.AuthorizationCode.Domain (AuthorizationCode (..), NewAuthorizationCode (..)) import Shomei.OAuth.AuthorizationCode.Store (OAuthCodeStore (..))-import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runSession)+import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runSession, runTransaction)+import Shomei.Persistence.Transaction.Postgres qualified as Tx import Shomei.Prelude+import Shomei.Session.Authentication.Guard (AuthenticationGuard (..))+import Shomei.Session.Authentication.Guard.Postgres (checkAuthentication, lockAuthenticationUser)  -- | The stored row, column order matching @shomei_oauth_authorization_codes@: -- @(code_hash, client_id, user_id, redirect_uri, scopes, nonce, code_challenge, auth_time,--- created_at, expires_at, consumed_at, session_id)@.-type CodeRow = (Text, Text, UUID, Text, Value, Maybe Text, Maybe Text, UTCTime, UTCTime, UTCTime, Maybe UTCTime, Maybe UUID)+-- created_at, expires_at, consumed_at, session_id, authentication_generation)@.+type CodeRow = (Text, Text, UUID, Text, Value, Maybe Text, Maybe Text, UTCTime, UTCTime, UTCTime, Maybe UTCTime, Maybe UUID, Maybe Int64)  runOAuthCodeStorePostgres ::   (Database :> es, IOE :> es, Error AuthError :> es) =>   Eff (OAuthCodeStore : es) a ->   Eff es a runOAuthCodeStorePostgres = interpret_ \case-  PutAuthorizationCode new -> do-    res <- runSession (Session.statement (toInsertRow new) insertStmt)-    either dbFail (const (pure ())) res+  PutAuthorizationCode proofState new -> do+    res <- runTransaction do+      checked <- checkAuthentication new.userId proofState new.createdAt+      case checked of+        Left err -> pure (Left err)+        Right () -> Right <$> Tx.statement (toInsertRow proofState new) insertStmt+    either dbFail pure res   ConsumeAuthorizationCode h t -> do     -- ONE statement. `UPDATE … WHERE consumed_at IS NULL AND expires_at > $2 RETURNING …` takes a     -- row lock and returns the row only to the transaction that flipped it, so two racing     -- exchanges of the same code cannot both receive it. Filtering expiry inside the same WHERE     -- means an expired code is never consumed and never returned.-    res <- runSession (Session.statement (h, t) consumeStmt)+    res <- runTransaction do+      owner <- Tx.statement h codeOwnerStmt+      case owner of+        Nothing -> pure Nothing+        Just uid -> do+          _ <- lockAuthenticationUser (userIdFromUUID uid)+          Tx.statement (h, t) consumeStmt     row <- either dbFail pure res     traverse rebuild row   BindAuthorizationCodeSession h sid -> do@@ -56,10 +70,10 @@     rebuild r = either (throwError . InternalAuthError) pure (rebuildCode r)  -- | The ten columns an INSERT writes; @consumed_at@ is always NULL on a fresh row.-type InsertRow = (Text, Text, UUID, Text, Value, Maybe Text, Maybe Text, UTCTime, UTCTime, UTCTime)+type InsertRow = (Text, Text, UUID, Text, Value, Maybe Text, Maybe Text, UTCTime, UTCTime, UTCTime, Int64) -toInsertRow :: NewAuthorizationCode -> InsertRow-toInsertRow NewAuthorizationCode {codeHash, clientId, redirectUri, userId, scopes, nonce, codeChallenge, authTime, createdAt, expiresAt} =+toInsertRow :: AuthenticationGuard -> NewAuthorizationCode -> InsertRow+toInsertRow proofState NewAuthorizationCode {codeHash, clientId, redirectUri, userId, scopes, nonce, codeChallenge, authTime, createdAt, expiresAt} =   ( codeHash,     clientId,     userIdToUUID userId,@@ -69,17 +83,19 @@     codeChallenge,     authTime,     createdAt,-    expiresAt+    expiresAt,+    proofState.generation   )  rebuildCode :: CodeRow -> Either Text AuthorizationCode-rebuildCode (h, cid, uid, uri, scopesJson, nonce, challenge, authTime, createdAt, expiresAt, consumedAt, sessionId) = do+rebuildCode (h, cid, uid, uri, scopesJson, nonce, challenge, authTime, createdAt, expiresAt, consumedAt, sessionId, generation) = do   scopes <- case fromJSON scopesJson of     Success ss -> Right (Set.fromList ss)     Error msg -> Left ("invalid scopes json: " <> Text.pack msg)   pure     AuthorizationCode-      { codeHash = h,+      { authenticationGeneration = generation,+        codeHash = h,         clientId = cid,         redirectUri = uri,         userId = userIdFromUUID uid,@@ -95,7 +111,7 @@  codeRowDecoder :: D.Row CodeRow codeRowDecoder =-  (,,,,,,,,,,,)+  (,,,,,,,,,,,,)     <$> D.column (D.nonNullable D.text)     <*> D.column (D.nonNullable D.text)     <*> D.column (D.nonNullable D.uuid)@@ -108,10 +124,11 @@     <*> D.column (D.nonNullable D.timestamptz)     <*> D.column (D.nullable D.timestamptz)     <*> D.column (D.nullable D.uuid)+    <*> D.column (D.nullable D.int8)  insertRowEncoder :: E.Params InsertRow insertRowEncoder =-  contrazip10+  contrazip11     (E.param (E.nonNullable E.text))     (E.param (E.nonNullable E.text))     (E.param (E.nonNullable E.uuid))@@ -122,11 +139,12 @@     (E.param (E.nonNullable E.timestamptz))     (E.param (E.nonNullable E.timestamptz))     (E.param (E.nonNullable E.timestamptz))+    (E.param (E.nonNullable E.int8))  -- | The SELECT/RETURNING column list (matches 'CodeRow' / 'codeRowDecoder' order). selectCols :: Text selectCols =-  "code_hash, client_id, user_id, redirect_uri, scopes, nonce, code_challenge, auth_time, created_at, expires_at, consumed_at, session_id"+  "code_hash, client_id, user_id, redirect_uri, scopes, nonce, code_challenge, auth_time, created_at, expires_at, consumed_at, session_id, authentication_generation"  insertStmt :: Statement InsertRow () insertStmt =@@ -134,8 +152,8 @@     """     INSERT INTO shomei.shomei_oauth_authorization_codes       (code_hash, client_id, user_id, redirect_uri, scopes, nonce, code_challenge, auth_time,-       created_at, expires_at, consumed_at, session_id)-    VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NULL, NULL)+       created_at, expires_at, consumed_at, session_id, authentication_generation)+    VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NULL, NULL, $11)     """     insertRowEncoder     D.noResult@@ -178,3 +196,10 @@     )     (contrazip2 (E.param (E.nonNullable E.text)) (E.param (E.nonNullable E.timestamptz)))     (D.rowMaybe codeRowDecoder)++codeOwnerStmt :: Statement Text (Maybe UUID)+codeOwnerStmt =+  preparable+    "SELECT user_id FROM shomei.shomei_oauth_authorization_codes WHERE code_hash = $1"+    (E.param (E.nonNullable E.text))+    (D.rowMaybe (D.column (D.nonNullable D.uuid)))
src/Shomei/Passkey/Ceremony/Postgres.hs view
@@ -4,8 +4,9 @@   ) where -import Contravariant.Extras (contrazip6)+import Contravariant.Extras (contrazip8) import Data.ByteString (ByteString)+import Data.Int (Int64) import Data.UUID (UUID) import Effectful (Eff, IOE, (:>)) import Effectful.Dispatch.Dynamic (interpret_)@@ -15,16 +16,19 @@ import Hasql.Session qualified as Session import Hasql.Statement (Statement, preparable) import Shomei.Error (AuthError (..))-import Shomei.Id (ceremonyIdFromUUID, ceremonyIdToUUID, userIdFromUUID, userIdToUUID)+import Shomei.Id (ceremonyIdFromUUID, ceremonyIdToUUID, sessionIdFromUUID, sessionIdToUUID, userIdFromUUID, userIdToUUID) import Shomei.Passkey.Ceremony.Store (PendingCeremonyStore (..)) import Shomei.Passkey.Domain (CeremonyKind (..), PendingCeremony (..))-import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runSession)+import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runSession, runTransaction)+import Shomei.Persistence.Transaction.Postgres qualified as Tx import Shomei.Prelude+import Shomei.Session.Authentication.Guard (AuthenticationGuard (..))+import Shomei.Session.Authentication.Guard.Postgres (checkAuthentication)  -- | The pending-ceremony row, column order matching -- @shomei_webauthn_pending_ceremonies@: @(ceremony_id, user_id, kind, options_blob, -- created_at, expires_at)@. @user_id@ is nullable (a passwordless ceremony has no user yet).-type CeremonyRow = (UUID, Maybe UUID, Text, ByteString, UTCTime, UTCTime)+type CeremonyRow = (UUID, Maybe UUID, Text, ByteString, UTCTime, UTCTime, Maybe Int64, Maybe UUID)  runPendingCeremonyStorePostgres ::   (Database :> es, IOE :> es, Error AuthError :> es) =>@@ -32,8 +36,16 @@   Eff es a runPendingCeremonyStorePostgres = interpret_ \case   PutPendingCeremony pc -> do-    res <- runSession (Session.statement (toRow pc) insertStmt)-    either dbFail (const (pure ())) res+    let PendingCeremony {userId, authenticationGeneration, initiatingSession, createdAt} = pc+    res <- runTransaction do+      checked <- case (userId, authenticationGeneration) of+        (Nothing, _) -> pure (Right ())+        (Just uid, Just generation) -> checkAuthentication uid (AuthenticationGuard generation initiatingSession Nothing) createdAt+        _ -> pure (Left StaleAuthentication)+      case checked of+        Left err -> pure (Left err)+        Right () -> Right <$> Tx.statement (toRow pc) insertStmt+    either dbFail pure res   TakePendingCeremony cid now' -> do     -- DELETE ... RETURNING is atomic: at most one concurrent transaction removes and     -- returns the row, so a challenge is usable at most once. We still filter on expiry@@ -64,21 +76,25 @@ pcExpiresAt PendingCeremony {expiresAt} = expiresAt  toRow :: PendingCeremony -> CeremonyRow-toRow PendingCeremony {ceremonyId, userId, kind, optionsBlob, createdAt, expiresAt} =+toRow PendingCeremony {ceremonyId, userId, kind, optionsBlob, createdAt, expiresAt, authenticationGeneration, initiatingSession} =   ( ceremonyIdToUUID ceremonyId,     fmap userIdToUUID userId,     ceremonyKindToText kind,     optionsBlob,     createdAt,-    expiresAt+    expiresAt,+    authenticationGeneration,+    sessionIdToUUID <$> initiatingSession   )  rebuildCeremony :: CeremonyRow -> Either Text PendingCeremony-rebuildCeremony (cid, uid, k, blob, ca, ea) = do+rebuildCeremony (cid, uid, k, blob, ca, ea, generation, source) = do   kind <- ceremonyKindFromText k   pure     PendingCeremony-      { ceremonyId = ceremonyIdFromUUID cid,+      { authenticationGeneration = generation,+        initiatingSession = sessionIdFromUUID <$> source,+        ceremonyId = ceremonyIdFromUUID cid,         userId = fmap userIdFromUUID uid,         kind,         optionsBlob = blob,@@ -88,34 +104,38 @@  ceremonyRowDecoder :: D.Row CeremonyRow ceremonyRowDecoder =-  (,,,,,)+  (,,,,,,,)     <$> D.column (D.nonNullable D.uuid)     <*> D.column (D.nullable D.uuid)     <*> D.column (D.nonNullable D.text)     <*> D.column (D.nonNullable D.bytea)     <*> D.column (D.nonNullable D.timestamptz)     <*> D.column (D.nonNullable D.timestamptz)+    <*> D.column (D.nullable D.int8)+    <*> D.column (D.nullable D.uuid)  ceremonyRowEncoder :: E.Params CeremonyRow ceremonyRowEncoder =-  contrazip6+  contrazip8     (E.param (E.nonNullable E.uuid))     (E.param (E.nullable E.uuid))     (E.param (E.nonNullable E.text))     (E.param (E.nonNullable E.bytea))     (E.param (E.nonNullable E.timestamptz))     (E.param (E.nonNullable E.timestamptz))+    (E.param (E.nullable E.int8))+    (E.param (E.nullable E.uuid))  selectCols :: Text-selectCols = "ceremony_id, user_id, kind, options_blob, created_at, expires_at"+selectCols = "ceremony_id, user_id, kind, options_blob, created_at, expires_at, authentication_generation, initiating_session_id"  insertStmt :: Statement CeremonyRow () insertStmt =   preparable     """     INSERT INTO shomei.shomei_webauthn_pending_ceremonies-      (ceremony_id, user_id, kind, options_blob, created_at, expires_at)-    VALUES ($1, $2, $3, $4, $5, $6)+      (ceremony_id, user_id, kind, options_blob, created_at, expires_at, authentication_generation, initiating_session_id)+    VALUES ($1, $2, $3, $4, $5, $6, $7, $8)     """     ceremonyRowEncoder     D.noResult
src/Shomei/Passkey/Postgres.hs view
@@ -37,6 +37,7 @@ import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runSession, runTransaction) import Shomei.Persistence.Transaction.Postgres qualified as Tx import Shomei.Prelude+import Shomei.Session.Authentication.Guard.Postgres (checkAuthentication)  -- | The stored-credential row, column order matching @shomei_webauthn_credentials@: -- @(passkey_id, user_id, credential_id, user_handle, public_key, sign_counter, transports,@@ -49,7 +50,7 @@   Eff (PasskeyStore : es) a ->   Eff es a runPasskeyStorePostgres = interpret_ \case-  CreatePasskey limit NewPasskeyCredential {userId, credentialId, userHandle, publicKey, signCounter, transports, label, createdAt} -> do+  CreatePasskey proofState limit NewPasskeyCredential {userId, credentialId, userHandle, publicKey, signCounter, transports, label, createdAt} -> do     pid <- genPasskeyId     let pc =           PasskeyCredential@@ -65,11 +66,14 @@               lastUsedAt = Nothing             }     res <- runTransaction do-      Tx.statement (userIdToUUID userId) enrollmentLockStmt-      count <- Tx.statement (userIdToUUID userId) countByUserStmt-      if limit < 1 || limit > 100 || count >= fromIntegral limit-        then pure (Left PasskeyLimitReached)-        else Tx.statement (toRow pc) insertStmt >> pure (Right pc)+      checked <- checkAuthentication userId proofState createdAt+      case checked of+        Left err -> pure (Left err)+        Right () -> do+          count <- Tx.statement (userIdToUUID userId) countByUserStmt+          if limit < 1 || limit > 100 || count >= fromIntegral limit+            then pure (Left PasskeyLimitReached)+            else Tx.statement (toRow pc) insertStmt >> pure (Right pc)     either dbFail pure res   FindPasskeysByUser uid -> do     res <- runSession (Session.statement (userIdToUUID uid) findByUserStmt)
src/Shomei/Persistence/Codec/Postgres.hs view
@@ -31,7 +31,7 @@ import Shomei.Account.OneTimeToken.Domain (OneTimeTokenStatus (..)) import Shomei.Account.User.Domain (UserStatus (..)) import Shomei.Prelude-import Shomei.Session.Domain (SessionKind (..), SessionStatus (..))+import Shomei.Session.Domain (SessionStatus (..), sessionKindFromText, sessionKindToText) import Shomei.Session.LoginAttempt.Domain (AttemptFactor (..), LoginOutcome (..)) import Shomei.Session.RefreshToken.Domain (RefreshTokenStatus (..)) import Shomei.SigningKey.Domain (SigningKeyStatus (..))@@ -64,19 +64,6 @@   "revoked" -> Right SessionRevoked   "expired" -> Right SessionExpired   t -> Left ("unknown session status: " <> t)--sessionKindToText :: SessionKind -> Text-sessionKindToText = \case-  InteractiveSession -> "interactive"-  MachineSession -> "machine"-  DelegatedSession -> "delegated"--sessionKindFromText :: Text -> Either Text SessionKind-sessionKindFromText = \case-  "interactive" -> Right InteractiveSession-  "machine" -> Right MachineSession-  "delegated" -> Right DelegatedSession-  t -> Left ("unknown session kind: " <> t)  refreshTokenStatusToText :: RefreshTokenStatus -> Text refreshTokenStatusToText = \case
src/Shomei/ServiceAccount/Postgres.hs view
@@ -200,13 +200,25 @@     )     D.noResult +-- | Revoke the account and, in the same statement, every live machine session it holds and+-- every delegated session in which its backing user is subject or actor. Without the second+-- half a revoked account's outstanding tokens would keep introspecting as active until expiry. revokeStmt :: Statement (UUID, UTCTime) () revokeStmt =   preparable     """-    UPDATE shomei.shomei_service_accounts+    WITH revoked AS (+      UPDATE shomei.shomei_service_accounts+      SET status = 'revoked', revoked_at = $2+      WHERE service_account_id = $1+      RETURNING user_id+    )+    UPDATE shomei.shomei_sessions AS s     SET status = 'revoked', revoked_at = $2-    WHERE service_account_id = $1+    FROM revoked+    WHERE s.status = 'active'+      AND s.kind IN ('machine', 'delegated')+      AND (s.user_id = revoked.user_id OR s.actor_user_id = revoked.user_id)     """     (contrazip2 (E.param (E.nonNullable E.uuid)) (E.param (E.nonNullable E.timestamptz)))     D.noResult
+ src/Shomei/Session/Authentication/Guard/Postgres.hs view
@@ -0,0 +1,53 @@+-- | Acquire the owning user first; all recovery-sensitive writers share this lock order.+module Shomei.Session.Authentication.Guard.Postgres (checkAuthentication, lockAuthenticationUser, lockUserStmt) where++import Contravariant.Extras (contrazip3)+import Data.Functor.Contravariant (contramap)+import Data.Int (Int64)+import Data.UUID (UUID)+import Hasql.Decoders qualified as D+import Hasql.Encoders qualified as E+import Hasql.Statement (Statement, preparable)+import Shomei.Error (AuthError (..))+import Shomei.Id (UserId, passkeyIdToUUID, sessionIdToUUID, userIdToUUID)+import Shomei.Persistence.Transaction.Postgres qualified as Tx+import Shomei.Prelude+import Shomei.Session.Authentication.Guard (AuthenticationGuard (..))++lockUserStmt :: Statement UUID (Maybe (Text, Int64))+lockUserStmt =+  preparable+    "SELECT status, authentication_generation FROM shomei.shomei_users WHERE user_id = $1 FOR UPDATE"+    (E.param (E.nonNullable E.uuid))+    (D.rowMaybe ((,) <$> D.column (D.nonNullable D.text) <*> D.column (D.nonNullable D.int8)))++lockAuthenticationUser :: UserId -> Tx.Transaction (Maybe (Text, Int64))+lockAuthenticationUser uid = Tx.statement (userIdToUUID uid) lockUserStmt++checkAuthentication :: UserId -> AuthenticationGuard -> UTCTime -> Tx.Transaction (Either AuthError ())+checkAuthentication uid proofState ts = do+  user <- lockAuthenticationUser uid+  case user of+    Just ("active", generation) | generation == proofState.generation -> do+      sessionOk <- case proofState.initiatingSession of+        Nothing -> pure True+        Just sid -> Tx.statement (sessionIdToUUID sid, userIdToUUID uid, ts) liveSessionStmt+      credentialOk <- case proofState.assertedPasskey of+        Nothing -> pure True+        Just pid -> Tx.statement (passkeyIdToUUID pid, userIdToUUID uid) credentialStmt+      pure (if sessionOk && credentialOk then Right () else Left StaleAuthentication)+    _ -> pure (Left StaleAuthentication)++liveSessionStmt :: Statement (UUID, UUID, UTCTime) Bool+liveSessionStmt =+  preparable+    "SELECT session_id FROM shomei.shomei_sessions WHERE session_id = $1 AND user_id = $2 AND status = 'active' AND expires_at > $3 FOR SHARE"+    (contrazip3 (E.param (E.nonNullable E.uuid)) (E.param (E.nonNullable E.uuid)) (E.param (E.nonNullable E.timestamptz)))+    (isJust <$> D.rowMaybe (D.column (D.nonNullable D.uuid)))++credentialStmt :: Statement (UUID, UUID) Bool+credentialStmt =+  preparable+    "SELECT passkey_id FROM shomei.shomei_webauthn_credentials WHERE passkey_id = $1 AND user_id = $2 FOR SHARE"+    (contramap fst (E.param (E.nonNullable E.uuid)) <> contramap snd (E.param (E.nonNullable E.uuid)))+    (isJust <$> D.rowMaybe (D.column (D.nonNullable D.uuid)))
src/Shomei/Session/Postgres.hs view
@@ -211,13 +211,15 @@     (contrazip2 (E.param (E.nonNullable E.uuid)) (E.param (E.nonNullable E.timestamptz)))     (D.rowList (D.column (D.nonNullable D.uuid))) --- | Shared winner-producing update, also embedded in the bulk audited CTE. No application+-- | Shared winner-producing update, also embedded in the bulk audited CTE. It covers sessions+-- in which the principal is the delegated actor as well as the subject, so suspending an+-- operator also stops the impersonation sessions that operator opened. No application -- materialization of winners is needed by that operation. revokeAllUserSessionsSql :: Text revokeAllUserSessionsSql =   """   UPDATE shomei.shomei_sessions SET status = 'revoked', revoked_at = $2-  WHERE user_id = $1 AND status = 'active'+  WHERE status = 'active' AND (user_id = $1 OR actor_user_id = $1)   RETURNING session_id   """ 
src/Shomei/Session/UnitOfWork/Postgres.hs view
@@ -7,8 +7,8 @@ -- serialized store operation rather than a workflow tail. Other interpreters issue one statement -- per 'Shomei.Persistence.Database.Postgres.runSession', which is one pool checkout per statement. ----- No SQL is written here. Every statement is the prepared 'Statement' its own store--- interpreter already uses, lifted into the transaction with 'Tx.statement'. That matters most+-- Ordinary write tails reuse the prepared statements owned by each store; recovery and+-- bulk revocation own their coordinated statements here. Each is lifted with 'Tx.statement'. This matters most -- for 'markUsedStmt', the refresh-token compare-and-swap whose shape is owned by -- @docs/plans/28-enforce-absolute-session-expiry-and-atomic-token-state-transitions.md@: this -- module moves it inside a transaction and reads its result, but never alters it.@@ -20,7 +20,9 @@ import Contravariant.Extras (contrazip3) import Data.Aeson (Value, object) import Data.Aeson qualified as Aeson+import Data.Either (isRight) import Data.Foldable (traverse_)+import Data.Functor.Contravariant (contramap) import Data.Int (Int64) import Data.Set qualified as Set import Data.UUID (UUID)@@ -31,11 +33,14 @@ import Hasql.Decoders qualified as D import Hasql.Encoders qualified as E import Hasql.Statement (Statement, preparable)+import Shomei.Account.Admin.Recovery.Domain import Shomei.Account.Credential.Postgres (updatePasswordHashStmt)+import Shomei.Account.Email.Domain (parseStoredEmail) import Shomei.Account.Password.Domain (PasswordHash (..)) import Shomei.Account.PasswordReset.Postgres qualified as PR import Shomei.Audit.Event.Codec (projectAuthEvent) import Shomei.Audit.Event.Domain (AuthEvent)+import Shomei.Audit.Event.Domain qualified as Event import Shomei.Audit.Publisher.Postgres (AuthEventRow, insertAuthEventStmt) import Shomei.Authorization.Claims.Domain (Scope (..)) import Shomei.Error (AuthError (..))@@ -46,13 +51,16 @@     passwordResetTokenIdToUUID,     refreshTokenIdToUUID,     sessionIdToUUID,+    userIdFromUUID,     userIdToUUID,   ) import Shomei.Persistence.Codec.Postgres (refreshTokenStatusToText, sessionKindToText, sessionStatusToText) import Shomei.Persistence.Database.Postgres (Database, postgresUnavailable, runTransaction) import Shomei.Persistence.Transaction.Postgres qualified as Tx import Shomei.Prelude-import Shomei.Session.Domain (Session (..), SessionStatus (SessionActive))+import Shomei.Session.Authentication.Guard (AuthenticationGuard (..))+import Shomei.Session.Authentication.Guard.Postgres (checkAuthentication, lockAuthenticationUser)+import Shomei.Session.Domain (NewSession (..), Session (..), SessionStatus (SessionActive)) import Shomei.Session.Postgres   ( SessionRow,     insertSessionStmt,@@ -78,7 +86,7 @@   Eff (AuthUnitOfWork : es) a ->   Eff es a runAuthUnitOfWorkPostgres = interpret_ \case-  PersistNewSession ns nst mkEvents -> do+  PersistNewSession guard ns nst mkEvents -> do     -- The ids are generated here, before the transaction opens, exactly as the per-table     -- interpreters generate them: they are client-side (TypeID/UUIDv7-style) values, so no     -- round-trip is needed and the events can name the session id.@@ -96,10 +104,15 @@         persisted = mkPersisted rid newToken     eventRows <- traverse toEventRow (mkEvents sid)     res <- runTransaction do-      Tx.statement (sessionRow session) insertSessionStmt-      Tx.statement (tokenRow rid newToken) insertRefreshTokenStmt-      traverse_ (\row -> Tx.statement row insertAuthEventStmt) eventRows-    either dbFail (const (pure (session, persisted))) res+      checked <- checkAuthentication ns.userId guard ns.createdAt+      case checked of+        Left err -> pure (Left err)+        Right () -> do+          Tx.statement (sessionRow session) insertSessionStmt+          Tx.statement (tokenRow rid newToken) insertRefreshTokenStmt+          traverse_ (\row -> Tx.statement row insertAuthEventStmt) eventRows+          pure (Right (session, persisted))+    either dbFail pure res   RotateRefreshToken presentedId usedAt newToken ev -> do     rid <- genRefreshTokenId     eventRow <- toEventRow ev@@ -108,10 +121,22 @@       -- The compare-and-swap runs first and its result decides the rest. A conflict leaves the       -- transaction with nothing but a no-op UPDATE to commit; there is no need to abort it,       -- and nothing to roll back.-      won <- Tx.statement (refreshTokenIdToUUID presentedId, usedAt) markUsedStmt-      case won of-        Nothing -> pure RotationConflict-        Just _ -> do+      -- Resolve without a row lock, then always acquire user before session/token.+      owner <- Tx.statement (sessionIdToUUID newToken.sessionId) sessionOwnerStmt+      live <- case owner of+        Nothing -> pure False+        Just uid -> do+          locked <- lockAuthenticationUser (userIdFromUUID uid)+          case locked of+            Just ("active", generation) -> do+              checked <- checkAuthentication (userIdFromUUID uid) (AuthenticationGuard generation (Just newToken.sessionId) Nothing) usedAt+              pure (isRight checked)+            _ -> pure False+      won <- if live then Tx.statement (refreshTokenIdToUUID presentedId, usedAt) markUsedStmt else pure Nothing+      case (live, won) of+        (False, _) -> pure RotationInvalid+        (True, Nothing) -> pure RotationConflict+        (True, Just _) -> do           Tx.statement (tokenRow rid newToken) insertRefreshTokenStmt           Tx.statement eventRow insertAuthEventStmt           pure (Rotated persisted)@@ -119,6 +144,7 @@   CompletePasswordReset tid uid newHash ts events -> do     eventRows <- traverse toEventRow events     res <- runTransaction do+      _ <- lockAuthenticationUser uid       won <- Tx.statement (passwordResetTokenIdToUUID tid, ts) PR.markConsumedStmt       case won of         Nothing -> pure False@@ -133,11 +159,41 @@   CompletePasswordChange uid newHash ts events -> do     eventRows <- traverse toEventRow events     res <- runTransaction do+      _ <- lockAuthenticationUser uid       Tx.statement (userIdToUUID uid, passwordHashText newHash, ts) updatePasswordHashStmt       _ <- Tx.statement (userIdToUUID uid, ts) revokeAllUserSessionsStmt       Tx.statement (userIdToUUID uid, ts) RTP.revokeUserTokensStmt       traverse_ (\row -> Tx.statement row insertAuthEventStmt) eventRows     either dbFail pure res+  ResetUserSecondFactors actor uid cmd ts -> do+    eid <- liftIO UUIDv4.nextRandom+    let revocationPayload = object ["revokedBy" Aeson..= recoveryActorUser actor, "recoveryActor" Aeson..= actor, "occurredAt" Aeson..= ts]+    res <- runTransaction do+      user <- lockAuthenticationUser uid+      case user of+        Nothing -> pure (Left UserNotFound)+        Just (status, _) | status /= "active" -> pure (Left InvalidUserStatus)+        Just _ -> do+          Tx.statement (userIdToUUID uid) advanceGenerationStmt+          pk <- Tx.statement (userIdToUUID uid) (deleteCountStmt "shomei_webauthn_credentials")+          totp <- Tx.statement (userIdToUUID uid) (deleteCountStmt "shomei_totp_credentials")+          codes <- Tx.statement (userIdToUUID uid) (deleteCountStmt "shomei_recovery_codes")+          ceremonies <- Tx.statement (userIdToUUID uid) (deleteCountStmt "shomei_webauthn_pending_ceremonies")+          -- Count tokens before the session CTE transitions them.+          tokens <- Tx.statement (userIdToUUID uid) activeUserTokenCountStmt+          sessions <- Tx.statement (userIdToUUID uid, ts, revocationPayload) revokeUserSessionsWithAuditStmt+          -- Also retire tokens belonging to already expired/revoked sessions.+          Tx.statement (userIdToUUID uid, ts) RTP.revokeUserTokensStmt+          authCodes <- Tx.statement (userIdToUUID uid) (deleteCountStmt "shomei_oauth_authorization_codes")+          resetTokens <- Tx.statement (userIdToUUID uid, ts) revokeResetCountStmt+          storedDestination <- Tx.statement (userIdToUUID uid) verifiedDestinationStmt+          let destination = storedDestination >>= either (const Nothing) Just . parseStoredEmail+          let counts = RecoveryCounts pk totp codes ceremonies (fromIntegral sessions) tokens authCodes resetTokens+              ev = Event.UserSecondFactorsReset (Event.UserSecondFactorsResetData uid actor cmd.caseReference counts ts)+              (mu, ms, et, payload, occurred) = projectAuthEvent ev+          Tx.statement (eid, mu, ms, et, payload, occurred) insertAuthEventStmt+          pure (Right (RecoveryResult ts counts (isJust destination), destination))+    either dbFail pure res   RevokeUserSessionsWithAudit actor uid ts -> do     let payload = object ["revokedBy" Aeson..= actor, "occurredAt" Aeson..= ts]     res <- runTransaction (Tx.statement (userIdToUUID uid, ts, payload) revokeUserSessionsWithAuditStmt)@@ -221,3 +277,46 @@     )     (contrazip3 (E.param (E.nonNullable E.uuid)) (E.param (E.nonNullable E.timestamptz)) (E.param (E.nonNullable E.jsonb)))     (D.singleRow (D.column (D.nonNullable D.int8)))++advanceGenerationStmt :: Statement UUID ()+advanceGenerationStmt =+  preparable+    "UPDATE shomei.shomei_users SET authentication_generation = authentication_generation + 1 WHERE user_id = $1"+    (E.param (E.nonNullable E.uuid))+    D.noResult++-- Table names are closed literals owned by this module, never request input.+deleteCountStmt :: Text -> Statement UUID Int+deleteCountStmt table =+  preparable+    ("WITH removed AS (DELETE FROM shomei." <> table <> " WHERE user_id = $1 RETURNING 1) SELECT count(*) FROM removed")+    (E.param (E.nonNullable E.uuid))+    (fromIntegral <$> D.singleRow (D.column (D.nonNullable D.int8)))++activeUserTokenCountStmt :: Statement UUID Int+activeUserTokenCountStmt =+  preparable+    "SELECT count(*) FROM shomei.shomei_refresh_tokens WHERE session_id IN (SELECT session_id FROM shomei.shomei_sessions WHERE user_id = $1) AND status <> 'revoked'"+    (E.param (E.nonNullable E.uuid))+    (fromIntegral <$> D.singleRow (D.column (D.nonNullable D.int8)))++revokeResetCountStmt :: Statement (UUID, UTCTime) Int+revokeResetCountStmt =+  preparable+    "WITH revoked AS (UPDATE shomei.shomei_password_reset_tokens SET status = 'revoked', revoked_at = $2 WHERE user_id = $1 AND status = 'active' RETURNING 1) SELECT count(*) FROM revoked"+    (contramap fst (E.param (E.nonNullable E.uuid)) <> contramap snd (E.param (E.nonNullable E.timestamptz)))+    (fromIntegral <$> D.singleRow (D.column (D.nonNullable D.int8)))++verifiedDestinationStmt :: Statement UUID (Maybe Text)+verifiedDestinationStmt =+  preparable+    "SELECT CASE WHEN email_verified_at IS NOT NULL THEN email ELSE NULL END FROM shomei.shomei_users WHERE user_id = $1"+    (E.param (E.nonNullable E.uuid))+    (D.singleRow (D.column (D.nullable D.text)))++sessionOwnerStmt :: Statement UUID (Maybe UUID)+sessionOwnerStmt =+  preparable+    "SELECT user_id FROM shomei.shomei_sessions WHERE session_id = $1"+    (E.param (E.nonNullable E.uuid))+    (D.rowMaybe (D.column (D.nonNullable D.uuid)))
test/Main.hs view
@@ -7,10 +7,11 @@  import Control.Concurrent (MVar, forkIO, killThread, newEmptyMVar, putMVar, readMVar, takeMVar, threadDelay) import Control.Exception (SomeException, bracket, bracket_, evaluate, try)-import Control.Monad (forM, forM_, replicateM, void, when, (<=<))+import Control.Monad (forM, forM_, replicateM, void, when, (<=<), (>=>)) import Crypto.Cipher.AES (AES256) import Crypto.Cipher.Types (AEAD, AEADMode (AEAD_GCM), AuthTag (..), aeadInit, aeadSimpleEncrypt, cipherInit) import Crypto.Error (CryptoFailable (..))+import Data.Aeson (object, (.=)) import Data.ByteArray qualified as BA import Data.ByteString (ByteString) import Data.ByteString qualified as BS@@ -34,6 +35,7 @@ import Hasql.Errors qualified as Hasql import Hasql.Session qualified as Session import Hasql.Statement (preparable)+import Shomei.Account.Admin.Recovery import Shomei.Account.Credential.Domain (Credential (..)) import Shomei.Account.Credential.Postgres (runCredentialStorePostgres) import Shomei.Account.Credential.Store (CredentialStore, createPasswordCredential, findPasswordCredentialByEmail, findPasswordCredentialByLoginId, updatePasswordHash)@@ -131,10 +133,10 @@     revokeRole,   ) import Shomei.Authorization.Role.Workflow (grantRoleTo)-import Shomei.Config (RateLimitConfig (..), ShomeiConfig (..), defaultRateLimitConfig, defaultShomeiConfig)+import Shomei.Config (RateLimitConfig (..), ShomeiConfig (..), TotpConfig (..), defaultRateLimitConfig, defaultShomeiConfig) import Shomei.Error (AuthDependency (PostgreSQL), AuthError (DependencyUnavailable, EmailAlreadyRegistered, InvalidCredentials, LoginIdAlreadyRegistered, PasswordResetTokenInvalid, RefreshTokenReuseDetected, RoleNotDefined, UserNotFound)) import Shomei.Error qualified as Err-import Shomei.Id (OAuthClientId, PasskeyId, ServiceAccountDbId, genCeremonyId, genOAuthClientId, genRecoveryCodeId, genServiceAccountDbId, genSessionId, genTotpCredentialId, genUserId, idText, totpCredentialIdToUUID, userIdToUUID)+import Shomei.Id (CeremonyId, OAuthClientId, PasskeyId, ServiceAccountDbId, genCeremonyId, genOAuthClientId, genRecoveryCodeId, genServiceAccountDbId, genSessionId, genTotpCredentialId, genUserId, idText, totpCredentialIdToUUID, userIdToUUID) import Shomei.Mfa.RecoveryCode.Postgres (runRecoveryCodeStorePostgres) import Shomei.Mfa.RecoveryCode.Store   ( RecoveryCodeStore,@@ -142,6 +144,7 @@     countUnusedRecoveryCodes,     replaceRecoveryCodes,   )+import Shomei.Mfa.RecoveryCode.Store qualified as RecoveryStore import Shomei.Mfa.Totp.Algorithm (TotpSecret (..), totpCode, totpCounter) import Shomei.Mfa.Totp.Domain (NewRecoveryCode (..), NewTotpCredential (..), TotpCredential (..)) import Shomei.Mfa.Totp.Postgres@@ -159,7 +162,10 @@     setTotpLastUsedCounter,     upsertTotpEnrollment,   )+import Shomei.Mfa.Totp.Store qualified as TotpStore+import Shomei.Mfa.Totp.Workflow qualified as TotpWorkflow import Shomei.Mfa.Workflow (MfaCompletion (..), completeMfa, prepareMfaChallenge)+import Shomei.Mfa.Workflow qualified as MfaWorkflow import Shomei.Migrations.TestSupport (withShomeiMigratedDatabase) import Shomei.OAuth.AuthorizationCode.Domain (AuthorizationCode (..), NewAuthorizationCode (..)) import Shomei.OAuth.AuthorizationCode.Postgres (runOAuthCodeStorePostgres)@@ -185,6 +191,7 @@     revokeOAuthClient,   ) import Shomei.OAuth.IdToken.Domain (IdToken (..))+import Shomei.OAuth.TokenGrant.Workflow qualified as TokenGrant import Shomei.Passkey.Ceremony.Port (WebAuthnCeremony) import Shomei.Passkey.Ceremony.Postgres (runPendingCeremonyStorePostgres) import Shomei.Passkey.Ceremony.Store (PendingCeremonyStore, putPendingCeremony, takePendingCeremony)@@ -209,6 +216,8 @@     findPasskeysByUserHandle,     updatePasskeySignCounter,   )+import Shomei.Passkey.Store qualified as PasskeyStore+import Shomei.Passkey.Workflow qualified as PasskeyWorkflow import Shomei.Persistence.Database.Postgres (Database (..), TransactionRetryPolicy (..), retryableTransactionError, runDatabasePool, runDatabasePoolWith, runTransaction) import Shomei.Persistence.Maintenance.Postgres   ( SweepConfig (..),@@ -222,6 +231,7 @@ import Shomei.Persistence.Transaction.Postgres qualified as Tx import Shomei.ServiceAccount.Domain (NewServiceAccount (..), ServiceAccount (..), ServiceAccountStatus (..)) import Shomei.ServiceAccount.Postgres (runServiceAccountStorePostgres)+import Shomei.ServiceAccount.Secret (sha256Hex) import Shomei.ServiceAccount.Store   ( ServiceAccountStore,     createServiceAccount,@@ -230,6 +240,7 @@     revokeServiceAccount,     rotateServiceAccountSecret,   )+import Shomei.Session.Authentication.Guard (AuthenticationGuard (..), userGuard) import Shomei.Session.Authentication.Workflow (login, logout, refresh, signup) import Shomei.Session.Command (ClientContext (..), LoginCommand (..), LogoutCommand (..), ProofContext (..), RefreshCommand (..), SignupCommand (..)) import Shomei.Session.Domain (NewSession (..), Session (..), SessionKind (..), SessionStatus (..))@@ -253,6 +264,7 @@ import Shomei.Session.Token.Generator (TokenGen, hashRefreshToken) import Shomei.Session.UnitOfWork.Postgres (runAuthUnitOfWorkPostgres) import Shomei.Session.UnitOfWork.Store (AuthUnitOfWork, completePasswordChange, completePasswordReset, revokeSessionWithTokens, revokeUserSessionsWithAudit)+import Shomei.Session.UnitOfWork.Store qualified as Uow import Shomei.Session.Workflow (buildEnrichedClaims) import Shomei.SigningKey.Domain (SigningKeyStatus (..), StoredSigningKey (..)) import Shomei.SigningKey.Postgres (runSigningKeyStorePostgres)@@ -521,7 +533,11 @@  tests :: [TestTree] tests =-  [ testManagedPoolOwnership,+  [ testRecoveryWriteBarriers,+    testAdministrativeRecovery,+    testRecoveryAuditRollback,+    testRecoveryMfaCommitBarrier,+    testManagedPoolOwnership,     testPersistenceClock,     testAdminQueryPlans,     testRefreshRotationRace,@@ -817,10 +833,12 @@       tcid <- genTotpCredentialId       t <- now       created <--        upsertTotpEnrollment-          NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}+        either (error . show) pure+          =<< upsertTotpEnrollment+            (AuthenticationGuard 0 Nothing Nothing)+            NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}       found0 <- findTotpByUser u.userId-      confirmTotp tcid t+      confirmTotp u.userId (AuthenticationGuard 0 Nothing Nothing) tcid t       counterAdvanced <- setTotpLastUsedCounter tcid 42       found1 <- findTotpByUser u.userId       deleteTotpByUser u.userId@@ -843,8 +861,10 @@       tcid <- genTotpCredentialId       t <- now       _ <--        upsertTotpEnrollment-          NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}+        either (error . show) pure+          =<< upsertTotpEnrollment+            (AuthenticationGuard 0 Nothing Nothing)+            NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}       first <- setTotpLastUsedCounter tcid 42       same <- setTotpLastUsedCounter tcid 42       older <- setTotpLastUsedCounter tcid 41@@ -863,8 +883,10 @@       tcid <- genTotpCredentialId       t <- now       _ <--        upsertTotpEnrollment-          NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}+        either (error . show) pure+          =<< upsertTotpEnrollment+            (AuthenticationGuard 0 Nothing Nothing)+            NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}       pure tcid     tcid <- expectApp seeded     gate <- newEmptyMVar@@ -888,7 +910,7 @@       u <- createUser (NewUser {loginId = aliceLogin, email = Just aliceEmail, displayName = Nothing})       tcid <- genTotpCredentialId       t <- now-      _ <- upsertTotpEnrollment NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}+      _ <- either (error . show) pure =<< upsertTotpEnrollment (AuthenticationGuard 0 Nothing Nothing) NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}       pure ()     _ <- expectApp result     stored <- scalarBytea pool "SELECT secret_enc FROM shomei.shomei_totp_credentials LIMIT 1"@@ -906,7 +928,7 @@         forM_ [a, b] \u -> do           tcid <- genTotpCredentialId           t <- now-          _ <- upsertTotpEnrollment NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}+          _ <- either (error . show) pure =<< upsertTotpEnrollment (AuthenticationGuard 0 Nothing Nothing) NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}           pure ()         pure (a, b)     let aliceId = "'" <> Text.pack (show (userIdToUUID alice.userId)) <> "'"@@ -939,7 +961,7 @@       expectApp =<< runApp pool do         tcid <- genTotpCredentialId         t <- now-        c <- upsertTotpEnrollment NewTotpCredential {totpCredentialId = tcid, userId = alice.userId, secret = TotpSecret totpRawSecret, createdAt = t}+        c <- either (error . show) pure =<< upsertTotpEnrollment (AuthenticationGuard 0 Nothing Nothing) NewTotpCredential {totpCredentialId = tcid, userId = alice.userId, secret = TotpSecret totpRawSecret, createdAt = t}         found <- findTotpByUser alice.userId         pure (c, found)     fmap (\TotpCredential {totpCredentialId} -> totpCredentialId) (snd replacement)@@ -961,7 +983,7 @@         a <- createUser (NewUser {loginId = aliceLogin, email = Just aliceEmail, displayName = Nothing})         tcid <- genTotpCredentialId         t <- now-        _ <- upsertTotpEnrollment NewTotpCredential {totpCredentialId = tcid, userId = a.userId, secret = TotpSecret totpRawSecret, createdAt = t}+        _ <- either (error . show) pure =<< upsertTotpEnrollment (AuthenticationGuard 0 Nothing Nothing) NewTotpCredential {totpCredentialId = tcid, userId = a.userId, secret = TotpSecret totpRawSecret, createdAt = t}         pure a.userId     let seed =           preparable@@ -997,8 +1019,8 @@           u <- createUser (NewUser {loginId = lid, email = Nothing, displayName = Nothing})           tcid <- genTotpCredentialId           t <- now-          _ <- upsertTotpEnrollment NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}-          when (even i) (confirmTotp tcid t)+          _ <- either (error . show) pure =<< upsertTotpEnrollment (AuthenticationGuard 0 Nothing Nothing) NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret totpRawSecret, createdAt = t}+          when (even i) (void (confirmTotp u.userId (AuthenticationGuard 0 Nothing Nothing) tcid t))     let seed =           preparable             "UPDATE shomei.shomei_totp_credentials SET secret_enc = $1, envelope_version = 0"@@ -1020,12 +1042,12 @@       expectApp =<< runAppAtTime t0 pool do         a <- createUser (NewUser {loginId = aliceLogin, email = Just aliceEmail, displayName = Nothing})         tcid <- genTotpCredentialId-        _ <- upsertTotpEnrollment NewTotpCredential {totpCredentialId = tcid, userId = a.userId, secret = TotpSecret totpRawSecret, createdAt = t0}-        confirmTotp tcid t0+        _ <- either (error . show) pure =<< upsertTotpEnrollment (AuthenticationGuard 0 Nothing Nothing) NewTotpCredential {totpCredentialId = tcid, userId = a.userId, secret = TotpSecret totpRawSecret, createdAt = t0}+        confirmTotp a.userId (AuthenticationGuard 0 Nothing Nothing) tcid t0         pure a     let completeAt ts = do           result <- runAppAtTime ts pool do-            (cid, _, methods) <- prepareMfaChallenge cfg u ts+            (cid, _, methods) <- either (error . show) pure =<< prepareMfaChallenge cfg u ts             liftIO (assertBool "TOTP offered" ("totp" `elem` methods))             completeMfa               cfg@@ -1055,7 +1077,7 @@           a <- createUser (NewUser {loginId = aliceLogin, email = Just aliceEmail, displayName = Nothing})           tcid <- genTotpCredentialId           t <- now-          _ <- upsertTotpEnrollment NewTotpCredential {totpCredentialId = tcid, userId = a.userId, secret = TotpSecret totpRawSecret, createdAt = t}+          _ <- either (error . show) pure =<< upsertTotpEnrollment (AuthenticationGuard 0 Nothing Nothing) NewTotpCredential {totpCredentialId = tcid, userId = a.userId, secret = TotpSecret totpRawSecret, createdAt = t}           pure a       let seed =             preparable@@ -1085,7 +1107,7 @@         expectApp =<< runApp pool do           tcid <- genTotpCredentialId           t <- now-          upsertTotpEnrollment NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret "new enrollment secret", createdAt = t}+          either (error . show) pure =<< upsertTotpEnrollment (AuthenticationGuard 0 Nothing Nothing) NewTotpCredential {totpCredentialId = tcid, userId = u.userId, secret = TotpSecret "new enrollment secret", createdAt = t}       execSql gatePool "SELECT pg_advisory_unlock(1936224116, 2)"       _ <- expectRight =<< takeMVar blocker       takeMVar converted >>= (@?= Right 0)@@ -1105,13 +1127,13 @@       ids <- replicateM 3 genRecoveryCodeId       let mk i h = NewRecoveryCode {recoveryCodeId = i, codeHash = h, createdAt = t}           codes = zipWith mk ids ["h1", "h2", "h3"]-      replaceRecoveryCodes u.userId codes+      replaceRecoveryCodes u.userId (AuthenticationGuard 0 Nothing Nothing) t0 codes       countBefore <- countUnusedRecoveryCodes u.userId       firstConsume <- consumeRecoveryCode u.userId "h1" t       secondConsume <- consumeRecoveryCode u.userId "h1" t       countAfter <- countUnusedRecoveryCodes u.userId       ids2 <- replicateM 2 genRecoveryCodeId-      replaceRecoveryCodes u.userId (zipWith mk ids2 ["n1", "n2"])+      replaceRecoveryCodes u.userId (AuthenticationGuard 0 Nothing Nothing) t0 (zipWith mk ids2 ["n1", "n2"])       countAfterReplace <- countUnusedRecoveryCodes u.userId       oldConsume <- consumeRecoveryCode u.userId "h2" t       pure (countBefore, firstConsume, secondConsume, countAfter, countAfterReplace, oldConsume)@@ -1885,18 +1907,18 @@   _ <- expectApp loginRes >>= expectRight   readIORef counter >>= (@?= 10) --- | A wrong password costs four database operations: per-IP count, atomic record-and-count transaction,--- credential lookup, and the @LoginFailed@ audit insert. The user row is only needed after the--- password succeeds, and hashing itself is CPU-only.+-- | A wrong password costs five database operations: per-IP count, atomic proof reservation,+-- credential lookup, the user generation snapshot taken before hashing, and the failure audit.+-- Capturing generation after a valid password would attach new state to a stale proof. testFailedLoginRoundTripBudget :: TestTree-testFailedLoginRoundTripBudget = testCase "a wrong password costs exactly 4 database operations" $ withDb \pool -> do+testFailedLoginRoundTripBudget = testCase "a wrong password captures the generation and costs exactly 5 database operations" $ withDb \pool -> do   signupRes <- runApp pool (signup cfg (SignupCommand aliceLogin (Just aliceEmail) strongPw Nothing))   _ <- expectApp signupRes >>= expectRight   counter <- newIORef 0   let ctx = ClientContext (ClientIp "10.0.0.1") (AccountKey (loginIdText aliceLogin))   loginRes <- runApp pool (countingDatabase counter (login cfg ctx (LoginCommand aliceLogin (PlainPassword "wrong") False)))   expectApp loginRes >>= (@?= Left InvalidCredentials)-  readIORef counter >>= (@?= 4)+  readIORef counter >>= (@?= 5)  -- | A token refresh costs exactly five database operations: --@@ -2352,8 +2374,8 @@                 createdAt = t,                 expiresAt               }-      putAuthorizationCode (mk "hash-live" (addUTCTime 60 t))-      putAuthorizationCode (mk "hash-expired" (addUTCTime 60 t))+      putAuthorizationCode (AuthenticationGuard 0 Nothing Nothing) (mk "hash-live" (addUTCTime 60 t))+      putAuthorizationCode (AuthenticationGuard 0 Nothing Nothing) (mk "hash-expired" (addUTCTime 60 t))       first' <- consumeAuthorizationCode "hash-live" t       sid <- genSessionId       bindAuthorizationCodeSession "hash-live" sid@@ -2397,6 +2419,7 @@       u <- createUser (NewUser {loginId = aliceLogin, email = Just aliceEmail, displayName = Nothing})       t <- now       putAuthorizationCode+        (AuthenticationGuard 0 Nothing Nothing)         NewAuthorizationCode           { codeHash = "hash-raced",             clientId = "oauthclient_x",@@ -2440,7 +2463,7 @@       readMVar gate       result <- runApp pool do         t <- now-        createPasskey 1 ((newPasskey u t) {credentialId = WebAuthnCredentialId (BS.pack [fromIntegral i])})+        createPasskey (AuthenticationGuard 0 Nothing Nothing) 1 ((newPasskey u t) {credentialId = WebAuthnCredentialId (BS.pack [fromIntegral i])})       putMVar done result     pure done   putMVar gate ()@@ -2454,7 +2477,7 @@   result <- runApp pool do     u <- createUser (NewUser {loginId = aliceLogin, email = Just aliceEmail, displayName = Nothing})     t <- now-    created <- either (error . show) pure =<< createPasskey 20 (newPasskey u t)+    created <- either (error . show) pure =<< createPasskey (AuthenticationGuard 0 Nothing Nothing) 20 (newPasskey u t)     byUser <- findPasskeysByUser u.userId     byCred <- findPasskeyByCredentialId (WebAuthnCredentialId "cred-1")     byHandle <- findPasskeysByUserHandle (UserHandle "uh-1")@@ -2476,7 +2499,7 @@   result <- runApp pool do     u <- createUser (NewUser {loginId = aliceLogin, email = Just aliceEmail, displayName = Nothing})     t <- now-    created <- either (error . show) pure =<< createPasskey 20 (newPasskey u t)+    created <- either (error . show) pure =<< createPasskey (AuthenticationGuard 0 Nothing Nothing) 20 (newPasskey u t)     let pid = pkPasskeyId created     counterAdvanced <- updatePasskeySignCounter pid (SignatureCounter 42) t     afterUpdate <- findPasskeyByCredentialId (WebAuthnCredentialId "cred-1")@@ -2501,7 +2524,7 @@     result <- runApp pool do       u <- createUser (NewUser {loginId = aliceLogin, email = Just aliceEmail, displayName = Nothing})       t <- now-      created <- either (error . show) pure =<< createPasskey 20 (newPasskey u t)+      created <- either (error . show) pure =<< createPasskey (AuthenticationGuard 0 Nothing Nothing) 20 (newPasskey u t)       let pid = pkPasskeyId created       zeroToZero <- updatePasskeySignCounter pid (SignatureCounter 0) t       first <- updatePasskeySignCounter pid (SignatureCounter 42) t@@ -2522,7 +2545,7 @@     seeded <- runApp pool do       u <- createUser (NewUser {loginId = aliceLogin, email = Just aliceEmail, displayName = Nothing})       t <- now-      created <- either (error . show) pure =<< createPasskey 20 (newPasskey u t)+      created <- either (error . show) pure =<< createPasskey (AuthenticationGuard 0 Nothing Nothing) 20 (newPasskey u t)       pure (pkPasskeyId created, t)     (pid, t) <- expectApp seeded     gate <- newEmptyMVar@@ -2543,7 +2566,9 @@     t <- now     putPendingCeremony       PendingCeremony-        { ceremonyId = cid,+        { authenticationGeneration = Just 0,+          initiatingSession = Nothing,+          ceremonyId = cid,           userId = Nothing,           kind = RegistrationCeremony,           optionsBlob = "{\"challenge\":\"abc\"}",@@ -2566,7 +2591,9 @@     t <- now     putPendingCeremony       PendingCeremony-        { ceremonyId = cid,+        { authenticationGeneration = Just 0,+          initiatingSession = Nothing,+          ceremonyId = cid,           userId = Nothing,           kind = AuthenticationCeremony,           optionsBlob = "{\"challenge\":\"xyz\"}",@@ -3429,9 +3456,9 @@       user <- createUser (NewUser aliceLogin Nothing Nothing)       ts <- now       rid <- genRecoveryCodeId-      replaceRecoveryCodes user.userId [NewRecoveryCode rid "recovery-race" ts]+      replaceRecoveryCodes user.userId (AuthenticationGuard 0 Nothing Nothing) t0 [NewRecoveryCode rid "recovery-race" ts]       cid <- genCeremonyId-      putPendingCeremony (PendingCeremony cid (Just user.userId) AuthenticationCeremony "signed-options-fixture" ts (addUTCTime 60 ts))+      putPendingCeremony (PendingCeremony (Just 0) Nothing cid (Just user.userId) AuthenticationCeremony "signed-options-fixture" ts (addUTCTime 60 ts))       pure (user.userId, cid, ts)   recovery <- raceDatabase 8 (runApp pool (consumeRecoveryCode uid "recovery-race" ts)) >>= traverse expectApp   length (filter id recovery) @?= 1@@ -3495,3 +3522,214 @@     assertBool "bounded page uses the ordered index" (any (Text.isInfixOf indexName) plan)     assertBool "bounded page needs no sort" (not (any (Text.isInfixOf "Sort") plan))   writeFile "/tmp/shomei-admin-query-plans.txt" (Text.unpack (Text.unlines (concat (zipWith3 (\name b a -> [name <> " before:"] <> b <> [name <> " after:"] <> a) ["Users", "Suspended users", "Per-user audit", "40-client catalog (no new index)"] before after))))++-- Administrator recovery is tested on real independent pool connections. The barrier sits+-- after proof verification and immediately before the shared session transaction.+recoveryFixture :: Pool -> IO (User, CeremonyId, UTCTime)+recoveryFixture pool =+  expectApp =<< runApp pool do+    (user, _) <- either (error . show) pure =<< signup cfg (SignupCommand aliceLogin (Just aliceEmail) strongPw Nothing)+    ts <- now+    _ <- either (error . show) pure =<< createPasskey (userGuard user) 20 ((newPasskey user ts) {credentialId = WebAuthnCredentialId "recovery-lost-fixture"})+    _ <- putAuthorizationCode (userGuard user) (NewAuthorizationCode "recovery-old-code-hash" "fixture-client" "https://fixture.example/callback" user.userId Set.empty Nothing Nothing ts ts (addUTCTime 60 ts))+    _ <- createPasswordResetToken (NewPasswordResetToken user.userId (OneTimeTokenHash "recovery-old-reset-hash") ts (addUTCTime 60 ts))+    tcid <- genTotpCredentialId+    _ <-+      either (error . show) pure+        =<< upsertTotpEnrollment+          (userGuard user)+          (NewTotpCredential tcid user.userId (TotpSecret totpRawSecret) ts)+    _ <- confirmTotp user.userId (userGuard user) tcid ts+    rid <- genRecoveryCodeId+    _ <- replaceRecoveryCodes user.userId (userGuard user) ts [NewRecoveryCode rid "sentinel-old-code-hash" ts]+    (cid, _, _) <- either (error . show) pure =<< prepareMfaChallenge cfg user ts+    pure (user, cid, ts)++recoveryCommand :: RecoveryCommand+recoveryCommand = RecoveryCommand True "INC-1234"++testAdministrativeRecovery :: TestTree+testAdministrativeRecovery = testCase "administrator recovery clears state, isolates targets, and audits serial effects" $ withDb \pool -> do+  (user, _, _) <- recoveryFixture pool+  _ <- runApp pool (signup cfg (SignupCommand bobLogin (Just bobEmail) strongPw Nothing)) >>= expectApp >>= expectRight+  actors <- newIORef (0 :: Int)+  let operation = do+        index <- liftIO (atomicModifyIORef' actors (\n -> (n + 1, n)))+        resetUserSecondFactors (LocalOperator (if index == 0 then "ops.one" else "ops.two")) user.userId recoveryCommand+  outcomes <- raceDatabase 2 (runApp pool operation) >>= traverse (expectApp >=> expectRight)+  sum [r.counts.passkeysRemoved | r <- outcomes] @?= 1+  sum [r.counts.authorizationCodesInvalidated | r <- outcomes] @?= 1+  sum [r.counts.passwordResetTokensRevoked | r <- outcomes] @?= 1+  sum [r.counts.totpCredentialsRemoved | r <- outcomes] @?= 1+  sum [r.counts.recoveryCodesRemoved | r <- outcomes] @?= 1+  sum [r.counts.sessionsRevoked | r <- outcomes] @?= 1+  scalarInt pool "SELECT count(*) FROM shomei.shomei_sessions WHERE status='active'" >>= (@?= 1)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_auth_events WHERE event_type='user_second_factors_reset'" >>= (@?= 2)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_auth_events WHERE event_type='session_revoked'" >>= (@?= 1)+  scalarInt pool "SELECT max(authentication_generation) FROM shomei.shomei_users" >>= (@?= 2)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_totp_credentials" >>= (@?= 0)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_recovery_codes" >>= (@?= 0)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_webauthn_pending_ceremonies" >>= (@?= 0)+  events <- runApp pool (queryAuthEvents emptyAuditQuery) >>= expectApp+  let resets = [d | e <- events, Right (Event.UserSecondFactorsReset d) <- [reconstructAuthEvent e.storedEventType e.storedPayload]]+  length resets @?= 2+  assertBool "both concurrent local actors survive auditing" (all (`elem` map (.recoveryActor) resets) [LocalOperator "ops.one", LocalOperator "ops.two"])+  scalarInt pool "SELECT count(*) FROM shomei.shomei_auth_events WHERE payload::text LIKE '%sentinel-old-code-hash%'" >>= (@?= 0)++testRecoveryAuditRollback :: TestTree+testRecoveryAuditRollback = testCase "recovery audit insert failure restores generation, factors, challenges and sessions" $ withDb \pool -> do+  (user, _, _) <- recoveryFixture pool+  execSql pool "CREATE FUNCTION shomei.fail_recovery_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.event_type = 'user_second_factors_reset' THEN RAISE EXCEPTION 'test audit unavailable'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_recovery_audit BEFORE INSERT ON shomei.shomei_auth_events FOR EACH ROW EXECUTE FUNCTION shomei.fail_recovery_audit()"+  result <- runApp pool (resetUserSecondFactors (LocalOperator "ops") user.userId recoveryCommand)+  result @?= Left (DependencyUnavailable PostgreSQL)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_webauthn_credentials" >>= (@?= 1)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_oauth_authorization_codes" >>= (@?= 1)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_password_reset_tokens WHERE status='active'" >>= (@?= 1)+  scalarInt pool "SELECT max(authentication_generation) FROM shomei.shomei_users" >>= (@?= 0)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_totp_credentials" >>= (@?= 1)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_recovery_codes" >>= (@?= 1)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_webauthn_pending_ceremonies" >>= (@?= 1)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_sessions WHERE status='active'" >>= (@?= 1)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_refresh_tokens WHERE status='active'" >>= (@?= 1)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_auth_events WHERE event_type IN ('user_second_factors_reset','session_revoked')" >>= (@?= 0)++testRecoveryMfaCommitBarrier :: TestTree+testRecoveryMfaCommitBarrier =+  testGroup+    "recovery versus verified MFA"+    [ testCase "completion waiting to commit after reset is rejected" $ withDb \pool -> do+        (user, cid, ts) <- recoveryFixture pool+        ready <- newEmptyMVar+        release <- newEmptyMVar+        done <- newEmptyMVar+        let barrier =+              interpose+                ( \env -> \case+                    op@(Uow.PersistNewSession _ _ _ _) -> do+                      liftIO (putMVar ready () >> takeMVar release)+                      passthrough env op+                    op -> passthrough env op+                )+        _ <- forkIO (runApp pool (barrier (completeMfa cfg (ProofContext (ClientIp "test-ip") AccountKey) cid (MfaTotp (totpCode 6 (TotpSecret totpRawSecret) (totpCounter ts))))) >>= putMVar done)+        reached <- timeout 10000000 (takeMVar ready)+        reached @?= Just ()+        _ <- runApp pool (resetUserSecondFactors (LocalOperator "ops") user.userId recoveryCommand) >>= expectApp >>= expectRight+        putMVar release ()+        result <- timeout 10000000 (takeMVar done)+        case result of+          Just (Right (Left Err.StaleAuthentication)) -> pure ()+          other -> assertFailure ("expected stale verified proof, got " <> show other)+        scalarInt pool "SELECT count(*) FROM shomei.shomei_sessions WHERE status='active'" >>= (@?= 0)+        scalarInt pool "SELECT count(*) FROM shomei.shomei_refresh_tokens WHERE status='active'" >>= (@?= 0),+      testCase "completion committed before reset is revoked" $ withDb \pool -> do+        (user, cid, ts) <- recoveryFixture pool+        _ <- runApp pool (completeMfa cfg (ProofContext (ClientIp "test-ip") AccountKey) cid (MfaTotp (totpCode 6 (TotpSecret totpRawSecret) (totpCounter ts)))) >>= expectApp >>= expectRight+        result <- runApp pool (resetUserSecondFactors (LocalOperator "ops") user.userId recoveryCommand) >>= expectApp >>= expectRight+        result.counts.sessionsRevoked @?= 2+        scalarInt pool "SELECT count(*) FROM shomei.shomei_sessions WHERE status='active'" >>= (@?= 0)+    ]++-- Every barrier is a port boundary after expensive proof/generation work, before the+-- database-only commit. The reset uses another connection, with no timing sleeps.+pauseSessionPersistence :: MVar () -> MVar () -> Eff AppEffects a -> Eff AppEffects a+pauseSessionPersistence ready release = interpose \env -> \case+  op@(Uow.PersistNewSession _ _ _ _) -> do+    liftIO (putMVar ready () >> takeMVar release)+    passthrough env op+  op -> passthrough env op++expectStale :: Either AuthError (Either AuthError a) -> Bool+expectStale (Right (Left Err.StaleAuthentication)) = True+expectStale _ = False++resetWhilePaused :: (Show a) => Pool -> User -> (MVar () -> MVar () -> Eff AppEffects a) -> (Either AuthError a -> Bool) -> IO ()+resetWhilePaused pool user action expected = do+  ready <- newEmptyMVar+  release <- newEmptyMVar+  done <- newEmptyMVar+  bracket (forkIO (runApp pool (action ready release) >>= putMVar done)) killThread $ \_ -> do+    timeout 10000000 (takeMVar ready) >>= (@?= Just ())+    _ <- runApp pool (resetUserSecondFactors (LocalOperator "ops.barrier") user.userId recoveryCommand) >>= expectApp >>= expectRight+    putMVar release ()+    result <- timeout 10000000 (takeMVar done)+    case result of+      Just outcome | expected outcome -> pure ()+      other -> assertFailure ("unexpected post-recovery completion: " <> show other)+  scalarInt pool "SELECT count(*) FROM shomei.shomei_sessions WHERE status='active'" >>= (@?= 0)++testRecoveryWriteBarriers :: TestTree+testRecoveryWriteBarriers =+  testGroup+    "recovery commit barriers"+    [ testCase "verified password cannot mint a session after recovery" $ withDb \pool -> do+        (user, _) <- runApp pool (signup cfg (SignupCommand aliceLogin Nothing strongPw Nothing)) >>= expectApp >>= expectRight+        resetWhilePaused pool user (\ready release -> pauseSessionPersistence ready release (login cfg (ClientContext (ClientIp "test-ip") (AccountKey "password-barrier")) (LoginCommand aliceLogin strongPw False))) expectStale,+      testCase "verified passkey enrollment cannot resurrect a credential" $ withDb \pool -> do+        (user, _, _) <- recoveryFixture pool+        (cid, _) <- runApp pool (PasskeyWorkflow.beginPasskeyRegistration cfg user.userId Nothing) >>= expectApp >>= expectRight+        let cred = object ["challenge" .= ("ceremony-challenge-0" :: Text), "credentialId" .= WebAuthnCredentialId "barrier-cred", "userHandle" .= UserHandle "barrier-handle", "publicKey" .= PublicKeyBytes "barrier-key"]+            pause :: MVar () -> MVar () -> Eff AppEffects a -> Eff AppEffects a+            pause ready release =+              interpose+                ( \env -> \case+                    op@(PasskeyStore.CreatePasskey _ _ _) -> liftIO (putMVar ready () >> takeMVar release) >> passthrough env op+                    op -> passthrough env op+                )+        resetWhilePaused pool user (\ready release -> pause ready release (PasskeyWorkflow.completePasskeyRegistration cfg user.userId cid cred Nothing)) expectStale+        scalarInt pool "SELECT count(*) FROM shomei.shomei_webauthn_credentials" >>= (@?= 0),+      testCase "generated TOTP enrollment cannot persist after recovery" $ withDb \pool -> do+        (user, _) <- runApp pool (signup cfg (SignupCommand aliceLogin Nothing strongPw Nothing)) >>= expectApp >>= expectRight+        let pause :: MVar () -> MVar () -> Eff AppEffects a -> Eff AppEffects a+            pause ready release =+              interpose+                ( \env -> \case+                    op@(TotpStore.UpsertTotpEnrollment _ _) -> liftIO (putMVar ready () >> takeMVar release) >> passthrough env op+                    op -> passthrough env op+                )+        resetWhilePaused pool user (\ready release -> pause ready release (TotpWorkflow.enrollTotp (cfg {totpConfig = cfg.totpConfig {totpEnabled = True}}) user Nothing)) expectStale+        scalarInt pool "SELECT count(*) FROM shomei.shomei_totp_credentials" >>= (@?= 0),+      testCase "generated recovery codes cannot replace the set after recovery" $ withDb \pool -> do+        (user, _, _) <- recoveryFixture pool+        let pause :: MVar () -> MVar () -> Eff AppEffects a -> Eff AppEffects a+            pause ready release =+              interpose+                ( \env -> \case+                    op@(RecoveryStore.ReplaceRecoveryCodes _ _ _ _) -> liftIO (putMVar ready () >> takeMVar release) >> passthrough env op+                    op -> passthrough env op+                )+        resetWhilePaused pool user (\ready release -> pause ready release (TotpWorkflow.regenerateRecoveryCodes cfg user Nothing)) expectStale+        scalarInt pool "SELECT count(*) FROM shomei.shomei_recovery_codes" >>= (@?= 0),+      testCase "verified passwordless proof cannot mint after recovery" $ withDb \pool -> do+        (user, _, ts) <- recoveryFixture pool+        credential <- runApp pool (createPasskey (userGuard user) 20 (newPasskey user ts)) >>= expectApp >>= expectRight+        (cid, _) <- runApp pool (MfaWorkflow.beginPasswordlessLogin cfg) >>= expectApp >>= expectRight+        let PasskeyCredential {credentialId, userHandle, publicKey} = credential+            assertion = object ["challenge" .= ("ceremony-challenge-0" :: Text), "credentialId" .= credentialId, "userHandle" .= userHandle, "publicKey" .= publicKey]+        resetWhilePaused pool user (\ready release -> pauseSessionPersistence ready release (MfaWorkflow.completePasswordlessLogin cfg (ProofContext (ClientIp "test-ip") AccountKey) cid assertion)) expectStale,+      testCase "refresh already read by the workflow cannot rotate after recovery" $ withDb \pool -> do+        (user, pair) <- runApp pool (signup cfg (SignupCommand aliceLogin Nothing strongPw Nothing)) >>= expectApp >>= expectRight+        let pause :: MVar () -> MVar () -> Eff AppEffects a -> Eff AppEffects a+            pause ready release =+              interpose+                ( \env -> \case+                    op@(Uow.RotateRefreshToken _ _ _ _) -> liftIO (putMVar ready () >> takeMVar release) >> passthrough env op+                    op -> passthrough env op+                )+            rejected (Right (Left Err.SessionRevoked)) = True+            rejected _ = False+        resetWhilePaused pool user (\ready release -> pause ready release (refresh cfg (RefreshCommand pair.refreshToken))) rejected+        scalarInt pool "SELECT count(*) FROM shomei.shomei_refresh_tokens WHERE status='active'" >>= (@?= 0),+      testCase "consumed authorization code retains its pre-recovery generation at mint" $ withDb \pool -> do+        (user, _, ts) <- recoveryFixture pool+        client <-+          expectApp =<< runApp pool do+            ocid <- genOAuthClientId+            client <- createOAuthClient (NewOAuthClient ocid "barrier-client" (Just (sha256Hex "barrier-secret")) ConfidentialClient "barrier" ["https://client.example/callback"] Set.empty ts)+            _ <- putAuthorizationCode (userGuard user) (NewAuthorizationCode (sha256Hex "barrier-code") "barrier-client" "https://client.example/callback" user.userId Set.empty Nothing Nothing ts ts (addUTCTime 60 ts))+            pure client+        let command = TokenGrant.ExchangeAuthorizationCode "barrier-client" (Just "barrier-secret") "barrier-code" "https://client.example/callback" Nothing+            rejected (Right (Left (TokenGrant.GrantInvalidGrant _))) = True+            rejected _ = False+        resetWhilePaused pool user (\ready release -> pauseSessionPersistence ready release (TokenGrant.exchangeAuthorizationCode cfg command)) rejected+        scalarInt pool "SELECT count(*) FROM shomei.shomei_oauth_authorization_codes" >>= (@?= 0)+    ]