/** * 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 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'])) }) })