Files
ipal-kit/test/writeOnlySecrets.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 6e0ad26b2c M1 review round 3: late staff collections without guessing Payload's default; rules survive a dev reload
R3-1 nothing is decided by a function's name any more (a production build renames it): on a collection that
     arrives after ipalKit the plugin's rule is put in FRONT of the rule that is there and both must allow
     (bothAllow). unlock follows the same table. The log says exactly what was put.
R3-2 the adoption walks the live config (payload.config), which Payload swaps first on a dev reload.
R3-3 readVersions gets the read rule on staff collections.
R3-5 a secret that is not text is refused.
Also: the async check of requireSetup.exempt compares the constructor, not its name.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 00:39:24 +01:00

200 lines
12 KiB
TypeScript

/**
* 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 { ipalKit } 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<string, string>
const stored = async () => (await payload.findGlobal({ slug: 'site-integrations' as never })) as unknown as Record<string, null | string | undefined>
const get = async () => fetch(`${server.url}/api/globals/site-integrations`, { headers: auth })
const save = async (data: Record<string, unknown>) => 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<string, Record<string, unknown>>; 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: [ipalKit({ 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: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', 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<string, unknown>
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<string, unknown>
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<string, unknown>
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<string, unknown> }
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<string, unknown>
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 ipalKit({ 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)
})
})