Skip to content

fix: prevent $-pattern injection in prompt template and approval substitution - #123015

Merged
steipete merged 4 commits into
openclaw:mainfrom
miorbnli:fix/prompt-template-approval-dollar-injection
Aug 24, 2026
Merged

steipete merged 4 commits into
openclaw:mainfrom
miorbnli:fix/prompt-template-approval-dollar-injection

Conversation

@miorbnli

@miorbnli miorbnli commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Two call sites used String.replace/replaceAll with a string replacement fed a runtime variable. JavaScript interprets $&, $1–$9, $`, $' in string replacements, so user-supplied content containing $ is silently corrupted:

  1. packages/agent-core/src/harness/prompt-template-arguments.ts:83-84 — $ARGUMENTS and $@ substitution corrupts slash-command args containing $ (e.g. shell variables, prices). $$ collapses to $, $& becomes the entire match.
  2. Bundle command template expansion — replaceAll("$ARGUMENTS", normalizedArgs) as a string replacement re-interprets $ patterns from skillInvocation.args; the rendered result feeds agent prompt fields. (Owner moved during this PR's lifetime: originally src/auto-reply/reply/get-reply-inline-actions.ts, extracted upstream to src/skills/discovery/chat-command-invocation.ts in fix(ui): show skill mentions in the new-session composer #125554-era refactoring; this branch follows the invariant to the new owner.)

Why This Change Was Made

String.replace(regex, () => value) treats the return value literally — no $ interpretation. Each call site switches from the string form to the function form. Same fix pattern as #111398 (terminal-core display-string) and the core home-dir resolver PR #122991.

(An initially included third call site — the plugin-SDK replaceApprovalIdPlaceholder — was removed per review: that helper has no canonical /approve <id> placeholder producer in the plugin-SDK manual fallback path, so the rewrite was unproven.)

User Impact

When a user runs a slash command (or bundle command) with arguments containing $ — e.g. fix $HOME variable, price is $$5 — the args are mangled before reaching the model: $$ collapses to $, $& re-expands to the template placeholder text. The model sees corrupted input and acts on wrong data.

Evidence

Runtime probe through the real prompt-template owner (before → after)

node --import tsx /tmp/verify-prompt-dollar.mjs imports the real substituteArgs module from this branch:

########## BEFORE (pre-fix production code at base 683d37a35f2) ##########
FAIL substituteArgs keeps literal $ patterns
  args:     ["price","$$ and $& here","$`tail","$'quote"]
  rendered: "Quote for: price\nDetails: $$ and $& here $`tail $'quote\nEverything: price $ and $ARGUMENTS here Quote for: price\nDetails: … $`tail $'quote"   (all four $ patterns corrupted / re-expanded)
PROBE FAIL

########## AFTER (fixed production code at PR head) ##########
PASS substituteArgs keeps literal $ patterns
  rendered: "Quote for: price\nDetails: $$ and $& here $`tail $'quote\nEverything: price $$ and $& here $`tail $'quote"
PROBE PASS

Owner-boundary regressions (both red-green verified)

  • packages/agent-core/src/harness/prompt-template-arguments.test.ts: substituteArgs("Args: $ARGUMENTS", parseCommandArgs("price $$ and $& here")) must stay literal.
    • Red (pre-fix): expected 'Args: price $ and $ARGUMENTS here'.
  • src/auto-reply/reply/get-reply-inline-actions.skip-when-config-empty.test.ts: new case "keeps literal $ patterns in bundle command arguments" drives the actual changed route end-to-end through runTestInlineActions (real handleInlineActions, real skill-command rewriting) with /office_hours price $$ and $& here, asserting both ctx.Body and the handleCommands prompt body keep price $$ and $& here literally.
    • Red (pre-fix): AssertionError: expected 'Act as an engineering advisor.\n\nFoc…' to be '…' — the rendered prompt had $$/$& re-expanded.
    • Green (post-fix): full file 32 passed.

Single-pass placeholder resolution (addresses review finding)

substituteArgs previously ran four sequential replace passes ($1…, ${@:N}, $ARGUMENTS, $@), so text inserted by an early pass could be re-interpreted by a later one. It now resolves every placeholder in one combined pass; an inserted argument is final data.

  • Red (pre-fix, four-pass): AssertionError: expected '$ARGUMENTS safe $ARGUMENTS safe' to be '$ARGUMENTS $ARGUMENTS safe' for substituteArgs("$1 $@", ["$ARGUMENTS", "safe"]) — exactly the review's reproduction.
  • Green: substituteArgs("$1 $@", ["$ARGUMENTS", "safe"]) === "$ARGUMENTS $ARGUMENTS safe", plus substituteArgs("$1 ${@:2:1}", ["$@", "$ARGUMENTS", "safe"]) === "$@ $ARGUMENTS".
  • Runtime probe (node --import tsx /tmp/verify-prompt-dollar.mjs) now prints PASS substituteArgs resolves all placeholders in one pass alongside the literal-$ PASS above.

Tests (rebased onto latest main incl. the chat-command extraction, exact head 91cb18b38f2)

  • node scripts/run-vitest.mjs src/auto-reply/reply/get-reply-inline-actions.skip-when-config-empty.test.ts → 35 passed (red-green re-verified on the new chat-command-invocation.ts owner: reverting only that file to main makes the literal-$ case fail)
  • node scripts/run-vitest.mjs packages/agent-core/src/harness/prompt-template-arguments.test.ts → 3 passed
  • git diff --check → clean

Prior CI red-shard attribution (superseded head)

On head cb60ffe9f61, checks-node-compact-small-12 failed at test/scripts/install-sh.test.ts > install.sh > bounds installer npm prefix probes during finalization helpers. That test passes 88/88 on latest main locally (node 26.5.0) and touches the installer, unrelated to this diff — runner/flaky-specific, not introduced by this PR.

Production LOC: the two substitutions became one single-pass resolver (+6 net in prompt-template-arguments.ts, callback form retained); chat-command-invocation.ts net 0. Test LOC: +46.

Sibling already fixed: packages/terminal-core/src/display-string.ts:53 (#111398) uses the callback form for the same $-expansion invariant.

CI (exact head 91cb18b38f2)

Full CI matrix green: run 32098907313.

@clawsweeper

clawsweeper Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@miorbnli
miorbnli marked this pull request as ready for review August 13, 2026 05:14
@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 13, 2026
@clawsweeper

clawsweeper Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 22, 2026, 9:28 PM ET / August 23, 2026, 01:28 UTC.

ClawSweeper review

What this changes

This PR preserves literal dollar sequences in slash-command prompt-template and bundle-command arguments, and prevents inserted prompt arguments from being expanded again by later placeholder passes.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

The patch appears correct at its reviewed head and has credible real behavior proof, but this checkout could not materialize the supplied current-main revision to verify whether the work is already covered or safely fresh against main. Keep it open for an exact-main refresh rather than making an obsolete/merge-ready verdict.

Priority: P2
Reviewed head: 91cb18b38f2f3a15df14fc86aeae8278815cd0c4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The repair and its proof are strong, with the remaining confidence gap limited to an unavailable current-main comparison.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body supplies an after-fix terminal probe through the real prompt-template owner and red-green owner-boundary evidence for both changed paths.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body supplies an after-fix terminal probe through the real prompt-template owner and red-green owner-boundary evidence for both changed paths.
Evidence reviewed 6 items Prompt-template owner: The reviewed head resolves positional, slice, and all-arguments placeholders through one callback replacement, so returned argument text is literal and is not revisited by another replacement pass.
Prompt-template entry point: Session prompt expansion parses slash-command arguments and passes them to the changed substitution owner.
Bundle-command owner and caller: Bundle expansion uses a callback replacement, and the inline-action flow writes its rendered result into all model-facing body fields.
Findings None None.
Security None None.

Live Verification

Command: node --import tsx scripts/run-vitest.mjs packages/agent-core/src/harness/prompt-template-arguments.test.ts

Result: PASS (completed)

node --import tsx scripts/run-vitest.mjs packages/agent-core/src/harness/prompt-template-arguments.test.ts
runner@runnervm76f27:/tmp/clawsweeper-live-proof-123015-eZaQMz/target$ node --import tsx scripts/run-vitest.mjs packages/agent-core/src/harness/prompt-template-
arguments.test.ts
node --import tsx scripts/run-vitest.mjs packages/agent-core/src/harness/prompt-template-arguments.test.ts
[test] starting test/vitest/vitest.unit.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-123015-eZaQMz/target

 ✓  unit  packages/agent-core/src/harness/prompt-template-arguments.test.ts (3 tests) 63ms

 Test Files  1 passed (1)
      Tests  3 passed (3)
   Start at  01:29:24
   Duration  1.49s (transform 1.15s, setup 1.05s, import 10ms, tests 63ms, environment 0ms)





































Assertions:

  • PASS expect_output: 3 passed

How this fits together

Slash commands are converted into prompt text before an agent run. This change sits in the argument-template and bundle-command expansion paths, which pass user-entered arguments into the model-facing message body.

flowchart LR
A[Slash command] --> B[Argument parsing]
B --> C[Prompt template expansion]
A --> D[Bundle command lookup]
D --> E[Bundle prompt expansion]
C --> F[Model-facing message]
E --> F
F --> G[Agent run]
Loading

Before merge

  • Resolve merge risk (P1) - The branch is behind main, and the checkout could not fetch current-main objects; an exact-main rebase and focused rerun are needed before landing.
  • Resolve merge risk (P1) - Production code is net +1 line because the single-pass invariant needs an explanatory comment; no net-neutral form preserves that non-obvious semantic boundary as clearly.
  • Complete next step (P2) - Current-main comparison failed because required promisor objects could not be fetched, so a fresh exact-main review is needed before landing.
Agent review details

Security

None.

PR surface

Source +1, Tests +44. Total +45 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 31 30 +1
Tests 2 44 0 +44
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 75 30 +45

Review metrics

Metric Value Why it matters
Production versus test delta production +31/-30 (net +1); tests +44/-0 The small production increase is the single-pass owner-boundary rewrite and its invariant comment; regression coverage is concentrated in the two affected paths.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Rebase the focused repair onto current main, retain the canonical single-pass resolver and literal callback replacement, then rerun the two owner-boundary suites on the exact merge candidate.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Rebase the focused repair onto current main, retain the canonical single-pass resolver and literal callback replacement, then rerun the two owner-boundary suites on the exact merge candidate.

Do we have a high-confidence way to reproduce the issue?

Yes—source establishes both affected paths, and the PR body includes a before/after terminal probe through the real prompt-template owner plus owner-boundary red-green regressions.

Is this the best way to solve the issue?

Yes—the callback replacement and one-pass placeholder resolver repair the producing expansion owners without adding a parallel path or changing command syntax.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against d75164c46d43.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: This fixes silent corruption of user-provided slash-command arguments before they reach the agent, with a limited prompt-template and bundle-command blast radius.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body supplies an after-fix terminal probe through the real prompt-template owner and red-green owner-boundary evidence for both changed paths.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies an after-fix terminal probe through the real prompt-template owner and red-green owner-boundary evidence for both changed paths.

Evidence

What I checked:

Likely related people:

  • miorbnli: Current-head blame attributes both changed runtime owners to this contributor; older main-history ownership could not be recovered from the unavailable promisor objects. (role: current implementation contributor; confidence: low; commits: 91cb18b38f2f, b18fc026a57e; files: packages/agent-core/src/harness/prompt-template-arguments.ts, src/skills/discovery/chat-command-invocation.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Rebase onto current main and rerun the two focused owner-boundary suites against the exact merge candidate.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (7 earlier review cycles)
  • reviewed 2026-08-13T05:22:07.300Z sha 21dcceca4c8e50052345668d9a3784c9553c657e :: needs real behavior proof before merge. :: [P2] Remove the unproven approval-placeholder rewrite | [P2] Add owner-boundary regressions for literal dollar arguments
  • reviewed 2026-08-13T08:36:25.944Z sha cb60ffe9f614aee552d59c288cb554c0a4bbdccf :: needs real behavior proof before merge. :: [P2] Cover literal dollar arguments through the bundle command owner
  • reviewed 2026-08-14T08:46:20.137Z sha 535219fa9bfce26ae4120a6f94f4c5e616385aee :: needs changes before merge. :: [P2] Prevent later placeholder passes from reinterpreting arguments
  • reviewed 2026-08-15T05:02:58.890Z sha 535219fa9bfce26ae4120a6f94f4c5e616385aee :: needs changes before merge. :: [P2] Resolve all placeholders in one pass
  • reviewed 2026-08-18T04:07:39.833Z sha b18fc02 :: needs changes before merge. :: [P2] Resolve all placeholders in one pass
  • reviewed 2026-08-18T04:29:09.845Z sha 91cb18b :: needs maintainer review before merge. :: none
  • reviewed 2026-08-18T04:41:40.274Z sha 91cb18b :: needs maintainer review before merge. :: none

@miorbnli
miorbnli force-pushed the fix/prompt-template-approval-dollar-injection branch from 21dccec to cb60ffe Compare August 13, 2026 08:29
@miorbnli

Copy link
Copy Markdown
Contributor Author

CI failure attribution for checks-node-compact-small-12 on head cb60ffe9f6:

test/scripts/install-sh.test.ts > bounds installer npm prefix probes during finalization helpers (expected exit 0, got 1): passes locally on both clean upstream/main and this branch — node scripts/run-vitest.mjs test/scripts/install-sh.test.ts → 88 passed on each. The changed files (prompt-template substitution, bundle-command template) are unrelated to install.sh; the failure looks runner-environment-specific (npm prefix probing). No code change included for it; rerunning the job requires admin rights I don't have on this fork PR.

@miorbnli
miorbnli force-pushed the fix/prompt-template-approval-dollar-injection branch from cb60ffe to 535219f Compare August 14, 2026 08:38
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 14, 2026
… substitution

Three call sites used String.replace/replaceAll with a string replacement
fed a runtime variable, causing dollar-amp/dollar-1/dollar-backtick
sequences in user-supplied args or approval ids to corrupt the rendered text.

Switch each to a function replacement so the value is treated literally:

- prompt-template-arguments: dollar-ARGUMENTS and dollar-@ substitution
  corrupted slash-command args containing dollar signs
- get-reply-inline-actions: bundle command template expansion had the
  same issue with normalizedArgs
- approval-reaction-runtime: approval id placeholder rendering mangled
  ids containing dollar signs; the iMessage sibling
  (extensions/imessage/src/approval-text.ts) already escapes this
Address review: the approval placeholder helper has no canonical
/approve <id> producer in the plugin-SDK manual fallback path, so its
rewrite is unproven - revert it. Keep the two reachable prompt-template
fixes and add an owner-boundary regression covering literal dollar
sequences in dollar-ARGUMENTS and dollar-@ substitution (fails on the
old string replacement form, passes with the callback form).
@miorbnli
miorbnli force-pushed the fix/prompt-template-approval-dollar-injection branch from 535219f to b18fc02 Compare August 18, 2026 03:58
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. label Aug 18, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 18, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Aug 23, 2026
@steipete

Copy link
Copy Markdown
Contributor

Maintainer verification on the unchanged original contributor head 91cb18b38f2f3a15df14fc86aeae8278815cd0c4:

  • Reproduced the shipped/current production bug by invoking the real prompt-template owner. Input price $$ and $& here incorrectly became price $ and $ARGUMENTS here; an argument containing $ARGUMENTS was also recursively expanded by later substitution passes.
  • Invoked the exact contributor production owner with the same inputs. The result now preserves price $$ and $& here literally, and $1 $@ with arguments ["$ARGUMENTS", "safe"] correctly yields the single-pass result $ARGUMENTS $ARGUMENTS safe. Unsafe integer placeholders and zero-based slices retain their existing behavior.
  • Ran the repository-native test router from the exact contributor worktree across both prompt-template suites, bundle/skill-command siblings, and the real inline-action/model-facing route: 4 files, 72 tests passed, across the unit and auto-reply configurations.
  • Fresh isolated structured review and independent complete owner/caller/sibling/current-main review found no actionable issues. All four changed files pass the canonical formatter and git diff --check.
  • The latest automated review suggested rebasing only because its partial checkout could not materialize current main. A full current-main three-way merge was independently verified clean and preserves newer sibling tests, so that optional rebase is intentionally skipped to preserve the contributor's original commit and avoid unnecessary branch churn.
  • Scope is exactly the two prompt producers and their two regression files. Despite stale historical pull-request title wording, this final revision does not modify any approval, authentication, authorization, security, configuration, or persistence surface.

@steipete
steipete merged commit 3a17d59 into openclaw:main Aug 24, 2026
456 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 25, 2026
…titution (openclaw#123015)

* fix: prevent dollar-pattern injection in prompt template and approval substitution

Three call sites used String.replace/replaceAll with a string replacement
fed a runtime variable, causing dollar-amp/dollar-1/dollar-backtick
sequences in user-supplied args or approval ids to corrupt the rendered text.

Switch each to a function replacement so the value is treated literally:

- prompt-template-arguments: dollar-ARGUMENTS and dollar-@ substitution
  corrupted slash-command args containing dollar signs
- get-reply-inline-actions: bundle command template expansion had the
  same issue with normalizedArgs
- approval-reaction-runtime: approval id placeholder rendering mangled
  ids containing dollar signs; the iMessage sibling
  (extensions/imessage/src/approval-text.ts) already escapes this

* fix: rebase, drop unproven approval rewrite, add dollar regression

Address review: the approval placeholder helper has no canonical
/approve <id> producer in the plugin-SDK manual fallback path, so its
rewrite is unproven - revert it. Keep the two reachable prompt-template
fixes and add an owner-boundary regression covering literal dollar
sequences in dollar-ARGUMENTS and dollar-@ substitution (fails on the
old string replacement form, passes with the callback form).

* test(auto-reply): cover literal dollar bundle command arguments

* fix(agent-core): resolve prompt placeholders in a single substitution pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants