Files
clean-architecture-frontend…/tests/unit/contract-snapshot-bypass.test.ts
T
DongHyeonka c06338956e fix(contracts): 참조 기능 밖의 TEMPLATE_FIXTURE 기여를 거부한다 (07-04)
문제
조립기(composeContractContributions)의 TEMPLATE_FIXTURE 분기는
fixtureId·revision·이벤트 0개만 보고 featureId를 보지 않는다. 참조 기여
파일을 복사한 제품 기능(order)이 fixture 출처 그대로 조립을 통과한다.
fixture 기여는 계약 집합(externalPackages)에 들어가지 않으므로 그 API는
실행되지만 부팅 때 릴리스 계약 정합 검사에서 경고 없이 빠진다. 설계서
§4.8은 "product feature는 반드시 EXTERNAL_PACKAGE", §24.5는 정적 검사가
product TEMPLATE_FIXTURE를 거부한다고 적지만 구현이 없다.

고른 방법
- 조립기 fixture 분기에서 featureId가 fixture의 주인과 다르면
  ContractContributionError로 실패한다. 메시지가 EXTERNAL_PACKAGE를
  쓰라고 안내한다.
- fixture 기여가 둘 이상이면 실패한다(설계서의 "유일한 예외").
- 15-01 뒤 조립은 기능 적재 때마다 전체를 다시 조립하므로 두 검사 모두
  기능이 따로 적재돼도 걸린다. registry.install의 featureId 일치 검사가
  있어 다른 기능이 참조 기능 id를 빌려 쓰는 길도 막혀 있다.
- 주인 featureId는 리터럴로 쓰지 않고 fixtureId에서 만든다
  (REFERENCE_FEATURE_V1 -> 대문자 스네이크를 소문자 kebab으로, _V1 제거).
  이유를 주석에 적었다.
- starter-experience.md "Adding a feature"에 제품 기여는
  EXTERNAL_PACKAGE라는 문장을 넣었다.
- contract-snapshot-bypass의 "iterator에 숨긴 이벤트" 테스트는
  featureId test-feature의 fixture를 썼다. 새 검사가 그 행을 먼저 막아
  테스트가 아무것도 확인하지 못하게 되므로 EXTERNAL_PACKAGE 출처로
  바꿨다. 패키지 출처는 이벤트를 받으므로 숨긴 이벤트를 읽으면 설치되어
  단언이 실패한다. 예전 fixture 출처는 이벤트가 하나라도 있으면 던져서
  읽었는지 아닌지를 구분하지 못했다.

버린 대안
- 리뷰 문서 그대로 featureId !== "reference-feature" 리터럴 비교:
  test:sample-removal이 샘플 제거 뒤 src/·tests/ 전체에서
  /REFERENCE_RESOURCE|reference-feature|reference-resource/i를 찾아
  잔여물로 실패시킨다(scripts/test-sample-removal.ts:95). 플랫폼 코드와
  남는 단위 테스트에 그 id를 쓰면 이 게이트가 깨진다.
- 조립기에 허용 featureId 인자를 추가하거나 feature module에 fixture 표시
  필드를 추가: 공개 함수·타입 변경이라 이번 범위를 넘는다.
- 정적 검사(dependency-cruiser) 규칙: 출처 종류는 import가 아니라 값이라
  depcruise로 볼 수 없다.

위험·한계
- 실패 시점은 15-01 구조에 따라 부팅이 아니라 그 기능의 런타임 적재
  (라우트 진입) 때다. Node 쪽 loaded-feature-runtimes와 레지스트리
  스크립트는 import 때 전부 조립하므로 CI에서는 바로 드러난다.
- scripts/scale/measure-feature-shape-growth.ts는 참조 기능을 이름만 바꿔
  복사하고 REFERENCE_FEATURE_V1을 그대로 둔다. 그 복사본은 이제 조립에서
  거부된다. 이 스크립트는 tsc와 vite build만 하고 기여를 조립하지 않아
  측정에는 영향이 없다(실행하지 않음).
- 주인 id 유도는 fixtureId가 "<기능 id 대문자 스네이크>_V<revision>"
  꼴이라는 이름 규칙에 기댄다. fixtureId는 닫힌 리터럴 하나라 지금은
  참조 기능 id 하나로만 풀린다.

검증
- RED(수정 전 조립기): 새 테스트 2건 실패.
  external-contract-runtime "rejects a fixture copied into a product
  feature" -> "Expected contract composition to fail."
  reference-fixture-provenance "rejects a second fixture contribution"
  -> "expected undefined to be 'reference-feature: only one
  TEMPLATE_FIXTURE contribution is allowed'".
- GREEN: 같은 3파일 22/22 통과.
- 회귀(298201f 위로 rebase 뒤): run-vitest tests/unit tests/features
  tests/platform tests/component tests/contract tests/runtime-schema
  tests/integration (pnpm·corepack을 띄우는 fixture-node-modules,
  security-followup-archive, deployment-admission, lab-performance 제외)
  267 files / 3107 tests 중 3106 통과. 실패 1건은
  provider-guardian-transaction(guardian exit=126, 단독 실행도 같음)으로
  scripts/lib 프로세스 테스트라 이 변경과 무관하다. tsc app/test rc=0. 바꾼 파일 eslint rc=0.
- 바꾼 src·tests/unit 파일에 샘플 잔여물 정규식 일치 0건(grep).
- 미실행: test:sample-removal, check:architecture(pnpm 필요).

Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md
2026-11-01 22:35:54 +09:00

262 lines
8.1 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { installBrowserRpcContractBindings } from "../../src/contracts/browser-rpc.ts";
import { parseCacheInvalidationWireEvent } from "../../src/contracts/cache-invalidation.ts";
import {
composeContractContributions,
ContractContributionError,
} from "../../src/contracts/external-contract-runtime.ts";
import { createRealtimePolicyRegistry } from "../../src/contracts/realtime-streams.ts";
import {
installRestAuthProfileRegistry,
REST_AUTH_PROFILES,
} from "../../src/contracts/rest-profiles.ts";
import { decodeStaticAssetManifest } from "../../src/contracts/service-worker-static-manifest.ts";
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
import {
MAPPERS,
SCHEMA_CODECS,
UNARY_ENCODER,
unaryOperation,
unaryProfile,
} from "./browser-rpc/fixture.ts";
import {
EFFECT_PROFILE_ID,
ENDPOINT_ID,
KILL_SWITCH_ID,
TEST_API_OPERATIONS,
TEST_MAPPERS,
TEST_SCHEMA_CODECS,
createTestRealtimeRegistry,
} from "./realtime/fixture.ts";
/**
* Q-6.7-6. Every contract that installs a caller-supplied row must validate
* and install one owned snapshot. An own `Symbol.iterator` on an array or an
* accessor on a row lets the value that was checked differ from the value
* that was installed.
*/
/** An array whose length and indices say one thing and whose iterator says another. */
function iteratorSmuggling<T>(visible: readonly T[], smuggled: readonly T[]): T[] {
const array = [...visible];
Object.defineProperty(array, Symbol.iterator, {
value: function* () {
yield* smuggled;
},
});
return array;
}
const validator = Object.freeze({
schemaId: "SmuggledSchema",
safeParse: (value: unknown) =>
Object.freeze({ success: true as const, data: value }),
});
describe("external contract composition", () => {
it("does not install an event hidden behind an array iterator", () => {
const smuggled = Object.freeze({
eventType: "test.smuggled",
envelopeValidator: validator,
payloadValidator: validator,
});
let composed: ReturnType<typeof composeContractContributions> | undefined;
try {
composed = composeContractContributions([
{
contributionId: "smuggled-events-v1",
featureId: "test-feature",
// 07-04. A package source accepts events, so a hidden event that was
// read would be installed and fail the assertion below. A fixture
// source throws on any event, which hid whether it was read.
source: TEST_CONTRACT_CONTRIBUTION.source,
http: [],
events: iteratorSmuggling([], [smuggled]),
},
] as never);
} catch (error) {
expect(error).toBeInstanceOf(ContractContributionError);
return;
}
expect(composed.eventByType.has("test.smuggled")).toBe(false);
});
it("reports a throwing reflection trap as a composition failure", () => {
const row = new Proxy(
{ ...TEST_CONTRACT_CONTRIBUTION.http[0]! },
{
ownKeys() {
throw new TypeError("hostile ownKeys trap");
},
},
);
expect(() =>
composeContractContributions([
{ ...TEST_CONTRACT_CONTRIBUTION, http: [row] },
] as never),
).toThrow(ContractContributionError);
});
});
describe("realtime policy registry", () => {
it("rejects a limit accessor instead of reading it twice", () => {
const baseline = createTestRealtimeRegistry();
const stream = baseline.listStreams()[0]!;
let reads = 0;
const limits = { ...stream.limits };
Object.defineProperty(limits, "maxEventBytes", {
enumerable: true,
configurable: true,
get: () => {
reads += 1;
// Three reads validate it; the fourth is the install copy.
return reads <= 3 ? 1_024 : 999_999_999;
},
});
expect(() =>
createRealtimePolicyRegistry({
streams: [{ ...stream, limits }],
eventTypes: [baseline.listEventTypes()[0]!],
bindings: {
schemaCodecs: TEST_SCHEMA_CODECS,
mappers: TEST_MAPPERS,
apiOperations: TEST_API_OPERATIONS,
endpointIds: [ENDPOINT_ID],
effectProfileIds: [EFFECT_PROFILE_ID],
killSwitchIds: [KILL_SWITCH_ID],
rebuildInputIds: ["referenceRealtimeRebuild"],
},
}),
).toThrow();
});
});
describe("cache invalidation wire event", () => {
it("rejects an accessor field", () => {
const now = 1_000_000;
const event = {
protocolVersion: 1,
eventId: "remote-event-00000001",
sourceId: "remote-source-0000001",
sourceEpoch: "remote-epoch-0000001",
sequence: 1,
cacheEpoch: "cache-epoch-0001",
topicVersion: 1,
emittedAt: now,
expiresAt: now + 60_000,
};
Object.defineProperty(event, "topic", {
enumerable: true,
get: () => "sample-topic-alpha",
});
expect(
parseCacheInvalidationWireEvent(event, {
cacheEpoch: "cache-epoch-0001",
topicVersions: { "sample-topic-alpha": 1 },
nowEpochMilliseconds: now,
}),
).toEqual({ ok: false, reason: "INVALID_ENVELOPE" });
});
});
describe("static asset manifest", () => {
const row = {
url: "/assets/app-abcdefgh.js",
sha256: `sha256:${"a".repeat(64)}`,
bytes: 16,
contentType: "text/javascript",
};
const manifest = (assets: unknown) => ({
schemaVersion: 1,
buildId: "build-1",
releaseId: "release-1",
setDigest: `sha256:${"b".repeat(64)}`,
assets,
});
it("rejects an accessor on a row", () => {
const accessorRow = { ...row };
Object.defineProperty(accessorRow, "bytes", {
enumerable: true,
get: () => 16,
});
expect(decodeStaticAssetManifest(manifest([accessorRow])).ok).toBe(false);
});
it("does not decode rows hidden behind an array iterator", () => {
const decoded = decodeStaticAssetManifest(
manifest(iteratorSmuggling([], [row])),
);
expect(decoded.ok && decoded.manifest.assets.length > 0).toBe(false);
});
});
describe("browser RPC contract bindings", () => {
const install = (operations: Record<string, unknown>) =>
installBrowserRpcContractBindings({
operations: operations as never,
profiles: { [unaryProfile().runtimeProfileId]: unaryProfile() },
schemaCodecs: SCHEMA_CODECS,
mappers: MAPPERS,
requestEncoders: { RpcResourceRequestEncoder: UNARY_ENCODER },
});
it("rejects a non-enumerable registry entry", () => {
const operations = {};
Object.defineProperty(operations, "GET_RPC_RESOURCE", {
enumerable: false,
value: unaryOperation(),
});
expect(() => install(operations)).toThrow(TypeError);
});
it("rejects a non-enumerable row field", () => {
const { totalDeadlineMs, ...rest } = unaryOperation();
const operation = Object.defineProperty(rest, "totalDeadlineMs", {
enumerable: false,
value: totalDeadlineMs,
});
expect(() => install({ GET_RPC_RESOURCE: operation })).toThrow(TypeError);
});
});
describe("REST auth profile registry", () => {
it("rejects an accessor field", () => {
const profile = { ...REST_AUTH_PROFILES.ANONYMOUS };
Object.defineProperty(profile, "transport", {
enumerable: true,
get: () => "ANONYMOUS",
});
expect(() => installRestAuthProfileRegistry({ ANONYMOUS: profile })).toThrow(
TypeError,
);
});
it("installs the header set it validated, not the one an iterator yields", () => {
let iterations = 0;
const allowed = ["authorization"];
Object.defineProperty(allowed, Symbol.iterator, {
value: function* () {
iterations += 1;
yield "authorization";
if (iterations > 1) yield* ["x-csrf-token", "x-csrf-token"];
},
});
let installed: ReturnType<typeof installRestAuthProfileRegistry> | undefined;
try {
installed = installRestAuthProfileRegistry({
REFERENCE_EXTERNAL_BEARER: {
...REST_AUTH_PROFILES.REFERENCE_EXTERNAL_BEARER,
allowedCredentialHeaders: allowed as never,
},
});
} catch {
return;
}
expect(
installed.get("REFERENCE_EXTERNAL_BEARER")?.allowedCredentialHeaders,
).toEqual(["authorization"]);
});
});