M1 (8): 2FA attempts only from the own origin; the verify count is stored
R3-2. (b) POST /api/verify-totp and /api/setup-totp refuse a request that a browser marks as coming from another origin (Origin, Sec-Fetch-Site) — before it is counted, so another page (a sibling subdomain included) cannot burn an account's attempts and lock its owner out. Own origins: the request's host, serverURL, Payload's csrf / cors lists, twoFactor.sameOrigin.origins; requests without those headers pass. twoFactor.sameOrigin: false turns it off. (a) The verify count is kept in memory (exact for parallel bursts) and in Payload's key-value store (payload.kv, no new collection), so a restart or a second instance does not reset it; the higher count decides, and a failing store never opens the gate. verifyLimit.store: 'memory' = this instance only. Doctor: csrf-empty (static, warning) when neither serverURL nor csrf is set. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0b4c4e8295
commit
f7296edc71
@@ -10,6 +10,7 @@ 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 { requestFromOwnOrigin } from '../src/modules/security/totp/sameOrigin.js'
|
||||
import {
|
||||
ensurePayloadGuarded,
|
||||
guardPayloadAccess,
|
||||
@@ -21,7 +22,7 @@ import {
|
||||
watchPayloadConfig,
|
||||
} from '../src/modules/security/totp/secondFactor.js'
|
||||
import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js'
|
||||
import { buildVerifyLimit, clearVerifyLimits } from '../src/modules/security/totp/verifyLimit.js'
|
||||
import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { withTotpParts } from './helpers.js'
|
||||
|
||||
@@ -316,16 +317,16 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
clearVerifyLimits()
|
||||
const req = (id: unknown) => ({ i18n: undefined, payload: { logger: { warn: () => {} } }, user: { id, collection: 'users' } }) as never
|
||||
const limit = buildVerifyLimit('users') // 5 in 10 minutes
|
||||
for (let i = 0; i < 5; i++) {expect(limit(req(1))).toBeNull()}
|
||||
const refused = limit(req(1))!
|
||||
for (let i = 0; i < 5; i++) {expect(await limit(req(1))).toBeNull()}
|
||||
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(limit(req(2))).toBeNull() // another account is not affected
|
||||
expect(limit({ ...(req(1) as object), user: null } as never)).toBeNull() // no session: the package refuses by itself
|
||||
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([two(req(1)), two(req(1))]).toEqual([null, null])
|
||||
expect(two(req(1))!.status).toBe(429)
|
||||
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
|
||||
@@ -342,6 +343,134 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
expect(await call(await ipalKit({ 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<string, unknown>()
|
||||
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)
|
||||
expect(kv.data.get(verifyLimitKey('users', '1'))).toMatchObject({ count: 6 })
|
||||
// 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<string, string>, config: Record<string, unknown> = {}, 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],
|
||||
['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<string, string>, config))).toBe(expected)
|
||||
})
|
||||
|
||||
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: true }))
|
||||
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<string, unknown> = {}) => ipalKit({ 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<string, string>, user: Record<string, unknown>) =>
|
||||
(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()
|
||||
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 ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({
|
||||
...twoAuth(),
|
||||
|
||||
Reference in New Issue
Block a user