/** * Write-only secrets over real HTTP: the SMTP password and the Turnstile secret key stored in the Site * integrations global never come back — not over REST, not over GraphQL, not to an admin — while server code * still reads them, and a save that does not carry a new value keeps the old one. * Runs on SQLite by default, on 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 { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js' import { keepSecretBeforeValidate, maskSecretAfterRead, SECRET_CLEAR, SECRET_MASK, writeOnlySecret, writeOnlySecrets } from '../src/modules/secrets/writeOnly.js' import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer, type TestServer } from './http/server.js' vi.mock('server-only', () => ({})) const PASSWORD = 'a-long-test-password-1' const SMTP = 'S3CRET-smtp-value' const TURNSTILE = 'S3CRET-turnstile-value' let server: TestServer let payload: Payload let auth: Record const stored = async () => (await payload.findGlobal({ slug: 'site-integrations' as never })) as unknown as Record const get = async () => fetch(`${server.url}/api/globals/site-integrations`, { headers: auth }) const save = async (data: Record) => fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify(data), headers: { 'content-type': 'application/json', ...auth }, method: 'POST' }) const gql = async (query: string) => (await (await fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: { 'content-type': 'application/json', ...auth }, method: 'POST' })).json()) as { data?: Record>; errors?: unknown[] } beforeAll(async () => { const config = buildTestConfig({ admin: { user: 'users' }, collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }], db: testDatabase('secrets'), editor: lexicalEditor(), plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })], secret: 'integration-test-secret-0123456789', telemetry: false, }) payload = await getPayload({ config }) server = await startPayloadServer(config) await payload.create({ collection: 'users' as never, data: { email: 'admin@example.com', password: PASSWORD, roles: ['admin'] } as never }) const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: 'admin@example.com', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string } auth = { authorization: `JWT ${login.token}` } // as a seed or the panel's first save would await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpUser: 'mailer', turnstileSecretKey: TURNSTILE, turnstileSiteKey: 'site-key' } as never }) }, 120_000) afterAll(async () => { await server?.close() await payload?.destroy?.() }) describe('reading', () => { test('REST: an admin gets "a value is set", never the value', async () => { const res = await get() expect(res.status).toBe(200) const text = await res.text() expect(text).not.toContain('S3CRET') const body = JSON.parse(text) as Record expect(body.smtpPassword).toBe(SECRET_MASK) expect(body.turnstileSecretKey).toBe(SECRET_MASK) expect(body.smtpUser).toBe('mailer') // the rest of the global is as before expect(body.turnstileSiteKey).toBe('site-key') }) test('GraphQL: the same', async () => { const out = await gql('{ SiteIntegration { smtpPassword turnstileSecretKey smtpUser } }') expect(out.errors).toBeUndefined() expect(JSON.stringify(out)).not.toContain('S3CRET') expect(out.data?.SiteIntegration).toMatchObject({ smtpPassword: SECRET_MASK, smtpUser: 'mailer', turnstileSecretKey: SECRET_MASK }) }) test('server code (the Local API, access control off) reads the real values', async () => { expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE }) }) test('the Local API WITH access control (a user, overrideAccess: false) is masked like the API', async () => { const user = { ...(await payload.find({ collection: 'users' as never })).docs[0], collection: 'users' } const doc = (await payload.findGlobal({ slug: 'site-integrations' as never, overrideAccess: false, user: user as never })) as unknown as Record expect(doc.smtpPassword).toBe(SECRET_MASK) expect(doc.turnstileSecretKey).toBe(SECRET_MASK) }) }) describe('saving', () => { test('another field alone: the secrets stay, and the answer does not carry them', async () => { // (a field the SMTP password belongs to — server, port, user — asks for it again: writeOnlySecretsBound.test.ts) const res = await save({ smtpFromName: 'The site' }) expect(res.status).toBe(200) expect(await res.text()).not.toContain('S3CRET') expect(await stored()).toMatchObject({ smtpFromName: 'The site', smtpPassword: SMTP, turnstileSecretKey: TURNSTILE }) }) test('what the panel sends back when nothing was typed (the mask), an empty value, null: kept', async () => { for (const value of [SECRET_MASK, '', null]) { expect((await save({ smtpPassword: value, turnstileSecretKey: value })).status).toBe(200) expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE }) } }) test('a whole document read over the API and saved back unchanged keeps the secrets', async () => { const doc = (await (await get()).json()) as Record for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]} expect((await save(doc)).status).toBe(200) expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE }) }) test('a new value replaces the old one; the answer shows the mask', async () => { const res = await save({ smtpPassword: 'S3CRET-new-value' }) const body = (await res.json()) as { result: Record } expect(JSON.stringify(body)).not.toContain('S3CRET') expect(body.result.smtpPassword).toBe(SECRET_MASK) expect(await stored()).toMatchObject({ smtpPassword: 'S3CRET-new-value', turnstileSecretKey: TURNSTILE }) }) test('SECRET_CLEAR removes the stored value; an empty field then reads as empty, not as "set"', async () => { expect((await save({ smtpPassword: SECRET_CLEAR })).status).toBe(200) expect((await stored()).smtpPassword ?? null).toBeNull() const body = (await (await get()).json()) as Record expect(body.smtpPassword ?? null).toBeNull() expect(body.turnstileSecretKey).toBe(SECRET_MASK) // and an empty save on an empty field stays empty expect((await save({ smtpPassword: '' })).status).toBe(200) expect((await stored()).smtpPassword ?? null).toBeNull() }) test('a value that is not text is refused, and the stored one stays', async () => { await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: SMTP, turnstileSecretKey: TURNSTILE } as never }) for (const notText of [false, 0, 5, {}, { a: 1 }, [SECRET_MASK], ['x']]) { const res = await save({ smtpPassword: notText }) expect([JSON.stringify(notText), res.status]).toEqual([JSON.stringify(notText), 400]) expect(await res.text()).not.toContain('S3CRET') expect((await save({ turnstileSecretKey: notText })).status).toBe(400) } expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE }) }) test('GraphQL mutation: the mask keeps, a value replaces', async () => { await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: SMTP } as never }) let out = await gql(`mutation { updateSiteIntegration(data: { smtpPassword: "${SECRET_MASK}", smtpFromName: "By GraphQL" }) { smtpPassword smtpFromName } }`) expect(out.errors).toBeUndefined() expect(out.data?.updateSiteIntegration).toMatchObject({ smtpFromName: 'By GraphQL', smtpPassword: SECRET_MASK }) // a field the password belongs to, without the password: refused here as over REST const moved = await gql(`mutation { updateSiteIntegration(data: { smtpPassword: "${SECRET_MASK}", smtpHost: "other.example.com" }) { smtpHost } }`) expect(moved.errors?.length).toBeGreaterThan(0) expect((await stored()).smtpHost).not.toBe('other.example.com') expect((await stored()).smtpPassword).toBe(SMTP) out = await gql('mutation { updateSiteIntegration(data: { smtpPassword: "S3CRET-by-graphql" }) { smtpPassword } }') expect(JSON.stringify(out)).not.toContain('S3CRET') expect((await stored()).smtpPassword).toBe('S3CRET-by-graphql') }) }) describe('the building blocks', () => { test('the hooks', () => { const read = (value: unknown, overrideAccess?: boolean) => maskSecretAfterRead({ overrideAccess, value } as never) expect(read('x', false)).toBe(SECRET_MASK) expect(read('x', undefined)).toBe(SECRET_MASK) // not told that access control is off → masked expect(read('x', true)).toBe('x') expect(read('', false)).toBe('') expect(read(null, false)).toBeNull() const write = (value: unknown, originalDoc: unknown, p: (number | string)[] = ['token']) => keepSecretBeforeValidate({ originalDoc, path: p, value } as never) expect(write('new', { token: 'old' })).toBe('new') for (const nothing of [undefined, null, '', SECRET_MASK]) {expect(write(nothing, { token: 'old' })).toBe('old')} expect(write(SECRET_CLEAR, { token: 'old' })).toBeNull() expect(write(SECRET_MASK, undefined)).toBeNull() // nothing stored: never the mask itself expect(write(SECRET_MASK, { token: SECRET_MASK })).toBeNull() // a stored mask is not a secret: never written back expect(write('', { group: { items: [{ token: 'deep' }] } }, ['group', 'items', 0, 'token'])).toBe('deep') }) test('writeOnlySecret keeps a field\'s own hooks; writeOnlySecrets finds fields inside tabs, rows and groups', () => { const mine = () => 'mine' const field = writeOnlySecret({ name: 'apiToken', type: 'text', hooks: { afterRead: [mine], beforeValidate: [mine] } }) expect(field.hooks?.afterRead).toEqual([mine, maskSecretAfterRead]) expect(field.hooks?.beforeValidate).toEqual([keepSecretBeforeValidate, mine]) const tree = writeOnlySecrets( [{ type: 'tabs', tabs: [{ fields: [{ type: 'row', fields: [{ name: 'a', type: 'text' }, { name: 'b', type: 'text' }] }], label: 'T' }] }, { name: 'g', type: 'group', fields: [{ name: 'a', type: 'text' }] }], ['a'], ) const flat = JSON.stringify(tree, (_k, v) => (typeof v === 'function' ? v.name : v)) expect(flat.match(/maskSecretAfterRead/g)).toHaveLength(2) expect(flat).toContain('"name":"b","type":"text"}') }) test('the opt-out: secrets: { writeOnly: false } leaves the fields as plain text fields', async () => { const hooked = (fields: unknown) => JSON.stringify(fields, (_k, v) => (typeof v === 'function' ? v.name : v)).includes('maskSecretAfterRead') expect(hooked(buildSiteIntegrations().fields)).toBe(true) expect(hooked(buildSiteIntegrations({ writeOnlySecrets: false }).fields)).toBe(false) const off = await iapl({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, secrets: { writeOnly: false }, twoFactor: false })({ collections: [], secret: 'x' } as never) expect(hooked(off.globals!.find((g) => g.slug === 'site-integrations')!.fields)).toBe(false) }) })