문제: 짝 백엔드 Redis session 모드를 쿠키 recipe와 매뉴얼 04 4.3대로 이으면 서버 401이 세션에 닿지 않는다. 1103/09-01 수정 뒤 조립 루트는 제품 provider 프로필의 401을 제품의 선택 hook `onCredentialRejected`에만 알린다. 쿠키 모드의 operation은 모두 제품 프로필(SESSION_COOKIE_*)인데 매뉴얼 예시는 그 hook을 잇지 않았고, recipe와 매뉴얼은 "서버 401 → unauthenticated"라고 적었다. 이으려 해도 ProductCompositionContext에 세션에 알릴 길이 없었다. 리뷰 09-cookie401에서 세션 만료 뒤에도 상태가 authenticated, 이전 scope가 current로 남았다. 고른 방법: 두 가지를 더했다. - ProductCompositionContext.notifySessionUnauthenticated(): 템플릿 세션의 자기 401과 같은 판정(authSession.onUnauthenticated)을 제품이 부를 수 있게 한다(리뷰 안 C). - recipe의 createSessionCookieRejectionHandler(context): SESSION_COOKIE_* 프로필의 401만 세션에 넘긴다. 다른 제품 프로필의 401은 넘기지 않으므로 1103/09-01의 완료 기준(세션과 무관한 provider의 401은 로그아웃시키지 않는다)은 그대로다. 매뉴얼 04 4.3 예시에 `onCredentialRejected` 한 줄을 넣고, recipe 주석, 매뉴얼 04 흐름도, 매뉴얼 02 5절과 7절 업로드 예시(BACKEND_SESSION 쿠키 세션)를 맞췄다. 버린 대안: recipe가 owner와 provider를 한 번에 만드는 함수(안 B). owner는 composeProductSessionOwner, provider는 composeProduct 에서 따로 만들어져 모듈 변수가 필요하다. provider 선언에 "세션 자격 증명" 표시를 두는 안(D)은 계약 칸이 늘고 판정이 선언과 hook 둘로 갈린다. 위험·한계: 제품이 이 한 줄을 빼면 여전히 세션 만료를 모른다. 이것을 막는 검사는 없다(매뉴얼과 recipe 주석이 적는다). 이미 recipe를 복사한 다운스트림은 handler를 복사본에 옮기고 composeProduct에 한 줄을 더해야 한다. ProductCompositionContext에 칸이 하나 늘었다. 이 context는 템플릿만 만들므로 제품 코드는 깨지지 않는다. 실제 Redis 백엔드에는 붙이지 않았다(1103/09-03 남은 부분). 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/recipes/session-owners-runtime.test.ts tests/recipes/cookie-session-owner.test.ts 조립 루트를 지나는 테스트가 매뉴얼 4.3 연결로 쿠키 읽기·쓰기 401 뒤 세션 unauthenticated, 이전 scope not current를 본다. Refs: 1105/09-02
438 lines
16 KiB
TypeScript
438 lines
16 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";
|
|
import { testRuntimeConfig } from "../helpers/runtime-config.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,
|
|
createSessionCookieRejectionHandler,
|
|
} = 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,
|
|
}),
|
|
// Manual 04 4.3's cookie wiring (1105/09-02): the server's 401 to a
|
|
// SESSION_COOKIE_* request reaches the session.
|
|
...(fixture.mode === "cookie"
|
|
? { onCredentialRejected: createSessionCookieRejectionHandler(context) }
|
|
: {}),
|
|
};
|
|
},
|
|
};
|
|
});
|
|
|
|
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: testRuntimeConfig({
|
|
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, apiStatus: 200 | 401 = 200) {
|
|
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 });
|
|
}
|
|
// The server session ended after boot (Redis TTL, signed out elsewhere).
|
|
if (apiStatus === 401) {
|
|
return Response.json(
|
|
{ success: false, error: { code: "AUTH_REQUIRED" } },
|
|
{ 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");
|
|
});
|
|
|
|
// 1105/09-02. Manual 04 says a server 401 signs the cookie session out. The
|
|
// template tells a product provider's 401 to the product only (1103/09-01),
|
|
// so without the wiring above the page stayed signed in on the ended
|
|
// session, with the previous scope still current.
|
|
it.each([
|
|
["read", OPERATIONS.cookieRead],
|
|
["write", OPERATIONS.cookieWrite],
|
|
] as const)("signs out when the server answers a cookie %s with 401", async (_label, entry) => {
|
|
fixture.mode = "cookie";
|
|
const page = cookiePage(true, 401);
|
|
const { adapters, http } = 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"),
|
|
);
|
|
const scope = adapters.infrastructure.serverStateScope.getSnapshot();
|
|
|
|
await expect(
|
|
http.execute(operation(entry), { limit: 1 }, { routeId: "R" }),
|
|
).resolves.toMatchObject({ kind: "UNAUTHENTICATED" });
|
|
|
|
await vi.waitFor(() => expect(session.getState()).toBe("unauthenticated"));
|
|
await vi.waitFor(() => expect(scope.isCurrent()).toBe(false));
|
|
});
|
|
});
|