Files
clean-architecture-frontend…/tests/unit/deployment-admission.test.ts
T
DongHyeonka b3af26fc0e fix(release): 배포된 config.json 사본을 바꾸기 전에 검사한다 (1101/13-05)
문제
.env.example과 운영 문서는 runtime config를 재빌드 없이 바꿀 수 있다고
적는다(SERVICE_WORKER DISABLED, FEATURE_OVERRIDES). 그런데 고친 문서를
검사할 명령이 없다. check:release-admission은 dist/config.json만 읽고,
build:profile은 BUILD_ID를 덮어 다시 만든다. 브라우저는 부팅 때 문서를
스키마로 검사하고 BUILD_ID를 HTML과 맞춰 보므로, 오타 하나나 BUILD_ID
변경 하나가 모든 사용자의 BOOT_CONFIG_FAILURE가 된다. FE-RB-001은 세
줄이고 고치는 방법이 없다.

고른 방법
- check-release-admission.ts가 `--config <고친 사본> --original <배포된
  원본>`을 받는다. 사본에 기존 검사(스키마, 대상 규칙)를 그대로 돌리고,
  원본과 비교해 CAPABILITY_OVERRIDES·FEATURE_OVERRIDES 밖의 필드가 하나라도
  바뀌면 거절한다. BUILD_ID·RELEASE_ID 유지는 이 규칙에 들어 있다.
  `--original` 없이 `--config`만 주면 거절한다(비교 대상 없이 통과시키지
  않는다).
- 사본 검사는 artifacts/release/deployment-admission.json을 쓰지 않는다.
  그 파일은 빌드의 승인 증거(CI artifact)이고 운영자의 사본은 빌드가 아니다.
- FE-RB-001에 네 단계(사본 두 개 받기·고치기 → 검사 → 같은 파일시스템에서
  rename으로 교체, 되돌리기도 같은 방법 → 깨끗한 세션 부팅 확인)를 적고,
  release-cache-rollback.md와 browser-file-storage-recovery.md의 스위치
  설명이 그 절차를 가리킨다. .env.example 문장을 "비상 스위치만 재빌드
  없이 바꾼다"로 좁혔다.
- pnpm이 `--`를 넘겨도 되도록 맨 앞 `--`를 버린다.

버린 대안
- `--build-id <id>`로 BUILD_ID만 대조: API_BASE_URL·RELEASE_MANIFEST_URL처럼
  빌드가 정한 다른 필드를 바꿔도 통과한다. 원본 전체 비교가 같은 비용으로
  더 좁다.
- release-manifest.json에서 build id를 읽기: 운영자가 받을 파일이 하나 더
  늘고, 여전히 BUILD_ID만 본다.
- 비상 스위치도 빌드로만 바꾸기: 장애 대응 시간이 빌드·승격 시간만큼 늘어
  스위치의 목적이 사라진다(리뷰 대안 비교).

위험·한계
- 원본과 사본의 중첩 객체 비교는 JSON.stringify라 키 순서만 달라도
  "바뀜"으로 거절한다(닫힌 쪽으로 실패).
- 실제 서버에서 사본을 바꿔 부팅해 보지 않았다. 바뀐 문서가 release
  기록(checksums.txt, 승격 archive)과 달라지는 점은 런북에 적기만 했다.

검증
- RED: node scripts/run-vitest.ts run tests/unit/deployment-admission.test.ts
  새 6건 실패. 모두 "release admission refused: dist/config.json is
  unreadable"(--config를 무시하고 dist를 읽음)
- GREEN: 같은 파일 22 passed. 스위치만 바꾼 사본 ADMITTED·기록 없음,
  SERVICE_WORKER "DISABLE" 오타·BUILD_ID/RELEASE_ID/API_BASE_URL 변경·
  --original 누락은 exit 1
- runbook-contract, runbook-drill, feature-override-diagnostics 포함 35 passed
- 실제 local 빌드에서 인자 없는 기존 경로 ADMITTED(기록 작성),
  `-- --config dist/config.json --original public/config.json` ADMITTED
- tsc(node, test), eslint 바뀐 파일, verify-documentation-readiness
  PASS_SCOPED

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

342 lines
13 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
DEPLOYMENT_TARGETS,
findAdmissionViolations,
isDeploymentTarget,
type AdmissionInput,
} from "../../src/contracts/deployment-admission.ts";
import { ENV_REGISTRY, getBuildConfig } from "../../src/contracts/env.ts";
import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts";
import { generateRuntimeConfig } from "../../scripts/generate-runtime-config.ts";
const PRODUCTION_ARTIFACT: AdmissionInput = Object.freeze({
APP_ENV: "production",
API_BASE_URL: "https://api.example.com/",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 2,
TELEMETRY_ENABLED: false,
AUTH_MODE: "external",
CONFIG_SCHEMA_VERSION: "2.0",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "20260815.42",
RELEASE_ID: "r-2026.08.15-1",
CAPABILITY_OVERRIDES: Object.freeze({
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
}),
}) as AdmissionInput;
const LOCAL_ARTIFACT: AdmissionInput = Object.freeze({
...PRODUCTION_ARTIFACT,
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080/",
AUTH_MODE: "demo",
BUILD_ID: "local-build",
RELEASE_ID: "local-release",
}) as AdmissionInput;
describe("deployment admission", () => {
it("admits an artifact only to the environment it declares", () => {
expect(findAdmissionViolations("production", PRODUCTION_ARTIFACT)).toEqual([]);
expect(findAdmissionViolations("local", LOCAL_ARTIFACT)).toEqual([]);
});
it("refuses the exact local build that release coherence used to approve", () => {
// The review's strongest reproduction: FE-GATE-015 passed on a build whose
// runtime document was APP_ENV=local / AUTH_MODE=demo / loopback API. Each
// of those is now an independent refusal, so fixing one does not admit it.
const violations = findAdmissionViolations("production", LOCAL_ARTIFACT);
const fields = violations.map((violation) => violation.field);
expect(fields).toContain("APP_ENV");
expect(fields).toContain("AUTH_MODE");
expect(fields).toContain("API_BASE_URL");
expect(fields).toContain("BUILD_ID");
expect(fields).toContain("RELEASE_ID");
});
it("refuses endpoints a browser on the public internet cannot reach", () => {
for (const host of [
"http://api.example.com/",
"https://localhost/",
"https://127.0.0.1/",
"https://10.0.0.5/",
"https://192.168.1.10/",
"https://172.16.4.4/",
"https://169.254.169.254/",
"https://[::1]/",
]) {
const violations = findAdmissionViolations("production", {
...PRODUCTION_ARTIFACT,
API_BASE_URL: host,
} as AdmissionInput);
expect(violations.map((violation) => violation.field), host).toContain(
"API_BASE_URL",
);
}
});
it("refuses IPv6, mapped, CGNAT, 0/8 and internal-name hosts (Q-6.7-10)", () => {
for (const host of [
"https://[::ffff:127.0.0.1]/",
"https://[::ffff:8.8.8.8]/",
"https://[fd00::1]/",
"https://[fc12:3456::1]/",
"https://[fe80::1]/",
"https://[febf::1]/",
"https://[0:0:0:0:0:0:0:1]/",
"https://100.64.0.1/",
"https://100.127.255.254/",
"https://0.1.2.3/",
"https://api.internal/",
"https://printer.local/",
"https://localhost./",
"https://api.internal./",
]) {
const violations = findAdmissionViolations("production", {
...PRODUCTION_ARTIFACT,
API_BASE_URL: host,
} as AdmissionInput);
expect(violations.map((violation) => violation.field), host).toContain(
"API_BASE_URL",
);
}
});
it("permits a routable public host", () => {
for (const host of [
"https://api.172.16.example.com/",
"https://100.128.0.1/",
"https://100.63.255.255/",
"https://[2001:db8::1]/",
"https://[fec0::1]/",
"https://internal.example.com/",
"https://local.example.com/",
]) {
expect(
findAdmissionViolations("production", {
...PRODUCTION_ARTIFACT,
API_BASE_URL: host,
} as AdmissionInput),
host,
).toEqual([]);
}
});
it("refuses a placeholder identity on a public target", () => {
for (const buildId of ["local-build", "local", "dev", "unknown", ""]) {
const violations = findAdmissionViolations("production", {
...PRODUCTION_ARTIFACT,
BUILD_ID: buildId,
} as AdmissionInput);
expect(violations.map((violation) => violation.field), buildId).toContain(
"BUILD_ID",
);
}
});
it("treats an unknown target as not a target at all", () => {
for (const value of ["prod", "PRODUCTION", "", undefined, null, 1]) {
expect(isDeploymentTarget(value), String(value)).toBe(false);
}
for (const target of DEPLOYMENT_TARGETS) {
expect(isDeploymentTarget(target)).toBe(true);
}
});
});
describe("runtime config profiles", () => {
it("ships one valid profile per deployment target", async () => {
const files = (await readdir("config/runtime")).sort();
expect(files).toEqual(
[...DEPLOYMENT_TARGETS].map((target) => `${target}.json`).sort(),
);
for (const target of DEPLOYMENT_TARGETS) {
const source: unknown = JSON.parse(
await readFile(path.join("config/runtime", `${target}.json`), "utf8"),
);
const parsed = runtimeConfigV2ArtifactSchema.safeParse({
...(source as Record<string, unknown>),
BUILD_ID: "20260815.42",
RELEASE_ID: "r-1",
});
expect(parsed.success, `${target}: ${JSON.stringify(parsed.error?.issues)}`).toBe(
true,
);
expect((source as Record<string, unknown>)["APP_ENV"]).toBe(target);
}
});
it("produces an admissible document for every public target", async () => {
for (const target of ["staging", "production"] as const) {
const config = await generateRuntimeConfig(target, {
VITE_BUILD_ID: "20260815.42",
RELEASE_ID: "r-2026.08.15-1",
});
expect(
findAdmissionViolations(target, config as unknown as AdmissionInput),
).toEqual([]);
}
});
it("refuses a deployment override that would make the document unservable", async () => {
await expect(
generateRuntimeConfig("production", {
VITE_BUILD_ID: "20260815.42",
RELEASE_ID: "r-1",
RUNTIME_API_BASE_URL: "http://api.example.com/",
}),
).rejects.toThrow(/runtime config is invalid/u);
});
it("refuses a staging or production build without VITE_BUILD_ID (F-6)", async () => {
for (const target of ["staging", "production"] as const) {
await expect(
generateRuntimeConfig(target, { RELEASE_ID: "r-1" }),
).rejects.toThrow(/VITE_BUILD_ID/u);
await expect(
generateRuntimeConfig(target, { VITE_BUILD_ID: "", RELEASE_ID: "r-1" }),
).rejects.toThrow(/VITE_BUILD_ID/u);
}
});
it("declares the build defaults that getBuildConfig applies (F-6)", () => {
const applied = getBuildConfig({});
expect({
VITE_BUILD_ID: ENV_REGISTRY.VITE_BUILD_ID.defaultValue,
VITE_COMMIT_SHA: ENV_REGISTRY.VITE_COMMIT_SHA.defaultValue,
VITE_ROUTER_BASE_PATH: ENV_REGISTRY.VITE_ROUTER_BASE_PATH.defaultValue,
VITE_RUNTIME_CONFIG_URL: ENV_REGISTRY.VITE_RUNTIME_CONFIG_URL.defaultValue,
}).toEqual({
VITE_BUILD_ID: applied.buildId,
VITE_COMMIT_SHA: applied.commitSha,
VITE_ROUTER_BASE_PATH: applied.routerBasePath,
VITE_RUNTIME_CONFIG_URL: applied.runtimeConfigUrl,
});
});
it("keeps a developer build from carrying a released identity by default", async () => {
const config = await generateRuntimeConfig("local", {});
expect(config["BUILD_ID"]).toBe("local-build");
expect(
findAdmissionViolations("production", config as unknown as AdmissionInput)
.length,
).toBeGreaterThan(0);
});
// F-5 (13-15). `corepack pnpm dev` serves public/config.json while every
// build writes the local profile instead, so the two copies must not drift.
it("keeps public/config.json equal to what a local build writes", async () => {
const served: unknown = JSON.parse(await readFile("public/config.json", "utf8"));
expect(served).toEqual(await generateRuntimeConfig("local", {}));
});
// 13-01: the build profile and the admission target are two repository
// variables. A staging profile left in place for a production release has to
// stop the release, whatever the built document happens to say.
it.each([
["staging", 1],
["production", 0],
] as const)("admits a production artifact under APP_PROFILE=%s only when it names the target", async (profile, status) => {
const root = await mkdtemp(path.join(tmpdir(), "release-admission-profile-"));
try {
const config = await generateRuntimeConfig("production", {
VITE_BUILD_ID: "20260815.42",
RELEASE_ID: "r-2026.08.15-1",
});
await mkdir(path.join(root, "dist"), { recursive: true });
await writeFile(path.join(root, "dist/config.json"), JSON.stringify(config));
const result = spawnSync(
process.execPath,
[path.resolve("scripts/check-release-admission.ts")],
{
cwd: root,
encoding: "utf8",
env: { ...process.env, APP_PROFILE: profile, RELEASE_TARGET: "production" },
},
);
expect(result.status, result.stderr).toBe(status);
if (status === 1) expect(result.stderr).toMatch(/APP_PROFILE=staging/u);
} finally {
await rm(root, { recursive: true, force: true });
}
});
});
// 1101/13-05. The emergency switches (CAPABILITY_OVERRIDES, FEATURE_OVERRIDES)
// are changed in the deployed config.json without a rebuild. A typo there stops
// every boot, so the edited copy is checked against the deployed one first.
describe("checking an edited copy of the deployed runtime config", () => {
async function check(
edit: (deployed: Record<string, unknown>) => Record<string, unknown>,
args: readonly string[] = ["--config", "edited.json", "--original", "deployed.json"],
) {
const root = await mkdtemp(path.join(tmpdir(), "release-admission-copy-"));
try {
const deployed = await generateRuntimeConfig("production", {
VITE_BUILD_ID: "20260815.42",
RELEASE_ID: "r-2026.08.15-1",
});
await writeFile(path.join(root, "deployed.json"), JSON.stringify(deployed));
await writeFile(path.join(root, "edited.json"), JSON.stringify(edit(deployed)));
const result = spawnSync(
process.execPath,
[path.resolve("scripts/check-release-admission.ts"), ...args],
{
cwd: root,
encoding: "utf8",
env: { ...process.env, APP_PROFILE: "production", RELEASE_TARGET: "production" },
},
);
const records = await readdir(path.join(root, "artifacts/release")).catch(() => []);
return { status: result.status, stderr: result.stderr, stdout: result.stdout, records };
} finally {
await rm(root, { recursive: true, force: true });
}
}
const withServiceWorker = (deployed: Record<string, unknown>, value: string) => ({
...deployed,
CAPABILITY_OVERRIDES: {
...(deployed["CAPABILITY_OVERRIDES"] as Record<string, unknown>),
SERVICE_WORKER: value,
},
});
it("admits a copy that only flips an emergency switch, without writing the build's record", async () => {
const result = await check((deployed) => withServiceWorker(deployed, "DISABLED"));
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain("edited.json");
expect(result.records).toEqual([]);
});
it("refuses a typo in a switch value", async () => {
const result = await check((deployed) => withServiceWorker(deployed, "DISABLE"));
expect(result.status).toBe(1);
expect(result.stderr).toMatch(/edited\.json is not a valid runtime config/u);
});
// A valid value, so only the comparison with the deployed copy can refuse it.
it.each([
["BUILD_ID", "20260815.43"],
["RELEASE_ID", "r-2026.08.15-2"],
["API_BASE_URL", "https://other.example.org/"],
])("refuses a copy that changes %s, which only a build may change", async (field, value) => {
const result = await check((deployed) => ({ ...deployed, [field]: value }));
expect(result.status).toBe(1);
expect(result.stderr).toContain(`edited.json changes ${field}`);
});
it("refuses --config without the deployed original to compare with", async () => {
const result = await check((deployed) => deployed, ["--config", "edited.json"]);
expect(result.status).toBe(1);
expect(result.stderr).toContain("--original");
});
});