Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(x402): authorize complete requests and gate direct egress

Steven Enamakele88273535eb9
diff --git a/crates/openhuman-core/src/web3/x402/README.md b/crates/openhuman-core/src/web3/x402/README.md
index 4867dbd4e0..5cb43a98eb 100644
--- a/crates/openhuman-core/src/web3/x402/README.md
+++ b/crates/openhuman-core/src/web3/x402/README.md
@@ -41,7 +41,7 @@ and does not need a stub. Signatures must match the real ones exactly;
| File | Role |
| --- | --- |
| [`mod.rs`](./mod.rs) | Facade root: feature gate; re-exports from `tinywallet_x402` (`X402Client`, `X402Error`, `X402PaymentResult`, `handle_402`, the ledger and wire types); `init_ledger`, `handle_402_and_pay` and `request_tool`, which supply the seams; the `store` accessors used by `http_request`. |
-| [`seams.rs`](./seams.rs) | `WalletPaymentSigner` (the crate's `PaymentSigner`: keyring secret, decrypt, `modules::wallet::{derive_account, sign_message}`), `RuntimeProxyPolicy` (`ProxyPolicy` over `config::apply_runtime_proxy_to_builder`), and the `payments()` / `request_tool()` constructors that pair them with the wallet's `OpenHumanTransport`. |
+| [`seams.rs`](./seams.rs) | `WalletPaymentSigner` (the crate's `PaymentSigner`: keyring secret, decrypt, `modules::wallet::{derive_account, sign_message}`), `HostRequestGuard` (action, privacy and destination policy), `RuntimeProxyPolicy` (direct-egress permission from runtime and environment proxy settings), and the `payments()` / `request_tool()` constructors that pair them with the wallet's `OpenHumanTransport`. |
| [`budget.rs`](./budget.rs) | The spending limits: the crate's defaults plus the `OPENHUMAN_X402_*` overrides. |
| [`records.rs`](./records.rs) | `pending_record`: the `Pending` ledger record for the `http_request` fallback (ledger session + chat thread). |
| [`schemas.rs`](./schemas.rs) | RPC controller schemas and handlers for the `x402` namespace: `get_summary`, `list_payments`, `update_budget`. |
@@ -54,7 +54,8 @@ and does not need a stub. Signatures must match the real ones exactly;
| --- | --- | --- |
| `PaymentSigner` (`account`, `sign`) | `WalletPaymentSigner` | The mnemonic is decrypted here for one confidential module call and never enters the crate; it sees an address and finished signatures. Errors keep their historical prefixes (`wallet secret:`, `load config:`, `decrypt mnemonic:`, `derive account:`). |
| `rpc::Transport` (from `tinywallet-crypto`) | `wallet::transport::OpenHumanTransport` | Reads the Solana blockhash through the wallet's failover-aware RPC layer. |
-| `ProxyPolicy` (`apply`) | `RuntimeProxyPolicy` | Applies the runtime proxy configuration to the tool's HTTP client. |
+| `RequestGuard` (`authorize`) | `HostRequestGuard` | Checks action and privacy policy, vets DNS, and returns the complete request with pinned socket addresses. |
+| `ProxyPolicy` (`apply`, `allows_direct_connection`) | `RuntimeProxyPolicy` | Applies runtime proxy settings and refuses direct address-pinned requests while a runtime or environment proxy is required. |
## RPC / controllers
diff --git a/crates/openhuman-core/src/web3/x402/mod.rs b/crates/openhuman-core/src/web3/x402/mod.rs
index 1e9736f8f5..cad93e48fe 100644
--- a/crates/openhuman-core/src/web3/x402/mod.rs
+++ b/crates/openhuman-core/src/web3/x402/mod.rs
@@ -48,7 +48,7 @@ pub use schemas::all_registered_controllers as all_x402_registered_controllers;
#[cfg(feature = "web3")]
pub use tinywallet_x402::ledger::{PaymentRecord, PaymentStatus, SpendingBudget};
#[cfg(feature = "web3")]
-pub use tinywallet_x402::protocol::{X402Client, X402Error, X402PaymentResult, handle_402};
+pub use tinywallet_x402::protocol::{handle_402, X402Client, X402Error, X402PaymentResult};
#[cfg(feature = "web3")]
pub use tinywallet_x402::wire::{
EvmAuthorization, EvmPaymentProof, PaymentChain, PaymentPayload, PaymentProof, PaymentRequired,
diff --git a/crates/openhuman-core/src/web3/x402/seams.rs b/crates/openhuman-core/src/web3/x402/seams.rs
index 3382c64f7c..c3f128deec 100644
--- a/crates/openhuman-core/src/web3/x402/seams.rs
+++ b/crates/openhuman-core/src/web3/x402/seams.rs
@@ -10,8 +10,8 @@
//! - a `Transport`: [`OpenHumanTransport`](crate::web3::wallet::transport::OpenHumanTransport),
//! the failover-aware RPC adapter the wallet already uses, for the Solana
//! blockhash.
-//! - a [`ProxyPolicy`]: [`RuntimeProxyPolicy`] applies the runtime proxy
-//! configuration to the tool's HTTP client.
+//! - a [`ProxyPolicy`]: [`RuntimeProxyPolicy`] refuses direct, address-pinned
+//! requests when runtime or environment proxy policy requires a proxy.
//! - a [`ThreadScope`]: [`TaskLocalThread`] names the chat thread running the
//! tool call, so the ledger can attribute the payment to it.
//!
@@ -28,13 +28,15 @@ use tinytools_std::url_guard::validate_url_with_dns_check;
use tinywallet_x402::crypto::{CryptoPayments, PaymentAccount, PaymentSigner, SignScheme};
use tinywallet_x402::protocol::ProxyPolicy;
use tinywallet_x402::thread::ThreadScope;
-use tinywallet_x402::tools::{AuthorizedUrl, RequestGuard, X402RequestTool};
+use tinywallet_x402::tools::{
+ AuthorizedRequest, ProposedRequest, RequestAuthorizationError, RequestGuard, X402RequestTool,
+};
use tinywallet_x402::wire::PaymentChain;
-use crate::security::SecurityPolicy;
use crate::security::approval::APPROVAL_CHAT_CONTEXT;
-use crate::web3::wallet::WalletChain;
+use crate::security::SecurityPolicy;
use crate::web3::wallet::transport::OpenHumanTransport;
+use crate::web3::wallet::WalletChain;
const LOG_PREFIX: &str = "[x402::seams]";
@@ -42,7 +44,7 @@ const LOG_PREFIX: &str = "[x402::seams]";
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct WalletPaymentSigner;
-/// The runtime proxy configuration, applied to x402's outbound HTTP.
+/// The runtime and environment proxy configuration for x402 outbound HTTP.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct RuntimeProxyPolicy;
@@ -60,29 +62,42 @@ impl RequestGuard for HostRequestGuard {
async fn authorize(
&self,
- url: &str,
- has_body: bool,
- has_headers: bool,
- ) -> Result<AuthorizedUrl, String> {
+ request: &ProposedRequest,
+ ) -> Result<AuthorizedRequest, RequestAuthorizationError> {
if !self.security.can_act() {
- return Err("[policy-blocked] Action blocked: autonomy is read-only".into());
+ return Err(RequestAuthorizationError::Denied(
+ "Action blocked: autonomy is read-only".into(),
+ ));
}
if !self.security.record_action() {
- return Err("Action blocked: rate limit exceeded".into());
+ return Err(RequestAuthorizationError::Denied(
+ "Action blocked: rate limit exceeded".into(),
+ ));
}
- let host = reqwest::Url::parse(url)
+ let host = reqwest::Url::parse(&request.url)
.ok()
.and_then(|parsed| parsed.host_str().map(str::to_string))
.unwrap_or_else(|| "unknown".to_string());
if let Some(reason) = self.security.local_only_block(&host) {
- return Err(reason);
+ return Err(RequestAuthorizationError::Denied(
+ reason
+ .strip_prefix("[policy-blocked] ")
+ .unwrap_or(&reason)
+ .to_string(),
+ ));
}
- let target = validate_url_with_dns_check(url, &self.allowed_domains)
+ let target = validate_url_with_dns_check(&request.url, &self.allowed_domains)
.await
- .map_err(|error| error.to_string())?;
- self.security.disclose(&target.host, has_body, has_headers);
- Ok(AuthorizedUrl {
- url: target.url,
+ .map_err(|error| RequestAuthorizationError::InvalidDestination(error.to_string()))?;
+ self.security.disclose(
+ &target.host,
+ request.body.is_some(),
+ !request.headers.is_empty(),
+ );
+ let mut approved_request = request.clone();
+ approved_request.url = target.url;
+ Ok(AuthorizedRequest {
+ request: approved_request,
host: target.host,
addrs: target.addrs,
})
@@ -233,6 +248,37 @@ impl ProxyPolicy for RuntimeProxyPolicy {
fn apply(&self, builder: reqwest::ClientBuilder, service: &str) -> reqwest::ClientBuilder {
crate::config::apply_runtime_proxy_to_builder(builder, service)
}
+
+ fn allows_direct_connection(&self, service: &str) -> bool {
+ let config = crate::config::runtime_proxy_config();
+ direct_connection_allowed(&config, service, |key| {
+ std::env::var_os(key).is_some_and(|value| !value.is_empty())
+ })
+ }
+}
+
+/// A guarded request must connect to its vetted address directly. Treat any
+/// configured proxy for this service, including process proxy variables, as
+/// requiring the proxy until the host can pin an address through that proxy.
+fn direct_connection_allowed(
+ config: &crate::config::ProxyConfig,
+ service: &str,
+ env_has_value: impl Fn(&str) -> bool,
+) -> bool {
+ const PROXY_ENV_KEYS: &[&str] = &[
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "ALL_PROXY",
+ "http_proxy",
+ "https_proxy",
+ "all_proxy",
+ "OPENHUMAN_HTTP_PROXY",
+ "OPENHUMAN_HTTPS_PROXY",
+ "OPENHUMAN_ALL_PROXY",
+ ];
+ !(config.enabled && config.scope == crate::config::ProxyScope::Environment)
+ && !config.should_apply_to_service(service)
+ && !PROXY_ENV_KEYS.iter().any(|key| env_has_value(key))
}
/// The crypto rail's payment builder, over OpenHuman's wallet and transport.
diff --git a/crates/openhuman-core/src/web3/x402/seams_tests.rs b/crates/openhuman-core/src/web3/x402/seams_tests.rs
index 6654de4918..cee83f5969 100644
--- a/crates/openhuman-core/src/web3/x402/seams_tests.rs
+++ b/crates/openhuman-core/src/web3/x402/seams_tests.rs
@@ -83,6 +83,100 @@ fn the_proxy_policy_yields_a_buildable_client() {
assert!(builder.build().is_ok());
}
+#[test]
+fn x402_direct_egress_requires_absent_runtime_and_environment_proxies() {
+ let service = "tool.x402_request";
+ let clear = |_: &str| false;
+ let mut config = crate::config::ProxyConfig::default();
+ assert!(direct_connection_allowed(&config, service, clear));
+
+ config.enabled = true;
+ config.http_proxy = Some("http://proxy.example:3128".into());
+ assert!(!direct_connection_allowed(&config, service, clear));
+
+ config.scope = crate::config::ProxyScope::Services;
+ config.services = vec!["tool.http_request".into()];
+ assert!(direct_connection_allowed(&config, service, clear));
+ config.services = vec!["tool.*".into()];
+ assert!(!direct_connection_allowed(&config, service, clear));
+
+ config.scope = crate::config::ProxyScope::Environment;
+ assert!(!direct_connection_allowed(&config, service, clear));
+
+ config.enabled = false;
+ for key in [
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "ALL_PROXY",
+ "http_proxy",
+ "https_proxy",
+ "all_proxy",
+ "OPENHUMAN_HTTP_PROXY",
+ "OPENHUMAN_HTTPS_PROXY",
+ "OPENHUMAN_ALL_PROXY",
+ ] {
+ assert!(
+ !direct_connection_allowed(&config, service, |candidate| candidate == key),
+ "{key} must refuse direct egress"
+ );
+ }
+}
+
+fn proposed_request(url: &str) -> ProposedRequest {
+ ProposedRequest {
+ url: url.into(),
+ method: reqwest::Method::POST,
+ headers: vec![("x-custom".into(), "retained".into())],
+ body: Some("private body".into()),
+ }
+}
+
+#[tokio::test]
+async fn x402_guard_authorizes_the_complete_request_and_pins_destination() {
+ let guard = HostRequestGuard {
+ security: Arc::new(SecurityPolicy::default()),
+ allowed_domains: vec![],
+ };
+ let proposed = proposed_request("https://8.8.8.8/path");
+ let authorized = guard.authorize(&proposed).await.unwrap();
+ assert_eq!(authorized.request.url, proposed.url);
+ assert_eq!(authorized.request.method, proposed.method);
+ assert_eq!(authorized.request.headers, proposed.headers);
+ assert_eq!(authorized.request.body, proposed.body);
+ assert_eq!(authorized.host, "8.8.8.8");
+ assert_eq!(authorized.addrs.len(), 1);
+ assert_eq!(authorized.addrs[0].ip().to_string(), "8.8.8.8");
+ assert_eq!(authorized.addrs[0].port(), 443);
+}
+
+#[tokio::test]
+async fn x402_guard_rejects_readonly_and_private_destinations() {
+ let readonly = HostRequestGuard {
+ security: Arc::new(SecurityPolicy {
+ autonomy: crate::security::AutonomyLevel::ReadOnly,
+ ..SecurityPolicy::default()
+ }),
+ allowed_domains: vec![],
+ };
+ assert!(matches!(
+ readonly
+ .authorize(&proposed_request("https://8.8.8.8/"))
+ .await,
+ Err(RequestAuthorizationError::Denied(_))
+ ));
+
+ let guard = HostRequestGuard {
+ security: Arc::new(SecurityPolicy::default()),
+ allowed_domains: vec![],
+ };
+ assert!(matches!(
+ guard
+ .authorize(&proposed_request("http://127.0.0.1/"))
+ .await,
+ Err(RequestAuthorizationError::InvalidDestination(_))
+ ));
+}
+
#[test]
fn the_tool_is_built_from_the_host_seams() {
use tinytools::Tool;