Skip to content

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

fix(agent): refresh page-agent auth flows (#19689)

p0ny7fa01f14d863
diff --git a/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts b/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts
new file mode 100644
index 0000000000..50ac0964a7
--- /dev/null
+++ b/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts
@@ -0,0 +1,167 @@
+import { Code, ConnectError, createContextValues } from "@connectrpc/connect";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { ignoredCodesContextKey, silentContextKey } from "../context-key";
+
+const mocks = vi.hoisted(() => ({
+ authStore: {
+ unauthenticatedOccurred: false,
+ isLoggedIn: true,
+ },
+ pushNotification: vi.fn(),
+ refreshTokens: vi.fn(),
+ routerPush: vi.fn(),
+ currentRoute: {
+ value: {
+ name: "workspace.home",
+ fullPath: "/instances",
+ },
+ },
+}));
+
+vi.mock("@/plugins/i18n", () => ({
+ t: (key: string) => key,
+}));
+
+vi.mock("@/store", () => ({
+ pushNotification: mocks.pushNotification,
+ useAuthStore: () => mocks.authStore,
+}));
+
+vi.mock("@/router", () => ({
+ router: {
+ currentRoute: mocks.currentRoute,
+ push: mocks.routerPush,
+ },
+}));
+
+vi.mock("@/router/dashboard/workspaceRoutes", () => ({
+ WORKSPACE_ROUTE_403: "workspace.403",
+}));
+
+vi.mock("../refreshToken", () => ({
+ refreshTokens: mocks.refreshTokens,
+}));
+
+import { authInterceptor } from "./authInterceptorMiddleware";
+
+const createRequest = ({
+ methodName = "Chat",
+ silent = false,
+ ignoredCodes = [],
+}: {
+ methodName?: string;
+ silent?: boolean;
+ ignoredCodes?: Code[];
+} = {}) =>
+ ({
+ contextValues: createContextValues()
+ .set(silentContextKey, silent)
+ .set(ignoredCodesContextKey, ignoredCodes),
+ method: { name: methodName },
+ service: { name: "bytebase.v1.TestService" },
+ }) as never;
+
+describe("authInterceptor", () => {
+ beforeEach(() => {
+ mocks.authStore.unauthenticatedOccurred = false;
+ mocks.authStore.isLoggedIn = true;
+ mocks.pushNotification.mockReset();
+ mocks.refreshTokens.mockReset();
+ mocks.routerPush.mockReset();
+ mocks.currentRoute.value = {
+ name: "workspace.home",
+ fullPath: "/instances",
+ };
+ });
+
+ test("refreshes and retries silent unauthenticated requests", async () => {
+ const next = vi
+ .fn()
+ .mockRejectedValueOnce(
+ new ConnectError("access token not found", Code.Unauthenticated)
+ )
+ .mockResolvedValueOnce({ ok: true });
+ mocks.refreshTokens.mockResolvedValue(undefined);
+
+ const result = await authInterceptor(next)(createRequest({ silent: true }));
+
+ expect(result).toEqual({ ok: true });
+ expect(mocks.refreshTokens).toHaveBeenCalledTimes(1);
+ expect(next).toHaveBeenCalledTimes(2);
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
+ expect(mocks.authStore.unauthenticatedOccurred).toBe(false);
+ });
+
+ test("keeps silent unauthenticated refresh failures notification-free", async () => {
+ const next = vi
+ .fn()
+ .mockRejectedValue(
+ new ConnectError("access token not found", Code.Unauthenticated)
+ );
+ mocks.refreshTokens.mockRejectedValue(new Error("refresh failed"));
+
+ await expect(
+ authInterceptor(next)(createRequest({ silent: true }))
+ ).rejects.toMatchObject({ code: Code.Unauthenticated });
+
+ expect(mocks.refreshTokens).toHaveBeenCalledTimes(1);
+ expect(mocks.authStore.unauthenticatedOccurred).toBe(true);
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
+ });
+
+ test("notifies on non-silent unauthenticated refresh failure", async () => {
+ const next = vi
+ .fn()
+ .mockRejectedValue(
+ new ConnectError("access token not found", Code.Unauthenticated)
+ );
+ mocks.refreshTokens.mockRejectedValue(new Error("refresh failed"));
+
+ await expect(authInterceptor(next)(createRequest())).rejects.toMatchObject({
+ code: Code.Unauthenticated,
+ });
+
+ expect(mocks.authStore.unauthenticatedOccurred).toBe(true);
+ expect(mocks.pushNotification).toHaveBeenCalledWith({
+ module: "bytebase",
+ style: "WARN",
+ title: "auth.token-expired-title",
+ description: "auth.token-expired-description",
+ });
+ });
+
+ test("preserves ignored unauthenticated codes", async () => {
+ const next = vi
+ .fn()
+ .mockRejectedValue(
+ new ConnectError("access token not found", Code.Unauthenticated)
+ );
+
+ await expect(
+ authInterceptor(next)(
+ createRequest({ ignoredCodes: [Code.Unauthenticated] })
+ )
+ ).rejects.toMatchObject({ code: Code.Unauthenticated });
+
+ expect(mocks.refreshTokens).not.toHaveBeenCalled();
+ expect(mocks.authStore.unauthenticatedOccurred).toBe(false);
+ });
+
+ test("keeps permission denied redirects gated by silent mode", async () => {
+ const error = new ConnectError("forbidden", Code.PermissionDenied);
+ const next = vi.fn().mockRejectedValue(error);
+
+ await expect(
+ authInterceptor(next)(createRequest({ silent: true }))
+ ).rejects.toMatchObject({ code: Code.PermissionDenied });
+ expect(mocks.routerPush).not.toHaveBeenCalled();
+
+ await expect(authInterceptor(next)(createRequest())).rejects.toMatchObject({
+ code: Code.PermissionDenied,
+ });
+ expect(mocks.routerPush).toHaveBeenCalledWith({
+ name: "workspace.403",
+ query: undefined,
+ });
+ });
+});
diff --git a/frontend/src/connect/middlewares/authInterceptorMiddleware.ts b/frontend/src/connect/middlewares/authInterceptorMiddleware.ts
index b6fa0d824c..413af5e9be 100644
--- a/frontend/src/connect/middlewares/authInterceptorMiddleware.ts
+++ b/frontend/src/connect/middlewares/authInterceptorMiddleware.ts
@@ -17,90 +17,95 @@ const extractPermissionDeniedDetail = (error: unknown) => {
return undefined;
};
+const handleUnauthenticatedFailure = ({
+ silent,
+ isLoggedIn,
+}: {
+ silent: boolean;
+ isLoggedIn: boolean;
+}) => {
+ const authStore = useAuthStore();
+ authStore.unauthenticatedOccurred = true;
+ if (!silent && isLoggedIn) {
+ pushNotification({
+ module: "bytebase",
+ style: "WARN",
+ title: t("auth.token-expired-title"),
+ description: t("auth.token-expired-description"),
+ });
+ }
+};
+
export const authInterceptor: Interceptor = (next) => async (req) => {
try {
- const resp = await next(req);
- return resp;
+ return await next(req);
} catch (error) {
const authStore = useAuthStore();
const silent = req.contextValues.get(silentContextKey);
const ignoredCodes = req.contextValues.get(ignoredCodesContextKey);
- if (!silent && error instanceof ConnectError) {
+ if (error instanceof ConnectError) {
const { code } = error;
if (ignoredCodes?.includes(code)) {
- // omit specified errors
- } else {
- if (
- code === Code.Unauthenticated &&
- req.method.name !== "Login" &&
- req.method.name !== "Signup"
- ) {
- // Don't retry refresh endpoint failures - just propagate error
- // The caller (refreshTokens catch block) will handle the notification
- if (req.method.name === "Refresh") {
- throw error;
- }
+ throw error;
+ }
- // Try to refresh - catch ONLY refresh failures
- try {
- await refreshTokens();
- } catch {
- // Refresh itself failed - auth is broken
- authStore.unauthenticatedOccurred = true;
- if (authStore.isLoggedIn) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: t("auth.token-expired-title"),
- description: t("auth.token-expired-description"),
- });
- }
- throw error;
- }
+ if (
+ code === Code.Unauthenticated &&
+ req.method.name !== "Login" &&
+ req.method.name !== "Signup"
+ ) {
+ // Don't retry refresh endpoint failures - just propagate error.
+ if (req.method.name === "Refresh") {
+ throw error;
+ }
- // Refresh succeeded - retry the original request
- try {
- return await next(req);
- } catch (retryError) {
- // Retry failed - check if it's also an auth error
- if (
- retryError instanceof ConnectError &&
- retryError.code === Code.Unauthenticated
- ) {
- // New token also invalid (edge case) - auth is broken
- authStore.unauthenticatedOccurred = true;
- if (authStore.isLoggedIn) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: t("auth.token-expired-title"),
- description: t("auth.token-expired-description"),
- });
- }
- }
- // Throw retry error (not original) - let other handlers deal with it
- throw retryError;
- }
- } else if (
- code === Code.PermissionDenied &&
- router.currentRoute.value.name !== WORKSPACE_ROUTE_403
- ) {
- const errorDetail = extractPermissionDeniedDetail(error);
- router.push({
- name: WORKSPACE_ROUTE_403,
- query: errorDetail
- ? {
- from: router.currentRoute.value.fullPath,
- api: errorDetail.method,
- permissions: errorDetail.requiredPermissions.join(","),
- resources: errorDetail.resources.join(","),
- }
- : undefined,
+ try {
+ await refreshTokens();
+ } catch {
+ handleUnauthenticatedFailure({
+ silent,
+ isLoggedIn: authStore.isLoggedIn,
});
+ throw error;
+ }
+
+ try {
+ return await next(req);
+ } catch (retryError) {
+ if (
+ retryError instanceof ConnectError &&
+ retryError.code === Code.Unauthenticated
+ ) {
+ handleUnauthenticatedFailure({
+ silent,
+ isLoggedIn: authStore.isLoggedIn,
+ });
+ }
+ throw retryError;
}
}
+
+ if (
+ !silent &&
+ code === Code.PermissionDenied &&
+ router.currentRoute.value.name !== WORKSPACE_ROUTE_403
+ ) {
+ const errorDetail = extractPermissionDeniedDetail(error);
+ router.push({
+ name: WORKSPACE_ROUTE_403,
+ query: errorDetail
+ ? {
+ from: router.currentRoute.value.fullPath,
+ api: errorDetail.method,
+ permissions: errorDetail.requiredPermissions.join(","),
+ resources: errorDetail.resources.join(","),
+ }
+ : undefined,
+ });
+ }
}
+
throw error;
}
};
diff --git a/frontend/src/plugins/agent/logic/tools/callApi.test.ts b/frontend/src/plugins/agent/logic/tools/callApi.test.ts
new file mode 100644
index 0000000000..4e9cdfc194
--- /dev/null
+++ b/frontend/src/plugins/agent/logic/tools/callApi.test.ts
@@ -0,0 +1,157 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ fetch: vi.fn(),
+ getEndpointPath: vi.fn(),
+ refreshTokens: vi.fn(),
+}));
+
+vi.mock("@/connect/refreshToken", () => ({
+ refreshTokens: mocks.refreshTokens,
+}));
+
+vi.mock("./searchApi", () => ({
+ getEndpointPath: mocks.getEndpointPath,
+}));
+
+import { callApi } from "./callApi";
+
+const createResponse = ({
+ status,
+ body,
+ rejectJSON = false,
+}: {
+ status: number;
+ body?: unknown;
+ rejectJSON?: boolean;
+}) =>
+ ({
+ status,
+ json: rejectJSON
+ ? vi.fn().mockRejectedValue(new Error("invalid json"))
+ : vi.fn().mockResolvedValue(body),
+ }) as never;
+
+describe("callApi", () => {
+ beforeEach(() => {
+ vi.stubGlobal("fetch", mocks.fetch);
+ mocks.fetch.mockReset();
+ mocks.getEndpointPath.mockReset();
+ mocks.refreshTokens.mockReset();
+ mocks.getEndpointPath.mockReturnValue("/bytebase.v1.SQLService/Query");
+ });
+
+ test("refreshes once and retries unauthenticated requests", async () => {
+ mocks.fetch
+ .mockResolvedValueOnce(
+ createResponse({
+ status: 401,
+ body: { message: "access token not found" },
+ })
+ )
+ .mockResolvedValueOnce(
+ createResponse({
+ status: 200,
+ body: { rows: [] },
+ })
+ );
+ mocks.refreshTokens.mockResolvedValue(undefined);
+
+ const result = JSON.parse(
+ await callApi({
+ operationId: "SQLService/Query",
+ body: { statement: "SELECT 1" },
+ })
+ );
+
+ expect(result).toEqual({
+ status: 200,
+ response: { rows: [] },
+ });
+ expect(mocks.refreshTokens).toHaveBeenCalledTimes(1);
+ expect(mocks.fetch).toHaveBeenCalledTimes(2);
+ expect(mocks.fetch).toHaveBeenNthCalledWith(
+ 1,
+ expect.stringContaining("/bytebase.v1.SQLService/Query"),
+ expect.objectContaining({
+ method: "POST",
+ credentials: "include",
+ headers: {
+ "Content-Type": "application/json",
+ "Connect-Protocol-Version": "1",
+ },
+ body: JSON.stringify({ statement: "SELECT 1" }),
+ })
+ );
+ });
+
+ test("does not recurse on the refresh endpoint", async () => {
+ mocks.getEndpointPath.mockReturnValue("/bytebase.v1.AuthService/Refresh");
+ mocks.fetch.mockResolvedValue(
+ createResponse({
+ status: 401,
+ body: { message: "refresh token expired" },
+ })
+ );
+
+ const result = JSON.parse(
+ await callApi({
+ operationId: "AuthService/Refresh",
+ })
+ );
+
+ expect(result).toEqual({
+ status: 401,
+ error: "refresh token expired",
+ response: { message: "refresh token expired" },
+ });
+ expect(mocks.refreshTokens).not.toHaveBeenCalled();
+ expect(mocks.fetch).toHaveBeenCalledTimes(1);
+ });
+
+ test("preserves the original error shape when refresh fails", async () => {
+ mocks.fetch.mockResolvedValue(
+ createResponse({
+ status: 401,
+ body: { message: "access token not found" },
+ })
+ );
+ mocks.refreshTokens.mockRejectedValue(new Error("refresh failed"));
+
+ const result = JSON.parse(
+ await callApi({
+ operationId: "SQLService/Query",
+ })
+ );
+
+ expect(result).toEqual({
+ status: 401,
+ error: "access token not found",
+ response: { message: "access token not found" },
+ });
+ expect(mocks.refreshTokens).toHaveBeenCalledTimes(1);
+ expect(mocks.fetch).toHaveBeenCalledTimes(1);
+ });
+
+ test("preserves non-json error handling", async () => {
+ mocks.fetch.mockResolvedValue(
+ createResponse({
+ status: 500,
+ rejectJSON: true,
+ })
+ );
+
+ const result = JSON.parse(
+ await callApi({
+ operationId: "SQLService/Query",
+ })
+ );
+
+ expect(result).toEqual({
+ status: 500,
+ error: "HTTP 500",
+ response: null,
+ });
+ expect(mocks.refreshTokens).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/plugins/agent/logic/tools/callApi.ts b/frontend/src/plugins/agent/logic/tools/callApi.ts
index 24a360ead3..5479ebf6a4 100644
--- a/frontend/src/plugins/agent/logic/tools/callApi.ts
+++ b/frontend/src/plugins/agent/logic/tools/callApi.ts
@@ -1,12 +1,75 @@
+import { refreshTokens } from "@/connect/refreshToken";
import { getEndpointPath } from "./searchApi";
const baseAddress = import.meta.env.BB_GRPC_LOCAL || window.location.origin;
+const REFRESH_PATH = "/bytebase.v1.AuthService/Refresh";
export interface CallApiArgs {
operationId: string;
body?: Record<string, unknown>;
}
+interface ParsedApiResponse {
+ status: number;
+ response: unknown;
+ error?: string;
+}
+
+const parseResponse = async (
+ response: Response
+): Promise<ParsedApiResponse> => {
+ let respJSON: unknown = null;
+ try {
+ respJSON = await response.json();
+ } catch {
+ // Not valid JSON — leave as null.
+ }
+
+ if (response.status >= 400) {
+ let error = `HTTP ${response.status}`;
+ if (respJSON && typeof respJSON === "object") {
+ const errMap = respJSON as Record<string, unknown>;
+ if (typeof errMap.message === "string") {
+ error = errMap.message;
+ } else if (typeof errMap.code === "string") {
+ error = errMap.code;
+ }
+ }
+ return {
+ status: response.status,
+ error,
+ response: respJSON,
+ };
+ }
+
+ return {
+ status: response.status,
+ response: respJSON,
+ };
+};
+
+const fetchApi = async ({
+ path,
+ body,
+ signal,
+}: {
+ path: string;
+ body: string;
+ signal: AbortSignal;
+}) => {
+ const response = await fetch(`${baseAddress}${path}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Connect-Protocol-Version": "1",
+ },
+ credentials: "include",
+ body,
+ signal,
+ });
+ return parseResponse(response);
+};
+
export async function callApi(args: CallApiArgs): Promise<string> {
if (!args.operationId) {
return JSON.stringify({
@@ -24,47 +87,29 @@ export async function callApi(args: CallApiArgs): Promise<string> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30_000);
+ const body = JSON.stringify(args.body ?? {});
try {
- const response = await fetch(`${baseAddress}${path}`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "Connect-Protocol-Version": "1",
- },
- credentials: "include",
- body: JSON.stringify(args.body ?? {}),
+ let result = await fetchApi({
+ path,
+ body,
signal: controller.signal,
});
- let respJSON: unknown = null;
- try {
- respJSON = await response.json();
- } catch {
- // Not valid JSON — leave as null.
- }
-
- if (response.status >= 400) {
- let error = `HTTP ${response.status}`;
- if (respJSON && typeof respJSON === "object") {
- const errMap = respJSON as Record<string, unknown>;
- if (typeof errMap.message === "string") {
- error = errMap.message;
- } else if (typeof errMap.code === "string") {
- error = errMap.code;
- }
+ if (result.status === 401 && path !== REFRESH_PATH) {
+ try {
+ await refreshTokens();
+ result = await fetchApi({
+ path,
+ body,
+ signal: controller.signal,
+ });
+ } catch {
+ // Preserve the original API error shape when refresh fails.
}
- return JSON.stringify({
- status: response.status,
- error,
- response: respJSON,
- });
}
- return JSON.stringify({
- status: response.status,
- response: respJSON,
- });
+ return JSON.stringify(result);
} catch (err) {
return JSON.stringify({
error: `Failed to call ${args.operationId}: ${err instanceof Error ? err.message : String(err)}`,