Repository Public
1import { describe, expect, it, vi } from "vitest";2import { createTransport } from "./transport";34const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });5const stepUpRequired = () => json(403, { error: { code: "step_up_required", message: "A recent passkey verification is required.", correlation_id: "c-1" } });6const post = (body: unknown, headers: Record<string, string> = {}) => new Request("http://localhost/api/v1/actions", { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json", ...headers } });78describe("transport", () => {9 it("adds X-MCC-CSRF to non-safe requests only, from memory", async () => {10 const seen: Request[] = [];11 const t = createTransport(async (r) => { seen.push(r); return json(200, {}); });12 await t.fetch(post({}));13 expect(seen[0]?.headers.get("X-MCC-CSRF")).toBeNull();14 t.setCsrf("tok");15 await t.fetch(post({}));16 await t.fetch(new Request("http://localhost/api/v1/me"));17 expect(seen[1]?.headers.get("X-MCC-CSRF")).toBe("tok");18 expect(seen[2]?.headers.get("X-MCC-CSRF")).toBeNull();19 expect(t.getCsrf()).toBe("tok");20 });2122 it("on step_up_required runs the ceremony and replays the original request once, unchanged", async () => {23 const bodies: string[] = [];24 const keys: (string | null)[] = [];25 const base = vi.fn(async (r: Request) => {26 bodies.push(await r.text());27 keys.push(r.headers.get("Idempotency-Key"));28 return base.mock.calls.length === 1 ? stepUpRequired() : json(201, { id: "a1" });29 });30 const stepUp = vi.fn().mockResolvedValue(true);31 const t = createTransport(base);32 t.setCsrf("tok");33 t.setHooks({ stepUp });34 const res = await t.fetch(post({ type: "system.reboot" }, { "Idempotency-Key": "k-1" }));35 expect(res.status).toBe(201);36 expect(stepUp).toHaveBeenCalledTimes(1);37 expect(bodies).toEqual(['{"type":"system.reboot"}', '{"type":"system.reboot"}']);38 expect(keys).toEqual(["k-1", "k-1"]);39 });4041 it("uses the CSRF token current at replay time", async () => {42 const seen: (string | null)[] = [];43 const base = vi.fn(async (r: Request) => { seen.push(r.headers.get("X-MCC-CSRF")); return seen.length === 1 ? stepUpRequired() : json(200, {}); });44 const t = createTransport(base);45 t.setCsrf("old");46 t.setHooks({ stepUp: async () => { t.setCsrf("new"); return true; } });47 await t.fetch(post({}));48 expect(seen).toEqual(["old", "new"]);49 });5051 it("returns the 403 untouched when the user cancels the step-up, or when no handler exists", async () => {52 const base = vi.fn(async () => stepUpRequired());53 const t = createTransport(base);54 expect((await t.fetch(post({}))).status).toBe(403);55 t.setHooks({ stepUp: async () => false });56 const res = await t.fetch(post({}));57 expect(res.status).toBe(403);58 expect(((await res.json()) as { error: { code: string } }).error.code).toBe("step_up_required");59 expect(base).toHaveBeenCalledTimes(2);60 });6162 it("retries only once: a second step_up_required is returned as is", async () => {63 const base = vi.fn(async () => stepUpRequired());64 const stepUp = vi.fn().mockResolvedValue(true);65 const t = createTransport(base);66 t.setHooks({ stepUp });67 expect((await t.fetch(post({}))).status).toBe(403);68 expect(base).toHaveBeenCalledTimes(2);69 expect(stepUp).toHaveBeenCalledTimes(1);70 });7172 it("does not step up for other 403s nor for the step-up endpoints themselves", async () => {73 const stepUp = vi.fn().mockResolvedValue(true);74 const t = createTransport(async (r) => (r.url.includes("/auth/stepup/") ? stepUpRequired() : json(403, { error: { code: "forbidden", message: "no", correlation_id: "c", details: { permission: "audit.read" } } })));75 t.setHooks({ stepUp });76 expect((await t.fetch(post({}))).status).toBe(403);77 expect((await t.fetch(new Request("http://localhost/api/v1/auth/stepup/finish", { method: "POST" }))).status).toBe(403);78 expect(stepUp).not.toHaveBeenCalled();79 });8081 it("shares one ceremony between concurrent requests", async () => {82 let n = 0;83 const base = vi.fn(async () => (++n <= 2 ? stepUpRequired() : json(200, {})));84 let release!: (ok: boolean) => void;85 const stepUp = vi.fn(() => new Promise<boolean>((r) => { release = r; }));86 const t = createTransport(base);87 t.setHooks({ stepUp });88 const both = Promise.all([t.fetch(post({ a: 1 })), t.fetch(post({ a: 2 }))]);89 await new Promise((r) => setTimeout(r, 0));90 release(true);91 expect((await both).map((r) => r.status)).toEqual([200, 200]);92 expect(stepUp).toHaveBeenCalledTimes(1);93 });9495 it("reports 401 with the error code and merges hooks", async () => {96 const onUnauthenticated = vi.fn();97 const stepUp = vi.fn().mockResolvedValue(true);98 const t = createTransport(async () => json(401, { error: { code: "session_expired", message: "x", correlation_id: "c" } }));99 t.setHooks({ onUnauthenticated });100 t.setHooks({ stepUp }); // must not drop the first hook101 expect((await t.fetch(new Request("http://localhost/api/v1/nodes"))).status).toBe(401);102 expect(onUnauthenticated).toHaveBeenCalledWith("session_expired");103 });104});105