Files
clean-architecture-frontend…/scripts/check-release-admission.ts
T
DongHyeonka 1269992b1a fix(release): 공개 대상 승인이 자리표시자 계약 신원을 거절한다 (U7 결정 2)
문제
- 기능 생성 명령(U7)은 계약 패키지 인자가 없으면 자리표시자 신원으로
  기능을 만든다. 이 신원은 형식 검사(external-contract-runtime.ts의
  패키지 신원 검사)를 모두 통과한다. 계약 집합 검사도 같은 목록을 자기
  자신과 비교한다. 그래서 자리표시자를 그대로 둔 빌드가 staging·
  production 승인까지 통과한다.

고른 방법 (오케스트레이터 결정 2)
- 자리표시자를 src/contracts/deployment-admission.ts에 상수로 둔다.
  digest는 sha256: 뒤에 0 64개, version 0.0.0, revision 0000000이다.
  생성 명령이 이 상수를 import해 쓰므로 코드에서 자리표시자임이 보인다.
- findAdmissionViolations에 세 번째 인자로 빌드가 컴파일한 계약 패키지
  목록을 받는다. 대상이 PUBLIC(staging, production)이면 digest가
  자리표시자인 패키지마다 contractPackages.<packageId> 위반을 낸다.
  BUILD_ID·RELEASE_ID의 PLACEHOLDER_IDENTIFIERS 검사와 같은 꼴이다.
- check-release-admission.ts는 EXPECTED_CONTRACT_SET_PACKAGES를 넘긴다.
  이미 COMPILED_PRODUCT_FEATURE_IDS를 같은 방식으로 읽는다.
- 배포된 config.json의 수정본 검사(--config, 1101/13-05)는 패키지를
  보지 않는다. 수정본은 비상 스위치만 바꿀 수 있고, 패키지는 빌드 필드라
  빌드 승인 때 이미 검사했다.
- APP_PROFILE 테스트의 production 행은 컴파일된 계약 집합에 자리표시자가
  있으면 거절(그 이유로만)을, 없으면 승인을 기대한다. 생성 명령으로
  기능을 하나 만들면 저장소 자체 빌드가 production 승인을 받지 못하는
  것이 의도한 동작이기 때문이다.
- 버린 대안: 계약 형식 검사에서 거절하기. 그러면 생성한 기능이 로컬에서
  부팅·테스트되지 않는다. dist/release-manifest.json을 읽어 비교하기.
  릴리스 일관성 검사가 이미 manifest와 컴파일된 목록이 같은지 보므로
  같은 값을 한 번 더 읽고, 이 스크립트를 실행하는 테스트마다 manifest를
  써야 한다.

위험·한계
- digest만 본다. version이나 revision만 자리표시자이고 digest는 진짜인
  신원은 거절하지 않는다. 결정이 digest 하나를 자리표시자로 정했다.
- local·development 대상은 거절하지 않는다. 의도한 동작이다.
- 새 코드는 앱 번들에 들어가지 않는다(빌드 후 dist에서 거절 문구와
  상수 이름 grep 0건). 앱은 이 모듈에서 isLoopbackHostname만 쓴다.

검증
- RED: 상수만 넣고 거절 전 코드로 새 테스트를 돌리면 실패한다.
  "staging: expected [] to deeply equal [ Array(1) ]"
- RED(수정본·APP_PROFILE): 생성 명령으로 기능 하나를 만든 상태에서
  두 테스트가 "contractPackages.@org-contracts/order: pins the
  placeholder identity ..."로 실패했다.
- GREEN: tests/unit/deployment-admission.test.ts 25/25,
  feature-override-diagnostics.test.ts(스크립트 실행) 통과. 생성한 기능이
  있을 때와 없을 때 모두 통과. 생성한 기능이 있을 때 production 대상
  스크립트 실행은 rc=1과 위 위반 한 줄을 낸다.
- npx tsc app·node·test rc=0, 바꾼 3파일 eslint rc=0.
2026-11-03 06:52:43 +09:00

218 lines
8.0 KiB
TypeScript

import { mkdir, readFile, writeFile } from "node:fs/promises";
import process from "node:process";
import { parseArgs } from "node:util";
import {
DEPLOYMENT_TARGETS,
findAdmissionViolations,
isDeploymentTarget,
type AdmissionInput,
} from "../src/contracts/deployment-admission.ts";
import { unknownProductFeatureOverrides } from "../src/contracts/product-features.ts";
import { parseRuntimeConfigArtifact } from "../src/contracts/release-artifacts.ts";
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../src/features/installed-contract-contributions.ts";
import { COMPILED_PRODUCT_FEATURE_IDS } from "../src/features/installed-product-manifest.ts";
/**
* §6.4 / FE-GATE-027. Refuses to admit an artifact to an environment it was not
* built for.
*
* Release coherence already proves the artifacts agree with each other. It
* cannot prove they belong in production, because a local build is coherent
* with itself: `APP_ENV: local`, `AUTH_MODE: demo` and a loopback API pass
* every existing gate. This gate closes that by making the destination an
* explicit, declared input and refusing anything that does not match it.
*
* It fails closed in both directions. An undeclared destination is a refusal,
* not a default, so an artifact can never be admitted by omission; and every
* rule is stated as a reason to refuse, so an unreadable field cannot pass.
*/
const RUNTIME_CONFIG_PATH = "dist/config.json";
const RECORD_PATH = "artifacts/release/deployment-admission.json";
/**
* 1101/13-05. The only fields an operator may change in a deployed config.json
* without a rebuild (docs/runbooks/FE-RB-001.md). Every other field belongs to
* the build: BUILD_ID and RELEASE_ID must still match the deployed HTML and
* release manifest, or every boot stops with CONFIG_BUILD_MISMATCH.
*/
const EMERGENCY_SWITCHES: ReadonlySet<string> = new Set([
"CAPABILITY_OVERRIDES",
"FEATURE_OVERRIDES",
]);
function refuse(reason: string): void {
process.stderr.write(`release admission refused: ${reason}\n`);
process.exitCode = 1;
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
async function readRuntimeConfig(file: string): Promise<AdmissionInput | null> {
let document: unknown;
try {
document = JSON.parse(await readFile(file, "utf8"));
} catch (error) {
refuse(`${file} is unreadable: ${errorMessage(error)}`);
return null;
}
try {
return parseRuntimeConfigArtifact(document) as AdmissionInput;
} catch (error) {
refuse(`${file} is not a valid runtime config: ${errorMessage(error)}`);
return null;
}
}
function changedBuildFields(original: object, edited: object): string[] {
const before = new Map(Object.entries(original));
const after = new Map(Object.entries(edited));
return [...new Set([...before.keys(), ...after.keys()])]
.filter(
(field) =>
!EMERGENCY_SWITCHES.has(field) &&
JSON.stringify(before.get(field)) !== JSON.stringify(after.get(field)),
)
.sort();
}
async function main(): Promise<void> {
// `pnpm check:release-admission -- --config …` may pass the separator through.
const argv = process.argv.slice(2);
if (argv[0] === "--") argv.shift();
const { values: options } = parseArgs({
args: argv,
options: { config: { type: "string" }, original: { type: "string" } },
});
const declared = process.env["RELEASE_TARGET"];
if (!isDeploymentTarget(declared)) {
process.stderr.write(
"release admission refused: RELEASE_TARGET must be declared as one of " +
`${DEPLOYMENT_TARGETS.join(", ")}; received ${
declared === undefined ? "nothing" : declared
}.\n` +
"An artifact is never admitted by default — name the environment it is for.\n",
);
process.exitCode = 1;
return;
}
// 13-01: the build profile and the admission target are separate repository
// variables; a profile left on staging must not ship to production.
const profile = process.env["APP_PROFILE"];
if (profile !== undefined && profile !== declared) {
process.stderr.write(
`release admission refused: the artifact was built with APP_PROFILE=${profile} ` +
`but RELEASE_TARGET=${declared}. Set both to the same environment.\n`,
);
process.exitCode = 1;
return;
}
// 1101/13-05. An edited copy of the deployed document is checked against
// that document, so a changed build field is refused, not just a bad value.
const editedCopy = options.config;
if (editedCopy !== undefined && options.original === undefined) {
refuse(
"--config needs --original <the deployed config.json before the edit>; " +
"BUILD_ID, RELEASE_ID and every other build field are compared with it.",
);
return;
}
const configPath = editedCopy ?? RUNTIME_CONFIG_PATH;
const config = await readRuntimeConfig(configPath);
if (config === null) return;
if (options.original !== undefined) {
const original = await readRuntimeConfig(options.original);
if (original === null) return;
const changed = changedBuildFields(original, config);
if (changed.length > 0) {
refuse(
`${configPath} changes ${changed.join(", ")}; without a rebuild only ` +
`${[...EMERGENCY_SWITCHES].join(" and ")} may change.`,
);
return;
}
}
// U7 (decision 2). The packages the build compiled; a placeholder identity
// from create:feature is refused for staging and production. An edited copy
// is checked without them: packages are a build field it cannot change, and
// the build's own admission checked them.
const violations = findAdmissionViolations(
declared,
config,
editedCopy === undefined ? EXPECTED_CONTRACT_SET_PACKAGES : [],
);
// 09-09. Inert by design (a shared document may name another build's
// features), so this warns instead of refusing.
const warnings = unknownProductFeatureOverrides(
COMPILED_PRODUCT_FEATURE_IDS,
"FEATURE_OVERRIDES" in config ? config.FEATURE_OVERRIDES : undefined,
).map((featureId) => ({
field: `FEATURE_OVERRIDES.${featureId}`,
reason: `names no feature this build declares (${COMPILED_PRODUCT_FEATURE_IDS.join(", ") || "none"}); the override does nothing`,
}));
for (const warning of warnings) {
process.stderr.write(`release admission warning: ${warning.field} ${warning.reason}\n`);
}
if (editedCopy !== undefined) {
// The record is the build's admission evidence (a CI artifact); an
// operator's edited copy is not the build and does not replace it.
if (violations.length > 0) {
refuse(
`${editedCopy} for ${declared}:\n${violations
.map((violation) => ` ${violation.field}: ${violation.reason}`)
.join("\n")}`,
);
return;
}
process.stdout.write(
`release admission: ${editedCopy} ADMITTED for ${declared}; no field other than ` +
`${[...EMERGENCY_SWITCHES].join(" and ")} differs from ${options.original}. ` +
"Not recorded: this checks an edited copy, not the build.\n",
);
return;
}
await mkdir("artifacts/release", { recursive: true });
await writeFile(
RECORD_PATH,
`${JSON.stringify(
{
schemaVersion: 1,
target: declared,
appEnv: config.APP_ENV,
authMode: config.AUTH_MODE,
apiBaseUrl: config.API_BASE_URL,
buildId: config.BUILD_ID ?? null,
releaseId: config.RELEASE_ID ?? null,
status: violations.length === 0 ? "ADMITTED" : "REFUSED",
violations,
warnings,
},
null,
2,
)}\n`,
"utf8",
);
if (violations.length > 0) {
process.stderr.write(
`release admission refused for ${declared}:\n${violations
.map((violation) => ` ${violation.field}: ${violation.reason}`)
.join("\n")}\n`,
);
process.exitCode = 1;
return;
}
process.stdout.write(
`release admission: ${declared} ADMITTED ` +
`(APP_ENV=${config.APP_ENV}, AUTH_MODE=${config.AUTH_MODE}, ` +
`API=${config.API_BASE_URL}); record at ${RECORD_PATH}\n`,
);
}
await main();