Files
clean-architecture-frontend…/tests/unit/rest-profile-contract.test.ts
T
DongHyeonka abf3ce521d fix(contracts): REST 보안 프로필 오류가 operation·프로필·깨진 조건을 말한다 (16-03)
문제: `resolveRestSecurityProfiles`는 프로필이 없거나 조합이 틀리면 일곱
조건을 한 번에 보고 "REST security profiles are incoherent."만 던진다.
참조 기능을 복사해 `REFERENCE_EXTERNAL_BEARER`를 바꾸면 이 한 문장으로
레지스트리를 읽는 게이트가 모두 멈추고, 개발자는 스택에서
rest-profiles.ts를 열어 조건을 하나씩 대조해야 한다.

고른 방법: 조건마다 깨졌을 때의 문장을 만들어 모은 뒤, operation id와
함께 한 오류로 던진다. 예: "REST security profiles are incoherent for
CREATE_SAMPLE_RESOURCE: unknown authProfileId ORDER_EXTERNAL_BEARER."
operation 인자 타입에 선택 필드 `operationId`를 더했다(추가만). 호출부
두 곳(`validateRestProfileBindings`, V2 client)은 이미 operation 전체를
넘기므로 고칠 곳이 없다. 기존 문장 앞부분은 그대로라 "incoherent"를 찾는
테스트·로그 검색은 계속 맞는다.

버린 대안: 첫 번째로 깨진 조건에서 바로 throw하기. 조건이 둘 이상
깨진 경우(예: 이름도 틀리고 CSRF도 틀림) 고칠 때마다 다음 오류를 다시
봐야 한다.

위험·한계:
- 리뷰 16-03의 (1) 프로필 이름을 `EXTERNAL_BEARER`로 바꾸고 옛 이름을
  별칭으로 두는 부분은 하지 않았다. FE-REG-API 행이 바뀌어 레지스트리
  기준선을 다시 써야 하고, `update-registry-baseline.ts`는 소유자와
  사유(REGISTRY_BASELINE_OWNER/REASON)를 승인 파일에 남긴다. 그 승인은
  사용자 몫이다. 제거 드릴 잔여 정규식이 이 이름을 못 잡는 문제도 그
  작업에 남는다.
- 초기 JS +189 B gzip(202,806 → 202,995 B, 여유 1,805 B). rest-profiles가
  초기 청크에 있어 오류 문장이 그대로 실린다.

검증:
- RED: tests/unit/rest-profile-contract.test.ts의 새 테스트가
  "expected [Function] to throw error matching /incoherent.*
  CREATE_SAMPLE_RESOURCE.*u…/ but got 'REST security profiles are
  incoherent.'"로 실패.
- GREEN: 같은 파일 8건 통과(미등록 프로필, auth "none"+bearer 두 경우).
- 회귀: tests/unit(pnpm을 띄우는 5개 제외) 1,930건, tests/integration
  (프로세스를 띄우는 3개 제외) 131건, tests/{contract,features,
  runtime-schema,component,architecture,platform} 626건 통과. tsc app·test
  통과. 바꾼 파일 eslint 통과.
2026-11-01 22:56:29 +09:00

200 lines
6.2 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { defineRestOperation } from "../../src/contracts/api-operations.ts";
import {
composeContractContributions,
ContractContributionError,
} from "../../src/contracts/external-contract-runtime.ts";
import {
createRestProviderProfile,
INSTALLED_REST_AUTH_PROFILES,
installRestAuthProfileRegistry,
resolveRestSecurityProfiles,
REST_AUTH_PROFILES,
validateRestProfileBindings,
} from "../../src/contracts/rest-profiles.ts";
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
/**
* §24.12: the common REST profile contract must stay independently verifiable
* after the sample feature is removed, so this suite owns its own operation
* fixture instead of importing an installed feature contract.
*/
const SAMPLE_COMMAND = defineRestOperation({
method: "POST",
path: "/api/sample-resources",
operationId: "CREATE_SAMPLE_RESOURCE",
auth: "external-session",
timeoutMs: null,
idempotency: "keyed",
retry: "runtime",
requestSource: "body",
requestSchema: "SampleCommand",
responseSchema: "SamplePayload",
owner: "platform-test-fixture",
contractVersion: 2,
protocol: "REST",
semantics: "COMMAND",
replayPolicy: "KEYED_COMMAND",
idempotencyKeyPolicy: "REQUIRED",
mapperId: "SampleMapper",
successStatuses: [200, 201],
responseMediaTypes: ["application/json"],
maxResponseBytes: 32_768,
providerId: "PRIMARY_API",
authProfileId: "REFERENCE_EXTERNAL_BEARER",
csrfProfileId: "NO_CSRF_BEARER",
pathSchema: "NoRequest",
pathParameterNames: [],
maxEncodedSearchBytes: 0,
});
const SAMPLE_OPERATIONS = Object.freeze({
CREATE_SAMPLE_RESOURCE: SAMPLE_COMMAND,
});
describe("REST provider/auth/CSRF profiles", () => {
it("preserves the provider prefix and rejects unsafe endpoint forms", () => {
expect(
createRestProviderProfile(
"PRIMARY_API",
"https://api.test/base/",
["omit"],
),
).toMatchObject({
providerId: "PRIMARY_API",
baseUrl: "https://api.test/base/",
redirect: "error",
referrerPolicy: "no-referrer",
});
expect(() =>
createRestProviderProfile(
"PRIMARY_API",
"https://user:password@api.test/base/",
),
).toThrow("Invalid REST provider profile");
expect(() =>
createRestProviderProfile("PRIMARY_API", "http://api.test/base/"),
).toThrow("Invalid REST provider profile");
});
it("resolves bearer auth to omit credentials and no CSRF", () => {
const resolved = resolveRestSecurityProfiles(
SAMPLE_COMMAND,
createRestProviderProfile("PRIMARY_API", "https://api.test", ["omit"]),
);
expect(resolved).toMatchObject({
auth: {
transport: "BEARER_HEADER",
credentials: "omit",
allowedCredentialHeaders: ["authorization"],
},
csrf: { mode: "NONE" },
});
});
it("validates every installed profile binding as a set", () => {
expect(
validateRestProfileBindings(SAMPLE_OPERATIONS, {
PRIMARY_API: ["omit"],
}),
).toBe(true);
expect(() =>
validateRestProfileBindings(SAMPLE_OPERATIONS, {}),
).toThrow("Unregistered REST provider binding");
});
// 16-03. A copied feature that renamed the sample's profile id stopped every
// gate with one sentence that named neither the operation nor the profile.
it("names the operation, the profile and the broken condition", () => {
const renamed = Object.freeze({
CREATE_SAMPLE_RESOURCE: {
...SAMPLE_COMMAND,
authProfileId: "ORDER_EXTERNAL_BEARER",
},
});
expect(() =>
validateRestProfileBindings(renamed, { PRIMARY_API: ["omit"] }),
).toThrow(
/incoherent.*CREATE_SAMPLE_RESOURCE.*unknown authProfileId ORDER_EXTERNAL_BEARER/,
);
const publicWithBearer = Object.freeze({
CREATE_SAMPLE_RESOURCE: { ...SAMPLE_COMMAND, auth: "none" as const },
});
expect(() =>
validateRestProfileBindings(publicWithBearer, { PRIMARY_API: ["omit"] }),
).toThrow(
/CREATE_SAMPLE_RESOURCE.*auth "none" needs an ANONYMOUS profile.*REFERENCE_EXTERNAL_BEARER is BEARER_HEADER/,
);
});
});
/**
* Q-6.7-9. Composition, the V3 executor and the V2 resolve must all answer
* from one validated installed registry. A raw record handed to resolve used
* to skip installation, so a bearer profile with ambient credentials passed.
*/
describe("one installed REST auth profile registry", () => {
const provider = createRestProviderProfile("PRIMARY_API", "https://api.test", [
"omit",
"same-origin",
]);
it("rejects a raw profile record that installation would refuse", () => {
const incoherent = {
REFERENCE_EXTERNAL_BEARER: {
...REST_AUTH_PROFILES.REFERENCE_EXTERNAL_BEARER,
credentials: "same-origin" as const,
},
};
expect(() =>
resolveRestSecurityProfiles(SAMPLE_COMMAND, provider, incoherent),
).toThrow(TypeError);
});
it("resolves through the installed registry", () => {
expect(
resolveRestSecurityProfiles(
SAMPLE_COMMAND,
provider,
INSTALLED_REST_AUTH_PROFILES,
).auth,
).toBe(INSTALLED_REST_AUTH_PROFILES.get("REFERENCE_EXTERNAL_BEARER"));
});
it("does not resolve an inherited profile id", () => {
expect(() =>
resolveRestSecurityProfiles(
{ ...SAMPLE_COMMAND, authProfileId: "toString" },
provider,
REST_AUTH_PROFILES,
),
).toThrow("incoherent");
});
it("composes contributions against the registry it is given", () => {
const registry = installRestAuthProfileRegistry({
...REST_AUTH_PROFILES,
CUSTOM_BEARER: {
...REST_AUTH_PROFILES.REFERENCE_EXTERNAL_BEARER,
authProfileId: "CUSTOM_BEARER",
},
});
const row = TEST_CONTRACT_CONTRIBUTION.http[0]!;
const contribution = {
...TEST_CONTRACT_CONTRIBUTION,
http: [
{ ...row, frontend: { ...row.frontend, authProfileId: "CUSTOM_BEARER" } },
],
};
expect(() => composeContractContributions([contribution])).toThrow(
ContractContributionError,
);
expect(
composeContractContributions([contribution], registry).httpByOperationId
.size,
).toBe(1);
});
});