Files
ipal-kit/test/securityClasses.test.ts
T

299 lines
20 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. 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'
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 { 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, 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'
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: [{ 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 }
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', () => {
// 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({ rateLimit: false })
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)
})
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/[email protected]#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', () => {
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', () => {
// 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: [{ 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', { 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<string, unknown>, req: Record<string, unknown>, operation = 'read', h = hook) =>
h({ args, collection: { slug: 'pages' }, context: {}, operation, req } as never) as Record<string, unknown>
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({ limit: 0, overrideAccess: true, pagination: false }, visitor)).toEqual({ limit: 0, overrideAccess: true, pagination: false })
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<string, unknown>; 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:[email protected]')).not.toBe(true)
expect(isAllowedUrl('mailto:[email protected]', ['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 })
})
})