Skip to content

Commit 2ba88ef

Browse files
authored
fix(workflows-as-code): refuse copilot writes to server-managed fields in source apply (#10744)
1 parent b5bfa74 commit 2ba88ef

4 files changed

Lines changed: 201 additions & 24 deletions

File tree

‎apps/sim/lib/workflows/code/apply/gates.test.ts‎

Lines changed: 92 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,20 @@ const MOCK_REGISTRY_BLOCKS: Record<string, unknown> = {
5858
mothership: {
5959
type: 'mothership',
6060
name: 'Sim Chat',
61-
subBlocks: [{ id: 'tools', type: 'tool-input' }],
61+
subBlocks: [
62+
{ id: 'prompt', type: 'long-input' },
63+
{ id: 'tools', type: 'tool-input' },
64+
{ id: 'secretScope', type: 'dropdown', hideFromCopilot: true },
65+
{ id: 'mountedSecrets', type: 'dropdown', hideFromCopilot: true },
66+
],
67+
},
68+
mothership_next: {
69+
type: 'mothership_next',
70+
name: 'Sim Chat Next',
71+
subBlocks: [
72+
{ id: 'prompt', type: 'long-input' },
73+
{ id: 'secretScope', type: 'dropdown', hideFromCopilot: true },
74+
],
6275
},
6376
function: {
6477
type: 'function',
@@ -233,9 +246,16 @@ function isCredentialField(blockType: string, field: string): boolean {
233246
return config?.subBlocks.some((sb) => sb.id === field && sb.type === 'oauth-input') ?? false
234247
}
235248

236-
function toolInputField(blockType: string, field: string): boolean {
237-
const config = MOCK_REGISTRY_BLOCKS[blockType] as { subBlocks: { id: string; type: string }[] }
238-
return config?.subBlocks.some((sb) => sb.id === field && sb.type === 'tool-input') ?? false
249+
/** An engine validation error source apply raises only for Copilot: a tool binding or hidden field. */
250+
function copilotGatedField(blockType: string, field: string): boolean {
251+
const config = MOCK_REGISTRY_BLOCKS[blockType] as {
252+
subBlocks: { id: string; type: string; hideFromCopilot?: boolean }[]
253+
}
254+
return (
255+
config?.subBlocks.some(
256+
(sb) => sb.id === field && (sb.type === 'tool-input' || sb.hideFromCopilot === true)
257+
) ?? false
258+
)
239259
}
240260

241261
async function engineRefusals(testCase: ParityCase): Promise<string[]> {
@@ -269,7 +289,7 @@ async function engineRefusals(testCase: ParityCase): Promise<string[]> {
269289
if (!isDeferredSkippedItem(item)) refusals.add(`${item.type}:${item.blockId}`)
270290
}
271291
for (const error of result.validationErrors) {
272-
if (testCase.isCopilot && toolInputField(error.blockType, error.field)) {
292+
if (testCase.isCopilot && copilotGatedField(error.blockType, error.field)) {
273293
refusals.add(`invalid_subblock_field:${error.blockId}`)
274294
}
275295
}
@@ -323,6 +343,23 @@ const lockedLoopBase = graph(
323343
block(ID.b, 'agent', 'Outside', { sub: { systemPrompt: 'old' } })
324344
)
325345

346+
/** Sets a stored Sim Chat block's server-managed fields; Copilot is refused, a user is not. */
347+
const setServerManagedFields = {
348+
base: graph(block(ID.a, 'mothership', 'Sim Chat', { sub: { prompt: 'hi' } })),
349+
operations: [
350+
{
351+
operation_type: 'edit',
352+
block_id: ID.a,
353+
params: { inputs: { secretScope: 'selected', mountedSecrets: ['FOO'] } },
354+
},
355+
],
356+
target: graph(
357+
block(ID.a, 'mothership', 'Sim Chat', {
358+
sub: { prompt: 'hi', secretScope: 'selected', mountedSecrets: ['FOO'] },
359+
})
360+
),
361+
} satisfies Pick<ParityCase, 'base' | 'operations' | 'target'>
362+
326363
const CASES: ParityCase[] = [
327364
// editing/operations.test.ts › sunset block types
328365
{
@@ -735,6 +772,56 @@ const CASES: ParityCase[] = [
735772
isCopilot: true,
736773
expected: [`invalid_subblock_field:${ID.a}`],
737774
},
775+
// editing/validation.test.ts › hideFromCopilot fields (server-managed)
776+
{
777+
name: 'copilot: refuses setting a server-managed field on a stored block',
778+
...setServerManagedFields,
779+
isCopilot: true,
780+
expected: [`invalid_subblock_field:${ID.a}`],
781+
},
782+
{
783+
name: 'copilot: refuses a new block that sets a server-managed field',
784+
base: graph(),
785+
operations: [
786+
{
787+
operation_type: 'add',
788+
block_id: ID.a,
789+
params: { type: 'mothership', name: 'Sim Chat', inputs: { secretScope: 'all' } },
790+
},
791+
],
792+
target: graph(block(ID.a, 'mothership', 'Sim Chat', { sub: { secretScope: 'all' } })),
793+
isCopilot: true,
794+
expected: [`invalid_subblock_field:${ID.a}`],
795+
},
796+
{
797+
name: 'copilot: a stored server-managed value the edit leaves alone is not refused',
798+
base: graph(
799+
block(ID.a, 'mothership', 'Sim Chat', {
800+
sub: { prompt: 'hi', secretScope: 'selected', mountedSecrets: ['FOO'] },
801+
})
802+
),
803+
operations: [{ operation_type: 'edit', block_id: ID.a, params: { inputs: { prompt: 'bye' } } }],
804+
target: graph(
805+
block(ID.a, 'mothership', 'Sim Chat', {
806+
sub: { prompt: 'bye', secretScope: 'selected', mountedSecrets: ['FOO'] },
807+
})
808+
),
809+
isCopilot: true,
810+
expected: [],
811+
},
812+
{
813+
name: 'copilot: a retype keeping a stored server-managed value is not refused',
814+
base: graph(block(ID.a, 'mothership', 'Sim Chat', { sub: { secretScope: 'selected' } })),
815+
operations: [{ operation_type: 'edit', block_id: ID.a, params: { type: 'mothership_next' } }],
816+
target: graph(block(ID.a, 'mothership_next', 'Sim Chat', { sub: { secretScope: 'selected' } })),
817+
isCopilot: true,
818+
expected: [],
819+
},
820+
{
821+
name: 'user: accepts setting a server-managed field',
822+
...setServerManagedFields,
823+
expected: [],
824+
},
738825
// credentials (editing/validation.ts preValidateCredentialInputs)
739826
{
740827
name: 'credentials: refuses a credential the user cannot reach, on add and on edit',

‎apps/sim/lib/workflows/code/apply/gates.ts‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@ import type {
2828
SkippedItemType,
2929
ValidationError,
3030
} from '@/lib/workflows/editing/types'
31-
import { preValidateCredentialInputs } from '@/lib/workflows/editing/validation'
31+
import {
32+
preValidateCredentialInputs,
33+
serverManagedFieldError,
34+
} from '@/lib/workflows/editing/validation'
3235
import { validateToolBindingAuthoring } from '@/lib/workflows/tool-input/authoring'
3336
import { getBlock } from '@/blocks/registry'
3437

@@ -37,8 +40,8 @@ import { getBlock } from '@/blocks/registry'
3740
* operations. `BLOCK_GATES` (`editing/gates.ts`) is the one list both run: the engine withholds
3841
* what a gate refuses and applies the rest; source apply is atomic, so every refusal here is an
3942
* error diagnostic and nothing is written. The checks below that are not in that list (credential
40-
* reachability, the copilot tool-binding contract, enablement, the sandbox plan) call the
41-
* engine's own functions.
43+
* reachability, the copilot tool-binding contract and server-managed fields, enablement, the
44+
* sandbox plan) call the engine's own functions.
4245
*
4346
* Gates run on added and changed blocks only, as the engine runs them on the blocks an operation
4447
* names: a stored block the caller left alone is never refused for a policy that changed after
@@ -119,7 +122,10 @@ export interface GateSourceDiffArgs {
119122
/** The governed human subject: credential reachability is checked as this user. */
120123
subjectUserId: string
121124
workspaceId: string
122-
/** Copilot writes are held to the internal tool-binding authoring contract. */
125+
/**
126+
* Copilot writes are held to the internal tool-binding authoring contract and may not set a
127+
* `hideFromCopilot` field, as the editing engine refuses one.
128+
*/
123129
isCopilot: boolean
124130
}
125131

@@ -410,22 +416,33 @@ export async function gateSourceDiff(args: GateSourceDiffArgs): Promise<SourceGa
410416
gateFieldValues(entry, toolInputFields, ctx, record)
411417

412418
if (args.isCopilot) {
419+
const invalidField = (field: string, message: string) =>
420+
diagnostics.push({
421+
code: 'E_APPLY_INVALID_SUBBLOCK_FIELD',
422+
severity: 'error',
423+
message,
424+
...located(block.id),
425+
param: field,
426+
})
427+
const hiddenFields = new Set(
428+
(getBlock(block.type)?.subBlocks ?? [])
429+
.filter((subBlock) => subBlock.hideFromCopilot === true)
430+
.map((subBlock) => subBlock.id)
431+
)
432+
for (const field of entry.changedFields) {
433+
if (!hiddenFields.has(field)) continue
434+
// A retype lists every kept value; one kept as stored is no write by Copilot.
435+
if (isEqual(subBlockValue(entry.baseBlock, field), subBlockValue(block, field))) continue
436+
invalidField(field, serverManagedFieldError(field, block.type))
437+
}
413438
for (const field of toolInputFields) {
414439
if (!entry.changedFields.includes(field)) continue
415440
const error = validateToolBindingAuthoring(
416441
block.type,
417442
subBlockValue(block, field),
418443
subBlockValue(entry.baseBlock, field)
419444
)
420-
if (error) {
421-
diagnostics.push({
422-
code: 'E_APPLY_INVALID_SUBBLOCK_FIELD',
423-
severity: 'error',
424-
message: error,
425-
...located(block.id),
426-
param: field,
427-
})
428-
}
445+
if (error) invalidField(field, error)
429446
}
430447
}
431448

‎apps/sim/lib/workflows/code/corpus/copilot-gates.corpus.test.ts‎

Lines changed: 73 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
* every tool the editor's picker writes (the corpus `agent-tools` cases) is printed as source and
55
* written into the same workflow without its tools, as Mothership adds a tool, then gated as
66
* Copilot and as a user. A finding only Copilot gets is source the SDK itself prints that
7-
* Mothership cannot apply.
7+
* Mothership cannot apply. A server-managed (`hideFromCopilot`) value a user stored likewise
8+
* round-trips through the print, so Copilot is refused only for changing it.
89
*/
910
import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock'
1011
import { integrationsAvailabilityMock } from '@sim/testing/mocks/integrations-availability.mock'
@@ -46,10 +47,8 @@ function withoutTools(state: WorkflowState): WorkflowState {
4647
return stripped
4748
}
4849

49-
/** The printed source of `state`, applied over the same workflow without its tools. */
50-
function addPrintedTools(state: WorkflowState): ToolAddition {
51-
const before = withoutTools(state)
52-
const { files } = getSource(state, catalog)
50+
/** Source `files` applied over the stored `before`. */
51+
function applyOver(before: WorkflowState, files: Record<string, string>): ToolAddition {
5352
const applied = applySource(before, getSource(before, catalog), files, catalog)
5453
if (!applied.materialized) {
5554
const errors = applied.compiled.diagnostics.filter((d) => d.severity === 'error')
@@ -63,6 +62,11 @@ function addPrintedTools(state: WorkflowState): ToolAddition {
6362
}
6463
}
6564

65+
/** The printed source of `state`, applied over the same workflow without its tools. */
66+
function addPrintedTools(state: WorkflowState): ToolAddition {
67+
return applyOver(withoutTools(state), getSource(state, catalog).files)
68+
}
69+
6670
function gate({ base, target }: ToolAddition, isCopilot: boolean) {
6771
return gateSourceDiff({
6872
base,
@@ -102,6 +106,70 @@ describe('tools the picker writes, printed and added as Copilot', () => {
102106
})
103107
})
104108

109+
const START_ONLY: WorkflowState = {
110+
blocks: {
111+
'start-1': {
112+
id: 'start-1',
113+
type: 'start_trigger',
114+
name: 'Start',
115+
position: { x: 0, y: 0 },
116+
subBlocks: {},
117+
outputs: {},
118+
enabled: true,
119+
},
120+
},
121+
edges: [],
122+
loops: {},
123+
parallels: {},
124+
}
125+
126+
/** {@link START_ONLY} with a Sim Chat block storing `values`. */
127+
function chatWorkflow(values: Record<string, unknown>): WorkflowState {
128+
const chat = getBlock('mothership')
129+
const subBlocks: WorkflowState['blocks'][string]['subBlocks'] = {}
130+
for (const [id, value] of Object.entries(values)) {
131+
const type = chat?.subBlocks.find((subBlock) => subBlock.id === id)?.type ?? 'short-input'
132+
subBlocks[id] = { id, type, value } as WorkflowState['blocks'][string]['subBlocks'][string]
133+
}
134+
const block = {
135+
id: 'chat-1',
136+
type: 'mothership',
137+
name: 'Chat',
138+
position: { x: 200, y: 0 },
139+
subBlocks,
140+
outputs: {},
141+
enabled: true,
142+
}
143+
return { ...START_ONLY, blocks: { ...START_ONLY.blocks, [block.id]: block } }
144+
}
145+
146+
describe('server-managed fields a user set, in source Copilot applies', () => {
147+
const stored = chatWorkflow({ prompt: 'hi', secretScope: 'selected', mountedSecrets: ['FOO'] })
148+
const { files } = getSource(stored, catalog)
149+
const printed = files[SOURCE_ENTRY_FILE]
150+
const applyEdit = (from: string, to: string) => {
151+
const edited = printed.replace(from, to)
152+
expect(edited).not.toBe(printed)
153+
return gate(applyOver(stored, { ...files, [SOURCE_ENTRY_FILE]: edited }), true)
154+
}
155+
156+
it('refuses nothing when Copilot edits another field of the block', async () => {
157+
expect(await applyEdit("prompt: 'hi'", "prompt: 'bye'")).toEqual([])
158+
})
159+
160+
it('refuses Copilot changing a stored server-managed value', async () => {
161+
const findings = await applyEdit("mountedSecrets: ['FOO']", "mountedSecrets: ['BAR']")
162+
expect(findings.map((finding) => [finding.code, finding.param])).toEqual([
163+
['E_APPLY_INVALID_SUBBLOCK_FIELD', 'mountedSecrets'],
164+
])
165+
})
166+
167+
it('refuses nothing when Copilot adds a block that sets no server-managed field', async () => {
168+
const added = getSource(chatWorkflow({ prompt: 'hi' }), catalog).files
169+
expect(await gate(applyOver(START_ONLY, added), true)).toEqual([])
170+
})
171+
})
172+
105173
const slack = getBlock('slack_v2')
106174
const slackSend = getToolIdForOperation('slack_v2', 'send', slack)
107175
const blockTool = { type: 'slack_v2', operation: 'send', params: { channel: 'support' } }

‎apps/sim/lib/workflows/editing/validation.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,11 @@ function withCanonicalNamesResolved(
160160
return resolved
161161
}
162162

163+
/** Why a `hideFromCopilot` field refuses a write: it is server-managed lifecycle configuration. */
164+
export function serverManagedFieldError(field: string, blockType: string): string {
165+
return `Field "${field}" on block type "${blockType}" is server-managed and cannot be set by Copilot`
166+
}
167+
163168
/**
164169
* Validates and filters inputs against a block's subBlock configuration
165170
* Returns valid inputs and any validation errors encountered. `triggerSurface` is whether the
@@ -292,7 +297,7 @@ export function validateInputsForBlock(
292297
blockType,
293298
field: key,
294299
value,
295-
error: `Field "${key}" on block type "${blockType}" is server-managed and cannot be set by Copilot`,
300+
error: serverManagedFieldError(key, blockType),
296301
})
297302
continue
298303
}

0 commit comments

Comments
 (0)