Files
clean-architecture-frontend…/scripts/verify-hosting-headers.ts
T
DongHyeonka 4bce8bf379 fix(hosting): FE-GATE-019가 후보의 설정·entry와 HTTP/2·압축 전제를 대조한다
문제: (1) live probe는 배포된 release-manifest.json의 buildId·releaseId만
후보와 비교했다. 두 값은 CI run 번호로 만든 이름이라, 같은 run에서 로컬
프로필로 다시 빌드한 release(APP_ENV=local, AUTH_MODE=demo, loopback
API)를 올려도 PASS(live)였다(리뷰 실험 E-2c). 공개 대상 승인
(FE-GATE-027)을 받은 것은 후보의 config.json인데, 호스트가 내주는
config.json은 헤더만 보았다. entry script도 호스트의 두 응답끼리만
비교했다. (2) 템플릿은 HTTP/2와 압축을 전제로 초기 청크를 나누고 gzip
바이트로 예산을 재는데, 그 전제가 호스팅 계약에 없고 probe도 보지
않았다. 템플릿 nginx 예시는 http2도 gzip도 켜지 않았다.

고른 방법:
- 받은 /config.json을 후보 dist/config.json과 비교한다. 비상 스위치
  두 개(CAPABILITY_OVERRIDES, FEATURE_OVERRIDES) 밖의 필드가 다르거나
  읽을 수 없으면 FAIL. 규칙은 check-release-admission과 같은 함수
  (scripts/lib/runtime-config-switches.ts)로 옮겨 같이 쓴다.
- 받은 index.html의 entry script를 후보 index.html의 것과 비교한다.
- cache-policy.json에 transport.alpnProtocols(["h2"])와
  hashedAsset.contentEncodings(br, gzip, zstd)를 선언한다. probe는 TLS
  handshake의 ALPN(node:tls, h2와 http/1.1을 제안)과 entry script 응답의
  Content-Encoding을 본다. Node fetch는 h2를 지원하는 서버에도 HTTP/1.1로
  붙어서 프로토콜은 따로 확인해야 한다.
- nginx 예시에 http2 on과 gzip·gzip_types를 넣고, static-delivery.md와
  release-cache-rollback.md에 두 전제와 실패 조건을 적었다.
두 수정은 같은 probe 함수와 테스트를 고쳐 한 커밋에 넣었다.
버린 대안: archive SHA를 호스트에 올려 대조하기(호스트에 새 파일 규약이
생기고 일부 파일만 다른 배포는 못 잡는다). HTTP/2를 기록만 하기
(아무도 읽지 않는 경고는 청크를 묶는 결정을 부르지 못한다. 선언을 바꾸면
제품이 끌 수 있다).

위험·한계: HTTP/1.1만 되는 호스트는 이제 FE-GATE-019에서 FAIL한다. 그
제품은 cache-policy.json 선언을 바꾸고 초기 청크를 묶는다. 실제 nginx와
Gitea runner에서는 돌리지 않았다. 슬롯이 후보를 받도록 강제하는 계약
규칙은 다음 커밋(제품 overlay)에 있다.

검증: hosting-probe.test.ts에 같은 이름·다른 config.json → FAIL, 비상
스위치만 다름 → PASS, 읽을 수 없는 config.json → FAIL, 다른 entry →
FAIL, ALPN http/1.1·없음 → FAIL, 압축 없는 entry → FAIL, 정책 선언 확인을
더했다(고치기 전 실패). 33건 통과. 로컬 자체 서명 TLS 서버 실험:
http2.createSecureServer → "h2", https.createServer → "http/1.1",
인증서 이름 불일치 → ERR_TLS_CERT_ALTNAME_INVALID.
verify:hosting-headers(fixture) UNVERIFIED exit 3, deployment-admission 통과.

Refs: docs/reviews/2026-11-03-maturity-review/13-build-release-supply-chain.md 13-01, 13-02
2026-11-04 20:40:37 +09:00

241 lines
8.6 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,
probeLiveRelease,
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"),
};
const probed = await probeLiveRelease(liveTarget.url, paths, candidate, {
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(
"config/hosting/response-headers.fixture.json",
);
responses = responseHeaders(fixture.responses);
}
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 the deployment job in config/ci/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");