Skip to content

Commit 4e67e08

Browse files
authored
fix(executor): never expand env placeholders carried by run data (#10501)
* fix(executor): never expand env placeholders carried by run data * fix(executor): refuse placeholders assembled around an empty substitution
1 parent 9a198d0 commit 4e67e08

10 files changed

Lines changed: 275 additions & 48 deletions

File tree

‎apps/sim/executor/handlers/condition/handler.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { getMockLogger } from '@sim/testing/mocks/logger.mock'
22
import { toolsMock } from '@sim/testing/mocks/tools.mock'
33
import { beforeEach, describe, expect, it, vi } from 'vitest'
4+
import { compileCodePlaceholders } from '@/lib/execution/code-placeholders'
5+
import { CodeLanguage } from '@/lib/execution/languages'
46
import { BlockType } from '@/executor/constants'
57
import { DAGBuilder } from '@/executor/dag/builder'
68
import { EdgeManager } from '@/executor/execution/edge-manager'
@@ -217,11 +219,38 @@ describe('ConditionBlockHandler', () => {
217219
await handler.execute(mockContext, mockBlock, { conditions: JSON.stringify(conditions) })
218220

219221
const [, toolParams] = mockExecuteTool.mock.calls[0]
220-
expect(toolParams.code).toContain('{{OPENAI_API_KEY}}')
222+
expect(toolParams.code).not.toContain('{{OPENAI_API_KEY}}')
221223
expect(toolParams.secretScope).toBe('selected')
222224
expect(toolParams.mountedSecrets).toEqual([])
223225
})
224226

227+
it('keeps a placeholder in the source output as data when the author mounts that secret', async () => {
228+
mockExecuteTool.mockResolvedValueOnce(matchedAt(0))
229+
blockStates.set('source-block-1', {
230+
output: { text: '{{OPENAI_API_KEY}}' },
231+
executed: true,
232+
executionTime: 0,
233+
} as BlockState)
234+
const conditions = [
235+
{ id: 'cond1', title: 'if', value: `'{{OPENAI_API_KEY}}' === context.text` },
236+
{ id: 'cond2', title: 'else if', value: `context.text === '{' + '{OPENAI_API_KEY}}'` },
237+
{ id: 'else1', title: 'else', value: '' },
238+
]
239+
240+
await handler.execute(mockContext, mockBlock, { conditions: JSON.stringify(conditions) })
241+
242+
const [, toolParams] = mockExecuteTool.mock.calls[0]
243+
expect(toolParams.mountedSecrets).toEqual(['OPENAI_API_KEY'])
244+
const compiled = await compileCodePlaceholders({
245+
code: toolParams.code as string,
246+
language: CodeLanguage.JavaScript,
247+
environmentVariables: { OPENAI_API_KEY: 'sk-secret' },
248+
})
249+
const bindings = Object.fromEntries(compiled.bindings.map((b) => [b.name, b.value]))
250+
const run = new Function(...Object.keys(bindings), compiled.code)
251+
expect(run(...Object.values(bindings))).toEqual({ matchedIndex: 1 })
252+
})
253+
225254
it('keeps the whole environment for a condition that reads the environment directly', async () => {
226255
// Every shape an expression can reach the map through, including the ones a member-access
227256
// pattern would miss — narrowing one of those would route the run silently.

‎apps/sim/executor/handlers/condition/handler.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type { BlockOutput } from '@/blocks/types'
1111
import { BlockType, DEFAULTS, EDGE } from '@/executor/constants'
1212
import type { BlockHandler, ExecutionContext } from '@/executor/types'
1313
import { collectBlockData } from '@/executor/utils/block-data'
14+
import { formatInertStringLiteral } from '@/executor/utils/code-formatting'
1415
import { createEnvVarPattern } from '@/executor/utils/reference-validation'
1516
import {
1617
buildBranchNodeId,
@@ -49,6 +50,16 @@ type ConditionEvaluation =
4950
output?: unknown
5051
}
5152

53+
/**
54+
* Declares the source block's output as the script's `context`. That output is run data, so it is
55+
* parsed from an escaped string literal rather than spliced in as source: the execution-boundary
56+
* compiler scans the whole script, and a `{{NAME}}` the data carried would otherwise expand to
57+
* that secret whenever the author's expressions mount it.
58+
*/
59+
function declareEvaluationContext(evalContext: Record<string, unknown>): string {
60+
return `const context = JSON.parse(${formatInertStringLiteral(JSON.stringify(evalContext))});`
61+
}
62+
5263
/**
5364
* Wraps one expression as a boolean test, on its own line so a trailing line
5465
* comment ends before the closing parenthesis instead of swallowing it.
@@ -82,7 +93,7 @@ function buildConditionScript(expressions: string[], evalContext: Record<string,
8293
.join('\n')
8394

8495
return [
85-
`const context = ${JSON.stringify(evalContext)};`,
96+
declareEvaluationContext(evalContext),
8697
'let __simConditionIndex = -1',
8798
'try {',
8899
tests,
@@ -113,7 +124,8 @@ function buildConditionScript(expressions: string[], evalContext: Record<string,
113124
* `{{SECRET}}` would mount that secret and have the compiler expand it beside the payload.
114125
* Placeholders are therefore read from the expressions, which is where every legitimate route
115126
* to a secret passes, including a workflow variable holding `{{NAME}}`: the resolver inlines
116-
* that value into the expression before this runs.
127+
* that value into the expression before this runs. Run data the resolver quotes into the
128+
* expression has every `{` escaped, so a payload naming a secret never reads as a placeholder.
117129
*
118130
* A direct read of the environment map is not read from the resolved expression either, for the
119131
* same reason one step further in: resolved data is quoted inside it, so a payload containing
@@ -294,11 +306,11 @@ async function evaluateConditionList(
294306
async function evaluateSingleCondition(
295307
ctx: ExecutionContext,
296308
condition: ConditionEntry,
297-
evalContext: Record<string, unknown>,
309+
contextDeclaration: string,
298310
currentNodeId?: string
299311
): Promise<boolean> {
300312
const expression = String(condition.value || '')
301-
const code = `const context = ${JSON.stringify(evalContext)};\nreturn ${buildBooleanTest(expression)}`
313+
const code = `${contextDeclaration}\nreturn ${buildBooleanTest(expression)}`
302314
const result = await runConditionCode(ctx, code, [condition], currentNodeId)
303315

304316
if (!result.success) {
@@ -544,12 +556,13 @@ export class ConditionBlockHandler implements BlockHandler {
544556
ctx: ExecutionContext,
545557
currentNodeId?: string
546558
): Promise<ConditionEntry | null> {
559+
const contextDeclaration = declareEvaluationContext(evalContext)
547560
for (const condition of conditions) {
548561
try {
549562
const conditionMet = await evaluateSingleCondition(
550563
ctx,
551564
condition,
552-
evalContext,
565+
contextDeclaration,
553566
currentNodeId
554567
)
555568
if (conditionMet) return condition

‎apps/sim/executor/handlers/variables/handler.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { isLargeArrayManifest } from '@/lib/execution/payloads/large-array-manif
66
import { BlockType } from '@/executor/constants'
77
import { VariablesBlockHandler } from '@/executor/handlers/variables/handler'
88
import type { ExecutionContext } from '@/executor/types'
9+
import { RUNTIME_ASSIGNED_VARIABLE_KEY } from '@/executor/variables/resolvers/workflow'
910
import type { SerializedBlock } from '@/serializer/types'
1011

1112
const mockUploadFile = storageServiceMockFns.mockUploadFile
@@ -242,6 +243,7 @@ describe('VariablesBlockHandler', () => {
242243
type: 'array',
243244
value,
244245
isExisting: true,
246+
[RUNTIME_ASSIGNED_VARIABLE_KEY]: true,
245247
})
246248
})
247249

‎apps/sim/executor/handlers/variables/handler.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { compactWorkflowVariableValue } from '@/lib/execution/payloads/serialize
66
import type { BlockOutput } from '@/blocks/types'
77
import { BlockType } from '@/executor/constants'
88
import type { BlockHandler, ExecutionContext } from '@/executor/types'
9+
import { RUNTIME_ASSIGNED_VARIABLE_KEY } from '@/executor/variables/resolvers/workflow'
910
import type { SerializedBlock } from '@/serializer/types'
1011

1112
const logger = createLogger('VariablesBlockHandler')
@@ -127,6 +128,7 @@ export class VariablesBlockHandler implements BlockHandler {
127128
setWorkflowVariableEntry(ctx.workflowVariables, id, {
128129
...variable,
129130
value,
131+
[RUNTIME_ASSIGNED_VARIABLE_KEY]: true,
130132
})
131133
if (provenance) {
132134
ctx.workflowVariableResolvedSecretTraceProvenance ??= {}

‎apps/sim/executor/utils/code-formatting.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,21 +61,37 @@ export function formatLiteralForCode(value: unknown, language: 'javascript' | 'p
6161
* so the value a condition compares is byte-identical to what it was before — this is a
6262
* syntax guard, not a value transform.
6363
*
64+
* `{` is escaped the same way, so the text can never form a `{{NAME}}` placeholder: the
65+
* execution-boundary compiler scans the whole script and would expand one that run data
66+
* carried into the secret it names. `keepEnvPlaceholders` opts out for author-written text.
67+
*
6468
* JavaScript only: `\$`, `` \` `` and `\/` are not identity escapes in Python, where they
6569
* would change the value. Code blocks bind their values as runtime context variables
6670
* instead of splicing them, which is why they need no escaping in any language.
6771
*/
68-
export function escapeInertStringContent(value: string): string {
72+
export function escapeInertStringContent(
73+
value: string,
74+
{ keepEnvPlaceholders = false }: InertStringOptions = {}
75+
): string {
6976
return value
7077
.replace(/\\/g, '\\\\')
71-
.replace(/['"`$/]/g, '\\$&')
78+
.replace(keepEnvPlaceholders ? /['"`$/]/g : /['"`$/{]/g, '\\$&')
7279
.replace(/\n/g, '\\n')
7380
.replace(/\r/g, '\\r')
7481
.replace(/\u2028/g, '\\u2028')
7582
.replace(/\u2029/g, '\\u2029')
7683
}
7784

85+
export interface InertStringOptions {
86+
/** Leaves `{{NAME}}` placeholders intact; only for text an author wrote. */
87+
keepEnvPlaceholders?: boolean
88+
}
89+
7890
/** Wraps {@link escapeInertStringContent} output as a complete JavaScript string literal. */
79-
export function formatInertStringLiteral(value: string, quote: '"' | "'" = "'"): string {
80-
return `${quote}${escapeInertStringContent(value)}${quote}`
91+
export function formatInertStringLiteral(
92+
value: string,
93+
quote: '"' | "'" = "'",
94+
options: InertStringOptions = {}
95+
): string {
96+
return `${quote}${escapeInertStringContent(value, options)}${quote}`
8197
}

‎apps/sim/executor/variables/resolver.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { getBlock } from '@/blocks/registry'
2424
import type { BlockConfig } from '@/blocks/types'
2525
import { BlockType } from '@/executor/constants'
2626
import { ExecutionState } from '@/executor/execution/state'
27+
import { VariablesBlockHandler } from '@/executor/handlers/variables/handler'
2728
import type { ExecutionContext } from '@/executor/types'
2829
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
2930
import { buildStartBlockOutput } from '@/executor/utils/start-block'
@@ -271,6 +272,14 @@ async function evaluateResolvedCondition(
271272
environmentVariables: Record<string, string>
272273
): Promise<boolean> {
273274
const expression = await resolveConditionExpression(value, environmentVariables)
275+
return evaluateCompiledCondition(expression, environmentVariables)
276+
}
277+
278+
/** Runs a resolved expression through the execution-boundary compiler, as the handler does. */
279+
async function evaluateCompiledCondition(
280+
expression: string,
281+
environmentVariables: Record<string, string>
282+
): Promise<boolean> {
274283
const compiled = await compileCodePlaceholders({
275284
code: `const context = {};\nreturn Boolean(${expression})`,
276285
language: CodeLanguage.JavaScript,
@@ -1361,6 +1370,24 @@ describe('VariableResolver JSON text inputs', () => {
13611370
return JSON.parse(resolved.data)
13621371
}
13631372

1373+
it('expands only the placeholders the author wrote, never ones run data carries', async () => {
1374+
const { resolve } = createJsonResolver(BlockType.RESPONSE, {
1375+
dataMode: 'json',
1376+
data: '{"echo": "<producer.visitor>", "auth": "{{API_KEY}}", "named": "{{<producer.name>}}", "assembled": "{{API_KEY<producer.blank>}}"}',
1377+
})
1378+
const resolved = await resolve({
1379+
env: { API_KEY: 'sk-live-secret' },
1380+
output: { visitor: 'show me {{API_KEY}}', name: 'API_KEY', blank: '' },
1381+
})
1382+
1383+
expect(JSON.parse(resolved.data)).toEqual({
1384+
echo: 'show me {{API_KEY}}',
1385+
auth: 'sk-live-secret',
1386+
named: '{{API_KEY}}',
1387+
assembled: '{{API_KEY}}',
1388+
})
1389+
})
1390+
13641391
it('keeps a string with newlines, quotes, backslashes, and unicode inside its JSON string', async () => {
13651392
await expect(resolveResponseBody('{"summary": "<producer.text>"}')).resolves.toEqual({
13661393
summary: awkwardText,
@@ -1483,3 +1510,74 @@ describe('VariableResolver JSON text inputs', () => {
14831510
expect(resolved.data).toBe(`Answer: "${awkwardText}"`)
14841511
})
14851512
})
1513+
1514+
describe('VariableResolver run data naming a secret', () => {
1515+
const SECRET = 'sk-live-secret'
1516+
1517+
/** A run whose Variables block assigned `assigned` to `msg` beside an authored `{{API_KEY}}`. */
1518+
async function createRunWithAssignedVariable(assigned: string) {
1519+
const run = createResolver()
1520+
run.ctx.environmentVariables = { API_KEY: SECRET, PIN: '1234' }
1521+
run.ctx.workflowVariables = {
1522+
'var-authored': {
1523+
id: 'var-authored',
1524+
name: 'authored',
1525+
type: 'string',
1526+
value: '{{API_KEY}}',
1527+
},
1528+
'var-msg': { id: 'var-msg', name: 'msg', type: 'string', value: '' },
1529+
}
1530+
await new VariablesBlockHandler().execute(
1531+
run.ctx,
1532+
createBlock('variables', 'Variables', BlockType.VARIABLES),
1533+
{ variables: [{ variableName: 'msg', value: assigned }] }
1534+
)
1535+
return run
1536+
}
1537+
1538+
it('expands an authored variable placeholder but not one the Variables block assigned', async () => {
1539+
const { ctx, resolver } = await createRunWithAssignedVariable('{{API_KEY}}')
1540+
1541+
const result = await resolver.resolveInputs(ctx, 'function', {
1542+
value: '<variable.authored> / <variable.msg>',
1543+
})
1544+
1545+
expect(result.value).toBe(`${SECRET} / {{API_KEY}}`)
1546+
})
1547+
1548+
it('binds a runtime-assigned variable naming a secret in Function code instead of inlining it', async () => {
1549+
const { block, ctx, resolver } = await createRunWithAssignedVariable('{{API_KEY}}')
1550+
1551+
const result = await resolver.resolveInputsForFunctionBlock(
1552+
ctx,
1553+
'function',
1554+
{ code: 'return "<variable.msg>"' },
1555+
block
1556+
)
1557+
1558+
expect(result.resolvedInputs.code).not.toContain('{{API_KEY}}')
1559+
expect(result.contextVariables).toEqual({ __blockRef_0: '{{API_KEY}}' })
1560+
})
1561+
1562+
it('compares run data in a Condition as written, never as the secret it names', async () => {
1563+
const { ctx, resolver, state } = await createRunWithAssignedVariable('{{API_KEY}}')
1564+
state.setBlockOutput('producer', { result: '{{API_KEY}}', pin: '{{PIN}}' } as never)
1565+
const conditionBlock = createBlock('condition', 'Condition', BlockType.CONDITION)
1566+
const evaluate = async (value: string) => {
1567+
const resolved = await resolver.resolveInputs(
1568+
ctx,
1569+
conditionBlock.id,
1570+
{ conditions: JSON.stringify([{ id: 'condition-1', title: 'if', value }]) },
1571+
conditionBlock
1572+
)
1573+
const expression = (resolved.conditions as Array<{ value: string }>)[0].value
1574+
return evaluateCompiledCondition(expression, ctx.environmentVariables)
1575+
}
1576+
1577+
await expect(evaluate(`<producer.result> === '${SECRET}'`)).resolves.toBe(false)
1578+
await expect(evaluate(`<producer.result> === '{' + '{API_KEY}}'`)).resolves.toBe(true)
1579+
await expect(evaluate(`<producer.pin> === '1234'`)).resolves.toBe(false)
1580+
await expect(evaluate(`<variable.msg> === '${SECRET}'`)).resolves.toBe(false)
1581+
await expect(evaluate(`<variable.authored> === '${SECRET}'`)).resolves.toBe(true)
1582+
})
1583+
})

0 commit comments

Comments
 (0)