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]>
189 lines
11 KiB
TypeScript
189 lines
11 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('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)
|
|
})
|
|
})
|