chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import {
|
||||
authMockFns,
|
||||
dbChainMock,
|
||||
dbChainMockFns,
|
||||
mcpOauthMock,
|
||||
mcpOauthMockFns,
|
||||
resetDbChainMock,
|
||||
schemaMock,
|
||||
} from '@sim/testing'
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockDiscoverServerTools } = vi.hoisted(() => ({
|
||||
mockDiscoverServerTools: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@sim/db', () => dbChainMock)
|
||||
vi.mock('@sim/db/schema', () => schemaMock)
|
||||
vi.mock('drizzle-orm', () => ({
|
||||
and: vi.fn(),
|
||||
eq: vi.fn(),
|
||||
isNull: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/mcp/oauth', () => mcpOauthMock)
|
||||
vi.mock('@/lib/mcp/service', () => ({
|
||||
mcpService: { discoverServerTools: mockDiscoverServerTools },
|
||||
}))
|
||||
|
||||
import { GET } from './route'
|
||||
|
||||
describe('MCP OAuth callback route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetDbChainMock()
|
||||
authMockFns.mockGetSession.mockResolvedValue({ user: { id: 'user-1' } })
|
||||
mcpOauthMockFns.mockLoadOauthRowByState.mockResolvedValue({
|
||||
id: 'oauth-row-1',
|
||||
mcpServerId: 'server-1',
|
||||
userId: 'user-1',
|
||||
workspaceId: 'workspace-1',
|
||||
})
|
||||
dbChainMockFns.limit.mockResolvedValue([
|
||||
{
|
||||
id: 'server-1',
|
||||
url: 'https://mcp.example.com/mcp',
|
||||
workspaceId: 'workspace-1',
|
||||
},
|
||||
])
|
||||
mcpOauthMockFns.mockLoadPreregisteredClient.mockResolvedValue(undefined)
|
||||
mcpOauthMockFns.mockMcpAuthGuarded.mockResolvedValue('AUTHORIZED')
|
||||
mockDiscoverServerTools.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('performs the token exchange through the SSRF-guarded mcpAuthGuarded wrapper', async () => {
|
||||
const request = new NextRequest(
|
||||
'http://localhost:3000/api/mcp/oauth/callback?state=state-1&code=auth-code-1'
|
||||
)
|
||||
|
||||
await GET(request)
|
||||
|
||||
// The route must call the guarded wrapper (which defaults fetchFn to the
|
||||
// SSRF-guarded fetch internally) rather than the raw SDK `auth()` — see
|
||||
// apps/sim/lib/mcp/oauth/auth.test.ts for the wrapper's own fetchFn coverage.
|
||||
expect(mcpOauthMockFns.mockMcpAuthGuarded).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
serverUrl: 'https://mcp.example.com/mcp',
|
||||
authorizationCode: 'auth-code-1',
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
import { db } from '@sim/db'
|
||||
import { mcpServers } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { and, eq, isNull } from 'drizzle-orm'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { mcpOauthCallbackContract } from '@/lib/api/contracts/mcp'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import {
|
||||
assertSafeOauthServerUrl,
|
||||
clearState,
|
||||
clearVerifier,
|
||||
loadOauthRowByState,
|
||||
loadPreregisteredClient,
|
||||
type McpOauthCallbackReason,
|
||||
mcpAuthGuarded,
|
||||
SimMcpOauthProvider,
|
||||
} from '@/lib/mcp/oauth'
|
||||
import { mcpService } from '@/lib/mcp/service'
|
||||
|
||||
const logger = createLogger('McpOauthCallbackAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
function jsonLiteral(value: string | undefined): string {
|
||||
if (value === undefined) return 'undefined'
|
||||
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e')
|
||||
}
|
||||
|
||||
function htmlClose(
|
||||
message: string,
|
||||
ok: boolean,
|
||||
reason: McpOauthCallbackReason,
|
||||
serverId?: string
|
||||
): NextResponse {
|
||||
const safeMessage = escapeHtml(message)
|
||||
const title = ok ? 'Connected' : 'Connection failed'
|
||||
const body = `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body style="font-family: system-ui; padding: 24px"><p>${safeMessage}</p><script>
|
||||
try { window.opener && window.opener.postMessage({ type: 'mcp-oauth', ok: ${ok ? 'true' : 'false'}, serverId: ${jsonLiteral(serverId)}, reason: ${jsonLiteral(reason)} }, window.location.origin) } catch (e) {}
|
||||
setTimeout(function () { window.close() }, 800)
|
||||
</script></body></html>`
|
||||
return new NextResponse(body, {
|
||||
headers: { 'Content-Type': 'text/html; charset=utf-8' },
|
||||
})
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(async (request: NextRequest) => {
|
||||
const parsed = await parseRequest(mcpOauthCallbackContract, request, {})
|
||||
if (!parsed.success) {
|
||||
return htmlClose('Malformed authorization callback.', false, 'missing_params')
|
||||
}
|
||||
const { state, code, error: errorParam } = parsed.data.query
|
||||
|
||||
const initialRow = state ? await loadOauthRowByState(state).catch(() => null) : null
|
||||
const stateRowServerId = initialRow?.mcpServerId
|
||||
|
||||
if (errorParam) {
|
||||
logger.warn(`MCP OAuth callback received error: ${errorParam}`)
|
||||
if (initialRow) await clearState(initialRow.id).catch(() => {})
|
||||
return htmlClose(
|
||||
`Authorization failed: ${errorParam}`,
|
||||
false,
|
||||
'provider_error',
|
||||
stateRowServerId
|
||||
)
|
||||
}
|
||||
if (!state || !code) {
|
||||
return htmlClose(
|
||||
'Missing state or code in callback URL.',
|
||||
false,
|
||||
'missing_params',
|
||||
stateRowServerId
|
||||
)
|
||||
}
|
||||
|
||||
let serverId: string | undefined
|
||||
try {
|
||||
const session = await getSession()
|
||||
if (!session?.user?.id) {
|
||||
return htmlClose(
|
||||
'You must be signed in to complete authorization.',
|
||||
false,
|
||||
'unauthenticated',
|
||||
stateRowServerId
|
||||
)
|
||||
}
|
||||
|
||||
const row = initialRow
|
||||
if (!row) {
|
||||
return htmlClose('Invalid or expired authorization state.', false, 'invalid_state')
|
||||
}
|
||||
serverId = row.mcpServerId
|
||||
|
||||
if (session.user.id !== row.userId) {
|
||||
return htmlClose(
|
||||
'You must be signed in as the same user that initiated the flow.',
|
||||
false,
|
||||
'user_mismatch',
|
||||
serverId
|
||||
)
|
||||
}
|
||||
|
||||
const [server] = await db
|
||||
.select({ id: mcpServers.id, url: mcpServers.url, workspaceId: mcpServers.workspaceId })
|
||||
.from(mcpServers)
|
||||
.where(and(eq(mcpServers.id, row.mcpServerId), isNull(mcpServers.deletedAt)))
|
||||
.limit(1)
|
||||
if (!server || !server.url) {
|
||||
return htmlClose('Server no longer exists.', false, 'server_gone', serverId)
|
||||
}
|
||||
if (server.workspaceId !== row.workspaceId) {
|
||||
return htmlClose(
|
||||
'Workspace mismatch on authorization callback.',
|
||||
false,
|
||||
'invalid_state',
|
||||
serverId
|
||||
)
|
||||
}
|
||||
try {
|
||||
assertSafeOauthServerUrl(server.url)
|
||||
} catch {
|
||||
return htmlClose(
|
||||
'MCP OAuth requires https (or http://localhost for development).',
|
||||
false,
|
||||
'insecure_url',
|
||||
serverId
|
||||
)
|
||||
}
|
||||
|
||||
// Burn state before token exchange so a replayed callback cannot reuse it.
|
||||
await clearState(row.id)
|
||||
|
||||
const preregistered = await loadPreregisteredClient(server.id)
|
||||
const provider = new SimMcpOauthProvider({ row, preregistered })
|
||||
let result: Awaited<ReturnType<typeof mcpAuthGuarded>>
|
||||
try {
|
||||
result = await mcpAuthGuarded(provider, {
|
||||
serverUrl: server.url,
|
||||
authorizationCode: code,
|
||||
})
|
||||
} catch (e) {
|
||||
logger.error('Token exchange failed during MCP OAuth callback', e)
|
||||
return htmlClose(
|
||||
'Token exchange failed. Please try again.',
|
||||
false,
|
||||
'token_exchange_failed',
|
||||
server.id
|
||||
)
|
||||
} finally {
|
||||
await clearVerifier(row.id)
|
||||
}
|
||||
|
||||
if (result !== 'AUTHORIZED') {
|
||||
return htmlClose('Authorization did not complete.', false, 'token_exchange_failed', server.id)
|
||||
}
|
||||
|
||||
try {
|
||||
// forceRefresh: skip any stale cache from before re-auth.
|
||||
await mcpService.discoverServerTools(session.user.id, server.id, server.workspaceId, true)
|
||||
} catch (e) {
|
||||
logger.warn('Post-auth tools refresh failed', toError(e).message)
|
||||
}
|
||||
|
||||
return htmlClose('Connected. You can close this window.', true, 'authorized', server.id)
|
||||
} catch (error) {
|
||||
logger.error('MCP OAuth callback failed', error)
|
||||
return htmlClose('Authorization failed. Please try again.', false, 'unknown', serverId)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import {
|
||||
dbChainMock,
|
||||
dbChainMockFns,
|
||||
hybridAuthMock,
|
||||
hybridAuthMockFns,
|
||||
McpOauthRedirectRequiredMock,
|
||||
mcpOauthMock,
|
||||
mcpOauthMockFns,
|
||||
permissionsMock,
|
||||
permissionsMockFns,
|
||||
resetDbChainMock,
|
||||
schemaMock,
|
||||
} from '@sim/testing'
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('@sim/db', () => dbChainMock)
|
||||
vi.mock('@sim/db/schema', () => schemaMock)
|
||||
vi.mock('drizzle-orm', () => ({
|
||||
and: vi.fn(),
|
||||
eq: vi.fn(),
|
||||
isNull: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/auth/hybrid', () => hybridAuthMock)
|
||||
vi.mock('@/lib/workspaces/permissions/utils', () => permissionsMock)
|
||||
vi.mock('@/lib/mcp/oauth', () => mcpOauthMock)
|
||||
|
||||
import { GET, surfaceOauthError } from './route'
|
||||
|
||||
describe('MCP OAuth start route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetDbChainMock()
|
||||
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValue({
|
||||
success: true,
|
||||
userId: 'user-2',
|
||||
userName: 'User Two',
|
||||
userEmail: 'user2@example.com',
|
||||
authType: 'session',
|
||||
})
|
||||
permissionsMockFns.mockGetUserEntityPermissions.mockResolvedValue('write')
|
||||
dbChainMockFns.limit.mockResolvedValue([
|
||||
{
|
||||
id: 'server-1',
|
||||
name: 'Exa',
|
||||
url: 'https://mcp.exa.ai/mcp',
|
||||
workspaceId: 'workspace-1',
|
||||
authType: 'oauth',
|
||||
deletedAt: null,
|
||||
},
|
||||
])
|
||||
mcpOauthMockFns.mockGetOrCreateOauthRow.mockResolvedValue({
|
||||
id: 'oauth-row-1',
|
||||
mcpServerId: 'server-1',
|
||||
userId: 'user-1',
|
||||
workspaceId: 'workspace-1',
|
||||
clientInformation: null,
|
||||
tokens: null,
|
||||
codeVerifier: null,
|
||||
state: null,
|
||||
stateCreatedAt: null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
mcpOauthMockFns.mockLoadPreregisteredClient.mockResolvedValue(undefined)
|
||||
mcpOauthMockFns.mockMcpAuthGuarded.mockRejectedValue(
|
||||
new McpOauthRedirectRequiredMock('https://mcp.exa.ai/authorize')
|
||||
)
|
||||
})
|
||||
|
||||
it('routes OAuth discovery through the SSRF-guarded mcpAuthGuarded wrapper', async () => {
|
||||
const request = new NextRequest(
|
||||
'http://localhost:3000/api/mcp/oauth/start?workspaceId=workspace-1&serverId=server-1'
|
||||
)
|
||||
|
||||
await GET(request)
|
||||
|
||||
// The route must call the guarded wrapper (which defaults fetchFn to the
|
||||
// SSRF-guarded fetch internally) rather than the raw SDK `auth()` — see
|
||||
// apps/sim/lib/mcp/oauth/auth.test.ts for the wrapper's own fetchFn coverage.
|
||||
expect(mcpOauthMockFns.mockMcpAuthGuarded).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ serverUrl: 'https://mcp.exa.ai/mcp' })
|
||||
)
|
||||
})
|
||||
|
||||
it('requires workspace write permission via MCP auth middleware', async () => {
|
||||
const request = new NextRequest(
|
||||
'http://localhost:3000/api/mcp/oauth/start?workspaceId=workspace-1&serverId=server-1'
|
||||
)
|
||||
|
||||
await GET(request)
|
||||
|
||||
expect(permissionsMockFns.mockGetUserEntityPermissions).toHaveBeenCalledWith(
|
||||
'user-2',
|
||||
'workspace',
|
||||
'workspace-1'
|
||||
)
|
||||
})
|
||||
|
||||
it('uses a workspace-scoped OAuth row and stamps the latest authorizing user', async () => {
|
||||
const request = new NextRequest(
|
||||
'http://localhost:3000/api/mcp/oauth/start?workspaceId=workspace-1&serverId=server-1'
|
||||
)
|
||||
|
||||
const response = await GET(request)
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toEqual({
|
||||
status: 'redirect',
|
||||
authorizationUrl: 'https://mcp.exa.ai/authorize',
|
||||
})
|
||||
expect(mcpOauthMockFns.mockGetOrCreateOauthRow).toHaveBeenCalledWith({
|
||||
mcpServerId: 'server-1',
|
||||
userId: 'user-2',
|
||||
workspaceId: 'workspace-1',
|
||||
})
|
||||
expect(mcpOauthMockFns.mockSetOauthRowUser).toHaveBeenCalledWith('oauth-row-1', 'user-2')
|
||||
})
|
||||
|
||||
it('rejects a second user starting OAuth while another authorization is active', async () => {
|
||||
mcpOauthMockFns.mockGetOrCreateOauthRow.mockResolvedValueOnce({
|
||||
id: 'oauth-row-1',
|
||||
mcpServerId: 'server-1',
|
||||
userId: 'user-1',
|
||||
workspaceId: 'workspace-1',
|
||||
clientInformation: null,
|
||||
tokens: null,
|
||||
codeVerifier: null,
|
||||
state: 'hashed-active-state',
|
||||
stateCreatedAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
const request = new NextRequest(
|
||||
'http://localhost:3000/api/mcp/oauth/start?workspaceId=workspace-1&serverId=server-1'
|
||||
)
|
||||
|
||||
const response = await GET(request)
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(409)
|
||||
expect(body.error).toBe('OAuth authorization already in progress for this server')
|
||||
expect(mcpOauthMockFns.mockMcpAuthGuarded).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not leak non-OAuth internal error details to the client', async () => {
|
||||
mcpOauthMockFns.mockGetOrCreateOauthRow.mockRejectedValueOnce(
|
||||
new Error('connect ECONNREFUSED 10.0.0.5:5432 (internal-db-host)')
|
||||
)
|
||||
const request = new NextRequest(
|
||||
'http://localhost:3000/api/mcp/oauth/start?workspaceId=workspace-1&serverId=server-1'
|
||||
)
|
||||
|
||||
const response = await GET(request)
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body.error).toBe('Failed to start OAuth flow')
|
||||
expect(body.error).not.toContain('ECONNREFUSED')
|
||||
expect(body.error).not.toContain('internal-db-host')
|
||||
})
|
||||
})
|
||||
|
||||
describe('surfaceOauthError', () => {
|
||||
it('uses typed OAuthError errorCode and message for spec-compliant errors', async () => {
|
||||
const { InvalidGrantError } = await import('@modelcontextprotocol/sdk/server/auth/errors.js')
|
||||
const err = new InvalidGrantError('Refresh token expired')
|
||||
expect(surfaceOauthError(err)).toBe('invalid_grant: Refresh token expired')
|
||||
})
|
||||
|
||||
it('parses Raw body envelope for ServerError fallbacks (non-spec vendors)', async () => {
|
||||
const { ServerError } = await import('@modelcontextprotocol/sdk/server/auth/errors.js')
|
||||
const err = new ServerError(
|
||||
'HTTP 400: Invalid OAuth error response: zod error. Raw body: {"code":400,"message":"redirect URI https://example.com/cb is not allowed","retryable":false}'
|
||||
)
|
||||
expect(surfaceOauthError(err)).toBe(
|
||||
'Authorization server: redirect URI https://example.com/cb is not allowed'
|
||||
)
|
||||
})
|
||||
|
||||
it('prefers error_description over message over error in fallback envelope', async () => {
|
||||
const { ServerError } = await import('@modelcontextprotocol/sdk/server/auth/errors.js')
|
||||
const err = new ServerError(
|
||||
'HTTP 400: Invalid OAuth error response: zod. Raw body: {"error":"invalid_grant","error_description":"the description","message":"the message"}'
|
||||
)
|
||||
expect(surfaceOauthError(err)).toBe('Authorization server: the description')
|
||||
})
|
||||
|
||||
it('returns first line of generic errors', () => {
|
||||
const err = new Error('Network blip\n at fetch (...)')
|
||||
expect(surfaceOauthError(err)).toBe('Network blip')
|
||||
})
|
||||
|
||||
it('truncates messages longer than 250 chars with ellipsis', async () => {
|
||||
const { InvalidGrantError } = await import('@modelcontextprotocol/sdk/server/auth/errors.js')
|
||||
const longMessage = 'x'.repeat(300)
|
||||
const result = surfaceOauthError(new InvalidGrantError(longMessage))
|
||||
expect(result.endsWith('…')).toBe(true)
|
||||
expect(result.length).toBe(251)
|
||||
})
|
||||
|
||||
it('returns generic fallback for non-Error values', () => {
|
||||
expect(surfaceOauthError(null)).toBe('Failed to start OAuth flow')
|
||||
expect(surfaceOauthError(undefined)).toBe('Failed to start OAuth flow')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,162 @@
|
||||
import { OAuthError, ServerError } from '@modelcontextprotocol/sdk/server/auth/errors.js'
|
||||
import { db } from '@sim/db'
|
||||
import { mcpServers } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { and, eq, isNull } from 'drizzle-orm'
|
||||
import type { NextRequest } from 'next/server'
|
||||
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 { withMcpAuth } from '@/lib/mcp/middleware'
|
||||
import {
|
||||
assertSafeOauthServerUrl,
|
||||
getOrCreateOauthRow,
|
||||
loadPreregisteredClient,
|
||||
McpOauthInsecureUrlError,
|
||||
McpOauthRedirectRequired,
|
||||
mcpAuthGuarded,
|
||||
SimMcpOauthProvider,
|
||||
setOauthRowUser,
|
||||
} from '@/lib/mcp/oauth'
|
||||
import { createMcpErrorResponse } from '@/lib/mcp/utils'
|
||||
|
||||
const logger = createLogger('McpOauthStartAPI')
|
||||
const OAUTH_START_TTL_MS = 10 * 60 * 1000
|
||||
const MAX_SURFACED_ERROR_LENGTH = 250
|
||||
|
||||
export function surfaceOauthError(error: unknown): string {
|
||||
// Spec-compliant OAuth servers throw typed subclasses with clean RFC 6749 fields.
|
||||
if (error instanceof OAuthError && !(error instanceof ServerError)) {
|
||||
return truncate(`${error.errorCode}: ${error.message}`)
|
||||
}
|
||||
|
||||
// ServerError wraps non-spec response bodies as "HTTP N: Invalid OAuth error
|
||||
// response: ... Raw body: {...}". Dig the vendor message out of the JSON tail.
|
||||
if (error instanceof Error) {
|
||||
const rawBodyMatch = error.message.match(/Raw body:\s*(\{[\s\S]*\})\s*$/)
|
||||
if (rawBodyMatch) {
|
||||
try {
|
||||
const body = JSON.parse(rawBodyMatch[1]) as Record<string, unknown>
|
||||
const vendorMessage =
|
||||
(typeof body.error_description === 'string' && body.error_description) ||
|
||||
(typeof body.message === 'string' && body.message) ||
|
||||
(typeof body.error === 'string' && body.error) ||
|
||||
null
|
||||
if (vendorMessage) return truncate(`Authorization server: ${vendorMessage}`)
|
||||
} catch {}
|
||||
}
|
||||
return truncate(error.message.split('\n')[0] || 'Failed to start OAuth flow')
|
||||
}
|
||||
return 'Failed to start OAuth flow'
|
||||
}
|
||||
|
||||
function truncate(message: string): string {
|
||||
return message.length > MAX_SURFACED_ERROR_LENGTH
|
||||
? `${message.slice(0, MAX_SURFACED_ERROR_LENGTH)}…`
|
||||
: message
|
||||
}
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withMcpAuth('write')(async (request: NextRequest, { userId, workspaceId }) => {
|
||||
try {
|
||||
const parsed = await parseRequest(startMcpOauthContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
const { serverId } = parsed.data.query
|
||||
|
||||
const [server] = await db
|
||||
.select()
|
||||
.from(mcpServers)
|
||||
.where(
|
||||
and(
|
||||
eq(mcpServers.id, serverId),
|
||||
eq(mcpServers.workspaceId, workspaceId),
|
||||
isNull(mcpServers.deletedAt)
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
|
||||
if (!server) {
|
||||
return createMcpErrorResponse(new Error('Server not found'), 'Server not found', 404)
|
||||
}
|
||||
if (server.authType !== 'oauth') {
|
||||
return createMcpErrorResponse(
|
||||
new Error(`Server authType is "${server.authType}", not oauth`),
|
||||
'Server is not configured for OAuth',
|
||||
400
|
||||
)
|
||||
}
|
||||
if (!server.url) {
|
||||
return createMcpErrorResponse(new Error('Server has no URL'), 'Missing server URL', 400)
|
||||
}
|
||||
try {
|
||||
assertSafeOauthServerUrl(server.url)
|
||||
} catch (e) {
|
||||
if (e instanceof McpOauthInsecureUrlError) {
|
||||
return createMcpErrorResponse(
|
||||
e,
|
||||
'MCP OAuth requires https (or http://localhost for development)',
|
||||
400
|
||||
)
|
||||
}
|
||||
throw e
|
||||
}
|
||||
|
||||
const row = await getOrCreateOauthRow({
|
||||
mcpServerId: server.id,
|
||||
userId,
|
||||
workspaceId,
|
||||
})
|
||||
const hasActiveFlow =
|
||||
!!row.state &&
|
||||
!!row.stateCreatedAt &&
|
||||
row.stateCreatedAt.getTime() > Date.now() - OAUTH_START_TTL_MS
|
||||
if (hasActiveFlow && row.userId && row.userId !== userId) {
|
||||
return createMcpErrorResponse(
|
||||
new Error('OAuth authorization already in progress'),
|
||||
'OAuth authorization already in progress for this server',
|
||||
409
|
||||
)
|
||||
}
|
||||
if (row.userId !== userId) {
|
||||
await setOauthRowUser(row.id, userId)
|
||||
row.userId = userId
|
||||
}
|
||||
const preregistered = await loadPreregisteredClient(server.id)
|
||||
const provider = new SimMcpOauthProvider({ row, preregistered })
|
||||
|
||||
try {
|
||||
const result = await mcpAuthGuarded(provider, {
|
||||
serverUrl: server.url,
|
||||
})
|
||||
if (result === 'AUTHORIZED') {
|
||||
return NextResponse.json({ status: 'already_authorized' })
|
||||
}
|
||||
return createMcpErrorResponse(
|
||||
new Error('Provider did not capture redirect URL'),
|
||||
'Failed to start OAuth flow',
|
||||
500
|
||||
)
|
||||
} catch (e) {
|
||||
if (e instanceof McpOauthRedirectRequired) {
|
||||
logger.info(`OAuth redirect for server ${serverId}`)
|
||||
return NextResponse.json({
|
||||
status: 'redirect',
|
||||
authorizationUrl: e.authorizationUrl,
|
||||
})
|
||||
}
|
||||
throw e
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error starting MCP OAuth flow:', error)
|
||||
// Only surface OAuth-flow errors verbatim; everything else (DB, decryption,
|
||||
// network) gets a generic message to avoid leaking internal details.
|
||||
const userMessage =
|
||||
error instanceof OAuthError ? surfaceOauthError(error) : 'Failed to start OAuth flow'
|
||||
return createMcpErrorResponse(toError(error), userMessage, 500)
|
||||
}
|
||||
})
|
||||
)
|
||||
Reference in New Issue
Block a user