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
@@ -348,6 +348,7 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit
|
||||
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
|
||||
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
|
||||
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
|
||||
export { ownOrigins, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
|
||||
export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
|
||||
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
|
||||
export { SETUP_FROM_FIELD } from './modules/security/totp/secondFactor.js'
|
||||
@@ -364,6 +365,7 @@ export {
|
||||
} from './modules/security/totp/setupRequired.js'
|
||||
export type { RequireSetupOptions, TwoFactorResetOptions } from './modules/security/totp/setupRequired.js'
|
||||
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
|
||||
export { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from './modules/security/totp/verifyLimit.js'
|
||||
export type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
|
||||
export type { OgImage } from './modules/seo/buildMetadata.js'
|
||||
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
|
||||
|
||||
@@ -157,6 +157,19 @@ export const securityRules: DoctorRule[] = [
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// Payload accepts the login cookie from ANY origin while its `csrf` list is empty — and it is empty
|
||||
// unless `csrf` or `serverURL` is set. A page on a sibling subdomain can then act with a panel user's cookie.
|
||||
id: 'csrf-empty',
|
||||
check: (ctx) => {
|
||||
const code = cfg(ctx)
|
||||
if (!/buildConfig\s*\(/.test(code) || /\bcsrf\s*:/.test(code) || /\bserverURL\s*:/.test(code)) {return []}
|
||||
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "serverURL: process.env.NEXT_PUBLIC_SERVER_URL (Payload then trusts that origin only), or csrf: ['https://<site>']", message: 'neither `serverURL` nor `csrf` is set: Payload accepts the login cookie from any origin (a risk when other applications share the domain)', severity: 'warning' }]
|
||||
},
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// An auth collection anyone can register in. Often exactly what the project wants (customers) — said, not judged.
|
||||
id: 'open-signup',
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 2FA verify and setup attempts only from the site's own origin.
|
||||
*
|
||||
* The verify limit counts every attempt of an account. A page on another origin that the
|
||||
* browser still sends the login cookie to — a sibling subdomain is "same site", so
|
||||
* `SameSite=Lax` does not stop it, and Payload's own `csrf` list is empty unless `serverURL`
|
||||
* or `csrf` is set — could post wrong codes in the owner's name: no password needed, the
|
||||
* owner's five attempts burnt, the owner locked out for the window. So a request that a
|
||||
* browser marks as coming from elsewhere is refused BEFORE it is counted.
|
||||
*
|
||||
* What counts as the site's own origin: the host the request came in on (`Host`,
|
||||
* `X-Forwarded-Host`, the request URL), `serverURL`, Payload's `csrf` and `cors` lists, and
|
||||
* `twoFactor.sameOrigin.origins`. A request with neither `Origin` nor `Sec-Fetch-Site` is not
|
||||
* a browser's cross-site request (a script, `curl`, a server) and passes: it cannot ride on
|
||||
* somebody's cookie.
|
||||
*/
|
||||
type RequestLike = { headers?: { get(name: string): null | string }; payload?: { config?: { cors?: unknown; csrf?: unknown; serverURL?: unknown } }; url?: null | string }
|
||||
|
||||
const originOf = (value: unknown): null | string => {
|
||||
if (typeof value !== 'string' || !value) {return null}
|
||||
try {
|
||||
return new URL(value).origin
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Origins and hosts this request may come from. */
|
||||
export function ownOrigins(req: RequestLike, extra: string[] = []): { hosts: Set<string>; origins: Set<string> } {
|
||||
const config = req.payload?.config
|
||||
const cors = config?.cors
|
||||
const listed = [
|
||||
config?.serverURL,
|
||||
...(Array.isArray(config?.csrf) ? (config.csrf as unknown[]) : []),
|
||||
...(Array.isArray(cors) ? (cors as unknown[]) : Array.isArray((cors as { origins?: unknown } | undefined)?.origins) ? ((cors as { origins: unknown[] }).origins) : []),
|
||||
...extra,
|
||||
]
|
||||
const origins = new Set(listed.map(originOf).filter((o): o is string => o !== null))
|
||||
const hosts = new Set<string>()
|
||||
for (const name of ['host', 'x-forwarded-host']) {
|
||||
// a proxy may list several; the first is the one the browser asked for
|
||||
const value = req.headers?.get(name)?.split(',')[0]?.trim().toLowerCase()
|
||||
if (value) {hosts.add(value)}
|
||||
}
|
||||
const fromUrl = originOf(req.url)
|
||||
if (fromUrl) {hosts.add(new URL(fromUrl).host)}
|
||||
return { hosts, origins }
|
||||
}
|
||||
|
||||
/** False when a browser says the request comes from another origin (see the top of the file). */
|
||||
export function requestFromOwnOrigin(req: RequestLike, extra: string[] = []): boolean {
|
||||
const origin = req.headers?.get('origin')
|
||||
if (origin) {
|
||||
const parsed = originOf(origin)
|
||||
if (!parsed) {return false} // "null" (a sandboxed page, a redirect chain) or garbage
|
||||
const { hosts, origins } = ownOrigins(req, extra)
|
||||
return origins.has(parsed) || hosts.has(new URL(parsed).host.toLowerCase())
|
||||
}
|
||||
const site = req.headers?.get('sec-fetch-site')
|
||||
if (site) {return site === 'same-origin' || site === 'none'}
|
||||
return true
|
||||
}
|
||||
@@ -380,6 +380,11 @@ export type TotpEndpointGuards = {
|
||||
limitVerify?: (req: never) => null | Promise<null | Response> | Response
|
||||
/** The answer for an account whose setup window has passed (in the caller's language). Default: a plain 403. */
|
||||
onSetupClosed?: (req: never) => Response
|
||||
/**
|
||||
* Whether a verify / setup attempt may come from where the browser says it comes from
|
||||
* (sameOrigin.ts). False = refused, and NOT counted against the verify limit.
|
||||
*/
|
||||
ownOrigin?: (req: never) => boolean
|
||||
}
|
||||
|
||||
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T {
|
||||
@@ -395,6 +400,11 @@ export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collectio
|
||||
if (user && endpoint.path === '/setup-totp' && twoFactorSetupState(req) === 'closed') {
|
||||
return guards.onSetupClosed ? guards.onSetupClosed(req as never) : refused()
|
||||
}
|
||||
// An attempt a browser marks as coming from another origin is refused before it is counted:
|
||||
// otherwise another page could burn the owner's attempts and lock them out, without the password.
|
||||
if (user && (endpoint.path === '/verify-totp' || endpoint.path === '/setup-totp') && guards.ownOrigin && !guards.ownOrigin(req as never)) {
|
||||
return Response.json({ message: 'Not allowed from this origin.', ok: false }, { status: 403 })
|
||||
}
|
||||
// The code has about three right answers in a million and the package never counts tries.
|
||||
if (user && endpoint.path === '/verify-totp' && guards.limitVerify) {
|
||||
const limited = await guards.limitVerify(req as never)
|
||||
|
||||
@@ -13,12 +13,24 @@ import { serverText } from '../../integrations/texts.js'
|
||||
* already passed the password reaches the endpoint, so someone without the
|
||||
* password cannot use the limit to lock an account's owner out.
|
||||
*
|
||||
* In memory, per server instance, and always enforced (no "allow when the
|
||||
* store fails" path): with several instances the limit is per instance.
|
||||
* Counted twice, and the higher count decides:
|
||||
* - **in memory**, per server instance — exact also for a burst of parallel requests
|
||||
* (the count is taken before anything is awaited);
|
||||
* - **in the database** (Payload's key-value store, `payload.kv` — the `payload-kv`
|
||||
* collection Payload itself adds; no new collection, no migration of ours), so the count
|
||||
* survives a restart or redeploy and is shared between instances. `store: 'memory'`
|
||||
* leaves this part out.
|
||||
* Always enforced: when the database part fails, the memory count still decides — there is
|
||||
* no "allow when the store fails" path. Two instances can each let a few attempts through
|
||||
* before the other's write lands; the bound is then "max per instance", never "no limit".
|
||||
*
|
||||
* Requests a browser marks as coming from another origin never get here (sameOrigin.ts).
|
||||
*/
|
||||
export type VerifyLimitOptions = {
|
||||
/** Attempts per account in the window. Default 5. */
|
||||
max?: number
|
||||
/** Where the count is kept besides the instance's memory. Default `'database'`; `'memory'` = this instance only. */
|
||||
store?: 'database' | 'memory'
|
||||
/** Window in minutes; a refused account waits until it ends. Default 10. */
|
||||
windowMinutes?: number
|
||||
}
|
||||
@@ -31,11 +43,37 @@ export function clearVerifyLimits(): void {
|
||||
buckets.clear()
|
||||
}
|
||||
|
||||
type KV = { get: (key: string) => Promise<unknown>; set: (key: string, value: object) => Promise<void> }
|
||||
let warnedStore = false
|
||||
|
||||
/** Key of an account's stored count in `payload.kv`. */
|
||||
export const verifyLimitKey = (collection: string, id: string) => `ipal:2fa-verify:${collection}:${id}`
|
||||
|
||||
/** Counts one attempt in the database and returns the stored bucket; null when there is no store or it fails. */
|
||||
async function hitStored(payload: { kv?: unknown; logger?: { warn: (m: string) => void } }, key: string, windowMs: number, now: number): Promise<Bucket | null> {
|
||||
const kv = payload.kv as KV | undefined
|
||||
if (typeof kv?.get !== 'function' || typeof kv?.set !== 'function') {return null}
|
||||
try {
|
||||
const current = (await kv.get(key)) as Bucket | null
|
||||
const valid = current && typeof current.count === 'number' && typeof current.resetAt === 'number' && current.resetAt > now
|
||||
const next: Bucket = valid ? { count: current.count + 1, resetAt: current.resetAt } : { count: 1, resetAt: now + windowMs }
|
||||
await kv.set(key, next)
|
||||
return next
|
||||
} catch (err) {
|
||||
if (!warnedStore) {
|
||||
warnedStore = true
|
||||
payload.logger?.warn(`[ipal] 2FA: the verify limit could not be stored (${err instanceof Error ? err.message : String(err)}); counting in memory only.`)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function buildVerifyLimit(collection: string, options: VerifyLimitOptions = {}) {
|
||||
const max = Number.isFinite(options.max) && options.max! > 0 ? Math.floor(options.max!) : 5
|
||||
const windowMs = (Number.isFinite(options.windowMinutes) && options.windowMinutes! > 0 ? options.windowMinutes! : 10) * 60_000
|
||||
const stored = options.store !== 'memory'
|
||||
|
||||
return (req: PayloadRequest): null | Response => {
|
||||
return async (req: PayloadRequest): Promise<null | Response> => {
|
||||
// No session: the package refuses by itself, and there is no account to count against.
|
||||
if (!req.user) {return null}
|
||||
// Whatever the id looks like, it is one bucket per value — never "no limit".
|
||||
@@ -53,8 +91,13 @@ export function buildVerifyLimit(collection: string, options: VerifyLimitOptions
|
||||
const bucket = current && current.resetAt > now ? current : { count: 0, resetAt: now + windowMs }
|
||||
bucket.count += 1
|
||||
buckets.set(key, bucket)
|
||||
if (bucket.count <= max) {return null}
|
||||
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000))
|
||||
// This attempt's own number, taken now: the bucket is shared and keeps growing while we wait below.
|
||||
const mine: Bucket = { count: bucket.count, resetAt: bucket.resetAt }
|
||||
// …and in the database, so a restart or another instance does not start from zero. The higher count decides.
|
||||
const kept = stored ? await hitStored(req.payload as never, verifyLimitKey(collection, id), windowMs, now) : null
|
||||
const worst = kept && kept.count > mine.count ? kept : mine
|
||||
if (worst.count <= max) {return null}
|
||||
const retryAfter = Math.max(1, Math.ceil((worst.resetAt - now) / 1000))
|
||||
req.payload.logger.warn(`[ipal] 2FA: too many verify attempts for ${collection} ${id}; refused for ${retryAfter} s.`)
|
||||
return Response.json(
|
||||
{ message: serverText(req.i18n as never, 'twoFactorTooManyAttempts', { minutes: Math.ceil(retryAfter / 60) }), ok: false },
|
||||
|
||||
@@ -40,6 +40,7 @@ import { serverText } from './modules/integrations/texts.js'
|
||||
import { buildSystemPagesFields } from './modules/pages/index.js'
|
||||
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
|
||||
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
|
||||
import { requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
|
||||
import {
|
||||
buildGuardStrategy,
|
||||
ensurePayloadGuarded,
|
||||
@@ -273,8 +274,10 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
// Only accounts of the 2FA collection may use them (guardTotpEndpoint) —
|
||||
// whatever the package registered, also paths a later version adds.
|
||||
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, tf.verifyLimit)
|
||||
const extraOrigins = typeof tf.sameOrigin === 'object' ? (tf.sameOrigin.origins ?? []) : []
|
||||
const guards = {
|
||||
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}),
|
||||
...(tf.sameOrigin === false ? {} : { ownOrigin: (req: PayloadRequest) => requestFromOwnOrigin(req as never, extraOrigins) }),
|
||||
onSetupClosed: (req: PayloadRequest) =>
|
||||
Response.json({ message: serverText(req.i18n as never, 'twoFactorSetupClosed'), ok: false }, { status: 403 }),
|
||||
}
|
||||
|
||||
+15
-1
@@ -329,6 +329,17 @@ export type IpalOptions = {
|
||||
* package's views as they are. Run generate:importmap. docs/security.md.
|
||||
*/
|
||||
safeBack?: false | SafeBackRule
|
||||
/**
|
||||
* 2FA verify and setup attempts (`POST /api/verify-totp`, `/api/setup-totp`)
|
||||
* are accepted only from the site's own origin: a request that a browser
|
||||
* marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) is refused
|
||||
* with 403 and not counted — so another page, a sibling subdomain included,
|
||||
* cannot burn an account's verify attempts and lock its owner out. Own
|
||||
* origins: the request's host, `serverURL`, Payload's `csrf` / `cors`
|
||||
* lists, and `{ origins: ['https://app.example.com'] }` here. Requests
|
||||
* without those headers (scripts, servers) pass. `false` = off.
|
||||
*/
|
||||
sameOrigin?: { origins?: string[] } | false
|
||||
/**
|
||||
* Texts of the 2FA screens and user field. Default: ipal-kit's English and
|
||||
* Polish (`TOTP_TEXTS`), merged over the package's; your own
|
||||
@@ -340,7 +351,10 @@ export type IpalOptions = {
|
||||
* 2FA package never counts tries, and a six-digit code can be guessed by
|
||||
* whoever holds the password. Default `{ max: 5, windowMinutes: 10 }`: the
|
||||
* sixth attempt in ten minutes, right or wrong, is refused (429) until the
|
||||
* window ends. `false` = no limit (a limiter in front of the site).
|
||||
* window ends. The count is kept in memory and in the database (Payload's
|
||||
* `payload.kv`), so a restart or a second instance does not reset it;
|
||||
* `{ store: 'memory' }` = this instance only. `false` = no limit (a limiter
|
||||
* in front of the site).
|
||||
*/
|
||||
verifyLimit?: false | VerifyLimitOptions
|
||||
}
|
||||
|
||||
@@ -181,6 +181,13 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
|
||||
expect(await run(cfg, ['turnstile-env-key'])).toEqual([])
|
||||
})
|
||||
|
||||
test('csrf-empty: without serverURL and csrf Payload takes the login cookie from any origin', async () => {
|
||||
expect(await run("export default buildConfig({ plugins: [ipalKit({ access: { authCollection: 'users' } })] })", ['csrf-empty'])).toEqual(['csrf-empty:warning'])
|
||||
expect(await run('export default buildConfig({ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, plugins: [] })', ['csrf-empty'])).toEqual([])
|
||||
expect(await run("export default buildConfig({ csrf: ['https://site.example'], plugins: [] })", ['csrf-empty'])).toEqual([])
|
||||
expect(await run('// not a Payload config', ['csrf-empty'])).toEqual([])
|
||||
})
|
||||
|
||||
test('open-signup: an auth collection anyone can register in is said, as info', async () => {
|
||||
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
|
||||
expect(await run(cfg, ['open-signup'], { openSignUp: ['customers', 'members'] })).toEqual(['open-signup:info', 'open-signup:info'])
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -454,6 +454,28 @@ describe('the code cannot be guessed: verify attempts are limited per account',
|
||||
expect((await fetch(`${server.url}/api/pages`, { headers: { cookie } })).status).toBe(403)
|
||||
})
|
||||
|
||||
// M1 (R3-2). Order matters: this runs after the account above is already refused.
|
||||
test('attempts from another origin are refused without being counted, and the count survives a restart', async () => {
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'], totpSecret: GUESS_SECRET } as never })
|
||||
const mine = (await login('users', '[email protected]')).cookies.join('; ')
|
||||
// a page on a sibling subdomain posts wrong codes with the owner's cookie: refused, twenty times
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const res = await verify('000000', { cookie: mine, origin: 'https://blog.example.com' })
|
||||
expect(res.status).toBe(403)
|
||||
}
|
||||
expect((await verify('000000', { cookie: mine, 'sec-fetch-site': 'cross-site' })).status).toBe(403)
|
||||
// …and the owner still has every attempt: three wrong ones are answered, not refused
|
||||
for (let i = 0; i < 3; i++) {expect((await verify('000000', { cookie: mine, origin: server.url })).status).toBe(200)}
|
||||
// a restart / another instance: the memory is empty, the database is not
|
||||
const { clearVerifyLimits } = await import('../src/modules/security/totp/verifyLimit.js')
|
||||
clearVerifyLimits()
|
||||
expect((await verify('000000', { cookie: mine })).status).toBe(200) // 4th
|
||||
expect((await verify('000000', { cookie: mine })).status).toBe(200) // 5th
|
||||
expect((await verify(totp(GUESS_SECRET), { cookie: mine })).status).toBe(429) // 6th: refused, also the right code
|
||||
clearVerifyLimits()
|
||||
expect((await verify(totp(GUESS_SECRET), { cookie: mine })).status).toBe(429)
|
||||
})
|
||||
|
||||
test('the limit is the account\'s alone: nobody without its password can use it, other accounts are not affected', async () => {
|
||||
// someone without the password cannot count against the account: no session, or a session of another collection
|
||||
for (let i = 0; i < 8; i++) {
|
||||
|
||||
Reference in New Issue
Block a user