From 847ecb5caa87445e12c644e36439d3685ba73048 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 11:33:02 -0800 Subject: [PATCH 1/6] fix(catalog): label model-provider access ids read An Agent, Router or Evaluator lists the model providers it may call in tools.access; they are not registered tools, so both catalog projections labelled them write. A model call changes nothing outside Sim and a dry run sends it, so one accessIdEffect (blocks/access-effect.ts) labels them read for both projections, keeping any other unregistered id write. A block that runs tools its user chooses (a tool-input field, as an Agent has) stays write whatever its access ids say, so only Router and Evaluator become read. --- apps/sim/blocks/access-effect.ts | 27 +++++++++++++++++++ apps/sim/blocks/blocks/agent.ts | 10 ++----- apps/sim/blocks/blocks/evaluator.ts | 10 ++----- apps/sim/blocks/blocks/router.ts | 19 +++---------- .../lib/catalog/projection/block-detail.ts | 6 ++--- .../lib/workflows/code/catalog/build.test.ts | 17 ++++++++++++ .../sim/lib/workflows/code/catalog/project.ts | 20 +++++++------- .../workflow-sdk/test/fixtures/catalog.json | 2 +- 8 files changed, 66 insertions(+), 45 deletions(-) create mode 100644 apps/sim/blocks/access-effect.ts diff --git a/apps/sim/blocks/access-effect.ts b/apps/sim/blocks/access-effect.ts new file mode 100644 index 00000000000..8fc802ff1d1 --- /dev/null +++ b/apps/sim/blocks/access-effect.ts @@ -0,0 +1,27 @@ +import { getToolMetadata } from '@/tools/metadata' +import type { ToolEffect } from '@/tools/types' + +/** + * The `tools.access` of a block that calls a model (Agent, Router, Evaluator): one id per model + * provider it may call, not a registered tool. + */ +export const MODEL_PROVIDER_ACCESS_IDS: readonly string[] = [ + 'openai_chat', + 'anthropic_chat', + 'google_chat', + 'xai_chat', + 'deepseek_chat', + 'deepseek_reasoner', +] + +const MODEL_PROVIDER_ACCESS_ID_SET: ReadonlySet = new Set(MODEL_PROVIDER_ACCESS_IDS) + +/** + * The effect of one `tools.access` id: a registered tool's declared effect; `read` for a model + * provider, since a model call changes nothing outside Sim and a dry run sends it; `write` for any + * other id, which declares nothing. A block that also runs tools its user chooses is a writer + * whatever its access ids say. + */ +export function accessIdEffect(id: string): ToolEffect { + return getToolMetadata(id)?.effect ?? (MODEL_PROVIDER_ACCESS_ID_SET.has(id) ? 'read' : 'write') +} diff --git a/apps/sim/blocks/blocks/agent.ts b/apps/sim/blocks/blocks/agent.ts index 8316335b58a..a233581f4a5 100644 --- a/apps/sim/blocks/blocks/agent.ts +++ b/apps/sim/blocks/blocks/agent.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { AgentIcon } from '@/components/icons' +import { MODEL_PROVIDER_ACCESS_IDS } from '@/blocks/access-effect' import { getModelFallbackSubBlock, MODEL_FALLBACK_INPUTS } from '@/blocks/model-fallbacks' import type { BlockConfig } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' @@ -415,14 +416,7 @@ Return ONLY the JSON array.`, }, ], tools: { - access: [ - 'openai_chat', - 'anthropic_chat', - 'google_chat', - 'xai_chat', - 'deepseek_chat', - 'deepseek_reasoner', - ], + access: [...MODEL_PROVIDER_ACCESS_IDS], config: { tool: (params: Record) => { return resolveModelProviderId(params.model) diff --git a/apps/sim/blocks/blocks/evaluator.ts b/apps/sim/blocks/blocks/evaluator.ts index 95890acf151..ae925233b81 100644 --- a/apps/sim/blocks/blocks/evaluator.ts +++ b/apps/sim/blocks/blocks/evaluator.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { ChartBarIcon } from '@/components/icons' +import { MODEL_PROVIDER_ACCESS_IDS } from '@/blocks/access-effect' import { getModelFallbackSubBlock, MODEL_FALLBACK_INPUTS } from '@/blocks/model-fallbacks' import type { BlockConfig, ParamType } from '@/blocks/types' import { @@ -228,14 +229,7 @@ export const EvaluatorBlock: BlockConfig = { }, ], tools: { - access: [ - 'openai_chat', - 'anthropic_chat', - 'google_chat', - 'xai_chat', - 'deepseek_chat', - 'deepseek_reasoner', - ], + access: [...MODEL_PROVIDER_ACCESS_IDS], config: { tool: (params: Record) => resolveModelProviderId(params.model), }, diff --git a/apps/sim/blocks/blocks/router.ts b/apps/sim/blocks/blocks/router.ts index 60aa7ef7436..3951aa36f66 100644 --- a/apps/sim/blocks/blocks/router.ts +++ b/apps/sim/blocks/blocks/router.ts @@ -1,4 +1,5 @@ import { ConnectIcon } from '@/components/icons' +import { MODEL_PROVIDER_ACCESS_IDS } from '@/blocks/access-effect' import { getModelFallbackSubBlock, MODEL_FALLBACK_INPUTS } from '@/blocks/model-fallbacks' import { AuthMode, type BlockConfig } from '@/blocks/types' import { @@ -186,14 +187,7 @@ export const RouterBlock: BlockConfig = { }, ], tools: { - access: [ - 'openai_chat', - 'anthropic_chat', - 'google_chat', - 'xai_chat', - 'deepseek_chat', - 'deepseek_reasoner', - ], + access: [...MODEL_PROVIDER_ACCESS_IDS], config: { tool: (params: Record) => resolveModelProviderId(params.model), }, @@ -261,14 +255,7 @@ export const RouterV2Block: BlockConfig = { getModelFallbackSubBlock(), ], tools: { - access: [ - 'openai_chat', - 'anthropic_chat', - 'google_chat', - 'xai_chat', - 'deepseek_chat', - 'deepseek_reasoner', - ], + access: [...MODEL_PROVIDER_ACCESS_IDS], config: { tool: (params: Record) => resolveModelProviderId(params.model), }, diff --git a/apps/sim/lib/catalog/projection/block-detail.ts b/apps/sim/lib/catalog/projection/block-detail.ts index e0720362dd4..d24397385b8 100644 --- a/apps/sim/lib/catalog/projection/block-detail.ts +++ b/apps/sim/lib/catalog/projection/block-detail.ts @@ -21,6 +21,7 @@ import { type CatalogToolSummary, projectToolDetail, } from '@/lib/catalog/projection/tool' +import { accessIdEffect } from '@/blocks/access-effect' import { isCustomBlockType } from '@/blocks/custom/build-config' import { type BlockConfig, @@ -492,8 +493,7 @@ export function projectBlockDetail( id: toolId, name: toolId, description: '', - // An id with no registered tool declares no effect, which counts as a write. - effect: 'write', + effect: accessIdEffect(toolId), hostedApiKey: 'none', params: {}, outputs: {}, @@ -518,7 +518,7 @@ export function projectBlockDetail( inputs, outputs: tool?.outputs ?? {}, inputSchema: operationFields[operationId] ?? [], - ...(toolId !== undefined ? { toolId, effect: tool?.effect ?? 'write' } : {}), + ...(toolId !== undefined ? { toolId, effect: tool?.effect ?? accessIdEffect(toolId) } : {}), ...(tool ? { toolName: tool.name, description: describeTool(tool) } : {}), } } diff --git a/apps/sim/lib/workflows/code/catalog/build.test.ts b/apps/sim/lib/workflows/code/catalog/build.test.ts index deccd4ba9cd..6ca52198f13 100644 --- a/apps/sim/lib/workflows/code/catalog/build.test.ts +++ b/apps/sim/lib/workflows/code/catalog/build.test.ts @@ -183,6 +183,23 @@ describe('block catalog projection over the whole registry', () => { expect(gmailCredential?.credentialProviders).toEqual(['google-email', 'google-service-account']) }) + it('labels a block that only calls model providers read, unless it runs tools its user chooses', () => { + expect(view.blocks.router_v2.effect).toBe('read') + expect(view.blocks.evaluator.effect).toBe('read') + expect(view.blocks.agent.effect).toBe('write') + }) + + it('labels a block with an access id that is neither a tool nor a model provider write', () => { + const router = registryBlocks.find((block) => block.type === 'router_v2') + if (!router) throw new Error('The registry has no Router block') + const unknown: BlockConfig = { + ...router, + tools: { ...router.tools, access: [...router.tools.access, 'unregistered_tool'] }, + } + const projected = projectBlockCatalog({ ...registryInput, blocks: [unknown] }) + expect(projected.blocks.router_v2.effect).toBe('write') + }) + it('gives every operation a builder that pins it', () => { const missing: string[] = [] for (const block of registryBlocks) { diff --git a/apps/sim/lib/workflows/code/catalog/project.ts b/apps/sim/lib/workflows/code/catalog/project.ts index c06602c8f7b..9c23f5e3cee 100644 --- a/apps/sim/lib/workflows/code/catalog/project.ts +++ b/apps/sim/lib/workflows/code/catalog/project.ts @@ -20,13 +20,13 @@ import { probeThunk, readsOnly } from '@/lib/workflows/code/catalog/probe' import { operationOptions } from '@/lib/workflows/code/catalog/sdk-names' import { deriveValueShape } from '@/lib/workflows/code/catalog/value-kind' import { TRIGGER_TYPES } from '@/lib/workflows/triggers/types' +import { accessIdEffect } from '@/blocks/access-effect' import type { BlockConfig, SubBlockConfig } from '@/blocks/types' import { isHumanInTheLoopBlock, isMetadataOnlyBlockType, isSentinelBlockType, } from '@/executor/constants' -import { getToolMetadata } from '@/tools/metadata' import { getToolOutputsMetadata } from '@/tools/metadata-outputs' import { getSubBlockValueShape } from '@/tools/param-shape' import type { TriggerConfig } from '@/triggers/types' @@ -511,10 +511,10 @@ function projectOperationOutputs( } /** - * The block's effect from its tools' declared effects, and, when the operation picks the tool, each - * operation whose tool differs from it. An id that is not a registered tool (the model providers an - * Agent, Router, or Evaluator calls) counts as `write`. An opaque selector cannot be probed, so its - * operations inherit the block effect. + * The block's effect from its access ids' effects ({@link accessIdEffect}), and, when the + * operation picks the tool, each operation whose tool differs from it. A block that runs tools its + * user chooses (a `tool-input` field, as an Agent has) is `write`, whatever its access ids say. An + * opaque selector cannot be probed, so its operations inherit the block effect. */ function projectEffects( block: BlockConfig, @@ -522,11 +522,13 @@ function projectEffects( ): Pick { if (block.tools.access.length === 0) return {} const accessEffects = new Map( - block.tools.access.map( - (toolId) => [toolId, getToolMetadata(toolId)?.effect ?? 'write'] as const - ) + block.tools.access.map((toolId) => [toolId, accessIdEffect(toolId)] as const) ) - const effect = [...accessEffects.values()].every((entry) => entry === 'read') ? 'read' : 'write' + const runsChosenTools = block.subBlocks.some((subBlock) => subBlock.type === 'tool-input') + const effect = + !runsChosenTools && [...accessEffects.values()].every((entry) => entry === 'read') + ? 'read' + : 'write' if (effect === 'read' || !operationTools) return { effect } const operationEffects: NonNullable = {} for (const [operation, toolId] of operationTools) { diff --git a/packages/workflow-sdk/test/fixtures/catalog.json b/packages/workflow-sdk/test/fixtures/catalog.json index bfe065a5a9d..1abae86d164 100644 --- a/packages/workflow-sdk/test/fixtures/catalog.json +++ b/packages/workflow-sdk/test/fixtures/catalog.json @@ -15673,7 +15673,7 @@ "kind": "router" } }, - "effect": "write" + "effect": "read" }, "schedule": { "type": "schedule", From c0b3f35acd617238b7c7b50543ad82fe1da66b97 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 11:33:04 -0800 Subject: [PATCH 2/6] feat(workflows): dry runs stub code's network writes instead of listing code unchecked Isolate code (Function blocks, Condition expressions, While/Do While loop conditions, an Agent's run code) now meets the run's side-effect policy at the isolate host's fetch handler. Options are normalized once (the fetch standard's method normalization), the target is validated as a live fetch would be (URL length, egress policy), and then a read (GET/HEAD/OPTIONS without a method-override header) is sent while any other request gets an empty 200 with x-sim-dry-run: stubbed and is recorded in sideEffects.stubbed as function_execute. The recorded request keeps the method, a capped URL with query names only, header names and a capped body, with the code's env and personal secrets masked alongside the usual redaction. An allowed block sends everything and is recorded allowed on its first write. Only code in a remote sandbox is listed unchecked. The policy is trusted in-process state threaded through executeFunctionTool, executeFunction and executeFunctionRequest into executeInIsolatedVM. A Function block that fails after stubbed writes says how many got an empty response and that --allow '' sends them. http_request declares readsWhen, so a GET/HEAD/OPTIONS API call without a method-override header is sent as a read in a dry run while its catalog effect stays write. Contract, CLI help, workflow-test descriptions and docs updated. --- apps/docs/content/docs/cli/reference.mdx | 2 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 6 +- apps/sim/executor/execution/types.ts | 37 ++- apps/sim/executor/orchestrators/loop.test.ts | 16 +- apps/sim/executor/orchestrators/loop.ts | 47 ++- .../contracts/mothership-management-tools.ts | 2 +- apps/sim/lib/api/contracts/v2/workflows.ts | 6 +- apps/sim/lib/core/utils/http-methods.ts | 41 +++ apps/sim/lib/execution/isolated-vm.ts | 70 +++- .../application/execute-function.ts | 4 + .../lib/function-execution/execute-request.ts | 10 +- apps/sim/lib/internal/function/execute.ts | 6 +- .../application/dry-run.integration.ts | 313 ++++++++++++++++-- .../application/run-workflow-for-test.ts | 5 +- .../sim/lib/workflows/dry-run/side-effects.ts | 87 ++++- apps/sim/tools/http/request.ts | 11 + apps/sim/tools/index.ts | 19 +- apps/sim/tools/side-effects.test.ts | 94 ++++++ apps/sim/tools/side-effects.ts | 118 ++++++- apps/sim/tools/types.ts | 7 + .../src/commands/protocol/workflow-dir.ts | 2 +- .../commands/protocol/workflow-run-follow.ts | 32 +- 23 files changed, 822 insertions(+), 115 deletions(-) create mode 100644 apps/sim/lib/core/utils/http-methods.ts diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index edbee1d5ca8..5ea9f5bb906 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8534,7 +8534,7 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index d87fd3e7cf6..845ce2e2a95 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -851,7 +851,7 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 49c481780de..87ca6925643 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17265,7 +17265,7 @@ "type": "null" } ], - "description": "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain, or could not build the request once they were masked (such as a URL that is wholly a secret)." + "description": "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never header values; for code's `fetch`, header names, the URL capped with only query parameter names, the body capped, and the code's workspace and personal secrets masked, though a secret typed into the code itself is not), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain, or could not build the request once they were masked (such as a URL that is wholly a secret)." }, "returned": { "type": "object", @@ -17370,7 +17370,7 @@ "required": ["workflowId", "blockId", "block", "reason"], "additionalProperties": false }, - "description": "Blocks whose code ran for real, once per block: a Function block's code, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model wrote, which may make network calls the run cannot see." + "description": "Blocks whose code ran for real in a remote sandbox (shell, Python, JavaScript with imports, a selected sandbox or files), once per block: a Function block's code, a Condition's expressions, or code an Agent's model wrote, whose network calls the run cannot see. Code run in the isolate is not listed: its network writes are stubbed." }, "omitted": { "type": "object", @@ -17758,7 +17758,7 @@ "minLength": 1 }, "dry": { - "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", + "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls other than a GET, HEAD or OPTIONS without a method-override header, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes): JavaScript without imports sends its GET, HEAD and OPTIONS `fetch` calls (an API that writes on a GET is not stubbed), while any other request, or one carrying a method-override header, gets an empty 200 response (header `x-sim-dry-run: stubbed`) and is listed in `sideEffects.stubbed` as tool `function_execute`; code in a remote sandbox (shell, Python, JavaScript with imports, a selected sandbox or files) has network the run cannot see and is listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", "type": "boolean" }, "allowBlocks": { diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index b4d0189c191..c4cd785cec8 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -363,6 +363,32 @@ export interface AnsweredBlockCall extends SideEffectBlockSite { input: () => Promise | null> } +/** A network request code made in the isolate, decided before its host sends it. */ +interface CodeNetworkRequest { + /** The method as `fetch` sends it (`normalizeFetchMethod`); GET when the code named none. */ + method: string + /** The names of the headers it carries, never their values. */ + headerNames: string[] + /** + * What the request would send (method, capped origin and path with query parameter names, header + * names, a capped body; never a header value), redacted like a stubbed write's request; null + * when that cannot be vouched for. Built only when the request is recorded as stubbed. + */ + describe: () => Promise | null> +} + +/** How a run treats the network of one run of code, from {@link SideEffectPolicy.codeNetwork}. */ +export interface CodeNetworkPolicy { + /** + * Told before the code runs in a remote sandbox (shell, Python, JavaScript with imports, a + * selected sandbox or file system), whose network the run cannot see. Code that runs in the + * isolate instead has each network request decided by {@link onRequest}. + */ + ranInRemoteSandbox(): void + /** Whether the request is sent, or answered with an empty stubbed response instead. */ + onRequest(request: CodeNetworkRequest): Promise<'send' | 'stub'> +} + /** * How a run treats work that may change state outside it: a dry run, or a workflow test's * unmocked writes. Unlike {@link ExecutionTestHooks}, every child execution inherits it, including @@ -374,15 +400,16 @@ export interface AnsweredBlockCall extends SideEffectBlockSite { */ export interface SideEffectPolicy { /** - * Whether this write tool call is sent or answered with {@link stubWrite}. Records a sent call - * the run should report: an allowed block's write, or code that runs unchecked. + * Whether this write tool call is sent or answered with {@link stubWrite}. Records an allowed + * block's sent write. */ decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' /** - * Records code that ran for real, which can make network calls the run cannot see: code run - * through `function_execute`, or a While or Do While loop's condition. + * The network policy of code about to run at `site`: code run through `function_execute` (a + * Function block's, a Condition's expressions, or code an Agent's model wrote), or a While or Do + * While loop's condition. */ - ranCode(site: SideEffectSite): void + codeNetwork(site: SideEffectSite): CodeNetworkPolicy /** Records a write that was not sent and returns the placeholder output answering it. */ stubWrite(call: StubbedToolCall): Record /** Whether this block is answered with {@link answerBlock} instead of running its handler. */ diff --git a/apps/sim/executor/orchestrators/loop.test.ts b/apps/sim/executor/orchestrators/loop.test.ts index 8aa43144156..5144589e5cc 100644 --- a/apps/sim/executor/orchestrators/loop.test.ts +++ b/apps/sim/executor/orchestrators/loop.test.ts @@ -258,11 +258,9 @@ describe('LoopOrchestrator', () => { expect(shouldExecute).toBe(false) expect(scope.skippedAtStart).toBe(true) expect(state.setBlockOutput).not.toHaveBeenCalled() - expect(mockExecuteInIsolatedVM).toHaveBeenCalledWith( - expect.objectContaining({ - code: 'return Boolean(false)', - }) - ) + expect(mockExecuteInIsolatedVM.mock.calls[0]?.[0]).toMatchObject({ + code: 'return Boolean(false)', + }) }) it('escapes resolved strings without exposing rendered while conditions to logs', async () => { @@ -294,11 +292,9 @@ describe('LoopOrchestrator', () => { await orchestrator.evaluateInitialCondition(ctx, 'loop-1') - expect(mockExecuteInIsolatedVM).toHaveBeenCalledWith( - expect.objectContaining({ - code: `return Boolean(${JSON.stringify(resolvedSecret)})`, - }) - ) + expect(mockExecuteInIsolatedVM.mock.calls[0]?.[0]).toMatchObject({ + code: `return Boolean(${JSON.stringify(resolvedSecret)})`, + }) const logged = JSON.stringify([ ...mockLogger.debug.mock.calls, ...mockLogger.info.mock.calls, diff --git a/apps/sim/executor/orchestrators/loop.ts b/apps/sim/executor/orchestrators/loop.ts index ee12c24c1af..5450cb09a71 100644 --- a/apps/sim/executor/orchestrators/loop.ts +++ b/apps/sim/executor/orchestrators/loop.ts @@ -38,6 +38,7 @@ import { } from '@/executor/utils/subflow-node-id-codec' import { mergeSubflowSecretProvenance } from '@/executor/utils/subflow-secret-provenance' import type { VariableResolver } from '@/executor/variables/resolver' +import { codeNetworkFor } from '@/tools/side-effects' const logger = createLogger('LoopOrchestrator') @@ -813,24 +814,34 @@ export class LoopOrchestrator { }) const workflowLoopId = stripOuterBranchSuffix(loopId) - ctx.sideEffects?.ranCode({ - workflowId: ctx.workflowId, - blockId: workflowLoopId, - blockName: - ctx.workflow?.blocks.find((block) => block.id === workflowLoopId)?.metadata?.name ?? - workflowLoopId, - blockType: BlockType.LOOP, - }) - vmResult = await executeInIsolatedVM({ - code: `return Boolean(${evaluatedCondition})`, - params: {}, - envVars: {}, - contextVariables: {}, - timeoutMs: LOOP_CONDITION_TIMEOUT_MS, - requestId: generateRequestId(), - ownerKey: `user:${ctx.userId}`, - ownerWeight: 1, - }) + const codeNetwork = ctx.sideEffects + ? codeNetworkFor({ + executionContext: ctx, + site: { + workflowId: ctx.workflowId, + blockId: workflowLoopId, + blockName: + ctx.workflow?.blocks.find((block) => block.id === workflowLoopId)?.metadata?.name ?? + workflowLoopId, + blockType: BlockType.LOOP, + }, + params: {}, + registry: ctx.resolvedSecretTraceRegistry, + }) + : undefined + vmResult = await executeInIsolatedVM( + { + code: `return Boolean(${evaluatedCondition})`, + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: LOOP_CONDITION_TIMEOUT_MS, + requestId: generateRequestId(), + ownerKey: `user:${ctx.userId}`, + ownerWeight: 1, + }, + { fetchPolicy: codeNetwork?.fetchPolicy } + ) } catch (error) { return await this.failConditionEvaluation(ctx, loopId, scope, error) } diff --git a/apps/sim/lib/api/contracts/mothership-management-tools.ts b/apps/sim/lib/api/contracts/mothership-management-tools.ts index 9951634043e..282f26e8bfa 100644 --- a/apps/sim/lib/api/contracts/mothership-management-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-management-tools.ts @@ -25,7 +25,7 @@ export const managementToolContracts = [ route: 'sim', scope: 'all', description: - 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs (data only: no cost, tokens, model, providerTiming, toolCalls or field starting with _, which the run\u2019s trace and billing read); mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run (a custom block no mock answers is answered whole), while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', + 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs (data only: no cost, tokens, model, providerTiming, toolCalls or field starting with _, which the run\u2019s trace and billing read); mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run (a custom block no mock answers is answered whole), and a fetch a Function or Condition makes with any method but GET, HEAD or OPTIONS gets an empty 200 response, while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', inputSchema: mothershipTestsInputSchema, }, { diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 5dec74a85ee..3bcca7f573f 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1709,7 +1709,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .boolean() .optional() .describe( - "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." + "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls other than a GET, HEAD or OPTIONS without a method-override header, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes): JavaScript without imports sends its GET, HEAD and OPTIONS `fetch` calls (an API that writes on a GET is not stubbed), while any other request, or one carrying a method-override header, gets an empty 200 response (header `x-sim-dry-run: stubbed`) and is listed in `sideEffects.stubbed` as tool `function_execute`; code in a remote sandbox (shell, Python, JavaScript with imports, a selected sandbox or files) has network the run cannot see and is listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." ), allowBlocks: z .array(z.string().min(1, 'run.allowBlocks entries cannot be empty')) @@ -2009,7 +2009,7 @@ const v2RunSideEffectsSchema = z .record(z.string(), z.unknown().describe('Request field.')) .nullable() .describe( - "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain, or could not build the request once they were masked (such as a URL that is wholly a secret)." + "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never header values; for code's `fetch`, header names, the URL capped with only query parameter names, the body capped, and the code's workspace and personal secrets masked, though a secret typed into the code itself is not), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain, or could not build the request once they were masked (such as a URL that is wholly a secret)." ), returned: z .record(z.string(), z.unknown().describe('Placeholder field.')) @@ -2035,7 +2035,7 @@ const v2RunSideEffectsSchema = z }) ) .describe( - "Blocks whose code ran for real, once per block: a Function block's code, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model wrote, which may make network calls the run cannot see." + "Blocks whose code ran for real in a remote sandbox (shell, Python, JavaScript with imports, a selected sandbox or files), once per block: a Function block's code, a Condition's expressions, or code an Agent's model wrote, whose network calls the run cannot see. Code run in the isolate is not listed: its network writes are stubbed." ), omitted: z .object({ diff --git a/apps/sim/lib/core/utils/http-methods.ts b/apps/sim/lib/core/utils/http-methods.ts new file mode 100644 index 00000000000..65a41bc32dc --- /dev/null +++ b/apps/sim/lib/core/utils/http-methods.ts @@ -0,0 +1,41 @@ +/** Methods the fetch standard uppercases whatever their case; any other is sent as written. */ +const FETCH_NORMALIZED_METHODS: ReadonlySet = new Set([ + 'DELETE', + 'GET', + 'HEAD', + 'OPTIONS', + 'POST', + 'PUT', +]) + +/** Methods that ask for data rather than change it. */ +const READ_METHODS: ReadonlySet = new Set(['GET', 'HEAD', 'OPTIONS']) + +/** Headers some servers honor to run a different method than the one sent. */ +const METHOD_OVERRIDE_HEADERS: ReadonlySet = new Set([ + 'x-http-method-override', + 'x-http-method', + 'x-method-override', +]) + +/** + * A method as `fetch` sends it: DELETE, GET, HEAD, OPTIONS, POST and PUT uppercased in any case, + * any other method unchanged. + */ +export function normalizeFetchMethod(method: string): string { + const upper = method.toUpperCase() + return FETCH_NORMALIZED_METHODS.has(upper) ? upper : method +} + +/** + * Whether a request only reads: a GET, HEAD or OPTIONS (as {@link normalizeFetchMethod} sends it) + * that carries no method-override header. An API that changes state on a GET still counts as a + * read; nothing in the request can tell. + */ +export function isReadRequest(method: string, headerNames: Iterable): boolean { + if (!READ_METHODS.has(normalizeFetchMethod(method))) return false + for (const name of headerNames) { + if (METHOD_OVERRIDE_HEADERS.has(name.toLowerCase())) return false + } + return true +} diff --git a/apps/sim/lib/execution/isolated-vm.ts b/apps/sim/lib/execution/isolated-vm.ts index 8c7a1f7025d..83b93cf2506 100644 --- a/apps/sim/lib/execution/isolated-vm.ts +++ b/apps/sim/lib/execution/isolated-vm.ts @@ -12,8 +12,12 @@ import { getRedisClient } from '@/lib/core/config/redis' import { captureOutboundScope } from '@/lib/core/network/context.server' import { type SecureFetchOptions, + type SecureFetchResponse, + secureFetchWithPinnedIP, secureFetchWithValidation, + validateUrlWithDNS, } from '@/lib/core/security/input-validation.server' +import { normalizeFetchMethod } from '@/lib/core/utils/http-methods' import type { CodePlaceholderRuntimeBinding } from '@/lib/execution/code-placeholders' import { buildJavaScriptRuntimeBindingsSource } from '@/lib/execution/code-placeholders/javascript-runtime' import { MAX_ISOLATED_VM_BROKER_RESULT_JSON_CHARS } from '@/lib/execution/isolated-vm-limits' @@ -73,9 +77,28 @@ interface IsolatedVMTaskRequest { */ export type IsolatedVMBrokerHandler = (args: unknown, brokerId: number) => Promise +/** A network request isolate code made, as its host would send it. */ +interface IsolatedFetchRequest { + /** As sent ({@link normalizeFetchMethod}); GET when the code named none. */ + method: string + url: string + /** The names of the headers it carries, never their values. */ + headerNames: string[] + body: string | undefined +} + +/** + * Decides each network request isolate code makes before its host sends it: `stub` answers it + * with an empty 200 (`x-sim-dry-run: stubbed`) and sends nothing. Trusted host state, never + * anything user code or a request body sets. + */ +export type IsolatedFetchPolicy = (request: IsolatedFetchRequest) => Promise<'send' | 'stub'> + export interface IsolatedVMExecutionOptions { /** Broker name → handler. Must cover every broker listed in `request.task.brokers`. */ brokers?: Record + /** Decides each `fetch` the code makes; without one, every request is sent. */ + fetchPolicy?: IsolatedFetchPolicy /** Cancel the execution early. Broadcasts a cancellation error to the caller. */ signal?: AbortSignal } @@ -185,6 +208,7 @@ const DISTRIBUTED_LEASE_GRACE_MS = 30000 interface PendingExecution { runInOutboundScope: ReturnType + fetchPolicy?: IsolatedFetchPolicy resolve: (result: IsolatedVMExecutionResult) => void timeout: ReturnType ownerKey: string @@ -235,6 +259,7 @@ interface QueuedExecution { */ interface ExecutionState { runInOutboundScope: ReturnType + fetchPolicy?: IsolatedFetchPolicy cancelled: boolean queueId?: number workerId?: number @@ -339,7 +364,7 @@ function normalizeFetchOptions(options?: IsolatedFetchOptions): SecureFetchOptio } if (typeof options.method === 'string' && options.method.length > 0) { - normalized.method = options.method + normalized.method = normalizeFetchMethod(options.method) } if ( @@ -389,11 +414,27 @@ function normalizeFetchOptions(options?: IsolatedFetchOptions): SecureFetchOptio return normalized } +/** What isolate code gets for a request its {@link IsolatedFetchPolicy} stubbed. */ +const STUBBED_FETCH_RESPONSE = JSON.stringify({ + ok: true, + status: 200, + statusText: 'OK', + body: '{}', + bodyTruncated: false, + headers: { 'content-type': 'application/json', 'x-sim-dry-run': 'stubbed' }, +}) + +/** + * Sends one `fetch` of isolate code. With a policy, the target is validated before the policy + * decides, so a request it stubs fails where a live one would (a URL too long, invalid, or refused + * by the egress policy), and a request it sends goes to the IP that validation resolved. + */ async function secureFetch( requestId: string, url: string, options: IsolatedFetchOptions | undefined, - signal: AbortSignal + signal: AbortSignal, + fetchPolicy: IsolatedFetchPolicy | undefined ): Promise { if (url.length > MAX_FETCH_URL_LENGTH) { return JSON.stringify({ @@ -402,11 +443,22 @@ async function secureFetch( } try { - const response = await secureFetchWithValidation( - url, - { ...normalizeFetchOptions(options), signal }, - 'fetchUrl' - ) + const fetchOptions = { ...normalizeFetchOptions(options), signal } + let response: SecureFetchResponse + if (fetchPolicy) { + const target = await validateUrlWithDNS(url, 'fetchUrl', fetchOptions.profile, { signal }) + if (!target.isValid) return JSON.stringify({ error: target.error }) + const decision = await fetchPolicy({ + method: fetchOptions.method ?? 'GET', + url, + headerNames: Object.keys(fetchOptions.headers ?? {}), + body: typeof fetchOptions.body === 'string' ? fetchOptions.body : undefined, + }) + if (decision === 'stub') return STUBBED_FETCH_RESPONSE + response = await secureFetchWithPinnedIP(url, target.resolvedIP, fetchOptions) + } else { + response = await secureFetchWithValidation(url, fetchOptions, 'fetchUrl') + } const bodyResult = truncateString(await response.text(), MAX_FETCH_RESPONSE_CHARS) const headers: Record = {} for (const [key, value] of response.headers) { @@ -931,7 +983,7 @@ function handleWorkerMessage(workerId: number, message: unknown) { AbortSignal.timeout(pending.hostTimeoutMs), ]) pending - .runInOutboundScope(() => secureFetch(requestId, url, options, signal)) + .runInOutboundScope(() => secureFetch(requestId, url, options, signal, pending.fetchPolicy)) .then(sendFetchResponse) .catch((err) => { sendFetchResponse(JSON.stringify({ error: getErrorMessage(err, 'Fetch failed') })) @@ -1357,6 +1409,7 @@ function dispatchToWorker( workerInfo.pendingExecutions.set(execId, { runInOutboundScope: state.runInOutboundScope, + fetchPolicy: state.fetchPolicy, resolve, timeout, ownerKey: ownerState.ownerKey, @@ -1671,6 +1724,7 @@ export async function executeInIsolatedVM( const state: ExecutionState = { cancelled: false, runInOutboundScope: captureOutboundScope(), + fetchPolicy: options?.fetchPolicy, unsentRedispatches: 0, } diff --git a/apps/sim/lib/function-execution/application/execute-function.ts b/apps/sim/lib/function-execution/application/execute-function.ts index 2e5fbf3b713..cdbb43a1dae 100644 --- a/apps/sim/lib/function-execution/application/execute-function.ts +++ b/apps/sim/lib/function-execution/application/execute-function.ts @@ -6,6 +6,7 @@ import { functionExecutionDelegationPolicy } from '@/lib/function-execution/appl import { functionExecutionOperations } from '@/lib/function-execution/application/operations' import { resolveActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' +import type { CodeNetwork } from '@/tools/side-effects' export interface ExecuteFunctionInput { workspaceId: string @@ -15,6 +16,8 @@ export interface ExecuteFunctionInput { sandboxProfile?: 'mothership' /** Trusted in-process provenance state; never accepted from the Function request body. */ resolvedSecretTraceRegistry?: ResolvedSecretTraceRegistry + /** The run's side-effect policy for this code; trusted in-process state like the registry. */ + codeNetwork?: CodeNetwork } /** @@ -65,6 +68,7 @@ export const executeFunction = defineAuthorizedWorkspaceUseCase({ : {}), ...(subject?.kind === 'sim_user' ? { fileAccessUserId: subject.userId } : {}), ...(input.sandboxProfile ? { sandboxProfile: input.sandboxProfile } : {}), + ...(input.codeNetwork ? { codeNetwork: input.codeNetwork } : {}), } ) }, diff --git a/apps/sim/lib/function-execution/execute-request.ts b/apps/sim/lib/function-execution/execute-request.ts index 0168f85154b..537e58adae0 100644 --- a/apps/sim/lib/function-execution/execute-request.ts +++ b/apps/sim/lib/function-execution/execute-request.ts @@ -152,6 +152,7 @@ import { type ResolvedSecretTraceProvenanceV1, ResolvedSecretTraceRegistry, } from '@/executor/utils/resolved-secret-trace-registry' +import type { CodeNetwork } from '@/tools/side-effects' const TEXT_OUTPUT_MIME_TYPES = new Set(Object.values(FORMAT_TO_CONTENT_TYPE)) @@ -2259,6 +2260,8 @@ export interface TrustedFunctionExecutionAuth { principal: DelegatedPrincipal | OrganizationDelegatedPrincipal sandboxProfile?: 'mothership' resolvedSecretTraceRegistry?: ResolvedSecretTraceRegistry + /** The run's side-effect policy for this code: told of a remote sandbox, deciding each isolate `fetch`. */ + codeNetwork?: CodeNetwork } /** Executes the Function protocol after the application operation authorizes its principal. */ @@ -2750,6 +2753,7 @@ export async function executeFunctionRequest( ) } const { sandboxFiles: userFileMounts, manifest: mountManifest } = resolvedMounts + if (useRemoteSandbox || lang === CodeLanguage.Shell) auth.codeNetwork?.ranInRemoteSandbox() const activeRouteContext = routeContext const mothershipSession = admittedSession ? { @@ -3284,7 +3288,11 @@ export async function executeFunctionRequest( ownerKey: `user:${auth.attributedUserId}`, ownerWeight: 1, }, - { brokers: createFunctionRuntimeBrokers(routeContext), signal: executionSignal } + { + brokers: createFunctionRuntimeBrokers(routeContext), + signal: executionSignal, + fetchPolicy: auth.codeNetwork?.fetchPolicy, + } ) const executionTime = Date.now() - startTime diff --git a/apps/sim/lib/internal/function/execute.ts b/apps/sim/lib/internal/function/execute.ts index 81000f13976..c37e0e02eda 100644 --- a/apps/sim/lib/internal/function/execute.ts +++ b/apps/sim/lib/internal/function/execute.ts @@ -9,6 +9,7 @@ import { executeFunction } from '@/lib/function-execution/application/execute-fu import { createExecutorPrincipalFromExecutionContext } from '@/lib/internal/principals/executor' import type { InternalToolOperationContext } from '@/lib/internal/tool-operations/types' import { createTrustedOrganizationCopilotPrincipal } from '@/lib/mothership/auth/application-delegation' +import type { CodeNetwork } from '@/tools/side-effects' export type TrustedFunctionToolExecutionContext = InternalToolOperationContext @@ -19,11 +20,13 @@ export interface ExecuteFunctionToolInput { requestId: string signal?: AbortSignal sandboxProfile?: InternalSandboxProfile + /** The run's side-effect policy for this code; trusted in-process state, never from the body. */ + codeNetwork?: CodeNetwork } /** Executes a Function tool with authority taken only from trusted server execution context. */ export async function executeFunctionTool(input: ExecuteFunctionToolInput): Promise { - const { body, context, headers, requestId, signal, sandboxProfile } = input + const { body, context, headers, requestId, signal, sandboxProfile, codeNetwork } = input const issuedAt = new Date() const serializedDeadline = serializeExecutionDeadlineHeader(signal) const requestedTimeout = @@ -112,6 +115,7 @@ export async function executeFunctionTool(input: ExecuteFunctionToolInput): Prom : {}), ...(signal ? { signal } : {}), ...(sandboxProfile ? { sandboxProfile } : {}), + ...(codeNetwork ? { codeNetwork } : {}), }, }) } diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index 4c020bcc989..ad1d4eacbf7 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -7,14 +7,16 @@ * count. An MCP write is authorized before it is answered, and its check leaves the server's health * as it found it. An allowed block writes for real while reads run for real; a child workflow's * writes, an Agent's included, stay stubbed; custom and Wait blocks are answered whole; code runs - * and is listed unchecked, a Condition's expressions and a While loop's condition included; a - * mocked block steers a branch; a failed dry run keeps its side effects and is the source only of + * (a Condition's expressions and a While loop's condition included) and its isolate `fetch` writes + * are stubbed; a mocked block steers a branch; a failed dry run keeps its side effects and is the source only of * another dry run. A test run is never the source of a run that sends its writes (the v2 use case, * Copilot and the editor route alike) and is never resumed; a mock, a dry run's or a workflow * test's, is data that never controls the run, sets what it is billed or replaces a locked block; a * rerun record keeps only the ids of mocked blocks, while the log shows a mocked output redacted * like any other. Model calls are answered by a simulated Anthropic API. */ +import { createServer, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' import { db } from '@sim/db' import { agentMemoryTurn, @@ -56,6 +58,8 @@ const { subscriberRuns, session } = vi.hoisted(() => { process.env.CUSTOM_BLOCKS_ENABLED = 'true' /** Agents keep durable turn history (rich history and the memory retrieval tool). */ process.env.AGENT_MEMORY_HISTORY = 'true' + /** Code and HTTP blocks reach the suite's local server, which records what arrives. */ + process.env.EGRESS_ALLOWED_IP_RANGES = '127.0.0.1/32' return { subscriberRuns: { runIds: [] as string[] }, /** The browser session the editor route sees; none unless a test signs in. */ @@ -110,6 +114,8 @@ const workspaceId = generateId() const SECRET = `dry-secret-${generateId()}` const UNREFERENCED_SECRET = `unreferenced-${generateId()}` const SECRET_URL = `http://dry-run.invalid/hook/${generateId()}` +/** A secret whose variable name matches no credential pattern. */ +const HOOK_PATH = `hook-path-${generateId()}` const API_KEY = `sk-sim-fixture-${generateId()}` const principal = createDelegatedPrincipal({ subjectUserId: ownerId, @@ -428,6 +434,7 @@ beforeAll(async () => { DRY_SECRET: (await encryptSecret(SECRET)).encrypted, UNREFERENCED_SECRET: (await encryptSecret(UNREFERENCED_SECRET)).encrypted, DRY_SECRET_URL: (await encryptSecret(SECRET_URL)).encrypted, + HOOK_PATH: (await encryptSecret(HOOK_PATH)).encrypted, }, }) await db.insert(apiKey).values({ @@ -1101,7 +1108,7 @@ describe('a dry run', () => { } }) - it('runs code for real, listing a Function block and a Condition unchecked once each', async () => { + it('runs code for real, listing neither a Function block nor a Condition that sends nothing', async () => { const tableId = await createTable() const gate = condition('gate', ' > 50') const branching = graph( @@ -1125,21 +1132,10 @@ describe('a dry run', () => { expect(result.status, JSON.stringify(result.error)).toBe('completed') expect(result.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['high']) - expect(result.sideEffects?.unchecked).toEqual([ - expect.objectContaining({ - blockId: branching.idOf('score'), - block: 'score', - reason: expect.stringContaining('Function block code ran'), - }), - expect.objectContaining({ - blockId: branching.idOf('gate'), - block: 'gate', - reason: expect.stringContaining('Condition expressions ran'), - }), - ]) + expect(result.sideEffects?.unchecked).toEqual([]) }) - it('lists a While loop’s condition unchecked once, however often it runs', async () => { + it('runs a While loop’s condition for real without listing it unchecked', async () => { const repeat = block('repeat', 'loop') repeat.data = { loopType: 'while', whileCondition: ' < 3' } const tick = block('tick', 'function', { language: 'javascript', code: 'return 1' }) @@ -1156,14 +1152,7 @@ describe('a dry run', () => { const result = await run(workflowId, { dry: true }) expect(result.status, JSON.stringify(result.error)).toBe('completed') - expect(result.sideEffects?.unchecked).toEqual([ - expect.objectContaining({ - blockId: looping.idOf('repeat'), - block: 'repeat', - reason: expect.stringContaining('While or Do While loop condition ran'), - }), - expect.objectContaining({ blockId: looping.idOf('tick'), block: 'tick' }), - ]) + expect(result.sideEffects?.unchecked).toEqual([]) }) it('takes the branch a mocked block steers it to, and refuses mocks outside a dry run', async () => { @@ -1686,3 +1675,279 @@ describe('a dry run’s mocks', () => { expect(JSON.stringify(read)).not.toContain(secret) }) }) + +/** A local server that records each request that reaches it, and answers each with `{ ok: true }`. */ +const server = { + instance: null as Server | null, + url: '', + arrivals: [] as Array<{ method: string; path: string }>, +} + +/** What reached the local server under `path`'s prefix, as `METHOD /path`. */ +function arrivalsUnder(prefix: string): string[] { + return server.arrivals + .filter((arrival) => arrival.path.startsWith(prefix)) + .map((arrival) => `${arrival.method} ${arrival.path}`) +} + +/** A workflow of one Function block named `code` running `source`. */ +async function codeWorkflow(source: string) { + const fixture = graph( + [ + block('start', 'start_trigger'), + block('code', 'function', { language: 'javascript', code: source }), + ], + [['start', 'code']] + ) + return { workflowId: await saveWorkflow(fixture.state), idOf: fixture.idOf } +} + +describe('a dry run’s code network', () => { + beforeAll(async () => { + const instance = createServer((request, response) => { + request.resume() + server.arrivals.push({ method: request.method ?? '', path: request.url ?? '' }) + response.writeHead(200, { 'content-type': 'application/json' }) + response.end(JSON.stringify({ ok: true })) + }) + await new Promise((resolve) => instance.listen(0, '127.0.0.1', resolve)) + server.instance = instance + server.url = `http://127.0.0.1:${(instance.address() as AddressInfo).port}` + }) + + afterAll(async () => { + const instance = server.instance + if (instance) await new Promise((resolve) => instance.close(() => resolve())) + }) + + it('never sends a POST a Function block makes, and records it without its query values or secrets', async () => { + const prefix = `/${generateId()}` + const { workflowId, idOf } = await codeWorkflow( + `const res = await fetch('${server.url}${prefix}/hook?key={{DRY_SECRET}}&page=2', { method: 'POST', headers: { authorization: 'Bearer {{DRY_SECRET}}' }, body: JSON.stringify({ note: 'key={{DRY_SECRET}}' }) }) +return { status: res.status, body: await res.json(), stubbed: res.headers.get('x-sim-dry-run') }` + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([]) + expect(result.output).toMatchObject({ result: { status: 200, body: {}, stubbed: 'stubbed' } }) + expect(result.sideEffects?.stubbed).toEqual([ + expect.objectContaining({ + blockId: idOf('code'), + block: 'code', + tool: 'function_execute', + request: { + method: 'POST', + url: `${server.url}${prefix}/hook?key&page`, + headers: ['authorization'], + body: { note: 'key=[REDACTED]' }, + }, + returned: { status: 200, body: {} }, + }), + ]) + expect(result.sideEffects?.unchecked).toEqual([]) + expect(JSON.stringify(result.sideEffects)).not.toContain(SECRET) + }) + + it('masks a secret the code compiles in from a variable no credential pattern names', async () => { + const prefix = `/${generateId()}` + const { workflowId } = await codeWorkflow( + `const res = await fetch('${server.url}${prefix}/{{HOOK_PATH}}', { method: 'POST', body: JSON.stringify({ ref: '{{HOOK_PATH}}' }) }) +return res.status` + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([]) + expect(result.sideEffects?.stubbed).toHaveLength(1) + expect(JSON.stringify(result.sideEffects)).not.toContain(HOOK_PATH) + }) + + it('stubs a GET that carries a method-override header, recording only the header’s name', async () => { + const prefix = `/${generateId()}` + const { workflowId } = await codeWorkflow( + `const res = await fetch('${server.url}${prefix}', { headers: { 'X-HTTP-Method-Override': 'DELETE' } }) +return res.status` + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([]) + expect(result.sideEffects?.stubbed.map((entry) => entry.request)).toEqual([ + { method: 'GET', url: `${server.url}${prefix}`, headers: ['X-HTTP-Method-Override'] }, + ]) + }) + + it('fails a write the egress policy refuses, as a live run would, and records nothing', async () => { + const { workflowId } = await codeWorkflow( + `try { + await fetch('http://10.255.255.1/hook', { method: 'POST' }) + return 'answered' +} catch (error) { + return error.message +}` + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(JSON.stringify(result.output)).not.toContain('answered') + expect(result.sideEffects?.stubbed).toEqual([]) + }) + + it('stubs a write a While loop’s condition makes, recorded under the loop', async () => { + const prefix = `/${generateId()}` + const repeat = block('repeat', 'loop') + repeat.data = { + loopType: 'while', + whileCondition: `(await fetch('${server.url}${prefix}', { method: 'POST' })).status === 500`, + } + const tick = block('tick', 'function', { language: 'javascript', code: 'return 1' }) + tick.data = { parentId: repeat.id, extent: 'parent' } + const looping = graph( + [block('start', 'start_trigger'), repeat, tick], + [ + ['start', 'repeat'], + ['repeat', 'tick', 'loop-start-source'], + ] + ) + const workflowId = await saveWorkflow(looping.state) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([]) + expect(result.sideEffects?.stubbed.map((entry) => [entry.block, entry.tool])).toEqual([ + ['repeat', 'function_execute'], + ]) + }) + + it('stubs a write whose method is written in lowercase', async () => { + const prefix = `/${generateId()}` + const { workflowId } = await codeWorkflow( + `const res = await fetch('${server.url}${prefix}', { method: 'post' }) +return res.status` + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([]) + expect(result.sideEffects?.stubbed.map((entry) => toRecord(entry.request).method)).toEqual([ + 'POST', + ]) + }) + + it('sends a request whose method is not a string, as the GET it is sent as', async () => { + const prefix = `/${generateId()}` + const { workflowId } = await codeWorkflow( + `const res = await fetch('${server.url}${prefix}', { method: 1 }) +return await res.json()` + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([`GET ${prefix}`]) + expect(result.sideEffects?.stubbed).toEqual([]) + }) + + it('stubs a write the code never awaits, and sends the read it awaits after it', async () => { + const prefix = `/${generateId()}` + const { workflowId } = await codeWorkflow( + `fetch('${server.url}${prefix}/write', { method: 'PUT', body: 'x' }) +const res = await fetch('${server.url}${prefix}/read') +return await res.json()` + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([`GET ${prefix}/read`]) + expect(result.sideEffects?.stubbed.map((entry) => toRecord(entry.request).url)).toEqual([ + `${server.url}${prefix}/write`, + ]) + }) + + it('sends every request of an allowed block, recording it allowed once', async () => { + const prefix = `/${generateId()}` + const { workflowId, idOf } = await codeWorkflow( + `await fetch('${server.url}${prefix}/a', { method: 'POST' }) +await fetch('${server.url}${prefix}/b', { method: 'DELETE' }) +return 1` + ) + + const result = await run(workflowId, { dry: true, allowBlocks: ['code'] }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([`POST ${prefix}/a`, `DELETE ${prefix}/b`]) + expect(result.sideEffects?.allowed).toEqual([ + expect.objectContaining({ blockId: idOf('code'), tool: 'function_execute' }), + ]) + expect(result.sideEffects?.stubbed).toEqual([]) + }) + + it('records an allowed block that only reads as nothing allowed', async () => { + const prefix = `/${generateId()}` + const { workflowId } = await codeWorkflow( + `const res = await fetch('${server.url}${prefix}') +return await res.json()` + ) + + const result = await run(workflowId, { dry: true, allowBlocks: ['code'] }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([`GET ${prefix}`]) + expect(result.sideEffects?.allowed).toEqual([]) + }) + + it('tells a Function block that failed on its stubbed writes how to send them', async () => { + const prefix = `/${generateId()}` + const { workflowId } = await codeWorkflow( + `const res = await fetch('${server.url}${prefix}', { method: 'POST' }) +const created = await res.json() +return created.id.toString()` + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status).toBe('failed') + expect(JSON.stringify(result.error)).toContain( + "1 network write this code made got an empty stubbed response; --allow 'code' sends them" + ) + }) + + it('sends an API block’s GET, while its POST and a GET overriding its method stay stubbed', async () => { + const prefix = `/${generateId()}` + const fixture = graph( + [ + block('start', 'start_trigger'), + block('read', 'api', { url: `${server.url}${prefix}/read`, method: 'GET' }), + block('write', 'api', { url: `${server.url}${prefix}/write`, method: 'POST' }), + block('override', 'api', { + url: `${server.url}${prefix}/override`, + method: 'GET', + headers: [{ cells: { Key: 'X-HTTP-Method-Override', Value: 'PATCH' } }], + }), + ], + [ + ['start', 'read'], + ['read', 'write'], + ['write', 'override'], + ] + ) + const workflowId = await saveWorkflow(fixture.state) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([`GET ${prefix}/read`]) + expect(result.sideEffects?.stubbed.map((entry) => [entry.block, entry.tool])).toEqual([ + ['write', 'http_request'], + ['override', 'http_request'], + ]) + }) +}) diff --git a/apps/sim/lib/workflows/application/run-workflow-for-test.ts b/apps/sim/lib/workflows/application/run-workflow-for-test.ts index 16d26b389ab..aa557579557 100644 --- a/apps/sim/lib/workflows/application/run-workflow-for-test.ts +++ b/apps/sim/lib/workflows/application/run-workflow-for-test.ts @@ -47,8 +47,9 @@ export interface RunWorkflowForTestInput { * One workflow run inside a workflow test: the workflow's single runnable trigger, the * test's input, and its mocks installed as executor test hooks. A write the test does not mock * is not sent: as in a dry run, it is answered with a placeholder shaped like the tool's output, - * and so is a Human in the loop or Wait block, so the run never pauses. Billed and logged like any - * run, under the `test` trigger. + * a `fetch` the workflow's code makes with any method but GET, HEAD or OPTIONS gets an empty 200, + * and a Human in the loop or Wait block is answered whole, so the run never pauses. Billed and + * logged like any run, under the `test` trigger. * * A step of the `workflow_tests.run` operation, which authorized the caller's write access to * the workspace before any test ran; nothing else may call it. Each nested run is not diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index dc5f75fbb71..b80d8e1d31d 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -1,8 +1,11 @@ +import { createLogger } from '@sim/logger' +import { isReadRequest } from '@/lib/core/utils/http-methods' import { sampleBlockOutput, sampleToolOutput } from '@/lib/workflows/dry-run/samples' import { isCustomBlockType } from '@/blocks/custom/build-config' import { BlockType, HUMAN_IN_THE_LOOP_BLOCK_TYPES } from '@/executor/constants' import type { AnsweredBlockCall, + CodeNetworkPolicy, DryRunOptions, SideEffectBlockSite, SideEffectPolicy, @@ -11,9 +14,14 @@ import type { } from '@/executor/execution/types' import type { NormalizedBlockOutput } from '@/executor/types' +const logger = createLogger('DryRunSideEffects') + /** Each list keeps at most this many entries; `omitted` counts the rest per list. */ const MAX_RECORDED = 50 +/** The tool a stubbed or allowed network request of code is recorded under. */ +const CODE_TOOL_ID = 'function_execute' + /** Blocks whose handlers change state outside the tool seam, so a policy answers them whole. */ const SELF_DIRECTED_BLOCK_TYPES: ReadonlySet = new Set([BlockType.MOTHERSHIP, BlockType.PI]) @@ -59,7 +67,7 @@ interface AllowedSideEffect extends RecordedSite { tool: string | null } -/** Code that ran for real whose effects the run cannot see. */ +/** Code that ran for real in a remote sandbox, whose network the run cannot see. */ interface UncheckedSideEffect extends RecordedSite { reason: string } @@ -77,19 +85,32 @@ function recordedSite(site: SideEffectSite): RecordedSite { return { workflowId: site.workflowId, blockId: site.blockId, block: site.blockName } } -/** Why code the run cannot see ran for real, named for the block that ran it. */ +/** Why code ran where the run cannot see its network, named for the block that ran it. */ function uncheckedCodeReason(blockType: string | null): string { + const unseen = 'ran for real in a remote sandbox, whose network calls a dry run cannot stub' switch (blockType) { case BlockType.FUNCTION: - return 'Function block code ran for real; network calls it makes are not stubbed' + return `Function block code ${unseen}` case BlockType.AGENT: - return 'Code the Agent’s model wrote ran for real; network calls it makes are not stubbed' + return `Code the Agent’s model wrote ${unseen}` case BlockType.CONDITION: - return 'Condition expressions ran for real; network calls they make are not stubbed' - case BlockType.LOOP: - return 'While or Do While loop condition ran for real; network calls it makes are not stubbed' + return `Condition expressions ${unseen}` default: - return 'Code ran for real; network calls it makes are not stubbed' + return `Code ${unseen}` + } +} + +/** A stubbed request's description, or null when building it fails: the request stays stubbed. */ +async function describeOrNull( + describe: () => Promise | null> +): Promise | null> { + try { + return await describe() + } catch (error) { + logger.warn('Could not describe a stubbed request of code; recording none', { + errorName: error instanceof Error ? error.name : 'UnknownError', + }) + return null } } @@ -102,6 +123,11 @@ class RecordedList { omitted = 0 private readonly keys = new Set() + /** Whether the next entry would only be counted. */ + get full(): boolean { + return this.entries.length >= MAX_RECORDED + } + add(entry: T, key?: string): void { if (key !== undefined) { if (this.keys.has(key)) return @@ -117,7 +143,9 @@ class RecordedList { * write tool call is answered with a placeholder shaped like the tool's output, holding what the * request determines where the tool declares it (`dryRunOutput`), and recorded with * the request it would have sent, except an allowed block's, which are sent and recorded once per - * block and tool. Reads always run, and code runs and is listed unchecked. Custom blocks and + * block and tool. Reads always run. Code runs too: in the isolate its reads (`isReadRequest`) are + * sent and any other request is answered with an empty 200 and recorded like a write, while code + * in a remote sandbox, whose network the run cannot see, is listed unchecked. Custom blocks and * {@link PAUSING_BLOCK_TYPES} are answered whole, as is a block that acts outside the tool seam * unless it is allowed, and `blockMocks` answers its blocks with fixed outputs. Allowed and mocked * blocks are blocks of the workflow the run started, never of a child it calls, and an allowed @@ -165,16 +193,14 @@ export class WriteStubPolicy implements SideEffectPolicy { * like the block on a canvas; `workflow_executor` runs a child workflow, which inherits the * policy and decides its own writes, so it is sent; and `function_execute` runs the workflow's * own code (a Function block's, a Condition's expressions, or code an Agent's model wrote), - * which is sent and listed by {@link ranCode}. + * which is sent, its network decided by {@link codeNetwork}. */ decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' { switch (call.toolId) { case 'deployed_block_executor': return 'stub' case 'workflow_executor': - return 'send' - case 'function_execute': - this.ranCode(call) + case CODE_TOOL_ID: return 'send' } if (!this.allows(call)) return 'stub' @@ -185,11 +211,36 @@ export class WriteStubPolicy implements SideEffectPolicy { return 'send' } - ranCode(site: SideEffectSite): void { - this.unchecked.add( - { ...recordedSite(site), reason: uncheckedCodeReason(site.blockType) }, - `${site.workflowId}:${site.blockId}` - ) + codeNetwork(site: SideEffectSite): CodeNetworkPolicy { + const key = `${site.workflowId}:${site.blockId}` + if (this.allows(site)) { + const recordAllowed = () => + this.allowed.add({ ...recordedSite(site), tool: CODE_TOOL_ID }, `${key}:${CODE_TOOL_ID}`) + return { + ranInRemoteSandbox: recordAllowed, + onRequest: async (request) => { + if (!isReadRequest(request.method, request.headerNames)) recordAllowed() + return 'send' + }, + } + } + return { + ranInRemoteSandbox: () => + this.unchecked.add( + { ...recordedSite(site), reason: uncheckedCodeReason(site.blockType) }, + key + ), + onRequest: async (request) => { + if (isReadRequest(request.method, request.headerNames)) return 'send' + this.stubbed.add({ + ...recordedSite(site), + tool: CODE_TOOL_ID, + request: this.stubbed.full ? null : await describeOrNull(request.describe), + returned: { status: 200, body: {} }, + }) + return 'stub' + }, + } } stubWrite(call: StubbedToolCall): Record { diff --git a/apps/sim/tools/http/request.ts b/apps/sim/tools/http/request.ts index d24c0b8d7a8..5f8db384fe6 100644 --- a/apps/sim/tools/http/request.ts +++ b/apps/sim/tools/http/request.ts @@ -1,3 +1,4 @@ +import { isReadRequest } from '@/lib/core/utils/http-methods' import { readResponseTextWithLimit } from '@/lib/core/utils/stream-limits' import type { RequestParams, RequestResponse } from '@/tools/http/types' import { @@ -104,6 +105,16 @@ export const requestTool: ToolConfig = { }, }, + readsWhen: (params) => { + const method: unknown = params.method || 'GET' + if (typeof method !== 'string') return false + try { + return isReadRequest(method, Object.keys(transformTable(params.headers || null))) + } catch { + return false + } + }, + timeoutParamIsDeadline: true, request: { diff --git a/apps/sim/tools/index.ts b/apps/sim/tools/index.ts index b71740af5b1..d028e6bd459 100644 --- a/apps/sim/tools/index.ts +++ b/apps/sim/tools/index.ts @@ -138,6 +138,8 @@ import { AWS_CREDENTIAL_OAUTH, AWS_SESSION_SIGNED_TOOL_IDS } from '@/tools/share import { answerUnsentMcpWrite, answerUnsentWrite, + type CodeNetwork, + codeNetworkFor, describeMcpToolRequest, describeToolRequest, unsentWriteFor, @@ -2017,7 +2019,7 @@ async function executeToolImplementation( * spends no rate-limit slot. */ const unsentWrite = - tool.effect !== 'read' + tool.effect !== 'read' && !(executionContext?.sideEffects && tool.readsWhen?.(contextParams)) ? unsentWriteFor({ toolId: normalizedToolId, params: contextParams, executionContext }) : null @@ -2396,6 +2398,14 @@ async function executeToolImplementation( } if (tool.operation) { + const codeNetwork = + normalizedToolId === 'function_execute' + ? codeNetworkFor({ + executionContext, + params: contextParams, + registry: resolvedSecretTraceRegistry, + }) + : undefined const result = await executeDeclaredInternalOperation({ toolId: normalizedToolId, tool, @@ -2408,7 +2418,10 @@ async function executeToolImplementation( internalSandboxProfile, refreshCredential, authorizedServiceAccountCredential, + codeNetwork, }).catch(async (error: unknown) => { + const hint = codeNetwork?.failureHint() + if (hint && error instanceof Error) error.message = `${error.message} ${hint}` throw authorizedServiceAccountCredential ? await explainExpiredServiceAccountToken( error, @@ -2858,6 +2871,8 @@ interface ExecuteDeclaredInternalOperationInput { refreshCredential?: (signal: AbortSignal) => Promise /** Service-account credential the executor authorized for this call (never from tool params). */ authorizedServiceAccountCredential?: AuthorizedServiceAccountCredential + /** The run's side-effect policy for a Function's code (never from tool params). */ + codeNetwork?: CodeNetwork } function isFunctionExecuteBody(value: unknown): value is FunctionExecuteBody { @@ -2914,6 +2929,7 @@ async function executeDeclaredInternalOperation({ internalSandboxProfile, refreshCredential, authorizedServiceAccountCredential, + codeNetwork, }: ExecuteDeclaredInternalOperationInput): Promise { const organizationScratch = toolId === 'function_execute' && @@ -3034,6 +3050,7 @@ async function executeDeclaredInternalOperation({ requestId, ...(signal ? { signal } : {}), ...(internalSandboxProfile ? { sandboxProfile: internalSandboxProfile } : {}), + ...(codeNetwork ? { codeNetwork } : {}), }) } else { const handler = await getInternalToolOperationHandler(toolId) diff --git a/apps/sim/tools/side-effects.test.ts b/apps/sim/tools/side-effects.test.ts index 90b5b218054..05b914f502d 100644 --- a/apps/sim/tools/side-effects.test.ts +++ b/apps/sim/tools/side-effects.test.ts @@ -11,6 +11,7 @@ import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-tr import { answerUnsentMcpWrite, answerUnsentWrite, + codeNetworkFor, describeMcpToolRequest, unsentWriteFor, } from '@/tools/side-effects' @@ -162,3 +163,96 @@ describe('a write a dry run does not send', () => { } ) }) + +/** The dry-run policy's network for code run by block `blockId`, given `params`. */ +function codeNetwork(blockId: string, params: Record = {}) { + const policy = new WriteStubPolicy({ workflowId: 'wf-1' }) + const network = codeNetworkFor({ + executionContext: { + ...createExecutionContext({ workflowId: 'wf-1' }), + sideEffects: policy, + } as ExecutionContext, + params: { ...params, _context: { blockId } }, + registry: new ResolvedSecretTraceRegistry(), + }) + if (!network) throw new Error('The run has no side-effect policy') + return { network, policy } +} + +describe('code a dry run runs', () => { + it('is listed unchecked when it runs in a remote sandbox, whose network it cannot see', () => { + const { network, policy } = codeNetwork('python') + + network.ranInRemoteSandbox() + + expect(policy.summary().unchecked).toEqual([ + expect.objectContaining({ + blockId: 'python', + reason: expect.stringContaining('remote sandbox'), + }), + ]) + }) + + it('records a long stubbed body masked before it is capped, so no secret is cut in two', async () => { + const secret = 'code-secret-0123456789' + const { network, policy } = codeNetwork('code', { apiKey: secret }) + const body = `${'a'.repeat(4090)}${secret}` + + const decision = await network.fetchPolicy({ + method: 'POST', + url: 'https://hook.example/x', + headerNames: [], + body, + }) + + expect(decision).toBe('stub') + const [{ request }] = policy.summary().stubbed + expect(String(request?.body)).toContain(`${'a'.repeat(4090)}[REDA`) + expect(String(request?.body)).not.toContain(secret.slice(0, 6)) + }) + + it('still stubs a request whose description cannot be built, recording no request', async () => { + const policy = new WriteStubPolicy({ workflowId: 'wf-1' }) + const code = policy.codeNetwork({ + workflowId: 'wf-1', + blockId: 'code', + blockName: 'code', + blockType: 'function', + }) + + const decision = await code.onRequest({ + method: 'POST', + headerNames: [], + describe: async () => { + throw new Error('redaction failed') + }, + }) + + expect(decision).toBe('stub') + expect(policy.summary().stubbed.map((entry) => entry.request)).toEqual([null]) + }) + + it('stops describing stubbed requests once the list is full, counting the rest', async () => { + const policy = new WriteStubPolicy({ workflowId: 'wf-1' }) + const code = policy.codeNetwork({ + workflowId: 'wf-1', + blockId: 'code', + blockName: 'code', + blockType: 'function', + }) + let described = 0 + const request = { + method: 'POST', + headerNames: [], + describe: async () => { + described++ + return { method: 'POST' } + }, + } + + for (let call = 0; call < 60; call++) await code.onRequest(request) + + expect(described).toBe(50) + expect(policy.summary().omitted.stubbed).toBe(10) + }) +}) diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts index 7c7dc5ac3a5..e9c3a65bb56 100644 --- a/apps/sim/tools/side-effects.ts +++ b/apps/sim/tools/side-effects.ts @@ -6,11 +6,13 @@ */ import { createLogger } from '@sim/logger' import { isPlainRecord, toRecord } from '@sim/utils/object' +import { truncate } from '@sim/utils/string' import { isSensitiveKey, REDACTED_MARKER, redactExactSensitiveValues, } from '@/lib/core/security/redaction' +import type { IsolatedFetchPolicy } from '@/lib/execution/isolated-vm' import { redactObjectStrings } from '@/lib/logs/execution/pii-redaction' import { parseMcpToolArguments, RUN_CONTEXT_PARAMS } from '@/lib/mcp/tool-arguments' import { getBlock, getBlockByToolName, getBlockRegistry } from '@/blocks/registry' @@ -220,11 +222,19 @@ function maskSecrets( value: Record, params: Record, blockTypes: string[], - registry: ResolvedSecretTraceRegistry | undefined + registry: ResolvedSecretTraceRegistry | undefined, + knownSecrets: readonly string[] = [] ): Record | null { const projection = projectResolvedSecretModelContent(value, registry) if (!projection.safe || !isPlainRecord(projection.value)) return null - const masked = redactCredentials(projection.value, callSecrets(params, blockTypes)) + const secrets = callSecrets(params, blockTypes) + const masked = redactCredentials(projection.value, { + ...secrets, + values: [ + ...secrets.values, + ...knownSecrets.filter((secret) => !isNonIdentifyingSecretLiteral(secret)), + ], + }) return isPlainRecord(masked) ? masked : null } @@ -263,6 +273,8 @@ export async function redactSideEffectPayload(input: { blockTypes: string[] executionContext: ExecutionContext registry: ResolvedSecretTraceRegistry | undefined + /** Values masked wherever they appear, whatever field carried them. */ + knownSecrets?: readonly string[] }): Promise | null> { let masked: Record | null try { @@ -270,7 +282,8 @@ export async function redactSideEffectPayload(input: { asPayloadRecord(input.payload), input.params, input.blockTypes, - input.registry + input.registry, + input.knownSecrets ) } catch (error) { if (error instanceof SecretScanDepthError) return null @@ -390,3 +403,102 @@ export function answerUnsentMcpWrite( : params, }) } + +/** The longest URL and body a stubbed network request of code is recorded with. */ +const MAX_DESCRIBED_CODE_CHARS = 4096 + +/** A URL as its origin and path, its query reduced to parameter names, so no value is recorded. */ +function urlWithQueryNames(raw: string): string { + try { + const url = new URL(raw) + const names = [...new Set(url.searchParams.keys())] + return `${url.origin}${url.pathname}${names.length > 0 ? `?${names.join('&')}` : ''}` + } catch { + return raw.split(/[?#]/)[0] + } +} + +/** A recorded value cut to {@link MAX_DESCRIBED_CODE_CHARS}, after redaction: no secret is cut. */ +function capDescribed(value: unknown): unknown { + const text = typeof value === 'string' ? value : JSON.stringify(value) + if (text === undefined || text.length <= MAX_DESCRIBED_CODE_CHARS) return value + return truncate( + text, + MAX_DESCRIBED_CODE_CHARS, + `... [truncated ${text.length - MAX_DESCRIBED_CODE_CHARS} chars]` + ) +} + +/** Where a run's side-effect policy meets one run of code: its runtime and its isolate's network. */ +export interface CodeNetwork { + ranInRemoteSandbox(): void + /** The isolate host's policy for each `fetch` the code makes. */ + fetchPolicy: IsolatedFetchPolicy + /** What to add to the code's failure once it got stubbed responses; null when it got none. */ + failureHint(): string | null +} + +/** + * The run's side-effect policy for code about to run at `site` (read from the call's `_context` + * when omitted); undefined when the run has none. A request the policy stubs is recorded as its + * method, capped origin and path with query parameter names, header names and a capped body, never + * a header value. Masked in it: every value of `params.envVars` (the workspace and personal + * secrets the code is given, which the code compiles in after the registry has seen them), the + * secrets `params` carry by field, and those the registry resolved + * ({@link redactSideEffectPayload}). A secret typed into the code itself is not known to be one, + * so it is not masked. + */ +export function codeNetworkFor(input: { + executionContext: ExecutionContext | undefined + site?: SideEffectSite + params: Record + registry: ResolvedSecretTraceRegistry | undefined +}): CodeNetwork | undefined { + const { executionContext, params, registry } = input + const policy = executionContext?.sideEffects + if (!executionContext || !policy) return undefined + const site = input.site ?? sideEffectSite(executionContext, params) + const code = policy.codeNetwork(site) + const blockTypes = site.blockType ? [site.blockType] : [] + const knownSecrets = Object.values(toRecord(params.envVars)).filter( + (value): value is string => typeof value === 'string' + ) + let stubbed = 0 + return { + ranInRemoteSandbox: () => code.ranInRemoteSandbox(), + fetchPolicy: async (request) => { + const decision = await code.onRequest({ + method: request.method, + headerNames: request.headerNames, + describe: async () => { + const redacted = await redactSideEffectPayload({ + payload: { + method: request.method, + url: urlWithQueryNames(request.url), + ...(request.headerNames.length > 0 ? { headers: request.headerNames } : {}), + body: readBody(request.body), + }, + params, + blockTypes, + executionContext, + registry, + knownSecrets, + }) + return ( + redacted && { + ...redacted, + url: capDescribed(redacted.url), + body: capDescribed(redacted.body), + } + ) + }, + }) + if (decision === 'stub') stubbed++ + return decision + }, + failureHint: () => + stubbed === 0 || !site.blockName + ? null + : `Dry run: ${stubbed} network write${stubbed === 1 ? '' : 's'} this code made got an empty stubbed response; --allow '${site.blockName}' sends them.`, + } +} diff --git a/apps/sim/tools/types.ts b/apps/sim/tools/types.ts index 3c1322a9399..9eff4bd5184 100644 --- a/apps/sim/tools/types.ts +++ b/apps/sim/tools/types.ts @@ -290,6 +290,13 @@ export interface ToolConfig

{ * leaves out keeps the sample. */ dryRunOutput?: (params: P) => Record + /** + * Pure and total (never throws): whether this call of a `write` tool only reads (an HTTP + * request whose method is GET, HEAD or OPTIONS with no method-override header), so a dry run + * sends it like a `read` tool instead of stubbing it. Consulted only by a run with a side-effect + * policy; {@link effect} stays the catalog's conservative label for the tool as a whole. + */ + readsWhen?: (params: P) => boolean // OAuth configuration for this tool (if it requires authentication) oauth?: OAuthConfig diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 910bfdcd87e..f2b4292790b 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -216,7 +216,7 @@ The primer above is enough to edit; read a section here when a step needs it. ## Edit loop in detail -Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 (with its \`apply --dry-run\`, which only reviews the edit) is for a person, CI, or a change you want reviewed first. The test run's \`run --dry\` is another thing: it executes the saved draft but answers each write (table writes, sends, HTTP calls) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, so check those payloads instead of reading back or cleaning up data. Code is not stubbed: a Function block's code, a Condition's expressions, a While loop's condition and code an Agent's model writes run for real, network calls included, and are listed under \`sideEffects.unchecked\`, so check that list too. \`--mock ='{…}'\` answers a block with fixed output to steer a branch. Live runs write real data: \`--allow \` sends one block's writes for real and \`--manual\` sends every write, so point both at test resources. +Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 (with its \`apply --dry-run\`, which only reviews the edit) is for a person, CI, or a change you want reviewed first. The test run's \`run --dry\` is another thing: it executes the saved draft but answers each write (table writes, sends, HTTP calls) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, so check those payloads instead of reading back or cleaning up data. Code (a Function block's, a Condition's expressions, a While loop's condition, code an Agent's model writes) runs for real: its GET, HEAD and OPTIONS \`fetch\` calls are sent and any other gets an empty 200 and is listed under \`sideEffects.stubbed\`, while code in a remote sandbox (shell, Python, imports) is listed under \`sideEffects.unchecked\`, so check that list too. \`--mock ='{…}'\` answers a block with fixed output to steer a branch. Live runs write real data: \`--allow \` sends one block's writes for real and \`--manual\` sends every write, so point both at test resources. 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. 2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and \`apply --dry-run\` do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. \`apply --dry-run\` is the authority: a type error on a printed line you did not edit that it accepts can be skipped with \`--no-types\`. diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index 9468f8ca118..53a274b1a68 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -194,9 +194,9 @@ async function resolveWorkflowRunSelection( /** * A dry run's side effects in a few lines on stderr, for the human formats: each write that was - * not sent, sent because its block was allowed, or made by code the run cannot see, and a note - * for an allowed block whose writes all stayed stubbed (an Agent's call to a custom block). The - * request payloads are in the result itself (`--output json`). + * not sent, sent because its block was allowed, or code in a remote sandbox the run cannot see, + * and a note for an allowed block whose writes all stayed stubbed (an Agent's call to a custom + * block). The request payloads are in the result itself (`--output json`). */ function printSideEffects(sideEffects: unknown, dryRun: unknown): void { if (!isRecordLike(sideEffects)) return @@ -728,17 +728,21 @@ Without --manual (or a flag that implies it) this runs the active deployment; a deployed has none. --manual runs the saved draft, as the source loop leaves it. --dry runs the saved draft without its side effects: every tool call not declared read (sends, -table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in -sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function -block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model -writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in -the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but -write none, and the run raises no workspace event. --allow sends that block's writes for -real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or -custom block it calls. --mock = answers a block with fixed output, to steer a -branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's -execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry -run is the --source-run only of another dry run, and is never resumed. +table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a +placeholder and is listed in sideEffects.stubbed with the request it would have sent; check +those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's +condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API +that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, +gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, +imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows +run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never +pauses. Agents read memory but write none, and the run raises no workspace event. --allow + sends that block's writes (a Function's fetches included) for real (use a test +resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it +calls. --mock = answers a block with fixed output, to steer a branch; a locked block +cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or +billing reads (such as cost, tokens, model or a field starting with _). A dry run is the +--source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: From 2df5f7ec804f94541e453b6ad319da17bc7cf0e9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 11:57:17 -0800 Subject: [PATCH 3/6] fix(workflows): dry-run code results wait for unawaited fetch decisions An isolate result now waits for fetch-policy decisions still pending, so a write the code never awaited is recorded before the run reads its side effects. Remote-sandbox code of an allowed block stays listed unchecked instead of claiming a sent write. The egress test asserts the refusal itself, and the CLI and workflow-test guidance name the method-override exception. --- .../contracts/mothership-management-tools.ts | 2 +- apps/sim/lib/execution/isolated-vm.test.ts | 58 +++++++++++++++ apps/sim/lib/execution/isolated-vm.ts | 70 +++++++++++++++---- .../application/dry-run.integration.ts | 6 +- .../sim/lib/workflows/dry-run/side-effects.ts | 20 +++--- apps/sim/tools/side-effects.test.ts | 15 ++++ .../src/commands/protocol/workflow-dir.ts | 2 +- 7 files changed, 143 insertions(+), 30 deletions(-) diff --git a/apps/sim/lib/api/contracts/mothership-management-tools.ts b/apps/sim/lib/api/contracts/mothership-management-tools.ts index 282f26e8bfa..a1499c7fbbe 100644 --- a/apps/sim/lib/api/contracts/mothership-management-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-management-tools.ts @@ -25,7 +25,7 @@ export const managementToolContracts = [ route: 'sim', scope: 'all', description: - 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs (data only: no cost, tokens, model, providerTiming, toolCalls or field starting with _, which the run\u2019s trace and billing read); mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run (a custom block no mock answers is answered whole), and a fetch a Function or Condition makes with any method but GET, HEAD or OPTIONS gets an empty 200 response, while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', + 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs (data only: no cost, tokens, model, providerTiming, toolCalls or field starting with _, which the run\u2019s trace and billing read); mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run (a custom block no mock answers is answered whole), and a fetch a Function or Condition makes with any method but GET, HEAD or OPTIONS, or with a method-override header, gets an empty 200 response, while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', inputSchema: mothershipTestsInputSchema, }, { diff --git a/apps/sim/lib/execution/isolated-vm.test.ts b/apps/sim/lib/execution/isolated-vm.test.ts index 1af18b3c5be..24ce5ae4eb8 100644 --- a/apps/sim/lib/execution/isolated-vm.test.ts +++ b/apps/sim/lib/execution/isolated-vm.test.ts @@ -1100,6 +1100,64 @@ describe('isolated-vm scheduler', () => { expect(secureFetchMock).not.toHaveBeenCalled() }) + it('returns a result only once the fetch policy decided a request the code never awaited', async () => { + const unawaitedFetchProc = () => { + const proc = createBaseProc() + proc.send = (message: unknown) => { + const msg = message as { type?: string; executionId?: number } + if (msg.type === 'execute') { + setImmediate(() => { + proc.emit('message', { + type: 'fetch', + executionId: msg.executionId, + fetchId: 1, + requestId: 'req-unawaited', + url: 'https://hook.example/write', + optionsJson: JSON.stringify({ method: 'POST' }), + }) + proc.emit('message', { + type: 'result', + executionId: msg.executionId, + result: { result: 'returned', stdout: '' }, + }) + }) + } + return true + } + setImmediate(() => proc.emit('message', { type: 'ready' })) + return proc + } + const { executeInIsolatedVM } = await loadExecutionModule({ spawns: [unawaitedFetchProc] }) + inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({ + isValid: true, + resolvedIP: '93.184.216.34', + originalHostname: 'hook.example', + }) + const decided: string[] = [] + + const result = await executeInIsolatedVM( + { + code: 'fetch("https://hook.example/write", { method: "POST" }); return "returned"', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 1000, + requestId: 'req-unawaited', + }, + { + fetchPolicy: async (request) => { + await sleep(50) + decided.push(request.method) + return 'stub' + }, + } + ) + + expect(result.result).toBe('returned') + expect(decided).toEqual(['POST']) + expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled() + }) + it('does not log a resolved secret from a failed fetch URL or error', async () => { const secret = 'fetch-path-secret-value' const requestUrl = `https://example.com/${secret}` diff --git a/apps/sim/lib/execution/isolated-vm.ts b/apps/sim/lib/execution/isolated-vm.ts index 83b93cf2506..22c9874796b 100644 --- a/apps/sim/lib/execution/isolated-vm.ts +++ b/apps/sim/lib/execution/isolated-vm.ts @@ -209,6 +209,11 @@ const DISTRIBUTED_LEASE_GRACE_MS = 30000 interface PendingExecution { runInOutboundScope: ReturnType fetchPolicy?: IsolatedFetchPolicy + /** + * Fetches whose {@link fetchPolicy} decision is still pending. The result waits for them, so a + * request the code never awaited is decided (and recorded) before the caller reads the run. + */ + fetchDecisions: Set> resolve: (result: IsolatedVMExecutionResult) => void timeout: ReturnType ownerKey: string @@ -424,17 +429,43 @@ const STUBBED_FETCH_RESPONSE = JSON.stringify({ headers: { 'content-type': 'application/json', 'x-sim-dry-run': 'stubbed' }, }) +/** + * Validates the target of a `fetch` of isolate code, then asks the policy: the IP validation + * resolved when the request is sent, or what the isolate gets instead (a validation error or the + * stubbed response). + */ +async function decideFetch( + url: string, + fetchOptions: SecureFetchOptions, + fetchPolicy: IsolatedFetchPolicy +): Promise<{ resolvedIP: string } | { response: string }> { + const target = await validateUrlWithDNS(url, 'fetchUrl', fetchOptions.profile, { + signal: fetchOptions.signal, + }) + if (!target.isValid) return { response: JSON.stringify({ error: target.error }) } + const decision = await fetchPolicy({ + method: fetchOptions.method ?? 'GET', + url, + headerNames: Object.keys(fetchOptions.headers ?? {}), + body: typeof fetchOptions.body === 'string' ? fetchOptions.body : undefined, + }) + return decision === 'stub' + ? { response: STUBBED_FETCH_RESPONSE } + : { resolvedIP: target.resolvedIP } +} + /** * Sends one `fetch` of isolate code. With a policy, the target is validated before the policy * decides, so a request it stubs fails where a live one would (a URL too long, invalid, or refused - * by the egress policy), and a request it sends goes to the IP that validation resolved. + * by the egress policy), and a request it sends goes to the IP that validation resolved. Its + * decision is held in `policy.decisions` until made. */ async function secureFetch( requestId: string, url: string, options: IsolatedFetchOptions | undefined, signal: AbortSignal, - fetchPolicy: IsolatedFetchPolicy | undefined + policy: { decide: IsolatedFetchPolicy; decisions: Set> } | undefined ): Promise { if (url.length > MAX_FETCH_URL_LENGTH) { return JSON.stringify({ @@ -445,17 +476,14 @@ async function secureFetch( try { const fetchOptions = { ...normalizeFetchOptions(options), signal } let response: SecureFetchResponse - if (fetchPolicy) { - const target = await validateUrlWithDNS(url, 'fetchUrl', fetchOptions.profile, { signal }) - if (!target.isValid) return JSON.stringify({ error: target.error }) - const decision = await fetchPolicy({ - method: fetchOptions.method ?? 'GET', - url, - headerNames: Object.keys(fetchOptions.headers ?? {}), - body: typeof fetchOptions.body === 'string' ? fetchOptions.body : undefined, - }) - if (decision === 'stub') return STUBBED_FETCH_RESPONSE - response = await secureFetchWithPinnedIP(url, target.resolvedIP, fetchOptions) + if (policy) { + const pendingDecision = decideFetch(url, fetchOptions, policy.decide) + const settle = () => policy.decisions.delete(pendingDecision) + policy.decisions.add(pendingDecision) + pendingDecision.then(settle, settle) + const decision = await pendingDecision + if ('response' in decision) return decision.response + response = await secureFetchWithPinnedIP(url, decision.resolvedIP, fetchOptions) } else { response = await secureFetchWithValidation(url, fetchOptions, 'fetchUrl') } @@ -913,7 +941,8 @@ function handleWorkerMessage(workerId: number, message: unknown) { // accurate; just skip re-resolving. const result = msg.result as IsolatedVMExecutionResult if (!pending.abort.signal.aborted) { - pending.resolve(result) + if (pending.fetchDecisions.size === 0) pending.resolve(result) + else void Promise.allSettled(pending.fetchDecisions).then(() => pending.resolve(result)) } // The isolate's own timeout gives up on the execution just as the pool's does. if (result.termination === 'timeout') pending.abort.abort() @@ -983,7 +1012,17 @@ function handleWorkerMessage(workerId: number, message: unknown) { AbortSignal.timeout(pending.hostTimeoutMs), ]) pending - .runInOutboundScope(() => secureFetch(requestId, url, options, signal, pending.fetchPolicy)) + .runInOutboundScope(() => + secureFetch( + requestId, + url, + options, + signal, + pending.fetchPolicy + ? { decide: pending.fetchPolicy, decisions: pending.fetchDecisions } + : undefined + ) + ) .then(sendFetchResponse) .catch((err) => { sendFetchResponse(JSON.stringify({ error: getErrorMessage(err, 'Fetch failed') })) @@ -1410,6 +1449,7 @@ function dispatchToWorker( workerInfo.pendingExecutions.set(execId, { runInOutboundScope: state.runInOutboundScope, fetchPolicy: state.fetchPolicy, + fetchDecisions: new Set(), resolve, timeout, ownerKey: ownerState.ownerKey, diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index ad1d4eacbf7..b22912646c7 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -1784,7 +1784,7 @@ return res.status` it('fails a write the egress policy refuses, as a live run would, and records nothing', async () => { const { workflowId } = await codeWorkflow( `try { - await fetch('http://10.255.255.1/hook', { method: 'POST' }) + await fetch('https://10.255.255.1/hook', { method: 'POST' }) return 'answered' } catch (error) { return error.message @@ -1794,7 +1794,9 @@ return res.status` const result = await run(workflowId, { dry: true }) expect(result.status, JSON.stringify(result.error)).toBe('completed') - expect(JSON.stringify(result.output)).not.toContain('answered') + expect(result.output).toMatchObject({ + result: expect.stringContaining('fetchUrl resolves to a private or reserved address'), + }) expect(result.sideEffects?.stubbed).toEqual([]) }) diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index b80d8e1d31d..7bb12bbb07b 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -211,19 +211,13 @@ export class WriteStubPolicy implements SideEffectPolicy { return 'send' } + /** + * Code in a remote sandbox is listed unchecked even when its block is allowed: allowing it + * changes nothing there, and `allowed` lists only writes known to be sent. + */ codeNetwork(site: SideEffectSite): CodeNetworkPolicy { const key = `${site.workflowId}:${site.blockId}` - if (this.allows(site)) { - const recordAllowed = () => - this.allowed.add({ ...recordedSite(site), tool: CODE_TOOL_ID }, `${key}:${CODE_TOOL_ID}`) - return { - ranInRemoteSandbox: recordAllowed, - onRequest: async (request) => { - if (!isReadRequest(request.method, request.headerNames)) recordAllowed() - return 'send' - }, - } - } + const allowed = this.allows(site) return { ranInRemoteSandbox: () => this.unchecked.add( @@ -232,6 +226,10 @@ export class WriteStubPolicy implements SideEffectPolicy { ), onRequest: async (request) => { if (isReadRequest(request.method, request.headerNames)) return 'send' + if (allowed) { + this.allowed.add({ ...recordedSite(site), tool: CODE_TOOL_ID }, `${key}:${CODE_TOOL_ID}`) + return 'send' + } this.stubbed.add({ ...recordedSite(site), tool: CODE_TOOL_ID, diff --git a/apps/sim/tools/side-effects.test.ts b/apps/sim/tools/side-effects.test.ts index 05b914f502d..bc8d8d72b5a 100644 --- a/apps/sim/tools/side-effects.test.ts +++ b/apps/sim/tools/side-effects.test.ts @@ -193,6 +193,21 @@ describe('code a dry run runs', () => { ]) }) + it('is listed unchecked, not allowed, when its block is allowed and it runs in a remote sandbox', () => { + const policy = new WriteStubPolicy({ workflowId: 'wf-1', allowBlockIds: new Set(['python']) }) + const code = policy.codeNetwork({ + workflowId: 'wf-1', + blockId: 'python', + blockName: 'python', + blockType: 'function', + }) + + code.ranInRemoteSandbox() + + expect(policy.summary().unchecked).toEqual([expect.objectContaining({ blockId: 'python' })]) + expect(policy.summary().allowed).toEqual([]) + }) + it('records a long stubbed body masked before it is capped, so no secret is cut in two', async () => { const secret = 'code-secret-0123456789' const { network, policy } = codeNetwork('code', { apiKey: secret }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index f2b4292790b..078e7f3bfb5 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -216,7 +216,7 @@ The primer above is enough to edit; read a section here when a step needs it. ## Edit loop in detail -Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 (with its \`apply --dry-run\`, which only reviews the edit) is for a person, CI, or a change you want reviewed first. The test run's \`run --dry\` is another thing: it executes the saved draft but answers each write (table writes, sends, HTTP calls) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, so check those payloads instead of reading back or cleaning up data. Code (a Function block's, a Condition's expressions, a While loop's condition, code an Agent's model writes) runs for real: its GET, HEAD and OPTIONS \`fetch\` calls are sent and any other gets an empty 200 and is listed under \`sideEffects.stubbed\`, while code in a remote sandbox (shell, Python, imports) is listed under \`sideEffects.unchecked\`, so check that list too. \`--mock ='{…}'\` answers a block with fixed output to steer a branch. Live runs write real data: \`--allow \` sends one block's writes for real and \`--manual\` sends every write, so point both at test resources. +Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 (with its \`apply --dry-run\`, which only reviews the edit) is for a person, CI, or a change you want reviewed first. The test run's \`run --dry\` is another thing: it executes the saved draft but answers each write (table writes, sends, HTTP calls) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, so check those payloads instead of reading back or cleaning up data. Code (a Function block's, a Condition's expressions, a While loop's condition, code an Agent's model writes) runs for real: its GET, HEAD and OPTIONS \`fetch\` calls are sent (an API that writes on a GET is not stubbed, so point those at a test resource), and any other, or one carrying a method-override header, gets an empty 200 and is listed under \`sideEffects.stubbed\`, while code in a remote sandbox (shell, Python, imports) is listed under \`sideEffects.unchecked\`, so check that list too. \`--mock ='{…}'\` answers a block with fixed output to steer a branch. Live runs write real data: \`--allow \` sends one block's writes for real and \`--manual\` sends every write, so point both at test resources. 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. 2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and \`apply --dry-run\` do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. \`apply --dry-run\` is the authority: a type error on a printed line you did not edit that it accepts can be skipped with \`--no-types\`. From f6936684c34ca5ed4236c76cd26459ebde344af8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 12:04:20 -0800 Subject: [PATCH 4/6] test(execution): decide the unawaited fetch on a deferred, not a wall-clock wait --- apps/sim/lib/execution/isolated-vm.test.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/apps/sim/lib/execution/isolated-vm.test.ts b/apps/sim/lib/execution/isolated-vm.test.ts index 24ce5ae4eb8..1cb1fb7b6db 100644 --- a/apps/sim/lib/execution/isolated-vm.test.ts +++ b/apps/sim/lib/execution/isolated-vm.test.ts @@ -1134,8 +1134,10 @@ describe('isolated-vm scheduler', () => { originalHostname: 'hook.example', }) const decided: string[] = [] + const decision = Promise.withResolvers<'stub'>() + let returned = false - const result = await executeInIsolatedVM( + const running = executeInIsolatedVM( { code: 'fetch("https://hook.example/write", { method: "POST" }); return "returned"', params: {}, @@ -1146,15 +1148,19 @@ describe('isolated-vm scheduler', () => { }, { fetchPolicy: async (request) => { - await sleep(50) decided.push(request.method) - return 'stub' + return decision.promise }, } - ) + ).then((result) => { + returned = true + return result + }) + await vi.waitFor(() => expect(decided).toEqual(['POST'])) - expect(result.result).toBe('returned') - expect(decided).toEqual(['POST']) + expect(returned).toBe(false) + decision.resolve('stub') + expect((await running).result).toBe('returned') expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled() }) From 17d8d05623c209ee09860071de27f36fe64de1d6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 12:15:05 -0800 Subject: [PATCH 5/6] test(execution): build the deferred decision without Promise.withResolvers --- apps/sim/lib/execution/isolated-vm.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/execution/isolated-vm.test.ts b/apps/sim/lib/execution/isolated-vm.test.ts index 1cb1fb7b6db..11280868b21 100644 --- a/apps/sim/lib/execution/isolated-vm.test.ts +++ b/apps/sim/lib/execution/isolated-vm.test.ts @@ -1134,7 +1134,10 @@ describe('isolated-vm scheduler', () => { originalHostname: 'hook.example', }) const decided: string[] = [] - const decision = Promise.withResolvers<'stub'>() + let decide: (decision: 'stub') => void = () => {} + const decision = new Promise<'stub'>((resolve) => { + decide = resolve + }) let returned = false const running = executeInIsolatedVM( @@ -1149,7 +1152,7 @@ describe('isolated-vm scheduler', () => { { fetchPolicy: async (request) => { decided.push(request.method) - return decision.promise + return decision }, } ).then((result) => { @@ -1159,7 +1162,7 @@ describe('isolated-vm scheduler', () => { await vi.waitFor(() => expect(decided).toEqual(['POST'])) expect(returned).toBe(false) - decision.resolve('stub') + decide('stub') expect((await running).result).toBe('returned') expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled() }) From c3b3f7925aaa0dcd924e6311bd7ae5464a2519b1 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 12:20:43 -0800 Subject: [PATCH 6/6] fix(execution): stop waiting for fetch decisions at the execution deadline --- apps/sim/lib/execution/isolated-vm.test.ts | 96 ++++++++++++++++------ apps/sim/lib/execution/isolated-vm.ts | 24 +++++- 2 files changed, 90 insertions(+), 30 deletions(-) diff --git a/apps/sim/lib/execution/isolated-vm.test.ts b/apps/sim/lib/execution/isolated-vm.test.ts index 11280868b21..bf03a45b843 100644 --- a/apps/sim/lib/execution/isolated-vm.test.ts +++ b/apps/sim/lib/execution/isolated-vm.test.ts @@ -177,6 +177,34 @@ function createReadyFetchProxyProc(fetchMessage: { url: string; optionsJson?: st return proc } +/** A worker whose code starts a POST it never awaits and returns at once. */ +function createUnawaitedFetchProc(): MockProc { + const proc = createBaseProc() + proc.send = (message: unknown) => { + const msg = message as { type?: string; executionId?: number } + if (msg.type === 'execute') { + setImmediate(() => { + proc.emit('message', { + type: 'fetch', + executionId: msg.executionId, + fetchId: 1, + requestId: 'req-unawaited', + url: 'https://hook.example/write', + optionsJson: JSON.stringify({ method: 'POST' }), + }) + proc.emit('message', { + type: 'result', + executionId: msg.executionId, + result: { result: 'returned', stdout: '' }, + }) + }) + } + return true + } + setImmediate(() => proc.emit('message', { type: 'ready' })) + return proc +} + const { mockSpawn, mockExecSync } = vi.hoisted(() => ({ mockSpawn: vi.fn(), mockExecSync: vi.fn(() => Buffer.from('v23.11.0')), @@ -1101,33 +1129,9 @@ describe('isolated-vm scheduler', () => { }) it('returns a result only once the fetch policy decided a request the code never awaited', async () => { - const unawaitedFetchProc = () => { - const proc = createBaseProc() - proc.send = (message: unknown) => { - const msg = message as { type?: string; executionId?: number } - if (msg.type === 'execute') { - setImmediate(() => { - proc.emit('message', { - type: 'fetch', - executionId: msg.executionId, - fetchId: 1, - requestId: 'req-unawaited', - url: 'https://hook.example/write', - optionsJson: JSON.stringify({ method: 'POST' }), - }) - proc.emit('message', { - type: 'result', - executionId: msg.executionId, - result: { result: 'returned', stdout: '' }, - }) - }) - } - return true - } - setImmediate(() => proc.emit('message', { type: 'ready' })) - return proc - } - const { executeInIsolatedVM } = await loadExecutionModule({ spawns: [unawaitedFetchProc] }) + const { executeInIsolatedVM } = await loadExecutionModule({ + spawns: [createUnawaitedFetchProc], + }) inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({ isValid: true, resolvedIP: '93.184.216.34', @@ -1167,6 +1171,44 @@ describe('isolated-vm scheduler', () => { expect(inputValidationMockFns.mockSecureFetchWithPinnedIP).not.toHaveBeenCalled() }) + it('stops waiting for an unawaited request’s decision at the execution’s deadline', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }) + try { + const { executeInIsolatedVM } = await loadExecutionModule({ + spawns: [createUnawaitedFetchProc], + }) + inputValidationMockFns.mockValidateUrlWithDNS.mockResolvedValue({ + isValid: true, + resolvedIP: '93.184.216.34', + originalHostname: 'hook.example', + }) + const decided: string[] = [] + + const running = executeInIsolatedVM( + { + code: 'fetch("https://hook.example/write", { method: "POST" }); return "returned"', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-unawaited-slow', + }, + { + fetchPolicy: (request) => { + decided.push(request.method) + return new Promise<'stub'>(() => {}) + }, + } + ) + await vi.waitFor(() => expect(decided).toEqual(['POST'])) + await vi.advanceTimersByTimeAsync(1100) + + expect((await running).result).toBe('returned') + } finally { + vi.useRealTimers() + } + }) + it('does not log a resolved secret from a failed fetch URL or error', async () => { const secret = 'fetch-path-secret-value' const requestUrl = `https://example.com/${secret}` diff --git a/apps/sim/lib/execution/isolated-vm.ts b/apps/sim/lib/execution/isolated-vm.ts index 22c9874796b..d5541ae1992 100644 --- a/apps/sim/lib/execution/isolated-vm.ts +++ b/apps/sim/lib/execution/isolated-vm.ts @@ -210,10 +210,13 @@ interface PendingExecution { runInOutboundScope: ReturnType fetchPolicy?: IsolatedFetchPolicy /** - * Fetches whose {@link fetchPolicy} decision is still pending. The result waits for them, so a - * request the code never awaited is decided (and recorded) before the caller reads the run. + * Fetches whose {@link fetchPolicy} decision is still pending. The result waits for them until + * {@link deadline}, so a request the code never awaited is decided (and recorded) before the + * caller reads the run, and a slow decision never holds the code past its time limit. */ fetchDecisions: Set> + /** When the pool gives up on the execution (epoch ms): dispatch plus {@link hostTimeoutMs}. */ + deadline: number resolve: (result: IsolatedVMExecutionResult) => void timeout: ReturnType ownerKey: string @@ -905,6 +908,17 @@ function handleBrokerMessage( }) } +/** Settles once every promise in `pending` has, or at `deadline` (epoch ms), whichever is first. */ +function settleBefore(pending: Iterable>, deadline: number): Promise { + return new Promise((resolve) => { + const timer = setTimeout(resolve, Math.max(0, deadline - Date.now())) + void Promise.allSettled(pending).then(() => { + clearTimeout(timer) + resolve() + }) + }) +} + function handleWorkerMessage(workerId: number, message: unknown) { if (typeof message !== 'object' || message === null) return const msg = message as Record @@ -942,7 +956,10 @@ function handleWorkerMessage(workerId: number, message: unknown) { const result = msg.result as IsolatedVMExecutionResult if (!pending.abort.signal.aborted) { if (pending.fetchDecisions.size === 0) pending.resolve(result) - else void Promise.allSettled(pending.fetchDecisions).then(() => pending.resolve(result)) + else + void settleBefore(pending.fetchDecisions, pending.deadline).then(() => + pending.resolve(result) + ) } // The isolate's own timeout gives up on the execution just as the pool's does. if (result.termination === 'timeout') pending.abort.abort() @@ -1450,6 +1467,7 @@ function dispatchToWorker( runInOutboundScope: state.runInOutboundScope, fetchPolicy: state.fetchPolicy, fetchDecisions: new Set(), + deadline: Date.now() + hostTimeoutMs, resolve, timeout, ownerKey: ownerState.ownerKey,