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
+4 -3
View File
@@ -207,7 +207,7 @@ once there are more than 20.
consent-log`, commit the migration and have it applied when the new container starts (`prodMigrations`, or the start
command `pnpm payload migrate && pnpm start`) — **in the same deploy**. Or set `iapl({ consentLog: false })`. Without
either nothing breaks: the page and the banner work, `POST /api/ipal/consent` answers `503`, the server logs once
"the consent-records table does not exist…", and `iapl-doctor` reports `consent-log-migration` (error). A project
"the consent-records table does not exist…", and `iapl-doctor` reports `consent-log-migration` (warning). A project
that already had `consentLog: true`: nothing. **MongoDB** (the eight client sites): nothing — the collection
appears by itself.
- **Generated types:** where the consent log was off, `payload generate:types` adds the `consent-records` collection
@@ -280,7 +280,8 @@ once there are more than 20.
Cookie Banner Taskforce (2023) found a missing or weaker reject option an infringement for most authorities; a UODO
article repeats it. `equalChoice={false}` restores the secondary look; `iapl-doctor` (`consent-banner`) warns, and a
development console warning names a banner `order` without `'reject'`.
- **Consent log on by default** (`consentLog` — `false` turns it off). `<SiteProviders>` posts every decision to it by
- **Consent log on by default** (`consentLog` — `false` turns it off). The endpoint reads at most 4 KiB of body
(`413` beyond, before anything is parsed) and refuses a `version` above the site's policy version (`400`). `<SiteProviders>` posts every decision to it by
itself: `getSiteShell` gives `consentLogEndpoint` (`'/api/ipal/consent'` with the config's API route, `null` when
the log is off); `logEndpoint={false}` stops one layout. A write without its SQL table answers `503` and logs one line
per process. The posted body gains `gpc`; the record's fields are unchanged.
@@ -343,7 +344,7 @@ once there are more than 20.
- **`maxAgeDays`** on `SiteProviders` / `ConsentProvider` / `useConsent`: the re-ask period (default 180 days).
- **`CONSENT_LOG_PATH`** (`'/ipal/consent'`).
- **Doctor rules** `consent-log-migration` (Postgres / SQLite with the log on and no migration creating
`consent_records`: error) and `consent-banner` (`equalChoice={false}`, an `order` without `'reject'`, `gpc={false}`,
`consent_records`: warning — every consent check of 1.17.0 is a warning) and `consent-banner` (`equalChoice={false}`, an `order` without `'reject'`, `gpc={false}`,
`cookieButton={false}` with no `reopen`, a hand-wired `ConsentProvider` without `logEndpoint`: warnings; `gpc="ask"`:
info; the crawl judging another Consent Mode than the layout: warning).
- **`iapl-consent-check`**: five runs — adds Global Privacy Control, equal prominence (computed size and look of
@@ -187,6 +187,7 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant
| `REJECT_ALL_CONSENT` | `@intecion/ipal-kit` | Only `necessary: true` (a copy of `DEFAULT_CONSENT`). |
| `CONSENT_LOG_SLUG` | `@intecion/ipal-kit` | Consent log collection slug: `'consent-records'`. |
| `CONSENT_LOG_PATH` | `@intecion/ipal-kit` | The consent log endpoint's path under the API route: `'/ipal/consent'` (`/api/ipal/consent`). |
| `CONSENT_LOG_MAX_BYTES`, `readCappedBody(request, max?)` | `@intecion/ipal-kit` | The consent log endpoint's body cap (4096 bytes) and the reader it uses: `null` when a declared `content-length` or the stream itself passes the cap (read only up to it), else the text — for your own public JSON endpoint. |
| `resolveConsent(record, signal, mode?)` | `@intecion/ipal-kit` | Pure: what is in effect for a stored record (or `null`), the Global Privacy Control signal and the mode (`'honour'` default / `'ask'` / `false`) → `{ decided, gpc, stale, state }` (type `ResolvedConsent`; mode type `GpcMode`). The table in consent.md → "Global Privacy Control". |
| `gpcFromNavigator()` / `gpcFromHeaders(headers)` | `@intecion/ipal-kit` | The signal: `navigator.globalPrivacyControl === true` (false on the server) / `Sec-GPC: 1` exactly. Read the header only where a response is per visitor (endpoints) — never while rendering a static page. |
| `GPC_CATEGORIES`, `GPC_HEADER` | `@intecion/ipal-kit` | `['analytics', 'marketing']` (what the signal refuses) and `'sec-gpc'`. |
+1 -1
View File
@@ -588,7 +588,7 @@ tracker request. Every decision is now recorded in *Privacy → Consent records*
1. **Postgres / SQLite and the project never had `consentLog` on:** the consent log is now on by default and is a new
table. In the same deploy: `pnpm payload migrate:create consent-log`, commit it, apply it at container start
(`prodMigrations` or `pnpm payload migrate && pnpm start`). Or `iapl({ consentLog: false })`. Without either the site
works, but every choice answers 503 and is not recorded (one log line; `iapl-doctor` error `consent-log-migration`).
works, but every choice answers 503 and is not recorded (one log line; `iapl-doctor` warning `consent-log-migration`).
MongoDB: the collection appears by itself.
2. Every site: `pnpm payload generate:types` adds the `consent-records` collection's types (where it was off) — run it and
commit. No import-map change.
+3 -3
View File
@@ -578,8 +578,8 @@ to add the hook to a config. Nothing to migrate.
| Collection access | `read` / `delete` — admin (without `access`, i.e. no roles: any logged-in account — narrow it with `collectionOverrides`); `create` / `update` — nobody through the API (written only by the endpoint, `overrideAccess`) |
| Endpoint | `POST /api/ipal/consent`, public (no login) |
| Default | on (since 1.17.0); `consentLog: false` = no collection, no endpoint, `shell.consentLogEndpoint` null |
| Body | `{ id: string (hex 16–64), version: int ≥ 1, state: { necessary, functional, analytics, marketing: boolean }, gpc?: boolean }` (`gpc` is accepted and not stored) |
| Responses | `201 { ok: true }`, `400` (bad JSON/validation), `429` (limit 20 requests/min per IP, scope `consent`), `503` (the table does not exist: one log line per server start), `500` |
| Body | `{ id: string (hex 16–64), version: int from 1 to the site's policy version, state: { necessary, functional, analytics, marketing: boolean }, gpc?: boolean }` (`gpc` is accepted and not stored); at most 4 KiB (`CONSENT_LOG_MAX_BYTES`) |
| Responses | `201 { ok: true }`, `400` (bad JSON/validation, a version above the policy version), `413` (body over 4 KiB: refused by `content-length` before reading, or when the stream passes the cap), `429` (limit 20 requests/min per IP, scope `consent`), `503` (the table does not exist: one log line per server start), `500` |
| Cleanup | on a write, at most once per 24 h per process: one `db.deleteMany` for records older than `retentionDays`, **in the background** (the consent write does not wait; an error is logged and the cleanup is retried on the next write) |
The provider sends a record after every decision (`fetch` with `keepalive`, errors ignored —
@@ -601,7 +601,7 @@ pnpm payload migrate # applied at container start (prodMi
Or `iapl({ consentLog: false })` when the project does not want the log. Without the table nothing breaks: the page
and the banner work, each choice answers `503` and the server logs once *"the consent-records table does not
exist — create and apply a migration…"*; `iapl-doctor` reports `consent-log-migration` as an error while no
exist — create and apply a migration…"*; `iapl-doctor` reports `consent-log-migration` (a warning) while no
migration in `src/migrations` creates `consent_records`.
Narrow who reads the records (e.g. a project without roles, only the data protection officer):
+2
View File
@@ -79,6 +79,7 @@ export {
CONSENT_COOKIE,
CONSENT_FALLBACK,
CONSENT_FALLBACK_PL,
CONSENT_LOG_MAX_BYTES,
CONSENT_LOG_PATH,
CONSENT_LOG_SLUG,
CONSENT_MAX_AGE,
@@ -95,6 +96,7 @@ export {
gpcFromNavigator,
gpcWellKnown,
parseConsent,
readCappedBody,
readConsentRecord,
REJECT_ALL_CONSENT,
resolveConsent,
+65 -2
View File
@@ -7,6 +7,7 @@ import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { CONSENT_CATEGORIES } from './categories.js'
import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js'
import { CONSENT_VERSION } from './storage.js'
/**
* Consent log — proof of consent (GDPR Art. 7(1): the controller must be able
@@ -85,15 +86,77 @@ const purge = createDailyPurge(CONSENT_LOG_SLUG)
/** The missing-table line is logged once per Payload instance, not on every visitor's click. */
const missingTableLogged = new WeakSet<object>()
/** Largest body the endpoint reads. A decision is about 200 bytes; anything near this is not one. */
export const CONSENT_LOG_MAX_BYTES = 4096
/**
* The request body as text, or null when it is larger than `max` bytes: a declared `content-length` over the cap
* is refused before anything is read, and the stream is read only up to the cap (a body without a length, or with
* a false one, cannot make the server hold more).
*/
export async function readCappedBody(request: Request, max: number = CONSENT_LOG_MAX_BYTES): Promise<null | string> {
const declared = Number(request.headers.get('content-length'))
if (Number.isFinite(declared) && declared > max) {return null}
if (!request.body) {return ''}
const reader = request.body.getReader()
const chunks: Uint8Array[] = []
let size = 0
for (;;) {
const { done, value } = await reader.read()
if (done) {break}
size += value.byteLength
if (size > max) {
await reader.cancel().catch(() => {})
return null
}
chunks.push(value)
}
const all = new Uint8Array(size)
let at = 0
for (const chunk of chunks) {
all.set(chunk, at)
at += chunk.byteLength
}
return new TextDecoder().decode(all)
}
/** Cookie Settings → Policy version per Payload instance, cached for a minute. */
const policyCache = new WeakMap<object, { at: number; version: number }>()
async function currentPolicyVersion(req: PayloadRequest, fresh = false): Promise<number> {
const cached = policyCache.get(req.payload)
if (!fresh && cached && Date.now() - cached.at < 60_000) {return cached.version}
let version = CONSENT_VERSION
try {
const g = (await req.payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0 })) as { policyVersion?: unknown }
if (typeof g.policyVersion === 'number' && g.policyVersion >= 1) {version = Math.trunc(g.policyVersion)}
} catch {
// global missing — the default version applies
}
policyCache.set(req.payload, { at: Date.now(), version })
return version
}
/**
* A decision is made under the site's policy version or an earlier one (a page rendered before an editor raised
* it). A version above the current one is refused; when the cache says lower, it is read again once — the editor
* may have just raised it.
*/
async function versionAllowed(req: PayloadRequest, version: number): Promise<boolean> {
if (version <= (await currentPolicyVersion(req))) {return true}
return version <= (await currentPolicyVersion(req, true))
}
export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOptions = {}): Endpoint {
return {
handler: async (req: PayloadRequest) => {
const limit = await consumeRateLimit({ key: clientIp(req as unknown as Request), max: 20, scope: 'consent' })
if (!limit.ok) {return Response.json({ ok: false }, { status: 429 })}
const text = await readCappedBody(req as unknown as Request).catch(() => null)
if (text === null) {return Response.json({ ok: false }, { status: 413 })}
let body: unknown
try {
body = await (req as unknown as Request).json()
body = JSON.parse(text)
} catch {
return Response.json({ ok: false }, { status: 400 })
}
@@ -108,7 +171,7 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti
b.state !== null &&
typeof b.state === 'object' &&
CONSENT_CATEGORIES.every((c) => typeof b.state![c] === 'boolean')
if (!valid) {return Response.json({ ok: false }, { status: 400 })}
if (!valid || !(await versionAllowed(req, b.version as number))) {return Response.json({ ok: false }, { status: 400 })}
try {
await req.payload.create({
+1 -1
View File
@@ -9,7 +9,7 @@ export {
} from './categories.js'
export type { ConsentCategory, ConsentState } from './categories.js'
export { CONSENT_CATEGORY_LABELS, consentCategoryOptions } from './categoryLabels.js'
export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_PATH, CONSENT_LOG_SLUG } from './consentLog.js'
export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_MAX_BYTES, CONSENT_LOG_PATH, CONSENT_LOG_SLUG, readCappedBody } from './consentLog.js'
export type { ConsentLogOptions } from './consentLog.js'
export { consentBannerScript } from './firstPaint.js'
export type { ConsentBannerScriptOptions } from './firstPaint.js'
+2 -1
View File
@@ -66,7 +66,8 @@ export const consentRules: DoctorRule[] = [
message: files.length
? 'no migration creates the consent log table `consent_records` (the consent log is on by default since 1.17.0): banner choices are not recorded in production'
: 'a SQL database and no migrations folder: the consent log table `consent_records` (on by default since 1.17.0) must be created by a migration, or choices are not recorded',
severity: files.length ? 'error' : 'warning',
// A warning, like every consent check of 1.17.0 (the owner's decision): the site works without the table.
severity: 'warning',
}]
},
docs: 'docs/consent.md#consent-log-details-consentlog',
+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)
}
})