-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathmcp-oauth-provider.test.ts
More file actions
518 lines (434 loc) · 17.7 KB
/
Copy pathmcp-oauth-provider.test.ts
File metadata and controls
518 lines (434 loc) · 17.7 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/**
* Tests for mcp-oauth-provider.ts - OAuth provider implementation
*/
import { describe, it, before, after } from "node:test"
import assert from "node:assert"
import { existsSync, rmSync, mkdirSync } from "fs"
import { join } from "path"
import { tmpdir } from "os"
import { randomBytes } from "crypto"
// Set up isolated temp directory for tests
const TEST_DIR = join(tmpdir(), `mcp-oauth-test-${randomBytes(4).toString('hex')}`)
process.env.MCP_OAUTH_DIR = TEST_DIR
import {
getOAuthCallbackPath,
getOAuthCallbackPort,
McpOAuthProvider,
setOAuthCallbackPath,
setOAuthCallbackPort,
type McpOAuthConfig,
} from "./mcp-oauth-provider.ts"
import { getAuthForUrl, saveAuthEntry, updateOAuthState } from "./mcp-auth.ts"
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
import type { OAuthClientInformationFull, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js"
describe("McpOAuthProvider", () => {
const serverName = "test-server"
const serverUrl = "https://api.example.com"
let redirectCaptured: URL | undefined
before(() => {
// Ensure clean state
try {
if (existsSync(TEST_DIR)) {
rmSync(TEST_DIR, { recursive: true, force: true })
}
mkdirSync(TEST_DIR, { recursive: true })
} catch {
// Ignore cleanup errors
}
})
after(() => {
// Clean up temp directory
try {
if (existsSync(TEST_DIR)) {
rmSync(TEST_DIR, { recursive: true, force: true })
}
} catch {
// Ignore cleanup errors
}
redirectCaptured = undefined
})
function createProvider(config: McpOAuthConfig = {}) {
return new McpOAuthProvider(serverName, serverUrl, config, {
onRedirect: async (url) => {
redirectCaptured = url
},
})
}
describe("redirectUrl", () => {
it("should return the correct redirect URL", () => {
const provider = createProvider()
assert.strictEqual(
provider.redirectUrl,
"http://localhost:19876/callback"
)
})
it("should use a configured redirect URI", () => {
const provider = createProvider({ redirectUri: "http://localhost:3118/slack/callback" })
assert.strictEqual(provider.redirectUrl, "http://localhost:3118/slack/callback")
})
it("should snapshot generated redirect URI at construction", () => {
const originalPort = getOAuthCallbackPort()
const originalPath = getOAuthCallbackPath()
setOAuthCallbackPort(41234)
setOAuthCallbackPath("/snapshot/callback")
try {
const provider = createProvider()
setOAuthCallbackPort(52345)
setOAuthCallbackPath("/changed/callback")
assert.strictEqual(provider.redirectUrl, "http://localhost:41234/snapshot/callback")
assert.deepStrictEqual(provider.clientMetadata.redirect_uris, ["http://localhost:41234/snapshot/callback"])
} finally {
setOAuthCallbackPort(originalPort)
setOAuthCallbackPath(originalPath)
}
})
})
describe("clientMetadata", () => {
it("should return correct metadata for public client", () => {
const provider = createProvider()
const metadata = provider.clientMetadata
assert.deepStrictEqual(metadata.redirect_uris, ["http://localhost:19876/callback"])
assert.strictEqual(metadata.client_name, "Pi Coding Agent")
assert.strictEqual(metadata.client_uri, "https://github.com/nicobailon/pi-mcp-adapter")
assert.deepStrictEqual(metadata.grant_types, ["authorization_code", "refresh_token"])
assert.deepStrictEqual(metadata.response_types, ["code"])
assert.strictEqual(metadata.token_endpoint_auth_method, "none")
})
it("should return correct metadata for confidential client", () => {
const provider = createProvider({ clientSecret: "secret" })
const metadata = provider.clientMetadata
assert.strictEqual(metadata.token_endpoint_auth_method, "client_secret_post")
})
it("should use configured redirect URI and client metadata", () => {
const provider = createProvider({
redirectUri: "http://localhost:3118/slack/callback",
clientName: "Slack MCP",
clientUri: "https://example.com/slack-mcp",
})
const metadata = provider.clientMetadata
assert.deepStrictEqual(metadata.redirect_uris, ["http://localhost:3118/slack/callback"])
assert.strictEqual(metadata.client_name, "Slack MCP")
assert.strictEqual(metadata.client_uri, "https://example.com/slack-mcp")
})
it("should use configured client name for client_credentials", () => {
const provider = createProvider({
grantType: "client_credentials",
clientName: "Service MCP",
})
const metadata = provider.clientMetadata
assert.strictEqual(metadata.client_name, "Service MCP")
assert.deepStrictEqual(metadata.redirect_uris, [])
assert.deepStrictEqual(metadata.grant_types, ["client_credentials"])
})
})
describe("clientInformation", () => {
it("should return config clientId when provided", async () => {
const provider = createProvider({ clientId: "config-client", clientSecret: "config-secret" })
const info = await provider.clientInformation()
assert.strictEqual(info?.client_id, "config-client")
assert.strictEqual(info?.client_secret, "config-secret")
})
it("should return stored client info when no config", async () => {
const provider = createProvider()
// Save client info directly
saveAuthEntry(serverName, {
clientInfo: {
clientId: "stored-client",
clientSecret: "stored-secret",
clientIdIssuedAt: Math.floor(Date.now() / 1000),
clientSecretExpiresAt: Math.floor(Date.now() / 1000) + 3600,
},
serverUrl,
}, serverUrl)
const info = await provider.clientInformation()
assert.strictEqual(info?.client_id, "stored-client")
assert.strictEqual(info?.client_secret, "stored-secret")
})
it("should return undefined when URL doesn't match", async () => {
const provider = createProvider()
// Save client info with different URL
saveAuthEntry(serverName, {
clientInfo: {
clientId: "stored-client",
clientSecret: "stored-secret",
},
serverUrl: "https://different.com",
}, "https://different.com")
const info = await provider.clientInformation()
assert.strictEqual(info, undefined)
})
it("should return undefined when client secret expired", async () => {
const provider = createProvider()
// Save client info with expired secret
saveAuthEntry(serverName, {
clientInfo: {
clientId: "stored-client",
clientSecret: "stored-secret",
clientSecretExpiresAt: 1, // Expired in 1970
},
serverUrl,
}, serverUrl)
const info = await provider.clientInformation()
assert.strictEqual(info, undefined)
})
it("should prefer config over stored", async () => {
const provider = createProvider({ clientId: "config-client" })
// Save different client info
saveAuthEntry(serverName, {
clientInfo: {
clientId: "stored-client",
clientSecret: "stored-secret",
},
serverUrl,
}, serverUrl)
const info = await provider.clientInformation()
assert.strictEqual(info?.client_id, "config-client")
})
})
describe("saveClientInformation", () => {
it("should save client information", async () => {
const provider = createProvider()
const futureTime = Math.floor(Date.now() / 1000) + 3600
const info: OAuthClientInformationFull = {
client_id: "new-client",
client_secret: "new-secret",
redirect_uris: ["http://localhost:3118/callback"],
client_id_issued_at: Math.floor(Date.now() / 1000),
client_secret_expires_at: futureTime,
}
await provider.saveClientInformation(info)
const storedInfo = await provider.clientInformation()
assert.strictEqual(storedInfo?.client_id, "new-client")
assert.strictEqual(storedInfo?.client_secret, "new-secret")
assert.deepStrictEqual(getAuthForUrl(serverName, serverUrl)?.clientInfo?.redirectUris, ["http://localhost:3118/callback"])
})
it("should save the current redirect URL when registration omits redirect_uris", async () => {
const provider = new McpOAuthProvider("redirect-fallback", serverUrl, { redirectUri: "http://localhost:3118/custom" }, {
onRedirect: async () => {},
})
await provider.saveClientInformation({
client_id: "fallback-client",
client_secret: "fallback-secret",
} as OAuthClientInformationFull)
assert.deepStrictEqual(getAuthForUrl("redirect-fallback", serverUrl)?.clientInfo?.redirectUris, ["http://localhost:3118/custom"])
})
it("should return stored dynamic client info even when redirect URIs are stale", async () => {
const provider = new McpOAuthProvider("stale-redirect-client", serverUrl, { redirectUri: "http://localhost:3118/current" }, {
onRedirect: async () => {},
})
saveAuthEntry("stale-redirect-client", {
clientInfo: {
clientId: "stored-client",
clientSecret: "stored-secret",
redirectUris: ["http://localhost:19876/callback"],
},
serverUrl,
}, serverUrl)
const info = await provider.clientInformation()
assert.strictEqual(info?.client_id, "stored-client")
assert.strictEqual(info?.client_secret, "stored-secret")
})
})
describe("tokens / saveTokens", () => {
it("should save and retrieve tokens", async () => {
const provider = createProvider()
const tokens: OAuthTokens = {
access_token: "access-123",
token_type: "Bearer",
refresh_token: "refresh-456",
expires_in: 3600,
scope: "read write",
}
await provider.saveTokens(tokens)
const stored = await provider.tokens()
assert.strictEqual(stored?.access_token, "access-123")
assert.strictEqual(stored?.refresh_token, "refresh-456")
assert.strictEqual(stored?.scope, "read write")
})
it("should calculate expires_in from stored expiresAt", async () => {
const provider = createProvider()
const futureTime = Math.floor(Date.now() / 1000) + 3600
await provider.saveTokens({
access_token: "access",
token_type: "Bearer",
expires_in: 3600,
})
const stored = await provider.tokens()
assert.ok(stored?.expires_in !== undefined)
assert.ok(stored!.expires_in! > 0)
assert.ok(stored!.expires_in! <= 3600)
})
it("should return undefined when URL doesn't match", async () => {
const provider = createProvider()
// Save tokens with different URL
saveAuthEntry(serverName, {
tokens: {
accessToken: "token",
},
serverUrl: "https://different.com",
}, "https://different.com")
const stored = await provider.tokens()
assert.strictEqual(stored, undefined)
})
})
describe("redirectToAuthorization", () => {
it("should call onRedirect with URL when a flow is in progress", async () => {
const provider = new McpOAuthProvider("redirect-with-state", serverUrl, {}, {
onRedirect: async (url) => {
redirectCaptured = url
},
})
await updateOAuthState("redirect-with-state", "state-abc", serverUrl)
const testUrl = new URL("https://example.com/auth")
await provider.redirectToAuthorization(testUrl)
assert.strictEqual(redirectCaptured, testUrl)
})
it("should throw UnauthorizedError when no flow is in progress", async () => {
const provider = new McpOAuthProvider("redirect-no-state", serverUrl, {}, {
onRedirect: async () => {},
})
await assert.rejects(
async () => provider.redirectToAuthorization(new URL("https://example.com/auth")),
(err: unknown) => err instanceof UnauthorizedError && /Re-authentication required/.test((err as Error).message),
)
})
it("should ignore OAuth state saved for a different server URL before redirecting", async () => {
let redirected = false
const provider = new McpOAuthProvider("redirect-url-bound", serverUrl, {}, {
onRedirect: async () => {
redirected = true
},
})
saveAuthEntry("redirect-url-bound", {
oauthState: "stale-state",
serverUrl: "https://different.example.com",
}, "https://different.example.com")
await assert.rejects(
async () => provider.redirectToAuthorization(new URL("https://example.com/auth")),
(err: unknown) => err instanceof UnauthorizedError && /Re-authentication required/.test((err as Error).message),
)
assert.strictEqual(redirected, false)
})
})
describe("codeVerifier / saveCodeVerifier", () => {
it("should save and retrieve code verifier", async () => {
const provider = new McpOAuthProvider("code-verifier-test", serverUrl, {}, {
onRedirect: async () => {},
})
await provider.saveCodeVerifier("verifier-abc-123")
const verifier = await provider.codeVerifier()
assert.strictEqual(verifier, "verifier-abc-123")
assert.strictEqual(getAuthForUrl("code-verifier-test", serverUrl)?.codeVerifier, "verifier-abc-123")
})
it("should throw when no code verifier", async () => {
const provider = new McpOAuthProvider("code-verifier-throw", serverUrl, {}, {
onRedirect: async () => {},
})
await assert.rejects(
async () => provider.codeVerifier(),
/No code verifier saved/
)
})
it("should ignore code verifiers saved for a different server URL", async () => {
const provider = new McpOAuthProvider("code-verifier-url-bound", serverUrl, {}, {
onRedirect: async () => {},
})
saveAuthEntry("code-verifier-url-bound", {
codeVerifier: "stale-verifier",
serverUrl: "https://different.example.com",
}, "https://different.example.com")
await assert.rejects(
async () => provider.codeVerifier(),
/No code verifier saved/
)
})
})
describe("state / saveState", () => {
it("should save and retrieve state", async () => {
const provider = new McpOAuthProvider("state-test-save", serverUrl, {}, {
onRedirect: async () => {},
})
await provider.saveState("state-xyz-789")
const state = await provider.state()
assert.strictEqual(state, "state-xyz-789")
assert.strictEqual(getAuthForUrl("state-test-save", serverUrl)?.oauthState, "state-xyz-789")
})
it("should throw UnauthorizedError when no state is saved", async () => {
const provider = new McpOAuthProvider("state-test-throw", serverUrl, {}, {
onRedirect: async () => {},
})
await assert.rejects(
async () => provider.state(),
(err: unknown) => err instanceof UnauthorizedError && /Re-authentication required/.test((err as Error).message),
)
})
it("should ignore OAuth state saved for a different server URL", async () => {
const provider = new McpOAuthProvider("state-url-bound", serverUrl, {}, {
onRedirect: async () => {},
})
saveAuthEntry("state-url-bound", {
oauthState: "stale-state",
serverUrl: "https://different.example.com",
}, "https://different.example.com")
await assert.rejects(
async () => provider.state(),
(err: unknown) => err instanceof UnauthorizedError && /Re-authentication required/.test((err as Error).message),
)
})
})
describe("invalidateCredentials", () => {
it("should remove all credentials when type is 'all'", async () => {
const provider = createProvider()
await provider.saveTokens({
access_token: "token",
token_type: "Bearer",
})
await provider.saveClientInformation({
client_id: "client",
client_secret: "secret",
redirect_uris: ["http://localhost/callback"],
})
await provider.invalidateCredentials("all")
assert.strictEqual(await provider.tokens(), undefined)
assert.strictEqual(await provider.clientInformation(), undefined)
})
it("should only remove tokens when type is 'tokens'", async () => {
const provider = createProvider()
const futureTime = Math.floor(Date.now() / 1000) + 3600
await provider.saveTokens({
access_token: "token",
token_type: "Bearer",
})
await provider.saveClientInformation({
client_id: "client",
client_secret: "secret",
redirect_uris: ["http://localhost/callback"],
client_id_issued_at: Math.floor(Date.now() / 1000),
client_secret_expires_at: futureTime,
})
await provider.invalidateCredentials("tokens")
assert.strictEqual(await provider.tokens(), undefined)
const clientInfo = await provider.clientInformation()
assert.strictEqual(clientInfo?.client_id, "client")
})
it("should only remove client info when type is 'client'", async () => {
const provider = createProvider()
const futureTime = Math.floor(Date.now() / 1000) + 3600
await provider.saveTokens({
access_token: "token",
token_type: "Bearer",
})
await provider.saveClientInformation({
client_id: "client",
client_secret: "secret",
redirect_uris: ["http://localhost/callback"],
client_id_issued_at: Math.floor(Date.now() / 1000),
client_secret_expires_at: futureTime,
})
await provider.invalidateCredentials("client")
const tokens = await provider.tokens()
assert.strictEqual(tokens?.access_token, "token")
assert.strictEqual(await provider.clientInformation(), undefined)
})
})
})