문제
09-02(da1e128) 뒤에도 tech-log가 하는 일 두 가지는 템플릿 파일을 고쳐야
한다(리뷰 1101 README 14.4 "09-02 이식").
- 제품 설정 키의 FE-REG-ENV 행: tech-log는 템플릿 src/contracts/env.ts의
ENV_REGISTRY에 TECH_LOG_STUDIO_SOURCE·TECH_LOG_PUBLIC_SOURCE 행을 직접
넣었다(tech-log env.ts:63-70).
- 부트 전 BFF 세션 owner: 세션이 httpOnly 쿠키라 owner가 백엔드에 묻는다.
tech-log는 템플릿 create-runtime-composition.ts에서 AUTH_MODE external이고
Studio가 HTTP일 때 createRuntimeAdapters 전에 host 전역
__CA_FRONTEND_AUTH_OWNER__에 owner를 넣는다(:2, :36-52,
bff-session-owner.ts:188-194). composeProduct는 http가 생긴 뒤에 불리고
http는 세션이 필요해서 이 일을 받을 수 없다.
고른 방법
- product-contracts.ts에 PRODUCT_ENV_REGISTRY를 빈 값으로 둔다. env.ts는
PRODUCT_REST_AUTH_PROFILES·PRODUCT_RUNTIME_CONFIG_FIELDS와 같은 모양으로
그 행을 ENV_REGISTRY에 합친다. 템플릿 키와 이름이 겹치면 모듈 로드 때
throw한다. check:registries와 vite.config.ts가 같은 객체를 읽으므로 제품
행도 같은 필드 검사를 받는다. 행을 더하기만 하면 additive라 기준선을
고치지 않는다(실험: 제품 행 2개 → compatibility=additive PASS, 허용 밖
classification → 실패).
- product-composition.ts에 composeProductSessionOwner(context)를 둔다.
템플릿은 null을 돌려준다. 조립 루트가 세션을 고르기 전에, AUTH_MODE가
external일 때만 부른다. 제품 owner가 host 전역보다 먼저다. null이면
지금처럼 host 전역, 없으면 unavailable이다. demo 모드는 묻지 않는다.
context는 config와 fetcher뿐이다(http 전이라 capability가 없다).
버린 대안
- owner를 composeProduct 반환값에 넣기: http가 세션을 쓰므로 순서가 꼬인다.
- 제품이 host 전역에 계속 넣게 두고 문서화: 부트 전 훅이 템플릿 파일
(create-runtime-composition.ts)에 남는다.
- FE-REG-ENV 행을 PRODUCT_RUNTIME_CONFIG_FIELDS에서 자동으로 만들기: zod
필드로는 classification·required를 알 수 없다.
- 행 타입·도우미를 product-contracts.ts가 env.ts에서 import: 순환 의존
(no-circular-dependencies)이다. 타입 검사는 env.ts의 대입에서 한다.
위험·한계
- product-composition.ts에 export가 하나 늘었다. 이 파일을 이미 복사한
제품은 composeProductSessionOwner를 더해야 한다. da1e128은 아직 main에
없고 두 다운스트림 모두 받지 않았다.
- 제품 행을 as const 없이 쓰면 phase가 string으로 넓어져 tsc 오류가
env.ts:78(템플릿 파일)에서 난다. 메시지에 키 이름은 나온다. product-
contracts.ts 주석에 as const를 적었다.
- 제품 설정 키에 FE-REG-ENV 행이 있는지 요구하는 검사는 여전히 없다.
템플릿 키도 RELEASE_ID·BUILD_ID는 행이 없어서 이 변경에서 넣지 않았다.
- 제품 owner가 throw하면 createRuntimeAdapters가 실패해 부트 실패
화면이 된다. composeProduct와 같다.
- tech-log의 owner는 subject를 null로 돌려준다(템플릿 동작대로 매 변경
fence). 이 변경과 무관하다.
검증
- RED: tests/unit/product-composition-fixture.test.ts 13건 중 3건 실패.
FE-REG-ENV 행 없음, external 모드 세션이 authenticated가 아니라
integration-failed, env 이름 충돌을 거절하지 않음.
- GREEN: 같은 파일 13/13, runtime-adapters-credential-order 7/7(mock에
composeProductSessionOwner: () => null 추가).
- fixture는 vi.mock 대상이 제품 소유 두 파일(머리 주석 "Product-owned.")과
설치 기능 seam 두 개뿐이고, tech-log가 고친 템플릿 파일 4개(env.ts,
create-runtime-composition.ts, runtime-config-schema.ts,
runtime-adapters.ts)는 대상이 아님을 이 파일의 소스를 읽어 확인한다.
- 회귀: tests/unit·contract·runtime-schema·integration 198 files 2861
tests 통과(heavy lock 아래).
- tsc app·node·test 통과, 바꾼 파일 eslint 통과, check:registries PASS
(compatibility=none, 재승인 불필요), verify:documentation PASS_SCOPED,
check:adapter-inventory PASS.
- 초기 JS gzip 202,770 → 202,931 B(+161, 예산 204,800). 같은 방법(dist
manifest의 초기 파일 26개, gzipSync 기본 레벨)으로 전·후를 쟀다.
- 미실행: check:architecture(pnpm 필요), test:component, e2e.
343 lines
11 KiB
TypeScript
343 lines
11 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts";
|
|
import type { ProductCredentialProvider } from "../../src/bootstrap/product-composition-contract.ts";
|
|
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
|
|
import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
|
|
|
|
/**
|
|
* 09-02. The composition root alone decides the order a credential is looked
|
|
* for, so a product credential provider can never run outside the fences:
|
|
*
|
|
* scope fence -> ANONYMOUS profile -> product provider -> session -> scope fence again
|
|
*
|
|
* Each row runs the real `createRuntimeAdapters`. Replaced: the installed
|
|
* contract set (adds the fixture operations), the feature-input composer (to
|
|
* reach the `http` capability) and the product-owned composition file (the
|
|
* provider table under test).
|
|
*/
|
|
|
|
const fixture = vi.hoisted(() => ({
|
|
http: undefined as InstalledHttpOperationExecutor | undefined,
|
|
providers: {} as Record<string, unknown>,
|
|
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,
|
|
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>
|
|
) => {
|
|
fixture.http = Reflect.get(args[0], "http") as typeof fixture.http;
|
|
return original.createInstalledFeatureLoaders(...args);
|
|
},
|
|
};
|
|
});
|
|
|
|
/** The product-owned file, filled the way a product fills it. */
|
|
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
|
|
composeProductSessionOwner: () => null,
|
|
composeProduct: () => ({
|
|
capabilities: {},
|
|
credentialProviders: fixture.providers,
|
|
}),
|
|
}));
|
|
|
|
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
|
|
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: Parameters<typeof createRuntimeAdapters>[0]["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;
|
|
/** The only non-anonymous profile the template installs. */
|
|
const PROFILE_OPERATION = fixture.withProfile(
|
|
TEST_LIST_HTTP_CONTRACT,
|
|
"TEST_LIST_ENTITIES_BEARER",
|
|
"EXTERNAL_BEARER",
|
|
);
|
|
|
|
function externalOwner() {
|
|
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(async () => ({
|
|
headers: { authorization: "Bearer owner-token" },
|
|
})),
|
|
recoverSession: async () => "no-session",
|
|
notifyUnauthenticated: () => {},
|
|
switchUser() {
|
|
subject = "user-b";
|
|
for (const listener of listeners) listener();
|
|
},
|
|
};
|
|
}
|
|
|
|
let current: Adapters | undefined;
|
|
afterEach(() => {
|
|
current?.infrastructure.dispose();
|
|
current = undefined;
|
|
fixture.http = undefined;
|
|
fixture.providers = {};
|
|
});
|
|
|
|
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 };
|
|
}
|
|
|
|
const productToken: ProductCredentialProvider = async () => ({
|
|
kind: "READY",
|
|
headers: { authorization: "Bearer product-token" },
|
|
});
|
|
|
|
type Row = Readonly<{
|
|
step: string;
|
|
/** Builds the product provider table; may close over the composed state. */
|
|
providers: (owner: ReturnType<typeof externalOwner>) => Record<string, ProductCredentialProvider>;
|
|
authMode: "demo" | "external";
|
|
/** Runs after composition, before the request. */
|
|
before?: (adapters: Adapters) => void;
|
|
operation: typeof PROFILE_OPERATION;
|
|
outcome: Record<string, unknown>;
|
|
sentAuthorization: string | null;
|
|
providerCalls: number;
|
|
ownerCalls: number;
|
|
}>;
|
|
|
|
const ROWS: readonly Row[] = [
|
|
{
|
|
step: "1 scope fence comes before the product provider",
|
|
providers: () => ({ EXTERNAL_BEARER: productToken }),
|
|
authMode: "demo",
|
|
// The session change fences the scope synchronously; READY comes later.
|
|
before: (adapters) => void adapters.outputPorts.session.beginSignIn(),
|
|
operation: PROFILE_OPERATION,
|
|
outcome: { kind: "CONTRACT_VIOLATION", violation: { kind: "SCOPE_FENCED" } },
|
|
sentAuthorization: null,
|
|
providerCalls: 0,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "2 an ANONYMOUS profile never reaches a provider",
|
|
providers: () => ({ ANONYMOUS: productToken }),
|
|
authMode: "demo",
|
|
operation: ANONYMOUS_OPERATION,
|
|
outcome: { kind: "SUCCESS" },
|
|
sentAuthorization: null,
|
|
providerCalls: 0,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "3 a registered provider answers before the session (signed out)",
|
|
providers: () => ({ EXTERNAL_BEARER: productToken }),
|
|
authMode: "demo",
|
|
operation: PROFILE_OPERATION,
|
|
outcome: { kind: "SUCCESS" },
|
|
sentAuthorization: "Bearer product-token",
|
|
providerCalls: 1,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "3 a registered provider answers before the external owner",
|
|
providers: () => ({ EXTERNAL_BEARER: productToken }),
|
|
authMode: "external",
|
|
operation: PROFILE_OPERATION,
|
|
outcome: { kind: "SUCCESS" },
|
|
sentAuthorization: "Bearer product-token",
|
|
providerCalls: 1,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "4 a profile without a provider still needs the session",
|
|
providers: () => ({}),
|
|
authMode: "demo",
|
|
operation: PROFILE_OPERATION,
|
|
outcome: { kind: "UNAUTHENTICATED", effect: "NOT_APPLICABLE" },
|
|
sentAuthorization: null,
|
|
providerCalls: 0,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "5 the scope fence is checked again after the provider answers",
|
|
providers: (owner) => ({
|
|
EXTERNAL_BEARER: async (...args) => {
|
|
owner.switchUser();
|
|
return productToken(...args);
|
|
},
|
|
}),
|
|
authMode: "external",
|
|
operation: PROFILE_OPERATION,
|
|
// A fence during the credential wait aborts the transport (Q-6.3-6). The
|
|
// composition root's own re-check behind it is not visible from here.
|
|
outcome: { kind: "TRANSPORT_FAILURE", failure: { kind: "ABORTED_BY_SCOPE" } },
|
|
sentAuthorization: null,
|
|
providerCalls: 1,
|
|
ownerCalls: 0,
|
|
},
|
|
{
|
|
step: "6 a provider that throws fails closed",
|
|
providers: () => ({
|
|
EXTERNAL_BEARER: async () => {
|
|
throw new Error("product provider down");
|
|
},
|
|
}),
|
|
authMode: "demo",
|
|
operation: PROFILE_OPERATION,
|
|
outcome: {
|
|
kind: "AUTH_INTEGRATION_FAILURE",
|
|
reason: "CREDENTIAL_OWNER_FAILED",
|
|
},
|
|
sentAuthorization: null,
|
|
providerCalls: 1,
|
|
ownerCalls: 0,
|
|
},
|
|
];
|
|
|
|
describe("09-02 credential order in the composition root", () => {
|
|
it.each(ROWS)("$step", async (row) => {
|
|
const owner = externalOwner();
|
|
const providerCalls = vi.fn();
|
|
fixture.providers = Object.fromEntries(
|
|
Object.entries(row.providers(owner)).map(([profileId, provider]) => [
|
|
profileId,
|
|
((...args) => {
|
|
providerCalls(profileId);
|
|
return provider(...args);
|
|
}) satisfies ProductCredentialProvider,
|
|
]),
|
|
);
|
|
const { http, fetcher, adapters } = await compose(
|
|
row.authMode,
|
|
row.authMode === "external" ? { __CA_FRONTEND_AUTH_OWNER__: owner } : {},
|
|
);
|
|
row.before?.(adapters);
|
|
|
|
const outcome = await http.execute(
|
|
row.operation,
|
|
{ limit: 1 },
|
|
{ routeId: "TEST_ROUTE" },
|
|
);
|
|
|
|
expect(outcome).toMatchObject(row.outcome);
|
|
expect(providerCalls).toHaveBeenCalledTimes(row.providerCalls);
|
|
expect(owner.attachCredential).toHaveBeenCalledTimes(row.ownerCalls);
|
|
if (row.sentAuthorization === null) {
|
|
for (const [, init] of fetcher.mock.calls) {
|
|
expect(new Headers(init?.headers).has("authorization")).toBe(false);
|
|
}
|
|
} else {
|
|
expect(fetcher).toHaveBeenCalledOnce();
|
|
expect(
|
|
new Headers(fetcher.mock.calls[0]?.[1]?.headers).get("authorization"),
|
|
).toBe(row.sentAuthorization);
|
|
}
|
|
});
|
|
});
|