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
+24
View File
@@ -159,6 +159,30 @@ describe('forms collection: public read, editor+ write, Emails hidden from plain
})
})
describe('form submissions over REST / GraphQL: staff only (1.17.2)', () => {
const build = async (forms: object = {}) => {
const config = await iapl({ access: { authCollection: 'users' }, forms, i18n, twoFactor: false })(
empty({ collections: [{ slug: 'customers', auth: true, fields: [] }] }),
)
return config.collections?.find((c) => c.slug === 'form-submissions') as CollectionConfig
}
// the staff check reads the panel's collection from the request's Payload, as in a request
const runAs = (fn: Access | undefined, u: unknown) =>
(fn as Access)({ req: { payload: { config: { admin: { user: 'users' } } }, user: u } } as never)
test('a customer account, or nobody, cannot create a submission; any staff role can', async () => {
const { access = {} } = await build()
expect(runAs(access.create, null)).toBe(false)
expect(runAs(access.create, { id: 9, collection: 'customers' })).toBe(false)
for (const staff of [user, editor, admin]) {expect(runAs(access.create, staff)).toBe(true)}
})
test('formSubmissionOverrides.access.create is the way back', async () => {
const { access = {} } = await build({ formSubmissionOverrides: { access: { create: () => true } } })
expect(runAs(access.create, { id: 9, collection: 'customers' })).toBe(true)
})
})
describe('roles field: the first-register account becomes admin', () => {
const hook = async (totalDocs: number, value: string[], pathname = '/api/users/first-register') => {
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
+13 -1
View File
@@ -206,6 +206,18 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
expect(await run(cfg, ['open-signup'])).toEqual([])
})
test('visitor-writes: one warning per entity a visitor account may write, its operations named', async () => {
const cfg = "iapl({ access: { authCollection: 'users' } })"
const report = await doctor(project({ ...base(), 'src/payload.config.ts': cfg }), ['visitor-writes'], { deepStatus: { visitorWrites: ['globals/header:update', 'pages:create', 'pages:delete', 'pages:update'] } })
expect(report.findings.map((f) => `${f.severity}: ${f.message}`)).toEqual([
'warning: an account of a visitor login collection may update the global "header"',
'warning: an account of a visitor login collection may create, delete, update in "pages"',
])
expect(await run(cfg, ['visitor-writes'], { visitorWrites: [] })).toEqual([])
expect(await run(cfg, ['visitor-writes'], { visitorWrites: null })).toEqual([])
expect(await run(cfg, ['visitor-writes'])).toEqual([])
})
test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => {
const cfg = "iapl({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error'])
@@ -542,7 +554,7 @@ describe('security and deep status', () => {
}
const status = await collectDoctorStatus(payload as never)
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
expect(status.mail).toBeNull() // no Site integrations global in this config
})
+95
View File
@@ -0,0 +1,95 @@
/**
* Payload's job queue over HTTP (1.17.2, IAWL idea 35, owner's Q2): when the project writes no `jobs.access.run`,
* only an admin signed in with the second factor, or `Authorization: Bearer <CRON_SECRET>`, may run it. Payload's
* default let any signed-in account of any auth collection run the queue — a customer included.
*/
import type { Config, SanitizedConfig } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { jobsRunNotice, withJobsRunAccess } from '../src/modules/security/jobsAccess.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
const SECRET = 'a-cron-secret-of-32-characters!!'
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const project = (jobs?: Config['jobs']): Config =>
({
collections: [{ slug: 'customers', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }],
db: sqliteAdapter({ client: { url: 'file::memory:' } }),
jobs: { ...jobs, tasks: [{ slug: 'noop', handler: () => ({ output: {} }) }] },
secret: 'jobs-access-test',
telemetry: false,
}) as unknown as Config
const build = (jobs?: Config['jobs'], options: object = {}) =>
buildTestConfig({ ...project(jobs), plugins: [iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)] })
/** Calls the sanitized run rule the way Payload's run endpoint does. */
const runAs = async (config: SanitizedConfig, user: unknown, authorization?: string) => {
const req = { headers: new Headers(authorization ? { authorization } : {}), payload: { config }, user }
return Boolean(await (config.jobs.access!.run as (a: { req: unknown }) => unknown)({ req }))
}
const admin = { id: 1, collection: 'users', roles: ['admin'] }
const editor = { id: 2, collection: 'users', roles: ['editor'] }
const customer = { id: 3, collection: 'customers' }
afterEach(() => {
vi.unstubAllEnvs()
})
describe('jobs.access.run when the project writes none', () => {
test('an admin, or the cron secret; not an editor, a customer or nobody', async () => {
vi.stubEnv('CRON_SECRET', SECRET)
const config = await build()
expect(await runAs(config, admin)).toBe(true)
expect(await runAs(config, null, `Bearer ${SECRET}`)).toBe(true)
expect(await runAs(config, null)).toBe(false)
expect(await runAs(config, customer)).toBe(false)
expect(await runAs(config, editor)).toBe(false)
expect(await runAs(config, null, 'Bearer wrong-secret-wrong-secret')).toBe(false)
expect(await runAs(config, customer, SECRET)).toBe(false) // without "Bearer "
}, 30_000)
test('a missing or short secret never matches', async () => {
vi.stubEnv('CRON_SECRET', 'short')
const config = await build()
expect(await runAs(config, null, 'Bearer short')).toBe(false)
vi.stubEnv('CRON_SECRET', '')
expect(await runAs(config, null, 'Bearer ')).toBe(false)
}, 30_000)
test('secretVar names another variable', async () => {
vi.stubEnv('MY_JOBS_SECRET', SECRET)
const config = await build(undefined, { jobsRunAccess: { secretVar: 'MY_JOBS_SECRET' } })
expect(await runAs(config, null, `Bearer ${SECRET}`)).toBe(true)
}, 30_000)
test('the project\'s own rule wins; jobsRunAccess: false keeps Payload\'s default', async () => {
const own = await build({ access: { run: () => true } })
expect(await runAs(own, null)).toBe(true)
const payloadDefault = await build(undefined, { jobsRunAccess: false })
expect(await runAs(payloadDefault, customer)).toBe(true) // Payload: any signed-in account
}, 30_000)
test('a config without jobs gets the rule too (Payload turns the queue on for scheduled publishing)', () => {
const config = withJobsRunAccess({ secret: 'x' } as Config)
expect(typeof config.jobs?.access?.run).toBe('function')
expect(withJobsRunAccess({ secret: 'x' } as Config, false).jobs).toBeUndefined()
})
test('at start: a note when the queue is on, the rule is iapl\'s and the secret is missing', () => {
const custom = { iapl: { jobsRunDefault: { secretVar: 'CRON_SECRET' } } }
vi.stubEnv('CRON_SECRET', '')
expect(jobsRunNotice({ custom, jobs: { enabled: true } })).toMatch(/Authorization: Bearer <CRON_SECRET>.*not set/)
expect(jobsRunNotice({ custom, jobs: { enabled: false } })).toBeNull()
expect(jobsRunNotice({ custom: {}, jobs: { enabled: true } })).toBeNull()
vi.stubEnv('CRON_SECRET', SECRET)
expect(jobsRunNotice({ custom, jobs: { enabled: true } })).toBeNull()
})
})
+56
View File
@@ -0,0 +1,56 @@
/**
* The doctor's `visitor-writes` probe (1.17.2, the owner's Q3 answer (b)): on a site with a visitor login collection,
* every collection and global whose write rule lets such an account in — Payload's default "any signed-in account"
* included — is listed. Asked by behaviour on the built config, never by a rule's name.
*/
import type { Config, SanitizedConfig } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { describe, expect, test, vi } from 'vitest'
import { adminOrEditor } from '../src/modules/access/access.js'
import { visitorWritableEntities } from '../src/modules/doctor/visitorWrites.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
const build = (collections: Config['collections'], globals: Config['globals'] = []) =>
buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: true }, ...(collections ?? [])],
db: sqliteAdapter({ client: { url: 'file::memory:' } }),
editor: lexicalEditor(),
globals,
plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false } as never)],
secret: 'visitor-writes-test',
telemetry: false,
} as unknown as Config)
/** The live shape the probe reads (`payload.collections`, `payload.config`), from a built config. */
const live = (config: SanitizedConfig) => ({ collections: Object.fromEntries(config.collections.map((c) => [c.slug, { config: c }])), config }) as never
describe('visitorWritableEntities', () => {
test('with a visitor login collection: Payload\'s defaults are listed, explicit staff rules and the plugin\'s own are not', async () => {
const config = await build(
[
{ slug: 'customers', access: { create: () => true, delete: () => false, update: ({ req }) => ({ id: { equals: req.user?.id } }) }, auth: true, fields: [] },
{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] },
{ slug: 'posts', access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, fields: [{ name: 'title', type: 'text' }] },
],
[{ slug: 'header', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }],
)
const open = await visitorWritableEntities(live(config))
expect(open).toEqual(expect.arrayContaining(['customers:create', 'globals/header:update', 'media:create', 'media:delete', 'media:update', 'pages:create', 'pages:delete', 'pages:update', 'payload-locked-documents:create']))
// explicit staff rules, a rule that answers a query, "nobody", the plugin's own entities
for (const closed of ['posts:create', 'posts:update', 'posts:delete', 'customers:update', 'customers:delete', 'form-submissions:create', 'forms:create', 'globals/site-settings:update', 'globals/site-integrations:update', 'payload-kv:create']) {
expect(open).not.toContain(closed)
}
}, 30_000)
test('a site with only the staff login collection: nothing to report', async () => {
const config = await build([{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }])
expect(await visitorWritableEntities(live(config))).toEqual([])
}, 30_000)
})