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:
co-authored by
Claude Opus 5.5
parent
9a448ba5df
commit
963464d6cb
@@ -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,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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',
|
||||
|
||||
Reference in New Issue
Block a user