Files
ipal-kit/test/writeOnlySecretsBound.test.ts
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

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

277 lines
16 KiB
TypeScript

/**
* Write-only secrets, the two ways a stored value still got out (review of M1):
* - the SMTP password went to whatever server an admin session pointed the settings at;
* - with versions on for the global, a restore answered with the stored value.
* Real HTTP; 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 net from 'node:net'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'
import { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js'
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
import { buildKeepSecret, keepSecretBeforeValidate, maskSecretsOnRestore, maskWriteOnlySecrets, SECRET_CLEAR, SECRET_MASK, writeOnlySecret } 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 G = '/globals/site-integrations'
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, unknown>
const api = (pathname: string, init: RequestInit = {}, headers: Record<string, string> = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...auth, ...headers } })
const save = (data: Record<string, unknown>, headers: Record<string, string> = {}) => api(G, { body: JSON.stringify(data), method: 'POST' }, headers)
const reset = () => payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' } as never })
/** An SMTP server that offers no STARTTLS and writes down what a client logs in with. */
const fakeSmtp = async () => {
const seen = { auth: '', mails: 0 }
const srv = net.createServer((c) => {
c.on('error', () => {})
let body = false
c.write('220 fake ESMTP\r\n')
c.on('data', (d) => {
for (const line of d.toString().split('\r\n').filter(Boolean)) {
if (body) {
if (line === '.') {
body = false
seen.mails += 1
c.write('250 ok\r\n')
}
} else if (/^EHLO/i.test(line)) {c.write('250-fake\r\n250 AUTH PLAIN LOGIN\r\n')}
else if (/^AUTH PLAIN/i.test(line)) {
seen.auth = Buffer.from(line.split(' ')[2] ?? '', 'base64').toString().replace(/\0/g, '|')
c.write('235 ok\r\n')
} else if (/^(?:MAIL|RCPT|RSET)/i.test(line)) {c.write('250 ok\r\n')}
else if (/^DATA/i.test(line)) {
body = true
c.write('354 go\r\n')
} else if (/^QUIT/i.test(line)) {c.end('221 bye\r\n')}
else {c.write('502 not implemented\r\n')} // STARTTLS among them
}
})
})
await new Promise<void>((resolve) => srv.listen(0, '127.0.0.1', resolve))
return { close: () => new Promise<void>((resolve) => srv.close(() => resolve())), port: (srv.address() as net.AddressInfo).port, seen }
}
const testEmail = () => api('/ipal/test-email', { body: JSON.stringify({ to: '[email protected]' }), method: 'POST' })
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('secrets_bound'),
editor: lexicalEditor(),
email: mailAdapter(),
plugins: [
iapl({
access: { authCollection: 'users' },
forms: {},
// a project that turns versions on for the global
globalOverrides: { 'site-integrations': { versions: { drafts: true } } as never },
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}` }
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
beforeEach(async () => {
await reset()
})
describe('the SMTP password stays with the server it was saved for (secrets.reenterOnChange)', () => {
test('an admin session cannot send the stored password to a server of its own', async () => {
const mine = await fakeSmtp()
try {
// before: 200, then the test e-mail logged in to the new server with the stored password
const moved = await save({ smtpHost: '127.0.0.1', smtpPort: mine.port })
expect(moved.status).toBe(400)
const body = JSON.stringify(await moved.json())
expect(body).toMatch(/Enter the password again/)
expect(body).toContain('smtpPassword')
expect(body).not.toContain(SMTP)
expect(await stored()).toMatchObject({ smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587 })
await testEmail()
expect(mine.seen).toEqual({ auth: '', mails: 0 })
} finally {
await mine.close()
}
})
test.each([
['the server', { smtpHost: 'other.example.com' }],
['the port', { smtpPort: 2525 }],
['the user name', { smtpUser: 'someone-else' }],
['the server to another letter case', { smtpHost: 'SMTP.example.com' }],
['the server by a space', { smtpHost: 'smtp.example.com ' }],
['the server while naming Microsoft Graph as the transport', { emailTransport: 'graph', smtpHost: 'other.example.com' }],
['the port while naming Microsoft Graph as the transport', { emailTransport: 'graph', smtpPort: 2525 }],
['the server, sending the mask back as the panel does', { smtpHost: 'other.example.com', smtpPassword: SECRET_MASK }],
['the server, with an empty password', { smtpHost: 'other.example.com', smtpPassword: '' }],
['the server, in a draft', { _status: 'draft', smtpHost: 'other.example.com' }],
])('changing %s without the password is refused, and nothing is stored', async (_what, data) => {
const draft = '_status' in data
const res = await api(`${G}${draft ? '?draft=true' : ''}`, { body: JSON.stringify(data), method: 'POST' })
expect(res.status).toBe(400)
expect(await stored()).toMatchObject({ smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' })
})
test('in Polish for a Polish panel', async () => {
const res = await save({ smtpHost: 'other.example.com' }, { 'accept-language': 'pl' })
expect(res.status).toBe(400)
expect(JSON.stringify(await res.json())).toMatch(/Wpisz hasło ponownie/)
})
test('with the password typed again the new server is saved; removing the stored value works too', async () => {
expect((await save({ smtpHost: 'other.example.com', smtpPassword: 'typed-again' })).status).toBe(200)
expect(await stored()).toMatchObject({ smtpHost: 'other.example.com', smtpPassword: 'typed-again' })
expect((await save({ smtpHost: 'third.example.com', smtpPassword: SECRET_CLEAR })).status).toBe(200)
expect(await stored()).toMatchObject({ smtpHost: 'third.example.com' })
expect((await stored()).smtpPassword ?? null).toBeNull()
// nothing stored = nothing to protect: the server can be changed freely
expect((await save({ smtpHost: 'fourth.example.com' })).status).toBe(200)
})
test('a save that changes nothing the password belongs to keeps it: the same values sent back, other fields, the port as text', async () => {
const doc = (await (await api(G)).json()) as Record<string, unknown>
for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]}
expect((await save(doc)).status).toBe(200) // the whole form, as the panel sends it
expect((await save({ smtpFromName: 'The site', smtpHost: 'smtp.example.com', smtpPort: '587', smtpUser: 'mailer' })).status).toBe(200)
expect((await save({ turnstileSiteKey: 'site-key' })).status).toBe(200)
expect(await stored()).toMatchObject({ smtpFromName: 'The site', smtpPassword: SMTP })
})
test('a stored NULL where the field has a default (a SQL row, an older document) is not a change', async () => {
// the port sits inside a row; its default is 587, the transport's is 'smtp'
await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), emailTransport: null, smtpPort: null } as never })
expect((await save({ smtpFromName: 'Again' })).status).toBe(200)
expect((await save({ emailTransport: 'smtp', smtpFromName: 'Again', smtpPort: 587 })).status).toBe(200)
await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), emailTransport: null, smtpPort: null } as never })
expect((await save({ smtpFromName: 'Again', smtpPort: null })).status).toBe(200)
const doc = (await (await api(G)).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 save({ smtpPort: 2525 })).status).toBe(400)
expect((await stored()).smtpPassword).toBe(SMTP)
})
// Review round 2 (R2-1): "Microsoft Graph" in the panel does not mean Graph sends — the mail adapter falls back to
// SMTP when the GRAPH_* variables are missing. The transport decides nothing; the server, port and user do.
test('the transport switch is not a way round: Graph + my server in one save, or Graph first and my server after', async () => {
const mine = await fakeSmtp()
try {
const gql = async (data: string) => (await (await api('/graphql', { body: JSON.stringify({ query: `mutation { updateSiteIntegration(data: { ${data} }) { smtpHost } }` }), method: 'POST' })).json()) as { errors?: unknown[] }
// 1. in one save, over REST and over GraphQL
expect((await save({ emailTransport: 'graph', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
expect((await gql(`emailTransport: graph, smtpHost: "127.0.0.1", smtpPort: ${mine.port}`)).errors?.length).toBeGreaterThan(0)
await testEmail()
// 2. the switch alone passes (the password is not asked for, and stays)…
expect((await save({ emailTransport: 'graph' })).status).toBe(200)
// …and the server afterwards does not, with or without naming the transport again
expect((await save({ smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
expect((await save({ emailTransport: 'graph', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
expect((await save({ emailTransport: 'smtp', smtpHost: '127.0.0.1', smtpPort: mine.port })).status).toBe(400)
expect((await gql(`smtpHost: "127.0.0.1", smtpPort: ${mine.port}`)).errors?.length).toBeGreaterThan(0)
await testEmail()
await api('/ipal/test-email', { body: JSON.stringify({ attachmentMB: 5, to: '[email protected]' }), method: 'POST' })
expect(mine.seen).toEqual({ auth: '', mails: 0 })
expect(await stored()).toMatchObject({ emailTransport: 'graph', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587 })
// back to SMTP alone: the same server as before, nothing to ask
expect((await save({ emailTransport: 'smtp' })).status).toBe(200)
} finally {
await mine.close()
}
})
test('server code (a seed, the Local API with access control off) moves the server and keeps the password', async () => {
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'seeded.example.com' } as never })
expect(await stored()).toMatchObject({ smtpHost: 'seeded.example.com', smtpPassword: SMTP })
})
test('the option and the building block', () => {
const hooksOf = (global: ReturnType<typeof buildSiteIntegrations>) => {
const found: unknown[] = []
JSON.stringify(global.fields, (_k, v) => {
if (v && typeof v === 'object' && (v as { name?: string }).name === 'smtpPassword') {found.push((v as { hooks: { beforeValidate: unknown[] } }).hooks?.beforeValidate?.[0])}
return v as unknown
})
return found[0]
}
expect(hooksOf(buildSiteIntegrations())).not.toBe(keepSecretBeforeValidate)
expect(hooksOf(buildSiteIntegrations({ reenterSecretOnChange: false }))).toBe(keepSecretBeforeValidate)
// a field of a project's own
const field = writeOnlySecret({ name: 'apiToken', type: 'text' }, { boundTo: ['apiUrl'] })
const hook = (field as unknown as { hooks: { beforeValidate: ((args: never) => unknown)[] } }).hooks.beforeValidate[0]
const run = (siblingData: unknown, overrideAccess?: boolean) => hook({ originalDoc: { apiToken: 'old', apiUrl: 'https://a.example' }, overrideAccess, path: ['apiToken'], siblingData, value: undefined } as never)
expect(run({ apiUrl: 'https://a.example' })).toBe('old')
expect(run({})).toBe('old')
expect(() => run({ apiUrl: 'https://b.example' })).toThrow()
expect(run({ apiUrl: 'https://b.example' }, true)).toBe('old')
expect(buildKeepSecret({ appliesWhen: () => false, boundTo: ['apiUrl'] })({ originalDoc: { apiToken: 'old', apiUrl: 'a' }, path: ['apiToken'], siblingData: { apiUrl: 'b' }, value: '' } as never)).toBe('old')
})
})
describe('versions on the global: a restore does not hand the value back', () => {
test('REST restore answers with the mask; the stored value is the restored one', async () => {
await save({ smtpFromName: 'One' })
await save({ smtpFromName: 'Two' })
const versions = (await (await api(`${G}/versions?limit=50`)).json()) as { docs: { id: number | string; version: Record<string, unknown> }[] }
expect(versions.docs.length).toBeGreaterThan(1)
expect(JSON.stringify(versions)).not.toContain(SMTP)
const target = versions.docs.find((d) => d.version.smtpFromName === 'One')!
const restored = await api(`${G}/versions/${target.id}`, { method: 'POST' })
expect(restored.status).toBe(200)
const text = await restored.text()
// before: the stored password, under `version`
expect(text).not.toContain(SMTP)
expect(text).toContain(SECRET_MASK)
expect(await stored()).toMatchObject({ smtpFromName: 'One', smtpPassword: SMTP })
// server code that restores with access control off still gets the document as it is
const local = (await payload.restoreGlobalVersion({ id: target.id as never, slug: 'site-integrations' as never })) as unknown as { version?: Record<string, unknown> }
expect(JSON.stringify(local)).toContain(SMTP)
})
test('the hook and the walker', () => {
const fields = [
{ type: 'tabs', tabs: [{ fields: [writeOnlySecret({ name: 'a', type: 'text' }), { name: 'plain', type: 'text' }], label: 'T' }, { name: 'named', fields: [writeOnlySecret({ name: 'b', type: 'text' })] }] },
{ name: 'g', type: 'group', fields: [{ type: 'row', fields: [writeOnlySecret({ name: 'c', type: 'text' })] }] },
{ name: 'rows', type: 'array', fields: [writeOnlySecret({ name: 'd', type: 'text' })] },
{ name: 'layout', type: 'blocks', blocks: [{ slug: 'x', fields: [writeOnlySecret({ name: 'e', type: 'text' })] }] },
] as never
const doc = () => ({ a: 's', g: { c: 's' }, layout: [{ blockType: 'x', e: 's' }, { blockType: 'other', e: 'kept' }], named: { b: 's' }, plain: 'p', rows: [{ d: 's' }, { d: '' }] })
const masked = doc()
maskWriteOnlySecrets(masked, fields)
expect(masked).toEqual({ a: SECRET_MASK, g: { c: SECRET_MASK }, layout: [{ blockType: 'x', e: SECRET_MASK }, { blockType: 'other', e: 'kept' }], named: { b: SECRET_MASK }, plain: 'p', rows: [{ d: SECRET_MASK }, { d: '' }] })
const hook = (extra: Record<string, unknown>) => JSON.stringify(maskSecretsOnRestore({ context: { isRestoringVersion: true }, doc: { version: doc() }, global: { fields }, ...extra } as never))
expect(hook({})).not.toContain('"s"')
expect(hook({ overrideAccess: true })).toContain('"s"')
expect(hook({ context: {} })).toContain('"s"') // an ordinary read: the field hooks did the work already
expect(hook({ collection: { fields }, global: undefined })).not.toContain('"s"')
})
})