Files
clean-architecture-frontend…/scripts/verify-hosting-headers.ts
T
DongHyeonka afcd248780
frontend-quality-gates / merge / tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / browser tests (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Canceled after 0s
frontend-quality-gates / external-vulnerability-provider (pull_request) Canceled after 0s
frontend-quality-gates / external-provenance-provider (pull_request) Canceled after 0s
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Canceled after 0s
frontend-quality-gates / deploy-promoted-release (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Canceled after 0s
frontend-quality-gates / main / checker self-tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / static checks (pull_request) Canceled after 51s
fix(security): CSP 검사가 브라우저처럼 읽고 hosting fixture가 선언을 복사하지 않는다
앞 커밋 뒤 확인 리뷰가 셋을 찾았다.

- 같은 지시어가 두 번이면 검사는 뒤 값을, 브라우저는 앞 값을 쓴다(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
2026-11-13 00:12:23 +09:00

255 lines
9.3 KiB
TypeScript

import { mkdir, readFile, readdir } from "node:fs/promises";
import path from "node:path";
import { INSTALLED_RUNTIME_CAPABILITIES } from "../src/features/installed-runtime-capabilities.ts";
import { hostingHeadersArtifactSchema } from "./contracts/release-artifacts.ts";
import {
checkPublicServiceWorkers,
classifyLiveHostingBaseUrl,
hostingVerdict,
probeLiveHosting,
releaseIdentity,
shipsServiceWorker,
type HostingMode,
type ProbeResult,
type ResponseHeaders,
} from "./lib/hosting-probe.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
type Document = Record<string, unknown>;
function isRecord(value: unknown): value is Document {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function recordValue(value: unknown): Document {
return isRecord(value) ? value : {};
}
function strings(value: unknown): string[] {
return Array.isArray(value)
? value.filter((entry): entry is string => typeof entry === "string")
: [];
}
function stringRecord(value: unknown): Record<string, string> {
return Object.fromEntries(
Object.entries(recordValue(value)).filter(
(entry): entry is [string, string] => typeof entry[1] === "string",
),
);
}
function responseHeaders(value: unknown): ResponseHeaders {
return Object.fromEntries(
Object.entries(recordValue(value)).map(([surface, headers]) => [
surface,
stringRecord(headers),
]),
);
}
async function readDocument(file: string): Promise<Document> {
const parsed: unknown = JSON.parse(await readFile(file, "utf8"));
if (!isRecord(parsed)) throw new Error(`${file} must be a JSON object`);
return parsed;
}
const cachePolicy = await readDocument("config/hosting/cache-policy.json");
const cacheSurfaces = recordValue(cachePolicy.surfaces);
const securityPolicy = await readDocument(
"config/hosting/security-headers.json",
);
const securityHeaders = stringRecord(securityPolicy.headers);
const baseUrl = process.env.HOSTING_BASE_URL;
const liveTarget = baseUrl ? classifyLiveHostingBaseUrl(baseUrl) : null;
// 1101/13-01. FE-GATE-019 passes the promoted archive it extracted, so the
// files checked here and the identity the host must serve are the candidate's,
// not a local rebuild's. Without the flag a local run checks its own `dist`.
const releaseRootFlag = process.argv.indexOf("--release-root");
const releaseRoot = releaseRootFlag >= 0 ? process.argv[releaseRootFlag + 1] : ".";
if (!releaseRoot) {
process.stderr.write("Usage: verify:hosting-headers [-- --release-root <extracted release archive>]\n");
process.exit(2);
}
const distRoot = path.join(releaseRoot, "dist");
const distFiles = (await readdir(distRoot, { recursive: true })).map(String);
// 1101/13-01. The deployment slot job reports whether it deployed this
// candidate. An empty slot deployed nothing, so the host still serves an
// earlier release: probing it proves nothing about this one (UNVERIFIED).
const deployedBySlot = process.env.RELEASE_DEPLOYED;
const slotEmpty = deployedBySlot !== undefined && deployedBySlot !== "true";
const publicSourceMaps = distFiles.filter((file) => file.endsWith(".map"));
// 1101/13-04. The worker script surface exists only in a build that ships one.
const workerShipped = shipsServiceWorker(INSTALLED_RUNTIME_CAPABILITIES.serviceWorker);
const requiredSurfaces = Object.entries(cacheSurfaces)
.map(([surface, policy]) => [surface, recordValue(policy)] as const)
.filter(([, policy]) => policy.requiredWhen !== "service-worker-shipped" || workerShipped);
let responses: ResponseHeaders = {};
let mode: HostingMode;
const probeResults: ProbeResult[] = [];
if (liveTarget?.passed && !slotEmpty) {
mode = "live";
const paths = Object.fromEntries(
requiredSurfaces.flatMap(([surface, policy]) =>
typeof policy.path === "string" ? [[surface, policy.path] as const] : [],
),
);
const candidateManifest = await readFile(path.join(distRoot, "release-manifest.json"), "utf8").catch(() => null);
const identity = releaseIdentity(candidateManifest);
if (!identity) {
throw new Error(`${distRoot}/release-manifest.json does not name a buildId and releaseId`);
}
// 1103/13-01. The served config.json and index.html are compared with the
// candidate's, not only the manifest names a rebuild in the same run shares.
const candidate = {
...identity,
runtimeConfig: await readFile(path.join(distRoot, "config.json"), "utf8"),
indexHtml: await readFile(path.join(distRoot, "index.html"), "utf8"),
};
// 1103/06-03, 1105/06-02. Release surfaces and every precached asset type.
const probed = await probeLiveHosting(liveTarget.url, paths, candidate, distFiles, {
alpnProtocols: strings(recordValue(cachePolicy.transport).alpnProtocols),
});
responses = probed.responses;
probeResults.push(...probed.results);
} else if (liveTarget && !liveTarget.passed) {
mode = "invalid-live";
probeResults.push({
surface: "deployment",
header: "base-url",
expected: "canonical non-loopback HTTPS root URL",
observed: liveTarget.observedOrigin,
reason: liveTarget.reason,
passed: false,
});
} else {
mode = "fixture";
const fixture = await readDocument(
"tests/fixtures/hosting/response-headers.json",
);
// 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];
for (const [surface, policy] of requiredSurfaces) {
if (typeof policy.cacheControl !== "string") continue;
const contentTypes = strings(policy.contentTypes);
const observed = responses[surface]?.["cache-control"];
results.push({
surface,
header: "cache-control",
expected: policy.cacheControl,
observed,
passed: observed === policy.cacheControl,
});
const observedContentType = responses[surface]?.["content-type"];
const observedMime = observedContentType
?.split(";", 1)[0]
?.trim()
.toLowerCase();
results.push({
surface,
header: "content-type",
expected: contentTypes,
observed: observedContentType,
passed: observedMime !== undefined && contentTypes.includes(observedMime),
});
// 1103/13-02. The bundle budget counts gzip bytes. The probe's fetch offers
// br and gzip, so an uncompressed answer is the host's choice.
const contentEncodings = strings(policy.contentEncodings);
if (contentEncodings.length > 0) {
const observedEncoding = responses[surface]?.["content-encoding"];
results.push({
surface,
header: "content-encoding",
expected: contentEncodings,
observed: observedEncoding,
passed: observedEncoding !== undefined && contentEncodings.includes(observedEncoding.trim().toLowerCase()),
});
}
if (policy.securityHeaders === true) {
for (const [header, expected] of Object.entries(securityHeaders)) {
const observedSecurity = responses[surface]?.[header.toLowerCase()];
results.push({
surface,
header: header.toLowerCase(),
expected,
observed: observedSecurity,
passed: observedSecurity === expected,
});
}
}
}
const sourceMapPolicy = recordValue(cacheSurfaces.sourceMap);
results.push({
surface: "sourceMap",
header: "public",
expected: false,
observed: publicSourceMaps.length > 0,
passed: sourceMapPolicy.public === false && publicSourceMaps.length === 0,
});
results.push(
checkPublicServiceWorkers(
distFiles,
INSTALLED_RUNTIME_CAPABILITIES.serviceWorker,
),
);
const passed = results.every((result) => result.passed);
const status = hostingVerdict(mode, passed);
await mkdir("artifacts/release", { recursive: true });
await writeValidatedJsonArtifact({
path: "artifacts/release/hosting-headers.json",
schema: hostingHeadersArtifactSchema,
value: {
schemaVersion: 1,
generatedAt: new Date().toISOString(),
mode,
// The schema records a base URL only for a host that was probed.
baseUrl: mode === "live" ? (liveTarget?.observedOrigin ?? null) : null,
providerVerificationRequired: mode !== "live",
results,
passed,
status,
},
});
if (status === "FAIL") {
process.stderr.write(
"Hosting cache/content-type/security header verification failed.\n",
);
process.exit(1);
}
if (status === "UNVERIFIED" && slotEmpty) {
process.stderr.write(
"Hosting header contract: UNVERIFIED (the deployment slot is empty: nothing deployed this release, so the host was not probed; fill deployment in config/ci/product-gates.json)\n",
);
process.exit(3);
}
if (status === "UNVERIFIED") {
// Not a pass (D-14): set HOSTING_BASE_URL to the deployed release.
process.stderr.write(
"Hosting header contract: UNVERIFIED (fixture: declared headers are consistent; set HOSTING_BASE_URL to probe the deployed release)\n",
);
process.exit(3);
}
process.stdout.write("Hosting header contract: PASS (live)\n");