From e9f9947eb718e75757dd84afe039f0c4115af798 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 16:56:09 +0100 Subject: [PATCH] Security audit fixes for 1.18.0: Markdown negotiation private + Vary: Accept (F3), public lists capped (F4), operator sort names refused (F5), CSP report log normalised and capped (F1), buildUrlField and the reference socials (F2), document locks for staff only Co-Authored-By: Claude Opus 5.5 --- reference/e2e/closed-doors.ts | 5 +- reference/src/components/layout/Footer.tsx | 15 +- reference/src/globals/Company.ts | 5 +- reference/src/lib/content.ts | 4 +- src/index.ts | 23 ++- src/modules/content/createMarkdownRenderer.ts | 15 +- src/modules/content/index.ts | 2 +- src/modules/content/markdownNegotiation.ts | 18 +++ src/modules/i18n/createProxy.ts | 31 +++- src/modules/links/buildUrlField.ts | 74 +++++++++ src/modules/links/index.ts | 2 + src/modules/security/attackProbes.ts | 9 +- src/modules/security/createCspReportRoute.ts | 85 +++++++++- src/modules/security/index.ts | 2 +- src/modules/security/queryGuard.ts | 136 ++++++++++++++++ src/plugin.ts | 6 + src/types.ts | 25 +++ test/queryGuardHttp.test.ts | 112 +++++++++++++ test/securityClasses.test.ts | 149 ++++++++++++++++-- test/visitorWrites.test.ts | 8 + 20 files changed, 677 insertions(+), 49 deletions(-) create mode 100644 src/modules/links/buildUrlField.ts create mode 100644 src/modules/security/queryGuard.ts create mode 100644 test/queryGuardHttp.test.ts diff --git a/reference/e2e/closed-doors.ts b/reference/e2e/closed-doors.ts index beb16f6..c97d3d8 100644 --- a/reference/e2e/closed-doors.ts +++ b/reference/e2e/closed-doors.ts @@ -114,9 +114,8 @@ export const DOORS: Door[] = [ { closedFor: ['anonymous'], name: 'who edits what (Payload\'s document locks, with the editor\'s account)', - // Payload's own collection: the plugin-wide default for it is the owner's Q3 answer (a), recorded for 2.0; the doctor's - // `visitor-writes` rule lists it on a site with a visitor login collection - openFor: { callers: ['customer'], question: 'Q3 (a), 2.0: payload-locked-documents runs on Payload\'s default (any signed-in account)' }, + // Payload's own collection: staff only since 1.18.0 (iapl `lockedDocuments`, the owner's Q3 answer (a)); Payload's + // default let any signed-in account in path: '/api/payload-locked-documents', closed: forbidden, }, diff --git a/reference/src/components/layout/Footer.tsx b/reference/src/components/layout/Footer.tsx index 727a3ee..42e0ae1 100644 --- a/reference/src/components/layout/Footer.tsx +++ b/reference/src/components/layout/Footer.tsx @@ -1,4 +1,5 @@ import { Container } from '@intecion/ipal-kit/blocks/rsc' +import { safeHref } from '@intecion/ipal-kit' import { NoSnippet } from '@intecion/ipal-kit/rsc' import Link from 'next/link' @@ -47,11 +48,15 @@ export async function Footer({ company, footer, locale }: Props) { {link.label} ))} - {(company.socials ?? []).map((s) => ( -
  • - {s.label} -
  • - ))} + {(company.socials ?? []).flatMap((s) => { + // the field validates; the render checks again (an import or an older version may hold anything) + const href = safeHref(s.url) + return href ? [ +
  • + {s.label} +
  • , + ] : [] + })} diff --git a/reference/src/globals/Company.ts b/reference/src/globals/Company.ts index 0846158..4b46e18 100644 --- a/reference/src/globals/Company.ts +++ b/reference/src/globals/Company.ts @@ -1,6 +1,6 @@ import type { GlobalConfig } from 'payload' -import { adminOrEditor, buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit' +import { adminOrEditor, buildGlobalRevalidateHook, buildUrlField, rowLabel } from '@intecion/ipal-kit' import { revalidatePath } from 'next/cache' /** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */ @@ -33,7 +33,8 @@ export const Company: GlobalConfig = { labels: { plural: 'Profiles', singular: 'Profile' }, fields: [ { name: 'label', type: 'text', required: true }, - { name: 'url', type: 'text', required: true }, + // rendered into href: https:// only, never javascript: or data: (security.md "Addresses rendered into href") + buildUrlField({ required: true }), ], }, ], diff --git a/reference/src/lib/content.ts b/reference/src/lib/content.ts index 4bf7ee4..55fad32 100644 --- a/reference/src/lib/content.ts +++ b/reference/src/lib/content.ts @@ -1,6 +1,6 @@ import { faqItemsFromLayout } from '@intecion/ipal-kit/blocks' // @starter:if localBusiness -import { buildLocalBusinessJsonLd, createContentHelpers } from '@intecion/ipal-kit' +import { buildLocalBusinessJsonLd, createContentHelpers, isAllowedUrl } from '@intecion/ipal-kit' import { contentConfig } from '@/content.config' import { i18nConfig } from '@/i18n.config' @@ -72,7 +72,7 @@ export const { address: { city: company.address?.city ?? undefined, country: company.address?.country ?? 'PL', postalCode: company.address?.postalCode ?? undefined, street: company.address?.street ?? undefined }, name: company.name, openingHours: company.hours ?? undefined, - sameAs: (company.socials ?? []).map((s) => s.url), + sameAs: (company.socials ?? []).map((s) => s.url).filter((url) => isAllowedUrl(url)), telephone: company.phone ?? undefined, type: 'ProfessionalService', url: baseUrl, diff --git a/src/index.ts b/src/index.ts index 3980912..4f2752a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -241,6 +241,7 @@ export { pathOf } from './modules/construction/visibility.js' export type { PathVisibility } from './modules/construction/visibility.js' export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js' export { + appendVary, applyDraftRelations, archiveFieldName, blocksToMarkdown, @@ -253,9 +254,11 @@ export { isSiteLocale, limitQuery, listContent, + MARKDOWN_NEGOTIATED_HEADER, MARKDOWN_PREFIX, markdownHref, markdownResponse, + NEGOTIATED_CACHE_CONTROL, parsePageParam, prefersMarkdown, resolveNotFoundPage, @@ -420,7 +423,8 @@ export type { IntegrationBannerTexts, IntegrationLabel, IntegrationState, Integr // Image lightbox — pure helpers (components live in /client). export { formatLightboxCounter, LIGHTBOX_FALLBACK, LIGHTBOX_FALLBACK_PL, lightboxFallback, lightboxImage, lightboxIndex, resolveLightboxTexts } from './modules/lightbox/index.js' export type { LightboxClassNames, LightboxImage, LightboxImageOptions, LightboxRenderImage, LightboxTexts } from './modules/lightbox/index.js' -export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js' +export { buildLinkField, buildLinksField, buildUrlField, homeSlugFrom, isAllowedUrl, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js' +export type { BuildUrlFieldOptions, UrlScheme } from './modules/links/index.js' export type { BuildLinkFieldOptions, BuildLinksFieldOptions, @@ -493,8 +497,10 @@ export { COLOR_SCHEME_CLIENT_HINT, createCspNonce, createCspReportRoute, + CSP_LOG_VALUE_MAX, CSP_NONCE_HEADER, cspHeaderKey, + cspLogLine, DEFAULT_CSP_REPORT_GROUP, parseCspReports, scopeColorSchemeClientHints, @@ -518,6 +524,21 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit // Payload's job queue over HTTP: an admin with the second factor or Bearer CRON_SECRET (security.md "Payload's job queue") export { CRON_SECRET_ENV, CRON_SECRET_MIN_LENGTH, cronSecretMatches, jobsRunAccess, jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js' export type { JobsRunAccessOptions } from './modules/security/jobsAccess.js' +// Lists from outside (security.md "Lists and sorting"): page size capped for non-staff, operator sort names refused, +// Payload's document locks for staff only. +export { + applyLockedDocumentsAccess, + applyQueryGuard, + buildQueryGuardHook, + capListLimit, + DEFAULT_LIST_LIMIT, + isOperatorSort, + isStaffRequest, + LOCKED_DOCUMENTS_SLUG, + RefusedSortError, + staffOnlyLocks, +} from './modules/security/queryGuard.js' +export type { ListLimitOptions, LockedDocumentsAccess } from './modules/security/queryGuard.js' // The doors a built config opens (REST, GraphQL, Next route files) and the judged snapshot they are checked against. export { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from './modules/security/routeInventory.js' export type { GraphqlSchemaLike, RouteInventoryOptions, RouteSnapshot, RouteSnapshotDiff } from './modules/security/routeInventory.js' diff --git a/src/modules/content/createMarkdownRenderer.ts b/src/modules/content/createMarkdownRenderer.ts index f3f044e..78ea349 100644 --- a/src/modules/content/createMarkdownRenderer.ts +++ b/src/modules/content/createMarkdownRenderer.ts @@ -4,6 +4,7 @@ import type { PathVisibility } from '../construction/visibility.js' import type { ContentOption } from './types.js' import { blocksToMarkdown } from './blocksToMarkdown.js' +import { MARKDOWN_NEGOTIATED_HEADER, NEGOTIATED_CACHE_CONTROL } from './markdownNegotiation.js' import { resolveRoute } from './resolveRoute.js' type CreateMarkdownRendererArgs = { @@ -126,9 +127,11 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) { * Wraps a Markdown string in a `text/markdown` Response, or a 404 when null. * Uses the global Response — no next/server import. */ -export function markdownResponse(md: null | string, options: { canonical?: string } = {}): Response { +export function markdownResponse(md: null | string, options: { canonical?: string; negotiated?: boolean } = {}): Response { + // Negotiated at an HTML URL (the proxy's marker): never stored by a shared cache as that page (audit F3). + const negotiatedHeaders: Record = options.negotiated ? { 'cache-control': NEGOTIATED_CACHE_CONTROL, vary: 'Accept' } : {} if (md == null) { - return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 }) + return new Response('Not found', { headers: { 'content-type': 'text/plain', ...negotiatedHeaders }, status: 404 }) } return new Response(md, { headers: { @@ -138,6 +141,7 @@ export function markdownResponse(md: null | string, options: { canonical?: strin // index it as a duplicate — and should credit the HTML page instead. 'x-robots-tag': 'noindex', ...(options.canonical ? { link: `<${options.canonical}>; rel="canonical"` } : {}), + ...negotiatedHeaders, }, status: 200, }) @@ -197,16 +201,17 @@ export function createMarkdownRoute( const { getCachedPayload, isPathVisible, ...rendererArgs } = args const render = createMarkdownRenderer(rendererArgs) return { - GET: async (_req, { params }) => { + GET: async (req, { params }) => { + const negotiated = req.headers?.get(MARKDOWN_NEGOTIATED_HEADER) === '1' try { const { slug, locale } = routeOf(await params, rendererArgs.config) if (isPathVisible) { const multilingual = (rendererArgs.config?.locales.length ?? 0) > 1 const path = `/${[...(multilingual ? [locale] : []), ...(slug ?? [])].join('/')}` - if (!(await isPathVisible(path, locale))) {return markdownResponse(null, {})} + if (!(await isPathVisible(path, locale))) {return markdownResponse(null, { negotiated })} } const md = await render({ slug, locale, payload: await getCachedPayload() }) - return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) }) + return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug), negotiated }) } catch (err) { console.warn('[iapl] createMarkdownRoute: render failed:', err) return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 }) diff --git a/src/modules/content/index.ts b/src/modules/content/index.ts index 9ffa45f..db924d9 100644 --- a/src/modules/content/index.ts +++ b/src/modules/content/index.ts @@ -5,7 +5,7 @@ export { createSearchRoute } from './createSearchRoute.js' export { applyDraftRelations, type DraftRelations, withoutDraftRelations } from './draftRelations.js' export { getArchiveEntries } from './getArchiveEntries.js' export type { ArchiveEntries } from './getArchiveEntries.js' -export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js' +export { appendVary, MARKDOWN_NEGOTIATED_HEADER, MARKDOWN_PREFIX, markdownHref, NEGOTIATED_CACHE_CONTROL, prefersMarkdown } from './markdownNegotiation.js' export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js' export { resolveNotFoundPage } from './resolveNotFoundPage.js' export { resolveRedirect } from './resolveRedirect.js' diff --git a/src/modules/content/markdownNegotiation.ts b/src/modules/content/markdownNegotiation.ts index 232913b..83dbe0f 100644 --- a/src/modules/content/markdownNegotiation.ts +++ b/src/modules/content/markdownNegotiation.ts @@ -13,6 +13,24 @@ /** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */ export const MARKDOWN_PREFIX = '/md' +/** + * Request header the proxy sets when it rewrites an HTML URL to the Markdown route (content negotiation). The route + * then answers {@link NEGOTIATED_CACHE_CONTROL} with `Vary: Accept`: the answer shares the page's URL, so no shared + * cache may store it (security audit 2026-12, F3). A client sending it itself only makes its own answer private. + */ +export const MARKDOWN_NEGOTIATED_HEADER = 'x-iapl-markdown-negotiated' + +/** Cache-Control of a Markdown answer given at an HTML URL. */ +export const NEGOTIATED_CACHE_CONTROL = 'private, no-store' + +/** Adds a token to `Vary` once (case-insensitive), keeping what is there. */ +export function appendVary(headers: Headers | undefined, token: string): void { + if (!headers) {return} + const current = (headers.get('vary') ?? '').split(',').map((v) => v.trim()).filter(Boolean) + if (current.some((v) => v === '*' || v.toLowerCase() === token.toLowerCase())) {return} + headers.set('vary', [...current, token].join(', ')) +} + /** * The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so * the discovery link and the route agree. diff --git a/src/modules/i18n/createProxy.ts b/src/modules/i18n/createProxy.ts index 72e6f4d..e1f45e4 100644 --- a/src/modules/i18n/createProxy.ts +++ b/src/modules/i18n/createProxy.ts @@ -1,7 +1,7 @@ import type { BuildCspArgs } from '../security/buildCsp.js' import type { I18nConfig } from './types.js' -import { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from '../content/markdownNegotiation.js' +import { appendVary, MARKDOWN_NEGOTIATED_HEADER, MARKDOWN_PREFIX, markdownHref, NEGOTIATED_CACHE_CONTROL, prefersMarkdown } from '../content/markdownNegotiation.js' import { buildCsp, buildReportingEndpoints } from '../security/buildCsp.js' import { createCspNonce, CSP_NONCE_HEADER } from '../security/cspNonce.js' import { isValidLocale } from './helpers.js' @@ -38,7 +38,7 @@ type NextResponseLike = { next: (init?: { request?: { headers: Headers } }) => ProxyResponse redirect: (url: string | URL) => ProxyResponse /** Needed for `markdown` content negotiation; Next's NextResponse has it. */ - rewrite?: (url: string | URL) => ProxyResponse + rewrite?: (url: string | URL, init?: { request?: { headers: Headers } }) => ProxyResponse } type CreateProxyOptions = { @@ -62,8 +62,13 @@ type CreateProxyOptions = { * sets another one. Paths under the prefix pass through untouched (no locale * redirect — /md/pl/o-nas must not become /pl/md/pl/o-nas), and a page * requested with `Accept: text/markdown` is rewritten to its Markdown version. + * + * The negotiated answer shares the page's URL, so it is sent `private, no-store` with `Vary: Accept` (and the + * pages under the matcher get `Vary: Accept`): a cache in front never stores the Markdown as the page (security + * audit 2026-12, F3). `/md/…` itself keeps its public caching. The object form adapts it: + * `{ prefix?: string, negotiate?: boolean }` — `negotiate: false` serves Markdown only at `/md/…`. */ - markdown?: boolean | string + markdown?: { negotiate?: boolean; prefix?: string } | boolean | string /** Consent policy version to require for saving the locale cookie (createLocaleMiddleware). */ policyVersion?: number } @@ -89,7 +94,11 @@ export function createProxy( ): (request: ProxyRequest) => ProxyResponse { const { csp, exposeHeaders = true, markdown, NextResponse, ...mwOptions } = deps const run = createLocaleMiddleware({ config, ...mwOptions }) - const mdPrefix = markdown ? (typeof markdown === 'string' ? markdown : MARKDOWN_PREFIX).replace(/\/$/, '') : null + const mdOptions = typeof markdown === 'object' && markdown ? markdown : {} + const mdPrefix = markdown + ? (typeof markdown === 'string' ? markdown : (mdOptions.prefix ?? MARKDOWN_PREFIX)).replace(/\/$/, '') + : null + const negotiate = Boolean(mdPrefix) && mdOptions.negotiate !== false return (request: ProxyRequest): ProxyResponse => { const { pathname } = request.nextUrl @@ -99,8 +108,15 @@ export function createProxy( // Markdown route; the rest gets the locale redirect first, then negotiates. const seg = pathname.split('/').filter(Boolean)[0] ?? '' const routable = config.locales.length === 1 || isValidLocale(seg, config) - if (routable && NextResponse.rewrite && prefersMarkdown(request.headers)) { - return NextResponse.rewrite(new URL(markdownHref(pathname, mdPrefix), request.url)) + if (negotiate && routable && NextResponse.rewrite && prefersMarkdown(request.headers)) { + // The route reads the marker and answers private + Vary: Accept; the same headers on the rewrite itself + // for a route that is not the plugin's (security audit 2026-12, F3). + const mdHeaders = new Headers(request.headers) + mdHeaders.set(MARKDOWN_NEGOTIATED_HEADER, '1') + const rewritten = NextResponse.rewrite(new URL(markdownHref(pathname, mdPrefix), request.url), { request: { headers: mdHeaders } }) + rewritten.headers?.set('cache-control', NEGOTIATED_CACHE_CONTROL) + appendVary(rewritten.headers, 'Accept') + return rewritten } } @@ -133,6 +149,9 @@ export function createProxy( } } + // The same URL answers HTML or (negotiated) Markdown: say so to any cache in front. + if (negotiate && result.type !== 'redirect') {appendVary(response.headers, 'Accept')} + if (result.cookie) { response.cookies.set(result.cookie.name, result.cookie.value, { path: '/', diff --git a/src/modules/links/buildUrlField.ts b/src/modules/links/buildUrlField.ts new file mode 100644 index 0000000..113a16c --- /dev/null +++ b/src/modules/links/buildUrlField.ts @@ -0,0 +1,74 @@ +import type { TextField } from 'payload' + +import type { AdminText } from '../admin-i18n/define.js' + +import { safeHref } from './resolveLinkHref.js' + +/** Schemes {@link buildUrlField} may allow besides `https:` / `http:`. */ +export type UrlScheme = 'hash' | 'mailto' | 'relative' | 'sms' | 'tel' + +export type BuildUrlFieldOptions = { + /** Help under the field. Default: what the field accepts. */ + description?: AdminText | string + /** Panel label. Default "Address". */ + label?: AdminText | string + /** Field name. Default `url`. */ + name?: string + /** Anything else of Payload's text field (admin, access, hooks, localized…); wins over the defaults. */ + overrides?: Partial> + required?: boolean + /** + * Besides `https://` and `http://`: `mailto:`, `tel:`, `sms:`, `#section`, `/a/path` on this site. + * Default none — a profile or a website. `javascript:`, `data:`, `vbscript:` and `//host` never pass. + */ + schemes?: readonly UrlScheme[] +} + +const ALLOWED: Record = { + hash: /^#/, + mailto: /^mailto:/i, + relative: /^\/(?!\/)/, + sms: /^sms:/i, + tel: /^tel:/i, +} + +/** True when `value` is an address the field accepts: safe as an `href` ({@link safeHref}) and of an allowed kind. */ +export function isAllowedUrl(value: null | string | undefined, schemes: readonly UrlScheme[] = []): boolean { + const safe = safeHref(value) + if (!safe) {return false} + if (/^https?:\/\/[^\s/?#]+/i.test(safe)) {return true} + return schemes.some((s) => ALLOWED[s].test(safe)) +} + +/** + * A text field for an address that is rendered into `href` (a profile, a website, a map link): it accepts + * `https://…` (and the schemes you list) and refuses `javascript:`, `data:` and other addresses that would run script + * when clicked (security audit 2026-12, F2). Render the stored value with `safeHref()` as well: data can come from an + * import, a seed or an older version. + * + * fields: [{ name: 'label', type: 'text' }, buildUrlField({ required: true })] + */ +export function buildUrlField(options: BuildUrlFieldOptions = {}): TextField { + const { name = 'url', description, label, overrides = {}, required, schemes = [] } = options + const { admin, ...rest } = overrides + const pl = (req?: { i18n?: { language?: string } }) => req?.i18n?.language === 'pl' + return { + name, + type: 'text', + label: label ?? { en: 'Address', pl: 'Adres' }, + required, + validate: (v: null | string | undefined, { req }: { req?: { i18n?: { language?: string } } } = {}) => { + if (!v) {return required ? (pl(req) ? 'To pole jest wymagane.' : 'This field is required.') : true} + return isAllowedUrl(v, schemes) || (pl(req) ? 'Wpisz pełny adres, np. https://example.com.' : 'Enter a full address, e.g. https://example.com.') + }, + ...rest, + admin: { + description: + description ?? + (schemes.length + ? { en: 'A full address (https://…) or one of the other kinds this field allows.', pl: 'Pełny adres (https://…) albo inny rodzaj, na który pozwala to pole.' } + : { en: 'A full address, e.g. https://example.com', pl: 'Pełny adres, np. https://example.com' }), + ...admin, + }, + } as TextField +} diff --git a/src/modules/links/index.ts b/src/modules/links/index.ts index 922b2cd..598cc67 100644 --- a/src/modules/links/index.ts +++ b/src/modules/links/index.ts @@ -1,5 +1,7 @@ export { buildLinkField, buildLinksField } from './buildLinkField.js' export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance, LinkAppearanceOption } from './buildLinkField.js' +export { buildUrlField, isAllowedUrl } from './buildUrlField.js' +export type { BuildUrlFieldOptions, UrlScheme } from './buildUrlField.js' export { resolveLinkHref, safeHref } from './resolveLinkHref.js' export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js' export { homeSlugFrom, resolveLink, resolveNav, resolveSystemLinks } from './resolveNav.js' diff --git a/src/modules/security/attackProbes.ts b/src/modules/security/attackProbes.ts index be6d6da..5bbbe97 100644 --- a/src/modules/security/attackProbes.ts +++ b/src/modules/security/attackProbes.ts @@ -161,7 +161,6 @@ export const ATTACK_PROBES: AttackProbe[] = [ { id: 'markdown-vary', class: 'cache poisoning (content negotiation)', - finding: 'F3', live: true, run: async ({ fetch, page = '/' }) => { const a = await fetch(page, { follow: true, headers: { accept: 'text/markdown' } }) @@ -169,7 +168,7 @@ export const ATTACK_PROBES: AttackProbe[] = [ const cc = a.headers.get('cache-control') ?? '' const shared = /s-maxage|public/.test(cc) && !/private|no-store/.test(cc) const vary = (a.headers.get('vary') ?? '').split(',').map((v) => v.trim().toLowerCase()) - if (shared && !vary.includes('accept') && !vary.includes('*')) {return bad(`${page} answers Markdown to Accept: text/markdown with "${cc}" and no Vary: Accept: a shared cache stores it under the HTML URL`)} + if (shared && !vary.includes('accept') && !vary.includes('*')) {return bad(`${page} answers Markdown to Accept: text/markdown with "${cc}" and no Vary: Accept: a shared cache stores it under the HTML URL (IAPL 1.18.0's createProxy sends private + Vary: Accept; a proxy of your own must too)`)} return ok('the Markdown answer at the HTML URL varies by Accept or is not shared') }, title: 'the Markdown copy at an HTML URL cannot be cached as the page', @@ -260,7 +259,6 @@ export const ATTACK_PROBES: AttackProbe[] = [ { id: 'sort-operator', class: 'injection (operators in sort)', - finding: 'F5', live: true, run: async ({ fetch }) => { const problems: string[] = [] @@ -268,14 +266,13 @@ export const ATTACK_PROBES: AttackProbe[] = [ const a = await fetch(`/api/pages?sort=${sort}&limit=1&depth=0`) if (a.status >= 500 || LEAK.test(a.text)) {problems.push(`sort=${decodeURIComponent(sort)} → ${a.status}`)} } - return problems.length ? bad(`${problems.join('; ')}: an operator name reaches the database as a sort field (an error and a logged stack trace per request)`) : ok('operator names in sort are refused with a 4xx') + return problems.length ? bad(`${problems.join('; ')}: an operator name reaches the database as a sort field (an error and a logged stack trace per request; IAPL 1.18.0 refuses it unless refuseOperatorSort is false)`) : ok('operator names in sort are refused with a 4xx') }, title: 'an operator name in ?sort= is refused, not passed to the database', }, { id: 'unbounded-list', class: 'denial of service (unbounded queries)', - finding: 'F4', live: true, run: async ({ fetch }) => { const a = await fetch('/api/pages?limit=100000&depth=50') @@ -286,7 +283,7 @@ export const ATTACK_PROBES: AttackProbe[] = [ } catch { return skip('not JSON') } - return (body.limit ?? 0) > 1000 ? bad(`/api/pages?limit=100000 is honoured (limit ${body.limit}, ${a.ms} ms, ${a.text.length} bytes): one anonymous request reads a whole collection`) : ok(`limit capped at ${body.limit}`) + return (body.limit ?? 0) > 1000 ? bad(`/api/pages?limit=100000 is honoured (limit ${body.limit}, ${a.ms} ms, ${a.text.length} bytes): one anonymous request reads a whole collection (IAPL 1.18.0 caps it unless listLimit is false or the collection is excluded)`) : ok(`limit capped at ${body.limit}`) }, title: 'a public list caps limit (and depth) so one request cannot read a whole collection', }, diff --git a/src/modules/security/createCspReportRoute.ts b/src/modules/security/createCspReportRoute.ts index 64d83d8..562d17a 100644 --- a/src/modules/security/createCspReportRoute.ts +++ b/src/modules/security/createCspReportRoute.ts @@ -1,3 +1,4 @@ +import { clientIp, consumeRateLimit } from '../shared/rateLimit.js' import { readCappedBody } from '../shared/readCappedBody.js' /** One CSP violation, normalised from either report format. */ @@ -15,12 +16,79 @@ export type CspViolation = { export type CreateCspReportRouteArgs = { /** Largest accepted body in bytes; bigger requests get 413. Default 16 KB. */ maxBytes?: number + /** Most violations handled from one request (a body may hold many). Default 10; the rest are dropped. */ + maxReports?: number /** * What to do with each violation. Default: one `console.warn` line per - * violation (Coolify keeps container logs — read them there). Plug in - * payload.logger, Sentry or a database write here. + * violation (Coolify keeps container logs — read them there), made by + * {@link cspLogLine}: origins and paths only, no control characters, every value + * capped — a report cannot write a line of its own into the log. Your own + * `onReport` gets the values exactly as the browser sent them: escape them + * before you log them. Plug in payload.logger, Sentry or a database write here. */ onReport?: (violation: CspViolation) => Promise | void + /** + * Requests per client (`clientIp`, IPv6 per /64) and window that are handled; over it the route still answers 204 + * and handles nothing. Default `{ max: 60, windowMs: 60_000 }`; `false` = no limit. + */ + rateLimit?: { max?: number; windowMs?: number } | false +} + +/** Longest value {@link cspLogLine} writes. */ +export const CSP_LOG_VALUE_MAX = 128 + +/** Control characters (new lines among them) and the Unicode line separators: never in a log line. */ +// eslint-disable-next-line no-control-regex +const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g + +const clean = (value: string | undefined, max = CSP_LOG_VALUE_MAX): string => { + if (!value) {return '?'} + const text = value.replace(CONTROL, ' ').trim() + return text.length > max ? `${text.slice(0, max)}…` : text || '?' +} + +/** `https://cdn.x/a.js?q` → `https://cdn.x`; a keyword (`inline`, `eval`, `data`) stays as it is. */ +const originOf = (value: string | undefined): string | undefined => { + if (!value) {return undefined} + try { + const url = new URL(value) + return url.origin === 'null' ? `${url.protocol}` : url.origin + } catch { + return value + } +} + +/** `https://site.pl/pl/o-nas?x=1#y` → `/pl/o-nas` (no query: it may hold personal data). */ +const pathOf = (value: string | undefined): string | undefined => { + if (!value) {return undefined} + try { + return new URL(value).pathname + } catch { + return value.split(/[?#]/)[0] + } +} + +/** `https://cdn.x/a.js?q` → `https://cdn.x/a.js`: where the script lives, without its query. */ +const scriptOf = (value: string): string => { + try { + const url = new URL(value) + return url.origin === 'null' ? url.protocol : `${url.origin}${url.pathname}` + } catch { + return value.split(/[?#]/)[0] + } +} + +/** + * The default log line of one violation: the blocked resource's origin, the page's path, the script's origin and path + * with its line — control characters removed, every value at most {@link CSP_LOG_VALUE_MAX} characters (security + * audit 2026-12, F1). Use it in your own `onReport` for the same line. + */ +export function cspLogLine(v: CspViolation): string { + const source = v.sourceFile ? scriptOf(v.sourceFile) : '' + return ( + `[csp] ${clean(v.disposition ?? 'report', 16)} ${clean(v.effectiveDirective, 32)} blocked=${clean(originOf(v.blockedUri))} ` + + `page=${clean(pathOf(v.documentUri))}${source ? ` src=${clean(source)}:${typeof v.lineNumber === 'number' ? v.lineNumber : ''}` : ''}` + ) } type Raw = Record @@ -86,14 +154,19 @@ export function parseCspReports(body: unknown): CspViolation[] { export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (request: Request) => Promise { const { maxBytes = 16 * 1024, + maxReports = 10, onReport = (v: CspViolation) => { - console.warn( - `[csp] ${v.disposition ?? 'report'} ${v.effectiveDirective ?? '?'} blocked=${v.blockedUri ?? '?'} page=${v.documentUri ?? '?'}${v.sourceFile ? ` src=${v.sourceFile}:${v.lineNumber ?? ''}` : ''}`, - ) + console.warn(cspLogLine(v)) }, + rateLimit = {}, } = args return async (request: Request) => { + if (rateLimit) { + const { ok } = await consumeRateLimit({ key: clientIp(request), max: rateLimit.max ?? 60, scope: 'csp-report', windowMs: rateLimit.windowMs ?? 60_000 }) + // the browser does not read the answer: 204 either way, nothing handled + if (!ok) {return new Response(null, { status: 204 })} + } // read only up to the cap, whether or not the browser declared the length (a chunked body has none) let text: null | string try { @@ -110,7 +183,7 @@ export function createCspReportRoute(args: CreateCspReportRouteArgs = {}): (requ return new Response(null, { status: 400 }) } - for (const violation of parseCspReports(body).slice(0, 50)) { + for (const violation of parseCspReports(body).slice(0, Math.max(0, maxReports))) { try { await onReport(violation) } catch { diff --git a/src/modules/security/index.ts b/src/modules/security/index.ts index 48ad412..31b0ad5 100644 --- a/src/modules/security/index.ts +++ b/src/modules/security/index.ts @@ -10,7 +10,7 @@ export { export type { BuildAdminCspArgs, BuildCspArgs, CspDirective, CspSources } from './buildCsp.js' export { buildSecurityHeaders, buildUploadSecurityHeaders, UPLOAD_SECURITY_HEADERS } from './buildSecurityHeaders.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './buildSecurityHeaders.js' -export { createCspReportRoute, parseCspReports } from './createCspReportRoute.js' +export { createCspReportRoute, CSP_LOG_VALUE_MAX, cspLogLine, parseCspReports } from './createCspReportRoute.js' export type { CreateCspReportRouteArgs, CspViolation } from './createCspReportRoute.js' export { createCspNonce, CSP_NONCE_HEADER } from './cspNonce.js' export { totpAdminPath, totpRedirectTarget } from './totp/totpRedirect.js' diff --git a/src/modules/security/queryGuard.ts b/src/modules/security/queryGuard.ts new file mode 100644 index 0000000..7074a6f --- /dev/null +++ b/src/modules/security/queryGuard.ts @@ -0,0 +1,136 @@ +import type { Access, CollectionBeforeOperationHook, CollectionConfig, Config, PayloadRequest, SanitizedConfig } from 'payload' + +import { APIError } from 'payload' + +import { staffCollectionSlugs } from '../access/predicates.js' +import { secondFactorPassed } from './totp/secondFactor.js' + +/** + * Guards for what a REST / GraphQL caller may ask of a collection list (security audit 2026-12, F4 and F5), and + * Payload's document locks closed to visitor accounts (the "document locks" door). Each is on by default, each can be + * turned off or adapted, and every piece is exported for a project's own use (docs/security.md "Lists and sorting"). + * + * Local API calls (`req.payloadAPI === 'local'`: the frontend, seeds, the project's own code) are never touched. + */ + +export type ListLimitOptions = { + /** Collections left as Payload has them (their lists take any `limit`). */ + exclude?: string[] + /** Largest page a caller that is not staff gets. Default 100. */ + max?: number + /** Cap staff accounts too (the panel asks for at most 100 per page itself). Default false. */ + staff?: boolean +} + +export const DEFAULT_LIST_LIMIT = 100 + +type HookArgs = Parameters[0] +type ListArgs = { id?: unknown; limit?: number | string; pagination?: boolean | string; sort?: unknown } + +const fromOutside = (req: PayloadRequest | undefined): boolean => + Boolean(req) && (req as { payloadAPI?: string }).payloadAPI !== 'local' + +/** True when the request's account belongs to a staff collection (any role). */ +export function isStaffRequest(req: Pick | undefined): boolean { + const slug = (req?.user as { collection?: unknown } | null | undefined)?.collection + return typeof slug === 'string' && staffCollectionSlugs(req?.payload).includes(slug) +} + +/** + * The list arguments with `limit` at most `max` and pagination on — what a caller that is not staff gets. Pure: the + * hook below calls it, a project's own endpoint can too. + */ +export function capListLimit(args: T, max: number = DEFAULT_LIST_LIMIT): T { + // REST hands the query string over as text: '100000', 'false' + const raw = typeof args.limit === 'string' && (args.limit).trim() !== '' ? Number(args.limit) : args.limit + const limit = typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined + const noPages = args.pagination === false || (args.pagination as unknown) === 'false' + // pagination: false and limit 0 both mean "everything" to Payload + if (noPages || limit === 0 || (limit !== undefined && limit > max)) { + return { ...args, limit: limit && limit > 0 ? Math.min(limit, max) : max, pagination: true } + } + return args +} + +/** A sort field that names a database operator (`$where`, `-$natural`, `title.$ne`): never a field of a document. */ +export function isOperatorSort(sort: unknown): boolean { + const names = Array.isArray(sort) ? sort : typeof sort === 'string' ? sort.split(',') : [] + return names.some((n) => typeof n === 'string' && /(?:^-?|\.)\$/.test(n.trim())) +} + +/** + * The 400 for an operator sort name. Its own name so Payload logs it as one `info` line without a stack (the plugin + * sets `loggingLevels.RefusedSortError: 'info'` unless the project set it; `false` logs nothing). + */ +export class RefusedSortError extends APIError { + constructor() { + super('This sort field is not allowed.', 400, null, true) + this.name = 'RefusedSortError' + } +} + +const LIST_OPERATIONS = new Set(['findVersions', 'read', 'readDistinct']) + +/** + * One `beforeOperation` hook for lists from outside: refuses a database operator as a sort field with 400 (instead of + * a 500 and a logged stack trace, F5) and caps `limit` for callers that are not staff (F4). `listLimit: false` or + * `refuseOperatorSort: false` turns that half off. + */ +export function buildQueryGuardHook(options: { + listLimit?: false | ListLimitOptions + refuseOperatorSort?: boolean +}): CollectionBeforeOperationHook { + const limit = options.listLimit === false ? null : { max: DEFAULT_LIST_LIMIT, staff: false, ...options.listLimit } + const refuseSort = options.refuseOperatorSort !== false + return (({ args, collection, operation, req }: HookArgs) => { + if (!LIST_OPERATIONS.has(operation) || !fromOutside(req)) {return args} + const list = args as ListArgs + if (refuseSort && isOperatorSort(list.sort)) { + throw new RefusedSortError() + } + if (!limit || list.id != null || limit.exclude?.includes(collection.slug)) {return args} + if (!limit.staff && isStaffRequest(req)) {return args} + return capListLimit(list, limit.max) + }) as CollectionBeforeOperationHook +} + +/** The hook added to every collection of the config (the project's, the plugin's, other plugins' before iapl). */ +export function applyQueryGuard( + config: Config, + options: { listLimit?: false | ListLimitOptions; refuseOperatorSort?: boolean }, +): Config { + if (options.listLimit === false && options.refuseOperatorSort === false) {return config} + const hook = buildQueryGuardHook(options) + return { + ...config, + collections: (config.collections ?? []).map((c) => ({ + ...c, + hooks: { ...c.hooks, beforeOperation: [...(c.hooks?.beforeOperation ?? []), hook] }, + })), + // Payload's ErrorName union knows only its own errors; the name is looked up by string at log time + loggingLevels: { ...({ RefusedSortError: 'info' } as NonNullable), ...config.loggingLevels }, + } +} + +/** Payload's collection of document locks ("who edits what"). */ +export const LOCKED_DOCUMENTS_SLUG = 'payload-locked-documents' + +/** + * Staff accounts (with their second factor, when 2FA is on) — who edits in the panel. Payload's default for its + * document locks is any signed-in account, so a visitor account (a shop's customers) could read who edits what and + * write or delete locks. + */ +export const staffOnlyLocks: Access = ({ req }) => isStaffRequest(req) && secondFactorPassed({ payload: req.payload, user: req.user }) + +export type LockedDocumentsAccess = Partial, 'create' | 'delete' | 'read' | 'update'>> + +/** + * Payload adds its document-lock collection after every plugin has run, so its rules are set on the live config + * (onInit and after a dev reload). `access` keys the project gives win; the rest is {@link staffOnlyLocks}. + */ +export function applyLockedDocumentsAccess(config: Pick, access: LockedDocumentsAccess = {}): boolean { + const locks = config.collections?.find((c) => c.slug === LOCKED_DOCUMENTS_SLUG) + if (!locks) {return false} + locks.access = { ...locks.access, create: staffOnlyLocks, delete: staffOnlyLocks, read: staffOnlyLocks, update: staffOnlyLocks, ...access } + return true +} diff --git a/src/plugin.ts b/src/plugin.ts index 903c9ec..fcd6c25 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -53,6 +53,7 @@ import { serverText } from './modules/integrations/texts.js' import { buildSystemPagesFields } from './modules/pages/index.js' import { guardAdminEndpoints } from './modules/security/adminSameOrigin.js' import { jobsRunNotice, withJobsRunAccess } from './modules/security/jobsAccess.js' +import { applyLockedDocumentsAccess, applyQueryGuard } from './modules/security/queryGuard.js' import { buildEnrolmentEndpoints, buildTotpNoticeHooks, resolveConfirmByEmail, startEnrolment } from './modules/security/totp/enrolmentConfirm.js' import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js' import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js' @@ -229,6 +230,8 @@ export const iapl = (options: IaplOptions): Plugin => { const adoptConfig = (payload: BasePayload) => { const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken registerStaffCollections(payload, staffCollectionSlugs(payload), token) + // Payload adds its document-lock collection after every plugin: its rules are set on the live config. + if (options.lockedDocuments !== false) {applyLockedDocumentsAccess(payload.config, options.lockedDocuments?.access)} // Auth collections a plugin listed after iapl added: the account rules for them too — BEFORE the // 2FA guard below wraps their access (it needs the rule inside its wrapper). if (accounts) { @@ -1064,6 +1067,9 @@ export const iapl = (options: IaplOptions): Plugin => { config = guardConfigAccess(config) } + // --- lists from outside: operator sort names refused, page size capped for non-staff (audit F5, F4) --- + config = applyQueryGuard(config, { listLimit: options.listLimit, refuseOperatorSort: options.refuseOperatorSort }) + // --- hooks: onInit --- const incomingOnInit = config.onInit config.onInit = async (payload) => { diff --git a/src/types.ts b/src/types.ts index 7f6247e..d4202f8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,6 +1,7 @@ import type { CollectionSlug, Field, PayloadComponent, PayloadRequest, Plugin } from 'payload' import type { SignInLookOptions } from './modules/branding/signIn/options.js' +import type { ListLimitOptions, LockedDocumentsAccess } from './modules/security/queryGuard.js' /** * Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected @@ -237,6 +238,23 @@ export type IaplOptions = { */ lightbox?: boolean + /** + * Public lists are capped (security audit 2026-12, F4): a REST / GraphQL `find` (also versions and distinct values) + * from a caller that is not staff gets at most `max` (100) documents per request, and `pagination=false` / `limit=0` + * become one page of `max`. Staff accounts and the Local API (the frontend, seeds) are not touched. + * `false` = Payload's behaviour (any limit); `{ max, staff: true, exclude: ['slug'] }` adapts it. + * docs/security.md "Lists and sorting". + */ + listLimit?: false | ListLimitOptions + + /** + * Payload's document locks ("who edits what", `payload-locked-documents`) are for staff accounts only (with the + * second factor when 2FA is on). Payload's default lets any signed-in account in — also a visitor account of a + * login collection for customers. `false` = Payload's default; `{ access: { read, create, update, delete } }` + * sets your own rule per operation (the rest stays staff only). docs/security.md "Lists and sorting". + */ + lockedDocuments?: { access?: LockedDocumentsAccess } | false + /** * E-mail (docs/email.md). A site with no SMTP server in Site integrations sends through the * Intecion Notifications Webservice: it enrols by itself on its first send (an outbound call with @@ -259,6 +277,13 @@ export type IaplOptions = { */ pages?: PagesOption + /** + * A REST / GraphQL `sort` that names a database operator (`$where`, `-$natural`, `title.$ne`) is refused with 400 + * instead of reaching the database (a 500 and a logged stack trace on MongoDB; security audit 2026-12, F5). Default + * true; `false` = Payload's behaviour. The Local API is not touched. + */ + refuseOperatorSort?: boolean + /** * next/cache `revalidatePath`, INJECTED (the plugin never imports next/cache). * When given, saving any of the plugin's globals (Site Settings, Site diff --git a/test/queryGuardHttp.test.ts b/test/queryGuardHttp.test.ts new file mode 100644 index 0000000..16e38ce --- /dev/null +++ b/test/queryGuardHttp.test.ts @@ -0,0 +1,112 @@ +/** + * Lists from outside (1.18.0; security audit 2026-12, findings F4 and F5) and Payload's document locks for staff only + * (the "document locks" door), over real HTTP: Payload's REST and GraphQL handlers behind a server, a visitor login + * collection next to the staff one. + */ +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 { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' +import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' + +vi.mock('server-only', () => ({})) +vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock) + +const PASSWORD = 'a-long-test-password-1' +let server: TestServer +let payload: Payload +let base = '' +let editor = '' +let customer = '' + +const signIn = async (collection: string, email: string) => { + const res = await fetch(`${base}/api/${collection}/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: { 'content-type': 'application/json', origin: base }, method: 'POST' }) + expect(res.status).toBe(200) + return cookiesOf(res).join('; ') +} +const get = async (path: string, cookie = '') => { + const res = await fetch(`${base}${path}`, { headers: { cookie, origin: base } }) + return { body: (await res.json().catch(() => ({}))) as { docs?: unknown[]; limit?: number }, status: res.status } +} + +beforeAll(async () => { + const config = buildTestConfig({ + admin: { user: 'users' }, + collections: [ + { slug: 'notes', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }, + { slug: 'customers', access: { create: () => false }, auth: true, fields: [] }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }, + ], + db: testDatabase('query_guard'), + editor: lexicalEditor(), + plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })], + secret: 'integration-test-secret-0123456789', + telemetry: false, + }) + payload = await getPayload({ config }) + server = await startPayloadServer(config) + base = server.url + for (let i = 0; i < 130; i++) {await payload.create({ collection: 'notes' as never, data: { title: `n${i}` } as never })} + await payload.create({ collection: 'users' as never, data: { email: 'editor@example.com', password: PASSWORD, roles: ['editor'] } as never }) + await payload.create({ collection: 'customers' as never, data: { email: 'customer@example.com', password: PASSWORD } as never, overrideAccess: true }) + editor = await signIn('users', 'editor@example.com') + customer = await signIn('customers', 'customer@example.com') +}, 180_000) + +afterAll(async () => { + await server?.close() + await payload?.destroy?.() +}) + +describe('F4: public lists are capped for callers that are not staff', () => { + test('anonymous and a customer get at most 100; pagination=false and limit=0 too', async () => { + for (const cookie of ['', customer]) { + for (const q of ['limit=100000', 'pagination=false', 'limit=0']) { + const { body, status } = await get(`/api/notes?${q}&depth=0`, cookie) + expect([q, status, body.docs?.length]).toEqual([q, 200, 100]) + } + } + expect((await get('/api/notes?limit=5')).body.docs).toHaveLength(5) + }) + + test('staff and the Local API are not capped', async () => { + expect((await get('/api/notes?limit=1000&depth=0', editor)).body.docs).toHaveLength(130) + expect((await payload.find({ collection: 'notes' as never, limit: 1000 })).docs).toHaveLength(130) + }) + + test('GraphQL lists from outside are capped as well', async () => { + const res = await fetch(`${base}/api/graphql`, { body: JSON.stringify({ query: '{ Notes(limit: 100000) { docs { id } } }' }), headers: { 'content-type': 'application/json', origin: base }, method: 'POST' }) + const body = (await res.json()) as { data?: { Notes?: { docs: unknown[] } } } + expect(body.data?.Notes?.docs).toHaveLength(100) + }) +}) + +describe('F5: an operator name in ?sort= is refused', () => { + test('$where, -$where, $natural and a.$ne answer 400 — anonymous and staff alike; a field name still sorts', async () => { + for (const cookie of ['', editor]) { + for (const sort of ['%24where', '-%24where', '%24natural', 'title.%24ne']) { + expect([sort, (await get(`/api/notes?sort=${sort}&limit=1`, cookie)).status]).toEqual([sort, 400]) + } + } + expect((await get('/api/notes?sort=-title&limit=1')).status).toBe(200) + }) +}) + +describe('Payload\'s document locks are for staff only', () => { + test('a customer is refused on every operation; an editor works as before', async () => { + const page = (await payload.find({ collection: 'notes' as never, limit: 1 })).docs[0] as { id: number | string } + const lock = { document: { relationTo: 'notes', value: page.id }, user: { relationTo: 'customers', value: 1 } } + const asCustomer = { 'content-type': 'application/json', cookie: customer, origin: base } + expect((await fetch(`${base}/api/payload-locked-documents`, { headers: asCustomer })).status).toBe(403) + expect((await fetch(`${base}/api/payload-locked-documents`, { body: JSON.stringify(lock), headers: asCustomer, method: 'POST' })).status).toBe(403) + expect((await fetch(`${base}/api/payload-locked-documents`, { headers: { cookie: '', origin: base } })).status).toBe(403) + expect((await fetch(`${base}/api/payload-locked-documents`, { headers: { cookie: editor, origin: base } })).status).toBe(200) + }) +}) diff --git a/test/securityClasses.test.ts b/test/securityClasses.test.ts index 923948c..40843d2 100644 --- a/test/securityClasses.test.ts +++ b/test/securityClasses.test.ts @@ -5,7 +5,8 @@ * * A finding of the audit that is not fixed yet is an `it.fails` naming it (security-audit-2026-12-findings.md): * the test states the SAFE behaviour, so the day the fix lands vitest says the test "passed unexpectedly" and the - * `.fails` goes. The same convention as `openFor` in the closed-doors spec. + * `.fails` goes. The same convention as `openFor` in the closed-doors spec. Every finding of the 2026-12 audit is + * fixed in 1.18.0: no `.fails` is left. */ import { Script } from 'node:vm' import { createElement } from 'react' @@ -16,11 +17,14 @@ import { adminPathFromReferer } from '../src/modules/branding/signIn/languageEnd import { consentDecidedScript } from '../src/modules/consent/firstPaint.js' import { parseConsent, readConsentRecord } from '../src/modules/consent/storage.js' import { markdownResponse } from '../src/modules/content/createMarkdownRenderer.js' +import { MARKDOWN_NEGOTIATED_HEADER } from '../src/modules/content/markdownNegotiation.js' import { createProxy } from '../src/modules/i18n/createProxy.js' +import { buildUrlField, isAllowedUrl } from '../src/modules/links/buildUrlField.js' import { safeHref } from '../src/modules/links/resolveLinkHref.js' import { createMcpRoute } from '../src/modules/mcp/createMcpRoute.js' import { sanitizeRichTextLinks } from '../src/modules/richtext/sanitizeLinks.js' -import { createCspReportRoute } from '../src/modules/security/createCspReportRoute.js' +import { createCspReportRoute, CSP_LOG_VALUE_MAX, cspLogLine } from '../src/modules/security/createCspReportRoute.js' +import { applyLockedDocumentsAccess, buildQueryGuardHook, capListLimit, isOperatorSort, LOCKED_DOCUMENTS_SLUG } from '../src/modules/security/queryGuard.js' import { safeAdminBack } from '../src/modules/security/totp/safeBack.js' import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js' import { JsonLdGraph } from '../src/modules/seo/JsonLdGraph.js' @@ -99,7 +103,7 @@ describe('open redirect and header injection', () => { it('locale redirect: a path that looks like a host stays on this site', () => { const NextResponse = { next: () => ({ cookies: { set: () => {} }, headers: new Headers() }), redirect: (u: string | URL) => ({ cookies: { set: () => {} }, headers: new Headers({ location: String(u) }) }) } - const proxy = createProxy({ defaultLocale: 'pl', locales: ['pl', 'en'] } as never, { NextResponse }) + const proxy = createProxy({ defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] } as never, { NextResponse }) for (const p of ['//evil.example', '/\\evil.example', '/%2F%2Fevil.example', '/.evil.example']) { const url = new URL(`https://site.pl${p}`) const res = proxy({ cookies: { get: () => undefined }, headers: new Headers(), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers } @@ -121,18 +125,49 @@ describe('injection — prototype pollution and operators in stored or sent JSON }) describe('log injection', () => { - // FINDING F1 (security-audit-2026-12-findings.md): the report's own strings go into the log line as they are. - it.fails('F1: a CSP report cannot write a forged line into the server log', async () => { + // F1 (security-audit-2026-12-findings.md), fixed in 1.18.0: the default line holds origins and paths, no control characters. + it('F1: a CSP report cannot write a forged line into the server log', async () => { const lines: string[] = [] const warn = vi.spyOn(console, 'warn').mockImplementation((...a: unknown[]) => {lines.push(a.join(' '))}) try { - const route = createCspReportRoute() + const route = createCspReportRoute({ rateLimit: false }) await route(new Request('http://localhost/api/csp-report', { body: JSON.stringify({ 'csp-report': { 'blocked-uri': 'x\n[iapl] admin signed in: owner@site.pl from 10.0.0.1', 'document-uri': 'https://s.pl/', 'effective-directive': 'script-src' } }), method: 'POST' })) } finally { warn.mockRestore() } expect(lines.join('\n').split('\n')).toHaveLength(1) }) + + it('F1: the default line keeps the blocked origin and the page path (no query), every value capped', () => { + const line = cspLogLine({ + blockedUri: 'https://cdn.evil.example/x.js?token=secret', + documentUri: 'https://s.pl/pl/kontakt?email=a@b.pl#form', + effectiveDirective: 'script-src-elem', + lineNumber: 3, + sourceFile: `https://s.pl/_next/static/a.js?v=1\u2028${'x'.repeat(500)}`, + }) + expect(line).toContain('blocked=https://cdn.evil.example ') + expect(line).toContain('page=/pl/kontakt') + expect(line).not.toMatch(/secret|a@b\.pl|\u2028/) + expect(line.length).toBeLessThan(4 * CSP_LOG_VALUE_MAX) + expect(cspLogLine({ blockedUri: 'inline' })).toContain('blocked=inline') + }) + + it('F1: one request handles at most maxReports violations; a project\'s onReport gets the raw values', async () => { + const seen: string[] = [] + const route = createCspReportRoute({ maxReports: 3, onReport: (v) => {seen.push(v.blockedUri ?? '')}, rateLimit: false }) + const many = Array.from({ length: 40 }, (_, i) => ({ type: 'csp-violation', body: { blockedURL: `x\n${i}`, documentURL: 'https://s.pl/' } })) + expect((await route(new Request('http://localhost/api/csp-report', { body: JSON.stringify(many), method: 'POST' }))).status).toBe(204) + expect(seen).toEqual(['x\n0', 'x\n1', 'x\n2']) + }) + + it('F1: over the per-client limit the route answers 204 and handles nothing', async () => { + const seen: number[] = [] + const route = createCspReportRoute({ onReport: () => {seen.push(1)}, rateLimit: { max: 2, windowMs: 60_000 } }) + const send = () => route(new Request('http://localhost/api/csp-report', { body: JSON.stringify({ 'csp-report': { 'blocked-uri': 'inline' } }), headers: { 'x-forwarded-for': '203.0.113.77' }, method: 'POST' })) + for (let i = 0; i < 4; i++) {expect((await send()).status).toBe(204)} + expect(seen).toHaveLength(2) + }) }) describe('denial of service — bodies and batches', () => { @@ -152,19 +187,111 @@ describe('denial of service — bodies and batches', () => { }) describe('cache poisoning — one URL, two bodies', () => { - // FINDING F3: `Accept: text/markdown` on an HTML URL gets the Markdown copy at the SAME URL, cacheable by a shared - // cache for an hour (a day stale) and with no Vary: a CDN that caches HTML can serve the Markdown to every visitor. - it.fails('F3: the Markdown answer given at an HTML URL says it varies by Accept (or is not stored by shared caches)', () => { + // F3, fixed in 1.18.0: `Accept: text/markdown` on an HTML URL gets the Markdown copy at the SAME URL — now private, + // never stored by a shared cache, with Vary: Accept on both answers. + it('F3: the Markdown answer given at an HTML URL says it varies by Accept (or is not stored by shared caches)', () => { const rewrites: string[] = [] const response = () => ({ cookies: { set: () => {} }, headers: new Headers() }) const NextResponse = { next: response, redirect: response, rewrite: (u: string | URL) => {rewrites.push(String(u)); return response()} } - const proxy = createProxy({ defaultLocale: 'pl', locales: ['pl', 'en'] } as never, { markdown: true, NextResponse }) + const proxy = createProxy({ defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] } as never, { markdown: true, NextResponse }) const url = new URL('https://site.pl/pl/o-nas') const res = proxy({ cookies: { get: () => undefined }, headers: new Headers({ accept: 'text/markdown' }), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers } expect(rewrites).toHaveLength(1) - const md = markdownResponse('# x') + const md = markdownResponse('# x', { negotiated: true }) const varies = /accept/i.test(res.headers.get('vary') ?? '') || /accept/i.test(md.headers.get('vary') ?? '') const private_ = /private|no-store/.test(md.headers.get('cache-control') ?? '') expect(varies || private_).toBe(true) + expect(res.headers.get('cache-control')).toBe('private, no-store') + expect(res.headers.get('vary')).toBe('Accept') + }) + + it('F3: the route answers private + Vary: Accept only when the proxy marked the request; /md/… stays public', async () => { + expect(markdownResponse('# x').headers.get('cache-control')).toMatch(/public/) + expect(markdownResponse('# x').headers.get('vary')).toBeNull() + expect(markdownResponse(null, { negotiated: true }).headers.get('cache-control')).toBe('private, no-store') + }) + + it('F3: the proxy passes the marker to the route, adds Vary: Accept to pages, and markdown.negotiate: false turns negotiation off', () => { + const seen: { headers?: Headers; url: string }[] = [] + const response = () => ({ cookies: { set: () => {} }, headers: new Headers() }) + const NextResponse = { next: response, redirect: response, rewrite: (u: string | URL, init?: { request?: { headers: Headers } }) => {seen.push({ headers: init?.request?.headers, url: String(u) }); return response()} } + const ask = (accept: string, markdown: unknown) => { + const url = new URL('https://site.pl/pl/o-nas') + return createProxy({ defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] } as never, { markdown: markdown as never, NextResponse })({ cookies: { get: () => undefined }, headers: new Headers({ accept }), nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: '' }, url: url.toString() }) as unknown as { headers: Headers } + } + ask('text/markdown', true) + expect(seen[0].headers?.get(MARKDOWN_NEGOTIATED_HEADER)).toBe('1') + expect(ask('text/html', true).headers.get('vary')).toBe('Accept') + seen.length = 0 + const off = ask('text/markdown', { negotiate: false }) + expect(seen).toHaveLength(0) + expect(off.headers.get('vary')).toBeNull() + expect(ask('text/markdown', { prefix: '/ai' }) && seen[0].url).toBe('https://site.pl/ai/pl/o-nas') + }) +}) + +describe('denial of service and injection — lists from outside (F4, F5)', () => { + const hook = buildQueryGuardHook({}) + const run = (args: Record, req: Record, operation = 'read', h = hook) => + h({ args, collection: { slug: 'pages' }, context: {}, operation, req } as never) as Record + const visitor = { payload: { config: { admin: { user: 'users' }, custom: {} } }, payloadAPI: 'REST', user: null } + const staff = { ...visitor, user: { id: 1, collection: 'users' } } + + it('F4: a caller that is not staff gets at most 100 per request; pagination=false and limit=0 become one page', () => { + expect(run({ limit: 100000 }, visitor)).toMatchObject({ limit: 100, pagination: true }) + expect(run({ pagination: false }, visitor)).toMatchObject({ limit: 100, pagination: true }) + expect(run({ limit: 0 }, visitor)).toMatchObject({ limit: 100, pagination: true }) + expect(run({ limit: 20 }, visitor)).toEqual({ limit: 20 }) + expect(run({ limit: 5000 }, { ...visitor, user: { id: 1, collection: 'customers' } })).toMatchObject({ limit: 100 }) + expect(run({ limit: 5000 }, visitor, 'findVersions')).toMatchObject({ limit: 100 }) + }) + + it('F4: staff, the Local API, one document by id and listLimit: false are left alone; max / exclude / staff adapt it', () => { + expect(run({ limit: 5000 }, staff)).toEqual({ limit: 5000 }) + expect(run({ limit: 5000 }, { ...visitor, payloadAPI: 'local' })).toEqual({ limit: 5000 }) + expect(run({ id: 'a', limit: 5000 }, visitor)).toEqual({ id: 'a', limit: 5000 }) + expect(run({ limit: 5000 }, visitor, 'read', buildQueryGuardHook({ listLimit: false }))).toEqual({ limit: 5000 }) + expect(run({ limit: 5000 }, visitor, 'read', buildQueryGuardHook({ listLimit: { max: 20 } }))).toMatchObject({ limit: 20 }) + expect(run({ limit: 5000 }, visitor, 'read', buildQueryGuardHook({ listLimit: { exclude: ['pages'] } }))).toEqual({ limit: 5000 }) + expect(run({ limit: 5000 }, staff, 'read', buildQueryGuardHook({ listLimit: { staff: true } }))).toMatchObject({ limit: 100 }) + expect(capListLimit({ limit: 7 }, 5)).toEqual({ limit: 5, pagination: true }) + }) + + it('F5: a sort that names a database operator is refused with 400, for staff too; the Local API and refuseOperatorSort: false are not touched', () => { + for (const sort of ['$where', '-$where', '$natural', 'title.$ne', ['title', '-$where'], 'title,-$where']) { + expect(isOperatorSort(sort), String(sort)).toBe(true) + expect(() => run({ sort }, staff), String(sort)).toThrow(expect.objectContaining({ status: 400 })) + } + for (const sort of ['title', '-createdAt', 'meta.title', ['title', '-date']]) {expect(isOperatorSort(sort)).toBe(false)} + expect(run({ sort: '$where' }, { ...visitor, payloadAPI: 'local' })).toEqual({ sort: '$where' }) + expect(run({ sort: '$where' }, visitor, 'read', buildQueryGuardHook({ refuseOperatorSort: false }))).toEqual({ sort: '$where' }) + }) + + it('the document locks: staff only by default, the project\'s rule per operation wins, a config without them is left alone', () => { + const config = { collections: [{ slug: LOCKED_DOCUMENTS_SLUG, access: {} }] } as never as { collections: { access: Record; slug: string }[] } + expect(applyLockedDocumentsAccess(config as never)).toBe(true) + const rule = config.collections[0].access.read as (a: unknown) => boolean + expect(rule({ req: { payload: visitor.payload, user: { id: 1, collection: 'customers' } } })).toBe(false) + expect(rule({ req: { payload: visitor.payload, user: null } })).toBe(false) + expect(rule({ req: { payload: visitor.payload, user: { id: 1, collection: 'users' } } })).toBe(true) + const own = () => true + applyLockedDocumentsAccess(config as never, { read: own }) + expect(config.collections[0].access.read).toBe(own) + expect(applyLockedDocumentsAccess({ collections: [] } as never)).toBe(false) + }) +}) + +describe('XSS — addresses rendered into href (F2)', () => { + it('buildUrlField refuses javascript:, data: and protocol-relative addresses; https passes; other kinds only when listed', () => { + const field = buildUrlField({ required: true }) + const validate = field.validate as (v: unknown, o?: unknown) => string | true + for (const url of UNSAFE_URLS) {expect(validate(url), url).not.toBe(true)} + expect(validate('https://instagram.com/studio')).toBe(true) + expect(validate('')).not.toBe(true) + expect(validate('mailto:a@b.pl')).not.toBe(true) + expect(isAllowedUrl('mailto:a@b.pl', ['mailto'])).toBe(true) + expect(isAllowedUrl('/pl/o-nas', ['relative'])).toBe(true) + expect(isAllowedUrl('//evil.example', ['relative'])).toBe(false) + expect(buildUrlField({ name: 'website', overrides: { localized: true } })).toMatchObject({ name: 'website', type: 'text', localized: true }) }) }) diff --git a/test/visitorWrites.test.ts b/test/visitorWrites.test.ts index c6a9157..3c2d7ce 100644 --- a/test/visitorWrites.test.ts +++ b/test/visitorWrites.test.ts @@ -11,6 +11,7 @@ import { describe, expect, test, vi } from 'vitest' import { adminOrEditor } from '../src/modules/access/access.js' import { visitorWritableEntities } from '../src/modules/doctor/visitorWrites.js' +import { applyLockedDocumentsAccess } from '../src/modules/security/queryGuard.js' import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' @@ -49,6 +50,13 @@ describe('visitorWritableEntities', () => { } }, 30_000) + test('Payload\'s document locks are not listed once iapl\'s staff-only rule is on (lockedDocuments, 1.18.0)', async () => { + const config = await build([{ slug: 'customers', access: { create: () => false }, auth: true, fields: [] }]) + expect(await visitorWritableEntities(live(config))).toContain('payload-locked-documents:create') + applyLockedDocumentsAccess(config) + expect((await visitorWritableEntities(live(config))).filter((e) => e.startsWith('payload-locked-documents'))).toEqual([]) + }, 30_000) + test('a site with only the staff login collection: nothing to report', async () => { const config = await build([{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }]) expect(await visitorWritableEntities(live(config))).toEqual([])