Skip to content

Commit 2db84dd

Browse files
authored
improvement(workflow-code): say why a Function's code prints as stored() and how to make it editable (#10730)
A code field (a Function's code) holding a detected credential prints whole as stored(), and its W_LITERAL_SECRET hint said to interpolate env.NAME in a t template, which does not apply to code. The finding now says the whole code is hidden, and that storing the key as a workspace secret read as {{NAME}} ($env.NAME in a JavaScript code file) lets the next get print it. Print, compile and both tool paths carry the field's value kind. The CLI appends the sim secrets set command to that hint.
1 parent fff8456 commit 2db84dd

10 files changed

Lines changed: 109 additions & 35 deletions

File tree

‎apps/docs/content/docs/workflows/code/diagnostics.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ Reading and writing `workflow.ts`.
8282
| `W_VALUE_KIND` | A value whose JSON type differs from the field's. |
8383
| `W_OUT_OF_RANGE` | A literal slider value outside the catalog `min`/`max`, off its `step`, or fractional where it takes whole numbers; kept as written, and the executor forwards it unclamped. |
8484
| `W_TABLE_FILTER_SHAPE` | A literal table filter the runtime refuses: the legacy `$` operator grammar, or predicate and builder rows mixed. |
85-
| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field or workflow variable holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. A value Sim minted at creation (a webhook token) is not reported. For a literal token in a credential field, the hint says `credential('<key>')`. |
85+
| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field or workflow variable holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. A value Sim minted at creation (a webhook token) is not reported. For a literal token in a credential field, the hint says `credential('<key>')`. On a code field (a Function's code) get hides the whole code, and the hint says how to make it editable: store the key as a workspace secret and read it in the code as `{{NAME}}` (`$env.NAME` in a JavaScript code file). |
8686
| `W_SUBFLOW_COUNT` | A loop or parallel count, or a parallel batch size, the runtime replaces or clamps. |
8787
| `W_UNKNOWN_OUTPUT_PATH` | A ref path the block's outputs do not have; the hint has a did-you-mean or lists the outputs. |
8888
| `W_OUTPUT_PATH_UNDECLARED` | A path the block does not declare that the run still accepts: an undeclared `inputFormat` input, or `x.error` with no error edge. Never refused. |

‎packages/sim-cli/src/commands/protocol/source-ui.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,18 +243,30 @@ const QUIET_INFO_CODES: ReadonlySet<Diagnostic['code']> = new Set(['I_MAT_NEEDS_
243243
/** The compiler's message on a password field holding a literal secret, naming the param. */
244244
const LITERAL_PASSWORD = /^(\S+) holds a literal secret instead of an env reference/
245245

246+
/** The compiler's message on code holding a detected credential, which get hides whole. */
247+
const LITERAL_IN_CODE = /prints the whole code as stored\(\)/
248+
249+
const SECRETS_SET =
250+
'`sim secrets set NAME --scope workspace --value @-` with the value piped from a file or variable, never typed into the command'
251+
246252
/**
247253
* A finding with the CLI's own next step in its hint: a literal secret in a password field (a
248-
* webhook token, an API key) names the commands that store it and the reference that reads it,
249-
* so the fix is one command and one edit, not a lookup.
254+
* webhook token, an API key) or in code names the commands that store it and the reference that
255+
* reads it, so the fix is one command and one edit, not a lookup.
250256
*/
251257
function withCliHint(diagnostic: Diagnostic): Diagnostic {
252258
if (diagnostic.code !== 'W_LITERAL_SECRET') return diagnostic
259+
if (LITERAL_IN_CODE.test(diagnostic.message)) {
260+
return {
261+
...diagnostic,
262+
hint: `${diagnostic.hint ?? ''} Store it with ${SECRETS_SET}.`.trim(),
263+
}
264+
}
253265
const param = LITERAL_PASSWORD.exec(diagnostic.message)?.[1]
254266
if (param === undefined) return diagnostic
255267
return {
256268
...diagnostic,
257-
hint: `Store the value as a secret, never in the file: \`sim secrets set NAME --scope workspace --value @-\` with the value piped from a file or variable, never typed into the command, then write ${param}: env.NAME (import env from '@sim/workflow-sdk'). A check passes a name set since the get; the apply checks it against the workspace.`,
269+
hint: `Store the value as a secret, never in the file: ${SECRETS_SET}, then write ${param}: env.NAME (import env from '@sim/workflow-sdk'). A check passes a name set since the get; the apply checks it against the workspace.`,
258270
}
259271
}
260272

‎packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1446,6 +1446,24 @@ export default workflow('W', {}, () => {
14461446
expect(process.exitCode).toBe(1)
14471447
})
14481448

1449+
it('names the secret flow and the code reference on a credential written into Function code', async () => {
1450+
cacheCatalog()
1451+
const key = ['sk', 'proj', 'a1b2c3d4e5f6a7b8c9d0e1f2'].join('-')
1452+
writeFileSync(
1453+
join(dir, 'workflow.ts'),
1454+
CLEAN.replace('import { response,', 'import { fn, response,').replace(
1455+
' start.to(done)',
1456+
` const scrape = fn('Scrape', { code: "const apiKey = '${key}'\\nreturn apiKey.length" })\n start.to(scrape)\n scrape.to(done)`
1457+
)
1458+
)
1459+
1460+
await check()
1461+
1462+
expect(findingLines()).toMatch(
1463+
/W_LITERAL_SECRET: code holds what looks like a literal credential, so get prints the whole code[\s\S]*hint: .*\{\{NAME\}\}.*\$env\.NAME.*sim secrets set NAME --scope workspace --value @-/
1464+
)
1465+
})
1466+
14491467
it('passes that stored state on blocks renamed in source, which keep their lock ident', async () => {
14501468
cacheCatalog()
14511469
writeFileSync(join(dir, 'workflow.ts'), STORED_SHAPES_RENAMED)

‎packages/workflow-code/src/compile/SYNTAX.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,9 @@ value `CompileInput.stored` (the stored workflow the file continues) holds for t
189189
type and param, a pair's members and mode included. A new block, another type or an empty field is
190190
`E_STORED_VALUE_MISSING`; inside a value it is `E_UNSUPPORTED_SYNTAX`. A variable's
191191
`value: stored()` compiles to the stored workflow's variable of the same key, and is
192-
`E_STORED_VALUE_MISSING` when there is none.
192+
`E_STORED_VALUE_MISSING` when there is none. A code field (a Function's code) holding a detected credential prints
193+
whole as `stored()`, so source can neither show nor edit it until the key moves into a workspace
194+
secret the code reads as `{{NAME}}`; its `W_LITERAL_SECRET` says so.
193195

194196
A tool's `stored()` takes the value of the stored tool it continues, matched by identity: the one
195197
stored tool of the same type and operation whose params agree with every param the source writes.
@@ -465,7 +467,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio
465467
| `W_VALUE_KIND` | A value whose JSON type differs from the field's. |
466468
| `W_OUT_OF_RANGE` | A literal slider value outside the catalog `min`/`max`, off its `step`, or fractional where it takes whole numbers; kept as written, and the executor forwards it unclamped. |
467469
| `W_TABLE_FILTER_SHAPE` | A literal table filter the runtime refuses: the legacy `$` operator grammar, or predicate and builder rows mixed. |
468-
| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field or workflow variable holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. A value Sim minted at creation (a webhook token) is not reported. For a literal token in a credential field, the hint says `credential('<key>')`. |
470+
| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field or workflow variable holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. A value Sim minted at creation (a webhook token) is not reported. For a literal token in a credential field, the hint says `credential('<key>')`. On a code field (a Function's code) get hides the whole code, and the hint says how to make it editable: store the key as a workspace secret and read it in the code as `{{NAME}}` (`$env.NAME` in a JavaScript code file). |
469471
| `W_SUBFLOW_COUNT` | A loop or parallel count, or a parallel batch size, the runtime replaces or clamps. |
470472
| `W_UNKNOWN_OUTPUT_PATH` | A ref path the block's outputs do not have; the hint has a did-you-mean or lists the outputs. |
471473
| `W_OUTPUT_PATH_UNDECLARED` | A path the block does not declare that the run still accepts: an undeclared `inputFormat` input, or `x.error` with no error edge. Never refused. |

‎packages/workflow-code/src/compile/blocks.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ import {
7878
} from '../model'
7979
import { getOwn, setOwn } from '../records'
8080
import { BLOCK_META_KEYS, RESPONSE_BODY_KEYS, SDK_RESOURCE_CALLS } from '../sdk'
81-
import { holdsSecret, literalSecretFinding } from '../secrets'
81+
import { holdsSecret, literalSecretFinding, type SecretField } from '../secrets'
8282
import { structuredCodec } from '../structured'
8383
import { checkStorableText } from './characters'
8484
import {
@@ -581,7 +581,7 @@ function reportLiteralSecret(
581581
ctx: CompileContext,
582582
blockKey: BlockKey,
583583
entry: Pick<WrittenParam, 'property' | 'param'>,
584-
field: Pick<CatalogSubBlock, 'password' | 'resourceKind'>
584+
field: SecretField
585585
): void {
586586
const { message, hint } = literalSecretFinding(entry.param, field)
587587
ctx.reporter.report('W_LITERAL_SECRET', message, rangeOf(ctx, entry.property), {
@@ -807,7 +807,8 @@ function pairMode(field: Extract<CatalogField, { kind: 'pair' }>, value: Compile
807807
type StoredMember = Pick<
808808
CatalogSubBlock,
809809
'id' | 'password' | 'hidden' | 'readOnly' | 'valueDefault'
810-
>
810+
> &
811+
Partial<Pick<CatalogSubBlock, 'valueKind'>>
811812

812813
/**
813814
* `stored()`: the param keeps what the stored block holds (`CompileInput.stored`), a pair its
@@ -1640,11 +1641,7 @@ function checkOption(
16401641
* marked a credential when it is the manual member of a pair whose picker takes a saved credential
16411642
* (`credential: 'xoxb-…'` lands in `manualCredential`, but the fix is `credential('<key>')`).
16421643
*/
1643-
function secretFieldOf(
1644-
index: FieldIndex,
1645-
param: string,
1646-
sub: CatalogSubBlock
1647-
): Pick<CatalogSubBlock, 'password' | 'resourceKind'> {
1644+
function secretFieldOf(index: FieldIndex, param: string, sub: CatalogSubBlock): SecretField {
16481645
const field = index.fields.get(param) ?? index.aliased.get(param)
16491646
const credentialPair =
16501647
field?.kind === 'pair' && field.members.some((member) => member.resourceKind === 'credential')

‎packages/workflow-code/src/compile/tools.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,10 @@ function compileToolCall(
310310
if (value === undefined) return null
311311
const declared = declarationsOf(block, param)[0]
312312
if (holdsSecret(declared, value)) {
313-
const { message, hint } = literalSecretFinding(key, { password: declared?.password === true })
313+
const { message, hint } = literalSecretFinding(key, {
314+
password: declared?.password === true,
315+
valueKind: declared?.valueKind,
316+
})
314317
ctx.reporter.report('W_LITERAL_SECRET', message, rangeOf(ctx, property), {
315318
hint,
316319
blockKey: site.decl.key,

‎packages/workflow-code/src/print/params.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,10 @@ function printParamValue(
141141
if (holdsSecret(sb, param.value)) {
142142
// A value creation minted (a webhook token) stays out of the file, but source never wrote it.
143143
if (sb && mintsFreshValue(sb)) return ctx.values.call('stored', [])
144-
return storedSecret(ctx, block, sb?.id ?? id, sb?.password === true)
144+
return storedSecret(ctx, block, sb?.id ?? id, {
145+
password: sb?.password === true,
146+
valueKind: sb?.valueKind,
147+
})
145148
}
146149
if (
147150
jsonLiteral &&

‎packages/workflow-code/src/print/round-trip.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,23 @@ describe('printWorkflow round trip', () => {
101101
})
102102
})
103103

104+
describe('a Function whose code holds a detected credential', () => {
105+
it('prints the code as stored() with a finding naming the secret reference that makes it editable', () => {
106+
const key = ['sk', 'proj', 'a1b2c3d4e5f6a7b8c9d0e1f2'].join('-')
107+
const code = `const res = await fetch('https://api.x.co', { headers: { Authorization: 'Bearer ${key}' } })\nreturn res.json()`
108+
const output = printed(
109+
compiled(` const scrape = fn('Scrape', { code: ${JSON.stringify(code)} })`)
110+
)
111+
expect(output.files[0]?.text).toContain('code: stored()')
112+
expect(JSON.stringify(output)).not.toContain(key)
113+
const finding = output.diagnostics.find((d) => d.code === 'W_LITERAL_SECRET')
114+
expect(finding).toMatchObject({ blockKey: 'scrape', param: 'code' })
115+
expect(finding?.message).toContain('whole code')
116+
expect(finding?.hint).toContain('{{NAME}}')
117+
expect(finding?.hint).toContain('$env.NAME')
118+
})
119+
})
120+
104121
describe('a container param holding a detected credential', () => {
105122
it('prints as stored() under meta.extra and compiles back to the stored value', () => {
106123
const token = ['Bearer', 'abcdef0123456789abcdef'].join(' ')

‎packages/workflow-code/src/print/tools.ts‎

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
} from '../agent-tools'
1313
import { toolModeOverrides } from '../canonicalize/modes'
1414
import { builderPins, buildFieldIndex, paramAliases, typedForBuilder } from '../catalog/surface'
15-
import type { BlockCatalog, CatalogBlock, CatalogBuilder } from '../catalog/types'
15+
import type { BlockCatalog, CatalogBlock, CatalogBuilder, CatalogSubBlock } from '../catalog/types'
1616
import { catalogBlock, catalogBuildersOfType, declarationsOf } from '../catalog/view'
1717
import { diagnostic } from '../diagnostics/factory'
1818
import { isJson } from '../lock'
@@ -26,7 +26,13 @@ import {
2626
} from '../model'
2727
import { getOwn } from '../records'
2828
import { CUSTOM_TOOL_TYPE, hasToolForm } from '../sdk'
29-
import { holdsDetectedSecret, holdsSecret, isLiteralSecret, literalSecretFinding } from '../secrets'
29+
import {
30+
holdsDetectedSecret,
31+
holdsSecret,
32+
isLiteralSecret,
33+
literalSecretFinding,
34+
type SecretField,
35+
} from '../secrets'
3036
import type { PrintContext } from './context'
3137
import { printKey } from './strings'
3238
import { arrayExpr, type Expr, objectExpr, type Property } from './syntax'
@@ -137,7 +143,7 @@ function mcpToolCall(ctx: PrintContext, block: CanonicalBlock, form: McpToolForm
137143
args.map(([name, value]) => ({
138144
key: printKey(name),
139145
value: holdsDetectedSecret(value)
140-
? storedSecret(ctx, block, name, false)
146+
? storedSecret(ctx, block, name, { password: false })
141147
: ctx.values.value(value, nested),
142148
}))
143149
),
@@ -216,7 +222,10 @@ export function printTools(
216222
return {
217223
key: printKey(aliases.get(id) ?? id),
218224
value: holdsSecret(sb, value)
219-
? storedSecret(ctx, block, aliases.get(id) ?? id, sb?.password === true)
225+
? storedSecret(ctx, block, aliases.get(id) ?? id, {
226+
password: sb?.password === true,
227+
valueKind: sb?.valueKind,
228+
})
220229
: sb
221230
? ctx.values.field(value, { ...nested, subBlock: sb })
222231
: ctx.values.value(value, nested),
@@ -286,8 +295,8 @@ function toolParamsTyped(
286295
}
287296

288297
/**
289-
* `raw(tool)`: the tool verbatim, except that a password param holding literal text prints as
290-
* `stored()`, as it does through a builder. A param spelled like an alias is a password when the
298+
* `raw(tool)`: the tool verbatim, except that a param holding a secret prints as `stored()`, as it
299+
* does through a builder. A param spelled like an alias is a password when the
291300
* param the alias names is one.
292301
*/
293302
function rawToolCall(
@@ -297,15 +306,15 @@ function rawToolCall(
297306
declared: CatalogBlock | undefined,
298307
aliases: ReadonlyMap<string, string>
299308
): Expr {
300-
const passwordIds = new Set<string>()
309+
const fields = new Map<string, CatalogSubBlock>()
301310
for (const subBlock of declared?.subBlocks ?? []) {
302-
if (!subBlock.password) continue
303-
passwordIds.add(subBlock.id)
304-
const alias = aliases.get(subBlock.id)
305-
if (alias !== undefined) passwordIds.add(alias)
311+
for (const key of [subBlock.id, aliases.get(subBlock.id)]) {
312+
// A password field keeps its name when another field shares it.
313+
if (key !== undefined && !fields.get(key)?.password) fields.set(key, subBlock)
314+
}
306315
}
307316
const secret = (id: string, value: Value) =>
308-
passwordIds.has(id) ? isLiteralSecret(value) : holdsDetectedSecret(value)
317+
fields.get(id)?.password ? isLiteralSecret(value) : holdsDetectedSecret(value)
309318
const json = asToolJson(tool, tool)
310319
if (!isPlainRecord(json) || !Object.entries(tool.params).some(([id, v]) => secret(id, v))) {
311320
return ctx.values.raw(json)
@@ -314,7 +323,10 @@ function rawToolCall(
314323
Object.entries(tool.params).map(([id, value]) => ({
315324
key: printKey(id),
316325
value: secret(id, value)
317-
? storedSecret(ctx, block, id, passwordIds.has(id))
326+
? storedSecret(ctx, block, id, {
327+
password: fields.get(id)?.password === true,
328+
valueKind: fields.get(id)?.valueKind,
329+
})
318330
: ctx.values.json(asToolJson(tool, value)),
319331
}))
320332
)
@@ -340,16 +352,16 @@ function modesExpr(ctx: PrintContext, modes: Record<string, ParamMode>): Expr {
340352
}
341353

342354
/**
343-
* `stored()` for a password field holding literal text (`isLiteralSecret`), which keeps the
344-
* secret out of source, with the `W_LITERAL_SECRET` warning that it is stored as text.
355+
* `stored()` for a param holding a secret, which keeps the secret out of source, with the
356+
* `W_LITERAL_SECRET` finding `literalSecretFinding` builds for `field`.
345357
*/
346358
export function storedSecret(
347359
ctx: PrintContext,
348360
block: CanonicalBlock,
349361
name: string,
350-
password = true
362+
field: SecretField
351363
): Expr {
352-
const { message, hint } = literalSecretFinding(name, { password })
364+
const { message, hint } = literalSecretFinding(name, field)
353365
ctx.diagnostics.push(
354366
diagnostic('W_LITERAL_SECRET', message, { hint, blockKey: block.key, param: name })
355367
)

‎packages/workflow-code/src/secrets.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
*/
1313
import { isRecordLike } from '@sim/utils/object'
1414
import { findWorkflowReferenceTokens } from '@sim/utils/workflow-references'
15+
import type { CatalogValueKind } from './catalog/types'
1516
import type { ResourceKind, Value } from './model'
1617

1718
/** `text` with every reference and `{{ENV}}` token blanked to one space. */
@@ -204,15 +205,18 @@ export function holdsSecret(field: { password?: boolean } | undefined, value: Va
204205
}
205206

206207
/** The traits of the field a `W_LITERAL_SECRET` finding is about. */
207-
interface SecretField {
208+
export interface SecretField {
208209
password?: boolean
209210
/** Set on a resource selector; a `credential` one takes `credential('<key>')`. */
210211
resourceKind?: ResourceKind
212+
/** `code` on a code body (a Function's code, among others), which `stored()` hides whole. */
213+
valueKind?: CatalogValueKind
211214
}
212215

213216
/**
214217
* The message and hint of `W_LITERAL_SECRET` for the param written as `name`: a password field's,
215-
* a credential selector holding a literal token, or a credential detected in another field.
218+
* a credential selector holding a literal token, a code body (hidden whole, so the hint says how
219+
* to make it editable), or a credential detected in another field.
216220
*/
217221
export function literalSecretFinding(
218222
name: string,
@@ -230,6 +234,12 @@ export function literalSecretFinding(
230234
hint: `Save the token as a workspace credential and write ${name}: credential('<key>'), so the token never sits in the workflow.`,
231235
}
232236
}
237+
if (field.valueKind === 'code') {
238+
return {
239+
message: `${name} holds what looks like a literal credential, so get prints the whole code as stored(): source can neither show nor edit it.`,
240+
hint: 'Store the key as a workspace secret and read it in the code as {{NAME}} ($env.NAME in a JavaScript code file), then get again and the code prints. Code printed as stored() is changed where it can be seen, by someone who can open the block: code written in its place replaces code you cannot see.',
241+
}
242+
}
233243
return {
234244
message: `${name} holds what looks like a literal credential; get prints it as stored() so it never lands in a file.`,
235245
hint: 'Store the credential as a workspace or personal env variable and interpolate env.NAME into the value in a t template, so the key never sits in the workflow.',

0 commit comments

Comments
 (0)