diff --git a/app/src/lib/auth/queries.ts b/app/src/lib/auth/queries.ts index ce936c26a0..3bdc774656 100644 --- a/app/src/lib/auth/queries.ts +++ b/app/src/lib/auth/queries.ts @@ -49,7 +49,12 @@ export function needsOnboarding(user: AuthenticatedUser): boolean { export const authKeys = { all: ["auth"] as const, currentUser: () => [...authKeys.all, "current-user"] as const, - providers: () => [...authKeys.all, "providers"] as const, + /* + * Under `deployment`, not `auth`: what the sign-in screen offers is the deployment's, read as + * nobody, the same in every organization (query-client.ts). So it is neither dropped nor asked + * again when the sign-in screen forgets the organization the last person worked in. + */ + providers: () => ["deployment", "sign-in"] as const, }; /** An identity provider this deployment can sign somebody in with. */ @@ -73,7 +78,11 @@ export type SignInOptions = { async function signInOptions(): Promise { // The API's `deployment`, which answers before anybody has signed in, and after in their own. - const body = await readDeployment({ fallback: "Could not load sign-in" }); + // As nobody: this is what somebody signing in is offered, and just signed out, nobody is. + const body = await readDeployment({ + fallback: "Could not load sign-in", + asNobody: true, + }); return { providers: body.authProviders, hosted: body.hostedSignIn === true, diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 9fb350839c..72fc263768 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -120,12 +120,21 @@ function showsOpenBotOnThisComputer(): Promise { * Inside OpenBot Desktop, on the OpenBot on this computer, it is asked with the page's cookies, * which that OpenBot needs; the person is in `default` there. Told "not found" all the same, it is * asked in one of their own. + * + * `asNobody` asks it as nobody whatever organization the app last knew: the sign-in screen's read. + * Just signed out, the app still knows the organization the person worked in (it is forgotten once + * the sign-in screen shows, never while their pages are still on screen), and asked there as + * somebody no longer signed in, the server answers that it can't find it. */ -export async function readDeployment(options: { +export async function readDeployment({ + asNobody = false, + ...options +}: { signal?: AbortSignal; fallback: string; + asNobody?: boolean; }): Promise { - const known = currentOrganizationId(); + const known = asNobody ? undefined : currentOrganizationId(); if (known !== undefined) return getDeployment(known, options); if (!(await showsOpenBotOnThisComputer())) return getDeployment(DEPLOYMENT_ORGANIZATION, { diff --git a/app/src/query-client.ts b/app/src/query-client.ts index 9296f5d150..34f3e60a15 100644 --- a/app/src/query-client.ts +++ b/app/src/query-client.ts @@ -22,6 +22,7 @@ import { import { currentOrganizationId, onOrganizationChange, + setCurrentOrganization, } from "@/lib/organizations/current"; import { inNoOrganization } from "@/lib/organizations/in-no-organization"; @@ -170,6 +171,24 @@ export const queryClient = new OpenBotQueryClient({ holdReadsWhileConnectionLost(queryClient); +/** + * Nobody is signed in: forget the organization the last person worked in, with everything the app + * held for it and their list of organizations, so the next person to sign in on this browser reads + * nothing the last one was shown, and nothing is asked in an organization nobody here is in. + * + * Only once no page of theirs is on screen (the sign-in screen calls it). Forgotten while their + * pages still show, those pages are drawn again in no organization and fail. + */ +export function forgetOrganization(): void { + if (currentOrganizationId() === undefined) return; + setCurrentOrganization(undefined); + queryClient.removeQueries({ + predicate: (query) => + belongsToOrganization(query.queryKey) || + query.queryKey[0] === "organizations", + }); +} + /** * Moving from one organization to another drops everything the app held for the one left, in * flight or answered, so a screen can only be drawn from what the new one answers. Becoming known diff --git a/app/src/routes/sign.tsx b/app/src/routes/sign.tsx index 52aa1cce09..8900083b6e 100644 --- a/app/src/routes/sign.tsx +++ b/app/src/routes/sign.tsx @@ -1,7 +1,7 @@ import { useQuery } from "@tanstack/react-query"; import { createFileRoute, redirect } from "@tanstack/react-router"; import { motion, useReducedMotion } from "motion/react"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import AgentOrb from "@/components/agents/orb/agent-orb"; import { CopilotKitMark, ProviderLogo } from "@/components/auth/provider-logo"; import { Button, buttonVariants } from "@/components/ui/button"; @@ -18,6 +18,7 @@ import { appConfig } from "@/lib/generated/application-config"; import { inNoOrganization } from "@/lib/organizations/in-no-organization"; import { searchTextEntry } from "@/lib/search-text"; import { cn } from "@/lib/utils"; +import { forgetOrganization } from "@/query-client"; import { type AuthProviderId, authProvidersQueryOptions, @@ -87,6 +88,12 @@ function SignScreen() { >(null); const [error, setError] = useState(null); const { data: options } = useQuery(authProvidersQueryOptions()); + /* + * Nobody is signed in here, so the organization the last person worked in is forgotten, with what + * the app held for it. Here, once the sign-in screen shows, never at Sign out itself: the pages of + * the app are still on screen then, and forgetting under them draws them again in no organization. + */ + useEffect(() => forgetOrganization(), []); const providers = options?.providers ?? []; const hosted = options?.hosted === true; const [email, setEmail] = useState(""); diff --git a/app/tests/connect-your-ai.test.tsx b/app/tests/connect-your-ai.test.tsx index 82231aff63..28cf1142c4 100644 --- a/app/tests/connect-your-ai.test.tsx +++ b/app/tests/connect-your-ai.test.tsx @@ -132,6 +132,26 @@ function organizationAi(personal: PersonalAiConnection) { return GetAiConnectionResponse.parse(organization); } +/** A refusal as the API sends one: problem details (api/openapi/common.yaml, `Problem`). */ +function problem( + status: number, + code: string, + category: string, + detail: string, +) { + return { + type: `https://open.bot/errors/${code.toLowerCase().replaceAll("_", "-")}`, + title: detail, + status, + detail, + code, + category, + retryable: false, + requestId: "req_test", + traceId: "trace_test", + }; +} + /** A second organization the person is in, beside `default`. */ const ACME = "/api/v2/organizations/acme"; @@ -157,6 +177,8 @@ class FakeServer { signIns: unknown[] = []; signInReads = 0; signOuts = 0; + /** Whether the browser's session is signed in. Sign out ends it, as the server does. */ + signedIn = true; constructor(start: Start, onboarded = false) { this.personal = personalFor(start); @@ -173,6 +195,31 @@ class FakeServer { const path = inAcme ? `${ORGANIZATION}${url.pathname.slice(ACME.length)}` : url.pathname; + /* + * Signed out, as the real server answers: the deployment at `default` to anybody (the sign-in + * screen reads it), the deployment in any other organization not found, and everything else + * refused as unauthenticated. + */ + if (!this.signedIn && url.pathname !== `${ORGANIZATION}/deployment`) + return /^\/api\/v2\/organizations\/[^/]+\/deployment$/.test(url.pathname) + ? { + status: 404, + json: problem( + 404, + "ORGANIZATION_NOT_FOUND", + "not_found", + "Couldn't find that organization.", + ), + } + : { + status: 401, + json: problem( + 401, + "AUTH_UNAUTHENTICATED", + "auth", + "Authentication required.", + ), + }; if (inAcme && this.acme && path === PERSONAL && method === "GET") return { status: 200, json: this.acme }; if (inAcme && this.acme && path === `${ORGANIZATION}/ai-connection`) @@ -197,6 +244,7 @@ class FakeServer { } if (url.pathname === "/api/auth/sign-out") { this.signOuts += 1; + this.signedIn = false; return { status: 200, json: { success: true } }; } if (path === PERSONAL && method === "GET") diff --git a/app/tests/sign-out-lands-on-sign-in.test.tsx b/app/tests/sign-out-lands-on-sign-in.test.tsx new file mode 100644 index 0000000000..28cd501c21 --- /dev/null +++ b/app/tests/sign-out-lands-on-sign-in.test.tsx @@ -0,0 +1,264 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + type AnyRoute, + createMemoryHistory, + createRootRouteWithContext, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, render, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { useSignOut } from "@/components/app-sidebar/use-sign-out"; +import { getGetDeploymentResponseMock } from "@/lib/api/generated/organization-settings/organization-settings.msw"; +import { GetDeploymentResponse } from "@/lib/api/generated/organization-settings/organization-settings.zod"; +import { ListOrganizationsResponse } from "@/lib/api/generated/organizations/organizations.zod"; +import { OrganizationBoundary } from "@/components/organizations/organization-boundary"; +import { organizationId } from "@/lib/api/request"; +import { + currentOrganizationId, + onOrganizationChange, + setCurrentOrganization, +} from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; +import type { RouterContext } from "@/router-context"; +import { Route as AuthedRoute } from "@/routes/_authed"; +import { Route as SignRoute } from "@/routes/sign"; +import { personBody } from "./accounts-api"; +import { nativeFetch, pageFetch } from "./page-fetch"; +import { settleReactWork } from "./settle-react-work"; + +/** + * Signing out lands on the sign-in screen, not on an error. + * + * FOUND ON OPENBOT CLOUD. A person works in an organization of their own, not `default`. After + * signing out, the sign-in screen asked for the deployment in that organization, as somebody no + * longer signed in, and the server answered that it couldn't find it: the page read "Something went + * wrong! Couldn't find that organization." until a reload, which asked at `default` as nobody. + * + * The OpenBot is a real HTTP server on this computer answering as the real one does: the person's + * organizations and their own person only while they are signed in, the deployment in their + * organization only to its members, and at `default` to anybody. Answers are checked against the + * schemas generated from the spec. The app is the real sign-in gate, sign-in screen and Sign out. + */ + +const ORGANIZATION = "acme"; +const NativeResponse = globalThis.Response; +let openbot: ReturnType; +let signedIn: boolean; +let signOuts: number; + +const deployment = () => + GetDeploymentResponse.parse({ + ...getGetDeploymentResponseMock(), + authProviders: ["google"], + hostedSignIn: false, + ssoConfigured: false, + ssoRequired: false, + }); + +function problem(status: number, code: string, detail: string): Response { + return new NativeResponse(JSON.stringify({ status, code, detail }), { + status, + headers: { "content-type": "application/problem+json" }, + }); +} + +function answer(request: Request): Response { + const path = new URL(request.url).pathname; + if (path === "/api/auth/sign-out" && request.method === "POST") { + signedIn = false; + signOuts += 1; + return NativeResponse.json({ success: true }); + } + if (path === "/api/v2/organizations/default/deployment") + return NativeResponse.json(deployment()); + if (path === `/api/v2/organizations/${ORGANIZATION}/deployment`) + return signedIn + ? NativeResponse.json(deployment()) + : problem( + 404, + "ORGANIZATION_NOT_FOUND", + "Couldn't find that organization.", + ); + if (!signedIn) + return problem(401, "AUTH_UNAUTHENTICATED", "Authentication required."); + if (path === "/api/v2/people/me/organizations") + return NativeResponse.json( + ListOrganizationsResponse.parse({ + organizations: [ + { + personal: true, + id: ORGANIZATION, + slug: ORGANIZATION, + name: "Acme", + role: "owner", + active: true, + }, + ], + canCreate: true, + nextCursor: null, + }), + ); + if (path === `/api/v2/organizations/${ORGANIZATION}/people/me`) + return NativeResponse.json({ + person: personBody({ + id: "dana", + email: "dana@example.com", + name: "Dana Whitfield", + role: "owner", + }), + openbotVersion: null, + }); + return problem(404, "NOT_FOUND", "Not found."); +} + +beforeAll(() => { + openbot = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: answer }); + GlobalRegistrator.register({ url: `http://127.0.0.1:${openbot.port}/` }); +}); +beforeEach(() => { + signedIn = true; + signOuts = 0; + setCurrentOrganization(undefined); + queryClient.clear(); + globalThis.fetch = pageFetch(); +}); +afterEach(async () => { + cleanup(); + await settleReactWork(); + queryClient.clear(); + setCurrentOrganization(undefined); + globalThis.fetch = nativeFetch; +}); +afterAll(async () => { + await settleReactWork(); + await GlobalRegistrator.unregister(); + openbot.stop(true); +}); + +/** A screen that reads the organization it is drawn in, as the app's screens do. */ +function WorkingIn() { + return

Working in {organizationId()}

; +} + +/** + * Home with the account menu's Sign out (the same hook every Sign out in the app runs), inside the + * app's own boundary, which draws its pages again whenever the organization changes. + */ +function Home() { + const signOut = useSignOut(); + return ( + +
+

The app

+ + +
+
+ ); +} + +/** The app opened at home: the real sign-in gate in front of it, and the sign-in screen. */ +function openApp() { + const root = createRootRouteWithContext()({ + component: Outlet, + // A route that fails says why, as the app's error screen does. + errorComponent: ({ error }) => ( +

Something went wrong! {error.message}

+ ), + }); + const gate = AuthedRoute.options as unknown as Record; + const authed = createRoute({ + id: "_authed", + getParentRoute: () => root, + component: Outlet, + ...{ beforeLoad: gate.beforeLoad }, + } as never) as unknown as AnyRoute; + const home = createRoute({ + getParentRoute: () => authed, + path: "/", + component: Home, + } as never) as unknown as AnyRoute; + const sign = SignRoute.options as unknown as Record; + const signIn = createRoute({ + getParentRoute: () => root, + path: "/sign", + ...{ + validateSearch: sign.validateSearch, + beforeLoad: sign.beforeLoad, + component: sign.component, + }, + } as never) as unknown as AnyRoute; + const router = createRouter({ + routeTree: root.addChildren([authed.addChildren([home]), signIn]), + history: createMemoryHistory({ initialEntries: ["/"] }), + context: { queryClient }, + }); + const view = render( + + + , + ); + return Object.assign(view, { router }); +} + +test("signing out from an organization of their own lands on the sign-in screen, not an error", async () => { + const view = openApp(); + await view.findByText("The app"); + await userEvent.click(view.getByRole("button", { name: "Sign out" })); + + // The sign-in screen, with the deployment's ways in. + await view.findByRole( + "button", + { name: /Continue with Google/ }, + { timeout: 5_000 }, + ); + expect(view.router.state.location.pathname).toBe("/sign"); + expect(signOuts).toBe(1); + await waitFor(() => + expect(view.queryByText(/Couldn't find that organization/)).toBeNull(), + ); + expect(view.queryByText(/Something went wrong/)).toBeNull(); +}); + +test("signing out from the account menu leaves the app's pages before the organization is forgotten", async () => { + // Whether the app's pages were still on screen when the organization was forgotten. + const appShownWhenForgotten: boolean[] = []; + const stop = onOrganizationChange((next) => { + if (next === undefined) + appShownWhenForgotten.push( + document.body.textContent?.includes("The app") === true, + ); + }); + try { + const view = openApp(); + await view.findByText(`Working in ${ORGANIZATION}`); + await userEvent.click(view.getByRole("button", { name: "Sign out" })); + + await view.findByRole( + "button", + { name: /Continue with Google/ }, + { timeout: 5_000 }, + ); + expect(view.queryByText(/Something went wrong/)).toBeNull(); + expect(view.queryByText(/The organization is not known yet/)).toBeNull(); + // Forgotten once, on the sign-in screen, with nothing of the app left to draw in no organization. + await waitFor(() => expect(currentOrganizationId()).toBeUndefined()); + expect(appShownWhenForgotten).toEqual([false]); + } finally { + stop(); + } +});