|
| 1 | +// --------------------------------------------------------------------------- |
| 2 | +// Focused tests — the WorkOS login callback's CSRF gate. |
| 3 | +// |
| 4 | +// The callback's CSRF check must be unconditional: no state ⇒ 400 before any |
| 5 | +// WorkOS call; a replayed (already consumed) state ⇒ 400; a fresh state |
| 6 | +// matching the cookie ⇒ 302 + session. |
| 7 | +// |
| 8 | +// Test seams follow repo conventions: @effect/vitest, Layer.succeed stubs |
| 9 | +// (see org-selector-auth.node.test.ts), and HttpRouter.toWebHandler for the |
| 10 | +// HTTP surface (see api.request-scope.node.test.ts). |
| 11 | +// --------------------------------------------------------------------------- |
| 12 | + |
| 13 | +import { afterAll, describe, expect, it } from "@effect/vitest"; |
| 14 | +import { Effect, Layer } from "effect"; |
| 15 | +import { HttpRouter, HttpServer } from "effect/unstable/http"; |
| 16 | +import { HttpApiBuilder } from "effect/unstable/httpapi"; |
| 17 | +import { HttpApi } from "effect/unstable/httpapi"; |
| 18 | + |
| 19 | +import { CloudAuthPublicHandlers } from "./handlers"; |
| 20 | +import { CloudAuthPublicApi } from "./api"; |
| 21 | +import { UserStoreService } from "./context"; |
| 22 | +import { WorkOSClient, type WorkOSClientService } from "./workos"; |
| 23 | +import { encodeLoginState } from "./login-state"; |
| 24 | + |
| 25 | +// The route under test serves under the `/api` prefix in the composed app; |
| 26 | +// toWebHandler mounts the raw group, so paths here are relative to the group. |
| 27 | +const SESSION_COOKIE = "wos-session"; |
| 28 | +const STATE_COOKIE = "wos-login-state"; |
| 29 | + |
| 30 | +const STUB_USER_ID = "user_test"; |
| 31 | +const STUB_SESSION = "sealed-session-stub"; |
| 32 | +const STUB_ORG_ID = "org_test"; |
| 33 | + |
| 34 | +const stubWorkOS = Layer.succeed( |
| 35 | + WorkOSClient, |
| 36 | + new Proxy({} as WorkOSClientService, { |
| 37 | + get: (_t, prop) => { |
| 38 | + if (prop === "authenticateWithCode") { |
| 39 | + return () => |
| 40 | + Effect.succeed({ |
| 41 | + user: { id: STUB_USER_ID, email: "u@test" }, |
| 42 | + organizationId: STUB_ORG_ID, |
| 43 | + sealedSession: STUB_SESSION, |
| 44 | + }); |
| 45 | + } |
| 46 | + if (prop === "listUserMemberships") { |
| 47 | + return () => Effect.succeed({ data: [] }); |
| 48 | + } |
| 49 | + return () => Effect.die(`unexpected WorkOSClient.${String(prop)} call`); |
| 50 | + }, |
| 51 | + }), |
| 52 | +); |
| 53 | + |
| 54 | +const stubUsers = Layer.succeed(UserStoreService)({ |
| 55 | + use: (_op, fn) => |
| 56 | + Effect.promise(() => |
| 57 | + fn({ |
| 58 | + ensureAccount: async (id: string) => ({ id, createdAt: new Date() }), |
| 59 | + getAccount: async (id: string) => ({ id, createdAt: new Date() }), |
| 60 | + upsertOrganization: async (org: { id: string; name: string }) => ({ |
| 61 | + ...org, |
| 62 | + slug: org.id, |
| 63 | + createdAt: new Date(), |
| 64 | + }), |
| 65 | + getOrganization: async (id: string) => ({ |
| 66 | + id, |
| 67 | + name: "Org " + id, |
| 68 | + slug: id, |
| 69 | + createdAt: new Date(), |
| 70 | + }), |
| 71 | + getOrganizationBySlug: async (slug: string) => ({ |
| 72 | + id: slug, |
| 73 | + name: slug, |
| 74 | + slug, |
| 75 | + createdAt: new Date(), |
| 76 | + }), |
| 77 | + deleteOrganizationCascade: async () => {}, |
| 78 | + }), |
| 79 | + ), |
| 80 | +}); |
| 81 | + |
| 82 | +// Only the public group is under test; the session group (and its SessionAuth |
| 83 | +// middleware, which needs a live DB) is out of scope — the callback route lives |
| 84 | +// in CloudAuthPublicApi and requires no middleware. |
| 85 | +const PublicApi = HttpApi.make("cloudWeb").add(CloudAuthPublicApi); |
| 86 | + |
| 87 | +const App = HttpApiBuilder.layer(PublicApi).pipe( |
| 88 | + Layer.provide(CloudAuthPublicHandlers), |
| 89 | + Layer.provide(stubWorkOS), |
| 90 | + Layer.provide(stubUsers), |
| 91 | + Layer.provide(HttpServer.layerServices), |
| 92 | +); |
| 93 | + |
| 94 | +const app = HttpRouter.toWebHandler(App, { disableLogger: true }); |
| 95 | +afterAll(() => app.dispose()); |
| 96 | + |
| 97 | +const run = (request: Request) => { |
| 98 | + // beta.59: the handler type expects a context argument; this layer stack |
| 99 | + // needs none at runtime — pass undefined like the api.request-scope tests. |
| 100 | + return app.handler(request, undefined as never); |
| 101 | +}; |
| 102 | + |
| 103 | +const callbackUrl = (state?: string, code = "code_1") => |
| 104 | + `https://executor.test/auth/callback${state ? `?state=${encodeURIComponent(state)}` : ""}${state ? "&" : "?"}code=${code}`; |
| 105 | + |
| 106 | +describe("workos callback · CSRF state hardening", () => { |
| 107 | + it("rejects a callback with NO state (the former bypass) before any WorkOS call", async () => { |
| 108 | + const res = await run(new Request(callbackUrl(undefined), { redirect: "manual" })); |
| 109 | + expect(res.status).toBe(400); |
| 110 | + expect(await res.text()).toContain("Invalid login state"); |
| 111 | + expect(res.headers.get("set-cookie") ?? "").not.toContain(SESSION_COOKIE); |
| 112 | + }); |
| 113 | + |
| 114 | + it("rejects missing state even when the browser has a login cookie", async () => { |
| 115 | + const res = await run( |
| 116 | + new Request(callbackUrl(undefined), { |
| 117 | + headers: { cookie: `${STATE_COOKIE}=victim-login-state` }, |
| 118 | + redirect: "manual", |
| 119 | + }), |
| 120 | + ); |
| 121 | + expect(res.status).toBe(400); |
| 122 | + expect(await res.text()).toBe("Invalid login state"); |
| 123 | + expect(res.headers.get("set-cookie") ?? "").not.toContain(SESSION_COOKIE); |
| 124 | + }); |
| 125 | + |
| 126 | + it("rejects a state that does not match the login cookie", async () => { |
| 127 | + const res = await run( |
| 128 | + new Request(callbackUrl("attacker-controlled-state"), { |
| 129 | + headers: { cookie: `${STATE_COOKIE}=victim-login-state` }, |
| 130 | + redirect: "manual", |
| 131 | + }), |
| 132 | + ); |
| 133 | + expect(res.status).toBe(400); |
| 134 | + expect(await res.text()).toContain("Invalid login state"); |
| 135 | + }); |
| 136 | + |
| 137 | + it("accepts a fresh state matching the cookie and issues a session (302 + cookie)", async () => { |
| 138 | + // /login sets the cookie; simulate its value for this callback. |
| 139 | + const state = encodeLoginState({ nonce: "nonce-123", returnTo: "/" }); |
| 140 | + const res = await run( |
| 141 | + new Request(callbackUrl(state), { |
| 142 | + headers: { cookie: `${STATE_COOKIE}=${state}` }, |
| 143 | + redirect: "manual", |
| 144 | + }), |
| 145 | + ); |
| 146 | + expect(res.status).toBe(302); |
| 147 | + expect(res.headers.get("set-cookie") ?? "").toContain(SESSION_COOKIE); |
| 148 | + }); |
| 149 | + |
| 150 | + it("rejects a replayed state (single-use contract preserved downstream)", async () => { |
| 151 | + // Replay of a state whose cookie is gone (already consumed by the login |
| 152 | + // round-trip) must fail closed. |
| 153 | + const state = encodeLoginState({ nonce: "nonce-replay", returnTo: "/" }); |
| 154 | + const first = await run( |
| 155 | + new Request(callbackUrl(state), { |
| 156 | + headers: { cookie: `${STATE_COOKIE}=${state}` }, |
| 157 | + redirect: "manual", |
| 158 | + }), |
| 159 | + ); |
| 160 | + expect(first.status).toBe(302); |
| 161 | + |
| 162 | + // Second callback: same state, no cookie (session-store consumed it). |
| 163 | + const replay = await run(new Request(callbackUrl(state), { redirect: "manual" })); |
| 164 | + expect(replay.status).toBe(400); |
| 165 | + }); |
| 166 | +}); |
0 commit comments