Files
clean-architecture-frontend…/tests/unit/runtime-adapters-auth-profile.test.ts
DongHyeonka 245f428123 fix(features): 제품 capability 타입과 기본값 설정 키가 타입 검사 3종을 통과한다 (1103/09-02)
문제
제품 확장 지점이 실행 경로에서는 동작했지만 타입 검사 경로에서 막혔다.
(a) 문서대로 product-composition.ts에서 FeaturePlatformCapabilities를
보강하면 check:types:node가 실패했다. scripts 프로그램은 기능 코드를 끌어오지만
product-composition.ts는 끌어오지 않아 보강이 보이지 않았고, 오류는 기능
파일을 가리켰다. (b) 기본값 있는 제품 설정 키(.default()) 하나가 RuntimeConfig를
리터럴로 쓰는 템플릿 테스트 7개 파일의 타입을 깼다. 픽스처는 vi.mock이라 이
경로를 지나지 않았다.

고른 방법
- 제품 소유 빈 파일 src/features/product-capabilities.ts를 두고
  FeaturePlatformCapabilities가 그 ProductFeaturePlatformCapabilities를
  extends한다. feature-adapter-contribution.ts가 import하므로 기능을 보는 모든
  프로그램에 들어간다. 문서만 "기능 파일 안에서 보강"으로 고치는 최소안은
  capability 하나를 여러 기능이 쓸 때 보강 위치가 갈려 버렸다. 기존 제품 소유
  파일에 칸을 더하지 않고 새 파일로 둔 이유: 템플릿은 복사 뒤 제품 소유 파일을
  고치지 않으므로, 새 파일이어야 동기화 때 충돌 없이 들어간다.
- tests/helpers/runtime-config.ts의 testRuntimeConfig: 템플릿 키는 테스트가
  쓰고, 제품 키는 실제 스키마(validateRuntimeConfig)로 기본값을 채운다. 템플릿
  테스트 6개 파일이 이것을 쓰고, release-coherence는 문서 타입을 z.input으로
  바꿨다. 제품 키를 모두 Partial로 하는 대안은 기본값 키에도 undefined 처리를
  강요해 버렸다.
- tests/unit/product-extension-typecheck.test.ts: 복사본에 제품 소유 파일 세 개와
  기능 하나를 실제 파일로 채우고 tsc app·node·test를 돈다.
- 문서: starter-experience 표, 매뉴얼 01·03·patterns·create-feature,
  frontend-application-foundation, 계약 주석.

위험·한계
- 기본값 없는 필수 제품 키는 여전히 템플릿 테스트에서 실패한다(이제 타입이
  아니라 helper가 이유를 적고 throw). 문서에 ".default() 또는 .optional()"을
  적었다.
- product-composition.ts 안에서 이미 보강한 다운스트림은 보강을 새 파일로
  옮겨야 node 검사가 통과한다.

검증
- RED: 새 typecheck 테스트가 수정 전 app·node(보강 미연결)와 test(템플릿
  테스트 8건, E-PROD와 같은 위치)에서 실패.
- 수정 후 그 테스트와 영향받는 9개 테스트 파일 → 10 files / 83 tests 통과.
- check:types(tsc app·node·test), check:architecture, eslint,
  verify:documentation PASS_SCOPED.

Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-02
2026-11-04 20:30:47 +09:00

481 lines
15 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";
import { testRuntimeConfig } from "../helpers/runtime-config.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: testRuntimeConfig({
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> = {},
respond: () => Response = () =>
Response.json([{ id: "entity-1", name: "Entity" }]),
) {
const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
respond(),
);
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,
);
});
});
/**
* 1103/09-01. A server 401 is a verdict on the credential the request carried.
* An ANONYMOUS request carried none of the session's, so its 401 says nothing
* about the session: the signed-in user stays signed in and the server-state
* scope is not fenced. A request that carried the session's credential still
* signs out (R-3.2).
*/
describe("1103/09-01 a 401 is a session verdict only for the session's credential", () => {
const unauthorized = () => new Response(null, { status: 401 });
it("keeps a demo session signed in when an ANONYMOUS request gets 401", async () => {
const { http, fetcher, adapters } = await compose("demo", {}, unauthorized);
await signInDemo(adapters);
const scope = adapters.infrastructure.serverStateScope.getSnapshot();
const outcome = await http.execute(
ANONYMOUS_OPERATION,
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
expect(outcome.kind).toBe("UNAUTHENTICATED");
expect(fetcher).toHaveBeenCalledOnce();
expect(sentCredentialHeaders(fetcher.mock.calls[0]?.[1])).toEqual([]);
expect(adapters.outputPorts.session.getState()).toBe("authenticated");
expect(scope.isCurrent()).toBe(true);
});
it("does not tell the external owner about an ANONYMOUS request's 401", async () => {
const owner = externalOwner();
const notifyUnauthenticated = vi.spyOn(owner, "notifyUnauthenticated");
const { http } = await compose(
"external",
{ __CA_FRONTEND_AUTH_OWNER__: owner },
unauthorized,
);
const outcome = await http.execute(
ANONYMOUS_OPERATION,
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
expect(outcome.kind).toBe("UNAUTHENTICATED");
expect(owner.attachCredential).not.toHaveBeenCalled();
expect(notifyUnauthenticated).not.toHaveBeenCalled();
});
it("still tells the owner when the session's own credential gets 401", async () => {
const owner = externalOwner();
const notifyUnauthenticated = vi.spyOn(owner, "notifyUnauthenticated");
const { http } = await compose(
"external",
{ __CA_FRONTEND_AUTH_OWNER__: owner },
unauthorized,
);
const outcome = await http.execute(
BEARER_OPERATION,
{ limit: 1 },
{ routeId: "TEST_ROUTE" },
);
expect(outcome.kind).toBe("UNAUTHENTICATED");
expect(owner.attachCredential).toHaveBeenCalledOnce();
expect(notifyUnauthenticated).toHaveBeenCalledOnce();
});
it("still signs a demo session out when its credential gets 401", async () => {
const { http, adapters } = await compose("demo", {}, unauthorized);
await signInDemo(adapters);
await http.execute(BEARER_OPERATION, { limit: 1 }, { routeId: "TEST_ROUTE" });
expect(adapters.outputPorts.session.getState()).toBe("unauthenticated");
});
});
/**
* 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",
});
});
});