merge: PR #31을 합친 검사 브랜치에 넣는다
This commit is contained in:
@@ -7,6 +7,12 @@ production source map.
|
||||
선언된 header 집합은 `config/hosting/security-headers.json`이다. hosting 검증은
|
||||
이 선언과 실제 응답을 비교한다. CSP는 일부러 `unsafe-inline`과 `unsafe-eval`을
|
||||
뺀다. production 코드와 빌드된 asset은 이 기준선에서도 동작해야 한다.
|
||||
`check:browser-security`(FE-GATE-013)는 선언한 CSP가 `'unsafe-inline'`,
|
||||
`'unsafe-eval'`, `*`, script의 scheme 통째 허용(`https:`)을 담으면 실패한다.
|
||||
브라우저처럼 같은 지시어가 두 번이면 앞의 것을 읽고, 키워드의 대소문자를 가리지
|
||||
않는다(`scripts/lib/csp-policy.ts`). hosting fixture
|
||||
(`tests/fixtures/hosting/response-headers.json`)는 이 header를 복사하지 않는다.
|
||||
fixture 모드는 선언을 그대로 답으로 쓰므로 CSP를 바꿀 때 선언 파일 하나만 고친다.
|
||||
`tests/e2e/production-csp.spec.ts`(`test:e2e`의 일부, FE-GATE-008)는 이 header로
|
||||
빌드를 서빙한다. 그리고 `securitypolicyviolation` 이벤트나 console 오류가 나면
|
||||
실패한다(리뷰 0925/13-08). zod는 첫 object schema에서 `Function("")`을 시험 삼아
|
||||
|
||||
@@ -6,13 +6,3 @@ saveExact: true
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
msw: true
|
||||
# 12-07. These exact pins were added on 2026-07-25 (946cf40, f3e105f) while
|
||||
# they were younger than pnpm's minimum release age. An exclusion covers that
|
||||
# exact version only, so a later version is checked again. Owner:
|
||||
# frontend-platform. Revisit: remove an entry when its version is bumped or is
|
||||
# older than the configured minimum release age.
|
||||
minimumReleaseAgeExclude:
|
||||
- '@playwright/test@1.62.0'
|
||||
- playwright-core@1.62.0
|
||||
- playwright@1.62.0
|
||||
- eslint@10.8.0
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { readdir } from "node:fs/promises";
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { declaredCspProblems } from "./lib/csp-policy.ts";
|
||||
|
||||
function requiredPnpmCli(): string {
|
||||
const executable = process.env.npm_execpath;
|
||||
if (!executable) {
|
||||
@@ -35,15 +37,28 @@ 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 cspProblems = declaredCspProblems(await readFile(SECURITY_HEADERS, "utf8"));
|
||||
|
||||
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",
|
||||
);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import {
|
||||
checkDeclaredCspFixtures,
|
||||
checkNonmatchingSecurityIncludeFixture,
|
||||
checkSecurityFixtures,
|
||||
} from "./lib/security-fixture-check.ts";
|
||||
|
||||
await checkNonmatchingSecurityIncludeFixture();
|
||||
await checkSecurityFixtures();
|
||||
await checkDeclaredCspFixtures();
|
||||
process.stdout.write(
|
||||
"Security fixtures: unmatched include rejected; 3 forbidden files detected\n",
|
||||
"Security fixtures: unmatched include rejected; 3 forbidden files detected; unsafe CSP fixture rejected\n",
|
||||
);
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* 0929/13-04. What the declared Content-Security-Policy
|
||||
* (config/hosting/security-headers.json) may not allow.
|
||||
* scripts/verify-hosting-headers.ts compares a host's answer with it; this
|
||||
* reads what it allows. check:browser-security (FE-GATE-013) runs it, and
|
||||
* check:security:fixtures (FE-GATE-029) holds it to a rejected fixture.
|
||||
*/
|
||||
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"]);
|
||||
|
||||
/**
|
||||
* The directives as a browser reads them (CSP3): names and keywords in any
|
||||
* case, and the first of a repeated directive, the later ones ignored.
|
||||
*/
|
||||
function directivesOf(policy: string): Map<string, readonly string[]> {
|
||||
const directives = new Map<string, readonly string[]>();
|
||||
for (const part of policy.split(";")) {
|
||||
const [name, ...sources] = part.trim().split(/\s+/u);
|
||||
const key = name?.toLowerCase();
|
||||
if (key && !directives.has(key)) {
|
||||
directives.set(key, sources.map((source) => source.toLowerCase()));
|
||||
}
|
||||
}
|
||||
return directives;
|
||||
}
|
||||
|
||||
export function cspPolicyProblems(policy: string): string[] {
|
||||
const directives = directivesOf(policy);
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* The problems of the policy a security-headers document (the shape of
|
||||
* config/hosting/security-headers.json) declares, its header name in any case.
|
||||
*/
|
||||
export function declaredCspProblems(securityHeadersJson: string): string[] {
|
||||
const document = JSON.parse(securityHeadersJson) as { headers?: Record<string, unknown> };
|
||||
const policy = Object.entries(document.headers ?? {}).find(
|
||||
([name]) => name.toLowerCase() === "content-security-policy",
|
||||
)?.[1];
|
||||
return typeof policy === "string"
|
||||
? cspPolicyProblems(policy)
|
||||
: ["no Content-Security-Policy header"];
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { declaredCspProblems } from "./csp-policy.ts";
|
||||
|
||||
type ScanResult = Readonly<{
|
||||
error?: Error;
|
||||
status: number | null;
|
||||
@@ -168,3 +170,25 @@ export async function checkNonmatchingSecurityIncludeFixture(
|
||||
await cleanup(directory);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 0929/13-04. The policy check check:browser-security runs rejects its
|
||||
* fixture (a keyword in another case, in the first of two script-src) and
|
||||
* accepts the declared policy.
|
||||
*/
|
||||
export async function checkDeclaredCspFixtures(): Promise<void> {
|
||||
const fixture = "tests/fixtures/security/csp/rejected-security-headers.json";
|
||||
const rejected = declaredCspProblems(await readFile(fixture, "utf8"));
|
||||
const expected = ["script-src allows 'unsafe-inline'"];
|
||||
if (JSON.stringify(rejected) !== JSON.stringify(expected)) {
|
||||
throw new Error(
|
||||
`${fixture}: expected ${expected.join(", ")}; received ${rejected.join(", ") || "no problem"}`,
|
||||
);
|
||||
}
|
||||
const declared = declaredCspProblems(
|
||||
await readFile("config/hosting/security-headers.json", "utf8"),
|
||||
);
|
||||
if (declared.length > 0) {
|
||||
throw new Error(`config/hosting/security-headers.json: ${declared.join("; ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,7 +131,20 @@ if (liveTarget?.passed && !slotEmpty) {
|
||||
const fixture = await readDocument(
|
||||
"tests/fixtures/hosting/response-headers.json",
|
||||
);
|
||||
responses = responseHeaders(fixture.responses);
|
||||
// 0929/13-04. The fixture host answers with the declared security headers
|
||||
// wherever the fixture names none, so a policy change is one file. A value
|
||||
// the fixture names is compared like a host's answer.
|
||||
const declaredAnswer = Object.fromEntries(
|
||||
Object.entries(securityHeaders).map(([header, value]) => [header.toLowerCase(), value]),
|
||||
);
|
||||
responses = Object.fromEntries(
|
||||
Object.entries(responseHeaders(fixture.responses)).map(([surface, headers]) => [
|
||||
surface,
|
||||
recordValue(cacheSurfaces[surface]).securityHeaders === true
|
||||
? { ...declaredAnswer, ...headers }
|
||||
: headers,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const results: ProbeResult[] = [...probeResults];
|
||||
|
||||
+4
-28
@@ -3,33 +3,15 @@
|
||||
"responses": {
|
||||
"index": {
|
||||
"cache-control": "no-cache",
|
||||
"content-type": "text/html; charset=utf-8",
|
||||
"content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests",
|
||||
"strict-transport-security": "max-age=31536000; includeSubDomains",
|
||||
"x-frame-options": "DENY",
|
||||
"referrer-policy": "strict-origin-when-cross-origin",
|
||||
"x-content-type-options": "nosniff",
|
||||
"permissions-policy": "camera=(), microphone=(), geolocation=()"
|
||||
"content-type": "text/html; charset=utf-8"
|
||||
},
|
||||
"runtimeConfig": {
|
||||
"cache-control": "no-store",
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
"content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests",
|
||||
"strict-transport-security": "max-age=31536000; includeSubDomains",
|
||||
"x-frame-options": "DENY",
|
||||
"referrer-policy": "strict-origin-when-cross-origin",
|
||||
"x-content-type-options": "nosniff",
|
||||
"permissions-policy": "camera=(), microphone=(), geolocation=()"
|
||||
"content-type": "application/json; charset=utf-8"
|
||||
},
|
||||
"releaseManifest": {
|
||||
"cache-control": "no-store",
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
"content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests",
|
||||
"strict-transport-security": "max-age=31536000; includeSubDomains",
|
||||
"x-frame-options": "DENY",
|
||||
"referrer-policy": "strict-origin-when-cross-origin",
|
||||
"x-content-type-options": "nosniff",
|
||||
"permissions-policy": "camera=(), microphone=(), geolocation=()"
|
||||
"content-type": "application/json; charset=utf-8"
|
||||
},
|
||||
"hashedAsset": {
|
||||
"cache-control": "public, max-age=31536000, immutable",
|
||||
@@ -38,13 +20,7 @@
|
||||
},
|
||||
"appRoute": {
|
||||
"cache-control": "no-cache",
|
||||
"content-type": "text/html; charset=utf-8",
|
||||
"content-security-policy": "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' https:; font-src 'self'; upgrade-insecure-requests",
|
||||
"strict-transport-security": "max-age=31536000; includeSubDomains",
|
||||
"x-frame-options": "DENY",
|
||||
"referrer-policy": "strict-origin-when-cross-origin",
|
||||
"x-content-type-options": "nosniff",
|
||||
"permissions-policy": "camera=(), microphone=(), geolocation=()"
|
||||
"content-type": "text/html; charset=utf-8"
|
||||
},
|
||||
"serviceWorker": {
|
||||
"cache-control": "no-cache",
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"headers": {
|
||||
"content-security-policy": "default-src 'self'; script-src 'self' 'Unsafe-Inline'; script-src 'self'; object-src 'none'"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { cspPolicyProblems, declaredCspProblems } 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");
|
||||
});
|
||||
|
||||
// round9 confirm review. A browser uses the first of a repeated directive
|
||||
// and reads keywords in any case (CSP3), so the check does too.
|
||||
it.each([
|
||||
["script-src 'self' 'unsafe-inline'; script-src 'self'", "script-src allows 'unsafe-inline'"],
|
||||
["Script-Src 'self' 'unsafe-inline'; script-src 'self'", "script-src allows 'unsafe-inline'"],
|
||||
["script-src 'self' 'Unsafe-Inline'", "script-src allows 'unsafe-inline'"],
|
||||
["script-src 'self' 'UNSAFE-EVAL'", "script-src allows 'unsafe-eval'"],
|
||||
["script-src 'self' HTTPS:", "script-src allows the whole scheme https:"],
|
||||
])("reads %s as a browser does", (policy, problem) => {
|
||||
expect(cspPolicyProblems(policy)).toContain(problem);
|
||||
});
|
||||
|
||||
it("does not read a repeated directive's later sources", () => {
|
||||
expect(cspPolicyProblems("script-src 'self'; script-src 'unsafe-inline'")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// The check check:browser-security runs on config/hosting/security-headers.json.
|
||||
describe("declaredCspProblems", () => {
|
||||
it.each([
|
||||
["the declared file", readFileSync("config/hosting/security-headers.json", "utf8"), []],
|
||||
["a header name in another case", JSON.stringify({ headers: { "content-security-policy": "script-src 'self'" } }), []],
|
||||
["no policy", JSON.stringify({ headers: { "X-Frame-Options": "DENY" } }), ["no Content-Security-Policy header"]],
|
||||
[
|
||||
"an unsafe policy",
|
||||
JSON.stringify({ headers: { "Content-Security-Policy": "script-src 'self' 'unsafe-inline'" } }),
|
||||
["script-src allows 'unsafe-inline'"],
|
||||
],
|
||||
])("reads %s", (_label, text, problems) => {
|
||||
expect(declaredCspProblems(text)).toEqual(problems);
|
||||
});
|
||||
});
|
||||
@@ -507,6 +507,7 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () =>
|
||||
distFiles: Readonly<Record<string, string>>,
|
||||
env: Readonly<Record<string, string>> = {},
|
||||
editFixture?: (responses: Record<string, Record<string, string>>) => void,
|
||||
editDeclared?: (headers: Record<string, string>) => void,
|
||||
) {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "hosting-release-root-"));
|
||||
try {
|
||||
@@ -514,6 +515,14 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () =>
|
||||
for (const file of ["cache-policy.json", "security-headers.json"]) {
|
||||
await copyFile(`config/hosting/${file}`, path.join(root, "config/hosting", file));
|
||||
}
|
||||
if (editDeclared) {
|
||||
const declaredPath = path.join(root, "config/hosting/security-headers.json");
|
||||
const declared = JSON.parse(await readFile(declaredPath, "utf8")) as {
|
||||
headers: Record<string, string>;
|
||||
};
|
||||
editDeclared(declared.headers);
|
||||
await writeFile(declaredPath, JSON.stringify(declared));
|
||||
}
|
||||
await mkdir(path.join(root, "tests/fixtures/hosting"), { recursive: true });
|
||||
await copyFile(
|
||||
"tests/fixtures/hosting/response-headers.json",
|
||||
@@ -590,6 +599,27 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () =>
|
||||
);
|
||||
});
|
||||
|
||||
// 0929/13-04. A policy change is one file: the fixture host answers with
|
||||
// the declared security headers wherever the fixture names none.
|
||||
it("passes the fixture host after only the declared policy changes", async () => {
|
||||
const result = await verify(DIST, {}, undefined, (headers) => {
|
||||
headers["Content-Security-Policy"] = (headers["Content-Security-Policy"] ?? "").replace(
|
||||
"img-src 'self' data:",
|
||||
"img-src 'self' data: https://images.example.test",
|
||||
);
|
||||
});
|
||||
expect(result.failed, result.stderr).toEqual([]);
|
||||
expect(result.mode).toBe("fixture");
|
||||
}, childProcessTimeout(1_931));
|
||||
|
||||
it("still compares a security header the fixture host answers with", async () => {
|
||||
const result = await verify(DIST, {}, (responses) => {
|
||||
responses["index"] = { ...responses["index"], "x-frame-options": "SAMEORIGIN" };
|
||||
});
|
||||
expect(result.failed, result.stderr).toEqual(["index x-frame-options"]);
|
||||
expect(result.status).toBe(1);
|
||||
}, childProcessTimeout(1_931));
|
||||
|
||||
it("fails a hashed asset served without a declared content encoding", async () => {
|
||||
const result = await verify(DIST, {}, (responses) => {
|
||||
delete responses["hashedAsset"]?.["content-encoding"];
|
||||
|
||||
Reference in New Issue
Block a user