fix(security): 선언한 CSP가 unsafe 출처를 허용하면 check:browser-security가 실패한다

config/hosting/security-headers.json의 Content-Security-Policy는 hosting
fixture가 복사하고 verify-hosting-headers가 둘을 대조한다. 그러나 정책이
무엇을 허용하는지 보는 검사는 없다. script-src에 'unsafe-inline'을 넣은
선언도 모든 게이트를 지난다.

고른 방법: scripts/lib/csp-policy.ts의 cspPolicyProblems가 code 지시어
(default-src, script-src*, style-src*, object-src)의 'unsafe-inline'·
'unsafe-eval'·*와 script 계열의 scheme 통째 허용(https:)을 거절하고,
script-src·default-src가 없는 정책도 거절한다. check:browser-security
(FE-GATE-013)가 선언 파일에 부른다. 버린 대안: fixture를 선언에서 만들기
(대조 검사가 이미 같은 값을 지킨다. 허용 내용은 여전히 안 본다).

위험·한계: 제품이 인라인 스크립트가 필요한 CSP로 바꾸면 이 검사가
막는다. 그때는 nonce·hash로 바꾼다. connect-src의 https:는 보지 않는다
(스크립트 실행이 아니다).

검증: tests/unit/csp-policy.test.ts가 고치기 전에는 모듈이 없어 실패하고
고친 뒤 통과한다(desktop, PR 본문). check:browser-security는
`parts FE-GATE-013` 뒤 명령으로 돈다.

Refs: 0929/13-04
This commit is contained in:
DongHyeonka
2026-11-12 22:58:12 +09:00
parent 2f021aa020
commit 9f469b6065
3 changed files with 108 additions and 3 deletions
+22 -3
View File
@@ -1,6 +1,8 @@
import { readdir } from "node:fs/promises";
import { readdir, readFile } from "node:fs/promises";
import { spawnSync } from "node:child_process";
import { cspPolicyProblems } from "./lib/csp-policy.ts";
function requiredPnpmCli(): string {
const executable = process.env.npm_execpath;
if (!executable) {
@@ -35,15 +37,32 @@ const forbidden = runPnpm([
const distFiles = await readdir("dist", { recursive: true });
const publicSourceMaps = distFiles.filter((file) => String(file).endsWith(".map"));
if (allowed.status !== 0 || forbidden.status === 0 || publicSourceMaps.length > 0) {
const SECURITY_HEADERS = "config/hosting/security-headers.json";
const declared = (
JSON.parse(await readFile(SECURITY_HEADERS, "utf8")) as { headers?: Record<string, string> }
).headers?.["Content-Security-Policy"];
const cspProblems =
declared === undefined ? ["no Content-Security-Policy header"] : cspPolicyProblems(declared);
if (
allowed.status !== 0 ||
forbidden.status === 0 ||
publicSourceMaps.length > 0 ||
cspProblems.length > 0
) {
process.stderr.write(allowed.stderr || allowed.stdout);
process.stderr.write(forbidden.stderr || forbidden.stdout);
if (publicSourceMaps.length > 0) {
process.stderr.write(`Public source maps found: ${publicSourceMaps.join(", ")}\n`);
}
if (cspProblems.length > 0) {
process.stderr.write(
`${SECURITY_HEADERS} Content-Security-Policy: ${cspProblems.join("; ")}\n`,
);
}
process.exit(1);
}
process.stdout.write(
"Browser security fixtures: injection rejected, public source maps absent\n",
"Browser security fixtures: injection rejected, public source maps absent, declared CSP allows no unsafe source\n",
);
+43
View File
@@ -0,0 +1,43 @@
/**
* 0929/13-04. What the declared Content-Security-Policy
* (config/hosting/security-headers.json) may not allow. The hosting fixtures
* copy it and scripts/verify-hosting-headers.ts compares them; this reads what
* it allows. check:browser-security (FE-GATE-013) runs it.
*/
const UNSAFE_SOURCES = new Set(["'unsafe-inline'", "'unsafe-eval'", "*"]);
/** Directives whose sources decide what script or plugin code may run or style may apply. */
const CODE_DIRECTIVES = new Set([
"default-src",
"script-src",
"script-src-elem",
"script-src-attr",
"style-src",
"style-src-elem",
"style-src-attr",
"object-src",
]);
/** A scheme-only source (`https:`) lets any host on it run script. */
const SCHEME_ONLY = /^[a-z][a-z0-9+.-]*:$/u;
const SCRIPT_DIRECTIVES = new Set(["default-src", "script-src", "script-src-elem", "object-src"]);
export function cspPolicyProblems(policy: string): string[] {
const directives = new Map<string, readonly string[]>();
for (const part of policy.split(";")) {
const [name, ...sources] = part.trim().split(/\s+/u);
if (name) directives.set(name.toLowerCase(), sources);
}
const problems: string[] = [];
if (!directives.has("script-src") && !directives.has("default-src")) {
problems.push("no script-src and no default-src");
}
for (const [name, sources] of directives) {
if (!CODE_DIRECTIVES.has(name)) continue;
for (const source of sources) {
if (UNSAFE_SOURCES.has(source)) problems.push(`${name} allows ${source}`);
else if (SCRIPT_DIRECTIVES.has(name) && SCHEME_ONLY.test(source)) {
problems.push(`${name} allows the whole scheme ${source}`);
}
}
}
return problems;
}
+43
View File
@@ -0,0 +1,43 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { cspPolicyProblems } from "../../scripts/lib/csp-policy.ts";
/**
* 0929/13-04. The hosting fixtures copy the declared policy and a check
* compares them, but nothing read what the policy allows: a declaration with
* 'unsafe-inline' in script-src passed every gate.
*/
const DECLARED = (
JSON.parse(readFileSync("config/hosting/security-headers.json", "utf8")) as {
headers: Record<string, string>;
}
).headers["Content-Security-Policy"] ?? "";
describe("cspPolicyProblems", () => {
it("accepts the declared policy", () => {
expect(DECLARED).not.toBe("");
expect(cspPolicyProblems(DECLARED)).toEqual([]);
});
it.each([
["script-src 'self' 'unsafe-inline'", "script-src allows 'unsafe-inline'"],
["script-src 'self' 'unsafe-eval'", "script-src allows 'unsafe-eval'"],
["script-src *", "script-src allows *"],
["script-src 'self' https:", "script-src allows the whole scheme https:"],
["style-src 'self' 'unsafe-inline'", "style-src allows 'unsafe-inline'"],
["object-src *", "object-src allows *"],
])("refuses %s", (directive, problem) => {
const policy = DECLARED.split(/;\s*/u)
.filter((part) => !part.startsWith(directive.slice(0, directive.indexOf(" "))))
.concat(directive)
.join("; ");
expect(cspPolicyProblems(policy)).toContain(problem);
});
it("refuses a policy without script-src or default-src", () => {
expect(cspPolicyProblems("img-src 'self'")).toContain("no script-src and no default-src");
});
});