Merge claude/security-b-118: plugin status written alone, access answers announced (strict in 1.19.0), drafts left out of related documents

Merged onto ee241de (the prepared 1.17.2). Conflicts kept both sides: AGENT.md rows (consent version; drafts, status, access answers), security.md sections (job queue, visitor accounts; access callbacks), src/index.ts (the jobs exports).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 12:53:59 +01:00
co-authored by Claude Opus 5.5
29 changed files with 554 additions and 48 deletions
+52
View File
@@ -0,0 +1,52 @@
/**
* Access callbacks of a project (`cookieScanner.access`, the doctor's `access`), owner's decision Q4, 1.18.0:
* still allowed on any truthy answer, but an answer that is not a boolean is reported once per option, so a
* project sees it before the next minor version allows only `true`. Every call site goes through one function.
*/
import { readFileSync } from 'node:fs'
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { accessAllowed, resetAccessWarnings } from '../src/modules/shared/accessAnswer.js'
beforeEach(() => resetAccessWarnings())
describe('accessAllowed', () => {
test('true and false are read as they are, without a word', () => {
const warn = vi.fn()
expect(accessAllowed('cookieScanner.access', true, { warn })).toBe(true)
expect(accessAllowed('cookieScanner.access', false, { warn })).toBe(false)
expect(warn).not.toHaveBeenCalled()
})
test.each([
[{ id: 1 }, true, 'an object'],
['no', true, 'a string'],
[1, true, 'a number'],
[null, false, 'null'],
[undefined, false, 'a undefined'],
])('%j is read as before (%s) and reported once', (answer, allowed, kind) => {
const warn = vi.fn()
expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed)
expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed)
expect(warn).toHaveBeenCalledTimes(1)
expect(warn.mock.calls[0][0]).toContain(`doctor.access returned ${kind}`)
expect(warn.mock.calls[0][0]).toContain('only `true` allows')
})
test('each option is reported on its own', () => {
const warn = vi.fn()
accessAllowed('doctor.access', 'x', { warn })
accessAllowed('cookieScanner.access', 'x', { warn })
expect(warn).toHaveBeenCalledTimes(2)
})
})
test('every call of a project access callback goes through accessAllowed', () => {
const sites = ['src/modules/consent/scanner/endpoint.ts', 'src/modules/consent/scanner/approval.ts', 'src/modules/consent/scanner/crawl/endpoints.ts', 'src/modules/doctor/status.ts']
for (const file of sites) {
const text = readFileSync(file, 'utf8')
const calls = text.match(/await options\.access\(\{ req \}\)/g) ?? []
expect(calls.length, file).toBeGreaterThan(0)
expect(text.match(/accessAllowed\('[\w.]+', await options\.access\(\{ req \}\)\)/g)?.length, file).toBe(calls.length)
}
})
+105
View File
@@ -0,0 +1,105 @@
/**
* Drafts as related documents (owner's decision Q5, 1.18.0): a block, a menu or a System pages link that points at a
* page never published no longer brings that page's title, slug and text into what the public helpers answer.
* `draftRelations: 'keep'` and a preview (`draft: true`) keep the old behaviour.
* Real database; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { withoutDraftRelations } from '../src/modules/content/draftRelations.js'
import { getArchiveEntries } from '../src/modules/content/getArchiveEntries.js'
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
vi.mock('server-only', () => ({}))
describe('withoutDraftRelations', () => {
const draft = { id: 2, _status: 'draft', title: 'Secret' }
const live = { id: 1, _status: 'published', title: 'Live' }
test('drops a draft related document: null alone, removed from a list, value null in a polymorphic one', () => {
const doc = { id: 9, _status: 'published', layout: [{ blockType: 'cards', items: [live, draft], one: draft, poly: { relationTo: 'pages', value: draft } }] }
expect(withoutDraftRelations(doc)).toEqual({ id: 9, _status: 'published', layout: [{ blockType: 'cards', items: [live], one: null, poly: { relationTo: 'pages', value: null } }] })
})
test('the document itself, ids, uploads and documents without _status are left alone; nothing is mutated', () => {
const doc = { id: 3, _status: 'draft', image: { id: 5, url: '/m.png' }, page: 2, pages: [1, 2] }
expect(withoutDraftRelations(doc)).toBe(doc)
const nested = { a: { b: draft } }
const out = withoutDraftRelations(nested)
expect(out).toEqual({ a: { b: null } })
expect(nested.a.b).toBe(draft)
})
})
describe('the public helpers on a real database', () => {
let payload: Payload
beforeAll(async () => {
const config = buildTestConfig({
collections: [
{
slug: 'pages',
access: { read: () => true },
fields: [
{ name: 'title', type: 'text' },
{ name: 'slug', type: 'text', localized: true },
{ name: 'related', type: 'relationship', relationTo: 'pages' },
{ name: 'list', type: 'relationship', hasMany: true, relationTo: 'pages' },
{ name: 'layout', type: 'blocks', blocks: [{ slug: 'link', fields: [{ name: 'page', type: 'relationship', relationTo: ['pages', 'posts'] }] }] },
],
versions: { drafts: true },
},
{ slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }, { name: 'see', type: 'relationship', relationTo: 'pages' }], versions: { drafts: true } },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-draft-relations') } },
],
db: testDatabase('draft_relations'),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users' }, content: { collections: [{ slug: 'posts' }] }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail: { relay: false }, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'draft-relations-0123456789-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
const secret = await payload.create({ collection: 'pages' as never, data: { slug: 'tajna', _status: 'draft', title: 'Secret price list' } as never, draft: true })
const live = await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', _status: 'published', title: 'About' } as never })
await payload.create({
collection: 'pages' as never,
data: { slug: 'start', _status: 'published', layout: [{ blockType: 'link', page: { relationTo: 'pages', value: secret.id } }], list: [live.id, secret.id], related: secret.id, title: 'Start' } as never,
})
await payload.create({ collection: 'posts' as never, data: { slug: 'wpis', _status: 'published', see: secret.id, title: 'Post' } as never })
}, 120_000)
afterAll(async () => {
await payload?.destroy?.()
})
const start = async (options: Record<string, unknown> = {}) => (await resolveRoute({ locale: 'pl', payload, segments: ['start'], ...options }))?.doc as Record<string, unknown>
test('resolveRoute: the page answers without the draft it points at (single, list, polymorphic block)', async () => {
const doc = await start()
expect(doc.related).toBeNull()
expect((doc.list as { title: string }[]).map((p) => p.title)).toEqual(['About'])
expect((doc.layout as { page: { value: unknown } }[])[0].page.value).toBeNull()
expect(JSON.stringify(doc)).not.toContain('Secret price list')
})
test("draftRelations: 'keep' and a preview answer them as before", async () => {
for (const options of [{ draftRelations: 'keep' }, { draft: true }]) {
expect(JSON.stringify(await start(options))).toContain('Secret price list')
}
})
test('getArchiveEntries: an entry without the draft it points at; keep as before', async () => {
const hidden = await getArchiveEntries({ collection: 'posts', locale: 'pl', payload })
expect((hidden.docs[0] as { see: unknown }).see).toBeNull()
const kept = await getArchiveEntries({ collection: 'posts', draftRelations: 'keep', locale: 'pl', payload })
expect(JSON.stringify(kept.docs)).toContain('Secret price list')
})
})
+109
View File
@@ -0,0 +1,109 @@
/**
* Plugin writes that do not carry an old copy of a settings global back (owner's decision Q3, 1.18.0).
*
* - The integration status (`emailStatus`, `turnstileStatus`) is written after an ANONYMOUS form submit or a mail
* send. Payload's `updateGlobal` reads the whole document, merges the change and writes the whole result: an
* admin's SMTP or Turnstile change saved in between was put back silently. The status is now written alone.
* - `addToCookieList` (cookie approval, review) read the cookie list, added a row and wrote the whole list: a row
* an editor saved in between was lost. It now checks the list again right before writing and starts over when
* it changed.
*
* The race is made exact by holding the plugin's read and letting the other save land in between.
* Real database; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { addToCookieList } from '../src/modules/consent/scanner/sync.js'
import { recordIntegrationStatus } from '../src/modules/integrations/status.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
vi.mock('server-only', () => ({}))
let payload: Payload
const SI = 'site-integrations'
const si = async () => (await payload.findGlobal({ slug: SI as never })) as unknown as Record<string, unknown>
beforeAll(async () => {
const config = buildTestConfig({
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-status-writes') } }],
db: testDatabase('status_writes'),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })],
secret: 'status-writes-0123456789-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
}, 120_000)
afterAll(async () => {
await payload?.destroy?.()
})
describe('the integration status is written alone', () => {
test("an admin's SMTP change saved while the status is written stays", async () => {
await payload.updateGlobal({ slug: SI as never, data: { smtpHost: 'old.example.com', smtpPassword: 'old-secret', smtpUser: 'u' } as never })
// the copy any read-merge-write would hold: taken before the admin's save
const before = await payload.db.findGlobal({ slug: SI, req: {} as never })
const real = payload.db.findGlobal.bind(payload.db)
let held = true
const spy = vi.spyOn(payload.db, 'findGlobal').mockImplementation(async (args) => {
if (args.slug === SI && held) {
held = false
// the admin's save lands while the status write is under way
await payload.updateGlobal({ slug: SI as never, data: { smtpHost: 'new.example.com', smtpPassword: 'new-secret' } as never })
return before as never
}
return real(args)
})
try {
await recordIntegrationStatus(payload, 'emailStatus', null, { code: 'smtp-auth', message: 'Login refused', state: 'degraded' })
} finally {
spy.mockRestore()
}
const after = await si()
expect(after).toMatchObject({ smtpHost: 'new.example.com', smtpPassword: 'new-secret' })
expect(after.emailStatus).toMatchObject({ code: 'smtp-auth', state: 'degraded' })
})
test('the status write changes nothing else in the document', async () => {
await payload.updateGlobal({ slug: SI as never, data: { ga4MeasurementId: 'G-KEEP', smtpHost: 'keep.example.com', turnstileSiteKey: 'site-key' } as never })
const { turnstileStatus: _t, updatedAt: _u, ...before } = await si()
await recordIntegrationStatus(payload, 'turnstileStatus', null, { code: 'bad-secret', state: 'degraded' })
const { turnstileStatus, updatedAt: _u2, ...after } = await si()
expect(after).toEqual(before)
expect(turnstileStatus).toMatchObject({ code: 'bad-secret', state: 'degraded' })
})
})
describe('the cookie list keeps a row saved in between', () => {
test('an editor adds a row while the scanner adds its own: both rows stay', async () => {
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: [{ name: 'first', category: 'necessary' }] } as never, locale: 'pl' })
const real = payload.findGlobal.bind(payload)
let held = true
const spy = vi.spyOn(payload, 'findGlobal').mockImplementation(async (args) => {
const result = await real(args as never)
if ((args as { slug: string }).slug === 'cookie-settings' && held) {
held = false
// the editor's save lands after the scanner read the list
const rows = ((await real({ slug: 'cookie-settings' as never, depth: 0, locale: 'pl' as never })) as { cookies?: object[] }).cookies ?? []
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: [...rows, { name: 'editor_cookie', category: 'analytics' }] } as never, locale: 'pl' })
}
return result as never
})
try {
expect(await addToCookieList({ entry: { name: 'scanned_cookie', category: 'marketing' } as never, payload })).toBe('added')
} finally {
spy.mockRestore()
}
const names = (((await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, locale: 'pl' as never })) as { cookies?: { name?: string }[] }).cookies ?? []).map((r) => r.name)
expect(names).toEqual(expect.arrayContaining(['first', 'editor_cookie', 'scanned_cookie']))
})
})