/** * 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 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; 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)[name] if (own !== undefined) {return own === true ? true : (own as { read?: unknown }).read} for (const value of Object.values(fields as Record)) { 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: 'a@example.com', 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: 'a@example.com', 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') }) })