Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/sim/executor/execution/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ export class DAGExecutor {

const filteredSnapshot: SerializableExecutionState = {
...sourceSnapshot,
// Variables restart from their saved values, so no reassignment carries over.
reassignedWorkflowVariableIds: undefined,

@cubic-dev-ai cubic-dev-ai Bot Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Clearing reassignedWorkflowVariableIds on run-from-block makes variables that a Variables block reassigned before the source snapshot look authored again. Their saved values can be run data, so a {{SECRET}} inside them could be expanded. Carry the saved set through instead of resetting it, or document this as an accepted risk.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At apps/sim/executor/execution/executor.ts, line 234:

<comment>Clearing `reassignedWorkflowVariableIds` on run-from-block makes variables that a Variables block reassigned before the source snapshot look authored again. Their saved values can be run data, so a `{{SECRET}}` inside them could be expanded. Carry the saved set through instead of resetting it, or document this as an accepted risk.</comment>

<file context>
@@ -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,
</file context>
Suggested change
reassignedWorkflowVariableIds: undefined,
reassignedWorkflowVariableIds: sourceSnapshot.reassignedWorkflowVariableIds,
Fix with cubic

blockStates: filteredBlockStates,
executedBlocks: filteredExecutedBlocks,
loopExecutions: filteredLoopExecutions,
Expand Down Expand Up @@ -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 ?? {}),
},
Expand Down
4 changes: 3 additions & 1 deletion apps/sim/executor/execution/snapshot-serializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -95,6 +95,7 @@ describe('serializePauseSnapshot', () => {
workflowVariables: {
secretResult: { type: 'string', value: '{{TOKEN}}' },
},
reassignedWorkflowVariableIds: new Set(['secretResult']),
workflowVariableResolvedSecretTraceProvenance: {
secretResult: provenance,
},
Expand All @@ -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')
Expand Down
3 changes: 3 additions & 0 deletions apps/sim/executor/execution/snapshot-serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,9 @@ function buildExecutionSnapshot(
},
resolvedSecretTraceProvenance:
context.resolvedSecretTraceRegistry?.exportCheckpointProvenance(),
reassignedWorkflowVariableIds: context.reassignedWorkflowVariableIds
? Array.from(context.reassignedWorkflowVariableIds)
: undefined,
workflowVariableResolvedSecretTraceProvenance:
context.workflowVariableResolvedSecretTraceProvenance,
workflowInputResolvedSecretTraceProvenance: context.workflowInputResolvedSecretTraceProvenance,
Expand Down
2 changes: 2 additions & 0 deletions apps/sim/executor/execution/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, ResolvedSecretTraceProvenanceV1>
/** Exact-value provenance for the persisted workflow input. Absence means legacy/untracked. */
Expand Down
2 changes: 2 additions & 0 deletions apps/sim/executor/handlers/variables/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ export class VariablesBlockHandler implements BlockHandler {
...variable,
value,
})
ctx.reassignedWorkflowVariableIds ??= new Set()
ctx.reassignedWorkflowVariableIds.add(id)
if (provenance) {
ctx.workflowVariableResolvedSecretTraceProvenance ??= {}
setWorkflowVariableProvenance(
Expand Down
5 changes: 5 additions & 0 deletions apps/sim/executor/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any>
/**
* 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<string>
workflowVariableResolvedSecretTraceProvenance?: Record<string, ResolvedSecretTraceProvenanceV1>
workflowInputResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceV1
finalOutputResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceV1
Expand Down
68 changes: 68 additions & 0 deletions apps/sim/executor/variables/resolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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=<producer.result>&auth={{TOKEN}}',
assembled: '{{<producer.name>}}',
split: '{{TO<producer.empty>KEN}}',
})

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: '<variable.note>' })
const code = await resolver.resolveInputsForFunctionBlock(
ctx,
'function',
{ code: 'const note = <variable.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: `<producer.result> === {{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 = {
Expand Down
118 changes: 95 additions & 23 deletions apps/sim/executor/variables/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>
): Promise<string> {
): 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 `{{<ref>}}` cannot
* assemble a name from run data either.
*/
async function replaceEnvVarsAsync(
template: string,
runValueSpans: readonly TextSpan[],
replacer: (match: string, index: number) => Promise<string>
): Promise<string> {
const pattern = createEnvVarPattern()
Expand All @@ -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

@cubic-dev-ai cubic-dev-ai Bot Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Empty run-data substitutions are never considered overlapping by this predicate, so they can assemble an environment placeholder that the next pass expands into a secret. Handle zero-length spans explicitly by blocking an environment match that strictly contains the insertion point.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At apps/sim/executor/variables/resolver.ts, line 162:

<comment>Empty run-data substitutions are never considered overlapping by this predicate, so they can assemble an environment placeholder that the next pass expands into a secret. Handle zero-length spans explicitly by blocking an environment match that strictly contains the insertion point.</comment>

<file context>
@@ -126,9 +158,11 @@ async function replaceEnvVarsAsync(
     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)
</file context>
Fix with cubic

result += template.slice(cursor, index)
result += await replacer(fullMatch, index)
cursor = index + fullMatch.length
cursor = end
}
return result + template.slice(cursor)
}
Expand Down Expand Up @@ -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,
Expand All @@ -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,
]
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
* (`<variable.indirectSecret>`). 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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Loading