diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index 888a9e0..224e40c 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -35,6 +35,7 @@ through this procedure. Ask only when you are missing something you cannot get y | Symptom | Cause | Fix | |---|---|---| | the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment | +| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer | | `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` | | startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) | | own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count | diff --git a/docs/security.md b/docs/security.md index 4407e0b..0f54483 100644 --- a/docs/security.md +++ b/docs/security.md @@ -412,13 +412,17 @@ The order of the project's `plugins` array does not matter, and **there is no ex collections (in 3.94.1: `payload-preferences`, `payload-locked-documents`, `payload-migrations`, `payload-query-presets`, `payload-folders`, `payload-jobs`, `payload-kv`, the global `payload-jobs-stats`) are guarded like every other, and so is whatever a later Payload version or a plugin adds under any slug -(`payload-mcp-api-keys`, …). The job queue's own rules (`jobs.access.run / queue / cancel`) are guarded too. +(`payload-mcp-api-keys`, …). The job queue's own rules (`jobs.access.run / queue / cancel`) are guarded too: +Payload's defaults stay exactly as Payload sets them (in 3.94.1 a logged-in user for all three); a session that +owes its code is refused. Only `access.admin` (may this account open the panel) is left alone: the code is entered inside the panel, and the verify and setup screens are rendered from the session, not from any collection. A session that still owes its code is refused **everything**, also what anonymous visitors may read (Site settings, Notifications, the Cookie banner, forms): for that account the answer is `403` until the code is -entered. The public site is not affected — it reads on the server. +entered. The public site is not affected — it reads on the server; only files the browser fetches itself with +that session's cookie (images from `media`) are refused, so an editor who typed the password and not yet the code +sees broken images on the site until the code is entered or they log out. An account of the 2FA collection passes when it logged in with **password and code**, or uses an **API key** (`auth.useAPIKey`), or has **not set TOTP up yet** (the setup screen needs that; the package behaves the same). diff --git a/reference/.agents/skills/ipal-debug/SKILL.md b/reference/.agents/skills/ipal-debug/SKILL.md index 888a9e0..224e40c 100644 --- a/reference/.agents/skills/ipal-debug/SKILL.md +++ b/reference/.agents/skills/ipal-debug/SKILL.md @@ -35,6 +35,7 @@ through this procedure. Ask only when you are missing something you cannot get y | Symptom | Cause | Fix | |---|---|---| | the 2FA code screen answers "Too many codes were tried…" (`429` from `/api/verify-totp`) | more than 5 verify attempts for that account in 10 minutes (`twoFactor.verifyLimit`); repeated lines `[ipal] 2FA: too many verify attempts` in the log without the owner trying = someone has the password | wait for the window, enter the current code once; unexplained attempts: change that account's password. Tests that log in often: `verifyLimit: { max: … }` for that environment | +| `isAdmin(req.user)` says `false` for a real administrator on the server, in a process that loads two Payload configs (tests, a multi-site script) | a call without a source counts only collections that are staff in **every** config of the process | pass the source: `isAdmin(req.user, req.payload)` — with it each config gets its own answer | | `isAdmin(user)` / `isEditor(user)` is always `false` in a client component or in `proxy.ts` | the staff collections are not known there (no config in the browser bundle / middleware), and the predicates fail closed | `isAdmin(user, config)` with `useConfig()`; in middleware `isAdmin(user, { staffCollections: ['users'] })` | | startup: `[ipal] twoFactor: the injected 2FA plugin did not add the totpSecret field / hasTotp field / totp auth strategy` | the installed `@clocklimited/payload-2fa` is not a version ipal-kit's second-factor check recognises (tested: 3.0.0-beta.1 and beta.7), or a custom factory was injected | install a supported version; stop-gap only: `twoFactor.guard: false` (the plugin's own data is then not covered by 2FA — security.md) | | own route or script gets `403` / "not allowed" on `form-submissions`, `forms`, a settings global with `overrideAccess: false`, although the user is an admin | the `user` was fetched by id and passed by hand: it does not carry how the account logged in, so the second-factor check refuses it | take the user from `payload.auth({ headers })` (it sets `collection` and how the account logged in), or (server-only code that needs no access check) leave `overrideAccess` at its default; a hand-built user needs at least `collection: 'users'` for its role to count | diff --git a/src/modules/security/totp/secondFactor.ts b/src/modules/security/totp/secondFactor.ts index 060a093..f3b9da0 100644 --- a/src/modules/security/totp/secondFactor.ts +++ b/src/modules/security/totp/secondFactor.ts @@ -69,7 +69,10 @@ export function secondFactorPassed({ payload, user }: MaybeReq): boolean { 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 + // "Not set up yet" only when nothing says otherwise. The package computes `hasTotp` with a second + // database read and answers false when that read fails; the secret on the user object itself (it + // came with the account's own record) then still says the account has TOTP: refused. + return u.hasTotp === false && !(user as { totpSecret?: unknown }).totpSecret } const GUARDED = Symbol.for('ipal.secondFactorGuard') @@ -156,18 +159,26 @@ function guardEntity(entity: T, operations: readonly st return { ...entity, access } } +/** + * The job queue has its own rules outside any collection: `jobs.access.run / queue / cancel` + * (POST /api/payload-jobs/run, `payload.jobs.queue()` / `.cancel()` with `overrideAccess: false`). + * + * Payload's defaults are kept exactly, by not inventing any: only a rule that EXISTS is wrapped + * ("…and not while the second factor is owed"). At config time that is what the project wrote; + * when Payload builds the config it fills the rest in itself (3.94.1, config/defaults.js: `run`, + * `queue` and `cancel` are all `defaultAccess`, a logged-in user — the `?? (() => true)` in + * queues/localAPI.js is never reached on a built config), and the sweep of the running config + * wraps those. So a request without a user gets whatever Payload itself answers. + */ 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(jobs: T): T { - if (!jobs) {return jobs} + if (!jobs?.access) {return jobs} const access: AccessMap = { ...jobs.access } - for (const op of JOB_OPERATIONS) {access[op] = requireSecondFactor(access[op])} + for (const op of JOB_OPERATIONS) { + if (access[op]) {access[op] = requireSecondFactor(access[op])} + } return { ...jobs, access } } @@ -210,7 +221,7 @@ export function guardPayloadAccess(payload: Pick): string 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])) { + if (jobs?.access && JOB_OPERATIONS.some((op) => jobs.access?.[op] && !(jobs.access[op] as Guarded)[GUARDED])) { jobs.access = guardJobs(jobs).access late.push('jobs') } diff --git a/test/secondFactorGuard.test.ts b/test/secondFactorGuard.test.ts index 7c452f9..dc080b5 100644 --- a/test/secondFactorGuard.test.ts +++ b/test/secondFactorGuard.test.ts @@ -99,6 +99,7 @@ describe('secondFactorPassed', () => { ['an unknown strategy name (fail closed)', { _strategy: 'two-factor', collection: 'users', hasTotp: true }, false], ['an account of another auth collection', { _strategy: 'local-jwt', collection: 'customers' }, true], ['a user object that does not say its collection (fail closed)', { _strategy: 'totp', hasTotp: true }, false], + ['`hasTotp` false although the record carries a secret (the package\'s lookup failed): refused', { _strategy: 'local-jwt', collection: 'users', hasTotp: false, totpSecret: 'JBSWY3DPEHPK3PXP' }, false], ] test.each(cases)('%s', (_, user, expected) => { expect(secondFactorPassed({ payload, user })).toBe(expected) @@ -148,18 +149,27 @@ describe('ipalKit and the 2FA plugin', () => { const late = { slug: 'late', access: {} as Record } const prefixed = { slug: 'payload-vault', access: {} as Record } // a plugin's collection, e.g. payload-mcp-api-keys const internal = { slug: 'payload-preferences', access: {} as Record } - const jobs = { access: {} as Record } + const loggedIn = ({ req }: { req: { user?: unknown } }) => Boolean(req.user) // Payload's defaultAccess + const jobs = { access: { cancel: loggedIn, queue: loggedIn, run: loggedIn } as Record } const payload = { config: { collections: [late, prefixed, internal], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [{ slug: 'payload-jobs-stats' }], jobs } } as never expect(guardPayloadAccess(payload)).toEqual(['late', 'payload-vault', 'payload-preferences', 'payload-jobs-stats', 'jobs']) for (const entity of [late, prefixed, internal]) { expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false) expect((entity.access.read as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true) } - // the job queue's own rules (run / queue / cancel) + // the job queue's rules as Payload filled them in (3.94.1: all three "a logged-in user"): kept, plus + // "not while the second factor is owed" + const job = (op: string, user: unknown) => (jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user } }) for (const op of ['run', 'queue', 'cancel']) { - expect((jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user: passwordOnly } })).toBe(false) - expect((jobs.access[op] as (a: unknown) => unknown)({ req: { payload, user: verified } })).toBe(true) + expect([op, job(op, null), job(op, passwordOnly), job(op, verified)]).toEqual([op, false, false, true]) } + // a rule the project set is kept as it is; a rule nobody set is not invented (Payload fills it in) + const own = { access: { queue: () => true } as Record } + guardPayloadAccess({ config: { collections: [], custom: { ipal: { twoFactor: { collection: 'users' } } }, globals: [], jobs: own } } as never) + const ownQueue = (user: unknown) => (own.access.queue as (a: unknown) => unknown)({ req: { payload, user } }) + expect([ownQueue(null), ownQueue(passwordOnly), ownQueue(verified)]).toEqual([true, false, true]) + expect(own.access.run).toBeUndefined() + expect(own.access.cancel).toBeUndefined() expect(guardPayloadAccess(payload)).toEqual([]) // nothing left to do the second time expect(ensurePayloadGuarded(payload)).toEqual([]) expect(ensurePayloadGuarded(payload)).toBeNull() // this config object was done diff --git a/test/securityHttp.test.ts b/test/securityHttp.test.ts index b1ba6b8..6938ce1 100644 --- a/test/securityHttp.test.ts +++ b/test/securityHttp.test.ts @@ -419,6 +419,24 @@ describe('no exception by name: a later plugin\'s `payload-…` collection is gu }) }) +describe("the job queue keeps Payload's own defaults", () => { + // Payload's `defaultAccess` (3.94.1 fills run, queue and cancel with it when the config is built) + const payloadDefault = (user: unknown) => Boolean(user) + + test('without a user: what Payload itself answers; a password-only session is refused; a verified one is not', async () => { + const access = payload.config.jobs.access! + const admin = (await payload.find({ collection: 'users' as never, where: { email: { equals: 'admin@example.com' } } })).docs[0] + const as = (user: unknown) => ({ req: { payload, user } }) as never + for (const op of ['queue', 'cancel', 'run'] as const) { + expect([op, await access[op]!(as(null))]).toEqual([op, payloadDefault(null)]) + expect([op, await access[op]!(as({ ...admin, _strategy: 'local-jwt', collection: 'users' }))]).toEqual([op, false]) + expect([op, await access[op]!(as({ ...admin, _strategy: 'totp', collection: 'users' }))]).toEqual([op, true]) + } + // the Local API with access control on and no user: refused by Payload's own default, with or without the plugin + await expect(payload.jobs.queue({ input: {}, overrideAccess: false, task: 'no-such-task' } as never)).rejects.toThrow(/not allowed/i) + }) +}) + describe('the code cannot be guessed: verify attempts are limited per account', () => { const GUESS_SECRET = 'ONSWG4TFORRW6ZDF' let cookie: string