문제: 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
242 lines
9.2 KiB
TypeScript
242 lines
9.2 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import type { SessionOwnerFetch } from "../../src/bootstrap/product-composition-contract.ts";
|
|
import { installRestAuthProfileRegistry } from "../../src/contracts/rest-profiles.ts";
|
|
import {
|
|
createCookieSessionOwner,
|
|
createSessionCookieCredentialProviders,
|
|
SESSION_COOKIE_AUTH_PROFILES,
|
|
type CookieSessionOwnerOptions,
|
|
} from "../../recipes/session-owners/cookie-session-owner.ts";
|
|
|
|
/**
|
|
* 1103/09-03. The paired backend's Redis session mode
|
|
* (`APP_SECURITY_AUTH_MODE=redis-session`): an httpOnly `CA_SESSION` cookie,
|
|
* and Spring's `CookieCsrfTokenRepository` with the `XSRF-TOKEN` cookie and
|
|
* the `X-XSRF-TOKEN` header. The backend template ships no sign-in, sign-out
|
|
* or session endpoint, so their URLs are the product's and have no default.
|
|
*/
|
|
|
|
const SESSION_URL = "http://localhost:8080/api/session";
|
|
const SIGN_OUT_URL = "http://localhost:8080/api/session/sign-out";
|
|
|
|
/** The product's session endpoint answers the backend's Envelope. */
|
|
const subjectFrom: CookieSessionOwnerOptions["subjectFrom"] = (body) => {
|
|
const data = (body as { data?: { subject?: unknown } } | null)?.data;
|
|
return typeof data?.subject === "string" ? data.subject : null;
|
|
};
|
|
|
|
function harness(
|
|
answers: Array<() => Response | Promise<Response>> = [],
|
|
cookie: Record<string, string> = { "XSRF-TOKEN": "xsrf-1" },
|
|
) {
|
|
const fetch = vi.fn<SessionOwnerFetch>(async (input) => {
|
|
const answer = answers.shift();
|
|
if (!answer) throw new TypeError(`unexpected ${String(input)}`);
|
|
return answer();
|
|
});
|
|
const beginSignIn = vi.fn(async (_returnTo?: string) => {});
|
|
const options: CookieSessionOwnerOptions = {
|
|
sessionUrl: SESSION_URL,
|
|
signOutUrl: SIGN_OUT_URL,
|
|
subjectFrom,
|
|
beginSignIn,
|
|
fetch,
|
|
readCookie: (name) => cookie[name],
|
|
};
|
|
return { options, fetch, beginSignIn, answers, cookie };
|
|
}
|
|
|
|
const signedIn = (subject = "user-1") => () =>
|
|
Response.json({ success: true, data: { subject } });
|
|
const status = (code: number) => () =>
|
|
Response.json({ success: false, error: { code: "AUTH" } }, { status: code });
|
|
|
|
describe("cookie session owner: state", () => {
|
|
it("asks the session endpoint at boot with the cookie and recovers until it answers", async () => {
|
|
const setup = harness([signedIn()]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
|
|
expect(owner.readState()).toBe("recovery-pending");
|
|
await vi.waitFor(() => expect(owner.readState()).toBe("authenticated"));
|
|
expect(owner.readSubject()).toBe("user-1");
|
|
expect(setup.fetch).toHaveBeenCalledWith(SESSION_URL, {
|
|
method: "GET",
|
|
credentials: "include",
|
|
headers: { accept: "application/json" },
|
|
});
|
|
});
|
|
|
|
it("is signed out when the session endpoint answers 401", async () => {
|
|
const setup = harness([status(401)]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
|
|
await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated"));
|
|
expect(owner.readSubject()).toBeNull();
|
|
});
|
|
|
|
it("is signed out when the 200 names nobody", async () => {
|
|
const setup = harness([() => Response.json({ success: true, data: {} })]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
|
|
await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated"));
|
|
});
|
|
|
|
it("stays recovering when the endpoint cannot answer, and recovers on request", async () => {
|
|
const setup = harness([
|
|
() => {
|
|
throw new DOMException("timed out", "TimeoutError");
|
|
},
|
|
status(503),
|
|
signedIn(),
|
|
]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
|
|
// The first joins the boot probe, which times out; the second gets a 503.
|
|
await expect(owner.recoverSession()).rejects.toThrow("timed out");
|
|
await expect(owner.recoverSession()).rejects.toThrow("503");
|
|
expect(owner.readState()).toBe("recovery-pending");
|
|
await expect(owner.recoverSession()).resolves.toBe("restored");
|
|
expect(setup.fetch).toHaveBeenCalledTimes(3);
|
|
expect(owner.readState()).toBe("authenticated");
|
|
});
|
|
|
|
it("answers no-session already signed out, never still recovering", async () => {
|
|
const setup = harness([status(401), status(401)]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated"));
|
|
|
|
await expect(owner.recoverSession()).resolves.toBe("no-session");
|
|
expect(owner.readState()).toBe("unauthenticated");
|
|
});
|
|
|
|
it("shares one probe between boot and a recovery that starts meanwhile", async () => {
|
|
const setup = harness([signedIn()]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
|
|
await expect(owner.recoverSession()).resolves.toBe("restored");
|
|
expect(setup.fetch).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("signs out on a server 401 and notifies once per change", async () => {
|
|
const setup = harness([signedIn()]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
await vi.waitFor(() => expect(owner.readState()).toBe("authenticated"));
|
|
const listener = vi.fn();
|
|
owner.subscribe(listener);
|
|
|
|
owner.notifyUnauthenticated();
|
|
owner.notifyUnauthenticated();
|
|
|
|
expect(owner.readState()).toBe("unauthenticated");
|
|
expect(listener).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("refuses an over-long or empty subject", async () => {
|
|
const setup = harness([signedIn("x".repeat(256))]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
|
|
await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated"));
|
|
});
|
|
});
|
|
|
|
describe("cookie session owner: sign-in, sign-out, credentials", () => {
|
|
it("hands sign-in to the product", async () => {
|
|
const setup = harness([status(401)]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
|
|
await owner.beginSignIn("/items");
|
|
|
|
expect(setup.beginSignIn).toHaveBeenCalledWith("/items");
|
|
});
|
|
|
|
it("signs out with the CSRF header and is signed out after the server agrees", async () => {
|
|
const setup = harness([signedIn(), () => new Response(null, { status: 204 })]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
await vi.waitFor(() => expect(owner.readState()).toBe("authenticated"));
|
|
|
|
await owner.signOut();
|
|
|
|
expect(setup.fetch).toHaveBeenLastCalledWith(SIGN_OUT_URL, {
|
|
method: "POST",
|
|
credentials: "include",
|
|
headers: { "x-xsrf-token": "xsrf-1" },
|
|
});
|
|
expect(owner.readState()).toBe("unauthenticated");
|
|
});
|
|
|
|
it("keeps the session when the server did not sign it out", async () => {
|
|
const setup = harness([signedIn(), status(403)]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
await vi.waitFor(() => expect(owner.readState()).toBe("authenticated"));
|
|
|
|
await expect(owner.signOut()).rejects.toThrow();
|
|
expect(owner.readState()).toBe("authenticated");
|
|
});
|
|
|
|
it("sends no bearer header: operations use the cookie profiles", async () => {
|
|
const setup = harness([signedIn()]);
|
|
const owner = createCookieSessionOwner(setup.options);
|
|
|
|
await expect(
|
|
owner.attachCredential({ origin: "http://localhost:8080", method: "GET", operationId: "X" }),
|
|
).rejects.toThrow("SESSION_COOKIE_");
|
|
});
|
|
});
|
|
|
|
describe("session cookie credential providers", () => {
|
|
const operation = (authProfileId: string, method = "POST") =>
|
|
Object.freeze({ operationId: "WRITE", authProfileId, method });
|
|
const context = Object.freeze({
|
|
signal: new AbortController().signal,
|
|
deadlineAtMonotonicMs: 0,
|
|
});
|
|
|
|
it("installs as product auth profiles under the template's checks", () => {
|
|
const registry = installRestAuthProfileRegistry(SESSION_COOKIE_AUTH_PROFILES);
|
|
|
|
expect(registry.get("SESSION_COOKIE_READ")).toMatchObject({
|
|
transport: "SAME_ORIGIN_COOKIE",
|
|
credentials: "include",
|
|
requiredCredentialHeaders: [],
|
|
});
|
|
expect(registry.get("SESSION_COOKIE_WRITE")).toMatchObject({
|
|
transport: "SAME_ORIGIN_COOKIE",
|
|
credentials: "include",
|
|
allowedCredentialHeaders: ["x-xsrf-token"],
|
|
requiredCredentialHeaders: ["x-xsrf-token"],
|
|
});
|
|
});
|
|
|
|
it("sends the XSRF-TOKEN cookie as X-XSRF-TOKEN on writes", async () => {
|
|
const providers = createSessionCookieCredentialProviders({
|
|
readCookie: (name) => (name === "XSRF-TOKEN" ? "xsrf-1" : undefined),
|
|
});
|
|
|
|
await expect(
|
|
providers.SESSION_COOKIE_WRITE(operation("SESSION_COOKIE_WRITE"), context),
|
|
).resolves.toEqual({ kind: "READY", headers: { "x-xsrf-token": "xsrf-1" } });
|
|
await expect(
|
|
providers.SESSION_COOKIE_READ(operation("SESSION_COOKIE_READ", "GET"), context),
|
|
).resolves.toEqual({ kind: "READY", headers: {} });
|
|
});
|
|
|
|
it("fails a write closed without the cookie, so nothing is sent", async () => {
|
|
const providers = createSessionCookieCredentialProviders({ readCookie: () => undefined });
|
|
|
|
await expect(
|
|
providers.SESSION_COOKIE_WRITE(operation("SESSION_COOKIE_WRITE"), context),
|
|
).resolves.toEqual({ kind: "UNAVAILABLE" });
|
|
});
|
|
|
|
it("reads the cookie when the request goes, not when composed", async () => {
|
|
let token: string | undefined;
|
|
const providers = createSessionCookieCredentialProviders({ readCookie: () => token });
|
|
token = "xsrf-2";
|
|
|
|
await expect(
|
|
providers.SESSION_COOKIE_WRITE(operation("SESSION_COOKIE_WRITE"), context),
|
|
).resolves.toEqual({ kind: "READY", headers: { "x-xsrf-token": "xsrf-2" } });
|
|
});
|
|
});
|