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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(hub): gRPC XerjHub shares the HTTP rate-limit budget and honours trusted_proxies
xerj-orgb5a3994cf207
diff --git a/engine/crates/xerj-api/src/hub_api.rs b/engine/crates/xerj-api/src/hub_api.rsindex b4935abfd..906a9ef59 100644--- a/engine/crates/xerj-api/src/hub_api.rs+++ b/engine/crates/xerj-api/src/hub_api.rs@@ -1849,6 +1849,16 @@ async fn refusal(resp: Response) -> HubRefusal {}impl HubShared {+ /// Count one request from a transport that is not an axum request (the+ /// gRPC `XerjHub` service) against the same per-client budget the HTTP+ /// routes' layer draws on. The client is read exactly as there+ /// ([`crate::share::client_source`]): the TCP `peer`, or the+ /// `x-forwarded-for` values only when `peer` is a declared+ /// `server.trusted_proxies` entry.+ pub fn admit_peer(&self, peer: Option<IpAddr>, forwarded: &[&str]) -> Result<(), HubRefusal> {+ self.admit(&crate::share::client_source(&self.app, peer, forwarded))+ }+/// Count one request from `client` (an IP address, as text) against the same/// per-address budget the HTTP routes use ([`RATE_LIMIT`] per/// [`RATE_WINDOW`]); `Err` is the `429` refusal.diff --git a/engine/crates/xerj-api/src/lib.rs b/engine/crates/xerj-api/src/lib.rsindex 4e9ac1b14..1141762dd 100644--- a/engine/crates/xerj-api/src/lib.rs+++ b/engine/crates/xerj-api/src/lib.rs@@ -90,5 +90,5 @@ pub mod wal_tap_api;// ── Convenience re-exports ────────────────────────────────────────────────────pub use error::ApiError;-pub use router::{build_es_compat_router, build_native_router};+pub use router::{build_es_compat_router, build_es_compat_router_with_hub, build_native_router};pub use state::{AppState, IndexHandle, IndexSettings};diff --git a/engine/crates/xerj-api/src/router.rs b/engine/crates/xerj-api/src/router.rsindex 736382a41..f5a2264f8 100644--- a/engine/crates/xerj-api/src/router.rs+++ b/engine/crates/xerj-api/src/router.rs@@ -243,6 +243,18 @@ pub fn build_native_router(state: AppState) -> Router {/// POST /:index/_bulk bulk_ops/// ```pub fn build_es_compat_router(state: AppState) -> Router {+ let hub = hub_api::HubShared::new(state.clone());+ build_es_compat_router_with_hub(state, hub)+}++/// [`build_es_compat_router`] over a [`hub_api::HubShared`] the caller also+/// hands to the gRPC `XerjHub` service, so the two surfaces count one client+/// against ONE hub rate-limit budget (and share one query-slot pool and one+/// catalogue cache) instead of each granting the full allowance.+pub fn build_es_compat_router_with_hub(+ state: AppState,+ hub: std::sync::Arc<hub_api::HubShared>,+) -> Router {let body_limit = state.config.limits.max_body_bytes;let access_log = state.config.logging.access_log;// Build the CORS layer before `state` is moved into the auth middleware.@@ -928,8 +940,10 @@ pub fn build_es_compat_router(state: AppState) -> Router {// other route; with `hub.public = true` exactly these four skip// authentication, authorization and the audit log (the three// `*_unless_public_hub` wrappers below). The rate limit is a layer on- // the sub-router itself, so it holds in both modes.- .merge(hub_api::routes(hub_api::HubShared::new(state.clone())))+ // the sub-router itself, so it holds in both modes. `hub` is the+ // same `HubShared` the gRPC `XerjHub` service holds, so a client has+ // one budget across both listeners, not one per listener.+ .merge(hub_api::routes(hub))// ── Share links ───────────────────────────────────────────────────────// `xerj share`: hand one indexed corpus to a guest as a scoped,// read-only, expiring key. Create/list/revoke are superuser-only indiff --git a/engine/crates/xerj-api/src/share.rs b/engine/crates/xerj-api/src/share.rsindex bb0642b69..b13b5e769 100644--- a/engine/crates/xerj-api/src/share.rs+++ b/engine/crates/xerj-api/src/share.rs@@ -761,35 +761,50 @@ impl FromRequestParts<AppState> for ClaimSource {let peer = parts.extensions.get::<ConnectInfo<SocketAddr>>()- .map(|c| xerj_common::net::canonical_ip(c.0.ip()));- let Some(peer) = peer else {- return Ok(ClaimSource("unknown".to_string()));- };- let trusted = xerj_common::net::TrustedProxies::parse(&state.config.server.trusted_proxies)- .unwrap_or_else(|_| xerj_common::net::TrustedProxies::none());- if !trusted.contains(&peer) {- return Ok(ClaimSource(peer.to_string()));- }- let elements: Vec<&str> = parts+ .map(|c| c.0.ip());+ let forwarded: Vec<&str> = parts.headers.get_all("x-forwarded-for").iter().filter_map(|v| v.to_str().ok())- .flat_map(|v| v.split(',')).collect();- for element in elements.iter().rev() {- match xerj_common::net::parse_forwarded_element(element) {- Some(ip) => {- let ip: IpAddr = xerj_common::net::canonical_ip(ip);- if !trusted.contains(&ip) {- return Ok(ClaimSource(ip.to_string()));- }+ Ok(ClaimSource(client_source(state, peer, &forwarded)))+ }+}++/// The reading behind [`ClaimSource`], for a transport that is not an axum+/// request: the gRPC `XerjHub` service hands in its TCP peer and its+/// `x-forwarded-for` metadata values, so one client is one address on both+/// listeners.+///+/// `peer` is the TCP peer (`None`: every such caller shares `unknown`).+/// `forwarded` are the raw `X-Forwarded-For` values in the order received;+/// each may be a comma-separated list. They are consulted only when `peer` is+/// a declared `server.trusted_proxies` entry, walking right-to-left to the+/// first address that is not itself a declared proxy; an element that does+/// not parse stops the walk and the peer is used.+pub fn client_source(state: &AppState, peer: Option<IpAddr>, forwarded: &[&str]) -> String {+ let Some(peer) = peer.map(xerj_common::net::canonical_ip) else {+ return "unknown".to_string();+ };+ let trusted = xerj_common::net::TrustedProxies::parse(&state.config.server.trusted_proxies)+ .unwrap_or_else(|_| xerj_common::net::TrustedProxies::none());+ if !trusted.contains(&peer) {+ return peer.to_string();+ }+ let elements: Vec<&str> = forwarded.iter().flat_map(|v| v.split(',')).collect();+ for element in elements.iter().rev() {+ match xerj_common::net::parse_forwarded_element(element) {+ Some(ip) => {+ let ip: IpAddr = xerj_common::net::canonical_ip(ip);+ if !trusted.contains(&ip) {+ return ip.to_string();}- None => break,}+ None => break,}- Ok(ClaimSource(peer.to_string()))}+ peer.to_string()}// ─────────────────────────────────────────────────────────────────────────────@@ -1398,6 +1413,56 @@ fn too_many(retry_after_secs: u64) -> Response {mod tests {use super::*;+ /// `client_source` is the one reading of "who is this client" behind both+ /// `ClaimSource` (HTTP) and the gRPC hub service's rate limit.+ #[tokio::test]+ async fn client_source_believes_forwarding_only_from_a_declared_proxy() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ config.server.trusted_proxies = vec!["10.0.0.0/8".into()];+ let metrics = xerj_common::metrics::Metrics::new().unwrap();+ let engine = xerj_engine::Engine::new(config.clone()).unwrap();+ let state = AppState::new(config, engine, metrics);+ let ip = |s: &str| Some(s.parse::<IpAddr>().unwrap());++ assert_eq!(client_source(&state, None, &["198.51.100.1"]), "unknown");+ // Undeclared peer: its own address, whatever it forwards.+ assert_eq!(+ client_source(&state, ip("192.0.2.9"), &["198.51.100.1"]),+ "192.0.2.9"+ );+ // Declared peer: the right-most address that is not a declared proxy,+ // across repeated values and comma lists.+ assert_eq!(+ client_source(&state, ip("10.0.0.1"), &["198.51.100.1"]),+ "198.51.100.1"+ );+ assert_eq!(+ client_source(+ &state,+ ip("10.0.0.1"),+ &["203.0.113.4, 198.51.100.1", "10.2.2.2"]+ ),+ "198.51.100.1"+ );+ // Nothing forwarded, all-proxy chain, or garbage: the peer.+ assert_eq!(client_source(&state, ip("10.0.0.1"), &[]), "10.0.0.1");+ assert_eq!(+ client_source(&state, ip("10.0.0.1"), &["10.3.3.3"]),+ "10.0.0.1"+ );+ assert_eq!(+ client_source(&state, ip("10.0.0.1"), &["not-an-ip"]),+ "10.0.0.1"+ );+ // An IPv4-mapped IPv6 peer is the IPv4 address (one bucket, one match).+ assert_eq!(+ client_source(&state, ip("::ffff:10.0.0.1"), &["198.51.100.1"]),+ "198.51.100.1"+ );+ }+#[test]fn expires_in_parses_units_and_rejects_bare_numbers() {assert_eq!(parse_expires_in("24h"), Some(24 * 3_600_000));diff --git a/engine/crates/xerj-server/src/grpc.rs b/engine/crates/xerj-server/src/grpc.rsindex badba13dd..4f1f39b67 100644--- a/engine/crates/xerj-server/src/grpc.rs+++ b/engine/crates/xerj-server/src/grpc.rs@@ -436,7 +436,8 @@ wherelistener.set_nonblocking(true).with_context(|| format!("gRPC: set the listener on {addr} non-blocking"))?;- serve_grpc_on(listener, state, shutdown).await+ let hub = xerj_api::hub_api::HubShared::new(state.clone());+ serve_grpc_on(listener, state, hub, shutdown).await}/// Serve gRPC on a listener the caller already bound.@@ -445,9 +446,16 @@ where/// taken port fails startup instead of being logged under a banner that/// already claimed the port (issue #465). That requires handing the bound/// listener in rather than letting tonic bind it here.+///+/// `hub` is the [`xerj_api::hub_api::HubShared`] the ES-compat router's+/// `/_hub/v1/*` routes were built over+/// ([`xerj_api::router::build_es_compat_router_with_hub`]): the `XerjHub`+/// service draws on the same per-client rate-limit budget, query slots and+/// catalogue cache, so a second listener is not a second allowance.pub async fn serve_grpc_on<F>(listener: std::net::TcpListener,state: AppState,+ hub: std::sync::Arc<xerj_api::hub_api::HubShared>,shutdown: F,) -> anyhow::Result<()>where@@ -478,7 +486,7 @@ wherestate: state.clone(),};let hub = pb::xerj_hub_server::XerjHubServer::with_interceptor(- crate::grpc_hub::HubService::new(state.clone()),+ crate::grpc_hub::HubService::new(hub),interceptor.clone(),);let svc = XerjSearchServer::with_interceptor(GrpcService::new(state), interceptor);diff --git a/engine/crates/xerj-server/src/grpc_hub.rs b/engine/crates/xerj-server/src/grpc_hub.rsindex 09c158ae1..205ebb59f 100644--- a/engine/crates/xerj-server/src/grpc_hub.rs+++ b/engine/crates/xerj-server/src/grpc_hub.rs@@ -16,9 +16,16 @@//! decision (an `excluded` corpus is never served; an `approach-only` one tags//! every hit with its licence warning), the 512-byte input cap, the `k` clamp,//! the in-process node pinned to one corpus build, the `xc-*` visibility guard,-//! the query-concurrency cap and timeout, the per-address rate limit — applies+//! the query-concurrency cap and timeout, the per-client rate limit — applies//! here unchanged, because it is the same code.//!+//! It is also the same STATE: the service holds the very [`HubShared`] the+//! ES-compat router's `/_hub/v1/*` routes were built over, so a client has one+//! rate-limit budget across both listeners (not one per listener), and the+//! client is read as the HTTP layer reads it+//! ([`xerj_api::share::client_source`]: the TCP peer, or `x-forwarded-for`+//! metadata only when the peer is a declared `server.trusted_proxies` entry).+//!//! Read-only: none of the three RPCs writes, pulls, evicts or deletes anything//! (`ask_answer` runs the flow offline with a backend that refuses to pull).//!@@ -47,25 +54,23 @@ use tonic::{Request, Response, Status};use xerj_api::auth::Principal;use xerj_api::hub_api::{self, HubAsk, HubRefusal, HubShared};-use xerj_api::AppState;use xerj_common::hub::{Answer, AnswerMode, Hit};use xerj_engine::index_guard;use crate::grpc::pb;use pb::xerj_hub_server::XerjHub;-/// The `XerjHub` service. Holds its own [`HubShared`] (query slots, rate-limit-/// budget, catalogue cache), as each HTTP router does.+/// The `XerjHub` service. Holds the node's [`HubShared`] (query slots,+/// rate-limit budget, catalogue cache) — the one the ES-compat router's hub+/// routes hold, never a second one.#[derive(Clone)]pub struct HubService {shared: Arc<HubShared>,}impl HubService {- pub fn new(state: AppState) -> Self {- Self {- shared: HubShared::new(state),- }+ pub fn new(shared: Arc<HubShared>) -> Self {+ Self { shared }}/// Who is calling and from where, with the rate limit counted. The visibility@@ -88,11 +93,15 @@ impl HubService {"a share link reads the index it was issued for, not the hub",));}- let client = request- .remote_addr()- .map(|a| a.ip().to_string())- .unwrap_or_else(|| "unknown".to_string());- self.shared.admit(&client).map_err(refusal_status)?;+ let forwarded: Vec<&str> = request+ .metadata()+ .get_all("x-forwarded-for")+ .iter()+ .filter_map(|v| v.to_str().ok())+ .collect();+ self.shared+ .admit_peer(request.remote_addr().map(|a| a.ip()), &forwarded)+ .map_err(refusal_status)?;let visibility =(!principal.is_superuser()).then(|| xerj_api::authz::visibility_for(&principal));// The in-process node forwards the caller's credential the way the HTTP@@ -479,6 +488,122 @@ mod tests {assert_eq!(limited.message(), "why");}+ // ── the rate limit: one budget per client, across HTTP and gRPC ──++ mod rate_limit {+ use super::super::*;+ use axum::body::Body;+ use std::net::SocketAddr;+ use tonic::transport::server::TcpConnectInfo;+ use tower::ServiceExt;+ use xerj_api::hub_api::RATE_LIMIT;++ fn state(dir: &std::path::Path, trusted: &[&str]) -> xerj_api::AppState {+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = dir.to_string_lossy().into_owned();+ config.server.trusted_proxies = trusted.iter().map(|s| s.to_string()).collect();+ let metrics = xerj_common::metrics::Metrics::new().unwrap();+ let engine = xerj_engine::Engine::new(config.clone()).unwrap();+ xerj_api::AppState::new(config, engine, metrics)+ }++ /// A request as tonic's transport hands it to the service: the+ /// interceptor's principal installed, the TCP peer recorded, and+ /// whatever `x-forwarded-for` metadata the caller chose to send.+ fn from(peer: Option<&str>, xff: Option<&str>) -> Request<()> {+ let mut r = Request::new(());+ r.extensions_mut().insert(Principal::Superuser);+ if let Some(peer) = peer {+ r.extensions_mut().insert(TcpConnectInfo {+ local_addr: None,+ remote_addr: Some(peer.parse::<SocketAddr>().unwrap()),+ });+ }+ if let Some(xff) = xff {+ r.metadata_mut()+ .insert("x-forwarded-for", xff.parse().unwrap());+ }+ r+ }++ fn admitted(svc: &HubService, r: &Request<()>) -> Result<(), tonic::Code> {+ svc.admit(r).map(|_| ()).map_err(|s| s.code())+ }++ /// The two listeners wired as `main.rs` wires them: one `HubShared`+ /// for the ES-compat router and the gRPC service.+ #[tokio::test]+ async fn http_and_grpc_draw_on_one_budget() {+ let dir = tempfile::tempdir().unwrap();+ let state = state(dir.path(), &[]);+ let shared = HubShared::new(state.clone());+ let app = xerj_api::router::build_es_compat_router_with_hub(state, shared.clone());+ let svc = HubService::new(shared);+ // `oneshot` carries no ConnectInfo, so HTTP keys these on+ // `unknown`; a gRPC request with no peer keys on `unknown` too.+ for i in 0..RATE_LIMIT {+ let resp = app+ .clone()+ .oneshot(+ axum::http::Request::get("/_hub/v1/catalogue")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_ne!(resp.status().as_u16(), 429, "HTTP request {i}");+ }+ assert_eq!(+ admitted(&svc, &from(None, None)),+ Err(tonic::Code::ResourceExhausted),+ "{RATE_LIMIT} HTTP requests spent the client's budget; gRPC must not grant \+ a second one"+ );+ }++ #[tokio::test]+ async fn a_trusted_proxy_is_keyed_on_the_forwarded_client() {+ let dir = tempfile::tempdir().unwrap();+ let svc = HubService::new(HubShared::new(state(dir.path(), &["10.0.0.0/8"])));+ for _ in 0..RATE_LIMIT {+ admitted(&svc, &from(Some("10.1.1.1:5000"), Some("203.0.113.5"))).unwrap();+ }+ assert_eq!(+ admitted(&svc, &from(Some("10.1.1.1:5000"), Some("203.0.113.5"))),+ Err(tonic::Code::ResourceExhausted),+ "the forwarded client is throttled"+ );+ assert_eq!(+ admitted(&svc, &from(Some("10.1.1.1:5001"), Some("203.0.113.6"))),+ Ok(()),+ "another client behind the same sidecar has its own budget"+ );+ // Right-to-left past declared proxies, as the HTTP path reads it.+ assert_eq!(+ admitted(+ &svc,+ &from(Some("10.1.1.1:5002"), Some("198.51.100.7, 10.2.2.2"))+ ),+ Ok(()),+ );+ }++ #[tokio::test]+ async fn an_untrusted_peer_cannot_pick_its_bucket() {+ let dir = tempfile::tempdir().unwrap();+ let svc = HubService::new(HubShared::new(state(dir.path(), &["10.0.0.0/8"])));+ for i in 0..RATE_LIMIT {+ let xff = format!("203.0.113.{i}");+ admitted(&svc, &from(Some("192.0.2.9:7000"), Some(&xff))).unwrap();+ }+ assert_eq!(+ admitted(&svc, &from(Some("192.0.2.9:7000"), Some("198.51.100.99"))),+ Err(tonic::Code::ResourceExhausted),+ "a fresh x-forwarded-for from an untrusted peer is ignored"+ );+ }+ }+// ── end to end: a real node, a restored fixture corpus, a real listener ──mod e2e {@@ -587,7 +712,7 @@ mod tests {})}- fn state(dir: &std::path::Path) -> AppState {+ fn state(dir: &std::path::Path) -> xerj_api::AppState {let fx = fixture();let mut config = xerj_common::config::Config::default();config.server.data_dir = dir.to_string_lossy().into_owned();@@ -597,7 +722,7 @@ mod tests {config.auth.admin_api_key = ADMIN_KEY.into();let metrics = xerj_common::metrics::Metrics::new().unwrap();let engine = xerj_engine::Engine::new(config.clone()).unwrap();- AppState::new(config, engine, metrics)+ xerj_api::AppState::new(config, engine, metrics)}async fn http(@@ -697,7 +822,9 @@ mod tests {let fx = fixture();let data = tempfile::tempdir().unwrap();let state = state(data.path());- let app = xerj_api::router::build_es_compat_router(state.clone());+ let shared = HubShared::new(state.clone());+ let app =+ xerj_api::router::build_es_compat_router_with_hub(state.clone(), shared.clone());seed(&app,"mini-c",@@ -736,6 +863,7 @@ mod tests {let server = tokio::spawn(crate::grpc::serve_grpc_on(listener,state.clone(),+ shared,async move {let _ = rx.await;},diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 39154fe69..bcf72ca6f 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -86,7 +86,7 @@ use tokio::signal;use tracing::{error, info, warn};use tracing_subscriber::EnvFilter;-use xerj_api::{build_es_compat_router, build_native_router, AppState};+use xerj_api::{build_es_compat_router_with_hub, build_native_router, AppState};use xerj_cluster::{transport::TcpTransport, ClusterNode, ClusterRunner};use xerj_common::{config::Config, metrics::Metrics};use xerj_console_api::{state::ClusterMode, ConsoleState, RpConfig};@@ -2880,7 +2880,10 @@ async fn async_main() -> Result<()> {// merge would leave xerj-api compiling and serving on its own// — a property worth preserving.let mut native_router = build_native_router(state.clone());- let mut es_router = build_es_compat_router(state.clone());+ // One hub state for the ES-compat `/_hub/v1/*` routes AND the gRPC+ // `XerjHub` service: one rate-limit budget per client across both.+ let hub_shared = xerj_api::hub_api::HubShared::new(state.clone());+ let mut es_router = build_es_compat_router_with_hub(state.clone(), hub_shared.clone());if let Some(console_state) = xerj_console_state {let xerj_console_router = xerj_console_api::xerj_console_router(console_state);native_router = native_router.merge(xerj_console_router.clone());@@ -2970,7 +2973,9 @@ async fn async_main() -> Result<()> {// made no false claim: it did hold the port.let grpc_state = state.clone();let grpc = tokio::spawn(async move {- if let Err(e) = grpc::serve_grpc_on(grpc_listener, grpc_state, shutdown_signal()).await {+ if let Err(e) =+ grpc::serve_grpc_on(grpc_listener, grpc_state, hub_shared, shutdown_signal()).await+ {error!("gRPC server: {e:#}");}});