test(security): smoke the build under the production CSP (13-08)

The declared CSP was never applied in a browser. A Playwright spec now serves
the build with config/hosting/security-headers.json and fails on any
securitypolicyviolation. It found one: zod's Function('') probe, listed in the
spec as a known violation until zod is configured jitless before first use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-25 23:10:59 +09:00
co-authored by Claude Opus 5.5
parent a263d8cc4a
commit 8a0e5f55bb
3 changed files with 119 additions and 1 deletions
@@ -130,6 +130,15 @@ Web Push를 함께 설치하지 않는다.
integration test를 작성한다.
9. runtime config schema, dependency inventory/approval, SBOM, bundle budget,
browser support와 runbook을 갱신한다.
운영 CSP(`config/hosting/security-headers.json`)도 여기서 넓힌다. 기본 CSP는
아래 기능을 막는다(리뷰 13-08).
- 다른 origin의 realtime: `connect-src`에 `wss://<realtime origin>`을 더한다.
`https:`는 `wss:`를 허용하지 않는다(CSP3 scheme 비교).
- 파일 preview(`src/adapters/browser-files/object-url-lease.ts`의 object URL):
`img-src`에 `blob:`을 더한다.
- 이미지 CDN: `img-src`에 CDN origin을 더한다.
바꾼 CSP 아래에서 `tests/e2e/production-csp.spec.ts`가 그 기능의 화면을 열도록
smoke를 늘린다.
10. 실제 provider integration과 negative behavior가 통과한 뒤에만 catalog 상태를
별도 project catalog에서 `INSTALLED`로 바꾼다.
+13 -1
View File
@@ -7,7 +7,19 @@ maps are prohibited defaults.
`config/hosting/security-headers.json` is the declared header set. Hosting
verification compares that declaration with live responses. CSP deliberately
omits `unsafe-inline` and `unsafe-eval`; production code and built assets must
remain compatible with that baseline.
remain compatible with that baseline. `tests/e2e/production-csp.spec.ts` (part of
`test:e2e`, FE-GATE-008) serves the build with these headers and fails on a
`securitypolicyviolation` event (review 13-08). One violation is known and
listed in that spec: zod probes `Function("")` on its first object schema and
the policy refuses it. Parsing still works; the report is noise until zod is
configured `jitless` before the first schema is built. Features that are off by
default need CSP additions when a project selects them; see step 9 in
[optional adapter recipes](../architecture/optional-adapter-recipes.md).
`connect-src 'self' https:` lets script reach any HTTPS origin. Narrowing it to
the runtime config's `API_BASE_URL` and `TELEMETRY_ENDPOINT` origins needs a
header generated per environment at deploy time, because those values are set
per deployment (`scripts/generate-runtime-config.ts`). That generator does not
exist yet; a project that deploys should add it with its provider adapter.
Route guards are UX hints and client validation does not replace backend
authorization or validation.
+97
View File
@@ -0,0 +1,97 @@
import { readFileSync } from "node:fs";
import { expect, test, type ConsoleMessage, type Page } from "@playwright/test";
// 13-08. The Content-Security-Policy in config/hosting/security-headers.json was
// declared but never applied in a browser: `vite preview` sends no security
// headers. This smoke serves the build with the production headers attached
// and fails on any securitypolicyviolation event outside KNOWN_VIOLATIONS.
const { headers: declaredHeaders } = JSON.parse(
readFileSync("config/hosting/security-headers.json", "utf8"),
) as { headers: Record<string, string> };
// The preview server is plain HTTP on loopback. `upgrade-insecure-requests` is a
// no-op for an HTTPS origin, but WebKit applies it to loopback and rewrites
// every same-origin request to https, which this server cannot answer. Every
// other directive is served exactly as declared.
const securityHeaders = {
...declaredHeaders,
"Content-Security-Policy": declaredHeaders["Content-Security-Policy"]!
.split(";")
.map((directive) => directive.trim())
.filter((directive) => directive !== "upgrade-insecure-requests")
.join("; "),
};
/**
* Known violation, not accepted behavior. Zod probes `Function("")` when it
* builds its first object schema, to decide whether it may compile parsers.
* The policy has no 'unsafe-eval', so the probe is refused (zod catches it and
* parses without compiling) and reported on every boot. `z.config({ jitless:
* true })` removes the probe, but it must run before the first schema is
* built, and the bundler evaluates the shared chunks that build schemas before
* the entry module body. Owner: frontend-platform. Remove this entry when zod
* is configured before any schema construction; the test then requires zero
* violations.
*/
const KNOWN_VIOLATIONS = new Set(["script-src eval"]);
function isKnownConsoleViolation(message: ConsoleMessage): boolean {
return /unsafe-eval|JavaScript eval|evaluate a string as JavaScript/u.test(message.text());
}
test.beforeEach(async ({ page, baseURL }) => {
const origin = new URL(baseURL ?? "http://127.0.0.1:4173").origin;
await page.route(
(url) => url.origin === origin,
async (route) => {
const response = await route.fetch();
await route.fulfill({
response,
headers: { ...response.headers(), ...securityHeaders },
});
},
);
await page.addInitScript(() => {
const violations: string[] = [];
Object.defineProperty(window, "__cspViolations", { value: violations });
document.addEventListener("securitypolicyviolation", (event) => {
violations.push(`${event.effectiveDirective} ${event.blockedURI}`);
});
});
});
async function cspViolations(page: Page): Promise<string[]> {
return page.evaluate(() => (window as unknown as { __cspViolations: string[] }).__cspViolations);
}
test("boots and changes route under the production security headers", async ({ page }) => {
const failures: string[] = [];
page.on("console", (message) => {
if (message.type() === "error" && !isKnownConsoleViolation(message)) {
failures.push(`console:${message.text()}`);
}
});
page.on("pageerror", (error) => failures.push(`pageerror:${error.name}`));
page.on("requestfailed", (request) =>
failures.push(`requestfailed:${new URL(request.url()).pathname}:${request.failure()?.errorText ?? ""}`),
);
const response = await page.goto("/");
expect(response?.headers()["content-security-policy"]).toBe(
securityHeaders["Content-Security-Policy"],
);
await expect(page.getByRole("heading", { level: 1 })).toHaveText(
"Clean Architecture Frontend",
);
await page
.getByRole("navigation", { name: "주요 탐색" })
.getByRole("link", { name: "화면 상태" })
.click();
await expect(
page.getByRole("heading", { level: 1, name: "화면 상태" }),
).toBeFocused();
expect((await cspViolations(page)).filter((violation) => !KNOWN_VIOLATIONS.has(violation))).toEqual([]);
expect(failures).toEqual([]);
});