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
+112
View File
@@ -0,0 +1,112 @@
/**
* Lists from outside (1.18.0; security audit 2026-12, findings F4 and F5) and Payload's document locks for staff only
* (the "document locks" door), over real HTTP: Payload's REST and GraphQL handlers behind a server, a visitor login
* collection next to the staff one.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const PASSWORD = 'a-long-test-password-1'
let server: TestServer
let payload: Payload
let base = ''
let editor = ''
let customer = ''
const signIn = async (collection: string, email: string) => {
const res = await fetch(`${base}/api/${collection}/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: { 'content-type': 'application/json', origin: base }, method: 'POST' })
expect(res.status).toBe(200)
return cookiesOf(res).join('; ')
}
const get = async (path: string, cookie = '') => {
const res = await fetch(`${base}${path}`, { headers: { cookie, origin: base } })
return { body: (await res.json().catch(() => ({}))) as { docs?: unknown[]; limit?: number }, status: res.status }
}
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'notes', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] },
{ slug: 'customers', access: { create: () => false }, auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: testDatabase('query_guard'),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
base = server.url
for (let i = 0; i < 130; i++) {await payload.create({ collection: 'notes' as never, data: { title: `n${i}` } as never })}
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
await payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never, overrideAccess: true })
editor = await signIn('users', '[email protected]')
customer = await signIn('customers', '[email protected]')
}, 180_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
describe('F4: public lists are capped for callers that are not staff', () => {
test('anonymous and a customer get at most 100; pagination=false and limit=0 too', async () => {
for (const cookie of ['', customer]) {
for (const q of ['limit=100000', 'pagination=false', 'limit=0']) {
const { body, status } = await get(`/api/notes?${q}&depth=0`, cookie)
expect([q, status, body.docs?.length]).toEqual([q, 200, 100])
}
}
expect((await get('/api/notes?limit=5')).body.docs).toHaveLength(5)
})
test('staff and the Local API are not capped', async () => {
expect((await get('/api/notes?limit=1000&depth=0', editor)).body.docs).toHaveLength(130)
expect((await payload.find({ collection: 'notes' as never, limit: 1000 })).docs).toHaveLength(130)
})
test('GraphQL lists from outside are capped as well', async () => {
const res = await fetch(`${base}/api/graphql`, { body: JSON.stringify({ query: '{ Notes(limit: 100000) { docs { id } } }' }), headers: { 'content-type': 'application/json', origin: base }, method: 'POST' })
const body = (await res.json()) as { data?: { Notes?: { docs: unknown[] } } }
expect(body.data?.Notes?.docs).toHaveLength(100)
})
})
describe('F5: an operator name in ?sort= is refused', () => {
test('$where, -$where, $natural and a.$ne answer 400 — anonymous and staff alike; a field name still sorts', async () => {
for (const cookie of ['', editor]) {
for (const sort of ['%24where', '-%24where', '%24natural', 'title.%24ne']) {
expect([sort, (await get(`/api/notes?sort=${sort}&limit=1`, cookie)).status]).toEqual([sort, 400])
}
}
expect((await get('/api/notes?sort=-title&limit=1')).status).toBe(200)
})
})
describe('Payload\'s document locks are for staff only', () => {
test('a customer is refused on every operation; an editor works as before', async () => {
const page = (await payload.find({ collection: 'notes' as never, limit: 1 })).docs[0] as { id: number | string }
const lock = { document: { relationTo: 'notes', value: page.id }, user: { relationTo: 'customers', value: 1 } }
const asCustomer = { 'content-type': 'application/json', cookie: customer, origin: base }
expect((await fetch(`${base}/api/payload-locked-documents`, { headers: asCustomer })).status).toBe(403)
expect((await fetch(`${base}/api/payload-locked-documents`, { body: JSON.stringify(lock), headers: asCustomer, method: 'POST' })).status).toBe(403)
expect((await fetch(`${base}/api/payload-locked-documents`, { headers: { cookie: '', origin: base } })).status).toBe(403)
expect((await fetch(`${base}/api/payload-locked-documents`, { headers: { cookie: editor, origin: base } })).status).toBe(200)
})
})
+138 -11
View File
@@ -5,7 +5,8 @@
*
* A finding of the audit that is not fixed yet is an `it.fails` naming it (security-audit-2026-12-findings.md):
* the test states the SAFE behaviour, so the day the fix lands vitest says the test "passed unexpectedly" and the
* `.fails` goes. The same convention as `openFor` in the closed-doors spec.
* `.fails` goes. The same convention as `openFor` in the closed-doors spec. Every finding of the 2026-12 audit is
* fixed in 1.18.0: no `.fails` is left.
*/
import { Script } from 'node:vm'
import { createElement } from 'react'
@@ -16,11 +17,14 @@ import { adminPathFromReferer } from '../src/modules/branding/signIn/languageEnd
import { consentDecidedScript } from '../src/modules/consent/firstPaint.js'
import { parseConsent, readConsentRecord } from '../src/modules/consent/storage.js'
import { markdownResponse } from '../src/modules/content/createMarkdownRenderer.js'
import { MARKDOWN_NEGOTIATED_HEADER } from '../src/modules/content/markdownNegotiation.js'
import { createProxy } from '../src/modules/i18n/createProxy.js'
import { buildUrlField, isAllowedUrl } from '../src/modules/links/buildUrlField.js'
import { safeHref } from '../src/modules/links/resolveLinkHref.js'
import { createMcpRoute } from '../src/modules/mcp/createMcpRoute.js'
import { sanitizeRichTextLinks } from '../src/modules/richtext/sanitizeLinks.js'
import { createCspReportRoute } from '../src/modules/security/createCspReportRoute.js'
import { createCspReportRoute, CSP_LOG_VALUE_MAX, cspLogLine } from '../src/modules/security/createCspReportRoute.js'
import { applyLockedDocumentsAccess, buildQueryGuardHook, capListLimit, isOperatorSort, LOCKED_DOCUMENTS_SLUG } from '../src/modules/security/queryGuard.js'
import { safeAdminBack } from '../src/modules/security/totp/safeBack.js'
import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js'
import { JsonLdGraph } from '../src/modules/seo/JsonLdGraph.js'
@@ -99,7 +103,7 @@ describe('open redirect and header injection', () => {
it('locale redirect: a path that looks like a host stays on this site', () => {
const NextResponse = { next: () => ({ cookies: { set: () => {} }, headers: new Headers() }), redirect: (u: string | URL) => ({ cookies: { set: () => {} }, headers: new Headers({ location: String(u) }) }) }
const proxy = createProxy({ defaultLocale: 'pl', locales: ['pl', 'en'] } as never, { NextResponse })
const proxy = createProxy({ defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] } as never, { NextResponse })
for (const p of ['//evil.example', '/\\evil.example', '/%2F%2Fevil.example', '/.evil.example']) {
const url = new URL(`https://site.pl${p}`)
const res = proxy({ cookies: { get: () => undefined }, headers: new Headers(), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers }
@@ -121,18 +125,49 @@ describe('injection — prototype pollution and operators in stored or sent JSON
})
describe('log injection', () => {
// FINDING F1 (security-audit-2026-12-findings.md): the report's own strings go into the log line as they are.
it.fails('F1: a CSP report cannot write a forged line into the server log', async () => {
// F1 (security-audit-2026-12-findings.md), fixed in 1.18.0: the default line holds origins and paths, no control characters.
it('F1: a CSP report cannot write a forged line into the server log', async () => {
const lines: string[] = []
const warn = vi.spyOn(console, 'warn').mockImplementation((...a: unknown[]) => {lines.push(a.join(' '))})
try {
const route = createCspReportRoute()
const route = createCspReportRoute({ rateLimit: false })
await route(new Request('http://localhost/api/csp-report', { body: JSON.stringify({ 'csp-report': { 'blocked-uri': 'x\n[iapl] admin signed in: [email protected] from 10.0.0.1', 'document-uri': 'https://s.pl/', 'effective-directive': 'script-src' } }), method: 'POST' }))
} finally {
warn.mockRestore()
}
expect(lines.join('\n').split('\n')).toHaveLength(1)
})
it('F1: the default line keeps the blocked origin and the page path (no query), every value capped', () => {
const line = cspLogLine({
blockedUri: 'https://cdn.evil.example/x.js?token=secret',
documentUri: 'https://s.pl/pl/[email protected]#form',
effectiveDirective: 'script-src-elem',
lineNumber: 3,
sourceFile: `https://s.pl/_next/static/a.js?v=1\u2028${'x'.repeat(500)}`,
})
expect(line).toContain('blocked=https://cdn.evil.example ')
expect(line).toContain('page=/pl/kontakt')
expect(line).not.toMatch(/secret|a@b\.pl|\u2028/)
expect(line.length).toBeLessThan(4 * CSP_LOG_VALUE_MAX)
expect(cspLogLine({ blockedUri: 'inline' })).toContain('blocked=inline')
})
it('F1: one request handles at most maxReports violations; a project\'s onReport gets the raw values', async () => {
const seen: string[] = []
const route = createCspReportRoute({ maxReports: 3, onReport: (v) => {seen.push(v.blockedUri ?? '')}, rateLimit: false })
const many = Array.from({ length: 40 }, (_, i) => ({ type: 'csp-violation', body: { blockedURL: `x\n${i}`, documentURL: 'https://s.pl/' } }))
expect((await route(new Request('http://localhost/api/csp-report', { body: JSON.stringify(many), method: 'POST' }))).status).toBe(204)
expect(seen).toEqual(['x\n0', 'x\n1', 'x\n2'])
})
it('F1: over the per-client limit the route answers 204 and handles nothing', async () => {
const seen: number[] = []
const route = createCspReportRoute({ onReport: () => {seen.push(1)}, rateLimit: { max: 2, windowMs: 60_000 } })
const send = () => route(new Request('http://localhost/api/csp-report', { body: JSON.stringify({ 'csp-report': { 'blocked-uri': 'inline' } }), headers: { 'x-forwarded-for': '203.0.113.77' }, method: 'POST' }))
for (let i = 0; i < 4; i++) {expect((await send()).status).toBe(204)}
expect(seen).toHaveLength(2)
})
})
describe('denial of service — bodies and batches', () => {
@@ -152,19 +187,111 @@ describe('denial of service — bodies and batches', () => {
})
describe('cache poisoning — one URL, two bodies', () => {
// FINDING F3: `Accept: text/markdown` on an HTML URL gets the Markdown copy at the SAME URL, cacheable by a shared
// cache for an hour (a day stale) and with no Vary: a CDN that caches HTML can serve the Markdown to every visitor.
it.fails('F3: the Markdown answer given at an HTML URL says it varies by Accept (or is not stored by shared caches)', () => {
// F3, fixed in 1.18.0: `Accept: text/markdown` on an HTML URL gets the Markdown copy at the SAME URL — now private,
// never stored by a shared cache, with Vary: Accept on both answers.
it('F3: the Markdown answer given at an HTML URL says it varies by Accept (or is not stored by shared caches)', () => {
const rewrites: string[] = []
const response = () => ({ cookies: { set: () => {} }, headers: new Headers() })
const NextResponse = { next: response, redirect: response, rewrite: (u: string | URL) => {rewrites.push(String(u)); return response()} }
const proxy = createProxy({ defaultLocale: 'pl', locales: ['pl', 'en'] } as never, { markdown: true, NextResponse })
const proxy = createProxy({ defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] } as never, { markdown: true, NextResponse })
const url = new URL('https://site.pl/pl/o-nas')
const res = proxy({ cookies: { get: () => undefined }, headers: new Headers({ accept: 'text/markdown' }), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers }
expect(rewrites).toHaveLength(1)
const md = markdownResponse('# x')
const md = markdownResponse('# x', { negotiated: true })
const varies = /accept/i.test(res.headers.get('vary') ?? '') || /accept/i.test(md.headers.get('vary') ?? '')
const private_ = /private|no-store/.test(md.headers.get('cache-control') ?? '')
expect(varies || private_).toBe(true)
expect(res.headers.get('cache-control')).toBe('private, no-store')
expect(res.headers.get('vary')).toBe('Accept')
})
it('F3: the route answers private + Vary: Accept only when the proxy marked the request; /md/… stays public', async () => {
expect(markdownResponse('# x').headers.get('cache-control')).toMatch(/public/)
expect(markdownResponse('# x').headers.get('vary')).toBeNull()
expect(markdownResponse(null, { negotiated: true }).headers.get('cache-control')).toBe('private, no-store')
})
it('F3: the proxy passes the marker to the route, adds Vary: Accept to pages, and markdown.negotiate: false turns negotiation off', () => {
const seen: { headers?: Headers; url: string }[] = []
const response = () => ({ cookies: { set: () => {} }, headers: new Headers() })
const NextResponse = { next: response, redirect: response, rewrite: (u: string | URL, init?: { request?: { headers: Headers } }) => {seen.push({ headers: init?.request?.headers, url: String(u) }); return response()} }
const ask = (accept: string, markdown: unknown) => {
const url = new URL('https://site.pl/pl/o-nas')
return createProxy({ defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] } as never, { markdown: markdown as never, NextResponse })({ cookies: { get: () => undefined }, headers: new Headers({ accept }), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers }
}
ask('text/markdown', true)
expect(seen[0].headers?.get(MARKDOWN_NEGOTIATED_HEADER)).toBe('1')
expect(ask('text/html', true).headers.get('vary')).toBe('Accept')
seen.length = 0
const off = ask('text/markdown', { negotiate: false })
expect(seen).toHaveLength(0)
expect(off.headers.get('vary')).toBeNull()
expect(ask('text/markdown', { prefix: '/ai' }) && seen[0].url).toBe('https://site.pl/ai/pl/o-nas')
})
})
describe('denial of service and injection — lists from outside (F4, F5)', () => {
const hook = buildQueryGuardHook({})
const run = (args: Record<string, unknown>, req: Record<string, unknown>, operation = 'read', h = hook) =>
h({ args, collection: { slug: 'pages' }, context: {}, operation, req } as never) as Record<string, unknown>
const visitor = { payload: { config: { admin: { user: 'users' }, custom: {} } }, payloadAPI: 'REST', user: null }
const staff = { ...visitor, user: { id: 1, collection: 'users' } }
it('F4: a caller that is not staff gets at most 100 per request; pagination=false and limit=0 become one page', () => {
expect(run({ limit: 100000 }, visitor)).toMatchObject({ limit: 100, pagination: true })
expect(run({ pagination: false }, visitor)).toMatchObject({ limit: 100, pagination: true })
expect(run({ limit: 0 }, visitor)).toMatchObject({ limit: 100, pagination: true })
expect(run({ limit: 20 }, visitor)).toEqual({ limit: 20 })
expect(run({ limit: 5000 }, { ...visitor, user: { id: 1, collection: 'customers' } })).toMatchObject({ limit: 100 })
expect(run({ limit: 5000 }, visitor, 'findVersions')).toMatchObject({ limit: 100 })
})
it('F4: staff, the Local API, one document by id and listLimit: false are left alone; max / exclude / staff adapt it', () => {
expect(run({ limit: 5000 }, staff)).toEqual({ limit: 5000 })
expect(run({ limit: 5000 }, { ...visitor, payloadAPI: 'local' })).toEqual({ limit: 5000 })
expect(run({ id: 'a', limit: 5000 }, visitor)).toEqual({ id: 'a', limit: 5000 })
expect(run({ limit: 5000 }, visitor, 'read', buildQueryGuardHook({ listLimit: false }))).toEqual({ limit: 5000 })
expect(run({ limit: 5000 }, visitor, 'read', buildQueryGuardHook({ listLimit: { max: 20 } }))).toMatchObject({ limit: 20 })
expect(run({ limit: 5000 }, visitor, 'read', buildQueryGuardHook({ listLimit: { exclude: ['pages'] } }))).toEqual({ limit: 5000 })
expect(run({ limit: 5000 }, staff, 'read', buildQueryGuardHook({ listLimit: { staff: true } }))).toMatchObject({ limit: 100 })
expect(capListLimit({ limit: 7 }, 5)).toEqual({ limit: 5, pagination: true })
})
it('F5: a sort that names a database operator is refused with 400, for staff too; the Local API and refuseOperatorSort: false are not touched', () => {
for (const sort of ['$where', '-$where', '$natural', 'title.$ne', ['title', '-$where'], 'title,-$where']) {
expect(isOperatorSort(sort), String(sort)).toBe(true)
expect(() => run({ sort }, staff), String(sort)).toThrow(expect.objectContaining({ status: 400 }))
}
for (const sort of ['title', '-createdAt', 'meta.title', ['title', '-date']]) {expect(isOperatorSort(sort)).toBe(false)}
expect(run({ sort: '$where' }, { ...visitor, payloadAPI: 'local' })).toEqual({ sort: '$where' })
expect(run({ sort: '$where' }, visitor, 'read', buildQueryGuardHook({ refuseOperatorSort: false }))).toEqual({ sort: '$where' })
})
it('the document locks: staff only by default, the project\'s rule per operation wins, a config without them is left alone', () => {
const config = { collections: [{ slug: LOCKED_DOCUMENTS_SLUG, access: {} }] } as never as { collections: { access: Record<string, unknown>; slug: string }[] }
expect(applyLockedDocumentsAccess(config as never)).toBe(true)
const rule = config.collections[0].access.read as (a: unknown) => boolean
expect(rule({ req: { payload: visitor.payload, user: { id: 1, collection: 'customers' } } })).toBe(false)
expect(rule({ req: { payload: visitor.payload, user: null } })).toBe(false)
expect(rule({ req: { payload: visitor.payload, user: { id: 1, collection: 'users' } } })).toBe(true)
const own = () => true
applyLockedDocumentsAccess(config as never, { read: own })
expect(config.collections[0].access.read).toBe(own)
expect(applyLockedDocumentsAccess({ collections: [] } as never)).toBe(false)
})
})
describe('XSS — addresses rendered into href (F2)', () => {
it('buildUrlField refuses javascript:, data: and protocol-relative addresses; https passes; other kinds only when listed', () => {
const field = buildUrlField({ required: true })
const validate = field.validate as (v: unknown, o?: unknown) => string | true
for (const url of UNSAFE_URLS) {expect(validate(url), url).not.toBe(true)}
expect(validate('https://instagram.com/studio')).toBe(true)
expect(validate('')).not.toBe(true)
expect(validate('mailto:[email protected]')).not.toBe(true)
expect(isAllowedUrl('mailto:[email protected]', ['mailto'])).toBe(true)
expect(isAllowedUrl('/pl/o-nas', ['relative'])).toBe(true)
expect(isAllowedUrl('//evil.example', ['relative'])).toBe(false)
expect(buildUrlField({ name: 'website', overrides: { localized: true } })).toMatchObject({ name: 'website', type: 'text', localized: true })
})
})
+8
View File
@@ -11,6 +11,7 @@ import { describe, expect, test, vi } from 'vitest'
import { adminOrEditor } from '../src/modules/access/access.js'
import { visitorWritableEntities } from '../src/modules/doctor/visitorWrites.js'
import { applyLockedDocumentsAccess } from '../src/modules/security/queryGuard.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
@@ -49,6 +50,13 @@ describe('visitorWritableEntities', () => {
}
}, 30_000)
test('Payload\'s document locks are not listed once iapl\'s staff-only rule is on (lockedDocuments, 1.18.0)', async () => {
const config = await build([{ slug: 'customers', access: { create: () => false }, auth: true, fields: [] }])
expect(await visitorWritableEntities(live(config))).toContain('payload-locked-documents:create')
applyLockedDocumentsAccess(config)
expect((await visitorWritableEntities(live(config))).filter((e) => e.startsWith('payload-locked-documents'))).toEqual([])
}, 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([])