From eb2ad277879da024d59e9bd215df251fb6c96ffe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 21:10:45 +0100 Subject: [PATCH] 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 --- docs/agent/AGENT.md | 2 +- docs/agent/skills/iapl-audit/SKILL.md | 4 + docs/security.md | 8 ++ src/index.ts | 1 + src/modules/secrets/writeOnly.ts | 25 +++- test/writeOnlySecretQueries.test.ts | 197 ++++++++++++++++++++++++++ 6 files changed, 234 insertions(+), 3 deletions(-) create mode 100644 test/writeOnlySecretQueries.test.ts diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 19c1690..693965e 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1227,7 +1227,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | The second factor on every collection and global, whichever plugin added it, and on the plugin's endpoints; an unrecognised 2FA package = startup error | per entity: `custom.ipal.secondFactor: false` or `{ read: false }` (or the package's `custom.totp.disableAccessWrapper`); everywhere: `twoFactor.guard: false` (not recommended) | `requireSecondFactor` / `secondFactorPassed` in your own access functions and endpoints | | At most 5 verify attempts per account in 10 minutes (`POST /api/verify-totp` → `429`); the count is kept in memory and in the database (`payload.kv`), so a restart or a second instance does not reset it | `twoFactor.verifyLimit: false` | `verifyLimit: { max, windowMinutes, store: 'memory' }` | | 2FA verify and setup attempts only from the site's own origin: a request a browser marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) gets `403` and is not counted. **Set `serverURL`**: behind a proxy that rewrites `Host` and sends no `X-Forwarded-Host` the site's own page is refused without it (logged once per origin: `[iapl] 2FA: a code from origin … was refused`) | `twoFactor.sameOrigin: false` | `sameOrigin: { origins: ['https://app.example.com'] }`; `requestFromOwnOrigin`, `reportRefusedOrigin` | -| Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` | +| Stored secrets are write-only: `smtpPassword` and `turnstileSecretKey` come back as `'********'` over REST, GraphQL and in the panel; an empty save keeps the value, `'[[clear]]'` removes it; server code reads the real value with the Local API. A query cannot name a secret (1.17.1): `where` / `sort` on it — REST, GraphQL, versions — is refused (`secretReadAccess`, the field's `read` rule; verify: `GET /api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true` as an admin → 403, no `totalDocs`). **The panel is the source — never add an env variable for them** (`TURNSTILE_SECRET_KEY` is deprecated) | `secrets: { writeOnly: false }` | `writeOnlySecret(field)` / `writeOnlySecrets(fields, names)` for your own secret fields; with versions on the entity add `hooks.afterRead: [maskSecretsOnRestore]` | | The SMTP password stays with its server: a save in the panel or over the API that changes the server, port or user name without the password is refused (`400` "Enter the password again…"), whatever the transport says — otherwise an admin session points the server at its own machine and a test e-mail hands the password over. A change of the transport alone asks for nothing. Seeds and scripts (Local API, access control off) are not asked | `secrets: { reenterOnChange: false }` | `writeOnlySecret(field, { boundTo: [...] })`, `buildKeepSecret`, `SMTP_PASSWORD_BOUND_TO` | | The admin panel opens for `editor` and above; an account with only `user` sees "Unauthorized" (the API is not touched). First start logs how many accounts are below the role | `accounts: { panelRole: 'user' }` (or `false`) | `panelRole: 'admin'`; your own `access.admin`; `panelAccess(role)` | | Nobody creates an account for themselves, or takes one over. A staff collection (also the project's own, also one a later plugin adds) without a `create` / `update` / `delete` / `unlock` / `read` / `readVersions` rule gets one (on a collection a later plugin adds the plugin's rule is put in front of its own and both must allow; `custom: { ipal: { accountRules: false } }` on it keeps its own): with the plugin's roles, or wherever an account of it can hold `editor` or `admin` (`user, editor, admin, boss`; `viewer, editor`; a `roles` field that is text, json or a relationship holding a list — the value in the account's `roles` array makes a plugin admin or editor; a single-valued `roles` field is not affected: its value never counts) — create, delete, unlock: an admin; update: an admin or the account itself; the `roles` field: only an admin. With roles of its own that hold neither `editor` nor `admin`, or none: an account of that same collection, or a plugin admin, and an account never changes its own roles — **the plugin cannot rank a project's own roles: write that collection's rules** (`iapl-doctor` → `staff-own-roles`). `read`: a staff account. Payload's first-user route answers only for the panel's login collection (the first account, which becomes admin), in any spelling of the URL. `access.firstUserAdmin: false` with a default role below the panel role: the default panel role is not applied (logged), an explicit one is refused at start. With a slug in `access.staffCollections` that is not an auth collection Payload does not start (`/api/health` 503) | `accounts: { adminOnlyCreate: false, adminOnlyWrite: false, staffOnlyRead: false, firstUserRoute: 'all' }` | your own rule wins; `firstUserRoute: ['users', 'partners']`; a collection with open sign-up keeps its routes; `staffCreateAccess`, `staffUpdateAccess(slug)`, `staffReadAccess`, `sameStaffCollectionAccess(slug)`, `rolesByAdminOnly`, `rolesNotOwn(slug)`, `hasPluginRoles`, `applyStaffAccountAccess`, `adoptLateAuthCollections`, `buildFirstUserEndpoint` | diff --git a/docs/agent/skills/iapl-audit/SKILL.md b/docs/agent/skills/iapl-audit/SKILL.md index 8616853..b41752c 100644 --- a/docs/agent/skills/iapl-audit/SKILL.md +++ b/docs/agent/skills/iapl-audit/SKILL.md @@ -73,5 +73,9 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` — `curl -s "$U/api/?draft=true&limit=100" | grep -c '"_status":"draft"'` → `0`, else ERROR: give it `access: { read: readPublished(), readVersions: readPublished() }` (access.md). `curl -sI "$U/md/xx"` → `404` (no stand-in locale); a 404 page assigned in System pages must be published. +- **Secrets out of queries** (as an admin, with versions on for Site integrations or a collection using + `writeOnlySecret`): `curl -s -H "Authorization: JWT $T" "$U/api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true"` + answers an error with no `totalDocs`, else ERROR (the field lost `secretReadAccess`, e.g. an override replaced its + `access`). Do not say "done" until the full audit (without `--quick`) has no errors. diff --git a/docs/security.md b/docs/security.md index 0fc3a88..31f0d08 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1063,6 +1063,14 @@ document, the fields under `version`, where field hooks do not run: the global's value is set"; the API returns the mask. Code of your own that read the secret over REST / GraphQL as an admin must read it on the server with the Local API instead. - **Off:** `iapl({ secrets: { writeOnly: false } })` — the value is returned to whoever may read the global. +- **A query cannot name a secret (1.17.1).** A `where` or `sort` on a write-only field answers by the stored value + (`where[version.smtpPassword][like]=Zq` gave a count), so an admin could read the secret back one character at a + time. `writeOnlySecret` now gives the field a `read` rule, `secretReadAccess`, that refuses a query naming it — + REST and GraphQL, `like` / `equals` / `exists` / `sort`, on the document and its versions (an error, no count) — while + every read of a document still answers the mask and the panel shows and saves the field as before. Payload checks a + query's fields without a document and asks rules that depend on one to deny then; the panel always passes the + document. The field's own `access.read` is kept and decides for a document. Not in collection list columns or + list filters. Server code with `overrideAccess` (the Local API) may still query it. - **Your own secret fields:** `writeOnlySecret({ name: 'apiToken', type: 'text', admin: { components: { Field: '@intecion/ipal-kit/admin#MaskedField' } } })`, or `writeOnlySecrets(fields, ['apiToken'])` for fields inside tabs / rows / groups; the hooks `maskSecretAfterRead` / `keepSecretBeforeValidate`, `SECRET_MASK`, diff --git a/src/index.ts b/src/index.ts index 0fca720..9091026 100644 --- a/src/index.ts +++ b/src/index.ts @@ -421,6 +421,7 @@ export { maskWriteOnlySecrets, SECRET_CLEAR, SECRET_MASK, + secretReadAccess, SMTP_PASSWORD_BOUND_TO, writeOnlySecret, writeOnlySecrets, diff --git a/src/modules/secrets/writeOnly.ts b/src/modules/secrets/writeOnly.ts index eb45485..fce6b28 100644 --- a/src/modules/secrets/writeOnly.ts +++ b/src/modules/secrets/writeOnly.ts @@ -1,4 +1,4 @@ -import type { CollectionAfterReadHook, Field, FieldHook, GlobalAfterReadHook } from 'payload' +import type { CollectionAfterReadHook, Field, FieldAccess, FieldHook, GlobalAfterReadHook } from 'payload' import { ValidationError } from 'payload' @@ -130,11 +130,32 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp */ export const keepSecretBeforeValidate: FieldHook = buildKeepSecret() -/** Adds the two hooks to a field (a text field as a rule). The field's own hooks stay, and run around them. */ +/** + * The field `read` rule of a write-only secret: a document may be read (the value comes back masked), a query may + * not name the field. A `where` / `sort` on the field answers by the stored value — `like: "Zq"` gives a count — + * so it would read the secret back one character at a time (review B-R1). Payload checks a query's fields with + * permissions built WITHOUT a document and asks rules that depend on one to deny then; the panel's edit and create + * views always pass the document (a global's stored data, a collection's `{ _status: 'draft', … }`), so the field + * stays visible and editable there. The field's own `read` rule, if any, still decides for a document. + */ +export function secretReadAccess(own?: FieldAccess): FieldAccess { + return (args) => { + const { data, doc, siblingData } = args as { data?: unknown; doc?: unknown; siblingData?: unknown } + if (doc === undefined && data === undefined && siblingData === undefined) {return false} + return own ? own(args) : true + } +} + +/** + * Adds the two hooks to a field (a text field as a rule), and a `read` rule that keeps it out of queries + * (`secretReadAccess`). The field's own hooks stay, and run around them; its own `access` is kept. + */ export function writeOnlySecret(field: F, options: WriteOnlySecretOptions = {}): F { const own = (field as { hooks?: { afterRead?: FieldHook[]; beforeValidate?: FieldHook[] } }).hooks ?? {} + const access = (field as { access?: { create?: FieldAccess; read?: FieldAccess; update?: FieldAccess } }).access return { ...field, + access: { ...access, read: secretReadAccess(access?.read) }, custom: { ...(field as { custom?: Record }).custom, ipalWriteOnly: true }, hooks: { ...own, diff --git a/test/writeOnlySecretQueries.test.ts b/test/writeOnlySecretQueries.test.ts new file mode 100644 index 0000000..34c8fb9 --- /dev/null +++ b/test/writeOnlySecretQueries.test.ts @@ -0,0 +1,197 @@ +/** + * 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') + }) +})