Files
clean-architecture-frontend…/src/contracts/deployment-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

241 lines
8.1 KiB
TypeScript

import type { RuntimeConfigArtifact } from "./release-artifacts.ts";
/**
* §6.4. Which environment an artifact is allowed to be deployed to.
*
* Release coherence answers "do these artifacts describe each other?". It does
* not answer "is this the artifact production should receive?", and the two are
* not the same question: a build whose runtime document says `APP_ENV: local`,
* `AUTH_MODE: demo` and `API_BASE_URL: http://localhost:8080/` is perfectly
* coherent with itself. Without an admission step such a build is a valid
* release candidate, and the only thing standing between it and production is
* that nobody happened to promote it.
*
* Admission is therefore a separate, declared decision: a caller states the
* target it intends, and this module says whether the artifact may go there.
* Every rule below is a refusal, so an unrecognised target or an unreadable
* field fails closed rather than passing by omission.
*/
export const DEPLOYMENT_TARGETS = Object.freeze([
"local",
"development",
"staging",
"production",
] as const);
export type DeploymentTarget = (typeof DEPLOYMENT_TARGETS)[number];
/**
* Targets that serve real users over the public internet. They carry the full
* rule set; `local` and `development` only have to be honest about what they
* are.
*/
export const PUBLIC_TARGETS: ReadonlySet<DeploymentTarget> = new Set([
"staging",
"production",
]);
/** Placeholder identifiers a developer build emits when nothing supplied one. */
const PLACEHOLDER_IDENTIFIERS: ReadonlySet<string> = new Set([
"local-build",
"local-release",
"local",
"dev",
"unknown",
]);
/**
* U7 (decision 2). The contract package identity `pnpm create:feature` writes
* when no `--package` is given: an all-zero digest, version 0.0.0 and revision
* 0000000. It passes every format check (`external-contract-runtime.ts`), so a
* generated feature boots and tests locally; a public target refuses the
* digest below.
*/
export const PLACEHOLDER_CONTRACT_PACKAGE_DIGEST =
`sha256:${"0".repeat(64)}` as const;
export const PLACEHOLDER_CONTRACT_PACKAGE_VERSION = "0.0.0";
export const PLACEHOLDER_CONTRACT_PACKAGE_REVISION = "0000000";
export type AdmissionViolation = Readonly<{ field: string; reason: string }>;
export type AdmissionInput = RuntimeConfigArtifact &
Readonly<{ BUILD_ID?: string; RELEASE_ID?: string }>;
export function isDeploymentTarget(value: unknown): value is DeploymentTarget {
return (
typeof value === "string" &&
(DEPLOYMENT_TARGETS as readonly string[]).includes(value)
);
}
/** The fields of a contract package identity admission reads. */
export type AdmissionContractPackage = Readonly<{
packageId: string;
digest: string;
}>;
/**
* Every reason this artifact may not be deployed to `target`. An empty list is
* the only admission. `contractPackages` is the contract set the build
* compiled (`EXPECTED_CONTRACT_SET_PACKAGES`).
*/
export function findAdmissionViolations(
target: DeploymentTarget,
config: AdmissionInput,
contractPackages: readonly AdmissionContractPackage[] = [],
): readonly AdmissionViolation[] {
const violations: AdmissionViolation[] = [];
if (config.APP_ENV !== target) {
violations.push({
field: "APP_ENV",
reason: `artifact declares ${config.APP_ENV} but is being admitted to ${target}`,
});
}
if (!PUBLIC_TARGETS.has(target)) return Object.freeze(violations);
if (config.AUTH_MODE !== "external") {
violations.push({
field: "AUTH_MODE",
reason: `${target} requires an external identity provider, not ${config.AUTH_MODE}`,
});
}
violations.push(...publicEndpointViolations("API_BASE_URL", config.API_BASE_URL));
if (config.TELEMETRY_ENABLED && !config.TELEMETRY_ENDPOINT) {
violations.push({
field: "TELEMETRY_ENDPOINT",
reason: "telemetry is enabled without an endpoint",
});
}
if (config.TELEMETRY_ENDPOINT) {
violations.push(
...publicEndpointViolations("TELEMETRY_ENDPOINT", config.TELEMETRY_ENDPOINT),
);
}
for (const field of ["BUILD_ID", "RELEASE_ID"] as const) {
const value = config[field];
if (typeof value !== "string" || value.length === 0) {
violations.push({ field, reason: `${target} requires a build identity` });
continue;
}
if (PLACEHOLDER_IDENTIFIERS.has(value.toLowerCase())) {
violations.push({
field,
reason: `${value} is a developer placeholder, not a released identity`,
});
}
}
for (const contractPackage of contractPackages) {
if (contractPackage.digest === PLACEHOLDER_CONTRACT_PACKAGE_DIGEST) {
violations.push({
field: `contractPackages.${contractPackage.packageId}`,
reason:
"pins the placeholder identity create:feature writes; pin the published package's version, digest and revision",
});
}
}
return Object.freeze(violations);
}
function publicEndpointViolations(
field: string,
value: string,
): readonly AdmissionViolation[] {
let url: URL;
try {
url = new URL(value);
} catch {
return [{ field, reason: "is not an absolute URL" }];
}
const violations: AdmissionViolation[] = [];
if (url.protocol !== "https:") {
violations.push({ field, reason: `${url.protocol} is not permitted; use https` });
}
if (isNonPublicHost(url.hostname)) {
violations.push({
field,
reason: `${url.hostname} is not reachable from a user's browser`,
});
} else if (isReservedExampleHost(url.hostname)) {
violations.push({
field,
reason: `${url.hostname} is a name reserved for examples and tests; set the project's endpoint in config/runtime`,
});
}
return violations;
}
/**
* 1101/13-02. RFC 2606 and RFC 6761 reserve these names for documentation and
* tests. The staging and production profiles ship `*.example.com` endpoints,
* so a host here is a template value nobody replaced, the most common
* configuration to escape after a developer one.
*/
function isReservedExampleHost(hostname: string): boolean {
const host = hostname.toLowerCase().replace(/\.$/u, "");
return (
["example.com", "example.net", "example.org"].some(
(domain) => host === domain || host.endsWith(`.${domain}`),
) || /\.(?:example|invalid|test)$/u.test(host)
);
}
/**
* Q-6.7-10. The one list of loopback hosts (in `URL.hostname` form) on which
* a REST or browser RPC provider may use plain `http:`.
*/
export const LOOPBACK_HOSTNAMES = Object.freeze([
"localhost",
"127.0.0.1",
"[::1]",
] as const);
export function isLoopbackHostname(hostname: string): boolean {
return (LOOPBACK_HOSTNAMES as readonly string[]).includes(hostname);
}
/**
* Hosts that only resolve inside the machine or network that built the
* artifact. A deployment pointing at one of these is a developer configuration
* that escaped, not a production endpoint. `hostname` comes from `URL`, so
* IPv4 and IPv6 literals are already in canonical form.
*/
function isNonPublicHost(hostname: string): boolean {
if (isLoopbackHostname(hostname)) return true;
const host = hostname
.toLowerCase()
.replace(/^\[|\]$/gu, "")
.replace(/\.$/u, "");
if (
host === "localhost" ||
host.endsWith(".localhost") ||
host.endsWith(".local") ||
host.endsWith(".internal")
) {
return true;
}
if (host.includes(":")) return isNonPublicIpv6(host);
const octets = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(host);
if (!octets) return false;
const [first, second] = [Number(octets[1]), Number(octets[2])];
return (
first === 0 ||
first === 10 ||
first === 127 ||
(first === 100 && second >= 64 && second <= 127) ||
(first === 169 && second === 254) ||
(first === 172 && second >= 16 && second <= 31) ||
(first === 192 && second === 168)
);
}
/** Unspecified, loopback, IPv4-mapped, unique-local (fc00::/7), link-local (fe80::/10). */
function isNonPublicIpv6(host: string): boolean {
if (host === "::" || host === "::1") return true;
if (/^::ffff:[0-9a-f]{1,4}:[0-9a-f]{1,4}$/u.test(host)) return true;
const first = host.startsWith(":")
? 0
: Number.parseInt(host.slice(0, host.indexOf(":")), 16);
return (first & 0xfe00) === 0xfc00 || (first & 0xffc0) === 0xfe80;
}