Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(serve): require the client marker on proxied handoff fetches
AkitaOnRails0d7eafe11b4b
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 3e482d05..60b7c12b 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -2957,7 +2957,9 @@ async fn require_allowed_host(/// host name gets an `<img>` request with neither fetch metadata nor `Origin`./// For that case the session-start handoff fetch, the one state-changing `GET`/// on these routes, must also carry [`CLIENT_MARKER_HEADER`], which a page-/// cannot add without a preflight these routes never answer. Loopback hosts+/// cannot add without a preflight these routes never answer. A request that+/// carries a proxy's forwarding header counts as non-loopback even when the+/// proxy rewrote `Host` to a loopback address. Loopback hosts/// keep working without it, so hook scripts staged before the header existed/// still deliver handoffs on a default install. `POST`s need no marker: a/// browser sends `Origin` on every cross-origin `POST`, metadata or not.@@ -2972,7 +2974,7 @@ fn refuse_cross_origin_browser_requests(router: axum::Router, auth_enabled: bool/// reaches an operator through a hook staged before the header existed, so it/// names both ways out.const CLIENT_MARKER_REFUSAL: &str = "handoff fetch refused: this server has no bearer token and \- was reached through a non-loopback host name, so it accepts the handoff fetch only from \+ was reached through a non-loopback host name or a proxy, so it accepts the handoff fetch only from \current ai-memory hooks; re-stage them with `ai-memory install-hooks` (or `ai-memory \upgrade`), or configure AI_MEMORY_AUTH_TOKEN\n";@@ -3001,7 +3003,7 @@ async fn require_same_origin_browser(req: Request<Body>, next: Next) -> Response/// Whether this is a handoff fetch (`GET`, or `HEAD`, which axum routes to the/// same handler) without [`CLIENT_MARKER_HEADER`] on a host where a browser-/// sends no fetch metadata. The path is the one inside any `--base-path`+/// sends no fetch metadata, or through a forwarding proxy. The path is the one inside any `--base-path`/// mount, which strips its prefix before this layer runs.fn handoff_fetch_lacks_client_marker(method: &axum::http::Method,@@ -3018,12 +3020,28 @@ fn handoff_fetch_lacks_client_marker({return false;}- !headers- .get(header::HOST)- .and_then(|host| host.to_str().ok())- .is_some_and(is_loopback_host)+ // A plain-HTTP reverse proxy can rewrite `Host` to the loopback address+ // it forwards to, while the browser behind it saw a non-loopback origin+ // and so sent no fetch metadata. Such a request is not a loopback one.+ // First-party clients talk to the server directly and send none of these.+ let proxied = PROXY_HEADERS.iter().any(|name| headers.contains_key(*name));+ proxied+ || !headers+ .get(header::HOST)+ .and_then(|host| host.to_str().ok())+ .is_some_and(is_loopback_host)}+/// Headers a forwarding proxy adds; any of them means the `Host` a request+/// carries may not be the one the browser addressed.+const PROXY_HEADERS: [&str; 5] = [+ "forwarded",+ "x-forwarded-for",+ "x-forwarded-host",+ "x-real-ip",+ "via",+];+/// Whether a browser treats this `Host` as a potentially trustworthy origin/// and so sends fetch metadata to it over plain HTTP: `localhost`, a/// `*.localhost` name, `127.0.0.0/8` or `[::1]`. Anything else, including a@@ -5281,6 +5299,21 @@ mod tests {"{method} {path} host={host} marker={marker:?}");}+ // A plain-HTTP proxy that rewrites `Host` to loopback: the browser+ // behind it addressed a non-loopback origin and sent no metadata.+ for proxy_header in PROXY_HEADERS {+ let mut proxied = headers("127.0.0.1:49374", None);+ proxied.insert(proxy_header, "203.0.113.7".parse().unwrap());+ assert!(+ handoff_fetch_lacks_client_marker(&Method::GET, "/handoff", &proxied),+ "{proxy_header} without the marker"+ );+ proxied.insert(CLIENT_MARKER_HEADER, "hook".parse().unwrap());+ assert!(+ !handoff_fetch_lacks_client_marker(&Method::GET, "/handoff", &proxied),+ "{proxy_header} with the marker"+ );+ }let mut no_host = axum::http::HeaderMap::new();assert!(handoff_fetch_lacks_client_marker(&Method::GET,diff --git a/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rs b/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rsindex 89b68f14..1e508791 100644--- a/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rs@@ -524,6 +524,55 @@ mod slow {"legacy loopback fetch: {body}");assert_eq!(open_handoffs(&client, &base).await, 0);++ // Attack: a plain-HTTP proxy that rewrites `Host` to the loopback+ // address. The browser behind it addressed a non-loopback origin, so+ // it sent no fetch metadata; the proxy's forwarding header gives the+ // hop away.+ begin_handoff(&client, &base).await;+ let loopback = format!("127.0.0.1:{port}");+ let proxied = |proxy_header: &'static str, marker: Option<&'static str>| {+ let mut req = client+ .get(format!(+ "{base}/handoff?agent=claude-code&workspace={WORKSPACE}&project={PROJECT}"+ ))+ .header("host", &loopback)+ .header(proxy_header, "203.0.113.7");+ if let Some(marker) = marker {+ req = req.header("x-ai-memory-client", marker);+ }+ req.send()+ };+ for proxy_header in [+ "forwarded",+ "x-forwarded-for",+ "x-forwarded-host",+ "x-real-ip",+ "via",+ ] {+ let resp = proxied(proxy_header, None).await.expect("proxied fetch");+ assert_eq!(+ resp.status(),+ StatusCode::FORBIDDEN,+ "loopback Host behind a proxy ({proxy_header}) without the marker"+ );+ }+ assert_eq!(+ open_handoffs(&client, &base).await,+ 1,+ "a refused proxied fetch must not claim the baton"+ );+ // Control: a current hook behind the same proxy names itself.+ let resp = proxied("x-forwarded-for", Some("hook"))+ .await+ .expect("marked proxied fetch");+ assert_eq!(resp.status(), StatusCode::OK);+ let body = resp.text().await.expect("handoff body");+ assert!(+ body.contains(HANDOFF_SUMMARY),+ "marked proxied fetch: {body}"+ );+ assert_eq!(open_handoffs(&client, &base).await, 0);}#[tokio::test]diff --git a/docs/security.md b/docs/security.mdindex e7792f9b..63a8b963 100644--- a/docs/security.md+++ b/docs/security.md@@ -76,7 +76,12 @@ CLI command and generated integration sends; a web page cannot add it withouta CORS preflight, which these routes never answer. Hooks staged before thisheader existed get a 403 on such a server until you re-run`ai-memory install-hooks` (or `ai-memory upgrade`); on a loopback host they-keep working unchanged. A browser that sends no fetch metadata even to loopback+keep working unchanged. A request that carries a proxy's forwarding header+(`Forwarded`, `X-Forwarded-For`, `X-Forwarded-Host`, `X-Real-IP` or `Via`)+counts as non-loopback here even when its `Host` is a loopback address,+because a plain-HTTP reverse proxy may rewrite `Host` to the address it+forwards to while the browser behind it saw a non-loopback origin. ai-memory's+own clients connect directly and send none of these headers. A browser that sends no fetch metadata even to loopback(Safari before 16.4) only gets the `Origin` check there, which an image or linkdoes not trigger; set a bearer token if you use one. The `Host`allowlist refuses DNS-rebinding hostnames, and the JSON-only routes refuse the