Skip to content

Commit 9a28c95

Browse files
committed
🔐 Take selection out of the document's reach
`ActiveReturn` is a named context, and a named context is reachable by name from a document's own eval block: `createContext("expand.return")` names the slot the engine publishes on. The frame it carried was a plain mutable object, so a document could write a value onto it and publish something the engine never validated: --- returns: { type: number } --- ```js eval import { createContext } from "effection"; const frame = yield* createContext("expand.return").get(); frame.selected = { value: "schema-bypassed" }; ``` <If condition={false}><Return value={1} /></If> That printed "schema-bypassed" and exited 0 — a string through a number schema, from a document whose only authored return was unselected. What travels contextually is now a frozen carrier holding no facts, only an accessor that answers nothing without a `Symbol()` this module never exports. The owner, schema, claim and selected value live in that carrier's closure, so the state's lifetime is one execution of one body rather than a table's, and a document that reads, enumerates, calls, copies or replaces the carrier reaches none of it. A carrier the engine did not mint cannot supply the token, and state it fabricates lacks the mark the engine puts on its own — so a `<Return>` that finds one is reserved instead of selecting through it. Both settlement sites read the carrier their own body minted and has held since, never one read back from the context. RV10e covers both consumers: the value-root exploit exits 1 with empty stdout and the existing missing-return diagnostic, and the same attack inside a Markdown value component with an unselected authored return reports that component's own missing-return diagnostic and binds nothing. Restoring state to the carrier makes both fail and the exploit publish again. No suppression: the first attempt kept the state in a module-scoped WeakMap, which `local/no-module-scoped-registry` reports. The closure carries the same guarantee with the lifetime the rule asks for. Refs #640
1 parent 2f3871d commit 9a28c95

7 files changed

Lines changed: 296 additions & 50 deletions

File tree

‎architecture.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ Existing documents and code get aligned to this section retroactively.
108108
| syntax catalog | the complete, versioned description of what a document may write in one directory under one host profile: every structural construct the engine reserves, and the one implementation selection chooses for every other name. It is observation — describing an environment installs no operational state, runs nothing and journals nothing — and it is produced once per request and projected, never rediscovered per format |
109109
| run profile declarations | the component registrations a first-party package makes, held as plain values apart from the middleware, providers, activation and launchers its installer also arranges. The installer registers exactly those values and inspection reads exactly those values, so what a run installs and what the catalog reports cannot drift |
110110
| origin-only | the inspectability of a component whose contract could only be learned by loading it: a repository TypeScript module, whose schemas live on its exports and whose top level would run. Such an entry carries name, category, origin and source kind, and no contract field at all — an absent contract is stated, never rendered as an empty one |
111-
| definition-owned return state | which value body a `<Return>` selects for: one ephemeral state per execution of one value root or Markdown value component. Structural directives keep the ambient one, a component invocation hides it from the invoked body, a nested value body installs its own, and caller-projected content restores the caller's. It is composition state — no authority, no durable event, unreachable from a document — and the first claim on it is atomic, so a second executed return fails the body rather than replacing its value |
111+
| definition-owned return state | which value body a `<Return>` selects for: one ephemeral state per execution of one value root or Markdown value component. Structural directives keep the ambient one, a component invocation hides it from the invoked body, a nested value body installs its own, and caller-projected content restores the caller's. What travels contextually is a frozen carrier holding no facts, only an accessor that answers nothing without a token this module never exports; the state lives in that carrier's closure, so a document can read, enumerate, copy or replace the carrier and reach nothing. The first claim on it is atomic, so a second executed return fails the body rather than replacing its value, and it appends no durable event |
112112

113113
## Three axes
114114

@@ -2377,6 +2377,20 @@ second fails the body, evaluates nothing, and the first value is not published
23772377
there is no first-wins or last-wins fallback. A body that executes none reports
23782378
that instead, which is how a bounded search that found nothing reports itself.
23792379

2380+
**Selection is not a decision a document makes about itself.** The context this
2381+
travels through is named, and a named context is reachable by name from a
2382+
document's own eval block, so nothing that decides a value may live in it. What
2383+
it carries is a frozen carrier holding no facts, only an accessor guarded by an
2384+
unexported `Symbol()`; who owns the body, what schema it declares, whether it is
2385+
claimed, and which value it selected live in that carrier's own closure, whose
2386+
lifetime is one execution of one body. A carrier the engine did not mint owns
2387+
nothing — it cannot supply the token, and state it fabricates lacks the mark the
2388+
engine puts on its own — so a forged one makes a `<Return>` reserved rather than
2389+
selecting through it. Both settlement sites read the carrier their own body
2390+
minted and has held since, never one read back from the context. Mutating
2391+
the carrier, recreating the context, or replacing it therefore selects and
2392+
publishes nothing, and a value still crosses its declared schema on the way out.
2393+
23802394
Selection is not authority and not durable state: it appends no journal event, a
23812395
partial replay reconstructs it while completed effects replay, and a completed
23822396
document replay reuses the retained result without expanding the body. `<Return>`

‎packages/cli/tests/value-root.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,41 @@ const DUPLICATE_RETURN_ROOT = [
120120
"",
121121
].join("\n");
122122

123+
/**
124+
* A document attacking its own return state through the named context.
125+
*
126+
* `expand.return` is reachable by name from an eval block, so the document
127+
* reads the carrier the engine published, tries to write a selected value onto
128+
* it, tries to clear its claim, and finally replaces the context with a
129+
* fully-formed forgery. Its one authored `<Return>` is unselected, so anything
130+
* it manages to select would be a value the engine never validated.
131+
*/
132+
const CARRIER_ATTACK_ROOT = [
133+
"---",
134+
"returns:",
135+
" type: number",
136+
"---",
137+
"",
138+
"```js eval",
139+
'import { createContext } from "effection";',
140+
'const ctx = createContext("expand.return");',
141+
"const carrier = yield* ctx.get();",
142+
'try { carrier.selected = { value: "schema-bypassed" }; } catch (error) {}',
143+
"try { carrier.claimed = false; } catch (error) {}",
144+
"yield* ctx.set({",
145+
' owner: "__root__",',
146+
' returns: { type: "string" },',
147+
" claimed: true,",
148+
' selected: { value: "schema-bypassed" },',
149+
"});",
150+
"```",
151+
"",
152+
"<If condition={false}>",
153+
"<Return value={1} />",
154+
"</If>",
155+
"",
156+
].join("\n");
157+
123158
const FAILS_AFTER_RETURN_ROOT = [
124159
"---",
125160
"returns:",
@@ -244,6 +279,19 @@ describe("Tier VR — xmd run value roots", { sanitizeOps: false, sanitizeResour
244279
expect(result.stderr).not.toContain("SECOND_MARKER");
245280
});
246281

282+
it("RV10e: a document cannot select a value through the named return context", function* () {
283+
const result = yield* useFixture({ "doc.md": CARRIER_ATTACK_ROOT }, function* (dir) {
284+
return yield* runCli(["run", "doc.md"], { cwd: dir }).join();
285+
});
286+
expect(result.code).toBe(1);
287+
// Nothing was published: not the forged value, and not a partial result.
288+
expect(result.stdout).toBe("");
289+
expect(result.stderr).toContain(
290+
"The root document declares `returns` but produced no <Return> value.",
291+
);
292+
expect(result.stderr).not.toContain("schema-bypassed");
293+
});
294+
247295
it("VR5: a failure after <Return> exits nonzero with empty stdout", function* () {
248296
const result = yield* useFixture({ "doc.md": FAILS_AFTER_RETURN_ROOT }, function* (dir) {
249297
return yield* runCli(["run", "doc.md"], { cwd: dir }).join();

‎packages/core/src/execute.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,12 @@ import {
8282
validateBodyStructure,
8383
createBlockCounter,
8484
} from "./expand.ts";
85-
import { ActiveReturn, createReturnFrame, missingReturnMessage } from "./return-flow.ts";
85+
import {
86+
ActiveReturn,
87+
createReturnFrame,
88+
missingReturnMessage,
89+
settleReturn,
90+
} from "./return-flow.ts";
8691
import type { BlockCounter } from "./expand.ts";
8792
import {
8893
DocumentationError,
@@ -1595,7 +1600,7 @@ function* runValueRoot(
15951600
): Operation<DocumentResult> {
15961601
// Created outside the scope the body runs in, so the value it selected is
15971602
// still readable after that scope — and its teardown — has finished.
1598-
const frame = createReturnFrame("__root__", returns);
1603+
const carrier = createReturnFrame("__root__", returns);
15991604

16001605
yield* scoped(function* () {
16011606
yield* Component.around(
@@ -1610,7 +1615,7 @@ function* runValueRoot(
16101615
// The root's own frame, published for the whole body: a `<Return>` under
16111616
// `<If>` or inside a `<Loop>` is reached by ordinary expansion and finds it,
16121617
// because those directives keep the ambient frame.
1613-
yield* ActiveReturn.set(frame);
1618+
yield* ActiveReturn.set(carrier);
16141619

16151620
for (const segment of root.bodySegments) {
16161621
const expanded = yield* expandSegmentsWithin(
@@ -1637,7 +1642,9 @@ function* runValueRoot(
16371642

16381643
yield* refuseCheckedFailure(checkedFailures);
16391644
// Read after the body finished, so a return anywhere in it has executed.
1640-
const selected = frame.selected;
1645+
// Settled from the carrier this root minted and has held since, not from the
1646+
// context, so a document that replaces the context selects nothing.
1647+
const selected = settleReturn(carrier);
16411648
if (!selected) {
16421649
throw new Error(missingReturnMessage("__root__"));
16431650
}

‎packages/core/src/expand.ts‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,10 @@ import {
7878
claimReturn,
7979
createReturnFrame,
8080
missingReturnMessage,
81+
selectReturnValue,
82+
settleReturn,
8183
} from "./return-flow.ts";
82-
import type { ReturnFrame } from "./return-flow.ts";
84+
import type { ReturnCarrier } from "./return-flow.ts";
8385
import { unbox, useEvalScope } from "@effectionx/scope-eval";
8486
import type { EvalScope } from "@effectionx/scope-eval";
8587
import { SchemaValidationError, validateProps, validateReturnValue } from "./validate.ts";
@@ -252,7 +254,7 @@ interface ProjectionState {
252254
* Projected content is the caller's text, so a `<Return>` in it satisfies the
253255
* declaration the author could see.
254256
*/
255-
callerReturn: ReturnFrame | undefined;
257+
callerReturn: ReturnCarrier | undefined;
256258
/**
257259
* This invocation's own structural path (§5.6). A projection is identified by
258260
* the invocation that performed it, so the same authored content projected
@@ -359,7 +361,7 @@ function createProjectionHandle(state: ProjectionState): ProjectionHandle {
359361
hideSet: Set<string>;
360362
inner: ProjectionHandle | undefined;
361363
loop: LoopFrame | undefined;
362-
returnFrame: ReturnFrame | undefined;
364+
returnFrame: ReturnCarrier | undefined;
363365
errors: Segment[];
364366
/**
365367
* The caller's region, when this projection renders into one. Structural
@@ -817,18 +819,20 @@ export function* expandSegmentsWithin(
817819
// projected. Without one — a foreign body, dynamically scanned
818820
// markdown, or a text body — it stays reserved and is diagnosed
819821
// rather than resolving a component named Return.
820-
const owner = yield* ActiveReturn.get();
821-
if (owner === undefined) {
822+
// Claimed before the expression is evaluated, so a second return
823+
// reaching this body while the first is still resolving evaluates
824+
// nothing of its own. A carrier this engine did not mint owns no
825+
// body, so a forged one answers `undefined` here and takes the
826+
// reserved path below rather than selecting anything.
827+
const carrier = yield* ActiveReturn.get();
828+
const body = claimReturn(carrier);
829+
if (carrier === undefined || body === undefined) {
822830
result.push(yield* raise(misplacedReturnError(segment)));
823831
break;
824832
}
825-
// Claimed before the expression is evaluated, so a second return
826-
// reaching this body while the first is still resolving evaluates
827-
// nothing of its own.
828-
claimReturn(owner);
829-
owner.selected = {
830-
value: yield* resolveReturnValue(owner.owner, owner.returns, segment),
831-
};
833+
// What the value is validated against comes from the engine's own
834+
// record of this body, never from the carrier the context held.
835+
selectReturnValue(carrier, yield* resolveReturnValue(body.owner, body.returns, segment));
832836
break;
833837
}
834838

@@ -4180,8 +4184,8 @@ function* expandValueBody(
41804184
// per top-level segment: a `<Return>` under `<If>` or inside a `<Loop>` is
41814185
// reached by ordinary expansion, and finds this frame because those
41824186
// directives keep the ambient one.
4183-
const frame = createReturnFrame(componentName, returns);
4184-
yield* ActiveReturn.set(frame);
4187+
const carrier = createReturnFrame(componentName, returns);
4188+
yield* ActiveReturn.set(carrier);
41854189

41864190
for (const [index, segment] of bodySegments.entries()) {
41874191
const docSegments = substituteSegmentList([segment], slots, project, state, claim);
@@ -4199,8 +4203,10 @@ function* expandValueBody(
41994203
}
42004204

42014205
// Read after the body finished, so a return anywhere in it — including one a
4202-
// projection reached — has been executed by now.
4203-
const selected = frame.selected;
4206+
// projection reached — has been executed by now. Settled from the carrier
4207+
// this body minted and has held since, not from the context, so replacing the
4208+
// context selects nothing.
4209+
const selected = settleReturn(carrier);
42044210
if (!selected) {
42054211
throw new Error(missingReturnMessage(componentName));
42064212
}

0 commit comments

Comments
 (0)