History

Web clients scope by the URL org; drop cookie-based org switching (#1000)

The console URL's org slug is now the request scope on the client too: both API clients (core + account) read the slug from window.location at request time and send it as the x-executor-organization header, so every tab's requests are scoped to the org its own URL names — independent of the single shared session cookie. With requests URL-scoped, the cookie-based switch machinery is dead weight: - delete the switchOrganization endpoint/handler/atom; the org switcher and create-org just navigate to /<slug> (the session already authenticates the user to all their orgs, so there is nothing to switch server-side). - delete ForeignOrgSlug; a slug the caller can't access now resolves to a null org via /account/me and the shell 404s, no switch-into-org dance. - simplify OrgSlugGate to canonicalize a bare URL onto the active slug and otherwise render through (a slug in the URL is already the scope). Flips the multi-tab scenario from reproducing the cookie-steal corruption to asserting per-tab independence, and reframes the foreign-slug scenario around URL scoping (no session switch; the cookie is never rewritten).

Rhys Sullivan committed 5 months ago

Commit 1f9bfe01 parent 58e23e814 files · +233 −214Browse files

Showing the changes to e2e (2 of 14 files). Show all

Unified · Split

2 files
  1. e2e/cloud/org-multitab-cookie.test.ts +111 −0
  2. e2e/cloud/org-slug-foreign.test.ts +24 −18
e2e/cloud/org-multitab-cookie.test.ts+111−0
@@ -0,0 +1,111 @@
1// Cloud-only (browser): two tabs, two orgs, at the same time — independent.
2//
3// WorkOS still pins ONE org into the sealed `wos-session` cookie, and the whole
4// browser shares one cookie jar. Under the OLD cookie-based "active org" model
5// that made "active organization" a browser-global: two tabs could not be in
6// two orgs at once, and a switch (or the slug gate's switch-to-honor-the-URL)
7// silently re-scoped the other tab out from under it.
8//
9// The stateless URL model removes that hazard. The slug in the path is the
10// request scope: every API call carries it (the `x-executor-organization`
11// header), the server re-checks live membership and resolves data for THAT
12// org, and the session merely authenticates the user to all their orgs at
13// once. Nothing writes the cookie on a switch. So this scenario — once the
14// reproduction of the corruption — now asserts the opposite: each tab's
15// requests stay scoped to its own URL org, no matter what the other tab does.
16//
17// Everything runs through the browser (onboarding + the menu create-org), so
18// the single-use WorkOS refresh-token chain stays browser-owned and valid.
19import { expect } from "@effect/vitest";
20import { Effect } from "effect";
21
22import { scenario } from "../src/scenario";
23import { Browser, Target } from "../src/services";
24
25scenario(
26 "Org tabs · two tabs on different orgs stay independent (URL-scoped, no cookie steal)",
27 {},
28 Effect.gen(function* () {
29 const target = yield* Target;
30 const browser = yield* Browser;
31 const identity = yield* target.newIdentity({ org: false });
32
33 yield* browser.session(identity, async ({ page: tab1, step }) => {
34 const slugOf = (page: typeof tab1) => new URL(page.url()).pathname.replace(/^\/|\/.*$/g, "");
35
36 // The org slug a page's REAL app requests carry — read straight off the
37 // outgoing `x-executor-organization` header, the actual request scope.
38 // This is what makes the two tabs independent; the shared session cookie
39 // is irrelevant to it.
40 const requestOrgSlugOf = async (page: typeof tab1): Promise<string> => {
41 const matching = page.waitForRequest(
42 (request) =>
43 request.url().includes("/api/") &&
44 request.headers()["x-executor-organization"] !== undefined,
45 { timeout: 15_000 },
46 );
47 // Nudge the app to refetch so a fresh scoped request goes out.
48 void page.reload({ waitUntil: "commit" });
49 return (await matching).headers()["x-executor-organization"]!;
50 };
51
52 let slugA = "";
53 let slugB = "";
54
55 await step("Onboard org A in tab 1", async () => {
56 await tab1.goto("/", { waitUntil: "networkidle" });
57 await tab1.getByPlaceholder("Northwind Labs").fill("Multitab A");
58 await tab1.getByRole("button", { name: "Create organization" }).click();
59 await tab1.getByText("Connect your MCP client").waitFor({ timeout: 30_000 });
60 await tab1.getByRole("button", { name: "Continue to app" }).click();
61 await tab1.waitForURL((url) => /^\/[a-z0-9-]+\/?$/.test(url.pathname), { timeout: 30_000 });
62 await tab1.getByText("Integrations").first().waitFor({ timeout: 30_000 });
63 slugA = slugOf(tab1);
64 });
65
66 await step("Create org B from tab 1's account menu — tab 1 is now in B", async () => {
67 await tab1.getByRole("button", { name: /Test User/ }).click();
68 await tab1.getByRole("menuitem", { name: "Multitab A" }).click();
69 await tab1
70 .locator('[data-slot="dropdown-menu-sub-content"]')
71 .getByText("Create organization", { exact: true })
72 .click();
73 await tab1.getByText("Add another organization").waitFor();
74 await tab1.getByPlaceholder("Northwind Labs").fill("Multitab B");
75 await tab1.getByRole("button", { name: "Create organization" }).click();
76 await tab1.waitForURL((url) => url.pathname !== `/${slugA}`, { timeout: 30_000 });
77 await tab1.getByText("Integrations").first().waitFor({ timeout: 30_000 });
78 slugB = slugOf(tab1);
79 });
80 expect(slugB, "the two orgs have distinct slugs").not.toBe(slugA);
81
82 // A second tab in the SAME context — shares tab 1's cookie jar.
83 const tab2 = await tab1.context().newPage();
84
85 await step("Tab 2 opens org A's URL and stays in A — no switch, no reload loop", async () => {
86 await tab2.goto(`/${slugA}/policies`, { waitUntil: "networkidle" });
87 await tab2.getByText("Policies").first().waitFor({ timeout: 30_000 });
88 expect(new URL(tab2.url()).pathname, "tab 2 stays on org A's URL").toBe(
89 `/${slugA}/policies`,
90 );
91 expect(await requestOrgSlugOf(tab2), "tab 2's API requests are scoped to org A").toBe(
92 slugA,
93 );
94 });
95
96 await step("Tab 1 is untouched: still org B, and its requests still scope to B", async () => {
97 expect(new URL(tab1.url()).pathname, "tab 1's URL still says org B").toBe(`/${slugB}`);
98 expect(
99 await tab1.getByRole("button", { name: /Multitab B/ }).isVisible(),
100 "tab 1's sidebar still shows org B",
101 ).toBe(true);
102 // The crux: tab 2 opening org A did NOT re-scope tab 1. Tab 1's own
103 // requests still carry org B's slug — the URL is the scope, not a
104 // shared cookie a sibling tab can steal.
105 expect(await requestOrgSlugOf(tab1), "tab 1's API requests stay scoped to org B").toBe(
106 slugB,
107 );
108 });
109 });
110 }),
111);
e2e/cloud/org-slug-foreign.test.ts+24−18
@@ -1,12 +1,13 @@
1// Cloud-only (browser): opening another of YOUR orgs by its slug URL switches1// Cloud-only (browser): opening another of YOUR orgs by its slug URL just
2// the session into it. The org-slug gate's foreign-slug branch (ForeignOrgSlug)2// works — no switch, no cookie rewrite. The slug in the path is the request
3// resolves a URL slug that isn't the active org against the caller's3// scope (the `x-executor-organization` header), and the session authenticates
4// memberships — a match switches + reloads, so a bookmark or a teammate's link4// the user to ALL their orgs at once, so a bookmark or a teammate's link into a
5// into a shared org lands you there even when a different org is active.5// shared org lands you there regardless of which org the cookie happens to pin.
6//6//
7// org-switcher.test.ts covers switching via the account menu; this covers the7// org-switcher.test.ts covers the account-menu navigation; this covers the URL
8// URL path. (Unknown/unauthorized slugs → 404 is covered by8// path. (Unknown/unauthorized slugs → 404 is covered by
9// scenarios/org-slug-routing.test.ts.)9// scenarios/org-slug-routing.test.ts; two tabs at once by
10// org-multitab-cookie.test.ts.)
10import { expect } from "@effect/vitest";11import { expect } from "@effect/vitest";
11import { Effect } from "effect";12import { Effect } from "effect";
12 13
@@ -16,14 +17,14 @@ import { Browser, Target } from "../src/services"; · 3 unmodified lines
16const CLOUD_ORIGIN_HEADERS = (baseUrl: string) => ({ origin: new URL(baseUrl).origin });17const CLOUD_ORIGIN_HEADERS = (baseUrl: string) => ({ origin: new URL(baseUrl).origin });
17 18
18scenario(19scenario(
19 "Org URLs · opening another of your orgs by slug switches the session into it",20 "Org URLs · opening another of your orgs by slug works without switching the session",
20 {},21 {},
21 Effect.gen(function* () {22 Effect.gen(function* () {
22 const target = yield* Target;23 const target = yield* Target;
23 const browser = yield* Browser;24 const browser = yield* Browser;
24 25
25 // Identity starts in org A. Create org B through the real endpoint, which26 // Identity starts in org A. Create org B through the real endpoint, which
26 // switches the active session to B and returns its refreshed cookie.27 // returns its refreshed cookie (the session is now pinned to B).
27 const identity = yield* target.newIdentity();28 const identity = yield* target.newIdentity();
28 const cookie = identity.headers?.cookie ?? "";29 const cookie = identity.headers?.cookie ?? "";
29 30
@@ -42,23 +43,22 @@ scenario( · 12 unmodified lines
42 const orgB = (yield* Effect.promise(() => createB.json())) as { slug: string };43 const orgB = (yield* Effect.promise(() => createB.json())) as { slug: string };
43 const setCookie = createB.headers.get("set-cookie") ?? "";44 const setCookie = createB.headers.get("set-cookie") ?? "";
44 const sessionB = /wos-session=([^;]+)/.exec(setCookie)?.[1];45 const sessionB = /wos-session=([^;]+)/.exec(setCookie)?.[1];
45 expect(sessionB, "creating org B refreshed the session into it").toBeTruthy();46 expect(sessionB, "creating org B pinned the session into it").toBeTruthy();
46 47
47 // Both orgs' slugs from the session that is now active in B.48 // Both orgs' slugs (the org list is the same whichever org the cookie pins).
48 const orgs = (yield* Effect.promise(() =>49 const orgs = (yield* Effect.promise(() =>
49 fetch(new URL("/api/auth/organizations", target.baseUrl), {50 fetch(new URL("/api/auth/organizations", target.baseUrl), {
50 headers: { cookie: `wos-session=${sessionB}` },51 headers: { cookie: `wos-session=${sessionB}` },
51 }).then((r) => r.json()),52 }).then((r) => r.json()),
52 )) as {53 )) as {
53 organizations: ReadonlyArray<{ name: string; slug: string }>;54 organizations: ReadonlyArray<{ name: string; slug: string }>;
54 activeOrganizationId: string;
55 };55 };
56 const slugA = orgs.organizations.find((o) => o.name.startsWith("Org user-"))?.slug;56 const slugA = orgs.organizations.find((o) => o.name.startsWith("Org user-"))?.slug;
57 expect(slugA, "org A has a slug").toBeTruthy();57 expect(slugA, "org A has a slug").toBeTruthy();
58 expect(orgB.slug, "org B has a slug").toBeTruthy();58 expect(orgB.slug, "org B has a slug").toBeTruthy();
59 expect(slugA, "the two orgs have distinct slugs").not.toBe(orgB.slug);59 expect(slugA, "the two orgs have distinct slugs").not.toBe(orgB.slug);
60 60
61 // Drive the browser as the session that is ACTIVE IN B.61 // Drive the browser as the session pinned to B.
62 const inB = {62 const inB = {
63 ...identity,63 ...identity,
64 headers: { cookie: `wos-session=${sessionB}` },64 headers: { cookie: `wos-session=${sessionB}` },
@@ -69,15 +69,21 @@ scenario( · 4 unmodified lines
69 await step("Land in org B, then open org A's slug URL directly", async () => {69 await step("Land in org B, then open org A's slug URL directly", async () => {
70 await page.goto(`/${orgB.slug}`, { waitUntil: "networkidle" });70 await page.goto(`/${orgB.slug}`, { waitUntil: "networkidle" });
71 await page.getByText("Integrations").first().waitFor({ timeout: 30_000 });71 await page.getByText("Integrations").first().waitFor({ timeout: 30_000 });
72 // Navigate to org A — the gate sees a foreign-but-member slug.72 // Open org A by its slug while the cookie is still pinned to B.
73 await page.goto(`/${slugA}/policies`, { waitUntil: "networkidle" });73 await page.goto(`/${slugA}/policies`, { waitUntil: "networkidle" });
74 });74 });
75 75
76 await step("The session switches into org A and lands on the slugged URL", async () => {76 await step("Org A's page renders at its slugged URL — the URL is the scope", async () => {
77 // Reaching org A's policies at its URL is the proof: a switch that77 // Reaching org A's policies at its URL is the proof the request scoped
78 // failed would render the gate's 404 here, not the Policies page.78 // to A off the URL alone: a model that required the cookie to name A
79 // would 404 here (the cookie still says B).
79 await page.waitForURL((url) => url.pathname === `/${slugA}/policies`, { timeout: 30_000 });80 await page.waitForURL((url) => url.pathname === `/${slugA}/policies`, { timeout: 30_000 });
80 await page.getByText("Policies").first().waitFor({ timeout: 30_000 });81 await page.getByText("Policies").first().waitFor({ timeout: 30_000 });
82 // And no switch happened: the session cookie still names org B.
83 const sessionCookie = (await page.context().cookies())
84 .find((c) => c.name === "wos-session")
85 ?.value.split(";")[0];
86 expect(sessionCookie, "the session cookie was never rewritten — no switch").toBe(sessionB);
81 });87 });
82 });88 });
83 }),89 }),

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