Elffuss BraidHub

kikocis/continue public

main · 9.2 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 mockMcpServerId: string;
25 let mockMcpServerUrl: string;
26
27 beforeEach(() => {
28 // file is present in the core/test directory
29 globalContextFilePath = getGlobalContextFilePath();
30 if (fs.existsSync(globalContextFilePath)) {
31 fs.unlinkSync(globalContextFilePath);
32 }
33
34 mockIde = {
35 openUrl: vi.fn(),
36 showToast: vi.fn(),
37 getExternalUri: vi.fn((uri) => Promise.resolve(uri)),
38 };
39
40 mockMcpServerId = "test-server";
41 mockMcpServerUrl = "https://test-server.com";
42
43 vi.clearAllMocks();
44 });
45
46 afterEach(() => {
47 if (fs.existsSync(globalContextFilePath)) {
48 fs.unlinkSync(globalContextFilePath);
49 }
50 });
51
52 describe("getOauthToken", () => {
53 test("should return undefined when no tokens are stored", async () => {
54 const result = await getOauthToken("https://test-server.com", mockIde);
55 expect(result).toBeUndefined();
56 });
57
58 test("should return access token when tokens are stored", async () => {
59 const globalContext = new GlobalContext();
60 globalContext.update("mcpOauthStorage", {
61 "https://test-server.com": {
62 tokens: {
63 access_token: "test-access-token",
64 token_type: "Bearer",
65 },
66 },
67 });
68
69 const result = await getOauthToken("https://test-server.com", mockIde);
70 expect(result).toBe("test-access-token");
71 });
72
73 test("should handle different server URLs independently", async () => {
74 const globalContext = new GlobalContext();
75 globalContext.update("mcpOauthStorage", {
76 "https://server1.com": {
77 tokens: {
78 access_token: "token1",
79 token_type: "Bearer",
80 },
81 },
82 "https://server2.com": {
83 tokens: {
84 access_token: "token2",
85 token_type: "Bearer",
86 },
87 },
88 });
89
90 const result1 = await getOauthToken("https://server1.com", mockIde);
91 const result2 = await getOauthToken("https://server2.com", mockIde);
92 const result3 = await getOauthToken("https://server3.com", mockIde);
93
94 expect(result1).toBe("token1");
95 expect(result2).toBe("token2");
96 expect(result3).toBeUndefined();
97 });
98 });
99
100 describe("performAuth", () => {
101 test("should call auth with correct parameters and return auth result", async () => {
102 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
103 const mockAuth = vi.mocked(auth);
104 mockAuth.mockResolvedValue("AUTHORIZED");
105
106 const result = await performAuth(
107 mockMcpServerId,
108 mockMcpServerUrl,
109 mockIde,
110 );
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(mockMcpServerUrl, 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(mockMcpServerUrl, 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(mockMcpServerId, mockMcpServerUrl, 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(
214 mockMcpServerId,
215 mockMcpServerUrl,
216 ideWithoutExternalUri as any,
217 );
218
219 // Should still work without getExternalUri
220 expect(mockAuth).toHaveBeenCalled();
221 });
222
223 test("should handle getExternalUri errors gracefully", async () => {
224 const errorIde = {
225 ...mockIde,
226 getExternalUri: vi.fn(() => Promise.reject(new Error("Network error"))),
227 };
228
229 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
230 const mockAuth = vi.mocked(auth);
231 mockAuth.mockResolvedValue("AUTHORIZED");
232
233 // Should not throw, should fallback to localhost
234 await performAuth(mockMcpServerId, mockMcpServerUrl, errorIde);
235
236 expect(mockAuth).toHaveBeenCalled();
237 });
238 });
239
240 describe("concurrent authentication", () => {
241 test("should handle multiple concurrent auth flows", async () => {
242 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
243 const mockAuth = vi.mocked(auth);
244 mockAuth.mockResolvedValue("AUTHORIZED");
245
246 // Start two auth flows concurrently
247 const [result1, result2] = await Promise.all([
248 performAuth("server-1-id", "https://server1.com", mockIde),
249 performAuth("server-2-id", "https://server2.com", mockIde),
250 ]);
251
252 expect(result1).toBe("AUTHORIZED");
253 expect(result2).toBe("AUTHORIZED");
254 expect(mockAuth).toHaveBeenCalledTimes(2);
255 });
256 });
257
258 describe("error handling", () => {
259 test("should clean up context on auth failure", async () => {
260 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
261 const mockAuth = vi.mocked(auth);
262
263 // First successful call to set up the context
264 mockAuth.mockResolvedValueOnce("AUTHORIZED");
265 await performAuth(mockMcpServerId, mockMcpServerUrl, mockIde);
266
267 // Reset mock for the failure test
268 mockAuth.mockRejectedValueOnce(new Error("Auth failed"));
269
270 // Second call that should fail and clean up
271 await expect(
272 performAuth(mockMcpServerId, mockMcpServerUrl, mockIde),
273 ).rejects.toThrow("Auth failed");
274
275 // Verify auth was called twice
276 expect(mockAuth).toHaveBeenCalledTimes(2);
277
278 // The context cleanup happens internally in performAuth's catch block
279 // We can verify it indirectly by checking that a subsequent auth call works
280 mockAuth.mockResolvedValueOnce("AUTHORIZED");
281 const result = await performAuth(
282 mockMcpServerId,
283 mockMcpServerUrl,
284 mockIde,
285 );
286 expect(result).toBe("AUTHORIZED");
287 });
288
289 test("should handle missing server URL", async () => {
290 const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
291 const mockAuth = vi.mocked(auth);
292 mockAuth.mockResolvedValue("AUTHORIZED");
293
294 await performAuth("invalid-id", "", mockIde);
295
296 // Should still attempt auth with empty URL
297 expect(mockAuth).toHaveBeenCalled();
298 });
299 });
300});