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,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