Security suites from the 2026-12 audit: static rules, attack probes, per-class tests, gate

- doctor: code-patterns (unescaped HTML/JSON-LD, eval, shell, NEXT_PUBLIC_ secrets,
  overrideAccess / Local API user, where from the request, redirects and fetches to a
  request address) and config-dangerous; live-probes runs the safe attack probes on --url
- ATTACK_PROBES / runAttackProbes / createProbeContext exported from /doctor; the reference
  site runs all of them in pnpm e2e:built (both bundlers) plus CSRF and cookie flags;
  project template iapl-audit/resources/attack-probes.spec.template.ts
- test/securityPatterns.test.ts gates every hit against test/security-patterns.allow.json;
  test/securityClasses.test.ts covers XSS, redirects, pollution, logs, DoS, cache poisoning
- pnpm security:gate (pnpm audit --prod, the two suites, optional offline ZAP) in prepublishOnly
- audit findings F1, F3, F4, F5 reproduced as expected-to-fail tests/probes; no fix built
- docs: security.md threat list + Security suites, doctor.md, AGENT.md, CHANGELOG, skills

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 16:46:42 +01:00
co-authored by Claude Opus 5.5
parent a416411f01
commit d2f19095dc
25 changed files with 1400 additions and 5 deletions
+407
View File
@@ -0,0 +1,407 @@
/**
* HTTP attack probes (security audit 2026-12): the requests attackers send to Payload / Next.js sites, each with the
* answer a safe site gives. One list, two users:
* - `iapl-doctor --url https://site --only live-probes` runs the probes marked `live` against a project's own site:
* GET requests, plus requests that change nothing (a refused sign-in with operators in it);
* - the plugin's reference site runs every probe on a production build in both bundlers
* (reference/e2e/attack-probes.spec.ts, part of `pnpm e2e:built`); a project copies
* `.agents/skills/iapl-audit/resources/attack-probes.spec.template.ts`.
* Exported (`@intecion/ipal-kit/doctor`) so a project adds its own probes or runs a subset in its CI.
*
* A probe answers on STATUS CODES and headers first: a 500 page is never counted as "closed" (a test that passes on
* an error page proves nothing).
*/
export type ProbeAnswer = { error?: string; headers: Headers; ms: number; status: number; text: string }
export type ProbeContext = {
/** Site origin, no trailing slash. */
base: string
/** One request; never follows redirects unless asked. */
fetch: (path: string, init?: { body?: string; follow?: boolean; headers?: Record<string, string>; method?: string }) => Promise<ProbeAnswer>
/** A public page path of the site (default `/`), e.g. `/pl`. */
page?: string
/** Values that must never appear in a public file (the test knows the real secrets; a live run passes none). */
secrets?: string[]
}
export type ProbeResult = { detail: string; ok: boolean; skipped?: string }
export type AttackProbe = {
/** The vulnerability class (security.md → "Threat list"). */
class: string
/** A finding of the audit that is not fixed yet (security-audit-2026-12-findings.md): expected to fail until it is. */
finding?: string
id: string
/** Safe on a live site: reads only, or a request the site refuses without writing. */
live: boolean
run: (ctx: ProbeContext) => Promise<ProbeResult>
title: string
}
const ok = (detail = ''): ProbeResult => ({ detail, ok: true })
const bad = (detail: string): ProbeResult => ({ detail, ok: false })
const skip = (why: string): ProbeResult => ({ detail: '', ok: true, skipped: why })
/** A stack trace or a server path in an answer. */
const LEAK = /\n\s+at [\w$.<>]+ \(|\bat (?:async )?[\w$.]+ \((?:\/|[A-Z]:\\|file:)|\/node_modules\/|webpack-internal:|\/\.next\/server\//
/** What a secret looks like, without knowing it. */
const SECRET_SHAPES: Array<[string, RegExp]> = [
['a private key', /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/],
['a database URL with a password', /\b(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql):\/\/[^\s"'`:@/]+:[^\s"'`@/]+@/],
['a live Stripe key', /\bsk_live_[0-9a-zA-Z]{10,}/],
['an AWS secret', /\baws_secret_access_key\b|\bAKIA[0-9A-Z]{16}\b/],
['a variable assignment of a server secret', /\b(?:PAYLOAD_SECRET|DATABASE_URI|R2_SECRET_ACCESS_KEY|TURNSTILE_SECRET_KEY|CRON_SECRET|SMTP_PASS(?:WORD)?)\s*[=:]\s*["'`][^"'`]{8,}/],
]
const EVIL = 'evil.example'
const sameHost = (location: null | string, base: string) => {
if (!location) {return true}
try {
return new URL(location, base).host === new URL(base).host
} catch {
return false
}
}
const describe = (a: ProbeAnswer) => (a.error ? `no answer (${a.error})` : `${a.status}`)
const scriptSrcs = (html: string) => [...html.matchAll(/<script[^>]+src="([^"]+)"/g)].map((m) => m[1].replace(/&amp;/g, '&'))
export const ATTACK_PROBES: AttackProbe[] = [
{
id: 'secret-files',
class: 'secrets in public files',
live: true,
run: async ({ fetch }) => {
const paths = ['/.env', '/.env.local', '/.env.production', '/.git/config', '/.git/HEAD', '/package.json', '/pnpm-lock.yaml', '/next.config.ts', '/payload.config.ts', '/src/payload.config.ts', '/Dockerfile', '/docker-compose.yml', '/.DS_Store', '/api/media/file/..%2F..%2F.env', '/api/media/file/%2e%2e%2f%2e%2e%2fpackage.json', '/_next/static/..%2F..%2F.env', '/_next/../package.json']
const open: string[] = []
for (const path of paths) {
const a = await fetch(path)
if (a.status === 200 && /PAYLOAD_SECRET|DATABASE_URI|"dependencies"\s*:|\[core\]|^ref: refs\/|lockfileVersion|FROM node|buildConfig\(/m.test(a.text)) {open.push(path)}
if (a.status >= 500) {open.push(`${path} → ${a.status}`)}
}
return open.length ? bad(`served: ${open.join(', ')}`) : ok(`${paths.length} paths refused`)
},
title: 'source, env and git files are not served (also through ../ in a file route)',
},
{
id: 'bundle-secrets',
class: 'secrets in client bundles',
live: true,
run: async ({ fetch, page = '/', secrets = [] }) => {
const pages = [page, '/admin/login']
const files = new Set<string>()
for (const p of pages) {
const a = await fetch(p, { follow: true })
for (const src of scriptSrcs(a.text)) {if (src.startsWith('/') && !src.startsWith('//')) {files.add(src)}}
}
if (!files.size) {return skip('no script files found on the pages')}
const found: string[] = []
let maps = 0
for (const file of files) {
const a = await fetch(file)
for (const [what, re] of SECRET_SHAPES) {if (re.test(a.text)) {found.push(`${file}: ${what}`)}}
for (const s of secrets) {if (s && s.length >= 8 && a.text.includes(s)) {found.push(`${file}: a server secret's value`)}}
if (maps < 3 && /\/_next\/static\/.+\.js$/.test(file)) {
maps++
const map = await fetch(`${file.split('?')[0]}.map`)
if (map.status === 200 && /"sources"\s*:/.test(map.text)) {found.push(`${file}.map: source map is public (productionBrowserSourceMaps)`)}
}
}
return found.length ? bad(found.join('; ')) : ok(`${files.size} script files clean`)
},
title: 'no secret (or a secret-shaped value) in the JavaScript the pages load; no public source maps',
},
{
id: 'middleware-subrequest',
class: 'middleware / proxy bypass',
live: true,
run: async ({ fetch }) => {
const plain = await fetch('/')
if (plain.status < 300 || plain.status >= 400) {return skip(`/ answers ${describe(plain)} without the proxy redirecting (single locale?): nothing to compare`)}
const values = ['middleware:middleware:middleware:middleware:middleware', 'src/middleware:src/middleware:src/middleware:src/middleware:src/middleware', 'proxy:proxy:proxy:proxy:proxy', 'src/proxy:src/proxy:src/proxy:src/proxy:src/proxy', 'pages/_middleware']
for (const v of values) {
const a = await fetch('/', { headers: { 'x-middleware-subrequest': v } })
if (a.status !== plain.status) {return bad(`x-middleware-subrequest: ${v} changed / from ${plain.status} to ${describe(a)}: the proxy was skipped (CVE-2025-29927 class — upgrade Next)`)}
}
return ok(`the proxy ran for all ${values.length} header values`)
},
title: 'x-middleware-subrequest does not skip the proxy (CVE-2025-29927 class)',
},
{
id: 'open-redirect',
class: 'open redirect',
live: true,
run: async ({ base, fetch }) => {
const paths = [`//${EVIL}/`, `/%2F%2F${EVIL}`, `/\\${EVIL}`, `/%5C${EVIL}`, `/%09/${EVIL}`, `/admin/login?redirect=https://${EVIL}/`, `/admin?redirect=//${EVIL}`, `/api/ipal/admin-language?lng=en`]
const away: string[] = []
for (const path of paths) {
const a = await fetch(path, { headers: path.includes('admin-language') ? { referer: `https://${EVIL}/admin` } : {} })
const location = a.headers.get('location')
if (a.status >= 300 && a.status < 400 && !sameHost(location, base)) {away.push(`${path} → ${location}`)}
if (a.status >= 500) {away.push(`${path} → ${a.status}`)}
}
return away.length ? bad(away.join('; ')) : ok(`${paths.length} paths stay on the site`)
},
title: 'no path, parameter or Referer sends the browser to another host',
},
{
id: 'host-header',
class: 'cache poisoning (host headers)',
live: true,
run: async ({ fetch, page = '/' }) => {
const headers = { forwarded: `host=${EVIL}`, 'x-forwarded-host': EVIL, 'x-host': EVIL, 'x-original-host': EVIL }
const redirect = await fetch('/', { headers })
const location = redirect.headers.get('location') ?? ''
if (location.includes(EVIL)) {return bad(`/ redirects to ${location}: the redirect trusts X-Forwarded-Host`)}
const html = await fetch(page, { follow: true, headers })
if (html.text.includes(EVIL)) {return bad(`${page} prints ${EVIL} (canonical, og:url, hreflang or a link): a cached page would carry it for everyone`)}
return ok('neither the redirect nor the page uses a host the request named')
},
title: 'X-Forwarded-Host / Forwarded do not reach redirects or links in the page',
},
{
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' } })
if (!/text\/markdown/.test(a.headers.get('content-type') ?? '')) {return skip(`${page} with Accept: text/markdown answers ${a.headers.get('content-type') ?? describe(a)} (no Markdown negotiation)`)}
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`)}
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',
},
{
id: 'rsc-vary',
class: 'cache poisoning (RSC)',
live: true,
run: async ({ fetch, page = '/' }) => {
const a = await fetch(page, { follow: true, headers: { rsc: '1' } })
if (!/text\/x-component/.test(a.headers.get('content-type') ?? '')) {return skip(`${page} with RSC: 1 is not a flight answer`)}
return /\brsc\b/i.test(a.headers.get('vary') ?? '') ? ok() : bad(`the flight answer of ${page} has no Vary: RSC (vary: ${a.headers.get('vary') ?? 'none'})`)
},
title: 'the RSC (flight) answer of a page varies by the RSC header',
},
{
id: 'login-operators',
class: 'injection (NoSQL operators)',
live: true,
run: async ({ fetch }) => {
const bodies = [{ email: { $ne: null }, password: { $ne: null } }, { email: { $gt: '' }, password: 'x' }, { email: '[email protected]', password: { $ne: 'x' } }]
for (const body of bodies) {
const a = await fetch('/api/users/login', { body: JSON.stringify(body), headers: { 'content-type': 'application/json' }, method: 'POST' })
if (a.status === 200 || /"token"\s*:\s*"/.test(a.text)) {return bad(`login with ${JSON.stringify(body)} answered ${a.status} with a token`)}
if (a.status >= 500) {return bad(`login with ${JSON.stringify(body)} answered ${a.status}`)}
if (LEAK.test(a.text)) {return bad('the refused login answer carries a stack trace or a server path')}
}
return ok('operators in the e-mail or password are refused')
},
title: 'a sign-in with $ne / $gt in it is refused (no account, no 500)',
},
{
id: 'rest-where',
class: 'access control (REST where / drafts)',
live: true,
run: async ({ fetch }) => {
const problems: string[] = []
for (const path of ['/api/users?where[email][exists]=true&limit=1', '/api/users?where[password][exists]=true&limit=1', '/api/users?where[or][0][roles][equals]=admin&limit=1', '/api/form-submissions?limit=1', '/api/payload-preferences?limit=1', '/api/payload-kv?limit=1']) {
const a = await fetch(path)
if (a.status === 404) {continue}
if (a.status >= 500) {problems.push(`${path} → ${a.status}`); continue}
if (a.status === 200 && /"docs"\s*:\s*\[\s*\{/.test(a.text)) {problems.push(`${path} → 200 with documents`)}
}
const drafts = await fetch('/api/pages?draft=true&where[_status][equals]=draft&limit=5&depth=0')
if (drafts.status === 200 && /"_status"\s*:\s*"draft"/.test(drafts.text)) {problems.push('/api/pages?draft=true returns drafts to an anonymous visitor')}
if (drafts.status >= 500) {problems.push(`/api/pages?draft=true… → ${drafts.status}`)}
const versions = await fetch('/api/pages/versions?limit=1&depth=0')
if (versions.status === 200 && /"docs"\s*:\s*\[\s*\{/.test(versions.text)) {problems.push('/api/pages/versions lists versions to an anonymous visitor')}
return problems.length ? bad(problems.join('; ')) : ok('accounts, submissions, preferences, drafts and versions stay closed to a where query')
},
title: 'an anonymous where / draft / versions query reads no accounts, submissions or drafts',
},
{
id: 'graphql',
class: 'access control (GraphQL)',
live: true,
run: async ({ fetch }) => {
const post = (query: string) => fetch('/api/graphql', { body: JSON.stringify({ query }), headers: { 'content-type': 'application/json' }, method: 'POST' })
const intro = await post('{ __schema { types { name } } }')
if (intro.status === 404) {return skip('no GraphQL route')}
if (intro.status === 200 && /"__schema"\s*:\s*\{/.test(intro.text)) {return bad('introspection answers in production: the whole schema is public')}
const syntax = await post('{ Pages(where: { ')
if (syntax.status >= 500 || LEAK.test(syntax.text)) {return bad(`a broken query answers ${syntax.status}${LEAK.test(syntax.text) ? ' with a stack trace' : ''}`)}
const get = await fetch(`/api/graphql?query=${encodeURIComponent('mutation { __typename }')}`)
if (get.status === 200 && /"data"\s*:\s*\{\s*"__typename"/.test(get.text)) {return bad('a mutation runs over GET (CSRF: a link or <img> can run it with the visitor\'s cookie)')}
const users = await post('{ Users(limit: 1) { docs { email } } }')
if (users.status === 200 && /"email"\s*:\s*"/.test(users.text)) {return bad('an anonymous GraphQL query lists account e-mails')}
return ok('no introspection, no stack traces, no mutation over GET, no accounts')
},
title: 'GraphQL: no introspection in production, no mutation over GET, no accounts, no stack traces',
},
{
id: 'error-leak',
class: 'information disclosure (errors)',
live: true,
run: async ({ fetch }) => {
const paths = ['/api/pages/%27%22%3C%3E', '/api/pages?where[id][equals]=not-an-id', '/api/pages?depth=abc&limit=-1', '/api/pages?where[title][like][$regex]=.*', '/api/users/me', '/api/globals/does-not-exist', '/does-not-exist-%00']
const problems: string[] = []
for (const path of paths) {
const a = await fetch(path)
if (a.status >= 500) {problems.push(`${path} → ${a.status}`)}
if (LEAK.test(a.text)) {problems.push(`${path}: stack trace or server path in the answer`)}
}
return problems.length ? bad(problems.join('; ')) : ok(`${paths.length} malformed requests answered without a 500 or a stack trace`)
},
title: 'malformed ids, sorts, depths and operators give a 4xx without a stack trace',
},
{
id: 'sort-operator',
class: 'injection (operators in sort)',
finding: 'F5',
live: true,
run: async ({ fetch }) => {
const problems: string[] = []
for (const sort of ['%24where', '-%24where', '%24natural', 'title.%24ne']) {
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')
},
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')
if (a.status !== 200) {return skip(`/api/pages answers ${describe(a)}`)}
let body: { limit?: number } = {}
try {
body = JSON.parse(a.text) as typeof body
} 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}`)
},
title: 'a public list caps limit (and depth) so one request cannot read a whole collection',
},
{
id: 'image-optimizer',
class: 'SSRF / image optimizer',
live: true,
run: async ({ fetch }) => {
const problems: string[] = []
for (const url of ['http://169.254.169.254/latest/meta-data/', 'http://127.0.0.1:22/', `https://${EVIL}/x.png`, '//evil.example/x.png', '/api/media/file/x.svg']) {
const a = await fetch(`/_next/image?url=${encodeURIComponent(url)}&w=64&q=75`)
if (a.status === 200 && !/^image\/(?:png|jpe?g|webp|avif|gif)/.test(a.headers.get('content-type') ?? '')) {problems.push(`${url} → 200 ${a.headers.get('content-type')}`)}
if (a.status === 200 && /169\.254|127\.0\.0\.1|evil\.example/.test(url)) {problems.push(`${url} → 200: the optimizer fetched it`)}
// a missing local file is a 500 from Next's optimizer (it reports the upstream 404 so): not a door
if (a.status >= 500 && !url.startsWith('/api/media/')) {problems.push(`${url} → ${a.status}`)}
}
return problems.length ? bad(problems.join('; ')) : ok('inner addresses, foreign hosts and SVG are refused')
},
title: '/_next/image refuses inner addresses, unlisted hosts and SVG',
},
{
id: 'headers-everywhere',
class: 'security headers',
live: true,
run: async ({ fetch, page = '/' }) => {
const missing: string[] = []
for (const path of [page, '/this-page-does-not-exist-iapl', '/api/health', '/api/pages?limit=1', '/admin/login']) {
const a = await fetch(path, { follow: true })
if (!a.status) {continue}
const h = a.headers
const lacks = [
...(/nosniff/i.test(h.get('x-content-type-options') ?? '') ? [] : ['nosniff']),
...(h.get('x-frame-options') || /frame-ancestors/.test(h.get('content-security-policy') ?? '') ? [] : ['frame protection']),
...(h.get('x-powered-by') ? [`X-Powered-By: ${h.get('x-powered-by')}`] : []),
]
if (lacks.length) {missing.push(`${path}: ${lacks.join(', ')}`)}
}
return missing.length ? bad(missing.join('; ')) : ok()
},
title: 'pages, the 404 page, the API and the admin all carry nosniff and frame protection, no X-Powered-By',
},
{
id: 'methods',
class: 'unexpected methods',
live: true,
run: async ({ fetch, page = '/' }) => {
const problems: string[] = []
for (const method of ['TRACE', 'PUT', 'DELETE', 'PATCH']) {
const a = await fetch(page, { method })
if (a.status >= 500) {problems.push(`${method} ${page} → ${a.status}`)}
if (method === 'TRACE' && a.status === 200 && /TRACE \//.test(a.text)) {problems.push('TRACE echoes the request')}
}
const action = await fetch(page, { body: '[]', headers: { 'content-type': 'text/plain;charset=UTF-8', 'next-action': '0'.repeat(42) }, method: 'POST' })
if (action.status >= 500 || LEAK.test(action.text)) {problems.push(`an unknown Server Action id → ${action.status}`)}
return problems.length ? bad(problems.join('; ')) : ok()
},
title: 'TRACE / PUT / DELETE on a page and an unknown Server Action id give no 500',
},
{
id: 'body-size',
class: 'denial of service (body size)',
live: false,
run: async ({ fetch }) => {
const problems: string[] = []
const big = JSON.stringify({ email: '[email protected]', pad: 'x'.repeat(8 * 1024 * 1024), password: 'x' })
for (const path of ['/api/ipal/consent', '/api/csp-report', '/api/mcp', '/api/users/login', '/api/graphql']) {
const a = await fetch(path, { body: big, headers: { 'content-type': 'application/json' }, method: 'POST' })
if (a.status === 404 || a.status === 405) {continue}
if (a.status >= 500 || a.status === 0) {problems.push(`${path} → ${describe(a)} after ${a.ms} ms`)}
else if (a.ms > 5000) {problems.push(`${path} took ${a.ms} ms for an 8 MB body`)}
}
return problems.length ? bad(problems.join('; ')) : ok('8 MB bodies refused or answered quickly')
},
title: 'an 8 MB body to the public POST routes is refused quickly, never a 500',
},
]
/** Plain-fetch context for a site. */
export function createProbeContext(base: string, options: { page?: string; secrets?: string[]; timeoutMs?: number; userAgent?: string } = {}): ProbeContext {
const origin = base.replace(/\/+$/, '')
return {
base: origin,
fetch: async (path, init = {}) => {
const started = Date.now()
try {
const res = await fetch(origin + path, {
body: init.body,
headers: { 'user-agent': options.userAgent ?? 'iapl-doctor probes (read-only)', ...init.headers },
method: init.method ?? 'GET',
redirect: init.follow ? 'follow' : 'manual',
signal: AbortSignal.timeout(options.timeoutMs ?? 20_000),
})
const text = init.method === 'HEAD' ? '' : await res.text()
return { headers: res.headers, ms: Date.now() - started, status: res.status, text }
} catch (err) {
const e = err as { cause?: { code?: string }; message?: string }
return { error: e.cause?.code ?? e.message ?? 'unreachable', headers: new Headers(), ms: Date.now() - started, status: 0, text: '' }
}
},
page: options.page,
secrets: options.secrets,
}
}
/** Runs the probes (default: those safe on a live site) and returns each result. */
export async function runAttackProbes(ctx: ProbeContext, probes: AttackProbe[] = ATTACK_PROBES.filter((p) => p.live)): Promise<Array<{ probe: AttackProbe; result: ProbeResult }>> {
const out: Array<{ probe: AttackProbe; result: ProbeResult }> = []
for (const probe of probes) {
let result: ProbeResult
try {
result = await probe.run(ctx)
} catch (err) {
result = bad(`probe crashed: ${err instanceof Error ? err.message : String(err)}`)
}
out.push({ probe, result })
}
return out
}