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
30 changes: 28 additions & 2 deletions apps/sim/app/api/mcp/servers/test-connection/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,11 @@ vi.mock('@/lib/mcp/client', () => ({
},
}))

vi.mock('@/lib/mcp/domain-check', () => ({
vi.mock('@/lib/mcp/domain-check', async (importOriginal) => ({
MCP_EGRESS_PROFILE: 'selfHostedService',
OAUTH_EGRESS_PROFILE: 'contentFetch',
McpDnsResolutionError: class extends Error {},
McpDnsResolutionError: (await importOriginal<typeof import('@/lib/mcp/domain-check')>())
.McpDnsResolutionError,
McpDomainNotAllowedError: class extends Error {},
McpSsrfError: MockMcpSsrfError,
validateMcpDomain: vi.fn(),
Expand Down Expand Up @@ -80,6 +81,7 @@ vi.mock('@/lib/mcp/resolve-config', () => ({
resolveMcpConfigEnvVars: mockResolveMcpConfigEnvVars,
}))

import { McpDnsResolutionError } from '@/lib/mcp/domain-check'
import { POST } from '@/app/api/mcp/servers/test-connection/route'

const { mockDetectMcpAuthType } = mcpOauthMockFns
Expand Down Expand Up @@ -114,6 +116,30 @@ describe('MCP server test-connection route', () => {
mockDisconnect.mockResolvedValue(undefined)
})

it.each([
['before', true, 400],
['before', false, 502],
['after', true, 400],
['after', false, 502],
])(
'answers a DNS failure %s env resolution with hostNotFound=%s as %i',
async (phase, hostNotFound, status) => {
if (phase === 'after') mockValidateMcpServerSsrf.mockResolvedValueOnce('203.0.113.10')
mockValidateMcpServerSsrf.mockRejectedValueOnce(
new McpDnsResolutionError('example.invalid', hostNotFound)
)

const response = await POST(createTestRequest())

expect(response.status).toBe(status)
expect(await response.json()).toEqual({
success: false,
error: 'MCP server URL hostname "example.invalid" could not be resolved',
})
expect(mockValidateMcpServerSsrf).toHaveBeenCalledTimes(phase === 'after' ? 2 : 1)
}
)

it('tests configured bearer headers before treating OAuth discovery as mandatory', async () => {
const response = await POST(createTestRequest({ Authorization: 'Bearer static-api-token' }))
const body = await response.json()
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/app/api/mcp/servers/test-connection/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ export const POST = withRouteHandler(
await validateMcpServerSsrf(body.url)
} catch (e) {
if (e instanceof McpDnsResolutionError) {
return createMcpErrorResponse(e, e.message, 502)
return createMcpErrorResponse(e, e.message, e.hostNotFound ? 400 : 502)
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
}
if (e instanceof McpSsrfError) {
return createMcpErrorResponse(e, e.message, 403)
Expand Down Expand Up @@ -177,7 +177,7 @@ export const POST = withRouteHandler(
resolvedIP = await validateMcpServerSsrf(testConfig.url)
} catch (e) {
if (e instanceof McpDnsResolutionError) {
return createMcpErrorResponse(e, e.message, 502)
return createMcpErrorResponse(e, e.message, e.hostNotFound ? 400 : 502)
}
if (e instanceof McpSsrfError) {
return createMcpErrorResponse(e, e.message, 403)
Expand Down
13 changes: 13 additions & 0 deletions apps/sim/lib/mcp/domain-check.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ vi.mock('@/executor/utils/reference-validation', () => ({
import {
isMcpDomainAllowed,
MCP_EGRESS_PROFILE,
McpDnsResolutionError,
McpDomainNotAllowedError,
McpSsrfError,
OAUTH_EGRESS_PROFILE,
Expand Down Expand Up @@ -148,6 +149,18 @@ describe('validateMcpServerSsrf', () => {
)
})

it.each([
['ENOTFOUND', true],
['EAI_AGAIN', false],
])('classifies a %s lookup failure as hostNotFound=%s', async (code, hostNotFound) => {
mockDnsLookup.mockRejectedValue(
Object.assign(new Error(`getaddrinfo ${code} example.invalid`), { code })
)
const validation = validateMcpServerSsrf('https://example.invalid/mcp')
await expect(validation).rejects.toBeInstanceOf(McpDnsResolutionError)
await expect(validation).rejects.toMatchObject({ hostNotFound })
})

it('throws McpSsrfError for cloud metadata IP literal', async () => {
await expect(validateMcpServerSsrf('http://169.254.169.254/latest/meta-data/')).rejects.toThrow(
McpSsrfError
Expand Down
13 changes: 11 additions & 2 deletions apps/sim/lib/mcp/domain-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createLogger } from '@sim/logger'
import { getAllowedMcpDomainsFromEnv } from '@/lib/core/config/env-flags'
import type { EgressProfile } from '@/lib/core/security/egress/profiles'
import { validateUrlWithDNS } from '@/lib/core/security/input-validation.server'
import { isHostNotFound } from '@/lib/credentials/token-service-accounts/errors'
import { createEnvVarPattern } from '@/executor/utils/reference-validation'

const logger = createLogger('McpDomainCheck')
Expand Down Expand Up @@ -38,8 +39,16 @@ export class McpSsrfError extends Error {
}
}

/**
* The MCP server hostname did not resolve. `hostNotFound` is true only when the
* resolver proved the name doesn't exist (`ENOTFOUND`), which is the caller's input;
* a transient lookup failure (`EAI_AGAIN`, timeout) leaves it false.
*/
export class McpDnsResolutionError extends Error {
constructor(hostname: string) {
constructor(
hostname: string,
readonly hostNotFound = false
) {
super(`MCP server URL hostname "${hostname}" could not be resolved`)
this.name = 'McpDnsResolutionError'
}
Expand Down Expand Up @@ -154,7 +163,7 @@ export async function validateMcpServerSsrf(
// Fall back to the raw URL in the message.
}
logger.warn('DNS lookup failed for MCP server URL', { hostname })
throw new McpDnsResolutionError(hostname)
throw new McpDnsResolutionError(hostname, isHostNotFound(validation.cause))
}
logger.warn('MCP server URL refused by egress policy', { error })
throw new McpSsrfError(error)
Expand Down
Loading