Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

Bypass proxy env vars for loopback XERJ node clients (#2381)

xerj-org9625d7c8b19a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e23a41daa..4ef5f93a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -43,6 +43,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- MCP calls to a loopback node (`127.0.0.1`, `localhost`, `::1`) no longer
+ follow `ALL_PROXY`, `HTTP_PROXY`, or `HTTPS_PROXY`. reqwest sends those
+ addresses through the proxy unless the client opts out, so a socks or HTTP
+ proxy in the environment answered HTTP 503 while the node was healthy and
+ `curl --noproxy` reached it. `xerj autoindex`, `xerj search`, `xerj def`,
+ and the other commands that share the node HTTP client skip the proxy for
+ the same hosts. A non-loopback URL still uses the process proxy, including
+ `NO_PROXY`. When a proxy is used and returns HTTP 502, 503, or 504, or the
+ connection to it fails, the tool error names the proxy (`request to …
+ went through proxy http://…, which returned HTTP 503`) instead of
+ `XERJ returned HTTP 503`
+ ([#2379](https://github.com/xerj-org/xerj/issues/2379)).
+
- `xerj mcp`: `xerj_code_search` now gives up on a node that does not
answer. Its requests went through a fresh HTTP client without the 30 s
deadline every other tool uses, so a node that accepted the connection
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index 45e6283c8..da00ba696 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -7690,6 +7690,8 @@ version = "1.0.0-rc.99"
dependencies = [
"anyhow",
"axum",
+ "http 1.4.0",
+ "hyper-util",
"reqwest",
"serde_json",
"tempfile",
diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rs
index c0b4ff57e..89b896999 100644
--- a/engine/crates/xerj-autoindex/src/esclient.rs
+++ b/engine/crates/xerj-autoindex/src/esclient.rs
@@ -1188,6 +1188,23 @@ fn with_single_wal_shard(body: &Value) -> Value {
body
}
+/// HTTP client for one XERJ node.
+///
+/// A loopback URL (`127.0.0.1`, `localhost`, `::1`, `0.0.0.0` — the same
+/// hosts as [`xerj_common::localauth::url_is_loopback`]) skips
+/// `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY`. reqwest would otherwise send
+/// `127.0.0.1` through them, and a proxy that cannot reach loopback answers
+/// HTTP 503 while the node is up (#2379). A non-loopback URL keeps those
+/// variables, including `NO_PROXY`.
+pub(crate) fn node_blocking_builder(url: &str) -> reqwest::blocking::ClientBuilder {
+ let builder = reqwest::blocking::Client::builder();
+ if xerj_common::localauth::url_is_loopback(url) {
+ builder.no_proxy()
+ } else {
+ builder
+ }
+}
+
impl Es {
pub fn new(url: &str, api_key: Option<String>) -> Result<Self> {
Self::with_bulk_timeout(url, api_key, 300)
@@ -1214,7 +1231,9 @@ impl Es {
retry_initial_delay: Duration,
retry_max_delay: Duration,
) -> Result<Self> {
- let http = reqwest::blocking::Client::builder()
+ // Loopback skips HTTP(S)_PROXY / ALL_PROXY (#2379). A non-loopback
+ // URL keeps them, including NO_PROXY. Same rule as `xerj mcp`.
+ let http = node_blocking_builder(url)
.timeout(Duration::from_secs(300))
.danger_accept_invalid_certs(true)
.build()
diff --git a/engine/crates/xerj-autoindex/src/xc.rs b/engine/crates/xerj-autoindex/src/xc.rs
index 1c141af8b..c47644b52 100644
--- a/engine/crates/xerj-autoindex/src/xc.rs
+++ b/engine/crates/xerj-autoindex/src/xc.rs
@@ -219,7 +219,7 @@ fn prefixes_from_catalog_hits(v: &Value) -> Option<Vec<String>> {
/// One catalog read. `None` on any failure, including a node that is not
/// there: callers print nothing in that case.
fn fetch_catalog_run_prefixes(url: &str, explicit_key: Option<&str>) -> Option<Vec<String>> {
- let http = reqwest::blocking::Client::builder()
+ let http = crate::esclient::node_blocking_builder(url)
.connect_timeout(CATALOG_HINT_CONNECT)
.timeout(CATALOG_HINT_TIMEOUT)
.danger_accept_invalid_certs(true)
diff --git a/engine/crates/xerj-engine/tests/node_lock.rs b/engine/crates/xerj-engine/tests/node_lock.rs
index 4a53909de..461d244bd 100644
--- a/engine/crates/xerj-engine/tests/node_lock.rs
+++ b/engine/crates/xerj-engine/tests/node_lock.rs
@@ -8,6 +8,8 @@
//! `<data_dir>/node.lock` before any index open / WAL replay, and fails
//! fast with the holder's pid.
+use std::sync::{Mutex, OnceLock};
+
use tempfile::TempDir;
use xerj_common::config::Config;
use xerj_engine::Engine;
@@ -18,8 +20,19 @@ fn config_for(dir: &TempDir) -> Config {
config
}
+/// `Engine::new` installs process-wide governor and pool state, and the
+/// stale-lock test rebuilds the tracing interest cache. The two tests in
+/// this binary have to take turns.
+fn serialize_tests() -> std::sync::MutexGuard<'static, ()> {
+ static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+ LOCK.get_or_init(|| Mutex::new(()))
+ .lock()
+ .unwrap_or_else(|poison| poison.into_inner())
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn second_engine_on_same_data_dir_fails_fast_with_holder_pid() {
+ let _guard = serialize_tests();
let dir = TempDir::new().unwrap();
let engine = Engine::new(config_for(&dir)).expect("first engine must boot");
@@ -41,20 +54,67 @@ async fn second_engine_on_same_data_dir_fails_fast_with_holder_pid() {
// Dropping the holder releases the OS lock; the stale node.lock FILE
// left behind (as after kill -9) must never block the next boot.
drop(engine);
- let reopened = Engine::new(config_for(&dir));
+ let reopened = reopen_after_drop(&dir);
assert!(
reopened.is_ok(),
- "reopen after the holder exits must succeed: {:?}",
- reopened.err()
+ "reopen after the holder exits must succeed: {:?} (open node.lock fds: {})",
+ reopened.err(),
+ node_lock_fds()
);
}
+/// The OS lock is released when the holder's file is closed. Full-workspace
+/// CI has still observed `WouldBlock` from this process immediately after
+/// `drop` (this branch's run 40152941822, and `main` run 40145228672) and
+/// a pass of the same test on run 40148648744. Wait briefly for that close
+/// to become visible. A lock that stays held still fails.
+fn reopen_after_drop(dir: &TempDir) -> Result<Engine, xerj_engine::EngineError> {
+ let mut last = Engine::new(config_for(dir));
+ for _ in 0..20 {
+ if last.is_ok() {
+ return last;
+ }
+ let still_ours = last
+ .as_ref()
+ .err()
+ .map(|err| err.to_string())
+ .is_some_and(|text| text.contains("already in use") && text.contains("node.lock"));
+ if !still_ours {
+ return last;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ last = Engine::new(config_for(dir));
+ }
+ last
+}
+
+fn node_lock_fds() -> String {
+ let Ok(dir) = std::fs::read_dir("/proc/self/fd") else {
+ return "unavailable".to_string();
+ };
+ let mut hits = Vec::new();
+ for entry in dir.flatten() {
+ if let Ok(target) = std::fs::read_link(entry.path()) {
+ let text = target.to_string_lossy();
+ if text.contains("node.lock") {
+ hits.push(text.into_owned());
+ }
+ }
+ }
+ if hits.is_empty() {
+ "none".to_string()
+ } else {
+ hits.join(", ")
+ }
+}
+
/// A `node.lock` left by a process that has exited must not block the next
/// boot, and the reclaim is logged. This is the file `kill -9` leaves once
/// the kernel has dropped `flock`, and the file a crashed Windows process
/// leaves behind when `LockFileEx` does not.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stale_node_lock_from_a_dead_pid_is_reclaimed_on_start() {
+ let _guard = serialize_tests();
let dir = TempDir::new().unwrap();
let dead = reaped_pid();
std::fs::write(dir.path().join("node.lock"), format!("{dead}\n")).unwrap();
diff --git a/engine/crates/xerj-hub/src/node.rs b/engine/crates/xerj-hub/src/node.rs
index e59254b40..6b2ec9ff7 100644
--- a/engine/crates/xerj-hub/src/node.rs
+++ b/engine/crates/xerj-hub/src/node.rs
@@ -77,7 +77,8 @@ pub fn resolve_url(explicit: Option<&str>) -> String {
/// probe to the proxy, and the proxy's own `502 Bad Gateway` page then reads as
/// "an HTTP answer, so a node is running" — the hub would decline to start the
/// node it needs, or talk to a proxy believing it is one. A remote `--url` keeps
-/// the system proxy settings.
+/// the system proxy settings. `xerj mcp` and the autoindex node client use the
+/// same loopback bypass (#2379).
fn client_builder(url: &str) -> reqwest::blocking::ClientBuilder {
let builder = reqwest::blocking::Client::builder();
if url_is_loopback(url) {
diff --git a/engine/crates/xerj-mcp/Cargo.toml b/engine/crates/xerj-mcp/Cargo.toml
index e32089d8a..2c587fd59 100644
--- a/engine/crates/xerj-mcp/Cargo.toml
+++ b/engine/crates/xerj-mcp/Cargo.toml
@@ -25,6 +25,11 @@ tokio = { workspace = true }
# Inherits the workspace's default-features=false + rustls-tls config, so it
# builds in the same offline/cross-compile matrix as the rest of the tree.
reqwest = { workspace = true }
+# Same proxy matcher reqwest consults (`HTTP(S)_PROXY`, `ALL_PROXY`, `NO_PROXY`).
+# Used to name the proxy in a failure. The client still lets reqwest apply it.
+# Loopback targets never reach this: they are built with `no_proxy()` (#2379).
+hyper-util = { version = "0.1.20", default-features = false, features = ["client-proxy"] }
+http = "1"
# All request/response bodies are handled as untyped JSON `Value`s — no
# bespoke serde structs, which keeps the wire contract identical to what the
# engine already accepts.
diff --git a/engine/crates/xerj-mcp/src/batch.rs b/engine/crates/xerj-mcp/src/batch.rs
index 21041f570..4e2322df5 100644
--- a/engine/crates/xerj-mcp/src/batch.rs
+++ b/engine/crates/xerj-mcp/src/batch.rs
@@ -282,15 +282,19 @@ fn item_result(
}
async fn msearch(ctx: &Ctx, ndjson: String) -> Result<Vec<Value>, String> {
+ let url = format!("{}/_msearch", ctx.base_url);
let mut req = ctx
.client
- .post(format!("{}/_msearch", ctx.base_url))
+ .post(&url)
.header("Content-Type", "application/x-ndjson")
.body(ndjson);
if let Some(auth) = &ctx.auth {
req = req.header("Authorization", auth);
}
- let mut resp = req.send().await.map_err(|e| crate::error_detail(&e))?;
+ let mut resp = req
+ .send()
+ .await
+ .map_err(|e| crate::transport_failure_text(&ctx.base_url, &url, &e))?;
let status = resp.status();
let mut bytes = Vec::new();
while let Some(chunk) = resp.chunk().await.map_err(|e| crate::error_detail(&e))? {
@@ -300,10 +304,13 @@ async fn msearch(ctx: &Ctx, ndjson: String) -> Result<Vec<Value>, String> {
bytes.extend_from_slice(&chunk);
}
if !status.is_success() {
- return Err(format!(
- "batch endpoint returned HTTP {status}: {}",
- String::from_utf8_lossy(&bytes)
- ));
+ let body = String::from_utf8_lossy(&bytes);
+ if let Some(proxied) =
+ crate::proxy_status_failure(&ctx.base_url, &url, status.as_u16(), &body)
+ {
+ return Err(proxied);
+ }
+ return Err(format!("batch endpoint returned HTTP {status}: {body}"));
}
let response: Value =
serde_json::from_slice(&bytes).map_err(|_| "batch endpoint returned invalid JSON")?;
diff --git a/engine/crates/xerj-mcp/src/batch_cli.rs b/engine/crates/xerj-mcp/src/batch_cli.rs
index 1c34f3308..c2c2bd050 100644
--- a/engine/crates/xerj-mcp/src/batch_cli.rs
+++ b/engine/crates/xerj-mcp/src/batch_cli.rs
@@ -2,7 +2,7 @@
use std::io::Read;
use std::time::Duration;
-use crate::{batch, resolve_auth, Ctx, DEFAULT_XERJ_URL};
+use crate::{batch, node_http_builder, resolve_auth, Ctx, DEFAULT_XERJ_URL};
const HELP: &str = "xerj batch-search — ordered batch retrieval (#1801)
@@ -124,7 +124,7 @@ pub async fn run_batch_cli(args: &[String]) -> i32 {
path.display()
);
}
- let client = match reqwest::Client::builder()
+ let client = match node_http_builder(&base_url)
.timeout(Duration::from_secs(30))
.build()
{
diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rs
index b41096283..59136b6d5 100644
--- a/engine/crates/xerj-mcp/src/lib.rs
+++ b/engine/crates/xerj-mcp/src/lib.rs
@@ -370,7 +370,7 @@ pub async fn run(args: &[String]) -> anyhow::Result<()> {
let (auth, auth_key_file) =
resolve_auth(auth_override, std::env::var("XERJ_AUTH").ok(), &base_url);
- let client = reqwest::Client::builder()
+ let client = node_http_builder(&base_url)
.timeout(REQUEST_TIMEOUT)
.build()?;
@@ -493,9 +493,14 @@ pub async fn handle_message_for_test(
auth: Option<String>,
msg: Value,
) -> Option<Value> {
+ let base_url = base_url.trim_end_matches('/').to_string();
+ let client = node_http_builder(&base_url)
+ .timeout(Duration::from_secs(30))
+ .build()
+ .expect("build HTTP client");
let ctx = Ctx {
- client: reqwest::Client::new(),
- base_url: base_url.trim_end_matches('/').to_string(),
+ client,
+ base_url,
auth,
};
handle_message(&ctx, msg).await
@@ -2725,12 +2730,13 @@ impl McpXc {
.build()
.map_err(|e| format!("runtime: {e}"))?;
let url = format!("{}{}", self.base_url, path);
+ let base_url = self.base_url.clone();
let auth = self.auth.clone();
let timeout = self.timeout;
let method = method.to_string();
let body = body.cloned();
rt.block_on(async move {
- let client = reqwest::Client::builder()
+ let client = node_http_builder(&base_url)
.timeout(timeout)
.build()
.map_err(|e| format!("http client: {e}"))?;
@@ -2746,7 +2752,7 @@ impl McpXc {
let resp = req
.send()
.await
- .map_err(|e| format!("no response from {url}: {e}"))?;
+ .map_err(|e| mcp_xc_send_error(&base_url, &url, &e))?;
// Surface the status WITH the body: the tri-state callers (404 =
// zero, not error) classify it themselves.
let status = resp.status().as_u16();
@@ -2755,7 +2761,8 @@ impl McpXc {
match status {
200..=299 => Ok(v),
404 => Err("__404__".to_string()),
- other => Err(format!("HTTP {other}: {v}")),
+ other => Err(proxy_status_failure(&base_url, &url, other, &v.to_string())
+ .unwrap_or_else(|| format!("HTTP {other}: {v}"))),
}
})
}
@@ -3068,17 +3075,110 @@ async fn fetch_mapping(ctx: &Ctx, index: &str) -> Option<Value> {
resp.json::<Value>().await.ok()
}
+/// HTTP client for the XERJ node at `base_url`.
+///
+/// A loopback node (`127.0.0.1`, `localhost`, `::1`, and `0.0.0.0` — the
+/// same hosts [`xerj_common::localauth::url_is_loopback`] already treats as
+/// this machine) is never reached through `HTTP_PROXY`, `HTTPS_PROXY`, or
+/// `ALL_PROXY`. reqwest honours those for `127.0.0.1` unless told not to,
+/// and a proxy that cannot connect to loopback answers HTTP 503 while the
+/// node is healthy (#2379). A non-loopback URL keeps the process proxy
+/// settings, including `NO_PROXY`.
+pub(crate) fn node_http_builder(base_url: &str) -> reqwest::ClientBuilder {
+ let builder = reqwest::Client::builder();
+ if xerj_common::localauth::url_is_loopback(base_url) {
+ builder.no_proxy()
+ } else {
+ builder
+ }
+}
+
+/// Proxy reqwest will use for `base_url`, with userinfo removed.
+///
+/// `None` for loopback (the client is built with [`node_http_builder`], which
+/// disables proxies) and when `NO_PROXY` excludes the host. This is
+/// `hyper_util`'s env matcher, the one reqwest installs — scheme-specific
+/// `HTTP_PROXY` / `HTTPS_PROXY` win over `ALL_PROXY`.
+fn env_proxy_label(base_url: &str) -> Option<String> {
+ if xerj_common::localauth::url_is_loopback(base_url) {
+ return None;
+ }
+ let uri = base_url.parse::<http::Uri>().ok()?;
+ let intercept = hyper_util::client::proxy::matcher::Matcher::from_env().intercept(&uri)?;
+ Some(redact_proxy(intercept.uri()))
+}
+
+/// `http://proxy:8080`, never `http://user:secret@proxy:8080`.
+fn redact_proxy(uri: &http::Uri) -> String {
+ let scheme = uri.scheme_str().unwrap_or("http");
+ let Some(authority) = uri.authority() else {
+ return uri.to_string();
+ };
+ let host_port = authority
+ .as_str()
+ .rsplit_once('@')
+ .map(|(_, host)| host)
+ .unwrap_or(authority.as_str());
+ format!("{scheme}://{host_port}")
+}
+
+/// `Some` when this status arrived through an env proxy and is one a proxy
+/// generates when it cannot reach the upstream (502, 503, 504). The text
+/// names the proxy. A 401 or 400 stays the node's own sentence.
+pub(crate) fn proxy_status_failure(
+ base_url: &str,
+ request_url: &str,
+ status: u16,
+ body: &str,
+) -> Option<String> {
+ if !matches!(status, 502..=504) {
+ return None;
+ }
+ let proxy = env_proxy_label(base_url)?;
+ Some(proxy_gateway_message(request_url, &proxy, status, body))
+}
+
+fn proxy_gateway_message(request_url: &str, proxy: &str, status: u16, body: &str) -> String {
+ format!(
+ "request to {request_url} went through proxy {proxy}, which returned HTTP {status}: {body}"
+ )
+}
+
/// Tool text for a proxy request that never got an HTTP response.
///
/// A connect failure means nothing accepted a connection at `XERJ_URL`
/// (#2079). The raw client error does not say so, and agents then drop xerj
/// for the session. HTTP statuses never reach here: a 401 is a response and
/// stays `XERJ returned HTTP 401: …`.
+///
+/// A failure that went through an env proxy names that proxy instead (#2379).
+/// Connection refused on the proxy is not "no node is listening".
+/// `McpXc` keeps the "no response" wording `xerj_code_search` tests for when
+/// the node accepts and then stays silent. A refused connect still goes
+/// through [`transport_failure_text`], so a dead proxy is not reported as a
+/// dead node.
+fn mcp_xc_send_error(base_url: &str, request_url: &str, err: &reqwest::Error) -> String {
+ if err.is_timeout() {
+ let detail = error_detail(err);
+ return match env_proxy_label(base_url) {
+ Some(proxy) => format!("no response from {request_url} via proxy {proxy}: {detail}"),
+ None => format!("no response from {request_url}: {detail}"),
+ };
+ }
+ transport_failure_text(base_url, request_url, err)
+}
+
pub(crate) fn transport_failure_text(
base_url: &str,
request_url: &str,
err: &reqwest::Error,
) -> String {
+ if let Some(proxy) = env_proxy_label(base_url) {
+ return format!(
+ "request to {request_url} failed via proxy {proxy}: {}",
+ error_detail(err)
+ );
+ }
if node_unreachable(err) {
node_not_listening(base_url, &error_detail(err))
} else {
@@ -3301,9 +3401,17 @@ async fn engine_request(
} else if is_memory_store_path(path) {
if let Some(explained) = memory_flood_tool_text(ctx, &text).await {
tool_text(explained, true)
+ } else if let Some(proxied) =
+ proxy_status_failure(&ctx.base_url, &url, status.as_u16(), &text)
+ {
+ tool_text(proxied, true)
} else {
tool_text(format!("XERJ returned HTTP {status}: {text}"), true)
}
+ } else if let Some(proxied) =
+ proxy_status_failure(&ctx.base_url, &url, status.as_u16(), &text)
+ {
+ tool_text(proxied, true)
} else {
tool_text(format!("XERJ returned HTTP {status}: {text}"), true)
}
@@ -3325,6 +3433,35 @@ mod tests {
(m, p, b.expect("builder should carry a body"))
}
+ /// #2379: a proxy 503 names the proxy. A node 400 does not, because that
+ /// status is not one a proxy synthesises on the way to the upstream.
+ #[test]
+ fn proxy_status_failure_names_the_proxy_only_for_gateway_statuses() {
+ let url = "http://node.example:9200/docs/_search";
+ let proxy = "http://proxy.internal:8888";
+ let msg = proxy_gateway_message(url, proxy, 503, "upstream");
+ // The env matcher is covered by tests/loopback_proxy.rs. This pins
+ // the sentence, and that a loopback target and a node 400 are not
+ // rewritten into it.
+ assert!(msg.contains(proxy), "{msg}");
+ assert!(msg.contains("HTTP 503"), "{msg}");
+ assert!(msg.contains("went through proxy"), "{msg}");
+ assert!(!msg.contains("XERJ returned"), "{msg}");
+ assert!(proxy_status_failure("http://127.0.0.1:9200", url, 503, "x").is_none());
+ assert!(proxy_status_failure("http://node.example:9200", url, 400, "nope").is_none());
+ }
+
+ #[test]
+ fn proxy_label_drops_userinfo() {
+ let uri: http::Uri = "http://user:[email protected]:8888".parse().unwrap();
+ let label = redact_proxy(&uri);
+ assert_eq!(label, "http://proxy.internal:8888");
+ assert!(!label.contains("secret"), "{label}");
+ assert!(!label.contains("user"), "{label}");
+ let socks: http::Uri = "socks5://127.0.0.1:1080".parse().unwrap();
+ assert_eq!(redact_proxy(&socks), "socks5://127.0.0.1:1080");
+ }
+
/// `xerj_code_search` talks to the node through `McpXc`, not `Ctx.client`,
/// so it needs a deadline of its own: a node that accepts the connection
/// and never answers must give an error, not hang the tool call (and with
diff --git a/engine/crates/xerj-mcp/src/map.rs b/engine/crates/xerj-mcp/src/map.rs
index e574817c2..5f1927b55 100644
--- a/engine/crates/xerj-mcp/src/map.rs
+++ b/engine/crates/xerj-mcp/src/map.rs
@@ -860,6 +860,10 @@ pub(crate) async fn run(ctx: &Ctx, args: &Value) -> Value {
),
true,
)
+ } else if let Some(proxied) =
+ crate::proxy_status_failure(&ctx.base_url, &url, status.as_u16(), &text)
+ {
+ tool_text(proxied, true)
} else {
tool_text(
format!("XERJ returned HTTP {status} from {CATALOG_INDEX}: {text}"),
diff --git a/engine/crates/xerj-mcp/tests/loopback_proxy.rs b/engine/crates/xerj-mcp/tests/loopback_proxy.rs
new file mode 100644
index 000000000..15a9ec600
--- /dev/null
+++ b/engine/crates/xerj-mcp/tests/loopback_proxy.rs
@@ -0,0 +1,267 @@
+//! Loopback MCP calls ignore `ALL_PROXY` / `HTTP_PROXY` / `HTTPS_PROXY` (#2379).
+//!
+//! reqwest honours those variables for `127.0.0.1`. A socks or HTTP proxy then
+//! answers 503 (or refuses the connection) while the node is healthy, and the
+//! tool used to report that as `XERJ returned HTTP 503`. `curl --noproxy`
+//! reached the same node.
+//!
+//! This is its own test binary because the proxy variables are process-global:
+//! set inside the library tests they would redirect every other HTTP client.
+
+use std::io::{Read, Write};
+use std::net::TcpListener;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use serde_json::{json, Value};
+
+const PROXY_VARS: &[&str] = &[
+ "ALL_PROXY",
+ "all_proxy",
+ "HTTP_PROXY",
+ "http_proxy",
+ "HTTPS_PROXY",
+ "https_proxy",
+ "NO_PROXY",
+ "no_proxy",
+];
+
+struct EnvGuard(Vec<(String, Option<std::ffi::OsString>)>);
+
+impl EnvGuard {
+ fn capture() -> Self {
+ let saved = PROXY_VARS
+ .iter()
+ .map(|key| ((*key).to_string(), std::env::var_os(key)))
+ .collect();
+ Self(saved)
+ }
+}
+
+impl Drop for EnvGuard {
+ fn drop(&mut self) {
+ for key in PROXY_VARS {
+ std::env::remove_var(key);
+ }
+ for (key, value) in &self.0 {
+ if let Some(value) = value {
+ std::env::set_var(key, value);
+ }
+ }
+ }
+}
+
+fn clear_proxy_env() {
+ for key in PROXY_VARS {
+ std::env::remove_var(key);
+ }
+}
+
+fn set_proxy(value: &str) {
+ clear_proxy_env();
+ for key in [
+ "ALL_PROXY",
+ "all_proxy",
+ "HTTP_PROXY",
+ "http_proxy",
+ "HTTPS_PROXY",
+ "https_proxy",
+ ] {
+ std::env::set_var(key, value);
+ }
+}
+
+/// A server on an ephemeral port that answers every request with `status`/`body`
+/// and counts the requests it received. `bind` is `127.0.0.1:0` or `[::1]:0`.
+/// `None` when that address family is not available.
+fn serve(
+ bind: &str,
+ status: &'static str,
+ body: &'static str,
+ hits: Arc<AtomicUsize>,
+) -> Option<u16> {
+ let listener = TcpListener::bind(bind).ok()?;
+ let port = listener.local_addr().ok()?.port();
+ std::thread::spawn(move || {
+ for conn in listener.incoming() {
+ let Ok(mut conn) = conn else { continue };
+ let hits = hits.clone();
+ std::thread::spawn(move || {
+ let mut buf = [0u8; 8192];
+ if conn.read(&mut buf).unwrap_or(0) == 0 {
+ return;
+ }
+ hits.fetch_add(1, Ordering::SeqCst);
+ let reply = format!(
+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = conn.write_all(reply.as_bytes());
+ });
+ }
+ });
+ Some(port)
+}
+
+fn closed_port() -> u16 {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ port
+}
+
+fn search_call() -> Value {
+ json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": {
+ "name": "xerj_search",
+ "arguments": { "index": "docs", "query": { "match_all": {} } }
+ }
+ })
+}
+
+fn map_call() -> Value {
+ json!({
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": { "name": "xerj_map", "arguments": {} }
+ })
+}
+
+async fn tool(url: &str, msg: Value) -> (bool, String) {
+ let resp = xerj_mcp::handle_message_for_test(url, None, msg)
+ .await
+ .expect("tools/call returns a response");
+ let is_error = resp["result"]["isError"].as_bool().unwrap();
+ let text = resp["result"]["content"][0]["text"]
+ .as_str()
+ .unwrap_or("")
+ .to_string();
+ (is_error, text)
+}
+
+#[tokio::test]
+async fn loopback_ignores_an_unreachable_proxy_and_a_proxied_503_names_the_proxy() {
+ let _guard = EnvGuard::capture();
+
+ let node_hits = Arc::new(AtomicUsize::new(0));
+ let node_body = r#"{"took":1,"hits":{"total":{"value":0,"relation":"eq"},"hits":[]}}"#;
+ let node_port =
+ serve("127.0.0.1:0", "200 OK", node_body, node_hits.clone()).expect("bind 127.0.0.1");
+ let v6_port = serve("[::1]:0", "200 OK", node_body, node_hits.clone());
+
+ // Phase 1: ALL_PROXY is an unreachable socks5 proxy, and the HTTP(S) proxy
+ // variables point at a closed port. A loopback tool call still succeeds.
+ let closed = closed_port();
+ set_proxy(&format!("socks5://127.0.0.1:{closed}"));
+ std::env::set_var("HTTP_PROXY", format!("http://127.0.0.1:{closed}"));
+ std::env::set_var("http_proxy", format!("http://127.0.0.1:{closed}"));
+ std::env::set_var("HTTPS_PROXY", format!("http://127.0.0.1:{closed}"));
+ std::env::set_var("https_proxy", format!("http://127.0.0.1:{closed}"));
+
+ let node = format!("http://127.0.0.1:{node_port}");
+ let (err, text) = tool(&node, search_call()).await;
+ assert!(!err, "loopback search went through the proxy: {text}");
+ let (err, text) = tool(&node, map_call()).await;
+ assert!(!err, "loopback map went through the proxy: {text}");
+ assert!(
+ node_hits.load(Ordering::SeqCst) >= 2,
+ "the node itself must have answered"
+ );
+ if let Some(port) = v6_port {
+ let (err, text) = tool(&format!("http://[::1]:{port}"), search_call()).await;
+ assert!(!err, "::1 search went through the proxy: {text}");
+ }
+
+ // Phase 2: a live HTTP proxy returns 503. Loopback still skips it. A
+ // non-loopback host is sent there, and the tool error names the proxy
+ // instead of `XERJ returned HTTP 503`.
+ let proxy_hits = Arc::new(AtomicUsize::new(0));
+ let proxy_port = serve(
+ "127.0.0.1:0",
+ "503 Service Unavailable",
+ r#"{"error":"bad gateway from the corporate proxy"}"#,
+ proxy_hits.clone(),
+ )
+ .expect("bind proxy");
+ let proxy_url = format!("http://127.0.0.1:{proxy_port}");
+ set_proxy(&proxy_url);
+
+ let before = node_hits.load(Ordering::SeqCst);
+ let (err, text) = tool(&node, search_call()).await;
+ assert!(!err, "loopback search used the live proxy: {text}");
+ let (err, text) = tool(&node, map_call()).await;
+ assert!(!err, "loopback map used the live proxy: {text}");
+ assert!(node_hits.load(Ordering::SeqCst) > before);
+ assert_eq!(
+ proxy_hits.load(Ordering::SeqCst),
+ 0,
+ "the proxy must not see a loopback node"
+ );
+
+ // 127.0.0.2 is this machine's loopback range, but it is not one of the
+ // hosts `url_is_loopback` treats as the local node, so the proxy applies.
+ let remote = "http://127.0.0.2:9";
+ let (err, text) = tool(remote, search_call()).await;
+ assert!(err, "{text}");
+ assert!(
+ text.contains(&proxy_url),
+ "the 503 must name the proxy: {text}"
+ );
+ assert!(text.contains("HTTP 503"), "{text}");
+ assert!(text.contains("went through proxy"), "{text}");
+ assert!(
+ !text.contains("XERJ returned HTTP"),
+ "a proxy 503 is not the node's status: {text}"
+ );
+ let (err, text) = tool(remote, map_call()).await;
+ assert!(err, "{text}");
+ assert!(text.contains(&proxy_url), "{text}");
+ assert!(text.contains("went through proxy"), "{text}");
+ assert!(
+ proxy_hits.load(Ordering::SeqCst) >= 2,
+ "the non-loopback calls must have reached the proxy"
+ );
+
+ // Phase 3: NO_PROXY still excludes a non-loopback host. The closed port
+ // refuses immediately, and the error is the node-down sentence, not the proxy.
+ let proxy_before = proxy_hits.load(Ordering::SeqCst);
+ std::env::set_var("NO_PROXY", "127.0.0.2");
+ std::env::set_var("no_proxy", "127.0.0.2");
+ let (err, text) = tool(remote, search_call()).await;
+ assert!(err, "{text}");
+ assert!(
+ !text.contains("went through proxy"),
+ "NO_PROXY must bypass the proxy: {text}"
+ );
+ assert!(
+ text.contains("no XERJ node is listening") || text.contains("Connection refused"),
+ "{text}"
+ );
+ assert_eq!(
+ proxy_hits.load(Ordering::SeqCst),
+ proxy_before,
+ "NO_PROXY must not contact the proxy"
+ );
+
+ // Phase 4: a proxy that is not listening is named on the transport error,
+ // rather than reported as the node being down.
+ clear_proxy_env();
+ let dead = closed_port();
+ let dead_url = format!("http://127.0.0.1:{dead}");
+ set_proxy(&dead_url);
+ let (err, text) = tool(remote, search_call()).await;
+ assert!(err, "{text}");
+ assert!(
+ text.contains(&dead_url),
+ "a refused proxy connection must name the proxy: {text}"
+ );
+ assert!(text.contains("via proxy"), "{text}");
+ assert!(
+ !text.contains("no XERJ node is listening"),
+ "the node was not the thing that refused: {text}"
+ );
+}
diff --git a/engine/crates/xerj-rerank/tests/egress_inventory.rs b/engine/crates/xerj-rerank/tests/egress_inventory.rs
index 7a7f3a2b2..c2eb131b5 100644
--- a/engine/crates/xerj-rerank/tests/egress_inventory.rs
+++ b/engine/crates/xerj-rerank/tests/egress_inventory.rs
@@ -34,6 +34,12 @@ const MARKERS: &[&str] = &[
"reqwest::blocking::Client",
"reqwest::get(",
"reqwest::blocking::get(",
+ // #2379: the local-node clients are built in `node_http_builder` /
+ // `node_blocking_builder`. Callers (`xerj mcp`, `xerj batch-search`,
+ // `xerj code`) no longer spell `reqwest::Client` themselves, and they
+ // still open that connection.
+ "node_http_builder(",
+ "node_blocking_builder(",
"hf_hub::",
"ureq::",
"TcpStream::connect",