Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions apps/sim/app/api/mcp/oauth/callback/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ 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'
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,
Expand Down Expand Up @@ -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)
Expand Down
18 changes: 16 additions & 2 deletions apps/sim/app/api/mcp/oauth/callback/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -285,11 +286,24 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
const provider = new SimMcpOauthProvider({ row, preregistered })
let result: Awaited<ReturnType<typeof mcpAuthGuarded>>
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(
Expand Down
33 changes: 33 additions & 0 deletions apps/sim/app/api/mcp/oauth/start/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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'))

Expand Down
18 changes: 15 additions & 3 deletions apps/sim/app/api/mcp/oauth/start/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -173,16 +174,20 @@ 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 }) }
} catch (e) {
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,
Expand All @@ -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' })
}
Expand Down
11 changes: 11 additions & 0 deletions apps/sim/lib/mcp/domain-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
}

/**
* Core domain check. Returns null if the URL is allowed, or the hostname/url
* string to use in the rejection error.
Expand Down
Loading