Files
clean-architecture-frontend…/tests/unit/hosting-probe.test.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

385 lines
16 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
checkPublicServiceWorkers,
classifyLiveHostingBaseUrl,
hostingVerdict,
probeLiveRelease,
servedEntryScript,
} from "../../scripts/lib/hosting-probe.ts";
import { SERVICE_WORKER_SCRIPT_PATH } from "../../src/contracts/service-worker.ts";
describe("public service worker in dist", () => {
const app = ["index.html", "config.json", "assets/index-abc.js"];
const active = {
mode: "ACTIVE",
scriptPath: "service-worker.js",
handlers: ["PWA_STATIC_ASSETS"],
} as const;
const removal = { mode: "REMOVE_REGISTRATION", scriptPath: "service-worker.js" } as const;
const purge = { mode: "PURGE_OWNED_RESOURCES", scriptPath: "service-worker.js" } as const;
it("accepts the selected worker when the selection is ACTIVE", () => {
expect(
checkPublicServiceWorkers([...app, "service-worker.js"], active),
).toMatchObject({ expected: true, observed: true, passed: true });
});
// 06-03 (D-5). REMOVE_REGISTRATION ships the self-unregistering worker.
it("accepts the selected worker when the selection is REMOVE_REGISTRATION", () => {
expect(
checkPublicServiceWorkers([...app, "service-worker.js"], removal),
).toMatchObject({ expected: true, observed: true, passed: true });
});
it("accepts a worker-free dist when no worker is selected", () => {
expect(checkPublicServiceWorkers(app, null)).toMatchObject({
expected: false,
passed: true,
});
});
it.each([
["no selection", [...app, "service-worker.js"], null],
["a PURGE_OWNED_RESOURCES selection", [...app, "service-worker.js"], purge],
["REMOVE_REGISTRATION without the worker", app, removal],
["ACTIVE without the worker", app, active],
["ACTIVE with an extra worker", [...app, "service-worker.js", "assets/sw.js"], active],
["ACTIVE with the worker off the root", [...app, "assets/service-worker.js"], active],
] as const)("rejects %s", (_, files, selection) => {
expect(checkPublicServiceWorkers(files, selection)).toMatchObject({
passed: false,
reason: expect.stringContaining("dist worker scripts"),
});
});
});
describe("live hosting evidence target", () => {
it("accepts a canonical production HTTPS root", () => {
expect(
classifyLiveHostingBaseUrl("https://frontend.example.test/"),
).toMatchObject({
passed: true,
observedOrigin: "https://frontend.example.test",
});
});
it.each([
["http://frontend.example.test/", "requires HTTPS"],
["https://localhost:4173/", "not live deployment evidence"],
["https://127.0.0.1/", "not live deployment evidence"],
["https://frontend.example.test/app/", "canonical root URL"],
["https://user:secret@frontend.example.test/", "must not contain credentials"],
])("rejects %s", (url, reason) => {
expect(classifyLiveHostingBaseUrl(url)).toMatchObject({
passed: false,
reason: expect.stringContaining(reason),
});
});
});
// 13-05 (D-14). The declared-header fixture proves nothing about hosting, so it
// is UNVERIFIED, and a live probe checks the release actually served.
describe("hosting header verdict", () => {
it("passes only a live probe of the deployed release", () => {
expect(hostingVerdict("live", true)).toBe("PASS");
expect(hostingVerdict("fixture", true)).toBe("UNVERIFIED");
expect(hostingVerdict("fixture", false)).toBe("FAIL");
expect(hostingVerdict("invalid-live", false)).toBe("FAIL");
expect(hostingVerdict("live", false)).toBe("FAIL");
});
it("probes the entry script named by the served index.html", () => {
expect(
servedEntryScript(
'<head><link rel="modulepreload" href="/assets/a-1.js"><script type="module" crossorigin src="/app/assets/index-Dpjd89Th.js"></script></head>',
),
).toBe("/app/assets/index-Dpjd89Th.js");
expect(servedEntryScript("<html><body>maintenance</body></html>")).toBeNull();
});
});
// 1101/13-04. The router uses browser history, so a reload or a shared link of
// any route reaches the host as a path the build has no file for. The host has
// to answer it with the release's index.html; without that fallback `/` still
// opens and only deep links are 404, which no other check sees.
describe("SPA fallback and worker script surfaces (1101/13-04)", () => {
type Surface = Partial<{
path: string;
cacheControl: string;
contentTypes: string[];
securityHeaders: boolean;
requiredWhen: string;
}>;
const surfaces = async () =>
(JSON.parse(await readFile("config/hosting/cache-policy.json", "utf8")) as {
surfaces: Record<string, Surface | undefined>;
}).surfaces;
it("declares an app route the build has no file for, served like index.html", async () => {
const { appRoute, index } = await surfaces();
expect(appRoute).toMatchObject({
cacheControl: index?.cacheControl,
contentTypes: index?.contentTypes,
securityHeaders: true,
});
expect(appRoute?.path).toMatch(/^\/[^.]+$/u);
const { responses } = JSON.parse(
await readFile("config/hosting/response-headers.fixture.json", "utf8"),
) as { responses: Record<string, unknown> };
expect(responses["appRoute"]).toEqual(responses["index"]);
});
it("declares the worker script, served no-cache, only for a build that ships it", async () => {
expect((await surfaces())["serviceWorker"]).toMatchObject({
path: `/${SERVICE_WORKER_SCRIPT_PATH}`,
cacheControl: "no-cache",
requiredWhen: "service-worker-shipped",
});
});
const INDEX = '<script type="module" src="/assets/index-A1.js"></script>';
const PATHS = {
index: "/",
runtimeConfig: "/config.json",
releaseManifest: "/release-manifest.json",
appRoute: "/__probe/deep-link",
};
const IDENTITY = { buildId: "gitea-42-1", releaseId: "refs/tags/v1.2.0-42-1" };
const CONFIG = JSON.stringify({
APP_ENV: "production",
AUTH_MODE: "external",
API_BASE_URL: "https://api.frontend.example.test/",
BUILD_ID: IDENTITY.buildId,
RELEASE_ID: IDENTITY.releaseId,
CAPABILITY_OVERRIDES: {},
FEATURE_OVERRIDES: {},
});
const CANDIDATE = { ...IDENTITY, runtimeConfig: CONFIG, indexHtml: INDEX };
const RELEASE: Record<string, [number, string]> = {
"/": [200, INDEX],
"/config.json": [200, CONFIG],
"/release-manifest.json": [200, JSON.stringify({ schemaVersion: 2, ...IDENTITY })],
"/assets/index-A1.js": [200, ""],
};
const host = (routes: Record<string, [number, string]>) => async (url: URL) => {
const [status, body] = routes[url.pathname] ?? [404, "Not Found"];
const response = new Response(body, { status, headers: { "cache-control": "no-cache" } });
Object.defineProperty(response, "url", { value: url.href });
return response;
};
const base = new URL("https://frontend.example.test/");
const probe = (routes: Record<string, [number, string]>, alpn: string | null = "h2") =>
probeLiveRelease(base, PATHS, CANDIDATE, {
fetcher: host(routes),
negotiateAlpn: async () => alpn,
alpnProtocols: ["h2"],
});
const failed = async (routes: Record<string, [number, string]>, alpn?: string | null) =>
(await probe(routes, alpn)).results
.filter((result) => !result.passed)
.map((result) => `${result.surface} ${result.header}`);
it("passes a host that answers every route with the release's index.html", async () => {
expect(await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX] })).toEqual([]);
});
it("fails a host without the fallback", async () => {
expect(await failed(RELEASE)).toEqual(["appRoute http-status", "appRoute entry-script"]);
});
it("fails a fallback that answers 200 with a page that is not the release's index.html", async () => {
expect(
await failed({ ...RELEASE, "/__probe/deep-link": [200, "<h1>Not found</h1>"] }),
).toEqual(["appRoute entry-script"]);
});
// 1101/13-01. Headers alone pass for whatever release the host serves,
// usually the previous one when nothing deployed this candidate.
it("fails a host that still serves an earlier release", async () => {
const earlier = JSON.stringify({ schemaVersion: 2, buildId: "gitea-41-1", releaseId: "refs/tags/v1.1.0-41-1" });
expect(
await failed({
...RELEASE,
"/__probe/deep-link": [200, INDEX],
"/release-manifest.json": [200, earlier],
}),
).toEqual(["releaseManifest build-id", "releaseManifest release-id"]);
});
// 1103/13-01. The manifest names come from the CI run, so a release rebuilt
// in the same run with the local profile (APP_ENV=local, AUTH_MODE=demo, a
// loopback API) passed. The candidate's config.json is the one release
// admission (FE-GATE-027) admitted, so the served one must equal it.
it("fails a host whose config.json is not the candidate's", async () => {
const local = JSON.stringify({
...JSON.parse(CONFIG),
APP_ENV: "local",
AUTH_MODE: "demo",
API_BASE_URL: "http://localhost:8080/",
});
const { results } = await probe({
...RELEASE,
"/__probe/deep-link": [200, INDEX],
"/config.json": [200, local],
});
expect(results.filter(({ passed }) => !passed)).toEqual([
expect.objectContaining({
surface: "runtimeConfig",
header: "build-fields",
observed: ["API_BASE_URL", "APP_ENV", "AUTH_MODE"],
}),
]);
});
// FE-RB-001 changes the two emergency switches without a rebuild; the
// probe after it must still pass.
it("passes a host whose config.json differs only in the emergency switches", async () => {
const switched = JSON.stringify({
...JSON.parse(CONFIG),
CAPABILITY_OVERRIDES: { realtime: "DISABLED" },
FEATURE_OVERRIDES: { "reference-feature": false },
});
expect(
await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX], "/config.json": [200, switched] }),
).toEqual([]);
});
it("fails a host whose config.json is unreadable", async () => {
expect(
await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX], "/config.json": [200, "<html>"] }),
).toEqual(["runtimeConfig build-fields"]);
});
// 1103/13-01. A build of other sources under the same run names serves its
// own entry script; the fallback check compared the host only with itself.
it("fails a host whose index.html names another entry script than the candidate's", async () => {
const other = '<script type="module" src="/assets/index-B2.js"></script>';
expect(
await failed({
...RELEASE,
"/": [200, other],
"/__probe/deep-link": [200, other],
"/assets/index-B2.js": [200, ""],
}),
).toEqual(["index candidate-entry-script"]);
});
// 1103/13-02. The split initial chunks assume HTTP/2
// (docs/architecture/static-delivery.md); over HTTP/1.1 they queue.
it("fails a host that does not negotiate a declared protocol", async () => {
const release: Record<string, [number, string]> = { ...RELEASE, "/__probe/deep-link": [200, INDEX] };
expect(await failed(release, "http/1.1")).toEqual(["transport alpn"]);
expect(await failed(release, null)).toEqual(["transport alpn"]);
});
it("fails when the served release manifest is unreadable", async () => {
expect(
await failed({
...RELEASE,
"/__probe/deep-link": [200, INDEX],
"/release-manifest.json": [200, "<html>maintenance</html>"],
}),
).toEqual(["releaseManifest build-id", "releaseManifest release-id"]);
});
});
// 1101/13-01. FE-GATE-019 checks the promoted candidate it downloaded, not a
// local rebuild, and an empty deployment slot proves nothing about the host.
describe("verify-hosting-headers on a promoted release root (1101/13-01)", () => {
async function verify(
distFiles: Readonly<Record<string, string>>,
env: Readonly<Record<string, string>> = {},
editFixture?: (responses: Record<string, Record<string, string>>) => void,
) {
const root = await mkdtemp(path.join(tmpdir(), "hosting-release-root-"));
try {
await mkdir(path.join(root, "config/hosting"), { recursive: true });
for (const file of ["cache-policy.json", "security-headers.json", "response-headers.fixture.json"]) {
await copyFile(`config/hosting/${file}`, path.join(root, "config/hosting", file));
}
if (editFixture) {
const fixturePath = path.join(root, "config/hosting/response-headers.fixture.json");
const fixture = JSON.parse(await readFile(fixturePath, "utf8")) as {
responses: Record<string, Record<string, string>>;
};
editFixture(fixture.responses);
await writeFile(fixturePath, JSON.stringify(fixture));
}
for (const [file, content] of Object.entries(distFiles)) {
await mkdir(path.dirname(path.join(root, "candidate/dist", file)), { recursive: true });
await writeFile(path.join(root, "candidate/dist", file), content);
}
const environment: NodeJS.ProcessEnv = { ...process.env, ...env };
if (!("HOSTING_BASE_URL" in env)) delete environment["HOSTING_BASE_URL"];
if (!("RELEASE_DEPLOYED" in env)) delete environment["RELEASE_DEPLOYED"];
const result = spawnSync(
process.execPath,
[path.resolve("scripts/verify-hosting-headers.ts"), "--", "--release-root", "candidate"],
{ cwd: root, encoding: "utf8", env: environment },
);
const record = JSON.parse(
await readFile(path.join(root, "artifacts/release/hosting-headers.json"), "utf8"),
) as { mode: string; results: { surface: string; header: string; passed: boolean }[] };
return {
status: result.status,
stderr: result.stderr,
mode: record.mode,
failed: record.results
.filter((entry) => !entry.passed)
.map((entry) => `${entry.surface} ${entry.header}`),
};
} finally {
await rm(root, { recursive: true, force: true });
}
}
const DIST = {
"index.html": '<script type="module" src="/assets/index-A1.js"></script>',
"release-manifest.json": JSON.stringify({ buildId: "gitea-42-1", releaseId: "r-42" }),
"assets/index-A1.js": "",
};
it("checks the dist inside --release-root, with no local build present", async () => {
const result = await verify({ ...DIST, "assets/index-A1.js.map": "{}" });
expect(result.failed, result.stderr).toEqual(["sourceMap public"]);
expect(result.status).toBe(1);
});
it("ends UNVERIFIED without probing the host when the deployment slot is empty", async () => {
const result = await verify(DIST, {
HOSTING_BASE_URL: "https://frontend.example.test/",
RELEASE_DEPLOYED: "false",
});
expect(result.failed, result.stderr).toEqual([]);
expect(result.mode).toBe("fixture");
expect(result.status).toBe(3);
expect(result.stderr).toContain("deployment slot");
});
// 1103/13-02. The bundle budget counts gzip bytes; an uncompressed entry
// script means about three times as many bytes on the wire.
it("declares compression for hashed assets and HTTP/2 for the host", async () => {
const policy = JSON.parse(await readFile("config/hosting/cache-policy.json", "utf8")) as {
transport?: { alpnProtocols?: string[] };
surfaces: Record<string, { contentEncodings?: string[] }>;
};
expect(policy.transport?.alpnProtocols).toEqual(["h2"]);
expect(policy.surfaces["hashedAsset"]?.contentEncodings).toEqual(
expect.arrayContaining(["br", "gzip"]),
);
});
it("fails a hashed asset served without a declared content encoding", async () => {
const result = await verify(DIST, {}, (responses) => {
delete responses["hashedAsset"]?.["content-encoding"];
});
expect(result.failed, result.stderr).toEqual(["hashedAsset content-encoding"]);
expect(result.status).toBe(1);
});
});