diff --git a/.changeset/recovery-session-login-hooks.md b/.changeset/recovery-session-login-hooks.md new file mode 100644 index 00000000..1b37c05d --- /dev/null +++ b/.changeset/recovery-session-login-hooks.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': patch +--- + +A recovery session now runs the `post_login` and `pre_token` login hooks when its restriction lifts, after the user enrolls a passkey or authenticator app. The `pre_token` claims are kept on the session from then on. If a hook refuses, `POST /webauthn/register/finish` and `POST /totp/enroll/verify` answer 403 `login_denied` or 503 `login_hook_unavailable`, and the recovery session is revoked. The new factor is kept, so the user signs in with it, and that sign-in runs the hooks. Break-glass administrators still skip the hooks. diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md index 263403a1..99141bc2 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -74,7 +74,8 @@ The chain trigger updates the chain head row on every insert and holds that lock - `pre_token` runs when a token is minted for a new session and on organization switch. It may add claims or deny. It is not called on refresh: its claims are kept on the session, so refresh never waits on an adopter's server. - One hook per trigger. Timeout 2 seconds by default, 5 at most, one attempt. - Failure mode per hook, `closed` by default. A timeout, a non-2xx, a body that does not parse, or claims over the budget fail the sign-in when closed and are ignored when open. Every invocation is audited. -- Break-glass sign-in and recovery sessions never call a hook, so a hook that is down cannot lock out the administrator who would fix it. +- Break-glass sign-in never calls a hook, so a hook that is down cannot lock out the administrator who would fix it. +- A recovery session is issued without calling a hook, so a hook that is down cannot stop a user from getting a factor back. Both hooks run when its restriction lifts after the user enrolls a factor, since that is when it becomes a full session. A refusal there revokes the session and keeps the new factor, so the next sign-in with it runs the hooks again. - The call carries the user, method, organization, OpenID client, IP and user agent, never a token, code or secret. `reason` in the answer is audited and not shown; `userMessage` (200 characters) is. ### E6. Custom claims diff --git a/openapi.json b/openapi.json index 0f6aeb19..5ad540b0 100644 --- a/openapi.json +++ b/openapi.json @@ -35006,6 +35006,7 @@ "/totp/enroll/verify": { "post": { "summary": "Verify TOTP enrollment", + "description": "From a recovery session, enrolling lifts its restriction once the login hooks allow it. A hook can refuse: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`. Either way the recovery session is revoked and the new factor is kept, so the user signs in with it.", "tags": ["TOTP"], "security": [{ "bearerAuth": [] }], "requestBody": { @@ -35145,6 +35146,19 @@ } } } + }, + "503": { + "description": "HTTP 503", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } } } } @@ -36831,6 +36845,7 @@ "/webauthn/register/finish": { "post": { "summary": "Finish WebAuthn registration", + "description": "From a recovery session, enrolling lifts its restriction once the login hooks allow it. A hook can refuse: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`. Either way the recovery session is revoked and the new factor is kept, so the user signs in with it.", "tags": ["WebAuthn"], "security": [{ "bearerAuth": [] }], "requestBody": { @@ -37039,6 +37054,19 @@ } } } + }, + "503": { + "description": "HTTP 503", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } } } } diff --git a/src/controllers/authentication.ts b/src/controllers/authentication.ts index 478ffef3..af952892 100644 --- a/src/controllers/authentication.ts +++ b/src/controllers/authentication.ts @@ -768,7 +768,8 @@ export const refreshSession = async (req: Request, res: Response) => { // the sign-in. authMethods: session.authMethods ?? [], authTime: session.authTime ?? null, - // The pre_token hook is not called on refresh, so its claims ride the chain. + // The pre_token hook is not called on refresh, so its claims ride the chain. A recovery + // session gets them when its restriction lifts, which is also when the hooks first run. hookClaims: session.hookClaims ?? null, parentSessionId: session.parentSessionId ?? null, exchangeClientId: session.exchangeClientId ?? null, @@ -820,6 +821,15 @@ export const refreshSession = async (req: Request, res: Response) => { ); } + // A recovery lift that ran between reading this session and claiming its link updated + // the row being replaced, so the replacement takes the lifted state from it. + if (session.recovery === true) { + await session.reload(); + if (session.recovery !== true) { + await newSession.update({ recovery: false, hookClaims: session.hookClaims ?? null }); + } + } + // Read again because a revoke-all can land while this rotation is in flight. Its cutoff // covers the session the rotation started from, so the replacement is refused whether // or not the bulk update reached its row. diff --git a/src/controllers/totp.ts b/src/controllers/totp.ts index 71fb06c1..42f469bf 100644 --- a/src/controllers/totp.ts +++ b/src/controllers/totp.ts @@ -13,8 +13,10 @@ import { AuthEventService } from '../services/authEventService.js'; import { breakGlassWaivers, recordBreakGlassSignIn } from '../services/breakGlassService.js'; import { rejectIfUserLocked } from '../services/lockoutPolicyService.js'; import { isPasskeyRequiredForUser } from '../services/loginPolicyService.js'; -import { issueSessionAndRespond } from '../services/sessionIssuance.js'; -import { liftRecoveryRestriction } from '../services/sessionService.js'; +import { + issueSessionAndRespond, + liftRecoveryRestrictionAfterHooks, +} from '../services/sessionIssuance.js'; import { getStepUpSignInTime, recordStepUpVerification, @@ -134,7 +136,12 @@ export const verifyCurrentTotpEnrollment = async (req: Request, res: Response) = const authReq = req as AuthenticatedRequest; if (authReq.recoverySession) { - await liftRecoveryRestriction(authReq.sessionId); + const refusal = await liftRecoveryRestrictionAfterHooks({ + sessionId: authReq.sessionId, + user, + req, + }); + if (refusal) return res.status(refusal.status).json(refusal.body); } return res.json({ message: 'Success' }); diff --git a/src/controllers/webauthn.ts b/src/controllers/webauthn.ts index d3c473f8..96e9ca79 100644 --- a/src/controllers/webauthn.ts +++ b/src/controllers/webauthn.ts @@ -40,8 +40,10 @@ import { ensureMetadataServiceReady, hasMetadataStatement, } from '../services/metadataServiceBootstrap.js'; -import { issueSessionAndRespond } from '../services/sessionIssuance.js'; -import { liftRecoveryRestriction } from '../services/sessionService.js'; +import { + issueSessionAndRespond, + liftRecoveryRestrictionAfterHooks, +} from '../services/sessionIssuance.js'; import { consumeChallenge, issueChallenge } from '../services/webauthnChallengeService.js'; import { AuthenticatedRequest } from '../types/types.js'; import getLogger from '../utils/logger.js'; @@ -414,7 +416,12 @@ const verifyWebAuthnRegistration = async (req: Request, res: Response) => { } if (authReq.recoverySession) { - await liftRecoveryRestriction(authReq.sessionId); + const refusal = await liftRecoveryRestrictionAfterHooks({ + sessionId: authReq.sessionId, + user, + req, + }); + if (refusal) return res.status(refusal.status).json(refusal.body); } // Enrollment is not a sign-in. The caller reached here with an access session, so diff --git a/src/generated/api.ts b/src/generated/api.ts index da93732b..df22aca0 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -33472,7 +33472,10 @@ export interface paths { }; get?: never; put?: never; - /** Verify TOTP enrollment */ + /** + * Verify TOTP enrollment + * @description From a recovery session, enrolling lifts its restriction once the login hooks allow it. A hook can refuse: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`. Either way the recovery session is revoked and the new factor is kept, so the user signs in with it. + */ post: { parameters: { query?: never; @@ -33617,6 +33620,24 @@ export interface paths { }; }; }; + /** @description HTTP 503 */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; }; }; delete?: never; @@ -35265,7 +35286,10 @@ export interface paths { }; get?: never; put?: never; - /** Finish WebAuthn registration */ + /** + * Finish WebAuthn registration + * @description From a recovery session, enrolling lifts its restriction once the login hooks allow it. A hook can refuse: 403 `login_denied` with the hook's `message`, or 503 `login_hook_unavailable`. Either way the recovery session is revoked and the new factor is kept, so the user signs in with it. + */ post: { parameters: { query?: never; @@ -35458,6 +35482,24 @@ export interface paths { }; }; }; + /** @description HTTP 503 */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; }; }; delete?: never; diff --git a/src/routes/totp.routes.ts b/src/routes/totp.routes.ts index d8e02eb2..bbe6b24b 100644 --- a/src/routes/totp.routes.ts +++ b/src/routes/totp.routes.ts @@ -80,6 +80,11 @@ totpRouter.post( auth: 'access', allowRecoverySession: true, summary: 'Verify TOTP enrollment', + description: + 'From a recovery session, enrolling lifts its restriction once the login hooks allow it. A ' + + "hook can refuse: 403 `login_denied` with the hook's `message`, or 503 " + + '`login_hook_unavailable`. Either way the recovery session is revoked and the new factor is ' + + 'kept, so the user signs in with it.', tags: ['TOTP'], schemas: { @@ -88,6 +93,8 @@ totpRouter.post( response: { 200: TotpVerifySuccessSchema, 401: ErrorSchema, + 403: ErrorSchema, + 503: ErrorSchema, }, }, }, diff --git a/src/routes/webauthn.routes.ts b/src/routes/webauthn.routes.ts index 9a689245..904ae99e 100644 --- a/src/routes/webauthn.routes.ts +++ b/src/routes/webauthn.routes.ts @@ -68,6 +68,11 @@ webauthnRouter.post( auth: 'access', allowRecoverySession: true, summary: 'Finish WebAuthn registration', + description: + 'From a recovery session, enrolling lifts its restriction once the login hooks allow it. A ' + + "hook can refuse: 403 `login_denied` with the hook's `message`, or 503 " + + '`login_hook_unavailable`. Either way the recovery session is revoked and the new factor is ' + + 'kept, so the user signs in with it.', tags: ['WebAuthn'], schemas: { @@ -78,6 +83,7 @@ webauthnRouter.post( 401: ErrorSchema, 403: ErrorSchema, 500: ErrorSchema, + 503: ErrorSchema, }, }, }, diff --git a/src/services/sessionIssuance.ts b/src/services/sessionIssuance.ts index 54ecf70a..4fe18c2e 100644 --- a/src/services/sessionIssuance.ts +++ b/src/services/sessionIssuance.ts @@ -14,9 +14,17 @@ import { computeSessionTimes, parseDurationToSeconds } from '../utils/utils.js'; import { mintAccessToken } from './accessTokenService.js'; import { AuthEventService } from './authEventService.js'; import { enforceConcurrentSessionLimit } from './concurrentSessionPolicy.js'; -import { loginHookRefusal, runLoginHook, verdictClaims } from './loginHookService.js'; +import { + type HookClaims, + type LoginHookContext, + type LoginHookRefusal, + loginHookRefusal, + runLoginHook, + verdictClaims, +} from './loginHookService.js'; import { isPasskeyRequiredForUser } from './loginPolicyService.js'; import { getDefaultOrganizationIdForUser } from './organizationService.js'; +import { revokeSessionChain } from './sessionService.js'; /** The factor that proved the user, as far as session issuance needs to know it. */ export type SessionMethod = @@ -95,6 +103,19 @@ type IssueSessionParams = { extraFields?: Record; }; +async function runSignInHooks( + context: LoginHookContext, +): Promise<{ claims: HookClaims | null } | { refusal: LoginHookRefusal }> { + const postLoginRefusal = loginHookRefusal(await runLoginHook('post_login', context)); + if (postLoginRefusal) return { refusal: postLoginRefusal }; + + const preToken = await runLoginHook('pre_token', context); + const preTokenRefusal = loginHookRefusal(preToken); + if (preTokenRefusal) return { refusal: preTokenRefusal }; + + return { claims: verdictClaims(preToken) }; +} + /** * Answers the request either way. Resolves false when a login hook refused the sign-in, so the * caller stops before anything it does only for a completed sign-in. @@ -116,7 +137,7 @@ export async function issueSessionAndRespond(params: IssueSessionParams): Promis // gates. It covers both rules, phishing-resistant-only mode and an account that holds a // passkey while fallback is off, because OAuth once shipped without the second. A // break-glass admin is held to its own rule instead: a strong factor, whatever the - // policy says. A recovery session is exempt: enrolling a passkey is all it can do. + // policy says. A recovery session is exempt: enrolling a factor is all it can do. const breakGlass = isBreakGlassAdmin(user); if (breakGlass && !accountVerification && !BREAK_GLASS_FACTORS.has(method)) { @@ -136,26 +157,17 @@ export async function issueSessionAndRespond(params: IssueSessionParams): Promis const organizationId = await getDefaultOrganizationIdForUser(user.id); let hookClaims: Record | null = null; - // A hook that is down must not lock out the administrator who would fix it, and a recovery - // session can only enroll a factor. Both run before the concurrent session limit, so a + // A hook that is down must not lock out the administrator who would fix it. A recovery + // session runs the hooks when its restriction lifts instead (see + // `liftRecoveryRestrictionAfterHooks`). Both run before the concurrent session limit, so a // refused sign-in cannot cost the user a session they already had. if (!breakGlass && !recovery) { - const context = { user, method, organizationId, req }; - - const postLogin = await runLoginHook('post_login', context); - const postLoginRefusal = loginHookRefusal(postLogin); - if (postLoginRefusal) { - res.status(postLoginRefusal.status).json(postLoginRefusal.body); - return false; - } - - const preToken = await runLoginHook('pre_token', context); - const preTokenRefusal = loginHookRefusal(preToken); - if (preTokenRefusal) { - res.status(preTokenRefusal.status).json(preTokenRefusal.body); + const outcome = await runSignInHooks({ user, method, organizationId, req }); + if ('refusal' in outcome) { + res.status(outcome.refusal.status).json(outcome.refusal.body); return false; } - hookClaims = verdictClaims(preToken); + hookClaims = outcome.claims; } const refreshToken = generateRefreshToken(); @@ -235,3 +247,76 @@ export async function issueSessionAndRespond(params: IssueSessionParams): Promis return true; } + +export const RECOVERY_HOOK_REFUSED = 'recovery_login_hook_refused'; + +/** + * Ends a recovery session's restriction once the user has enrolled a factor of their own. + * The session was issued without the login hooks, so they run here, the first point at which + * it can do more than enroll. A refusal revokes the session rather than leaving it restricted: + * the factor just enrolled is kept, and signing in with it runs the hooks again. + * + * Resolves the refusal for the caller to answer with, or null when the session is now + * unrestricted (or was not a recovery session to begin with). + */ +export async function liftRecoveryRestrictionAfterHooks(params: { + sessionId: string | undefined; + user: { id: string; email: string; phone: string | null; roles?: string[] }; + req: Request; +}): Promise { + const { sessionId, req } = params; + const { id, email, phone, roles } = params.user; + const user = { id, email, phone, roles: roles ?? [] }; + if (!sessionId) return null; + + const session = await Session.findOne({ + where: { id: sessionId, userId: user.id, recovery: true, revokedAt: null }, + }); + if (!session) return null; + + let hookClaims: HookClaims | null = null; + + if (!isBreakGlassAdmin(user)) { + const outcome = await runSignInHooks({ + user, + method: session.authMethods?.[0]?.method ?? 'account_recovery', + organizationId: session.organizationId ?? null, + req, + }); + + if ('refusal' in outcome) { + // The hooks can take seconds, and a refresh in that time moves the session on, so + // the whole chain is ended rather than the row read before they ran. + await revokeSessionChain(session, RECOVERY_HOOK_REFUSED); + return outcome.refusal; + } + hookClaims = outcome.claims; + } + + await liftAtChainHead(session, hookClaims); + + return null; +} + +const MAX_LIFT_HOPS = 8; + +/** + * Lifts the restriction on whichever row is the chain's head now. A rotation that claims + * the head after this update copies the lifted state itself (see `refreshSession`). + */ +async function liftAtChainHead(session: Session, hookClaims: HookClaims | null) { + let current: Session | null = session; + + for (let hops = 0; current && hops < MAX_LIFT_HOPS; hops += 1) { + const [lifted] = await Session.update( + { recovery: false, hookClaims }, + { where: { id: current.id, recovery: true, revokedAt: null, replacedBySessionId: null } }, + ); + if (lifted > 0) return; + + await current.reload(); + if (current.revokedAt || !current.replacedBySessionId) return; + + current = await Session.findByPk(current.replacedBySessionId); + } +} diff --git a/src/services/sessionService.ts b/src/services/sessionService.ts index 9bd54277..a19e1d5f 100644 --- a/src/services/sessionService.ts +++ b/src/services/sessionService.ts @@ -467,19 +467,3 @@ export async function validateBearerToken( } : null; } - -/** - * Ends a recovery session's restriction once the user has enrolled a factor of their - * own. The API reads the flag from the row, so this applies to the very next request; - * the access token keeps its `recovery` claim until the client refreshes. - */ -export async function liftRecoveryRestriction(sessionId: string | undefined) { - if (!sessionId) return false; - - const [updated] = await Session.update( - { recovery: false }, - { where: { id: sessionId, recovery: true } }, - ); - - return updated > 0; -} diff --git a/tests/integration/recovery/recoveryLoginHooks.spec.ts b/tests/integration/recovery/recoveryLoginHooks.spec.ts new file mode 100644 index 00000000..d00713f4 --- /dev/null +++ b/tests/integration/recovery/recoveryLoginHooks.spec.ts @@ -0,0 +1,155 @@ +import { isoCBOR } from '@simplewebauthn/server/helpers'; +import { Application } from 'express'; +import request from 'supertest'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +let currentUser: any; + +vi.mock('../../../src/middleware/attachAuthMiddleware.js', async (importOriginal) => { + const actual = + await importOriginal(); + + return { + ...actual, + attachAuthMiddleware: () => (req: any, _res: any, next: any) => { + req.user = currentUser; + req.sessionId = 'session-1'; + req.recoverySession = true; + next(); + }, + }; +}); + +vi.mock('../../../src/services/metadataServiceBootstrap.js', () => ({ + hasMetadataStatement: vi.fn(async () => false), + ensureMetadataServiceReady: vi.fn(async () => true), +})); + +vi.mock('../../../src/services/loginHookService.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, runLoginHook: vi.fn(async () => ({ outcome: 'skipped' })) }; +}); + +import { createApp } from '../../../src/app.js'; +import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; +import { Credential } from '../../../src/models/credentials.js'; +import { Session } from '../../../src/models/sessions.js'; +import { User } from '../../../src/models/users.js'; +import { WebAuthnChallenge } from '../../../src/models/webauthnChallenges.js'; +import { runLoginHook } from '../../../src/services/loginHookService.js'; +import { revokeSessionChain } from '../../../src/services/sessionService.js'; +import { buildSystemConfig } from '../../factories/systemConfigFactory.js'; +import { buildUser } from '../../factories/userFactory.js'; +import { buildWebAuthnChallenge } from '../../factories/webauthnChallengeFactory.js'; + +let app: Application; + +const NONE_ATTESTATION = isoCBOR.encode( + new Map([ + ['fmt', 'none'], + ['attStmt', new Map()], + ['authData', new Uint8Array([1, 2, 3])], + ]) as never, +); + +const recoverySession = { + id: 'session-1', + organizationId: null, + authMethods: [{ method: 'recovery_code', at: new Date().toISOString() }], +}; + +function register() { + return request(app) + .post('/webauthn/register/finish') + .send({ attestationResponse: {}, metadata: {} }); +} + +beforeAll(async () => { + app = await createApp(); +}); + +beforeEach(async () => { + vi.clearAllMocks(); + currentUser = buildUser(); + + const { verifyRegistrationResponse } = await import('@simplewebauthn/server'); + (verifyRegistrationResponse as any).mockResolvedValue({ + verified: true, + registrationInfo: { + fmt: 'none', + aaguid: '00000000-0000-0000-0000-000000000000', + attestationObject: NONE_ATTESTATION, + credential: { id: 'cred-1', publicKey: Buffer.from('key'), counter: 0, transports: [] }, + credentialBackedUp: true, + credentialDeviceType: 'multiDevice', + }, + }); + + (getSystemConfig as any).mockResolvedValue( + buildSystemConfig({ + authenticator_policy: { + attachment: 'any', + userVerification: 'required', + attestation: 'none', + requireKnownAuthenticator: false, + syncedPasskeys: 'allow', + aaguidAllowList: [], + aaguidDenyList: [], + }, + }), + ); + (User.findOne as any).mockResolvedValue(currentUser); + (Credential.create as any).mockResolvedValue({ createdAt: new Date() }); + (WebAuthnChallenge.findOne as any).mockResolvedValue( + buildWebAuthnChallenge({ purpose: 'registration' }), + ); + (Session.findOne as any).mockResolvedValue(recoverySession); + (Session.update as any).mockResolvedValue([1]); +}); + +describe('passkey enrollment from a recovery session', () => { + it('runs the login hooks before lifting the restriction', async () => { + vi.mocked(runLoginHook).mockImplementation(async (trigger) => + trigger === 'pre_token' + ? { outcome: 'allowed', claims: { tier: 'gold' } } + : { outcome: 'allowed', claims: null }, + ); + + const res = await register(); + + expect(res.status).toBe(200); + expect(vi.mocked(runLoginHook).mock.calls.map(([trigger]) => trigger)).toEqual([ + 'post_login', + 'pre_token', + ]); + expect(Session.update).toHaveBeenCalledWith( + { recovery: false, hookClaims: { tier: 'gold' } }, + { where: { id: 'session-1', recovery: true, revokedAt: null, replacedBySessionId: null } }, + ); + }); + + it('keeps the passkey but ends the session when post_login denies', async () => { + vi.mocked(runLoginHook).mockResolvedValue({ + outcome: 'denied', + userMessage: 'Your account is on hold.', + }); + + const res = await register(); + + expect(res.status).toBe(403); + expect(res.body).toEqual({ error: 'login_denied', message: 'Your account is on hold.' }); + expect(Credential.create).toHaveBeenCalled(); + expect(revokeSessionChain).toHaveBeenCalledWith(recoverySession, expect.any(String)); + expect(Session.update).not.toHaveBeenCalled(); + }); + + it('fails closed when a hook cannot be reached', async () => { + vi.mocked(runLoginHook).mockResolvedValue({ outcome: 'failed_closed' }); + + const res = await register(); + + expect(res.status).toBe(503); + expect(res.body).toEqual({ error: 'login_hook_unavailable' }); + expect(Session.update).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/setup/mocks.ts b/tests/setup/mocks.ts index 98209716..e409ec46 100644 --- a/tests/setup/mocks.ts +++ b/tests/setup/mocks.ts @@ -312,7 +312,6 @@ vi.mock('../../src/services/sessionService.js', () => ({ revokeSessionChain: vi.fn(), hardRevokeSession: vi.fn(), revokeOrphanedChildSessions: vi.fn(), - liftRecoveryRestriction: vi.fn(async () => true), })); vi.mock('../../src/middleware/attachAuthMiddleware.js', async (importOriginal) => { diff --git a/tests/unit/controllers/authentication.spec.ts b/tests/unit/controllers/authentication.spec.ts index a6986f4f..fe051622 100644 --- a/tests/unit/controllers/authentication.spec.ts +++ b/tests/unit/controllers/authentication.spec.ts @@ -241,6 +241,56 @@ describe('refreshSession', () => { expect(res.status).toHaveBeenCalledWith(200); }); + it('takes a recovery lift that landed during the rotation onto the new session', async () => { + const { + refreshSession, + getSystemConfig, + Session, + User, + findRefreshSessionByToken, + generateRefreshToken, + createRefreshTokenLookup, + signAccessToken, + } = await loadAuthenticationModule(); + const { req, res } = mockReqRes('Bearer raw-refresh-token'); + const user = buildUser({ id: 'user-1', roles: ['user'] }); + const session: Record = { + id: 'session-1', + replacedBySessionId: null, + revokedAt: null, + userId: user.id, + recovery: true, + hookClaims: null, + save: vi.fn(), + }; + session.reload = vi.fn(async () => { + session.recovery = false; + session.hookClaims = { plan: 'pro' }; + }); + const newSession: Record = { id: 'session-2', recovery: true }; + newSession.update = vi.fn(async (values: Record) => + Object.assign(newSession, values), + ); + + (findRefreshSessionByToken as any).mockResolvedValue(session); + (User.findOne as any).mockResolvedValue(user); + (generateRefreshToken as any).mockReturnValue('new-raw-refresh-token'); + (createRefreshTokenLookup as any).mockReturnValue('new-refresh-lookup'); + (Session.create as any).mockResolvedValue(newSession); + (signAccessToken as any).mockResolvedValue('new-access-token'); + (getSystemConfig as any).mockResolvedValue({ access_token_ttl: '15m' }); + + await refreshSession(req, res); + + expect(Session.create).toHaveBeenCalledWith(expect.objectContaining({ recovery: true })); + expect(newSession.update).toHaveBeenCalledWith({ + recovery: false, + hookClaims: { plan: 'pro' }, + }); + expect(newSession.recovery).toBe(false); + expect(res.status).toHaveBeenCalledWith(200); + }); + describe('absolute session lifetime', () => { const hour = 60 * 60 * 1000; diff --git a/tests/unit/controllers/totp.spec.ts b/tests/unit/controllers/totp.spec.ts index c8296e94..ac5ef755 100644 --- a/tests/unit/controllers/totp.spec.ts +++ b/tests/unit/controllers/totp.spec.ts @@ -8,6 +8,9 @@ const verifyEnabledTotpMock = vi.fn(); const authEventLogMock = vi.fn(); const rejectIfUserLockedMock = vi.fn(); const issueSessionAndRespondMock = vi.fn(async () => true); +const liftRecoveryRestrictionAfterHooksMock = vi.fn< + (params: unknown) => Promise<{ status: number; body: { error: string } } | null> +>(async () => null); const recordStepUpVerificationMock = vi.fn(); const getStepUpSignInTimeMock = vi.fn(); const signedInAt = new Date('2026-11-01T00:00:00Z'); @@ -40,6 +43,7 @@ vi.mock('../../../src/services/lockoutPolicyService.js', () => ({ vi.mock('../../../src/services/sessionIssuance.js', () => ({ issueSessionAndRespond: issueSessionAndRespondMock, + liftRecoveryRestrictionAfterHooks: liftRecoveryRestrictionAfterHooksMock, })); vi.mock('../../../src/services/stepUpService.js', () => ({ @@ -264,9 +268,34 @@ describe('totp controller', () => { describe('enrolling from a recovery session', () => { it('lifts the restriction once the new factor is confirmed', async () => { - const { liftRecoveryRestriction } = await import('../../../src/services/sessionService.js'); const { verifyCurrentTotpEnrollment } = await loadTotpController(); verifyTotpEnrollmentMock.mockResolvedValue({ verified: true }); + const res = buildRes(); + const user = buildUser(); + const req = buildReq(user, { + body: { code: '123456' }, + recoverySession: true, + sessionId: 'session-1', + }); + + await verifyCurrentTotpEnrollment(req, res); + + expect(liftRecoveryRestrictionAfterHooksMock).toHaveBeenCalledWith({ + sessionId: 'session-1', + user, + req, + }); + expect(res.json).toHaveBeenCalledWith({ message: 'Success' }); + }); + + it('answers with the hook refusal when a login hook stops the lift', async () => { + const { verifyCurrentTotpEnrollment } = await loadTotpController(); + verifyTotpEnrollmentMock.mockResolvedValue({ verified: true }); + liftRecoveryRestrictionAfterHooksMock.mockResolvedValueOnce({ + status: 403, + body: { error: 'login_denied' }, + }); + const res = buildRes(); await verifyCurrentTotpEnrollment( buildReq(buildUser(), { @@ -274,14 +303,14 @@ describe('totp controller', () => { recoverySession: true, sessionId: 'session-1', }), - buildRes(), + res, ); - expect(liftRecoveryRestriction).toHaveBeenCalledWith('session-1'); + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ error: 'login_denied' }); }); it('leaves an ordinary session alone', async () => { - const { liftRecoveryRestriction } = await import('../../../src/services/sessionService.js'); const { verifyCurrentTotpEnrollment } = await loadTotpController(); verifyTotpEnrollmentMock.mockResolvedValue({ verified: true }); @@ -290,7 +319,7 @@ describe('totp controller', () => { buildRes(), ); - expect(liftRecoveryRestriction).not.toHaveBeenCalled(); + expect(liftRecoveryRestrictionAfterHooksMock).not.toHaveBeenCalled(); }); }); diff --git a/tests/unit/services/sessionIssueService.spec.ts b/tests/unit/services/sessionIssueService.spec.ts index 21acb6ec..ff5334b3 100644 --- a/tests/unit/services/sessionIssueService.spec.ts +++ b/tests/unit/services/sessionIssueService.spec.ts @@ -3,7 +3,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { BreakGlassFactorError, issueSessionAndRespond, + liftRecoveryRestrictionAfterHooks, PasskeyRequiredError, + RECOVERY_HOOK_REFUSED, } from '../../../src/services/sessionIssuance.js'; vi.mock('../../../src/lib/token.js', () => ({ @@ -15,6 +17,9 @@ vi.mock('../../../src/lib/token.js', () => ({ vi.mock('../../../src/models/sessions.js', () => ({ Session: { create: vi.fn(), + findOne: vi.fn(), + findByPk: vi.fn(), + update: vi.fn(), }, })); @@ -52,6 +57,7 @@ import { import { Session } from '../../../src/models/sessions.js'; import { enforceConcurrentSessionLimit } from '../../../src/services/concurrentSessionPolicy.js'; import { runLoginHook } from '../../../src/services/loginHookService.js'; +import { revokeSessionChain } from '../../../src/services/sessionService.js'; import { getDefaultOrganizationIdForUser } from '../../../src/services/organizationService.js'; import { computeSessionTimes, parseDurationToSeconds } from '../../../src/utils/utils.js'; @@ -707,3 +713,196 @@ describe('login hooks', () => { expect(runLoginHook).not.toHaveBeenCalled(); }); }); + +describe('liftRecoveryRestrictionAfterHooks', () => { + const recoverySession = (overrides: Record = {}) => ({ + id: 'session-1', + organizationId: 'org-1', + authMethods: [{ method: 'recovery_code', at: new Date().toISOString() }], + ...overrides, + }); + + beforeEach(() => { + (Session.update as any).mockResolvedValue([1]); + }); + + function hooksAnswer( + postLogin: Awaited>, + preToken: Awaited> = { outcome: 'skipped' }, + ) { + vi.mocked(runLoginHook).mockImplementation(async (trigger) => + trigger === 'post_login' ? postLogin : preToken, + ); + } + + it('runs both hooks and keeps the pre_token claims when it lifts the restriction', async () => { + const session = recoverySession(); + (Session.findOne as any).mockResolvedValue(session); + hooksAnswer( + { outcome: 'allowed', claims: null }, + { outcome: 'allowed', claims: { tier: 'gold' } }, + ); + const req = mockReq(); + + expect( + await liftRecoveryRestrictionAfterHooks({ sessionId: 'session-1', user: mockUser, req }), + ).toBeNull(); + + expect(Session.findOne).toHaveBeenCalledWith({ + where: { id: 'session-1', userId: 'user-1', recovery: true, revokedAt: null }, + }); + expect(vi.mocked(runLoginHook).mock.calls.map(([trigger]) => trigger)).toEqual([ + 'post_login', + 'pre_token', + ]); + expect(runLoginHook).toHaveBeenCalledWith('post_login', { + user: mockUser, + method: 'recovery_code', + organizationId: 'org-1', + req, + }); + expect(Session.update).toHaveBeenCalledWith( + { recovery: false, hookClaims: { tier: 'gold' } }, + { where: { id: 'session-1', recovery: true, revokedAt: null, replacedBySessionId: null } }, + ); + expect(revokeSessionChain).not.toHaveBeenCalled(); + }); + + it('names account recovery as the method when the session recorded no factor', async () => { + (Session.findOne as any).mockResolvedValue( + recoverySession({ authMethods: [], organizationId: null }), + ); + + await liftRecoveryRestrictionAfterHooks({ + sessionId: 'session-1', + user: mockUser, + req: mockReq(), + }); + + expect(runLoginHook).toHaveBeenCalledWith( + 'post_login', + expect.objectContaining({ method: 'account_recovery', organizationId: null }), + ); + }); + + it('revokes the session and keeps it restricted when post_login denies', async () => { + const session = recoverySession(); + (Session.findOne as any).mockResolvedValue(session); + hooksAnswer({ outcome: 'denied', userMessage: 'Your account is on hold.' }); + + expect( + await liftRecoveryRestrictionAfterHooks({ + sessionId: 'session-1', + user: mockUser, + req: mockReq(), + }), + ).toEqual({ + status: 403, + body: { error: 'login_denied', message: 'Your account is on hold.' }, + }); + expect(runLoginHook).toHaveBeenCalledTimes(1); + expect(revokeSessionChain).toHaveBeenCalledWith(session, RECOVERY_HOOK_REFUSED); + expect(Session.update).not.toHaveBeenCalled(); + }); + + it('fails closed with 503 when pre_token cannot be reached', async () => { + const session = recoverySession(); + (Session.findOne as any).mockResolvedValue(session); + hooksAnswer({ outcome: 'allowed', claims: null }, { outcome: 'failed_closed' }); + + expect( + await liftRecoveryRestrictionAfterHooks({ + sessionId: 'session-1', + user: mockUser, + req: mockReq(), + }), + ).toEqual({ status: 503, body: { error: 'login_hook_unavailable' } }); + expect(revokeSessionChain).toHaveBeenCalledWith(session, RECOVERY_HOOK_REFUSED); + expect(Session.update).not.toHaveBeenCalled(); + }); + + it('lifts a break-glass administrator without calling a hook', async () => { + vi.stubEnv('BREAK_GLASS_EMAILS', 'root@example.com'); + (Session.findOne as any).mockResolvedValue(recoverySession()); + hooksAnswer({ outcome: 'failed_closed' }, { outcome: 'failed_closed' }); + + expect( + await liftRecoveryRestrictionAfterHooks({ + sessionId: 'session-1', + user: { ...mockUser, email: 'root@example.com', roles: ['admin:write'] }, + req: mockReq(), + }), + ).toBeNull(); + vi.unstubAllEnvs(); + expect(runLoginHook).not.toHaveBeenCalled(); + expect(Session.update).toHaveBeenCalledWith( + { recovery: false, hookClaims: null }, + { where: { id: 'session-1', recovery: true, revokedAt: null, replacedBySessionId: null } }, + ); + }); + + it('lifts the row a refresh rotated to while the hooks ran', async () => { + const session = recoverySession({ + reload: vi.fn(async function (this: Record) { + this.replacedBySessionId = 'session-2'; + }), + }); + (Session.findOne as any).mockResolvedValue(session); + (Session.findByPk as any).mockResolvedValue(recoverySession({ id: 'session-2' })); + (Session.update as any).mockResolvedValueOnce([0]).mockResolvedValueOnce([1]); + hooksAnswer({ outcome: 'allowed', claims: null }); + + await liftRecoveryRestrictionAfterHooks({ + sessionId: 'session-1', + user: mockUser, + req: mockReq(), + }); + + expect(Session.findByPk).toHaveBeenCalledWith('session-2'); + expect(Session.update).toHaveBeenLastCalledWith( + { recovery: false, hookClaims: null }, + { where: { id: 'session-2', recovery: true, revokedAt: null, replacedBySessionId: null } }, + ); + }); + + it('stops at a session revoked while the hooks ran', async () => { + const session = recoverySession({ + reload: vi.fn(async function (this: Record) { + this.revokedAt = new Date(); + }), + }); + (Session.findOne as any).mockResolvedValue(session); + (Session.update as any).mockResolvedValue([0]); + hooksAnswer({ outcome: 'allowed', claims: null }); + + await liftRecoveryRestrictionAfterHooks({ + sessionId: 'session-1', + user: mockUser, + req: mockReq(), + }); + + expect(Session.update).toHaveBeenCalledTimes(1); + expect(Session.findByPk).not.toHaveBeenCalled(); + }); + + it('does nothing without a live recovery session', async () => { + (Session.findOne as any).mockResolvedValue(null); + + expect( + await liftRecoveryRestrictionAfterHooks({ + sessionId: 'session-1', + user: mockUser, + req: mockReq(), + }), + ).toBeNull(); + expect( + await liftRecoveryRestrictionAfterHooks({ + sessionId: undefined, + user: mockUser, + req: mockReq(), + }), + ).toBeNull(); + expect(runLoginHook).not.toHaveBeenCalled(); + expect(Session.update).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/services/sessionService.spec.ts b/tests/unit/services/sessionService.spec.ts index 110cbfda..5742992d 100644 --- a/tests/unit/services/sessionService.spec.ts +++ b/tests/unit/services/sessionService.spec.ts @@ -973,26 +973,6 @@ describe('sessionService', () => { }); }); -describe('liftRecoveryRestriction', () => { - it('clears the flag on a recovery session only', async () => { - const { Session } = await import('../../../src/models/sessions'); - const { liftRecoveryRestriction } = await import('../../../src/services/sessionService'); - (Session.update as any).mockResolvedValueOnce([1]); - - expect(await liftRecoveryRestriction('session-1')).toBe(true); - expect(Session.update).toHaveBeenCalledWith( - { recovery: false }, - { where: { id: 'session-1', recovery: true } }, - ); - }); - - it('does nothing without a session', async () => { - const { liftRecoveryRestriction } = await import('../../../src/services/sessionService'); - - expect(await liftRecoveryRestriction(undefined)).toBe(false); - }); -}); - describe('exchanged sessions', () => { const future = new Date(Date.now() + 60_000); const childRow = {