Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,23 @@ vi.mock("@/utils/mcpTokenStore", () => ({
}));

// Mutable holder so individual tests can simulate "Authorize & Fetch" having
// produced a token before submit.
const oauthHook = vi.hoisted(() => ({ tokenResponse: null as Record<string, unknown> | null }));
// produced a token before submit, and inspect the reset wiring.
const oauthHook = vi.hoisted(() => ({
tokenResponse: null as Record<string, unknown> | null,
reset: vi.fn(),
onTokenReceived: null as ((token: Record<string, unknown> | null) => void) | null,
}));
vi.mock("@/hooks/useMcpOAuthFlow", () => ({
useMcpOAuthFlow: () => ({
startOAuthFlow: vi.fn(),
status: "idle",
error: null,
tokenResponse: oauthHook.tokenResponse,
}),
useMcpOAuthFlow: (opts: { onTokenReceived: (token: Record<string, unknown> | null) => void }) => {
oauthHook.onTokenReceived = opts.onTokenReceived;
return {
startOAuthFlow: vi.fn(),
status: "idle",
error: null,
tokenResponse: oauthHook.tokenResponse,
reset: oauthHook.reset,
};
},
}));

vi.mock("./mcp_server_cost_config", () => ({
Expand Down Expand Up @@ -121,6 +129,7 @@ describe("CreateMCPServer", () => {
beforeEach(() => {
vi.clearAllMocks();
oauthHook.tokenResponse = null;
oauthHook.onTokenReceived = null;
});

it("should render the modal with title when visible", () => {
Expand Down Expand Up @@ -614,6 +623,55 @@ describe("CreateMCPServer", () => {

expect(defaultProps.setModalVisible).toHaveBeenCalledWith(false);
});

it("does not leak a previous server's OAuth token into the next add-server session", async () => {
const usedToken = (token: string) =>
vi.mocked(networking.testMCPToolsListRequest).mock.calls.some((call) => call[2] === token);

const { rerender } = render(<CreateMCPServer {...defaultProps} />);

await selectAntOption("Transport Type", "Streamable HTTP");
await waitFor(() => {
expect(screen.getByPlaceholderText("https://your-mcp-server.com")).toBeInTheDocument();
});
await selectAntOption("Authentication", "OAuth");
await waitFor(() => {
expect(screen.getByText("OAuth Flow Type")).toBeInTheDocument();
});

const urlInput = screen.getByPlaceholderText("https://your-mcp-server.com");
await act(async () => {
fireEvent.change(urlInput, { target: { value: "https://server-a.example.com/mcp" } });
});

// Simulate "Authorize & Fetch Token" completing for server A.
await act(async () => {
oauthHook.onTokenReceived?.({ access_token: "stale-token-A", expires_in: 3600 });
});

// Precondition: the freshly fetched token drives the tool preview for server A.
await waitFor(() => {
expect(usedToken("stale-token-A")).toBe(true);
});

// Parent hides the modal (Cancel / successful create both flip this prop).
rerender(<CreateMCPServer {...defaultProps} isModalVisible={false} />);

// The OAuth flow state (source of the "Token fetched" badge) is reset on close.
expect(oauthHook.reset).toHaveBeenCalled();

vi.mocked(networking.testMCPToolsListRequest).mockClear();

// Reopen for a brand-new server and enter a different URL without re-authorizing.
rerender(<CreateMCPServer {...defaultProps} isModalVisible={true} />);
const reopenedUrlInput = screen.getByPlaceholderText("https://your-mcp-server.com");
await act(async () => {
fireEvent.change(reopenedUrlInput, { target: { value: "https://server-b.example.com/mcp" } });
});

// The previous server's token must never be replayed for the new session.
expect(usedToken("stale-token-A")).toBe(false);
});
});

describe("when stdio transport is selected", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@
const [form] = Form.useForm();
const [isLoading, setIsLoading] = useState(false);
const [costConfig, setCostConfig] = useState<MCPServerCostInfo>({});
const [formValues, setFormValues] = useState<Record<string, any>>({});

Check warning on line 75 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
const [pendingRestoredValues, setPendingRestoredValues] = useState<{
values: Record<string, any>;

Check warning on line 77 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
transport?: string;
} | null>(null);
const [aliasManuallyEdited, setAliasManuallyEdited] = useState(false);
Expand Down Expand Up @@ -134,6 +134,7 @@
status: oauthStatus,
error: oauthError,
tokenResponse: oauthTokenResponse,
reset: resetOAuthFlow,
} = useMcpOAuthFlow({
accessToken,
getCredentials: () => form.getFieldValue("credentials"),
Expand Down Expand Up @@ -265,7 +266,7 @@
const transport = prefillData.transport || "";
setTransportType(transport);

const prefillValues: Record<string, any> = {

Check warning on line 269 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
server_name: sanitizedName,
alias: sanitizedName,
description: prefillData.description || "",
Expand All @@ -273,7 +274,7 @@
};

if (transport === "stdio") {
const stdioObj: Record<string, any> = {};

Check warning on line 277 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
if (prefillData.command) stdioObj.command = prefillData.command;
if (prefillData.args && prefillData.args.length > 0) stdioObj.args = prefillData.args;
if (prefillData.env_vars && prefillData.env_vars.length > 0) {
Expand All @@ -295,7 +296,7 @@
setAliasManuallyEdited(false);
}, [isModalVisible, prefillData, form]);

const handleCreate = async (values: Record<string, any>) => {

Check warning on line 299 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Async arrow function has a complexity of 37. Maximum allowed is 20

Check warning on line 299 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
setIsLoading(true);
try {
const {
Expand All @@ -319,7 +320,7 @@

const credentialsPayload =
credentialValues && typeof credentialValues === "object"
? Object.entries(credentialValues).reduce((acc: Record<string, any>, [key, value]) => {

Check warning on line 323 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
if (value === undefined || value === null || value === "") {
return acc;
}
Expand Down Expand Up @@ -352,12 +353,12 @@
// If it's the full mcpServers structure, extract the first server config
if (stdioConfig.mcpServers && typeof stdioConfig.mcpServers === "object") {
const serverNames = Object.keys(stdioConfig.mcpServers);
if (serverNames.length > 0) {

Check warning on line 356 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Blocks are nested too deeply (5). Maximum allowed is 4
const firstServerName = serverNames[0];
actualConfig = stdioConfig.mcpServers[firstServerName];

// If no alias is provided, use the server name from the JSON
if (!restValues.server_name) {

Check warning on line 361 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Blocks are nested too deeply (6). Maximum allowed is 4
restValues.server_name = firstServerName.replace(/-/g, "_"); // Replace hyphens with underscores
}
}
Expand All @@ -382,7 +383,7 @@
}

// Parse token_validation JSON if provided
let tokenValidation: Record<string, any> | null = null;

Check warning on line 386 in ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
if (rawTokenValidationJson && rawTokenValidationJson.trim() !== "") {
try {
tokenValidation = JSON.parse(rawTokenValidationJson);
Expand Down Expand Up @@ -554,12 +555,15 @@
}
}, [formValues.server_name]);

// Clear formValues when modal closes to reset child components
// Clear form and OAuth state when the modal closes so a previous server's
// authorization never bleeds into the next "Add New MCP Server" session.
React.useEffect(() => {
if (!isModalVisible) {
setFormValues({});
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
setOauthAccessToken(null);
resetOAuthFlow();
}
}, [isModalVisible]);
}, [isModalVisible, resetOAuthFlow]);
Comment thread
tin-berri marked this conversation as resolved.
Resolved

const isAdmin = isAdminRole(userRole);

Expand Down
78 changes: 78 additions & 0 deletions ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import * as networking from "@/components/networking";
import { setSecureItem } from "@/utils/secureStorage";
import { useMcpOAuthFlow } from "./useMcpOAuthFlow";

vi.mock("@/components/networking", () => ({
exchangeMcpOAuthToken: vi.fn(),
cacheTemporaryMcpServer: vi.fn(),
registerMcpOAuthClient: vi.fn(),
buildMcpOAuthAuthorizeUrl: vi.fn(),
getProxyBaseUrl: vi.fn(() => ""),
serverRootPath: "",
}));

vi.mock("@/components/molecules/notifications_manager", () => ({
default: { success: vi.fn(), error: vi.fn() },
}));

const FLOW_STATE_KEY = "litellm-mcp-oauth-flow-state";
const RESULT_KEY = "litellm-mcp-oauth-result";

/** Seed storage so the hook's on-mount resume flow exchanges a code for a token. */
function seedCompletedRedirect() {
setSecureItem(RESULT_KEY, JSON.stringify({ state: "state-1", code: "code-1" }));
setSecureItem(
FLOW_STATE_KEY,
JSON.stringify({
state: "state-1",
codeVerifier: "verifier-1",
serverId: "server-1",
clientId: "client-1",
redirectUri: "https://app.example.com/ui/mcp/oauth/callback",
flowSource: "create",
}),
);
}

function renderFlow(onTokenReceived = vi.fn()) {
return renderHook(() =>
useMcpOAuthFlow({
accessToken: "admin-token",
getCredentials: () => ({}),
getTemporaryPayload: () => ({ url: "https://server-1.example.com/mcp", transport: "http" }),
onTokenReceived,
flowSource: "create",
}),
);
}

describe("useMcpOAuthFlow reset", () => {
beforeEach(() => {
vi.clearAllMocks();
window.sessionStorage.clear();
window.localStorage.clear();
});

it("clears a successfully fetched token so it cannot leak into the next session", async () => {
const token = { access_token: "tok-123", expires_in: 3600 };
vi.mocked(networking.exchangeMcpOAuthToken).mockResolvedValue(token);
seedCompletedRedirect();

const onTokenReceived = vi.fn();
const { result } = renderFlow(onTokenReceived);

await waitFor(() => expect(result.current.status).toBe("success"));
expect(result.current.tokenResponse).toEqual(token);
expect(onTokenReceived).toHaveBeenCalledWith(token);

act(() => {
result.current.reset();
});

expect(result.current.status).toBe("idle");
expect(result.current.tokenResponse).toBeNull();
expect(result.current.error).toBeNull();
});
});
8 changes: 8 additions & 0 deletions ui/litellm-dashboard/src/hooks/useMcpOAuthFlow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ interface UseMcpOAuthFlowResult {
status: McpOAuthStatus;
error: string | null;
tokenResponse: Record<string, any> | null;
reset: () => void;
}

export const useMcpOAuthFlow = ({
Expand Down Expand Up @@ -336,10 +337,17 @@ export const useMcpOAuthFlow = ({
resumeOAuthFlow();
}, [resumeOAuthFlow]);

const reset = useCallback(() => {
setStatus("idle");
setError(null);
setTokenResponse(null);
}, []);
Comment thread
tin-berri marked this conversation as resolved.
Resolved

return {
startOAuthFlow,
status,
error,
tokenResponse,
reset,
};
};
Loading