From e1f7c9a12e9f09cbe75176b79abb962ef9ac8135 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Tue, 17 Nov 2026 17:37:08 -0500 Subject: [PATCH 1/3] fix(step-up): require proof to add a factor and count only earlier factors Step-up now accepts only a passkey or TOTP enrolled before the session signed in, walking exchanged sessions to the earliest in their lineage. Adding a passkey, TOTP, phone or recovery code set needs a fresh step-up when the account already has a factor, or a sign-in from the last ten minutes when it has none. Recovery sessions are exempt. DELETE /users/credentials needs a fresh step-up (L-API-1, #600). --- .changeset/step-up-factor-age.md | 11 ++ docs/security-posture.md | 18 ++- openapi.json | 1 + src/controllers/stepUp.ts | 31 +++- src/controllers/totp.ts | 17 ++- src/generated/api.ts | 5 +- .../requireFactorEnrollmentProof.ts | 91 +++++++++++ src/models/credentials.ts | 1 + src/routes/recoveryCodes.routes.ts | 4 +- src/routes/registration.routes.ts | 6 +- src/routes/totp.routes.ts | 5 +- src/routes/users.routes.ts | 5 +- src/routes/webauthn.routes.ts | 6 +- src/services/stepUpService.ts | 58 ++++++- src/services/totpService.ts | 17 ++- tests/factories/credentialFactory.ts | 2 +- tests/factories/sessionFactory.ts | 9 ++ tests/factories/totpCredentialFactory.ts | 2 +- .../integration/breakGlass/breakGlass.spec.ts | 2 + .../recovery/recoveryCodes.spec.ts | 4 +- .../integration/registration/register.spec.ts | 3 + .../stepUp/factorEnrollment.spec.ts | 121 +++++++++++++++ tests/integration/totp/totp.spec.ts | 3 +- tests/integration/user/user.spec.ts | 2 +- .../webauthn/attestationPolicy.spec.ts | 2 + .../webauthn/enrollmentAuth.spec.ts | 3 + tests/integration/webauthn/webauthn.spec.ts | 2 + tests/unit/controllers/stepUp.spec.ts | 82 +++++++++- tests/unit/controllers/totp.spec.ts | 40 +++++ .../requireFactorEnrollmentProof.spec.ts | 142 ++++++++++++++++++ tests/unit/services/stepUpService.spec.ts | 131 ++++++++++++++++ tests/unit/services/totpService.spec.ts | 47 ++++++ 32 files changed, 844 insertions(+), 29 deletions(-) create mode 100644 .changeset/step-up-factor-age.md create mode 100644 src/middleware/requireFactorEnrollmentProof.ts create mode 100644 tests/integration/stepUp/factorEnrollment.spec.ts create mode 100644 tests/unit/middleware/requireFactorEnrollmentProof.spec.ts diff --git a/.changeset/step-up-factor-age.md b/.changeset/step-up-factor-age.md new file mode 100644 index 00000000..d377fa92 --- /dev/null +++ b/.changeset/step-up-factor-age.md @@ -0,0 +1,11 @@ +--- +'seamless-auth-api': minor +--- + +Step-up and factor enrollment are stricter. + +- A step-up only accepts a passkey or TOTP enrolled before the session signed in. One added during the session works from the next sign-in. `/totp/verify-mfa` answers `401 step_up_unavailable` for a TOTP that is too new, and `/step-up/webauthn/start` leaves out passkeys that are too new. +- Passkey and TOTP enrollment, phone registration and recovery code generation need a fresh step-up (`403 step_up_required`) when the account already has a passkey or TOTP. An account with neither needs a sign-in from the last ten minutes, and otherwise gets `403 reauthentication_required`. Recovery sessions are exempt. +- `DELETE /users/credentials` needs a fresh step-up. + +Clients that add a passkey or TOTP from an existing session should run a step-up when they get `step_up_required`, and ask the user to sign in again when they get `reauthentication_required`. diff --git a/docs/security-posture.md b/docs/security-posture.md index 13eb877a..a769b478 100644 --- a/docs/security-posture.md +++ b/docs/security-posture.md @@ -839,13 +839,27 @@ step-up has to happen on that same session within five minutes. The full route l `403 step_up_required` body are in [Admin Operations](./admin-operations.md#step-up-on-admin-writes). +A step-up only counts when it is made with a factor the account had before the session signed +in. A passkey or TOTP added since, by whoever holds the session, cannot vouch for that session; +it is accepted after the next sign-in. For a session from a token exchange, "signed in" means +the earliest session in its lineage, and a lineage that cannot be read counts no factor at all. + +Adding a factor needs proof as well. Passkey and TOTP enrollment, phone registration and +recovery code generation answer `403 step_up_required` until an account that already has a +passkey or TOTP has stepped up, and `403 reauthentication_required` to an account with neither +whose sign-in is more than ten minutes old. A recovery session is exempt, since enrolling is +what it is for. Deleting a passkey (`DELETE /users/credentials`) also needs a fresh step-up. + ### What is still accepted - **A fresh step-up is a window, not a per-request proof.** For five minutes after a step-up, the session's access token makes guarded writes on its own. Shortening the window is a `requireStepUp({ maxAgeSeconds })` change per route. -- **Self-service account deletion is not guarded.** `DELETE /users/delete` deletes the caller's - own account and is open to accounts with no passkey or TOTP, which could never step up. +- **A factor added in a session is trusted from the next sign-in.** Enrolling it needs the + proof above, not a second factor's approval after the fact, and the owner is not yet sent a + notice when one is added. +- **An account with no factor can add its first one with a recent sign-in alone.** It has + nothing else to prove with. - **Enrollment invites are not guarded.** They email existing users a sign-in link and change no account. diff --git a/openapi.json b/openapi.json index 74512d23..0bad2cd9 100644 --- a/openapi.json +++ b/openapi.json @@ -36232,6 +36232,7 @@ }, "delete": { "summary": "Delete credential", + "description": "Needs a fresh step-up.", "tags": ["Users"], "security": [{ "bearerAuth": [] }], "requestBody": { diff --git a/src/controllers/stepUp.ts b/src/controllers/stepUp.ts index a81b6e41..d58de048 100644 --- a/src/controllers/stepUp.ts +++ b/src/controllers/stepUp.ts @@ -18,7 +18,9 @@ import { buildPrfAuthenticationExtensions, containsPrfOutput } from '../lib/weba import { Credential } from '../models/credentials.js'; import { AuthEventService } from '../services/authEventService.js'; import { + factorPredatesSignIn, getSessionStepUpStatus, + getStepUpSignInTime, recordStepUpVerification, serializeStepUpStatus, } from '../services/stepUpService.js'; @@ -30,13 +32,17 @@ const logger = getLogger('step-up'); function filterAssertionCredentials( credentials: Credential[], - options: { credentialId?: string; requiresPrf: boolean }, + options: { credentialId?: string; requiresPrf: boolean; signedInAt: Date | null }, ) { return credentials.filter((credential) => { if (options.credentialId && credential.id !== options.credentialId) { return false; } + if (!factorPredatesSignIn(credential.createdAt, options.signedInAt)) { + return false; + } + if (options.requiresPrf && !credential.prfCapable) { return false; } @@ -70,22 +76,29 @@ export const startWebAuthnStepUp = async (req: Request, res: Response) => { const user = authReq.user; const { credentialId, prf } = req.body ?? {}; - if (!user?.id) { + if (!user?.id || !authReq.sessionId) { await AuthEventService.log({ userId: null, type: 'step_up_suspicious', req, - metadata: { reason: 'No authenticated user' }, + metadata: { reason: 'No authenticated user or session' }, }); return res.status(401).json({ error: 'unauthorized' }); } try { + const { sessionFound, signedInAt } = await getStepUpSignInTime(authReq.sessionId, user.id); + + if (!sessionFound) { + return res.status(401).json({ error: 'unauthorized' }); + } + const credentials = await Credential.findAll({ where: { userId: user.id } }); const assertionCredentials = filterAssertionCredentials(credentials ?? [], { credentialId, requiresPrf: Boolean(prf), + signedInAt, }); if (!assertionCredentials || assertionCredentials.length === 0) { @@ -198,6 +211,18 @@ export const finishWebAuthnStepUp = async (req: Request, res: Response) => { return res.status(401).json({ error: 'step_up_failed' }); } + const { signedInAt } = await getStepUpSignInTime(authReq.sessionId, user.id); + + if (!factorPredatesSignIn(credential.createdAt, signedInAt)) { + await AuthEventService.log({ + userId: user.id, + type: 'step_up_failed', + req, + metadata: { reason: 'Credential enrolled after sign-in' }, + }); + return res.status(401).json({ error: 'step_up_failed' }); + } + const expectedChallenge = issued.challenge; try { diff --git a/src/controllers/totp.ts b/src/controllers/totp.ts index 7d65419c..71fb06c1 100644 --- a/src/controllers/totp.ts +++ b/src/controllers/totp.ts @@ -15,7 +15,11 @@ 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 { recordStepUpVerification, serializeStepUpStatus } from '../services/stepUpService.js'; +import { + getStepUpSignInTime, + recordStepUpVerification, + serializeStepUpStatus, +} from '../services/stepUpService.js'; import { disableTotp, getTotpStatus, @@ -252,7 +256,13 @@ export const verifyTotpMfa = async (req: Request, res: Response) => { return; } - const result = await verifyEnabledTotp(user.id, code); + const { sessionFound, signedInAt } = await getStepUpSignInTime(authReq.sessionId, user.id); + + if (!sessionFound) { + return res.status(401).json({ error: 'unauthorized' }); + } + + const result = await verifyEnabledTotp(user.id, code, { enrolledBefore: signedInAt }); if (!result.verified) { await AuthEventService.log({ @@ -261,6 +271,9 @@ export const verifyTotpMfa = async (req: Request, res: Response) => { req, metadata: { reason: result.reason, method: 'totp' }, }); + if (result.reason === 'enrolled_after_sign_in') { + return res.status(401).json({ error: 'step_up_unavailable' }); + } return res.status(401).json({ error: 'totp_verification_failed' }); } diff --git a/src/generated/api.ts b/src/generated/api.ts index 89a12013..2e015c70 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -34676,7 +34676,10 @@ export interface paths { }; }; }; - /** Delete credential */ + /** + * Delete credential + * @description Needs a fresh step-up. + */ delete: { parameters: { query?: never; diff --git a/src/middleware/requireFactorEnrollmentProof.ts b/src/middleware/requireFactorEnrollmentProof.ts new file mode 100644 index 00000000..568f2814 --- /dev/null +++ b/src/middleware/requireFactorEnrollmentProof.ts @@ -0,0 +1,91 @@ +/* + * 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 { NextFunction, Request, Response } from 'express'; + +import { Credential } from '../models/credentials.js'; +import { TotpCredential } from '../models/totpCredentials.js'; +import { + findCurrentSession, + FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS, + getStepUpStatusFromSession, + serializeStepUpStatus, +} from '../services/stepUpService.js'; +import { AuthenticatedRequest } from '../types/types.js'; +import { + DeviceStepUpAwareHandler, + refuseDeviceSessionWithoutStepUp, +} from './requireDeviceSessionStepUp.js'; + +async function hasStepUpFactor(userId: string) { + const [passkeys, totp] = await Promise.all([ + Credential.count({ where: { userId } }), + TotpCredential.count({ where: { userId, enabled: true } }), + ]); + + return passkeys > 0 || totp > 0; +} + +function signedInRecently(authTime: Date | null | undefined, now = Date.now()) { + if (!authTime) return false; + + return now - new Date(authTime).getTime() <= FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS * 1000; +} + +/** + * For a route that adds something the account can sign in or step up with. An access token + * alone is not enough: whoever holds a stolen one could add their own factor and keep the + * account. An account that has a factor proves it with a fresh step-up, which only a factor + * from before this sign-in can satisfy. An account with none has nothing to prove with, so + * the sign-in itself must be recent. A recovery session exists to enrol and is let through. + */ +export const requireFactorEnrollmentProof: DeviceStepUpAwareHandler = async ( + req: Request, + res: Response, + next: NextFunction, +) => { + if (refuseDeviceSessionWithoutStepUp(req, res)) return; + + const authReq = req as AuthenticatedRequest; + if (authReq.recoverySession) return next(); + + const userId = authReq.user?.id; + const session = + userId && authReq.sessionId ? await findCurrentSession(authReq.sessionId, userId) : null; + + if (!userId || !session) { + res.status(401).json({ error: 'unauthorized' }); + return; + } + + if (await hasStepUpFactor(userId)) { + const status = getStepUpStatusFromSession(session); + + if (!status.fresh) { + res.status(403).json({ + error: 'step_up_required', + message: 'Recent step-up authentication is required', + ...serializeStepUpStatus(status), + }); + return; + } + + return next(); + } + + if (!signedInRecently(session.authTime)) { + res.status(403).json({ + error: 'reauthentication_required', + message: 'Sign in again to add a sign-in method', + maxAgeSeconds: FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS, + }); + return; + } + + return next(); +}; + +requireFactorEnrollmentProof.seamlessDeviceStepUp = true; diff --git a/src/models/credentials.ts b/src/models/credentials.ts index 613622a1..8d0f6775 100644 --- a/src/models/credentials.ts +++ b/src/models/credentials.ts @@ -33,6 +33,7 @@ export class Credential extends Model { declare platform: string | null; declare browser: string | null; declare deviceInfo: string | null; + declare readonly createdAt: Date; declare readonly user?: User; diff --git a/src/routes/recoveryCodes.routes.ts b/src/routes/recoveryCodes.routes.ts index 4b018a9e..9ed1cbd0 100644 --- a/src/routes/recoveryCodes.routes.ts +++ b/src/routes/recoveryCodes.routes.ts @@ -12,7 +12,7 @@ import { } from '../controllers/recoveryCodes.js'; import { createRouter } from '../lib/createRouter.js'; import { otpIdentityLimiter, otpIpLimiter } from '../middleware/rateLimit.js'; -import { requireDeviceSessionStepUp } from '../middleware/requireDeviceSessionStepUp.js'; +import { requireFactorEnrollmentProof } from '../middleware/requireFactorEnrollmentProof.js'; import { ErrorSchema } from '../schemas/generic.responses.js'; import { RecoveryCodeRedeemRequestSchema, @@ -44,7 +44,7 @@ recoveryCodesRouter.get( recoveryCodesRouter.post( '/', { - middleware: [requireDeviceSessionStepUp], + middleware: [requireFactorEnrollmentProof], auth: 'access', allowRecoverySession: true, summary: 'Generate recovery codes', diff --git a/src/routes/registration.routes.ts b/src/routes/registration.routes.ts index 071092fa..9a081880 100644 --- a/src/routes/registration.routes.ts +++ b/src/routes/registration.routes.ts @@ -7,7 +7,7 @@ import { register, registerPhone, verifyRegisteredPhone } from '../controllers/registration.js'; import { createRouter } from '../lib/createRouter.js'; import { otpIdentityLimiter, otpIpLimiter } from '../middleware/rateLimit.js'; -import { requireDeviceSessionStepUp } from '../middleware/requireDeviceSessionStepUp.js'; +import { requireFactorEnrollmentProof } from '../middleware/requireFactorEnrollmentProof.js'; import { ErrorSchema } from '../schemas/generic.responses.js'; import { VerifyOTPRequestSchema } from '../schemas/otp.requests.js'; import { OTPVerifyTokenSuccessSchema } from '../schemas/otp.responses.js'; @@ -51,7 +51,7 @@ registrationRouter.post( auth: 'access', summary: 'Register a phone number for the authenticated user', tags: ['Registration'], - middleware: [requireDeviceSessionStepUp, otpIpLimiter, otpIdentityLimiter], + middleware: [requireFactorEnrollmentProof, otpIpLimiter, otpIdentityLimiter], schemas: { body: RegisterPhoneRequestSchema, @@ -71,7 +71,7 @@ registrationRouter.post( registrationRouter.post( '/phone/verify', { - middleware: [requireDeviceSessionStepUp], + middleware: [requireFactorEnrollmentProof], auth: 'access', summary: 'Verify the authenticated user phone number', tags: ['Registration'], diff --git a/src/routes/totp.routes.ts b/src/routes/totp.routes.ts index 1848ffe5..d8e02eb2 100644 --- a/src/routes/totp.routes.ts +++ b/src/routes/totp.routes.ts @@ -16,6 +16,7 @@ import { import { createRouter } from '../lib/createRouter.js'; import { otpIdentityLimiter, otpIpLimiter } from '../middleware/rateLimit.js'; import { requireDeviceSessionStepUp } from '../middleware/requireDeviceSessionStepUp.js'; +import { requireFactorEnrollmentProof } from '../middleware/requireFactorEnrollmentProof.js'; import { ErrorSchema, InternalErrorSchema, @@ -54,7 +55,7 @@ totpRouter.get( totpRouter.post( '/enroll/start', { - middleware: [requireDeviceSessionStepUp], + middleware: [requireFactorEnrollmentProof], auth: 'access', allowRecoverySession: true, summary: 'Start TOTP enrollment', @@ -75,7 +76,7 @@ totpRouter.post( totpRouter.post( '/enroll/verify', { - middleware: [requireDeviceSessionStepUp, otpIpLimiter, otpIdentityLimiter], + middleware: [requireFactorEnrollmentProof, otpIpLimiter, otpIdentityLimiter], auth: 'access', allowRecoverySession: true, summary: 'Verify TOTP enrollment', diff --git a/src/routes/users.routes.ts b/src/routes/users.routes.ts index 486bfa5f..0f910b3f 100644 --- a/src/routes/users.routes.ts +++ b/src/routes/users.routes.ts @@ -9,7 +9,6 @@ import { DeleteCredentialRequestSchema, UpdateCredentialRequestSchema } from '@s import { getEffectivePermissions } from '../controllers/permissions.js'; import { deleteCredential, deleteUser, getUser, updateCredential } from '../controllers/user.js'; import { createRouter } from '../lib/createRouter.js'; -import { requireDeviceSessionStepUp } from '../middleware/requireDeviceSessionStepUp.js'; import { requireStepUp } from '../middleware/requireStepUp.js'; import { CredentialUpdateResponseSchema } from '../schemas/credential.responses.js'; import { ErrorSchema, MessageSchema } from '../schemas/generic.responses.js'; @@ -96,15 +95,17 @@ usersRouter.delete( usersRouter.delete( '/credentials', { - middleware: [requireDeviceSessionStepUp], + middleware: [requireStepUp()], auth: 'access', tags: ['Users'], summary: 'Delete credential', + description: 'Needs a fresh step-up.', schemas: { body: DeleteCredentialRequestSchema, response: { 200: MessageSchema, + 403: StepUpRequiredErrorSchema, }, }, }, diff --git a/src/routes/webauthn.routes.ts b/src/routes/webauthn.routes.ts index df747c29..9a689245 100644 --- a/src/routes/webauthn.routes.ts +++ b/src/routes/webauthn.routes.ts @@ -15,7 +15,7 @@ import { verifyWebAuthnRegistration, } from '../controllers/webauthn.js'; import { createRouter } from '../lib/createRouter.js'; -import { requireDeviceSessionStepUp } from '../middleware/requireDeviceSessionStepUp.js'; +import { requireFactorEnrollmentProof } from '../middleware/requireFactorEnrollmentProof.js'; import { CredentialUpdateResponseSchema } from '../schemas/credential.responses.js'; import { ErrorSchema, InternalErrorSchema } from '../schemas/generic.responses.js'; import { @@ -40,7 +40,7 @@ const webauthnRouter = createRouter('/webauthn'); webauthnRouter.get( '/register/start', { - middleware: [requireDeviceSessionStepUp], + middleware: [requireFactorEnrollmentProof], auth: 'access', allowRecoverySession: true, summary: 'Start WebAuthn registration', @@ -64,7 +64,7 @@ webauthnRouter.get( webauthnRouter.post( '/register/finish', { - middleware: [requireDeviceSessionStepUp], + middleware: [requireFactorEnrollmentProof], auth: 'access', allowRecoverySession: true, summary: 'Finish WebAuthn registration', diff --git a/src/services/stepUpService.ts b/src/services/stepUpService.ts index 1bc245b5..4b9b0790 100644 --- a/src/services/stepUpService.ts +++ b/src/services/stepUpService.ts @@ -9,6 +9,11 @@ import { deriveAcrAmr } from './oidcAuthContext.js'; export const DEFAULT_STEP_UP_MAX_AGE_SECONDS = 5 * 60; +/** How recent a sign-in must be to add the first factor to an account that has none. */ +export const FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS = 10 * 60; + +const MAX_SESSION_LINEAGE = 8; + export type StepUpMethod = 'webauthn' | 'totp'; export interface StepUpStatus { @@ -62,7 +67,7 @@ export function getStepUpStatusFromSession( }; } -async function findCurrentSession(sessionId: string, userId: string) { +export async function findCurrentSession(sessionId: string, userId: string) { return Session.findOne({ where: { id: sessionId, @@ -72,6 +77,57 @@ async function findCurrentSession(sessionId: string, userId: string) { }); } +function chainStart(session: Pick) { + return session.chainStartedAt ?? session.createdAt ?? null; +} + +/** + * When the human behind this session last signed in: the earliest chain start across the + * session and the sessions it was exchanged from, since an exchanged child starts a chain + * of its own. Null when any link is missing, which callers treat as no factor counting. + */ +export async function findSessionSignInTime( + session: Pick, +): Promise { + let earliest = chainStart(session); + let parentId = session.parentSessionId ?? null; + + for (let hops = 0; parentId; hops += 1) { + if (!earliest || hops >= MAX_SESSION_LINEAGE) return null; + + const parent = await Session.findByPk(parentId); + if (!parent) return null; + + const parentStart = chainStart(parent); + if (!parentStart) return null; + + if (parentStart < earliest) earliest = parentStart; + parentId = parent.parentSessionId ?? null; + } + + return earliest; +} + +/** + * A factor proves the session's holder only if it was enrolled before that holder signed + * in. One enrolled since could have been added by whoever holds the session's token, so + * accepting it would let the token vouch for itself. + */ +export function factorPredatesSignIn( + enrolledAt: Date | null | undefined, + signedInAt: Date | null, +): boolean { + return Boolean(enrolledAt && signedInAt && new Date(enrolledAt) < signedInAt); +} + +/** The current session and when its holder signed in, for a step-up ceremony. */ +export async function getStepUpSignInTime(sessionId: string, userId: string) { + const session = await findCurrentSession(sessionId, userId); + if (!session) return { sessionFound: false, signedInAt: null }; + + return { sessionFound: true, signedInAt: await findSessionSignInTime(session) }; +} + export async function getSessionStepUpStatus({ sessionId, userId, diff --git a/src/services/totpService.ts b/src/services/totpService.ts index 55c22249..61583bee 100644 --- a/src/services/totpService.ts +++ b/src/services/totpService.ts @@ -18,6 +18,7 @@ import { randomBuffer, verifyTotpCode, } from '../utils/totp.js'; +import { factorPredatesSignIn } from './stepUpService.js'; const TOTP_CIPHER = 'aes-256-gcm'; @@ -194,13 +195,26 @@ export async function verifyTotpEnrollment(userId: string, code: string) { return { verified: true, credential }; } -export async function verifyEnabledTotp(userId: string, code: string) { +/** + * `enrolledBefore` limits the check to a credential enabled before that time, for step-up, + * where a TOTP the current session enrolled must not count. Null refuses every credential. + */ +export async function verifyEnabledTotp( + userId: string, + code: string, + { enrolledBefore }: { enrolledBefore?: Date | null } = {}, +) { const credential = await findEnabledCredential(userId); if (!credential) { return { verified: false, reason: 'missing_enabled_credential' }; } + const restricted = enrolledBefore !== undefined; + if (restricted && !factorPredatesSignIn(credential.verifiedAt, enrolledBefore)) { + return { verified: false, reason: 'enrolled_after_sign_in' }; + } + const verification = await verifyCredentialCode(credential, code); if (!verification.verified || verification.counter === null) { @@ -216,6 +230,7 @@ export async function verifyEnabledTotp(userId: string, code: string) { where: { id: credential.id, enabled: true, + ...(restricted ? { verifiedAt: { [Op.lt]: enrolledBefore } } : {}), [Op.or]: [ { lastUsedCounter: null }, { lastUsedCounter: { [Op.lt]: verification.counter } }, diff --git a/tests/factories/credentialFactory.ts b/tests/factories/credentialFactory.ts index 6d334ec0..5f9e364f 100644 --- a/tests/factories/credentialFactory.ts +++ b/tests/factories/credentialFactory.ts @@ -15,7 +15,7 @@ export function buildCredential(overrides: any = {}) { platform: 'web', browser: 'chrome', deviceInfo: 'test', - createdAt: new Date(), + createdAt: new Date(Date.now() - 24 * 60 * 60 * 1000), publicKey: 'key', update: vi.fn(), destroy: vi.fn(), diff --git a/tests/factories/sessionFactory.ts b/tests/factories/sessionFactory.ts index af2f66d1..d27bc2a9 100644 --- a/tests/factories/sessionFactory.ts +++ b/tests/factories/sessionFactory.ts @@ -1,8 +1,17 @@ import { vi } from 'vitest'; +const HOUR_MS = 60 * 60 * 1000; + +/** Signed in a moment ago on a chain that began an hour ago, after the factory factors. */ export function buildSession(overrides: any = {}) { + const chainStartedAt = new Date(Date.now() - HOUR_MS); + return { id: 'session-1', + createdAt: chainStartedAt, + chainStartedAt, + authTime: new Date(), + parentSessionId: null, deviceName: 'MacBook', ipAddress: '127.0.0.1', userAgent: 'agent', diff --git a/tests/factories/totpCredentialFactory.ts b/tests/factories/totpCredentialFactory.ts index f9fe6437..6f5e5325 100644 --- a/tests/factories/totpCredentialFactory.ts +++ b/tests/factories/totpCredentialFactory.ts @@ -10,7 +10,7 @@ export function buildTotpCredential(overrides: any = {}) { issuer: 'Seamless Auth', accountName: 'test@example.com', enabled: true, - verifiedAt: new Date(), + verifiedAt: new Date(Date.now() - 24 * 60 * 60 * 1000), lastUsedAt: null, lastUsedCounter: null, createdAt: new Date(), diff --git a/tests/integration/breakGlass/breakGlass.spec.ts b/tests/integration/breakGlass/breakGlass.spec.ts index 17b34761..8b83b063 100644 --- a/tests/integration/breakGlass/breakGlass.spec.ts +++ b/tests/integration/breakGlass/breakGlass.spec.ts @@ -50,6 +50,7 @@ import { buildSystemConfig } from '../../factories/systemConfigFactory.js'; import { buildTotpCredential } from '../../factories/totpCredentialFactory.js'; import { buildUser } from '../../factories/userFactory.js'; import { buildWebAuthnChallenge } from '../../factories/webauthnChallengeFactory.js'; +import { buildFreshStepUpSession } from '../../factories/sessionFactory.js'; let app: Application; @@ -138,6 +139,7 @@ beforeAll(async () => { beforeEach(() => { vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); vi.stubEnv('BREAK_GLASS_EMAILS', 'Root@Example.com, listed@example.com'); process.env.TOTP_SECRET_ENCRYPTION_KEY = 'test-totp-encryption-key'; process.env.REFRESH_TOKEN_LOOKUP_SECRET = 'lookup-secret'; diff --git a/tests/integration/recovery/recoveryCodes.spec.ts b/tests/integration/recovery/recoveryCodes.spec.ts index 41646b08..e0cd4ac6 100644 --- a/tests/integration/recovery/recoveryCodes.spec.ts +++ b/tests/integration/recovery/recoveryCodes.spec.ts @@ -17,6 +17,7 @@ import { Session } from '../../../src/models/sessions.js'; import { AuthEventService } from '../../../src/services/authEventService.js'; import { sendNoticeEmail, sendNoticeSms } from '../../../src/services/messagingService.js'; import { buildSystemConfig } from '../../factories/systemConfigFactory.js'; +import { buildFreshStepUpSession, buildSession } from '../../factories/sessionFactory.js'; let app: Application; @@ -26,6 +27,7 @@ beforeAll(async () => { beforeEach(() => { vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); process.env.REFRESH_TOKEN_LOOKUP_SECRET = 'lookup-secret'; (getSystemConfig as any).mockResolvedValue(buildSystemConfig()); }); @@ -65,7 +67,7 @@ describe('POST /recovery-codes', () => { it('needs a fresh step-up to replace an existing set', async () => { withExistingSet(); - (Session.findOne as any).mockResolvedValue({ id: 'session-1', stepUpVerifiedAt: null }); + (Session.findOne as any).mockResolvedValue(buildSession({ authTime: new Date() })); const res = await request(app).post('/recovery-codes'); diff --git a/tests/integration/registration/register.spec.ts b/tests/integration/registration/register.spec.ts index ad37a51b..a29182d3 100644 --- a/tests/integration/registration/register.spec.ts +++ b/tests/integration/registration/register.spec.ts @@ -47,6 +47,8 @@ import { registerPhone, verifyRegisteredPhone, } from '../../../src/controllers/registration.js'; +import { Session } from '../../../src/models/sessions.js'; +import { buildFreshStepUpSession } from '../../factories/sessionFactory.js'; let app: Application; @@ -73,6 +75,7 @@ beforeAll(async () => { beforeEach(() => { vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); (getSystemConfig as any).mockResolvedValue({ default_roles: ['user'], diff --git a/tests/integration/stepUp/factorEnrollment.spec.ts b/tests/integration/stepUp/factorEnrollment.spec.ts new file mode 100644 index 00000000..aa1446fb --- /dev/null +++ b/tests/integration/stepUp/factorEnrollment.spec.ts @@ -0,0 +1,121 @@ +import { Application } from 'express'; +import request from 'supertest'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +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 { TotpCredential } from '../../../src/models/totpCredentials.js'; +import { encryptTotpSecret } from '../../../src/services/totpService.js'; +import { generateTotpCode } from '../../../src/utils/totp.js'; +import { buildCredential } from '../../factories/credentialFactory.js'; +import { buildSession } from '../../factories/sessionFactory.js'; +import { buildSystemConfig } from '../../factories/systemConfigFactory.js'; +import { buildTotpCredential } from '../../factories/totpCredentialFactory.js'; + +let app: Application; + +beforeAll(async () => { + app = await createApp(); +}); + +beforeEach(() => { + vi.clearAllMocks(); + process.env.TOTP_SECRET_ENCRYPTION_KEY = 'test-totp-encryption-key'; + (getSystemConfig as any).mockResolvedValue(buildSystemConfig()); + (Credential.count as any).mockResolvedValue(0); + (TotpCredential.count as any).mockResolvedValue(0); +}); + +const enrollmentRoutes: Array<[string, (agent: request.Agent) => request.Test]> = [ + ['POST /totp/enroll/start', (agent) => agent.post('/totp/enroll/start')], + [ + 'POST /totp/enroll/verify', + (agent) => agent.post('/totp/enroll/verify').send({ code: '123456' }), + ], + ['GET /webauthn/register/start', (agent) => agent.get('/webauthn/register/start')], + ['POST /webauthn/register/finish', (agent) => agent.post('/webauthn/register/finish').send({})], + [ + 'POST /registration/phone', + (agent) => agent.post('/registration/phone').send({ phone: '+14155552671' }), + ], + [ + 'POST /registration/phone/verify', + (agent) => agent.post('/registration/phone/verify').send({ verificationToken: '123456' }), + ], + ['POST /recovery-codes', (agent) => agent.post('/recovery-codes')], +]; + +describe('adding a sign-in factor', () => { + it.each(enrollmentRoutes)( + '%s needs a fresh step-up on an account that has a factor', + async (_name, send) => { + (Credential.count as any).mockResolvedValue(1); + (Session.findOne as any).mockResolvedValue(buildSession({ stepUpVerifiedAt: null })); + + const res = await send(request.agent(app)); + + expect(res.status).toBe(403); + expect(res.body.error).toBe('step_up_required'); + }, + ); + + it.each(enrollmentRoutes)( + '%s needs a recent sign-in on an account with no factor', + async (_name, send) => { + (Session.findOne as any).mockResolvedValue( + buildSession({ authTime: new Date(Date.now() - 60 * 60 * 1000) }), + ); + + const res = await send(request.agent(app)); + + expect(res.status).toBe(403); + expect(res.body).toEqual( + expect.objectContaining({ error: 'reauthentication_required', maxAgeSeconds: 600 }), + ); + }, + ); +}); + +describe('a factor added in the current session', () => { + it('cannot satisfy a TOTP step-up', async () => { + const secret = 'JBSWY3DPEHPK3PXP'; + const session = buildSession({ stepUpVerifiedAt: null }); + (Session.findOne as any).mockResolvedValue(session); + (TotpCredential.findOne as any).mockResolvedValue( + buildTotpCredential({ ...encryptTotpSecret(secret), verifiedAt: new Date() }), + ); + + const res = await request(app) + .post('/totp/verify-mfa') + .send({ code: generateTotpCode({ secret }) }); + + expect(res.status).toBe(401); + expect(res.body).toEqual({ error: 'step_up_unavailable' }); + expect(TotpCredential.update).not.toHaveBeenCalled(); + expect(session.save).not.toHaveBeenCalled(); + }); + + it('cannot satisfy a passkey step-up', async () => { + (Session.findOne as any).mockResolvedValue(buildSession()); + (Credential.findAll as any).mockResolvedValue([buildCredential({ createdAt: new Date() })]); + + const res = await request(app).post('/step-up/webauthn/start').send({}); + + expect(res.status).toBe(401); + expect(res.body).toEqual({ error: 'step_up_unavailable' }); + }); +}); + +describe('DELETE /users/credentials', () => { + it('needs a fresh step-up', async () => { + (Session.findOne as any).mockResolvedValue(buildSession({ stepUpVerifiedAt: null })); + + const res = await request(app).delete('/users/credentials').send({ id: 'cred-1' }); + + expect(res.status).toBe(403); + expect(res.body.error).toBe('step_up_required'); + expect(Credential.findOne).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/integration/totp/totp.spec.ts b/tests/integration/totp/totp.spec.ts index d6b11472..1e2546f3 100644 --- a/tests/integration/totp/totp.spec.ts +++ b/tests/integration/totp/totp.spec.ts @@ -17,7 +17,7 @@ import { Session } from '../../../src/models/sessions.js'; import { TotpCredential } from '../../../src/models/totpCredentials.js'; import { encryptTotpSecret } from '../../../src/services/totpService.js'; import { generateTotpCode } from '../../../src/utils/totp.js'; -import { buildSession } from '../../factories/sessionFactory.js'; +import { buildSession, buildFreshStepUpSession } from '../../factories/sessionFactory.js'; import { buildTotpCredential } from '../../factories/totpCredentialFactory.js'; let app: Application; @@ -28,6 +28,7 @@ beforeAll(async () => { beforeEach(() => { vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); process.env.TOTP_SECRET_ENCRYPTION_KEY = 'test-totp-encryption-key'; }); diff --git a/tests/integration/user/user.spec.ts b/tests/integration/user/user.spec.ts index 19b16713..ecf5facd 100644 --- a/tests/integration/user/user.spec.ts +++ b/tests/integration/user/user.spec.ts @@ -236,7 +236,7 @@ describe('DELETE /users/credentials', () => { .send({ id: 'cred-1' }); expect(res.status).toBe(401); - expect(res.body.error).toBe('Unauthorized'); + expect(res.body.error).toBe('unauthorized'); }); }); diff --git a/tests/integration/webauthn/attestationPolicy.spec.ts b/tests/integration/webauthn/attestationPolicy.spec.ts index da553523..59ac3c01 100644 --- a/tests/integration/webauthn/attestationPolicy.spec.ts +++ b/tests/integration/webauthn/attestationPolicy.spec.ts @@ -15,6 +15,7 @@ import { AuthEventService } from '../../../src/services/authEventService'; import { hasMetadataStatement } from '../../../src/services/metadataServiceBootstrap'; import { buildUser } from '../../factories/userFactory'; import { buildWebAuthnChallenge } from '../../factories/webauthnChallengeFactory'; +import { buildFreshStepUpSession } from '../../factories/sessionFactory.js'; let app: Application; @@ -122,6 +123,7 @@ beforeAll(async () => { beforeEach(() => { vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); (WebAuthnChallenge.findOne as any).mockResolvedValue(buildWebAuthnChallenge()); (AuthEvent.count as any).mockResolvedValue(0); (User.findOne as any).mockResolvedValue(buildUser()); diff --git a/tests/integration/webauthn/enrollmentAuth.spec.ts b/tests/integration/webauthn/enrollmentAuth.spec.ts index 658ec012..1e17cc8d 100644 --- a/tests/integration/webauthn/enrollmentAuth.spec.ts +++ b/tests/integration/webauthn/enrollmentAuth.spec.ts @@ -4,6 +4,8 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; import { Credential } from '../../../src/models/credentials.js'; +import { Session } from '../../../src/models/sessions.js'; +import { buildFreshStepUpSession } from '../../factories/sessionFactory.js'; /** * The enrollment gate itself, driven through the real auth middleware. @@ -35,6 +37,7 @@ beforeEach(async () => { const { validateBearerToken } = await import('../../../src/services/sessionService.js'); vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); (validateBearerToken as any).mockResolvedValue(null); (Credential.findAll as any).mockResolvedValue([]); (getSystemConfig as any).mockResolvedValue({ diff --git a/tests/integration/webauthn/webauthn.spec.ts b/tests/integration/webauthn/webauthn.spec.ts index b6f2b146..afd044cd 100644 --- a/tests/integration/webauthn/webauthn.spec.ts +++ b/tests/integration/webauthn/webauthn.spec.ts @@ -25,6 +25,7 @@ import { verifyWebAuthn, verifyWebAuthnRegistration, } from '../../../src/controllers/webauthn'; +import { buildFreshStepUpSession } from '../../factories/sessionFactory.js'; let app: Application; @@ -89,6 +90,7 @@ beforeAll(async () => { beforeEach(() => { vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); (WebAuthnChallenge.findOne as any).mockResolvedValue(buildWebAuthnChallenge()); (AuthEvent.count as any).mockResolvedValue(0); (getSystemConfig as any).mockResolvedValue({ diff --git a/tests/unit/controllers/stepUp.spec.ts b/tests/unit/controllers/stepUp.spec.ts index 203a6cf0..243962eb 100644 --- a/tests/unit/controllers/stepUp.spec.ts +++ b/tests/unit/controllers/stepUp.spec.ts @@ -38,6 +38,7 @@ function buildRes() { beforeEach(() => { vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildSession()); challengeRecord.update = vi.fn(); (WebAuthnChallenge.findOne as any).mockResolvedValue(challengeRecord); }); @@ -206,6 +207,9 @@ describe('step-up controller', () => { authenticationInfo: { newCounter: 2, credentialDeviceType: 'singleDevice' }, }); + const session = buildSession(); + (Session.findOne as any).mockResolvedValue(session); + const req = buildReq({ user, body: { assertionResponse: { id: 'cred-1' } }, @@ -214,7 +218,7 @@ describe('step-up controller', () => { await finishWebAuthnStepUp(req, res); - expect(Session.findOne).not.toHaveBeenCalled(); + expect(session.save).not.toHaveBeenCalled(); expect(credential.update).not.toHaveBeenCalled(); expect(res.status).toHaveBeenCalledWith(401); expect(res.json).toHaveBeenCalledWith({ error: 'step_up_failed' }); @@ -400,7 +404,7 @@ describe('step-up controller', () => { const credential = buildCredential({ id: 'cred-1', userId: user.id }); (Credential.findOne as any).mockResolvedValue(credential); - (Session.findOne as any).mockResolvedValue(null); + (Session.findOne as any).mockResolvedValueOnce(buildSession()).mockResolvedValueOnce(null); (getSystemConfig as any).mockResolvedValue({ origins: ['http://localhost:5137'], rpid: 'localhost', @@ -447,4 +451,78 @@ describe('step-up controller', () => { expect(res.status).toHaveBeenCalledWith(401); expect(res.json).toHaveBeenCalledWith({ error: 'step_up_failed' }); }); + + describe('a passkey enrolled after the session signed in', () => { + it('is left out of the step-up challenge', async () => { + const user = buildUser(); + (Credential.findAll as any).mockResolvedValue([ + buildCredential({ id: 'new-cred', userId: user.id, createdAt: new Date() }), + ]); + + const res = buildRes(); + await startWebAuthnStepUp(buildReq({ user }), res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ error: 'step_up_unavailable' }); + expect(WebAuthnChallenge.create).not.toHaveBeenCalled(); + }); + + it('cannot finish a step-up', async () => { + const user = buildUser(); + const credential = buildCredential({ + id: 'new-cred', + userId: user.id, + createdAt: new Date(), + }); + (Credential.findOne as any).mockResolvedValue(credential); + const { verifyAuthenticationResponse } = await import('@simplewebauthn/server'); + + const res = buildRes(); + await finishWebAuthnStepUp( + buildReq({ user, body: { assertionResponse: { id: 'new-cred' } } }), + res, + ); + + expect(verifyAuthenticationResponse).not.toHaveBeenCalled(); + expect(credential.update).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ error: 'step_up_failed' }); + }); + + it('counts from the session it was exchanged from', async () => { + const user = buildUser(); + const parentStart = new Date(Date.now() - 3 * 60 * 60 * 1000); + (Session.findOne as any).mockResolvedValue(buildSession({ parentSessionId: 'parent-1' })); + (Session.findByPk as any).mockResolvedValueOnce( + buildSession({ id: 'parent-1', chainStartedAt: parentStart, parentSessionId: null }), + ); + (Credential.findAll as any).mockResolvedValue([ + buildCredential({ userId: user.id, createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000) }), + ]); + + const res = buildRes(); + await startWebAuthnStepUp(buildReq({ user }), res); + + expect(res.json).toHaveBeenCalledWith({ error: 'step_up_unavailable' }); + }); + }); + + it('refuses to start a step-up without a session', async () => { + const res = buildRes(); + await startWebAuthnStepUp(buildReq({ sessionId: undefined }), res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ error: 'unauthorized' }); + }); + + it('refuses to start a step-up when the session is gone', async () => { + (Session.findOne as any).mockResolvedValue(null); + + const res = buildRes(); + await startWebAuthnStepUp(buildReq(), res); + + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ error: 'unauthorized' }); + expect(Credential.findAll).not.toHaveBeenCalled(); + }); }); diff --git a/tests/unit/controllers/totp.spec.ts b/tests/unit/controllers/totp.spec.ts index f7dc96cc..c8296e94 100644 --- a/tests/unit/controllers/totp.spec.ts +++ b/tests/unit/controllers/totp.spec.ts @@ -9,6 +9,8 @@ const authEventLogMock = vi.fn(); const rejectIfUserLockedMock = vi.fn(); const issueSessionAndRespondMock = vi.fn(async () => true); const recordStepUpVerificationMock = vi.fn(); +const getStepUpSignInTimeMock = vi.fn(); +const signedInAt = new Date('2026-11-01T00:00:00Z'); const serializeStepUpStatusMock = vi.fn(); const getSystemConfigMock = vi.fn(); const loggerMock = { @@ -41,6 +43,7 @@ vi.mock('../../../src/services/sessionIssuance.js', () => ({ })); vi.mock('../../../src/services/stepUpService.js', () => ({ + getStepUpSignInTime: getStepUpSignInTimeMock, recordStepUpVerification: recordStepUpVerificationMock, serializeStepUpStatus: serializeStepUpStatusMock, })); @@ -96,6 +99,7 @@ async function loadTotpController() { beforeEach(() => { vi.clearAllMocks(); rejectIfUserLockedMock.mockResolvedValue(false); + getStepUpSignInTimeMock.mockResolvedValue({ sessionFound: true, signedInAt }); getSystemConfigMock.mockResolvedValue({ app_name: 'Seamless Auth' }); }); @@ -473,6 +477,42 @@ describe('totp controller', () => { expect(verifyEnabledTotpMock).not.toHaveBeenCalled(); }); + it('returns 401 when the current session is gone', async () => { + const { verifyTotpMfa } = await loadTotpController(); + const res = buildRes(); + getStepUpSignInTimeMock.mockResolvedValue({ sessionFound: false, signedInAt: null }); + + await verifyTotpMfa( + buildReq(buildUser(), { body: { code: '123456' }, sessionId: 'session-1' }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ error: 'unauthorized' }); + expect(verifyEnabledTotpMock).not.toHaveBeenCalled(); + }); + + it('refuses a TOTP enrolled after the session signed in', async () => { + const { verifyTotpMfa } = await loadTotpController(); + const res = buildRes(); + verifyEnabledTotpMock.mockResolvedValue({ + verified: false, + reason: 'enrolled_after_sign_in', + }); + + await verifyTotpMfa( + buildReq(buildUser(), { body: { code: '123456' }, sessionId: 'session-1' }), + res, + ); + + expect(verifyEnabledTotpMock).toHaveBeenCalledWith('user-1', '123456', { + enrolledBefore: signedInAt, + }); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ error: 'step_up_unavailable' }); + expect(recordStepUpVerificationMock).not.toHaveBeenCalled(); + }); + it('returns 401 and logs failure when the code is invalid', async () => { const { verifyTotpMfa } = await loadTotpController(); const res = buildRes(); diff --git a/tests/unit/middleware/requireFactorEnrollmentProof.spec.ts b/tests/unit/middleware/requireFactorEnrollmentProof.spec.ts new file mode 100644 index 00000000..a26e7cb8 --- /dev/null +++ b/tests/unit/middleware/requireFactorEnrollmentProof.spec.ts @@ -0,0 +1,142 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { requireFactorEnrollmentProof } from '../../../src/middleware/requireFactorEnrollmentProof'; +import { Credential } from '../../../src/models/credentials'; +import { Session } from '../../../src/models/sessions'; +import { TotpCredential } from '../../../src/models/totpCredentials'; +import { buildSession } from '../../factories/sessionFactory'; + +const MINUTE_MS = 60_000; + +function buildReq(overrides: Record = {}) { + return { user: { id: 'user-1' }, sessionId: 'session-1', ...overrides } as never; +} + +describe('requireFactorEnrollmentProof', () => { + let res: any; + let next: any; + + beforeEach(() => { + vi.clearAllMocks(); + res = { status: vi.fn().mockReturnThis(), json: vi.fn() }; + next = vi.fn(); + (Credential.count as any).mockResolvedValue(0); + (TotpCredential.count as any).mockResolvedValue(0); + }); + + function withSession(overrides: Record = {}) { + (Session.findOne as any).mockResolvedValue(buildSession(overrides)); + } + + it('documents the 403 it can answer', () => { + expect(requireFactorEnrollmentProof.seamlessDeviceStepUp).toBe(true); + }); + + it('refuses a session from a device grant with no step-up', async () => { + await requireFactorEnrollmentProof( + buildReq({ deviceChildSession: { stepUpVerifiedAt: null, stepUpMethod: null } }), + res, + next, + ); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ error: 'step_up_required' })); + }); + + it('lets a recovery session enrol', async () => { + await requireFactorEnrollmentProof(buildReq({ recoverySession: true }), res, next); + + expect(next).toHaveBeenCalled(); + expect(Session.findOne).not.toHaveBeenCalled(); + }); + + it('refuses when the session is gone', async () => { + (Session.findOne as any).mockResolvedValue(null); + + await requireFactorEnrollmentProof(buildReq(), res, next); + + expect(res.status).toHaveBeenCalledWith(401); + expect(next).not.toHaveBeenCalled(); + }); + + it('refuses a request with no user or session id', async () => { + await requireFactorEnrollmentProof(buildReq({ user: undefined }), res, next); + await requireFactorEnrollmentProof(buildReq({ sessionId: undefined }), res, next); + + expect(res.status).toHaveBeenCalledTimes(2); + expect(res.status).toHaveBeenCalledWith(401); + expect(Session.findOne).not.toHaveBeenCalled(); + }); + + describe('an account that already has a factor', () => { + it('needs a fresh step-up even right after signing in', async () => { + (Credential.count as any).mockResolvedValue(1); + withSession({ authTime: new Date(), stepUpVerifiedAt: null }); + + await requireFactorEnrollmentProof(buildReq(), res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith( + expect.objectContaining({ error: 'step_up_required', fresh: false }), + ); + }); + + it('counts only an enabled TOTP as a factor', async () => { + (TotpCredential.count as any).mockResolvedValue(1); + withSession({ stepUpVerifiedAt: new Date(Date.now() - 6 * MINUTE_MS) }); + + await requireFactorEnrollmentProof(buildReq(), res, next); + + expect(TotpCredential.count).toHaveBeenCalledWith({ + where: { userId: 'user-1', enabled: true }, + }); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ error: 'step_up_required' })); + }); + + it('passes a fresh step-up', async () => { + (Credential.count as any).mockResolvedValue(2); + withSession({ stepUpVerifiedAt: new Date(), stepUpMethod: 'webauthn' }); + + await requireFactorEnrollmentProof(buildReq(), res, next); + + expect(next).toHaveBeenCalled(); + }); + }); + + describe('an account with no factor', () => { + it('passes a recent sign-in', async () => { + withSession({ authTime: new Date(Date.now() - 9 * MINUTE_MS) }); + + await requireFactorEnrollmentProof(buildReq(), res, next); + + expect(next).toHaveBeenCalled(); + }); + + it('asks for a new sign-in once the sign-in is old', async () => { + withSession({ authTime: new Date(Date.now() - 11 * MINUTE_MS) }); + + await requireFactorEnrollmentProof(buildReq(), res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(403); + expect(res.json).toHaveBeenCalledWith({ + error: 'reauthentication_required', + message: 'Sign in again to add a sign-in method', + maxAgeSeconds: 600, + }); + }); + + it('asks for a new sign-in when the session carries no sign-in time', async () => { + withSession({ authTime: null }); + + await requireFactorEnrollmentProof(buildReq(), res, next); + + expect(next).not.toHaveBeenCalled(); + expect(res.json).toHaveBeenCalledWith( + expect.objectContaining({ error: 'reauthentication_required' }), + ); + }); + }); +}); diff --git a/tests/unit/services/stepUpService.spec.ts b/tests/unit/services/stepUpService.spec.ts index 1454fee6..227f1a20 100644 --- a/tests/unit/services/stepUpService.spec.ts +++ b/tests/unit/services/stepUpService.spec.ts @@ -3,7 +3,10 @@ import { describe, expect, it, vi } from 'vitest'; import { Session } from '../../../src/models/sessions.js'; import { DEFAULT_STEP_UP_MAX_AGE_SECONDS, + factorPredatesSignIn, + findSessionSignInTime, getSessionStepUpStatus, + getStepUpSignInTime, getStepUpStatusFromSession, mergeAuthMethod, recordStepUpVerification, @@ -251,4 +254,132 @@ describe('stepUpService', () => { maxAgeSeconds: DEFAULT_STEP_UP_MAX_AGE_SECONDS, }); }); + + describe('when the session holder signed in', () => { + const at = (iso: string) => new Date(iso); + + it('is the chain start of a session with no parent', async () => { + await expect( + findSessionSignInTime({ + chainStartedAt: at('2026-11-01T10:00:00Z'), + createdAt: at('2026-11-01T11:00:00Z'), + parentSessionId: null, + } as never), + ).resolves.toEqual(at('2026-11-01T10:00:00Z')); + }); + + it('falls back to the row creation time', async () => { + await expect( + findSessionSignInTime({ + chainStartedAt: null, + createdAt: at('2026-11-01T11:00:00Z'), + } as never), + ).resolves.toEqual(at('2026-11-01T11:00:00Z')); + }); + + it('walks to the earliest session an exchanged child came from', async () => { + (Session.findByPk as any) + .mockResolvedValueOnce({ + chainStartedAt: at('2026-11-01T09:00:00Z'), + parentSessionId: 'root', + }) + .mockResolvedValueOnce({ chainStartedAt: at('2026-11-01T08:00:00Z') }); + + await expect( + findSessionSignInTime({ + chainStartedAt: at('2026-11-01T12:00:00Z'), + parentSessionId: 'middle', + } as never), + ).resolves.toEqual(at('2026-11-01T08:00:00Z')); + expect(Session.findByPk).toHaveBeenNthCalledWith(1, 'middle'); + expect(Session.findByPk).toHaveBeenNthCalledWith(2, 'root'); + }); + + it('keeps the child start when a parent began later', async () => { + (Session.findByPk as any).mockResolvedValueOnce({ + chainStartedAt: at('2026-11-01T13:00:00Z'), + }); + + await expect( + findSessionSignInTime({ + chainStartedAt: at('2026-11-01T12:00:00Z'), + parentSessionId: 'later', + } as never), + ).resolves.toEqual(at('2026-11-01T12:00:00Z')); + }); + + it('is unknown when a parent is missing or has no start', async () => { + (Session.findByPk as any).mockResolvedValueOnce(null); + await expect( + findSessionSignInTime({ + chainStartedAt: at('2026-11-01T12:00:00Z'), + parentSessionId: 'gone', + } as never), + ).resolves.toBeNull(); + + (Session.findByPk as any).mockResolvedValueOnce({ chainStartedAt: null, createdAt: null }); + await expect( + findSessionSignInTime({ + chainStartedAt: at('2026-11-01T12:00:00Z'), + parentSessionId: 'blank', + } as never), + ).resolves.toBeNull(); + }); + + it('is unknown when the session itself has no start', async () => { + await expect( + findSessionSignInTime({ chainStartedAt: null, createdAt: null } as never), + ).resolves.toBeNull(); + }); + + it('is unknown when the lineage does not end', async () => { + (Session.findByPk as any).mockResolvedValue({ + chainStartedAt: at('2026-11-01T12:00:00Z'), + parentSessionId: 'loop', + }); + + await expect( + findSessionSignInTime({ + chainStartedAt: at('2026-11-01T12:00:00Z'), + parentSessionId: 'loop', + } as never), + ).resolves.toBeNull(); + (Session.findByPk as any).mockReset(); + }); + + it('reports a missing current session', async () => { + (Session.findOne as any).mockResolvedValueOnce(null); + + await expect(getStepUpSignInTime('session-1', 'user-1')).resolves.toEqual({ + sessionFound: false, + signedInAt: null, + }); + }); + + it('reports the current session sign-in time', async () => { + const session = buildSession({ parentSessionId: null }); + (Session.findOne as any).mockResolvedValueOnce(session); + + await expect(getStepUpSignInTime('session-1', 'user-1')).resolves.toEqual({ + sessionFound: true, + signedInAt: session.chainStartedAt, + }); + }); + }); + + describe('whether a factor predates the sign-in', () => { + const signedInAt = new Date('2026-11-01T12:00:00Z'); + + it('counts only a factor enrolled strictly before it', () => { + expect(factorPredatesSignIn(new Date('2026-11-01T11:59:59Z'), signedInAt)).toBe(true); + expect(factorPredatesSignIn(signedInAt, signedInAt)).toBe(false); + expect(factorPredatesSignIn(new Date('2026-11-01T12:00:01Z'), signedInAt)).toBe(false); + }); + + it('fails closed on a missing time', () => { + expect(factorPredatesSignIn(null, signedInAt)).toBe(false); + expect(factorPredatesSignIn(undefined, signedInAt)).toBe(false); + expect(factorPredatesSignIn(new Date('2026-01-01T00:00:00Z'), null)).toBe(false); + }); + }); }); diff --git a/tests/unit/services/totpService.spec.ts b/tests/unit/services/totpService.spec.ts index fc7b4b31..f8b18bce 100644 --- a/tests/unit/services/totpService.spec.ts +++ b/tests/unit/services/totpService.spec.ts @@ -137,6 +137,53 @@ describe('totpService', () => { expect(credential.lastUsedCounter).toBe(values.lastUsedCounter); }); + describe('restricted to a credential enrolled before a time', () => { + const secret = 'JBSWY3DPEHPK3PXP'; + const signedInAt = new Date('2026-11-01T12:00:00Z'); + + it('refuses a credential enabled after that time without checking the code', async () => { + (TotpCredential.findOne as any).mockResolvedValue( + buildTotpCredential({ + ...encryptTotpSecret(secret), + verifiedAt: new Date('2026-11-01T12:00:01Z'), + }), + ); + + await expect( + verifyEnabledTotp('user-1', generateTotpCode({ secret }), { enrolledBefore: signedInAt }), + ).resolves.toEqual({ verified: false, reason: 'enrolled_after_sign_in' }); + expect(TotpCredential.update).not.toHaveBeenCalled(); + }); + + it('refuses every credential when the time is unknown', async () => { + (TotpCredential.findOne as any).mockResolvedValue( + buildTotpCredential({ ...encryptTotpSecret(secret) }), + ); + + await expect( + verifyEnabledTotp('user-1', generateTotpCode({ secret }), { enrolledBefore: null }), + ).resolves.toEqual({ verified: false, reason: 'enrolled_after_sign_in' }); + }); + + it('accepts an older credential and keeps the restriction in the claim', async () => { + (TotpCredential.findOne as any).mockResolvedValue( + buildTotpCredential({ + ...encryptTotpSecret(secret), + verifiedAt: new Date('2026-10-01T00:00:00Z'), + lastUsedCounter: null, + }), + ); + + const result = await verifyEnabledTotp('user-1', generateTotpCode({ secret }), { + enrolledBefore: signedInAt, + }); + + expect(result.verified).toBe(true); + const [, options] = (TotpCredential.update as any).mock.calls[0]; + expect(options.where.verifiedAt).toEqual({ [Op.lt]: signedInAt }); + }); + }); + it('rejects a code another request consumed between the read and the write', async () => { const secret = 'JBSWY3DPEHPK3PXP'; const credential = buildTotpCredential({ ...encryptTotpSecret(secret), lastUsedCounter: null }); From af23ae0e51d02731db9b521f3f963a936f691956 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Tue, 17 Nov 2026 22:37:58 -0500 Subject: [PATCH 2/3] fix(step-up): shorten the first-factor sign-in window to five minutes --- .changeset/step-up-factor-age.md | 2 +- docs/security-posture.md | 2 +- src/services/stepUpService.ts | 2 +- tests/integration/stepUp/factorEnrollment.spec.ts | 2 +- tests/unit/middleware/requireFactorEnrollmentProof.spec.ts | 6 +++--- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.changeset/step-up-factor-age.md b/.changeset/step-up-factor-age.md index d377fa92..c8c86dca 100644 --- a/.changeset/step-up-factor-age.md +++ b/.changeset/step-up-factor-age.md @@ -5,7 +5,7 @@ Step-up and factor enrollment are stricter. - A step-up only accepts a passkey or TOTP enrolled before the session signed in. One added during the session works from the next sign-in. `/totp/verify-mfa` answers `401 step_up_unavailable` for a TOTP that is too new, and `/step-up/webauthn/start` leaves out passkeys that are too new. -- Passkey and TOTP enrollment, phone registration and recovery code generation need a fresh step-up (`403 step_up_required`) when the account already has a passkey or TOTP. An account with neither needs a sign-in from the last ten minutes, and otherwise gets `403 reauthentication_required`. Recovery sessions are exempt. +- Passkey and TOTP enrollment, phone registration and recovery code generation need a fresh step-up (`403 step_up_required`) when the account already has a passkey or TOTP. An account with neither needs a sign-in from the last five minutes, and otherwise gets `403 reauthentication_required`. Recovery sessions are exempt. - `DELETE /users/credentials` needs a fresh step-up. Clients that add a passkey or TOTP from an existing session should run a step-up when they get `step_up_required`, and ask the user to sign in again when they get `reauthentication_required`. diff --git a/docs/security-posture.md b/docs/security-posture.md index a769b478..cc05c41c 100644 --- a/docs/security-posture.md +++ b/docs/security-posture.md @@ -847,7 +847,7 @@ the earliest session in its lineage, and a lineage that cannot be read counts no Adding a factor needs proof as well. Passkey and TOTP enrollment, phone registration and recovery code generation answer `403 step_up_required` until an account that already has a passkey or TOTP has stepped up, and `403 reauthentication_required` to an account with neither -whose sign-in is more than ten minutes old. A recovery session is exempt, since enrolling is +whose sign-in is more than five minutes old. A recovery session is exempt, since enrolling is what it is for. Deleting a passkey (`DELETE /users/credentials`) also needs a fresh step-up. ### What is still accepted diff --git a/src/services/stepUpService.ts b/src/services/stepUpService.ts index 4b9b0790..02c5b241 100644 --- a/src/services/stepUpService.ts +++ b/src/services/stepUpService.ts @@ -10,7 +10,7 @@ import { deriveAcrAmr } from './oidcAuthContext.js'; export const DEFAULT_STEP_UP_MAX_AGE_SECONDS = 5 * 60; /** How recent a sign-in must be to add the first factor to an account that has none. */ -export const FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS = 10 * 60; +export const FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS = 5 * 60; const MAX_SESSION_LINEAGE = 8; diff --git a/tests/integration/stepUp/factorEnrollment.spec.ts b/tests/integration/stepUp/factorEnrollment.spec.ts index aa1446fb..e6dfa0c8 100644 --- a/tests/integration/stepUp/factorEnrollment.spec.ts +++ b/tests/integration/stepUp/factorEnrollment.spec.ts @@ -72,7 +72,7 @@ describe('adding a sign-in factor', () => { expect(res.status).toBe(403); expect(res.body).toEqual( - expect.objectContaining({ error: 'reauthentication_required', maxAgeSeconds: 600 }), + expect.objectContaining({ error: 'reauthentication_required', maxAgeSeconds: 300 }), ); }, ); diff --git a/tests/unit/middleware/requireFactorEnrollmentProof.spec.ts b/tests/unit/middleware/requireFactorEnrollmentProof.spec.ts index a26e7cb8..6fe41c87 100644 --- a/tests/unit/middleware/requireFactorEnrollmentProof.spec.ts +++ b/tests/unit/middleware/requireFactorEnrollmentProof.spec.ts @@ -107,7 +107,7 @@ describe('requireFactorEnrollmentProof', () => { describe('an account with no factor', () => { it('passes a recent sign-in', async () => { - withSession({ authTime: new Date(Date.now() - 9 * MINUTE_MS) }); + withSession({ authTime: new Date(Date.now() - 4 * MINUTE_MS) }); await requireFactorEnrollmentProof(buildReq(), res, next); @@ -115,7 +115,7 @@ describe('requireFactorEnrollmentProof', () => { }); it('asks for a new sign-in once the sign-in is old', async () => { - withSession({ authTime: new Date(Date.now() - 11 * MINUTE_MS) }); + withSession({ authTime: new Date(Date.now() - 6 * MINUTE_MS) }); await requireFactorEnrollmentProof(buildReq(), res, next); @@ -124,7 +124,7 @@ describe('requireFactorEnrollmentProof', () => { expect(res.json).toHaveBeenCalledWith({ error: 'reauthentication_required', message: 'Sign in again to add a sign-in method', - maxAgeSeconds: 600, + maxAgeSeconds: 300, }); }); From 92824f83e31ef4202df76e77d081741cd811a2fa Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Wed, 25 Nov 2026 13:42:50 -0500 Subject: [PATCH 3/3] test(sessions): date factor fixtures before the sign-in they step up --- tests/postgres/sessionExchange.spec.ts | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/tests/postgres/sessionExchange.spec.ts b/tests/postgres/sessionExchange.spec.ts index 4297e26b..af7505d4 100644 --- a/tests/postgres/sessionExchange.spec.ts +++ b/tests/postgres/sessionExchange.spec.ts @@ -1585,6 +1585,21 @@ describe('session lists', () => { }); }); +/** Dates the user's factors to before they signed in, since a newer one cannot step up. */ +async function backdateFactors(userId: string) { + const { TotpCredential } = await import('../../src/models/totpCredentials.js'); + const { Credential } = await import('../../src/models/credentials.js'); + const at = new Date(Date.now() - 24 * 60 * 60_000); + + await TotpCredential.update({ verifiedAt: at }, { where: { userId } }); + await Credential.sequelize!.query( + 'UPDATE credentials SET "createdAt" = :at WHERE "userId" = :userId', + { + replacements: { at, userId }, + }, + ); +} + describe('factor changes on a device child', () => { const ADMIN_ROLES = ['admin:read', 'admin:write']; @@ -1627,6 +1642,7 @@ describe('factor changes on a device child', () => { generateTotpCode({ secret, counter: getTotpCounter() - 1 }), ); expect(enrolled.verified).toBe(true); + await backdateFactors(user.id); return { secret, code: () => generateTotpCode({ secret }) }; } @@ -1798,7 +1814,7 @@ describe('factor changes on a device child', () => { it('does not change a first-party session', async () => { const user = await createUser(); - const session = await createSession(user.id); + const session = await createSession(user.id, { authTime: new Date() }); const token = await accessTokenFor(session); expect((await request(app).post('/totp/enroll/start').set(bearer(token))).status).toBe(200); @@ -1921,6 +1937,7 @@ describe('organization routes on a device child', () => { user.id, generateTotpCode({ secret, counter: getTotpCounter() - 1 }), ); + await backdateFactors(user.id); const stepUp = await request(app) .post('/totp/verify-mfa') .set(bearer(token)) @@ -2129,7 +2146,9 @@ describe('a passkey step-up on a device child', () => { /** The user's own passkey, registered from a first-party session, and a device sign-in. */ async function signedInWithPasskey() { const { SoftwareAuthenticator } = await import('../factories/softwareAuthenticator.js'); - const { client, user, parent } = await signedInToCli({}, {}, ['admin:read']); + const { client, user, parent } = await signedInToCli({ authTime: new Date() }, {}, [ + 'admin:read', + ]); const browser = await accessTokenFor(parent, ['admin:read']); const passkey = new SoftwareAuthenticator(); @@ -2146,6 +2165,7 @@ describe('a passkey step-up on a device child', () => { }), }); expect(finish.status).toBe(200); + await backdateFactors(user.id); const { token: subject } = await signSubject(client, parent, { grantType: DEVICE_CODE }); const child = await exchange(subject);