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
185 changes: 127 additions & 58 deletions apps/docs/openapi-v2-workflows.json

Large diffs are not rendered by default.

5 changes: 1 addition & 4 deletions apps/sim/app/api/billing/update-cost/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,7 @@ describe('POST /api/billing/update-cost — workspaceId attribution', () => {
)

expect(res.status).toBe(401)
await expect(res.json()).resolves.toEqual({
success: false,
error: 'Invalid internal API key',
})
await expect(res.json()).resolves.toEqual({ success: false, error: 'Unauthorized' })
expect(mockCheckInternalApiKey).toHaveBeenCalledTimes(1)
expect(mockRecordCumulativeUsage).not.toHaveBeenCalled()
})
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/app/api/billing/update-cost/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ async function updateCostInner(req: NextRequest, span: Span): Promise<NextRespon
return NextResponse.json(
{
success: false,
error: authResult.error || 'Authentication failed',
error: 'Unauthorized',
},
{ status: 401 }
)
Expand Down
53 changes: 46 additions & 7 deletions apps/sim/app/api/mcp/servers/test-connection/route.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createMockRequest, loggerMock } from '@sim/testing'
import { createRouteContext } from '@sim/testing/helpers/http'
import { mcpOauthMock, mcpOauthMockFns } from '@sim/testing/mocks/mcp-oauth.mock'
import type { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
Expand Down Expand Up @@ -45,10 +46,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 +82,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,8 +117,35 @@ 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(), createRouteContext({}))

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 response = await POST(
createTestRequest({ Authorization: 'Bearer static-api-token' }),
createRouteContext({})
)
const body = await response.json()

expect(response.status).toBe(200)
Expand All @@ -136,7 +166,10 @@ describe('MCP server test-connection route', () => {
it('returns a header-auth failure when the configured token is rejected', async () => {
mockConnect.mockRejectedValueOnce(new Error('HTTP 401: Unauthorized'))

const response = await POST(createTestRequest({ Authorization: 'Bearer invalid-static-token' }))
const response = await POST(
createTestRequest({ Authorization: 'Bearer invalid-static-token' }),
createRouteContext({})
)
const body = await response.json()

expect(response.status).toBe(400)
Expand All @@ -156,7 +189,10 @@ describe('MCP server test-connection route', () => {
const token = 'opaque-static-token'
mockConnect.mockRejectedValueOnce(new Error(`Upstream rejected ${token}`))

const response = await POST(createTestRequest({ Authorization: `Bearer ${token}` }))
const response = await POST(
createTestRequest({ Authorization: `Bearer ${token}` }),
createRouteContext({})
)
const body = await response.json()

expect(response.status).toBe(400)
Expand All @@ -168,7 +204,7 @@ describe('MCP server test-connection route', () => {
})

it('preserves OAuth discovery when no static headers are configured', async () => {
const response = await POST(createTestRequest())
const response = await POST(createTestRequest(), createRouteContext({}))
const body = await response.json()

expect(response.status).toBe(200)
Expand Down Expand Up @@ -201,7 +237,10 @@ describe('MCP server test-connection route', () => {
return '203.0.113.10'
})

const response = await POST(createTestRequest({ Authorization: `Bearer ${token}` }))
const response = await POST(
createTestRequest({ Authorization: `Bearer ${token}` }),
createRouteContext({})
)
const responseText = await response.text()

expect(response.status).toBe(403)
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)
}
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
10 changes: 2 additions & 8 deletions apps/sim/app/api/v2/lib/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
type OrchestrationErrorCode,
} from '@/lib/core/orchestration/types'
import type { HttpError } from '@/lib/core/utils/http-error'
import { describeResponseError } from '@/lib/core/utils/response-error'
import { describeResponseError, describeValidationError } from '@/lib/core/utils/response-error'
import type { RateLimitResult } from '@/app/api/v1/middleware'

/**
Expand Down Expand Up @@ -280,13 +280,7 @@ export function v2ValidationError(error: ZodError, slice?: RequestSlice): NextRe
const response = v2Error('BAD_REQUEST', location ? `${location}: ${message}` : message, {
details: serializeZodIssues(error),
})
// Deeper segments can be record keys the caller wrote (an import's CSV headers); no slice is itself a record.
const field = [slice, path[0]].filter((part) => part !== undefined && part !== '').join('.')
describeResponseError(response, {
errorCode: 'BAD_REQUEST',
...(field ? { errorField: field } : {}),
...(error.issues[0] ? { errorReason: error.issues[0].code } : {}),
})
describeValidationError(response, error, slice)
return response
}

Expand Down
48 changes: 48 additions & 0 deletions apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,43 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => {
expect(mockExecuteWorkflowCore).not.toHaveBeenCalled()
})

describe('names used before the draft-run rename', () => {
it('keeps the draft-run limits for source manual: no async, no input beside the sample', async () => {
authenticatePersonalKey()

const asyncResponse = await callExecute({ run: { source: 'manual' }, async: true })
expect(asyncResponse.status).toBe(400)
expect((await asyncResponse.json()).error.message).toBe(
'A draft run does not support async mode'
)

const withInput = await callExecute({
input: { event: 'created' },
run: { source: 'manual', entry: { type: 'trigger', useMockPayload: true } },
})
expect(withInput.status).toBe(400)
expect((await withInput.json()).error.message).toBe(
'input and run.entry.sample cannot be combined'
)
expect(mockExecuteManualTrigger).not.toHaveBeenCalled()
expect(mockExecuteWorkflowCore).not.toHaveBeenCalled()
})

it('refuses useMockPayload and sample that disagree, before dispatch', async () => {
authenticatePersonalKey()

const response = await callExecute({
run: { source: 'draft', entry: { type: 'trigger', sample: true, useMockPayload: false } },
})

expect(response.status).toBe(400)
expect(JSON.stringify(await response.json())).toContain(
'useMockPayload is the deprecated name of sample'
)
expect(mockExecuteManualTrigger).not.toHaveBeenCalled()
})
})

it('dispatches an OAuth manual trigger run through the same manual operation', async () => {
mockAuthenticateV2ApiKey.mockResolvedValue({
principal: {
Expand Down Expand Up @@ -1045,6 +1082,17 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => {
expect(mockExecuteManualTrigger).not.toHaveBeenCalled()
})

it('never permits a run named source manual on the anonymous public path', async () => {
dbChainMockFns.limit.mockReset()
queuePublicWorkflowReads()

const response = await callPublicExecute({ run: { source: 'manual' } })

expect(response.status).toBe(401)
expect(mockExecuteManualTrigger).not.toHaveBeenCalled()
expect(mockExecuteWorkflowCore).not.toHaveBeenCalled()
})

it('returns not found when a public workflow disappears before authorization', async () => {
dbChainMockFns.limit.mockReset()
queuePublicWorkflowReads()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { presentDry } from '@/lib/api/contracts/v2/deprecated-names'
import { v2ApplyWorkflowOperationsContract } from '@/lib/api/contracts/v2/workflows'
import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes'
import { v2WorkflowErrorPolicies } from '@/lib/workflows/api'
Expand Down Expand Up @@ -53,7 +54,7 @@ export const POST = defineV2JsonRoute({
lint: presentWorkflowLint(result.lint),
warnings: result.warnings,
needsRedeployment: result.needsRedeployment,
dry: result.dryRun,
...presentDry(result.dryRun),
},
}),
})
3 changes: 2 additions & 1 deletion apps/sim/app/api/v2/workflows/[workflowId]/state/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow'
import { presentDry } from '@/lib/api/contracts/v2/deprecated-names'
import {
v2GetWorkflowStateContract,
v2ReplaceWorkflowStateContract,
Expand Down Expand Up @@ -71,7 +72,7 @@ export const PUT = defineV2JsonRoute({
warnings,
needsRedeployment,
lint: presentWorkflowLint(lint),
dry: dryRun,
...presentDry(dryRun),
},
}),
})
23 changes: 23 additions & 0 deletions apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,29 @@ describe('POST /api/v2/workspaces/{workspaceId}/source', () => {
expect(charges()).toEqual(['workflows.source.write 1', 'workflows.source.write 39'])
})

it('runs the pre-rename ?dryRun as a dry run, in the plan bucket, answering under both names', async () => {
v2RouteMocks.operationRate.mockClear()
mocks.apply.mockClear()
mocks.apply.mockResolvedValue({
workspaceId: WORKSPACE_ID,
dryRun: true,
plan: [],
applied: [],
needBlobs: [],
files: {},
base: { version: 1, workspaceId: WORKSPACE_ID, resources: {} },
diagnostics: [],
})

const response = await apply('?dryRun=true')

expect(response.status).toBe(200)
expect(mocks.apply.mock.calls[0][0].input).toMatchObject({ dryRun: true })
const buckets = v2RouteMocks.operationRate.mock.calls.map(([key]) => String(key).split(':')[1])
expect(new Set(buckets)).toEqual(new Set(['source.plan']))
expect((await response.json()).data).toMatchObject({ dry: true, dryRun: true })
})

it('runs dry runs in plan slots, never in an apply’s: past the plans this server runs at once a dry run answers 429 and a real apply still runs', async () => {
const result = {
workspaceId: WORKSPACE_ID,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,14 @@ describe('POST /api/v2/workspaces/{workspaceId}/workflows/source', () => {
expect(response.status).toBe(200)
expect(mocks.create.mock.calls[0][0].input).toMatchObject({ dryRun: true })
})

it('treats the pre-rename ?dryRun as dry and answers under both names', async () => {
mocks.create.mockResolvedValue({ ...created, dryRun: true, applied: false })

const response = await POST(createRequest({ files }, '?dryRun=true'), context)

expect(response.status).toBe(200)
expect(mocks.create.mock.calls[0][0].input).toMatchObject({ dryRun: true })
expect((await response.json()).data).toMatchObject({ dry: true, dryRun: true })
})
})
Loading
Loading