Files
clean-architecture-frontend…/tests/unit/product-composition-fixture.test.ts
T
DongHyeonka 183a4a373d feat(contracts): 짝 백엔드 CSRF 헤더 x-xsrf-token을 자격증명 헤더에 더한다 (1101/09-02)
문제
짝 백엔드는 쿠키 세션의 CSRF를 Spring CookieCsrfTokenRepository로
검사하고, 기본 헤더 이름은 X-XSRF-TOKEN이다(백엔드 SecurityConfig.java,
docs/registries/env-keys.yaml APP_SESSION_CSRF_HEADER_NAME). 프론트의 닫힌
자격증명 헤더 목록(VD-23, rest-profiles.ts CREDENTIAL_HEADER_NAMES)에는
x-csrf-token만 있다. 제품 인증 프로필이 x-xsrf-token을 allowed·required에
적으면 프로필 레지스트리 설치가 모듈 로드 때 throw한다. 그래서 memento가
템플릿 파일을 고쳤고, 09-02(da1e128)의 제품 제공자 테스트 fixture는
x-csrf-token으로 우회해 적었다.

고른 방법
- 목록이 닫힌 이유(VD-23 5-1): 자격증명 제공자가 transport 소유 헤더
  (accept, content-type, idempotency-key)나 금지 헤더를 넣지 못하게 하고,
  프로필이 정확한 allowed·required 집합을 갖게 하려는 것이다. x-xsrf-token은
  그 어느 쪽도 아닌 proof 헤더라 목록에 더해도 이 이유를 깨지 않는다.
- 목록에 x-xsrf-token 하나를 더한다. 실제로 보낼 수 있는지는 여전히
  프로필의 allowed 집합이 정한다. 템플릿 기본 프로필(EXTERNAL_BEARER,
  ANONYMOUS)은 바뀌지 않는다.
- 09-02 fixture의 memento BFF 쓰기 프로필과 제공자를 x-xsrf-token으로
  바꿔 우회를 없앤다. 이 fixture가 RED 테스트다.

버린 대안
- 헤더 이름을 프로필이 자유롭게 정하게 열기: 닫힌 목록이 막는 shadowing·
  금지 헤더 위험이 돌아온다.
- 백엔드가 X-CSRF-TOKEN을 받게 설정: 백엔드 기본값을 바꾸는 일이고 이
  repo 범위 밖이다. 백엔드 repo는 고치지 않는다.

위험·한계
- RestCsrfProfile.headerName 타입("x-csrf-token" | null)은 그대로다. CSRF
  프로필은 템플릿 상수(REST_CSRF_PROFILES)뿐이고 제품이 더할 확장 지점이
  없다. 제품 쿠키 프로필은 인증 프로필의 헤더 집합으로 표현한다.
- V2 legacy 허용 목록(client.ts LEGACY_ALLOWED_CREDENTIAL_HEADERS)은
  "기존 동작 그대로"가 목적이라 바꾸지 않았다.
- 외부 세션 어댑터(external-session-adapter.ts)도 같은 목록을 읽으므로
  이제 x-xsrf-token을 받는다. 보낼지는 V3 프로필 검사가 정한다.

검증
- RED: tests/unit/product-composition-fixture.test.ts를 x-xsrf-token으로
  바꾸자 파일 전체 실패("REST auth profile allowedCredentialHeaders is not
  an exact set", 모듈 로드).
- GREEN: 같은 파일과 tests/unit/runtime-adapters-auth-profile·runtime-
  adapters-credential-order·contract-snapshot-bypass, tests/integration/
  legacy-http-credential-authority 5 files 44 tests 통과. tsc app·test
  통과, 바꾼 파일 eslint 통과.

Refs: clean-architecture-backend-template docs/reviews/2026-11-01-maturity-review/README.md 14.3, 15
2026-11-03 02:00:45 +09:00

467 lines
18 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts";
import type {
ProductComposition,
ProductCompositionContext,
} from "../../src/bootstrap/product-composition-contract.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts";
import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts";
import type { FeaturePlatformCapabilityId } from "../../src/features/feature-adapter-contribution.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
/**
* 09-02 completion check. The two products' current needs — memento's
* `offsetUpload` and `runtime` capabilities and its BFF cookie XSRF write,
* tech-log's Studio CSRF and its product runtime-config key — expressed by
* filling only the two product-owned files:
*
* - `src/contracts/product-contracts.ts`: product auth profiles and config keys
* - `src/bootstrap/product-composition.ts`: capabilities and credential providers
*
* Both are replaced below by what a product would write in them. Everything
* else is the template as shipped; only the installed contract set (adds the
* operations) and the feature-input composer (to read the capability context
* a feature receives) are swapped, as in the 09-01 test.
*/
declare module "../../src/features/feature-adapter-contribution.ts" {
interface FeaturePlatformCapabilities {
readonly offsetUpload: Readonly<{
upload(path: string, body: Blob): Promise<number | "NO_CREDENTIAL">;
}>;
readonly runtime: Readonly<{ appEnvironment: string; apiBaseUrl: string }>;
readonly studioSource: "MOCK" | "HTTP";
readonly studioHttp: InstalledHttpOperationExecutor;
}
}
/** Fails to compile unless the capability interface takes product keys. */
const PRODUCT_NEEDS: readonly FeaturePlatformCapabilityId[] = [
"offsetUpload",
"runtime",
"studioSource",
"studioHttp",
];
const fixture = vi.hoisted(() => ({
capabilities: undefined as Record<string, unknown> | undefined,
withProfile<T extends { contract: object; frontend: object }>(
contract: T,
operationId: string,
authProfileId: string,
): T {
return {
...contract,
contract: { ...contract.contract, operationId },
frontend: { ...contract.frontend, authProfileId },
};
},
}));
/** The product's `src/contracts/product-contracts.ts`. */
vi.mock("../../src/contracts/product-contracts.ts", async () => {
const { z } = await import("../../src/contracts/zod.ts");
const cookieProfile = (
authProfileId: string,
header: readonly ("x-csrf-token" | "x-xsrf-token")[],
) =>
Object.freeze({
authProfileId,
transport: "SAME_ORIGIN_COOKIE" as const,
credentials: "include" as const,
allowedCredentialHeaders: Object.freeze([...header]),
requiredCredentialHeaders: Object.freeze([...header]),
});
return {
PRODUCT_RUNTIME_CONFIG_FIELDS: Object.freeze({
TECH_LOG_STUDIO_SOURCE: z.enum(["MOCK", "HTTP"]).default("MOCK"),
}),
PRODUCT_REST_AUTH_PROFILES: Object.freeze({
MEMENTO_BFF_READ: cookieProfile("MEMENTO_BFF_READ", []),
// The paired backend's default CSRF header (Spring CookieCsrfTokenRepository).
MEMENTO_BFF_WRITE: cookieProfile("MEMENTO_BFF_WRITE", ["x-xsrf-token"]),
TECH_LOG_STUDIO_BOOTSTRAP: cookieProfile("TECH_LOG_STUDIO_BOOTSTRAP", []),
TECH_LOG_STUDIO_SESSION: cookieProfile("TECH_LOG_STUDIO_SESSION", ["x-csrf-token"]),
}),
};
});
const OPERATIONS = vi.hoisted(() => ({
bffRead: ["MEMENTO_READ", "MEMENTO_BFF_READ"],
bffWrite: ["MEMENTO_WRITE", "MEMENTO_BFF_WRITE"],
studio: ["STUDIO_LIST", "TECH_LOG_STUDIO_SESSION"],
studioSession: ["STUDIO_SESSION", "TECH_LOG_STUDIO_BOOTSTRAP"],
} as const));
/** The product's `src/bootstrap/product-composition.ts`. */
vi.mock("../../src/bootstrap/product-composition.ts", async () => {
const { TEST_DETAIL_HTTP_CONTRACT: detail } = await import(
"../helpers/external-contract-fixture.ts"
);
const studioSession = fixture.withProfile(detail, ...OPERATIONS.studioSession);
function composeProduct(context: ProductCompositionContext) {
// tech-log: one Studio CSRF token per session, fetched through `http` with
// the credential-free bootstrap profile and dropped on 401/403.
let csrfToken: Promise<string> | null = null;
const csrf = {
token(signal?: AbortSignal) {
csrfToken ??= context.http
.execute(studioSession, { entityId: "session" }, {
routeId: "STUDIO",
...(signal === undefined ? {} : { signal }),
})
.then((outcome) => {
if (outcome.kind !== "SUCCESS") throw new Error("no studio session");
return outcome.value.id;
});
return csrfToken.catch((error: unknown) => {
csrfToken = null;
throw error;
});
},
invalidate() {
csrfToken = null;
},
};
return {
capabilities: {
// memento: its resumable upload transport, fenced like every request.
offsetUpload: Object.freeze({
async upload(path: string, body: Blob) {
const token = context.isScopeReady()
? context.readCookie("XSRF-TOKEN")
: undefined;
if (token === undefined) return "NO_CREDENTIAL" as const;
const fetcher = context.fetcher ?? fetch;
const response = await fetcher(
new URL(path, context.config.API_BASE_URL),
{
method: "PATCH",
credentials: "include",
headers: { "x-xsrf-token": token },
body,
},
);
return response.status;
},
}),
// memento: runtime values its features read.
runtime: Object.freeze({
appEnvironment: context.config.APP_ENV,
apiBaseUrl: context.config.API_BASE_URL,
}),
// tech-log: a product runtime-config key. Read untyped here only
// because the shipped `product-contracts.ts` declares no keys.
studioSource: Reflect.get(context.config, "TECH_LOG_STUDIO_SOURCE") as
| "MOCK"
| "HTTP",
// tech-log: Studio calls go through `http`; a 401/403 drops the token.
studioHttp: Object.freeze({
async execute(...args: Parameters<InstalledHttpOperationExecutor["execute"]>) {
const outcome = await context.http.execute(...args);
if (outcome.kind === "UNAUTHENTICATED" || outcome.kind === "FORBIDDEN") {
csrf.invalidate();
}
return outcome;
},
}) as InstalledHttpOperationExecutor,
},
credentialProviders: {
// memento BFF: the cookie is the session; writes add the XSRF cookie.
MEMENTO_BFF_READ: () => ({ kind: "READY" as const, headers: {} }),
MEMENTO_BFF_WRITE: () => {
const token = context.readCookie("XSRF-TOKEN");
return token === undefined
? { kind: "UNAVAILABLE" as const }
: { kind: "READY" as const, headers: { "x-xsrf-token": token } };
},
// tech-log Studio: the token's own issuing call carries none.
TECH_LOG_STUDIO_BOOTSTRAP: () => ({ kind: "READY" as const, headers: {} }),
TECH_LOG_STUDIO_SESSION: async (_operation, { signal }) => ({
kind: "READY" as const,
headers: { "x-csrf-token": await csrf.token(signal) },
}),
},
} satisfies ProductComposition;
}
return { composeProduct };
});
vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-contract-contributions.ts")>();
const fixtures = await import("../helpers/external-contract-fixture.ts");
const { TEST_CONTRACT_CONTRIBUTION: contribution } = fixtures;
const source = 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(contribution.featureId, [
{
...contribution,
http: [
fixture.withProfile(fixtures.TEST_LIST_HTTP_CONTRACT, ...OPERATIONS.bffRead),
fixture.withProfile(fixtures.TEST_LIST_HTTP_CONTRACT, ...OPERATIONS.bffWrite),
fixture.withProfile(fixtures.TEST_LIST_HTTP_CONTRACT, ...OPERATIONS.studio),
fixture.withProfile(fixtures.TEST_DETAIL_HTTP_CONTRACT, ...OPERATIONS.studioSession),
] as typeof 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.capabilities = { ...args[0] };
return original.createInstalledFeatureLoaders(...args);
},
};
});
const CONFIG_DOCUMENT = {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
CONFIG_SCHEMA_VERSION: "2.0",
RELEASE_MANIFEST_URL: "/release-manifest.json",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
} as const;
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" },
};
let current: Awaited<ReturnType<typeof createRuntimeAdapters>> | undefined;
afterEach(() => {
current?.infrastructure.dispose();
current = undefined;
fixture.capabilities = undefined;
});
async function compose(options: Readonly<{ cookie?: string; studioStatus?: number }> = {}) {
const validated = validateRuntimeConfig({
...CONFIG_DOCUMENT,
TECH_LOG_STUDIO_SOURCE: "HTTP",
});
if (!validated.success) throw new Error(JSON.stringify(validated.issues));
const fetcher = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => {
const url = String(input);
if (url.endsWith("/api/test-entities/session")) {
return Response.json({ id: "studio-csrf", name: "session" });
}
if (url.includes("/api/test-entities?") && options.studioStatus !== undefined) {
return Response.json(
{ type: "about:blank", title: "Forbidden", status: options.studioStatus },
{ status: options.studioStatus },
);
}
return Response.json([{ id: "entity-1", name: "Entity" }]);
});
current = await createRuntimeAdapters({
runtime: {
config: validated.data,
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
},
release,
host: options.cookie === undefined ? {} : { document: { cookie: options.cookie } },
fetcher: fetcher as unknown as typeof fetch,
});
const capabilities = fixture.capabilities;
if (!capabilities) throw new Error("feature capabilities were not composed");
return {
capabilities,
http: capabilities.http as InstalledHttpOperationExecutor,
studioHttp: capabilities.studioHttp as InstalledHttpOperationExecutor,
fetcher,
};
}
const list = (operation: readonly [string, string]) =>
fixture.withProfile(TEST_LIST_HTTP_CONTRACT, ...operation);
function sent(fetcher: ReturnType<typeof vi.fn>, index: number) {
const [url, init] = fetcher.mock.calls[index] as [RequestInfo | URL, RequestInit];
return { url: String(url), credentials: init.credentials, headers: new Headers(init.headers) };
}
describe("09-02 product needs through the product-owned files only", () => {
it("adds product capabilities next to the template's own", async () => {
const { capabilities } = await compose();
expect(Object.keys(capabilities).sort()).toEqual(
[...PRODUCT_NEEDS, "http", "telemetry"].sort(),
);
expect(capabilities.runtime).toEqual({
appEnvironment: "local",
apiBaseUrl: "http://localhost:8080/",
});
expect(capabilities.studioSource).toBe("HTTP");
});
it("memento: offsetUpload sends the XSRF cookie while the scope is ready", async () => {
const { capabilities, fetcher } = await compose({ cookie: "XSRF-TOKEN=xsrf-1" });
const offsetUpload = capabilities.offsetUpload as {
upload(path: string, body: Blob): Promise<unknown>;
};
await expect(offsetUpload.upload("/api/uploads/1", new Blob(["chunk"]))).resolves.toBe(200);
expect(sent(fetcher, 0).headers.get("x-xsrf-token")).toBe("xsrf-1");
});
it("memento: BFF reads go out signed out, with the cookie and no header", async () => {
const { http, fetcher } = await compose();
const outcome = await http.execute(list(OPERATIONS.bffRead), { limit: 1 }, { routeId: "R" });
expect(outcome.kind).toBe("SUCCESS");
expect(sent(fetcher, 0).credentials).toBe("include");
expect([...sent(fetcher, 0).headers.keys()]).not.toContain("x-xsrf-token");
});
it("memento: BFF writes carry the XSRF cookie and fail closed without it", async () => {
const withCookie = await compose({ cookie: "theme=dark; XSRF-TOKEN=xsrf-1" });
await expect(
withCookie.http.execute(list(OPERATIONS.bffWrite), { limit: 1 }, { routeId: "R" }),
).resolves.toMatchObject({ kind: "SUCCESS" });
expect(sent(withCookie.fetcher, 0).headers.get("x-xsrf-token")).toBe("xsrf-1");
current?.infrastructure.dispose();
const without = await compose();
await expect(
without.http.execute(list(OPERATIONS.bffWrite), { limit: 1 }, { routeId: "R" }),
).resolves.toMatchObject({
kind: "AUTH_INTEGRATION_FAILURE",
reason: "CREDENTIAL_OWNER_UNAVAILABLE",
});
expect(without.fetcher).not.toHaveBeenCalled();
});
it("tech-log: Studio calls fetch the CSRF token once and then send it", async () => {
const { studioHttp, fetcher } = await compose();
for (let call = 0; call < 2; call += 1) {
await expect(
studioHttp.execute(list(OPERATIONS.studio), { limit: 1 }, { routeId: "STUDIO" }),
).resolves.toMatchObject({ kind: "SUCCESS" });
}
expect(fetcher.mock.calls.map((_, index) => sent(fetcher, index).url)).toEqual([
"http://localhost:8080/api/test-entities/session",
"http://localhost:8080/api/test-entities?limit=1",
"http://localhost:8080/api/test-entities?limit=1",
]);
expect(sent(fetcher, 0).headers.has("x-csrf-token")).toBe(false);
expect(sent(fetcher, 2).headers.get("x-csrf-token")).toBe("studio-csrf");
});
it("tech-log: a 403 drops the Studio token so the next call fetches a new one", async () => {
const { studioHttp, fetcher } = await compose({ studioStatus: 403 });
for (let call = 0; call < 2; call += 1) {
await expect(
studioHttp.execute(list(OPERATIONS.studio), { limit: 1 }, { routeId: "STUDIO" }),
).resolves.toMatchObject({ kind: "FORBIDDEN" });
}
const sessionFetches = fetcher.mock.calls.filter(([url]) =>
String(url).endsWith("/session"),
);
expect(sessionFetches).toHaveLength(2);
});
it("tech-log: the product config key joins the strict document", () => {
const parsed = (document: Record<string, unknown>) => validateRuntimeConfig(document);
expect(parsed({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "HTTP" })).toMatchObject({
success: true,
data: { TECH_LOG_STUDIO_SOURCE: "HTTP" },
});
expect(parsed(CONFIG_DOCUMENT)).toMatchObject({
success: true,
data: { TECH_LOG_STUDIO_SOURCE: "MOCK" },
});
expect(parsed({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "LIVE" })).toMatchObject({
success: false,
issues: [{ path: "TECH_LOG_STUDIO_SOURCE" }],
});
expect(parsed({ ...CONFIG_DOCUMENT, TECH_LOG_TYPO: "HTTP" })).toMatchObject({
success: false,
issues: [{ path: "TECH_LOG_TYPO", code: "unrecognized_keys" }],
});
// The build scripts read the same schema (generate-runtime-config.ts).
expect(
runtimeConfigV2ArtifactSchema.parse({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "HTTP" }),
).toMatchObject({ TECH_LOG_STUDIO_SOURCE: "HTTP" });
});
});
describe("09-02 a product row cannot take a template name", () => {
afterEach(() => {
vi.doUnmock("../../src/contracts/product-contracts.ts");
vi.resetModules();
});
it.each([
{
registry: "auth profiles",
load: () => import("../../src/contracts/rest-profiles.ts"),
product: { PRODUCT_RUNTIME_CONFIG_FIELDS: {}, PRODUCT_REST_AUTH_PROFILES: { ANONYMOUS: {} } },
error: "Product REST auth profile ANONYMOUS reuses a template profile id.",
},
{
registry: "runtime config",
load: () => import("../../src/contracts/release-artifacts.ts"),
product: { PRODUCT_RUNTIME_CONFIG_FIELDS: { APP_ENV: {} }, PRODUCT_REST_AUTH_PROFILES: {} },
error: "Product runtime config key APP_ENV is a template key.",
},
])("refuses to load ($registry)", async ({ load, product, error }) => {
vi.resetModules();
vi.doMock("../../src/contracts/product-contracts.ts", () => product);
await expect(load()).rejects.toThrow(error);
});
});