-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathmcp_oauth.e2e.test.ts
More file actions
311 lines (282 loc) · 11.4 KB
/
Copy pathmcp_oauth.e2e.test.ts
File metadata and controls
311 lines (282 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { dirname, resolve } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { describe, expect, it, onTestFinished } from "vitest";
import type { CopilotSession, MCPServerConfig, McpAuthRequest } from "../../src/index.js";
import { approveAll } from "../../src/index.js";
import { createSdkTestContext } from "./harness/sdkTestContext.js";
import { waitForCondition } from "./harness/sdkTestHelper.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const TEST_MCP_OAUTH_SERVER = resolve(__dirname, "../../../test/harness/test-mcp-oauth-server.mjs");
const EXPECTED_TOKEN = "sdk-host-token";
const REFRESH_TOKEN = `${EXPECTED_TOKEN}-refresh`;
const UPSCOPE_TOKEN = `${EXPECTED_TOKEN}-upscope`;
const REAUTH_TOKEN = `${EXPECTED_TOKEN}-reauth`;
describe("MCP OAuth host auth", async () => {
const { copilotClient: client } = await createSdkTestContext({
copilotClientOptions: {
env: {
COPILOT_MCP_APPS: "true",
MCP_APPS: "true",
},
},
});
it("should satisfy MCP OAuth using host-provided token", { timeout: 120_000 }, async () => {
const oauthServer = await startOAuthMcpServer();
const serverName = "oauth-protected-mcp";
let authRequest: McpAuthRequest | undefined;
const session = await client.createSession({
onPermissionRequest: approveAll,
enableMcpApps: true,
onMcpAuthRequest: async (request) => {
authRequest = request;
return {
kind: "token",
accessToken: EXPECTED_TOKEN,
tokenType: "Bearer",
expiresIn: 3600,
};
},
mcpServers: {
[serverName]: {
type: "http",
url: `${oauthServer.url}/mcp`,
tools: ["*"],
oauthClientId: "sdk-e2e-client",
oauthPublicClient: true,
} as unknown as MCPServerConfig,
},
});
onTestFinished(() => disconnectSession(session));
await waitForMcpServerStatus(session, serverName);
const tools = await session.rpc.mcp.listTools({ serverName });
expect(tools.tools.map((tool) => tool.name)).toContain("whoami");
expect(authRequest).toMatchObject({
requestId: expect.any(String),
serverName,
serverUrl: `${oauthServer.url}/mcp`,
reason: "initial",
wwwAuthenticateParams: {
resourceMetadataUrl: `${oauthServer.url}/.well-known/oauth-protected-resource`,
scope: "mcp.read",
error: "invalid_token",
},
resourceMetadata: JSON.stringify({
resource: `${oauthServer.url}/mcp`,
authorization_servers: [oauthServer.url],
scopes_supported: ["mcp.read"],
bearer_methods_supported: ["header"],
}),
});
const requests = await oauthServer.requests();
expect(requests.some((request) => request.authorization === null)).toBe(true);
expect(
requests.some((request) => request.authorization === `Bearer ${EXPECTED_TOKEN}`)
).toBe(true);
});
it(
"should request host-owned replacement tokens across the MCP OAuth lifecycle",
{ timeout: 120_000 },
async () => {
const oauthServer = await startOAuthMcpServer();
const serverName = "oauth-lifecycle-mcp";
const authRequests: McpAuthRequest[] = [];
let refreshCount = 0;
const session = await client.createSession({
onPermissionRequest: approveAll,
enableMcpApps: true,
onMcpAuthRequest: async (request) => {
authRequests.push(request);
switch (request.reason) {
case "initial":
return { kind: "token", accessToken: EXPECTED_TOKEN };
case "refresh":
refreshCount++;
if (refreshCount === 1) {
return { kind: "token", accessToken: REFRESH_TOKEN };
}
return { kind: "cancelled" };
case "upscope":
return { kind: "token", accessToken: UPSCOPE_TOKEN };
case "reauth":
return { kind: "token", accessToken: REAUTH_TOKEN };
}
},
mcpServers: {
[serverName]: {
type: "http",
url: `${oauthServer.url}/mcp`,
tools: ["*"],
oauthClientId: "sdk-e2e-client",
oauthPublicClient: true,
} as unknown as MCPServerConfig,
},
});
onTestFinished(() => disconnectSession(session));
await waitForMcpServerStatus(session, serverName);
await callWhoami(session, serverName, "refresh");
await callWhoami(session, serverName, "upscope");
await callWhoami(session, serverName, "reauth");
expect(authRequests.map((request) => request.reason)).toEqual([
"initial",
"refresh",
"upscope",
"refresh",
"reauth",
]);
const upscopeRequest = authRequests.find((request) => request.reason === "upscope");
expect(upscopeRequest?.wwwAuthenticateParams).toEqual({
resourceMetadataUrl: `${oauthServer.url}/.well-known/oauth-protected-resource`,
scope: "mcp.write",
error: "insufficient_scope",
});
expect(upscopeRequest?.resourceMetadata).toBe(
JSON.stringify({
resource: `${oauthServer.url}/mcp`,
authorization_servers: [oauthServer.url],
scopes_supported: ["mcp.read"],
bearer_methods_supported: ["header"],
})
);
const requests = await oauthServer.requests();
for (const token of [EXPECTED_TOKEN, REFRESH_TOKEN, UPSCOPE_TOKEN, REAUTH_TOKEN]) {
expect(
requests.some((request) => request.authorization === `Bearer ${token}`)
).toBe(true);
}
}
);
it(
"should cancel pending MCP OAuth requests when the host declines",
{ timeout: 120_000 },
async () => {
const oauthServer = await startOAuthMcpServer();
const serverName = "oauth-cancelled-mcp";
let authRequest: McpAuthRequest | undefined;
const session = await client.createSession({
onPermissionRequest: approveAll,
onMcpAuthRequest: async (request) => {
authRequest = request;
return { kind: "cancelled" };
},
mcpServers: {
[serverName]: {
type: "http",
url: `${oauthServer.url}/mcp`,
tools: ["*"],
oauthClientId: "sdk-e2e-client",
oauthPublicClient: true,
} as unknown as MCPServerConfig,
},
});
onTestFinished(() => disconnectSession(session));
await waitForMcpServerStatus(session, serverName, "failed");
expect(authRequest).toMatchObject({
serverName,
reason: "initial",
});
}
);
});
async function waitForMcpServerStatus(
session: CopilotSession,
serverName: string,
expectedStatus = "connected"
): Promise<void> {
let lastStatus = "<not listed>";
await waitForCondition(
async () => {
const result = await session.rpc.mcp.list();
const server = result.servers.find((entry) => entry.name === serverName);
lastStatus = server?.status ?? "<not listed>";
return server?.status === expectedStatus;
},
{
timeoutMs: 60_000,
intervalMs: 200,
timeoutMessage: `${serverName} did not reach ${expectedStatus}; last status was ${lastStatus}`,
}
);
}
async function callWhoami(
session: CopilotSession,
serverName: string,
scenario: "refresh" | "upscope" | "reauth"
): Promise<void> {
const result = await session.rpc.mcp.apps.callTool({
serverName,
originServerName: serverName,
toolName: "whoami",
arguments: { scenario },
});
expect(result.content).toEqual([{ type: "text", text: "oauth-test-user" }]);
}
async function startOAuthMcpServer(): Promise<{
url: string;
requests: () => Promise<Array<{ authorization: string | null }>>;
}> {
const child = spawn(process.execPath, [TEST_MCP_OAUTH_SERVER], {
env: { ...process.env, EXPECTED_TOKEN },
stdio: ["ignore", "pipe", "pipe"],
});
onTestFinished(() => stopChild(child));
const stderr: string[] = [];
child.stderr.on("data", (chunk) => stderr.push(String(chunk)));
const url = await new Promise<string>((resolvePromise, reject) => {
const rl = createInterface({ input: child.stdout });
const timeout = setTimeout(() => {
rl.close();
reject(new Error(`Timed out waiting for OAuth MCP server. ${stderr.join("")}`));
}, 10_000);
child.once("exit", (code, signal) => {
clearTimeout(timeout);
rl.close();
reject(
new Error(
`OAuth MCP server exited before listening. code=${code} signal=${signal} ${stderr.join("")}`
)
);
});
rl.on("line", (line) => {
const match = /^Listening: (.+)$/.exec(line);
if (!match) {
return;
}
clearTimeout(timeout);
rl.close();
resolvePromise(match[1]);
});
});
return {
url,
requests: async () => {
const response = await fetch(`${url}/__requests`);
if (!response.ok) {
throw new Error(`Failed to fetch OAuth MCP requests: ${response.status}`);
}
return response.json();
},
};
}
async function disconnectSession(session: CopilotSession): Promise<void> {
try {
await session.disconnect();
} catch {
// Best-effort cleanup.
}
}
function stopChild(child: ChildProcessWithoutNullStreams): Promise<void> {
if (child.exitCode !== null || child.killed) {
return Promise.resolve();
}
const exitPromise = new Promise<void>((resolvePromise) => {
child.once("exit", () => resolvePromise());
});
child.kill("SIGTERM");
return exitPromise;
}