From c6a276823ccad8b2213c412c4956a65e41df8080 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 13:51:52 +0100 Subject: [PATCH] Consent log: missing-table line once per Payload instance; SQL upgrade proof on Postgres and SQLite MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit test/consentLogUpgrade.test.ts: a site without the log (migrations applied) upgraded to 1.17.0 — without a migration the site works and a consent write answers 503 with one log line; migrate:create adds only consent_records (and the lock-relation column) and writes succeed. SQLite always; Postgres with IAPL_TEST_PG_URL. Docs say exactly what the migration creates. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + docs/CHANGELOG.md | 3 +- docs/consent.md | 10 ++- src/modules/consent/consentLog.ts | 8 +- test/consentLogUpgrade.test.ts | 142 ++++++++++++++++++++++++++++++ 5 files changed, 155 insertions(+), 9 deletions(-) create mode 100644 test/consentLogUpgrade.test.ts diff --git a/.gitignore b/.gitignore index 0f4cfee..83861d4 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,4 @@ next-env.d.ts # pnpm starter:gate work folder .starter-gate/ .legacy-site-*/ +.tmp-consent-upgrade-* diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 98dbcd9..8659e34 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -202,7 +202,8 @@ once there are more than 20. ### Requires project changes - **Postgres / SQLite, consent log (first, before the deploy):** the consent log (`consent-records`) is now on by - default. A project that did not set `consentLog` before gets a **new table**: run `pnpm payload migrate:create + default. A project that did not set `consentLog` before gets a **new table** (`consent_records`, plus a + `consent_records_id` column on Payload's `payload_locked_documents_rels`; nothing dropped): run `pnpm payload migrate:create 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 diff --git a/docs/consent.md b/docs/consent.md index 3a15f98..9af33ad 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -579,7 +579,7 @@ to add the hook to a config. Nothing to migrate. | 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 process), `500` | +| 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` | | 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 — @@ -588,9 +588,11 @@ from `@intecion/ipal-kit`; `CONSENT_LOG_PATH` is the endpoint's path under the A ### Postgres / SQLite: the consent log is a table -On MongoDB the collection appears by itself. On a SQL database `consent-records` is a table (`consent_records` -plus `consent_records_choices`… as Payload names them), so the deploy that brings 1.17.0 to a project that never had -`consentLog` on must create it — **in the same deploy**, before the new version serves requests: +On MongoDB the collection appears by itself. On a SQL database `consent-records` is a table, so the deploy that +brings 1.17.0 to a project that never had `consentLog` on must create it — **in the same deploy**, before the new +version serves requests. The migration Payload generates (checked on Postgres 16 and SQLite) creates one table, +`consent_records` (the choices are its columns, three indexes), and adds one column, `consent_records_id`, with its +index and foreign key to Payload's own `payload_locked_documents_rels`; it drops nothing: ```bash pnpm payload migrate:create consent-log # commit the file in src/migrations/ diff --git a/src/modules/consent/consentLog.ts b/src/modules/consent/consentLog.ts index 0f1b6bc..115bb36 100644 --- a/src/modules/consent/consentLog.ts +++ b/src/modules/consent/consentLog.ts @@ -82,8 +82,8 @@ export function buildConsentLogCollection(): CollectionConfig { } const purge = createDailyPurge(CONSENT_LOG_SLUG) -/** The missing-table line is logged once per process, not on every visitor's click. */ -let missingTableLogged = false +/** The missing-table line is logged once per Payload instance, not on every visitor's click. */ +const missingTableLogged = new WeakSet() export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOptions = {}): Endpoint { return { @@ -124,8 +124,8 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti return Response.json({ ok: true }, { status: 201 }) } catch (err) { if (isMissingTableError(err)) { - if (!missingTableLogged) { - missingTableLogged = true + if (!missingTableLogged.has(req.payload)) { + missingTableLogged.add(req.payload) req.payload.logger.error( "[iapl] consent log: the consent-records table does not exist — create and apply a migration (pnpm payload migrate:create consent-log, commit, migrate at container start) or set iapl({ consentLog: false }). Banner choices are not recorded until then; the site works.", ) diff --git a/test/consentLogUpgrade.test.ts b/test/consentLogUpgrade.test.ts new file mode 100644 index 0000000..465ea46 --- /dev/null +++ b/test/consentLogUpgrade.test.ts @@ -0,0 +1,142 @@ +/** + * The consent log is on by default since 1.17.0: on Postgres / SQLite that is a new table. This proves the upgrade + * of a site that ran WITHOUT the log, both ways: + * 1. a 1.16-style site (consentLog off) with its migrations applied; + * 2. 1.17.0 started WITHOUT a new migration: the site works, a consent write answers 503 with ONE log line; + * 3. `migrate:create` makes a migration that only adds the consent tables; after `migrate` writes succeed. + * SQLite always runs (a file in the repo's temp folder). Postgres runs when IAPL_TEST_PG_URL points at an EMPTY + * throw-away database (e.g. `docker run --rm -p 55437:5432 -e POSTGRES_PASSWORD=x postgres:16` → + * postgres://postgres:x@127.0.0.1:55437/postgres). + */ +import type { Config, Payload, PayloadRequest } from 'payload' + +import { postgresAdapter } from '@payloadcms/db-postgres' +import { sqliteAdapter } from '@payloadcms/db-sqlite' +import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { getPayload } from 'payload' +import { afterAll, describe, expect, test, vi } from 'vitest' + +import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' + +const root = path.resolve(import.meta.dirname, '..') +// Inside the repository so the migration files resolve the adapters from node_modules. +const work = path.join(root, `.tmp-consent-upgrade-${process.pid}`) +afterAll(() => rmSync(work, { force: true, recursive: true })) + +/** + * Payload's CLI runs migration files through tsx; here Node loads them itself (type stripping), which cannot tell that + * `MigrateUpArgs` / `MigrateDownArgs` are types. Split them into an `import type` — the SQL is untouched. + */ +function loadableByNode(dir: string) { + for (const name of readdirSync(dir).filter((f) => f.endsWith('.ts'))) { + const file = path.join(dir, name) + const code = readFileSync(file, 'utf8').replace(/import \{([^}]*)\} from '(@payloadcms\/db-\w+)'/, (_m, names: string, from: string) => { + const all = names.split(',').map((n) => n.trim()).filter(Boolean) + const types = all.filter((n) => /^Migrate/.test(n)) + const values = all.filter((n) => !/^Migrate/.test(n)) + return `import type { ${types.join(', ')} } from '${from}'\n${values.length ? `import { ${values.join(', ')} } from '${from}'` : ''}` + }) + writeFileSync(file, code) + } +} + +type Db = 'postgres' | 'sqlite' +const adapter = (db: Db, migrationDir: string) => + db === 'sqlite' + ? sqliteAdapter({ client: { url: `file:${path.join(work, 'site.db')}` }, migrationDir, push: false }) + : postgresAdapter({ migrationDir, pool: { connectionString: process.env.IAPL_TEST_PG_URL! }, push: false }) + +const config = (db: Db, migrationDir: string, consentLog: boolean) => + buildTestConfig({ + collections: [ + { slug: 'users', auth: true, fields: [] }, + // Site settings' logo / favicon upload fields point here + { slug: 'media', fields: [], upload: { staticDir: path.join(work, 'media') } }, + ], + db: adapter(db, migrationDir), + plugins: [ + iapl({ + access: { authCollection: 'users' }, + // 1.16 sites: off (the option was opt-in); 1.17.0: the default (option left out) + ...(consentLog ? {} : { consentLog: false }), + i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, + twoFactor: false, + }), + ], + secret: 'consent-upgrade-test-secret', + telemetry: false, + } as Config) + +const post = (payload: Payload, ip: string) => + (buildConsentLogEndpoint().handler as (r: PayloadRequest) => Promise)( + Object.assign( + new Request('http://acme.pl/api/ipal/consent', { + body: JSON.stringify({ gpc: false, id: 'a1b2c3d4e5f6a7b8c9d0e1f2', state: { analytics: true, functional: false, marketing: false, necessary: true }, version: 1 }), + headers: { 'content-type': 'application/json', 'x-real-ip': ip }, + method: 'POST', + }), + { payload }, + ) as unknown as PayloadRequest, + ) + +async function upgrade(db: Db) { + const migrationDir = path.join(work, db, 'migrations') + mkdirSync(migrationDir, { recursive: true }) + if (db === 'sqlite') {mkdirSync(work, { recursive: true })} + + // 1. the site before 1.17.0: consent log off, its schema from a migration + const before = await getPayload({ config: config(db, migrationDir, false), key: `${db}-before` }) + await before.db.createMigration({ forceAcceptWarning: true, migrationName: 'init', payload: before }) + loadableByNode(migrationDir) + await before.db.migrate() + expect(before.config.collections.map((c) => c.slug)).not.toContain('consent-records') + await before.create({ collection: 'users', data: { email: 'editor@acme.pl', password: 'a-long-enough-password' } }) + await before.db.destroy?.() + + // 2. 1.17.0 deployed WITHOUT a migration: the collection is configured, its table is not there + const after = await getPayload({ config: config(db, migrationDir, true), key: `${db}-after` }) + expect(after.config.collections.map((c) => c.slug)).toContain('consent-records') + const errors = vi.spyOn(after.logger, 'error').mockImplementation(() => undefined as never) + // the rest of the site works + expect((await after.find({ collection: 'users' })).totalDocs).toBe(1) + const first = await post(after, '203.0.113.20') + const second = await post(after, '203.0.113.21') + expect([first.status, second.status]).toEqual([503, 503]) + const lines = errors.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('consent-records table does not exist')) + expect(lines).toHaveLength(1) + errors.mockRestore() + + // 3. the migration the docs ask for: only the consent tables, nothing dropped + await after.db.createMigration({ migrationName: 'consent-log', payload: after }) + const file = readdirSync(migrationDir).find((f) => f.endsWith('.ts') && /consent[_-]log/.test(f))! + const sql = readFileSync(path.join(migrationDir, file), 'utf8') + const up = sql.slice(sql.indexOf('export async function up'), sql.indexOf('export async function down')) + expect(up).toMatch(/CREATE TABLE[^\n]*consent_records/) + expect(up).not.toMatch(/DROP TABLE|DROP COLUMN/i) + // one new table; the only other change is Payload's own document-lock relation gaining a column for it + const created = up.match(/CREATE TABLE[^\n]*/g) ?? [] + expect(created.length).toBeGreaterThan(0) + expect(created.filter((line) => !/consent_records/.test(line))).toEqual([]) + expect((up.match(/ALTER TABLE[^\n]*/g) ?? []).filter((line) => !/payload_locked_documents_rels[^\n]*consent_records/.test(line))).toEqual([]) + loadableByNode(migrationDir) + await after.db.migrate() + expect((await post(after, '203.0.113.22')).status).toBe(201) + const { docs } = await after.find({ collection: 'consent-records' as never, overrideAccess: true }) + expect(docs).toHaveLength(1) + expect(docs[0]).toMatchObject({ choices: { analytics: true, marketing: false }, consentId: 'a1b2c3d4e5f6a7b8c9d0e1f2', version: 1 }) + expect(Object.keys(docs[0])).not.toContain('gpc') + await after.db.destroy?.() +} + +describe('consent log on by default: upgrading a SQL site that never had it', () => { + test('SQLite: without the migration it fails soft; migrate:create adds only the consent tables', { timeout: 120_000 }, async () => { + await upgrade('sqlite') + }) + + test.skipIf(!process.env.IAPL_TEST_PG_URL)('Postgres: the same', { timeout: 120_000 }, async () => { + await upgrade('postgres') + }) +})