Skip to content
Draft
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
25 changes: 25 additions & 0 deletions .changeset/automation-variable-keys-reserved-segments.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
'@objectstack/service-automation': minor
'@objectstack/spec': patch
'@objectstack/runtime': patch
---

fix(service-automation)!: automation variable keys cannot use reserved object segments, and one run's writes never change a flow's defaults

Clause-②: no (narrowing)
Metadata-protocol: narrowed

<!-- adr-0087: registered flow-variable-key-reserved-segment-refused -->

- **BREAKING: a flow variable key may not use `__proto__`, `constructor` or `prototype` as its name or as any dot-separated part of it.** Registration (and `os migrate meta --stored`, which previews it) judges every key a flow names, in every graph it holds: each node's `id` (it heads every key the node's output is stored under), each declared variable's `name`, each `assignment` node's targets in every shape, each node's `outputVariable`, `iteratorVariable`, `indexVariable`, `errorVariable` and `idVariable`, and each `screen` field's `name`. A name is judged with surrounding whitespace trimmed.
- FROM: a flow naming such a key registered.
- TO: the flow is refused at registration, and the refusal names every such key and where it sits. A name that only contains one of the three words (`constructor_name`, `prototype_count`) is unaffected.
- The fix: rename the key, for example `constructor` to `constructor_name`, and save the flow again.
- **BREAKING: a resume signal may not carry such a key.** Each key of a caller's `output` and `inputs` is judged, a signal handed on to a paused subflow child included; the engine's own continuations (a `map` item handing back, a subflow child finishing) are not, so a run paused before this release still completes.
- FROM: such a key in `output` was accepted; in `inputs` on a screen with declared fields it answered 400 under `INVALID_SCREEN_INPUT`.
- TO: the resume answers `INVALID_SIGNAL` before anything reads the submitted values; nothing is applied, and the run stays paused for a valid submission.
- The fix: send the screen's declared field names, and `output` keys without those segments.
- **BREAKING: one run's writes never change a flow's defaults, another run's values, or the record the run was handed.** Each run binds its own copy of a declared variable's object or list default, and of the trigger record (`record` and `$record`). A dotted write whose head names a value the run holds (`cfg.mode` over a declared `cfg`, `record.x` over the trigger record) is read back by the run's expressions (conditions and CEL values); the value itself keeps what it was, and a text hole (`{{ cfg.mode }}`) and `$record` read the value. With no durable suspended-run store, a resumed run works on its own copy of its variables, as a stored run does.
- FROM: such a write also changed the value it named: a text hole and `$record` read the write, the next run of the flow started from the changed default, and a node that changed the record in place changed the trigger's object.
- TO: only the run's expressions read the write; text holes, `$record`, the flow's default, the next run and the trigger's object do not.
- The fix: to show or keep a value a run computed, assign it to a variable of its own (`assignments: { mode_now: { dialect: 'cel', source: 'cfg.mode' } }`) and read that variable in the text hole or the later step.
26 changes: 26 additions & 0 deletions content/docs/automation/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1476,6 +1476,15 @@ key. A reserved name answers **400**, nothing is applied (not even legitimate
keys sent alongside it), and the run stays parked. Ordinary author variables are
unaffected, `$` mid-name (`price$`) included.

A third: **no signal key, nor any dot-separated part of one, may be `__proto__`,
`constructor` or `prototype`** — the rule a flow's own variable keys follow (see
[Variables](#variables)). It covers both signal fields of a caller's signal,
one handed on to a paused subflow child included, and is judged before anything
else reads the submitted values: such a key answers **400** `INVALID_SIGNAL`,
nothing is applied, and the run stays parked. The engine's own continuations (a
`map` item handing back, a subflow child finishing) are not judged, so a run
paused before this rule still completes.

### A `screen` resume is checked against the declared fields

A screen node's `config.fields` is a **contract**, not just a rendering hint:
Expand Down Expand Up @@ -2242,6 +2251,23 @@ variables: [
| `defaultValue` | `unknown` | Bound at run start when no parameter supplies one — this is what makes the declaration a guarantee. Optional |
| `objectName` | `string` | **Planned.** On an input only (refused at parse on any other variable): the input is the id of a record of this object. No start door reads it yet. See [a start input that is a record id](#a-start-input-that-is-a-record-id). Optional |

A variable key — a node's `id` (it heads every key the node's output is stored
under), a declared `name`, an `assignment` target, a node's `outputVariable` /
`iteratorVariable` / `indexVariable` / `errorVariable` / `idVariable`, a
`screen` field's `name` — may not be `__proto__`, `constructor` or `prototype`,
nor have one as any dot-separated part (`cfg.prototype`), judged with
surrounding whitespace trimmed. Registration refuses such a flow and names each
key; a name that only contains one of the words (`constructor_name`) is fine.

Each run starts from its own copy of a declared object or list `defaultValue`
and of the trigger record (`record` and `$record`). A dotted write under a value
the run holds (`cfg.mode`, `record.x`) is read back by the run's expressions —
conditions and CEL values — and leaves the value itself as it was, so a text
hole (`{{ cfg.mode }}`) and `$record` read the value, not the write. To show or
keep a computed value, assign it to a variable of its own and read that. One run
never changes the flow's default, the next run's values, or the object the
trigger handed over.

### `defaultValue` — declaring a variable is not the same as binding it

Without `defaultValue`, a declaration is documentation. The engine binds an
Expand Down
18 changes: 14 additions & 4 deletions packages/qa/dogfood/test/flow-condition-scope-keys.dogfood.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
// The doors, each with its own probe name:
// • the record that starts a record-triggered flow (`POST` / `PATCH /data`);
// • a flow trigger's `params` bag (`POST /automation/:name/trigger`);
// • a screen resume's `inputs` and `output` (`POST …/runs/:runId/resume`).
// • a screen resume's `inputs` and `output` (`POST …/runs/:runId/resume`),
// where a key with a reserved segment is refused (`INVALID_SIGNAL`) and the
// run stays paused for a valid submission.
//
// Control: an ordinary dotted key (`<node>.<key>`, a resumed screen's output)
// still nests, and a condition after the screen still reads it.
Expand Down Expand Up @@ -214,16 +216,24 @@ describe('a flow condition scope: no variable key reaches a prototype', () => {
const runId = await pause();
const res = await resume(runId, { inputs: { note: 'fcsk-in', '__proto__.fcsk_resume_inputs': true } });
expect(res.status, await res.clone().text()).toBe(400);
expect(((await res.json()) as any).error?.code).toBe('INVALID_SCREEN_INPUT');
expect(((await res.json()) as any).error?.code).toBe('INVALID_SIGNAL');
expect(inherited('fcsk_resume_inputs')).toBeUndefined();
// Nothing was applied: the pause is live, and the valid submission lands.
const ok = await resume(runId, { inputs: { note: 'fcsk-in' }, output: { tag: 'go' } });
expect(ok.status, await ok.clone().text()).toBeLessThan(300);
expect(await marks('fcsk-in')).toBe(1);
});

it('its output bag', async () => {
const runId = await pause();
const res = await resume(runId, { inputs: { note: 'fcsk-out' }, output: { tag: 'go', '__proto__.fcsk_resume_output': true } });
expect(inherited('fcsk_resume_output')).toBeUndefined();
// The rest of the bag still nests: the condition after the screen read `ask.tag`.
expect(res.status, await res.clone().text()).toBeLessThan(300);
expect(res.status, await res.clone().text()).toBe(400);
expect(((await res.json()) as any).error?.code).toBe('INVALID_SIGNAL');
expect(await marks('fcsk-out')).toBe(0);
// Nothing was applied: the pause is live, and the valid submission lands.
const ok = await resume(runId, { inputs: { note: 'fcsk-out' }, output: { tag: 'go' } });
expect(ok.status, await ok.clone().text()).toBeLessThan(300);
expect(await marks('fcsk-out')).toBe(1);
});

Expand Down
4 changes: 3 additions & 1 deletion packages/runtime/src/domains/automation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4813,7 +4813,9 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str
// resume ran and the flow failed"):
// PERMISSION_DENIED → 403, the suspension is service-owned (#3801)
// INVALID_SIGNAL → 400, the signal wrote the engine's `$` variable
// namespace (#3853 follow-up)
// namespace (#3853 follow-up), or named a key
// whose name or any dot-separated part of it is
// `__proto__`, `constructor` or `prototype`
// INVALID_SCREEN_INPUT → 400, the bag violates the suspended screen's
// declared field contract — a required field the
// caller was asked for is missing, or an
Expand Down
41 changes: 31 additions & 10 deletions packages/services/service-automation/src/dag-traversal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ import { readPartialSteps } from './partial-steps.js';
import { isRegionSuspensionRefusal, refuseRegionSuspension } from './region-suspension-refusal.js';
import { stampFlowRunSlot } from './flow-slots.js';
import { stampRootRun } from './root-run.js';
import { isSkippedScopeKey, scopeContainer } from './scope-key-segments.js';
import { copyForScopeDescent, copyHeldValue, isSkippedScopeKey, scopeContainer } from './scope-key-segments.js';

/**
* The value the flow CEL scope binds as `current_user` for a run (#19939 —
Expand Down Expand Up @@ -1052,17 +1052,28 @@ export function celScope(
): { extra: Record<string, unknown> } {
// No variable key reaches a prototype (`./scope-key-segments.ts`):
// prototype-free containers, and a key with a skipped segment binds
// nothing. A dotted tail whose head names a value the run holds is still
// written into that value.
// nothing. And no key writes into a value the run holds: a dotted tail
// whose head names one descends into a copy the scope owns
// (`copyForScopeDescent`), so the scope reads the write and the held
// value — a flow's default, the trigger's record, a value `$record`
// shares — keeps what it was.
const vars = scopeContainer();
const owned = new WeakSet<object>([vars]);
for (const [key, value] of variables) {
// Convert "step.result" keys into nested object paths.
const segs = key.split('.');
if (isSkippedScopeKey(segs)) continue;
let cursor = vars;
for (let i = 0; i < segs.length - 1; i++) {
if (typeof cursor[segs[i]] !== 'object' || cursor[segs[i]] === null) {
cursor[segs[i]] = scopeContainer();
const next = cursor[segs[i]];
if (typeof next !== 'object' || next === null) {
const container = scopeContainer();
owned.add(container);
cursor[segs[i]] = container;
} else if (!owned.has(next)) {
const copy = copyForScopeDescent(next);
owned.add(copy);
cursor[segs[i]] = copy;
}
cursor = cursor[segs[i]] as Record<string, unknown>;
}
Expand Down Expand Up @@ -1262,7 +1273,10 @@ export function seedDeclaredVariables(
if (supplied !== undefined) {
variables.set(v.name, supplied);
} else if (v.defaultValue !== undefined) {
variables.set(v.name, v.defaultValue);
// The default is the registered flow's; the run gets its own copy
// (`copyHeldValue`), so nothing one run does to it — a node that
// changes it in place included — reaches the flow or the next run.
variables.set(v.name, copyHeldValue(v.defaultValue));
}
}
return variables;
Expand All @@ -1278,9 +1292,13 @@ export function seedRunVariables(
): Map<string, unknown> {
const variables = this.seedDeclaredVariables(flow, context);
if (context?.record) {
variables.set('$record', context.record);
variables.set('record', context.record);
for (const [k, v] of Object.entries(context.record)) {
// The run's own copy of the record it was handed (`copyHeldValue`):
// nothing the run does to `record` / `$record` — a node that changes
// it in place included — reaches the trigger's object.
const record = copyHeldValue(context.record) as Record<string, unknown>;
variables.set('$record', record);
variables.set('record', record);
for (const [k, v] of Object.entries(record)) {
if (!variables.has(k)) variables.set(k, v);
}
}
Expand Down Expand Up @@ -1378,7 +1396,6 @@ export async function executeWithoutRetry(
// to its author — and a pausing node on a retry attempt had no `$runId`
// to map its external state back to this run with (ADR-0019).
const runId = this.nextRunId();
const variables = this.seedRunVariables(flow, flowName, context, runId);
const startedAt = new Date().toISOString();
const steps: StepLogEntry[] = [];

Expand All @@ -1387,6 +1404,10 @@ export async function executeWithoutRetry(
// `flowRunId` is stamped here too (#3456). [#31696] And the slot, as
// `execute()` stamps it.
const runContext = await this.resolveRunContext(flow, context, runId);
// Seeded AFTER the context resolves: the run takes its own copy of the
// trigger record, so the lookups the start node declares (`expand`, grafted
// while the context resolves) must already be on it.
const variables = this.seedRunVariables(flow, flowName, context, runId);
stampFlowRunSlot(runContext, flowName, runPackage);
// [ADR-0162 item 7] Each attempt is a run of its own, and its own root
// when it has no parent, as `execute()` stamps it.
Expand Down
4 changes: 3 additions & 1 deletion packages/services/service-automation/src/dry-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -796,9 +796,11 @@ export async function dryRun(this: DryRunHost, definition: unknown, options: Flo
...(options.params !== undefined ? { params: options.params } : {}),
...(options.locale !== undefined ? { locale: options.locale } : {}),
};
const runContext = await this.resolveRunContext({ ...flow, runAs: 'user' }, start);
// Seeded after the context resolves, as a run is: the run's own copy of the
// record carries the lookups its start node declares.
const variables: Map<string, unknown> = this.seedRunVariables(flow, flow.name, start, '');
variables.delete('$runId');
const runContext = await this.resolveRunContext({ ...flow, runAs: 'user' }, start);

const startNode = flow.nodes.find((n) => n.type === 'start')!;
const condition = (startNode.config as { condition?: unknown } | undefined)?.condition;
Expand Down
Loading
Loading