Files
ipal-kit/test/writeOnlySecretQueries.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 eb2ad27787 Write-only secrets cannot be queried (review B-R1)
A where or sort on a write-only field answered by the stored value: as an admin,
where[version.smtpPassword][like]=Zq on Site integrations' versions gave a count, so the
secret could be read back one character at a time. writeOnlySecret now gives the field a
read rule, secretReadAccess (exported), that denies when Payload checks a query's fields
(no document) and allows a document read (masked as before). The panel's edit and create
views pass the document, so the field stays visible and editable there.

Covered: the global, its versions, a collection with and without versions, REST and
GraphQL, like / equals / exists / or / sort / count; reads still masked; panel
permissions; a save still stores the new value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 21:10:45 +01:00

198 lines
9.8 KiB
TypeScript

/**
* A write-only secret cannot be read back through a query (review B-R1 of the IAWL ideas, item 22).
*
* Every read masks the value, but a `where` (or a `sort`) on the field answers by the stored value:
* `where[version.smtpPassword][like]=Zq` gave totalDocs 2 against 0 for a wrong prefix, so an admin (or a stolen
* admin session) read the password back one character at a time. The field now refuses to be named in a query —
* REST and GraphQL, `like` / `equals` / `exists` / `sort`, on the global, its versions and a collection with
* `writeOnlySecret` (with and without versions) — while the panel keeps showing it (masked) and saving it.
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Access, Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { docAccessOperation, docAccessOperationGlobal, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { userMeetsRole } from '../src/modules/access/predicates.js'
import { 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 = 'Correct-horse-battery-9'
const SECRET = 'Zq-SMTP-SECRET-777'
const TOKEN = 'Zq-API-TOKEN-555'
let server: TestServer
let payload: Payload
let auth: Record<string, string>
const admin: Access = ({ req }) => userMeetsRole(req, 'admin')
const vault = (slug: string, versions: boolean) => ({
slug,
access: { create: admin, read: admin, readVersions: admin, update: admin },
fields: [{ name: 'label', type: 'text' as const }, writeOnlySecret({ name: 'apiToken', type: 'text' as const })],
...(versions ? { versions: { maxPerDoc: 5 } } : {}),
})
const get = async (pathname: string) => {
const res = await fetch(`${server.url}/api${pathname}`, { headers: auth })
return { body: await res.text(), status: res.status }
}
const gql = async (query: string) => {
const res = await fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: { ...auth, 'content-type': 'application/json' }, method: 'POST' })
return (await res.json()) as { data?: null | Record<string, unknown>; errors?: { message: string }[] }
}
/** A field's read permission, wherever it sits in the permission tree (`true` = everything allowed). */
const readOf = (fields: unknown, name: string): unknown => {
if (fields === true) {return true}
if (!fields || typeof fields !== 'object') {return undefined}
const own = (fields as Record<string, unknown>)[name]
if (own !== undefined) {return own === true ? true : (own as { read?: unknown }).read}
for (const value of Object.values(fields as Record<string, unknown>)) {
const inner = value && typeof value === 'object' ? readOf((value as { fields?: unknown }).fields, name) : undefined
if (inner !== undefined) {return inner}
}
return undefined
}
/** What a query lets an admin learn: the number of matches, or nothing (refused). */
const total = (body: string) => body.match(/"totalDocs":(\d+)/)?.[1]
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [vault('vaults', true), vault('keys', false), { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-secret-queries') } }],
db: testDatabase('secret_queries'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
globalOverrides: { 'site-integrations': { versions: { max: 5 } } as never },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
mail: { relay: false },
twoFactor: false,
}),
],
secret: 'secret-queries-0123456789-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 })
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp.example.com', smtpPassword: SECRET, smtpUser: 'u' } as never })
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp2.example.com' } as never })
for (const slug of ['vaults', 'keys']) {
const doc = await payload.create({ collection: slug as never, data: { apiToken: TOKEN, label: 'one' } as never })
await payload.update({ id: doc.id, collection: slug as never, data: { label: 'two' } 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?.()
})
describe('reads stay masked (unchanged)', () => {
test.each([
'/globals/site-integrations',
'/globals/site-integrations?locale=all&depth=3',
'/globals/site-integrations?select[smtpPassword]=true',
'/globals/site-integrations/versions?limit=5',
'/vaults?limit=5',
'/vaults/versions?limit=5',
'/keys?limit=5',
])('%s answers the mask, never the value', async (pathname) => {
const { body, status } = await get(pathname)
expect(status).toBe(200)
expect(body).not.toContain(SECRET)
expect(body).not.toContain(TOKEN)
expect(body).toContain(SECRET_MASK)
})
test('GraphQL reads answer the mask', async () => {
const res = await gql('{ SiteIntegration { smtpPassword } versionsSiteIntegration { docs { version { smtpPassword } } } Vaults { docs { apiToken } } }')
expect(res.errors).toBeUndefined()
const text = JSON.stringify(res.data)
expect(text).toContain(SECRET_MASK)
expect(text).not.toContain(SECRET)
expect(text).not.toContain(TOKEN)
})
})
describe('a query cannot name a write-only field (REST)', () => {
const guesses = (field: string, right: string) => [
`where[${field}][like]=${right.slice(0, 2)}`,
`where[${field}][like]=NOPE`,
`where[${field}][equals]=${right}`,
`where[${field}][exists]=true`,
`where[or][0][${field}][like]=${right.slice(0, 2)}`,
`sort=${field}`,
`sort=-${field}`,
]
test.each([
...guesses('version.smtpPassword', SECRET).map((q) => ['/globals/site-integrations/versions', q]),
...guesses('apiToken', TOKEN).map((q) => ['/vaults', q]),
...guesses('version.apiToken', TOKEN).map((q) => ['/vaults/versions', q]),
...guesses('apiToken', TOKEN).map((q) => ['/keys', q]),
])('%s?%s is refused, with no count', async (pathname, query) => {
const { body, status } = await get(`${pathname}?${query}`)
expect(status).toBeGreaterThanOrEqual(400)
expect(total(body)).toBeUndefined()
expect(body).not.toContain(SECRET)
expect(body).not.toContain(TOKEN)
})
test('the same queries on an ordinary field still work', async () => {
expect(total((await get('/globals/site-integrations/versions?where[version.smtpHost][like]=smtp2')).body)).toBe('1')
expect(total((await get('/vaults?where[label][equals]=two')).body)).toBe('1')
expect((await get('/keys?sort=-label')).status).toBe(200)
})
test('a count by the secret is refused too', async () => {
const { body, status } = await get('/vaults/count?where[apiToken][like]=Zq')
expect(status).toBeGreaterThanOrEqual(400)
expect(body).not.toMatch(/"totalDocs":\d/)
})
})
describe('a query cannot name a write-only field (GraphQL)', () => {
test.each([
'{ versionsSiteIntegration(where: { version__smtpPassword: { like: "Zq" } }) { totalDocs } }',
'{ versionsSiteIntegration(where: { version__smtpPassword: { equals: "Zq-SMTP-SECRET-777" } }) { totalDocs } }',
'{ Vaults(where: { apiToken: { like: "Zq" } }) { totalDocs } }',
'{ Keys(where: { apiToken: { exists: true } }) { totalDocs } }',
'{ versionsVaults(where: { version__apiToken: { like: "Zq" } }) { totalDocs } }',
])('%s gives no count', async (query) => {
const res = await gql(query)
expect(res.errors?.length).toBeGreaterThan(0)
expect(JSON.stringify(res.data ?? {})).not.toMatch(/"totalDocs":\d/)
})
})
describe('the panel keeps the field', () => {
test('the edit view of the global may read and change the secret field', async () => {
const req = { payload, user: { ...(await payload.find({ collection: 'users' as never, limit: 1 })).docs[0], collection: 'users' } } as never
const perms = await docAccessOperationGlobal({ data: {}, globalConfig: payload.globals.config.find((g) => g.slug === 'site-integrations')!, req })
expect(readOf(perms.fields, 'smtpPassword')).toBe(true)
})
test('the create view of a collection shows the secret field (the panel passes { _status: "draft" })', async () => {
const req = { payload, user: { ...(await payload.find({ collection: 'users' as never, limit: 1 })).docs[0], collection: 'users' } } as never
const perms = await docAccessOperation({ collection: payload.collections['keys' as never], data: { _status: 'draft' }, req })
expect(readOf(perms.fields, 'apiToken')).toBe(true)
})
test('an admin still saves a new secret and the stored value is the new one', async () => {
const res = await fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify({ smtpPassword: 'Zq-NEW-1' }), headers: { ...auth, 'content-type': 'application/json' }, method: 'POST' })
expect(res.status).toBe(200)
expect(((await payload.findGlobal({ slug: 'site-integrations' as never })) as { smtpPassword?: string }).smtpPassword).toBe('Zq-NEW-1')
})
})