Files
ipal-kit/test/writeOnlySecretsBound.test.ts
T
Radosław SmolińskiandClaude Fable 5.2 1141c749de M1 review: account rules before 2FA, the SMTP password stays with its server, the rest of the findings
M1-1 the first-user route is the plugin's own endpoint in front of Payload's; nothing is read from the path.
M1-2 the account rules are put on the collections before the 2FA package wraps them.
M1-6 the admin rule only where the roles are the plugin's; other staff collections: an account of that collection.
     update / delete get the matching defaults (accounts.adminOnlyWrite); doctor rule staff-accounts-open.
M1-5 access.firstUserAdmin: false with a role below the panel role: the default panel role steps aside, an explicit one is refused.
M1-3 a save that changes the SMTP server, port, user or encryption must send the password again (secrets.reenterOnChange);
     new panel field smtpRequireTls.
M1-4 a restore of a version masks the secrets (maskSecretsOnRestore).
M1-7 a refused origin is logged once with the ways to allow it; default ports are normalised.
Minors: m1 day boundary, m3 e-mail check on reset and bulk update, m4 text of 'all', m5 the mask is never kept.
The account suite runs with 2FA off and on.

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

263 lines
15 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 { 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 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, smtpRequireTls: false, 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: [
ipalKit({
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' }],
['"require an encrypted connection"', { smtpRequireTls: true }],
['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, another letter case', 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 document saved before the port and the checkbox had a value: their defaults are not a change', async () => {
await payload.db.updateGlobal({ slug: 'site-integrations', data: { ...(await stored()), smtpPort: null, smtpRequireTls: null } as never })
expect((await save({ smtpFromName: 'Again', smtpPort: 587, smtpRequireTls: false })).status).toBe(200)
expect((await stored()).smtpPassword).toBe(SMTP)
})
test('switching to Microsoft Graph asks for nothing (the password is not used there); switching back to another server does', async () => {
expect((await save({ emailTransport: 'graph' })).status).toBe(200)
expect((await stored()).smtpPassword).toBe(SMTP)
expect((await save({ emailTransport: 'smtp', smtpHost: 'other.example.com' })).status).toBe(400)
expect((await save({ emailTransport: 'smtp' })).status).toBe(400) // the transport itself is one of the settings
expect((await save({ emailTransport: 'smtp', smtpPassword: 'typed-again' })).status).toBe(200)
})
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('"Require an encrypted connection" (smtpRequireTls)', () => {
test('a server that offers no encryption never sees the password; without the option it does, as before', async () => {
const plain = await fakeSmtp()
try {
expect((await save({ smtpHost: '127.0.0.1', smtpPassword: SMTP, smtpPort: plain.port, smtpRequireTls: true })).status).toBe(200)
await testEmail()
expect(plain.seen).toEqual({ auth: '', mails: 0 })
expect((await save({ smtpPassword: SMTP, smtpRequireTls: false })).status).toBe(200)
await testEmail()
expect(plain.seen.auth).toContain(SMTP)
expect(plain.seen.mails).toBe(1)
} finally {
await plain.close()
}
})
})
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"')
})
})