diff --git a/apps/sim/app/api/mcp/oauth/callback/route.test.ts b/apps/sim/app/api/mcp/oauth/callback/route.test.ts index 28fdcff930f..f3f9a7c3a6c 100644 --- a/apps/sim/app/api/mcp/oauth/callback/route.test.ts +++ b/apps/sim/app/api/mcp/oauth/callback/route.test.ts @@ -8,6 +8,7 @@ import { resetDbChainMock, } from '@sim/testing' import { flushMicrotasks } from '@sim/testing/helpers/async' +import { createRouteContext } from '@sim/testing/helpers/http' import { emcnMock } from '@sim/testing/mocks/emcn.mock' import { getMockLogger } from '@sim/testing/mocks/logger.mock' import { mcpServiceMock, mcpServiceMockFns } from '@sim/testing/mocks/mcp-service.mock' @@ -15,6 +16,7 @@ import { NextRequest } from 'next/server' import { beforeEach, describe, expect, it, vi } from 'vitest' import { CredentialGroupOAuthStateVersionError } from '@/lib/credential-groups/oauth-attempt-version' import { connectCredentialGroupInPopup } from '@/lib/credential-groups/oauth-popup' +import { McpDnsResolutionError, McpSsrfError } from '@/lib/mcp/domain-check' const { mockAuthenticateEnrollment, @@ -181,6 +183,38 @@ describe('MCP OAuth callback route', () => { expect(body).toContain('serverId: undefined') }) + it('shows the egress refusal when the token endpoint is refused', async () => { + mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce( + new McpSsrfError('MCP server URL resolves to a private or reserved address (10.0.0.1).') + ) + + const body = await ( + await GET( + new NextRequest('http://localhost:3000/api/mcp/oauth/callback?state=state-1&code=code-1'), + createRouteContext({}) + ) + ).text() + + expect(body).toContain('ok: false') + expect(body).toContain('resolves to a private or reserved address (10.0.0.1).') + }) + + it('keeps the generic failure for a transient token exchange error', async () => { + mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce( + new McpDnsResolutionError('auth.example.com', false) + ) + + const body = await ( + await GET( + new NextRequest('http://localhost:3000/api/mcp/oauth/callback?state=state-1&code=code-1'), + createRouteContext({}) + ) + ).text() + + expect(body).toContain('ok: false') + expect(body).toContain('Token exchange failed. Please try again.') + }) + it('rate limits a managed callback before consuming its one-time state', async () => { const limitedResponse = new Response('rate limited', { status: 429 }) mockEnforceCallbackRateLimit.mockResolvedValueOnce(limitedResponse) diff --git a/apps/sim/app/api/mcp/oauth/callback/route.ts b/apps/sim/app/api/mcp/oauth/callback/route.ts index bd3ff0915ac..9a521e49585 100644 --- a/apps/sim/app/api/mcp/oauth/callback/route.ts +++ b/apps/sim/app/api/mcp/oauth/callback/route.ts @@ -20,6 +20,7 @@ import { CredentialGroupOAuthStateVersionError } from '@/lib/credential-groups/o import type { CredentialGroupOAuthFailure } from '@/lib/credential-groups/oauth-completion' import { CredentialGroupOAuthError } from '@/lib/credential-groups/provider-adapter' import { enforcePublicCredentialGroupIpRateLimit } from '@/lib/credential-groups/rate-limit' +import { isMcpUrlRefusal } from '@/lib/mcp/domain-check' import { assertSafeOauthServerUrl, clearState, @@ -285,11 +286,24 @@ export const GET = withRouteHandler(async (request: NextRequest) => { const provider = new SimMcpOauthProvider({ row, preregistered }) let result: Awaited> try { - result = await withResourceOutboundScope({ workspaceId: serverWorkspaceId }, () => + // An egress refusal of a URL the server named is the server's configuration, not a + // Sim fault: returned as a value so timedStep does not error-log it. + const outcome = await withResourceOutboundScope({ workspaceId: serverWorkspaceId }, () => timedStep('mcpAuthGuarded', 120_000, () => - mcpAuthGuarded(provider, { serverUrl, authorizationCode: code }) + mcpAuthGuarded(provider, { serverUrl, authorizationCode: code }).catch((e: unknown) => { + if (isMcpUrlRefusal(e)) return e + throw e + }) ) ) + if (isMcpUrlRefusal(outcome)) { + logger.warn('MCP OAuth token exchange URL refused by egress policy', { + serverId: server.id, + error: outcome.message, + }) + return respond(outcome.message, false, 'token_exchange_failed', server.id) + } + result = outcome } catch (e) { logger.error('Token exchange failed during MCP OAuth callback', e) return respond( diff --git a/apps/sim/app/api/mcp/oauth/start/route.test.ts b/apps/sim/app/api/mcp/oauth/start/route.test.ts index 1520a1741e6..a65c55b6f1d 100644 --- a/apps/sim/app/api/mcp/oauth/start/route.test.ts +++ b/apps/sim/app/api/mcp/oauth/start/route.test.ts @@ -12,6 +12,7 @@ import { import { createRouteContext } from '@sim/testing/helpers/http' import { NextRequest } from 'next/server' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { McpDnsResolutionError, McpSsrfError } from '@/lib/mcp/domain-check' vi.mock('@/lib/workspaces/permissions/utils', () => permissionsMock) vi.mock('@/lib/mcp/oauth', () => mcpOauthMock) @@ -236,6 +237,38 @@ describe('MCP OAuth start route: authorization-server refusals', () => { } ) + it.each([ + [ + 'a metadata-endpoint destination', + new McpSsrfError( + 'MCP server URL resolves to a cloud metadata endpoint (169.254.169.254), which is never reachable and cannot be allowlisted.' + ), + ], + [ + 'a non-public destination', + new McpSsrfError('MCP server URL must use https:// to a public destination.'), + ], + ['a hostname that does not exist', new McpDnsResolutionError('missing.example.com', true)], + ] as const)('answers 400 with the refusal for %s', async (_name, refusal) => { + mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce(refusal) + + const response = await start() + + expect(response.status).toBe(400) + expect((await response.json()).error).toBe(refusal.message) + }) + + it('keeps a 500 for a transient DNS failure', async () => { + mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce( + new McpDnsResolutionError('mcp.example.com', false) + ) + + const response = await start() + + expect(response.status).toBe(500) + expect((await response.json()).error).toBe('Failed to start OAuth flow') + }) + it('keeps a 500 for a failure that is not an authorization-server answer', async () => { mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValueOnce(new Error('decrypt failed')) diff --git a/apps/sim/app/api/mcp/oauth/start/route.ts b/apps/sim/app/api/mcp/oauth/start/route.ts index 0bcbf06ef49..4d0fd73bc37 100644 --- a/apps/sim/app/api/mcp/oauth/start/route.ts +++ b/apps/sim/app/api/mcp/oauth/start/route.ts @@ -10,6 +10,7 @@ import { NextResponse } from 'next/server' import { startMcpOauthContract } from '@/lib/api/contracts/mcp' import { parseRequest } from '@/lib/api/server' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' +import { isMcpUrlRefusal } from '@/lib/mcp/domain-check' import { withMcpAuth } from '@/lib/mcp/middleware' import { assertSafeOauthServerUrl, @@ -173,9 +174,10 @@ export const GET = withRouteHandler( // OAuth discovery + DCR through the guarded fetch, bounded so a transient stall fails // fast with a labeled log instead of hanging the popup. `McpOauthRedirectRequired` is // the SUCCESS signal (a throw carrying the authorize URL), and an authorization-server - // refusal is an expected outcome rather than a Sim fault, so both are caught INSIDE the - // bounded step and returned as values — otherwise timedStep would error-log them. Only - // a real error or a timeout escapes as a throw. + // refusal or an egress refusal of a URL the server named is an expected outcome rather + // than a Sim fault, so all are caught INSIDE the bounded step and returned as values — + // otherwise timedStep would error-log them. Only a real error or a timeout escapes as a + // throw. const authOutcome = await timedStep('mcpAuthGuarded', MCP_AUTH_STEP_MS, async () => { try { return { kind: 'result' as const, value: await mcpAuthGuarded(provider, { serverUrl }) } @@ -183,6 +185,9 @@ export const GET = withRouteHandler( if (e instanceof McpOauthRedirectRequired) { return { kind: 'redirect' as const, authorizationUrl: e.authorizationUrl } } + if (isMcpUrlRefusal(e)) { + return { kind: 'refused' as const, error: e } + } if (isDynamicClientRegistrationUnsupported(e)) { return { kind: 'rejected' as const, @@ -209,6 +214,13 @@ export const GET = withRouteHandler( }) return createMcpErrorResponse(authOutcome.error, authOutcome.message, 422) } + if (authOutcome.kind === 'refused') { + logger.warn('MCP OAuth URL refused by egress policy', { + serverId, + error: authOutcome.error.message, + }) + return createMcpErrorResponse(authOutcome.error, authOutcome.error.message, 400) + } if (authOutcome.value === 'AUTHORIZED') { return NextResponse.json({ status: 'already_authorized' }) } diff --git a/apps/sim/lib/mcp/domain-check.ts b/apps/sim/lib/mcp/domain-check.ts index 6499dd0ed7c..528c993ec6f 100644 --- a/apps/sim/lib/mcp/domain-check.ts +++ b/apps/sim/lib/mcp/domain-check.ts @@ -54,6 +54,17 @@ export class McpDnsResolutionError extends Error { } } +/** + * True when an MCP URL was refused because of what the caller supplied: the egress policy + * refused the destination, or its hostname provably does not exist. A transient DNS failure + * is not one, so it stays a server fault. + */ +export function isMcpUrlRefusal(error: unknown): error is McpSsrfError | McpDnsResolutionError { + return ( + error instanceof McpSsrfError || (error instanceof McpDnsResolutionError && error.hostNotFound) + ) +} + /** * Core domain check. Returns null if the URL is allowed, or the hostname/url * string to use in the rejection error.