diff --git a/.changeset/refresh-rotation-chain.md b/.changeset/refresh-rotation-chain.md new file mode 100644 index 00000000..c544c298 --- /dev/null +++ b/.changeset/refresh-rotation-chain.md @@ -0,0 +1,11 @@ +--- +'seamless-auth-api': minor +--- + +Refresh rotation fixes: + +- `DELETE /sessions/:id` and `DELETE /admin/sessions/by-id/:id` revoke the whole chain from the row given, so a session that rotated after it was listed is revoked at its head instead of surviving while the API answers 200 (#592). +- A rotated refresh token is treated as reuse however long after its rotation it is presented. It used to be answered `401 invalid_refresh_token` once the rotated row's idle window had passed, without revoking the chain. It is now `401 refresh_token_reused` and the chain is revoked (#593). +- New refresh replay window (#598): for `REFRESH_REPLAY_WINDOW_SECONDS` (default 5, at most 60, `0` disables) after a rotation, the rotated token is answered with the same successor, up to three times, so two adapter instances refreshing at once no longer sign the user out. The response shape is unchanged. Only the immediate predecessor of a live head qualifies. The successor token is stored encrypted on the rotated row and cleared when the window lapses or the chain is revoked. + +Adds a migration for the `rotatedAt`, `replayTokenCiphertext` and `replayCount` session columns. diff --git a/docs/configuration.md b/docs/configuration.md index 92ce208e..c105f99d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -99,6 +99,15 @@ there means a coordinated release across both SDKs for what is an operational tu rather than a policy changed at runtime. See [security-posture.md](./security-posture.md) for what it is defending. +#### Refresh replay window + +| Variable | Required | Default | Notes | +| ------------------------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `REFRESH_REPLAY_WINDOW_SECONDS` | No | `5` | How long after a refresh token rotates it is still answered with the same successor, up to three times, so two adapter instances refreshing at once do not read as reuse. Capped at `60`; `0` turns it off. Outside it, a rotated token is reuse and ends the session chain. | + +Not a `system_config` key, for the same reason as the `/login` floor. See +[security-posture.md](./security-posture.md#refresh-replay-window). + ### Audit retention Audit events are kept forever unless retention is set. Retention archives before it deletes, diff --git a/docs/security-posture.md b/docs/security-posture.md index 5b20cd23..5542681a 100644 --- a/docs/security-posture.md +++ b/docs/security-posture.md @@ -414,15 +414,65 @@ triggered by that very theft could not reach, while the trail recorded `claimSessionRotation` writes the link conditional on it still being unset, in one statement the database serialises. No affected rows means another rotation got there first, which is the same thing an already rotated token means, and it is answered the same -way: the replacement this request made is revoked with `rotation_race_lost`, the session is -reloaded so the chain walk follows the link the winner wrote, the chain is revoked from -there, and the caller gets `401 refresh_token_reused`. - -Two legitimate refreshes racing each other therefore end the session chain, the same as -presenting a rotated token twice in sequence does. A client that fires concurrent refreshes -of one token signs its user out, which is the direction this has to fail: the alternative -is that whoever wins the race keeps a session, and the winner is not always the client that -should have it. +way: the replacement this request made is revoked with `rotation_race_lost` and the session +is reloaded to see the link the winner wrote. Inside the replay window the caller then gets +the winner's successor. Outside it the chain is revoked from there, following that link, +and the caller gets `401 refresh_token_reused`. + +Outside the replay window below, two refreshes racing each other end the session chain, +the same as presenting a rotated token twice in sequence does. That is the direction this +has to fail: the alternative is that whoever wins the race keeps a session, and the winner +is not always the client that should have it. + +### Reuse detection does not expire + +A rotated token is reuse however long after its rotation it comes back. The lookup used to +filter on the presented row's own idle window, so a rotated token presented more than +`SESSION_IDLE_TTL` after its row was created matched nothing and was answered as an unknown +token, without ending the chain. A thief who rotated a stolen token kept that chain to its +absolute lifetime while the victim's return was discarded as noise. + +[`findRefreshSessionByToken`](../src/services/sessionService.ts) now finds the row by its +fingerprint alone. Any row with `replacedBySessionId` set is answered by the replay window +or as reuse, and only then are revocation and expiry checked, for rows that never rotated. + +### Refresh replay window + +**Posture: a rotated token is answered with its existing successor for a few seconds, and +is reuse after that.** + +Server adapters deduplicate refreshes per process. Behind a load balancer, with replicas or +on serverless, two instances can each receive a request carrying the same expired access +token and both refresh. One wins the rotation and the other used to trip reuse detection, +which signed the user out at random under horizontal scale. + +For `REFRESH_REPLAY_WINDOW_SECONDS` (5 by default, at most 60) after a rotation, the +rotated token is answered with the same response the winner got: the same `refreshToken` +and `sessionId`, and a freshly signed access token for that session. This applies only: + +- to the immediate predecessor of the chain head. An older ancestor's successor has itself + rotated, so it is reuse at any time; +- while the successor is still a live head (not revoked, rotated, expired, or cut off by a + sign-out everywhere), and its owner is not revoked; +- three times per rotation, counted in the database so concurrent replays cannot all spend + the last one. + +Nothing new is minted, so a replay cannot start a parallel chain. The request that loses +the rotation race revokes the replacement it made and is answered from the window too. + +Refresh tokens are stored only as keyed fingerprints, so the successor token is kept on the +rotated row encrypted with AES-256-GCM, under a key derived with HMAC from +`REFRESH_TOKEN_LOOKUP_SECRET` and the rotated token itself, bound to the two session ids. +Opening it needs both the server secret and the token being replayed, so a copy of the +database alone reveals nothing. It is cleared when the window lapses and when the chain is +revoked. Deriving the successor deterministically from its predecessor would have needed no +storage, but it would make every later token in a chain computable from any one old token +plus the secret, for the life of the chain. + +The window is a deliberate trade: someone who has copied a refresh token and presents it +within seconds of the legitimate rotation gets the same successor without tripping +detection. Past the window, the replay count, or the head moving on, they trip it as +before. Setting the variable to `0` restores strict single use. ### Log out everywhere diff --git a/src/controllers/admin.ts b/src/controllers/admin.ts index 1a3e58ec..14ddbd81 100644 --- a/src/controllers/admin.ts +++ b/src/controllers/admin.ts @@ -42,7 +42,7 @@ import { sendIdentityChangeNotices, } from '../services/identityChangeService.js'; import { revokeAllSessionsForUsers } from '../services/sessionRevocation.js'; -import { hardRevokeSession } from '../services/sessionService.js'; +import { revokeSessionChain } from '../services/sessionService.js'; import { importUsers as runUserImport } from '../services/userImportService.js'; import type { AuthenticatedRequest } from '../types/types.js'; import { RouteRequest, ServiceRequest } from '../types/types.js'; @@ -579,7 +579,8 @@ export const revokeUserSessionById = async (req: Request, res: Response) => { return res.status(404).json({ error: 'Session not found' }); } - await hardRevokeSession(session, 'admin_revoke'); + // Walked to the head, because the row the admin listed may have rotated since (#592). + await revokeSessionChain(session, 'admin_revoke'); await AuthEventService.log({ userId: session.userId, diff --git a/src/controllers/authentication.ts b/src/controllers/authentication.ts index 8071b811..bd3885e5 100644 --- a/src/controllers/authentication.ts +++ b/src/controllers/authentication.ts @@ -10,6 +10,8 @@ import { Request, Response } from 'express'; import { isBreakGlassAdmin } from '../config/breakGlass.js'; import { getSystemConfig } from '../config/getSystemConfig.js'; import { EPHEMERAL_TOKEN_TTL_SECONDS } from '../lib/ephemeralTokenTtl.js'; +import { classifyRefreshRefusal, RefreshRefusalReason } from '../lib/refreshRefusal.js'; +import { refreshReplayWindowMs, sealReplayToken } from '../lib/refreshReplayToken.js'; import { createRefreshTokenLookup, generateRefreshToken, @@ -44,10 +46,9 @@ import { } from '../services/sessionRevocation.js'; import { claimSessionRotation, - classifyExpiredRefreshToken, findRefreshSessionByToken, hardRevokeSession, - RefreshRefusalReason, + replayRefreshRotation, revokeSessionChain, } from '../services/sessionService.js'; import { AuthenticatedRequest } from '../types/types.js'; @@ -523,6 +524,121 @@ async function refuseRevokedRefresh(req: Request, res: Response, userId: string, return res.status(401).json({ error: 'invalid_refresh_token' }); } +async function refuseReusedRefresh( + req: Request, + res: Response, + session: Session, + reason = 'Refresh token reuse detected', +) { + logger.warn( + `Token reuse detected for session ${session.id}. replacedBySessionId=${session.replacedBySessionId ?? 'none'} revokedAt=${session.revokedAt ? session.revokedAt.toISOString() : 'null'}. This usually means an already-rotated refresh token was sent again.`, + ); + await revokeSessionChain(session); + await AuthEventService.log({ + userId: session.userId, + type: 'refresh_token_suspicious', + req, + metadata: { + reason, + sessionId: session.id, + replacedBySessionId: session.replacedBySessionId, + revokedAt: session.revokedAt?.toISOString() ?? null, + }, + }); + return res.status(401).json({ error: 'refresh_token_reused' }); +} + +async function respondWithRefreshedSession( + req: Request, + res: Response, + { + session, + user, + claimsFrom = session, + refreshToken, + expiresAt, + now = new Date(), + replayOf, + }: { + session: Session; + /** The row the organization, recovery state and hook claims are read from. */ + claimsFrom?: Session; + user: User; + refreshToken: string; + expiresAt: Date; + now?: Date; + replayOf?: string; + }, +) { + const { access_token_ttl } = await getSystemConfig(); + const { token, organizationId } = await mintAccessToken({ + session: { + id: session.id, + organizationId: claimsFrom.organizationId, + recovery: claimsFrom.recovery, + hookClaims: claimsFrom.hookClaims ?? null, + }, + user, + }); + + if (!token) { + return res.status(500).json({ error: 'Failed to refresh session' }); + } + + await AuthEventService.log({ + userId: user.id, + type: 'refresh_token_success', + req, + ...(replayOf ? { sessionId: session.id, metadata: { replayOf } } : {}), + }); + + return res.status(200).json({ + message: 'Success', + token, + refreshToken, + sub: user.id, + sessionId: session.id, + organizationId, + roles: user.roles, + email: user.email, + phone: user.phone, + ttl: parseDurationToSeconds(access_token_ttl || '15m'), + // What is left of the chain, not a full lifetime, so a caller sizing a cookie or a + // keychain entry from it does not outlive the session. + refreshTtl: Math.floor((expiresAt.getTime() - now.getTime()) / 1000), + ...(claimsFrom.recovery === true ? { recovery: true } : {}), + }); +} + +/** + * A rotated token presented again: the same successor while the replay window holds, + * reuse otherwise. + */ +async function answerRotatedRefresh( + req: Request, + res: Response, + session: Session, + refreshToken: string, + reuseReason?: string, +) { + const replay = await replayRefreshRotation(session, refreshToken); + + if (replay) { + logger.info( + `Refresh token replayed within the window. sessionId=${session.id} successorId=${replay.successor.id}`, + ); + return respondWithRefreshedSession(req, res, { + session: replay.successor, + user: replay.user, + refreshToken: replay.refreshToken, + expiresAt: new Date(replay.successor.expiresAt), + replayOf: session.id, + }); + } + + return refuseReusedRefresh(req, res, session, reuseReason); +} + export const refreshSession = async (req: Request, res: Response) => { logger.info(`Refreshing user token`); @@ -540,9 +656,17 @@ export const refreshSession = async (req: Request, res: Response) => { } const now = new Date(); - const session = await findRefreshSessionByToken(refreshToken, now); + const presented = await findRefreshSessionByToken(refreshToken); - if (!session) { + // Checked before any expiry, so a rotated token is reuse however long after its own idle + // window it comes back (#593). + if (presented?.replacedBySessionId) { + return answerRotatedRefresh(req, res, presented, refreshToken); + } + + const refusal = presented ? classifyRefreshRefusal(presented, now) : 'revoked'; + + if (!presented || refusal) { const looksLikeJwt = refreshToken.split('.').length === 3; logger.warn( @@ -555,20 +679,16 @@ export const refreshSession = async (req: Request, res: Response) => { ); } - const expired = looksLikeJwt ? null : await classifyExpiredRefreshToken(refreshToken, now); - - if (expired) { + if (presented && refusal && refusal !== 'revoked') { await AuthEventService.log({ - userId: expired.session.userId, - sessionId: expired.session.id, + userId: presented.userId, + sessionId: presented.id, type: 'refresh_token_failed', req, metadata: { - reason: REFRESH_REFUSAL_MESSAGES[expired.reason], - refusal: expired.reason, - chainStartedAt: ( - expired.session.chainStartedAt ?? expired.session.createdAt - )?.toISOString(), + reason: REFRESH_REFUSAL_MESSAGES[refusal], + refusal, + chainStartedAt: (presented.chainStartedAt ?? presented.createdAt)?.toISOString(), }, }); } else { @@ -580,26 +700,7 @@ export const refreshSession = async (req: Request, res: Response) => { return res.status(401).json({ error: 'invalid_refresh_token' }); } - // Reuse detection: if this session was already rotated, it means we’ve seen this token before - if (session.replacedBySessionId || session.revokedAt) { - logger.warn( - `Token reuse detected for session ${session.id}. replacedBySessionId=${session.replacedBySessionId ?? 'none'} revokedAt=${session.revokedAt ? session.revokedAt.toISOString() : 'null'}. This usually means an already-rotated refresh token was sent again.`, - ); - // Reuse -> revoke session chain - await revokeSessionChain(session); - await AuthEventService.log({ - userId: session.userId, - type: 'refresh_token_suspicious', - req, - metadata: { - reason: 'Refresh token reuse detected', - sessionId: session.id, - replacedBySessionId: session.replacedBySessionId, - revokedAt: session.revokedAt?.toISOString() ?? null, - }, - }); - return res.status(401).json({ error: 'refresh_token_reused' }); - } + const session = presented; // Update idle timeout on current session (just for bookkeeping) session.lastUsedAt = now; @@ -641,7 +742,7 @@ export const refreshSession = async (req: Request, res: Response) => { return res.status(401).json({ error: 'invalid_refresh_token' }); } - const { access_token_ttl, refresh_token_ttl, session_idle_ttl } = await getSystemConfig(); + const { refresh_token_ttl, session_idle_ttl } = await getSystemConfig(); const chainStartedAt = session.chainStartedAt ?? session.createdAt ?? now; const times = computeRotatedSessionTimes( { absoluteTtl: refresh_token_ttl || '1d', idleTtl: session_idle_ttl || '8h' }, @@ -702,7 +803,21 @@ export const refreshSession = async (req: Request, res: Response) => { // decides which of them rotated: unconditionally, both completed, the second write won, // and the other replacement stayed live while reachable from nothing, so the chain // revocation that reuse detection triggers walked past it and left it working. - const rotated = await claimSessionRotation(session, newSession.id); + const replayWindowMs = refreshReplayWindowMs(); + const rotated = await claimSessionRotation(session, newSession.id, { + rotatedAt: now, + replayTokenCiphertext: + replayWindowMs > 0 + ? sealReplayToken( + { + predecessorToken: refreshToken, + predecessorId: session.id, + successorId: newSession.id, + }, + newRefreshToken, + ) + : null, + }); if (!rotated) { logger.warn( @@ -713,25 +828,19 @@ export const refreshSession = async (req: Request, res: Response) => { // rather than left behind. Its refresh token was never returned to anyone. await hardRevokeSession(newSession, 'rotation_race_lost'); - // Reloaded so the chain walk follows the link the winner wrote rather than the null - // this instance still holds, which would stop at the old session and leave the - // winner's session live. + // Reloaded so what follows sees the link and the sealed token the winner wrote rather + // than the null this instance still holds. Inside the replay window that answers this + // request with the winner's successor (#598); outside it the chain walk follows the + // link, rather than stopping at the old session and leaving the winner's session live. await session.reload(); - await revokeSessionChain(session); - await AuthEventService.log({ - userId: user.id, - type: 'refresh_token_suspicious', + return answerRotatedRefresh( req, - metadata: { - reason: 'Refresh token rotated twice concurrently', - sessionId: session.id, - replacedBySessionId: session.replacedBySessionId, - abandonedSessionId: newSession.id, - }, - }); - - return res.status(401).json({ error: 'refresh_token_reused' }); + res, + session, + refreshToken, + 'Refresh token rotated twice concurrently', + ); } // Read again because a revoke-all can land while this rotation is in flight. Its cutoff @@ -753,39 +862,16 @@ export const refreshSession = async (req: Request, res: Response) => { }); } - const { token, organizationId } = await mintAccessToken({ - session: { - id: newSession.id, - organizationId: session.organizationId, - recovery: session.recovery, - hookClaims: session.hookClaims ?? null, - }, + logger.info( + `Refresh token rotated for user ${user.id}. oldSessionId=${session.id} newSessionId=${newSession.id}`, + ); + + return respondWithRefreshedSession(req, res, { + session: newSession, + claimsFrom: session, user, + refreshToken: newRefreshToken, + expiresAt, + now, }); - - if (token && newRefreshToken) { - logger.info( - `Refresh token rotated for user ${user.id}. oldSessionId=${session.id} newSessionId=${newSession.id}`, - ); - await AuthEventService.log({ userId: user.id, type: 'refresh_token_success', req }); - - return res.status(200).json({ - message: 'Success', - token, - refreshToken: newRefreshToken, - sub: user.id, - sessionId: newSession.id, - organizationId, - roles: user.roles, - email: user.email, - phone: user.phone, - ttl: parseDurationToSeconds(access_token_ttl || '15m'), - // What is left of the chain, not a full lifetime, so a caller sizing a cookie or a - // keychain entry from it does not outlive the session. - refreshTtl: Math.floor((expiresAt.getTime() - now.getTime()) / 1000), - ...(session.recovery === true ? { recovery: true } : {}), - }); - } - - return res.status(500).json({ error: 'Failed to refresh session' }); }; diff --git a/src/controllers/sessions.ts b/src/controllers/sessions.ts index a21d0458..a0a14838 100644 --- a/src/controllers/sessions.ts +++ b/src/controllers/sessions.ts @@ -11,7 +11,7 @@ import { Session } from '../models/sessions.js'; import { serializeSession } from '../services/apiResponseSerializers.js'; import { exchangeSubjectToken } from '../services/sessionExchangeService.js'; import { revokeAllSessionsForUsers } from '../services/sessionRevocation.js'; -import { hardRevokeSession } from '../services/sessionService.js'; +import { revokeSessionChain } from '../services/sessionService.js'; import { AuthenticatedRequest } from '../types/types.js'; import getLogger from '../utils/logger.js'; @@ -64,7 +64,8 @@ export const revokeSession = async (req: Request, res: Response) => { return res.status(404).json({ error: 'Session not found' }); } - await hardRevokeSession(session, 'user_revoked'); + // Walked to the head, because the row the caller listed may have rotated since (#592). + await revokeSessionChain(session, 'user_revoked'); logger.info(`Session revoked ${session.id}`); diff --git a/src/lib/refreshRefusal.ts b/src/lib/refreshRefusal.ts new file mode 100644 index 00000000..094c9349 --- /dev/null +++ b/src/lib/refreshRefusal.ts @@ -0,0 +1,24 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { Session } from '../models/sessions.js'; + +export type RefreshRefusalReason = 'absolute_lifetime_reached' | 'idle_timeout'; + +/** + * Why an unrotated session can no longer be refreshed: revoked, or out of time. `null` means + * it can be. + */ +export function classifyRefreshRefusal( + session: Pick, + now = new Date(), +): RefreshRefusalReason | 'revoked' | null { + if (session.revokedAt) return 'revoked'; + if (session.expiresAt <= now) return 'absolute_lifetime_reached'; + if (session.idleExpiresAt <= now) return 'idle_timeout'; + + return null; +} diff --git a/src/lib/refreshReplayToken.ts b/src/lib/refreshReplayToken.ts new file mode 100644 index 00000000..a596aa94 --- /dev/null +++ b/src/lib/refreshReplayToken.ts @@ -0,0 +1,92 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { createCipheriv, createDecipheriv, createHmac, randomBytes } from 'crypto'; + +import { authSecret } from '../config/authSecrets.js'; + +const DEFAULT_WINDOW_SECONDS = 5; +const MAX_WINDOW_SECONDS = 60; + +/** How many times a rotated refresh token may be answered again inside the window. */ +export const MAX_REFRESH_REPLAYS = 3; + +// Not a valid refresh token (`:` is outside base64url), so the key input can never equal +// the input of a stored refresh token lookup. +const KEY_CONTEXT = 'seamless-refresh-replay:v1:'; +const FORMAT = 'v1'; +const AUTH_TAG_LENGTH = 16; + +/** + * How long after a rotation the rotated token is still answered with the same successor, + * so two adapter instances refreshing at once do not read as reuse. `0` disables it. + */ +export function refreshReplayWindowMs(env: Record = process.env) { + const raw = env.REFRESH_REPLAY_WINDOW_SECONDS; + const seconds = raw === undefined || raw.trim() === '' ? DEFAULT_WINDOW_SECONDS : Number(raw); + + if (!Number.isFinite(seconds) || seconds <= 0) return 0; + + return Math.min(seconds, MAX_WINDOW_SECONDS) * 1000; +} + +// Keyed by the rotated token as well as the server secret, so the stored ciphertext is +// useless to anyone who does not already hold the token it answers for. +function replayKey(predecessorToken: string) { + return createHmac('sha256', authSecret('REFRESH_TOKEN_LOOKUP_SECRET')) + .update(KEY_CONTEXT) + .update(predecessorToken) + .digest(); +} + +function associatedData(predecessorId: string, successorId: string) { + return Buffer.from(`${predecessorId}:${successorId}`); +} + +export interface ReplayBinding { + predecessorToken: string; + predecessorId: string; + successorId: string; +} + +export function sealReplayToken(binding: ReplayBinding, successorToken: string) { + const iv = randomBytes(12); + const cipher = createCipheriv('aes-256-gcm', replayKey(binding.predecessorToken), iv, { + authTagLength: AUTH_TAG_LENGTH, + }); + cipher.setAAD(associatedData(binding.predecessorId, binding.successorId)); + + const ciphertext = Buffer.concat([cipher.update(successorToken, 'utf8'), cipher.final()]); + + return [FORMAT, iv, ciphertext, cipher.getAuthTag()] + .map((part) => (typeof part === 'string' ? part : part.toString('base64url'))) + .join('.'); +} + +export function openReplayToken(binding: ReplayBinding, sealed: string): string | null { + const [format, iv, ciphertext, tag] = sealed.split('.'); + + if (format !== FORMAT || !iv || !ciphertext || !tag) return null; + + try { + const decipher = createDecipheriv( + 'aes-256-gcm', + replayKey(binding.predecessorToken), + Buffer.from(iv, 'base64url'), + // Pinned, or a truncated tag would be accepted. + { authTagLength: AUTH_TAG_LENGTH }, + ); + decipher.setAAD(associatedData(binding.predecessorId, binding.successorId)); + decipher.setAuthTag(Buffer.from(tag, 'base64url')); + + return Buffer.concat([ + decipher.update(Buffer.from(ciphertext, 'base64url')), + decipher.final(), + ]).toString('utf8'); + } catch { + return null; + } +} diff --git a/src/migrations/20261118120000-add-refresh-replay.cjs b/src/migrations/20261118120000-add-refresh-replay.cjs new file mode 100644 index 00000000..80878a75 --- /dev/null +++ b/src/migrations/20261118120000-add-refresh-replay.cjs @@ -0,0 +1,32 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +'use strict'; + +/** + * The refresh replay window (#598): when a session rotated, its successor's refresh token + * sealed for a holder of the rotated token, and how many times it has been replayed. + * + * @type {import('sequelize-cli').Migration} + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query(` + ALTER TABLE public.sessions ADD COLUMN IF NOT EXISTS "rotatedAt" timestamp with time zone; + ALTER TABLE public.sessions ADD COLUMN IF NOT EXISTS "replayTokenCiphertext" text; + ALTER TABLE public.sessions + ADD COLUMN IF NOT EXISTS "replayCount" integer NOT NULL DEFAULT 0; + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(` + ALTER TABLE public.sessions DROP COLUMN IF EXISTS "replayCount"; + ALTER TABLE public.sessions DROP COLUMN IF EXISTS "replayTokenCiphertext"; + ALTER TABLE public.sessions DROP COLUMN IF EXISTS "rotatedAt"; + `); + }, +}; diff --git a/src/models/sessions.ts b/src/models/sessions.ts index 424ff3f4..5625e3a2 100644 --- a/src/models/sessions.ts +++ b/src/models/sessions.ts @@ -31,6 +31,10 @@ export interface SessionAttributes { /** What the `pre_token` login hook added, kept so a refresh never calls the hook. */ hookClaims?: Record | null; replacedBySessionId?: string | null; + rotatedAt?: Date | null; + /** The successor's refresh token, sealed for a holder of this row's token (see refreshReplay). */ + replayTokenCiphertext?: string | null; + replayCount?: number; parentSessionId?: string | null; exchangeClientId?: string | null; exchangeGrantType?: string | null; @@ -44,6 +48,9 @@ type SessionCreationAttributes = Optional< SessionAttributes, | 'id' | 'replacedBySessionId' + | 'rotatedAt' + | 'replayTokenCiphertext' + | 'replayCount' | 'revokedAt' | 'revokedReason' | 'deviceName' @@ -82,6 +89,9 @@ export class Session declare authTime: Date | null; declare hookClaims: Record | null; declare replacedBySessionId: string | null; + declare rotatedAt: Date | null; + declare replayTokenCiphertext: string | null; + declare replayCount: number; declare parentSessionId: string | null; declare exchangeClientId: string | null; declare exchangeGrantType: string | null; @@ -174,6 +184,19 @@ const initializeSessionModel = (sequelize: Sequelize) => { type: DataTypes.UUID, allowNull: true, }, + rotatedAt: { + type: DataTypes.DATE, + allowNull: true, + }, + replayTokenCiphertext: { + type: DataTypes.TEXT, + allowNull: true, + }, + replayCount: { + type: DataTypes.INTEGER, + allowNull: false, + defaultValue: 0, + }, // A session a token exchange issued (ADR 0003): the provider sign-in it ends with, the // client that exchanged, and the grant behind the sign-in. Carried across rotation. parentSessionId: { diff --git a/src/services/sessionService.ts b/src/services/sessionService.ts index 3375c7ce..9bd54277 100644 --- a/src/services/sessionService.ts +++ b/src/services/sessionService.ts @@ -6,8 +6,13 @@ import { timingSafeEqual } from 'crypto'; import { importSPKI, jwtVerify } from 'jose'; -import { Op } from 'sequelize'; +import { literal, Op } from 'sequelize'; +import { + MAX_REFRESH_REPLAYS, + openReplayToken, + refreshReplayWindowMs, +} from '../lib/refreshReplayToken.js'; import { createRefreshTokenLookup } from '../lib/token.js'; import { Session } from '../models/sessions.js'; import { User } from '../models/users.js'; @@ -100,11 +105,21 @@ export async function revokeSessionChain(session: Session, reason = 'refresh_tok while (current && !seen.has(current.id)) { seen.add(current.id); - current.revokedAt = now; - current.revokedReason = reason; + // A row an earlier revoke already ended keeps the reason it was ended for. + if (!current.revokedAt) { + current.revokedAt = now; + current.revokedReason = reason; + } + current.replayTokenCiphertext = null; await current.save(); - if (!current.replacedBySessionId) break; + if (!current.replacedBySessionId) { + // A rotation can claim the head between its read and the save above, and the save + // leaves that link in place without this copy seeing it. Once saved as revoked the + // head cannot be claimed again, so one reload settles where the chain ends. + await current.reload(); + if (!current.replacedBySessionId) break; + } current = await Session.findByPk(current.replacedBySessionId); } @@ -172,9 +187,12 @@ export async function revokeOrphanedChildSessions( export async function claimSessionRotation( session: Session, replacementSessionId: string, + replay?: { rotatedAt: Date; replayTokenCiphertext: string | null }, ): Promise { + // The sealed successor token is written in the same statement as the link, so a request + // that loses this race finds it there when it falls back to the replay window. const [claimed] = await Session.update( - { replacedBySessionId: replacementSessionId }, + { replacedBySessionId: replacementSessionId, ...replay }, { where: { id: session.id, replacedBySessionId: null, revokedAt: null } }, ); @@ -183,6 +201,7 @@ export async function claimSessionRotation( } session.replacedBySessionId = replacementSessionId; + if (replay) Object.assign(session, replay); return true; } @@ -216,20 +235,16 @@ function safeEqual(left: string, right: string | null) { return timingSafeEqual(leftBuffer, rightBuffer); } -export async function findRefreshSessionByToken( - refreshToken: string, - now = new Date(), -): Promise { +/** + * The session a refresh token belongs to, whatever state it is in. Expired, idled out, + * revoked and rotated rows are all returned, because what the caller does next depends on + * which: a rotated row is reuse however long ago it rotated, and that signal is lost if the + * lookup filters it out first. + */ +export async function findRefreshSessionByToken(refreshToken: string): Promise { const refreshTokenLookup = createRefreshTokenLookup(refreshToken); - const session = await Session.findOne({ - where: { - revokedAt: null, - expiresAt: { [Op.gt]: now }, - idleExpiresAt: { [Op.gt]: now }, - refreshTokenLookup, - }, - }); + const session = await Session.findOne({ where: { refreshTokenLookup } }); if (!session) return null; @@ -245,29 +260,76 @@ export async function findRefreshSessionByToken( return session; } -export type RefreshRefusalReason = 'absolute_lifetime_reached' | 'idle_timeout'; +export interface RefreshReplay { + successor: Session; + user: User; + refreshToken: string; +} /** - * Why a refresh token that `findRefreshSessionByToken` rejected no longer works, when the - * answer is that its session ran out of time. Only used to make the audit trail say so, - * never to accept the token. + * Answers a rotated refresh token with the successor it already rotated into, when it is + * presented again within the replay window (#598). Two adapter instances refreshing the + * same token at once otherwise read as reuse and sign the user out. + * + * Only the immediate predecessor of a live head qualifies, only inside the window and only + * `MAX_REFRESH_REPLAYS` times, and the answer is the existing successor, never a new one. + * `null` means the presentation is reuse. */ -export async function classifyExpiredRefreshToken( - refreshToken: string, +export async function replayRefreshRotation( + session: Session, + presentedToken: string, now = new Date(), -): Promise<{ reason: RefreshRefusalReason; session: Session } | null> { - const refreshTokenLookup = createRefreshTokenLookup(refreshToken); +): Promise { + const windowMs = refreshReplayWindowMs(); + const { rotatedAt, replayTokenCiphertext, replacedBySessionId } = session; - const session = await Session.findOne({ - where: { revokedAt: null, replacedBySessionId: null, refreshTokenLookup }, - }); + if (session.revokedAt || !replacedBySessionId || !rotatedAt || !replayTokenCiphertext) { + return null; + } - if (!session || !safeEqual(refreshTokenLookup, session.refreshTokenLookup)) return null; + if (windowMs === 0 || now.getTime() - new Date(rotatedAt).getTime() > windowMs) { + await Session.update({ replayTokenCiphertext: null }, { where: { id: session.id } }); + return null; + } + + // Also refuses a successor that has itself rotated, so an older ancestor is never answered. + const successor = await validateSessionRecord(replacedBySessionId); + if (!successor) return null; + + const refreshToken = openReplayToken( + { predecessorToken: presentedToken, predecessorId: session.id, successorId: successor.id }, + replayTokenCiphertext, + ); + + if ( + !refreshToken || + !safeEqual(createRefreshTokenLookup(refreshToken), successor.refreshTokenLookup) + ) { + logger.warn(`Replay token for session ${session.id} did not open to its successor`); + return null; + } + + const user = await getUserFromSession(successor); + if (!user) return null; + + // Counted in the database, so concurrent replays cannot all read the same count and + // each spend the last one. + const [claimed] = await Session.update( + { replayCount: literal('"replayCount" + 1') }, + { + where: { + id: session.id, + revokedAt: null, + replacedBySessionId: successor.id, + replayCount: { [Op.lt]: MAX_REFRESH_REPLAYS }, + rotatedAt: { [Op.gt]: new Date(now.getTime() - windowMs) }, + }, + }, + ); - if (session.expiresAt <= now) return { reason: 'absolute_lifetime_reached', session }; - if (session.idleExpiresAt <= now) return { reason: 'idle_timeout', session }; + if (claimed === 0) return null; - return null; + return { successor, user, refreshToken }; } export async function validateSessionRecord(sessionId: string) { diff --git a/tests/e2e/authFlow.spec.ts b/tests/e2e/authFlow.spec.ts index ba74d495..d3f0afa8 100644 --- a/tests/e2e/authFlow.spec.ts +++ b/tests/e2e/authFlow.spec.ts @@ -139,6 +139,6 @@ describe('E2E Auth Flow', () => { .set('Authorization', 'Bearer refresh-token'); expect(refreshRes.status).toBe(200); - expect(findRefreshSessionByToken).toHaveBeenCalledWith('refresh-token', expect.any(Date)); + expect(findRefreshSessionByToken).toHaveBeenCalledWith('refresh-token'); }); }); diff --git a/tests/factories/sessionFactory.ts b/tests/factories/sessionFactory.ts index 8bf7599e..af2f66d1 100644 --- a/tests/factories/sessionFactory.ts +++ b/tests/factories/sessionFactory.ts @@ -15,6 +15,7 @@ export function buildSession(overrides: any = {}) { return Promise.resolve(this); }), save: vi.fn(), + reload: vi.fn(), ...overrides, }; } diff --git a/tests/integration/admin/admin.spec.ts b/tests/integration/admin/admin.spec.ts index 935568e4..1f68dc0a 100644 --- a/tests/integration/admin/admin.spec.ts +++ b/tests/integration/admin/admin.spec.ts @@ -13,7 +13,7 @@ import { verifyAuthEventChain } from '../../../src/services/auditIntegrity.js'; import { AuthEventService } from '../../../src/services/authEventService.js'; import { Session } from '../../../src/models/sessions.js'; import { TotpCredential } from '../../../src/models/totpCredentials.js'; -import { hardRevokeSession } from '../../../src/services/sessionService.js'; +import { hardRevokeSession, revokeSessionChain } from '../../../src/services/sessionService.js'; import { createUser, getAuthEvents, @@ -217,7 +217,7 @@ describe('DELETE /admin/sessions/by-id/:id', () => { const res = await request(app).delete('/admin/sessions/by-id/session-to-revoke'); expect(res.status).toBe(200); - expect(hardRevokeSession).toHaveBeenCalledWith(session, 'admin_revoke'); + expect(revokeSessionChain).toHaveBeenCalledWith(session, 'admin_revoke'); }); it('returns 404 when a single admin-managed session is missing', async () => { diff --git a/tests/integration/authentication/authentication.spec.ts b/tests/integration/authentication/authentication.spec.ts index 027a1797..1b9380b0 100644 --- a/tests/integration/authentication/authentication.spec.ts +++ b/tests/integration/authentication/authentication.spec.ts @@ -19,6 +19,7 @@ import { claimSessionRotation, findRefreshSessionByToken, hardRevokeSession, + replayRefreshRotation, revokeSessionChain, } from '../../../src/services/sessionService'; import { AuthEvent } from '../../../src/models/authEvents'; @@ -904,7 +905,8 @@ describe('POST /refresh', () => { expect(res.body.error).toBe('invalid_refresh_token'); }); - it('detects refresh token reuse for an already revoked session', async () => { + // Revoked but never rotated is a session that ended, not a token presented twice. + it('refuses a revoked session that never rotated without treating it as reuse', async () => { const session = { id: 'session-1', replacedBySessionId: null, @@ -917,17 +919,39 @@ describe('POST /refresh', () => { const res = await request(app).post('/refresh').set('Authorization', 'Bearer refresh-token'); + expect(res.status).toBe(401); + expect(res.body.error).toBe('invalid_refresh_token'); + expect(revokeSessionChain).not.toHaveBeenCalled(); + }); + + it('detects refresh token reuse and revokes the chain', async () => { + const session = { + id: 'session-1', + replacedBySessionId: 'session-2', + revokedAt: null, + userId: 'user-1', + save: vi.fn(), + }; + + (findRefreshSessionByToken as any).mockResolvedValue(session); + + const res = await request(app).post('/refresh').set('Authorization', 'Bearer refresh-token'); + expect(res.status).toBe(401); expect(res.body.error).toBe('refresh_token_reused'); expect(revokeSessionChain).toHaveBeenCalledWith(session); }); - it('detects refresh token reuse and revokes the chain', async () => { + // The rotated row's idle window passing used to hide it from the lookup, which answered + // a plain 401 and left the chain live (#593). + it('treats a rotated token as reuse after its idle window and revokes the chain', async () => { const session = { id: 'session-1', replacedBySessionId: 'session-2', revokedAt: null, userId: 'user-1', + expiresAt: new Date(Date.now() + 3_600_000), + idleExpiresAt: new Date(Date.now() - 1_000), save: vi.fn(), }; @@ -935,11 +959,171 @@ describe('POST /refresh', () => { const res = await request(app).post('/refresh').set('Authorization', 'Bearer refresh-token'); + expect(replayRefreshRotation).toHaveBeenCalledWith(session, 'refresh-token'); expect(res.status).toBe(401); expect(res.body.error).toBe('refresh_token_reused'); expect(revokeSessionChain).toHaveBeenCalledWith(session); }); + describe('within the replay window', () => { + const successor = () => ({ + id: 'session-2', + userId: 'user-1', + organizationId: null, + recovery: false, + hookClaims: null, + expiresAt: new Date(Date.now() + 3_600_000), + }); + + beforeEach(() => { + (signAccessToken as any).mockResolvedValue('access-for-successor'); + (getSystemConfig as any).mockResolvedValue({ + access_token_ttl: '15m', + refresh_token_ttl: '1h', + session_idle_ttl: '8h', + }); + }); + + // Two adapter instances refreshing the same token: the second gets the successor the + // first already made, not a parallel chain and not a sign-out (#598). + it('answers the rotated token with the same successor', async () => { + const session = { + id: 'session-1', + replacedBySessionId: 'session-2', + revokedAt: null, + userId: 'user-1', + save: vi.fn(), + }; + (findRefreshSessionByToken as any).mockResolvedValue(session); + (replayRefreshRotation as any).mockResolvedValue({ + successor: successor(), + user: buildUser({ id: 'user-1' }), + refreshToken: 'successor-refresh-token', + }); + + const res = await request(app).post('/refresh').set('Authorization', 'Bearer refresh-token'); + + expect(res.status).toBe(200); + expect(res.body.refreshToken).toBe('successor-refresh-token'); + expect(res.body.sessionId).toBe('session-2'); + expect(res.body.token).toBe('access-for-successor'); + expect(res.body.refreshTtl).toBeGreaterThan(3_590); + expect((signAccessToken as any).mock.calls.at(-1)[0]).toBe('session-2'); + expect(Session.create).not.toHaveBeenCalled(); + expect(revokeSessionChain).not.toHaveBeenCalled(); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'refresh_token_success', + sessionId: 'session-2', + metadata: { replayOf: 'session-1' }, + }), + ); + }); + + it('answers the rotation that lost the race with the winner’s successor', async () => { + const session = { + id: 'session-1', + replacedBySessionId: null as string | null, + revokedAt: null, + userId: 'user-1', + infraId: 'app', + mode: 'server', + userAgent: 'agent', + save: vi.fn(), + reload: vi.fn(async function (this: { replacedBySessionId: string | null }) { + this.replacedBySessionId = 'session-2'; + }), + }; + (findRefreshSessionByToken as any).mockResolvedValue(session); + (User.findOne as any).mockResolvedValue(buildUser({ id: 'user-1' })); + (Session.create as any).mockResolvedValue({ id: 'losing-session' }); + (claimSessionRotation as any).mockResolvedValue(false); + (generateRefreshToken as any).mockReturnValue('losing-refresh-token'); + (createRefreshTokenLookup as any).mockReturnValue('losing-lookup'); + (replayRefreshRotation as any).mockResolvedValue({ + successor: successor(), + user: buildUser({ id: 'user-1' }), + refreshToken: 'successor-refresh-token', + }); + + const res = await request(app).post('/refresh').set('Authorization', 'Bearer refresh-token'); + + expect(res.status).toBe(200); + expect(res.body.refreshToken).toBe('successor-refresh-token'); + expect(res.body.sessionId).toBe('session-2'); + expect(hardRevokeSession).toHaveBeenCalledWith( + { id: 'losing-session' }, + 'rotation_race_lost', + ); + expect(session.reload).toHaveBeenCalled(); + expect(replayRefreshRotation).toHaveBeenCalledWith(session, 'refresh-token'); + expect(revokeSessionChain).not.toHaveBeenCalled(); + }); + + it('answers 500 when the access token for the successor cannot be signed', async () => { + (findRefreshSessionByToken as any).mockResolvedValue({ + id: 'session-1', + replacedBySessionId: 'session-2', + revokedAt: null, + userId: 'user-1', + }); + (replayRefreshRotation as any).mockResolvedValue({ + successor: successor(), + user: buildUser({ id: 'user-1' }), + refreshToken: 'successor-refresh-token', + }); + (signAccessToken as any).mockResolvedValue(null); + + const res = await request(app).post('/refresh').set('Authorization', 'Bearer refresh-token'); + + expect(res.status).toBe(500); + }); + }); + + describe('sealing the successor for the replay window', () => { + function rotatable() { + (findRefreshSessionByToken as any).mockResolvedValue({ + id: 'session-1', + replacedBySessionId: null, + revokedAt: null, + userId: 'user-1', + save: vi.fn(), + }); + (User.findOne as any).mockResolvedValue(buildUser({ id: 'user-1' })); + (Session.create as any).mockResolvedValue({ id: 'session-2' }); + (signAccessToken as any).mockResolvedValue('access'); + (generateRefreshToken as any).mockReturnValue('successor-refresh-token'); + (createRefreshTokenLookup as any).mockReturnValue('successor-lookup'); + (getSystemConfig as any).mockResolvedValue({ + access_token_ttl: '15m', + refresh_token_ttl: '1h', + session_idle_ttl: '8h', + }); + } + + it('writes the sealed successor token with the rotation link', async () => { + rotatable(); + + const res = await request(app).post('/refresh').set('Authorization', 'Bearer refresh-token'); + + expect(res.status).toBe(200); + const [, successorId, replay] = (claimSessionRotation as any).mock.calls[0]; + expect(successorId).toBe('session-2'); + expect(replay.rotatedAt).toBeInstanceOf(Date); + expect(replay.replayTokenCiphertext).toMatch(/^v1\./); + expect(replay.replayTokenCiphertext).not.toContain('successor-refresh-token'); + }); + + it('seals nothing while the window is disabled', async () => { + vi.stubEnv('REFRESH_REPLAY_WINDOW_SECONDS', '0'); + rotatable(); + + await request(app).post('/refresh').set('Authorization', 'Bearer refresh-token'); + + expect((claimSessionRotation as any).mock.calls[0][2].replayTokenCiphertext).toBeNull(); + }); + }); + it('revokes the session when the refresh user no longer exists', async () => { const session = { id: 'session-1', diff --git a/tests/integration/session/session.security.spec.ts b/tests/integration/session/session.security.spec.ts index 580997e0..934792a5 100644 --- a/tests/integration/session/session.security.spec.ts +++ b/tests/integration/session/session.security.spec.ts @@ -5,7 +5,7 @@ import { Application } from 'express'; import { createApp } from '../../../src/app'; import { Session } from '../../../src/models/sessions.js'; import { User } from '../../../src/models/users.js'; -import { hardRevokeSession } from '../../../src/services/sessionService.js'; +import { hardRevokeSession, revokeSessionChain } from '../../../src/services/sessionService.js'; import { buildSession } from '../../factories/sessionFactory.js'; let mockUser: any = { @@ -104,7 +104,7 @@ describe('Session Security - Revocation', () => { const res = await request(app).delete('/sessions/session-1'); expect(res.status).toBe(200); - expect(hardRevokeSession).toHaveBeenCalledWith(session, 'user_revoked'); + expect(revokeSessionChain).toHaveBeenCalledWith(session, 'user_revoked'); }); it('revokes all active sessions in one update and records the cutoff', async () => { diff --git a/tests/integration/session/session.spec.ts b/tests/integration/session/session.spec.ts index ad35e01c..c883efda 100644 --- a/tests/integration/session/session.spec.ts +++ b/tests/integration/session/session.spec.ts @@ -7,7 +7,7 @@ import { Op } from 'sequelize'; import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; import { Session } from '../../../src/models/sessions.js'; import { User } from '../../../src/models/users.js'; -import { hardRevokeSession } from '../../../src/services/sessionService.js'; +import { hardRevokeSession, revokeSessionChain } from '../../../src/services/sessionService.js'; import { buildSession } from '../../factories/sessionFactory.js'; let app: Application; @@ -67,7 +67,7 @@ describe('DELETE /sessions/:id', () => { const res = await request(app).delete('/sessions/session-1'); expect(res.status).toBe(200); - expect(hardRevokeSession).toHaveBeenCalledWith(session, 'user_revoked'); + expect(revokeSessionChain).toHaveBeenCalledWith(session, 'user_revoked'); }); it('returns 404 if session not found', async () => { diff --git a/tests/postgres/refreshRotation.spec.ts b/tests/postgres/refreshRotation.spec.ts new file mode 100644 index 00000000..b7973585 --- /dev/null +++ b/tests/postgres/refreshRotation.spec.ts @@ -0,0 +1,277 @@ +import { randomUUID } from 'crypto'; +import fs from 'fs'; +import { decodeJwt } from 'jose'; +import os from 'os'; +import path from 'path'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { invalidateSystemConfigCache } from '../../src/config/getSystemConfig.js'; +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { Session } from '../../src/models/sessions.js'; +import { SystemConfig } from '../../src/models/systemConfig.js'; +import { User } from '../../src/models/users.js'; +import { buildSystemConfig } from '../factories/systemConfigFactory.js'; + +type App = Awaited>; +type Issuance = typeof import('../../src/services/sessionIssuance.js'); + +const EMAIL_DOMAIN = 'refresh-rotation.test'; + +let app: App; +let issuance: Issuance; +const savedEnv: Record = {}; + +function setEnv(values: Record) { + for (const [key, value] of Object.entries(values)) { + savedEnv[key] = process.env[key]; + process.env[key] = value; + } +} + +beforeAll(async () => { + setEnv({ + ISSUER: 'http://localhost:5312', + DISABLE_AUTH_RATE_LIMITS: 'true', + SEAMLESS_DEV_KEYS_DIR: fs.mkdtempSync(path.join(os.tmpdir(), 'seamless-keys-')), + }); + + await initializeModels(); + + for (const [key, value] of Object.entries(buildSystemConfig())) { + await getSequelize().query( + `INSERT INTO system_config (key, value, "createdAt", "updatedAt") + VALUES (:key, CAST(:value AS jsonb), now(), now()) + ON CONFLICT (key) DO NOTHING`, + { replacements: { key, value: JSON.stringify(value) } }, + ); + } + await getSequelize().query( + `INSERT INTO system_config (key, value, "createdAt", "updatedAt") + VALUES ('max_concurrent_sessions', 'null'::jsonb, now(), now()) + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`, + ); + invalidateSystemConfigCache(); + + issuance = await import('../../src/services/sessionIssuance.js'); + + const { initDevSigningKey } = await import('../../src/utils/signingKeyStore.js'); + const { createApp } = await import('../../src/app.js'); + initDevSigningKey(); + app = await createApp(); +}); + +beforeEach(() => { + invalidateSystemConfigCache(); +}); + +afterAll(async () => { + await SystemConfig.destroy({ where: { key: ['max_concurrent_sessions'] } }); + await getSequelize().query(`DELETE FROM users WHERE email LIKE :pattern`, { + replacements: { pattern: `%@${EMAIL_DOMAIN}` }, + }); + invalidateSystemConfigCache(); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + await getSequelize().close(); +}); + +function fakeResponse() { + const res: any = { body: undefined, statusCode: 200 }; + res.status = (code: number) => { + res.statusCode = code; + return res; + }; + res.json = (body: unknown) => { + res.body = body; + return res; + }; + return res; +} + +async function signIn(roles = ['user']) { + const user = await User.create({ + email: `${randomUUID()}@${EMAIL_DOMAIN}`, + phone: null, + roles, + } as never); + const res = fakeResponse(); + + await issuance.issueSessionAndRespond({ + method: 'passkey', + user: { id: user.id, email: user.email, phone: null, roles }, + req: { + ip: '127.0.0.1', + headers: { 'user-agent': 'refresh-rotation-test' }, + get: () => 'refresh-rotation-test', + } as never, + res, + }); + + return { + user, + sessionId: decodeJwt(res.body.token).sid as string, + refreshToken: res.body.refreshToken as string, + token: res.body.token as string, + }; +} + +function refresh(refreshToken: string) { + return request(app).post('/refresh').set('Authorization', `Bearer ${refreshToken}`); +} + +async function liveSessions(userId: string) { + const rows = await Session.findAll({ where: { userId, revokedAt: null } }); + return rows.filter((row) => row.replacedBySessionId === null); +} + +async function ageRotation(sessionId: string, ms: number) { + await Session.update({ rotatedAt: new Date(Date.now() - ms) }, { where: { id: sessionId } }); +} + +describe('the refresh replay window (#598)', () => { + it('answers two concurrent refreshes of one token with the same successor', async () => { + const { user, refreshToken, sessionId } = await signIn(); + + const [first, second] = await Promise.all([refresh(refreshToken), refresh(refreshToken)]); + + expect(first.status).toBe(200); + expect(second.status).toBe(200); + expect(second.body.refreshToken).toBe(first.body.refreshToken); + expect(second.body.sessionId).toBe(first.body.sessionId); + expect(first.body.sessionId).not.toBe(sessionId); + + // One chain, not two: whatever the race created besides the successor is revoked. + const live = await liveSessions(user.id); + expect(live.map((row) => row.id)).toEqual([first.body.sessionId]); + + const next = await refresh(first.body.refreshToken); + expect(next.status).toBe(200); + }); + + it('answers a sequential replay in the window, a bounded number of times', async () => { + const { user, refreshToken } = await signIn(); + + const rotated = await refresh(refreshToken); + expect(rotated.status).toBe(200); + + for (let replay = 0; replay < 3; replay += 1) { + const again = await refresh(refreshToken); + expect(again.status).toBe(200); + expect(again.body.refreshToken).toBe(rotated.body.refreshToken); + } + + const spent = await refresh(refreshToken); + expect(spent.status).toBe(401); + expect(spent.body.error).toBe('refresh_token_reused'); + expect(await liveSessions(user.id)).toEqual([]); + }); + + it('treats the predecessor as reuse once the window has passed', async () => { + const { user, refreshToken, sessionId } = await signIn(); + + const rotated = await refresh(refreshToken); + await ageRotation(sessionId, 6_000); + + const late = await refresh(refreshToken); + + expect(late.status).toBe(401); + expect(late.body.error).toBe('refresh_token_reused'); + expect(await liveSessions(user.id)).toEqual([]); + expect((await refresh(rotated.body.refreshToken)).status).toBe(401); + + const predecessor = await Session.findByPk(sessionId); + expect(predecessor?.replayTokenCiphertext).toBeNull(); + }); + + it('treats an older ancestor as reuse even inside the window', async () => { + const { user, refreshToken } = await signIn(); + + const second = await refresh(refreshToken); + const third = await refresh(second.body.refreshToken); + expect(third.status).toBe(200); + + const ancestor = await refresh(refreshToken); + + expect(ancestor.status).toBe(401); + expect(ancestor.body.error).toBe('refresh_token_reused'); + expect(await liveSessions(user.id)).toEqual([]); + }); + + it('stores the successor token only sealed', async () => { + const { refreshToken, sessionId } = await signIn(); + + const rotated = await refresh(refreshToken); + const predecessor = await Session.findByPk(sessionId); + + expect(predecessor?.replayTokenCiphertext).toMatch(/^v1\./); + expect(predecessor?.replayTokenCiphertext).not.toContain(rotated.body.refreshToken); + }); +}); + +describe('reuse detection after the idle window (#593)', () => { + it('revokes the chain when a rotated token returns after its row idled out', async () => { + const { user, refreshToken, sessionId } = await signIn(); + + const rotated = await refresh(refreshToken); + await Session.update( + { + idleExpiresAt: new Date(Date.now() - 1_000), + rotatedAt: new Date(Date.now() - 9 * 3_600_000), + }, + { where: { id: sessionId } }, + ); + + const reused = await refresh(refreshToken); + + expect(reused.status).toBe(401); + expect(reused.body.error).toBe('refresh_token_reused'); + expect(await liveSessions(user.id)).toEqual([]); + expect((await refresh(rotated.body.refreshToken)).status).toBe(401); + }); +}); + +describe('revoking a session that has rotated since it was listed (#592)', () => { + it('ends the head of the chain for the user', async () => { + const { user, refreshToken, sessionId } = await signIn(); + const other = await signIn(); + const rotated = await refresh(refreshToken); + + const res = await request(app) + .delete(`/sessions/${sessionId}`) + .set('Authorization', `Bearer ${other.token}`); + // Another user's row is not theirs to revoke. + expect(res.status).toBe(404); + + const own = await request(app) + .delete(`/sessions/${sessionId}`) + .set('Authorization', `Bearer ${rotated.body.token}`); + + expect(own.status).toBe(200); + expect(await liveSessions(user.id)).toEqual([]); + const head = await Session.findByPk(rotated.body.sessionId); + expect(head?.revokedReason).toBe('user_revoked'); + expect((await refresh(rotated.body.refreshToken)).status).toBe(401); + }); + + it('ends the head of the chain for an admin', async () => { + const admin = await signIn(['admin']); + await Session.update( + { stepUpVerifiedAt: new Date(), stepUpMethod: 'webauthn' }, + { where: { id: admin.sessionId } }, + ); + const target = await signIn(); + const rotated = await refresh(target.refreshToken); + + const res = await request(app) + .delete(`/admin/sessions/by-id/${target.sessionId}`) + .set('Authorization', `Bearer ${admin.token}`); + + expect(res.status).toBe(200); + expect(await liveSessions(target.user.id)).toEqual([]); + const head = await Session.findByPk(rotated.body.sessionId); + expect(head?.revokedReason).toBe('admin_revoke'); + }); +}); diff --git a/tests/postgres/sessionExchange.spec.ts b/tests/postgres/sessionExchange.spec.ts index 91f27d31..4297e26b 100644 --- a/tests/postgres/sessionExchange.spec.ts +++ b/tests/postgres/sessionExchange.spec.ts @@ -115,6 +115,15 @@ beforeEach(() => { invalidateSystemConfigCache(); }); +// Inside the replay window a rotated token is answered with its successor (#598), so +// reuse is presented after it. +async function outlastReplayWindow(successorId: string) { + await Session.update( + { rotatedAt: new Date(Date.now() - 61_000) }, + { where: { replacedBySessionId: successorId } }, + ); +} + function nativeClient(overrides: Partial = {}) { return OidcClient.create({ id: `cli-${randomUUID()}`, @@ -1259,6 +1268,7 @@ describe('the child session lifecycle', () => { const { parent, childRefresh } = await family(); const rotated = await refresh(childRefresh); + await outlastReplayWindow(rotated.body.sessionId); const reused = await refresh(childRefresh); expect(reused.status).toBe(401); @@ -1339,7 +1349,8 @@ describe('the child session lifecycle', () => { it('refresh token reuse on the parent chain', async () => { const { parentRefresh, childId, childToken } = await family(); - await refresh(parentRefresh); + const rotated = await refresh(parentRefresh); + await outlastReplayWindow(rotated.body.sessionId); const reused = await refresh(parentRefresh); expect(reused.status).toBe(401); diff --git a/tests/setup/mocks.ts b/tests/setup/mocks.ts index 72f343e6..2ef8e25a 100644 --- a/tests/setup/mocks.ts +++ b/tests/setup/mocks.ts @@ -305,7 +305,7 @@ vi.mock('../../src/services/sessionService.js', () => ({ validateBearerToken: vi.fn(), validateSessionRecord: vi.fn(), findRefreshSessionByToken: vi.fn(), - classifyExpiredRefreshToken: vi.fn(async () => null), + replayRefreshRotation: vi.fn(async () => null), getUserFromSession: vi.fn(), verifyJwtWithKid: vi.fn(), revokeSessionChain: vi.fn(), diff --git a/tests/unit/controllers/authentication.spec.ts b/tests/unit/controllers/authentication.spec.ts index 485444c0..e6003b62 100644 --- a/tests/unit/controllers/authentication.spec.ts +++ b/tests/unit/controllers/authentication.spec.ts @@ -52,7 +52,6 @@ async function loadAuthenticationModule() { User, AuthEventService, findRefreshSessionByToken: sessionService.findRefreshSessionByToken, - classifyExpiredRefreshToken: sessionService.classifyExpiredRefreshToken, hardRevokeSession: sessionService.hardRevokeSession, generateRefreshToken: tokenLib.generateRefreshToken, createRefreshTokenLookup: tokenLib.createRefreshTokenLookup, @@ -91,7 +90,7 @@ describe('refreshSession', () => { await refreshSession(req, res); - expect(findRefreshSessionByToken).toHaveBeenCalledWith('raw-refresh-token', expect.any(Date)); + expect(findRefreshSessionByToken).toHaveBeenCalledWith('raw-refresh-token'); expect(AuthEventService.refreshTokenFailed).toHaveBeenCalledWith( req, expect.objectContaining({ @@ -141,7 +140,7 @@ describe('refreshSession', () => { await refreshSession(req, res); - expect(findRefreshSessionByToken).toHaveBeenCalledWith('raw-refresh-token', expect.any(Date)); + expect(findRefreshSessionByToken).toHaveBeenCalledWith('raw-refresh-token'); expect(Session.create).toHaveBeenCalledWith( expect.objectContaining({ userId: user.id, @@ -307,19 +306,19 @@ describe('refreshSession', () => { }); it('records an expired chain distinctly from an unknown token', async () => { - const { - refreshSession, - AuthEventService, - findRefreshSessionByToken, - classifyExpiredRefreshToken, - } = await loadAuthenticationModule(); + const { refreshSession, AuthEventService, findRefreshSessionByToken, Session } = + await loadAuthenticationModule(); const { req, res } = mockReqRes('Bearer raw-refresh-token'); const chainStartedAt = new Date(Date.now() - 25 * hour); - (findRefreshSessionByToken as any).mockResolvedValue(null); - (classifyExpiredRefreshToken as any).mockResolvedValue({ - reason: 'absolute_lifetime_reached', - session: { id: 'session-1', userId: 'user-1', chainStartedAt }, + (findRefreshSessionByToken as any).mockResolvedValue({ + id: 'session-1', + userId: 'user-1', + replacedBySessionId: null, + revokedAt: null, + chainStartedAt, + expiresAt: new Date(Date.now() - hour), + idleExpiresAt: new Date(Date.now() + hour), }); await refreshSession(req, res); @@ -337,6 +336,37 @@ describe('refreshSession', () => { }, }), ); + expect(Session.create).not.toHaveBeenCalled(); + expect(res.json).toHaveBeenCalledWith({ error: 'invalid_refresh_token' }); + }); + + it('records an idled-out session by its idle refusal', async () => { + const { refreshSession, AuthEventService, findRefreshSessionByToken } = + await loadAuthenticationModule(); + const { req, res } = mockReqRes('Bearer raw-refresh-token'); + const createdAt = new Date(Date.now() - 9 * hour); + + (findRefreshSessionByToken as any).mockResolvedValue({ + id: 'session-1', + userId: 'user-1', + replacedBySessionId: null, + revokedAt: null, + chainStartedAt: null, + createdAt, + expiresAt: new Date(Date.now() + hour), + idleExpiresAt: new Date(Date.now() - hour), + }); + + await refreshSession(req, res); + + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + metadata: expect.objectContaining({ + refusal: 'idle_timeout', + chainStartedAt: createdAt.toISOString(), + }), + }), + ); expect(res.json).toHaveBeenCalledWith({ error: 'invalid_refresh_token' }); }); }); diff --git a/tests/unit/lib/refreshReplayToken.spec.ts b/tests/unit/lib/refreshReplayToken.spec.ts new file mode 100644 index 00000000..23c91af6 --- /dev/null +++ b/tests/unit/lib/refreshReplayToken.spec.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest'; + +import { classifyRefreshRefusal } from '../../../src/lib/refreshRefusal.js'; +import { + openReplayToken, + refreshReplayWindowMs, + sealReplayToken, +} from '../../../src/lib/refreshReplayToken.js'; + +const binding = { + predecessorToken: 'predecessor-refresh-token', + predecessorId: 'session-1', + successorId: 'session-2', +}; + +describe('refreshReplayWindowMs', () => { + it('defaults to five seconds', () => { + expect(refreshReplayWindowMs({})).toBe(5_000); + expect(refreshReplayWindowMs({ REFRESH_REPLAY_WINDOW_SECONDS: ' ' })).toBe(5_000); + }); + + it('reads the configured window and caps it at a minute', () => { + expect(refreshReplayWindowMs({ REFRESH_REPLAY_WINDOW_SECONDS: '12' })).toBe(12_000); + expect(refreshReplayWindowMs({ REFRESH_REPLAY_WINDOW_SECONDS: '3600' })).toBe(60_000); + }); + + it('is disabled by zero, a negative value or nonsense', () => { + expect(refreshReplayWindowMs({ REFRESH_REPLAY_WINDOW_SECONDS: '0' })).toBe(0); + expect(refreshReplayWindowMs({ REFRESH_REPLAY_WINDOW_SECONDS: '-3' })).toBe(0); + expect(refreshReplayWindowMs({ REFRESH_REPLAY_WINDOW_SECONDS: 'soon' })).toBe(0); + }); +}); + +describe('sealReplayToken', () => { + it('opens to the successor token for the holder of the predecessor token', () => { + const sealed = sealReplayToken(binding, 'successor-refresh-token'); + + expect(sealed).not.toContain('successor-refresh-token'); + expect(openReplayToken(binding, sealed)).toBe('successor-refresh-token'); + }); + + it('does not open without the predecessor token', () => { + const sealed = sealReplayToken(binding, 'successor-refresh-token'); + + expect(openReplayToken({ ...binding, predecessorToken: 'guess' }, sealed)).toBeNull(); + }); + + it('does not open when moved to another session pair', () => { + const sealed = sealReplayToken(binding, 'successor-refresh-token'); + + expect(openReplayToken({ ...binding, successorId: 'session-3' }, sealed)).toBeNull(); + expect(openReplayToken({ ...binding, predecessorId: 'session-0' }, sealed)).toBeNull(); + }); + + it('refuses a tampered, truncated or unknown format', () => { + const sealed = sealReplayToken(binding, 'successor-refresh-token'); + const [format, iv, ciphertext, tag] = sealed.split('.'); + + expect(openReplayToken(binding, [format, iv, ciphertext, tag.slice(0, 8)].join('.'))).toBe( + null, + ); + expect(openReplayToken(binding, ['v2', iv, ciphertext, tag].join('.'))).toBeNull(); + expect(openReplayToken(binding, `${format}.${iv}`)).toBeNull(); + }); +}); + +describe('classifyRefreshRefusal', () => { + const now = new Date('2026-01-01T12:00:00Z'); + const past = new Date('2026-01-01T11:00:00Z'); + const future = new Date('2026-01-01T13:00:00Z'); + + it('names why a session cannot be refreshed', () => { + expect( + classifyRefreshRefusal({ revokedAt: past, expiresAt: future, idleExpiresAt: future }, now), + ).toBe('revoked'); + expect( + classifyRefreshRefusal({ revokedAt: null, expiresAt: past, idleExpiresAt: past }, now), + ).toBe('absolute_lifetime_reached'); + expect( + classifyRefreshRefusal({ revokedAt: null, expiresAt: future, idleExpiresAt: past }, now), + ).toBe('idle_timeout'); + }); + + it('says nothing about a live session', () => { + expect( + classifyRefreshRefusal({ revokedAt: null, expiresAt: future, idleExpiresAt: future }, now), + ).toBeNull(); + }); +}); diff --git a/tests/unit/services/sessionService.spec.ts b/tests/unit/services/sessionService.spec.ts index e456346e..110cbfda 100644 --- a/tests/unit/services/sessionService.spec.ts +++ b/tests/unit/services/sessionService.spec.ts @@ -25,6 +25,12 @@ vi.mock('../../../src/utils/signingKeyStore', () => ({ getPublicKeyByKid: vi.fn(), })); +vi.mock('../../../src/lib/refreshReplayToken', () => ({ + MAX_REFRESH_REPLAYS: 3, + openReplayToken: vi.fn(), + refreshReplayWindowMs: vi.fn(() => 5_000), +})); + vi.mock('../../../src/lib/token', () => ({ createRefreshTokenLookup: vi.fn(), })); @@ -363,67 +369,168 @@ describe('sessionService', () => { expect(result).toBeNull(); }); - describe('classifyExpiredRefreshToken', () => { - const now = new Date('2026-01-01T12:00:00Z'); - const past = new Date('2026-01-01T11:00:00Z'); - const future = new Date('2026-01-01T13:00:00Z'); + // Rotated, revoked and expired rows all come back, so a rotated token is still known + // as reuse after its own idle window (#593). + it('looks a refresh token up by its fingerprint alone, whatever state its row is in', async () => { + const { Session } = await import('../../../src/models/sessions'); + const { createRefreshTokenLookup } = await import('../../../src/lib/token'); + + const session = buildSession({ + refreshTokenLookup: 'lookup', + replacedBySessionId: 'session-2', + idleExpiresAt: new Date(Date.now() - 1000), + }); + (createRefreshTokenLookup as any).mockReturnValue('lookup'); + (Session.findOne as any).mockResolvedValue(session); + + const { findRefreshSessionByToken } = await import('../../../src/services/sessionService'); - async function classify(session: unknown) { + expect(await findRefreshSessionByToken('refresh-token')).toBe(session); + expect(Session.findOne).toHaveBeenCalledWith({ where: { refreshTokenLookup: 'lookup' } }); + }); + + describe('replayRefreshRotation', () => { + const now = new Date(); + const successorRow = () => + buildSession({ + id: 'session-2', + userId: 'user-1', + refreshTokenLookup: 'successor-lookup', + replacedBySessionId: null, + expiresAt: new Date(now.getTime() + 3_600_000), + idleExpiresAt: new Date(now.getTime() + 3_600_000), + }); + const rotatedRow = (overrides: Record = {}) => + buildSession({ + id: 'session-1', + userId: 'user-1', + replacedBySessionId: 'session-2', + rotatedAt: new Date(now.getTime() - 2_000), + replayTokenCiphertext: 'sealed', + ...overrides, + }); + + async function setUp({ + successor = successorRow() as unknown, + opened = 'successor-token' as string | null, + claimed = 1, + windowMs = 5_000, + } = {}) { const { Session } = await import('../../../src/models/sessions'); + const { User } = await import('../../../src/models/users'); const { createRefreshTokenLookup } = await import('../../../src/lib/token'); - (createRefreshTokenLookup as any).mockReturnValue('lookup'); - (Session.findOne as any).mockResolvedValue(session); - const { classifyExpiredRefreshToken } = await import('../../../src/services/sessionService'); - return classifyExpiredRefreshToken('refresh-token', now); + const replayToken = await import('../../../src/lib/refreshReplayToken'); + + (replayToken.refreshReplayWindowMs as any).mockReturnValue(windowMs); + (replayToken.openReplayToken as any).mockReturnValue(opened); + (createRefreshTokenLookup as any).mockReturnValue('successor-lookup'); + (Session.findByPk as any).mockResolvedValue(successor); + (Session.update as any).mockResolvedValue([claimed]); + (User.findOne as any).mockResolvedValue({ id: 'user-1', sessionsRevokedBefore: null }); + + const { replayRefreshRotation } = await import('../../../src/services/sessionService'); + return { Session, User, replayToken, replayRefreshRotation }; } - it('reports a session past its absolute bound', async () => { - const session = buildSession({ - refreshTokenLookup: 'lookup', - expiresAt: past, - idleExpiresAt: past, - }); + it('answers the immediate predecessor with its existing successor', async () => { + const { Session, replayToken, replayRefreshRotation } = await setUp(); + const session = rotatedRow(); + + const replay = await replayRefreshRotation(session as any, 'predecessor-token', now); + + expect(replay?.successor.id).toBe('session-2'); + expect(replay?.refreshToken).toBe('successor-token'); + expect(replayToken.openReplayToken).toHaveBeenCalledWith( + { + predecessorToken: 'predecessor-token', + predecessorId: 'session-1', + successorId: 'session-2', + }, + 'sealed', + ); + const [values, { where }] = (Session.update as any).mock.calls[0]; + expect(Object.keys(values)).toEqual(['replayCount']); + expect(where).toEqual( + expect.objectContaining({ + id: 'session-1', + revokedAt: null, + replacedBySessionId: 'session-2', + }), + ); + }); - expect(await classify(session)).toEqual({ reason: 'absolute_lifetime_reached', session }); + it('refuses once the window has passed, and discards the sealed token', async () => { + const { Session, replayRefreshRotation } = await setUp(); + const session = rotatedRow({ rotatedAt: new Date(now.getTime() - 6_000) }); + + expect(await replayRefreshRotation(session as any, 'predecessor-token', now)).toBeNull(); + expect(Session.update).toHaveBeenCalledWith( + { replayTokenCiphertext: null }, + { where: { id: 'session-1' } }, + ); + expect(Session.findByPk).not.toHaveBeenCalled(); }); - it('reports a session past only its idle bound', async () => { - const session = buildSession({ - refreshTokenLookup: 'lookup', - expiresAt: future, - idleExpiresAt: past, - }); + it('refuses everything while the window is disabled', async () => { + const { replayRefreshRotation } = await setUp({ windowMs: 0 }); - expect(await classify(session)).toEqual({ reason: 'idle_timeout', session }); + expect(await replayRefreshRotation(rotatedRow() as any, 'predecessor-token', now)).toBeNull(); }); - it('says nothing about a session that has not expired', async () => { - const session = buildSession({ - refreshTokenLookup: 'lookup', - expiresAt: future, - idleExpiresAt: future, + it('refuses a row that is revoked, unrotated or carries nothing to replay', async () => { + const { Session, replayRefreshRotation } = await setUp(); + + for (const overrides of [ + { revokedAt: now }, + { replacedBySessionId: null }, + { rotatedAt: null }, + { replayTokenCiphertext: null }, + ]) { + expect( + await replayRefreshRotation(rotatedRow(overrides) as any, 'predecessor-token', now), + ).toBeNull(); + } + expect(Session.update).not.toHaveBeenCalled(); + }); + + // An older ancestor's successor has itself rotated, so it is never answered. + it('refuses when the successor is no longer the live head', async () => { + const { Session, replayRefreshRotation } = await setUp({ + successor: buildSession({ ...successorRow(), replacedBySessionId: 'session-3' }), }); - expect(await classify(session)).toBeNull(); + expect(await replayRefreshRotation(rotatedRow() as any, 'predecessor-token', now)).toBeNull(); + expect(Session.update).not.toHaveBeenCalled(); }); - it('only considers live, unrotated sessions', async () => { - const { Session } = await import('../../../src/models/sessions'); - await classify(null); + it('refuses a sealed token that does not open, or opens to another token', async () => { + let ctx = await setUp({ opened: null }); + expect( + await ctx.replayRefreshRotation(rotatedRow() as any, 'predecessor-token', now), + ).toBeNull(); - expect(Session.findOne).toHaveBeenCalledWith({ - where: { revokedAt: null, replacedBySessionId: null, refreshTokenLookup: 'lookup' }, - }); + ctx = await setUp(); + const { createRefreshTokenLookup } = await import('../../../src/lib/token'); + (createRefreshTokenLookup as any).mockReturnValue('other-lookup'); + expect( + await ctx.replayRefreshRotation(rotatedRow() as any, 'predecessor-token', now), + ).toBeNull(); + expect(ctx.Session.update).not.toHaveBeenCalled(); }); - it('says nothing when the fingerprint does not verify', async () => { - const session = buildSession({ - refreshTokenLookup: 'other', - expiresAt: past, - idleExpiresAt: past, - }); + it('refuses when the successor owner is gone', async () => { + const { User, replayRefreshRotation } = await setUp(); + (User.findOne as any) + .mockResolvedValueOnce({ id: 'user-1', sessionsRevokedBefore: null }) + .mockResolvedValueOnce(null); - expect(await classify(session)).toBeNull(); + expect(await replayRefreshRotation(rotatedRow() as any, 'predecessor-token', now)).toBeNull(); + }); + + it('refuses once the replays are spent', async () => { + const { replayRefreshRotation } = await setUp({ claimed: 0 }); + + expect(await replayRefreshRotation(rotatedRow() as any, 'predecessor-token', now)).toBeNull(); }); }); @@ -472,6 +579,44 @@ describe('sessionService', () => { expect(Session.findByPk).not.toHaveBeenCalled(); }); + it('keeps the reason a row was already revoked for and clears its sealed replay token', async () => { + const earlier = new Date(Date.now() - 60_000); + const session = buildSession({ + replacedBySessionId: null, + revokedAt: earlier, + revokedReason: 'user_revoked', + replayTokenCiphertext: 'sealed', + }); + + const { revokeSessionChain } = await import('../../../src/services/sessionService'); + + await revokeSessionChain(session as any); + + expect(session.revokedAt).toBe(earlier); + expect(session.revokedReason).toBe('user_revoked'); + expect(session.replayTokenCiphertext).toBeNull(); + }); + + // A rotation can claim the head between the walk reading it and saving it as revoked. + it('follows a link a rotation wrote while the head was being revoked', async () => { + const { Session } = await import('../../../src/models/sessions'); + + const head = buildSession({ id: 'head', replacedBySessionId: null }); + head.reload.mockImplementation(async () => { + head.replacedBySessionId = 'late'; + }); + const late = buildSession({ id: 'late', replacedBySessionId: null }); + (Session.findByPk as any).mockResolvedValue(late); + + const { revokeSessionChain } = await import('../../../src/services/sessionService'); + + await revokeSessionChain(head as any, 'user_revoked'); + + expect(Session.findByPk).toHaveBeenCalledWith('late'); + expect(late.revokedReason).toBe('user_revoked'); + expect(late.save).toHaveBeenCalled(); + }); + it('rejects access tokens whose subject or session id are not strings', async () => { const jose = await import('jose'); const { getPublicKeyByKid } = await import('../../../src/utils/signingKeyStore');