Consent log endpoint: body capped at 4 KiB (413), version bounded by the policy version; consent-log-migration a warning

Review C-1: the endpoint, on on every site, parsed a 20 MB body. It now refuses a content-length over
CONSENT_LOG_MAX_BYTES (4096) before reading and reads the stream only up to the cap (readCappedBody), so a missing or
false length cannot make it hold more. A version above Cookie settings' policy version is 400 (the cached version is
read again once, for an editor's fresh raise); versions from 1 up are accepted (pages rendered before a raise).
Review C-2: consent-log-migration is a warning, like every consent check of 1.17.0 (the owner's decision).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 14:10:44 +01:00
co-authored by Claude Opus 5.5
parent 9a448ba5df
commit 963464d6cb
10 changed files with 147 additions and 21 deletions
+60 -2
View File
@@ -423,6 +423,64 @@ describe('consent log: on by default, fails soft without its table', () => {
// the body's gpc never reaches the record (the shape is unchanged)
expect(Object.keys((payload.create.mock.calls[0] as unknown as [{ data: object }])[0].data).sort()).toEqual(['choices', 'consentId', 'version'])
})
describe('limits: body size and version', () => {
let ipN = 30
const site = (policyVersion: (() => number) | number = 3) => ({
create: vi.fn(async ({ data }: { data: object }) => ({ id: 1, ...data })),
db: { deleteMany: vi.fn(async () => {}) },
findGlobal: vi.fn(async () => ({ policyVersion: typeof policyVersion === 'function' ? policyVersion() : policyVersion })),
logger: { error: vi.fn() },
})
const send = (payload: object, init: { body?: BodyInit; headers?: Record<string, string> }) =>
(buildConsentLogEndpoint().handler as (r: PayloadRequest) => Promise<Response>)(
Object.assign(new Request('http://acme.pl/api/ipal/consent', { duplex: 'half', method: 'POST', ...init, headers: { 'content-type': 'application/json', 'x-real-ip': `203.0.113.${ipN++}`, ...init.headers } } as RequestInit), { payload }) as unknown as PayloadRequest,
)
const decision = (version: number, extra: object = {}) => JSON.stringify({ id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state: REJECT, version, ...extra })
test('a body over 4 KiB is refused with 413 and never parsed: by content-length, and by the stream without one', async () => {
const payload = site()
const parse = vi.spyOn(JSON, 'parse')
const big = decision(1, { pad: 'x'.repeat(20 * 1024 * 1024) })
expect((await send(payload, { body: big })).status).toBe(413)
// no length declared (a chunked stream): read only up to the cap
let pulled = 0
const stream = new ReadableStream<Uint8Array>({
pull(controller) {
pulled++
if (pulled > 10_000) {controller.close(); return}
controller.enqueue(new Uint8Array(1024).fill(32))
},
})
expect((await send(payload, { body: stream })).status).toBe(413)
expect(pulled).toBeLessThan(10)
// a false, small content-length does not let a large body through
expect((await send(payload, { body: big, headers: { 'content-length': '100' } })).status).toBe(413)
expect(parse.mock.calls.filter(([text]) => typeof text === 'string' && text.length > 4096)).toEqual([])
expect(payload.create).not.toHaveBeenCalled()
parse.mockRestore()
})
test('a normal decision passes; just under the cap passes', async () => {
const payload = site()
expect((await send(payload, { body: decision(3) })).status).toBe(201)
const near = decision(3, { pad: 'x'.repeat(4096 - decision(3, { pad: '' }).length) })
expect(near.length).toBe(4096)
expect((await send(payload, { body: near })).status).toBe(201)
})
test('version: from 1 to the policy version; above it 400; an editor\'s fresh raise is read again', async () => {
let current = 3
const payload = site(() => current)
expect((await send(payload, { body: decision(1) })).status).toBe(201) // a page rendered before a raise
expect((await send(payload, { body: decision(3) })).status).toBe(201)
expect((await send(payload, { body: decision(99) })).status).toBe(400)
expect((await send(payload, { body: decision(0) })).status).toBe(400)
current = 4 // the editor raises it; the cache still says 3
expect((await send(payload, { body: decision(4) })).status).toBe(201)
expect((await send(payload, { body: decision(5) })).status).toBe(400)
})
})
})
describe('doctor: consent rules', () => {
@@ -452,8 +510,8 @@ describe('doctor: consent rules', () => {
const pg = { 'node_modules/@payloadcms/db-postgres/package.json': { name: '@payloadcms/db-postgres', version: '3.70.0' } }
const config = (opts = '') => ({ 'src/payload.config.ts': `export default withPlugins({ plugins: [iapl({ i18n${opts} })] })` })
test('Postgres, consent log on, no migration creating consent_records → error; with one, or consentLog: false → nothing', async () => {
expect(await findings({ ...pg, ...config(), 'src/migrations/20260101_init.ts': 'create table "users"' })).toEqual([expect.stringMatching(/^consent-log-migration:error/)])
test('Postgres, consent log on, no migration creating consent_records → warning (every 1.17.0 consent check is); with one, or consentLog: false → nothing', async () => {
expect(await findings({ ...pg, ...config(), 'src/migrations/20260101_init.ts': 'create table "users"' })).toEqual([expect.stringMatching(/^consent-log-migration:warning/)])
expect(await findings({ ...pg, ...config(), 'src/migrations/20261126_consent.ts': 'CREATE TABLE "consent_records"' })).toEqual([])
expect(await findings({ ...pg, ...config(', consentLog: false'), 'src/migrations/20260101_init.ts': 'x' })).toEqual([])
expect(await findings({ ...config() })).toEqual([]) // MongoDB: no table, nothing to migrate
+8 -8
View File
@@ -287,25 +287,25 @@ describe('one-call helpers — layout, page, GEO routes', () => {
})
describe('consent log', () => {
// a real Request, as Payload passes one (the endpoint reads the body stream with a cap)
const post = (body: unknown, ip = '10.6.0.1') =>
buildConsentLogEndpoint().handler({
headers: new Headers({ 'x-real-ip': ip }),
json: async () => body,
payload,
} as never) as Promise<Response>
buildConsentLogEndpoint().handler(
Object.assign(new Request('http://localhost/api/ipal/consent', { body: JSON.stringify(body), headers: { 'content-type': 'application/json', 'x-real-ip': ip }, method: 'POST' }), { payload }) as never,
) as Promise<Response>
const state = { analytics: true, functional: false, marketing: false, necessary: true }
test('stores id, choices and version only', async () => {
const res = await post({ id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state, version: 2 })
// the site's policy version is 1 (Cookie settings not changed): a decision carries 1 at most (1.17.0)
const res = await post({ id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state, version: 1 })
expect(res.status).toBe(201)
const { docs } = await payload.find({ collection: 'consent-records' as never, where: { consentId: { equals: 'a1b2c3d4e5f6a7b8c9d0e1f2' } } })
const rec = docs[0] as unknown as Record<string, unknown>
expect(rec).toMatchObject({ choices: state, version: 2 })
expect(rec).toMatchObject({ choices: state, version: 1 })
expect(Object.keys(rec).filter((k) => /ip|agent|email/i.test(k))).toEqual([])
})
test('rejects malformed records', async () => {
for (const bad of [{}, { id: 'x', state, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state: { analytics: 'yes' }, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state, version: 0 }]) {
for (const bad of [{}, { id: 'x', state, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state: { analytics: 'yes' }, version: 1 }, { id: 'a1b2c3d4e5f6a7b8', state, version: 0 }, { id: 'a1b2c3d4e5f6a7b8', state, version: 2 }]) {
expect((await post(bad, '10.6.0.2')).status).toBe(400)
}
})