Elffuss BraidHub

kikocis/continue public

e31fcddb0dec · 9.9 KiBRawPermalink
1import fs from "node:fs";
2import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
3import { GlobalContext } from "../../util/GlobalContext";
4import { getGlobalContextFilePath } from "../../util/paths";
5import { getOauthToken, performAuth, removeMCPAuth } from "./MCPOauth";
6
7// Mock the MCP SDK auth module
8vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
9 auth: vi.fn(),
10}));
11
12// Mock the MCPManagerSingleton to avoid circular imports
13vi.mock("./MCPManagerSingleton", () => ({
14 MCPManagerSingleton: {
15 getInstance: vi.fn(() => ({
16 refreshConnection: vi.fn(),
17 })),
18 },
19}));
20
21describe("MCPOauth", () => {
22 let globalContextFilePath: string;
23 let mockIde: any;
24 let mockMcpServer: any;
25
26 beforeEach(() => {
27 // file is present in the core/test directory
28 globalContextFilePath = getGlobalContextFilePath();
29 if (fs.existsSync(globalContextFilePath)) {
30 fs.unlinkSync(globalContextFilePath);
31 }
32
33 mockIde = {
34 openUrl: vi.fn(),
35 showToast: vi.fn(),
36 getExternalUri: vi.fn((uri) => Promise.resolve(uri)),
37 };
38
39 mockMcpServer = {
40 id: "test-server",
41 transport: {
42 type: "sse",
43 url: "https://test-server.com",
44 },
45 };
46
47 vi.clearAllMocks();
48 });
49
50 afterEach(() => {
51 if (fs.existsSync(globalContextFilePath)) {
52 fs.unlinkSync(globalContextFilePath);
53 }
54 });
55
56 describe("getOauthToken", () => {
57 test("should return undefined when no tokens are stored", async () => {
58 const result = await getOauthToken("https://test-server.com", mockIde);
59 expect(result).toBeUndefined();
60 });
61
62 test("should return access token when tokens are stored", async () => {
63 const globalContext = new GlobalContext();
64 globalContext.update("mcpOauthStorage", {
65 "https://test-server.com": {
66 tokens: {
67 access_token: "test-access-token",
68 token_type: "Bearer",
69 },
70 },
71 });
72
73 const result = await getOauthToken("https://test-server.com", mockIde);
74 expect(result).toBe("test-access-token");
75 });
76
77 test("should handle different server URLs independently", async () => {
78 const globalContext = new GlobalContext();
79 globalContext.update("mcpOauthStorage", {
80 "https://server1.com": {
81 tokens: {
82 access_token: "token1",
83 token_type: "Bearer",
84 },
85 },
86 "https://server2.com": {
87 tokens: {
88 access_token: "token2",
89 token_type: "Bearer",
90 },
91 },
92 });
93
94 const result1 = await getOauthToken("https://server1.com", mockIde);
95 const result2 = await getOauthToken("https://server2.com", mockIde);
96 const result3 = await getOauthToken("https://server3.com", mockIde);
97
98 expect(result1).toBe("token1");
99 expect(result2).toBe("token2");
100 expect(result3).toBeUndefined();
101 });
102 });
103
104 describe("performAuth", () => {
105 test("should call auth with correct parameters and return auth result", async () => {
106 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
107 const mockAuth = vi.mocked(auth);
108 mockAuth.mockResolvedValue("AUTHORIZED");
109
110 const result = await performAuth(mockMcpServer, mockIde);
111
112 expect(mockAuth).toHaveBeenCalledWith(
113 expect.any(Object), // MCPConnectionOauthProvider instance
114 {
115 serverUrl: "https://test-server.com",
116 },
117 );
118 expect(result).toBe("AUTHORIZED");
119 });
120 });
121
122 describe("removeMCPAuth", () => {
123 test("should clear oauth storage for the server", () => {
124 const globalContext = new GlobalContext();
125 globalContext.update("mcpOauthStorage", {
126 "https://test-server.com": {
127 tokens: {
128 access_token: "test-access-token",
129 token_type: "Bearer",
130 },
131 clientInformation: {
132 client_id: "test-client-id",
133 redirect_uris: ["http://localhost:3000"],
134 },
135 codeVerifier: "test-code-verifier",
136 },
137 "https://other-server.com": {
138 tokens: {
139 access_token: "other-access-token",
140 token_type: "Bearer",
141 },
142 },
143 });
144
145 removeMCPAuth(mockMcpServer, mockIde);
146
147 const updatedStorage = globalContext.get("mcpOauthStorage");
148 expect(updatedStorage).toEqual({
149 "https://other-server.com": {
150 tokens: {
151 access_token: "other-access-token",
152 token_type: "Bearer",
153 },
154 },
155 });
156 });
157
158 test("should handle non-existent server gracefully", () => {
159 const globalContext = new GlobalContext();
160 globalContext.update("mcpOauthStorage", {
161 "https://other-server.com": {
162 tokens: {
163 access_token: "other-access-token",
164 token_type: "Bearer",
165 },
166 },
167 });
168
169 removeMCPAuth(mockMcpServer, mockIde);
170
171 const updatedStorage = globalContext.get("mcpOauthStorage");
172 expect(updatedStorage).toEqual({
173 "https://other-server.com": {
174 tokens: {
175 access_token: "other-access-token",
176 token_type: "Bearer",
177 },
178 },
179 });
180 });
181 });
182
183 describe("redirect URL handling", () => {
184 test("should use getExternalUri when available for VS Code", async () => {
185 const vscodeIde = {
186 ...mockIde,
187 getExternalUri: vi.fn((uri) =>
188 Promise.resolve("https://vscode.dev/redirect"),
189 ),
190 };
191
192 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
193 const mockAuth = vi.mocked(auth);
194 mockAuth.mockResolvedValue("AUTHORIZED");
195
196 await performAuth(mockMcpServer, vscodeIde);
197
198 expect(vscodeIde.getExternalUri).toHaveBeenCalledWith(
199 "http://localhost:3000",
200 );
201 });
202
203 test("should fallback to localhost when getExternalUri is not available", async () => {
204 const ideWithoutExternalUri = {
205 openUrl: vi.fn(() => Promise.resolve()),
206 showToast: vi.fn(() => Promise.resolve()),
207 };
208
209 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
210 const mockAuth = vi.mocked(auth);
211 mockAuth.mockResolvedValue("AUTHORIZED");
212
213 await performAuth(mockMcpServer, ideWithoutExternalUri as any);
214
215 // Should still work without getExternalUri
216 expect(mockAuth).toHaveBeenCalled();
217 });
218
219 test("should handle getExternalUri errors gracefully", async () => {
220 const errorIde = {
221 ...mockIde,
222 getExternalUri: vi.fn(() => Promise.reject(new Error("Network error"))),
223 };
224
225 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
226 const mockAuth = vi.mocked(auth);
227 mockAuth.mockResolvedValue("AUTHORIZED");
228
229 // Should not throw, should fallback to localhost
230 await performAuth(mockMcpServer, errorIde);
231
232 expect(mockAuth).toHaveBeenCalled();
233 });
234 });
235
236 describe("concurrent authentication", () => {
237 test("should handle multiple concurrent auth flows", async () => {
238 const server1 = {
239 id: "server-1",
240 transport: { type: "sse" as const, url: "https://server1.com" },
241 status: "connected" as const,
242 errors: [],
243 infos: [],
244 isProtectedResource: false,
245 prompts: [],
246 tools: [],
247 resources: [],
248 resourceTemplates: [],
249 name: "server-1",
250 };
251 const server2 = {
252 id: "server-2",
253 transport: { type: "sse" as const, url: "https://server2.com" },
254 status: "connected" as const,
255 errors: [],
256 infos: [],
257 isProtectedResource: false,
258 prompts: [],
259 tools: [],
260 resources: [],
261 resourceTemplates: [],
262 name: "server-2",
263 };
264
265 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
266 const mockAuth = vi.mocked(auth);
267 mockAuth.mockResolvedValue("AUTHORIZED");
268
269 // Start two auth flows concurrently
270 const [result1, result2] = await Promise.all([
271 performAuth(server1, mockIde),
272 performAuth(server2, mockIde),
273 ]);
274
275 expect(result1).toBe("AUTHORIZED");
276 expect(result2).toBe("AUTHORIZED");
277 expect(mockAuth).toHaveBeenCalledTimes(2);
278 });
279 });
280
281 describe("error handling", () => {
282 test("should clean up context on auth failure", async () => {
283 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
284 const mockAuth = vi.mocked(auth);
285
286 // First successful call to set up the context
287 mockAuth.mockResolvedValueOnce("AUTHORIZED");
288 await performAuth(mockMcpServer, mockIde);
289
290 // Reset mock for the failure test
291 mockAuth.mockRejectedValueOnce(new Error("Auth failed"));
292
293 // Second call that should fail and clean up
294 await expect(performAuth(mockMcpServer, mockIde)).rejects.toThrow(
295 "Auth failed",
296 );
297
298 // Verify auth was called twice
299 expect(mockAuth).toHaveBeenCalledTimes(2);
300
301 // The context cleanup happens internally in performAuth's catch block
302 // We can verify it indirectly by checking that a subsequent auth call works
303 mockAuth.mockResolvedValueOnce("AUTHORIZED");
304 const result = await performAuth(mockMcpServer, mockIde);
305 expect(result).toBe("AUTHORIZED");
306 });
307
308 test("should handle missing server URL", async () => {
309 const invalidServer = {
310 id: "invalid",
311 transport: { type: "sse" as const, url: "" },
312 status: "connected" as const,
313 errors: [],
314 infos: [],
315 isProtectedResource: false,
316 prompts: [],
317 tools: [],
318 resources: [],
319 resourceTemplates: [],
320 name: "invalid",
321 };
322
323 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
324 const mockAuth = vi.mocked(auth);
325 mockAuth.mockResolvedValue("AUTHORIZED");
326
327 await performAuth(invalidServer, mockIde);
328
329 // Should still attempt auth with empty URL
330 expect(mockAuth).toHaveBeenCalled();
331 });
332 });
333});