From 20df06a13755bfec67f47548b37a0da633782131 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 28 Nov 2026 14:05:07 -0800 Subject: [PATCH] fix(executor): never expand {{ENV}} placeholders that arrive as run data The template resolver spliced values into a field and then expanded {{NAME}} over the result, so trigger data carrying {{SECRET}} resolved to the decrypted secret. The env pass now skips any placeholder overlapping a substituted run value. Workflow variables keep their authored {{NAME}} expansion until a Variables block reassigns them this run; the reassigned set persists across pause/resume and gates Function-block literal inlining too. --- apps/sim/executor/execution/executor.ts | 3 + .../execution/snapshot-serializer.test.ts | 4 +- .../executor/execution/snapshot-serializer.ts | 3 + apps/sim/executor/execution/types.ts | 2 + .../executor/handlers/variables/handler.ts | 2 + apps/sim/executor/types.ts | 5 + apps/sim/executor/variables/resolver.test.ts | 68 +++++++++ apps/sim/executor/variables/resolver.ts | 118 ++++++++++++---- .../executor/variables/resolvers/workflow.ts | 129 +++++++++--------- 9 files changed, 249 insertions(+), 85 deletions(-) diff --git a/apps/sim/executor/execution/executor.ts b/apps/sim/executor/execution/executor.ts index da887cd2a68..4d19e5110fd 100644 --- a/apps/sim/executor/execution/executor.ts +++ b/apps/sim/executor/execution/executor.ts @@ -230,6 +230,8 @@ export class DAGExecutor { const filteredSnapshot: SerializableExecutionState = { ...sourceSnapshot, + // Variables restart from their saved values, so no reassignment carries over. + reassignedWorkflowVariableIds: undefined, blockStates: filteredBlockStates, executedBlocks: filteredExecutedBlocks, loopExecutions: filteredLoopExecutions, @@ -507,6 +509,7 @@ export class DAGExecutor { environmentVariables: this.environmentVariables, resolvedSecretTraceRegistry: this.contextExtensions.resolvedSecretTraceRegistry, workflowVariables: this.workflowVariables, + reassignedWorkflowVariableIds: new Set(snapshotState?.reassignedWorkflowVariableIds), workflowVariableResolvedSecretTraceProvenance: { ...(snapshotState?.workflowVariableResolvedSecretTraceProvenance ?? {}), }, diff --git a/apps/sim/executor/execution/snapshot-serializer.test.ts b/apps/sim/executor/execution/snapshot-serializer.test.ts index 3fb1451d70b..1e0089e8d96 100644 --- a/apps/sim/executor/execution/snapshot-serializer.test.ts +++ b/apps/sim/executor/execution/snapshot-serializer.test.ts @@ -62,7 +62,7 @@ describe('serializePauseSnapshot', () => { expect(snapshot.snapshot).not.toContain('raw-secret') }) - it('persists only encrypted value-adjacent provenance across pause and resume', () => { + it('persists only encrypted provenance and the variable-reassignment set across pause and resume', () => { const provenance = { version: 1 as const, complete: true, @@ -95,6 +95,7 @@ describe('serializePauseSnapshot', () => { workflowVariables: { secretResult: { type: 'string', value: '{{TOKEN}}' }, }, + reassignedWorkflowVariableIds: new Set(['secretResult']), workflowVariableResolvedSecretTraceProvenance: { secretResult: provenance, }, @@ -112,6 +113,7 @@ describe('serializePauseSnapshot', () => { expect(serialized.state.workflowVariableResolvedSecretTraceProvenance.secretResult).toEqual( provenance ) + expect(serialized.state.reassignedWorkflowVariableIds).toEqual(['secretResult']) expect(serialized.state.workflowInputResolvedSecretTraceProvenance).toEqual(provenance) expect(serialized.state.finalOutputResolvedSecretTraceProvenance).toEqual(provenance) expect(snapshot.snapshot).not.toContain('raw-secret') diff --git a/apps/sim/executor/execution/snapshot-serializer.ts b/apps/sim/executor/execution/snapshot-serializer.ts index 6b0a19b7b18..0a87a7d648f 100644 --- a/apps/sim/executor/execution/snapshot-serializer.ts +++ b/apps/sim/executor/execution/snapshot-serializer.ts @@ -240,6 +240,9 @@ function buildExecutionSnapshot( }, resolvedSecretTraceProvenance: context.resolvedSecretTraceRegistry?.exportCheckpointProvenance(), + reassignedWorkflowVariableIds: context.reassignedWorkflowVariableIds + ? Array.from(context.reassignedWorkflowVariableIds) + : undefined, workflowVariableResolvedSecretTraceProvenance: context.workflowVariableResolvedSecretTraceProvenance, workflowInputResolvedSecretTraceProvenance: context.workflowInputResolvedSecretTraceProvenance, diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index 550b308a809..b57504adeec 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -141,6 +141,8 @@ export interface SerializableExecutionState { } /** Encrypted-only provenance for Secrets-tab values resolved during this execution. */ resolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceV1 + /** Workflow variables a Variables block reassigned before the pause; see `ExecutionContext`. */ + reassignedWorkflowVariableIds?: string[] /** Exact-value provenance for mutable workflow variables, keyed by persisted variable id. */ workflowVariableResolvedSecretTraceProvenance?: Record /** Exact-value provenance for the persisted workflow input. Absence means legacy/untracked. */ diff --git a/apps/sim/executor/handlers/variables/handler.ts b/apps/sim/executor/handlers/variables/handler.ts index 28e32d0179d..7bbac29d313 100644 --- a/apps/sim/executor/handlers/variables/handler.ts +++ b/apps/sim/executor/handlers/variables/handler.ts @@ -128,6 +128,8 @@ export class VariablesBlockHandler implements BlockHandler { ...variable, value, }) + ctx.reassignedWorkflowVariableIds ??= new Set() + ctx.reassignedWorkflowVariableIds.add(id) if (provenance) { ctx.workflowVariableResolvedSecretTraceProvenance ??= {} setWorkflowVariableProvenance( diff --git a/apps/sim/executor/types.ts b/apps/sim/executor/types.ts index 69142a48a17..f62a5b40213 100644 --- a/apps/sim/executor/types.ts +++ b/apps/sim/executor/types.ts @@ -526,6 +526,11 @@ export interface ExecutionContext { /** Exact candidates that may be carried by this block's terminal error, never its normal output. */ errorResolvedSecretTraceRegistry?: ResolvedSecretTraceRegistry workflowVariables?: Record + /** + * Ids of workflow variables a Variables block reassigned this run. Their values may be run + * data, so a `{{NAME}}` they carry is never expanded as if the author had written it. + */ + reassignedWorkflowVariableIds?: Set workflowVariableResolvedSecretTraceProvenance?: Record workflowInputResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceV1 finalOutputResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceV1 diff --git a/apps/sim/executor/variables/resolver.test.ts b/apps/sim/executor/variables/resolver.test.ts index 25142569776..190e42d9972 100644 --- a/apps/sim/executor/variables/resolver.test.ts +++ b/apps/sim/executor/variables/resolver.test.ts @@ -24,6 +24,7 @@ import { getBlock } from '@/blocks/registry' import type { BlockConfig } from '@/blocks/types' import { BlockType } from '@/executor/constants' import { ExecutionState } from '@/executor/execution/state' +import { VariablesBlockHandler } from '@/executor/handlers/variables/handler' import type { ExecutionContext } from '@/executor/types' import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' import { buildStartBlockOutput } from '@/executor/utils/start-block' @@ -538,6 +539,73 @@ describe('VariableResolver function block inputs', () => { ]) }) + it('never expands a secret placeholder that arrives as run data', async () => { + const { ctx, resolver, state } = createResolver() + state.setBlockOutput('producer', { result: '{{TOKEN}}', name: 'TOKEN', empty: '' } as never) + ctx.environmentVariables = { TOKEN: 'resolved-secret' } + + const result = await resolver.resolveInputs(ctx, 'function', { + query: 'note=&auth={{TOKEN}}', + assembled: '{{}}', + split: '{{TOKEN}}', + }) + + expect(result).toEqual({ + query: 'note={{TOKEN}}&auth=resolved-secret', + assembled: '{{TOKEN}}', + split: '{{TOKEN}}', + }) + }) + + it('never expands a secret placeholder a Variables block assigned from run data', async () => { + const { block, ctx, resolver } = createResolver('javascript') + ctx.environmentVariables = { TOKEN: 'resolved-secret' } + ctx.workflowVariables = { + 'var-1': { id: 'var-1', name: 'note', type: 'string', value: 'authored' }, + } + await new VariablesBlockHandler().execute( + ctx, + createBlock('vars', 'Vars', BlockType.VARIABLES), + { + variables: [ + { variableId: 'var-1', variableName: 'note', type: 'string', value: '{{TOKEN}}' }, + ], + } + ) + + const resolved = await resolver.resolveInputs(ctx, 'function', { value: '' }) + const code = await resolver.resolveInputsForFunctionBlock( + ctx, + 'function', + { code: 'const note = ' }, + block + ) + + expect(resolved.value).toBe('{{TOKEN}}') + expect(code.resolvedInputs.code).toBe('const note = globalThis["__blockRef_0"]') + expect(code.contextVariables).toEqual({ __blockRef_0: '{{TOKEN}}' }) + }) + + it('keeps a secret placeholder that arrives as run data out of resolved condition text', async () => { + const { ctx, resolver, state } = createResolver() + state.setBlockOutput('producer', { result: '{{COUNT}}' } as never) + ctx.environmentVariables = { COUNT: '7' } + const conditionBlock = createBlock('condition', 'Condition', BlockType.CONDITION) + + const resolved = await resolver.resolveInputs( + ctx, + conditionBlock.id, + { + conditions: JSON.stringify([ + { id: 'condition-1', title: 'if', value: ` === {{COUNT}}` }, + ]), + }, + conditionBlock + ) + + expect((resolved.conditions as Array<{ value: string }>)[0].value).toBe(`'{{COUNT}}' === 7`) + }) + it('binds propagated references to exact model-selected inputs without changing runtime values', async () => { const secret = 'xxxxxxxx' const provenance = { diff --git a/apps/sim/executor/variables/resolver.ts b/apps/sim/executor/variables/resolver.ts index 08e7b299e5c..face7c716a8 100644 --- a/apps/sim/executor/variables/resolver.ts +++ b/apps/sim/executor/variables/resolver.ts @@ -97,27 +97,59 @@ function getNestedLargeValueMaterializationError(): Error { ) } +/** A half-open `[start, end)` range of offsets in a resolved string. */ +interface TextSpan { + start: number + end: number +} + +/** The output range a reference's value was written to. */ +interface Substitution extends TextSpan { + reference: string +} + +/** + * Replaces each reference in `template`. Alongside the text it returns where each value landed, + * so a later `{{NAME}}` pass can tell run data apart from authored text. + */ async function replaceValidReferencesAsync( template: string, replacer: (match: string, index: number, template: string) => Promise -): Promise { +): Promise<{ text: string; substitutions: Substitution[] }> { const pattern = createReferencePattern() + const substitutions: Substitution[] = [] let cursor = 0 - let result = '' + let text = '' for (const match of template.matchAll(pattern)) { const fullMatch = match[0] const index = match.index ?? 0 - result += template.slice(cursor, index) - result += isLikelyReferenceSegment(fullMatch) + text += template.slice(cursor, index) + const replacement = isLikelyReferenceSegment(fullMatch) ? await replacer(fullMatch, index, template) : fullMatch + if (replacement !== fullMatch) { + substitutions.push({ + start: text.length, + end: text.length + replacement.length, + reference: fullMatch, + }) + } + text += replacement cursor = index + fullMatch.length } - return result + template.slice(cursor) + return { text: text + template.slice(cursor), substitutions } } +/** + * Replaces each `{{NAME}}` in `template`, leaving as written any match that overlaps one of + * `runValueSpans`. Those spans hold run data (trigger payloads, block outputs), and expanding a + * placeholder found there would hand whoever supplied the data the plaintext of any secret they + * can name. An empty span still splits a match that straddles it, so `{{}}` cannot + * assemble a name from run data either. + */ async function replaceEnvVarsAsync( template: string, + runValueSpans: readonly TextSpan[], replacer: (match: string, index: number) => Promise ): Promise { const pattern = createEnvVarPattern() @@ -126,9 +158,11 @@ async function replaceEnvVarsAsync( for (const match of template.matchAll(pattern)) { const fullMatch = match[0] const index = match.index ?? 0 + const end = index + fullMatch.length + if (runValueSpans.some((span) => span.start < end && index < span.end)) continue result += template.slice(cursor, index) result += await replacer(fullMatch, index) - cursor = index + fullMatch.length + cursor = end } return result + template.slice(cursor) } @@ -344,6 +378,7 @@ function isJsonTextInput(block: SerializedBlock | undefined, key: string): boole export class VariableResolver { private resolvers: Resolver[] private blockResolver: BlockResolver + private workflowResolver: WorkflowResolver constructor( workflow: SerializedWorkflow, @@ -352,10 +387,11 @@ export class VariableResolver { options: { navigatePathAsync?: AsyncPathNavigator } = {} ) { this.blockResolver = new BlockResolver(workflow, options.navigatePathAsync) + this.workflowResolver = new WorkflowResolver(workflowVariables, options.navigatePathAsync) this.resolvers = [ new LoopResolver(workflow, options.navigatePathAsync), new ParallelResolver(workflow, options.navigatePathAsync), - new WorkflowResolver(workflowVariables, options.navigatePathAsync), + this.workflowResolver, new EnvResolver(), this.blockResolver, ] @@ -645,7 +681,7 @@ export class VariableResolver { let displayCursor = 0 const scan: CodeTemplateScan = { template } - const result = await replaceValidReferencesAsync(template, async (match, index) => { + const { text: result } = await replaceValidReferencesAsync(template, async (match, index) => { if (replacementError) return match displayResult += template.slice(displayCursor, index) displayCursor = index + match.length @@ -804,7 +840,7 @@ export class VariableResolver { throw getNestedLargeValueMaterializationError() } - if (this.canInlineResolvedCodeLiteral(effectiveValue, match)) { + if (this.canInlineResolvedCodeLiteral(effectiveValue, match, resolutionContext)) { const replacement = this.blockResolver.formatValueForBlock( effectiveValue, BlockType.FUNCTION, @@ -1094,23 +1130,53 @@ export class VariableResolver { * is what let a runtime-assigned variable or loop item carrying trigger data close the * string it landed in and run as code. * - * The placeholder case is admitted only for a workflow variable, never for a loop item or - * any other run value. Whoever supplies the text picks which secret the compiler expands - * into the generated source, so that choice stays with the surface an author configures. + * The placeholder case is admitted only for an authored variable (`readsAuthoredVariable`), + * never for a loop item or any other run value. Whoever supplies the text picks which secret + * the compiler expands into the generated source, so that choice stays with the surface an + * author configures. */ - private canInlineResolvedCodeLiteral(value: unknown, reference: string): boolean { + private canInlineResolvedCodeLiteral( + value: unknown, + reference: string, + context: ResolutionContext + ): boolean { if (value === null || typeof value === 'number' || typeof value === 'boolean') { return true } if (typeof value !== 'string') { return false } - if (parseReferencePath(reference)[0] !== REFERENCE.PREFIX.VARIABLE) { + if (!this.readsAuthoredVariable(reference, context)) { return false } return createEnvVarPattern().test(value) && !/['"`$\\\n\r\u2028\u2029]/.test(value) } + /** + * Whether `reference` reads a workflow variable that still holds its saved value: the one + * reference whose value an author configures to carry a `{{NAME}}` placeholder + * (``). A variable a Variables block reassigned may hold run data, + * so it reads like any other run value. + */ + private readsAuthoredVariable(reference: string, context: ResolutionContext): boolean { + if (parseReferencePath(reference)[0] !== REFERENCE.PREFIX.VARIABLE) return false + const variableId = this.workflowResolver.findVariableId(reference, context) + return ( + variableId !== undefined && + !context.executionContext.reassignedWorkflowVariableIds?.has(variableId) + ) + } + + /** The substitutions whose text is run data rather than an authored variable's value. */ + private runValueSpans( + substitutions: readonly Substitution[], + context: ResolutionContext + ): TextSpan[] { + return substitutions.filter( + (substitution) => !this.readsAuthoredVariable(substitution.reference, context) + ) + } + private formatJavaScriptAsyncExpression( expression: string, scan: CodeTemplateScan, @@ -1867,7 +1933,7 @@ export class VariableResolver { const spliceReference = placeholderSplicer(template, options.jsonText) let projectedReferenceResult = '' let projectedReferenceCursor = 0 - let result = await replaceValidReferencesAsync(template, async (match, index) => { + const references = await replaceValidReferencesAsync(template, async (match, index) => { if (replacementError) return match projectedReferenceResult += template.slice(projectedReferenceCursor, index) @@ -1918,12 +1984,17 @@ export class VariableResolver { throw replacementError } - const spliceEnvVar = placeholderSplicer(result, options.jsonText) - result = await replaceEnvVarsAsync(result, async (match, index) => { - const resolved = await this.resolveReference(match, resolutionContext) - if (typeof resolved !== 'string') return match - return spliceEnvVar(resolved, index, index + match.length, true) - }) + const spliceEnvVar = placeholderSplicer(references.text, options.jsonText) + const runValueSpans = this.runValueSpans(references.substitutions, resolutionContext) + const result = await replaceEnvVarsAsync( + references.text, + runValueSpans, + async (match, index) => { + const resolved = await this.resolveReference(match, resolutionContext) + if (typeof resolved !== 'string') return match + return spliceEnvVar(resolved, index, index + match.length, true) + } + ) ctx.resolvedSecretTraceRegistry?.recordResolvedInputProjection( options.inputPath, result, @@ -1952,7 +2023,7 @@ export class VariableResolver { let projectedReferenceResult = '' let projectedReferenceCursor = 0 - let result = await replaceValidReferencesAsync(template, async (match, index) => { + const references = await replaceValidReferencesAsync(template, async (match, index) => { if (replacementError) return match projectedReferenceResult += template.slice(projectedReferenceCursor, index) @@ -2002,7 +2073,8 @@ export class VariableResolver { throw replacementError } - result = await replaceEnvVarsAsync(result, async (match) => { + const runValueSpans = this.runValueSpans(references.substitutions, resolutionContext) + const result = await replaceEnvVarsAsync(references.text, runValueSpans, async (match) => { const resolved = await this.resolveReference(match, resolutionContext) if (typeof resolved !== 'string') return match return isStructurallyInertConditionLiteral(resolved) ? resolved : match diff --git a/apps/sim/executor/variables/resolvers/workflow.ts b/apps/sim/executor/variables/resolvers/workflow.ts index 3cbdc7decee..6bdbc41f410 100644 --- a/apps/sim/executor/variables/resolvers/workflow.ts +++ b/apps/sim/executor/variables/resolvers/workflow.ts @@ -14,6 +14,13 @@ import type { VariableType } from '@/stores/variables/types' const logger = createLogger('WorkflowResolver') +interface WorkflowVariableEntry { + id?: string + name?: string + type?: VariableType + value?: unknown +} + export class WorkflowResolver implements Resolver { constructor( private workflowVariables: Record, @@ -33,49 +40,43 @@ export class WorkflowResolver implements Resolver { } resolve(reference: string, context: ResolutionContext): any { - const parts = parseReferencePath(reference) - if (parts.length < 2) { - logger.warn('Invalid variable reference - missing variable name', { reference }) - return undefined - } - - const [_, rawVariableName, ...rawPathParts] = parts - const { property: variableName, pathParts: bracketPathParts } = - splitLeadingBracketPath(rawVariableName) - const pathParts = [...bracketPathParts, ...rawPathParts] - const normalizedRefName = normalizeName(variableName) - - const workflowVars = context.executionContext.workflowVariables || this.workflowVariables + const match = this.findVariable(reference, context) + if (!match) return undefined + const { variable: v, variableName, pathParts } = match - for (const varObj of Object.values(workflowVars)) { - const v = varObj as any - if (!v) continue + const normalizedType = (v.type === 'string' ? 'plain' : v.type) || 'plain' + const value = this.resolveVariableValue(v.value, normalizedType, variableName) - // Match by normalized name or exact ID - const normalizedVarName = v.name ? normalizeName(v.name) : '' - if (normalizedVarName === normalizedRefName || v.id === variableName) { - const normalizedType = (v.type === 'string' ? 'plain' : v.type) || 'plain' - let value: any - value = this.resolveVariableValue(v.value, normalizedType, variableName) - - if (pathParts.length > 0) { - return navigatePath(value, pathParts, { - allowLargeValueRefs: context.allowLargeValueRefs, - executionContext: context.executionContext, - }) - } + if (pathParts.length > 0) { + return navigatePath(value, pathParts, { + allowLargeValueRefs: context.allowLargeValueRefs, + executionContext: context.executionContext, + }) + } - if (!context.allowLargeValueRefs) { - assertNoLargeValueRefs(value) - } - return value - } + if (!context.allowLargeValueRefs) { + assertNoLargeValueRefs(value) } + return value + } - return undefined + /** The `workflowVariables` key of the variable `reference` reads, if one matches. */ + findVariableId(reference: string, context: ResolutionContext): string | undefined { + return this.findVariable(reference, context)?.variableId } - async resolveAsync(reference: string, context: ResolutionContext): Promise { + /** Matches a variable by normalized name or exact id. */ + private findVariable( + reference: string, + context: ResolutionContext + ): + | { + variableId: string + variable: WorkflowVariableEntry + variableName: string + pathParts: string[] + } + | undefined { const parts = parseReferencePath(reference) if (parts.length < 2) { logger.warn('Invalid variable reference - missing variable name', { reference }) @@ -89,36 +90,42 @@ export class WorkflowResolver implements Resolver { const normalizedRefName = normalizeName(variableName) const workflowVars = context.executionContext.workflowVariables || this.workflowVariables - for (const [variableId, varObj] of Object.entries(workflowVars)) { - const v = varObj as any - if (!v) continue - - const normalizedVarName = v.name ? normalizeName(v.name) : '' - if (normalizedVarName === normalizedRefName || v.id === variableName) { - const normalizedType = (v.type === 'string' ? 'plain' : v.type) || 'plain' - let value: any - value = this.resolveVariableValue(v.value, normalizedType, variableName) - - if (pathParts.length > 0) { - const resolved = this.navigatePathAsync - ? this.navigatePathAsync(value, pathParts, context) - : navigatePath(value, pathParts, { - allowLargeValueRefs: context.allowLargeValueRefs, - executionContext: context.executionContext, - }) - return this.importResolvedVariableProvenance(variableId, await resolved, context) - } - - if (!context.allowLargeValueRefs) { - assertNoLargeValueRefs(value) - } - return this.importResolvedVariableProvenance(variableId, value, context) + for (const [variableId, variable] of Object.entries( + workflowVars + )) { + if (!variable) continue + const normalizedVarName = variable.name ? normalizeName(variable.name) : '' + if (normalizedVarName === normalizedRefName || variable.id === variableName) { + return { variableId, variable, variableName, pathParts } } } - return undefined } + async resolveAsync(reference: string, context: ResolutionContext): Promise { + const match = this.findVariable(reference, context) + if (!match) return undefined + const { variableId, variable: v, variableName, pathParts } = match + + const normalizedType = (v.type === 'string' ? 'plain' : v.type) || 'plain' + const value = this.resolveVariableValue(v.value, normalizedType, variableName) + + if (pathParts.length > 0) { + const resolved = this.navigatePathAsync + ? this.navigatePathAsync(value, pathParts, context) + : navigatePath(value, pathParts, { + allowLargeValueRefs: context.allowLargeValueRefs, + executionContext: context.executionContext, + }) + return this.importResolvedVariableProvenance(variableId, await resolved, context) + } + + if (!context.allowLargeValueRefs) { + assertNoLargeValueRefs(value) + } + return this.importResolvedVariableProvenance(variableId, value, context) + } + private async importResolvedVariableProvenance( variableId: string, value: unknown,