Skip to content

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

fix: 403 redirect loop (#21073)

ecmadaoc35242caae64
diff --git a/frontend/src/app/AuthGate.test.tsx b/frontend/src/app/AuthGate.test.tsx
index 3bbc169ffb..0ef7eff940 100644
--- a/frontend/src/app/AuthGate.test.tsx
+++ b/frontend/src/app/AuthGate.test.tsx
@@ -157,6 +157,8 @@ describe("AuthGate", () => {
expect(container.querySelector("[data-testid='page']")).not.toBeNull();
expect(container.querySelector("[role='status']")).toBeNull();
+ expect(mocks.fetchWorkspaceIamPolicy).toHaveBeenCalledWith(true);
+ expect(mocks.listRoles).toHaveBeenCalledWith(true);
act(() => {
const currentUser = useAppStore.getState().currentUser;
@@ -285,7 +287,9 @@ describe("AuthGate", () => {
expect(mocks.fetchCurrentUser).toHaveBeenCalledTimes(1);
expect(mocks.fetchWorkspaceIamPolicy).toHaveBeenCalledTimes(1);
+ expect(mocks.fetchWorkspaceIamPolicy).toHaveBeenCalledWith(true);
expect(mocks.listRoles).toHaveBeenCalledTimes(1);
+ expect(mocks.listRoles).toHaveBeenCalledWith(true);
expect(container.querySelector("[data-testid='page']")).not.toBeNull();
expect(container.querySelector("[role='status']")).toBeNull();
});
diff --git a/frontend/src/app/AuthGate.tsx b/frontend/src/app/AuthGate.tsx
index 324bad76b8..e01815b2d1 100644
--- a/frontend/src/app/AuthGate.tsx
+++ b/frontend/src/app/AuthGate.tsx
@@ -67,7 +67,7 @@ export function AuthGate({ children }: { children: ReactNode }) {
// Load workspace-scoped data once authenticated, then reveal the app.
useEffect(() => {
const store = useAppStore.getState();
- if (!isLoggedIn || !currentUserName) {
+ if (!isLoggedIn || !currentUserName || isPublicRoute) {
setReady(true);
return;
}
@@ -75,9 +75,9 @@ export function AuthGate({ children }: { children: ReactNode }) {
setReady(false);
void Promise.all([
store.loadSubscription(),
- store.fetchWorkspaceIamPolicy(),
+ store.fetchWorkspaceIamPolicy(true),
store.loadWorkspaceList(),
- store.listRoles(),
+ store.listRoles(true),
store.batchGetOrFetchGroups(
currentUserGroupsKey ? currentUserGroupsKey.split("\0") : []
),
@@ -87,27 +87,33 @@ export function AuthGate({ children }: { children: ReactNode }) {
return () => {
cancelled = true;
};
- }, [currentUserGroupsKey, currentUserName, currentUserWorkspace, isLoggedIn]);
+ }, [
+ currentUserGroupsKey,
+ currentUserName,
+ currentUserWorkspace,
+ isLoggedIn,
+ isPublicRoute,
+ ]);
// Periodically revalidate the session (skip when logged out / on auth routes).
useEffect(() => {
const id = setInterval(() => {
const store = useAppStore.getState();
if (!store.isLoggedIn() || store.unauthenticatedOccurred) return;
- if (isAuthRoute) return;
+ if (isAuthRoute || isPublicRoute) return;
void (async () => {
const user = await store.fetchCurrentUser();
if (!user || !store.isLoggedIn() || store.unauthenticatedOccurred) {
return;
}
await Promise.allSettled([
- store.fetchWorkspaceIamPolicy(),
- store.listRoles(),
+ store.fetchWorkspaceIamPolicy(true),
+ store.listRoles(true),
]);
})();
}, CHECK_AUTHORIZATION_INTERVAL);
return () => clearInterval(id);
- }, [isAuthRoute]);
+ }, [isAuthRoute, isPublicRoute]);
// Cross-tab user switch: when the signed-in user changes, redirect to the
// workspace root with a notification (unless it's a self email update).
diff --git a/frontend/src/app/router/permissionDenied.test.ts b/frontend/src/app/router/permissionDenied.test.ts
index 975714da0f..618b3fefa7 100644
--- a/frontend/src/app/router/permissionDenied.test.ts
+++ b/frontend/src/app/router/permissionDenied.test.ts
@@ -37,4 +37,22 @@ describe("permission denied route query", () => {
resources: "instances/prod",
});
});
+
+ test("does not record the 403 route as its own source", () => {
+ expect(
+ buildPermissionDeniedRouteQuery({
+ route: {
+ fullPath:
+ "/403?from=%2Fsql-editor%2Fprojects%2Fprod%3Fschema%3Dpublic&api=/bytebase.v1.UserService/GetCurrentUser",
+ requiredPermissions: [],
+ },
+ api: "/bytebase.v1.RoleService/ListRoles",
+ })
+ ).toEqual({
+ from: "/sql-editor/projects/prod?schema=public",
+ api: "/bytebase.v1.RoleService/ListRoles",
+ permissions: "",
+ resources: "",
+ });
+ });
});
diff --git a/frontend/src/app/router/permissionDenied.ts b/frontend/src/app/router/permissionDenied.ts
index 3b35d305bb..cb41b06f3a 100644
--- a/frontend/src/app/router/permissionDenied.ts
+++ b/frontend/src/app/router/permissionDenied.ts
@@ -3,6 +3,22 @@ export type PermissionDeniedRoute = {
requiredPermissions: readonly string[];
};
+function permissionDeniedFromPath(fullPath: string): string {
+ let from = fullPath;
+ for (let i = 0; i < 3; i++) {
+ const url = new URL(from, window.location.origin);
+ if (url.pathname !== "/403") {
+ return from;
+ }
+ const nested = url.searchParams.get("from");
+ if (!nested || !nested.startsWith("/") || nested.startsWith("//")) {
+ return "";
+ }
+ from = nested;
+ }
+ return "";
+}
+
export function buildPermissionDeniedRouteQuery({
route,
api = "",
@@ -15,7 +31,7 @@ export function buildPermissionDeniedRouteQuery({
resources?: string[];
}): Record<string, string> {
return {
- from: route.fullPath,
+ from: permissionDeniedFromPath(route.fullPath),
api,
permissions: (permissions ?? route.requiredPermissions).join(","),
resources: resources.join(","),
diff --git a/frontend/src/routes/auth/SignupPage.test.tsx b/frontend/src/routes/auth/SignupPage.test.tsx
index 920c2a2309..b1fc58f26c 100644
--- a/frontend/src/routes/auth/SignupPage.test.tsx
+++ b/frontend/src/routes/auth/SignupPage.test.tsx
@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({
},
loadServerInfo: vi.fn(),
replace: vi.fn(),
+ resolve: vi.fn(() => ({ href: "/signin" })),
signup: vi.fn(),
}));
@@ -22,6 +23,7 @@ vi.mock("@/app/router", async (importOriginal) => ({
router: {
currentRoute: mocks.currentRoute,
replace: mocks.replace,
+ resolve: mocks.resolve,
},
}));
@@ -93,7 +95,20 @@ beforeEach(async () => {
});
describe("SignupPage", () => {
- test("renders the admin setup title with the normal left-aligned heading layout", () => {
+ test("centers the regular sign-up title", () => {
+ mocks.activeUserCount = 1;
+
+ const { container, render, unmount } = renderIntoContainer(<SignupPage />);
+ render();
+
+ const heading = container.querySelector("h2");
+ expect(heading?.textContent).toBe("auth.sign-up.title");
+ expect(heading?.className).toContain("text-center");
+
+ unmount();
+ });
+
+ test("centers the admin setup title", () => {
const { container, render, unmount } = renderIntoContainer(<SignupPage />);
render();
@@ -101,7 +116,7 @@ describe("SignupPage", () => {
expect(heading?.textContent).toBe("auth.sign-up.admin-title");
expect(heading?.className).toContain("text-main");
expect(heading?.querySelector("p")).toBeNull();
- expect(heading?.querySelector(".text-center")).toBeNull();
+ expect(heading?.className).toContain("text-center");
unmount();
});
diff --git a/frontend/src/routes/auth/SignupPage.tsx b/frontend/src/routes/auth/SignupPage.tsx
index 614c09a928..63a7bceacf 100644
--- a/frontend/src/routes/auth/SignupPage.tsx
+++ b/frontend/src/routes/auth/SignupPage.tsx
@@ -108,7 +108,7 @@ export function SignupPage() {
<div className="h-full flex flex-col justify-center gap-y-4 mx-auto w-full max-w-sm">
<div>
<BytebaseLogo className="mx-auto" />
- <h2 className="text-2xl leading-9 font-medium text-main mt-4">
+ <h2 className="text-2xl leading-9 font-medium text-main text-center mt-4">
{needAdminSetup ? (
<Trans
i18nKey="auth.sign-up.admin-title"
diff --git a/frontend/src/stores/app/auth.ts b/frontend/src/stores/app/auth.ts
index 8bd78c14c6..d69194566a 100644
--- a/frontend/src/stores/app/auth.ts
+++ b/frontend/src/stores/app/auth.ts
@@ -143,9 +143,10 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
]),
}
);
- const getRedirectQuery = () =>
- new URLSearchParams(window.location.search).get("redirect");
- let nextPage = redirectUrl ?? (getRedirectQuery() || "/");
+ const redirectQuery = new URLSearchParams(window.location.search).get(
+ "redirect"
+ );
+ let nextPage = redirectUrl ?? (redirectQuery || "/");
if (resp.mfaTempToken) {
set({ unauthenticatedOccurred: false });
navigateByName(AUTH_MFA_MODULE, {
@@ -169,8 +170,10 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
set({ authSessionKey: uniqueId() });
if (
+ redirectUrl === undefined &&
+ !redirectQuery &&
get().appFeatures["bb.feature.database-change-mode"] ===
- DatabaseChangeMode.EDITOR
+ DatabaseChangeMode.EDITOR
) {
nextPage = resolvePath(SQL_EDITOR_HOME_MODULE);
}
@@ -235,15 +238,15 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
// nothing
} finally {
set({ unauthenticatedOccurred: false });
- const pathname = location.pathname;
+ const fullPath = `${location.pathname}${location.search}${location.hash}`;
const getRedirectQuery = () =>
new URLSearchParams(window.location.search).get("redirect");
// Replace and reload the page to clear frontend state directly.
- window.location.href = resolvePath(AUTH_SIGNIN_MODULE, {
+ location.href = resolvePath(AUTH_SIGNIN_MODULE, {
query: {
redirect:
getRedirectQuery() ||
- (pathname.startsWith("/auth") ? undefined : pathname),
+ (location.pathname.startsWith("/auth") ? undefined : fullPath),
},
});
}
diff --git a/frontend/src/stores/app/iam.ts b/frontend/src/stores/app/iam.ts
index 6774aaf58f..f1d1fa4650 100644
--- a/frontend/src/stores/app/iam.ts
+++ b/frontend/src/stores/app/iam.ts
@@ -1,10 +1,12 @@
import { create as createProto } from "@bufbuild/protobuf";
+import { createContextValues } from "@connectrpc/connect";
import { cloneDeep } from "lodash-es";
import {
projectServiceClientConnect,
roleServiceClientConnect,
workspaceServiceClientConnect,
} from "@/api";
+import { silentContextKey } from "@/api/context-key";
import { userNamePrefix, workspaceNamePrefix } from "@/lib/resourceName";
import { PRESET_WORKSPACE_ROLES } from "@/types/iam/role";
import {
@@ -66,7 +68,9 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({
const rolesRequest =
get().rolesRequest ??
roleServiceClientConnect
- .listRoles(createProto(ListRolesRequestSchema, {}))
+ .listRoles(createProto(ListRolesRequestSchema, {}), {
+ contextValues: createContextValues().set(silentContextKey, true),
+ })
.then((response) => {
set({
roles: response.roles,
@@ -90,7 +94,8 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({
get().workspacePolicyRequest ??
workspaceServiceClientConnect
.getIamPolicy(
- createProto(GetIamPolicyRequestSchema, { resource: policyResource })
+ createProto(GetIamPolicyRequestSchema, { resource: policyResource }),
+ { contextValues: createContextValues().set(silentContextKey, true) }
)
.then(async (workspacePolicy) => {
set({ workspacePolicy, workspacePolicyRequest: undefined });
@@ -240,14 +245,15 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({
return updated;
},
- fetchWorkspaceIamPolicy: async () => {
+ fetchWorkspaceIamPolicy: async (silent = false) => {
const resource =
get().serverInfo?.workspace ||
get().workspace?.name ||
get().currentUser?.workspace ||
`${workspaceNamePrefix}-`;
const policy = await workspaceServiceClientConnect.getIamPolicy(
- createProto(GetIamPolicyRequestSchema, { resource })
+ createProto(GetIamPolicyRequestSchema, { resource }),
+ { contextValues: createContextValues().set(silentContextKey, silent) }
);
// Prefetch groups referenced by the policy so the derived role/user maps
// can expand group members from the same app-store cache.
diff --git a/frontend/src/stores/app/index.test.ts b/frontend/src/stores/app/index.test.ts
index 2104475ebc..893b986604 100644
--- a/frontend/src/stores/app/index.test.ts
+++ b/frontend/src/stores/app/index.test.ts
@@ -78,7 +78,29 @@ const mocks = vi.hoisted(() => ({
return localStorage;
})(),
getCurrentUser: vi.fn(),
+ login: vi.fn(),
logout: vi.fn(),
+ navigateByName: vi.fn(),
+ navigateToPath: vi.fn(),
+ resolvePath: vi.fn(
+ (
+ name: string,
+ options?: { query?: Record<string, string | undefined> }
+ ) => {
+ const base =
+ name === "auth.signin"
+ ? "/auth"
+ : name === "sql-editor.home"
+ ? "/sql-editor"
+ : "/";
+ const query = new URLSearchParams();
+ for (const [key, value] of Object.entries(options?.query ?? {})) {
+ if (value) query.set(key, value);
+ }
+ const serialized = query.toString();
+ return serialized ? `${base}?${serialized}` : base;
+ }
+ ),
getActuatorInfo: vi.fn(),
getWorkspace: vi.fn(),
updateWorkspace: vi.fn(),
@@ -166,6 +188,7 @@ vi.mock("@/api", () => ({
getActuatorInfo: mocks.getActuatorInfo,
},
authServiceClientConnect: {
+ login: mocks.login,
logout: mocks.logout,
},
projectServiceClientConnect: {
@@ -290,6 +313,12 @@ vi.mock("@/api", () => ({
},
}));
+vi.mock("@/app/router/navigation", () => ({
+ navigateByName: mocks.navigateByName,
+ navigateToPath: mocks.navigateToPath,
+ resolvePath: mocks.resolvePath,
+}));
+
const user = createProto(UserSchema, {
name: "users/[email protected]",
@@ -461,6 +490,55 @@ describe("useAppStore", () => {
expect(store.getState().isLoggedIn()).toBe(true);
});
+ test("auto logout preserves the full current path for signin redirect", async () => {
+ const fakeLocation = {
+ pathname: "/sql-editor/projects/prod/instances/pg/databases/app",
+ search: "?schema=public",
+ hash: "#result",
+ href: "",
+ };
+ vi.stubGlobal("location", fakeLocation);
+ mocks.logout.mockResolvedValue({});
+ const store = createAppStore();
+
+ await store.getState().logout();
+
+ expect(mocks.resolvePath).toHaveBeenCalledWith("auth.signin", {
+ query: {
+ redirect:
+ "/sql-editor/projects/prod/instances/pg/databases/app?schema=public#result",
+ },
+ });
+ expect(fakeLocation.href).toBe(
+ "/auth?redirect=%2Fsql-editor%2Fprojects%2Fprod%2Finstances%2Fpg%2Fdatabases%2Fapp%3Fschema%3Dpublic%23result"
+ );
+ });
+
+ test("login keeps an explicit redirect URL in SQL Editor mode", async () => {
+ const redirectUrl =
+ "/sql-editor/projects/prod/instances/pg/databases/app?schema=public#result";
+ mocks.login.mockResolvedValue({ requireResetPassword: false });
+ mocks.getCurrentUser.mockResolvedValue(user);
+ mocks.getActuatorInfo.mockResolvedValue({ workspace: user.workspace });
+ mocks.getWorkspace.mockResolvedValue({ name: user.workspace });
+ 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,
+ redirectUrl,
+ });
+
+ expect(mocks.navigateToPath).toHaveBeenCalledWith(redirectUrl, {
+ replace: true,
+ });
+ });
+
test("lists groups and populates the group cache", async () => {
mocks.listGroups.mockResolvedValue({
groups: [groupA, groupB],
@@ -859,6 +937,17 @@ describe("useAppStore", () => {
);
});
+ test("lists roles silently when requested", async () => {
+ mocks.listRoles.mockResolvedValue({ roles: [roleA] });
+ const store = createAppStore();
+
+ await store.getState().listRoles(true);
+
+ expect(
+ mocks.listRoles.mock.calls[0][1]?.contextValues.get(silentContextKey)
+ ).toBe(true);
+ });
+
test("loads workspace permission roles into the role display cache", async () => {
mocks.getCurrentUser.mockResolvedValue(user);
mocks.getActuatorInfo.mockResolvedValue({
@@ -873,6 +962,28 @@ describe("useAppStore", () => {
expect(store.getState().roles).toEqual([roleA, roleB]);
expect(store.getState().roleList).toEqual([roleA, roleB]);
+ expect(
+ mocks.listRoles.mock.calls[0][1]?.contextValues.get(silentContextKey)
+ ).toBe(true);
+ expect(
+ mocks.getIamPolicy.mock.calls[0][1]?.contextValues.get(silentContextKey)
+ ).toBe(true);
+ });
+
+ test("fetches workspace IAM policy silently when requested", async () => {
+ mocks.getActuatorInfo.mockResolvedValue({
+ workspace: "workspaces/default",
+ });
+ mocks.getWorkspace.mockResolvedValue({ name: "workspaces/default" });
+ mocks.getIamPolicy.mockResolvedValue(createProto(IamPolicySchema, {}));
+ const store = createAppStore();
+ store.setState({ currentUser: user });
+
+ await store.getState().fetchWorkspaceIamPolicy(true);
+
+ expect(
+ mocks.getIamPolicy.mock.calls[0][1]?.contextValues.get(silentContextKey)
+ ).toBe(true);
});
test("prefetches user members referenced by the workspace policy", async () => {
diff --git a/frontend/src/stores/app/role.ts b/frontend/src/stores/app/role.ts
index 9eafb396bc..5edc4d0e33 100644
--- a/frontend/src/stores/app/role.ts
+++ b/frontend/src/stores/app/role.ts
@@ -1,5 +1,7 @@
import { create as createProto } from "@bufbuild/protobuf";
+import { createContextValues } from "@connectrpc/connect";
import { roleServiceClientConnect } from "@/api";
+import { silentContextKey } from "@/api/context-key";
import {
DeleteRoleRequestSchema,
ListRolesRequestSchema,
@@ -10,9 +12,10 @@ import type { AppSliceCreator, RoleSlice } from "./types";
export const createRoleSlice: AppSliceCreator<RoleSlice> = (set, get) => ({
roleList: [],
- listRoles: async () => {
+ listRoles: async (silent = false) => {
const response = await roleServiceClientConnect.listRoles(
- createProto(ListRolesRequestSchema, {})
+ createProto(ListRolesRequestSchema, {}),
+ { contextValues: createContextValues().set(silentContextKey, silent) }
);
set({ roleList: response.roles });
return response.roles;
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index 9b13682b8f..3b08260937 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -363,7 +363,7 @@ export type IamSlice = {
project: string,
policy: IamPolicy
) => Promise<IamPolicy>;
- fetchWorkspaceIamPolicy: () => Promise<IamPolicy>;
+ fetchWorkspaceIamPolicy: (silent?: boolean) => Promise<IamPolicy>;
patchWorkspaceIamPolicy: (
batchPatch: { member: string; roles: string[] }[]
) => Promise<void>;
@@ -784,7 +784,7 @@ export type UserSlice = {
export type RoleSlice = {
roleList: Role[];
- listRoles: () => Promise<Role[]>;
+ listRoles: (silent?: boolean) => Promise<Role[]>;
getRoleByName: (name: string) => Role | undefined;
upsertRole: (role: Role) => Promise<Role>;
deleteRole: (role: Role) => Promise<void>;