문제: AUTH_MODE external은 제품이 owner 8개 메서드를 직접 써야 하는데, 짝 백엔드(JWT·Keycloak 또는 Redis session)에 맞는 owner가 src·recipes 어디에도 없다. 쿠키 owner 모양은 테스트 파일 안 스케치뿐이다. 그래서 제품마다 첫 연동 전에 토큰 획득·갱신·subject·상태 전이·401 처리를 처음부터 쓴다. 짝 백엔드(bbe944bd)에서 확인한 계약: - jwt 모드(기본): OAuth2 resource server. iss = APP_SECURITY_JWT_ISSUER (local http://localhost:8081/realms/ca-skeleton), aud 필수. CSRF·세션 없음. 그러나 realm에는 서비스용 confidential client(ca-skeleton-api, standard flow 꺼짐)만 있고 브라우저용 public client가 없다. - redis-session 모드: CA_SESSION httpOnly 쿠키, CookieCsrfTokenRepository (XSRF-TOKEN 쿠키, X-XSRF-TOKEN 헤더, plain handler). 로그인·로그아웃· 세션 조회·CSRF 발급 엔드포인트는 운영 코드에 없다(테스트 픽스처만). 고른 방법: recipes/session-owners/에 둘을 둔다. 제품은 src/bootstrap/로 복사해 composeProductSessionOwner에서 돌려준다. - oidc-pkce-session-owner.ts: authorization code + PKCE S256, WebCrypto와 context fetch만 쓴다(라이브러리 없음). 토큰은 메모리에만, sessionStorage 에는 10분짜리 거래(verifier·state·nonce·returnTo)만 두고 콜백이 먼저 지운다. 콜백 URL에서 code를 네트워크 호출 전에 지운다. state·RFC 9207 iss·nonce·aud·azp·exp·sub를 검사하고, 갱신 때 sub가 바뀌면 로그아웃. bearer는 apiOrigins에만 보낸다. 만료 30초 전 갱신은 한 번만 하고 상태 알림이 없다. 401이면 refresh token으로 한 번 복구하고, 그 토큰도 401이면 로그아웃. 설정이 틀리면 integration-failed로 닫는다. - cookie-session-owner.ts: 세션 조회·로그아웃 URL과 로그인 시작을 기본값 없이 받는다(백엔드에 없는 엔드포인트를 지어내지 않는다). 200+subject → authenticated, 401 → unauthenticated, 그 밖은 reject(상태 유지). SESSION_COOKIE_READ/WRITE 프로필과 XSRF-TOKEN → x-xsrf-token provider. 쿠키가 없으면 쓰기는 UNAVAILABLE로 아무것도 보내지 않는다. - 두 owner 모두 SessionState·recover 전이 계약을 따른다. - PRODUCTION_IMPORTS_RECIPE 검사를 recipes/session-owners에도 건다. recipe는 복사하지 import하지 않는다(초기 번들 밖). 버린 대안: src에 기본 owner 내장(IdP 결합이 템플릿 본체에 들어간다), OIDC 라이브러리 의존(fetch·WebCrypto로 충분), 매뉴얼만(같은 실수 반복). 위험·한계: 실제 Keycloak·Redis session 백엔드에 붙여 보지 않았다. ID token 서명은 검사하지 않는다(토큰 엔드포인트 직접 응답, OIDC Core 3.1.3.7 (6)); access token 서명은 백엔드가 본다. 새로고침하면 메모리 토큰이 사라져 다시 로그인한다(Keycloak SSO면 비밀번호 없이 돌아온다). 쿠키 모드는 페이지와 API가 같은 host여야 XSRF-TOKEN을 읽는다. 검증: tests/recipes 3파일 52건(구현 전 모듈 없음으로 실패 확인). 변이 15개(state·origin·401 한 번·nonce·iss·URL 정리·갱신 sub·TTL, CSRF 헤더·401·로그아웃 실패·notify·단일 조회·subject 상한·credentials) 모두 실패로 잡힘. runtime 조립 테스트 4건이 실제 createRuntimeAdapters로 EXTERNAL_BEARER bearer, 401 뒤 갱신, 쿠키 쓰기의 x-xsrf-token을 확인. check:optional-recipe-fixtures(regex 변경 없이는 실패 확인), check:optional-recipes:source, check:types, eslint 통과. 두 recipe의 minify+gzip 크기 3.8 kB, 1.1 kB. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-03
397 lines
14 KiB
TypeScript
397 lines
14 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts";
|
|
import type {
|
|
ProductCompositionContext,
|
|
ProductSessionOwnerContext,
|
|
} from "../../src/bootstrap/product-composition-contract.ts";
|
|
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
|
|
import { OIDC_PKCE_TRANSACTION_KEY } from "../../recipes/session-owners/oidc-pkce-session-owner.ts";
|
|
import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
|
|
|
|
/**
|
|
* 1103/09-03 completion check, short of the real backend: each recipe wired
|
|
* the way docs/manual/04-paired-backend-session.md tells a product to, through
|
|
* the template's real composition root. Only the two product-owned files, the
|
|
* installed contract set (adds the operations) and the feature-input composer
|
|
* (to reach the `http` capability) are replaced.
|
|
*/
|
|
|
|
const ISSUER = "http://localhost:8081/realms/ca-skeleton";
|
|
const APP = "http://localhost:5173";
|
|
const API = "http://localhost:8080";
|
|
|
|
const fixture = vi.hoisted(() => ({
|
|
mode: "oidc" as "oidc" | "cookie",
|
|
http: undefined as InstalledHttpOperationExecutor | 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` for the cookie mode. */
|
|
vi.mock("../../src/contracts/product-contracts.ts", async () => {
|
|
const { SESSION_COOKIE_AUTH_PROFILES } = await import(
|
|
"../../recipes/session-owners/cookie-session-owner.ts"
|
|
);
|
|
return {
|
|
PRODUCT_RUNTIME_CONFIG_FIELDS: Object.freeze({}),
|
|
PRODUCT_ENV_REGISTRY: Object.freeze({}),
|
|
PRODUCT_REST_AUTH_PROFILES: SESSION_COOKIE_AUTH_PROFILES,
|
|
};
|
|
});
|
|
|
|
/** The product's `src/bootstrap/product-composition.ts`, one mode at a time. */
|
|
vi.mock("../../src/bootstrap/product-composition.ts", async () => {
|
|
const { createOidcPkceSessionOwner } = await import(
|
|
"../../recipes/session-owners/oidc-pkce-session-owner.ts"
|
|
);
|
|
const { createCookieSessionOwner, createSessionCookieCredentialProviders } = await import(
|
|
"../../recipes/session-owners/cookie-session-owner.ts"
|
|
);
|
|
return {
|
|
composeProductSessionOwner(context: ProductSessionOwnerContext) {
|
|
const api = new URL(context.config.API_BASE_URL);
|
|
return fixture.mode === "oidc"
|
|
? createOidcPkceSessionOwner({
|
|
issuer: ISSUER,
|
|
clientId: "ca-frontend",
|
|
redirectUri: `${APP}/`,
|
|
apiOrigins: [api.origin],
|
|
fetch: context.fetch,
|
|
page: context.page,
|
|
redirectStorage: context.redirectStorage,
|
|
})
|
|
: createCookieSessionOwner({
|
|
sessionUrl: new URL("api/session", api).href,
|
|
signOutUrl: new URL("api/session/sign-out", api).href,
|
|
subjectFrom: (body) =>
|
|
(body as { data?: { subject?: string } }).data?.subject ?? null,
|
|
beginSignIn: async () => context.page.assign(`${APP}/login`),
|
|
fetch: context.fetch,
|
|
readCookie: context.readCookie,
|
|
});
|
|
},
|
|
composeProduct(context: ProductCompositionContext) {
|
|
return {
|
|
capabilities: {},
|
|
credentialProviders: createSessionCookieCredentialProviders({
|
|
readCookie: context.readCookie,
|
|
}),
|
|
};
|
|
},
|
|
};
|
|
});
|
|
|
|
const OPERATIONS = vi.hoisted(() => ({
|
|
bearer: ["LIST_BEARER", "EXTERNAL_BEARER"],
|
|
cookieRead: ["LIST_COOKIE_READ", "SESSION_COOKIE_READ"],
|
|
cookieWrite: ["LIST_COOKIE_WRITE", "SESSION_COOKIE_WRITE"],
|
|
} as const));
|
|
|
|
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: contribution, TEST_LIST_HTTP_CONTRACT: list } =
|
|
await import("../helpers/external-contract-fixture.ts");
|
|
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: Object.values(OPERATIONS).map(([operationId, authProfileId]) =>
|
|
fixture.withProfile(list, operationId, authProfileId),
|
|
) as unknown 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.http = Reflect.get(args[0], "http") as InstalledHttpOperationExecutor;
|
|
return original.createInstalledFeatureLoaders(...args);
|
|
},
|
|
};
|
|
});
|
|
|
|
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
const jwt = (claims: Record<string, unknown>) =>
|
|
`${encode({ alg: "RS256" })}.${encode(claims)}.signature`;
|
|
|
|
let dispose: (() => void) | undefined;
|
|
afterEach(() => {
|
|
dispose?.();
|
|
dispose = undefined;
|
|
fixture.http = undefined;
|
|
});
|
|
|
|
async function compose(
|
|
host: Record<string, unknown>,
|
|
respond: (url: string, init: RequestInit) => Response,
|
|
) {
|
|
const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) =>
|
|
respond(String(input), init ?? {}),
|
|
);
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime: {
|
|
config: {
|
|
APP_ENV: "local",
|
|
API_BASE_URL: `${API}/`,
|
|
TELEMETRY_ENABLED: false,
|
|
AUTH_MODE: "external",
|
|
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,
|
|
},
|
|
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" },
|
|
},
|
|
host,
|
|
fetcher: fetcher as unknown as typeof fetch,
|
|
});
|
|
dispose = () => adapters.infrastructure.dispose();
|
|
const http = fixture.http;
|
|
if (!http) throw new Error("The http capability was not composed");
|
|
return { adapters, http, fetcher };
|
|
}
|
|
|
|
const operation = (entry: readonly [string, string]) =>
|
|
fixture.withProfile(TEST_LIST_HTTP_CONTRACT, ...entry);
|
|
|
|
function apiCalls(fetcher: ReturnType<typeof vi.fn>) {
|
|
return fetcher.mock.calls
|
|
.map(([url, init]) => ({ url: String(url), init: (init ?? {}) as RequestInit }))
|
|
.filter((call) => call.url.startsWith(`${API}/api/test-entities`));
|
|
}
|
|
|
|
describe("OIDC PKCE owner in the composition root (JWT mode)", () => {
|
|
function signInReturn() {
|
|
const storage = new Map([
|
|
[
|
|
OIDC_PKCE_TRANSACTION_KEY,
|
|
JSON.stringify({
|
|
v: 1,
|
|
state: "state-1",
|
|
nonce: "nonce-1",
|
|
verifier: "v".repeat(43),
|
|
returnTo: "/items",
|
|
createdAt: Date.now(),
|
|
}),
|
|
],
|
|
]);
|
|
const replaceState = vi.fn();
|
|
const host = {
|
|
location: { href: `${APP}/?code=code-1&state=state-1&iss=${encodeURIComponent(ISSUER)}`, assign: vi.fn() },
|
|
history: { state: null, replaceState },
|
|
sessionStorage: {
|
|
getItem: (key: string) => storage.get(key) ?? null,
|
|
setItem: (key: string, value: string) => void storage.set(key, value),
|
|
removeItem: (key: string) => void storage.delete(key),
|
|
},
|
|
};
|
|
let issued = 0;
|
|
let apiStatus = 200;
|
|
const respond = (url: string) => {
|
|
if (url.endsWith("/.well-known/openid-configuration")) {
|
|
return Response.json({
|
|
issuer: ISSUER,
|
|
authorization_endpoint: `${ISSUER}/protocol/openid-connect/auth`,
|
|
token_endpoint: `${ISSUER}/protocol/openid-connect/token`,
|
|
});
|
|
}
|
|
if (url === `${ISSUER}/protocol/openid-connect/token`) {
|
|
issued += 1;
|
|
return Response.json({
|
|
access_token: `access-${issued}`,
|
|
token_type: "Bearer",
|
|
expires_in: 300,
|
|
refresh_token: `refresh-${issued}`,
|
|
id_token: jwt({
|
|
iss: ISSUER,
|
|
aud: "ca-frontend",
|
|
sub: "user-1",
|
|
nonce: "nonce-1",
|
|
exp: Math.floor(Date.now() / 1000) + 300,
|
|
}),
|
|
});
|
|
}
|
|
if (apiStatus === 401) {
|
|
apiStatus = 200;
|
|
return Response.json(
|
|
{ success: false, error: { code: "AUTH_TOKEN_EXPIRED" } },
|
|
{ status: 401, headers: { "www-authenticate": "Bearer" } },
|
|
);
|
|
}
|
|
return Response.json([{ id: "entity-1", name: "Entity" }]);
|
|
};
|
|
return {
|
|
host,
|
|
storage,
|
|
replaceState,
|
|
respond,
|
|
failNextApiCall() {
|
|
apiStatus = 401;
|
|
},
|
|
};
|
|
}
|
|
|
|
it("signs in on the returning page load and sends the bearer on EXTERNAL_BEARER", async () => {
|
|
fixture.mode = "oidc";
|
|
const page = signInReturn();
|
|
const { adapters, http, fetcher } = await compose(page.host, page.respond);
|
|
const session = adapters.outputPorts.session;
|
|
|
|
expect(page.replaceState).toHaveBeenCalledWith(null, "", "/items");
|
|
expect(page.storage.size).toBe(0);
|
|
await vi.waitFor(() => expect(session.getState()).toBe("authenticated"));
|
|
expect(session.getSubject()).toBe("user-1");
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
|
|
const outcome = await http.execute(operation(OPERATIONS.bearer), { limit: 1 }, { routeId: "R" });
|
|
|
|
expect(outcome.kind).toBe("SUCCESS");
|
|
const [call] = apiCalls(fetcher);
|
|
expect(new Headers(call!.init.headers).get("authorization")).toBe("Bearer access-1");
|
|
expect(call!.init.credentials).toBe("omit");
|
|
});
|
|
|
|
it("turns a server 401 into one refresh and keeps the same subject", async () => {
|
|
fixture.mode = "oidc";
|
|
const page = signInReturn();
|
|
const { adapters, http, fetcher } = await compose(page.host, page.respond);
|
|
const session = adapters.outputPorts.session;
|
|
await vi.waitFor(() => expect(session.getState()).toBe("authenticated"));
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
page.failNextApiCall();
|
|
|
|
await expect(
|
|
http.execute(operation(OPERATIONS.bearer), { limit: 1 }, { routeId: "R" }),
|
|
).resolves.toMatchObject({ kind: "UNAUTHENTICATED" });
|
|
|
|
await vi.waitFor(() => expect(session.getState()).toBe("authenticated"));
|
|
expect(session.getSubject()).toBe("user-1");
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
await http.execute(operation(OPERATIONS.bearer), { limit: 1 }, { routeId: "R" });
|
|
expect(new Headers(apiCalls(fetcher).at(-1)!.init.headers).get("authorization")).toBe(
|
|
"Bearer access-2",
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("cookie owner and CSRF providers in the composition root (Redis session mode)", () => {
|
|
function cookiePage(signedIn = true) {
|
|
const host = {
|
|
location: { href: `${APP}/items`, assign: vi.fn() },
|
|
history: { state: null, replaceState: vi.fn() },
|
|
document: { cookie: "XSRF-TOKEN=xsrf-1" },
|
|
};
|
|
const respond = (url: string) => {
|
|
if (url === `${API}/api/session`) {
|
|
return signedIn
|
|
? Response.json({ success: true, data: { subject: "user-1" } })
|
|
: Response.json({ success: false }, { status: 401 });
|
|
}
|
|
return Response.json([{ id: "entity-1", name: "Entity" }]);
|
|
};
|
|
return { host, respond };
|
|
}
|
|
|
|
it("asks the session at boot and sends writes with the cookie and X-XSRF-TOKEN", async () => {
|
|
fixture.mode = "cookie";
|
|
const page = cookiePage();
|
|
const { adapters, http, fetcher } = await compose(page.host, page.respond);
|
|
const session = adapters.outputPorts.session;
|
|
expect(session.getState()).toBe("recovery-pending");
|
|
await vi.waitFor(() => expect(session.getState()).toBe("authenticated"));
|
|
expect(fetcher.mock.calls[0]?.[1]).toMatchObject({ credentials: "include", redirect: "error" });
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
|
|
await expect(
|
|
http.execute(operation(OPERATIONS.cookieWrite), { limit: 1 }, { routeId: "R" }),
|
|
).resolves.toMatchObject({ kind: "SUCCESS" });
|
|
await expect(
|
|
http.execute(operation(OPERATIONS.cookieRead), { limit: 1 }, { routeId: "R" }),
|
|
).resolves.toMatchObject({ kind: "SUCCESS" });
|
|
|
|
const [write, read] = apiCalls(fetcher);
|
|
expect(write!.init.credentials).toBe("include");
|
|
expect(new Headers(write!.init.headers).get("x-xsrf-token")).toBe("xsrf-1");
|
|
expect(read!.init.credentials).toBe("include");
|
|
expect(new Headers(read!.init.headers).has("x-xsrf-token")).toBe(false);
|
|
expect(new Headers(read!.init.headers).has("authorization")).toBe(false);
|
|
});
|
|
|
|
it("is signed out when the session endpoint says nobody is", async () => {
|
|
fixture.mode = "cookie";
|
|
const page = cookiePage(false);
|
|
const { adapters } = await compose(page.host, page.respond);
|
|
|
|
await vi.waitFor(() =>
|
|
expect(adapters.outputPorts.session.getState()).toBe("unauthenticated"),
|
|
);
|
|
await expect(adapters.outputPorts.session.recover()).resolves.toBe("no-session");
|
|
});
|
|
});
|