From 2f021aa020ece128ec5cf54b380ed9012c9e2556 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:58:12 +0900 Subject: [PATCH 1/3] =?UTF-8?q?build(deps):=20=EC=9E=AC=EA=B2=80=ED=86=A0?= =?UTF-8?q?=20=EC=A1=B0=EA=B1=B4=EC=9D=84=20=EB=84=98=EA=B8=B4=20=EC=B5=9C?= =?UTF-8?q?=EC=86=8C=20=EA=B3=B5=EA=B0=9C=20=EA=B2=BD=EA=B3=BC=20=EC=98=88?= =?UTF-8?q?=EC=99=B8=20=EB=84=B7=EC=9D=84=20=EC=A7=80=EC=9A=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pnpm-workspace.yaml의 minimumReleaseAgeExclude 넷(@playwright/test, playwright, playwright-core 1.62.0, eslint 10.8.0)은 2026-07-25에 그 버전이 최소 공개 경과 기간보다 어릴 때 더했다. 주석이 적은 제거 조건("설정한 최소 경과 기간보다 오래되면 지운다")을 몇 달 전에 넘겼다. 남은 예외는 같은 버전의 다른 출처가 생겨도 지연 검사를 건너뛰게 한다. 고른 방법: 넷과 그 주석을 지운다. 버전 고정(package.json exact pin)은 그대로다. 버린 대안: 주석만 고치기(예외가 할 일이 없다). 위험·한계: 이 버전들을 다시 받을 때 pnpm이 지연 검사를 한다. 이미 하루 넘게 지난 버전이라 설치는 바뀌지 않는다. 검증: FE-GATE-001(verify:lockfile)과 tests/unit/pnpm-install-policy.test.ts, desktop의 frozen-lockfile 오프라인 설치(PR 본문). RED 없음 — 설정 정리라 동작이 바뀌지 않는다. Refs: 1112/07-02 --- pnpm-workspace.yaml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index ade8c8d4..6912a8e0 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -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 From 9f469b6065416f0eca97ae7696c0a8e3d6acc541 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:58:12 +0900 Subject: [PATCH 2/3] =?UTF-8?q?fix(security):=20=EC=84=A0=EC=96=B8?= =?UTF-8?q?=ED=95=9C=20CSP=EA=B0=80=20unsafe=20=EC=B6=9C=EC=B2=98=EB=A5=BC?= =?UTF-8?q?=20=ED=97=88=EC=9A=A9=ED=95=98=EB=A9=B4=20check:browser-securit?= =?UTF-8?q?y=EA=B0=80=20=EC=8B=A4=ED=8C=A8=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- scripts/check-browser-security.ts | 25 +++++++++++++++--- scripts/lib/csp-policy.ts | 43 +++++++++++++++++++++++++++++++ tests/unit/csp-policy.test.ts | 43 +++++++++++++++++++++++++++++++ 3 files changed, 108 insertions(+), 3 deletions(-) create mode 100644 scripts/lib/csp-policy.ts create mode 100644 tests/unit/csp-policy.test.ts diff --git a/scripts/check-browser-security.ts b/scripts/check-browser-security.ts index ba8acb51..b27fe808 100644 --- a/scripts/check-browser-security.ts +++ b/scripts/check-browser-security.ts @@ -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 } +).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", ); diff --git a/scripts/lib/csp-policy.ts b/scripts/lib/csp-policy.ts new file mode 100644 index 00000000..126d02e5 --- /dev/null +++ b/scripts/lib/csp-policy.ts @@ -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(); + 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; +} diff --git a/tests/unit/csp-policy.test.ts b/tests/unit/csp-policy.test.ts new file mode 100644 index 00000000..61443f6c --- /dev/null +++ b/tests/unit/csp-policy.test.ts @@ -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; + } +).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"); + }); +}); From afcd248780e13c545f7138b43f92ce4c9d53db44 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 00:12:23 +0900 Subject: [PATCH 3/3] =?UTF-8?q?fix(security):=20CSP=20=EA=B2=80=EC=82=AC?= =?UTF-8?q?=EA=B0=80=20=EB=B8=8C=EB=9D=BC=EC=9A=B0=EC=A0=80=EC=B2=98?= =?UTF-8?q?=EB=9F=BC=20=EC=9D=BD=EA=B3=A0=20hosting=20fixture=EA=B0=80=20?= =?UTF-8?q?=EC=84=A0=EC=96=B8=EC=9D=84=20=EB=B3=B5=EC=82=AC=ED=95=98?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 앞 커밋 뒤 확인 리뷰가 셋을 찾았다. - 같은 지시어가 두 번이면 검사는 뒤 값을, 브라우저는 앞 값을 쓴다(CSP3). 키워드도 대소문자를 가려 비교한다. 그래서 `script-src 'self' 'unsafe-inline'; script-src 'self'`와 `'Unsafe-Inline'`이 통과한다. - 0929/13-04 완료 기준 「CSP를 바꿀 때 한 파일만 고친다」가 안 됐다. hosting fixture가 선언한 보안 header 일곱을 표면 넷에 그대로 복사한다. - check:browser-security가 검사를 부르는 연결을 지키는 시험이 없다. 고른 방법: 지시어는 첫 것만, 이름과 키워드는 소문자로 읽는다. 선언 문서를 읽는 declaredCspProblems를 두고 check:browser-security가 그것을 부른다. check:security:fixtures(FE-GATE-029)가 거절 fixture(대소문자를 바꾼 'unsafe-inline'이 앞 script-src에 있음)를 거절하고 선언을 받는지 본다. hosting fixture에서 보안 header를 지우고, verify-hosting-headers의 fixture 모드는 보안 header가 필요한 표면에 선언을 답으로 채운다. fixture가 적은 값은 그대로 host의 답으로 비교한다. 버린 대안: fixture를 선언에서 생성하는 스크립트(생성물이 하나 더 생기고 대조할 것은 같다). 위험·한계: fixture 모드의 보안 header 비교는 선언끼리의 비교가 된다. 전에도 fixture 모드는 UNVERIFIED였다(live 모드만 host를 본다). 검증: csp-policy.test.ts 새 시험(브라우저처럼 읽기 다섯, 뒤 지시어 무시, declaredCspProblems 넷)과 hosting-probe.test.ts 새 시험 둘(선언만 바꾼 뒤 fixture 통과, fixture가 적은 header는 비교)을 고치기 전 코드에서 RED로 보고 desktop에서 GREEN·FE-GATE-029를 돌린다(PR 본문). Refs: 0929/13-04 --- docs/security/browser-boundary.md | 6 +++ scripts/check-browser-security.ts | 8 +--- scripts/check-security-fixtures.ts | 4 +- scripts/lib/csp-policy.ts | 37 ++++++++++++++++--- scripts/lib/security-fixture-check.ts | 24 ++++++++++++ scripts/verify-hosting-headers.ts | 15 +++++++- tests/fixtures/hosting/response-headers.json | 32 ++-------------- .../csp/rejected-security-headers.json | 5 +++ tests/unit/csp-policy.test.ts | 34 ++++++++++++++++- tests/unit/hosting-probe.test.ts | 30 +++++++++++++++ 10 files changed, 153 insertions(+), 42 deletions(-) create mode 100644 tests/fixtures/security/csp/rejected-security-headers.json diff --git a/docs/security/browser-boundary.md b/docs/security/browser-boundary.md index c957d0a6..1d193c80 100644 --- a/docs/security/browser-boundary.md +++ b/docs/security/browser-boundary.md @@ -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 오류가 나면 실패한다(리뷰 13-08). zod는 첫 object schema에서 `Function("")`을 시험 삼아 diff --git a/scripts/check-browser-security.ts b/scripts/check-browser-security.ts index b27fe808..0791f6cf 100644 --- a/scripts/check-browser-security.ts +++ b/scripts/check-browser-security.ts @@ -1,7 +1,7 @@ import { readdir, readFile } from "node:fs/promises"; import { spawnSync } from "node:child_process"; -import { cspPolicyProblems } from "./lib/csp-policy.ts"; +import { declaredCspProblems } from "./lib/csp-policy.ts"; function requiredPnpmCli(): string { const executable = process.env.npm_execpath; @@ -38,11 +38,7 @@ const distFiles = await readdir("dist", { recursive: true }); const publicSourceMaps = distFiles.filter((file) => String(file).endsWith(".map")); const SECURITY_HEADERS = "config/hosting/security-headers.json"; -const declared = ( - JSON.parse(await readFile(SECURITY_HEADERS, "utf8")) as { headers?: Record } -).headers?.["Content-Security-Policy"]; -const cspProblems = - declared === undefined ? ["no Content-Security-Policy header"] : cspPolicyProblems(declared); +const cspProblems = declaredCspProblems(await readFile(SECURITY_HEADERS, "utf8")); if ( allowed.status !== 0 || diff --git a/scripts/check-security-fixtures.ts b/scripts/check-security-fixtures.ts index f46417ea..6018ef6b 100644 --- a/scripts/check-security-fixtures.ts +++ b/scripts/check-security-fixtures.ts @@ -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", ); diff --git a/scripts/lib/csp-policy.ts b/scripts/lib/csp-policy.ts index 126d02e5..c66b8fad 100644 --- a/scripts/lib/csp-policy.ts +++ b/scripts/lib/csp-policy.ts @@ -1,8 +1,9 @@ /** * 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. + * (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. */ @@ -20,12 +21,24 @@ const CODE_DIRECTIVES = new Set([ 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[] { +/** + * 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 { const directives = new Map(); for (const part of policy.split(";")) { const [name, ...sources] = part.trim().split(/\s+/u); - if (name) directives.set(name.toLowerCase(), sources); + 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"); @@ -41,3 +54,17 @@ export function cspPolicyProblems(policy: string): string[] { } 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 }; + 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"]; +} diff --git a/scripts/lib/security-fixture-check.ts b/scripts/lib/security-fixture-check.ts index ee378bce..943bc2a4 100644 --- a/scripts/lib/security-fixture-check.ts +++ b/scripts/lib/security-fixture-check.ts @@ -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 { + 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("; ")}`); + } +} diff --git a/scripts/verify-hosting-headers.ts b/scripts/verify-hosting-headers.ts index d46073d5..7ec12a74 100644 --- a/scripts/verify-hosting-headers.ts +++ b/scripts/verify-hosting-headers.ts @@ -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]; diff --git a/tests/fixtures/hosting/response-headers.json b/tests/fixtures/hosting/response-headers.json index 6d301ac4..a83573cb 100644 --- a/tests/fixtures/hosting/response-headers.json +++ b/tests/fixtures/hosting/response-headers.json @@ -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", diff --git a/tests/fixtures/security/csp/rejected-security-headers.json b/tests/fixtures/security/csp/rejected-security-headers.json new file mode 100644 index 00000000..d54672a4 --- /dev/null +++ b/tests/fixtures/security/csp/rejected-security-headers.json @@ -0,0 +1,5 @@ +{ + "headers": { + "content-security-policy": "default-src 'self'; script-src 'self' 'Unsafe-Inline'; script-src 'self'; object-src 'none'" + } +} diff --git a/tests/unit/csp-policy.test.ts b/tests/unit/csp-policy.test.ts index 61443f6c..cc105793 100644 --- a/tests/unit/csp-policy.test.ts +++ b/tests/unit/csp-policy.test.ts @@ -2,7 +2,7 @@ import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import { cspPolicyProblems } from "../../scripts/lib/csp-policy.ts"; +import { cspPolicyProblems, declaredCspProblems } from "../../scripts/lib/csp-policy.ts"; /** * 0929/13-04. The hosting fixtures copy the declared policy and a check @@ -40,4 +40,36 @@ describe("cspPolicyProblems", () => { 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); + }); }); diff --git a/tests/unit/hosting-probe.test.ts b/tests/unit/hosting-probe.test.ts index bf2484db..7d82e34d 100644 --- a/tests/unit/hosting-probe.test.ts +++ b/tests/unit/hosting-probe.test.ts @@ -507,6 +507,7 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () => distFiles: Readonly>, env: Readonly> = {}, editFixture?: (responses: Record>) => void, + editDeclared?: (headers: Record) => 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; + }; + 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"];