openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat(wallet): bind prepared transaction quotes to originating chat session

Open oxoxDev opened this issue 6 months ago • 3 comments

Summary

  • Stamp the originating chat session onto every PreparedTransaction at wallet_prepare_* time.
  • Gate wallet_execute_prepared so the caller's session must match the prepared quote's stamped owner.
  • Owner mismatch returns the existing "quote '<id>' not found" error verbatim (no enumeration oracle).
  • Defense-in-depth follow-up to #2331.

Problem

#2331 hardened the channel inbound path so two distinct senders in the same shared channel no longer collapse into one cached agent session. The wallet broadcast path was not aware of that session boundary: QUOTE_STORE is process-global keyed only by quote_id, and execute_prepared only checks confirmed: true.

In a shared multi-member channel where the agent's confirmation prompt is broadcast back to every channel member, a co-channel observer can read the prepared quote_id and then pass it into wallet_execute_prepared from their own (now session-isolated) agent run, triggering the original sender's prepared transaction.

Solution

  1. Introduce a private QuoteOwner { thread_id, client_id } derived from the APPROVAL_CHAT_CONTEXT task-local that already scopes the agent tool loop (channels/providers/web.rs::run_chat_task).
  2. Stamp Option<QuoteOwner> onto each PreparedTransaction at prepare time — prepare_transfer, prepare_swap, prepare_contract_call.
  3. execute_prepared reads current_owner() once on entry and gates retrieval through take_quote_for(id, caller_owner). Owner mismatch returns the same not-found error string the genuine not-found branch returns, so error-string diffing cannot enumerate other sessions' quote ids.
  4. Option<QuoteOwner> preserves single-session flows: None == None round-trips successfully so CLI, direct JSON-RPC, single-DM Telegram, single-user Discord channels are unchanged.

A // SAFETY: doc on current_owner() flags reliance on the inline .await chain in run_chat_task. A future refactor that detaches the wallet handler onto a freshly spawned task would land caller_owner = None against a Some(owner) quote → reject. The safe default.

Submission Checklist

  • [x] Added unit tests covering the new gate semantics — 5 new cases in wallet/execution.rs:
    • execute_prepared_rejects_cross_owner_execution
    • execute_prepared_allows_same_owner_execution
    • execute_prepared_allows_no_context_flows
    • execute_prepared_rejects_chat_quote_from_no_context_caller
    • execute_prepared_owner_mismatch_error_matches_not_found_shape
  • [x] cargo fmt --all -- --check clean
  • [x] cargo check --lib clean
  • [x] cargo clippy --lib — zero new warnings on changed lines
  • [x] cargo test --lib openhuman::wallet::execution — 18 passed / 0 failed (13 pre-existing + 5 new)
  • [x] N/A: i18n strings — no UI surface touched
  • [x] N/A: frontend typecheck / lint / vitest — no TS surface touched
  • [x] N/A: docs / changelog — internal defense-in-depth, no observable behavior change for legitimate single-session callers

Impact

  • Legitimate single-session callers (unchanged): CLI, direct JSON-RPC, single-DM Telegram, single-user Discord channels. Both prepare and execute run with owner = None (no APPROVAL_CHAT_CONTEXT), so the equality check is None == None and the existing flow keeps working.
  • Shared multi-member channels (new behavior): a quote prepared by user A in their agent session cannot be executed from user B's session in the same channel, even if user B observed the broadcast confirmation prompt.
  • Wire-compat: owner is #[serde(skip_serializing_if = "Option::is_none")]. Legacy None quotes serialize byte-identically to today; only quotes prepared inside a chat scope add the new field.
  • Telegram carve-out preserved: owner.thread_id derives from the same APPROVAL_CHAT_CONTEXT.thread_id that derive_inbound_thread_id already special-cases via channel_is_telegram. No separate plumbing.

Related

  • Builds on #2331 (channel inbound per-sender session isolation).
  • Follow-up hardening identified during this work (out of scope here, may file as a separate issue):
    • Confirmation-prompt broadcast to shared channels is still channel-wide (send_channel_reply) — privacy-only residual after the execution path is gated; consider sensitive-reply DM redirect on multi-member shared channels.
    • Convert current_owner() from a task-local read to explicit-argument plumbing so a future refactor cannot silently no-op the gate by detaching the wallet handler onto a fresh task.

AI Authored PR Metadata

  • AI authored: yes — implementation produced by a Claude-driven worktree-dev agent following a plan derived via sequential-thinking MCP.
  • Human review: all four commits manually reviewed; tests run locally.

Summary by CodeRabbit

  • Bug Fixes

    • Quotes are now bound to the session that created them, preventing cross-session execution or enumeration and reducing accidental/malicious reuse.
  • Tests

    • Added and updated tests to validate session-scoped quote behavior, same-session allowance, cross-session rejection, and no-session flows.

Review Change Stack

oxoxDev avatar May 26 '26 18:05 oxoxDev

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 71a182a7-9aa5-4291-8598-8fbb4bf4b2c9

📥 Commits

Reviewing files that changed from the base of the PR and between a8d9a543bf00d56dfe7df5291bbc1d638d51d974 and c63ac3f2b1effae8d6ba525b3d61f1c90c00cccb.

📒 Files selected for processing (1)
  • src/openhuman/wallet/execution.rs
💤 Files with no reviewable changes (1)
  • src/openhuman/wallet/execution.rs

📝 Walkthrough

Walkthrough

PreparedTransaction gains an optional owner derived from task-local chat context. Quotes are stamped with that owner at prepare time and consumed only via take_quote_for when the caller's owner matches; mismatches return the same "quote '' not found" error. Tests and chain fixtures updated accordingly.

Changes

Quote Owner Gating

Layer / File(s) Summary
PreparedTransaction owner field and context reading
src/openhuman/wallet/execution.rs
Adds owner: Option<QuoteOwner> to PreparedTransaction. Introduces QuoteOwner and current_owner() which reads identity from task-local APPROVAL_CHAT_CONTEXT.
Owner-gated quote consumption
src/openhuman/wallet/execution.rs
Implements take_quote_for and updates consumption semantics so quote removal only occurs when caller owner matches prepare-time owner; owner mismatch yields identical "quote '' not found" error shape.
Owner stamping at prepare time
src/openhuman/wallet/execution.rs
prepare_transfer, prepare_swap, and prepare_contract_call stamp prepared quotes with owner: current_owner().
Execute prepared uses owner gate
src/openhuman/wallet/execution.rs
execute_prepared now computes caller = current_owner() and consumes quotes with take_quote_for(&params.quote_id, caller).
Test utilities and owner-gating tests
src/openhuman/wallet/execution.rs
Adds helpers to insert owner-stamped quotes and create chat contexts; new tests for cross-owner rejection, same-owner pass, no-context flows, chat-quote rejection from no-context callers, invariant error shape, and verifies prepare stamps owner.
Chain-specific test fixture updates
src/openhuman/wallet/chains/btc.rs, src/openhuman/wallet/chains/solana.rs, src/openhuman/wallet/chains/tron.rs
Updated tests include owner: None in PreparedTransaction fixtures to match the new struct shape.

Sequence Diagram

sequenceDiagram
  participant Caller
  participant PrepareEndpoint
  participant CurrentOwner
  participant QuoteStore
  participant ExecutePrepared

  Caller->>PrepareEndpoint: prepare_transfer(params)
  PrepareEndpoint->>CurrentOwner: current_owner()
  CurrentOwner-->>PrepareEndpoint: Option<QuoteOwner>
  PrepareEndpoint->>QuoteStore: store quote with owner
  QuoteStore-->>PrepareEndpoint: quote_id
  PrepareEndpoint-->>Caller: PreparedTransaction{quote_id, owner: Some(...)}

  Caller->>ExecutePrepared: execute_prepared(quote_id, ...)
  ExecutePrepared->>CurrentOwner: current_owner()
  CurrentOwner-->>ExecutePrepared: Option<QuoteOwner>
  ExecutePrepared->>QuoteStore: take_quote_for(quote_id, caller_owner)
  QuoteStore-->>ExecutePrepared: quote (owner matches) / not found
  ExecutePrepared-->>Caller: execution result / error

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly Related PRs

  • tinyhumansai/openhuman#2519: Modifies quote handling and execute_prepared flow; directly related to quote consumption and execution path changes.

Suggested Labels

feature

🐰 A rabbit hops through threads with care,
Each quote now knows whose hands it'll share,
No thief can steal across the line—
The owner's seal keeps quotes benign,
Safe trades bloom where contexts pair. 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and specifically describes the main change: binding prepared transaction quotes to the originating chat session with ownership tracking.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 26 '26 18:05 coderabbitai[bot]

@oxoxDev unresolved review feedback — please address before we review.

graycyrus avatar May 27 '26 19:05 graycyrus

Unresolved review feedback from coderabbitai[bot] — please address before we review.

graycyrus avatar May 27 '26 19:05 graycyrus

@graycyrus — CodeRabbit's serde concern on the owner field is resolved by c63ac3f2 (which Steven pushed directly): #[serde(skip_serializing)] instead of skip_serializing_if = Option::is_none, and the Serialize derive on QuoteOwner itself was dropped since it's internal gate data only. That commit also adds a prepare_stamps_owner_via_task_local integration test that exercises a real prepare_transfer inside an APPROVAL_CHAT_CONTEXT.scope(...). CI is 26 pass / 4 skip / 0 fail. Ready for re-review when you have a slot.

oxoxDev avatar May 28 '26 05:05 oxoxDev