diff --git a/src/crates/adapters/ai-adapters/AGENTS.md b/src/crates/adapters/ai-adapters/AGENTS.md index c3d146106a..03fea22a5a 100644 --- a/src/crates/adapters/ai-adapters/AGENTS.md +++ b/src/crates/adapters/ai-adapters/AGENTS.md @@ -255,6 +255,18 @@ metadata with credential revision checks, preserving their tokens and models. A failed account request (including 404) must not fall back to public OAuth inference. Account route metadata must not contain keys or token material. +HTTP proxy policy (legacy disabled settings stay direct; Windows bypass rules +retain wildcard and `` semantics): + +```bash +cargo test --locked -p openbitfun-ai-adapters --lib client::http::tests +cargo test --locked -p openbitfun-ai-adapters --features subscription-auth --lib client::http::tests::router_proxy_policy_preserves_environment_explicit_and_disabled_routes +``` + +The second command uses the auth feature's hidden-process helper for an isolated +environment-proxy fixture, including on Windows. Fixtures do not change the OS +proxy, access provider accounts, or verify remote-host behavior. + Router HTTP serialization, classifier parsing, authentication, and failures: ```bash diff --git a/src/crates/adapters/ai-adapters/src/client/http.rs b/src/crates/adapters/ai-adapters/src/client/http.rs index 045294fc65..907d103c5c 100644 --- a/src/crates/adapters/ai-adapters/src/client/http.rs +++ b/src/crates/adapters/ai-adapters/src/client/http.rs @@ -3,7 +3,7 @@ use crate::types::ProxyConfig; use anyhow::{anyhow, Result}; use log::{debug, error, info, warn}; use openbitfun_services_core::system_proxy::SystemProxy; -use reqwest::{Client, ClientBuilder, NoProxy, Proxy}; +use reqwest::{Client, ClientBuilder, Proxy}; /// Router requests use the shared proxy policy with their own total timeout. pub(crate) fn create_router_http_client( @@ -61,55 +61,59 @@ pub(crate) fn create_http_client( ); } - builder = apply_proxy_policy(builder, proxy_config); + builder = apply_proxy_policy(builder, proxy_config.clone()); match builder.build() { Ok(client) => client, Err(e) => { error!( - "HTTP client initialization failed: {}, using default client", + "HTTP client initialization failed: {}, using default transport options", e ); - Client::new() + apply_proxy_policy(Client::builder(), proxy_config) + .build() + .expect("Failed to initialize HTTP client with configured proxy policy") } } } -/// Resolve the transport proxy policy in priority order. -/// -/// 1. An enabled proxy with an address is used as configured. -/// 2. A configured address with the switch off means "connect directly"; the -/// user turned the proxy off on purpose. -/// 3. No configured address falls back to the operating system proxy. Many users -/// reach providers only through a local proxy agent, and that setting lives in -/// the OS rather than in this app. -/// 4. Without any of the above the client keeps reqwest's default, which honours -/// the `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` environment variables. +/// Missing or disabled app proxy settings retain the legacy direct connection. +/// Only an enabled proxy may select a manual address or, when its address is +/// empty, inherit operating system / environment settings. fn apply_proxy_policy(builder: ClientBuilder, proxy_config: Option) -> ClientBuilder { - if let Some(proxy_cfg) = proxy_config { - let configured = !proxy_cfg.url.trim().is_empty(); - if proxy_cfg.enabled && configured { - return match build_proxy(&proxy_cfg) { - Ok(proxy) => { - info!("Using proxy: {}", proxy_cfg.url); - builder.proxy(proxy) - } - Err(e) => { - error!( - "Proxy configuration failed: {}, proceeding without proxy", - e - ); - builder.no_proxy() - } - }; - } - if configured { - info!("Proxy disabled by configuration, connecting directly"); - return builder.no_proxy(); - } + apply_proxy_policy_with_system_proxy( + builder, + proxy_config, + openbitfun_services_core::system_proxy::detect, + ) +} + +fn apply_proxy_policy_with_system_proxy( + builder: ClientBuilder, + proxy_config: Option, + detect: impl FnOnce() -> Option, +) -> ClientBuilder { + let Some(proxy_cfg) = proxy_config.filter(|config| config.enabled) else { + return builder.no_proxy(); + }; + + if !proxy_cfg.url.trim().is_empty() { + return match build_proxy(&proxy_cfg) { + Ok(proxy) => { + info!("Using proxy: {}", proxy_cfg.url); + builder.proxy(proxy) + } + Err(e) => { + error!( + "Proxy configuration failed: {}, proceeding without proxy", + e + ); + builder.no_proxy() + } + }; } - match openbitfun_services_core::system_proxy::detect() { + match detect() { Some(system) => match system_proxy(&system) { Some(proxy) => { info!("Using operating system proxy: {}", system.url); @@ -131,9 +135,14 @@ fn apply_proxy_policy(builder: ClientBuilder, proxy_config: Option) /// /// Loopback targets always bypass the proxy so local model servers keep working. fn system_proxy(system: &SystemProxy) -> Option { - let proxy = Proxy::all(&system.url).ok()?; - let no_proxy = system.no_proxy.as_deref().and_then(NoProxy::from_string); - Some(proxy.no_proxy(no_proxy)) + // Validate eagerly, then use the Windows matcher rather than translating + // wildcard / rules into reqwest's narrower NoProxy syntax. + Proxy::all(&system.url).ok()?; + let system = system.clone(); + Some(Proxy::custom(move |url| { + let host = url.host_str()?; + (!system.bypasses_host(host)).then(|| system.url.clone()) + })) } pub(crate) fn build_proxy(config: &ProxyConfig) -> Result { @@ -161,7 +170,9 @@ fn normalize_proxy_url(url: &str) -> String { #[cfg(test)] mod tests { - use super::{build_proxy, normalize_proxy_url, system_proxy}; + use super::{ + apply_proxy_policy_with_system_proxy, build_proxy, normalize_proxy_url, system_proxy, + }; use crate::types::ProxyConfig; use openbitfun_services_core::system_proxy::SystemProxy; @@ -213,6 +224,109 @@ mod tests { proxy_server.abort(); } + #[tokio::test] + async fn legacy_proxy_payloads_round_trip_and_connect_directly_without_system_detection() { + openbitfun_services_core::tls_provider::ensure_ring_crypto_provider(); + let (direct_url, direct_server) = response_fixture("direct").await; + let address = direct_url.strip_prefix("http://").unwrap().parse().unwrap(); + let target = direct_url.replace("127.0.0.1", "legacy-model.corp.internal"); + let mut configs = vec![None]; + for payload in [ + serde_json::json!({}), + serde_json::json!({"enabled": false}), + serde_json::json!({"enabled": false, "url": ""}), + serde_json::json!({"enabled": false, "url": " "}), + serde_json::json!({ + "enabled": false, + "url": "http://unused-proxy.invalid:7897", + "username": "saved-user", + "password": "saved-password" + }), + ] { + let config: ProxyConfig = serde_json::from_value(payload.clone()).unwrap(); + let stored = serde_json::to_value(&config).unwrap(); + for (key, value) in payload.as_object().unwrap() { + assert_eq!(&stored[key], value, "legacy field {key} changed"); + } + configs.push(Some(serde_json::from_value(stored).unwrap())); + } + for config in configs { + let builder = reqwest::Client::builder() + .resolve("legacy-model.corp.internal", address) + .timeout(std::time::Duration::from_secs(3)); + let client = apply_proxy_policy_with_system_proxy(builder, config, || { + panic!("legacy direct settings must not inspect the system proxy") + }) + .build() + .unwrap(); + assert_eq!( + client + .get(&target) + .send() + .await + .unwrap() + .text() + .await + .unwrap(), + "direct" + ); + } + direct_server.abort(); + } + + #[tokio::test] + async fn system_proxy_routes_windows_wildcards_and_local_marker_without_bypassing_public_hosts() + { + openbitfun_services_core::tls_provider::ensure_ring_crypto_provider(); + let (direct_url, direct_server) = response_fixture("direct").await; + let (proxy_url, proxy_server) = response_fixture("system proxy").await; + let address = direct_url.strip_prefix("http://").unwrap().parse().unwrap(); + let mut builder = reqwest::Client::builder().timeout(std::time::Duration::from_secs(3)); + for host in ["model.corp.internal", "intranet", "exact.internal"] { + builder = builder.resolve(host, address); + } + let client = apply_proxy_policy_with_system_proxy( + builder, + Some(ProxyConfig { + enabled: true, + ..Default::default() + }), + || { + Some(SystemProxy { + url: proxy_url, + no_proxy: Some("*.corp.internal,,exact.internal".into()), + }) + }, + ) + .build() + .unwrap(); + for (host, expected) in [ + ("model.corp.internal", "direct"), + ("intranet", "direct"), + ("exact.internal", "direct"), + ("public.example", "system proxy"), + ("corp.internal", "system proxy"), + ("child.exact.internal", "system proxy"), + ("model.corp.internal.attacker.example", "system proxy"), + ] { + let target = direct_url.replace("127.0.0.1", host); + assert_eq!( + client + .get(target) + .send() + .await + .unwrap() + .text() + .await + .unwrap(), + expected, + "unexpected route for {host}" + ); + } + direct_server.abort(); + proxy_server.abort(); + } + #[tokio::test] async fn router_client_keeps_its_total_timeout_and_rejects_redirects() { use axum::{http::StatusCode, response::Redirect, routing::get}; @@ -262,12 +376,10 @@ mod tests { server.abort(); } - // On Windows OS proxy detection precedes the environment fallback; the - // synthetic SystemProxy test above covers that portable adapter boundary. // A separate process keeps reqwest's environment cache and proxy variables // isolated from concurrent tests. The existing auth feature supplies the // platform-safe process helper without adding a production dependency. - #[cfg(all(feature = "subscription-auth", not(windows)))] + #[cfg(feature = "subscription-auth")] #[tokio::test] async fn router_proxy_policy_preserves_environment_explicit_and_disabled_routes() { use super::create_router_http_client; @@ -286,17 +398,44 @@ mod tests { None, Some(ProxyConfig::default()), Some(ProxyConfig { - enabled: true, - ..Default::default() - }), - Some(ProxyConfig { - enabled: true, - url: " ".into(), + enabled: false, + url: explicit_proxy.clone(), ..Default::default() }), ] { - let client = - create_router_http_client(Duration::from_secs(3), config, false).unwrap(); + for client in [ + super::create_http_client(config.clone(), false), + create_router_http_client(Duration::from_secs(3), config, false).unwrap(), + ] { + assert_eq!( + client + .get(&direct_url) + .send() + .await + .unwrap() + .text() + .await + .unwrap(), + "direct" + ); + } + } + + // An enabled proxy with no address retains inheritance. Inject the + // absence of an OS proxy so this fixture is independent of the + // Windows machine's actual registry configuration. + for url in ["", " "] { + let client = apply_proxy_policy_with_system_proxy( + reqwest::Client::builder().timeout(Duration::from_secs(3)), + Some(ProxyConfig { + enabled: true, + url: url.into(), + ..Default::default() + }), + || None, + ) + .build() + .unwrap(); assert_eq!( client .get("http://router-proxy-fixture.invalid/probe") diff --git a/src/crates/services/services-core/src/system_proxy.rs b/src/crates/services/services-core/src/system_proxy.rs index 54118afc96..da7458c82c 100644 --- a/src/crates/services/services-core/src/system_proxy.rs +++ b/src/crates/services/services-core/src/system_proxy.rs @@ -14,10 +14,70 @@ pub struct SystemProxy { /// Proxy URL with an explicit scheme, for example `http://127.0.0.1:7897`. pub url: String, - /// Hosts that must bypass the proxy, ready for `reqwest::NoProxy` syntax. + /// Comma-separated Windows bypass patterns, including `*` and ``. + /// These are not reqwest `NoProxy` rules; use [`Self::bypasses_host`]. pub no_proxy: Option, } +impl SystemProxy { + /// Match the URL host without resolving DNS. Windows wildcard patterns + /// cannot be passed to reqwest's suffix-only `NoProxy` matcher unchanged. + pub fn bypasses_host(&self, host: &str) -> bool { + let host = host.trim_start_matches('[').trim_end_matches(']'); + if host.eq_ignore_ascii_case("localhost") + || host + .parse::() + .is_ok_and(|ip| ip.is_loopback()) + { + return true; + } + + self.no_proxy.as_deref().is_some_and(|list| { + list.split(',').map(str::trim).any(|pattern| { + if pattern.eq_ignore_ascii_case("") { + // Windows defines as a hostname without a dot, + // not all addresses and not arbitrary private IP ranges. + !host.contains('.') && !host.contains(':') + } else { + !pattern.is_empty() && wildcard_matches(pattern, host) + } + }) + }) + } +} + +/// Case-insensitive host matching with Windows `*` wildcards. Literal entries +/// stay exact: `corp.example` must not also bypass `api.corp.example`. +fn wildcard_matches(pattern: &str, host: &str) -> bool { + let pattern = pattern.as_bytes(); + let host = host.as_bytes(); + let (mut p, mut h) = (0, 0); + let mut star = None; + let mut retry = 0; + + while h < host.len() { + if p < pattern.len() && pattern[p] == b'*' { + star = Some(p); + p += 1; + retry = h; + } else if p < pattern.len() && pattern[p].eq_ignore_ascii_case(&host[h]) { + p += 1; + h += 1; + } else if let Some(position) = star { + retry += 1; + h = retry; + p = position + 1; + } else { + return false; + } + } + + while p < pattern.len() && pattern[p] == b'*' { + p += 1; + } + p == pattern.len() +} + /// Hosts that must never be sent through a system proxy. /// /// Local model servers (Ollama, LM Studio, llama.cpp) bind to loopback and a @@ -83,31 +143,22 @@ fn with_scheme(value: &str) -> String { } } -/// Convert a registry `ProxyOverride` value into `reqwest::NoProxy` syntax. +/// Normalize a registry `ProxyOverride` list without changing its semantics. /// /// `` means "bypass plain hostnames"; entries are separated by `;` and -/// may use `*` wildcards, which reqwest understands. +/// may use `*` wildcards. Keep `` intact for the host matcher. #[cfg(any(windows, test))] fn parse_proxy_override(raw: &str) -> Option { let mut entries: Vec = Vec::new(); - let mut bypass_plain_hostnames = false; for entry in raw.split(';') { let entry = entry.trim(); if entry.is_empty() { continue; } - if entry.eq_ignore_ascii_case("") { - bypass_plain_hostnames = true; - continue; - } entries.push(entry.to_string()); } - if bypass_plain_hostnames && !entries.iter().any(|entry| entry == "*") { - entries.push("*".to_string()); - } - (!entries.is_empty()).then(|| entries.join(",")) } @@ -194,7 +245,7 @@ mod windows_registry { #[cfg(test)] mod tests { - use super::{merged_no_proxy, parse_proxy_override, parse_proxy_server}; + use super::{merged_no_proxy, parse_proxy_override, parse_proxy_server, SystemProxy}; #[test] fn bare_host_and_port_gets_a_scheme() { @@ -239,11 +290,11 @@ mod tests { } #[test] - fn override_list_translates_local_marker() { - assert_eq!(parse_proxy_override("").as_deref(), Some("*")); + fn override_list_preserves_local_marker() { + assert_eq!(parse_proxy_override("").as_deref(), Some("")); assert_eq!( parse_proxy_override(";*.corp.example").as_deref(), - Some("*.corp.example,*") + Some(",*.corp.example") ); assert_eq!(parse_proxy_override(" "), None); } @@ -259,4 +310,71 @@ mod tests { Some("localhost,127.0.0.1,::1,*.corp") ); } + + fn proxy_with_overrides(raw: &str) -> SystemProxy { + SystemProxy { + url: "http://127.0.0.1:7897".into(), + no_proxy: merged_no_proxy(parse_proxy_override(raw)), + } + } + + #[test] + fn windows_wildcards_match_hosts_without_broadening_literal_entries() { + let proxy = proxy_with_overrides("*.corp.example;10.*;exact.internal;build-*-api.*"); + for host in [ + "model.corp.example", + "nested.model.CORP.EXAMPLE", + "10.23.45.67", + "EXACT.internal", + "build-one-api.internal", + ] { + assert!(proxy.bypasses_host(host), "should bypass {host}"); + } + for host in [ + "corp.example", + "model.corp.example.attacker.test", + "notcorp.example", + "110.23.45.67", + "child.exact.internal", + "build-one-web.internal", + "public.example", + ] { + assert!(!proxy.bypasses_host(host), "must proxy {host}"); + } + } + + #[test] + fn local_marker_only_bypasses_plain_hostnames() { + let proxy = proxy_with_overrides(";*.corp.example"); + for host in ["intranet", "model.corp.example"] { + assert!(proxy.bypasses_host(host)); + } + for host in [ + "public.example", + "other.internal", + "10.23.45.67", + "[fd00::1]", + ] { + assert!(!proxy.bypasses_host(host), "must proxy {host}"); + } + } + + #[test] + fn explicit_star_bypasses_all_hosts_but_empty_list_only_bypasses_loopback() { + let empty = proxy_with_overrides(" ; "); + for host in [ + "localhost", + "LOCALHOST", + "127.0.0.1", + "127.0.0.2", + "::1", + "[::1]", + ] { + assert!(empty.bypasses_host(host), "should bypass {host}"); + } + for host in ["public.example", "intranet", "192.168.1.2", "[fd00::1]"] { + assert!(!empty.bypasses_host(host)); + assert!(proxy_with_overrides("*").bypasses_host(host)); + } + } }