Files
clean-architecture-frontend…/scripts/verify-hosting-headers.ts
T
DongHyeonka de379ea78d ci(release): FE-GATE-019가 승격 후보를 배포된 release와 대조한다 (1101/13-01)
문제
production_gate는 promotion 직후 같은 run에서 시작하고 그 사이에 배포 job이
없다. CI 계약이 job 9개·그래프·env를 정확히 고정해 배포 job을 넣을 자리도
없다. live probe는 헤더만 보고 배포된 release가 승격 후보인지 확인하지
않는다. FE-GATE-019의 명령은 [build, verify-hosting-headers]라서 local
프로필로 다시 빌드한 dist를 검사한다. 그래서 FE-GATE-019 PASS는 "지금 떠
있는 release(대개 이전 것)의 헤더가 맞다"는 거짓 PASS다.

고른 방법 (리뷰 대안 (c), (1)~(3))
(1) live probe가 배포된 release-manifest.json의 buildId·releaseId를 후보와
    비교한다. 다르거나 읽을 수 없으면 FAIL(releaseManifest build-id·
    release-id). 후보는 검사하는 dist의 release-manifest.json이다.
(2) FE-GATE-019에서 build를 뺀다. verify-hosting-headers가
    `--release-root .release/promoted-release`를 받아 후보 dist를 본다.
    계약의 13-03 규칙(drill만 --release-root 필수)을 production_gate의 모든
    게이트 명령으로 넓혔다. 플래그 없이 돌리면 local dist를 본다.
(3) promotion과 production_gate 사이에 `deployment` job(kind deployment)을
    선언한다. 기본은 빈 슬롯이다: deploy 단계 하나가 deployed=false를 job
    output으로 낸다. production_gate는 RELEASE_DEPLOYED로 받고, 비어 있으면
    FE-GATE-019가 호스트를 probe하지 않고 UNVERIFIED(exit 3)로 끝난다.
    프로젝트는 gates.json의 deployment job을 채운다. 계약이 허용하는 것:
    checkout·setup-node·frozen-install·download·extract와 마지막 deploy 하나
    (`script`는 package 스크립트, 존재·스크립트 그래프 검사를 gate 명령과
    같이 받는다). env는 immutable_build의 CANDIDATE_ARCHIVE_SHA256과
    vars.*·secrets.*만. 게이트를 소유하지 않아 채워도 계약 기준선이 안
    바뀐다.
- ci-contract 보고서 jobCount 9→10, 계약 기준선 commandReferences
  103→102(update-ci-contract-baseline, owner frontend-platform).
- verify-hosting-headers가 live가 아닌 모드에서 baseUrl을 null로 적는다.
  스키마가 live에만 baseUrl을 허용해서, 비어 있는 슬롯과 기존 invalid-live
  (예: http:// URL)는 산출물 쓰기에서 ZodError로 죽었다. 이제 기록을 남기고
  각각 UNVERIFIED·FAIL로 끝난다.

버린 대안
- (b) (1)(2)만: 거짓 PASS는 사라지지만 배포 자리가 없어 운영 단계가 항상
  FAIL이 된다.
- (d) production_gate를 별도 workflow로 분리: Gitea에서 run 사이 artifact
  전달이 검증되지 않았다.
- 슬롯이 비었는지를 HOSTING_BASE_URL 유무로 판단: 변수만 있고 배포가 없으면
  이전 release를 probe해 FAIL이 된다. 슬롯이 직접 보고하게 했다.

위험·한계
- Gitea runner가 꺼져 있어 workflow를 실제로 돌리지 않았다. job outputs와
  `$GITHUB_OUTPUT`는 immutable_build가 이미 쓰는 방식과 같다.
- 실제 HTTPS 호스트에 이전 release를 띄워 probe하지 않았다. 불일치 판정은
  fetcher를 주입한 단위 테스트로만 확인했다.
- 채운 슬롯의 secrets는 그 job의 모든 단계(checkout, download action 포함)
  env에 보인다. 프로젝트가 고르는 값이다.
- FE-GATE-019를 수동으로 돌리는 운영자(provider 없는 최소 구성)는 후보
  archive를 .release/promoted-release에 풀어야 한다. drill과 같은 전제다.

검증
- RED: node scripts/run-vitest.ts run tests/unit/hosting-probe.test.ts
  7 failed / 19 passed(후보 인자 없음, verify가 dist ENOENT로 산출물 없음).
  tests/unit/ci-workflow-generation.test.ts 8 failed / 415 passed
  ("expected [ 'build', 'verify:hosting-headers' ] to deeply equal ...",
  "expected -1 to be 6", deployment job 없음)
- GREEN: hosting-probe 26 passed, ci-workflow-generation 423 passed
  (스냅샷 1개 갱신)
- check:ci 하위 명령 직접 실행: generate-artifact-schemas --check PASS,
  check-ci-contract.ts PASS, generate-ci-workflow --check PASS
- 슬롯을 채운 실험(체크아웃→다운로드→extract→deploy:release, vars·secrets
  env, package 스크립트 추가) 뒤 같은 세 명령 PASS. package 스크립트를 빼면
  "CI gate contract missing package scripts: deploy:release"로 실패. 실험
  뒤 원복
- 관련 테스트 16파일 596 passed(ci-workflow-generation, hosting-probe,
  service-worker-build-output, deployment-admission, ungated-*,
  supply-chain, removal-fixture, task3-selective-integration,
  documentation-readiness, tests/release, tests/platform/release)
- tsc(node, test, app) 0, eslint 바뀐 파일 0,
  verify-documentation-readiness PASS_SCOPED
- 미실행: tests/system/ci-runner(pnpm 실행), check:architecture(pnpm)

Refs: docs/reviews/2026-11-01-maturity-review/13-build-release-supply-chain.md 13-01
2026-11-03 00:56:00 +09:00

219 lines
7.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 candidate = releaseIdentity(candidateManifest);
if (!candidate) {
throw new Error(`${distRoot}/release-manifest.json does not name a buildId and releaseId`);
}
const probed = await probeLiveRelease(liveTarget.url, paths, candidate);
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),
});
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");