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,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