Skip to content

Commit 3ba16d1

Browse files
authored
fix(mcp): answer 400 when MCP OAuth URL is refused by egress policy (#10492)
* fix(mcp): answer 400 when MCP OAuth URL is refused by egress policy * fix(mcp): pass route context in callback refusal tests
1 parent 2d2e434 commit 3ba16d1

5 files changed

Lines changed: 109 additions & 5 deletions

File tree

‎apps/sim/app/api/mcp/oauth/callback/route.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@ import {
88
resetDbChainMock,
99
} from '@sim/testing'
1010
import { flushMicrotasks } from '@sim/testing/helpers/async'
11+
import { createRouteContext } from '@sim/testing/helpers/http'
1112
import { emcnMock } from '@sim/testing/mocks/emcn.mock'
1213
import { getMockLogger } from '@sim/testing/mocks/logger.mock'
1314
import { mcpServiceMock, mcpServiceMockFns } from '@sim/testing/mocks/mcp-service.mock'
1415
import { NextRequest } from 'next/server'
1516
import { beforeEach, describe, expect, it, vi } from 'vitest'
1617
import { CredentialGroupOAuthStateVersionError } from '@/lib/credential-groups/oauth-attempt-version'
1718
import { connectCredentialGroupInPopup } from '@/lib/credential-groups/oauth-popup'
19+
import { McpDnsResolutionError, McpSsrfError } from '@/lib/mcp/domain-check'
1820

1921
const {
2022
mockAuthenticateEnrollment,
@@ -181,6 +183,38 @@ describe('MCP OAuth callback route', () => {
181183
expect(body).toContain('serverId: undefined')
182184
})
183185

186+
it('shows the egress refusal when the token endpoint is refused', async () => {
187+
mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce(
188+
new McpSsrfError('MCP server URL resolves to a private or reserved address (10.0.0.1).')
189+
)
190+
191+
const body = await (
192+
await GET(
193+
new NextRequest('http://localhost:3000/api/mcp/oauth/callback?state=state-1&code=code-1'),
194+
createRouteContext({})
195+
)
196+
).text()
197+
198+
expect(body).toContain('ok: false')
199+
expect(body).toContain('resolves to a private or reserved address (10.0.0.1).')
200+
})
201+
202+
it('keeps the generic failure for a transient token exchange error', async () => {
203+
mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce(
204+
new McpDnsResolutionError('auth.example.com', false)
205+
)
206+
207+
const body = await (
208+
await GET(
209+
new NextRequest('http://localhost:3000/api/mcp/oauth/callback?state=state-1&code=code-1'),
210+
createRouteContext({})
211+
)
212+
).text()
213+
214+
expect(body).toContain('ok: false')
215+
expect(body).toContain('Token exchange failed. Please try again.')
216+
})
217+
184218
it('rate limits a managed callback before consuming its one-time state', async () => {
185219
const limitedResponse = new Response('rate limited', { status: 429 })
186220
mockEnforceCallbackRateLimit.mockResolvedValueOnce(limitedResponse)

‎apps/sim/app/api/mcp/oauth/callback/route.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { CredentialGroupOAuthStateVersionError } from '@/lib/credential-groups/o
2020
import type { CredentialGroupOAuthFailure } from '@/lib/credential-groups/oauth-completion'
2121
import { CredentialGroupOAuthError } from '@/lib/credential-groups/provider-adapter'
2222
import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit'
23+
import { isMcpUrlRefusal } from '@/lib/mcp/domain-check'
2324
import {
2425
assertSafeOauthServerUrl,
2526
clearState,
@@ -285,11 +286,24 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
285286
const provider = new SimMcpOauthProvider({ row, preregistered })
286287
let result: Awaited<ReturnType<typeof mcpAuthGuarded>>
287288
try {
288-
result = await withResourceOutboundScope({ workspaceId: serverWorkspaceId }, () =>
289+
// An egress refusal of a URL the server named is the server's configuration, not a
290+
// Sim fault: returned as a value so timedStep does not error-log it.
291+
const outcome = await withResourceOutboundScope({ workspaceId: serverWorkspaceId }, () =>
289292
timedStep('mcpAuthGuarded', 120_000, () =>
290-
mcpAuthGuarded(provider, { serverUrl, authorizationCode: code })
293+
mcpAuthGuarded(provider, { serverUrl, authorizationCode: code }).catch((e: unknown) => {
294+
if (isMcpUrlRefusal(e)) return e
295+
throw e
296+
})
291297
)
292298
)
299+
if (isMcpUrlRefusal(outcome)) {
300+
logger.warn('MCP OAuth token exchange URL refused by egress policy', {
301+
serverId: server.id,
302+
error: outcome.message,
303+
})
304+
return respond(outcome.message, false, 'token_exchange_failed', server.id)
305+
}
306+
result = outcome
293307
} catch (e) {
294308
logger.error('Token exchange failed during MCP OAuth callback', e)
295309
return respond(

‎apps/sim/app/api/mcp/oauth/start/route.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
import { createRouteContext } from '@sim/testing/helpers/http'
1313
import { NextRequest } from 'next/server'
1414
import { beforeEach, describe, expect, it, vi } from 'vitest'
15+
import { McpDnsResolutionError, McpSsrfError } from '@/lib/mcp/domain-check'
1516

1617
vi.mock('@/lib/workspaces/permissions/utils', () => permissionsMock)
1718
vi.mock('@/lib/mcp/oauth', () => mcpOauthMock)
@@ -236,6 +237,38 @@ describe('MCP OAuth start route: authorization-server refusals', () => {
236237
}
237238
)
238239

240+
it.each([
241+
[
242+
'a metadata-endpoint destination',
243+
new McpSsrfError(
244+
'MCP server URL resolves to a cloud metadata endpoint (169.254.169.254), which is never reachable and cannot be allowlisted.'
245+
),
246+
],
247+
[
248+
'a non-public destination',
249+
new McpSsrfError('MCP server URL must use https:// to a public destination.'),
250+
],
251+
['a hostname that does not exist', new McpDnsResolutionError('missing.example.com', true)],
252+
] as const)('answers 400 with the refusal for %s', async (_name, refusal) => {
253+
mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce(refusal)
254+
255+
const response = await start()
256+
257+
expect(response.status).toBe(400)
258+
expect((await response.json()).error).toBe(refusal.message)
259+
})
260+
261+
it('keeps a 500 for a transient DNS failure', async () => {
262+
mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce(
263+
new McpDnsResolutionError('mcp.example.com', false)
264+
)
265+
266+
const response = await start()
267+
268+
expect(response.status).toBe(500)
269+
expect((await response.json()).error).toBe('Failed to start OAuth flow')
270+
})
271+
239272
it('keeps a 500 for a failure that is not an authorization-server answer', async () => {
240273
mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce(new Error('decrypt failed'))
241274

‎apps/sim/app/api/mcp/oauth/start/route.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { NextResponse } from 'next/server'
1010
import { startMcpOauthContract } from '@/lib/api/contracts/mcp'
1111
import { parseRequest } from '@/lib/api/server'
1212
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
13+
import { isMcpUrlRefusal } from '@/lib/mcp/domain-check'
1314
import { withMcpAuth } from '@/lib/mcp/middleware'
1415
import {
1516
assertSafeOauthServerUrl,
@@ -173,16 +174,20 @@ export const GET = withRouteHandler(
173174
// OAuth discovery + DCR through the guarded fetch, bounded so a transient stall fails
174175
// fast with a labeled log instead of hanging the popup. `McpOauthRedirectRequired` is
175176
// the SUCCESS signal (a throw carrying the authorize URL), and an authorization-server
176-
// refusal is an expected outcome rather than a Sim fault, so both are caught INSIDE the
177-
// bounded step and returned as values — otherwise timedStep would error-log them. Only
178-
// a real error or a timeout escapes as a throw.
177+
// refusal or an egress refusal of a URL the server named is an expected outcome rather
178+
// than a Sim fault, so all are caught INSIDE the bounded step and returned as values —
179+
// otherwise timedStep would error-log them. Only a real error or a timeout escapes as a
180+
// throw.
179181
const authOutcome = await timedStep('mcpAuthGuarded', MCP_AUTH_STEP_MS, async () => {
180182
try {
181183
return { kind: 'result' as const, value: await mcpAuthGuarded(provider, { serverUrl }) }
182184
} catch (e) {
183185
if (e instanceof McpOauthRedirectRequired) {
184186
return { kind: 'redirect' as const, authorizationUrl: e.authorizationUrl }
185187
}
188+
if (isMcpUrlRefusal(e)) {
189+
return { kind: 'refused' as const, error: e }
190+
}
186191
if (isDynamicClientRegistrationUnsupported(e)) {
187192
return {
188193
kind: 'rejected' as const,
@@ -209,6 +214,13 @@ export const GET = withRouteHandler(
209214
})
210215
return createMcpErrorResponse(authOutcome.error, authOutcome.message, 422)
211216
}
217+
if (authOutcome.kind === 'refused') {
218+
logger.warn('MCP OAuth URL refused by egress policy', {
219+
serverId,
220+
error: authOutcome.error.message,
221+
})
222+
return createMcpErrorResponse(authOutcome.error, authOutcome.error.message, 400)
223+
}
212224
if (authOutcome.value === 'AUTHORIZED') {
213225
return NextResponse.json({ status: 'already_authorized' })
214226
}

‎apps/sim/lib/mcp/domain-check.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,17 @@ export class McpDnsResolutionError extends Error {
5454
}
5555
}
5656

57+
/**
58+
* True when an MCP URL was refused because of what the caller supplied: the egress policy
59+
* refused the destination, or its hostname provably does not exist. A transient DNS failure
60+
* is not one, so it stays a server fault.
61+
*/
62+
export function isMcpUrlRefusal(error: unknown): error is McpSsrfError | McpDnsResolutionError {
63+
return (
64+
error instanceof McpSsrfError || (error instanceof McpDnsResolutionError && error.hostNotFound)
65+
)
66+
}
67+
5768
/**
5869
* Core domain check. Returns null if the URL is allowed, or the hostname/url
5970
* string to use in the rejection error.

0 commit comments

Comments
 (0)