Security review round 2: no exception by name, staff list fails closed, verify limit

R2-1: the sweep skipped every collection whose slug starts with payload-,
so a plugin's payload-... collection added after ipalKit was never guarded.
There is no exception by name or prefix now: every collection and global
is guarded, Payload's own included, and the job queue's run / queue /
cancel rules too.

R2-2: role predicates called without a source fail closed where the staff
collections are not known (browser bundle, middleware, edge): nobody is
staff. They accept req.payload, a config (also the client config) or
{ staffCollections } as the source.

R2-3: the staff list is filed per config / Payload instance; a call without
a source gets only what every config in the process calls staff.

R2-4: payload.config is watched on the instance, so a config swapped in by
a dev reload is guarded before any request or Local API call.

R2-5: verify attempts are limited per account (default 5 in 10 minutes,
twoFactor.verifyLimit), counted in memory, never skipped.

R2-6: a user object without collection owes the second factor; endpoints
the 2FA package may add on collections or globals are guarded too; a
warning names staff collections that 2FA does not cover; docs state what
is not covered, fix the one-argument examples and the doctor example.

HTTP tests for each on payload-2fa beta.7, run on SQLite, Postgres and
MongoDB (test adapter added).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 01:46:25 +01:00
co-authored by Claude Fable 5.2
parent 32faaa5e30
commit c56f0d41b8
34 changed files with 871 additions and 108 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ export {
requireRoleField,
} from './access.js'
export { injectRoles } from './injectRoles.js'
export { hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffCollectionSlugs, userMeetsRole } from './predicates.js'
export { clearStaffRegistry, hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffCollectionSlugs, userMeetsRole } from './predicates.js'
export { buildRolesField } from './rolesField.js'
export type { AccessOption, Role } from './types.js'
export { ROLE_HIERARCHY } from './types.js'
+60 -23
View File
@@ -13,19 +13,50 @@ import { ROLE_HIERARCHY } from './types.js'
*/
type MaybeUser = { roles?: null | Role[] } | null | Record<string, unknown> | undefined
/** `req.payload`, or anything with the sanitized config on it. */
type MaybePayload = null | Pick<BasePayload, 'config'> | undefined
/**
* Where the staff collections come from: `req.payload` (anything with the
* sanitized `config` on it), a config itself (also the client config from
* `useConfig()` — it has `admin.user`), or the list given outright.
*/
type StaffSource = { admin?: { user?: string }; config?: StaffConfig; custom?: unknown; staffCollections?: string[] } | null | undefined
type StaffConfig = { admin?: { user?: string }; custom?: unknown }
type MaybePayload = Pick<BasePayload, 'config'> | StaffSource
/**
* The staff collections of the config ipalKit last built in this process —
* what the predicates fall back to when they get no `payload` (`isAdmin(req.user)`
* in a hook or an endpoint). `null` where ipalKit never ran: a browser bundle.
* The staff lists of the configs ipalKit built in this process, by owner: the
* running Payload instance once it exists, a token of the config before that.
* Used when a predicate gets no source (`isAdmin(req.user)` in a hook).
*/
let registeredStaff: null | string[] = null
const registered = new Map<object, string[]>()
/** Called by ipalKit (config time, then onInit with the sanitized config). Not for projects. */
export function registerStaffCollections(slugs: string[]): void {
registeredStaff = [...new Set(slugs.filter(Boolean))]
/**
* Called by ipalKit: at config time with a token, then with the Payload
* instance (`replaces` = that config's token) on init and after every reload.
* Not for projects.
*/
export function registerStaffCollections(owner: object, slugs: string[], replaces?: object): void {
if (replaces) {registered.delete(replaces)}
registered.set(owner, [...new Set(slugs.filter(Boolean))])
}
/** For tests. */
export function clearStaffRegistry(): void {
registered.clear()
}
/** For tests: how many configs / instances have a staff list filed. */
export const staffRegistrySize = (): number => registered.size
/**
* The staff collections every config in this process agrees on, or null when
* ipalKit never ran here (a browser bundle, Next middleware, the edge
* runtime). Two configs with different lists: only what both call staff — a
* call that does not say which config it means must not get the wider answer.
*/
function agreedStaff(): null | string[] {
if (!registered.size) {return null}
const lists = [...registered.values()]
return lists[0].filter((slug) => lists.every((list) => list.includes(slug)))
}
/**
@@ -34,29 +65,33 @@ export function registerStaffCollections(slugs: string[]): void {
* (`access.authCollection`) and `access.staffCollections`. Accounts of any
* other auth collection — customers, members — are visitors to the plugin:
* no role and no staff check counts for them, whatever fields they have.
*
* Pass `req.payload` (or a config, or `{ staffCollections: [...] }`). Without
* an argument: what the configs built in this process agree on, `[]` when
* there is none.
*/
export function staffCollectionSlugs(payload?: MaybePayload): string[] {
const config = payload?.config
if (!config) {return registeredStaff ?? []}
export function staffCollectionSlugs(source?: MaybePayload): string[] {
if (!source) {return agreedStaff() ?? []}
const given = (source as { staffCollections?: unknown }).staffCollections
if (Array.isArray(given)) {return given.filter((s): s is string => typeof s === 'string' && s !== '')}
const config = ((source as { config?: StaffConfig }).config ?? source) as StaffConfig
const extra = (config.custom as { ipal?: { staffCollections?: string[] } } | undefined)?.ipal?.staffCollections ?? []
return [...new Set([config.admin?.user, ...extra].filter((s): s is string => typeof s === 'string' && s !== ''))]
}
/**
* Whether this account's roles may count at all: it belongs to a staff
* collection. Checked before any role. An account without `collection` (a
* user object built by hand) does not count either — pass the user Payload
* authenticated, or add `collection` yourself in server code you trust.
*
* Only where no staff list is known (no `payload` given and ipalKit never ran
* in this bundle — client components) the roles are taken as they are; that is
* for showing or hiding things, never for access control.
* collection. Checked before any role, and it fails closed:
* - an account without `collection` (a user object built by hand) is not staff;
* - where the staff collections are not known — no source given and ipalKit
* never ran in this bundle (client components, Next middleware, the edge
* runtime) — nobody is staff. Pass the source there: `isAdmin(user, config)`
* with the config from `useConfig()`, or `isAdmin(user, { staffCollections: ['users'] })`.
*/
function isStaffAccount(user: MaybeUser, payload?: MaybePayload): boolean {
function isStaffAccount(user: MaybeUser, source?: MaybePayload): boolean {
if (!user || typeof user !== 'object') {return false}
if (!payload?.config && registeredStaff === null) {return true}
const slug = (user as { collection?: unknown }).collection
return typeof slug === 'string' && staffCollectionSlugs(payload).includes(slug)
return typeof slug === 'string' && staffCollectionSlugs(source).includes(slug)
}
/** Safely extracts the roles array from a loosely-typed user. */
@@ -80,7 +115,9 @@ function highestRoleIndex(user: MaybeUser): number {
*
* Pass `req.payload` as the third argument where you have it (access
* functions, hooks, endpoints); without it the staff collections of the
* config ipalKit built in this process are used.
* config ipalKit built in this process are used — and where there is none
* (a browser bundle, middleware) the answer is false: pass the config from
* `useConfig()` or `{ staffCollections: ['users'] }` there.
*/
export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean {
if (!isStaffAccount(user, payload)) {return false}
+3 -2
View File
@@ -1,12 +1,13 @@
import { consentTexts } from './consent.js'
import { contentTexts } from './content.js'
import { integrationsTexts } from './integrations.js'
import { securityTexts } from './security.js'
import { settingsTexts } from './settings.js'
/** Every admin component text, by language. Payload reads them as `ipal:<key>`. */
export const adminTexts = {
en: { ...settingsTexts.en, ...integrationsTexts.en, ...consentTexts.en, ...contentTexts.en },
pl: { ...settingsTexts.pl, ...integrationsTexts.pl, ...consentTexts.pl, ...contentTexts.pl },
en: { ...settingsTexts.en, ...integrationsTexts.en, ...consentTexts.en, ...contentTexts.en, ...securityTexts.en },
pl: { ...settingsTexts.pl, ...integrationsTexts.pl, ...consentTexts.pl, ...contentTexts.pl, ...securityTexts.pl },
}
export type AdminTextKey = keyof typeof adminTexts.en
+11
View File
@@ -0,0 +1,11 @@
import { defineTexts } from '../define.js'
/** Admin component texts — two-step verification (2FA). Placeholders use Payload's {{name}} syntax. */
export const securityTexts = defineTexts({
en: {
twoFactorTooManyAttempts: 'Too many codes were tried for this account. Wait {{minutes}} min, then enter the current code from your app.',
},
pl: {
twoFactorTooManyAttempts: 'Dla tego konta wpisano zbyt wiele kodów. Odczekaj {{minutes}} min, a potem wpisz aktualny kod z aplikacji.',
},
})
+1 -1
View File
@@ -42,7 +42,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
}
export type DoctorEndpointOptions = {
/** Who may read the status besides a valid token, e.g. `({ req }) => req.user?.roles?.includes('admin')`. */
/** Who may read the status besides a valid token, e.g. `({ req }) => isAdmin(req.user, req.payload)` (a staff admin; the second factor is checked for you). */
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/** Env variable that holds the token (≥ 32 characters). Default IPAL_DOCTOR_TOKEN. */
tokenVar?: string
+135 -15
View File
@@ -12,6 +12,27 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa
* applies it to everything in the config when it finishes, and again in onInit
* to whatever other plugins added later; `userMeetsRole` asks it too.
*
* Every way past this check, and why it is safe — keep this list complete:
* 1. no user → the access function itself decides (anonymous visitors);
* 2. 2FA off or `twoFactor.guard: false` → there is no check (the project's choice);
* 3. an account of another auth collection → 2FA is about ONE collection; such an
* account is not staff unless the project names its collection in
* `access.staffCollections` (then it is staff WITHOUT a second factor — ipalKit
* logs a warning at start);
* 4. `_strategy === 'totp'` → set by the package's strategy after password and code;
* 5. `_strategy === 'api-key'` → an API key is its own credential (the package's rule);
* 6. `hasTotp === false` → TOTP not set up yet (the setup screen needs the session);
* 7. per-entity opt-out in the project's config (`custom.totp.disableAccessWrapper`,
* `custom.ipal.secondFactor`), or the package's global `disableAccessWrapper`;
* 8. `access.admin` (may this account open the panel) is not wrapped: the code is
* entered inside the panel;
* 9. endpoints are not access functions: the plugin's own check `userMeetsRole` /
* `secondFactorPassed`, the 2FA package's are wrapped (guardTotpEndpoint), a
* project's own must call `secondFactorPassed(req)`;
* 10. the Local API with `overrideAccess: true` (server code).
* There is no exception by slug, name or prefix, and a user object the check cannot
* read (no `collection`, an unknown `_strategy`, no `hasTotp`) is refused.
*
* It fails closed. An account of the 2FA collection passes only when
* - it came through the package's `totp` strategy (password AND code), or
* - it authenticated with an API key (the package's own rule), or
@@ -43,6 +64,9 @@ export function secondFactorPassed({ payload, user }: MaybeReq): boolean {
const guard = guardConfig(payload)
if (!guard) {return true}
const u = user as { _strategy?: unknown; collection?: unknown; hasTotp?: unknown }
// A user object that does not say which collection it is from cannot be told apart from a
// 2FA account: refused. (Payload's strategies and payload.auth() always set `collection`.)
if (typeof u.collection !== 'string') {return false}
if (u.collection !== guard.collection) {return true}
if (u._strategy === 'totp' || u._strategy === 'api-key') {return true}
return u.hasTotp === false
@@ -57,7 +81,7 @@ type Guarded = { [GUARDED]?: true } & AnyAccess
* otherwise the function itself (or Payload's default, "logged in", when there
* is none). Wrapping twice is harmless — an already wrapped function is returned as is.
*
* access: { read: requireSecondFactor(({ req }) => isAdmin(req.user)) }
* access: { read: requireSecondFactor(({ req }) => isAdmin(req.user, req.payload)) }
*/
export function requireSecondFactor<T extends AnyAccess>(access?: T): T {
if (access && (access as Guarded)[GUARDED]) {return access}
@@ -132,11 +156,27 @@ function guardEntity<T extends GuardedEntity>(entity: T, operations: readonly st
return { ...entity, access }
}
const JOB_OPERATIONS = ['cancel', 'queue', 'run'] as const
type JobsLike = { access?: AccessMap } | undefined
/**
* The job queue has its own rules outside any collection (`jobs.access.run / queue / cancel`,
* by default "logged in"): POST /api/payload-jobs/run and the Local API's queue. Guarded like
* an entity, only when the project configured `jobs` at all.
*/
function guardJobs<T extends JobsLike>(jobs: T): T {
if (!jobs) {return jobs}
const access: AccessMap = { ...jobs.access }
for (const op of JOB_OPERATIONS) {access[op] = requireSecondFactor(access[op])}
return { ...jobs, access }
}
/** Every collection and global of a (not yet sanitized) config, guarded. Returns a new config. */
export function guardConfigAccess(config: Config): Config {
if (wrapperDisabled(config.custom)) {return config}
return {
...config,
...(config.jobs ? { jobs: guardJobs(config.jobs as JobsLike) as Config['jobs'] } : {}),
collections: (config.collections ?? []).map((c) => guardEntity(c as GuardedEntity, COLLECTION_OPERATIONS) as CollectionConfig),
globals: (config.globals ?? []).map((g) => guardEntity(g as GuardedEntity, GLOBAL_OPERATIONS) as GlobalConfig),
}
@@ -144,7 +184,17 @@ export function guardConfigAccess(config: Config): Config {
/**
* The same for a running Payload, in place: what plugins listed after ipalKit
* added. Returns the slugs it had to guard.
* added, and what Payload itself adds when it sanitizes the config. Returns
* the slugs it had to guard.
*
* EVERY collection and global is guarded — there is no exception by name or
* prefix. That includes Payload's own collections (in 3.94.1:
* payload-preferences, payload-locked-documents, payload-migrations,
* payload-query-presets, payload-folders, payload-jobs, payload-kv and the
* global payload-jobs-stats) and any a later Payload adds: an account that
* still owes its code needs none of them — the verify and setup screens are
* rendered from the session. A plugin that names its collection `payload-…`
* (e.g. `payload-mcp-api-keys`) is therefore covered like any other.
*/
export function guardPayloadAccess(payload: Pick<BasePayload, 'config'>): string[] {
if (wrapperDisabled(payload.config.custom)) {return []}
@@ -157,26 +207,61 @@ export function guardPayloadAccess(payload: Pick<BasePayload, 'config'>): string
for (const op of todo) {access[op] = requireSecondFactor(access[op])}
entity.access = access
}
// Payload's own collections (payload-preferences, payload-locked-documents, …) keep their rules:
// the panel uses them before the code is entered, and the package leaves them alone too.
for (const c of payload.config.collections ?? []) {
if (!c.slug.startsWith('payload-')) {sweep(c as GuardedEntity, COLLECTION_OPERATIONS)}
}
for (const c of payload.config.collections ?? []) {sweep(c as GuardedEntity, COLLECTION_OPERATIONS)}
for (const g of payload.config.globals ?? []) {sweep(g as GuardedEntity, GLOBAL_OPERATIONS)}
const jobs = (payload.config as { jobs?: JobsLike }).jobs
if (jobs && JOB_OPERATIONS.some((op) => !(jobs.access?.[op] as Guarded | undefined)?.[GUARDED])) {
jobs.access = guardJobs(jobs).access
late.push('jobs')
}
return late
}
/** Configs already swept — a new sanitized config (start, dev hot reload) is swept once. */
const swept = new WeakSet<object>()
/** Sweeps `payload.config` once per config object. Returns the slugs guarded now (empty when already done). */
export function ensurePayloadGuarded(payload: Pick<BasePayload, 'config'>): string[] {
/**
* Sweeps `payload.config` once per config object. Returns the slugs guarded
* now, or null when this config was swept before.
*/
export function ensurePayloadGuarded(payload: Pick<BasePayload, 'config'>): null | string[] {
const config = payload?.config
if (!config || swept.has(config)) {return []}
if (!config || swept.has(config)) {return null}
swept.add(config)
return guardPayloadAccess(payload)
}
/**
* Makes `payload.config` an accessor on this instance, so the moment Payload
* swaps the config (its dev `reload()` assigns `payload.config = …` and runs no
* onInit) `onConfig` is called — before any request or Local API call can use
* the new config. Without it the first HTTP request would do the same (the
* guard strategy), but a Local API call made before that request would meet
* unguarded entities from plugins listed after ipalKit. Never throws.
*/
export function watchPayloadConfig(payload: BasePayload, onConfig: (payload: BasePayload) => void): void {
try {
const own = Object.getOwnPropertyDescriptor(payload, 'config')
if (!own || own.get || !own.configurable) {return}
let current = own.value as BasePayload['config']
Object.defineProperty(payload, 'config', {
configurable: true,
enumerable: own.enumerable ?? true,
get: () => current,
set: (next: BasePayload['config']) => {
current = next
try {
onConfig(payload)
} catch {
// the guard strategy repeats it on the next request
}
},
})
} catch {
// an instance we cannot instrument: the guard strategy still covers HTTP
}
}
/** Name of the auth strategy ipalKit adds to the 2FA collection (see buildGuardStrategy). */
export const GUARD_STRATEGY_NAME = 'ipal-second-factor-guard'
@@ -188,12 +273,15 @@ export const GUARD_STRATEGY_NAME = 'ipal-second-factor-guard'
* where Payload swaps in a freshly built config and does not run onInit, and
* when Payload was started with `disableOnInit`.
*/
export function buildGuardStrategy(onLate?: (payload: BasePayload, slugs: string[]) => void) {
export function buildGuardStrategy(onConfig?: (payload: BasePayload) => void) {
return {
name: GUARD_STRATEGY_NAME,
authenticate: ({ payload }: { payload: BasePayload }) => {
const late = ensurePayloadGuarded(payload)
if (late.length) {onLate?.(payload, late)}
if (onConfig) {
onConfig(payload)
} else {
ensurePayloadGuarded(payload)
}
return { user: null }
},
}
@@ -216,20 +304,52 @@ type EndpointLike = { handler: (req: never) => Promise<Response> | Response; pat
* endpoints, whatever a later version adds) also needs the second factor,
* so a password alone cannot reset or remove TOTP.
*/
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string): T {
export type TotpEndpointGuards = {
/**
* Called for a verify attempt of a logged-in account before the package sees
* it. Return a Response to refuse (too many attempts), null to let it through.
*/
limitVerify?: (req: never) => null | Promise<null | Response> | Response
}
export function guardTotpEndpoint<T extends EndpointLike>(endpoint: T, collection: string, guards: TotpEndpointGuards = {}): T {
const handler = endpoint.handler as (req: MaybeReq) => Promise<Response> | Response
const refused = () => Response.json({ message: 'Not allowed.', ok: false }, { status: 403 })
return {
...endpoint,
handler: ((req: MaybeReq) => {
handler: (async (req: MaybeReq) => {
const user = req.user as { collection?: unknown } | null | undefined
if (user && user.collection !== collection) {return refused()}
if (user && !BEFORE_SECOND_FACTOR.has(endpoint.path) && !secondFactorPassed(req)) {return refused()}
// 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)
if (limited) {return limited}
}
return handler(req)
}) as unknown as T['handler'],
}
}
/**
* The same for endpoints the package may register on a collection or a global
* (none in the versions seen; a later one might): every endpoint that was not
* there before the package ran gets `guardTotpEndpoint`.
*/
export function guardNewEntityEndpoints<T extends { endpoints?: unknown; slug: string }>(
entities: T[] | undefined,
before: Map<string, Set<unknown>>,
collection: string,
guards?: TotpEndpointGuards,
): T[] {
return (entities ?? []).map((entity) => {
if (!Array.isArray(entity.endpoints)) {return entity}
const known = before.get(entity.slug) ?? new Set()
if (entity.endpoints.every((e) => known.has(e))) {return entity}
return { ...entity, endpoints: entity.endpoints.map((e) => (known.has(e) ? e : guardTotpEndpoint(e as EndpointLike, collection, guards))) }
})
}
/**
* The parts of @clocklimited/payload-2fa the guard relies on, checked right
* after the injected factory ran. A missing part means a version this guard
+64
View File
@@ -0,0 +1,64 @@
import type { PayloadRequest } from 'payload'
import { serverText } from '../../integrations/texts.js'
/**
* A limit on TOTP verify attempts. The 2FA package checks the code and never
* counts tries: a six-digit code with a ±1 step window has about three right
* answers in a million, so whoever holds the password could simply try.
*
* Counted per ACCOUNT, not per IP (an attacker changes addresses; the account
* is what is being guessed). Every attempt counts, right or wrong — nobody
* needs more than a handful of logins in the window. Only a session that
* 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.
*/
export type VerifyLimitOptions = {
/** Attempts per account in the window. Default 5. */
max?: number
/** Window in minutes; a refused account waits until it ends. Default 10. */
windowMinutes?: number
}
type Bucket = { count: number; resetAt: number }
const buckets = new Map<string, Bucket>()
/** For tests. */
export function clearVerifyLimits(): void {
buckets.clear()
}
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
return (req: PayloadRequest): 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".
const raw = (req.user as { id?: unknown }).id
const id = typeof raw === 'string' || typeof raw === 'number' ? String(raw) : JSON.stringify(raw ?? null)
const now = Date.now()
// keep the map small: forget windows that are over
if (buckets.size > 5000) {
for (const [key, bucket] of buckets) {
if (bucket.resetAt <= now) {buckets.delete(key)}
}
}
const key = `${collection}:${id}`
const current = buckets.get(key)
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))
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 },
{ headers: { 'Retry-After': String(retryAfter) }, status: 429 },
)
}
}