From c3b6468f81438b2dc2e447fac22d493042164025 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Tue, 17 Nov 2026 23:42:55 -0500 Subject: [PATCH] fix(recovery): count wrong recovery codes per account and lengthen the codes Email recovery codes are six letters and phone codes eight digits. Wrong codes are recorded in auth_failures per account and channel, claimed before the code is compared, and ten in 24 hours stop that channel until the oldest ages out. A spent or unreadable budget answers as a wrong code and sends nothing. --- .changeset/recovery-code-budget.md | 5 + docs/account-recovery.md | 20 ++- openapi.json | 4 +- src/controllers/accountRecovery.ts | 18 ++- src/generated/api.ts | 4 +- src/routes/accountRecovery.routes.ts | 7 +- src/services/accountRecoveryService.ts | 113 +++++++++++++- tests/factories/accountRecoveryStore.ts | 30 ++++ .../recovery/accountRecovery.spec.ts | 91 +++++++++++- tests/postgres/accountRecovery.spec.ts | 64 +++++++- .../services/accountRecoveryService.spec.ts | 138 ++++++++++++++++-- 11 files changed, 456 insertions(+), 38 deletions(-) create mode 100644 .changeset/recovery-code-budget.md diff --git a/.changeset/recovery-code-budget.md b/.changeset/recovery-code-budget.md new file mode 100644 index 00000000..11f796b2 --- /dev/null +++ b/.changeset/recovery-code-budget.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': patch +--- + +Self-service account recovery codes are stronger and their guesses are counted per account. Email codes are now six letters, like the sign-in code, and phone codes are eight digits. Each account may spend ten wrong recovery codes per channel in any 24 hours, counted across every `/recovery/start` and kept in the database. Once the budget is spent, `/recovery/start` sends no code and `/recovery/verify` checks none until the oldest wrong code is 24 hours old. Both answer as they otherwise would (`200` and `401 invalid_recovery_code`). The budget is separate for each channel and does not affect sign-in lockout or recovery codes. If it cannot be read, the channel is treated as spent. diff --git a/docs/account-recovery.md b/docs/account-recovery.md index 32ad5ecd..2b284eef 100644 --- a/docs/account-recovery.md +++ b/docs/account-recovery.md @@ -78,7 +78,7 @@ open requests), and `GET /system-config/public` reports | Route | Auth | What it does | | ------------------------------- | ---------------------------- | --------------------------------------------------------------------------------- | -| `POST /recovery/start` | pre-auth token from `/login` | `{ channel: "email" \| "phone" }`, sends a six-digit code | +| `POST /recovery/start` | pre-auth token from `/login` | `{ channel: "email" \| "phone" }`, sends a code | | `POST /recovery/verify` | the same attempt | `{ code }`, opens the request and starts the delay | | `GET /recovery/status` | the same attempt | `{ state, requestedAt, completesAt }` | | `POST /recovery/cancel` | none | `{ cancelToken }` from the notice | @@ -91,9 +91,11 @@ open requests), and `GET /system-config/public` reports 1. **Start.** The code goes to the verified address on file for the channel, through the same delivery as OTP codes (including external delivery, where the response carries `delivery`). The answer is the same whether or not the account has a verified address - there, so it does not say which channels exist. The code lasts ten minutes and is stored + there, so it does not say which channels exist. Email codes are six letters, like the + sign-in code, and phone codes are eight digits. The code lasts ten minutes and is stored hashed. -2. **Verify.** Five wrong codes void the request. The right one opens it: `state` is +2. **Verify.** Five wrong codes void the request, and every wrong code also counts against + the account's [failure budget](#failure-budget). The right one opens it: `state` is `pending`, `completesAt` is now plus the delay, and a notice goes to the account's verified email **and** phone saying recovery was requested, when it completes and how to cancel it. The cancel link is `${FRONTEND_URL}/recovery/cancel#`; the token is in @@ -120,6 +122,18 @@ Starting is not enough to disturb anything: anyone who knows an address can star a verified code opens, resumes or cancels a request. Five wrong codes on a resume void that code and leave the open request as it was. +### Failure budget + +An account may spend ten wrong codes on each channel in any 24 hours, counted across every +start and attempt and stored in the database, so starting again or reaching another +instance does not refill it. Once it is spent, start sends no code and verify checks none +until the oldest wrong code is 24 hours old. Both answer as they would anyway (`200` with +the usual message, `401` with `invalid_recovery_code`), so a spent budget does not reveal +that the account exists. The two channels have separate budgets, and none of this touches +sign-in lockout or recovery codes. If the count cannot be read, the channel is treated as +spent. Someone who knows an address can spend its budget and hold that channel's recovery +off for a day at a time; the other channel and recovery codes still work. + ### Cancelling `POST /recovery/cancel` with the token from the notice cancels the request whether it is diff --git a/openapi.json b/openapi.json index 74512d23..4d8c640e 100644 --- a/openapi.json +++ b/openapi.json @@ -13,7 +13,7 @@ "/recovery/start": { "post": { "summary": "Start account recovery", - "description": "Sends a code to the verified address on file for the channel. Answers the same whether or not the account has one. Not subject to account lockout.", + "description": "Sends a code to the verified address on file for the channel. Answers the same whether or not the account has one, or while the channel failure budget is spent. Not subject to account lockout.", "tags": ["Recovery"], "security": [{ "bearerAuth": [] }], "requestBody": { @@ -243,7 +243,7 @@ "/recovery/verify": { "post": { "summary": "Verify an account recovery code", - "description": "Opens the request started on this attempt, which completes after the configured delay, and tells every verified address how to cancel it. A code for a request that is already open resumes it on this attempt. Five wrong codes void the code. Answers 503 and voids the request when no verified address could be notified. A credentialed caller that owns delivery and lists `account_notice_email` / `account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as `deliveries` to send; one that does not list them gets the 503.", + "description": "Opens the request started on this attempt, which completes after the configured delay, and tells every verified address how to cancel it. A code for a request that is already open resumes it on this attempt. Five wrong codes void the code, and ten on a channel within 24 hours stop that channel for the account until the oldest ages out, answering as a wrong code. Answers 503 and voids the request when no verified address could be notified. A credentialed caller that owns delivery and lists `account_notice_email` / `account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as `deliveries` to send; one that does not list them gets the 503.", "tags": ["Recovery"], "security": [{ "bearerAuth": [] }], "requestBody": { diff --git a/src/controllers/accountRecovery.ts b/src/controllers/accountRecovery.ts index 2e06a234..7d88d614 100644 --- a/src/controllers/accountRecovery.ts +++ b/src/controllers/accountRecovery.ts @@ -112,6 +112,17 @@ export const startAccountRecovery = async (req: Request, res: Response) => { try { const code = await startRecovery(user.id, channel, attemptId); + // Answers as if sent, so a spent budget does not confirm the account has the address. + if (code === null) { + await AuthEventService.log({ + userId: user.id, + type: 'account_recovery_started', + req, + metadata: { channel, sent: false, reason: 'Recovery failure budget spent' }, + }); + return res.status(200).json({ message: RECOVERY_STARTED_MESSAGE }); + } + if (!external) { if (channel === 'email') { await sendOTPEmail(to, code); @@ -189,12 +200,15 @@ export const verifyAccountRecovery = async (req: Request, res: Response) => { ? await verifyRecovery(user.id, attemptId, req.body.code, delaySeconds) : ({ outcome: 'invalid' } as const); - if (result.outcome === 'invalid') { + // A spent budget answers like a wrong code, so it is not an oracle on the account. + if (result.outcome === 'invalid' || result.outcome === 'locked') { await AuthEventService.log({ userId: user.id, type: 'account_recovery_failed', req, - metadata: { reason: 'Invalid code' }, + metadata: { + reason: result.outcome === 'locked' ? 'Recovery failure budget spent' : 'Invalid code', + }, }); return res.status(401).json({ error: 'invalid_recovery_code' }); } diff --git a/src/generated/api.ts b/src/generated/api.ts index 89a12013..f7ae2fe3 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -23,7 +23,7 @@ export interface paths { put?: never; /** * Start account recovery - * @description Sends a code to the verified address on file for the channel. Answers the same whether or not the account has one. Not subject to account lockout. + * @description Sends a code to the verified address on file for the channel. Answers the same whether or not the account has one, or while the channel failure budget is spent. Not subject to account lockout. */ post: { parameters: { @@ -249,7 +249,7 @@ export interface paths { put?: never; /** * Verify an account recovery code - * @description Opens the request started on this attempt, which completes after the configured delay, and tells every verified address how to cancel it. A code for a request that is already open resumes it on this attempt. Five wrong codes void the code. Answers 503 and voids the request when no verified address could be notified. A credentialed caller that owns delivery and lists `account_notice_email` / `account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as `deliveries` to send; one that does not list them gets the 503. + * @description Opens the request started on this attempt, which completes after the configured delay, and tells every verified address how to cancel it. A code for a request that is already open resumes it on this attempt. Five wrong codes void the code, and ten on a channel within 24 hours stop that channel for the account until the oldest ages out, answering as a wrong code. Answers 503 and voids the request when no verified address could be notified. A credentialed caller that owns delivery and lists `account_notice_email` / `account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as `deliveries` to send; one that does not list them gets the 503. */ post: { parameters: { diff --git a/src/routes/accountRecovery.routes.ts b/src/routes/accountRecovery.routes.ts index b428284f..2c851cc4 100644 --- a/src/routes/accountRecovery.routes.ts +++ b/src/routes/accountRecovery.routes.ts @@ -47,7 +47,8 @@ accountRecoveryRouter.post( summary: 'Start account recovery', description: 'Sends a code to the verified address on file for the channel. Answers the same ' + - 'whether or not the account has one. Not subject to account lockout.', + 'whether or not the account has one, or while the channel failure budget is spent. ' + + 'Not subject to account lockout.', tags: ['Recovery'], schemas: { body: AccountRecoveryStartRequestSchema, @@ -73,7 +74,9 @@ accountRecoveryRouter.post( description: 'Opens the request started on this attempt, which completes after the configured ' + 'delay, and tells every verified address how to cancel it. A code for a request ' + - 'that is already open resumes it on this attempt. Five wrong codes void the code. ' + + 'that is already open resumes it on this attempt. Five wrong codes void the code, and ' + + 'ten on a channel within 24 hours stop that channel for the account until the oldest ' + + 'ages out, answering as a wrong code. ' + 'Answers 503 and voids the request when no verified address could be notified. A ' + 'credentialed caller that owns delivery and lists `account_notice_email` / ' + '`account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as ' + diff --git a/src/services/accountRecoveryService.ts b/src/services/accountRecoveryService.ts index 6c1a4db9..53217503 100644 --- a/src/services/accountRecoveryService.ts +++ b/src/services/accountRecoveryService.ts @@ -4,7 +4,7 @@ * See LICENSE file in the project root for full license information */ -import { randomBytes } from 'crypto'; +import { randomBytes, randomInt } from 'crypto'; import { Op } from 'sequelize'; import { @@ -12,13 +12,98 @@ import { RecoveryChannel, StoredRecoveryState, } from '../models/accountRecoveryRequests.js'; -import { generateRandomPhoneOTP, hashOtpToken, otpHashMatches } from '../utils/otp.js'; +import { AuthFailure } from '../models/authFailures.js'; +import getLogger from '../utils/logger.js'; +import { generateRandomEmailOTP, hashOtpToken, otpHashMatches } from '../utils/otp.js'; import { hashSha256 } from '../utils/utils.js'; import { revokeAllSessionsForUsers } from './sessionRevocation.js'; +const logger = getLogger('accountRecoveryService'); + export const RECOVERY_CODE_TTL_MS = 10 * 60 * 1000; export const MAX_RECOVERY_CODE_ATTEMPTS = 5; +/** + * Wrong codes an account may spend on one channel in {@link RECOVERY_FAILURE_WINDOW_MS}, + * across every start. Kept in the database so restarting the flow, or reaching another + * instance, does not refill it. Per channel, so spending one does not stop the other. + */ +export const RECOVERY_FAILURE_BUDGET = 10; +export const RECOVERY_FAILURE_WINDOW_MS = 24 * 60 * 60 * 1000; + +// Not a lockout failure type, so these never lock the account out of signing in. +export function recoveryFailureType(channel: RecoveryChannel) { + return `account_recovery_${channel}_failed`; +} + +function generateRecoveryCode(channel: RecoveryChannel) { + return channel === 'email' + ? generateRandomEmailOTP() + : String(randomInt(10_000_000, 100_000_000)); +} + +async function spentRecoveryFailures(userId: string, channel: RecoveryChannel) { + return AuthFailure.count({ + where: { + userId, + type: recoveryFailureType(channel), + occurredAt: { [Op.gte]: new Date(Date.now() - RECOVERY_FAILURE_WINDOW_MS) }, + }, + }); +} + +/** Whether the channel's budget is spent. An unreadable count is treated as spent. */ +export async function isRecoveryChannelLocked(userId: string, channel: RecoveryChannel) { + try { + return (await spentRecoveryFailures(userId, channel)) >= RECOVERY_FAILURE_BUDGET; + } catch (error) { + logger.error(`Could not read the recovery failure count, treating it as spent: ${error}`); + return true; + } +} + +async function releaseRecoveryGuess(claimId: string) { + try { + await AuthFailure.destroy({ where: { id: claimId } }); + } catch (error) { + logger.error(`Could not release a recovery guess: ${error}`); + } +} + +/** + * Spends one guess from the budget before the code is compared. The row is written + * first and the window counted after, so concurrent guesses on any instance each see + * the others and no more than the budget get through. Returns null, having spent + * nothing, when the budget is gone or cannot be checked. + */ +async function claimRecoveryGuess(userId: string, channel: RecoveryChannel) { + let claimId: string; + + try { + claimId = ( + await AuthFailure.create({ + userId, + type: recoveryFailureType(channel), + occurredAt: new Date(), + }) + ).id; + } catch (error) { + logger.error(`Could not record a recovery guess, refusing it: ${error}`); + return null; + } + + try { + if ((await spentRecoveryFailures(userId, channel)) <= RECOVERY_FAILURE_BUDGET) { + return claimId; + } + } catch (error) { + logger.error(`Could not read the recovery failure count, refusing the guess: ${error}`); + } + + await releaseRecoveryGuess(claimId); + return null; +} + export type RecoveryState = 'pending' | 'ready' | 'cancelled' | 'completed'; export interface RecoveryStatus { @@ -51,9 +136,15 @@ function hashCancelToken(token: string) { * * Nothing earlier is cancelled here. A stranger who knows the address can call this, and * only a verified code may cancel the owner's request. + * + * Returns null, issuing nothing, while the channel's failure budget is spent. */ export async function startRecovery(userId: string, channel: RecoveryChannel, attemptId: string) { - const code = String(generateRandomPhoneOTP()); + if (await isRecoveryChannelLocked(userId, channel)) { + return null; + } + + const code = generateRecoveryCode(channel); const codeFields = { codeAttemptId: attemptId, codeHash: hashOtpToken(code), @@ -82,6 +173,7 @@ export async function startRecovery(userId: string, channel: RecoveryChannel, at export type VerifyRecoveryResult = | { outcome: 'invalid' } + | { outcome: 'locked' } | { outcome: 'opened'; request: AccountRecoveryRequest; cancelToken: string } | { outcome: 'resumed'; request: AccountRecoveryRequest }; @@ -98,7 +190,8 @@ function clearCode(request: AccountRecoveryRequest) { /** * Checks the code issued to this attempt. Each try is claimed with a conditional update * before the code is compared, so parallel requests cannot spend more than - * {@link MAX_RECOVERY_CODE_ATTEMPTS} between them. + * {@link MAX_RECOVERY_CODE_ATTEMPTS} between them, or more than the account's + * {@link RECOVERY_FAILURE_BUDGET} on the channel. */ export async function verifyRecovery( userId: string, @@ -127,22 +220,32 @@ export async function verifyRecovery( return { outcome: 'invalid' }; } + const guess = await claimRecoveryGuess(userId, request.channel); + + if (!guess) { + return { outcome: 'locked' }; + } + const [claimed] = await AccountRecoveryRequest.update( { failedAttempts: tries + 1 }, { where: { id: request.id, failedAttempts: tries } }, ); if (claimed !== 1) { + await releaseRecoveryGuess(guess); return { outcome: 'invalid' }; } - if (!otpHashMatches(request.codeHash, code)) { + // Email codes are letters, compared case-insensitively like the login OTP. + if (!otpHashMatches(request.codeHash, code.toUpperCase())) { if (tries + 1 >= MAX_RECOVERY_CODE_ATTEMPTS) { await request.update(clearCode(request)); } return { outcome: 'invalid' }; } + await releaseRecoveryGuess(guess); + if (request.state === 'pending') { await request.update({ ...clearCode(request), attemptId, failedAttempts: 0 }); return { outcome: 'resumed', request }; diff --git a/tests/factories/accountRecoveryStore.ts b/tests/factories/accountRecoveryStore.ts index b528d785..449b74c2 100644 --- a/tests/factories/accountRecoveryStore.ts +++ b/tests/factories/accountRecoveryStore.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'crypto'; import { Op } from 'sequelize'; import { AccountRecoveryRequest } from '../../src/models/accountRecoveryRequests.js'; +import { AuthFailure } from '../../src/models/authFailures.js'; type Row = Record; type Where = Record; @@ -16,6 +17,7 @@ function matchesCondition(value: any, condition: any): boolean { if (op === Op.in) return operand.includes(value); if (op === Op.ne) return operand === null ? value != null : value !== operand; if (op === Op.lte) return value != null && +value <= +operand; + if (op === Op.gte) return value != null && +value >= +operand; throw new Error(`Unsupported operator ${String(op)}`); }); } @@ -27,6 +29,32 @@ function matches(row: Row, where: Where) { return Object.keys(where).every((key) => matchesCondition(row[key], where[key])); } +/** + * An in-memory stand-in for `auth_failures`, which holds the recovery failure budget. + * Installed by {@link installAccountRecoveryStore}; call it again to get the rows. + */ +export function installAuthFailureStore() { + const failures: Row[] = []; + + (AuthFailure.create as any).mockImplementation(async (data: Row) => { + const row = { id: randomUUID(), ...data }; + failures.push(row); + return row; + }); + + (AuthFailure.count as any).mockImplementation( + async ({ where }: { where: Where }) => failures.filter((row) => matches(row, where)).length, + ); + + (AuthFailure.destroy as any).mockImplementation(async ({ where }: { where: Where }) => { + const found = failures.filter((row) => matches(row, where)); + for (const row of found) failures.splice(failures.indexOf(row), 1); + return found.length; + }); + + return failures; +} + /** * An in-memory stand-in for the requests table that honours the where clauses the * service writes, so its conditional updates are exercised rather than assumed. @@ -35,6 +63,8 @@ export function installAccountRecoveryStore() { const rows: Row[] = []; let clock = 0; + installAuthFailureStore(); + const instance = (row: Row) => { Object.defineProperties(row, { update: { value: async (fields: Row) => Object.assign(row, fields), enumerable: false }, diff --git a/tests/integration/recovery/accountRecovery.spec.ts b/tests/integration/recovery/accountRecovery.spec.ts index 2db36161..e5e79daa 100644 --- a/tests/integration/recovery/accountRecovery.spec.ts +++ b/tests/integration/recovery/accountRecovery.spec.ts @@ -174,7 +174,7 @@ describe('POST /recovery/start', () => { expect(sendOTPEmail).toHaveBeenCalledWith( 'owner@example.com', - expect.stringMatching(/^\d{6}$/), + expect.stringMatching(/^[A-Z]{6}$/), ); }); @@ -209,7 +209,7 @@ describe('POST /recovery/start', () => { expect(res.body.delivery).toEqual({ kind: 'otp_email', to: 'owner@example.com', - token: expect.stringMatching(/^\d{6}$/), + token: expect.stringMatching(/^[A-Z]{6}$/), purpose: 'account_recovery', }); expect(sendOTPEmail).not.toHaveBeenCalled(); @@ -242,7 +242,9 @@ describe('POST /recovery/start', () => { it('ignores an existing lockout, which is what recovery is for', async () => { const { AuthFailure } = await import('../../../src/models/authFailures.js'); - (AuthFailure.count as any).mockResolvedValue(1000); + (AuthFailure.findAll as any).mockResolvedValue( + Array.from({ length: 1000 }, () => ({ occurredAt: new Date() })), + ); const res = await request(app).post('/recovery/start').send({ channel: 'email' }); @@ -485,6 +487,89 @@ describe('POST /recovery/verify', () => { expect(sendNoticeEmail).not.toHaveBeenCalled(); }); + describe('failure budget', () => { + async function spendWrongCodes(count: number) { + await request(app).post('/recovery/start').send({ channel: 'email' }); + const code = sentCode(); + const other = code === 'AAAAAA' ? 'BBBBBB' : 'AAAAAA'; + for (let i = 0; i < count; i += 1) { + await request(app).post('/recovery/verify').send({ code: other }); + } + } + + it('carries wrong codes across starts, then sends no more codes on that channel', async () => { + await spendWrongCodes(5); + attemptId = 'attempt-2'; + await spendWrongCodes(5); + (sendOTPEmail as any).mockClear(); + attemptId = 'attempt-3'; + + const email = await request(app).post('/recovery/start').send({ channel: 'email' }); + const phone = await request(app).post('/recovery/start').send({ channel: 'phone' }); + + expect(email.status).toBe(200); + expect(email.body).toEqual({ message: expect.any(String) }); + expect(sendOTPEmail).not.toHaveBeenCalled(); + expect(sendOTPSMS).toHaveBeenCalled(); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'account_recovery_started', + metadata: expect.objectContaining({ channel: 'email', sent: false }), + }), + ); + }); + + it('refuses even the right code once the budget is spent elsewhere', async () => { + const { AuthFailure } = await import('../../../src/models/authFailures.js'); + await spendWrongCodes(4); + attemptId = 'attempt-2'; + await request(app).post('/recovery/start').send({ channel: 'email' }); + const code = sentCode(); + for (let i = 0; i < 6; i += 1) { + await AuthFailure.create({ + userId: 'user-1', + type: 'account_recovery_email_failed', + occurredAt: new Date(), + }); + } + + const res = await request(app).post('/recovery/verify').send({ code }); + + expect(res.status).toBe(401); + expect(res.body).toEqual({ error: 'invalid_recovery_code' }); + expect(sendNoticeEmail).not.toHaveBeenCalled(); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'account_recovery_failed', + metadata: { reason: 'Recovery failure budget spent' }, + }), + ); + }); + + it('fails closed when the budget cannot be read', async () => { + const { AuthFailure } = await import('../../../src/models/authFailures.js'); + await request(app).post('/recovery/start').send({ channel: 'email' }); + const code = sentCode(); + (sendOTPEmail as any).mockClear(); + (AuthFailure.count as any).mockRejectedValue(new Error('db down')); + + const verify = await request(app).post('/recovery/verify').send({ code }); + const start = await request(app).post('/recovery/start').send({ channel: 'email' }); + + expect(verify.status).toBe(401); + expect(start.status).toBe(200); + expect(sendOTPEmail).not.toHaveBeenCalled(); + }); + + it('does not lock sign-in', async () => { + await spendWrongCodes(5); + + const { getUserLockoutStatus } = + await import('../../../src/services/lockoutPolicyService.js'); + expect((await getUserLockoutStatus('user-1')).locked).toBe(false); + }); + }); + it('resumes an open request on a new attempt without notifying again', async () => { const opened = await startAndVerify('email'); vi.clearAllMocks(); diff --git a/tests/postgres/accountRecovery.spec.ts b/tests/postgres/accountRecovery.spec.ts index fbab716f..d72b5c09 100644 --- a/tests/postgres/accountRecovery.spec.ts +++ b/tests/postgres/accountRecovery.spec.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'crypto'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { AccountRecoveryRequest } from '../../src/models/accountRecoveryRequests.js'; +import { AuthFailure } from '../../src/models/authFailures.js'; import { getSequelize, initializeModels } from '../../src/models/index.js'; import { cancelRecoveryByToken, @@ -9,6 +10,8 @@ import { completeRecovery, findRecoveryForAttempt, listOpenRecoveries, + RECOVERY_FAILURE_BUDGET, + recoveryFailureType, startRecovery, supersedeOtherRecoveries, verifyRecovery, @@ -34,13 +37,13 @@ afterAll(async () => { // evaluates them, rather than as the in-memory double does. describe('account recovery against Postgres', () => { it('opens, refuses early completion, cancels and cascades with the user', async () => { - const code = await startRecovery(userId, 'email', 'attempt-1'); + const code = (await startRecovery(userId, 'email', 'attempt-1'))!; const opened = await verifyRecovery(userId, 'attempt-1', code, 3600); expect(opened.outcome).toBe('opened'); expect((await completeRecovery(userId, 'attempt-1')).outcome).toBe('not_ready'); - const resumeCode = await startRecovery(userId, 'email', 'attempt-2'); + const resumeCode = (await startRecovery(userId, 'email', 'attempt-2'))!; expect((await verifyRecovery(userId, 'attempt-2', resumeCode, 3600)).outcome).toBe('resumed'); expect((await findRecoveryForAttempt(userId, 'attempt-2'))?.state).toBe('pending'); @@ -64,13 +67,13 @@ describe('account recovery against Postgres', () => { const first = await verifyRecovery( owner, 'attempt-a', - await startRecovery(owner, 'email', 'attempt-a'), + (await startRecovery(owner, 'email', 'attempt-a'))!, 3600, ); const second = await verifyRecovery( owner, 'attempt-b', - await startRecovery(owner, 'phone', 'attempt-b'), + (await startRecovery(owner, 'phone', 'attempt-b'))!, 3600, ); if (first.outcome !== 'opened' || second.outcome !== 'opened') throw new Error('not opened'); @@ -82,7 +85,7 @@ describe('account recovery against Postgres', () => { const third = await verifyRecovery( owner, 'attempt-c', - await startRecovery(owner, 'phone', 'attempt-c'), + (await startRecovery(owner, 'phone', 'attempt-c'))!, 3600, ); if (third.outcome !== 'opened') throw new Error('not opened'); @@ -105,7 +108,7 @@ describe('account recovery against Postgres', () => { const opened = await verifyRecovery( owner, 'attempt-l', - await startRecovery(owner, 'email', 'attempt-l'), + (await startRecovery(owner, 'email', 'attempt-l'))!, 3600, ); if (opened.outcome !== 'opened') throw new Error('not opened'); @@ -126,7 +129,7 @@ describe('account recovery against Postgres', () => { VALUES (:id, :email, '{user}', now(), now())`, { replacements: { id: owner, email: `recovery-${owner}@example.com` } }, ); - const code = await startRecovery(owner, 'phone', 'attempt-3'); + const code = (await startRecovery(owner, 'phone', 'attempt-3'))!; await verifyRecovery(owner, 'attempt-3', code, 3600); await AccountRecoveryRequest.update( { completesAt: new Date(Date.now() - 1000) }, @@ -138,4 +141,51 @@ describe('account recovery against Postgres', () => { expect(result.outcome).toBe('completed'); expect((await findRecoveryForAttempt(owner, 'attempt-3'))?.state).toBe('completed'); }); + + it('compares no more parallel guesses across attempts than the budget allows', async () => { + const owner = randomUUID(); + await getSequelize().query( + `INSERT INTO users (id, email, roles, created_at, updated_at) + VALUES (:id, :email, '{user}', now(), now())`, + { replacements: { id: owner, email: `recovery-${owner}@example.com` } }, + ); + const attempts = ['b-1', 'b-2', 'b-3', 'b-4']; + const codes = await Promise.all( + attempts.map(async (attempt) => (await startRecovery(owner, 'email', attempt))!), + ); + + const outcomes = await Promise.all( + attempts.flatMap((attempt, i) => + Array.from({ length: 5 }, () => + verifyRecovery(owner, attempt, codes[i] === 'AAAAAA' ? 'BBBBBB' : 'AAAAAA', 3600), + ), + ), + ); + + const spent = await AuthFailure.count({ + where: { userId: owner, type: recoveryFailureType('email') }, + }); + + expect(outcomes.filter(({ outcome }) => outcome === 'invalid').length).toBe(spent); + expect(spent).toBeLessThanOrEqual(RECOVERY_FAILURE_BUDGET); + expect(outcomes.filter(({ outcome }) => outcome === 'locked').length).toBe(20 - spent); + }); + + it('issues no code once the budget is spent, and keeps the other channel', async () => { + const owner = randomUUID(); + await getSequelize().query( + `INSERT INTO users (id, email, roles, created_at, updated_at) + VALUES (:id, :email, '{user}', now(), now())`, + { replacements: { id: owner, email: `recovery-${owner}@example.com` } }, + ); + for (const attempt of ['s-1', 's-2']) { + const code = (await startRecovery(owner, 'email', attempt))!; + for (let i = 0; i < 5; i += 1) { + await verifyRecovery(owner, attempt, code === 'AAAAAA' ? 'BBBBBB' : 'AAAAAA', 3600); + } + } + + expect(await startRecovery(owner, 'email', 's-3')).toBeNull(); + expect(await startRecovery(owner, 'phone', 's-3')).toMatch(/^\d{8}$/); + }); }); diff --git a/tests/unit/services/accountRecoveryService.spec.ts b/tests/unit/services/accountRecoveryService.spec.ts index de505f25..b4705c66 100644 --- a/tests/unit/services/accountRecoveryService.spec.ts +++ b/tests/unit/services/accountRecoveryService.spec.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { AccountRecoveryRequest } from '../../../src/models/accountRecoveryRequests.js'; +import { AuthFailure } from '../../../src/models/authFailures.js'; import { Session } from '../../../src/models/sessions.js'; import { User } from '../../../src/models/users.js'; import { @@ -8,19 +9,26 @@ import { completeRecovery, findRecoveryForAttempt, MAX_RECOVERY_CODE_ATTEMPTS, + RECOVERY_FAILURE_BUDGET, + RECOVERY_FAILURE_WINDOW_MS, recoveryStatus, startRecovery, supersedeOtherRecoveries, verifyRecovery, voidUnannouncedRecovery, } from '../../../src/services/accountRecoveryService.js'; -import { installAccountRecoveryStore } from '../../factories/accountRecoveryStore.js'; +import { + installAccountRecoveryStore, + installAuthFailureStore, +} from '../../factories/accountRecoveryStore.js'; const HOUR = 3600; let rows: ReturnType; +let failures: ReturnType; beforeEach(() => { rows = installAccountRecoveryStore(); + failures = installAuthFailureStore(); (Session.update as any).mockResolvedValue([3]); }); @@ -29,21 +37,21 @@ afterEach(() => { }); function wrong(code: string) { - return code === '000000' ? '111111' : '000000'; + return code === 'AAAAAA' ? 'BBBBBB' : 'AAAAAA'; } async function open(attemptId = 'attempt-1', channel: 'email' | 'phone' = 'email') { - const code = await startRecovery('user-1', channel, attemptId); + const code = (await startRecovery('user-1', channel, attemptId))!; const result = await verifyRecovery('user-1', attemptId, code, HOUR); if (result.outcome !== 'opened') throw new Error(`expected opened, got ${result.outcome}`); return result; } describe('startRecovery', () => { - it('stores a six-digit code only as a hash, bound to the attempt', async () => { - const code = await startRecovery('user-1', 'email', 'attempt-1'); + it('stores a six-letter email code only as a hash, bound to the attempt', async () => { + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; - expect(code).toMatch(/^\d{6}$/); + expect(code).toMatch(/^[A-Z]{6}$/); expect(rows).toHaveLength(1); expect(rows[0]).toMatchObject({ state: 'awaiting_code', codeAttemptId: 'attempt-1' }); expect(rows[0].codeHash).toMatch(/^sha256:/); @@ -51,6 +59,42 @@ describe('startRecovery', () => { expect(+rows[0].codeExpiresAt - Date.now()).toBeGreaterThan(9 * 60 * 1000); }); + it('sends an eight-digit code by phone', async () => { + expect(await startRecovery('user-1', 'phone', 'attempt-1')).toMatch(/^[1-9]\d{7}$/); + }); + + it('issues nothing once the channel budget is spent, and still issues on the other', async () => { + for (let i = 0; i < RECOVERY_FAILURE_BUDGET; i += 1) { + await AuthFailure.create({ + userId: 'user-1', + type: 'account_recovery_email_failed', + occurredAt: new Date(), + }); + } + + expect(await startRecovery('user-1', 'email', 'attempt-1')).toBeNull(); + expect(rows).toHaveLength(0); + expect(await startRecovery('user-1', 'phone', 'attempt-1')).not.toBeNull(); + }); + + it('issues again once the oldest wrong code leaves the window', async () => { + for (let i = 0; i < RECOVERY_FAILURE_BUDGET; i += 1) { + await AuthFailure.create({ + userId: 'user-1', + type: 'account_recovery_email_failed', + occurredAt: new Date(Date.now() - RECOVERY_FAILURE_WINDOW_MS - 1), + }); + } + + expect(await startRecovery('user-1', 'email', 'attempt-1')).not.toBeNull(); + }); + + it('issues nothing when the budget cannot be read', async () => { + (AuthFailure.count as any).mockRejectedValueOnce(new Error('db down')); + + expect(await startRecovery('user-1', 'email', 'attempt-1')).toBeNull(); + }); + it('voids an earlier unverified code on the same attempt', async () => { await startRecovery('user-1', 'email', 'attempt-1'); await startRecovery('user-1', 'phone', 'attempt-1'); @@ -82,8 +126,77 @@ describe('verifyRecovery', () => { expect(recoveryStatus(request).state).toBe('pending'); }); + it('accepts an email code in any case', async () => { + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; + + expect((await verifyRecovery('user-1', 'attempt-1', code.toLowerCase(), HOUR)).outcome).toBe( + 'opened', + ); + }); + + it('spends the budget across starts and attempts, and keeps nothing for a right code', async () => { + const first = (await startRecovery('user-1', 'email', 'attempt-1'))!; + for (let i = 0; i < MAX_RECOVERY_CODE_ATTEMPTS; i += 1) { + await verifyRecovery('user-1', 'attempt-1', wrong(first), HOUR); + } + const second = (await startRecovery('user-1', 'email', 'attempt-2'))!; + await verifyRecovery('user-1', 'attempt-2', wrong(second), HOUR); + + expect(failures).toHaveLength(MAX_RECOVERY_CODE_ATTEMPTS + 1); + expect(failures.every((row) => row.type === 'account_recovery_email_failed')).toBe(true); + + expect((await verifyRecovery('user-1', 'attempt-2', second, HOUR)).outcome).toBe('opened'); + expect(failures).toHaveLength(MAX_RECOVERY_CODE_ATTEMPTS + 1); + }); + + it('refuses the right code once the budget is spent, without spending more', async () => { + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; + for (let i = 0; i < RECOVERY_FAILURE_BUDGET; i += 1) { + await AuthFailure.create({ + userId: 'user-1', + type: 'account_recovery_email_failed', + occurredAt: new Date(), + }); + } + + expect(await verifyRecovery('user-1', 'attempt-1', code, HOUR)).toEqual({ + outcome: 'locked', + }); + expect(failures).toHaveLength(RECOVERY_FAILURE_BUDGET); + expect(rows[0]).toMatchObject({ state: 'awaiting_code', failedAttempts: 0 }); + }); + + it('refuses the guess when it cannot be recorded', async () => { + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; + (AuthFailure.create as any).mockRejectedValueOnce(new Error('db down')); + + expect((await verifyRecovery('user-1', 'attempt-1', code, HOUR)).outcome).toBe('locked'); + }); + + it('refuses the guess when the budget cannot be counted', async () => { + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; + (AuthFailure.count as any).mockRejectedValueOnce(new Error('db down')); + + expect((await verifyRecovery('user-1', 'attempt-1', code, HOUR)).outcome).toBe('locked'); + expect(failures).toHaveLength(0); + }); + + it('still refuses when a spent guess cannot be released', async () => { + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; + for (let i = 0; i < RECOVERY_FAILURE_BUDGET; i += 1) { + await AuthFailure.create({ + userId: 'user-1', + type: 'account_recovery_email_failed', + occurredAt: new Date(), + }); + } + (AuthFailure.destroy as any).mockRejectedValueOnce(new Error('db down')); + + expect((await verifyRecovery('user-1', 'attempt-1', code, HOUR)).outcome).toBe('locked'); + }); + it('refuses a code from another attempt', async () => { - const code = await startRecovery('user-1', 'email', 'attempt-1'); + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; expect(await verifyRecovery('user-1', 'attempt-2', code, HOUR)).toEqual({ outcome: 'invalid', @@ -91,7 +204,7 @@ describe('verifyRecovery', () => { }); it(`voids the request after ${MAX_RECOVERY_CODE_ATTEMPTS} wrong codes`, async () => { - const code = await startRecovery('user-1', 'email', 'attempt-1'); + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; for (let i = 0; i < MAX_RECOVERY_CODE_ATTEMPTS; i += 1) { expect((await verifyRecovery('user-1', 'attempt-1', wrong(code), HOUR)).outcome).toBe( @@ -104,7 +217,7 @@ describe('verifyRecovery', () => { }); it('refuses an expired code and voids it', async () => { - const code = await startRecovery('user-1', 'email', 'attempt-1'); + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; rows[0].codeExpiresAt = new Date(Date.now() - 1); expect((await verifyRecovery('user-1', 'attempt-1', code, HOUR)).outcome).toBe('invalid'); @@ -112,11 +225,12 @@ describe('verifyRecovery', () => { }); it('refuses a try that lost the race to claim it', async () => { - const code = await startRecovery('user-1', 'email', 'attempt-1'); + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; (AccountRecoveryRequest.update as any).mockResolvedValueOnce([0]); expect((await verifyRecovery('user-1', 'attempt-1', code, HOUR)).outcome).toBe('invalid'); expect(rows[0].state).toBe('awaiting_code'); + expect(failures).toHaveLength(0); }); it('leaves an earlier open request alone until the new one is announced', async () => { @@ -144,7 +258,7 @@ describe('verifyRecovery', () => { it('resumes an open request on a new attempt through the same channel, keeping its clock', async () => { const { request } = await open('attempt-1', 'email'); const completesAt = request.completesAt; - const code = await startRecovery('user-1', 'email', 'attempt-2'); + const code = (await startRecovery('user-1', 'email', 'attempt-2'))!; const result = await verifyRecovery('user-1', 'attempt-2', code, HOUR * 48); @@ -155,7 +269,7 @@ describe('verifyRecovery', () => { it('leaves an open request intact when a resume code is guessed wrong too often', async () => { await open('attempt-1', 'email'); - const code = await startRecovery('user-1', 'email', 'attempt-2'); + const code = (await startRecovery('user-1', 'email', 'attempt-2'))!; for (let i = 0; i < MAX_RECOVERY_CODE_ATTEMPTS; i += 1) { await verifyRecovery('user-1', 'attempt-2', wrong(code), HOUR);