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:
co-authored by
Claude Opus 5.5
parent
a416411f01
commit
d2f19095dc
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$comment": "Places in the plugin and the reference site that match a static security rule (src/modules/doctor/rules/securityCode.ts) on purpose. Key: '<rule> <file>' → { count, reason }. test/securityPatterns.test.ts fails on a new place, a raised count or an empty reason; a lowered count is reported so the entry can shrink. Judge a new entry before adding it (security.md → Security suites).",
|
||||
"entries": {
|
||||
"code-override-access src/modules/access/panelRole.ts": { "count": 2, "reason": "counts staff accounts at start / in the doctor; no request data, counts only" },
|
||||
"code-override-access src/modules/access/passwordRule.ts": { "count": 1, "reason": "the password rule looks up the account being changed; the where is built from req.user's id or a string-checked reset token (typeof === 'string'), never an object from the body" },
|
||||
"code-override-access src/modules/access/rolesField.ts": { "count": 1, "reason": "first-account check (is the collection empty?): a count, no data returned" },
|
||||
"code-override-access src/modules/access/selfRegistration.ts": { "count": 3, "reason": "start-time inventory of auth collections (count / admin ids); never reached by a request" },
|
||||
"code-override-access src/modules/consent/consentLog.ts": { "count": 1, "reason": "POST /api/ipal/consent writes the visitor's own record: the collection's create is false over the API on purpose; body capped at 4 KiB, fields whitelisted" },
|
||||
"code-override-access src/modules/consent/scanner/approval.ts": { "count": 3, "reason": "cookie approval endpoint: runs after cookieScanner.access (editor+ with the second factor) has passed" },
|
||||
"code-override-access src/modules/consent/scanner/collection.ts": { "count": 2, "reason": "hooks of the cookie-review collection writing the scanner's own fields (context ipalCookieScan)" },
|
||||
"code-override-access src/modules/consent/scanner/crawl/endpoints.ts": { "count": 2, "reason": "crawl endpoints: after the editor+/second-factor check or the IAPL_COOKIE_SCAN_TOKEN + jobId check" },
|
||||
"code-override-access src/modules/consent/scanner/crawl/ingest.ts": { "count": 2, "reason": "crawler call-back ingest: only after the token and running jobId are checked" },
|
||||
"code-override-access src/modules/consent/scanner/scan.ts": { "count": 3, "reason": "cookie scan endpoint: after cookieScanner.access; writes the scanner's own collection" },
|
||||
"code-override-access src/modules/consent/scanner/sync.ts": { "count": 1, "reason": "copies approved cookies into Cookie settings after the approval check" },
|
||||
"code-override-access src/modules/doctor/status.ts": { "count": 4, "reason": "doctor status: counts and states only (no secrets returned); the endpoint needs IAPL_DOCTOR_TOKEN or doctor.access" },
|
||||
"code-override-access src/modules/email/method.ts": { "count": 1, "reason": "records the sending method chosen in the panel by an admin (the panel action checks the admin first)" },
|
||||
"code-override-access src/modules/email/relay/adapter.ts": { "count": 1, "reason": "reads the site name for the mail sender; no request data" },
|
||||
"code-override-access src/modules/forms/emailLayout.ts": { "count": 1, "reason": "reads the form's e-mail settings (staff-only fields) to send the notification of a submission; the visitor never sees them" },
|
||||
"code-override-access src/modules/hooks/fillEmptyLocales.ts": { "count": 1, "reason": "afterChange hook of a save the editor's own access already allowed; fills empty locales of the same document" },
|
||||
"code-override-access src/modules/security/totp/TwoFactorStatusField.tsx": { "count": 1, "reason": "admin field component: shows the 2FA state of an account the viewer may already open" },
|
||||
"code-override-access src/modules/security/totp/setupRequired.ts": { "count": 5, "reason": "2FA set-up window: start-time backfill, counts, and stamping the signed-in account's own record" },
|
||||
"code-override-access src/modules/stats/admin/loadStats.ts": { "count": 3, "reason": "the stats admin view, behind the stats access rule" },
|
||||
"code-override-access src/modules/stats/endpoint.ts": { "count": 3, "reason": "POST /api/ipal/hit (opt-in stats): writes the visit counters; body capped, fields parsed (stats/parse.ts)" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* 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('<script>')
|
||||
})
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Static security rules (src/modules/doctor/rules/securityCode.ts): each pattern found and not found, the
|
||||
* accept marker, the config checks, the doctor wiring — and the GATE: the plugin's own code and the reference site
|
||||
* hold no place that matches a rule unless test/security-patterns.allow.json judges it.
|
||||
*/
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterAll, describe, expect, test } from 'vitest'
|
||||
|
||||
import { listCodeFiles, scanCode, scanConfigs } from '../src/modules/doctor/rules/securityCode.js'
|
||||
import { runDoctor } from '../src/modules/doctor/run.js'
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..')
|
||||
const rules = (file: string, code: string) => scanCode(file, code).map((h) => h.rule)
|
||||
|
||||
describe('static security rules — each pattern', () => {
|
||||
test('HTML and JSON printed into the page', () => {
|
||||
expect(rules('src/a.tsx', '<div dangerouslySetInnerHTML={{ __html: post.body }} />')).toEqual(['code-inner-html'])
|
||||
expect(rules('src/a.tsx', '<script dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }} />')).toEqual(['code-inner-html'])
|
||||
expect(scanCode('src/a.tsx', '<script dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }} />')[0].message).toMatch(/<\/script>/)
|
||||
expect(rules('src/a.tsx', "<script dangerouslySetInnerHTML={{ __html: JSON.stringify(s).replace(/</g, '\\\\u003c') }} />")).toEqual([])
|
||||
expect(rules('src/a.tsx', '<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />')).toEqual([])
|
||||
expect(rules('src/a.ts', 'el.innerHTML = text')).toEqual(['code-inner-html'])
|
||||
expect(rules('src/a.ts', "el.innerHTML = ''")).toEqual([])
|
||||
expect(rules('src/a.ts', 'el.insertAdjacentHTML("beforeend", x)')).toEqual(['code-inner-html'])
|
||||
})
|
||||
|
||||
test('code from strings and shell commands', () => {
|
||||
expect(rules('src/a.ts', 'eval(code)')).toEqual(['code-eval'])
|
||||
expect(rules('src/a.ts', 'const f = new Function("a", body)')).toEqual(['code-eval'])
|
||||
expect(rules('src/a.ts', 'setTimeout("go()", 10)')).toEqual(['code-eval'])
|
||||
expect(rules('src/a.ts', 'setTimeout(() => go(), 10); retrieval(x)')).toEqual([])
|
||||
expect(rules('src/a.ts', 'execSync(`convert ${file} out.png`)')).toEqual(['code-shell'])
|
||||
expect(rules('src/a.ts', "execFileSync('convert', [file, 'out.png'])")).toEqual([])
|
||||
})
|
||||
|
||||
test('secrets that reach the browser', () => {
|
||||
expect(rules('src/a.ts', 'const k = process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY')).toEqual(['code-public-secret'])
|
||||
expect(rules('src/a.ts', 'const k = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY')).toEqual([])
|
||||
expect(rules('src/a.tsx', "'use client'\nconst s = process.env.PAYLOAD_SECRET")).toEqual(['code-public-secret'])
|
||||
expect(rules('src/a.tsx', 'const s = process.env.PAYLOAD_SECRET')).toEqual([])
|
||||
})
|
||||
|
||||
test('the Local API with access off where a request reaches it', () => {
|
||||
expect(rules('src/app/api/x/route.ts', "await payload.find({ collection: 'orders', overrideAccess: true })")).toEqual(['code-override-access'])
|
||||
expect(rules('src/seed/run.ts', "await payload.find({ collection: 'orders', overrideAccess: true })")).toEqual([])
|
||||
expect(rules('src/app/page.tsx', "await payload.find({ collection: 'orders', user: req.user })")).toEqual(['code-local-api-user'])
|
||||
expect(rules('src/app/page.tsx', "await payload.find({ collection: 'orders', user, overrideAccess: false })")).toEqual([])
|
||||
expect(rules('src/app/page.tsx', "await payload.find({ collection: 'pages', where: { slug: { equals: slug } } })")).toEqual([])
|
||||
})
|
||||
|
||||
test('a where clause from the request', () => {
|
||||
expect(rules('src/app/api/x/route.ts', "payload.find({ collection: 'pages', where: req.query.where })")).toEqual(['code-raw-where'])
|
||||
expect(rules('src/app/api/x/route.ts', "payload.find({ collection: 'pages', where: JSON.parse(searchParams.get('w')) })")).toEqual(['code-raw-where'])
|
||||
expect(rules('src/app/api/x/route.ts', "payload.find({ collection: 'pages', where: { slug: { equals: String(params.slug) } } })")).toEqual([])
|
||||
})
|
||||
|
||||
test('redirects and fetches to an address from the request', () => {
|
||||
expect(rules('src/app/x/page.tsx', "redirect(searchParams.get('next'))")).toEqual(['code-open-redirect'])
|
||||
expect(rules('src/app/x/route.ts', "return NextResponse.redirect(new URL(req.nextUrl.searchParams.get('to'), req.url))")).toEqual(['code-open-redirect'])
|
||||
expect(rules('src/app/x/page.tsx', "redirect('/pl')")).toEqual([])
|
||||
expect(rules('src/app/x/route.ts', 'const r = await fetch(body.url)')).toEqual(['code-ssrf'])
|
||||
expect(rules('src/app/x/route.ts', "const r = await fetch(searchParams.get('u'))")).toEqual(['code-ssrf'])
|
||||
expect(rules('src/app/x/route.ts', "const r = await fetch('https://api.example.com/x', { body: JSON.stringify(body) })")).toEqual([])
|
||||
})
|
||||
|
||||
test('a place accepted with its reason; comments do not count', () => {
|
||||
expect(rules('src/a.tsx', '// iapl-security-ok: escaped by toSafeHtml above\n<div dangerouslySetInnerHTML={{ __html: html }} />')).toEqual([])
|
||||
expect(rules('src/a.ts', 'eval(x) // iapl-security-ok: build-time only')).toEqual([])
|
||||
expect(rules('src/a.ts', '// eval(x) in a comment\n/* new Function() */')).toEqual([])
|
||||
})
|
||||
|
||||
test('config settings that open a door', () => {
|
||||
const next = (code: string) => scanConfigs({ code, file: 'next.config.ts' }, null).map((f) => f.severity)
|
||||
expect(next("images: { dangerouslyAllowSVG: true }")).toEqual(['error'])
|
||||
expect(next("images: { dangerouslyAllowSVG: true, contentSecurityPolicy: \"sandbox\" }")).toEqual([])
|
||||
expect(next("images: { remotePatterns: [{ hostname: '**' }] }")).toEqual(['warning'])
|
||||
expect(next("experimental: { serverActions: { allowedOrigins: ['*'] } }")).toEqual(['error'])
|
||||
const payload = (code: string) => scanConfigs(null, { code, file: 'src/payload.config.ts' }).length
|
||||
expect(payload("cors: '*', debug: true, graphQL: { disableIntrospectionInProduction: false }, maxDepth: 50")).toBe(4)
|
||||
expect(payload('cors: [process.env.NEXT_PUBLIC_SERVER_URL], maxDepth: 10')).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('static security rules — in the doctor', () => {
|
||||
const dirs: string[] = []
|
||||
afterAll(() => {for (const d of dirs) {rmSync(d, { force: true, recursive: true })}})
|
||||
|
||||
test('iapl-doctor --only security reports a project\'s own unsafe code, and an iapl-doctor.json entry silences one file', async () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), 'iapl-sec-'))
|
||||
dirs.push(dir)
|
||||
const files: Record<string, string> = {
|
||||
'package.json': JSON.stringify({ name: 'x', dependencies: {} }),
|
||||
'src/app/(frontend)/[locale]/page.tsx': '<div dangerouslySetInnerHTML={{ __html: page.html }} />',
|
||||
'src/app/api/orders/route.ts': "export const GET = async (req) => Response.json(await payload.find({ collection: 'orders', where: req.query.where, overrideAccess: true }))",
|
||||
'src/seed/index.ts': "await payload.find({ collection: 'orders', overrideAccess: true })",
|
||||
}
|
||||
for (const [rel, content] of Object.entries(files)) {
|
||||
mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true })
|
||||
writeFileSync(path.join(dir, rel), content)
|
||||
}
|
||||
const report = await runDoctor({ offline: true, only: ['code-patterns'], packageRoot: root, root: dir, writeSeen: false })
|
||||
const found = report.findings.filter((f) => !f.silenced).map((f) => `${f.rule} ${f.file}`).sort()
|
||||
expect(found).toEqual([
|
||||
'code-inner-html src/app/(frontend)/[locale]/page.tsx',
|
||||
'code-override-access src/app/api/orders/route.ts',
|
||||
'code-raw-where src/app/api/orders/route.ts',
|
||||
])
|
||||
const silenced = await runDoctor({
|
||||
config: { rules: { 'code-override-access': { files: ['src/app/api/**'], off: true, reason: 'orders are public in this shop' } } },
|
||||
offline: true, only: ['security'], packageRoot: root, root: dir, writeSeen: false,
|
||||
})
|
||||
expect(silenced.findings.find((f) => f.rule === 'code-override-access')?.silenced, JSON.stringify(silenced.findings.map((f) => [f.rule, f.message.slice(0, 80)]))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GATE: the plugin and the reference site hold only judged places', () => {
|
||||
test('every hit is in test/security-patterns.allow.json with a reason, and no count grew', () => {
|
||||
const allow = (JSON.parse(readFileSync(path.join(root, 'test/security-patterns.allow.json'), 'utf8')) as { entries: Record<string, { count: number; reason: string }> }).entries
|
||||
const counts = new Map<string, number>()
|
||||
const where = new Map<string, string[]>()
|
||||
for (const [base, start, prefix] of [[root, 'src', ''], [path.join(root, 'reference'), 'src', 'reference/'], [root, 'bin', ''], [root, 'scripts', '']] as const) {
|
||||
for (const file of listCodeFiles(base, start)) {
|
||||
for (const hit of scanCode(file, readFileSync(path.join(base, file), 'utf8'))) {
|
||||
const key = `${hit.rule} ${prefix}${hit.file}`
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1)
|
||||
where.set(key, [...(where.get(key) ?? []), `${prefix}${hit.file}:${hit.line} ${hit.text}`])
|
||||
}
|
||||
}
|
||||
}
|
||||
const problems: string[] = []
|
||||
for (const [key, n] of counts) {
|
||||
const entry = allow[key]
|
||||
if (!entry) {problems.push(`NOT JUDGED ${key} (${n}):\n ${where.get(key)!.join('\n ')}`)} else if (n > entry.count) {problems.push(`MORE THAN JUDGED ${key}: ${n} > ${entry.count}\n ${where.get(key)!.join('\n ')}`)}
|
||||
}
|
||||
for (const [key, entry] of Object.entries(allow)) {
|
||||
if (!entry.reason?.trim() || /TODO/i.test(entry.reason)) {problems.push(`no reason: ${key}`)}
|
||||
if ((counts.get(key) ?? 0) < entry.count) {console.warn(`[security-patterns] ${key}: ${counts.get(key) ?? 0} now, ${entry.count} judged — lower the count`)}
|
||||
}
|
||||
expect(problems, problems.join('\n')).toEqual([])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user