History

Restart hosted invitation logins with fresh state

Rhys Sullivan committed 2 months ago

Commit 2ad15a51 parent f60ae014 files · +97 −25Browse files

Unified · Split

4 files
  1. .changeset/restart-hosted-invitation-login.md +5 −0
  2. apps/cloud/src/auth/handlers.ts +12 −7
  3. apps/cloud/src/auth/workos-callback-state.node.test.ts +26 −15
  4. e2e/cloud/login-csrf.test.ts +54 −3
.changeset/restart-hosted-invitation-login.md+5−0
@@ -0,0 +1,5 @@
1+---
2+"@executor-js/cloud": patch
3+---
4+
5+Restart hosted invitation logins that return without state, while keeping authorization codes bound to the browser that started the login.
apps/cloud/src/auth/handlers.ts+12−7
@@ -188,14 +188,19 @@ export const CloudAuthPublicHandlers = HttpApiBuilder.group( · 187 unmodified lines
188188 Effect.gen(function* () {
189189 const workos = yield* WorkOSClient;
190190 const users = yield* UserStoreService;
191+ // Hosted invitations can start at WorkOS without app-issued state.
192+ // Discard that unbound code and start a fresh browser-bound login.
193+ // Exchanging it here would allow login CSRF.
194+ if (query.state === undefined) {
195+ return deleteResponseCookie(
196+ HttpServerResponse.redirect(AUTH_PATHS.login, { status: 302 }),
197+ STATE_COOKIE,
198+ );
199+ }
200+
191201 const cookieState = request.cookies[STATE_COOKIE] ?? null;
192− // CSRF is unconditional: every callback must carry a state that
193− // matches the cookie set on /login. There is no legitimate
194− // no-state entry path — omitting state previously allowed an
195− // attacker to complete their own OAuth round-trip and redirect a
196− // victim's browser through this callback, signing the victim into
197− // the attacker's account (login CSRF).
198− if (!cookieState || !timingSafeEqual(cookieState, query.state ?? "")) {
202+ // Only exchange codes bound to the state cookie set on /login.
203+ if (!cookieState || !timingSafeEqual(cookieState, query.state)) {
199204 return deleteResponseCookie(
200205 HttpServerResponse.text("Invalid login state", { status: 400 }),
201206 STATE_COOKIE,
apps/cloud/src/auth/workos-callback-state.node.test.ts+26−15
@@ -1,9 +1,8 @@
11 // ---------------------------------------------------------------------------
22 // Focused tests — the WorkOS login callback's CSRF gate.
33 //
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.
4+// Codes without state restart login without a WorkOS exchange; a replayed
5+// state still fails with 400; a fresh state matching the cookie issues a session.
76 //
87 // Test seams follow repo conventions: @effect/vitest, Layer.succeed stubs
98 // (see org-selector-auth.node.test.ts), and HttpRouter.toWebHandler for the
@@ -38,12 +37,14 @@ const stubWorkOS = Layer.succeed( · 28 unmodified lines
3837 new Proxy({} as WorkOSClientService, {
3938 get: (_t, prop) => {
4039 if (prop === "authenticateWithCode") {
41− return () =>
42− Effect.succeed({
43− user: { id: STUB_USER_ID, email: "u@test" },
44− organizationId: STUB_ORG_ID,
45− sealedSession: STUB_SESSION,
46− });
40+ return (code: string) =>
41+ code === "unbound-code"
42+ ? Effect.die("An unbound authorization code must never be exchanged")
43+ : Effect.succeed({
44+ user: { id: STUB_USER_ID, email: "u@test" },
45+ organizationId: STUB_ORG_ID,
46+ sealedSession: STUB_SESSION,
47+ });
4748 }
4849 if (prop === "listUserMemberships") {
4950 return () => Effect.succeed({ data: [] });
@@ -128,20 +129,30 @@ describe("workos callback · CSRF state hardening", () => { · 78 unmodified lines
128129 });
129130 }
130131
131− it("rejects a callback with NO state (the former bypass) before any WorkOS call", async () => {
132− const res = await run(new Request(callbackUrl(undefined), { redirect: "manual" }));
133− expect(res.status).toBe(400);
134− expect(await res.text()).toContain("Invalid login state");
132+ it("restarts login without exchanging a code that has no state", async () => {
133+ const res = await run(
134+ new Request(callbackUrl(undefined, "unbound-code"), { redirect: "manual" }),
135+ );
136+ expect(res.status).toBe(302);
137+ expect(res.headers.get("location")).toBe("/api/auth/login");
135138 expect(res.headers.get("set-cookie") ?? "").not.toContain(SESSION_COOKIE);
136139 });
137140
138− it("rejects missing state even when the browser has a login cookie", async () => {
141+ it("discards an existing login cookie when restarting a callback without state", async () => {
139142 const res = await run(
140− new Request(callbackUrl(undefined), {
143+ new Request(callbackUrl(undefined, "unbound-code"), {
141144 headers: { cookie: `${STATE_COOKIE}=victim-login-state` },
142145 redirect: "manual",
143146 }),
144147 );
148+ expect(res.status).toBe(302);
149+ expect(res.headers.get("location")).toBe("/api/auth/login");
150+ expect(res.headers.get("set-cookie")).toContain(`${STATE_COOKIE}=; Max-Age=0`);
151+ expect(res.headers.get("set-cookie") ?? "").not.toContain(SESSION_COOKIE);
152+ });
153+
154+ it("rejects empty state instead of treating it as a provider-initiated login", async () => {
155+ const res = await run(new Request(`${callbackUrl(undefined, "unbound-code")}&state=`));
145156 expect(res.status).toBe(400);
146157 expect(await res.text()).toBe("Invalid login state");
147158 expect(res.headers.get("set-cookie") ?? "").not.toContain(SESSION_COOKIE);
e2e/cloud/login-csrf.test.ts+54−3
@@ -36,12 +36,12 @@ scenario( · 35 unmodified lines
3636 if (!callback) throw new Error("AuthKit did not return a callback");
3737 return callback;
3838 };
39− await step("Refuse a valid authorization code with no state", async () => {
39+ await step("Discard a valid code without state and restart login", async () => {
4040 const callback = new URL(await interceptCallback());
4141 callback.searchParams.delete("state");
4242 const response = await page.request.get(callback.toString(), { maxRedirects: 0 });
43− expect(response.status()).toBe(400);
44− expect(await response.text()).toBe("Invalid login state");
43+ expect(response.status()).toBe(302);
44+ expect(response.headers().location).toBe("/api/auth/login");
4545 expect(
4646 (await page.context().cookies()).some((cookie) => cookie.name === "wos-session"),
4747 ).toBe(false);
@@ -73,3 +73,54 @@ scenario( · 25 unmodified lines
7373 });
7474 }),
7575 );
76+
77+scenario(
78+ "Auth · a provider-initiated login restarts with browser-bound state",
79+ { timeout: 180_000 },
80+ Effect.gen(function* () {
81+ const target = yield* Target;
82+ const browser = yield* Browser;
83+ const email = `provider-login-${randomUUID()}@e2e.test`;
84+ // Discover this deployment's provider URL without setting a browser cookie.
85+ const login = yield* Effect.promise(() =>
86+ fetch(new URL("/api/auth/login", target.baseUrl), { redirect: "manual" }),
87+ );
88+ expect(login.status).toBe(302);
89+ const location = login.headers.get("location");
90+ if (!location) throw new Error("Login did not redirect to AuthKit");
91+ const providerUrl = new URL(location);
92+ providerUrl.searchParams.delete("state");
93+
94+ yield* browser.session({ label: "anonymous" }, async ({ page, step }) => {
95+ await step("Sign in directly at the provider, as a hosted invitation does", async () => {
96+ await page.goto(providerUrl.toString());
97+ await page.getByPlaceholder("new-user@example.com").fill(email);
98+ const callbackResponse = page.waitForResponse(
99+ (response) => new URL(response.url()).pathname === "/api/auth/callback",
100+ );
101+ await page.getByRole("button", { name: /Continue/ }).click();
102+ const callback = await callbackResponse;
103+ expect(new URL(callback.url()).searchParams.has("state")).toBe(false);
104+ expect(callback.status()).toBe(302);
105+ expect(callback.headers().location).toBe("/api/auth/login");
106+ await page.waitForURL((url) => url.searchParams.has("state"));
107+ expect((await page.context().cookies()).map((cookie) => cookie.name)).not.toContain(
108+ "wos-session",
109+ );
110+ });
111+
112+ await step("Complete the fresh login and reach the signed-in app", async () => {
113+ // The emulator asks again; hosted AuthKit can reuse its browser session.
114+ await page.getByPlaceholder("new-user@example.com").fill(email);
115+ await page.getByRole("button", { name: /Continue/ }).click();
116+ await page.waitForURL((url) => url.pathname === "/create-org", { timeout: 30_000 });
117+ const me = await page.request.get(new URL("/api/auth/me", target.baseUrl).toString());
118+ expect(me.status()).toBe(200);
119+ expect(await me.json()).toMatchObject({ user: { email } });
120+ const cookieNames = (await page.context().cookies()).map((cookie) => cookie.name);
121+ expect(cookieNames).toContain("wos-session");
122+ expect(cookieNames).not.toContain("wos-login-state");
123+ });
124+ });
125+ }),
126+);

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t