Repository navigation
feat(gateway): B4 — Confirmation Governor (commit-arg binding) + descriptor producer bridge - #59
Conversation
…urity-critical pending-confirmation state (128-bit CSPRNG cnf_ ids, externalId user-isolation gating every read, single-use atomic consume delete-then-return, TTL + sweepExpired, sessionKey never an auth input) + 17 tests Generated-With: Claude Code Co-Authored-By: openclaw <[email protected]> Co-Authored-By: Claude <[email protected]>
… A&D CRIT fix. Preview wrapper (requires_confirm ⇒ descriptor + gateway-stamped pending, no commit; commit_tool allowlist-gated) + deterministic confirm-turn parse (before_agent_start event.prompt, edits validated vs editableFields+constraints, NOT via LLM) + arg-reconstruction commit guard (params = previewArgs ⊕ constraint-validated confirmedFields, MODEL PARAMS DISCARDED; consume-before-allow single-use; externalId-isolated; pending binds to its commit_tool). + A4 producer bridge (marked-only tool-result → payload.channelData lift in embedded-runner, behavior-preserving). CRIT props red-first: confirmed-X-committed-Y impossible, no-pending/hallucinated/replay/cross-user all blocked. 714 tests green, tsgo 0, sealed 60/60 QGR-Finding: A Generated-With: Claude Code Co-Authored-By: openclaw <[email protected]> Co-Authored-By: Claude <[email protected]>
…s fixed red-first: SEC-COLLISION (guard now resolves the SURFACED tool name + server-binds the pending so a collision-prefixed commit tool stays gated; fail-closed catch keys on surfaced name too) + CODE-STALE-EXTID (invalidate externalId cache on identity downgrade). Plus SEC-REDOS (unconditional pattern/value caps), DESIGN-REPROMPT (guard blocks unstaged confirm + surfaces re-prompt, no silent commit of un-edited previews), CODE-SILENT-DROP (synthesize ui.summary carrier when no text payload), SEC-FORGE-MARKER strip+re-validate, cap-lastwins, firstline-nonblank; +29 coverage locks (all constraint branches, guard-throw, proto, expiry-guard, xuser-parse, marker-drift). 743 tests green QGR-Finding: SEC-COLLISION Generated-With: Claude Code Co-Authored-By: openclaw <[email protected]> Co-Authored-By: Claude <[email protected]>
…ion Governor (security-critical) Generated-With: Claude Code Co-Authored-By: openclaw <[email protected]> Co-Authored-By: Claude <[email protected]>
📝 WalkthroughWalkthroughChangesConfirmation flow
Estimated code review effort: 4 (Complex) | ~60 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
The formal models extracted constants ( This check is informational (not blocking merges yet). If this change is intentional, follow up by updating the formal models repo or regenerating the extracted artifacts there. |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@extensions/syntropy-mcp/src/governor.ts`:
- Around line 411-430: The pattern validation in the c.pattern branch still uses
Node’s backtracking RegExp engine, allowing backend-controlled patterns such as
nested quantifiers to stall the event loop. Replace the new RegExp construction
and re.test call with a non-backtracking RE2-based matcher, or isolate matching
in a worker with a hard timeout and terminate over-budget execution; preserve
the existing length checks and invalid-pattern error handling.
In `@src/agents/pi-embedded-runner/run.ts`:
- Around line 966-968: Limit the component descriptor scan performed by
extractComponentChannelData() to tool-result messages generated during the
current turn rather than the session-wide attempt.messagesSnapshot; filter or
pass the current-turn message collection when constructing the assistant
payload’s channelData.
In `@src/agents/pi-embedded-runner/run/payloads.ts`:
- Around line 66-77: In the component-marker handling logic, retain the
validated result returned by parseComponentDescriptor instead of discarding it.
Update the carrier assignment to forward that parsed descriptor rather than raw
shape.component, ensuring sanitized fields are surfaced through the channel
path.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 6f1a2835-0e43-4345-9d8b-471fa88a856c
📒 Files selected for processing (11)
extensions/syntropy-mcp/openclaw.plugin.jsonextensions/syntropy-mcp/src/governor.test.tsextensions/syntropy-mcp/src/governor.tsextensions/syntropy-mcp/src/index.test.tsextensions/syntropy-mcp/src/index.tsextensions/syntropy-mcp/src/pending-confirm-store.test.tsextensions/syntropy-mcp/src/pending-confirm-store.tssrc/agents/pi-embedded-runner/run.tssrc/agents/pi-embedded-runner/run/payloads.component-bridge.test.tssrc/agents/pi-embedded-runner/run/payloads.tsworkstreams/openclaw/qgr/SyntropyHealth-Applications-mo-openclaw-openclaw-SyntropyHealth-Applications-qgr-pr-prep-20260710-1610-d646258.md
| if (c?.pattern !== undefined) { | ||
| // ReDoS guard (CWE-1333): the pattern is BACKEND-controlled and could be | ||
| // catastrophic-backtracking. Cap the pattern source AND the tested value | ||
| // length UNCONDITIONALLY — independent of whether the backend set | ||
| // maxLength — before compiling or testing, so a malicious pattern/value | ||
| // can never stall the event loop. | ||
| if (c.pattern.length > MAX_PATTERN_LENGTH) { | ||
| return `field "${field.name}" has an invalid pattern constraint`; | ||
| } | ||
| if (value.length > MAX_PATTERN_TEST_LENGTH) { | ||
| return `field "${field.name}" is too long to validate against the pattern`; | ||
| } | ||
| let re: RegExp; | ||
| try { | ||
| re = new RegExp(c.pattern); | ||
| } catch { | ||
| return `field "${field.name}" has an invalid pattern constraint`; | ||
| } | ||
| if (!re.test(value)) return `field "${field.name}" does not match the required pattern`; | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🌐 Web query:
Does Node.js V8 irregexp use backtracking (ReDoS possible with catastrophic patterns)?
💡 Result:
Yes, the standard Node.js (V8) regular expression engine, known as Irregexp, is a backtracking engine [1][2]. Because it uses backtracking, it is susceptible to Regular Expression Denial of Service (ReDoS) when processing catastrophic patterns—regular expressions that can lead to exponential time complexity when matched against crafted input [2][3][4]. To mitigate this, V8 introduced an experimental, non-backtracking regular expression engine (based on a Thompson-style NFA) that guarantees linear-time execution [5][2][3]. However, this engine: - Is not enabled by default in Node.js [2][3]. - Must be explicitly enabled using the --enable-experimental-regexp-engine flag [6][7]. - Lacks support for certain advanced features, such as backreferences and some types of look-arounds [6][2][3]. - Serves as an opt-in alternative; if an unsupported feature is used or the engine is not enabled, Node.js falls back to the default backtracking Irregexp engine [8][9][3]. Consequently, most Node.js applications remain vulnerable to ReDoS if they process untrusted input with complex regular expressions, as the default behavior remains backtracking-based [2][3]. Developers are often advised to use static analysis tools to identify vulnerable patterns or consider alternative libraries (such as those providing bindings for Google's RE2 engine) if they require non-backtracking performance for untrusted input [6][4].
Citations:
- 1: https://stackoverflow.com/questions/34249522/how-is-regular-expression-matching-implemented-in-node-v8
- 2: https://arxiv.org/html/2406.11618v2
- 3: https://arxiv.org/html/2406.11618v3
- 4: https://www.sonarsource.com/blog/vulnerable-regular-expressions-javascript/
- 5: https://v8.dev/blog/non-backtracking-regexp
- 6: Linear regex algorithm nodejs/node#51659
- 7: https://v8.github.io/api/head/classv8_1_1RegExp.html
- 8: re2 as safer opt-in regexp engine replacement ? nodejs/node#28642
- 9: https://chromium.googlesource.com/v8/v8/+/cb4415bd68fbd673e4b73545ac388688673a123c/src/regexp/regexp.cc
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the relevant file region with line numbers.
file="extensions/syntropy-mcp/src/governor.ts"
wc -l "$file"
sed -n '360,470p' "$file" | cat -n
echo
echo "---- search constants/usages ----"
rg -n "MAX_PATTERN_LENGTH|MAX_PATTERN_TEST_LENGTH|pattern" extensions/syntropy-mcp/src/governor.ts extensions/syntropy-mcp/src -g '!**/node_modules/**'Repository: Syntropy-Health/openclaw
Length of output: 9154
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find the file and map its structure.
fd -a "governor.ts" .
ast-grep outline extensions/syntropy-mcp/src/governor.ts --view expanded || trueRepository: Syntropy-Health/openclaw
Length of output: 1611
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the surrounding implementation and the source of the constraint object.
file="extensions/syntropy-mcp/src/governor.ts"
echo "=== around target lines ==="
sed -n '390,445p' "$file" | cat -n
echo
echo "=== relevant symbols in governor.ts ==="
rg -n "MAX_PATTERN_LENGTH|MAX_PATTERN_TEST_LENGTH|new RegExp\\(|pattern\\.length|pattern:|validate.*pattern|constraint" "$file"
echo
echo "=== broader project search for RE2/safe-regex/regexp engine alternatives ==="
rg -n "re2|safe-regex|regexp.*timeout|non-backtracking|experimental-regexp-engine|pattern constraint" extensions/syntropy-mcp -g '!**/node_modules/**'Repository: Syntropy-Health/openclaw
Length of output: 4231
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find the type that defines `c` and the field metadata source.
rg -n "interface .*pattern|type .*pattern|pattern\\?: string|maxLength|pattern" extensions/syntropy-mcp/src -g '!**/node_modules/**'
# If a likely type is found, show its definition file in context.Repository: Syntropy-Health/openclaw
Length of output: 3426
Use a non-backtracking regex strategy here. The length caps reduce exposure, but they don’t prevent catastrophic backtracking in Node’s default RegExp engine for short adversarial patterns like (a+)+$. Since c.pattern is backend-controlled, this path can still stall the event loop; use RE2 or run the match under a hard timeout/worker budget.
🧰 Tools
🪛 ast-grep (0.44.1)
[warning] 424-424: Do not use variable for regular expressions
Context: new RegExp(c.pattern)
Note: [CWE-1333] Inefficient Regular Expression Complexity. Security best practice.
(regexp-non-literal-typescript)
[warning] 424-424: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(c.pattern)
Note: [CWE-1333] Inefficient Regular Expression Complexity
(regexp-from-variable)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@extensions/syntropy-mcp/src/governor.ts` around lines 411 - 430, The pattern
validation in the c.pattern branch still uses Node’s backtracking RegExp engine,
allowing backend-controlled patterns such as nested quantifiers to stall the
event loop. Replace the new RegExp construction and re.test call with a
non-backtracking RE2-based matcher, or isolate matching in a worker with a hard
timeout and terminate over-budget execution; preserve the existing length checks
and invalid-pattern error handling.
Source: Linters/SAST tools
| // A4: surface any component descriptor a tool result marked | ||
| // (Confirm Governor) onto the assistant payload's channelData. | ||
| toolResultMessages: attempt.messagesSnapshot, |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Determine messagesSnapshot construction, scope, and the role string used for tool results.
rg -nP -C4 'messagesSnapshot' src/agents/pi-embedded-runner
rg -nP -C3 'role:\s*["'\'']toolResult|role:\s*["'\'']tool' src/agents/pi-embedded-runnerRepository: Syntropy-Health/openclaw
Length of output: 20289
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Map the payload helper and snapshot plumbing, then inspect the exact logic.
ast-grep outline src/agents/pi-embedded-runner/run/payloads.ts --view expanded
ast-grep outline src/agents/pi-embedded-runner/run/attempt.ts --view expanded
ast-grep outline src/agents/pi-embedded-runner/run/types.ts --view expanded
# Read the relevant sections with line numbers.
sed -n '1,220p' src/agents/pi-embedded-runner/run/payloads.ts | cat -n
sed -n '820,1210p' src/agents/pi-embedded-runner/run/attempt.ts | cat -n
sed -n '1,120p' src/agents/pi-embedded-runner/run/types.ts | cat -n
# Look for tests or call sites that characterize the snapshot scope and toolResult role.
rg -n -C3 'extractComponentChannelData|toolResultMessages|messagesSnapshot|role:\s*"toolResult"' src/agents/pi-embedded-runner/runRepository: Syntropy-Health/openclaw
Length of output: 50380
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the payload assembly around the component bridge and the surrounding tests.
sed -n '360,430p' src/agents/pi-embedded-runner/run/payloads.ts | cat -n
sed -n '1,180p' src/agents/pi-embedded-runner/run/payloads.component-bridge.test.ts | cat -n
# Check whether any code filters toolResultMessages down to the current turn.
rg -n -C2 'toolResultMessages\s*:|messagesSnapshot\b|extractComponentChannelData\(' src/agents/pi-embedded-runner/run | head -n 120Repository: Syntropy-Health/openclaw
Length of output: 19142
Scope the component scan to this turn attempt.messagesSnapshot is session-wide, so extractComponentChannelData() can reuse an older role: "toolResult" marker and attach stale channelData to a later assistant reply.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/agents/pi-embedded-runner/run.ts` around lines 966 - 968, Limit the
component descriptor scan performed by extractComponentChannelData() to
tool-result messages generated during the current turn rather than the
session-wide attempt.messagesSnapshot; filter or pass the current-turn message
collection when constructing the assistant payload’s channelData.
| const shape = marker as { type?: unknown; component?: unknown }; | ||
| if (shape.type !== "component" || !shape.component || typeof shape.component !== "object") { | ||
| continue; | ||
| } | ||
| // Defense-in-depth: re-validate the descriptor on the channel path (the | ||
| // gateway re-validates too, but this path may not). A forged/invalid | ||
| // descriptor is dropped rather than surfaced. | ||
| if (!parseComponentDescriptor(shape.component)) { | ||
| continue; | ||
| } | ||
| // Last-wins: the most recent valid component of the turn is surfaced. | ||
| carrier = { type: "component", component: shape.component }; |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm whether the schema strips/passes unknown keys and how data is shaped.
fd -t f 'component-descriptor.schema.ts' src | xargs -I{} ast-grep outline {} --items all
rg -nP -C3 '(passthrough|strict|strip|ComponentDescriptorSchema\s*=)' src/gateway/component-descriptor.schema.tsRepository: Syntropy-Health/openclaw
Length of output: 2915
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the payload extraction logic and descriptor parsing shape.
sed -n '1,220p' src/agents/pi-embedded-runner/run/payloads.ts
printf '\n---\n'
sed -n '1,240p' src/gateway/component-descriptor.schema.tsRepository: Syntropy-Health/openclaw
Length of output: 15638
Surface the parsed descriptor, not the raw marker payload. parseComponentDescriptor already sanitizes the marker before returning it; forwarding shape.component here re-emits the unsanitized input and can preserve stripped unsafe keys in channelData.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/agents/pi-embedded-runner/run/payloads.ts` around lines 66 - 77, In the
component-marker handling logic, retain the validated result returned by
parseComponentDescriptor instead of discarding it. Update the carrier assignment
to forward that parsed descriptor rather than raw shape.component, ensuring
sanitized fields are surfaced through the channel path.
openclaw-syntropy-agentic-chat B4 (Governor + food-logging gate). Additive/inert (disabled-by-default plugin; core bridge behavior-preserving, no marker⇒byte-identical). T4.1 PendingConfirmStore (128-bit CSPRNG cnf_ ids, externalId-isolated, single-use atomic consume, TTL). T4.2-4.4 ConfirmGovernor — the A&D CRIT fix (commit-arg binding): preview wrapper (requires_confirm⇒descriptor+gateway-stamped pending, NO backend commit; gated on config commitTools allowlist, NEVER on backend-supplied requires_confirm = anti-compromise invariant) + deterministic confirm-parse (event.prompt, not LLM) + arg-reconstruction commit guard (params=previewArgs⊕constraint-validated confirmedFields, MODEL PARAMS DISCARDED; consume-before-allow; externalId+server+commit_tool bound). A4 producer bridge: payloads.ts lifts a governor-marked (details.__openclaw_component) tool result onto channelData={type:component,component} = B3's consumer's producer (grounding: AgentToolResult had no channelData; B3 consumer had no producer). CTO-RATIFIED (A4 refinement accepted — minimal, behavior-preserving, characterization-tested). QG: 4 reviewers+scorer heavy-security, 17 findings/14 FIXED incl. 2 commit-path FAIL-OPENS red-first (SEC-COLLISION cross-server-name-collision→ungated-commit; CODE-STALE-EXTID identity-downgrade→unverified-commit) + REDoS caps + forge-marker strip. CRIT kernel proven sound (confirmed-X-committed-Y impossible), cross-user/replay/TOCTOU verified. Gates: tsgo 0, 743 tests, sealed 60/60, B3 consumer unregressed. Receipt qgr-pr-prep-20260710-1610-d646258 ✓. 🤖 Generated with Claude Code
Summary by CodeRabbit