Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Gateway: dev-only role switcher to check each permission level (CHOO-4042) (#1846)

Christian McDermott233649fff5d5
diff --git a/.dockerignore b/.dockerignore
index 2dcbfc115..5f7cb297b 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -6,6 +6,8 @@
**/node_modules
# Rebuilt inside the image; a local build is only context to upload.
gateway/dist
+# The dev role switcher's local logins (`just seed-dev-roles`).
+gateway/.dev-role-accounts.json
internal/deploy/terraform/.terraform
deploy/remote/helm/switch/charts
.claude
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 376254f8f..af953b139 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -73,6 +73,14 @@ version of their own to them without also giving them a release of their own.
answers for every workspace the caller may enter, counting people as the
workspace's members list shows them: its members, and its organization's
admins who are not one. The dashboard's new workspace switcher reads it.
+- **A dev-only role switcher for the dashboard.** `just seed-dev-roles`
+ creates local test accounts for an org admin, a workspace admin and a
+ member, plus a second workspace only the org admin can open, and
+ `just gateway-dev`, on a server with `gateway_v2` on, shows a **Role:**
+ control in the top bar that signs in as any of them, or as the operator from
+ `.env`, so a page can be checked as each role. Switching is an ordinary
+ sign-in, so every check is the server's own. A production build leaves the
+ switcher out, and `npm run build` now fails if it gets in.
#### Changed
- **The dashboard no longer claims the system is healthy.** The "System
diff --git a/docs/old/LOCAL_DEVELOPMENT.md b/docs/old/LOCAL_DEVELOPMENT.md
index c0aaad018..0380db619 100644
--- a/docs/old/LOCAL_DEVELOPMENT.md
+++ b/docs/old/LOCAL_DEVELOPMENT.md
@@ -140,6 +140,29 @@ them. That's also why cookie-based gateway auth (including OIDC login, see
any CORS configuration: as far as the browser can tell, it never left
`:5173`.
+### Viewing the dashboard as each role
+
+To check what each permission level sees, run `just seed-dev-roles` once the
+stack and `just run` are up. It creates a test account per level on your
+local server (an org admin, a workspace admin and a member, with a random
+password) plus a second workspace that only the org admin can open, and saves
+their logins, with the gateway admin's from `.env` as the operator, to
+`gateway/.dev-role-accounts.json` (gitignored). It is safe to run again.
+
+With the new layout turned on (`FEATURE_FLAGS_ENABLED=gateway_v2`),
+`just gateway-dev` then shows a **Role:** control at the right end of the top
+bar. Sign in once as anyone, such as the gateway admin from `.env`: the
+server tells a signed-out page none of its flags, so the control is not on
+the sign-in page. Picking a role signs you in as that account, an ordinary
+password sign-in, and reloads the page, staying in the same workspace when
+that account can open it. The server sees only that account, so what you see is
+exactly what a person with that role gets.
+
+It exists only in the Vite dev server: a production build leaves it out, and
+`npm run build` fails if any of it gets in (`gateway/scripts/check-no-dev-tools.mjs`).
+The dashboard switch-core serves from `GATEWAY_UI_DIR` is such a build, so it
+never has the switcher.
+
## Which URL is which
| URL | What's there | Started by |
@@ -274,3 +297,4 @@ out, not for judging its latency. Another model is `DECISION_MODEL_URL`,
| `just test-integration` | Integration tests against a real Postgres via testcontainers |
| `just migration "message"` | Autogenerate a new Alembic migration |
| `just gateway-build` | Build the gateway frontend's production bundle |
+| `just seed-dev-roles` | Create the test accounts the dashboard's dev role switcher signs in as (see above) |
diff --git a/gateway/.gitignore b/gateway/.gitignore
index 232ebbaf4..829029c03 100644
--- a/gateway/.gitignore
+++ b/gateway/.gitignore
@@ -1,2 +1,5 @@
# TypeScript incremental build info
*.tsbuildinfo
+
+# The dev role switcher's local logins, written by `just seed-dev-roles`
+.dev-role-accounts.json
diff --git a/gateway/README.md b/gateway/README.md
index 924fb5b29..1c3bbea6f 100644
--- a/gateway/README.md
+++ b/gateway/README.md
@@ -8,6 +8,16 @@ Built with Node/Vite and served via nginx. Development commands live in the
repository-root `justfile`: `just gateway-install` (deps, first time only),
`just gateway-dev` (dev server), `just gateway-build` (production build).
+## Dev-only tools
+
+`src/dev/` holds tools for the dev server alone, such as the role switcher
+that shows the dashboard as an operator, org admin, workspace admin or member
+(seed its accounts with `just seed-dev-roles`; see
+[LOCAL_DEVELOPMENT.md](../docs/old/LOCAL_DEVELOPMENT.md#viewing-the-dashboard-as-each-role)).
+Import them only behind `import.meta.env.DEV`, as `src/layout/DevRoleSlot.tsx`
+does: a production build then leaves them out, and `npm run build` fails if
+one gets in anyway (`scripts/check-no-dev-tools.mjs`).
+
## Design system
The UI follows the Hoot design system. `src/theme/hoot.css` is vendored from
diff --git a/gateway/package.json b/gateway/package.json
index 9505fa5c8..d927db24f 100644
--- a/gateway/package.json
+++ b/gateway/package.json
@@ -7,7 +7,7 @@
},
"scripts": {
"dev": "vite",
- "build": "tsc -b && vite build",
+ "build": "tsc -b && vite build && node scripts/check-no-dev-tools.mjs",
"preview": "vite preview",
"test": "vitest run",
"gen:tokens": "node scripts/gen-hoot-tokens.mjs"
diff --git a/gateway/scripts/check-no-dev-tools.mjs b/gateway/scripts/check-no-dev-tools.mjs
new file mode 100644
index 000000000..c7156a843
--- /dev/null
+++ b/gateway/scripts/check-no-dev-tools.mjs
@@ -0,0 +1,34 @@
+/* Fails a production build that still carries the dev-only tools in `src/dev/`.
+ *
+ * They are left out because a build reads `import.meta.env.DEV` as false,
+ * which drops the only import of them (`src/layout/DevRoleSlot.tsx`). That
+ * holds only while nothing imports them another way, so every build checks it:
+ * `npm run build` runs this after `vite build`, and so does everything that
+ * builds the dashboard through it (the images, Switch Console's bundled copy,
+ * CI). A role switcher that shipped would let whoever opens the page pick who
+ * they are.
+ *
+ * Run: npm run build (or node scripts/check-no-dev-tools.mjs after one)
+ */
+import { readdir, readFile, stat } from "node:fs/promises";
+import { join, relative } from "node:path";
+import { fileURLToPath } from "node:url";
+import { devToolsIn } from "./dev-tools.mjs";
+
+const dist = fileURLToPath(new URL("../dist", import.meta.url));
+const files = [];
+for (const name of await readdir(dist, { recursive: true })) {
+ const path = join(dist, name);
+ if (!(await stat(path)).isFile()) continue;
+ files.push([relative(process.cwd(), path), await readFile(path, "utf8")]);
+}
+const found = devToolsIn(files);
+for (const [path, marker] of found) console.error(`${path} carries "${marker}"`);
+if (found.length > 0) {
+ console.error(
+ "This build carries dev-only tools from src/dev/, which must never ship. " +
+ "Import them only behind import.meta.env.DEV, as src/layout/DevRoleSlot.tsx does.",
+ );
+ process.exit(1);
+}
+console.log("no dev-only tools in the build");
diff --git a/gateway/scripts/dev-role-accounts.d.mts b/gateway/scripts/dev-role-accounts.d.mts
new file mode 100644
index 000000000..c707bae1e
--- /dev/null
+++ b/gateway/scripts/dev-role-accounts.d.mts
@@ -0,0 +1,14 @@
+import type { Plugin } from "vite";
+
+export interface DevRequest {
+ socket: { remoteAddress?: string };
+}
+
+export interface DevResponse {
+ statusCode: number;
+ setHeader(name: string, value: string): void;
+ end(body: string): void;
+}
+
+export function serveDevRoleAccounts(file: URL): (req: DevRequest, res: DevResponse) => Promise<void>;
+export function devRoleAccounts(file: URL): Plugin;
diff --git a/gateway/scripts/dev-role-accounts.mjs b/gateway/scripts/dev-role-accounts.mjs
new file mode 100644
index 000000000..6770db84e
--- /dev/null
+++ b/gateway/scripts/dev-role-accounts.mjs
@@ -0,0 +1,41 @@
+/* The Vite dev server's side of the dev role switcher (`src/dev/`): it hands
+ * the switcher the logins `just seed-dev-roles` wrote. A plugin rather than
+ * something bundled, so the logins never become part of the page's code, and
+ * `apply: "serve"`, so no build carries the route at all.
+ */
+import { readFile } from "node:fs/promises";
+
+const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
+
+/** Answers with `file`'s contents, to this machine only, so `vite --host`
+ * does not hand the logins to the network; 404 while it does not exist. */
+export function serveDevRoleAccounts(file) {
+ return async (req, res) => {
+ if (!LOOPBACK.has(req.socket.remoteAddress ?? "")) {
+ res.statusCode = 403;
+ res.end("The dev role accounts are served to this machine only.");
+ return;
+ }
+ let body;
+ try {
+ body = await readFile(file, "utf8");
+ } catch (error) {
+ res.statusCode = error.code === "ENOENT" ? 404 : 500;
+ res.end(error.message);
+ return;
+ }
+ res.setHeader("Content-Type", "application/json");
+ res.setHeader("Cache-Control", "no-store");
+ res.end(body);
+ };
+}
+
+export function devRoleAccounts(file) {
+ return {
+ name: "switch-dev-role-accounts",
+ apply: "serve",
+ configureServer(server) {
+ server.middlewares.use("/__dev/role-accounts", serveDevRoleAccounts(file));
+ },
+ };
+}
diff --git a/gateway/scripts/dev-tools.d.mts b/gateway/scripts/dev-tools.d.mts
new file mode 100644
index 000000000..aac0eaa16
--- /dev/null
+++ b/gateway/scripts/dev-tools.d.mts
@@ -0,0 +1,4 @@
+export const DEV_MARKERS: string[];
+export function devToolsIn(
+ files: [path: string, text: string][],
+): [path: string, marker: string][];
diff --git a/gateway/scripts/dev-tools.mjs b/gateway/scripts/dev-tools.mjs
new file mode 100644
index 000000000..75a7a18ce
--- /dev/null
+++ b/gateway/scripts/dev-tools.mjs
@@ -0,0 +1,15 @@
+/* What tells a build apart from one that carries the dev-only tools in
+ * `src/dev/`, for `check-no-dev-tools.mjs` and its tests.
+ */
+
+/** Strings each dev tool cannot work without, so minifying keeps them. */
+export const DEV_MARKERS = ["/__dev/role-accounts", "dev-role-switcher"];
+
+/** Every `[path, marker]` where a built file names a marker. Throws when
+ * there are no files, rather than passing a build with nothing in it. */
+export function devToolsIn(files) {
+ if (files.length === 0) throw new Error("the build holds no files to check");
+ return files.flatMap(([path, text]) =>
+ DEV_MARKERS.filter((marker) => text.includes(marker)).map((marker) => [path, marker]),
+ );
+}
diff --git a/gateway/src/App.tsx b/gateway/src/App.tsx
index 7e3205ba8..37970571c 100644
--- a/gateway/src/App.tsx
+++ b/gateway/src/App.tsx
@@ -2,6 +2,7 @@ import { Alert, Box, Button, CircularProgress } from "@mui/material";
import { BrowserRouter, Navigate, Route, Routes } from "react-router";
import { AuthProvider, useAuth } from "./data/AuthContext";
import { appView, readPendingInvite } from "./data/sessionState";
+import { DevRoleCorner } from "./layout/DevRoleSlot";
import PageShell from "./layout/PageShell";
import { renderRoutes } from "./routes/renderRoutes";
import { NotFoundPage } from "./routes/StatusPages";
@@ -77,11 +78,14 @@ export function AppRoutes() {
<OnboardingPage />
);
return (
- <Routes>
- <Route path="/invite" element={<InviteCapture />} />
- <Route path="/" element={screen} />
- <Route path="*" element={<Navigate to="/" replace />} />
- </Routes>
+ <>
+ <Routes>
+ <Route path="/invite" element={<InviteCapture />} />
+ <Route path="/" element={screen} />
+ <Route path="*" element={<Navigate to="/" replace />} />
+ </Routes>
+ <DevRoleCorner />
+ </>
);
}
diff --git a/gateway/src/dev/DevRoleSwitcher.test.tsx b/gateway/src/dev/DevRoleSwitcher.test.tsx
new file mode 100644
index 000000000..656b0d470
--- /dev/null
+++ b/gateway/src/dev/DevRoleSwitcher.test.tsx
@@ -0,0 +1,162 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Session } from "../data/api";
+import { useAuth } from "../data/AuthContext";
+import DevRoleSwitcher from "./DevRoleSwitcher";
+import { type DevAccount, DEV_ROLE_ACCOUNTS_PATH, storeNote } from "./devRoleAccounts";
+
+vi.mock("../data/AuthContext", () => ({ useAuth: vi.fn() }));
+
+const accounts: DevAccount[] = [
+ { role: "operator", label: "Operator", email: "[email protected]", password: "placeholder-1" },
+ { role: "org_admin", label: "Org admin", email: "[email protected]", password: "placeholder-2" },
+ {
+ role: "workspace_admin",
+ label: "Workspace admin",
+ email: "[email protected]",
+ password: "placeholder-2",
+ },
+ { role: "member", label: "Member", email: "[email protected]", password: "placeholder-2" },
+];
+
+function sessionFor(email: string, name: string): Session {
+ return {
+ user: { id: "u1", name, email, is_operator: false },
+ tenant: {
+ id: "t1",
+ slug: "default",
+ name: "Default",
+ role: "admin",
+ organization_role: "member",
+ organization_id: "o1",
+ },
+ tenants: [],
+ state: "ready",
+ can_create_workspace: false,
+ can_add_workspace: false,
+ invite_email_enabled: false,
+ };
+}
+
+function signedIn(session: Session | null) {
+ vi.mocked(useAuth).mockReturnValue({ session, loading: false } as unknown as ReturnType<
+ typeof useAuth
+ >);
+}
+
+function mockFetch(routes: Record<string, [number, unknown]>) {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const key = `${init?.method ?? "GET"} ${String(input)}`;
+ const [status, body] = routes[key] ?? [404, { detail: `unmocked ${key}` }];
+ return new Response(JSON.stringify(body), { status });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+const originalLocation = window.location;
+const reload = vi.fn();
+
+beforeEach(() => {
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: { ...originalLocation, reload },
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ reload.mockClear();
+ vi.unstubAllGlobals();
+ window.sessionStorage.clear();
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ });
+});
+
+describe("DevRoleSwitcher", () => {
+ it("names the seeded role the session is signed in as", async () => {
+ mockFetch({ [`GET ${DEV_ROLE_ACCOUNTS_PATH}`]: [200, { accounts }] });
+ signedIn(sessionFor("[email protected]", "Dev Workspace Admin"));
+ render(<DevRoleSwitcher />);
+ expect(
+ await screen.findByRole("button", { name: /Role: Workspace admin/ }),
+ ).toBeTruthy();
+ });
+
+ it("says when the session is someone else, or nobody", async () => {
+ mockFetch({ [`GET ${DEV_ROLE_ACCOUNTS_PATH}`]: [200, { accounts }] });
+ signedIn(sessionFor("[email protected]", "Ada"));
+ const { unmount } = render(<DevRoleSwitcher />);
+ expect(await screen.findByRole("button", { name: /Role: other account/ })).toBeTruthy();
+ unmount();
+ signedIn(null);
+ render(<DevRoleSwitcher />);
+ expect(await screen.findByRole("button", { name: /Role: signed out/ })).toBeTruthy();
+ });
+
+ it("ticks the role the session is signed in as", async () => {
+ mockFetch({ [`GET ${DEV_ROLE_ACCOUNTS_PATH}`]: [200, { accounts }] });
+ signedIn(sessionFor("[email protected]", "Dev Org Admin"));
+ render(<DevRoleSwitcher />);
+ fireEvent.click(await screen.findByRole("button", { name: /Role: Org admin/ }));
+ const ticked = (await screen.findAllByRole("menuitemradio"))
+ .filter((item) => item.getAttribute("aria-checked") === "true")
+ .map((item) => item.textContent);
+ expect(ticked).toEqual(["Org admin"]);
+ });
+
+ it("signs in as the role picked, back in the same workspace, and reloads", async () => {
+ const fetchMock = mockFetch({
+ [`GET ${DEV_ROLE_ACCOUNTS_PATH}`]: [200, { accounts }],
+ "POST /gateway/auth/login": [200, { id: "u4" }],
+ "GET /gateway/auth/session": [200, { tenant: { id: "t1" } }],
+ });
+ signedIn(sessionFor("[email protected]", "Admin"));
+ render(<DevRoleSwitcher />);
+ fireEvent.click(await screen.findByRole("button", { name: /Role: Operator/ }));
+ fireEvent.click(await screen.findByRole("menuitemradio", { name: "Member" }));
+
+ await vi.waitFor(() => expect(reload).toHaveBeenCalled());
+ const login = fetchMock.mock.calls.find(([input]) => String(input) === "/gateway/auth/login");
+ expect(JSON.parse(String(login?.[1]?.body))).toEqual({
+ email: "[email protected]",
+ password: "placeholder-2",
+ });
+ });
+
+ it("shows why a sign-in failed and stays put", async () => {
+ mockFetch({
+ [`GET ${DEV_ROLE_ACCOUNTS_PATH}`]: [200, { accounts }],
+ "POST /gateway/auth/login": [401, { detail: "Invalid email or password" }],
+ });
+ signedIn(sessionFor("[email protected]", "Admin"));
+ render(<DevRoleSwitcher />);
+ fireEvent.click(await screen.findByRole("button", { name: /Role: Operator/ }));
+ fireEvent.click(await screen.findByRole("menuitemradio", { name: "Member" }));
+
+ expect(await screen.findByText(/Could not sign in: Invalid email or password/)).toBeTruthy();
+ expect(reload).not.toHaveBeenCalled();
+ expect(screen.getByRole("menuitemradio", { name: "Member" }).getAttribute("aria-disabled")).toBeNull();
+ });
+
+ it("says how to seed the accounts when there are none", async () => {
+ mockFetch({});
+ signedIn(null);
+ render(<DevRoleSwitcher />);
+ fireEvent.click(await screen.findByRole("button", { name: /Role: signed out/ }));
+ expect(await screen.findByText(/just seed-dev-roles/)).toBeTruthy();
+ expect(screen.queryByRole("menuitemradio")).toBeNull();
+ });
+
+ it("shows the note the last switch left", async () => {
+ mockFetch({ [`GET ${DEV_ROLE_ACCOUNTS_PATH}`]: [200, { accounts }] });
+ storeNote({ severity: "info", text: "Member can't open Second workspace." });
+ signedIn(sessionFor("[email protected]", "Dev Member"));
+ render(<DevRoleSwitcher />);
+ expect(await screen.findByText("Member can't open Second workspace.")).toBeTruthy();
+ });
+});
diff --git a/gateway/src/dev/DevRoleSwitcher.tsx b/gateway/src/dev/DevRoleSwitcher.tsx
new file mode 100644
index 000000000..874d9bcd3
--- /dev/null
+++ b/gateway/src/dev/DevRoleSwitcher.tsx
@@ -0,0 +1,171 @@
+import Check from "@mui/icons-material/Check";
+import ExpandMoreOutlined from "@mui/icons-material/ExpandMoreOutlined";
+import { Alert, Button, Menu, MenuItem, Snackbar, Typography } from "@mui/material";
+import { useEffect, useState } from "react";
+import { useAuth } from "../data/AuthContext";
+import {
+ type DevAccount,
+ type Note,
+ fetchDevAccounts,
+ signInAs,
+ storeNote,
+ takeNote,
+} from "./devRoleAccounts";
+
+function errorMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+/** Dev builds only (`layout/DevRoleSlot.tsx`): shows the dashboard as each
+ * permission level by signing in as a test account that holds it. The server
+ * sees that account and nothing else, so every check is the one a real person
+ * meets. Looks like the design prototype's role control: plain text in the top
+ * bar, naming the role you are looking as. */
+export default function DevRoleSwitcher() {
+ const { session, loading } = useAuth();
+ // Undefined until the dev server answers; null when nothing is seeded.
+ const [accounts, setAccounts] = useState<DevAccount[] | null>();
+ const [accountsError, setAccountsError] = useState<string | null>(null);
+ const [anchor, setAnchor] = useState<HTMLElement | null>(null);
+ const [switching, setSwitching] = useState(false);
+ const [switchError, setSwitchError] = useState<string | null>(null);
+ const [note, setNote] = useState<Note | null>(null);
+
+ useEffect(() => {
+ fetchDevAccounts().then(setAccounts, (err) => setAccountsError(errorMessage(err)));
+ }, []);
+
+ useEffect(() => {
+ const left = takeNote();
+ if (left !== null) setNote(left);
+ }, []);
+
+ if (loading) return null;
+
+ const email = session?.user.email.toLowerCase();
+ const current = accounts?.find((account) => account.email.toLowerCase() === email);
+ const role = session === null ? "signed out" : (current?.label ?? "other account");
+ const open = anchor !== null;
+
+ async function choose(account: DevAccount) {
+ setSwitching(true);
+ setSwitchError(null);
+ let left: Note | null;
+ try {
+ left = await signInAs(account, session?.tenant ?? null);
+ } catch (err) {
+ setSwitchError(errorMessage(err));
+ setSwitching(false);
+ return;
+ }
+ if (left !== null) storeNote(left);
+ // A full reload, as switching workspace does: everything on the page was
+ // fetched as the account it was opened by.
+ window.location.reload();
+ }
+
+ return (
+ <>
+ <Button
+ id="dev-role-switcher"
+ color="inherit"
+ disabled={switching}
+ aria-haspopup="menu"
+ aria-controls={open ? "dev-role-switcher-menu" : undefined}
+ aria-expanded={open}
+ onClick={(event) => setAnchor(event.currentTarget)}
+ endIcon={
+ <ExpandMoreOutlined
+ sx={{ fontSize: 14, transition: "transform 150ms", transform: open ? "rotate(180deg)" : "none" }}
+ />
+ }
+ sx={{
+ height: "auto",
+ minWidth: 0,
+ px: 0.5,
+ fontWeight: 400,
+ color: "text.secondary",
+ "&:hover": { color: "text.primary", backgroundColor: "transparent" },
+ "& .MuiButton-endIcon": { ml: 0.5 },
+ }}
+ >
+ Role: {role}
+ </Button>
+ <Menu
+ id="dev-role-switcher-menu"
+ anchorEl={anchor}
+ open={open}
+ onClose={() => setAnchor(null)}
+ anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
+ transformOrigin={{ vertical: "top", horizontal: "right" }}
+ slotProps={{ list: { "aria-labelledby": "dev-role-switcher", dense: true, sx: { py: 0.5 } } }}
+ >
+ <Typography
+ variant="body2"
+ sx={{
+ maxWidth: 280,
+ px: 1.5,
+ pt: 0.75,
+ pb: 1,
+ mb: 0.5,
+ color: "text.secondary",
+ borderBottom: 1,
+ borderColor: "divider",
+ }}
+ >
+ Dev only. Picking a role signs you in as a test account that holds it, so every page shows
+ what that person sees.
+ </Typography>
+ {accounts?.map((account) => {
+ const active = account === current;
+ return (
+ <MenuItem
+ key={account.role}
+ role="menuitemradio"
+ aria-checked={active}
+ disabled={switching}
+ onClick={() => void choose(account)}
+ sx={{
+ gap: 1,
+ mx: 0.5,
+ fontWeight: active ? 500 : 400,
+ color: active ? "text.primary" : "text.secondary",
+ "&:hover": { color: "text.primary" },
+ }}
+ >
+ <Check sx={{ fontSize: 14, opacity: active ? 1 : 0 }} />
+ {account.label}
+ </MenuItem>
+ );
+ })}
+ {accounts === null && (
+ <Typography variant="body2" sx={{ maxWidth: 280, px: 1.5, py: 0.75 }}>
+ No test accounts yet. Run <code>just seed-dev-roles</code>, then reload.
+ </Typography>
+ )}
+ {accountsError !== null && (
+ <Alert severity="error" sx={{ mx: 1, my: 0.5, maxWidth: 280 }}>
+ {accountsError}
+ </Alert>
+ )}
+ {switchError !== null && (
+ <Alert severity="error" sx={{ mx: 1, my: 0.5, maxWidth: 280 }}>
+ Could not sign in: {switchError}
+ </Alert>
+ )}
+ </Menu>
+ {note !== null && (
+ <Snackbar
+ open
+ autoHideDuration={note.severity === "info" ? 8000 : null}
+ onClose={() => setNote(null)}
+ anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
+ >
+ <Alert severity={note.severity} variant="filled" onClose={() => setNote(null)}>
+ {note.text}
+ </Alert>
+ </Snackbar>
+ )}
+ </>
+ );
+}
diff --git a/gateway/src/dev/checkNoDevTools.test.ts b/gateway/src/dev/checkNoDevTools.test.ts
new file mode 100644
index 000000000..dd47339ad
--- /dev/null
+++ b/gateway/src/dev/checkNoDevTools.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import { DEV_MARKERS, devToolsIn } from "../../scripts/dev-tools.mjs";
+
+describe("the build's dev-tools check", () => {
+ it("passes a build without them", () => {
+ expect(
+ devToolsIn([
+ ["dist/index.html", "<div id=root></div>"],
+ ["dist/assets/index.js", "console.log(1)"],
+ ]),
+ ).toEqual([]);
+ });
+
+ it("finds each marker in whichever file carries it", () => {
+ const chunk = `fetch("${DEV_MARKERS[0]}");document.getElementById("${DEV_MARKERS[1]}")`;
+ expect(
+ devToolsIn([
+ ["dist/assets/index.js", "console.log(1)"],
+ ["dist/assets/chunk.js", chunk],
+ ]),
+ ).toEqual(DEV_MARKERS.map((marker) => ["dist/assets/chunk.js", marker]));
+ });
+
+ it("refuses to pass a build with nothing in it", () => {
+ expect(() => devToolsIn([])).toThrow("no files to check");
+ });
+
+ // A marker the code no longer uses would pass every build, switcher or not.
+ it("looks for strings the dev tools still use", () => {
+ const sources = import.meta.glob<string>(["./*.{ts,tsx}", "!./*.test.*"], {
+ query: "?raw",
+ import: "default",
+ eager: true,
+ });
+ const source = Object.values(sources).join("\n");
+ expect(Object.keys(sources).length).toBeGreaterThan(0);
+ for (const marker of DEV_MARKERS) expect(source).toContain(marker);
+ });
+});
diff --git a/gateway/src/dev/devRoleAccounts.test.ts b/gateway/src/dev/devRoleAccounts.test.ts
new file mode 100644
index 000000000..257788d18
--- /dev/null
+++ b/gateway/src/dev/devRoleAccounts.test.ts
@@ -0,0 +1,147 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { TenantMembership } from "../data/api";
+import { readPendingInvite, storePendingInvite } from "../data/sessionState";
+import {
+ type DevAccount,
+ DEV_ROLE_ACCOUNTS_PATH,
+ fetchDevAccounts,
+ signInAs,
+ storeNote,
+ takeNote,
+} from "./devRoleAccounts";
+
+const member: DevAccount = {
+ role: "member",
+ label: "Member",
+ email: "[email protected]",
+ password: "placeholder",
+};
+
+const second: TenantMembership = {
+ id: "t2",
+ slug: "second",
+ name: "Second workspace",
+ role: "admin",
+ organization_role: "org_admin",
+ organization_id: "o1",
+};
+
+type Answer = [status: number, body: unknown];
+
+/** Answers each request from `routes` by method and path, and records it. */
+function mockFetch(routes: Record<string, Answer>) {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const key = `${init?.method ?? "GET"} ${String(input)}`;
+ const [status, body] = routes[key] ?? [404, { detail: `unmocked ${key}` }];
+ return new Response(typeof body === "string" ? body : JSON.stringify(body), { status });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+function calls(fetchMock: ReturnType<typeof mockFetch>): string[] {
+ return fetchMock.mock.calls.map(([input, init]) => `${init?.method ?? "GET"} ${String(input)}`);
+}
+
+function sessionIn(tenantId: string): Answer {
+ return [200, { user: { id: "u3" }, tenant: { id: tenantId }, tenants: [], state: "ready" }];
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ window.sessionStorage.clear();
+});
+
+describe("fetchDevAccounts", () => {
+ it("reads the accounts the dev server hands out", async () => {
+ mockFetch({ [`GET ${DEV_ROLE_ACCOUNTS_PATH}`]: [200, { accounts: [member] }] });
+ expect(await fetchDevAccounts()).toEqual([member]);
+ });
+
+ it("answers null when nothing has been seeded", async () => {
+ mockFetch({ [`GET ${DEV_ROLE_ACCOUNTS_PATH}`]: [404, "ENOENT"] });
+ expect(await fetchDevAccounts()).toBeNull();
+ });
+
+ it("says so when the dev server cannot read them", async () => {
+ mockFetch({ [`GET ${DEV_ROLE_ACCOUNTS_PATH}`]: [500, "EACCES: permission denied"] });
+ await expect(fetchDevAccounts()).rejects.toThrow("EACCES: permission denied");
+ });
+});
+
+describe("signInAs", () => {
+ const signedIn: Record<string, Answer> = {
+ "POST /gateway/auth/login": [200, { id: "u3" }],
+ };
+
+ beforeEach(() => {
+ storePendingInvite("someone-elses-invite");
+ });
+
+ it("signs in with the account's password, and nothing more when there is no workspace", async () => {
+ const fetchMock = mockFetch(signedIn);
+ expect(await signInAs(member, null)).toBeNull();
+ expect(calls(fetchMock)).toEqual(["POST /gateway/auth/login"]);
+ expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toEqual({
+ email: member.email,
+ password: member.password,
+ });
+ expect(readPendingInvite()).toBeNull();
+ });
+
+ it("leaves the session alone when it already landed in the workspace", async () => {
+ const fetchMock = mockFetch({ ...signedIn, "GET /gateway/auth/session": sessionIn("t2") });
+ expect(await signInAs(member, second)).toBeNull();
+ expect(calls(fetchMock)).not.toContain("POST /gateway/tenants/t2/switch");
+ });
+
+ it("goes back into the workspace it was viewing", async () => {
+ const fetchMock = mockFetch({
+ ...signedIn,
+ "GET /gateway/auth/session": sessionIn("t1"),
+ "POST /gateway/tenants/t2/switch": [200, {}],
+ });
+ expect(await signInAs(member, second)).toBeNull();
+ expect(calls(fetchMock)).toContain("POST /gateway/tenants/t2/switch");
+ });
+
+ it("says when the account may not open that workspace", async () => {
+ mockFetch({
+ ...signedIn,
+ "GET /gateway/auth/session": sessionIn("t1"),
+ "POST /gateway/tenants/t2/switch": [403, { detail: "Not a member of this workspace" }],
+ });
+ expect(await signInAs(member, second)).toEqual({
+ severity: "info",
+ text: "Member can't open Second workspace.",
+ });
+ });
+
+ it("reports any other failure after signing in as an error", async () => {
+ mockFetch({
+ ...signedIn,
+ "GET /gateway/auth/session": sessionIn("t1"),
+ "POST /gateway/tenants/t2/switch": [500, { detail: "database unavailable" }],
+ });
+ expect(await signInAs(member, second)).toEqual({
+ severity: "error",
+ text: "Signed in as Member, but could not go back to Second workspace: database unavailable",
+ });
+ });
+
+ it("throws when the sign-in is refused, going no further", async () => {
+ const fetchMock = mockFetch({
+ "POST /gateway/auth/login": [401, { detail: "Invalid email or password" }],
+ });
+ await expect(signInAs(member, second)).rejects.toThrow("Invalid email or password");
+ expect(calls(fetchMock)).toEqual(["POST /gateway/auth/login"]);
+ });
+});
+
+describe("the note left for the reloaded page", () => {
+ it("is read once", () => {
+ storeNote({ severity: "info", text: "Member can't open Second workspace." });
+ expect(takeNote()).toEqual({ severity: "info", text: "Member can't open Second workspace." });
+ expect(takeNote()).toBeNull();
+ });
+});
diff --git a/gateway/src/dev/devRoleAccounts.ts b/gateway/src/dev/devRoleAccounts.ts
new file mode 100644
index 000000000..694f0cc81
--- /dev/null
+++ b/gateway/src/dev/devRoleAccounts.ts
@@ -0,0 +1,72 @@
+import { ApiError, type TenantMembership, fetchSession, login, switchTenant } from "../data/api";
+import { clearPendingInvite } from "../data/sessionState";
+
+/** One of the accounts `just seed-dev-roles` makes, one per permission level. */
+export interface DevAccount {
+ role: "operator" | "org_admin" | "workspace_admin" | "member";
+ label: string;
+ email: string;
+ password: string;
+}
+
+/** Where the dev server serves them (`scripts/dev-role-accounts.mjs`). No
+ * build serves it, and `scripts/check-no-dev-tools.mjs` refuses a build whose
+ * code names it. */
+export const DEV_ROLE_ACCOUNTS_PATH = "/__dev/role-accounts";
+
+/** The seeded accounts, or null when `just seed-dev-roles` has not been run. */
+export async function fetchDevAccounts(): Promise<DevAccount[] | null> {
+ const res = await fetch(DEV_ROLE_ACCOUNTS_PATH, { cache: "no-store" });
+ if (res.status === 404) return null;
+ if (!res.ok) {
+ throw new Error(`Vite could not hand out the test accounts: ${await res.text()}`);
+ }
+ const body = (await res.json()) as { accounts: DevAccount[] };
+ return body.accounts;
+}
+
+export interface Note {
+ severity: "info" | "error";
+ text: string;
+}
+
+/** Sign in as `account`, an ordinary password sign-in, then go back into
+ * `workspace` where it may open it, so a page can be checked as each role in
+ * turn. Throws only when the sign-in itself fails, which leaves the session
+ * as it was; after that, returns what to tell the person, if anything. */
+export async function signInAs(
+ account: DevAccount,
+ workspace: TenantMembership | null,
+): Promise<Note | null> {
+ // As on signing out: the next account must not inherit an invitation.
+ clearPendingInvite();
+ await login(account.email, account.password);
+ if (workspace === null) return null;
+ try {
+ const session = await fetchSession();
+ if (session?.tenant?.id !== workspace.id) await switchTenant(workspace.id);
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 403) {
+ return { severity: "info", text: `${account.label} can't open ${workspace.name}.` };
+ }
+ const reason = err instanceof Error ? err.message : String(err);
+ return {
+ severity: "error",
+ text: `Signed in as ${account.label}, but could not go back to ${workspace.name}: ${reason}`,
+ };
+ }
+ return null;
+}
+
+const NOTE_KEY = "switch.devRoleNote";
+
+/** A note for the page the switch reloads onto. */
+export function storeNote(note: Note): void {
+ window.sessionStorage.setItem(NOTE_KEY, JSON.stringify(note));
+}
+
+export function takeNote(): Note | null {
+ const stored = window.sessionStorage.getItem(NOTE_KEY);
+ window.sessionStorage.removeItem(NOTE_KEY);
+ return stored === null ? null : (JSON.parse(stored) as Note);
+}
diff --git a/gateway/src/dev/devRoleAccountsServer.test.ts b/gateway/src/dev/devRoleAccountsServer.test.ts
new file mode 100644
index 000000000..2e521ddaa
--- /dev/null
+++ b/gateway/src/dev/devRoleAccountsServer.test.ts
@@ -0,0 +1,54 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import {
+ type DevResponse,
+ devRoleAccounts,
+ serveDevRoleAccounts,
+} from "../../scripts/dev-role-accounts.mjs";
+
+/** Any file that exists will do for the contents. */
+const EXISTING = new URL("../../package.json", import.meta.url);
+const MISSING = new URL("../../.no-such-accounts.json", import.meta.url);
+
+async function ask(file: URL, remoteAddress: string) {
+ const answer = { status: 200, headers: {} as Record<string, string>, body: "" };
+ const res: DevResponse = {
+ set statusCode(status: number) {
+ answer.status = status;
+ },
+ get statusCode() {
+ return answer.status;
+ },
+ setHeader: (name, value) => {
+ answer.headers[name] = value;
+ },
+ end: (body) => {
+ answer.body = body;
+ },
+ };
+ await serveDevRoleAccounts(file)({ socket: { remoteAddress } }, res);
+ return answer;
+}
+
+describe("the dev server's role accounts route", () => {
+ it.each(["127.0.0.1", "::1", "::ffff:127.0.0.1"])("hands the file to %s", async (address) => {
+ const answer = await ask(EXISTING, address);
+ expect(answer.status).toBe(200);
+ expect(answer.body).toContain('"name": "switch-gateway"');
+ expect(answer.headers["Cache-Control"]).toBe("no-store");
+ });
+
+ it("refuses anyone not on this machine, without reading the file", async () => {
+ const answer = await ask(EXISTING, "192.168.0.17");
+ expect(answer.status).toBe(403);
+ expect(answer.body).not.toContain("switch-gateway");
+ });
+
+ it("answers 404 while nothing has been seeded", async () => {
+ expect((await ask(MISSING, "127.0.0.1")).status).toBe(404);
+ });
+
+ it("exists only in the dev server", () => {
+ expect(devRoleAccounts(MISSING).apply).toBe("serve");
+ });
+});
diff --git a/gateway/src/layout/DevRoleSlot.test.tsx b/gateway/src/layout/DevRoleSlot.test.tsx
new file mode 100644
index 000000000..c3a83b258
--- /dev/null
+++ b/gateway/src/layout/DevRoleSlot.test.tsx
@@ -0,0 +1,36 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useAuth } from "../data/AuthContext";
+import { ALL_OFF, GATEWAY_V2 } from "../data/featureFlags";
+import { DevRoleCorner, DevRoleSlot } from "./DevRoleSlot";
+
+vi.mock("../data/AuthContext", () => ({ useAuth: vi.fn() }));
+vi.mock("../dev/DevRoleSwitcher", () => ({ default: () => <span>role switcher</span> }));
+
+function withNewLayout(on: boolean) {
+ vi.mocked(useAuth).mockReturnValue({
+ capabilities: { features: { ...ALL_OFF, [GATEWAY_V2]: on } },
+ } as unknown as ReturnType<typeof useAuth>);
+}
+
+afterEach(cleanup);
+
+describe("DevRoleSlot", () => {
+ it("shows the switcher when the server runs the new layout", async () => {
+ withNewLayout(true);
+ render(<DevRoleSlot />);
+ expect(await screen.findByText("role switcher")).toBeTruthy();
+ });
+
+ it("shows nothing without it, including signed out, where every flag reads off", async () => {
+ withNewLayout(false);
+ const { container } = render(
+ <>
+ <DevRoleSlot />
+ <DevRoleCorner />
+ </>,
+ );
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(container.innerHTML).toBe("");
+ });
+});
diff --git a/gateway/src/layout/DevRoleSlot.tsx b/gateway/src/layout/DevRoleSlot.tsx
new file mode 100644
index 000000000..e2d504bb8
--- /dev/null
+++ b/gateway/src/layout/DevRoleSlot.tsx
@@ -0,0 +1,48 @@
+import { Box } from "@mui/material";
+import { Suspense, lazy } from "react";
+import { useAuth } from "../data/AuthContext";
+
+// Dev builds only. A production build reads `import.meta.env.DEV` as false and
+// drops this import with it, and `scripts/check-no-dev-tools.mjs` fails the
+// build if any of `src/dev/` is left in.
+const DevRoleSwitcher = import.meta.env.DEV ? lazy(() => import("../dev/DevRoleSwitcher")) : null;
+
+/** The switcher where it shows: in a dev build, on a server running the new
+ * layout (`gateway_v2`). Flags are read only for a signed-in session, so
+ * signed out it is off, like every flag. */
+function useDevRoleSwitcher(): typeof DevRoleSwitcher {
+ const { capabilities } = useAuth();
+ return capabilities.features.gateway_v2 ? DevRoleSwitcher : null;
+}
+
+/** The dev role switcher, at the right end of the top bar. */
+export function DevRoleSlot() {
+ const Switcher = useDevRoleSwitcher();
+ if (Switcher === null) return null;
+ return (
+ <Suspense fallback={null}>
+ <Switcher />
+ </Suspense>
+ );
+}
+
+/** The same, for the signed-in screens that have no top bar (choosing a
+ * workspace, creating one), where the top bar's right end would be. */
+export function DevRoleCorner() {
+ if (useDevRoleSwitcher() === null) return null;
+ return (
+ <Box
+ sx={{
+ position: "fixed",
+ top: 0,
+ right: 16,
+ height: "var(--top-bar-height)",
+ display: "flex",
+ alignItems: "center",
+ zIndex: "appBar",
+ }}
+ >
+ <DevRoleSlot />
+ </Box>
+ );
+}
diff --git a/gateway/src/layout/TopBar.tsx b/gateway/src/layout/TopBar.tsx
index 623a469d8..0df16db99 100644
--- a/gateway/src/layout/TopBar.tsx
+++ b/gateway/src/layout/TopBar.tsx
@@ -14,6 +14,7 @@ import {
} from "../data/workspaceSwitcher";
import CreateInvitationDialog from "../pages/workspace/CreateInvitationDialog";
import { type Layout, areaOf } from "../routes/routeTable";
+import { DevRoleSlot } from "./DevRoleSlot";
import WorkspaceMenu from "./WorkspaceMenu";
const SECTION_LABELS: [prefix: string, label: string][] = [
@@ -247,6 +248,7 @@ export default function TopBar({ layout }: { layout: Layout }) {
)}
<Stack direction="row" sx={{ alignItems: "center", gap: 1 }}>
+ <DevRoleSlot />
{layout === "v2" && (
<LinkButton href={HELP_URL} icon={<HelpOutlineOutlined sx={{ fontSize: 18 }} />}>
Help
diff --git a/gateway/vite.config.ts b/gateway/vite.config.ts
index 487f8c33e..ea9f37ebb 100644
--- a/gateway/vite.config.ts
+++ b/gateway/vite.config.ts
@@ -1,8 +1,9 @@
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
+import { devRoleAccounts } from "./scripts/dev-role-accounts.mjs";
export default defineConfig({
- plugins: [react()],
+ plugins: [react(), devRoleAccounts(new URL(".dev-role-accounts.json", import.meta.url))],
build: { outDir: "dist" },
server: {
proxy: {
diff --git a/justfile b/justfile
index 4048ab13d..f033a748e 100644
--- a/justfile
+++ b/justfile
@@ -274,6 +274,14 @@ gateway-build:
gateway-test:
cd gateway && npm test
+# Create the local accounts the dev role switcher signs in as, one per
+# permission level (operator, org admin, workspace admin, member), and save
+# their logins where `just gateway-dev` serves them to it. The switcher shows
+# with the `gateway_v2` flag on. Needs `just up` and `just run`; safe to run
+# again.
+seed-dev-roles:
+ uv run --project core python scripts/seed_dev_roles.py
+
# ── Standalone deployment (all-in-one Docker, no host toolchain) ──────────────
# Repo users build from source: the build override re-adds the `build:` blocks
# so images come from the working tree, not GHCR. All profiles are enabled to
diff --git a/scripts/seed_dev_roles.py b/scripts/seed_dev_roles.py
new file mode 100644
index 000000000..fbbf67024
--- /dev/null
+++ b/scripts/seed_dev_roles.py
@@ -0,0 +1,260 @@
+#!/usr/bin/env python3
+"""Create the local accounts the gateway's dev role switcher signs in as.
+
+The switcher (`gateway/src/dev/`) shows the dashboard as each permission level
+by signing in as a real account that holds it, so every check it meets is the
+server's own. This makes those accounts on a local switch-core and writes their
+logins to `gateway/.dev-role-accounts.json`, which only the Vite dev server
+reads (`gateway/scripts/dev-role-accounts.mjs`):
+
+- Operator: the gateway admin from `.env`, the server's operator.
+- Org admin: `org_admin` of the default workspace's organization.
+- Workspace admin: admin of the default workspace.
+- Member: a member of the default workspace.
+
+It also adds a second workspace to the organization, which the org admin and
+the operator can open and the other two cannot, so the two admin levels show
+different things.
+
+Safe to run again: an account that still signs in with the saved password is
+kept, one that does not is deleted and made again, and every role is set
+afresh. Needs `just up` and `just run`; run it as `just seed-dev-roles`, which
+loads the gateway admin's login from `.env`.
+"""
+
+from __future__ import annotations
+
+import http.cookiejar
+import json
+import os
+import secrets
+import sys
+import urllib.error
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+SERVER = "http://localhost:8000"
+DEFAULT_WORKSPACE_ID = "00000000-0000-0000-0000-000000000000"
+SECOND_WORKSPACE_NAME = "Second workspace"
+REPO = Path(__file__).resolve().parents[1]
+ACCOUNTS_FILE = REPO / "gateway" / ".dev-role-accounts.json"
+
+
+@dataclass(frozen=True)
+class SeededAccount:
+ role: str
+ label: str
+ name: str
+ email: str
+
+
+SEEDED = [
+ SeededAccount(
+ "org_admin", "Org admin", "Dev Org Admin", "[email protected]"
+ ),
+ SeededAccount(
+ "workspace_admin",
+ "Workspace admin",
+ "Dev Workspace Admin",
+ ),
+ SeededAccount("member", "Member", "Dev Member", "[email protected]"),
+]
+
+
+class RequestFailed(Exception):
+ def __init__(self, method: str, path: str, status: int, detail: str) -> None:
+ super().__init__(f"{method} {path} answered {status}: {detail}")
+ self.status = status
+
+
+class Client:
+ """One browser's worth of session cookie."""
+
+ def __init__(self) -> None:
+ self._opener = urllib.request.build_opener(
+ urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())
+ )
+
+ def call(self, method: str, path: str, body: object = None) -> Any:
+ data = None if body is None else json.dumps(body).encode()
+ request = urllib.request.Request(
+ f"{SERVER}/gateway{path}", data=data, method=method
+ )
+ if data is not None:
+ request.add_header("Content-Type", "application/json")
+ try:
+ with self._opener.open(request) as response:
+ raw = response.read()
+ except urllib.error.HTTPError as error:
+ raise RequestFailed(
+ method, path, error.code, error.read().decode()
+ ) from None
+ return json.loads(raw) if raw else None
+
+ def sign_in(self, email: str, password: str) -> None:
+ self.call("POST", "/auth/login", {"email": email, "password": password})
+
+
+def saved_password() -> str | None:
+ """The seeded accounts' password from the last run, if there was one."""
+ if not ACCOUNTS_FILE.exists():
+ return None
+ try:
+ accounts = json.loads(ACCOUNTS_FILE.read_text())["accounts"]
+ except (ValueError, KeyError) as error:
+ sys.exit(
+ f"{ACCOUNTS_FILE} is not what this script writes ({error}). Delete it and run again."
+ )
+ for account in accounts:
+ if account["role"] == SEEDED[0].role:
+ return str(account["password"])
+ return None
+
+
+def signs_in(email: str, password: str) -> bool:
+ try:
+ Client().sign_in(email, password)
+ except RequestFailed as error:
+ if error.status == 401:
+ return False
+ raise
+ return True
+
+
+def ensure_account(
+ operator: Client,
+ existing: dict[str, Any] | None,
+ account: SeededAccount,
+ password: str,
+) -> str:
+ """The account's id, made (again, if its password is lost) as needed. The
+ operator's session is in the default workspace, so a new account joins it."""
+ if existing is not None:
+ if signs_in(account.email, password):
+ return str(existing["id"])
+ print(
+ f"{account.email} does not sign in with the saved password; making it again."
+ )
+ operator.call("DELETE", f"/users/{existing['id']}")
+ created = operator.call(
+ "POST",
+ "/users",
+ {
+ "name": account.name,
+ "email": account.email,
+ "password": password,
+ "role": "user",
+ },
+ )
+ return str(created["id"])
+
+
+def ensure_second_workspace(operator: Client) -> None:
+ workspaces = operator.call("GET", "/organizations/current/workspaces")
+ if any(workspace["name"] == SECOND_WORKSPACE_NAME for workspace in workspaces):
+ return
+ operator.call(
+ "POST", "/organizations/current/workspaces", {"name": SECOND_WORKSPACE_NAME}
+ )
+
+
+def write_accounts(operator_email: str, operator_password: str, password: str) -> None:
+ accounts = [
+ {
+ "role": "operator",
+ "label": "Operator",
+ "email": operator_email,
+ "password": operator_password,
+ }
+ ] + [
+ {
+ "role": account.role,
+ "label": account.label,
+ "email": account.email,
+ "password": password,
+ }
+ for account in SEEDED
+ ]
+ ACCOUNTS_FILE.write_text(json.dumps({"accounts": accounts}, indent=2) + "\n")
+ ACCOUNTS_FILE.chmod(0o600)
+
+
+def seed(operator_email: str, operator_password: str) -> None:
+ operator = Client()
+ operator.sign_in(operator_email, operator_password)
+ operator.call("POST", f"/tenants/{DEFAULT_WORKSPACE_ID}/switch")
+ # Only an org admin may give out organization roles. A new server makes
+ # the gateway admin one when it seeds the account.
+ tenant = operator.call("GET", "/auth/session")["tenant"]
+ if tenant["organization_role"] != "org_admin":
+ sys.exit(
+ f"{operator_email} is not an org admin of the default workspace's "
+ "organization, so it cannot give the test accounts their roles. "
+ "A server started on a new database (`just reset`) makes it one."
+ )
+
+ password = saved_password() or secrets.token_hex(16)
+ users = {user["email"]: user for user in operator.call("GET", "/users")}
+ ids = {
+ account.role: ensure_account(
+ operator, users.get(account.email), account, password
+ )
+ for account in SEEDED
+ }
+
+ # The organization role first: it decides what someone holds in every
+ # workspace, and an org admin's own workspace role cannot be changed at all.
+ organization_roles = {
+ "org_admin": "org_admin",
+ "workspace_admin": "member",
+ "member": "member",
+ }
+ for role, user_id in ids.items():
+ operator.call(
+ "PATCH",
+ f"/organizations/current/members/{user_id}",
+ {"role": organization_roles[role]},
+ )
+ workspace_roles = {"workspace_admin": "admin", "member": "member"}
+ for role, workspace_role in workspace_roles.items():
+ operator.call(
+ "PATCH",
+ f"/tenants/{DEFAULT_WORKSPACE_ID}/members/{ids[role]}",
+ {"role": workspace_role},
+ )
+ ensure_second_workspace(operator)
+ write_accounts(operator_email, operator_password, password)
+
+
+def main() -> None:
+ operator_email = os.environ.get("GATEWAY_ADMIN_EMAIL")
+ operator_password = os.environ.get("GATEWAY_ADMIN_PASSWORD")
+ if not operator_email or not operator_password:
+ sys.exit(
+ "GATEWAY_ADMIN_EMAIL and GATEWAY_ADMIN_PASSWORD are not set. "
+ "Run this as `just seed-dev-roles`, which loads them from .env."
+ )
+ try:
+ seed(operator_email, operator_password)
+ except urllib.error.URLError as error:
+ sys.exit(
+ f"Could not reach switch-core at {SERVER} ({error.reason}). Is `just run` up?"
+ )
+ except RequestFailed as error:
+ sys.exit(str(error))
+
+ print(f"Seeded the dev role switcher's accounts on {SERVER}:")
+ print(f" {'Operator':<16} {operator_email}")
+ for account in SEEDED:
+ print(f" {account.label:<16} {account.email}")
+ print(f'"{SECOND_WORKSPACE_NAME}" is open to the org admin and the operator only.')
+ print(
+ f"Logins are in {ACCOUNTS_FILE.relative_to(REPO)}; `just gateway-dev` serves them to the switcher, which shows with the gateway_v2 flag on."
+ )
+
+
+if __name__ == "__main__":
+ main()