Files
clean-architecture-frontend…/tests/unit/contract-registry-immutability.test.ts
T
DongHyeonka dddf6353e0 test(contracts): 이벤트 계약 검증을 실제 이벤트 행으로 고정한다 (10-01)
문제: "정확하지 않은 이벤트 계약을 거부한다" 테스트는 공용 fixture의
events가 빈 배열이라 첫 줄 `if (events.length === 0) return;`에서 끝난다.
단언이 하나도 실행되지 않는다. 그래서 composeContractContributions의
이벤트 snapshot(M17)이나 assertEventContract 호출(M18)을 빼도 관련
테스트가 모두 통과한다. 템플릿 안에는 이벤트를 기여하는 계약이 없어서
이 경로를 지키는 테스트가 따로 없다.

고른 방법:
- tests/helpers/external-contract-fixture.ts에 TEST_EVENT_CONTRACT를
  추가한다. 공용 TEST_CONTRACT_CONTRIBUTION의 events는 그대로 비워 둔다.
  이 fixture를 쓰는 다른 테스트 20여 파일의 전제를 바꾸지 않기 위해서다.
- 빈 배열이면 return하던 테스트를 지우고 "event contracts" 묶음을 둔다.
  정상 행이 snapshot으로 설치되는지(같은 내용, 다른 객체, frozen) 먼저
  확인해서 아래 거부 경우가 다른 이유로 throw하는 것이 아님을 보인다.
  거부 경우는 HTTP 쪽 hostileRows처럼 모양(추가 필드, 다른 prototype,
  accessor)과 내용(빈 eventType, 공백, C1 제어문자, 160바이트 초과,
  validator 없음, 빈 schemaId), 중복 eventType이다.
  ContractContributionError로 던지는지까지 본다.

버린 대안: tests/setup.ts에 전역 expect.hasAssertions()를 두는 방법.
같은 종류의 빈 테스트를 모두 막지만 모든 vitest 프로젝트의 테스트 계약을
바꾸고, 리뷰는 빠른 계층 8개 폴더에서만 확인했다. 이 발견의 범위를
넘는다.

위험·한계: 템플릿 안에서 eventByType을 읽는 코드는 여전히 없다. 이
테스트는 composition 단계의 검증만 고정한다.

검증:
- RED(변경 전 테스트 파일과 새 파일을 함께, 변이 적용):
  M17(snapshotEventContract가 입력을 그대로 반환) — 옛 파일 16개 통과,
  새 파일 4개 실패("installs a well-formed event contract as its own
  snapshot", extra own field, custom prototype, accessor eventType).
  M18(assertEventContract 호출 제거) — 옛 파일 16개 통과, 새 파일 6개
  실패(빈·공백·제어문자·160바이트 초과 eventType, validator 2종).
- GREEN: node scripts/run-vitest.ts run
  tests/unit/contract-registry-immutability.test.ts — 26 passed.
- related tests/helpers/external-contract-fixture.ts
  src/contracts/external-contract-runtime.ts — 97파일 796 passed.
- tsc -p tsconfig.test.json, eslint(바꾼 2파일) 통과.

Refs: docs/reviews/2026-11-01-maturity-review/10-tests-fast-layers.md 10-01
2026-11-01 23:18:45 +09:00

417 lines
13 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
composeContractContributions,
ContractContributionError,
type ComposedContractContributions,
} from "../../src/contracts/external-contract-runtime.ts";
import {
installRestAuthProfileRegistry,
INSTALLED_REST_AUTH_PROFILES,
REST_AUTH_PROFILES,
} from "../../src/contracts/rest-profiles.ts";
import {
TEST_CONTRACT_CONTRIBUTION,
TEST_EVENT_CONTRACT,
} from "../helpers/external-contract-fixture.ts";
/**
* LIVE-02 / LIVE-03. `Object.freeze(new Map(...))` freezes the wrapper object,
* not the backing store: `set`, `delete` and `clear` keep working. Every
* registry the executor consults after composition must therefore be a read
* facade over a private store, and the rows it hands back must be exact
* own-data snapshots that a later mutation of the source cannot reach.
*/
const MUTATORS = ["set", "delete", "clear"] as const;
function borrowedMapMutation(
facade: unknown,
mutator: (typeof MUTATORS)[number],
): "THREW" | "MUTATED" {
try {
switch (mutator) {
case "set":
Map.prototype.set.call(facade as never, "INJECTED", {} as never);
break;
case "delete":
Map.prototype.delete.call(facade as never, "ANONYMOUS");
break;
case "clear":
Map.prototype.clear.call(facade as never);
break;
}
return "MUTATED";
} catch {
return "THREW";
}
}
describe("LIVE-02 installed REST auth profile registry", () => {
it("exposes no mutation API", () => {
const registry = INSTALLED_REST_AUTH_PROFILES as unknown as Record<
string,
unknown
>;
for (const mutator of MUTATORS) {
expect(registry[mutator]).toBeUndefined();
}
});
it("survives a cast mutation and a borrowed Map.prototype mutator", () => {
const registry = installRestAuthProfileRegistry(REST_AUTH_PROFILES);
const before = registry.size;
const identity = registry.get("ANONYMOUS");
expect(identity).toBeDefined();
for (const mutator of MUTATORS) {
expect(borrowedMapMutation(registry, mutator)).toBe("THREW");
}
expect(registry.size).toBe(before);
expect(registry.get("ANONYMOUS")).toBe(identity);
expect(registry.get("REFERENCE_EXTERNAL_BEARER")?.credentials).toBe("omit");
});
it("does not observe a post-installation mutation of the source record", () => {
const source: Record<string, (typeof REST_AUTH_PROFILES)["ANONYMOUS"]> = {
ANONYMOUS: {
authProfileId: "ANONYMOUS",
transport: "ANONYMOUS",
credentials: "omit",
allowedCredentialHeaders: [],
requiredCredentialHeaders: [],
},
};
const registry = installRestAuthProfileRegistry(source);
delete source.ANONYMOUS;
expect(registry.get("ANONYMOUS")?.transport).toBe("ANONYMOUS");
});
it("keeps read APIs the executor depends on", () => {
const registry = INSTALLED_REST_AUTH_PROFILES;
expect(registry.has("ANONYMOUS")).toBe(true);
expect(registry.has("NO_SUCH_PROFILE")).toBe(false);
expect([...registry.keys()].sort()).toEqual([
"ANONYMOUS",
"REFERENCE_EXTERNAL_BEARER",
]);
expect([...registry.entries()].length).toBe(registry.size);
expect([...registry.values()].length).toBe(registry.size);
});
});
describe("LIVE-03 composed contract registry", () => {
function compose(): ComposedContractContributions {
return composeContractContributions([TEST_CONTRACT_CONTRIBUTION] as never);
}
it("exposes no mutation API on either lookup", () => {
const composed = compose();
for (const facade of [composed.httpByOperationId, composed.eventByType]) {
const record = facade as unknown as Record<string, unknown>;
for (const mutator of MUTATORS) {
expect(record[mutator]).toBeUndefined();
}
for (const mutator of MUTATORS) {
expect(borrowedMapMutation(facade, mutator)).toBe("THREW");
}
}
expect(composed.httpByOperationId.size).toBeGreaterThan(0);
});
it("snapshots the frontend policy so a later source mutation cannot reach it", () => {
const mutablePolicy = {
...TEST_CONTRACT_CONTRIBUTION.http[0]!.frontend,
};
const contribution = {
...TEST_CONTRACT_CONTRIBUTION,
http: [
{
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
frontend: mutablePolicy,
},
],
};
const composed = composeContractContributions([contribution] as never);
const operationId = [...composed.httpByOperationId.keys()][0]!;
const installedBefore =
composed.httpByOperationId.get(operationId)!.frontend.totalDeadlineMs;
mutablePolicy.totalDeadlineMs = 999_999;
expect(
composed.httpByOperationId.get(operationId)!.frontend.totalDeadlineMs,
).toBe(installedBefore);
expect(installedBefore).not.toBe(999_999);
});
it("rejects an accessor or inherited policy field", () => {
const inherited = Object.create({ diagnosticsOperation: "INHERITED" }) as
Record<string, unknown>;
for (const [key, value] of Object.entries(
TEST_CONTRACT_CONTRIBUTION.http[0]!.frontend,
)) {
if (key === "diagnosticsOperation") continue;
inherited[key] = value;
}
const accessor = { ...TEST_CONTRACT_CONTRIBUTION.http[0]!.frontend };
Object.defineProperty(accessor, "totalDeadlineMs", {
configurable: true,
enumerable: true,
get: () => 10_000,
});
for (const frontend of [inherited, accessor]) {
expect(() =>
composeContractContributions([
{
...TEST_CONTRACT_CONTRIBUTION,
http: [{ ...TEST_CONTRACT_CONTRIBUTION.http[0]!, frontend }],
},
] as never),
).toThrow();
}
});
/**
* NS-02. Composition validated the caller's object and then read it again to
* copy it. Between those two reads a stateful answer could swap a deadline or
* a retry budget, so the value that passed the ceiling check and the value the
* executor ran with were two different things.
*/
describe("validate the snapshot, never the source", () => {
/** Answers a safe value to a plain read and a hostile one to a copy. */
const statefulFrontend = () =>
new Proxy(
{ ...TEST_CONTRACT_CONTRIBUTION.http[0]!.frontend },
{
get(target, key, receiver) {
if (key === "totalDeadlineMs") return 10_000;
return Reflect.get(target, key, receiver);
},
getOwnPropertyDescriptor(target, key) {
if (key === "totalDeadlineMs") {
return {
configurable: true,
enumerable: true,
value: 999_999,
};
}
return Reflect.getOwnPropertyDescriptor(target, key);
},
},
);
const contributionWith = (row: unknown) => [
{ ...TEST_CONTRACT_CONTRIBUTION, http: [row] },
];
it("validates the deadline it will install, not the one it was shown", () => {
// The copied value exceeds the hard ceiling, so composition must stop
// rather than install a deadline no check ever saw.
expect(() =>
composeContractContributions(
contributionWith({
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
frontend: statefulFrontend(),
}) as never,
),
).toThrow();
});
it("keys the registry by the operation id it copied, not the one it was shown", () => {
const base = { ...TEST_CONTRACT_CONTRIBUTION.http[0]!.contract };
const contract = new Proxy(base, {
get(target, key, receiver) {
if (key === "operationId") return base.operationId;
return Reflect.get(target, key, receiver);
},
getOwnPropertyDescriptor(target, key) {
if (key === "operationId") {
return {
configurable: true,
enumerable: true,
value: "SwappedOperation",
};
}
return Reflect.getOwnPropertyDescriptor(target, key);
},
});
const composed = composeContractContributions(
contributionWith({
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
contract,
}) as never,
);
expect([...composed.httpByOperationId.keys()]).toEqual([
"SwappedOperation",
]);
expect(
composed.httpByOperationId.get("SwappedOperation")!.contract
.operationId,
).toBe("SwappedOperation");
});
const hostileRows = [
{
label: "an installed row with an extra own field",
row: () => ({
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
injected: true,
}),
},
{
label: "an installed row with a symbol field",
row: () => ({
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
[Symbol.for("injected")]: true,
}),
},
{
label: "an installed row with a custom prototype",
row: () =>
Object.assign(Object.create({ injected: true }), {
...TEST_CONTRACT_CONTRIBUTION.http[0]!,
}),
},
{
label: "an installed row hiding a non-enumerable own field",
row: () =>
Object.defineProperty(
{ ...TEST_CONTRACT_CONTRIBUTION.http[0]! },
"injected",
{ enumerable: false, value: true },
),
},
{
label: "an installed row behind a throwing ownKeys trap",
row: () =>
new Proxy(
{ ...TEST_CONTRACT_CONTRIBUTION.http[0]! },
{
ownKeys() {
throw new TypeError("hostile ownKeys trap");
},
},
),
},
];
for (const { label, row } of hostileRows) {
it(`refuses to compose ${label}`, () => {
expect(() =>
composeContractContributions(contributionWith(row()) as never),
).toThrow();
});
}
it("refuses a contribution whose own shape is not exact", () => {
for (const contribution of [
{ ...TEST_CONTRACT_CONTRIBUTION, injected: true },
Object.assign(Object.create({ injected: true }), {
...TEST_CONTRACT_CONTRIBUTION,
}),
{
...TEST_CONTRACT_CONTRIBUTION,
[Symbol.for("injected")]: true,
},
]) {
expect(() =>
composeContractContributions([contribution] as never),
).toThrow();
}
});
});
describe("event contracts", () => {
// 10-01. The shared contribution has no events, so every case here puts
// TEST_EVENT_CONTRACT (or a broken copy of it) into a copy of it.
const withEvents = (...events: unknown[]) =>
[{ ...TEST_CONTRACT_CONTRIBUTION, events }] as never;
it("installs a well-formed event contract as its own snapshot", () => {
const composed = composeContractContributions(
withEvents(TEST_EVENT_CONTRACT),
);
const installed = composed.eventByType.get(TEST_EVENT_CONTRACT.eventType);
expect(installed).toEqual(TEST_EVENT_CONTRACT);
expect(installed).not.toBe(TEST_EVENT_CONTRACT);
expect(Object.isFrozen(installed)).toBe(true);
expect(composed.contributions[0]!.events).toEqual([installed]);
});
const hostileEvents = [
{
label: "an extra own field",
event: () => ({ ...TEST_EVENT_CONTRACT, injected: true }),
},
{
label: "a custom prototype",
event: () =>
Object.assign(Object.create({ injected: true }), {
...TEST_EVENT_CONTRACT,
}),
},
{
label: "an accessor eventType",
event: () =>
Object.defineProperty({ ...TEST_EVENT_CONTRACT }, "eventType", {
enumerable: true,
get: () => TEST_EVENT_CONTRACT.eventType,
}),
},
{
label: "an empty eventType",
event: () => ({ ...TEST_EVENT_CONTRACT, eventType: "" }),
},
{
label: "an eventType with a space",
event: () => ({ ...TEST_EVENT_CONTRACT, eventType: "test entity" }),
},
{
label: "an eventType with a control character",
event: () => ({
...TEST_EVENT_CONTRACT,
eventType: "test\u0085entity",
}),
},
{
label: "an eventType over 160 UTF-8 bytes",
// 54 three-byte characters = 162 bytes in 54 UTF-16 units.
event: () => ({ ...TEST_EVENT_CONTRACT, eventType: "가".repeat(54) }),
},
{
label: "a missing envelope validator",
event: () => ({ ...TEST_EVENT_CONTRACT, envelopeValidator: null }),
},
{
label: "a payload validator without a schemaId",
event: () => ({
...TEST_EVENT_CONTRACT,
payloadValidator: {
...TEST_EVENT_CONTRACT.payloadValidator,
schemaId: "",
},
}),
},
];
for (const { label, event } of hostileEvents) {
it(`refuses an event contract with ${label}`, () => {
expect(() => composeContractContributions(withEvents(event()))).toThrow(
ContractContributionError,
);
});
}
it("refuses two event contracts with the same eventType", () => {
expect(() =>
composeContractContributions(
withEvents(TEST_EVENT_CONTRACT, { ...TEST_EVENT_CONTRACT }),
),
).toThrow(ContractContributionError);
});
});
});