/** * The rules behind test/securityHttp.test.ts, one by one: who is staff (userMeetsRole), when the second * factor counts as passed, and what iapl does with a 2FA plugin it does not recognise. */ import type { Access, Config } from 'payload' import { describe, expect, test, vi } from 'vitest' import type { I18nConfig } from '../src/modules/i18n/types.js' import { adminOrSelfIn } from '../src/modules/access/access.js' import { isAdmin, staffCollectionSlugs, userMeetsRole } from '../src/modules/access/predicates.js' import { clearReportedOrigins, reportRefusedOrigin, requestFromOwnOrigin } from '../src/modules/security/totp/sameOrigin.js' import { ensurePayloadGuarded, guardPayloadAccess, guardTotpEndpoint, requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState, watchPayloadConfig, } from '../src/modules/security/totp/secondFactor.js' import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js' import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js' import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } const fakeTotp = (o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection) /** A payload as the access functions see it: sanitized `admin.user`, the collections by slug, `custom`. */ const payloadOf = (config: Config, adminUser = 'users') => ({ collections: Object.fromEntries((config.collections ?? []).map((c) => [c.slug, { config: c }])), config: { admin: { user: adminUser }, collections: config.collections, custom: config.custom, globals: config.globals }, }) as never const twoAuth = (): Config => ({ collections: [ { slug: 'customers', auth: true, fields: [] }, { slug: 'partners', auth: true, fields: [] }, ], secret: 'x', }) as unknown as Config describe('userMeetsRole: who is staff', () => { test('with roles: the role decides; an account of another auth collection never passes', async () => { const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(twoAuth()) const payload = payloadOf(config) expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true) expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['user'] } }, 'editor')).toBe(false) expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'user')).toBe(false) expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false) expect(userMeetsRole({ payload, user: { collection: 'no-such-collection' } }, 'user')).toBe(false) // a role value on an account of a non-staff collection counts for nothing expect(userMeetsRole({ payload, user: { collection: 'customers', roles: ['admin'] } }, 'user')).toBe(false) expect(userMeetsRole({ payload, user: { roles: ['admin'] } }, 'user')).toBe(false) // no collection at all expect(userMeetsRole({ payload, user: null }, 'user')).toBe(false) }) test('without `access`: every account of the panel collection passes, other auth collections do not', async () => { const config = await iapl({ i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config) const payload = payloadOf(config) expect(staffCollectionSlugs(payload)).toEqual(['users']) expect(userMeetsRole({ payload, user: { collection: 'users' } }, 'admin')).toBe(true) expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false) }) test('access.staffCollections names more staff collections, on purpose', async () => { const config = await iapl({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: false })(twoAuth()) const payload = payloadOf(config) expect(staffCollectionSlugs(payload)).toEqual(['users', 'partners']) expect(userMeetsRole({ payload, user: { collection: 'partners' } }, 'admin')).toBe(true) // no roles field there: all equal expect(userMeetsRole({ payload, user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false) expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false) }) test('without a payload: the staff collections of the config iapl built last; only a held role counts', async () => { await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config) expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false) expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true) expect(userMeetsRole({ user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false) expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) // isAdmin(req.user) in a hook expect(isAdmin({ collection: 'users', roles: ['admin'] })).toBe(true) }) }) describe('adminOrSelfIn', () => { const run = (fn: Access, user: unknown) => fn({ req: { payload: { config: { admin: { user: 'users' } } }, user } } as never) test('"self" is an account of that collection only', () => { const access = adminOrSelfIn('users') expect(run(access, { id: 5, collection: 'users', roles: ['user'] })).toEqual({ id: { equals: 5 } }) expect(run(access, { id: 5, collection: 'customers' })).toBe(false) // same id, other collection expect(run(access, { id: 1, collection: 'users', roles: ['admin'] })).toBe(true) expect(run(access, null)).toBe(false) }) }) describe('secondFactorPassed', () => { const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } } as never const cases: [string, unknown, boolean][] = [ ['no user', null, true], ['password and code (the totp strategy)', { _strategy: 'totp', collection: 'users', hasTotp: true }, true], ['API key', { _strategy: 'api-key', collection: 'users', hasTotp: true }, true], ['TOTP not set up yet, setup not required (requireSetup: false)', { _strategy: 'local-jwt', collection: 'users', hasTotp: false }, true], ['password only', { _strategy: 'local-jwt', collection: 'users', hasTotp: true }, false], ['a user object without the fields the check knows (fail closed)', { collection: 'users' }, false], ['an unknown strategy name (fail closed)', { _strategy: 'two-factor', collection: 'users', hasTotp: true }, false], ['an account of another auth collection', { _strategy: 'local-jwt', collection: 'customers' }, true], ['a user object that does not say its collection (fail closed)', { _strategy: 'totp', hasTotp: true }, false], ['`hasTotp` false although the record carries a secret (the package\'s lookup failed): refused', { _strategy: 'local-jwt', collection: 'users', hasTotp: false, totpSecret: 'JBSWY3DPEHPK3PXP' }, false], ] test.each(cases)('%s', (_, user, expected) => { expect(secondFactorPassed({ payload, user })).toBe(expected) }) describe('setup required (the default)', () => { const HOUR = 3_600_000 const required = (extra: object = {}) => ({ config: { custom: { ipal: { twoFactor: { collection: 'users', requireSetup: true, setupWindowMs: 72 * HOUR, ...extra } } } } }) as never const fresh = { _strategy: 'local-jwt', collection: 'users', email: 'new@example.com', hasTotp: false, totpSetupFrom: new Date(Date.now() - HOUR).toISOString() } const late = { ...fresh, totpSetupFrom: new Date(Date.now() - 73 * HOUR).toISOString() } test('an account without TOTP is refused, inside the window and after it', () => { expect(secondFactorPassed({ payload: required(), user: fresh })).toBe(false) expect(secondFactorPassed({ payload: required(), user: late })).toBe(false) expect(twoFactorSetupState({ payload: required(), user: fresh })).toBe('open') expect(twoFactorSetupState({ payload: required(), user: late })).toBe('closed') expect(twoFactorSetupDeadline({ payload: required(), user: fresh })!.getTime()).toBeGreaterThan(Date.now()) }) test('no window (windowHours: false / 0): never closed, still refused until set up', () => { const noWindow = required({ setupWindowMs: 0 }) expect(twoFactorSetupState({ payload: noWindow, user: late })).toBe('open') expect(twoFactorSetupDeadline({ payload: noWindow, user: late })).toBeNull() expect(secondFactorPassed({ payload: noWindow, user: late })).toBe(false) }) test('an account without a recorded start (before the first start after the upgrade) is open, not closed', () => { const legacy = { _strategy: 'local-jwt', collection: 'users', hasTotp: false } expect(twoFactorSetupState({ payload: required(), user: legacy })).toBe('open') expect(secondFactorPassed({ payload: required(), user: legacy })).toBe(false) }) test('the project exempts a service account on purpose', () => { const exempt = required({ exempt: ({ user }: { user: { email?: string } }) => user.email === 'bot@example.com' }) const bot = { ...late, email: 'bot@example.com' } expect(secondFactorPassed({ payload: exempt, user: bot })).toBe(true) expect(twoFactorSetupState({ payload: exempt, user: bot })).toBe('exempt') expect(secondFactorPassed({ payload: exempt, user: late })).toBe(false) }) test('an API key passes whatever the setup state; the set-up and other-collection cases are unchanged', () => { expect(secondFactorPassed({ payload: required(), user: { ...late, _strategy: 'api-key' } })).toBe(true) expect(secondFactorPassed({ payload: required(), user: { _strategy: 'totp', collection: 'users', hasTotp: true } })).toBe(true) expect(secondFactorPassed({ payload: required(), user: { _strategy: 'local-jwt', collection: 'customers' } })).toBe(true) expect(twoFactorSetupState({ payload: required(), user: { collection: 'customers' } })).toBe('not-applicable') expect(twoFactorSetupState({ payload: required(), user: { collection: 'users', hasTotp: true } })).toBe('set-up') }) test('resolveRequireSetup: the option → what the guard reads', () => { expect(resolveRequireSetup(undefined)).toEqual({ requireSetup: true, setupWindowMs: 72 * HOUR }) expect(resolveRequireSetup({ windowHours: 24 })).toEqual({ requireSetup: true, setupWindowMs: 24 * HOUR }) expect(resolveRequireSetup({ windowHours: false })).toEqual({ requireSetup: true, setupWindowMs: 0 }) expect(resolveRequireSetup({ windowHours: 0 })).toEqual({ requireSetup: true, setupWindowMs: 0 }) expect(resolveRequireSetup(false)).toEqual({ requireSetup: false, setupWindowMs: 0 }) }) test('the setup endpoint refuses an account whose window has passed', async () => { const inner = () => Promise.resolve(Response.json({ ok: true })) const endpoint = guardTotpEndpoint({ handler: inner as (req: never) => Promise, path: '/setup-totp' }, 'users') expect((await endpoint.handler({ payload: required(), user: fresh } as never)).status).toBe(200) expect((await endpoint.handler({ payload: required(), user: late } as never)).status).toBe(403) }) }) test('2FA off: everyone passes', () => { expect(secondFactorPassed({ payload: { config: {} } as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } })).toBe(true) }) test('requireSecondFactor wraps once and keeps the inner rule', () => { const inner: Access = ({ req }) => Boolean((req.user as { ok?: boolean } | null)?.ok) const wrapped = requireSecondFactor(inner) expect(requireSecondFactor(wrapped)).toBe(wrapped) const call = (user: unknown) => wrapped({ req: { payload, user } } as never) expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true, ok: true })).toBe(true) expect(call({ _strategy: 'totp', collection: 'users', hasTotp: true })).toBe(false) expect(call({ _strategy: 'local-jwt', collection: 'users', hasTotp: true, ok: true })).toBe(false) }) }) describe('iapl and the 2FA plugin', () => { const passwordOnly = { id: 1, _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] } const verified = { ...passwordOnly, _strategy: 'totp' } test('every collection and global in the config is guarded, whenever it was added', async () => { const config = await iapl({ access: { authCollection: 'users' }, consentLog: true, cookieScanner: { crawl: true }, forms: {}, i18n, stats: true, twoFactor: { issuer: 'A', plugin: fakeTotp as never }, })({ collections: [{ slug: 'pages', fields: [] }], globals: [{ slug: 'own', fields: [] }], secret: 'x' } as unknown as Config) const payload = payloadOf(config) const open: string[] = [] const check = (kind: string, slug: string, access: Record | undefined, ops: string[]) => { for (const op of ops) { const fn = access?.[op] as ((a: unknown) => unknown) | undefined if (!fn || fn({ req: { payload, user: passwordOnly } }) !== false) {open.push(`${kind} ${slug}.${op}`)} } } for (const c of config.collections ?? []) {check('collection', c.slug, c.access as never, ['create', 'delete', 'read', 'readVersions', 'unlock', 'update'])} for (const g of config.globals ?? []) {check('global', g.slug, g.access as never, ['read', 'readDrafts', 'readVersions', 'update'])} expect(open).toEqual([]) // and a verified admin still gets in const integrations = config.globals!.find((g) => g.slug === 'site-integrations')! expect((integrations.access!.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true) }) test('the sweep guards everything a later plugin or Payload itself added — no exception by name or prefix', () => { const late = { slug: 'late', access: {} as Record } const prefixed = { slug: 'payload-vault', access: {} as Record } // a plugin's collection, e.g. payload-mcp-api-keys const internal = { slug: 'payload-preferences', access: {} as Record } const loggedIn = ({ req }: { req: { user?: unknown } }) => Boolean(req.user) // Payload's defaultAccess const jobs = { access: { cancel: loggedIn, queue: loggedIn, run: loggedIn } as Record } const payload = { config: { collections: [late, prefixed, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [{ slug: 'payload-jobs-stats' }], jobs } } as never expect(guardPayloadAccess(payload)).toEqual(['late', 'payload-vault', 'payload-preferences', 'payload-jobs-stats', 'jobs']) for (const entity of [late, prefixed, internal]) { expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false) expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true) } // the job queue's rules as Payload filled them in (3.94.1: all three "a logged-in user"): kept, plus // "not while the second factor is owed" const job = (op: string, user: unknown) => (jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user } }) for (const op of ['run', 'queue', 'cancel']) { expect([op, job(op, null), job(op, passwordOnly), job(op, verified)]).toEqual([op, false, false, true]) } // a rule the project set is kept as it is; a rule nobody set is not invented (Payload fills it in) const own = { access: { queue: () => true } as Record } guardPayloadAccess({ config: { collections: [], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [], jobs: own } } as never) const ownQueue = (user: unknown) => (own.access.queue as (a: unknown) => unknown)({ req: { payload, user } }) expect([ownQueue(null), ownQueue(passwordOnly), ownQueue(verified)]).toEqual([true, false, true]) expect(own.access.run).toBeUndefined() expect(own.access.cancel).toBeUndefined() expect(guardPayloadAccess(payload)).toEqual([]) // nothing left to do the second time expect(ensurePayloadGuarded(payload)).toEqual([]) expect(ensurePayloadGuarded(payload)).toBeNull() // this config object was done }) test('a config swapped onto the instance (dev reload) is adopted at once, before any request', () => { const adopted: unknown[] = [] const instance = { config: { name: 'first' } } as never as { config: { name: string } } watchPayloadConfig(instance as never, (p) => adopted.push((p as never as { config: { name: string } }).config.name)) instance.config = { name: 'second' } expect(adopted).toEqual(['second']) expect(instance.config.name).toBe('second') expect({ ...instance }.config.name).toBe('second') // still an ordinary enumerable property to readers }) test('a 2FA plugin without the parts the guard relies on stops the start', async () => { const unknown = () => (c: Config) => c const run = (guard?: false) => iapl({ i18n, twoFactor: { issuer: 'A', plugin: unknown as never, ...(guard === false ? { guard } : {}) } })({ collections: [], secret: 'x' } as unknown as Config) await expect(run()).rejects.toThrow(/did not add the `totpSecret` field, the `hasTotp` field, the `totp` auth strategy/) // twoFactor.guard: false = the package alone, as before const config = await run(false) expect((config.custom as { ipal?: { twoFactor?: unknown } } | undefined)?.ipal?.twoFactor).toBeUndefined() }) test('per-entity opt-out: the package key and IAPL\'s key, operation by operation', async () => { const config = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({ collections: [ { slug: 'a', custom: { totp: { disableAccessWrapper: { read: true } } }, fields: [] }, { slug: 'b', custom: { ipal: { secondFactor: false } }, fields: [] }, ], globals: [{ slug: 'g', custom: { ipal: { secondFactor: { read: false } } }, fields: [] }], secret: 'x', } as unknown as Config) const payload = payloadOf(config) // an operation without a function = Payload's default: any logged-in account const call = (access: unknown, op: string) => { const fn = (access as Record unknown) | undefined> | undefined)?.[op] return fn ? fn({ req: { payload, user: passwordOnly } }) : true } const col = (slug: string) => config.collections!.find((c) => c.slug === slug)!.access expect(call(col('a'), 'read')).toBe(true) expect(call(col('a'), 'update')).toBe(false) // opted out of everything and no rule of its own: left exactly as the project wrote it (Payload's default applies) expect(col('b')).toBeUndefined() const g = config.globals!.find((x) => x.slug === 'g')!.access expect(call(g, 'read')).toBe(true) expect(call(g, 'update')).toBe(false) // IAPL's key reaches the package in its own key, so the package leaves the operation alone too expect((config.globals!.find((x) => x.slug === 'g')!.custom as { totp: unknown }).totp).toEqual({ disableAccessWrapper: { read: true } }) }) test("the 2FA package's endpoints: accounts of the 2FA collection only; management needs the second factor", async () => { const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users' } } } } } const inner = () => Promise.resolve(Response.json({ ok: true })) const call = async (path: string, user: unknown) => { const endpoint = guardTotpEndpoint({ handler: inner as (req: never) => Promise, path }, 'users') return (await endpoint.handler({ payload, user } as never)).status } const customer = { id: 1, collection: 'customers' } const newcomer = { id: 2, _strategy: 'local-jwt', collection: 'users', hasTotp: false } for (const path of ['/setup-totp', '/verify-totp', '/remove-totp', '/admin/reset-user-totp', '/some-future-endpoint']) { expect([path, await call(path, customer)]).toEqual([path, 403]) expect([path, await call(path, null)]).toEqual([path, 200]) // no user: the package answers itself } expect(await call('/setup-totp', newcomer)).toBe(200) expect(await call('/verify-totp', passwordOnly)).toBe(200) expect(await call('/remove-totp', passwordOnly)).toBe(403) expect(await call('/admin/reset-user-totp', passwordOnly)).toBe(403) expect(await call('/some-future-endpoint', passwordOnly)).toBe(403) expect(await call('/admin/reset-user-totp', verified)).toBe(200) }) test('verify attempts are limited per account, and the limit can be changed or switched off', async () => { clearVerifyLimits() const req = (id: unknown) => ({ i18n: undefined, payload: { logger: { warn: () => {} } }, user: { id, collection: 'users' } }) as never const limit = buildVerifyLimit('users') // 5 wrong codes in 10 minutes for (let i = 0; i < 5; i++) { const attempt = req(1) expect(await limit(attempt)).toBeNull() await limit.settle(attempt, false) // a wrong code (1.17.1: a right one gives its place back) } const refused = (await limit(req(1)))! expect(refused.status).toBe(429) expect(Number(refused.headers.get('retry-after'))).toBeGreaterThan(0) expect(((await refused.json()) as { message: string }).message).toMatch(/Too many codes/) expect(await limit(req(2))).toBeNull() // another account is not affected expect(await limit({ ...(req(1) as object), user: null } as never)).toBeNull() // no session: the package refuses by itself const two = buildVerifyLimit('admins', { max: 2, windowMinutes: 1 }) expect([await two(req(1)), await two(req(1))]).toEqual([null, null]) expect((await two(req(1)))!.status).toBe(429) // wired by default; twoFactor.verifyLimit: false leaves the package's endpoint as it is const base = () => ({ collections: [], endpoints: [], secret: 'x' }) as unknown as Config const withEndpoint = (o: { collection: string }) => (c: Config) => ({ ...withTotpParts(c, o.collection), endpoints: [...(c.endpoints ?? []), { handler: () => Response.json({ ok: false }), method: 'post' as const, path: '/verify-totp' }] }) const call = async (config: Config, n: number) => { const endpoint = config.endpoints!.find((e) => e.path === '/verify-totp')! let last = 0 for (let i = 0; i < n; i++) {last = (await endpoint.handler(req(77))).status} return last } clearVerifyLimits() expect(await call(await iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never } })(base()), 6)).toBe(429) clearVerifyLimits() expect(await call(await iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).toBe(200) }) // M1 (R3-2): the count is also kept in the database, so a restart or a second instance does not reset it. describe('the verify limit: stored count', () => { const store = () => { const data = new Map() return { data, get: vi.fn(async (k: string) => data.get(k) ?? null), set: vi.fn(async (k: string, v: unknown) => void data.set(k, v)) } } const req = (kv: unknown, id: unknown = 1) => ({ i18n: undefined, payload: { kv, logger: { warn: vi.fn() } }, user: { id, collection: 'users' } }) as never test('a restart (the memory is empty again) does not hand out new attempts', async () => { clearVerifyLimits() const kv = store() const limit = buildVerifyLimit('users') for (let i = 0; i < 3; i++) {expect(await limit(req(kv))).toBeNull()} clearVerifyLimits() // the process restarted, or this is another instance expect(await limit(req(kv))).toBeNull() // 4th expect(await limit(req(kv))).toBeNull() // 5th expect((await limit(req(kv)))!.status).toBe(429) // five attempts; the refused sixth compared nothing and gave its place back (1.17.1) expect(kv.data.get(verifyLimitKey('users', '1'))).toMatchObject({ count: 5 }) // and a restart while refused keeps refusing, with the stored window's Retry-After clearVerifyLimits() const again = (await limit(req(kv)))! expect(again.status).toBe(429) expect(Number(again.headers.get('retry-after'))).toBeGreaterThan(0) }) test('a burst of parallel attempts cannot slip under the limit', async () => { clearVerifyLimits() const kv = store() const limit = buildVerifyLimit('users') const answers = await Promise.all(Array.from({ length: 40 }, () => limit(req(kv)))) expect(answers.filter((a) => a === null)).toHaveLength(5) }) test('when the window is over, the stored count starts again', async () => { clearVerifyLimits() const kv = store() kv.data.set(verifyLimitKey('users', '1'), { count: 99, resetAt: Date.now() - 1000 }) expect(await buildVerifyLimit('users')(req(kv))).toBeNull() expect(kv.data.get(verifyLimitKey('users', '1'))).toMatchObject({ count: 1 }) }) test('a failing store never opens the gate: the memory count still decides', async () => { clearVerifyLimits() const broken = { get: vi.fn(async () => { throw new Error('db down') }), set: vi.fn() } const limit = buildVerifyLimit('users') const request = req(broken) for (let i = 0; i < 5; i++) {expect(await limit(request)).toBeNull()} expect((await limit(request))!.status).toBe(429) // no store at all (an older Payload without payload.kv): the same clearVerifyLimits() const none = buildVerifyLimit('users') for (let i = 0; i < 5; i++) {expect(await none(req(undefined))).toBeNull()} expect((await none(req(undefined)))!.status).toBe(429) }) test("store: 'memory' leaves the database alone", async () => { clearVerifyLimits() const kv = store() const limit = buildVerifyLimit('users', { store: 'memory' }) for (let i = 0; i < 6; i++) {await limit(req(kv))} expect(kv.get).not.toHaveBeenCalled() expect(kv.set).not.toHaveBeenCalled() }) }) // M1 (R3-2): an attempt a browser marks as coming from another origin is refused before it is counted. describe('2FA verify and setup only from the own origin', () => { const req = (headers: Record, config: Record = {}, url = 'http://internal:3000/api/verify-totp') => ({ headers: new Headers(headers), payload: { config }, url }) test.each([ ['no Origin, no Sec-Fetch-Site (a script, curl, a server)', {}, {}, true], ['Origin = the host the request came in on', { host: 'site.example', origin: 'https://site.example' }, {}, true], ['Origin = the forwarded host (behind a proxy)', { host: 'internal:3000', origin: 'https://site.example', 'x-forwarded-host': 'site.example' }, {}, true], ['Origin = serverURL', { host: 'internal:3000', origin: 'https://site.example' }, { serverURL: 'https://site.example' }, true], ['Origin in csrf', { origin: 'https://app.example.com' }, { csrf: ['https://app.example.com'] }, true], ['Origin in cors', { origin: 'https://app.example.com' }, { cors: { origins: ['https://app.example.com'] } }, true], ['a sibling subdomain', { host: 'site.example', origin: 'https://blog.site.example' }, { serverURL: 'https://site.example' }, false], ['another site', { host: 'site.example', origin: 'https://evil.example' }, {}, false], ['the same host on another port', { host: 'site.example', origin: 'https://site.example:8443' }, {}, false], // a proxy that writes the default port out ['the forwarded host with :443 for an https origin', { host: 'internal:3000', origin: 'https://site.example', 'x-forwarded-host': 'site.example:443' }, {}, true], ['the host with :80 for an http origin', { host: 'site.example:80', origin: 'http://site.example' }, {}, true], ['Origin with the default port written out', { host: 'site.example', origin: 'https://site.example:443' }, {}, true], [':443 is not the default of http', { host: 'site.example:443', origin: 'http://site.example' }, {}, false], [':80 is not the default of https', { host: 'site.example:80', origin: 'https://site.example' }, {}, false], // nginx's plain proxy_pass: Host rewritten, no X-Forwarded-Host, no serverURL — the site's own page is refused (and reported, below) ['a proxy that hides the address, nothing configured', { host: 'upstream:3000', origin: 'https://site.example' }, {}, false], ['Origin: null (a sandboxed page)', { host: 'site.example', origin: 'null' }, {}, false], ['Sec-Fetch-Site: same-origin without Origin', { 'sec-fetch-site': 'same-origin' }, {}, true], ['Sec-Fetch-Site: same-site (a sibling subdomain) without Origin', { 'sec-fetch-site': 'same-site' }, {}, false], ['Sec-Fetch-Site: cross-site without Origin', { 'sec-fetch-site': 'cross-site' }, {}, false], ])('%s', (_name, headers, config, expected) => { expect(requestFromOwnOrigin(req(headers as Record, config))).toBe(expected) }) test('a refusal is never silent: one line per origin, with the ways to allow it', () => { clearReportedOrigins() const warn = vi.fn() const hidden = { headers: new Headers({ host: 'upstream:3000', origin: 'https://site.example' }), payload: { config: {}, logger: { warn } }, url: 'http://upstream:3000/api/verify-totp' } expect(reportRefusedOrigin(hidden)).toBe(true) expect(reportRefusedOrigin(hidden)).toBe(false) // once per origin expect(warn).toHaveBeenCalledTimes(1) const line = warn.mock.calls[0][0] as string expect(line).toContain('origin "https://site.example"') expect(line).toContain('host upstream:3000') expect(line).toMatch(/serverURL/) expect(line).toMatch(/sameOrigin: \{ origins: \['https:\/\/site\.example'\] \}/) expect(line).toMatch(/X-Forwarded-Host/) // another origin gets its own line; a request without Origin is named by what the browser said expect(reportRefusedOrigin({ ...hidden, headers: new Headers({ origin: 'https://evil.example' }) })).toBe(true) expect(reportRefusedOrigin({ ...hidden, headers: new Headers({ 'sec-fetch-site': 'cross-site' }) })).toBe(true) expect(warn.mock.calls[2][0]).toContain('sec-fetch-site: cross-site') // the log cannot be flooded with made-up origins for (let i = 0; i < 200; i++) {reportRefusedOrigin({ ...hidden, headers: new Headers({ origin: `https://n${i}.example` }) })} expect(warn.mock.calls.length).toBeLessThanOrEqual(50) clearReportedOrigins() }) test('twoFactor.sameOrigin.origins adds an origin', () => { const other = req({ host: 'site.example', origin: 'https://panel.example.org' }) expect(requestFromOwnOrigin(other)).toBe(false) expect(requestFromOwnOrigin(other, ['https://panel.example.org'])).toBe(true) }) test('wired by default on verify and setup, before the limit; not on other endpoints; sameOrigin: false turns it off', async () => { const handler = vi.fn(() => Response.json({ ok: false })) // wrong codes: they stay counted (a right one gives its place back) const warn = vi.fn() clearReportedOrigins() const withEndpoints = (o: { collection: string }) => (c: Config) => ({ ...withTotpParts(c, o.collection), endpoints: [...(c.endpoints ?? []), ...['/verify-totp', '/setup-totp', '/remove-totp'].map((path) => ({ handler, method: 'post' as const, path }))], }) const build = (twoFactor: Record = {}) => iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config) const call = async (config: Config, path: string, headers: Record, user: Record) => (await config.endpoints!.find((e) => e.path === path)!.handler({ headers: new Headers(headers), i18n: undefined, payload: { config, logger: { warn } }, url: 'https://site.example/api' + path, user: { id: 5, collection: 'users', ...user } } as never)).status const elsewhere = { host: 'site.example', origin: 'https://blog.site.example' } const own = { host: 'site.example', origin: 'https://site.example' } const owes = { _strategy: 'local-jwt', hasTotp: true } const fresh = { _strategy: 'local-jwt', hasTotp: false, totpSetupFrom: new Date().toISOString() } clearVerifyLimits() const config = await build() // twenty attempts from elsewhere: all refused, none counted for (let i = 0; i < 20; i++) {expect(await call(config, '/verify-totp', elsewhere, owes)).toBe(403)} expect(handler).not.toHaveBeenCalled() // …and said in the log, once, with the origin and how to allow it expect(warn.mock.calls.filter(([line]) => String(line).includes('blog.site.example'))).toHaveLength(1) for (let i = 0; i < 5; i++) {expect(await call(config, '/verify-totp', own, owes)).toBe(200)} // the owner still has all five expect(await call(config, '/verify-totp', own, owes)).toBe(429) expect(await call(config, '/setup-totp', elsewhere, fresh)).toBe(403) expect(await call(config, '/setup-totp', own, fresh)).toBe(200) // other endpoints of the package are not part of this rule (they need the second factor instead) expect(await call(config, '/remove-totp', elsewhere, { _strategy: 'totp', hasTotp: true })).toBe(200) clearVerifyLimits() const off = await build({ sameOrigin: false }) expect(await call(off, '/verify-totp', elsewhere, owes)).toBe(200) clearVerifyLimits() const listed = await build({ sameOrigin: { origins: ['https://blog.site.example'] } }) expect(await call(listed, '/verify-totp', elsewhere, owes)).toBe(200) }) }) test('staff collections outside the 2FA collection are named in a warning at start', async () => { const config = await iapl({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({ ...twoAuth(), admin: { user: 'users' }, } as Config) const warnings: string[] = [] const auth = (slug: string) => ({ slug, auth: true, custom: { ipalAccounts: { slug, staff: true } }, fields: [] }) const payload = { collections: {}, config: { admin: { user: 'users' }, collections: [auth('partners'), auth('users')], custom: config.custom, globals: [] }, count: () => ({ totalDocs: 0 }), find: () => ({ docs: [] }), findGlobal: () => ({}), logger: { info: () => {}, warn: (m: string) => warnings.push(m) }, updateGlobal: () => ({}), } await Promise.resolve(config.onInit!(payload as never)).catch(() => {}) // later onInit steps need a real database expect(warnings.join('\n')).toMatch(/2FA covers "users" only\. Staff accounts of "partners"/) }) test('setup required: on by default, with the field, the hook, the reset endpoint and the notices; every part can be changed', async () => { const base = () => ({ collections: [], secret: 'x' }) as unknown as Config const on = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })(base()) const guard = (c: Config) => (c.custom as { ipal: { twoFactor: Record } }).ipal.twoFactor expect(guard(on)).toMatchObject({ collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 }) const users = on.collections!.find((c) => c.slug === 'users')! expect(users.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true) expect(users.hooks?.beforeChange?.length).toBe(1) expect(on.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true) expect(JSON.stringify(on.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert') const custom = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: 24 } } })(base()) expect(guard(custom).setupWindowMs).toBe(24 * 3_600_000) const off = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base()) expect(guard(off)).toMatchObject({ requireSetup: false }) // the data field stays whenever 2FA is on: the schema must not depend on the switch (SQL would drop the column) const offUsers = off.collections!.find((c) => c.slug === 'users')! expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true) expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus')).toBe(false) expect(offUsers.hooks?.beforeChange?.length ?? 0).toBe(0) // no stamping while the mode is off expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert') const guardOff = await iapl({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never } })(base()) expect(guardOff.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true) // each part of the mode has its own switch const has = (c: Config) => ({ dashboard: JSON.stringify(c.admin?.components?.beforeDashboard ?? []).includes('TwoFactorAlert'), setupNotice: JSON.stringify(c.admin?.components?.providers ?? []).includes('"requireSetup":true'), status: c.collections!.find((x) => x.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'), }) // fakeTotp registers no provider, so the setup notice is checked with the real package in test/safeBack.test.ts expect(has(on)).toMatchObject({ dashboard: true, status: true }) const noDash = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { dashboardNotice: false } } })(base()) expect(has(noDash)).toMatchObject({ dashboard: false, status: true }) const noStatus = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { statusField: false } } })(base()) expect(has(noStatus)).toMatchObject({ dashboard: true, status: false }) expect(guard(noStatus)).toMatchObject({ requireSetup: true }) // the lock itself is unchanged expect(off.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true) // an admin can still reset a lost phone // 2FA off: nothing of this exists const none = await iapl({ i18n, twoFactor: false })(base()) expect(none.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(false) expect(none.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false) }) test.each([['24'], [-1], [Number.NaN], [Number.POSITIVE_INFINITY], [true], [null]])('requireSetup.windowHours %s stops the start (a typo must not mean "no limit")', async (windowHours) => { await expect(Promise.resolve().then(() => iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours must be a number/) // also when IAPL's own check is off: a wrong value is never silently accepted await expect(Promise.resolve().then(() => iapl({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours/) expect(() => resolveRequireSetup({ windowHours: windowHours as never })).toThrow(/windowHours/) }) test('requireSetup: null is the default, like leaving it out', async () => { const config = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: null as never } })({ collections: [], secret: 'x' } as unknown as Config) expect((config.custom as { ipal: { twoFactor: Record } }).ipal.twoFactor).toMatchObject({ requireSetup: true, setupWindowMs: 72 * 3_600_000 }) expect(JSON.stringify(config.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert') expect(resolveRequireSetup(null as never)).toEqual({ requireSetup: true, setupWindowMs: 72 * 3_600_000 }) }) test('windowHours: a number, 0 or false still work', () => { expect(resolveRequireSetup({ windowHours: 1.5 }).setupWindowMs).toBe(1.5 * 3_600_000) expect(resolveRequireSetup({ windowHours: 0 }).setupWindowMs).toBe(0) expect(resolveRequireSetup({ windowHours: false }).setupWindowMs).toBe(0) }) // exempt lets an account in on its password: anything but a plain `true` must never do that. describe('requireSetup.exempt', () => { const user = { _strategy: 'local-jwt', collection: 'users', hasTotp: false, totpSetupFrom: new Date().toISOString() } const payloadWith = (exempt: unknown) => ({ config: { custom: { ipal: { twoFactor: { collection: 'users', ...resolveRequireSetup({ exempt: exempt as never }) } } } } }) test('an async function stops the start', async () => { expect(() => resolveRequireSetup({ exempt: (async () => false) as never })).toThrow(/must not be async/) await expect(Promise.resolve().then(() => iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { exempt: (async () => true) as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/must not be async/) expect(() => resolveRequireSetup({ exempt: 'yes' as never })).toThrow(/must be a function/) }) test.each([ ['a Promise from a plain function', () => Promise.resolve(false)], ['a rejecting Promise', () => Promise.reject(new Error('x'))], ['a string', () => 'yes'], ['a number', () => 1], ['an object', () => ({})], ['an error', () => { throw new Error('boom') }], ['false', () => false], ['undefined', () => undefined], ])('%s exempts nobody', (_name, exempt) => { const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) const payload = payloadWith(exempt) expect(secondFactorPassed({ payload: payload as never, user })).toBe(false) expect(twoFactorSetupState({ payload: payload as never, user })).toBe('open') error.mockRestore() }) test('only true exempts; a wrong answer is logged', () => { const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) const yes = payloadWith(() => true) expect(secondFactorPassed({ payload: yes as never, user })).toBe(true) expect(twoFactorSetupState({ payload: yes as never, user })).toBe('exempt') expect(error).not.toHaveBeenCalled() const odd = strictExempt(() => Symbol('yes') as never) expect(odd({ user })).toBe(false) expect(odd({ user })).toBe(false) expect(error).toHaveBeenCalledTimes(1) // each kind of wrong answer once, not on every request expect(String(error.mock.calls[0]?.[0])).toMatch(/exempt returned a symbol.*NOT exempt/) error.mockRestore() }) test('a guard config built without resolveRequireSetup is strict too', () => { const payload = { config: { custom: { ipal: { twoFactor: { collection: 'users', exempt: () => Promise.resolve(true), requireSetup: true } } } } } expect(secondFactorPassed({ payload: payload as never, user })).toBe(false) expect(twoFactorSetupState({ payload: payload as never, user })).toBe('open') }) }) // Postgres / SQLite without the migration: the start-up step is the first to hit the missing column. It must not // stop the site, and must say what the real consequence is (every login fails), not only "no window yet". test('a missing column at start: no throw, and the log says nobody can log in', async () => { const { backfillSetupFrom } = await import('../src/modules/security/totp/setupRequired.js') const fake = (name: string, message: string) => { const logger = { error: vi.fn(), warn: vi.fn() } return { logger, payload: { count: async () => { throw new Error(message) }, db: { name }, logger } } } const pg = fake('postgres', 'column users.totp_setup_from does not exist') expect(await backfillSetupFrom(pg.payload as never, 'users')).toBe(0) expect(String(pg.logger.error.mock.calls[0]?.[0])).toMatch(/NOBODY CAN LOG IN.*migrate/s) const sqlite = fake('sqlite', 'no such column: totp_setup_from') await backfillSetupFrom(sqlite.payload as never, 'users') expect(sqlite.logger.error).toHaveBeenCalledTimes(1) // any other failure — also on a SQL adapter — is not "the column is missing" for (const other of [fake('mongoose', 'connection lost'), fake('postgres', 'connect ECONNREFUSED 127.0.0.1:5432'), fake('sqlite', 'database is locked'), fake('postgres', 'relation "users" does not exist')]) { await backfillSetupFrom(other.payload as never, 'users') expect(other.logger.error).not.toHaveBeenCalled() expect(other.logger.warn).toHaveBeenCalledTimes(1) } expect(String(pg.logger.error.mock.calls[0]?.[0])).toMatch(/prodMigrations.*not in a pre-deployment command/s) // What the SQL adapters really throw: Drizzle's "Failed query: …" with the database's own words in `cause`. const wrapped = (name: string, cause: unknown, message = 'Failed query: select count(*) from "users" where …') => { const logger = { error: vi.fn(), warn: vi.fn() } return { logger, payload: { count: async () => { throw Object.assign(new Error(message), { cause }) }, db: { name }, logger } } } for (const real of [ wrapped('postgres', Object.assign(new Error('column users.totp_setup_from does not exist'), { code: '42703' })), wrapped('sqlite', new Error('SQLITE_ERROR: no such column: users.totp_setup_from')), wrapped('sqlite', { message: 'no such column: totp_setup_from' }), // a plain object as the cause wrapped('postgres', Object.assign(new Error('driver'), { cause: new Error('column "totp_setup_from" does not exist') })), // two levels down ]) { await backfillSetupFrom(real.payload as never, 'users') expect(real.logger.warn).not.toHaveBeenCalled() expect(String(real.logger.error.mock.calls[0]?.[0])).toMatch(/NOBODY CAN LOG IN/) expect(String(real.logger.error.mock.calls[0]?.[0])).toMatch(/totp_setup_from/) // the database's own words are in the line } for (const other of [ wrapped('postgres', Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:5432'), { code: 'ECONNREFUSED' })), wrapped('sqlite', new Error('SQLITE_BUSY: database is locked')), wrapped('postgres', new Error('relation "users" does not exist')), ]) { await backfillSetupFrom(other.payload as never, 'users') expect(other.logger.error).not.toHaveBeenCalled() expect(other.logger.warn).toHaveBeenCalledTimes(1) } // a cause that points at itself does not loop const loop = new Error('Failed query') as { cause?: unknown } & Error loop.cause = loop const looping = { logger: { error: vi.fn(), warn: vi.fn() }, payload: {} as Record } looping.payload = { count: async () => { throw loop }, db: { name: 'postgres' }, logger: looping.logger } await backfillSetupFrom(looping.payload as never, 'users') expect(looping.logger.warn).toHaveBeenCalledTimes(1) }) // The reset removes a second factor: by default only a session that entered its own TOTP code may do it. describe('the reset endpoint: who may use it', () => { const run = async (reqUser: Record, options: Parameters[1] = {}, guardExtra: Record = {}) => { const update = vi.fn(async () => ({})) const payload = { collections: { users: { config: { auth: { useSessions: true } } } }, config: { collections: [{ slug: 'users', auth: true, fields: [{ name: 'roles', type: 'select' }] }], custom: { ipal: { staffCollections: ['users'], twoFactor: { collection: 'users', requireSetup: true, ...guardExtra } } } }, logger: { error: () => undefined, info: () => undefined }, update, } const req = { i18n: { t: (k: string) => k }, json: async () => ({ userId: '7' }), payload, user: reqUser } const res = await buildTwoFactorResetEndpoint('users', options).handler(req as never) return { status: res.status, update } } const admin = { id: 1, collection: 'users', hasTotp: true, roles: ['admin'] } test('a session that entered its code: allowed; the account loses its secret AND its sessions', async () => { const { status, update } = await run({ ...admin, _strategy: 'totp' }) expect(status).toBe(200) const data = (update.mock.calls[0] as unknown as [{ data: Record; id: string }])[0] expect(data.id).toBe('7') expect(data.data).toMatchObject({ sessions: [], totpSecret: null }) expect(typeof data.data.totpSetupFrom).toBe('string') }) test('an exempt admin on its password, and an API-key admin: refused by default', async () => { const exempt = { exempt: () => true } expect((await run({ ...admin, _strategy: 'local-jwt', hasTotp: false }, {}, exempt)).status).toBe(403) expect((await run({ ...admin, _strategy: 'api-key' })).status).toBe(403) expect((await run({ ...admin, _strategy: 'local-jwt' })).status).toBe(403) // password only }) test('resetAccess loosens it for those sessions — never for one that still owes its code', async () => { const access = () => true expect((await run({ ...admin, _strategy: 'api-key' }, { access })).status).toBe(200) expect((await run({ ...admin, _strategy: 'local-jwt', hasTotp: false }, { access }, { exempt: () => true })).status).toBe(200) expect((await run({ ...admin, _strategy: 'local-jwt' }, { access })).status).toBe(403) expect((await run({ ...admin, _strategy: 'totp' }, { access: () => 'yes' as never })).status).toBe(403) // only true expect((await run({ ...admin, _strategy: 'totp' }, { access: async () => true })).status).toBe(200) }) }) test('twoFactor: false — no guard, a password is enough (as documented)', async () => { const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config) const payload = payloadOf(config) const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: unknown) => unknown expect(read({ req: { payload, user: { collection: 'users', roles: ['admin'] } } })).toBe(true) }) })