143 lines
7.4 KiB
TypeScript
143 lines
7.4 KiB
TypeScript
/**
|
|
* 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:[email protected]: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<Response>)(
|
|
Object.assign(
|
|
new Request('http://acme.pl/api/ipal/consent', {
|
|
body: JSON.stringify({ id: 'a1b2c3d4e5f6a7b8c9d0e1f2', gpc: false, 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: '[email protected]', 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')
|
|
})
|
|
})
|