Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(frontend): land EDITOR-mode workspaces on the SQL Editor after re-auth (#21163)

Vincent Huangcb90f950e184
diff --git a/frontend/src/app/router/guard.test.ts b/frontend/src/app/router/guard.test.ts
index e73a058be2..eb572168d1 100644
--- a/frontend/src/app/router/guard.test.ts
+++ b/frontend/src/app/router/guard.test.ts
@@ -1,5 +1,6 @@
import { matchRoutes, RouterContextProvider } from "react-router";
import { beforeEach, describe, expect, test, vi } from "vitest";
+import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
// Configurable fake session, controlled per test.
const session = {
@@ -10,6 +11,8 @@ const session = {
hasTwoFa: false,
isSaaSMode: false,
currentUser: undefined as { mfaEnabled: boolean } | undefined,
+ // Mirrors the store default: PIPELINE until the workspace profile loads.
+ databaseChangeMode: DatabaseChangeMode.PIPELINE,
};
const resets = {
@@ -28,6 +31,9 @@ vi.mock("@/stores/app", () => ({
hasFeature: () => session.hasTwoFa,
isSaaSMode: () => session.isSaaSMode,
currentUser: session.currentUser,
+ appFeatures: {
+ "bb.feature.database-change-mode": session.databaseChangeMode,
+ },
...resets,
}),
},
@@ -46,7 +52,10 @@ import {
AUTH_SIGNIN_MODULE,
AUTH_SIGNUP_MODULE,
PROJECT_V1_ROUTE_DASHBOARD,
+ SQL_EDITOR_HOME_MODULE,
+ WORKSPACE_ROOT_MODULE,
WORKSPACE_ROUTE_404,
+ WORKSPACE_ROUTE_LANDING,
} from "./handles";
import { setRouteNameIndex } from "./navigation";
import { routes } from "./routes";
@@ -59,6 +68,7 @@ beforeEach(() => {
session.hasTwoFa = false;
session.isSaaSMode = false;
session.currentUser = undefined;
+ session.databaseChangeMode = DatabaseChangeMode.PIPELINE;
vi.clearAllMocks();
setRouteNameIndex(
new Map<string, string>([
@@ -66,6 +76,8 @@ beforeEach(() => {
[AUTH_2FA_SETUP_MODULE, "/auth/2fa-setup"],
[AUTH_PASSWORD_RESET_MODULE, "/auth/password-reset"],
[WORKSPACE_ROUTE_404, "/404"],
+ [SQL_EDITOR_HOME_MODULE, "/sql-editor"],
+ [WORKSPACE_ROUTE_LANDING, "/landing"],
])
);
});
@@ -102,6 +114,24 @@ describe("rootGuard", () => {
expect(run(WORKSPACE_ROUTE_404, "/404")).toBeNull();
});
+ test("root sends an EDITOR workspace to the SQL Editor", () => {
+ session.isLoggedIn = true;
+ session.databaseChangeMode = DatabaseChangeMode.EDITOR;
+
+ expect(location(run(WORKSPACE_ROOT_MODULE, "/"))).toBe("/sql-editor");
+ });
+
+ // Documents why `login()` must load the workspace profile before it
+ // navigates: this guard cannot tell "not loaded" from "PIPELINE", and the
+ // last-visit fallback ignores /sql-editor, so an EDITOR workspace whose
+ // profile is still unloaded lands here instead of the editor.
+ test("root falls back to landing while the workspace profile is unloaded", () => {
+ session.isLoggedIn = true;
+ session.databaseChangeMode = DatabaseChangeMode.PIPELINE;
+
+ expect(location(run(WORKSPACE_ROOT_MODULE, "/"))).toBe("/landing");
+ });
+
test("logged-out user on an unknown URL matched by the 404 catch-all is redirected to signin", () => {
const target = location(run(WORKSPACE_ROUTE_404, "/ioewjfiwoejf"));
expect(target).toBe("/auth?redirect=%2Fioewjfiwoejf");
diff --git a/frontend/src/app/router/guard.ts b/frontend/src/app/router/guard.ts
index b1c5155f39..ecfd42969a 100644
--- a/frontend/src/app/router/guard.ts
+++ b/frontend/src/app/router/guard.ts
@@ -95,8 +95,15 @@ const ALLOWED_ROUTE_PATTERNS = [
// - EDITOR change-mode workspaces go to the SQL Editor home
// - otherwise the user's last meaningful visit, if any
// - falling back to the landing page
-// `loadWorkspaceProfile()` is awaited before the router mounts (see main.ts),
-// so `appFeatures` is populated by the time this runs.
+// It reads `appFeatures`, so every caller that navigates here must have loaded
+// the workspace profile first:
+// `main.ts` awaits it before mounting when the boot already had a session, and
+// `login()`/`signup()` await it before navigating when it did not (a signed-out
+// boot cannot load it, the setting is authenticated-only). Miss that and an
+// EDITOR workspace silently falls through to the landing page. This loader
+// resolves synchronously (see AppRoot), so it does not fetch the profile
+// itself. `SetupPage.homePath` still keeps its own copy of the EDITOR rule;
+// folding it in here is a follow-up.
function resolveRootRedirect(
store: ReturnType<typeof useAppStore.getState>
): string {
diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx
index 4b76cab033..52e4b37f37 100644
--- a/frontend/src/app/router/routes.test.tsx
+++ b/frontend/src/app/router/routes.test.tsx
@@ -69,6 +69,21 @@ function collectBareLeaves(
return bare;
}
+describe("workspace root", () => {
+ // The redirect for "/" is decided by `rootGuard` in the index route's loader,
+ // not by a static <Navigate>. `login()` and `signup()` rely on that seam:
+ // they navigate to "/" and expect the guard to resolve the real destination.
+ // Lose the loader and an EDITOR workspace silently lands on the landing page,
+ // which is the customer bug this guards.
+ it("matches an index route carrying a loader", () => {
+ const matched = matchRoutes(routes, "/");
+ const leaf = matched?.at(-1)?.route;
+
+ expect(leaf).toBeDefined();
+ expect(typeof leaf?.loader).toBe("function");
+ });
+});
+
describe("react route table reachability", () => {
it("every leaf route renders something or redirects (no blank-body bare leaves)", () => {
expect(collectBareLeaves(routes)).toEqual([]);
diff --git a/frontend/src/stores/app/auth.ts b/frontend/src/stores/app/auth.ts
index d69194566a..23843ce670 100644
--- a/frontend/src/stores/app/auth.ts
+++ b/frontend/src/stores/app/auth.ts
@@ -9,7 +9,6 @@ import {
AUTH_PROFILE_SETUP_MODULE,
AUTH_SIGNIN_MODULE,
SETUP_MODULE,
- SQL_EDITOR_HOME_MODULE,
} from "@/app/router/handles";
import {
navigateByName,
@@ -21,7 +20,6 @@ import {
SendEmailLoginCodeRequestSchema,
SignupRequestSchema,
} from "@/types/proto-es/v1/auth_service_pb";
-import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
import type { User } from "@/types/proto-es/v1/user_service_pb";
import { UNKNOWN_USER_NAME } from "@/types/v1/user";
import { storageKeyResetPassword } from "@/utils/storage-keys";
@@ -146,7 +144,7 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
const redirectQuery = new URLSearchParams(window.location.search).get(
"redirect"
);
- let nextPage = redirectUrl ?? (redirectQuery || "/");
+ const nextPage = redirectUrl ?? (redirectQuery || "/");
if (resp.mfaTempToken) {
set({ unauthenticatedOccurred: false });
navigateByName(AUTH_MFA_MODULE, {
@@ -165,18 +163,16 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
await get().fetchServerInfo(user?.workspace);
// Re-fetch the current workspace now that we're authenticated.
await get().loadWorkspace();
+ // `rootGuard` decides where "/" goes, and it reads the workspace change
+ // mode from this store. The profile is only fetchable once authenticated,
+ // so a boot that started signed out left `appFeatures` at its PIPELINE
+ // default and an EDITOR workspace would fall through to the landing page.
+ // `force` because a previous user's profile must not survive a re-auth.
+ await get().loadWorkspaceProfile(true);
// After user login, reset the auth session key.
set({ authSessionKey: uniqueId() });
- if (
- redirectUrl === undefined &&
- !redirectQuery &&
- get().appFeatures["bb.feature.database-change-mode"] ===
- DatabaseChangeMode.EDITOR
- ) {
- nextPage = resolvePath(SQL_EDITOR_HOME_MODULE);
- }
if (resp.requireResetPassword) {
navigateByName(AUTH_PASSWORD_RESET_MODULE, {
query: { redirect: nextPage },
@@ -212,6 +208,9 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
}
await get().fetchServerInfo(user?.workspace);
+ // See `login()`. Loaded above the onboarding branch because `SetupPage`
+ // reads the change mode too, and its skip button navigates to "/".
+ await get().loadWorkspaceProfile(true);
set({ authSessionKey: uniqueId() });
if (get().enableOnboarding()) {
@@ -219,16 +218,10 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
return;
}
- const getRedirectQuery = () =>
- new URLSearchParams(window.location.search).get("redirect");
- let nextPage = getRedirectQuery() || "/";
- if (
- get().appFeatures["bb.feature.database-change-mode"] ===
- DatabaseChangeMode.EDITOR
- ) {
- nextPage = resolvePath(SQL_EDITOR_HOME_MODULE);
- }
- navigateToPath(nextPage, { replace: true });
+ const redirectQuery = new URLSearchParams(window.location.search).get(
+ "redirect"
+ );
+ navigateToPath(redirectQuery || "/", { replace: true });
},
logout: async () => {
diff --git a/frontend/src/stores/app/index.test.ts b/frontend/src/stores/app/index.test.ts
index 3c89f7f440..856641b1ba 100644
--- a/frontend/src/stores/app/index.test.ts
+++ b/frontend/src/stores/app/index.test.ts
@@ -101,6 +101,7 @@ const mocks = vi.hoisted(() => ({
return serialized ? `${base}?${serialized}` : base;
}
),
+ signup: vi.fn(),
getActuatorInfo: vi.fn(),
getWorkspace: vi.fn(),
updateWorkspace: vi.fn(),
@@ -192,6 +193,7 @@ vi.mock("@/api", () => ({
authServiceClientConnect: {
login: mocks.login,
logout: mocks.logout,
+ signup: mocks.signup,
},
projectServiceClientConnect: {
getProject: mocks.getProject,
@@ -447,6 +449,11 @@ const timestampSeconds = (seconds: number) => ({
beforeEach(() => {
vi.clearAllMocks();
+ // Tests here stub `location`; without this the stub leaks into every test
+ // declared after it, with only the keys that test happened to supply. The
+ // unstub is blanket, so re-install the localStorage mock it also removes.
+ vi.unstubAllGlobals();
+ vi.stubGlobal("localStorage", mocks.localStorage);
localStorage.clear();
});
@@ -527,13 +534,21 @@ describe("useAppStore", () => {
mocks.getCurrentUser.mockResolvedValue(user);
mocks.getActuatorInfo.mockResolvedValue({ workspace: user.workspace });
mocks.getWorkspace.mockResolvedValue({ name: user.workspace });
+ // `login()` loads the profile itself, so EDITOR mode comes from the server
+ // rather than a seeded `appFeatures`.
+ mocks.getSetting.mockResolvedValue(
+ createProto(SettingSchema, {
+ value: createProto(SettingValueSchema, {
+ value: {
+ case: "workspaceProfile",
+ value: createProto(WorkspaceProfileSettingSchema, {
+ databaseChangeMode: DatabaseChangeMode.EDITOR,
+ }),
+ },
+ }),
+ })
+ );
const store = createAppStore();
- store.setState({
- appFeatures: {
- ...store.getState().appFeatures,
- "bb.feature.database-change-mode": DatabaseChangeMode.EDITOR,
- },
- });
await store.getState().login({
request: { email: user.email, password: "secret" } as never,
@@ -545,6 +560,120 @@ describe("useAppStore", () => {
});
});
+ // Regression guard (customer report): signing in from the bare root left
+ // `appFeatures` at its PIPELINE default, because a signed-out boot never
+ // fetches the workspace profile and `login()` did not fetch it either. The
+ // EDITOR branch below then failed and the user landed on the workspace
+ // landing page instead of the SQL Editor. Note this test seeds no
+ // `appFeatures` — the profile must come from the server during `login()`.
+ test("login loads the workspace profile before choosing the next page", async () => {
+ mocks.login.mockResolvedValue({ requireResetPassword: false });
+ mocks.getCurrentUser.mockResolvedValue(user);
+ mocks.getActuatorInfo.mockResolvedValue({ workspace: user.workspace });
+ mocks.getWorkspace.mockResolvedValue({ name: user.workspace });
+ mocks.getSetting.mockResolvedValue(
+ createProto(SettingSchema, {
+ value: createProto(SettingValueSchema, {
+ value: {
+ case: "workspaceProfile",
+ value: createProto(WorkspaceProfileSettingSchema, {
+ databaseChangeMode: DatabaseChangeMode.EDITOR,
+ }),
+ },
+ }),
+ })
+ );
+ const store = createAppStore();
+
+ await store.getState().login({
+ request: { email: user.email, password: "secret" } as never,
+ });
+
+ expect(
+ store.getState().appFeatures["bb.feature.database-change-mode"]
+ ).toBe(DatabaseChangeMode.EDITOR);
+ // `rootGuard` owns the "/" policy and turns this into the SQL Editor; see
+ // the root-redirect tests in app/router/guard.test.ts. What `login()` owes
+ // it is a loaded profile, asserted above.
+ expect(mocks.navigateToPath).toHaveBeenCalledWith("/", { replace: true });
+ });
+
+ // Regression guard: `signup()` used to override the destination with the SQL
+ // Editor whenever the mode read EDITOR, with no check for an explicit
+ // redirect. That branch was dead (signup always boots signed out, so the mode
+ // was never EDITOR) until the profile load made it live, which would have
+ // silently dropped deep links.
+ test("signup keeps an explicit redirect in an EDITOR workspace", async () => {
+ vi.stubGlobal("location", { search: "?redirect=%2Fprojects%2Ffoo" });
+ mocks.signup.mockResolvedValue({});
+ mocks.getCurrentUser.mockResolvedValue(user);
+ // activeUserCount > 1 so `enableOnboarding()` is false and signup navigates.
+ mocks.getActuatorInfo.mockResolvedValue({
+ workspace: user.workspace,
+ activatedUserCount: 2,
+ });
+ mocks.getSetting.mockResolvedValue(
+ createProto(SettingSchema, {
+ value: createProto(SettingValueSchema, {
+ value: {
+ case: "workspaceProfile",
+ value: createProto(WorkspaceProfileSettingSchema, {
+ databaseChangeMode: DatabaseChangeMode.EDITOR,
+ }),
+ },
+ }),
+ })
+ );
+ const store = createAppStore();
+
+ await store.getState().signup({
+ email: user.email,
+ name: "Test",
+ password: "secret",
+ } as never);
+
+ expect(mocks.navigateToPath).toHaveBeenCalledWith("/projects/foo", {
+ replace: true,
+ });
+ });
+
+ // Guards signup's own `loadWorkspaceProfile` call. The explicit-redirect test
+ // above returns before `rootGuard` is consulted, so it passes with or without
+ // the load; this one pins that a no-redirect signup hands the guard a loaded
+ // profile, which is what sends an EDITOR workspace to the SQL Editor.
+ test("signup loads the workspace profile before choosing the next page", async () => {
+ mocks.signup.mockResolvedValue({});
+ mocks.getCurrentUser.mockResolvedValue(user);
+ mocks.getActuatorInfo.mockResolvedValue({
+ workspace: user.workspace,
+ activatedUserCount: 2,
+ });
+ mocks.getSetting.mockResolvedValue(
+ createProto(SettingSchema, {
+ value: createProto(SettingValueSchema, {
+ value: {
+ case: "workspaceProfile",
+ value: createProto(WorkspaceProfileSettingSchema, {
+ databaseChangeMode: DatabaseChangeMode.EDITOR,
+ }),
+ },
+ }),
+ })
+ );
+ const store = createAppStore();
+
+ await store.getState().signup({
+ email: user.email,
+ name: "Test",
+ password: "secret",
+ } as never);
+
+ expect(
+ store.getState().appFeatures["bb.feature.database-change-mode"]
+ ).toBe(DatabaseChangeMode.EDITOR);
+ expect(mocks.navigateToPath).toHaveBeenCalledWith("/", { replace: true });
+ });
+
test("lists groups and populates the group cache", async () => {
mocks.listGroups.mockResolvedValue({
groups: [groupA, groupB],