security-headers.test.ts (10893B)
1 import { test } from 'node:test'; 2 import assert from 'node:assert/strict'; 3 import { createHash } from 'node:crypto'; 4 import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'; 5 import { execFileSync } from 'node:child_process'; 6 import { tmpdir } from 'node:os'; 7 import path from 'node:path'; 8 import { fileURLToPath } from 'node:url'; 9 import { 10 prepareSecurityHeaders, 11 extractFrameworkStyleAttributes, 12 relayConnectSources, 13 verifySecurityHeaders 14 } from '../../tools/security-headers.mjs'; 15 import { validateRelayPolicy } from '../../src/lib/config/relays.ts'; 16 import { createStaticHarness } from './harness/static.ts'; 17 18 const web = fileURLToPath(new URL('../../', import.meta.url)); 19 const sha = (bytes: Uint8Array) => 20 createHash('sha256').update(bytes).digest('hex'); 21 22 await test('actual compiled announcer extraction rejects missing, altered, duplicate, extra and substituted styles', async () => { 23 const manifest = JSON.parse( 24 await readFile( 25 path.join(web, '.svelte-kit/output/client/.vite/manifest.json'), 26 'utf8' 27 ) 28 ) as Record<string, { name?: string; file: string }>; 29 const navigation = Object.values(manifest).filter( 30 (entry) => entry.name === 'navigation' 31 ); 32 assert.equal(navigation.length, 1); 33 const file = navigation[0].file; 34 const source = await readFile(path.join(web, 'build', file), 'utf8'); 35 const literal = 36 /`(<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="[^"]+"><!><\/div>)`/.exec( 37 source 38 ); 39 assert.ok(literal); 40 assert.equal( 41 extractFrameworkStyleAttributes( 42 file, 43 Buffer.from(source), 44 sha(Buffer.from(source)) 45 ).length, 46 1 47 ); 48 assert.throws( 49 () => 50 extractFrameworkStyleAttributes( 51 file, 52 Buffer.from(source), 53 '0'.repeat(64) 54 ), 55 /security_headers_stale_or_invalid/ 56 ); 57 const positive = 'const announcer = ' + literal[0] + ';'; 58 assert.equal( 59 extractFrameworkStyleAttributes( 60 file, 61 Buffer.from(positive), 62 sha(Buffer.from(positive)) 63 ).length, 64 1 65 ); 66 for (const candidate of [ 67 'const missing = 1;', 68 positive.replace('position: absolute', 'position: fixed'), 69 positive + 'const duplicate = ' + literal[0] + ';', 70 positive + 'const extra = `<div style="position: fixed"></div>`;', 71 positive.replace('position: absolute', 'position: ${value}'), 72 positive + 'const broken = (' 73 ]) 74 assert.throws( 75 () => 76 extractFrameworkStyleAttributes( 77 file, 78 Buffer.from(candidate), 79 sha(Buffer.from(candidate)) 80 ), 81 /security_headers_unreviewed_style_shape/ 82 ); 83 }); 84 85 await test('actual command prepares external evidence, checks freshness and refuses overwrite', async () => { 86 const directory = await realpath( 87 await mkdtemp(path.join(tmpdir(), 'hc headers ')) 88 ); 89 const output = path.join(directory, 'headers.json'); 90 const command = (operation: string, destination = output) => 91 execFileSync( 92 process.execPath, 93 ['tools/security-headers.mjs', operation, destination], 94 { cwd: web, stdio: 'pipe' } 95 ).toString(); 96 try { 97 assert.match(command('prepare'), /qualification remains pending/); 98 assert.match(command('check'), /match the current audited build/); 99 assert.throws(() => command('prepare'), /EEXIST/); 100 assert.throws( 101 () => command('prepare', path.join(web, 'build/headers.json')), 102 /outside the capsule/ 103 ); 104 const candidate: unknown = JSON.parse(await readFile(output, 'utf8')); 105 assert.ok(candidate && typeof candidate === 'object'); 106 Reflect.set(candidate, 'readiness', 'QUALIFIED'); 107 await writeFile(output, JSON.stringify(candidate)); 108 assert.throws(() => command('check'), /security_headers_stale_or_invalid/); 109 } finally { 110 await rm(directory, { recursive: true, force: true }); 111 } 112 }); 113 114 await test('connect-src is exactly the two admitted scopes, detached from caller hints', () => { 115 const policy = validateRelayPolicy( 116 JSON.stringify({ 117 schemaVersion: 1, 118 public: [ 119 { 120 origin: 'wss://one.example.org', 121 read: true, 122 write: false, 123 nip50: false 124 }, 125 { 126 origin: 'wss://shared.example.org', 127 read: false, 128 write: true, 129 nip50: false 130 } 131 ], 132 inbox: [ 133 { origin: 'wss://shared.example.org', read: true, write: true }, 134 { origin: 'wss://two.example.org', read: true, write: false } 135 ], 136 postingEnabled: false, 137 messagingEnabled: false, 138 operatorDenylist: [] 139 }) 140 ); 141 assert.ok(policy); 142 const sources = relayConnectSources(policy); 143 assert.deepEqual(sources, [ 144 'wss://one.example.org', 145 'wss://shared.example.org', 146 'wss://two.example.org' 147 ]); 148 sources.push('wss://hinted.example.org'); 149 assert.deepEqual(relayConnectSources(policy), sources.slice(0, -1)); 150 assert.throws( 151 () => relayConnectSources({ ...policy }), 152 /relay_policy_invalid/ 153 ); 154 }); 155 156 await test('actual audited HTML supplies every exact script hash without unsafe policies', async () => { 157 const prepared = await prepareSecurityHeaders(web); 158 assert.equal(prepared.schema, 'harvestcircle.static_security_headers.v1'); 159 assert.equal( 160 prepared.readiness, 161 'SOURCE_PREPARATION_ONLY_HOST_QUALIFICATION_PENDING' 162 ); 163 assert.equal(Object.keys(prepared.artifacts).length, 59); 164 assert.equal(Object.keys(prepared.inline_scripts).length, 8); 165 assert.deepEqual(prepared.connect_sources, []); 166 const csp = prepared.headers['Content-Security-Policy']; 167 assert.equal(prepared.framework_style_attributes.length, 1); 168 const style = prepared.framework_style_attributes[0]; 169 assert.equal(style.owner, 'svelte-announcer'); 170 assert.equal(style.source_sha256, prepared.artifacts[style.file].sha256); 171 const compiled = await readFile(path.join(web, 'build', style.file), 'utf8'); 172 const attribute = 173 /id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="([^"]+)"/.exec( 174 compiled 175 ); 176 assert.ok(attribute); 177 assert.equal(style.style_sha256, sha(Buffer.from(attribute[1]))); 178 assert.equal( 179 style.csp_hash, 180 "'sha256-" + 181 createHash('sha256').update(attribute[1]).digest('base64') + 182 "'" 183 ); 184 assert.ok(csp.includes("style-src-attr 'unsafe-hashes' " + style.csp_hash)); 185 assert.equal( 186 prepared.compiler_manifest_sha256, 187 sha( 188 await readFile( 189 path.join(web, '.svelte-kit/output/client/.vite/manifest.json') 190 ) 191 ) 192 ); 193 assert.match(csp, /(?:^|; )connect-src 'none'(?:;|$)/); 194 assert.doesNotMatch( 195 csp, 196 /unsafe-inline|unsafe-eval|wasm-unsafe-eval|data:|blob:|https:|wss:|\*/ 197 ); 198 for (const [name, artifact] of Object.entries(prepared.artifacts)) { 199 const bytes = await readFile( 200 new URL('../../build/' + name, import.meta.url) 201 ); 202 assert.equal(artifact.sha256, sha(bytes), name); 203 assert.equal(artifact.bytes, bytes.length, name); 204 if (!name.endsWith('.html')) continue; 205 const scripts = [ 206 ...bytes.toString('utf8').matchAll(/<script>([\s\S]*?)<\/script>/g) 207 ]; 208 assert.equal(scripts.length, 1, name); 209 const hashes = scripts.map( 210 (match) => 211 "'sha256-" + 212 createHash('sha256').update(match[1]).digest('base64') + 213 "'" 214 ); 215 assert.deepEqual(prepared.inline_scripts[name], hashes); 216 for (const hash of hashes) assert.ok(csp.includes(hash), name); 217 } 218 assert.equal(prepared.headers['Referrer-Policy'], 'no-referrer'); 219 assert.equal( 220 prepared.headers['Permissions-Policy'], 221 'camera=(), microphone=(), geolocation=(), payment=(), usb=()' 222 ); 223 for (const directive of [ 224 "frame-ancestors 'none'", 225 "base-uri 'none'", 226 "form-action 'none'", 227 "object-src 'none'", 228 "worker-src 'none'", 229 "img-src 'self'", 230 "font-src 'self'", 231 "style-src 'self'" 232 ]) 233 assert.ok(csp.includes(directive), directive); 234 await verifySecurityHeaders( 235 web, 236 JSON.parse(JSON.stringify(prepared)) as unknown 237 ); 238 }); 239 240 await test('stale, widened or falsely qualified header records are rejected', async () => { 241 const original = await prepareSecurityHeaders(web); 242 for (const poison of [ 243 'headers', 244 'artifact', 245 'script', 246 'style', 247 'manifest', 248 'policy', 249 'qualification' 250 ]) { 251 const candidate = structuredClone(original); 252 if (poison === 'headers') 253 candidate.headers['Content-Security-Policy'] += '; connect-src *'; 254 if (poison === 'artifact') 255 candidate.artifacts['200.html'].sha256 = '0'.repeat(64); 256 if (poison === 'script') candidate.inline_scripts['200.html'] = []; 257 if (poison === 'style') 258 candidate.framework_style_attributes[0].style_sha256 = '0'.repeat(64); 259 if (poison === 'manifest') 260 candidate.compiler_manifest_sha256 = '0'.repeat(64); 261 if (poison === 'policy') 262 candidate.connect_sources.push('wss://hinted.example.org'); 263 if (poison === 'qualification') 264 Reflect.set(candidate, 'readiness', 'QUALIFIED'); 265 await assert.rejects( 266 verifySecurityHeaders(web, candidate), 267 /security_headers_stale_or_invalid/ 268 ); 269 } 270 }); 271 272 await test('actual HTTP serves prepared headers on navigation and real missing-asset failures', async () => { 273 const prepared = await prepareSecurityHeaders(web); 274 const server = await createStaticHarness({ headers: prepared.headers }); 275 try { 276 for (const pathname of [ 277 '/', 278 '/search', 279 '/sell', 280 '/selling', 281 '/messages', 282 '/about', 283 '/privacy', 284 '/products/unsupported-coordinate', 285 '/products/unsupported-coordinate/edit', 286 '/selling/drafts/unknown-draft', 287 '/messages/unknown-conversation' 288 ]) { 289 const response = await fetch(server.url + pathname, { 290 headers: { accept: 'text/html' } 291 }); 292 assert.equal(response.status, 200, pathname); 293 for (const [name, value] of Object.entries(prepared.headers)) 294 assert.equal(response.headers.get(name), value, name); 295 assert.equal(response.headers.get('content-type'), 'text/html'); 296 await response.arrayBuffer(); 297 } 298 for (const pathname of [ 299 '/missing.js', 300 '/missing.css', 301 '/missing.png', 302 '/products/missing.js' 303 ]) { 304 const response = await fetch(server.url + pathname, { 305 headers: { accept: 'text/html' } 306 }); 307 assert.equal(response.status, 404, pathname); 308 assert.equal( 309 response.headers.get('content-security-policy'), 310 prepared.headers['Content-Security-Policy'] 311 ); 312 assert.doesNotMatch(response.headers.get('content-type') ?? '', /html/); 313 assert.equal(await response.text(), ''); 314 } 315 assert.equal((await fetch(server.url, { method: 'POST' })).status, 405); 316 } finally { 317 await server.close(); 318 } 319 assert.deepEqual(server.state(), { listening: false, childProcesses: 0 }); 320 });