Files
clean-architecture-frontend…/tests/unit/runtime-adapters-auth-profile.test.ts
T
DongHyeonka 6c5818faec refactor(contracts): bearer 인증 프로필을 EXTERNAL_BEARER로 바꾼다 (1101/16-03)
문제
유일한 bearer 인증 프로필 이름이 샘플 이름 REFERENCE_EXTERNAL_BEARER다.
세션이 필요한 제품 기능은 지운 샘플의 이름을 계속 쓰거나 템플릿 소유
파일에 프로필을 더해야 한다. 샘플 제거 드릴의 잔여 검사 정규식도 이
이름을 잡지 않아 샘플을 지운 제품에 그대로 남는다. 리뷰 (2) 오류
메시지는 abf3ce5가 했고 (1) 이름 변경이 남았다.

고른 방법 (2026-11-03 결정)
- 프로필 이름을 EXTERNAL_BEARER로 바꿨다. 참조 기능의 V2 operation 3개와
  V3 descriptor 3개, external-session-adapter 주석, 테스트, VD-23 문서를
  새 이름으로 옮겼다.
- 옛 이름은 한 릴리스 동안 REST_AUTH_PROFILES에 별칭 한 줄로 남기고
  JSDoc @deprecated를 붙였다. 레지스트리는 키와 authProfileId가 같아야
  하므로 별칭은 EXTERNAL_BEARER를 펼치고 id만 옛 이름으로 둔 객체다.
  그래서 옛 이름을 적은 다운스트림 operation도 같은 transport·헤더로
  해석된다.
- scripts/scale의 PLATFORM_TOKENS에서 이 이름을 뺐다. 참조 기능에 더는
  "REFERENCE"가 든 프로필 이름이 없어 이름 바꾸기에서 보호할 것이 없다.
- 새 테스트 두 개: 별칭이 id만 빼고 EXTERNAL_BEARER와 같게 설치되는지,
  src에 옛 이름이 별칭 한 줄 외에 없는지(완료 기준).

버린 대안
- 별칭 없이 바로 바꾸기: 옛 이름을 쓰는 다운스트림 기능이 모듈 로드에서
  바로 실패한다. 공개 이름을 깨는 변경은 BREAKING 결정이 있을 때만 한다.
- 조회 시점의 이름 매핑(alias 표): resolve·executor·composition 세 곳이
  매핑을 알아야 한다. 프로필 항목 하나가 더 작다.

위험·한계
- 설치된 프로필이 셋이 된다. 같은 설정이 두 id로 있을 뿐 권한이 넓어지지
  않는다. 별칭은 다음 minor에서 지우고 CHANGELOG [계약] 행을 남긴다.
  그때 "src only on the alias line" 테스트의 기대값을 빈 목록으로 바꾼다.
- 다운스트림 문자열 id("REFERENCE_EXTERNAL_BEARER")에는 @deprecated 표시가
  보이지 않는다. CHANGELOG로 알린다.
- FE-REG-API 행 3개의 authProfileId가 바뀐다. breakingFields가 아니라
  behavior-change이므로 증거 없이 게이트를 통과한다. 기준선 재승인은 이번
  작업 묶음 끝에서 한 번에 한다.
- 초기 JS gzip(초기 청크 파일별 gzip 합) 203,818 → 203,840 B(+22 B). 별칭
  항목이 rest-profiles가 있는 초기 청크에 실린다. 참조 기능 계약은 lazy
  청크라 초기 크기에 영향이 없다.

검증
- RED(수정 전): rest-profile-contract.test.ts 새 사례 2건 실패("expected
  undefined to match object { transport: 'BEARER_HEADER', …(1) }",
  "expected [ …(9) ] to deeply equal [ Array(1) ]").
- GREEN: 같은 파일 10/10 통과. check-registries "11 registries PASS"
  (FE-REG-API authProfileId 3건 behavior-change).
- 회귀: tests/{unit,integration,features,contract,runtime-schema}
  207 파일 2,366건 통과(pnpm·corepack을 띄우는 6개 제외:
  http-scenario-evidence, ci-workflow-generation, lab-performance,
  fixture-node-modules, deployment-admission, security-followup-archive).
  tsc app·test·node rc=0, 바꾼 파일 eslint rc=0. vite build 성공.
- 미실행: check:architecture, test:sample-removal(pnpm 필요), e2e.

Refs: docs/reviews/2026-11-01-maturity-review/16-structure-patterns.md
2026-11-03 00:55:33 +09:00

400 lines
12 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { DEMO_AUTHORIZATION_MARKER } from "../../src/adapters/auth/index.ts";
import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { CREDENTIAL_HEADER_NAMES } from "../../src/contracts/rest-profiles.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
/**
* 09-01. The composition root decides credentials for every V3 operation. An
* `ANONYMOUS` operation must go out exactly once with no credential header in
* every session state, and a profile that needs a credential must keep failing
* closed. This runs the real `createRuntimeAdapters`; only the installed
* contract set (adds the fixture) and the feature-input composer (to reach the
* `http` capability a feature would receive) are replaced.
*/
const fixture = vi.hoisted(() => ({
http: undefined as InstalledHttpOperationExecutor | undefined,
/** The fixture list operation under another id and auth profile. */
withProfile<T extends { contract: object; frontend: object }>(
contract: T,
operationId: string,
authProfileId: string,
): T {
return {
...contract,
contract: { ...contract.contract, operationId },
frontend: { ...contract.frontend, authProfileId },
};
},
}));
vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-contract-contributions.ts")>();
const { TEST_CONTRACT_CONTRIBUTION, TEST_LIST_HTTP_CONTRACT: list } =
await import("../helpers/external-contract-fixture.ts");
const source = TEST_CONTRACT_CONTRIBUTION.source;
if (source.kind !== "EXTERNAL_PACKAGE") throw new Error("fixture source changed");
return {
...original,
// 15-01. The registry fills as feature runtimes load; this one starts with
// the fixture contribution, as if its feature had loaded.
createInstalledContractRegistry: () => {
const registry = original.createInstalledContractRegistry([
...original.EXPECTED_CONTRACT_SET_PACKAGES,
source.package,
]);
registry.install(TEST_CONTRACT_CONTRIBUTION.featureId, [
{
...TEST_CONTRACT_CONTRIBUTION,
http: [
list,
fixture.withProfile(list, "TEST_LIST_ENTITIES_BEARER", "EXTERNAL_BEARER"),
] as typeof TEST_CONTRACT_CONTRIBUTION.http,
},
]);
return registry;
},
};
});
vi.mock("../../src/features/installed-feature-adapters.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-feature-adapters.ts")>();
return {
...original,
createInstalledFeatureLoaders: (
...args: Parameters<typeof original.createInstalledFeatureLoaders>
) => {
// The context has no `http` key with no installed feature
// (test:sample-removal), so it is read without its static type.
fixture.http = Reflect.get(args[0], "http") as typeof fixture.http;
return original.createInstalledFeatureLoaders(...args);
},
};
});
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
type Release = Parameters<typeof createRuntimeAdapters>[0]["release"];
type Adapters = Awaited<ReturnType<typeof createRuntimeAdapters>>;
function runtimeFor(authMode: "demo" | "external"): Runtime {
return {
config: {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
TELEMETRY_ENABLED: false,
AUTH_MODE: authMode,
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 0,
RELEASE_MANIFEST_URL: "/release-manifest.json",
CONFIG_SCHEMA_VERSION: "2.0",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
},
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
};
}
const release: Release = {
schemaVersion: 2,
appVersion: "0.1.0",
buildId: "build-a",
commitSha: "abc123",
configSchemaVersion: "2.0",
contractSet: {
setAlgorithm: "CA_CONTRACT_SET_V1",
setDigest: `sha256:${"0".repeat(64)}`,
packages: [],
},
assetManifestHash: "hash-a",
releaseId: "release-a",
builtAt: "2026-07-25T00:00:00Z",
routeChunks: { "route-home": "assets/home.js" },
};
const ANONYMOUS_OPERATION = TEST_LIST_HTTP_CONTRACT;
const BEARER_OPERATION = fixture.withProfile(
TEST_LIST_HTTP_CONTRACT,
"TEST_LIST_ENTITIES_BEARER",
"EXTERNAL_BEARER",
);
function externalOwner(
attachCredential: () => Promise<unknown> = async () => ({
headers: { authorization: "Bearer owner-token" },
}),
) {
const listeners = new Set<() => void>();
let subject = "user-a";
return {
readState: () => "authenticated",
readSubject: () => subject,
subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: vi.fn(attachCredential),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
/** Another user signs in on this owner: the scope fences. */
switchUser() {
subject = "user-b";
for (const listener of listeners) listener();
},
};
}
let current: Adapters | undefined;
afterEach(() => {
current?.infrastructure.dispose();
current = undefined;
fixture.http = undefined;
});
async function compose(
authMode: "demo" | "external",
host: Record<string, unknown> = {},
) {
const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
Response.json([{ id: "entity-1", name: "Entity" }]),
);
current = await createRuntimeAdapters({
runtime: runtimeFor(authMode),
release,
host,
fetcher: fetcher as unknown as typeof fetch,
});
const http = fixture.http;
if (!http) throw new Error("The http capability was not composed");
return { adapters: current, http, fetcher };
}
async function signInDemo(adapters: Adapters) {
await adapters.outputPorts.session.beginSignIn();
await vi.waitFor(() => {
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY");
});
}
function sentCredentialHeaders(init: RequestInit | undefined): string[] {
return [...new Headers(init?.headers).keys()].filter((name) =>
(CREDENTIAL_HEADER_NAMES as readonly string[]).includes(name),
);
}
describe("09-01 ANONYMOUS operations through the composition root", () => {
it.each([
{
state: "demo signed out",
setup: () => compose("demo"),
},
{
state: "demo signed in",
setup: async () => {
const composed = await compose("demo");
await signInDemo(composed.adapters);
return composed;
},
},
{
state: "external owner signed in",
setup: () =>
compose("external", { __CA_FRONTEND_AUTH_OWNER__: externalOwner() }),
},
{
state: "external mode without an owner",
setup: () => compose("external"),
},
])("sends once with no credential header ($state)", async ({ setup }) => {
const { http, fetcher } = await setup();
const outcome = await http.execute(
ANONYMOUS_OPERATION,
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
expect(outcome.kind).toBe("SUCCESS");
expect(fetcher).toHaveBeenCalledOnce();
const [url, init] = fetcher.mock.calls[0] ?? [];
expect(String(url)).toBe("http://localhost:8080/api/test-entities?limit=1");
expect(init?.credentials).toBe("omit");
expect(sentCredentialHeaders(init)).toEqual([]);
});
it("does not hand an ANONYMOUS operation to the external owner", async () => {
const owner = externalOwner();
const { http } = await compose("external", {
__CA_FRONTEND_AUTH_OWNER__: owner,
});
await http.execute(ANONYMOUS_OPERATION, { limit: 1 }, { routeId: "TEST_ROUTE" });
expect(owner.attachCredential).not.toHaveBeenCalled();
});
it("still holds an ANONYMOUS operation while the scope is fenced", async () => {
const { http, fetcher, adapters } = await compose("demo");
// The session change fences the scope synchronously; READY comes later.
void adapters.outputPorts.session.beginSignIn();
const outcome = await http.execute(
ANONYMOUS_OPERATION,
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
expect(outcome).toMatchObject({
kind: "CONTRACT_VIOLATION",
violation: { kind: "SCOPE_FENCED" },
});
expect(fetcher).not.toHaveBeenCalled();
});
});
describe("09-01 credentialed operations keep failing closed", () => {
it("refuses without a session instead of downgrading to anonymous", async () => {
const { http, fetcher } = await compose("demo");
const outcome = await http.execute(
BEARER_OPERATION,
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
expect(outcome).toEqual({
kind: "UNAUTHENTICATED",
effect: "NOT_APPLICABLE",
});
expect(fetcher).not.toHaveBeenCalled();
});
it.each([
{
state: "external mode without an owner",
host: () => ({}),
},
{
state: "an owner that fails to attach",
host: () => ({
__CA_FRONTEND_AUTH_OWNER__: externalOwner(async () => {
throw new Error("owner down");
}),
}),
},
])("reports the credential owner unavailable ($state)", async ({ host }) => {
const { http, fetcher } = await compose("external", host());
const outcome = await http.execute(
BEARER_OPERATION,
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
expect(outcome).toMatchObject({
kind: "AUTH_INTEGRATION_FAILURE",
reason: "CREDENTIAL_OWNER_UNAVAILABLE",
});
expect(fetcher).not.toHaveBeenCalled();
});
it("abandons the request when the session changes while the owner attaches", async () => {
const owner = externalOwner(async () => {
owner.switchUser();
return { headers: { authorization: "Bearer owner-token" } };
});
const { http, fetcher } = await compose("external", {
__CA_FRONTEND_AUTH_OWNER__: owner,
});
const outcome = await http.execute(
BEARER_OPERATION,
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
// A fence during the credential wait aborts the transport (Q-6.3-6).
expect(outcome).toMatchObject({
kind: "TRANSPORT_FAILURE",
failure: { kind: "ABORTED_BY_SCOPE" },
});
expect(fetcher).not.toHaveBeenCalled();
});
it("sends the session credential once signed in", async () => {
const { http, fetcher, adapters } = await compose("demo");
await signInDemo(adapters);
const outcome = await http.execute(
BEARER_OPERATION,
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
expect(outcome.kind).toBe("SUCCESS");
expect(fetcher).toHaveBeenCalledOnce();
const init = fetcher.mock.calls[0]?.[1];
expect(new Headers(init?.headers).get("authorization")).toBe(
DEMO_AUTHORIZATION_MARKER,
);
});
});
/**
* 03-02. An operation no loaded feature contributed is refused before the
* executor runs. That refusal must still leave the one diagnostic every V3
* execution leaves, with the cause, so it is not invisible in the buffer.
*/
describe("03-02 an operation the registry does not hold", () => {
it("is refused without a fetch and leaves one diagnostic naming the cause", async () => {
const { http, fetcher, adapters } = await compose("demo");
const completed = () =>
adapters.outputPorts.diagnostics
.entries()
.filter((entry) => entry.eventId === "http.request.completed");
const before = completed().length;
const outcome = await http.execute(
fixture.withProfile(TEST_LIST_HTTP_CONTRACT, "TEST_NOT_INSTALLED", "ANONYMOUS"),
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
expect(outcome).toMatchObject({
kind: "CONTRACT_VIOLATION",
effect: "NOT_STARTED",
violation: {
kind: "FINAL_REQUEST_INVARIANT_FAILED",
reason: "CONTRACT_NOT_INSTALLED",
},
});
expect(fetcher).not.toHaveBeenCalled();
expect(completed()).toHaveLength(before + 1);
expect(completed().at(-1)?.context).toMatchObject({
route_id: "TEST_ROUTE",
operation_id: "TEST_NOT_INSTALLED",
outcome: "CONTRACT_VIOLATION",
error_kind: "FINAL_REQUEST_INVARIANT_FAILED",
reason: "CONTRACT_NOT_INSTALLED",
});
});
});