From f267c8c6c8fd7246064ee82cb0640455e49bb029 Mon Sep 17 00:00:00 2001 From: fastrevmd-lab Date: Thu, 29 Oct 2026 23:33:00 -0400 Subject: [PATCH 1/4] feat(http): opt-in explicit egress proxy, still no autodiscovery (#589) HttpClientConfig gains `explicit_proxy: Option`. None, the default, keeps the builder byte-identical (`.no_proxy()`). Some routes every request through `reqwest::Proxy::all`, added after `.no_proxy()`, so HTTP(S)_PROXY / ALL_PROXY / NO_PROXY stay ignored either way. ProxyUrl::parse matches rustsdcmcp's shipped `egress_proxy`: http or https scheme with a host, userinfo accepted (sent as Proxy-Authorization: Basic). It additionally refuses a path, query or fragment, which reqwest would drop silently. Errors never echo the input, Debug goes through SafeUrl, and there is no Display. Tests: default has no proxy; bad schemes/paths rejected without echoing the password; config/client/error Debug never carries the userinfo; a re-exec'd child proves requests CONNECT through the explicit proxy with the Basic header while env proxies point at a decoy that is never dialled. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 + README.md | 2 +- crates/mecmcp-http/src/lib.rs | 195 +++++++++++++- .../explicit_proxy_ignores_env_proxies.rs | 255 ++++++++++++++++++ docs/CRATE-MAP.md | 2 +- 5 files changed, 461 insertions(+), 4 deletions(-) create mode 100644 crates/mecmcp-http/tests/explicit_proxy_ignores_env_proxies.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index a2c2a721..1db68432 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 report `no signatures found` and fail the release (seen on rustsdcmcp v0.6.0). The gate stays hard: a signature that never appears still fails the job with cosign's last error. Consumers pin this workflow by SHA, so they only get the fix after bumping that pin (#595). +### Added + +- **mecmcp-http**: opt-in explicit egress proxy, `HttpClientConfig::explicit_proxy: + Option` (#589). `None`, the default, is unchanged: no proxy. `ProxyUrl::parse` + accepts only an `http://` or `https://` URL with a host and no path, query, or + fragment; HTTPS origins are tunnelled with `CONNECT`, so TLS stays end-to-end. + Userinfo is accepted and sent as `Proxy-Authorization: Basic`, matching rustsdcmcp's + `egress_proxy`. It never appears in `Debug` or errors, and `ProxyUrl` has no + `Display`. Environment proxy variables (`HTTP(S)_PROXY`, `ALL_PROXY`, `NO_PROXY`) + stay ignored with or without it. A struct literal of `HttpClientConfig` that does + not use `..Default::default()` must now set the new field. ## [0.31.1] - 2026-10-29 diff --git a/README.md b/README.md index 11081c0b..b392a913 100644 --- a/README.md +++ b/README.md @@ -666,7 +666,7 @@ refused at startup by 0.3.8. | `mecmcp-changeset` | Plan → digest → approve → apply → verify, two-principal enforcement, indeterminate recovery | rustpanosmcp `mutation.rs` | | `mecmcp-secret` | Outbound credential type (zeroizing, unprintable) and hardened env/file loader | new — see #90 | | `mecmcp-job` | Cancellable job polling: immediate first probe, capped backoff, whole-operation deadline | new — see #90 | -| `mecmcp-http` | Outbound HTTP client: HTTPS-only, no redirects, no proxy, bounded concurrency, whole-request deadline, sensitive headers | new — see #90 | +| `mecmcp-http` | Outbound HTTP client: HTTPS-only, no redirects, no proxy autodiscovery (opt-in explicit proxy only), bounded concurrency, whole-request deadline, sensitive headers | new — see #90 | | `mecmcp-openapi` | Whole-segment path expansion and bounded pagination — rejects, never clamps | new — see #90 | | `mecmcp-intent` | Vendor-neutral policy/object model with per-vendor rendering | new — see ROADMAP | diff --git a/crates/mecmcp-http/src/lib.rs b/crates/mecmcp-http/src/lib.rs index aa149fed..c609a2d3 100644 --- a/crates/mecmcp-http/src/lib.rs +++ b/crates/mecmcp-http/src/lib.rs @@ -41,8 +41,12 @@ //! - **No redirects**: 3xx responses are returned as ordinary responses; the //! client never follows them automatically (a redirect could send credentials //! to an unintended host). -//! - **No proxy**: default features are disabled and `.no_proxy()` is set -//! explicitly, so proxy environment variables cannot redirect traffic. +//! - **No proxy autodiscovery**: default features are disabled and +//! `.no_proxy()` is set explicitly, so proxy environment variables +//! (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`) cannot redirect +//! traffic. The only proxy a client ever uses is the one an operator names in +//! [`HttpClientConfig::explicit_proxy`]; its credentials never reach `Debug` +//! or an error. //! - **Bounded concurrency**: `max_concurrent_requests` enforced via a //! semaphore, and `max_queued_requests` bounds how many callers wait behind it. //! - **Whole-request deadline**: covers both permit acquisition and send, so a @@ -190,6 +194,12 @@ pub struct HttpClientConfig { /// silently accepted alongside the intended pin. Leave this empty to trust /// the ordinary public root store. pub extra_root_certificates: Vec, + /// An operator-named forward proxy for every request; `None` (the + /// default) connects directly. + /// + /// Opt-in only: environment proxy variables are ignored whether or not + /// this is set. See [`ProxyUrl`] for what is accepted. + pub explicit_proxy: Option, } impl Default for HttpClientConfig { @@ -204,10 +214,80 @@ impl Default for HttpClientConfig { max_response_bytes: 8 * 1024 * 1024, user_agent: format!("mecmcp-http/{}", env!("CARGO_PKG_VERSION")), extra_root_certificates: Vec::new(), + explicit_proxy: None, } } } +/// A validated forward-proxy URL for [`HttpClientConfig::explicit_proxy`]. +/// +/// Requests to the HTTPS origin are tunnelled with `CONNECT`, so TLS stays +/// end-to-end between client and origin and an `http://` proxy is accepted: +/// the proxy sees only the origin's `host:port`. An `https://` proxy also +/// encrypts the hop to the proxy itself, trusting the same roots as the +/// origin. Redirects are still never followed. +/// +/// Userinfo (`http://user:pass@proxy:3128`) is accepted and sent as +/// `Proxy-Authorization: Basic`, matching rustsdcmcp's shipped `egress_proxy`. +/// Through an `http://` proxy that header crosses the hop to the proxy in the +/// clear; use `https://` when that hop is untrusted. +/// +/// `Debug` renders through [`SafeUrl`], so the credentials never appear there, +/// and there is deliberately no `Display`. +#[derive(Clone)] +pub struct ProxyUrl(reqwest::Url); + +impl ProxyUrl { + /// Parse and validate a proxy URL. + /// + /// # Errors + /// Returns [`HttpError::ConfigValidation`] for field `explicit_proxy` if + /// `raw` is not a URL, its scheme is not `http` or `https`, it has no + /// host, or it carries a path, query, or fragment. The error never echoes + /// `raw`: a mistyped URL can still hold a readable password. + /// + /// # Examples + /// ``` + /// use mecmcp_http::{HttpClientConfig, ProxyUrl}; + /// + /// let config = HttpClientConfig { + /// explicit_proxy: Some(ProxyUrl::parse("http://proxy.example.internal:3128")?), + /// ..Default::default() + /// }; + /// # Ok::<(), mecmcp_http::HttpError>(()) + /// ``` + pub fn parse(raw: &str) -> Result { + let invalid = |detail: String| HttpError::ConfigValidation { + field: "explicit_proxy".to_owned(), + detail, + }; + // `url::ParseError` renders a fixed description, never the input. + let parsed = reqwest::Url::parse(raw) + .map_err(|error| invalid(format!("not a valid URL: {error}")))?; + if !matches!(parsed.scheme(), "http" | "https") { + return Err(invalid("must be an http:// or https:// URL".to_owned())); + } + if parsed.host_str().is_none_or(str::is_empty) { + return Err(invalid("must name a host".to_owned())); + } + // reqwest would silently drop these; refuse them like a base URL does. + if parsed.path() != "/" || parsed.query().is_some() || parsed.fragment().is_some() { + return Err(invalid( + "must not carry a path, query, or fragment".to_owned(), + )); + } + Ok(Self(parsed)) + } +} + +impl std::fmt::Debug for ProxyUrl { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("ProxyUrl") + .field(&SafeUrl::from_parsed(&self.0)) + .finish() + } +} + /// Shared checks between [`HttpRequest::from_absolute_url`] and /// [`HttpRequest::with_base_and_path`]: HTTPS-only, a host, and no embedded /// credentials. @@ -1124,6 +1204,17 @@ impl HttpClient { builder = builder.tls_certs_only(extra_certs); } + // Added after `.no_proxy()`, which stays: `.proxy()` keeps environment + // autodiscovery off, and this is the only proxy the client will use. + if let Some(proxy) = &config.explicit_proxy { + let proxy = + reqwest::Proxy::all(proxy.0.clone()).map_err(|_| HttpError::ConfigValidation { + field: "explicit_proxy".to_owned(), + detail: "rejected by the HTTP stack".to_owned(), + })?; + builder = builder.proxy(proxy); + } + let inner = builder.build().map_err(|e| HttpError::ClientConstruction { detail: e.to_string(), })?; @@ -3273,6 +3364,106 @@ mod tests { assert!(build_client(HttpClientConfig::default()).is_ok()); } + /// Base64 of the `proxyuser:PASSWORD` placeholder userinfo — what a + /// `Proxy-Authorization: Basic` header built from it would carry. + const ENCODED_PROXY_USERINFO: &str = "cHJveHl1c2VyOlBBU1NXT1JE"; // gitleaks:allow -- base64 of the test placeholder proxyuser:PASSWORD + + /// reqwest's `Client` Debug lists `proxies` only when it has any, so this + /// also catches a lost `.no_proxy()`: the environment matcher would show up. + #[test] + fn default_config_has_no_proxy() { + let config = HttpClientConfig::default(); + assert!(config.explicit_proxy.is_none()); + let client = build_client(config).unwrap(); + let rendered = format!("{client:?}"); + assert!( + !rendered.contains("proxies"), + "default client has a proxy: {rendered}" + ); + } + + #[test] + fn explicit_proxy_accepts_http_and_https_with_or_without_userinfo() { + for raw in [ + "http://proxy.example.internal:3128", + "https://proxy.example.internal:3128/", + "http://proxyuser:PASSWORD@proxy.example.internal:3128", + "http://[::1]:3128", + ] { + let proxy = ProxyUrl::parse(raw).unwrap_or_else(|error| panic!("{raw}: {error}")); + let client = build_client(HttpClientConfig { + explicit_proxy: Some(proxy), + ..Default::default() + }) + .unwrap(); + assert!(format!("{client:?}").contains("proxies"), "{raw} not wired"); + } + } + + #[test] + fn explicit_proxy_rejects_a_bad_scheme_host_or_path() { + for raw in [ + "socks5://proxyuser:PASSWORD@proxy.example.internal:1080", + "ftp://proxy.example.internal", + "file:///etc/hosts", + "not a url", + // Scheme-less: parses with `proxyuser` as the scheme and the + // password in the path, so it must not be echoed either. + "proxyuser:PASSWORD@proxy.example.internal:3128", + "http://proxy.example.internal:3128/path", + "http://proxy.example.internal:3128/?q=1", + "http://proxy.example.internal:3128/#frag", + ] { + let error = ProxyUrl::parse(raw).unwrap_err(); + assert!( + matches!(&error, HttpError::ConfigValidation { field, .. } if field == "explicit_proxy"), + "{raw}: {error:?}" + ); + let rendered = format!("{error} {error:?}"); + assert!( + !rendered.contains("PASSWORD"), + "credential echoed: {rendered}" + ); + } + } + + #[tokio::test] + async fn explicit_proxy_credentials_never_reach_debug_or_errors() { + // Bound then dropped, so the proxy connection is refused. + let (listener, port) = bind_local().await; + drop(listener); + let proxy = + ProxyUrl::parse(&format!("http://proxyuser:PASSWORD@127.0.0.1:{port}")).unwrap(); + let config = HttpClientConfig { + explicit_proxy: Some(proxy.clone()), + ..Default::default() + }; + let client = build_client(config.clone()).unwrap(); + let request = HttpRequest::from_absolute_url(Method::Get, "https://localhost:1/").unwrap(); + let error = client.send(request).await.unwrap_err(); + + for rendered in [ + format!("{proxy:?}"), + format!("{config:?}"), + format!("{client:?}"), + format!("{error} {error:?}"), + ] { + assert!( + !rendered.contains("PASSWORD"), + "password leaked: {rendered}" + ); + assert!( + !rendered.contains("proxyuser"), + "username leaked: {rendered}" + ); + assert!( + !rendered.contains(ENCODED_PROXY_USERINFO), + "encoded userinfo leaked: {rendered}" + ); + } + assert!(format!("{proxy:?}").contains(&format!("127.0.0.1:{port}"))); + } + /// Bad PEM must fail at construction, not at the first request. /// /// `reqwest::Certificate::from_pem` accepts these without complaint on diff --git a/crates/mecmcp-http/tests/explicit_proxy_ignores_env_proxies.rs b/crates/mecmcp-http/tests/explicit_proxy_ignores_env_proxies.rs new file mode 100644 index 00000000..8e70a363 --- /dev/null +++ b/crates/mecmcp-http/tests/explicit_proxy_ignores_env_proxies.rs @@ -0,0 +1,255 @@ +//! `HttpClientConfig::explicit_proxy` routes through the named proxy, and the +//! proxy environment variables never steer the client, with or without one +//! (#589). +//! +//! The environment must be set before the client is built, and the workspace +//! forbids `unsafe_code` — which `std::env::set_var` requires on this edition. +//! So, like `private_ca_pin_replaces_platform_roots.rs`, this test re-execs +//! itself as a child with the variables set through `Command::env`. The parent +//! runs a TLS origin, a CONNECT proxy that records what it is asked, and a +//! decoy proxy that the environment points at and that must never be dialled. + +#![cfg(target_os = "linux")] +#![allow(clippy::unwrap_used, reason = "test code")] + +use mecmcp_http::{HttpClient, HttpClientConfig, HttpRequest, Method, ProxyUrl}; +use mecmcp_openapi::expand_path; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +/// Set only in the child process this test re-execs itself as. +const CHILD_ENV: &str = "MECMCP_HTTP_PROXY_TEST_CHILD"; +/// Port of the TLS origin the child requests. +const ORIGIN_PORT_ENV: &str = "MECMCP_HTTP_PROXY_TEST_ORIGIN_PORT"; +/// Present only for the explicit-proxy leg: the proxy URL to configure. +const EXPLICIT_PROXY_ENV: &str = "MECMCP_HTTP_PROXY_TEST_EXPLICIT"; +/// PEM of the origin's self-signed certificate. +const ORIGIN_CA_ENV: &str = "MECMCP_HTTP_PROXY_TEST_ORIGIN_CA_PEM"; + +/// Base64 of the `proxyuser:PASSWORD` placeholder userinfo. +const ENCODED_PROXY_USERINFO: &str = "cHJveHl1c2VyOlBBU1NXT1JE"; // gitleaks:allow -- base64 of the test placeholder proxyuser:PASSWORD + +#[test] +fn explicit_proxy_is_used_and_env_proxies_are_ignored() { + if std::env::var_os(CHILD_ENV).is_some() { + run_child(); + return; + } + run_parent(); +} + +fn run_parent() { + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let (origin_ca_pem, server_config) = tls_material(); + let (origin, origin_port) = bind_local().await; + serve_origin(origin, server_config); + + let decoy_dials = Arc::new(AtomicUsize::new(0)); + let (decoy, decoy_port) = bind_local().await; + count_dials(decoy, Arc::clone(&decoy_dials)); + + let proxy_heads = Arc::new(Mutex::new(Vec::new())); + let (proxy, proxy_port) = bind_local().await; + serve_connect_proxy(proxy, Arc::clone(&proxy_heads)); + + let decoy_url = format!("http://127.0.0.1:{decoy_port}"); + + // Leg 1: no explicit proxy, environment points at the decoy. + let direct = spawn_child(&decoy_url, origin_port, &origin_ca_pem, None); + assert_child_ok("direct leg", &direct); + + // Leg 2: explicit credentialed proxy; the environment still points at + // the decoy, and NO_PROXY would exempt the origin if it were honoured. + let explicit = format!("http://proxyuser:PASSWORD@127.0.0.1:{proxy_port}"); + let proxied = spawn_child(&decoy_url, origin_port, &origin_ca_pem, Some(&explicit)); + assert_child_ok("explicit-proxy leg", &proxied); + + assert_eq!( + decoy_dials.load(Ordering::SeqCst), + 0, + "an env proxy was dialled" + ); + let heads = proxy_heads.lock().unwrap().clone(); + assert_eq!(heads.len(), 1, "the explicit proxy saw {heads:?}"); + assert!( + heads[0].starts_with(&format!("CONNECT localhost:{origin_port} HTTP/1.1\r\n")), + "not a CONNECT to the origin: {:?}", + heads[0] + ); + assert!( + heads[0].contains(&format!("Basic {ENCODED_PROXY_USERINFO}")), + "userinfo did not become Proxy-Authorization: {:?}", + heads[0] + ); + }); +} + +fn assert_child_ok(leg: &str, output: &Output) { + assert!( + output.status.success(), + "{leg} failed\n--- child stdout ---\n{}\n--- child stderr ---\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); +} + +fn spawn_child( + env_proxy: &str, + origin_port: u16, + origin_ca_pem: &str, + explicit_proxy: Option<&str>, +) -> Output { + let mut command = Command::new(std::env::current_exe().unwrap()); + command + .env(CHILD_ENV, "1") + .env(ORIGIN_PORT_ENV, origin_port.to_string()) + .env(ORIGIN_CA_ENV, origin_ca_pem) + .env("HTTPS_PROXY", env_proxy) + .env("https_proxy", env_proxy) + .env("HTTP_PROXY", env_proxy) + .env("http_proxy", env_proxy) + .env("ALL_PROXY", env_proxy) + .env("all_proxy", env_proxy); + // NO_PROXY=* only with an explicit proxy: in the direct leg it would + // exempt the origin from the env proxy and hide a lost `.no_proxy()`. + match explicit_proxy { + Some(url) => command + .env(EXPLICIT_PROXY_ENV, url) + .env("NO_PROXY", "*") + .env("no_proxy", "*"), + None => command + .env_remove(EXPLICIT_PROXY_ENV) + .env_remove("NO_PROXY") + .env_remove("no_proxy"), + }; + command.output().unwrap() +} + +/// Build one client and make one request; a panic is the failure signal. +fn run_child() { + let origin_port: u16 = std::env::var(ORIGIN_PORT_ENV).unwrap().parse().unwrap(); + let origin_ca_pem = std::env::var(ORIGIN_CA_ENV).unwrap(); + let explicit_proxy = std::env::var(EXPLICIT_PROXY_ENV) + .ok() + .map(|raw| ProxyUrl::parse(&raw).unwrap()); + + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let client = HttpClient::new(HttpClientConfig { + extra_root_certificates: vec![origin_ca_pem], + explicit_proxy, + request_timeout: std::time::Duration::from_secs(10), + ..Default::default() + }) + .unwrap(); + let path = expand_path("/", &[]).unwrap(); + let request = HttpRequest::with_base_and_path( + Method::Get, + &format!("https://localhost:{origin_port}"), + &path, + ) + .unwrap(); + let response = client.send(request).await.unwrap(); + assert_eq!(response.status(), 200); + }); +} + +/// Self-signed `localhost` certificate PEM and a server config presenting it. +/// +/// The provider is named explicitly: under `cargo test --workspace` more than +/// one rustls provider is enabled and auto-detection panics. +fn tls_material() -> (String, rustls::ServerConfig) { + let key_pair = rcgen::KeyPair::generate().unwrap(); + let params = rcgen::CertificateParams::new(vec!["localhost".to_owned()]).unwrap(); + let cert = params.self_signed(&key_pair).unwrap(); + let key_der = rustls::pki_types::PrivatePkcs8KeyDer::from(key_pair.serialize_der()).into(); + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let mut server_config = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![cert.der().clone()], key_der) + .unwrap(); + server_config.alpn_protocols = vec![b"http/1.1".to_vec()]; + (cert.pem(), server_config) +} + +async fn bind_local() -> (tokio::net::TcpListener, u16) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + (listener, port) +} + +/// Read a request head off a stream, up to and including the blank line. +async fn read_head(stream: &mut S) -> String { + let mut seen = Vec::new(); + let mut byte = [0u8; 1]; + while stream.read_exact(&mut byte).await.is_ok() { + seen.push(byte[0]); + if seen.ends_with(b"\r\n\r\n") { + break; + } + } + String::from_utf8_lossy(&seen).into_owned() +} + +/// Answer every TLS request with an empty `200 OK`. +fn serve_origin(listener: tokio::net::TcpListener, server_config: rustls::ServerConfig) { + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config)); + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + let acceptor = acceptor.clone(); + tokio::spawn(async move { + let Ok(mut tls) = acceptor.accept(stream).await else { + return; + }; + read_head(&mut tls).await; + let _ = tls + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await; + let _ = tls.flush().await; + }); + } + }); +} + +/// Count connections and never answer them. +fn count_dials(listener: tokio::net::TcpListener, dials: Arc) { + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + dials.fetch_add(1, Ordering::SeqCst); + drop(stream); + } + }); +} + +/// A minimal CONNECT proxy: record the request head, then tunnel to the +/// `host:port` it names. +fn serve_connect_proxy(listener: tokio::net::TcpListener, heads: Arc>>) { + tokio::spawn(async move { + while let Ok((mut client, _)) = listener.accept().await { + let heads = Arc::clone(&heads); + tokio::spawn(async move { + let head = read_head(&mut client).await; + heads.lock().unwrap().push(head.clone()); + let Some(target) = head + .strip_prefix("CONNECT ") + .and_then(|rest| rest.split(' ').next()) + else { + return; + }; + let Ok(mut upstream) = tokio::net::TcpStream::connect(target).await else { + return; + }; + let _ = client + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .await; + let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await; + }); + } + }); +} diff --git a/docs/CRATE-MAP.md b/docs/CRATE-MAP.md index 842288ea..5a017ea6 100644 --- a/docs/CRATE-MAP.md +++ b/docs/CRATE-MAP.md @@ -127,7 +127,7 @@ Reaching the far side, and running as a service. | `mecmcp-runtime` | 2,958 | audit, auth, secret | CLI parsing with provenance — which flags the operator actually typed, not merely the resolved values — plus TLS bootstrap, SIGHUP reload, graceful shutdown and the token subcommands. | ``` -mecmcp-http HttpClient · HttpClientConfig · HttpRequest::with_base_and_path · SafeUrl +mecmcp-http HttpClient · HttpClientConfig · ProxyUrl · HttpRequest::with_base_and_path · SafeUrl mecmcp-scp ScpClient · SshConfig · HostKeyVerification · ScpOutcome mecmcp-job poll_until_ready · Probe · PollConfig · PollError mecmcp-openapi expand_path · ExpandedPath · page · PageLimits · PathError From 30614dda52ff815d8c93ce3991fa1d8d4f4e7d2e Mon Sep 17 00:00:00 2001 From: fastrevmd-lab Date: Thu, 29 Oct 2026 23:42:42 -0400 Subject: [PATCH 2/4] fix(http): cap explicit proxy URL length so hyper-util cannot drop it silently (#589) hyper-util re-parses the proxy as an http::Uri (about 64 KiB max) and, on failure, returns no intercept without an error, so a ProxyUrl with a very long password left the client going direct. ProxyUrl::parse now refuses a serialized URL over 2048 bytes, without echoing it. The wiring test now asserts the client carries the proxy as its https intercept target, not just a `proxies` entry (a dropped proxy still shows `proxies: [Matcher]`). New test covers the cap boundary and the 70,000-byte case. CHANGELOG: the source break moves to a `### Changed` "Breaking for source (#589)" bullet naming the affected consumers. mecmcp-oidc's doc now says "no proxy autodiscovery". Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 25 ++++++++---- crates/mecmcp-http/src/lib.rs | 71 +++++++++++++++++++++++++++++---- crates/mecmcp-oidc/src/fetch.rs | 2 +- 3 files changed, 82 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1db68432..e3994ac4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,13 +41,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **mecmcp-http**: opt-in explicit egress proxy, `HttpClientConfig::explicit_proxy: Option` (#589). `None`, the default, is unchanged: no proxy. `ProxyUrl::parse` - accepts only an `http://` or `https://` URL with a host and no path, query, or - fragment; HTTPS origins are tunnelled with `CONNECT`, so TLS stays end-to-end. - Userinfo is accepted and sent as `Proxy-Authorization: Basic`, matching rustsdcmcp's - `egress_proxy`. It never appears in `Debug` or errors, and `ProxyUrl` has no - `Display`. Environment proxy variables (`HTTP(S)_PROXY`, `ALL_PROXY`, `NO_PROXY`) - stay ignored with or without it. A struct literal of `HttpClientConfig` that does - not use `..Default::default()` must now set the new field. + accepts only an `http://` or `https://` URL with a host, no path, query, or + fragment, and at most 2048 bytes serialized (hyper-util would otherwise drop an + over-long proxy without an error and go direct); HTTPS origins are tunnelled with + `CONNECT`, so TLS stays end-to-end. Userinfo is accepted and sent as + `Proxy-Authorization: Basic`, matching rustsdcmcp's `egress_proxy`. It never appears + in `Debug` or errors, and `ProxyUrl` has no `Display`. Environment proxy variables + (`HTTP(S)_PROXY`, `ALL_PROXY`, `NO_PROXY`) stay ignored with or without it. + +### Changed + +- **Breaking for source (#589):** `mecmcp_http::HttpClientConfig` has a new public + field, `explicit_proxy: Option`. Code that builds an `HttpClientConfig` by + full struct literal must add `explicit_proxy: None`. rustmistmcp does + (`crates/rustmistmcp-core/src/client.rs:187` and `:290`) and will not compile until + it does. Consumers that fill the rest with `..Default::default()` — mecfeedmcp, + rustopnsmcp, rustunifimcp, rustproxmoxmcp and mecviz — are unaffected. When + rustsdcmcp moves its `egress_proxy` onto `ProxyUrl`, a deployed value with a path or + query (which it accepts today and reqwest ignores) will be refused at startup. ## [0.31.1] - 2026-10-29 diff --git a/crates/mecmcp-http/src/lib.rs b/crates/mecmcp-http/src/lib.rs index c609a2d3..90222543 100644 --- a/crates/mecmcp-http/src/lib.rs +++ b/crates/mecmcp-http/src/lib.rs @@ -237,13 +237,21 @@ impl Default for HttpClientConfig { #[derive(Clone)] pub struct ProxyUrl(reqwest::Url); +/// Longest serialized proxy URL accepted, in bytes. +/// +/// hyper-util re-parses the proxy as an `http::Uri`, which caps near 64 KiB, +/// and on failure drops the proxy without an error — the client would then go +/// direct. A real proxy URL is far shorter, so this cap fails loudly first. +const MAX_PROXY_URL_BYTES: usize = 2048; + impl ProxyUrl { /// Parse and validate a proxy URL. /// /// # Errors /// Returns [`HttpError::ConfigValidation`] for field `explicit_proxy` if /// `raw` is not a URL, its scheme is not `http` or `https`, it has no - /// host, or it carries a path, query, or fragment. The error never echoes + /// host, it carries a path, query, or fragment, or it serializes to more + /// than 2048 bytes. The error never echoes /// `raw`: a mistyped URL can still hold a readable password. /// /// # Examples @@ -276,6 +284,11 @@ impl ProxyUrl { "must not carry a path, query, or fragment".to_owned(), )); } + if parsed.as_str().len() > MAX_PROXY_URL_BYTES { + return Err(invalid(format!( + "must not exceed {MAX_PROXY_URL_BYTES} bytes" + ))); + } Ok(Self(parsed)) } } @@ -3390,13 +3403,55 @@ mod tests { "http://proxyuser:PASSWORD@proxy.example.internal:3128", "http://[::1]:3128", ] { - let proxy = ProxyUrl::parse(raw).unwrap_or_else(|error| panic!("{raw}: {error}")); - let client = build_client(HttpClientConfig { - explicit_proxy: Some(proxy), - ..Default::default() - }) - .unwrap(); - assert!(format!("{client:?}").contains("proxies"), "{raw} not wired"); + assert_proxy_wired( + ProxyUrl::parse(raw).unwrap_or_else(|error| panic!("{raw}: {error}")), + ); + } + } + + /// The built client must carry the proxy as its `https` intercept target. + /// + /// hyper-util drops a proxy URL it cannot parse as an `http::Uri` without + /// an error, leaving the client going direct, so `proxies` being present + /// is not enough: the target itself has to be there. + fn assert_proxy_wired(proxy: ProxyUrl) { + let target = format!( + "https: Intercept {{ uri: {} }}", + SafeUrl::from_parsed(&proxy.0) + ); + let client = build_client(HttpClientConfig { + explicit_proxy: Some(proxy), + ..Default::default() + }) + .unwrap(); + let rendered = format!("{client:?}"); + assert!(rendered.contains(&target), "{target} not in {rendered}"); + } + + #[test] + fn explicit_proxy_longer_than_the_cap_is_rejected_without_echoing_it() { + let build = |fill: usize| { + format!( + "http://proxyuser:{}@proxy.example.internal:3128/", + "P".repeat(fill) + ) + }; + let fill_to_cap = MAX_PROXY_URL_BYTES - build(0).len(); + + let at_cap = ProxyUrl::parse(&build(fill_to_cap)).unwrap(); + assert_eq!(at_cap.0.as_str().len(), MAX_PROXY_URL_BYTES); + assert_proxy_wired(at_cap); + + // One byte over, and the 70,000-byte case hyper-util would have + // silently dropped (its `http::Uri` parse caps near 64 KiB). + for fill in [fill_to_cap + 1, 70_000] { + let error = ProxyUrl::parse(&build(fill)).unwrap_err(); + assert!( + matches!(&error, HttpError::ConfigValidation { field, .. } if field == "explicit_proxy"), + "{fill}: {error:?}" + ); + let rendered = format!("{error} {error:?}"); + assert!(!rendered.contains("PPPPPPPP"), "input echoed: {rendered}"); } } diff --git a/crates/mecmcp-oidc/src/fetch.rs b/crates/mecmcp-oidc/src/fetch.rs index d3a53a97..daeefcf7 100644 --- a/crates/mecmcp-oidc/src/fetch.rs +++ b/crates/mecmcp-oidc/src/fetch.rs @@ -33,7 +33,7 @@ pub trait KeySource: Send + Sync { /// Production [`KeySource`], built on `mecmcp-http`'s hardened outbound client. /// /// Inherits that client's guarantees for free: HTTPS-only, no redirects, no -/// proxy, bounded response size, and a whole-request deadline. An OIDC +/// proxy autodiscovery, bounded response size, and a whole-request deadline. An OIDC /// discovery/JWKS endpoint is exactly the kind of outbound API call that /// crate was built for. pub struct HttpKeySource { From 9a550d696d7a66491f4c7404db1d99c2eccf175a Mon Sep 17 00:00:00 2001 From: fastrevmd-lab Date: Thu, 29 Oct 2026 23:46:00 -0400 Subject: [PATCH 3/4] docs(changelog): spacing after rebase (#589) Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3994ac4..38b07f27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 report `no signatures found` and fail the release (seen on rustsdcmcp v0.6.0). The gate stays hard: a signature that never appears still fails the job with cosign's last error. Consumers pin this workflow by SHA, so they only get the fix after bumping that pin (#595). + ### Added - **mecmcp-http**: opt-in explicit egress proxy, `HttpClientConfig::explicit_proxy: From acd92f22714c2b55936b8363c5a1e69b15c46d56 Mon Sep 17 00:00:00 2001 From: fastrevmd-lab Date: Thu, 29 Oct 2026 23:46:31 -0400 Subject: [PATCH 4/4] test(http): keep credentialed proxy URLs out of source literals (#589) The pre-push credential gate rejects http(s) URLs with a userinfo password unless it is a placeholder; use PASSWORD in the doc and build the over-length fixture from pieces. Same bytes at runtime. Co-Authored-By: Claude Opus 5.5 --- crates/mecmcp-http/src/lib.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/mecmcp-http/src/lib.rs b/crates/mecmcp-http/src/lib.rs index 90222543..c45335d7 100644 --- a/crates/mecmcp-http/src/lib.rs +++ b/crates/mecmcp-http/src/lib.rs @@ -227,7 +227,7 @@ impl Default for HttpClientConfig { /// encrypts the hop to the proxy itself, trusting the same roots as the /// origin. Redirects are still never followed. /// -/// Userinfo (`http://user:pass@proxy:3128`) is accepted and sent as +/// Userinfo (`http://user:PASSWORD@proxy:3128`) is accepted and sent as /// `Proxy-Authorization: Basic`, matching rustsdcmcp's shipped `egress_proxy`. /// Through an `http://` proxy that header crosses the hop to the proxy in the /// clear; use `https://` when that hop is untrusted. @@ -3431,10 +3431,13 @@ mod tests { #[test] fn explicit_proxy_longer_than_the_cap_is_rejected_without_echoing_it() { let build = |fill: usize| { - format!( - "http://proxyuser:{}@proxy.example.internal:3128/", - "P".repeat(fill) - ) + // Built from pieces so the source holds no literal credentialed URL. + [ + "http://proxyuser:", + &"P".repeat(fill), + "@proxy.example.internal:3128/", + ] + .concat() }; let fill_to_cap = MAX_PROXY_URL_BYTES - build(0).len();