Merge claude/security-b-content-state-cc308e: sizes before work, one link rule, no stand-in locale, strict switches, write-only secrets cannot be queried

AGENT.md conflict: the 2FA rows from A, the stored-secrets row from B (its check answers 400 QueryError, not 403).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 21:43:03 +01:00
co-authored by Claude Opus 5.5
40 changed files with 1148 additions and 72 deletions
+199
View File
@@ -0,0 +1,199 @@
/**
* IAWL security ideas, group B (locales, save and state, signatures, switches, secret fields, HTML) — the unit
* proofs of what was fixed. The HTTP proofs are in iawlIdeasBHttp.test.ts.
*/
import { describe, expect, test } from 'vitest'
import { describeFromMarkdown, truncate } from '../src/modules/seo/plainText.js'
/** Idea 2: a value the plugin writes after validation must still fit the limit it was cut to. */
describe('a cut value fits its limit', () => {
test.each([10, 155, 300])('truncate(…, %i) is never longer than the limit', (max) => {
for (const text of ['x'.repeat(max * 2), `${'word '.repeat(max)}`, `${'y'.repeat(max - 1)} ${'z'.repeat(max)}`]) {
const out = truncate(text, max)
expect(out.length).toBeLessThanOrEqual(max)
expect(out.endsWith('…')).toBe(true)
}
})
test('describeFromMarkdown keeps to its length when it has to cut', () => {
expect(describeFromMarkdown('a'.repeat(400), 155).length).toBeLessThanOrEqual(155)
})
test('a text within the limit is left as it is', () => {
expect(truncate('short text', 155)).toBe('short text')
})
})
/** A body sent without a content-length (chunked): the stream is the only thing that tells its size. */
const chunked = (url: string, size: number, init: RequestInit = {}) => {
const chunk = new TextEncoder().encode('x'.repeat(1024))
let sent = 0
let pulled = 0
const body = new ReadableStream<Uint8Array>({
pull(controller) {
pulled += 1
if (sent >= size) {return controller.close()}
sent += chunk.byteLength
controller.enqueue(chunk)
},
})
const request = new Request(url, { ...init, body, duplex: 'half', method: 'POST' } as RequestInit)
return { pulled: () => pulled, request }
}
/** Idea 1: the size of a request is checked before it is read whole, the length of a query before it is searched. */
describe('request size and list length before the work', () => {
test('the CSP report route stops reading a chunked body at its cap', async () => {
const { createCspReportRoute } = await import('../src/modules/security/createCspReportRoute.js')
const reports: unknown[] = []
const route = createCspReportRoute({ maxBytes: 4096, onReport: (v) => void reports.push(v) })
const big = chunked('http://site.test/api/csp-report', 1024 * 1024)
expect((await route(big.request)).status).toBe(413)
expect(big.pulled()).toBeLessThan(16)
})
test('the mail service confirm call stops reading a chunked body at its cap', async () => {
const { relayConfirmEndpoint } = await import('../src/modules/email/relay/confirm.js')
const endpoint = relayConfirmEndpoint()
const big = chunked('http://site.test/api/iapl/mail-relay/confirm', 1024 * 1024, { headers: { 'x-forwarded-for': '203.0.113.9' } })
const res = await endpoint.handler(big.request as never)
expect(res.status).toBe(404)
expect(big.pulled()).toBeLessThan(16)
})
test('the MCP route refuses a body over its cap before parsing it', async () => {
const { createMcpRoute } = await import('../src/modules/mcp/createMcpRoute.js')
const { POST } = createMcpRoute({
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
getCachedPayload: () => Promise.reject(new Error('must not be reached')),
rateLimit: false,
})
const big = chunked('http://site.test/api/mcp', 4 * 1024 * 1024)
const res = await POST(big.request)
expect(res.status).toBe(413)
expect(big.pulled()).toBeLessThan(200)
})
test('searchContent cuts a huge query before it reaches the database', async () => {
const { searchContent } = await import('../src/modules/content/searchContent.js')
const seen: string[] = []
const payload = {
find: async ({ where }: { where: { or: { title: { like: string } }[] } }) => {
seen.push(where.or[0].title.like)
return { docs: [] }
},
findGlobal: async () => ({}),
}
const query = Array.from({ length: 5000 }, (_, i) => `w${i}`).join(' ')
await searchContent({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, payload: payload as never, query })
expect(seen).toHaveLength(1)
expect(seen[0].length).toBeLessThanOrEqual(200)
expect(seen[0].split(' ').length).toBeLessThanOrEqual(10)
// a normal query is passed as it is
await searchContent({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, payload: payload as never, query: 'cennik usług' })
expect(seen[1]).toBe('cennik usług')
})
test('the visit counter does not read a chunked body past its cap', async () => {
const { buildStatsEndpoint } = await import('../src/modules/stats/endpoint.js')
const endpoint = buildStatsEndpoint({} as never)
const big = chunked('http://site.test/api/ipal/hit', 1024 * 1024, { headers: { 'user-agent': 'Mozilla/5.0', 'x-forwarded-for': '203.0.113.10' } })
const res = await endpoint.handler(Object.assign(big.request, { payload: {} }) as never)
expect(res.status).toBe(204)
expect(big.pulled()).toBeLessThan(16)
})
})
/** Idea 21: a value nobody understands as off is refused at start, never read as off or open. */
describe('switches refuse nonsense at start', () => {
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
const start = async (options: Record<string, unknown>) => {
const { iapl } = await import('../src/plugin.js')
return () => iapl({ i18n, ...options } as never)
}
test.each([
['accounts', { accounts: 0 }],
['accounts', { accounts: '' }],
['stats', { stats: 'false' }],
['cookieScanner', { cookieScanner: 'off' }],
['indexNow', { indexNow: 'false' }],
['forms.attachments', { forms: { attachments: 'false' } }],
['twoFactor.allowCollectionMismatch', { twoFactor: { allowCollectionMismatch: 'false', collection: 'users', totp: { issuer: 'x' } } }],
['consentLog.retentionDays', { consentLog: { retentionDays: null } }],
['consentLog.retentionDays', { consentLog: { retentionDays: 0 } }],
['adminMeta.robots.index', { adminMeta: { robots: { index: 'false' } } }],
['dashboardAlerts.integrations', { dashboardAlerts: { integrations: 'Admin' } }],
['mail.relay.accountMail.windowMinutes', { mail: { relay: { accountMail: { windowMinutes: 0 } } } }],
['mail.relay.confirmRateLimit.windowMs', { mail: { relay: { confirmRateLimit: { windowMs: 0 } } } }],
['mail.relay', { mail: { relay: 'off' } }],
['storageNames', { storageNames: 'IAPL' }],
['forms.attachments.submit.maxPerMinute', { forms: { attachments: { submit: { maxPerMinute: 'off' } } } }],
])('%s: %j fails at start', async (name, options) => {
expect(await start(options)).toThrow(name)
})
test.each([
[{}],
[{ accounts: false, consentLog: { retentionDays: 30 }, cookieScanner: false, indexNow: true, stats: true }],
[{ dashboardAlerts: { cookies: 'all', integrations: 'editor' }, mail: { relay: { accountMail: false } } }],
[{ adminMeta: { robots: { follow: false, index: false } }, forms: { attachments: { submit: { maxPerMinute: 0 } } } }],
])('real values start as before: %j', async (options) => {
expect(await start(options)).not.toThrow()
})
test('an unknown role name is met by nobody, and requireRole refuses it where it is written', async () => {
const { hasMinimumRole, userMeetsRole } = await import('../src/modules/access/predicates.js')
const { requireRole, requireRoleField } = await import('../src/modules/access/access.js')
const payload = { collections: { users: { config: { fields: [{ name: 'roles' }] } } }, config: { admin: { user: 'users' }, collections: [{ slug: 'users', auth: true }] } }
const admin = { id: 1, collection: 'users', roles: ['admin'] }
expect(hasMinimumRole(admin as never, 'admin', payload as never)).toBe(true)
expect(hasMinimumRole(admin as never, 'Admin' as never, payload as never)).toBe(false)
expect(userMeetsRole({ payload: payload as never, user: { ...admin, roles: [] } }, 'admins' as never)).toBe(false)
expect(() => requireRole('superadmin' as never)).toThrow('requireRole')
expect(() => requireRoleField('Editor' as never)).toThrow('requireRoleField')
expect(() => requireRole('editor')).not.toThrow()
})
test('buildCsp refuses a string where sources are a list, and a dev flag that is not a boolean', async () => {
const { buildCsp } = await import('../src/modules/security/buildCsp.js')
expect(() => buildCsp({ extra: { 'img-src': 'https://*.cdn.com' as never } })).toThrow("extra['img-src']")
expect(() => buildCsp({ dev: 'false' as never })).toThrow('buildCsp.dev')
expect(buildCsp({ dev: false, extra: { 'img-src': ['https://cdn.example.com'] } }).value).toContain('img-src')
})
test('buildSecurityHeaders refuses values a browser would drop', async () => {
const { buildSecurityHeaders } = await import('../src/modules/security/buildSecurityHeaders.js')
expect(() => buildSecurityHeaders({ hsts: null as never })).toThrow('hsts')
expect(() => buildSecurityHeaders({ hstsMaxAge: 'abc' as never })).toThrow('hstsMaxAge')
expect(() => buildSecurityHeaders({ frameOptions: 'false' as never })).toThrow('frameOptions')
expect(buildSecurityHeaders({ frameOptions: null, permissionsPolicy: null }).map((h) => h.key)).not.toContain('X-Frame-Options')
expect(buildSecurityHeaders().map((h) => h.key)).toContain('Strict-Transport-Security')
})
test('the seed guard cannot be switched off by 0 or allowed by "false"', async () => {
const { createSeeder } = await import('../src/modules/seed/seeder.js')
const payload = { logger: { info: () => {} } } as never
expect(() => createSeeder(payload, { guard: 0 as never })).toThrow('seed guard')
expect(() => createSeeder(payload, { guard: { allowFull: 'false' as never } })).toThrow('seed guard.allowFull')
})
})
/** Idea 25 at the search route: a code the site does not have is the default locale, in the search and the answer. */
test('createSearchRoute never passes an unknown ?locale on', async () => {
const { createSearchRoute } = await import('../src/modules/content/createSearchRoute.js')
const asked: string[] = []
const route = createSearchRoute({
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
getCachedPayload: async () => ({ find: async () => ({ docs: [{ id: 1, slug: 'o-nas', title: 'O nas' }] }), findGlobal: async () => ({}) }) as never,
isPathVisible: async (_path, locale) => {
asked.push(locale)
return true
},
rateLimit: false,
})
const body = (await (await route(new Request('http://site.test/api/search?q=nas&locale=../xx'))).json()) as { locale: string }
expect(body.locale).toBe('pl')
expect(asked.every((l) => l === 'pl')).toBe(true)
})
+99
View File
@@ -0,0 +1,99 @@
/**
* IAWL ideas 23–25 against a running Payload (SQLite): what a visitor's URL can make the content helpers serve.
* 23 — a draft is shown only where it is asked for: never as the site's 404 page.
* 24/25 — IAPL has no hidden locales; the stand-in it must not invent is a page in a locale the site does not
* have (`/md/xx`, `/xx/…` past the proxy, `all`): those are "not found", not the default locale's page.
*/
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 { createMarkdownRoute } from '../src/modules/content/createMarkdownRenderer.js'
import { resolveNotFoundPage } from '../src/modules/content/resolveNotFoundPage.js'
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
vi.mock('server-only', () => ({}))
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const
let payload: Payload
let draft404: number | string
let published404: number | string
beforeAll(async () => {
const config = buildTestConfig({
collections: [
{
slug: 'pages',
access: { read: () => true },
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', localized: true },
{ name: 'layout', type: 'blocks', blocks: [{ slug: 'text', fields: [{ name: 'body', type: 'textarea', localized: true }] }] },
],
versions: { drafts: true },
},
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iawlb-content-media') } },
],
db: testDatabase('iawlb_content'),
editor: lexicalEditor(),
plugins: [iapl({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'iawl-ideas-b-content',
telemetry: false,
})
payload = await getPayload({ config })
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'start', _status: 'published', layout: [{ blockType: 'text', body: 'Witamy' }], title: 'Start' } as never, locale: 'pl' })
await payload.update({ id: home.id, collection: 'pages' as never, data: { slug: 'home', _status: 'published', title: 'Home' } as never, locale: 'en' })
draft404 = (await payload.create({ collection: 'pages' as never, data: { slug: 'nie-znaleziono', _status: 'draft', title: 'Szkic: nowa cena 999 zł' } as never, draft: true, locale: 'pl' })).id
published404 = (await payload.create({ collection: 'pages' as never, data: { slug: 'brak', _status: 'published', title: 'Nie ma takiej strony' } as never, locale: 'pl' })).id
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, notFound: draft404, siteName: 'Test' } as never })
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('idea 23: a never-published page is not the 404 page', () => {
test('resolveNotFoundPage gives the built-in view (null) while the assigned page is a draft', async () => {
expect(await resolveNotFoundPage({ locale: 'pl', payload })).toBeNull()
})
test('once a published page is assigned, it is the 404 page', async () => {
await payload.updateGlobal({ slug: 'site-settings' as never, data: { notFound: published404 } as never })
expect(await resolveNotFoundPage({ locale: 'pl', payload })).toMatchObject({ title: 'Nie ma takiej strony' })
await payload.updateGlobal({ slug: 'site-settings' as never, data: { notFound: draft404 } as never })
})
test('createContentHelpers().getNotFoundPage keeps the draft out too', async () => {
const { createContentHelpers } = await import('../src/modules/frontend/createContentHelpers.js')
const helpers = createContentHelpers({ config: payload.config, i18n })
expect(await helpers.getNotFoundPage('pl')).toBeNull()
})
})
describe('ideas 24/25: no stand-in locale', () => {
test('a configured locale resolves its own page', async () => {
expect(await resolveRoute({ locale: 'en', payload, segments: [] })).toMatchObject({ doc: { title: 'Home' } })
})
test.each(['xx', 'all', '*', 'de'])('locale %j resolves nothing (not the default locale\'s page)', async (locale) => {
expect(await resolveRoute({ locale, payload, segments: [] })).toBeNull()
})
test('the Markdown route answers 404 for /md/xx and /md/all', async () => {
const { GET } = createMarkdownRoute({ config: i18n, getCachedPayload: async () => payload })
for (const locale of ['xx', 'all']) {
const res = await GET(new Request(`http://site.test/md/${locale}`), { params: Promise.resolve({ locale }) })
expect(res.status).toBe(404)
}
const ok = await GET(new Request('http://site.test/md/pl'), { params: Promise.resolve({ locale: 'pl' }) })
expect(ok.status).toBe(200)
expect(await ok.text()).toContain('Witamy')
})
})
+170
View File
@@ -0,0 +1,170 @@
/**
* IAWL security ideas, group B, through real HTTP (REST and GraphQL) against a running Payload.
* SQLite by default; Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
*
* 22/37 — the versions of Site integrations (a project may turn them on) are read by the people who read the
* global, not by every signed-in account; the secrets stay masked there.
* 23 — drafts over REST / GraphQL follow the collection's `read` rule: Payload's open `read: () => true`
* answers `?draft=true` with the draft; readPublished() (exported) keeps drafts for the editors.
* 24/25 — locales: every locale IAPL configures is public; an unknown `?locale=` is the default locale's text,
* never another locale's draft.
*/
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 { readPublished } from '../src/modules/access/access.js'
import { SECRET_MASK } 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 = 'a-long-test-password-1'
const SMTP = 'S3CRET-smtp-value'
let server: TestServer
let payload: Payload
const tokens: Record<'admin' | 'editor' | 'user', string> = { admin: '', editor: '', user: '' }
let openDraftId: number | string
let guardedDraftId: number | string
let guardedPublishedId: number | string
const api = (pathname: string, as?: keyof typeof tokens, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...(as ? { authorization: `JWT ${tokens[as]}` } : {}) } })
const gql = async (query: string, as?: keyof typeof tokens) =>
(await (await api('/graphql', as, { body: JSON.stringify({ query }), method: 'POST' })).json()) as { data?: Record<string, unknown>; errors?: { message: string }[] }
const pageFields = [
{ name: 'title', type: 'text' as const, localized: true },
{ name: 'secretNote', type: 'text' as const },
]
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
// a project collection with drafts and Payload's open read rule
{ slug: 'open-pages', access: { read: () => true }, fields: pageFields, versions: { drafts: true } },
// the same with the exported rule
{ slug: 'guarded-pages', access: { read: readPublished(), readVersions: readPublished() }, fields: pageFields, versions: { drafts: true } },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iawlb-http-media') } },
],
db: testDatabase('iawlb_http'),
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
globalOverrides: { 'site-integrations': { versions: { drafts: true } } as never },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
twoFactor: false,
}),
],
secret: 'iawl-ideas-b-http-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
for (const role of ['admin', 'editor', 'user'] as const) {
await payload.create({ collection: 'users' as never, data: { email: `${role}@example.com`, password: PASSWORD, roles: [role] } as never })
const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: `${role}@example.com`, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }
tokens[role] = login.token
}
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' } as never })
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp2.example.com', smtpPassword: `${SMTP}-2` } as never })
const draft = { _status: 'draft', secretNote: 'draft only', title: 'Nowy cennik (szkic)' }
openDraftId = (await payload.create({ collection: 'open-pages' as never, data: draft as never, draft: true, locale: 'pl' })).id
guardedDraftId = (await payload.create({ collection: 'guarded-pages' as never, data: draft as never, draft: true, locale: 'pl' })).id
guardedPublishedId = (await payload.create({ collection: 'guarded-pages' as never, data: { _status: 'published', secretNote: 'v1', title: 'Cennik' } as never, locale: 'pl' })).id
await payload.update({ id: guardedPublishedId, collection: 'guarded-pages' as never, data: { _status: 'published', title: 'Prices' } as never, locale: 'en' })
// a newer draft on top of the published page
await payload.update({ id: guardedPublishedId, collection: 'guarded-pages' as never, data: { _status: 'draft', title: 'Cennik — szkic podwyżki' } as never, draft: true, locale: 'pl' })
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
describe('ideas 22/37: versions of Site integrations', () => {
test.each(['user', 'editor'] as const)('a %s account cannot list them (REST)', async (as) => {
expect((await api('/globals/site-integrations/versions', as)).status).toBe(403)
})
test('an anonymous visitor cannot list them (REST)', async () => {
expect((await api('/globals/site-integrations/versions')).status).toBe(403)
})
test.each(['user', 'editor'] as const)('a %s account gets nothing over GraphQL', async (as) => {
const res = await gql('{ versionsSiteIntegrations { docs { id version { smtpHost smtpUser } } } }', as)
expect(JSON.stringify(res.data ?? {})).not.toContain('smtp')
expect(res.errors?.length).toBeGreaterThan(0)
})
test('an admin lists them, with every stored secret masked', async () => {
const res = await api('/globals/site-integrations/versions?depth=0&limit=50', 'admin')
expect(res.status).toBe(200)
const body = JSON.stringify(await res.json())
expect(body).toContain('smtp2.example.com')
expect(body).not.toContain(SMTP)
expect(body).toContain(SECRET_MASK)
})
})
describe('idea 23: drafts over REST and GraphQL', () => {
test("Payload's open read rule answers ?draft=true with the draft (the project's rule, shown for the record)", async () => {
const res = (await (await api(`/open-pages/${openDraftId}?draft=true`)).json()) as { secretNote?: string }
expect(res.secretNote).toBe('draft only')
})
test('readPublished(): a never-published page is not found for a visitor, by id, list, draft=true or GraphQL', async () => {
expect((await api(`/guarded-pages/${guardedDraftId}`)).status).toBe(404)
expect((await api(`/guarded-pages/${guardedDraftId}?draft=true`)).status).toBe(404)
const list = (await (await api('/guarded-pages?draft=true&limit=50')).json()) as { docs: { id: unknown }[] }
expect(list.docs.map((d) => d.id)).not.toContain(guardedDraftId)
const res = await gql(`{ GuardedPages(draft: true, limit: 50) { docs { id title } } }`)
expect(JSON.stringify(res.data)).not.toContain('szkic')
})
test('readPublished(): a published page shows its published text, never the newer draft', async () => {
const res = (await (await api(`/guarded-pages/${guardedPublishedId}?locale=pl`)).json()) as { title?: string }
expect(res.title).toBe('Cennik')
// asking for the draft: Payload applies the rule to the newest version, which is a draft — not found, no text
const asked = await api(`/guarded-pages/${guardedPublishedId}?draft=true&locale=pl`)
expect(asked.status).toBe(404)
expect(await asked.text()).not.toContain('szkic')
// the version list: a visitor sees published versions only
expect(await (await api('/guarded-pages/versions?limit=50')).text()).not.toContain('szkic')
})
test('readPublished(): an editor still sees the draft', async () => {
const res = (await (await api(`/guarded-pages/${guardedPublishedId}?draft=true&locale=pl`, 'editor')).json()) as { title?: string }
expect(res.title).toBe('Cennik — szkic podwyżki')
expect((await api(`/guarded-pages/${guardedDraftId}`, 'editor')).status).toBe(200)
})
test('readPublished(): a plain user account is a visitor', async () => {
expect((await api(`/guarded-pages/${guardedDraftId}`, 'user')).status).toBe(404)
})
})
describe('ideas 24/25: locales', () => {
test('every configured locale is public; locale=all gives the published text of each', async () => {
const res = (await (await api(`/guarded-pages/${guardedPublishedId}?locale=all`)).json()) as { title?: Record<string, string> }
expect(res.title).toEqual({ en: 'Prices', pl: 'Cennik' })
})
test('an unknown ?locale= and ?fallback-locale= give the default locale, never a draft', async () => {
for (const q of ['locale=xx', 'locale=xx&fallback-locale=en', 'locale=en&fallback-locale=xx']) {
const res = (await (await api(`/guarded-pages/${guardedPublishedId}?${q}`)).json()) as { title?: string }
expect(['Cennik', 'Prices']).toContain(res.title)
expect(await (await api(`/guarded-pages/${guardedPublishedId}?${q}&draft=true`)).text()).not.toContain('szkic')
}
})
})
+32
View File
@@ -49,3 +49,35 @@ describe('RenderRichText', () => {
expect(raw).toContain('href="data:text/html')
})
})
/**
* One rule, one function (IAWL idea 19): an `autolink` marked `linkType: 'internal'` is rendered by Payload from
* `fields.url` all the same, and the Markdown output (llms / `.md` routes) prints link URLs too — both must pass
* the same safeHref check as <CMSLink> and the plain link.
*/
describe('a second way to write the same link', () => {
const bad = 'data:text/html,<script>alert(1)</script>'
test('an autolink marked internal is neutralised like any other', () => {
expect(urls(sanitizeRichTextLinks(doc(link(bad, 'autolink', 'internal'))))).toEqual(['#'])
})
test('a link marked internal loses an unsafe stored url too (Payload renders its own href)', () => {
expect(urls(sanitizeRichTextLinks(doc(link(bad, 'link', 'internal'))))).toEqual(['#'])
})
test('RenderRichText never prints the unsafe URL of an internal autolink', async () => {
const { renderToStaticMarkup } = await import('react-dom/server')
const { createElement } = await import('react')
const { RenderRichText } = await import('../src/modules/richtext/RenderRichText.js')
const html = renderToStaticMarkup(createElement(RenderRichText, { data: doc(link(bad, 'autolink', 'internal')) as never }))
expect(html).not.toContain('data:')
})
test('the Markdown output drops an unsafe link target and keeps the label', async () => {
const { lexicalToMarkdown } = await import('../src/modules/richtext/lexicalToMarkdown.js')
const md = lexicalToMarkdown(doc(link('javascript:alert(1)'), link(bad, 'autolink'), link('https://acme.pl')) as never)
expect(md).not.toMatch(/javascript:|data:/)
expect(md).toContain('[x](https://acme.pl)')
})
})
+197
View File
@@ -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<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')
})
})