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> = [], cookie: Record = { "XSRF-TOKEN": "xsrf-1" }, ) { const fetch = vi.fn(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); }); });