문제: 짝 백엔드 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
264 lines
10 KiB
TypeScript
264 lines
10 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,
|
|
createSessionCookieRejectionHandler,
|
|
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" } });
|
|
});
|
|
});
|
|
|
|
/**
|
|
* 1105/09-02. The template tells a product provider's 401 to the product
|
|
* (`onCredentialRejected`), not to the session. For the cookie profiles the
|
|
* credential is the session's own cookie, so this handler passes it on; a
|
|
* 401 on another product profile is not the session's.
|
|
*/
|
|
describe("session cookie rejection handler", () => {
|
|
it("tells the session about a 401 on a SESSION_COOKIE_* profile only", () => {
|
|
const notifySessionUnauthenticated = vi.fn();
|
|
const onCredentialRejected = createSessionCookieRejectionHandler({
|
|
notifySessionUnauthenticated,
|
|
});
|
|
|
|
onCredentialRejected({ operationId: "LIST", authProfileId: "SESSION_COOKIE_READ" });
|
|
onCredentialRejected({ operationId: "SAVE", authProfileId: "SESSION_COOKIE_WRITE" });
|
|
onCredentialRejected({ operationId: "PARTNER", authProfileId: "PARTNER_API_TOKEN" });
|
|
|
|
expect(notifySessionUnauthenticated).toHaveBeenCalledTimes(2);
|
|
});
|
|
});
|