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:
@@ -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
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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`.
|
||||
*/
|
||||
|
||||
@@ -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").'
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user