From 4d457026cd2b4401599490cb8b560ba3f83fa833 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 12 Nov 2026 16:01:40 +0000 Subject: [PATCH 1/8] test(wallet): cover x402 rpc permit routing and lifecycle Add tests for the x402 RPC permit path, verifying that payments within the caller cap and per-request budget are approved while over-cap and over-budget requests are refused. Also cover that a permit only authorizes its own URL, is consumed by the first authorization, and stays active only while its scoped future runs. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/modules/wallet_host_tests.rs | 95 ++++++++++++++++++- 1 file changed, 93 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/modules/wallet_host_tests.rs b/crates/openhuman-core/src/modules/wallet_host_tests.rs index d273f28a230..8d0c060b559 100644 --- a/crates/openhuman-core/src/modules/wallet_host_tests.rs +++ b/crates/openhuman-core/src/modules/wallet_host_tests.rs @@ -1,7 +1,8 @@ use super::{ consume_approval, native_approval_matches_request, validate_module_endpoint_url, - web3_approval_matches_request, x402_approval_facts, x402_request_owner_matches, x402_route, - ApprovalKind, ApprovalPermit, X402Route, + web3_approval_matches_request, with_x402_rpc_permit, x402_approval_facts, + x402_request_owner_matches, x402_route, x402_rpc_permit_route, ApprovalKind, ApprovalPermit, + X402Route, X402RpcPermit, X402RpcPermitOutcome, }; use tinywallet_bus::wire::{ AuthorizeNativeWalletExecutionRequest, AuthorizeWeb3ExecutionRequest, @@ -605,3 +606,93 @@ fn x402_from_scheduled_actions_cron_is_budgeted_and_plain_cron_is_refused() { X402Route::Refused(_) )); } + +fn x402_request_for(url: &str, amount_atomic: u64) -> AuthorizeX402PaymentRequest { + AuthorizeX402PaymentRequest { + url: url.into(), + ..x402_request(amount_atomic, None) + } +} + +#[test] +fn x402_rpc_permit_approves_a_payment_within_the_caller_cap() { + let url = "https://rpc-permit.example/within-cap"; + let permit = X402RpcPermit::new(url, 500); + assert_eq!( + x402_rpc_permit_route(&x402_request_for(url, 500), 1_000), + Some(X402Route::RpcPermitApproved) + ); + assert_eq!(permit.finish(), X402RpcPermitOutcome::Approved); +} + +#[test] +fn x402_rpc_permit_refuses_a_payment_over_the_caller_cap() { + let url = "https://rpc-permit.example/over-cap"; + let permit = X402RpcPermit::new(url, 500); + assert!(matches!( + x402_rpc_permit_route(&x402_request_for(url, 501), u64::MAX), + Some(X402Route::Refused(_)) + )); + assert!(matches!(permit.finish(), X402RpcPermitOutcome::Refused(_))); +} + +#[test] +fn x402_rpc_permit_refuses_a_payment_over_the_per_request_budget() { + let url = "https://rpc-permit.example/over-budget"; + let permit = X402RpcPermit::new(url, 1_000); + assert!(matches!( + x402_rpc_permit_route(&x402_request_for(url, 500), 499), + Some(X402Route::Refused(_)) + )); + assert!(matches!(permit.finish(), X402RpcPermitOutcome::Refused(_))); +} + +#[test] +fn x402_without_a_matching_rpc_permit_keeps_the_existing_refusal() { + let permitted = "https://rpc-permit.example/permitted"; + let other = "https://rpc-permit.example/other"; + let permit = X402RpcPermit::new(permitted, u64::MAX); + // A permit for one URL never authorizes another; routing falls through. + assert_eq!( + x402_rpc_permit_route(&x402_request_for(other, 1), u64::MAX), + None + ); + assert!(matches!( + x402_route(&x402_request_for(other, 1), None, u64::MAX), + X402Route::Refused(_) + )); + assert_eq!(permit.finish(), X402RpcPermitOutcome::Unused); + // No permit at all: nothing is approved for a plain RPC caller. + assert_eq!( + x402_rpc_permit_route(&x402_request_for(permitted, 1), u64::MAX), + None + ); +} + +#[test] +fn x402_rpc_permit_is_consumed_by_the_first_authorization() { + let url = "https://rpc-permit.example/consumed-once"; + let permit = X402RpcPermit::new(url, 10); + assert_eq!( + x402_rpc_permit_route(&x402_request_for(url, 1), 10), + Some(X402Route::RpcPermitApproved) + ); + assert_eq!(x402_rpc_permit_route(&x402_request_for(url, 1), 10), None); + assert_eq!(permit.finish(), X402RpcPermitOutcome::Approved); +} + +#[tokio::test] +async fn x402_rpc_permit_is_active_only_while_its_future_runs() { + let url = "https://rpc-permit.example/scoped"; + let (route, outcome) = with_x402_rpc_permit(url, 10, async { + x402_rpc_permit_route(&x402_request_for(url, 10), 10) + }) + .await; + assert_eq!(route, Some(X402Route::RpcPermitApproved)); + assert_eq!(outcome, X402RpcPermitOutcome::Approved); + assert_eq!(x402_rpc_permit_route(&x402_request_for(url, 1), 10), None); + + let ((), unused) = with_x402_rpc_permit(url, 10, async {}).await; + assert_eq!(unused, X402RpcPermitOutcome::Unused); + assert_eq!(x402_rpc_permit_route(&x402_request_for(url, 1), 10), None); +} From 1d2c08036ca5c438ecfa88c1f92c1bd5672a204f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 12 Nov 2026 16:04:11 +0000 Subject: [PATCH 2/8] feat(wallet): approve direct x402_fetch RPC payments via one-shot permits Direct x402_fetch RPC calls now register a one-shot permit keyed by URL and the caller's maxAmountAtomic, which the authorization callback consumes to approve payments within that cap and the per-request budget. This lets RPC-originated payments skip the WebChat approval prompt while still failing closed when no permit matches. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/modules/wallet_host.rs | 127 ++++++++++++++++-- 1 file changed, 117 insertions(+), 10 deletions(-) diff --git a/crates/openhuman-core/src/modules/wallet_host.rs b/crates/openhuman-core/src/modules/wallet_host.rs index 1d966268e69..1335ff99067 100644 --- a/crates/openhuman-core/src/modules/wallet_host.rs +++ b/crates/openhuman-core/src/modules/wallet_host.rs @@ -106,6 +106,9 @@ pub(super) enum X402Route { /// module has already reserved the amount against its own budget before /// asking; the host re-checks the per-request cap as a second line. AutomationApproved, + /// A direct `openhuman.x402_fetch` RPC holds a one-shot permit for this + /// URL and the amount is within both its cap and the per-request budget. + RpcPermitApproved, /// The originating WebChat turn: ask the user with a forced approval. PromptWebChat, /// Refused, with the reason handed back to the module. @@ -138,6 +141,110 @@ pub(super) fn x402_route( } } +/// How a direct-RPC x402 permit was used by the module's authorization callback. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum X402RpcPermitOutcome { + /// No authorization callback matched the permit. + Unused, + /// The payment was within the caller's cap and the per-request budget. + Approved, + /// The permit matched but the payment was refused, with the reason. + Refused(&'static str), +} + +#[derive(Debug)] +struct X402RpcPermitEntry { + url: String, + max_amount_atomic: u64, + outcome: Option, +} + +static X402_RPC_PERMITS: OnceLock>> = OnceLock::new(); +static X402_RPC_PERMIT_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +fn x402_rpc_permits() -> &'static Mutex> { + X402_RPC_PERMITS.get_or_init(|| Mutex::new(HashMap::new())) +} + +/// One-shot x402 authorization for a direct `openhuman.x402_fetch` RPC call, +/// correlated by the exact URL the module reports in its callback and bounded +/// by the caller's `maxAmountAtomic`. Removed when dropped. +pub(super) struct X402RpcPermit(u64); + +impl X402RpcPermit { + pub(super) fn new(url: &str, max_amount_atomic: u64) -> Self { + let id = X402_RPC_PERMIT_IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if let Ok(mut permits) = x402_rpc_permits().lock() { + permits.insert( + id, + X402RpcPermitEntry { + url: url.to_owned(), + max_amount_atomic, + outcome: None, + }, + ); + } + Self(id) + } + + /// Retire the permit and report what the authorization callback decided. + pub(super) fn finish(self) -> X402RpcPermitOutcome { + x402_rpc_permits() + .lock() + .ok() + .and_then(|mut permits| permits.remove(&self.0)) + .and_then(|entry| entry.outcome) + .unwrap_or(X402RpcPermitOutcome::Unused) + } +} + +impl Drop for X402RpcPermit { + fn drop(&mut self) { + if let Ok(mut permits) = x402_rpc_permits().lock() { + permits.remove(&self.0); + } + } +} + +/// Consume an active, unused direct-RPC permit for `request.url` and decide +/// the payment against its cap and `per_request_max_atomic` (the module +/// budget's second line, as for automation). `None` when no permit matches, +/// so the caller falls through to [`x402_route`] unchanged. +pub(super) fn x402_rpc_permit_route( + request: &AuthorizeX402PaymentRequest, + per_request_max_atomic: u64, +) -> Option { + let mut permits = x402_rpc_permits().lock().ok()?; + let entry = permits + .values_mut() + .find(|entry| entry.outcome.is_none() && entry.url == request.url)?; + let outcome = if request.amount_atomic > entry.max_amount_atomic { + X402RpcPermitOutcome::Refused("x402 payment exceeds the caller's maxAmountAtomic") + } else if request.amount_atomic > per_request_max_atomic { + X402RpcPermitOutcome::Refused("x402 payment exceeds the per-request budget") + } else { + X402RpcPermitOutcome::Approved + }; + entry.outcome = Some(outcome); + Some(match outcome { + X402RpcPermitOutcome::Approved => X402Route::RpcPermitApproved, + X402RpcPermitOutcome::Refused(reason) => X402Route::Refused(reason), + X402RpcPermitOutcome::Unused => unreachable!("a matched permit always records a decision"), + }) +} + +/// Keep a direct-RPC x402 permit alive only while `future` (the module's +/// payment preparation) runs, and report how it was used. +pub(crate) async fn with_x402_rpc_permit( + url: &str, + max_amount_atomic: u64, + future: F, +) -> (F::Output, X402RpcPermitOutcome) { + let permit = X402RpcPermit::new(url, max_amount_atomic); + let output = future.await; + (output, permit.finish()) +} + fn x402_approval_facts(request: &AuthorizeX402PaymentRequest) -> serde_json::Value { serde_json::json!({ "url": request.url, @@ -490,27 +597,27 @@ impl WalletHost { })) } - /// x402 authorization: a WebChat turn asks its user with a forced approval - /// (the guarded HTTP request path), trusted automation is approved within - /// the per-request budget ([`x402_route`]), and any other origin fails - /// closed. + /// x402 authorization: a direct `x402_fetch` RPC holding a permit for this + /// URL is approved within its cap and the per-request budget + /// ([`x402_rpc_permit_route`]); otherwise a WebChat turn asks its user with + /// a forced approval (the guarded HTTP request path), trusted automation is + /// approved within the per-request budget ([`x402_route`]), and any other + /// origin fails closed. async fn authorize_x402_payment( &self, request: AuthorizeX402PaymentRequest, ) -> tinybus::Result { let origin = crate::core::runtime::DispatchCtx::ambient_turn().turn_origin(); - let route = x402_route( - &request, - origin.as_ref(), - super::x402_service::per_request_max_atomic(), - ); + let per_request_max_atomic = super::x402_service::per_request_max_atomic(); + let route = x402_rpc_permit_route(&request, per_request_max_atomic) + .unwrap_or_else(|| x402_route(&request, origin.as_ref(), per_request_max_atomic)); tracing::debug!( origin = origin.as_ref().map(|o| o.class()).unwrap_or_else(|| "none".into()), route = ?route, "[modules:wallet] x402 authorization" ); let (approved, reason) = match route { - X402Route::AutomationApproved => (true, None), + X402Route::AutomationApproved | X402Route::RpcPermitApproved => (true, None), X402Route::PromptWebChat => { let approved = match crate::security::approval::ApprovalGate::try_global() { Some(gate) => matches!( From 99aa32dd2a17e1b5c280b0504947c722f734040d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 12 Nov 2026 16:04:22 +0000 Subject: [PATCH 3/8] fix(wallet_host): return refusal route for rejected x402 permits The permit route now derives the refusal reason before recording the outcome, so a rejected permit returns the matching refused route instead of relying on a second match over the stored outcome. This removes the unreachable branch for unused permits and keeps the decision and its route in sync. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/modules/wallet_host.rs | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/crates/openhuman-core/src/modules/wallet_host.rs b/crates/openhuman-core/src/modules/wallet_host.rs index 1335ff99067..30e43e431da 100644 --- a/crates/openhuman-core/src/modules/wallet_host.rs +++ b/crates/openhuman-core/src/modules/wallet_host.rs @@ -218,19 +218,25 @@ pub(super) fn x402_rpc_permit_route( let entry = permits .values_mut() .find(|entry| entry.outcome.is_none() && entry.url == request.url)?; - let outcome = if request.amount_atomic > entry.max_amount_atomic { - X402RpcPermitOutcome::Refused("x402 payment exceeds the caller's maxAmountAtomic") + let refusal = if request.amount_atomic > entry.max_amount_atomic { + Some("x402 payment exceeds the caller's maxAmountAtomic") } else if request.amount_atomic > per_request_max_atomic { - X402RpcPermitOutcome::Refused("x402 payment exceeds the per-request budget") + Some("x402 payment exceeds the per-request budget") } else { - X402RpcPermitOutcome::Approved + None + }; + let (outcome, route) = match refusal { + Some(reason) => ( + X402RpcPermitOutcome::Refused(reason), + X402Route::Refused(reason), + ), + None => ( + X402RpcPermitOutcome::Approved, + X402Route::RpcPermitApproved, + ), }; entry.outcome = Some(outcome); - Some(match outcome { - X402RpcPermitOutcome::Approved => X402Route::RpcPermitApproved, - X402RpcPermitOutcome::Refused(reason) => X402Route::Refused(reason), - X402RpcPermitOutcome::Unused => unreachable!("a matched permit always records a decision"), - }) + Some(route) } /// Keep a direct-RPC x402 permit alive only while `future` (the module's From d855335f4e690749a0f41f2a5fbb00ea75e015e7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 12 Nov 2026 16:05:21 +0000 Subject: [PATCH 4/8] feat(x402): add fetch controller for paid HTTP requests Introduce an x402 fetch module that performs HTTP requests gated by payment, and register its controller schema with url and maxAmountAtomic as required inputs. A test asserts the controller is registered alongside its schema. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/x402/fetch.rs | 6 + .../src/web3/x402/fetch_tests.rs | 192 ++++++++++++++++++ crates/openhuman-core/src/web3/x402/mod.rs | 2 + .../src/web3/x402/schemas_tests.rs | 20 ++ 4 files changed, 220 insertions(+) create mode 100644 crates/openhuman-core/src/web3/x402/fetch.rs create mode 100644 crates/openhuman-core/src/web3/x402/fetch_tests.rs diff --git a/crates/openhuman-core/src/web3/x402/fetch.rs b/crates/openhuman-core/src/web3/x402/fetch.rs new file mode 100644 index 00000000000..ec460853b39 --- /dev/null +++ b/crates/openhuman-core/src/web3/x402/fetch.rs @@ -0,0 +1,6 @@ +//! `openhuman.x402_fetch`: one HTTP request that may pay an HTTP 402 challenge +//! within a cap the caller states. + +#[cfg(test)] +#[path = "fetch_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/web3/x402/fetch_tests.rs b/crates/openhuman-core/src/web3/x402/fetch_tests.rs new file mode 100644 index 00000000000..f5d0b36e705 --- /dev/null +++ b/crates/openhuman-core/src/web3/x402/fetch_tests.rs @@ -0,0 +1,192 @@ +use super::*; +use serde_json::json; + +fn params(value: Value) -> Map { + value.as_object().cloned().expect("object params") +} + +#[test] +fn params_default_to_get_with_no_headers_or_body() { + let parsed = parse_params(params(json!({ + "url": "https://api.example.test/resource", + "maxAmountAtomic": 2500, + }))) + .expect("valid params"); + assert_eq!(parsed.url, "https://api.example.test/resource"); + assert_eq!(parsed.method, reqwest::Method::GET); + assert!(parsed.headers.is_empty()); + assert_eq!(parsed.body, None); + assert_eq!(parsed.max_amount_atomic, 2500); +} + +#[test] +fn params_accept_a_post_with_headers_and_body() { + let parsed = parse_params(params(json!({ + "url": "https://api.example.test/resource", + "method": "post", + "headers": {"Content-Type": "application/json"}, + "body": "{}", + "maxAmountAtomic": 1, + }))) + .expect("valid params"); + assert_eq!(parsed.method, reqwest::Method::POST); + assert_eq!( + parsed.headers, + vec![("Content-Type".to_string(), "application/json".to_string())] + ); + assert_eq!(parsed.body.as_deref(), Some("{}")); +} + +#[test] +fn params_reject_a_non_https_url() { + for url in [ + "http://api.example.test/resource", + "ftp://api.example.test/resource", + "not a url", + ] { + let error = parse_params(params(json!({"url": url, "maxAmountAtomic": 1}))) + .expect_err("non-https URL is refused"); + assert!(error.contains("https"), "{error}"); + } +} + +#[test] +fn params_reject_a_method_other_than_get_or_post() { + let error = parse_params(params(json!({ + "url": "https://api.example.test/resource", + "method": "PUT", + "maxAmountAtomic": 1, + }))) + .expect_err("PUT is refused"); + assert!(error.contains("method"), "{error}"); +} + +#[test] +fn params_reject_a_body_on_get() { + let error = parse_params(params(json!({ + "url": "https://api.example.test/resource", + "body": "x", + "maxAmountAtomic": 1, + }))) + .expect_err("GET with a body is refused"); + assert!(error.contains("body"), "{error}"); +} + +#[test] +fn params_reject_caller_supplied_payment_headers() { + for name in ["PAYMENT-SIGNATURE", "payment-signature", "X-PAYMENT", "x-Payment"] { + let error = parse_params(params(json!({ + "url": "https://api.example.test/resource", + "headers": {name: "forged"}, + "maxAmountAtomic": 1, + }))) + .expect_err("payment header is refused"); + assert!(error.contains("header"), "{error}"); + } +} + +#[test] +fn params_reject_a_non_string_header_value() { + assert!(parse_params(params(json!({ + "url": "https://api.example.test/resource", + "headers": {"X-Count": 3}, + "maxAmountAtomic": 1, + }))) + .is_err()); +} + +#[test] +fn params_require_a_positive_max_amount() { + assert!(parse_params(params(json!({"url": "https://api.example.test/resource"}))).is_err()); + let error = parse_params(params(json!({ + "url": "https://api.example.test/resource", + "maxAmountAtomic": 0, + }))) + .expect_err("zero cap is refused"); + assert!(error.contains("maxAmountAtomic"), "{error}"); +} + +#[tokio::test] +async fn destination_guard_refuses_loopback_and_private_hosts() { + for url in ["https://127.0.0.1/x", "https://10.0.0.1/x", "https://localhost/x"] { + assert!(guard_destination(url).await.is_err(), "{url}"); + } +} + +#[test] +fn body_text_truncates_at_the_cap_and_flags_it() { + assert_eq!(body_text(b"hello".to_vec(), 5), ("hello".to_string(), false)); + assert_eq!(body_text(b"hello!".to_vec(), 5), ("hello".to_string(), true)); + // A cut inside a multi-byte character never yields invalid UTF-8. + let (text, truncated) = body_text("aé".as_bytes().to_vec(), 2); + assert!(truncated); + assert_eq!(text, "a"); +} + +#[test] +fn a_refused_authorization_is_reported_with_the_refusal_prefix() { + let refused = prepare_error( + crate::modules::wallet_host::X402RpcPermitOutcome::Refused("over cap"), + "module said no", + ); + assert!(refused.starts_with(REFUSED_PREFIX), "{refused}"); + assert!(refused.contains("over cap"), "{refused}"); + + let failed = prepare_error( + crate::modules::wallet_host::X402RpcPermitOutcome::Unused, + "challenge invalid", + ); + assert!(!failed.starts_with(REFUSED_PREFIX), "{failed}"); + assert!(failed.contains("challenge invalid"), "{failed}"); +} + +#[test] +fn an_unpaid_response_has_a_null_payment() { + assert_eq!( + response_value(200, Some("text/plain".into()), "ok".into(), false, None), + json!({ + "status": 200, + "contentType": "text/plain", + "body": "ok", + "truncated": false, + "payment": null, + }) + ); +} + +#[test] +fn a_paid_response_carries_the_payment_facts() { + let payment = FetchPayment { + payment_id: "x402_1".into(), + amount_atomic: 2500, + asset: "USDC".into(), + recipient: "0x01".into(), + network: "eip155:8453".into(), + settled: true, + settlement_response: Some("receipt".into()), + }; + assert_eq!( + response_value(200, None, "ok".into(), true, Some(payment)), + json!({ + "status": 200, + "body": "ok", + "truncated": true, + "payment": { + "paymentId": "x402_1", + "amountAtomic": 2500, + "asset": "USDC", + "recipient": "0x01", + "network": "eip155:8453", + "settled": true, + "settlementResponse": "receipt", + }, + }) + ); +} + +#[test] +fn the_payment_amount_must_not_exceed_the_caller_cap() { + assert!(ensure_within_cap(2500, 2500).is_ok()); + let error = ensure_within_cap(2501, 2500).expect_err("over cap"); + assert!(error.starts_with(REFUSED_PREFIX), "{error}"); +} diff --git a/crates/openhuman-core/src/web3/x402/mod.rs b/crates/openhuman-core/src/web3/x402/mod.rs index 6de8be2b528..8871823cbc7 100644 --- a/crates/openhuman-core/src/web3/x402/mod.rs +++ b/crates/openhuman-core/src/web3/x402/mod.rs @@ -5,6 +5,8 @@ //! host retains generic HTTP execution, explicit user approval, and secret //! custody; payment material crosses only the confidential module call. +#[cfg(feature = "web3")] +mod fetch; #[cfg(feature = "web3")] mod schemas; diff --git a/crates/openhuman-core/src/web3/x402/schemas_tests.rs b/crates/openhuman-core/src/web3/x402/schemas_tests.rs index 195eb838324..107b02a8b4d 100644 --- a/crates/openhuman-core/src/web3/x402/schemas_tests.rs +++ b/crates/openhuman-core/src/web3/x402/schemas_tests.rs @@ -91,3 +91,23 @@ fn payment_list_preserves_legacy_rpc_shape_and_rfc3339_values() { }) ); } + +#[test] +fn fetch_controller_is_registered_with_its_schema() { + assert!(all_controller_schemas() + .iter() + .any(|schema| schema.namespace == "x402" && schema.function == "fetch")); + let registered = all_registered_controllers(); + let fetch = registered + .iter() + .find(|controller| controller.schema.function == "fetch") + .expect("x402 fetch controller is registered"); + let required: Vec<&str> = fetch + .schema + .inputs + .iter() + .filter(|field| field.required) + .map(|field| field.name) + .collect(); + assert_eq!(required, vec!["url", "maxAmountAtomic"]); +} From 5f2dbd96756507966514fdb410f3c23c8afe616b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 12 Nov 2026 16:06:28 +0000 Subject: [PATCH 5/8] feat(x402): add capped payment preparation for direct RPC callers Direct x402_fetch RPC callers have no turn to approve through, so payment preparation now accepts an optional amount cap and runs the confidential call under a one-shot permit scoped to the URL. The permit is installed while the service lock is held, ensuring only this preparation can match it, and the outcome is returned so refusals are distinguishable from other failures. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/modules/x402_service.rs | 83 ++++++++++++++++--- .../src/web3/x402/fetch_tests.rs | 4 +- 2 files changed, 75 insertions(+), 12 deletions(-) diff --git a/crates/openhuman-core/src/modules/x402_service.rs b/crates/openhuman-core/src/modules/x402_service.rs index 1280c19ff0c..22e98d7c2e1 100644 --- a/crates/openhuman-core/src/modules/x402_service.rs +++ b/crates/openhuman-core/src/modules/x402_service.rs @@ -18,6 +18,8 @@ use crate::config::Config; use super::wallet::{self, WalletCallError}; +pub(crate) use super::wallet_host::X402RpcPermitOutcome; + /// Prepare and sign a 402 challenge inside TinyWallet. Both supported rails' /// secret material is sent only through the attested confidential call; the /// module parses the challenge and selects the matching chain. @@ -28,16 +30,70 @@ pub(crate) async fn prepare_payment( payment_required: String, owner: Option, ) -> Result<(X402ServiceHandle, X402PreparePaymentResponse), WalletCallError> { + prepare(ctx, config, url, payment_required, owner, None) + .await + .0 +} + +/// [`prepare_payment`] for a direct `openhuman.x402_fetch` RPC caller, which +/// has no turn to approve through. The host's authorization callback approves +/// this payment only while a one-shot permit for `url` is active, and only +/// within `max_amount_atomic` and the per-request budget. The permit is +/// installed while the service lock is held, so it can only be matched by this +/// preparation. Returns how the permit was used so a refusal is recognisable. +pub(crate) async fn prepare_capped_payment( + ctx: &DispatchCtx, + config: &Config, + url: String, + payment_required: String, + max_amount_atomic: u64, +) -> ( + Result<(X402ServiceHandle, X402PreparePaymentResponse), WalletCallError>, + X402RpcPermitOutcome, +) { + prepare( + ctx, + config, + url, + payment_required, + None, + Some(max_amount_atomic), + ) + .await +} + +async fn prepare( + ctx: &DispatchCtx, + config: &Config, + url: String, + payment_required: String, + owner: Option, + rpc_cap: Option, +) -> ( + Result<(X402ServiceHandle, X402PreparePaymentResponse), WalletCallError>, + X402RpcPermitOutcome, +) { let mut active = service().lock().await; - ensure_service(ctx, config, &mut active).await?; - let service_handle = active - .as_ref() - .ok_or_else(|| WalletCallError::Failed("x402 service is unavailable".into()))? - .handle - .clone(); + if let Err(error) = ensure_service(ctx, config, &mut active).await { + return (Err(error), X402RpcPermitOutcome::Unused); + } + let Some(service_handle) = active.as_ref().map(|current| current.handle.clone()) else { + return ( + Err(WalletCallError::Failed("x402 service is unavailable".into())), + X402RpcPermitOutcome::Unused, + ); + }; - let evm = signing_secret(ctx, config, crate::web3::wallet::WalletChain::Evm).await?; - let solana = signing_secret(ctx, config, crate::web3::wallet::WalletChain::Solana).await?; + let secrets = async { + let evm = signing_secret(ctx, config, crate::web3::wallet::WalletChain::Evm).await?; + let solana = signing_secret(ctx, config, crate::web3::wallet::WalletChain::Solana).await?; + Ok::<_, WalletCallError>((evm, solana)) + }; + let (evm, solana) = match secrets.await { + Ok(secrets) => secrets, + Err(error) => return (Err(error), X402RpcPermitOutcome::Unused), + }; + let permit_url = url.clone(); let mut request = X402PreparePaymentRequest { service: service_handle.clone(), url, @@ -46,12 +102,19 @@ pub(crate) async fn prepare_payment( secret: evm, additional_secrets: vec![solana], }; - let response = wallet::call_confidential(config, methods::X402_PREPARE_PAYMENT, &request).await; + let call = wallet::call_confidential(config, methods::X402_PREPARE_PAYMENT, &request); + let (response, outcome) = match rpc_cap { + Some(max_amount_atomic) => { + super::wallet_host::with_x402_rpc_permit(&permit_url, max_amount_atomic, call).await + } + None => (call.await, X402RpcPermitOutcome::Unused), + }; request.secret.mnemonic.zeroize(); for secret in &mut request.additional_secrets { secret.mnemonic.zeroize(); } - Ok((service_handle, response?)) + drop(active); + (response.map(|response| (service_handle, response)), outcome) } /// Record the retry result through the same module-owned payment ledger. diff --git a/crates/openhuman-core/src/web3/x402/fetch_tests.rs b/crates/openhuman-core/src/web3/x402/fetch_tests.rs index f5d0b36e705..b8ab66e5b8f 100644 --- a/crates/openhuman-core/src/web3/x402/fetch_tests.rs +++ b/crates/openhuman-core/src/web3/x402/fetch_tests.rs @@ -126,14 +126,14 @@ fn body_text_truncates_at_the_cap_and_flags_it() { #[test] fn a_refused_authorization_is_reported_with_the_refusal_prefix() { let refused = prepare_error( - crate::modules::wallet_host::X402RpcPermitOutcome::Refused("over cap"), + crate::modules::x402_service::X402RpcPermitOutcome::Refused("over cap"), "module said no", ); assert!(refused.starts_with(REFUSED_PREFIX), "{refused}"); assert!(refused.contains("over cap"), "{refused}"); let failed = prepare_error( - crate::modules::wallet_host::X402RpcPermitOutcome::Unused, + crate::modules::x402_service::X402RpcPermitOutcome::Unused, "challenge invalid", ); assert!(!failed.starts_with(REFUSED_PREFIX), "{failed}"); From 38ba4f9acc7f665bfea5b5685481a5849ca583b9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 12 Nov 2026 16:07:45 +0000 Subject: [PATCH 6/8] feat(web3): add capped x402 fetch for local callers Adds an `openhuman.x402_fetch` entry point that performs a single HTTP request and, on a 402 challenge, routes the payment through TinyWallet's capped preparation so the authorization callback can approve only that payment within the caller's atomic cap and per-request budget. Requests reuse the existing URL guard, reject caller-supplied payment headers, and always report the paid retry's outcome so the module ledger can commit or release the reservation. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/openhuman-core/src/web3/x402/fetch.rs | 396 +++++++++++++++++++ 1 file changed, 396 insertions(+) diff --git a/crates/openhuman-core/src/web3/x402/fetch.rs b/crates/openhuman-core/src/web3/x402/fetch.rs index ec460853b39..58ec4e7a48a 100644 --- a/crates/openhuman-core/src/web3/x402/fetch.rs +++ b/crates/openhuman-core/src/web3/x402/fetch.rs @@ -1,5 +1,401 @@ //! `openhuman.x402_fetch`: one HTTP request that may pay an HTTP 402 challenge //! within a cap the caller states. +//! +//! For a local, non-model caller with no agent turn. The request goes through +//! the same URL guard as `http_request` (https only, no local or private +//! destinations, connections pinned to the vetted addresses, no redirects). +//! On a 402 the challenge goes to TinyWallet through +//! [`x402_service::prepare_capped_payment`], whose one-shot host permit lets +//! the authorization callback approve only this payment, only within +//! `maxAmountAtomic` and the per-request budget. The paid retry's outcome is +//! always reported back so the module ledger commits or keeps the reservation. +//! +//! Logging names the host, status and payment amount only: never the URL path +//! or query, request headers, bodies, or wallet material. + +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use tinyagents_harness::url_guard::ValidatedUrl; + +use crate::core::runtime::DispatchCtx; +use crate::modules::x402_service::{self, X402RpcPermitOutcome}; + +/// Prefix of every error that means the payment was refused by policy (the +/// caller's cap or the host's authorization), as opposed to a failure. +pub(super) const REFUSED_PREFIX: &str = "X402_REFUSED:"; + +/// Largest response body returned to the caller, in bytes. +pub(super) const MAX_BODY_BYTES: usize = 256 * 1024; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +const PROXY_SERVICE: &str = "rpc.x402_fetch"; +const USER_AGENT: &str = concat!("OpenHuman/", env!("CARGO_PKG_VERSION")); +/// Headers that carry an x402 payment; only the module may produce them. +const PAYMENT_HEADERS: [&str; 2] = ["PAYMENT-SIGNATURE", "X-PAYMENT"]; + +#[derive(Debug)] +pub(super) struct FetchParams { + pub(super) url: String, + pub(super) method: reqwest::Method, + pub(super) headers: Vec<(String, String)>, + pub(super) body: Option, + pub(super) max_amount_atomic: u64, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct RawFetchParams { + url: String, + #[serde(default)] + method: Option, + #[serde(default)] + headers: Option>, + #[serde(default)] + body: Option, + max_amount_atomic: u64, +} + +/// Validate the caller's request before anything leaves the device. +pub(super) fn parse_params(params: Map) -> Result { + let raw: RawFetchParams = serde_json::from_value(Value::Object(params)) + .map_err(|error| format!("x402_fetch params: {error}"))?; + + let parsed = reqwest::Url::parse(raw.url.trim()).ok(); + if !parsed + .as_ref() + .is_some_and(|url| url.scheme() == "https" && url.host_str().is_some()) + { + return Err("x402_fetch params: url must be an absolute https:// URL".into()); + } + + let method = match raw.method.as_deref().map(str::to_ascii_uppercase).as_deref() { + None | Some("GET") => reqwest::Method::GET, + Some("POST") => reqwest::Method::POST, + Some(_) => return Err("x402_fetch params: method must be GET or POST".into()), + }; + if raw.body.is_some() && method != reqwest::Method::POST { + return Err("x402_fetch params: a body is only allowed with POST".into()); + } + + let mut headers = Vec::new(); + for (name, value) in raw.headers.unwrap_or_default() { + if PAYMENT_HEADERS + .iter() + .any(|payment| payment.eq_ignore_ascii_case(&name)) + { + return Err(format!( + "x402_fetch params: the {name} header is set by the wallet, not the caller" + )); + } + let Value::String(value) = value else { + return Err(format!( + "x402_fetch params: header {name} must have a string value" + )); + }; + if reqwest::header::HeaderName::from_bytes(name.as_bytes()).is_err() + || reqwest::header::HeaderValue::from_str(&value).is_err() + { + return Err(format!("x402_fetch params: header {name} is not valid")); + } + headers.push((name, value)); + } + + if raw.max_amount_atomic == 0 { + return Err("x402_fetch params: maxAmountAtomic must be greater than zero".into()); + } + + Ok(FetchParams { + url: raw.url.trim().to_owned(), + method, + headers, + body: raw.body, + max_amount_atomic: raw.max_amount_atomic, + }) +} + +/// The `http_request` URL guard in open mode: refuses local and private +/// hosts, including names that resolve to them, and pins the vetted addresses. +pub(super) async fn guard_destination(url: &str) -> Result { + tinyagents_harness::url_guard::validate_url_with_dns_check(url, &[]) + .await + .map_err(|error| format!("x402_fetch: destination refused: {error}")) +} + +/// The caller-facing error for a failed payment preparation: refusals carry +/// [`REFUSED_PREFIX`] so the caller can tell policy from failure. +pub(super) fn prepare_error(outcome: X402RpcPermitOutcome, error: impl std::fmt::Display) -> String { + match outcome { + X402RpcPermitOutcome::Refused(reason) => format!("{REFUSED_PREFIX} {reason}"), + X402RpcPermitOutcome::Approved | X402RpcPermitOutcome::Unused => { + format!("x402_fetch: payment failed: {error}") + } + } +} + +/// Second line behind the host callback: the module's prepared amount must +/// not exceed the caller's cap. +pub(super) fn ensure_within_cap(amount_atomic: u64, max_amount_atomic: u64) -> Result<(), String> { + if amount_atomic > max_amount_atomic { + return Err(format!( + "{REFUSED_PREFIX} x402 payment of {amount_atomic} exceeds maxAmountAtomic {max_amount_atomic}" + )); + } + Ok(()) +} + +/// Decode at most `limit` bytes as UTF-8 text, reporting whether the body was +/// cut. A cut inside a multi-byte character drops that partial character. +pub(super) fn body_text(mut bytes: Vec, limit: usize) -> (String, bool) { + let truncated = bytes.len() > limit; + bytes.truncate(limit); + match String::from_utf8(bytes) { + Ok(text) => (text, truncated), + Err(error) => { + let utf8 = error.utf8_error(); + let mut bytes = error.into_bytes(); + if truncated && utf8.error_len().is_none() { + bytes.truncate(utf8.valid_up_to()); + } + (String::from_utf8_lossy(&bytes).into_owned(), truncated) + } + } +} + +/// Public facts of a payment made for the request. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct FetchPayment { + pub(super) payment_id: String, + pub(super) amount_atomic: u64, + pub(super) asset: String, + pub(super) recipient: String, + pub(super) network: String, + /// The paid retry succeeded and the module ledger recorded it as settled. + pub(super) settled: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub(super) settlement_response: Option, +} + +pub(super) fn response_value( + status: u16, + content_type: Option, + body: String, + truncated: bool, + payment: Option, +) -> Value { + let mut value = json!({ + "status": status, + "body": body, + "truncated": truncated, + "payment": payment, + }); + if let (Some(content_type), Some(object)) = (content_type, value.as_object_mut()) { + object.insert("contentType".into(), Value::String(content_type)); + } + value +} + +async fn send( + target: &ValidatedUrl, + params: &FetchParams, + payment_header: Option<&str>, +) -> Result { + let builder = reqwest::Client::builder() + .timeout(REQUEST_TIMEOUT) + .connect_timeout(CONNECT_TIMEOUT) + .user_agent(USER_AGENT) + .redirect(reqwest::redirect::Policy::none()); + let builder = crate::config::apply_runtime_proxy_to_builder(builder, PROXY_SERVICE) + .resolve_to_addrs(&target.host, &target.addrs); + let client = builder + .build() + .map_err(|error| format!("x402_fetch: HTTP client unavailable: {error}"))?; + let mut request = client.request(params.method.clone(), &target.url); + for (name, value) in ¶ms.headers { + request = request.header(name, value); + } + if let Some(payment_header) = payment_header { + request = request.header("PAYMENT-SIGNATURE", payment_header); + } + if let Some(body) = ¶ms.body { + request = request.body(body.clone()); + } + request + .send() + .await + .map_err(|error| format!("x402_fetch: request failed: {}", error.without_url())) +} + +fn header(response: &reqwest::Response, names: &[&str]) -> Option { + names.iter().find_map(|name| { + response + .headers() + .get(*name) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned) + }) +} + +async fn response_body(mut response: reqwest::Response) -> Result<(String, bool), String> { + let mut bytes = Vec::new(); + while bytes.len() <= MAX_BODY_BYTES { + match response.chunk().await { + Ok(Some(chunk)) => bytes.extend_from_slice(&chunk), + Ok(None) => break, + Err(error) => { + return Err(format!( + "x402_fetch: reading the response failed: {}", + error.without_url() + )) + } + } + } + Ok(body_text(bytes, MAX_BODY_BYTES)) +} + +async fn into_value( + response: reqwest::Response, + payment: Option, +) -> Result { + let status = response.status().as_u16(); + let content_type = header(&response, &["content-type"]); + let (body, truncated) = response_body(response).await?; + Ok(response_value(status, content_type, body, truncated, payment)) +} + +/// Whether the module ledger holds `payment_id` as settled. The host does not +/// parse settlement payloads; the module's verdict is the answer. +async fn ledger_settled( + ctx: &DispatchCtx, + config: &crate::config::Config, + payment_id: &str, +) -> bool { + match x402_service::list_payments(ctx, config, 50).await { + Ok(response) => response.payments.iter().any(|record| { + record.id == payment_id + && record.status == tinywallet_bus::wire::X402PaymentStatus::Settled + }), + Err(error) => { + log::warn!("[x402_fetch] settlement status unavailable: {error}"); + false + } + } +} + +/// Run one `x402_fetch` request. +pub(super) async fn fetch(ctx: DispatchCtx, params: Map) -> Result { + let params = parse_params(params)?; + let target = guard_destination(¶ms.url).await?; + crate::security::egress::enforce_egress(&crate::security::egress::EgressDescriptor::network_fetch( + &target.host, + )) + .await + .map_err(|error| format!("x402_fetch: {error}"))?; + + log::debug!( + "[x402_fetch] {} host={} cap={}", + params.method, + target.host, + params.max_amount_atomic + ); + let response = send(&target, ¶ms, None).await?; + if response.status() != reqwest::StatusCode::PAYMENT_REQUIRED { + return into_value(response, None).await; + } + let Some(challenge) = header(&response, &["PAYMENT-REQUIRED", "X-PAYMENT-REQUIRED"]) else { + // A 402 without an x402 challenge passes through unpaid, as in `http_request`. + return into_value(response, None).await; + }; + + let config = ctx + .load_config() + .await + .map_err(|error| format!("x402_fetch: {error}"))?; + if !config.components.wallet { + return Err(format!( + "{}:wallet", + crate::core::runtime::components::COMPONENT_DISABLED + )); + } + + let (prepared, outcome) = x402_service::prepare_capped_payment( + &ctx, + &config, + target.url.clone(), + challenge, + params.max_amount_atomic, + ) + .await; + let (service, payment) = prepared.map_err(|error| prepare_error(outcome, error))?; + + let record = |status: u16, settlement: Option| { + let config = &config; + let service = service.clone(); + let payment_id = payment.payment_id.clone(); + async move { + match x402_service::record_payment(config, service, payment_id, status, settlement) + .await + { + Ok(()) => true, + Err(error) => { + log::warn!("[x402_fetch] x402 settlement recording failed: {error}"); + false + } + } + } + }; + + if let Err(error) = ensure_within_cap(payment.amount_atomic, params.max_amount_atomic) { + // The proof is never sent; report the attempt so the module keeps its + // own record of the reservation. + record(reqwest::StatusCode::PAYMENT_REQUIRED.as_u16(), None).await; + return Err(error); + } + + log::debug!( + "[x402_fetch] retrying with x402 payment host={} amount={} asset={}", + target.host, + payment.amount_atomic, + payment.asset + ); + let retry = match send(&target, ¶ms, Some(&payment.payment_header)).await { + Ok(retry) => retry, + Err(error) => { + // No response: the module cannot tell whether the proof settled. + record(0, None).await; + return Err(error); + } + }; + let status = retry.status(); + let settlement_response = header(&retry, &["PAYMENT-RESPONSE"]); + let recorded = record(status.as_u16(), settlement_response.clone()).await; + let settled = recorded + && status.is_success() + && settlement_response.is_some() + && ledger_settled(&ctx, &config, &payment.payment_id).await; + log::debug!( + "[x402_fetch] paid retry host={} status={} settled={settled}", + target.host, + status.as_u16() + ); + + into_value( + retry, + Some(FetchPayment { + payment_id: payment.payment_id, + amount_atomic: payment.amount_atomic, + asset: payment.asset, + recipient: payment.recipient, + network: payment.network, + settled, + settlement_response, + }), + ) + .await +} #[cfg(test)] #[path = "fetch_tests.rs"] From 45b65a97c75eb2f7ecd79fb9e6a61b5bd86bf6de Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 12 Nov 2026 16:10:08 +0000 Subject: [PATCH 7/8] feat(x402): add fetch controller schema and handler Register a new x402_fetch controller that exposes the paid-fetch capability, with inputs for url, method, headers, body and maxAmountAtomic and outputs covering status, body, truncation and payment details. This lets callers make an HTTPS request that settles an x402 challenge within a per-request budget. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/web3/x402/schemas.rs | 89 ++++++++++++++++++- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/crates/openhuman-core/src/web3/x402/schemas.rs b/crates/openhuman-core/src/web3/x402/schemas.rs index 3f1bb01faff..77b3a45f45c 100644 --- a/crates/openhuman-core/src/web3/x402/schemas.rs +++ b/crates/openhuman-core/src/web3/x402/schemas.rs @@ -1,7 +1,7 @@ //! Controller schemas + handlers for the `x402` namespace. //! -//! Wires `x402_get_summary`, `x402_list_payments`, and `x402_update_budget` -//! into the global registry consumed by `crates/openhuman-core/src/core/all.rs`. +//! Wires `x402_get_summary`, `x402_list_payments`, `x402_update_budget`, and +//! `x402_fetch` into the global registry consumed by `crates/openhuman-core/src/core/all.rs`. use crate::core::runtime::DispatchCtx; use serde::Deserialize; @@ -15,6 +15,7 @@ pub fn all_controller_schemas() -> Vec { schemas("get_summary"), schemas("list_payments"), schemas("update_budget"), + schemas("fetch"), ] } @@ -32,6 +33,10 @@ pub fn all_registered_controllers() -> Vec { schema: schemas("update_budget"), handler: handle_update_budget, }, + RegisteredController { + schema: schemas("fetch"), + handler: handle_fetch, + }, ] } @@ -105,6 +110,82 @@ pub fn schemas(function: &str) -> ControllerSchema { required: true, }], }, + "fetch" => ControllerSchema { + namespace: "x402", + function: "fetch", + description: "Make one HTTPS request and, on an HTTP 402 x402 challenge, pay it from the wallet within maxAmountAtomic and the per-request budget, then retry once. Refusals are errors prefixed X402_REFUSED:.", + inputs: vec![ + FieldSchema { + name: "url", + ty: TypeSchema::String, + comment: "Absolute https:// URL; local and private hosts are refused.", + required: true, + }, + FieldSchema { + name: "method", + ty: TypeSchema::Option(Box::new(TypeSchema::Enum { + variants: vec!["GET", "POST"], + })), + comment: "GET (default) or POST.", + required: false, + }, + FieldSchema { + name: "headers", + ty: TypeSchema::Option(Box::new(TypeSchema::Map(Box::new( + TypeSchema::String, + )))), + comment: "Request headers; PAYMENT-SIGNATURE and X-PAYMENT are refused.", + required: false, + }, + FieldSchema { + name: "body", + ty: TypeSchema::Option(Box::new(TypeSchema::String)), + comment: "Request body (POST only).", + required: false, + }, + FieldSchema { + name: "maxAmountAtomic", + ty: TypeSchema::BoundedU64 { + min: 1, + max: u64::MAX, + }, + comment: "Most this request may pay, in token atomic units.", + required: true, + }, + ], + outputs: vec![ + FieldSchema { + name: "status", + ty: TypeSchema::U64, + comment: "HTTP status of the final response.", + required: true, + }, + FieldSchema { + name: "contentType", + ty: TypeSchema::Option(Box::new(TypeSchema::String)), + comment: "Response Content-Type, when present.", + required: false, + }, + FieldSchema { + name: "body", + ty: TypeSchema::String, + comment: "Response body as UTF-8 text, at most 256 KiB.", + required: true, + }, + FieldSchema { + name: "truncated", + ty: TypeSchema::Bool, + comment: "Whether the body was cut at the size limit.", + required: true, + }, + FieldSchema { + name: "payment", + ty: TypeSchema::Option(Box::new(TypeSchema::Json)), + comment: "Null when unpaid, else paymentId, amountAtomic, asset, recipient, network, settled and settlementResponse.", + required: true, + }, + ], + }, other => panic!("unknown x402 schema function: {other}"), } } @@ -122,6 +203,10 @@ fn handle_get_summary(ctx: DispatchCtx, _params: Map) -> Controll }) } +fn handle_fetch(ctx: DispatchCtx, params: Map) -> ControllerFuture { + Box::pin(super::fetch::fetch(ctx, params)) +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct ListPaymentsParams { From 0a0c17664270d4f521c5c161b01662635410f4db Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 12 Nov 2026 16:10:45 +0000 Subject: [PATCH 8/8] feat(x402): add x402_fetch RPC for direct paid HTTPS requests Adds an x402_fetch RPC that lets a local caller make a single paid HTTPS request with an explicit maxAmountAtomic cap, without going through an agent turn. It validates parameters, guards the destination, caps the payment, retries after settlement, and reports the outcome while logging only method, host, status and amount. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../openhuman-core/src/modules/wallet_host.rs | 5 +- .../src/modules/x402_service.rs | 4 +- .../about_app/catalog_workflows_automation.rs | 2 +- crates/openhuman-core/src/web3/README.md | 4 +- crates/openhuman-core/src/web3/x402/README.md | 49 +++++++++++++++++-- crates/openhuman-core/src/web3/x402/fetch.rs | 26 +++++++--- .../src/web3/x402/fetch_tests.rs | 23 +++++++-- 7 files changed, 92 insertions(+), 21 deletions(-) diff --git a/crates/openhuman-core/src/modules/wallet_host.rs b/crates/openhuman-core/src/modules/wallet_host.rs index 30e43e431da..30a3c07ad84 100644 --- a/crates/openhuman-core/src/modules/wallet_host.rs +++ b/crates/openhuman-core/src/modules/wallet_host.rs @@ -230,10 +230,7 @@ pub(super) fn x402_rpc_permit_route( X402RpcPermitOutcome::Refused(reason), X402Route::Refused(reason), ), - None => ( - X402RpcPermitOutcome::Approved, - X402Route::RpcPermitApproved, - ), + None => (X402RpcPermitOutcome::Approved, X402Route::RpcPermitApproved), }; entry.outcome = Some(outcome); Some(route) diff --git a/crates/openhuman-core/src/modules/x402_service.rs b/crates/openhuman-core/src/modules/x402_service.rs index 22e98d7c2e1..f67d7756cf8 100644 --- a/crates/openhuman-core/src/modules/x402_service.rs +++ b/crates/openhuman-core/src/modules/x402_service.rs @@ -79,7 +79,9 @@ async fn prepare( } let Some(service_handle) = active.as_ref().map(|current| current.handle.clone()) else { return ( - Err(WalletCallError::Failed("x402 service is unavailable".into())), + Err(WalletCallError::Failed( + "x402 service is unavailable".into(), + )), X402RpcPermitOutcome::Unused, ); }; diff --git a/crates/openhuman-core/src/platform/about_app/catalog_workflows_automation.rs b/crates/openhuman-core/src/platform/about_app/catalog_workflows_automation.rs index 1e02c09799d..882b8d65718 100644 --- a/crates/openhuman-core/src/platform/about_app/catalog_workflows_automation.rs +++ b/crates/openhuman-core/src/platform/about_app/catalog_workflows_automation.rs @@ -208,7 +208,7 @@ Capability { domain: "x402", category: CapabilityCategory::Workflows, description: "Automatic HTTP 402 payment handling for machine-payable APIs via the x402 protocol. When an API returns 402 Payment Required, the agent pays with USDC on Solana using the local wallet and retries. Budget enforcement with per-request, daily, and monthly caps; automated turns (background jobs, approval-free workflows) pay within the budget without a prompt.", - how_to: "Use x402.* RPC methods (get_summary, list_payments, update_budget) to manage spending. Payments happen automatically when the http_request tool encounters a 402 with a PAYMENT-REQUIRED header.", + how_to: "Use x402.* RPC methods (get_summary, list_payments, update_budget) to manage spending. Payments happen automatically when the http_request tool encounters a 402 with a PAYMENT-REQUIRED header; a local caller can make one paid HTTPS request with x402.fetch and an explicit maxAmountAtomic cap.", status: CapabilityStatus::Beta, privacy: LOCAL_CREDENTIALS, }, diff --git a/crates/openhuman-core/src/web3/README.md b/crates/openhuman-core/src/web3/README.md index ffee120db39..fa7a84f8df6 100644 --- a/crates/openhuman-core/src/web3/README.md +++ b/crates/openhuman-core/src/web3/README.md @@ -92,7 +92,7 @@ Namespace names are wire contracts. | `web3_bridge` | `quote`, `execute` | | `web3_dapp` | `call`, `execute` | | [`wallet`](./wallet/README.md) | `setup`, `status`, `reveal_recovery_phrase`, `balances`, `token_balances`, `chain_status`, `network_defaults`, `supported_assets`, `encode_erc20_transfer`, `prepare_transfer`, `execute_prepared`, `tx_status`, `tx_receipt`, `lookup_tx`, `policy_get`, `policy_update`, `ledger_list` | -| [`x402`](./x402/README.md) | `get_summary`, `list_payments`, `update_budget` | +| [`x402`](./x402/README.md) | `get_summary`, `list_payments`, `update_budget`, `fetch` | The existing Wallet/Web3/x402 agent declarations come from `tinywallet-bus`; OpenHuman supplies adapters that call the module. The policy-bound @@ -115,6 +115,8 @@ name and parameter schema. contract and module support, not TinyWallet implementation crates. - The `client` logs endpoint and operation metadata only; request bodies and wallet addresses must not be logged. +- `x402_fetch` logs the method, host, status and payment amount only; the URL + path and query, request headers, bodies and wallet material are never logged. ```bash cargo test -p openhuman --features web3 web3:: diff --git a/crates/openhuman-core/src/web3/x402/README.md b/crates/openhuman-core/src/web3/x402/README.md index a0306996df1..71e9a5394bf 100644 --- a/crates/openhuman-core/src/web3/x402/README.md +++ b/crates/openhuman-core/src/web3/x402/README.md @@ -12,9 +12,10 @@ module call. The module returns the payment header; after the retry, the host passes the raw response status and settlement header back to the module. The host does not parse x402 payloads or keep a parallel ledger. -Payments are available through both the `x402_request` tool and the generic -`http_request` tool's HTTP 402 payment hook. Both use the same module-owned -budget and ledger. +Payments are available through the `x402_request` tool, the generic +`http_request` tool's HTTP 402 payment hook, and the `openhuman.x402_fetch` RPC +for a local caller with no agent turn. All use the same module-owned budget and +ledger. ## Compile-time gate @@ -29,6 +30,8 @@ product enables `web3` through `scripts/ci/product-features.txt`. | [`mod.rs`](./mod.rs) | Facade, payment record vocabulary re-exports, and disabled stub. | | [`schemas.rs`](./schemas.rs) | Stable `openhuman.x402_*` controller names and RPC projections. | | [`schemas_tests.rs`](./schemas_tests.rs) | Pins payment history output, amount display, and UTC timestamp representation. | +| [`fetch.rs`](./fetch.rs) | `x402_fetch`: parameter validation, guarded HTTPS request, capped payment, retry, settlement report, response projection. | +| [`fetch_tests.rs`](./fetch_tests.rs) | Pins `x402_fetch` parameter refusals, the destination guard, body truncation, the refusal prefix, and the response shape. | | [`../../modules/x402_service.rs`](../../modules/x402_service.rs) | User-scoped module configuration, confidential payment calls, history and budget calls, and close/reconfigure cleanup. | | [`../../tools/impl/network/host.rs`](../../tools/impl/network/host.rs) | Generic HTTP payment hook; sends the challenge and returns the module-produced payment header. | @@ -39,6 +42,42 @@ product enables `web3` through `scripts/ci/product-features.txt`. | `get_summary` | Project module-owned spending totals and configured limits. | | `list_payments` | Project recent module-owned payment records using the existing RPC shape. | | `update_budget` | Ask the module to update per-request, daily, and monthly limits. | +| `fetch` | Make one HTTPS request and pay an HTTP 402 challenge within the caller's `maxAmountAtomic`. | + +### `fetch` + +For a local, non-model caller (for example a script over loopback JSON-RPC) +that has no agent turn to approve a payment through. + +Params: `url` (required, `https://` only; local and private hosts are refused +by the `http_request` URL guard, including names that resolve to them), +`method` (`GET` default, or `POST`), `headers` (string map; `PAYMENT-SIGNATURE` +and `X-PAYMENT` are refused), `body` (string, `POST` only), and +`maxAmountAtomic` (required, greater than zero: the most this request may pay). + +The request runs with a 30 s timeout, no redirects, and connections pinned to +the vetted addresses; the privacy mode's egress check applies. A response other +than a 402 with a `PAYMENT-REQUIRED` challenge is returned unpaid. On a +challenge the host calls the module's prepare with a one-shot permit installed +(`modules::wallet_host::with_x402_rpc_permit`) while it holds the x402 service +lock. The authorization callback approves only when that permit is active for +the exact URL the module reports, the amount is within `maxAmountAtomic`, and +it is within the per-request budget; the permit is consumed by the first +callback. Without a permit, routing is unchanged. The module still reserves its +own per-request, daily and monthly budget first. The host retries once with the +payment header and always reports the retry status and `PAYMENT-RESPONSE` +header back to the module, also when the retry fails. + +Response: `{status, contentType?, body, truncated, payment}`. `body` is UTF-8 +text cut at 256 KiB (`truncated: true`). `payment` is `null` when nothing was +paid, else `{paymentId, amountAtomic, asset, recipient, network, settled, +settlementResponse?}`, where `settled` means the retry was 2xx, carried a +settlement header, and the module ledger recorded the payment as settled. + +A payment over `maxAmountAtomic` or the per-request budget, or otherwise +refused by the host's authorization, is an error starting with +`X402_REFUSED:`. A module-side budget refusal (daily or monthly) and other +payment failures start with `x402_fetch: payment failed:`. Payment history keeps the established fields and formatting, including `amount_display` and UTC timestamps. These are host projections of module DTOs, @@ -47,7 +86,9 @@ not host-side accounting or protocol interpretation. ## Safety and lifecycle - The module reserves the amount against its budget, then asks the host to - authorize (`modules::wallet_host::x402_route`). A WebChat turn gets a forced + authorize (`modules::wallet_host::x402_rpc_permit_route`, then + `x402_route`). A direct `x402_fetch` RPC holding a permit for the URL is + approved within its cap and the per-request budget. A WebChat turn gets a forced approval prompt in its own chat; trusted automation (a background job or an approval-free workflow) is approved without a person when the amount is within the per-request budget; an external channel, an unlabelled turn and diff --git a/crates/openhuman-core/src/web3/x402/fetch.rs b/crates/openhuman-core/src/web3/x402/fetch.rs index 58ec4e7a48a..a34e61d5905 100644 --- a/crates/openhuman-core/src/web3/x402/fetch.rs +++ b/crates/openhuman-core/src/web3/x402/fetch.rs @@ -71,7 +71,12 @@ pub(super) fn parse_params(params: Map) -> Result reqwest::Method::GET, Some("POST") => reqwest::Method::POST, Some(_) => return Err("x402_fetch params: method must be GET or POST".into()), @@ -126,7 +131,10 @@ pub(super) async fn guard_destination(url: &str) -> Result /// The caller-facing error for a failed payment preparation: refusals carry /// [`REFUSED_PREFIX`] so the caller can tell policy from failure. -pub(super) fn prepare_error(outcome: X402RpcPermitOutcome, error: impl std::fmt::Display) -> String { +pub(super) fn prepare_error( + outcome: X402RpcPermitOutcome, + error: impl std::fmt::Display, +) -> String { match outcome { X402RpcPermitOutcome::Refused(reason) => format!("{REFUSED_PREFIX} {reason}"), X402RpcPermitOutcome::Approved | X402RpcPermitOutcome::Unused => { @@ -263,7 +271,13 @@ async fn into_value( let status = response.status().as_u16(); let content_type = header(&response, &["content-type"]); let (body, truncated) = response_body(response).await?; - Ok(response_value(status, content_type, body, truncated, payment)) + Ok(response_value( + status, + content_type, + body, + truncated, + payment, + )) } /// Whether the module ledger holds `payment_id` as settled. The host does not @@ -289,9 +303,9 @@ async fn ledger_settled( pub(super) async fn fetch(ctx: DispatchCtx, params: Map) -> Result { let params = parse_params(params)?; let target = guard_destination(¶ms.url).await?; - crate::security::egress::enforce_egress(&crate::security::egress::EgressDescriptor::network_fetch( - &target.host, - )) + crate::security::egress::enforce_egress( + &crate::security::egress::EgressDescriptor::network_fetch(&target.host), + ) .await .map_err(|error| format!("x402_fetch: {error}"))?; diff --git a/crates/openhuman-core/src/web3/x402/fetch_tests.rs b/crates/openhuman-core/src/web3/x402/fetch_tests.rs index b8ab66e5b8f..8a6c68e852d 100644 --- a/crates/openhuman-core/src/web3/x402/fetch_tests.rs +++ b/crates/openhuman-core/src/web3/x402/fetch_tests.rs @@ -74,7 +74,12 @@ fn params_reject_a_body_on_get() { #[test] fn params_reject_caller_supplied_payment_headers() { - for name in ["PAYMENT-SIGNATURE", "payment-signature", "X-PAYMENT", "x-Payment"] { + for name in [ + "PAYMENT-SIGNATURE", + "payment-signature", + "X-PAYMENT", + "x-Payment", + ] { let error = parse_params(params(json!({ "url": "https://api.example.test/resource", "headers": {name: "forged"}, @@ -108,15 +113,25 @@ fn params_require_a_positive_max_amount() { #[tokio::test] async fn destination_guard_refuses_loopback_and_private_hosts() { - for url in ["https://127.0.0.1/x", "https://10.0.0.1/x", "https://localhost/x"] { + for url in [ + "https://127.0.0.1/x", + "https://10.0.0.1/x", + "https://localhost/x", + ] { assert!(guard_destination(url).await.is_err(), "{url}"); } } #[test] fn body_text_truncates_at_the_cap_and_flags_it() { - assert_eq!(body_text(b"hello".to_vec(), 5), ("hello".to_string(), false)); - assert_eq!(body_text(b"hello!".to_vec(), 5), ("hello".to_string(), true)); + assert_eq!( + body_text(b"hello".to_vec(), 5), + ("hello".to_string(), false) + ); + assert_eq!( + body_text(b"hello!".to_vec(), 5), + ("hello".to_string(), true) + ); // A cut inside a multi-byte character never yields invalid UTF-8. let (text, truncated) = body_text("aé".as_bytes().to_vec(), 2); assert!(truncated);