Merge claude/security-c-1172: form submissions over REST only for staff, the job queue for an admin or Bearer CRON_SECRET, doctor visitor-writes

Conflicts with security-a-1172 kept both sides: imports (adminSameOrigin, jobsAccess), the doctor status (originKnown and visitorWrites), its test, and the e2e:built line (A's sign-in answers spec with C's CRON_SECRET).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 11:17:51 +01:00
co-authored by Claude Opus 5.5
40 changed files with 657 additions and 187 deletions
+3
View File
@@ -496,6 +496,9 @@ export type {
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
// Payload's job queue over HTTP: an admin with the second factor or Bearer CRON_SECRET (security.md "Payload's job queue")
export { CRON_SECRET_ENV, CRON_SECRET_MIN_LENGTH, cronSecretMatches, jobsRunAccess, jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js'
export type { JobsRunAccessOptions } from './modules/security/jobsAccess.js'
// The doors a built config opens (REST, GraphQL, Next route files) and the judged snapshot they are checked against.
export { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from './modules/security/routeInventory.js'
export type { GraphqlSchemaLike, RouteInventoryOptions, RouteSnapshot, RouteSnapshotDiff } from './modules/security/routeInventory.js'
+24
View File
@@ -233,6 +233,30 @@ export const securityRules: DoctorRule[] = [
group: 'security',
source: 'deep',
},
{
// An account of a visitor login collection (customers, members) may write content or settings: Payload fills a
// missing rule with "any signed-in account", and the plugin narrows only its own entities (owner's Q3, 1.17.2).
id: 'visitor-writes',
check: (ctx) => {
const byEntity = new Map<string, string[]>()
for (const entry of ctx.deep?.visitorWrites ?? []) {
const at = entry.lastIndexOf(':')
byEntity.set(entry.slice(0, at), [...(byEntity.get(entry.slice(0, at)) ?? []), entry.slice(at + 1)])
}
return [...byEntity].map(([entity, operations]) => {
const global = entity.startsWith('globals/')
const slug = global ? entity.slice('globals/'.length) : entity
return {
fix: `give ${global ? 'the global' : 'the collection'} "${slug}" its own ${operations.map((o) => `access.${o}`).join(' / ')} (adminOrEditor, requireRole('editor'), …) — Payload's default lets every signed-in account in (access.md "Who is staff")`,
message: `an account of a visitor login collection may ${operations.join(', ')} ${global ? 'the global' : 'in'} "${slug}"`,
severity: 'warning' as const,
}
})
},
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// A staff collection that an account of another auth collection (a customer, a member) may write to:
// it can create a staff account, or change a staff account's password. The plugin's default rules close
+8 -1
View File
@@ -15,6 +15,7 @@ import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
import { readEnv } from '../shared/envName.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { turnstileSecretFromEnv } from '../turnstile/config.js'
import { visitorWritableEntities } from './visitorWrites.js'
/** The plugin's own version — a constant (src/version.ts), never a file read at run time. */
export function pluginVersion(): string {
@@ -111,9 +112,15 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
} catch {
staffOnOwnRoles = null
}
let visitorWrites: null | string[] = null
try {
visitorWrites = await visitorWritableEntities(payload as never)
} catch {
visitorWrites = null
}
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites }
}
export type DoctorEndpointOptions = {
+6
View File
@@ -123,6 +123,12 @@ export type DoctorStatus = {
/** Of `usersWithout2fa`: accounts whose setup window has passed (blocked until an admin reopens setup). */
usersSetupClosed?: null | number
usersWithout2fa?: null | number
/**
* What an account of a visitor login collection (an auth collection that is not staff) may write, as `pages:create`
* or `globals/header:update` — rules that answer `true` for it, Payload's default included. Empty without a visitor
* login collection; null = could not be checked.
*/
visitorWrites?: null | string[]
}
export type DoctorLive = {
+46
View File
@@ -0,0 +1,46 @@
import { staffCollectionSlugs } from '../access/predicates.js'
type Rule = ((args: never) => unknown) | undefined
type LiveEntity = { access?: Record<string, Rule>; auth?: unknown; slug: string }
type LivePayload = {
collections?: Record<string, { config: LiveEntity }>
config?: { globals?: LiveEntity[] }
}
/**
* What an account of a visitor login collection (a shop's customers, a member zone — an auth collection that is not
* staff) may WRITE: every collection `create` / `update` / `delete` and global `update` whose rule answers a plain
* `true` for such an account, as `pages:create` or `globals/header:update`. For the doctor's `visitor-writes` rule
* (IAWL idea 35, the owner's Q3). Empty when the site has no visitor login collection.
*
* Asked by behaviour, never by the rule's name (a production build renames every function): Payload's default
* ("any signed-in account") and a project's own rule that is as wide both answer `true`. A rule that answers a query
* (e.g. "its own document") is not counted, nor one that throws. Staff collections are left to `staff-accounts-open`.
*/
export async function visitorWritableEntities(payload: LivePayload): Promise<string[]> {
const staff = staffCollectionSlugs(payload as never)
const collections = Object.values(payload.collections ?? {}).map(({ config }) => config)
const visitors = collections.filter((c) => c.auth && !staff.includes(c.slug)).map((c) => c.slug)
if (!visitors.length) {return []}
const open = new Set<string>()
const ask = async (rule: Rule, key: string) => {
for (const collection of visitors) {
const user = { id: '__iapl-visitor__', collection, email: '[email protected]' }
try {
// no rule = Payload's default: any signed-in account
if (!rule || (await rule({ id: '__iapl-other__', req: { context: {}, headers: new Headers(), payload, user } } as never)) === true) {
open.add(key)
return
}
} catch {
/* closed */
}
}
}
for (const config of collections) {
if (staff.includes(config.slug)) {continue}
for (const operation of ['create', 'update', 'delete'] as const) {await ask(config.access?.[operation], `${config.slug}:${operation}`)}
}
for (const global of payload.config?.globals ?? []) {await ask(global.access?.update, `globals/${global.slug}:update`)}
return [...open].sort()
}
+8 -3
View File
@@ -162,8 +162,13 @@ const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'ra
/** Text-like built-ins also get a localized "Placeholder" (select already has one). */
const withHint = (key: 'email' | 'number' | 'text' | 'textarea') => withShowWhen(withPlaceholder(builtinBlocks[key] as Block))
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
/**
* REST/GraphQL: a staff account (any role) with its second factor. Local API (submitForm) is unaffected. Before
* 1.17.2 any signed-in account was enough — a customer of a visitor login collection could POST
* /api/form-submissions past the rate limit, Turnstile, consent and validation, and the form's e-mails went out.
* `formSubmissionOverrides.access.create` is the way back.
*/
const submissionsCreateAccess = ({ req }: AccessArgs) => userMeetsRole(req, 'user')
/**
* Submissions are visitors' personal data: editors and admins only. The
* form-builder default lets ANY account of the admin collection read them —
@@ -205,7 +210,7 @@ function hideEmails(fields: Field[]): Field[] {
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
* anyone can POST /api/form-submissions and skip everything submitForm enforces
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
* creation is limited to logged-in users; the site submits through submitForm
* creation is limited to staff accounts with their second factor; the site submits through submitForm
* (server action → Local API, which bypasses access by design). A project that
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
*/
+78
View File
@@ -0,0 +1,78 @@
import type { Config, PayloadRequest } from 'payload'
import { createHash, timingSafeEqual } from 'node:crypto'
import { userMeetsRole } from '../access/predicates.js'
/**
* Who may run Payload's job queue over HTTP (`GET /api/payload-jobs/run`, `/api/payload-jobs/handle-schedules`,
* both checked by `jobs.access.run`). Payload's own default is any signed-in account of ANY auth collection — a
* customer of a shop included (IAWL idea 35: a route open to the web is a visitor, not the system). Since 1.17.2,
* when the project writes no `jobs.access.run`, iapl sets: an admin signed in with the second factor (an admin's API
* key counts), or `Authorization: Bearer <CRON_SECRET>`. A project's own rule always wins; `jobsRunAccess: false`
* keeps Payload's default. Jobs run in-process (`jobs.autoRun`, `payload jobs:run`, `payload.jobs.run()`) never
* pass through this rule.
*/
export type JobsRunAccessOptions = {
/** The variable holding the cron secret. Default `CRON_SECRET`. Shorter than 16 characters = not used. */
secretVar?: string
}
export const CRON_SECRET_ENV = 'CRON_SECRET'
/** The secret's minimum length: a short one would be guessable over the run route. */
export const CRON_SECRET_MIN_LENGTH = 16
const sha = (value: string) => createHash('sha256').update(value).digest()
/** True when the request carries `Authorization: Bearer <secret>` (constant-time; an unset or short secret never matches). */
export function cronSecretMatches(req: Pick<PayloadRequest, 'headers'>, secret: string | undefined): boolean {
const expected = secret?.trim() ?? ''
if (expected.length < CRON_SECRET_MIN_LENGTH) {return false}
const header = req.headers?.get?.('authorization') ?? ''
if (!/^Bearer\s+/i.test(header)) {return false}
return timingSafeEqual(sha(header.replace(/^Bearer\s+/i, '').trim()), sha(expected))
}
/**
* The rule iapl puts on `jobs.access.run` (exported for a project that writes its own and wants to keep this part):
* jobs: { access: { run: (args) => jobsRunAccess()(args) || myOwnCheck(args) } }
*/
export function jobsRunAccess({ secretVar = CRON_SECRET_ENV }: JobsRunAccessOptions = {}) {
return ({ req }: { req: PayloadRequest }): boolean =>
cronSecretMatches(req, process.env[secretVar]) || userMeetsRole(req, 'admin')
}
/**
* The config with iapl's `jobs.access.run`, only when the project wrote none (checked before Payload fills its
* default in, so a project's rule is never mistaken for Payload's). Also when the config has no `jobs` at all:
* Payload turns the queue on by itself for collections with scheduled publishing. Marks the config
* (`custom.iapl.jobsRunDefault`) so the start-up note knows the rule is iapl's.
*/
export function withJobsRunAccess(config: Config, options: false | JobsRunAccessOptions = {}): Config {
if (options === false || config.jobs?.access?.run) {return config}
const custom = (config.custom ?? {}) as Record<string, unknown>
const iapl = (custom.iapl ?? {}) as Record<string, unknown>
return {
...config,
custom: { ...custom, iapl: { ...iapl, jobsRunDefault: { secretVar: options.secretVar ?? CRON_SECRET_ENV } } },
jobs: { ...config.jobs, access: { ...config.jobs?.access, run: jobsRunAccess(options) } } as Config['jobs'],
}
}
/**
* The one line said at start when the queue is on and the rule is iapl's: how a cron reaches the run route.
* Null when there is nothing to say.
*/
export function jobsRunNotice(config: { custom?: unknown; jobs?: { enabled?: boolean } }): null | string {
const own = ((config.custom as { iapl?: { jobsRunDefault?: { secretVar?: string } } } | undefined)?.iapl)?.jobsRunDefault
if (!own || !config.jobs?.enabled) {return null}
const secretVar = own.secretVar ?? CRON_SECRET_ENV
const secret = process.env[secretVar]?.trim() ?? ''
if (secret.length >= CRON_SECRET_MIN_LENGTH) {return null}
return (
`[iapl] Payload's job queue runs over HTTP (/api/payload-jobs/run, /handle-schedules) only for an admin signed in with the second factor ` +
`or with "Authorization: Bearer <${secretVar}>" (1.17.2), and ${secretVar} is ${secret ? `shorter than ${CRON_SECRET_MIN_LENGTH} characters` : 'not set'}. ` +
`A cron that calls the run route: set ${secretVar} and send the header. In-process runs (jobs.autoRun, payload jobs:run) are not affected. ` +
'Your own jobs.access.run wins; iapl({ jobsRunAccess: false }) keeps Payload\'s default (docs/security.md "Payload\'s job queue").'
)
}
+7
View File
@@ -51,6 +51,7 @@ import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/inde
import { serverText } from './modules/integrations/texts.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { guardAdminEndpoints } from './modules/security/adminSameOrigin.js'
import { jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js'
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
import { reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
@@ -987,6 +988,9 @@ export const iapl = (options: IaplOptions): Plugin => {
},
}
// --- Payload's job queue over HTTP: an admin or the cron secret, unless the project wrote its own rule
config = withJobsRunAccess(config, options.jobsRunAccess ?? {})
// --- second factor on everything in the config by now: the project's
// collections (wrapped by the package already; twice is harmless), the
// plugin's globals and collections, the form builder's.
@@ -1016,6 +1020,9 @@ export const iapl = (options: IaplOptions): Plugin => {
watchTransactions(payload, options.connectionReserve === false ? false : (options.connectionReserve ?? defaultConnectionReserve(poolSize(payload) ?? 10)))
// Microsoft Graph is deprecated (removed in 2.0): one warning per start while its variables are set.
if (graphAvailable() && options.mail?.graphDeprecationWarning !== false) {payload.logger.warn(GRAPH_DEPRECATION_NOTICE)}
// The queue is on and the run route is iapl's: say how a cron reaches it, when the secret is missing.
const jobsNotice = jobsRunNotice(payload.config as never)
if (jobsNotice) {payload.logger.warn(jobsNotice)}
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
watchPayloadConfig(payload, adoptConfig)
if (staleSignInLook) {
+11
View File
@@ -27,6 +27,7 @@ import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
import type { I18nConfig } from './modules/i18n/types.js'
import type { PagesOption } from './modules/pages/types.js'
import type { AdminSameOriginOption } from './modules/security/adminSameOrigin.js'
import type { JobsRunAccessOptions } from './modules/security/jobsAccess.js'
import type { SafeBackRule } from './modules/security/totp/safeBack.js'
import type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
@@ -209,6 +210,16 @@ export type IaplOptions = {
/** Additional fields injected into SiteIntegrations global */
integrationsFields?: Field[]
/**
* Who may run Payload's job queue over HTTP (`/api/payload-jobs/run`, `/handle-schedules`) when the project
* writes no `jobs.access.run` of its own: an admin signed in with the second factor (an admin's API key counts), or
* `Authorization: Bearer <CRON_SECRET>` (16+ characters). Default on since 1.17.2; `secretVar` names another
* variable; `false` keeps Payload's default (any signed-in account of any auth collection). A project's own
* `jobs.access.run` always wins. In-process runs (`jobs.autoRun`, `payload jobs:run`) are not affected.
* docs/security.md "Payload's job queue".
*/
jobsRunAccess?: false | JobsRunAccessOptions
/**
* Image lightbox labels in the Notifications global (a "Lightbox" group:
* close, previous, next, counter, dialog name, trigger name), localized per