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,453 @@
|
||||
/**
|
||||
* Tests that internal JWT callers receive the standard response format
|
||||
* even when the child workflow has a Response block.
|
||||
*
|
||||
* @vitest-environment node
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AuthType } from '@/lib/auth/hybrid'
|
||||
import { clearLargeValueCacheForTests } from '@/lib/execution/payloads/cache'
|
||||
import { createLargeArrayManifest } from '@/lib/execution/payloads/large-array-manifest'
|
||||
import { compactExecutionPayload } from '@/lib/execution/payloads/serializer'
|
||||
import { storeLargeValue } from '@/lib/execution/payloads/store'
|
||||
import { EXECUTION_RESOURCE_LIMIT_CODE } from '@/lib/execution/resource-errors'
|
||||
import type { ExecutionResult } from '@/lib/workflows/types'
|
||||
import { createHttpResponseFromBlock, workflowHasResponseBlock } from '@/lib/workflows/utils'
|
||||
|
||||
const {
|
||||
mockAddLargeValueReference,
|
||||
mockDownloadFile,
|
||||
mockRegisterLargeValueOwner,
|
||||
mockUploadFile,
|
||||
uploadedFiles,
|
||||
mockIsWorkspaceApiExecutionEntitled,
|
||||
} = vi.hoisted(() => ({
|
||||
mockAddLargeValueReference: vi.fn(),
|
||||
mockDownloadFile: vi.fn(),
|
||||
mockRegisterLargeValueOwner: vi.fn(),
|
||||
mockUploadFile: vi.fn(),
|
||||
uploadedFiles: new Map<string, Buffer>(),
|
||||
mockIsWorkspaceApiExecutionEntitled: vi.fn().mockResolvedValue(true),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/billing/core/api-access', () => ({
|
||||
API_EXECUTION_REQUIRES_PAID_PLAN_MESSAGE: 'paid plan required',
|
||||
isWorkspaceApiExecutionEntitled: mockIsWorkspaceApiExecutionEntitled,
|
||||
}))
|
||||
|
||||
const MATERIALIZATION_CONTEXT = {
|
||||
workspaceId: 'workspace-1',
|
||||
workflowId: 'workflow-1',
|
||||
executionId: 'execution-1',
|
||||
userId: 'user-1',
|
||||
}
|
||||
|
||||
vi.mock('@/lib/uploads', () => ({
|
||||
StorageService: {
|
||||
downloadFile: mockDownloadFile,
|
||||
uploadFile: mockUploadFile,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/execution/payloads/large-value-metadata', () => ({
|
||||
addLargeValueReference: mockAddLargeValueReference,
|
||||
registerLargeValueOwner: mockRegisterLargeValueOwner,
|
||||
}))
|
||||
|
||||
function buildExecutionResult(overrides: Partial<ExecutionResult> = {}): ExecutionResult {
|
||||
return {
|
||||
success: true,
|
||||
output: { data: { issues: [] }, status: 200, headers: {} },
|
||||
logs: [
|
||||
{
|
||||
blockId: 'response-1',
|
||||
blockType: 'response',
|
||||
blockName: 'Response',
|
||||
success: true,
|
||||
output: { data: { issues: [] }, status: 200, headers: {} },
|
||||
startedAt: '2026-01-01T00:00:00Z',
|
||||
endedAt: '2026-01-01T00:00:01Z',
|
||||
},
|
||||
],
|
||||
metadata: {
|
||||
duration: 500,
|
||||
startTime: '2026-01-01T00:00:00Z',
|
||||
endTime: '2026-01-01T00:00:01Z',
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('Response block gating by auth type', () => {
|
||||
let resultWithResponseBlock: ExecutionResult
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
clearLargeValueCacheForTests()
|
||||
uploadedFiles.clear()
|
||||
mockAddLargeValueReference.mockResolvedValue(undefined)
|
||||
mockRegisterLargeValueOwner.mockResolvedValue(true)
|
||||
mockUploadFile.mockImplementation(async ({ customKey, file }) => {
|
||||
uploadedFiles.set(customKey, file)
|
||||
return { key: customKey }
|
||||
})
|
||||
mockDownloadFile.mockImplementation(
|
||||
async ({ key }) => uploadedFiles.get(key) ?? Buffer.from('{}')
|
||||
)
|
||||
resultWithResponseBlock = buildExecutionResult()
|
||||
})
|
||||
|
||||
it('should detect a Response block in execution result', () => {
|
||||
expect(workflowHasResponseBlock(resultWithResponseBlock)).toBe(true)
|
||||
})
|
||||
|
||||
it('should not detect a Response block when none exists', () => {
|
||||
const resultWithoutResponseBlock = buildExecutionResult({
|
||||
output: { result: 'hello' },
|
||||
logs: [
|
||||
{
|
||||
blockId: 'agent-1',
|
||||
blockType: 'agent',
|
||||
blockName: 'Agent',
|
||||
success: true,
|
||||
output: { result: 'hello' },
|
||||
startedAt: '2026-01-01T00:00:00Z',
|
||||
endedAt: '2026-01-01T00:00:01Z',
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(workflowHasResponseBlock(resultWithoutResponseBlock)).toBe(false)
|
||||
})
|
||||
|
||||
it('should skip Response block formatting for internal JWT callers', () => {
|
||||
const authType = AuthType.INTERNAL_JWT
|
||||
const hasResponseBlock = workflowHasResponseBlock(resultWithResponseBlock)
|
||||
|
||||
expect(hasResponseBlock).toBe(true)
|
||||
|
||||
// This mirrors the route.ts condition:
|
||||
// if (auth.authType !== AuthType.INTERNAL_JWT && workflowHasResponseBlock(...))
|
||||
const shouldFormatAsResponseBlock = authType !== AuthType.INTERNAL_JWT && hasResponseBlock
|
||||
expect(shouldFormatAsResponseBlock).toBe(false)
|
||||
})
|
||||
|
||||
it('should apply Response block formatting for API key callers', async () => {
|
||||
const authType = AuthType.API_KEY
|
||||
const hasResponseBlock = workflowHasResponseBlock(resultWithResponseBlock)
|
||||
|
||||
const shouldFormatAsResponseBlock = authType !== AuthType.INTERNAL_JWT && hasResponseBlock
|
||||
expect(shouldFormatAsResponseBlock).toBe(true)
|
||||
|
||||
const response = await createHttpResponseFromBlock(resultWithResponseBlock)
|
||||
expect(response.status).toBe(200)
|
||||
})
|
||||
|
||||
it('should apply Response block formatting for session callers', () => {
|
||||
const authType = AuthType.SESSION
|
||||
const hasResponseBlock = workflowHasResponseBlock(resultWithResponseBlock)
|
||||
|
||||
const shouldFormatAsResponseBlock = authType !== AuthType.INTERNAL_JWT && hasResponseBlock
|
||||
expect(shouldFormatAsResponseBlock).toBe(true)
|
||||
})
|
||||
|
||||
it('should return raw user data via createHttpResponseFromBlock', async () => {
|
||||
const response = await createHttpResponseFromBlock(resultWithResponseBlock)
|
||||
const body = await response.json()
|
||||
|
||||
// Response block returns the user-defined data directly (no success/executionId wrapper)
|
||||
expect(body).toEqual({ issues: [] })
|
||||
expect(body.success).toBeUndefined()
|
||||
expect(body.executionId).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should respect custom status codes from Response block', async () => {
|
||||
const result = buildExecutionResult({
|
||||
output: { data: { error: 'Not found' }, status: 404, headers: {} },
|
||||
})
|
||||
|
||||
const response = await createHttpResponseFromBlock(result)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('should materialize manifest data for Response block HTTP output', async () => {
|
||||
const rows = Array.from({ length: 100 }, (_, index) => ({
|
||||
key: `SIM-${index}`,
|
||||
payload: 'x'.repeat(100),
|
||||
}))
|
||||
const output = await compactExecutionPayload(
|
||||
{
|
||||
data: { rows },
|
||||
status: 200,
|
||||
headers: {},
|
||||
},
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
requireDurable: true,
|
||||
preserveRoot: true,
|
||||
thresholdBytes: 1024,
|
||||
}
|
||||
)
|
||||
const response = await createHttpResponseFromBlock(
|
||||
buildExecutionResult({ output }),
|
||||
MATERIALIZATION_CONTEXT
|
||||
)
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.rows).toEqual(rows)
|
||||
expect(body.success).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should materialize Response block manifests from an allowed source execution', async () => {
|
||||
const rows = [{ key: 'SIM-1' }, { key: 'SIM-2' }]
|
||||
const manifest = await createLargeArrayManifest(rows, {
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
executionId: 'source-execution-1',
|
||||
})
|
||||
|
||||
const response = await createHttpResponseFromBlock(
|
||||
buildExecutionResult({
|
||||
output: {
|
||||
data: { rows: manifest },
|
||||
status: 200,
|
||||
headers: {},
|
||||
},
|
||||
}),
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
largeValueExecutionIds: ['source-execution-1'],
|
||||
}
|
||||
)
|
||||
const body = await response.json()
|
||||
|
||||
expect(body.rows).toEqual(rows)
|
||||
})
|
||||
|
||||
it('should reject Response block manifests from non-source same-workflow executions', async () => {
|
||||
const manifest = await createLargeArrayManifest([{ key: 'SIM-stale' }], {
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
executionId: 'stale-execution-1',
|
||||
})
|
||||
|
||||
await expect(
|
||||
createHttpResponseFromBlock(
|
||||
buildExecutionResult({
|
||||
output: {
|
||||
data: { rows: manifest },
|
||||
status: 200,
|
||||
headers: {},
|
||||
},
|
||||
}),
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
largeValueExecutionIds: ['source-execution-1'],
|
||||
}
|
||||
)
|
||||
).rejects.toThrow('Large execution value is not available in this execution')
|
||||
})
|
||||
|
||||
it('should materialize Response block manifests inherited by the source snapshot', async () => {
|
||||
const rows = [{ key: 'SIM-inherited' }]
|
||||
const manifest = await createLargeArrayManifest(rows, {
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
executionId: 'original-execution-1',
|
||||
})
|
||||
|
||||
const response = await createHttpResponseFromBlock(
|
||||
buildExecutionResult({
|
||||
output: {
|
||||
data: { rows: manifest },
|
||||
status: 200,
|
||||
headers: {},
|
||||
},
|
||||
}),
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
largeValueExecutionIds: ['source-execution-1', 'original-execution-1'],
|
||||
}
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
|
||||
expect(body.rows).toEqual(rows)
|
||||
})
|
||||
|
||||
it('should recursively materialize refs inside Response block manifest rows', async () => {
|
||||
const text = 'nested'.repeat(2 * 1024 * 1024)
|
||||
const nestedOutput = await compactExecutionPayload(
|
||||
{ text },
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
executionId: 'original-execution-1',
|
||||
requireDurable: true,
|
||||
preserveRoot: true,
|
||||
}
|
||||
)
|
||||
const nestedRef = (nestedOutput as unknown as { text: unknown }).text
|
||||
const manifest = await createLargeArrayManifest([{ nested: nestedRef }], {
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
executionId: 'source-execution-1',
|
||||
})
|
||||
const response = await createHttpResponseFromBlock(
|
||||
buildExecutionResult({
|
||||
output: {
|
||||
data: { rows: manifest },
|
||||
status: 200,
|
||||
headers: {},
|
||||
},
|
||||
}),
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
largeValueExecutionIds: ['source-execution-1'],
|
||||
}
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
|
||||
expect(body.rows).toEqual([{ nested: text }])
|
||||
})
|
||||
|
||||
it('should recursively materialize refs inside stored Response block objects', async () => {
|
||||
const text = 'nested'.repeat(2 * 1024 * 1024)
|
||||
const nestedOutput = await compactExecutionPayload(
|
||||
{ text },
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
executionId: 'original-execution-1',
|
||||
requireDurable: true,
|
||||
preserveRoot: true,
|
||||
}
|
||||
)
|
||||
const nestedRef = (nestedOutput as unknown as { text: unknown }).text
|
||||
const storedValue = {
|
||||
wrapper: {
|
||||
nested: nestedRef,
|
||||
padding: 'x'.repeat(2048),
|
||||
},
|
||||
}
|
||||
const storedJson = JSON.stringify(storedValue)
|
||||
const storedOutput = await storeLargeValue(
|
||||
storedValue,
|
||||
storedJson,
|
||||
Buffer.byteLength(storedJson),
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
executionId: 'source-execution-1',
|
||||
requireDurable: true,
|
||||
}
|
||||
)
|
||||
|
||||
const response = await createHttpResponseFromBlock(
|
||||
buildExecutionResult({
|
||||
output: {
|
||||
data: storedOutput,
|
||||
status: 200,
|
||||
headers: {},
|
||||
},
|
||||
}),
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
largeValueExecutionIds: ['source-execution-1'],
|
||||
}
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
|
||||
expect(body.wrapper.nested).toEqual(text)
|
||||
})
|
||||
|
||||
it('should memoize repeated materialized objects while resolving nested refs', async () => {
|
||||
const text = 'nested'.repeat(2 * 1024 * 1024)
|
||||
const nestedOutput = await compactExecutionPayload(
|
||||
{ text },
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
executionId: 'original-execution-1',
|
||||
requireDurable: true,
|
||||
preserveRoot: true,
|
||||
}
|
||||
)
|
||||
const nestedRef = (nestedOutput as unknown as { text: unknown }).text
|
||||
const sourceValue = { nested: nestedRef }
|
||||
const sourceJson = JSON.stringify(sourceValue)
|
||||
const sourceRef = await storeLargeValue(
|
||||
sourceValue,
|
||||
sourceJson,
|
||||
Buffer.byteLength(sourceJson),
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
executionId: 'source-execution-1',
|
||||
requireDurable: true,
|
||||
}
|
||||
)
|
||||
|
||||
const response = await createHttpResponseFromBlock(
|
||||
buildExecutionResult({
|
||||
output: {
|
||||
data: { first: sourceRef, second: sourceRef },
|
||||
status: 200,
|
||||
headers: {},
|
||||
},
|
||||
}),
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
largeValueKeys: sourceRef.key ? [sourceRef.key] : [],
|
||||
}
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
|
||||
expect(body).toEqual({
|
||||
first: { nested: text },
|
||||
second: { nested: text },
|
||||
})
|
||||
})
|
||||
|
||||
it('should materialize large string refs for Response block HTTP output', async () => {
|
||||
const text = 'x'.repeat(9 * 1024 * 1024)
|
||||
const output = await compactExecutionPayload(
|
||||
{
|
||||
data: { text },
|
||||
status: 200,
|
||||
headers: {},
|
||||
},
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
requireDurable: true,
|
||||
preserveRoot: true,
|
||||
}
|
||||
)
|
||||
const response = await createHttpResponseFromBlock(
|
||||
buildExecutionResult({ output }),
|
||||
MATERIALIZATION_CONTEXT
|
||||
)
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.text).toBe(text)
|
||||
})
|
||||
|
||||
it('should reject Response block HTTP output that is too large to inline', async () => {
|
||||
const output = await compactExecutionPayload(
|
||||
{
|
||||
data: {
|
||||
text: 'x'.repeat(17 * 1024 * 1024),
|
||||
},
|
||||
status: 200,
|
||||
headers: {},
|
||||
},
|
||||
{
|
||||
...MATERIALIZATION_CONTEXT,
|
||||
requireDurable: true,
|
||||
preserveRoot: true,
|
||||
}
|
||||
)
|
||||
|
||||
await expect(
|
||||
createHttpResponseFromBlock(buildExecutionResult({ output }), MATERIALIZATION_CONTEXT)
|
||||
).rejects.toMatchObject({
|
||||
code: EXECUTION_RESOURCE_LIMIT_CODE,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,473 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
|
||||
import {
|
||||
createMockRequest,
|
||||
executionPreprocessingMock,
|
||||
executionPreprocessingMockFns,
|
||||
hybridAuthMockFns,
|
||||
loggingSessionMock,
|
||||
requestUtilsMockFns,
|
||||
workflowAuthzMockFns,
|
||||
workflowsPersistenceUtilsMock,
|
||||
workflowsPersistenceUtilsMockFns,
|
||||
workflowsUtilsMock,
|
||||
workflowsUtilsMockFns,
|
||||
} from '@sim/testing'
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockEnqueue,
|
||||
mockExecuteWorkflowCore,
|
||||
mockHandlePostExecutionPauseState,
|
||||
mockIsWorkspaceApiExecutionEntitled,
|
||||
} = vi.hoisted(() => ({
|
||||
mockEnqueue: vi.fn().mockResolvedValue('job-123'),
|
||||
mockExecuteWorkflowCore: vi.fn(),
|
||||
mockHandlePostExecutionPauseState: vi.fn(),
|
||||
mockIsWorkspaceApiExecutionEntitled: vi.fn().mockResolvedValue(true),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/billing/core/api-access', () => ({
|
||||
API_EXECUTION_REQUIRES_PAID_PLAN_MESSAGE: 'paid plan required',
|
||||
isWorkspaceApiExecutionEntitled: mockIsWorkspaceApiExecutionEntitled,
|
||||
}))
|
||||
|
||||
const mockCheckHybridAuth = hybridAuthMockFns.mockCheckHybridAuth
|
||||
const mockPreprocessExecution = executionPreprocessingMockFns.mockPreprocessExecution
|
||||
|
||||
const mockAuthorizeWorkflowByWorkspacePermission =
|
||||
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission
|
||||
|
||||
vi.mock('@/lib/workflows/utils', () => workflowsUtilsMock)
|
||||
|
||||
vi.mock('@/lib/execution/preprocessing', () => executionPreprocessingMock)
|
||||
|
||||
vi.mock('@/lib/workflows/persistence/utils', () => workflowsPersistenceUtilsMock)
|
||||
|
||||
vi.mock('@/lib/workflows/executor/execution-core', () => ({
|
||||
executeWorkflowCore: mockExecuteWorkflowCore,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/executor/pause-persistence', () => ({
|
||||
handlePostExecutionPauseState: mockHandlePostExecutionPauseState,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/execution/payloads/store', () => ({
|
||||
storeLargeValue: vi.fn(async (_value, _json, size: number) => ({
|
||||
__simLargeValueRef: true,
|
||||
version: 1,
|
||||
id: 'lv_abcdefghijkl',
|
||||
kind: 'string',
|
||||
size,
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/async-jobs', () => ({
|
||||
getJobQueue: vi.fn().mockResolvedValue({
|
||||
enqueue: mockEnqueue,
|
||||
startJob: vi.fn(),
|
||||
completeJob: vi.fn(),
|
||||
markJobFailed: vi.fn(),
|
||||
}),
|
||||
shouldExecuteInline: vi.fn().mockReturnValue(false),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/utils/urls', () => ({
|
||||
getBaseUrl: vi.fn().mockReturnValue('http://localhost:3000'),
|
||||
getOllamaUrl: vi.fn().mockReturnValue('http://localhost:11434'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/execution/call-chain', () => ({
|
||||
SIM_VIA_HEADER: 'x-sim-via',
|
||||
parseCallChain: vi.fn().mockReturnValue([]),
|
||||
validateCallChain: vi.fn().mockReturnValue(null),
|
||||
buildNextCallChain: vi.fn().mockReturnValue(['workflow-1']),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/logs/execution/logging-session', () => loggingSessionMock)
|
||||
|
||||
vi.mock('@/background/workflow-execution', () => ({
|
||||
executeWorkflowJob: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@sim/utils/id', () => ({
|
||||
generateId: vi.fn(() => 'execution-123'),
|
||||
generateShortId: vi.fn(() => 'mock-short-id'),
|
||||
isValidUuid: vi.fn((v: string) =>
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v)
|
||||
),
|
||||
}))
|
||||
|
||||
import { storeLargeValue } from '@/lib/execution/payloads/store'
|
||||
import { POST } from './route'
|
||||
|
||||
describe('workflow execute async route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
requestUtilsMockFns.mockGenerateRequestId.mockReturnValue('req-12345678')
|
||||
workflowsUtilsMockFns.mockWorkflowHasResponseBlock.mockReturnValue(false)
|
||||
hybridAuthMockFns.mockHasExternalApiCredentials.mockReturnValue(true)
|
||||
|
||||
mockCheckHybridAuth.mockResolvedValue({
|
||||
success: true,
|
||||
userId: 'session-user-1',
|
||||
authType: 'session',
|
||||
})
|
||||
|
||||
mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
|
||||
allowed: true,
|
||||
workflow: {
|
||||
id: 'workflow-1',
|
||||
userId: 'owner-1',
|
||||
workspaceId: 'workspace-1',
|
||||
},
|
||||
})
|
||||
|
||||
mockPreprocessExecution.mockResolvedValue({
|
||||
success: true,
|
||||
actorUserId: 'actor-1',
|
||||
workflowRecord: {
|
||||
id: 'workflow-1',
|
||||
userId: 'owner-1',
|
||||
workspaceId: 'workspace-1',
|
||||
},
|
||||
})
|
||||
workflowsPersistenceUtilsMockFns.mockLoadDeployedWorkflowState.mockResolvedValue(null)
|
||||
workflowsPersistenceUtilsMockFns.mockLoadWorkflowFromNormalizedTables.mockResolvedValue(null)
|
||||
mockExecuteWorkflowCore.mockResolvedValue({
|
||||
success: true,
|
||||
status: 'completed',
|
||||
output: { ok: true },
|
||||
metadata: {
|
||||
duration: 100,
|
||||
startTime: '2026-01-01T00:00:00Z',
|
||||
endTime: '2026-01-01T00:00:01Z',
|
||||
},
|
||||
})
|
||||
mockHandlePostExecutionPauseState.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('queues async execution with matching correlation metadata', async () => {
|
||||
const req = createMockRequest(
|
||||
'POST',
|
||||
{ input: { hello: 'world' } },
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'X-Execution-Mode': 'async',
|
||||
}
|
||||
)
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(202)
|
||||
expect(body.executionId).toBe('execution-123')
|
||||
expect(body.jobId).toBe('job-123')
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
'workflow-execution',
|
||||
expect.objectContaining({
|
||||
workflowId: 'workflow-1',
|
||||
userId: 'actor-1',
|
||||
workspaceId: 'workspace-1',
|
||||
executionId: 'execution-123',
|
||||
executionMode: 'async',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
metadata: expect.objectContaining({
|
||||
workflowId: 'workflow-1',
|
||||
userId: 'actor-1',
|
||||
workspaceId: 'workspace-1',
|
||||
correlation: expect.objectContaining({
|
||||
executionId: 'execution-123',
|
||||
requestId: 'req-12345678',
|
||||
source: 'workflow',
|
||||
workflowId: 'workflow-1',
|
||||
triggerType: 'manual',
|
||||
}),
|
||||
}),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects cross-site session requests before authorization work', async () => {
|
||||
const req = createMockRequest(
|
||||
'POST',
|
||||
{ input: { hello: 'world' } },
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'Sec-Fetch-Site': 'cross-site',
|
||||
}
|
||||
)
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
expect(body.error).toBe('Access denied')
|
||||
expect(mockAuthorizeWorkflowByWorkspacePermission).not.toHaveBeenCalled()
|
||||
expect(mockEnqueue).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('allows same-site session requests (multi-subdomain Run, e.g. www.<domain>)', async () => {
|
||||
const req = createMockRequest(
|
||||
'POST',
|
||||
{ input: { hello: 'world' } },
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'X-Execution-Mode': 'async',
|
||||
'Sec-Fetch-Site': 'same-site',
|
||||
}
|
||||
)
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
|
||||
expect(response.status).toBe(202)
|
||||
expect(mockEnqueue).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects oversized request bodies before authorization work', async () => {
|
||||
const req = createMockRequest(
|
||||
'POST',
|
||||
{ input: { hello: 'world' } },
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': String(10 * 1024 * 1024 + 1),
|
||||
}
|
||||
)
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(413)
|
||||
expect(body.error).toContain('Workflow execution request body')
|
||||
expect(mockAuthorizeWorkflowByWorkspacePermission).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('authenticates before rejecting oversized request bodies', async () => {
|
||||
mockCheckHybridAuth.mockResolvedValueOnce({
|
||||
success: false,
|
||||
error: 'Unauthorized',
|
||||
authType: 'api_key',
|
||||
})
|
||||
const req = createMockRequest(
|
||||
'POST',
|
||||
{ input: { hello: 'world' } },
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': String(10 * 1024 * 1024 + 1),
|
||||
'X-API-Key': 'invalid',
|
||||
}
|
||||
)
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(body.error).toBe('Unauthorized')
|
||||
expect(mockCheckHybridAuth).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 499 when a non-SSE execution is cancelled by client disconnect', async () => {
|
||||
const abortController = new AbortController()
|
||||
mockExecuteWorkflowCore.mockImplementationOnce(
|
||||
async ({ abortSignal }: { abortSignal: AbortSignal }) => {
|
||||
abortController.abort()
|
||||
expect(abortSignal.aborted).toBe(true)
|
||||
return {
|
||||
success: false,
|
||||
status: 'cancelled',
|
||||
output: { partial: true },
|
||||
metadata: {
|
||||
duration: 100,
|
||||
startTime: '2026-01-01T00:00:00Z',
|
||||
endTime: '2026-01-01T00:00:01Z',
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
const req = new NextRequest('http://localhost:3000/api/workflows/workflow-1/execute', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ input: { hello: 'world' } }),
|
||||
signal: abortController.signal,
|
||||
})
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(499)
|
||||
expect(body.error).toBe('Client cancelled request')
|
||||
})
|
||||
|
||||
it('rejects large MCP bridge outputs instead of returning large-value refs', async () => {
|
||||
mockCheckHybridAuth.mockResolvedValueOnce({
|
||||
success: true,
|
||||
userId: 'internal-user-1',
|
||||
authType: 'internal_jwt',
|
||||
})
|
||||
mockExecuteWorkflowCore.mockResolvedValueOnce({
|
||||
success: true,
|
||||
status: 'completed',
|
||||
output: 'x'.repeat(10 * 1024 * 1024 + 1),
|
||||
metadata: {
|
||||
duration: 100,
|
||||
startTime: '2026-01-01T00:00:00Z',
|
||||
endTime: '2026-01-01T00:00:01Z',
|
||||
},
|
||||
})
|
||||
const req = createMockRequest(
|
||||
'POST',
|
||||
{ input: { hello: 'world' } },
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'X-Sim-MCP-Tool-Call': 'true',
|
||||
}
|
||||
)
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(413)
|
||||
expect(body.error).toContain('Workflow execution response')
|
||||
expect(storeLargeValue).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not trust client-spoofed MCP bridge headers on API key executions', async () => {
|
||||
mockCheckHybridAuth.mockResolvedValueOnce({
|
||||
success: true,
|
||||
userId: 'api-user-1',
|
||||
authType: 'api_key',
|
||||
apiKeyType: 'personal',
|
||||
})
|
||||
workflowsUtilsMockFns.mockWorkflowHasResponseBlock.mockReturnValueOnce(true)
|
||||
workflowsUtilsMockFns.mockCreateHttpResponseFromBlock.mockResolvedValueOnce(
|
||||
Response.json({ response: 'plain text body' })
|
||||
)
|
||||
mockExecuteWorkflowCore.mockResolvedValueOnce({
|
||||
success: true,
|
||||
status: 'completed',
|
||||
output: { response: 'plain text body' },
|
||||
metadata: {
|
||||
duration: 100,
|
||||
startTime: '2026-01-01T00:00:00Z',
|
||||
endTime: '2026-01-01T00:00:01Z',
|
||||
},
|
||||
})
|
||||
const req = createMockRequest(
|
||||
'POST',
|
||||
{ input: { hello: 'world' } },
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'valid',
|
||||
'X-Sim-MCP-Tool-Call': 'true',
|
||||
}
|
||||
)
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toEqual({ response: 'plain text body' })
|
||||
expect(workflowsUtilsMockFns.mockCreateHttpResponseFromBlock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps trusted internal MCP bridge executions on the JSON envelope path', async () => {
|
||||
mockCheckHybridAuth.mockResolvedValueOnce({
|
||||
success: true,
|
||||
userId: 'internal-user-1',
|
||||
authType: 'internal_jwt',
|
||||
})
|
||||
workflowsUtilsMockFns.mockWorkflowHasResponseBlock.mockReturnValueOnce(true)
|
||||
mockExecuteWorkflowCore.mockResolvedValueOnce({
|
||||
success: true,
|
||||
status: 'completed',
|
||||
output: { response: 'plain text body' },
|
||||
metadata: {
|
||||
duration: 100,
|
||||
startTime: '2026-01-01T00:00:00Z',
|
||||
endTime: '2026-01-01T00:00:01Z',
|
||||
},
|
||||
})
|
||||
const req = createMockRequest(
|
||||
'POST',
|
||||
{ input: { hello: 'world' } },
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'X-Sim-MCP-Tool-Call': 'true',
|
||||
}
|
||||
)
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toMatchObject({
|
||||
success: true,
|
||||
output: { response: 'plain text body' },
|
||||
})
|
||||
expect(workflowsUtilsMockFns.mockCreateHttpResponseFromBlock).not.toHaveBeenCalled()
|
||||
expect(mockExecuteWorkflowCore).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
snapshot: expect.objectContaining({
|
||||
input: { hello: 'world' },
|
||||
}),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves authenticated-user actor semantics for trusted MCP bridge calls', async () => {
|
||||
mockCheckHybridAuth.mockResolvedValueOnce({
|
||||
success: true,
|
||||
userId: 'api-user-1',
|
||||
authType: 'internal_jwt',
|
||||
})
|
||||
mockExecuteWorkflowCore.mockResolvedValueOnce({
|
||||
success: true,
|
||||
status: 'completed',
|
||||
output: { ok: true },
|
||||
metadata: {
|
||||
duration: 100,
|
||||
startTime: '2026-01-01T00:00:00Z',
|
||||
endTime: '2026-01-01T00:00:01Z',
|
||||
},
|
||||
})
|
||||
const req = createMockRequest(
|
||||
'POST',
|
||||
{ input: { hello: 'world' } },
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'X-Sim-MCP-Tool-Call': 'true',
|
||||
'X-Sim-MCP-Tool-Actor': 'authenticated-user',
|
||||
}
|
||||
)
|
||||
const params = Promise.resolve({ id: 'workflow-1' })
|
||||
|
||||
const response = await POST(req, { params })
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPreprocessExecution).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 'api-user-1',
|
||||
useAuthenticatedUserAsActor: true,
|
||||
})
|
||||
)
|
||||
const executionCall = mockExecuteWorkflowCore.mock.calls[0][0]
|
||||
const snapshot =
|
||||
typeof executionCall.snapshot === 'string'
|
||||
? JSON.parse(executionCall.snapshot)
|
||||
: executionCall.snapshot
|
||||
expect(snapshot.metadata.enforceCredentialAccess).toBe(true)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user