2FA setup required: review fixes (SR-1 to SR-9)
SR-1: /api/ipal/admin-icon sends the upload security headers (sandbox policy, nosniff) with the bytes: an SVG is shown, never run. fetchPublicImage stops reading at the size limit. SR-2: requireSetup.exempt exempts only on exactly true; an async function, and a windowHours that is not a number or false, stop the start. SR-3: on Postgres / SQLite the missing column makes every login fail: the log says so, the docs call the migration a required step of the same deploy, and ipal-doctor reports a SQL project without it. SR-4: an admin's reset also ends the account's sessions. SR-5: the reset needs a session that entered its own TOTP code by default. SR-6: the doctor's import-map rule covers TwoFactorStatusField and TwoFactorAlert. SR-7: building blocks exported; dashboard notice, status field, setup notice and the server-side image fetch can be switched off one by one. SR-8: totpSetupFrom is on the 2FA collection whenever 2FA is on. SR-9: both ways out of "every administrator is blocked" in security.md. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
9d2ab43438
commit
75a6f5209e
@@ -99,6 +99,57 @@ describe('importmap rule and the 2FA back-link check', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('2FA setup required: what a project must have', () => {
|
||||
const MAP = 'src/app/(payload)/admin/importMap.js'
|
||||
const NEW = ['@intecion/ipal-kit/admin#TwoFactorStatusField', '@intecion/ipal-kit/admin#TwoFactorAlert']
|
||||
const OLD = ['@clocklimited/payload-2fa/rsc#TOTPSetup', '@intecion/ipal-kit/admin#TotpRedirectProvider', '@intecion/ipal-kit/admin#SafeTotpView']
|
||||
const entries = (names: string[]) => `export const importMap = { ${names.map((n) => `"${n}": X`).join(', ')} }`
|
||||
const plugin = {
|
||||
...base(),
|
||||
...installed('@clocklimited/payload-2fa', '3.0.0'),
|
||||
'node_modules/@intecion/ipal-kit/dist/exports/admin.js': 'export { SafeTotpView, TotpRedirectProvider, TwoFactorAlert, TwoFactorStatusField }',
|
||||
'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': "export const SETUP_FROM_FIELD = 'totpSetupFrom'",
|
||||
}
|
||||
const lacks = async (config: string, map: string[]) =>
|
||||
(await doctor(project({ ...plugin, [MAP]: entries(map), 'src/payload.config.ts': config }), ['importmap'])).findings.filter((f) => /import map lacks/.test(f.message)).map((f) => f.message).join()
|
||||
|
||||
test('the import map must hold the status field and the dashboard notice', async () => {
|
||||
const missing = await lacks('twoFactor: { plugin: payloadTotp }', OLD)
|
||||
for (const name of NEW) {expect(missing).toContain(name)}
|
||||
const complete = await lacks('twoFactor: { plugin: payloadTotp }', [...OLD, ...NEW])
|
||||
for (const name of NEW) {expect(complete).not.toContain(name)}
|
||||
})
|
||||
|
||||
test.each([
|
||||
['requireSetup: false', []],
|
||||
['guard: false', []],
|
||||
['requireSetup: { statusField: false }', [NEW[1]]],
|
||||
['requireSetup: { dashboardNotice: false }', [NEW[0]]],
|
||||
])('%s: only what is still on is expected', async (option, expected) => {
|
||||
const missing = await lacks(`twoFactor: { plugin: payloadTotp, ${option} }`, OLD)
|
||||
for (const name of NEW) {expect([name, missing.includes(name)]).toEqual([name, expected.includes(name)])}
|
||||
})
|
||||
|
||||
const migration = async (files: Record<string, object | string>, config = 'twoFactor: { plugin: payloadTotp }') =>
|
||||
(await doctor(project({ ...plugin, [MAP]: entries([...OLD, ...NEW]), 'src/payload.config.ts': config, ...files }), ['2fa'])).findings.filter((f) => /totp_setup_from/.test(f.message)).map((f) => f.severity)
|
||||
|
||||
test('Postgres / SQLite: a migration must add the 2FA column, or nobody can log in', async () => {
|
||||
const pg = installed('@payloadcms/db-postgres', '3.94.1')
|
||||
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'await db.execute(sql`CREATE TABLE "users" ("id" serial)`)' })).toEqual(['error'])
|
||||
expect(await migration({ ...pg, 'src/migrations/20260101_init.ts': 'x', 'src/migrations/20261124_totp.ts': 'ALTER TABLE "users" ADD COLUMN "totp_setup_from" timestamp' })).toEqual([])
|
||||
expect(await migration({ ...pg, 'migrations/20261124_totp.json': '{ "columns": { "totpSetupFrom": {} } }' })).toEqual([])
|
||||
expect(await migration(pg)).toEqual(['warning']) // no migrations folder: the doctor cannot see how the schema gets there
|
||||
expect(await migration({ ...installed('@payloadcms/db-sqlite', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual(['error'])
|
||||
})
|
||||
|
||||
test('MongoDB, 2FA off, or a plugin version without the column: nothing to report', async () => {
|
||||
expect(await migration({ ...installed('@payloadcms/db-mongodb', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' })).toEqual([])
|
||||
expect(await migration({ ...installed('@payloadcms/db-postgres', '3.94.1'), 'src/migrations/20260101_init.ts': 'x' }, 'twoFactor: false')).toEqual([])
|
||||
const older = { ...installed('@payloadcms/db-postgres', '3.94.1'), 'node_modules/@intecion/ipal-kit/dist/modules/security/totp/secondFactor.js': 'export {}', 'src/migrations/20260101_init.ts': 'x' }
|
||||
expect(await migration(older)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('helpers', () => {
|
||||
test('parseEnvFile reads KEY=value, strips quotes, skips comments', () => {
|
||||
expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' })
|
||||
|
||||
@@ -72,3 +72,77 @@ describe('the brand image for a session the browser cannot load it in', () => {
|
||||
expect((await icon.handler(req as never)).status).toBe(302)
|
||||
})
|
||||
})
|
||||
|
||||
// An uploaded SVG from the site's own origin can run script when opened directly. The upload routes send a sandbox
|
||||
// policy for that; the icon endpoint serves the same bytes and must send the same headers.
|
||||
describe('the tab icon endpoint and an SVG', () => {
|
||||
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"><script>document.title="XSS"</script></svg>'
|
||||
const icon = (fields: Record<string, unknown> = {}) => buildAdminImageEndpoints({ agency: false, language: 'en' } as never, fields as never).find((e) => e.path.endsWith('admin-icon'))!
|
||||
const req = {
|
||||
payload: { config: {}, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.svg' }, siteName: 'Example' }) },
|
||||
url: 'https://example.com/api/ipal/admin-icon',
|
||||
user: null,
|
||||
}
|
||||
|
||||
test.each([
|
||||
['an SVG', SVG, 'image/svg+xml'],
|
||||
['a PNG', png, 'image/png'],
|
||||
])('%s is served with the sandbox policy and nosniff', async (_name, body, type) => {
|
||||
vi.stubGlobal('fetch', respond(body, { headers: { 'content-type': type }, status: 200 }))
|
||||
const res = await icon().handler(req as never)
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe(type)
|
||||
expect(res.headers.get('content-security-policy')).toBe("default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox")
|
||||
expect(res.headers.get('x-content-type-options')).toBe('nosniff')
|
||||
})
|
||||
|
||||
test('the headers are the ones of the upload routes', async () => {
|
||||
const { buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } = await import('../src/modules/security/buildSecurityHeaders.js')
|
||||
expect(buildUploadSecurityHeaders()[0].headers).toEqual([...UPLOAD_SECURITY_HEADERS])
|
||||
expect(UPLOAD_SECURITY_HEADERS.find((h) => h.key === 'Content-Security-Policy')?.value).toContain('sandbox')
|
||||
})
|
||||
|
||||
test('adminMeta.serveIcon: false → the redirect to the media file, no fetch', async () => {
|
||||
const fetchMock = respond(SVG, { headers: { 'content-type': 'image/svg+xml' }, status: 200 })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const res = await icon({ serveIcon: false }).handler(req as never)
|
||||
expect(res.status).toBe(302)
|
||||
expect(res.headers.get('location')).toBe('https://example.com/api/media/file/icon.svg')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('an image that is too large is not read to the end', () => {
|
||||
test('a declared length over the limit: the body is not read', async () => {
|
||||
const cancel = vi.fn(async () => undefined)
|
||||
const body = new ReadableStream<Uint8Array>({ cancel, pull: (c) => c.enqueue(new Uint8Array(1024)) })
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { headers: { 'content-length': String(10 * 1024 * 1024), 'content-type': 'image/png' }, status: 200 })))
|
||||
expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull()
|
||||
expect(cancel).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('no declared length: reading stops at the limit', async () => {
|
||||
let sent = 0
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
pull: (c) => {
|
||||
sent += 64 * 1024
|
||||
c.enqueue(new Uint8Array(64 * 1024)) // endless
|
||||
},
|
||||
})
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { headers: { 'content-type': 'image/png' }, status: 200 })))
|
||||
expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull()
|
||||
expect(sent).toBeLessThan(2 * 1024 * 1024) // stopped soon after 512 KB, not after "everything"
|
||||
})
|
||||
|
||||
test('whiteLabel.inlineImages: false → the logo keeps its address, nothing is fetched', async () => {
|
||||
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const payload = {
|
||||
config: { custom: { ipal: { twoFactor: { collection: 'users' } } }, serverURL: 'https://example.com' },
|
||||
findGlobal: async () => ({ logo: { url: '/api/media/file/logo.png' }, siteName: 'Example' }),
|
||||
}
|
||||
const out = (await AdminLogo({ inlineImages: false, payload: payload as never, user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true } as never })) as { props: { src?: string } }
|
||||
expect(out.props.src).toBe('/api/media/file/logo.png')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
+16
-2
@@ -320,10 +320,12 @@ describe('requireSetup x safeBack x guard', () => {
|
||||
const wrapped = totpViews.filter((v) => typeof v.Component === 'object' && v.Component.path === '@intecion/ipal-kit/admin#SafeTotpView').length
|
||||
expect(wrapped).toBe(options.safeBack === false ? 0 : 4)
|
||||
|
||||
// setup required needs ipal-kit's own check; with either off there is no window field and no notice
|
||||
// setup required needs ipal-kit's own check; with either off there is no status field, hook or notice
|
||||
const setupOn = options.requireSetup !== false && options.guard !== false
|
||||
const users = config.collections?.find((c) => c.slug === 'users')
|
||||
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom'))).toBe(setupOn)
|
||||
// the data field whenever 2FA is on (the schema does not follow the switches); the panel's status field with the mode
|
||||
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom'))).toBe(true)
|
||||
expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'))).toBe(setupOn)
|
||||
// the administrator's reset (a lost phone) comes with ipal-kit's own check, also when setup is not required
|
||||
expect(Boolean(config.endpoints?.some((e) => e.path === '/ipal/two-factor/reset'))).toBe(options.guard !== false)
|
||||
const provider = JSON.stringify(config.admin?.components?.providers ?? [])
|
||||
@@ -335,6 +337,18 @@ describe('requireSetup x safeBack x guard', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('requireSetup.setupNotice', () => {
|
||||
const providers = async (requireSetup?: Record<string, unknown>) =>
|
||||
JSON.stringify((await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup } as never })({ collections: [], secret: 'x' } as unknown as Config)).admin?.components?.providers ?? [])
|
||||
|
||||
test('on by default; false removes the notice, not the lock', async () => {
|
||||
expect(await providers()).toContain('"requireSetup":true')
|
||||
expect(await providers({ setupNotice: false })).not.toContain('"requireSetup":true')
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup: { setupNotice: false } } as never })({ collections: [], secret: 'x' } as unknown as Config)
|
||||
expect((config.custom as { ipal: { twoFactor: { requireSetup: boolean } } }).ipal.twoFactor.requireSetup).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a 2FA factory that hands back the same view objects on every call', () => {
|
||||
const views = {
|
||||
SetupTOTP: { Component: { path: 'pkg/rsc#TOTPSetup' }, path: 'setup-totp' },
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import type { Access, Config } from 'payload'
|
||||
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
twoFactorSetupState,
|
||||
watchPayloadConfig,
|
||||
} from '../src/modules/security/totp/secondFactor.js'
|
||||
import { resolveRequireSetup } from '../src/modules/security/totp/setupRequired.js'
|
||||
import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js'
|
||||
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { withTotpParts } from './helpers.js'
|
||||
@@ -377,8 +377,28 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
|
||||
const off = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base())
|
||||
expect(guard(off)).toMatchObject({ requireSetup: false })
|
||||
expect(off.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(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 ipalKit({ 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 ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { dashboardNotice: false } } })(base())
|
||||
expect(has(noDash)).toMatchObject({ dashboard: false, status: true })
|
||||
const noStatus = await ipalKit({ 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
|
||||
@@ -387,6 +407,130 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
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(() => ipalKit({ 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 ipal-kit's own check is off: a wrong value is never silently accepted
|
||||
await expect(Promise.resolve().then(() => ipalKit({ 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('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(() => ipalKit({ 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)
|
||||
const mongo = fake('mongoose', 'connection lost')
|
||||
await backfillSetupFrom(mongo.payload as never, 'users')
|
||||
expect(mongo.logger.error).not.toHaveBeenCalled()
|
||||
expect(mongo.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<string, unknown>, options: Parameters<typeof buildTwoFactorResetEndpoint>[1] = {}, guardExtra: Record<string, unknown> = {}) => {
|
||||
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<string, unknown>; 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 ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
|
||||
const payload = payloadOf(config)
|
||||
|
||||
@@ -529,6 +529,39 @@ describe('2FA setup required: an account without TOTP reaches nothing but setup'
|
||||
expect(ok.status).toBe(200)
|
||||
const doc = (await payload.findByID({ id: userId, collection: 'users' as never })) as unknown as { totpSetupFrom: string }
|
||||
expect(Date.now() - new Date(doc.totpSetupFrom).getTime()).toBeLessThan(120_000)
|
||||
// the reset ends the account's sessions: the token from before is nobody's now, the account logs in again
|
||||
expect(((await (await api('/users/me', sessions.newcomer)).json()) as { user: unknown }).user).toBeNull()
|
||||
expect(((await (await setup(sessions.newcomer)).json().catch(() => ({}))) as { ok?: boolean }).ok).not.toBe(true)
|
||||
sessions.newcomer = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
|
||||
})
|
||||
|
||||
// A reset is also what an administrator presses for an account that may be in someone else's hands. A session of
|
||||
// that account which had passed 2FA must not survive it: /api/setup-totp asks for no password, so it could
|
||||
// otherwise enrol the thief's own authenticator.
|
||||
test('a reset ends every session of the account: a stolen verified session cannot enrol its own authenticator', async () => {
|
||||
const THIEF_SECRET = 'KRSXG5CTMVRXEZLU'
|
||||
const victim = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: TOTP_SECRET } as never })
|
||||
// the victim's fully verified session, as a thief would hold it (token + 2FA cookie)
|
||||
const signIn = await login('users', '[email protected]')
|
||||
const verify = await api('/verify-totp', { headers: { authorization: `JWT ${signIn.token}` } }, { body: JSON.stringify({ token: totp(TOTP_SECRET) }), method: 'POST' })
|
||||
expect(((await verify.json()) as { ok: boolean }).ok).toBe(true)
|
||||
const stolen: Session = { headers: { authorization: `JWT ${signIn.token}`, cookie: cookiesOf(verify).join('; ') } }
|
||||
expect((await api('/pages', stolen)).status).toBe(200)
|
||||
|
||||
expect((await api('/ipal/two-factor/reset', sessions.verified, { body: JSON.stringify({ userId: victim.id }), method: 'POST' })).status).toBe(200)
|
||||
|
||||
expect(((await (await api('/users/me', stolen)).json()) as { user: unknown }).user).toBeNull()
|
||||
const enrol = await api('/setup-totp', stolen, { body: JSON.stringify({ secret: THIEF_SECRET, token: totp(THIEF_SECRET) }), method: 'POST' })
|
||||
expect(((await enrol.json().catch(() => ({}))) as { ok?: boolean }).ok).not.toBe(true)
|
||||
const after = (await payload.findByID({ id: victim.id, collection: 'users' as never, showHiddenFields: true })) as unknown as { sessions?: unknown[]; totpSecret?: null | string }
|
||||
expect(after.totpSecret ?? null).toBeNull()
|
||||
expect(after.sessions ?? []).toEqual([])
|
||||
expect((await api('/form-submissions', stolen)).status).toBe(403)
|
||||
|
||||
// the owner logs in again with the password and sets TOTP up; the old session stays dead
|
||||
const owner: Session = { headers: { authorization: `JWT ${(await login('users', '[email protected]')).token}` } }
|
||||
expect((await setup(owner)).status).toBe(200)
|
||||
expect(((await (await api('/users/me', stolen)).json()) as { user: unknown }).user).toBeNull()
|
||||
})
|
||||
|
||||
test('inside the window it sets TOTP up, and then everything its role allows opens', async () => {
|
||||
|
||||
Reference in New Issue
Block a user