Security audit fixes for 1.18.0: Markdown negotiation private + Vary: Accept (F3), public lists capped (F4), operator sort names refused (F5), CSP report log normalised and capped (F1), buildUrlField and the reference socials (F2), document locks for staff only

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 16:56:09 +01:00
co-authored by Claude Opus 5.5
parent d2f19095dc
commit e9f9947eb7
20 changed files with 677 additions and 49 deletions
+3 -6
View File
@@ -161,7 +161,6 @@ export const ATTACK_PROBES: AttackProbe[] = [
{
id: 'markdown-vary',
class: 'cache poisoning (content negotiation)',
finding: 'F3',
live: true,
run: async ({ fetch, page = '/' }) => {
const a = await fetch(page, { follow: true, headers: { accept: 'text/markdown' } })
@@ -169,7 +168,7 @@ export const ATTACK_PROBES: AttackProbe[] = [
const cc = a.headers.get('cache-control') ?? ''
const shared = /s-maxage|public/.test(cc) && !/private|no-store/.test(cc)
const vary = (a.headers.get('vary') ?? '').split(',').map((v) => v.trim().toLowerCase())
if (shared && !vary.includes('accept') && !vary.includes('*')) {return bad(`${page} answers Markdown to Accept: text/markdown with "${cc}" and no Vary: Accept: a shared cache stores it under the HTML URL`)}
if (shared && !vary.includes('accept') && !vary.includes('*')) {return bad(`${page} answers Markdown to Accept: text/markdown with "${cc}" and no Vary: Accept: a shared cache stores it under the HTML URL (IAPL 1.18.0's createProxy sends private + Vary: Accept; a proxy of your own must too)`)}
return ok('the Markdown answer at the HTML URL varies by Accept or is not shared')
},
title: 'the Markdown copy at an HTML URL cannot be cached as the page',
@@ -260,7 +259,6 @@ export const ATTACK_PROBES: AttackProbe[] = [
{
id: 'sort-operator',
class: 'injection (operators in sort)',
finding: 'F5',
live: true,
run: async ({ fetch }) => {
const problems: string[] = []
@@ -268,14 +266,13 @@ export const ATTACK_PROBES: AttackProbe[] = [
const a = await fetch(`/api/pages?sort=${sort}&limit=1&depth=0`)
if (a.status >= 500 || LEAK.test(a.text)) {problems.push(`sort=${decodeURIComponent(sort)} → ${a.status}`)}
}
return problems.length ? bad(`${problems.join('; ')}: an operator name reaches the database as a sort field (an error and a logged stack trace per request)`) : ok('operator names in sort are refused with a 4xx')
return problems.length ? bad(`${problems.join('; ')}: an operator name reaches the database as a sort field (an error and a logged stack trace per request; IAPL 1.18.0 refuses it unless refuseOperatorSort is false)`) : ok('operator names in sort are refused with a 4xx')
},
title: 'an operator name in ?sort= is refused, not passed to the database',
},
{
id: 'unbounded-list',
class: 'denial of service (unbounded queries)',
finding: 'F4',
live: true,
run: async ({ fetch }) => {
const a = await fetch('/api/pages?limit=100000&depth=50')
@@ -286,7 +283,7 @@ export const ATTACK_PROBES: AttackProbe[] = [
} catch {
return skip('not JSON')
}
return (body.limit ?? 0) > 1000 ? bad(`/api/pages?limit=100000 is honoured (limit ${body.limit}, ${a.ms} ms, ${a.text.length} bytes): one anonymous request reads a whole collection`) : ok(`limit capped at ${body.limit}`)
return (body.limit ?? 0) > 1000 ? bad(`/api/pages?limit=100000 is honoured (limit ${body.limit}, ${a.ms} ms, ${a.text.length} bytes): one anonymous request reads a whole collection (IAPL 1.18.0 caps it unless listLimit is false or the collection is excluded)`) : ok(`limit capped at ${body.limit}`)
},
title: 'a public list caps limit (and depth) so one request cannot read a whole collection',
},
+79 -6
View File
@@ -1,3 +1,4 @@
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody } from '../shared/readCappedBody.js'
/** One CSP violation, normalised from either report format. */
@@ -15,12 +16,79 @@ export type CspViolation = {
export type CreateCspReportRouteArgs = {
/** Largest accepted body in bytes; bigger requests get 413. Default 16 KB. */
maxBytes?: number
/** Most violations handled from one request (a body may hold many). Default 10; the rest are dropped. */
maxReports?: number
/**
* What to do with each violation. Default: one `console.warn` line per
* violation (Coolify keeps container logs — read them there). Plug in
* payload.logger, Sentry or a database write here.
* violation (Coolify keeps container logs — read them there), made by
* {@link cspLogLine}: origins and paths only, no control characters, every value
* capped — a report cannot write a line of its own into the log. Your own
* `onReport` gets the values exactly as the browser sent them: escape them
* before you log them. Plug in payload.logger, Sentry or a database write here.
*/
onReport?: (violation: CspViolation) => Promise<void> | void
/**
* Requests per client (`clientIp`, IPv6 per /64) and window that are handled; over it the route still answers 204
* and handles nothing. Default `{ max: 60, windowMs: 60_000 }`; `false` = no limit.
*/
rateLimit?: { max?: number; windowMs?: number } | false
}
/** Longest value {@link cspLogLine} writes. */
export const CSP_LOG_VALUE_MAX = 128
/** Control characters (new lines among them) and the Unicode line separators: never in a log line. */
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g
const clean = (value: string | undefined, max = CSP_LOG_VALUE_MAX): string => {
if (!value) {return '?'}
const text = value.replace(CONTROL, ' ').trim()
return text.length > max ? `${text.slice(0, max)}…` : text || '?'
}
/** `https://cdn.x/a.js?q` → `https://cdn.x`; a keyword (`inline`, `eval`, `data`) stays as it is. */
const originOf = (value: string | undefined): string | undefined => {
if (!value) {return undefined}
try {
const url = new URL(value)
return url.origin === 'null' ? `${url.protocol}` : url.origin
} catch {
return value
}
}
/** `https://site.pl/pl/o-nas?x=1#y` → `/pl/o-nas` (no query: it may hold personal data). */
const pathOf = (value: string | undefined): string | undefined => {
if (!value) {return undefined}
try {
return new URL(value).pathname
} catch {
return value.split(/[?#]/)[0]
}
}
/** `https://cdn.x/a.js?q` → `https://cdn.x/a.js`: where the script lives, without its query. */
const scriptOf = (value: string): string => {
try {
const url = new URL(value)
return url.origin === 'null' ? url.protocol : `${url.origin}${url.pathname}`
} catch {
return value.split(/[?#]/)[0]
}
}
/**
* The default log line of one violation: the blocked resource's origin, the page's path, the script's origin and path
* with its line — control characters removed, every value at most {@link CSP_LOG_VALUE_MAX} characters (security
* audit 2026-12, F1). Use it in your own `onReport` for the same line.
*/
export function cspLogLine(v: CspViolation): string {
const source = v.sourceFile ? scriptOf(v.sourceFile) : ''
return (
`[csp] ${clean(v.disposition ?? 'report', 16)} ${clean(v.effectiveDirective, 32)} blocked=${clean(originOf(v.blockedUri))} ` +
`page=${clean(pathOf(v.documentUri))}${source ? ` src=${clean(source)}:${typeof v.lineNumber === 'number' ? v.lineNumber : ''}` : ''}`
)
}
type Raw = Record<string, unknown>
@@ -86,14 +154,19 @@ export function parseCspReports(body: unknown): CspViolation[] {
export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (request: Request) => Promise<Response> {
const {
maxBytes = 16 * 1024,
maxReports = 10,
onReport = (v: CspViolation) => {
console.warn(
`[csp] ${v.disposition ?? 'report'} ${v.effectiveDirective ?? '?'} blocked=${v.blockedUri ?? '?'} page=${v.documentUri ?? '?'}${v.sourceFile ? ` src=${v.sourceFile}:${v.lineNumber ?? ''}` : ''}`,
)
console.warn(cspLogLine(v))
},
rateLimit = {},
} = args
return async (request: Request) => {
if (rateLimit) {
const { ok } = await consumeRateLimit({ key: clientIp(request), max: rateLimit.max ?? 60, scope: 'csp-report', windowMs: rateLimit.windowMs ?? 60_000 })
// the browser does not read the answer: 204 either way, nothing handled
if (!ok) {return new Response(null, { status: 204 })}
}
// read only up to the cap, whether or not the browser declared the length (a chunked body has none)
let text: null | string
try {
@@ -110,7 +183,7 @@ export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (requ
return new Response(null, { status: 400 })
}
for (const violation of parseCspReports(body).slice(0, 50)) {
for (const violation of parseCspReports(body).slice(0, Math.max(0, maxReports))) {
try {
await onReport(violation)
} catch {
+1 -1
View File
@@ -10,7 +10,7 @@ export {
export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } from './buildSecurityHeaders.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js'
export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js'
export { createCspReportRoute, CSP_LOG_VALUE_MAX, cspLogLine, parseCspReports } from './createCspReportRoute.js'
export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js'
export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js'
export { totpAdminPath, totpRedirectTarget } from './totp/totpRedirect.js'
+136
View File
@@ -0,0 +1,136 @@
import type { Access, CollectionBeforeOperationHook, CollectionConfig, Config, PayloadRequest, SanitizedConfig } from 'payload'
import { APIError } from 'payload'
import { staffCollectionSlugs } from '../access/predicates.js'
import { secondFactorPassed } from './totp/secondFactor.js'
/**
* Guards for what a REST / GraphQL caller may ask of a collection list (security audit 2026-12, F4 and F5), and
* Payload's document locks closed to visitor accounts (the "document locks" door). Each is on by default, each can be
* turned off or adapted, and every piece is exported for a project's own use (docs/security.md "Lists and sorting").
*
* Local API calls (`req.payloadAPI === 'local'`: the frontend, seeds, the project's own code) are never touched.
*/
export type ListLimitOptions = {
/** Collections left as Payload has them (their lists take any `limit`). */
exclude?: string[]
/** Largest page a caller that is not staff gets. Default 100. */
max?: number
/** Cap staff accounts too (the panel asks for at most 100 per page itself). Default false. */
staff?: boolean
}
export const DEFAULT_LIST_LIMIT = 100
type HookArgs = Parameters<CollectionBeforeOperationHook>[0]
type ListArgs = { id?: unknown; limit?: number | string; pagination?: boolean | string; sort?: unknown }
const fromOutside = (req: PayloadRequest | undefined): boolean =>
Boolean(req) && (req as { payloadAPI?: string }).payloadAPI !== 'local'
/** True when the request's account belongs to a staff collection (any role). */
export function isStaffRequest(req: Pick<PayloadRequest, 'payload' | 'user'> | undefined): boolean {
const slug = (req?.user as { collection?: unknown } | null | undefined)?.collection
return typeof slug === 'string' && staffCollectionSlugs(req?.payload).includes(slug)
}
/**
* The list arguments with `limit` at most `max` and pagination on — what a caller that is not staff gets. Pure: the
* hook below calls it, a project's own endpoint can too.
*/
export function capListLimit<T extends ListArgs>(args: T, max: number = DEFAULT_LIST_LIMIT): T {
// REST hands the query string over as text: '100000', 'false'
const raw = typeof args.limit === 'string' && (args.limit).trim() !== '' ? Number(args.limit) : args.limit
const limit = typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined
const noPages = args.pagination === false || (args.pagination as unknown) === 'false'
// pagination: false and limit 0 both mean "everything" to Payload
if (noPages || limit === 0 || (limit !== undefined && limit > max)) {
return { ...args, limit: limit && limit > 0 ? Math.min(limit, max) : max, pagination: true }
}
return args
}
/** A sort field that names a database operator (`$where`, `-$natural`, `title.$ne`): never a field of a document. */
export function isOperatorSort(sort: unknown): boolean {
const names = Array.isArray(sort) ? sort : typeof sort === 'string' ? sort.split(',') : []
return names.some((n) => typeof n === 'string' && /(?:^-?|\.)\$/.test(n.trim()))
}
/**
* The 400 for an operator sort name. Its own name so Payload logs it as one `info` line without a stack (the plugin
* sets `loggingLevels.RefusedSortError: 'info'` unless the project set it; `false` logs nothing).
*/
export class RefusedSortError extends APIError {
constructor() {
super('This sort field is not allowed.', 400, null, true)
this.name = 'RefusedSortError'
}
}
const LIST_OPERATIONS = new Set(['findVersions', 'read', 'readDistinct'])
/**
* One `beforeOperation` hook for lists from outside: refuses a database operator as a sort field with 400 (instead of
* a 500 and a logged stack trace, F5) and caps `limit` for callers that are not staff (F4). `listLimit: false` or
* `refuseOperatorSort: false` turns that half off.
*/
export function buildQueryGuardHook(options: {
listLimit?: false | ListLimitOptions
refuseOperatorSort?: boolean
}): CollectionBeforeOperationHook {
const limit = options.listLimit === false ? null : { max: DEFAULT_LIST_LIMIT, staff: false, ...options.listLimit }
const refuseSort = options.refuseOperatorSort !== false
return (({ args, collection, operation, req }: HookArgs) => {
if (!LIST_OPERATIONS.has(operation) || !fromOutside(req)) {return args}
const list = args as ListArgs
if (refuseSort && isOperatorSort(list.sort)) {
throw new RefusedSortError()
}
if (!limit || list.id != null || limit.exclude?.includes(collection.slug)) {return args}
if (!limit.staff && isStaffRequest(req)) {return args}
return capListLimit(list, limit.max)
}) as CollectionBeforeOperationHook
}
/** The hook added to every collection of the config (the project's, the plugin's, other plugins' before iapl). */
export function applyQueryGuard(
config: Config,
options: { listLimit?: false | ListLimitOptions; refuseOperatorSort?: boolean },
): Config {
if (options.listLimit === false && options.refuseOperatorSort === false) {return config}
const hook = buildQueryGuardHook(options)
return {
...config,
collections: (config.collections ?? []).map((c) => ({
...c,
hooks: { ...c.hooks, beforeOperation: [...(c.hooks?.beforeOperation ?? []), hook] },
})),
// Payload's ErrorName union knows only its own errors; the name is looked up by string at log time
loggingLevels: { ...({ RefusedSortError: 'info' } as NonNullable<Config['loggingLevels']>), ...config.loggingLevels },
}
}
/** Payload's collection of document locks ("who edits what"). */
export const LOCKED_DOCUMENTS_SLUG = 'payload-locked-documents'
/**
* Staff accounts (with their second factor, when 2FA is on) — who edits in the panel. Payload's default for its
* document locks is any signed-in account, so a visitor account (a shop's customers) could read who edits what and
* write or delete locks.
*/
export const staffOnlyLocks: Access = ({ req }) => isStaffRequest(req) && secondFactorPassed({ payload: req.payload, user: req.user })
export type LockedDocumentsAccess = Partial<Pick<NonNullable<CollectionConfig['access']>, 'create' | 'delete' | 'read' | 'update'>>
/**
* Payload adds its document-lock collection after every plugin has run, so its rules are set on the live config
* (onInit and after a dev reload). `access` keys the project gives win; the rest is {@link staffOnlyLocks}.
*/
export function applyLockedDocumentsAccess(config: Pick<SanitizedConfig, 'collections'>, access: LockedDocumentsAccess = {}): boolean {
const locks = config.collections?.find((c) => c.slug === LOCKED_DOCUMENTS_SLUG)
if (!locks) {return false}
locks.access = { ...locks.access, create: staffOnlyLocks, delete: staffOnlyLocks, read: staffOnlyLocks, update: staffOnlyLocks, ...access }
return true
}