Files
ipal-kit/test/securityClasses.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 d2f19095dc 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]>
2026-12-01 16:46:42 +01:00

171 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Security audit 2026-12: one block per vulnerability class, each asking the plugin's own building blocks with the
* payloads that class is known for (docs/security.md → "Security suites"). The HTTP side of the same classes runs
* against a BUILT site in reference/e2e/attack-probes.spec.ts.
*
* 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.
*/
import { Script } from 'node:vm'
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { adminPathFromReferer } from '../src/modules/branding/signIn/languageEndpoint.js'
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 { createProxy } from '../src/modules/i18n/createProxy.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 { safeAdminBack } from '../src/modules/security/totp/safeBack.js'
import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js'
import { JsonLdGraph } from '../src/modules/seo/JsonLdGraph.js'
import { themeScript } from '../src/modules/theme/theme.js'
/** Strings that end a script, open markup, or run as a URL — the XSS payloads used below. */
const XSS = ['</script><script>alert(1)</script>', '<img src=x onerror=alert(1)>', '"><svg onload=alert(1)>', '
alert(1)//']
const UNSAFE_URLS = ['javascript:alert(1)', 'JaVaScRiPt:alert(1)', ' javascript:alert(1)', 'java\tscript:alert(1)', 'java\nscript:alert(1)', 'data:text/html,<script>alert(1)</script>', 'vbscript:msgbox(1)', '//evil.example/x', '/\\evil.example', '\\\\evil.example']
const chunked = (text: string) => new Request('http://localhost/x', {
body: new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode(text)); c.close() } }),
// @ts-expect-error Node's fetch needs it for a stream body
duplex: 'half',
headers: { 'content-type': 'application/json' },
method: 'POST',
})
describe('XSS — output into HTML, scripts and URLs', () => {
it('JSON-LD: no value can end the <script> (</script>, <!--, U+2028)', () => {
const html = renderToStaticMarkup(createElement(JsonLdGraph, { schemas: XSS.map((name) => ({ name, '@type': 'Thing' })) as never }))
expect(html.match(/<\/script>/gi)).toHaveLength(1)
expect(html).not.toMatch(/<img|<svg|<!--/i)
// what reaches the browser is still the same data
const json = html.replace(/^<script[^>]*>/, '').replace(/<\/script>$/, '')
expect(JSON.stringify(JSON.parse(json))).toContain('</script><script>alert(1)')
})
it('first-paint scripts: a cookie name with </script> stays inside its string', () => {
for (const cookieName of XSS) {
const js = consentDecidedScript({ cookieName })
expect(js).not.toMatch(/<\/script|<img|<svg/i)
expect(() => new Script(js)).not.toThrow() // compiled, never run
}
})
// dev-config input only (the storage key is set in code, not by visitors): hardening, not a finding
it('theme script: the storage key is a JSON string literal', () => {
expect(() => new Script(themeScript({ allowToggle: true, defaultTheme: 'system', storageKey: 'a"b\\c' }))).not.toThrow()
})
it('links: javascript:, data:, protocol-relative and control-character tricks never become an href', () => {
// a link to another host is an editor's right (https://…); only schemes that run script are dropped
for (const url of UNSAFE_URLS.filter((u) => !/^(?:\/\/|\/\\|\\\\)/.test(u))) {expect(safeHref(url), url).toBeNull()}
for (const url of ['https://example.com', '/pl/o-nas', '#top', 'mailto:[email protected]', 'tel:+48123']) {expect(safeHref(url)).toBe(url)}
})
it('rich text: a stored javascript: link loses its URL, keeps its text', () => {
const data = { root: { type: 'root', children: [{ type: 'link', children: [{ type: 'text', text: 'click' }], fields: { linkType: 'custom', url: 'javascript:alert(1)' } }] } }
expect(JSON.stringify(sanitizeRichTextLinks(data))).not.toContain('javascript:')
expect(JSON.stringify(sanitizeRichTextLinks(data))).toContain('click')
})
it('sitemap: a URL with markup is escaped in the XML', () => {
const xml = buildSitemapXml([{ url: 'https://s.pl/a"><script>alert(1)</script>&' } as never])
expect(xml).not.toContain('<script>')
expect(xml).toContain('&lt;script&gt;')
})
})
describe('open redirect and header injection', () => {
it('2FA back link: only a path inside the panel', () => {
for (const back of [...UNSAFE_URLS, 'https://evil.example/admin', '/admin/../../evil', 'https:evil.example']) {
const to = safeAdminBack(back, { adminRoute: '/admin', origin: 'https://site.pl' })
expect(to, back).toMatch(/^\/admin(?:\/|$)/)
expect(to).not.toMatch(/^\/\/|\\/)
}
})
it('admin language link: the way back is a path of this panel, never a host; no CR/LF reaches Location', () => {
for (const referer of ['https://evil.example/admin/x', 'https://site.pl//evil.example', 'https://site.pl/admin\\..\\x', 'https://site.pl/admin/%0d%0aSet-Cookie:x=1', 'not a url', 'javascript:alert(1)']) {
const to = adminPathFromReferer(referer, '/admin')
expect(to, referer).toMatch(/^\/admin(?:\/|$)/)
expect(to).not.toMatch(/[\r\n\\]|^\/\//)
}
})
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 })
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 }
expect(new URL(res.headers.get('location')!).host, p).toBe('site.pl')
}
})
})
describe('injection — prototype pollution and operators in stored or sent JSON', () => {
it('a consent cookie carrying __proto__ / constructor pollutes nothing', () => {
const raw = encodeURIComponent('{"version":1,"__proto__":{"polluted":true},"constructor":{"prototype":{"polluted2":true}},"state":{"analytics":true,"__proto__":{"x":1}}}')
const record = readConsentRecord(raw, 1)
parseConsent(raw, 1)
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
expect(({} as Record<string, unknown>).polluted2).toBeUndefined()
expect(Object.getPrototypeOf(record)).toBe(Object.prototype)
expect(record?.state.analytics).toBe(true)
})
})
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 () => {
const lines: string[] = []
const warn = vi.spyOn(console, 'warn').mockImplementation((...a: unknown[]) => {lines.push(a.join(' '))})
try {
const route = createCspReportRoute()
await route(new Request('http://localhost/api/csp-report', { body: JSON.stringify({ 'csp-report': { 'blocked-uri': 'x\n[iapl] admin signed in: [email protected] 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)
})
})
describe('denial of service — bodies and batches', () => {
it('CSP reports: a chunked body without content-length is cut at the cap (413)', async () => {
const res = await createCspReportRoute({ maxBytes: 1024 })(chunked('x'.repeat(200_000)))
expect(res.status).toBe(413)
})
it('MCP: a body over the cap is 413 and a batch over the cap is refused before any database work', async () => {
const getCachedPayload = vi.fn()
const { POST } = createMcpRoute({ config: { defaultLocale: 'pl', locales: ['pl'] } as never, getCachedPayload, rateLimit: false } as never)
expect((await POST(chunked(`[${'1,'.repeat(40_000)}1]`))).status).toBe(413)
const batch = Array.from({ length: 11 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'tools/list' }))
expect((await POST(new Request('http://localhost/api/mcp', { body: JSON.stringify(batch), method: 'POST' }))).status).toBe(400)
expect(getCachedPayload).not.toHaveBeenCalled()
})
})
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)', () => {
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 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 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)
})
})