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(auth): find the local admin key and say when the node is up (#1625)
xerj-orgef164966a750
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex dc9d5f8c4..f89da08c2 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -11,7 +11,7 @@ use std::time::Duration;// are pinned by the `local admin-key discovery` tests at the bottom of this// file: they stayed here when the helpers moved to `xerj-common`, so they// are the shared helpers' tests wherever the helpers live.-use xerj_common::localauth::{discover_local_admin_key, url_is_loopback};+use xerj_common::localauth::{discover_local_admin_key_for_url, url_is_loopback};/// Largest `--max-minutes` accepted: one week. Past that the flag is a typo,/// and `--max-minutes 0` already exists to mean "never ask".@@ -1306,7 +1306,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {// we are talking to a server on this machine, and sending it anywhere else// would leak a credential to a host it does not belong to.if api_key.is_none() && url_is_loopback(&url) {- if let Some((key, path)) = discover_local_admin_key() {+ if let Some((key, path)) = discover_local_admin_key_for_url(&url) {// Announced, never silent: a blind onboarding run found this// fallback made success depend on the working directory, because// `./data/admin.key` is resolved relative to cwd. Saying which@@ -2722,6 +2722,8 @@ mod tests {// ─── local admin-key discovery ──────────────────────────────────────+ use xerj_common::localauth::{discover_local_admin_key, discover_local_admin_key_for_url};+/// `url_is_loopback` decides whether a credential read off this machine's/// disk is put on the wire, so a false positive is a credential leak, not/// a cosmetic bug. The negatives below are the shapes an attacker would@@ -2869,32 +2871,46 @@ mod tests {#[test]fn discovery_walks_the_candidates_in_order_and_trims_the_key() {let sandbox = Sandbox::new();- assert_eq!(super::discover_local_admin_key(), None, "nothing to find");+ assert_eq!(discover_local_admin_key(), None, "nothing to find");// Weakest candidate first, then override it one rung at a time.sandbox.write("home/.xerj/admin.key", "home-key\n");assert_eq!(- super::discover_local_admin_key().map(|(k, _)| k).as_deref(),+ discover_local_admin_key().map(|(k, _)| k).as_deref(),Some("home-key"));+ sandbox.write("home/xerj-data/admin.key", "llms-home-key\n");+ assert_eq!(+ discover_local_admin_key().map(|(k, _)| k).as_deref(),+ Some("llms-home-key"),+ "~/xerj-data is the data dir llms.txt tells an agent to start"+ );+sandbox.write("home/.xerj/brain/admin.key", " brain-key \t\r\n");assert_eq!(- super::discover_local_admin_key().map(|(k, _)| k).as_deref(),+ discover_local_admin_key().map(|(k, _)| k).as_deref(),Some("brain-key"),"the brain data dir outranks the bare ~/.xerj key, and is trimmed");sandbox.write("xerj-data/admin.key", "xerj-data-key\n");assert_eq!(- super::discover_local_admin_key().map(|(k, _)| k).as_deref(),+ discover_local_admin_key().map(|(k, _)| k).as_deref(),Some("xerj-data-key"),"a data dir in the working directory outranks anything in $HOME");+ sandbox.write(".xerj-data/admin.key", "dot-data-key\n");+ assert_eq!(+ discover_local_admin_key().map(|(k, _)| k).as_deref(),+ Some("dot-data-key"),+ "./.xerj-data is the directory the search/def start hint names"+ );+sandbox.write("data/admin.key", "\ndata-key\n");assert_eq!(- super::discover_local_admin_key().map(|(k, _)| k).as_deref(),+ discover_local_admin_key().map(|(k, _)| k).as_deref(),Some("data-key"),"./data is the quickstart's own path and wins outright");@@ -2909,19 +2925,61 @@ mod tests {sandbox.write("data/admin.key", " \n\t\n");sandbox.write("xerj-data/admin.key", "");assert_eq!(- super::discover_local_admin_key(),+ discover_local_admin_key(),None,"whitespace-only and zero-byte files are not credentials");sandbox.write("home/.xerj/admin.key", "real-key\n");assert_eq!(- super::discover_local_admin_key().map(|(k, _)| k).as_deref(),+ discover_local_admin_key().map(|(k, _)| k).as_deref(),Some("real-key"),"an empty candidate must be skipped over, not stop the search");}+ /// The server writes `~/.xerj/by-port/<port>` with the path of that+ /// listener's admin.key. That pointer outranks a leftover `./data` key,+ /// and a different port does not read it.+ #[test]+ fn a_port_pointer_names_the_key_for_that_listener() {+ let sandbox = Sandbox::new();+ sandbox.write("data/admin.key", "cwd-key\n");+ sandbox.write("elsewhere/admin.key", "port-key\n");+ let abs = sandbox.dir.path().join("elsewhere/admin.key");+ xerj_common::localauth::publish_admin_key_for_port(9200, &abs).unwrap();+ let (key, _) = discover_local_admin_key_for_url("http://localhost:9200").unwrap();+ assert_eq!(key, "port-key");+ let (key, _) = discover_local_admin_key_for_url("http://127.0.0.1:9201").unwrap();+ assert_eq!(+ key, "cwd-key",+ "another port must not reuse the 9200 pointer"+ );+ assert_eq!(+ discover_local_admin_key().map(|(k, _)| k).as_deref(),+ Some("cwd-key"),+ "discovery without a URL does not guess a port"+ );+ assert_eq!(+ xerj_common::localauth::xerj_url_port("localhost:9207"),+ 9207+ );+ assert_eq!(+ xerj_common::localauth::xerj_url_port("http://localhost"),+ 9200+ );+ }++ #[test]+ fn an_auth_rejection_is_not_reported_as_an_unreachable_node() {+ let auth = anyhow::anyhow!(+ "the server at http://localhost:9200 requires authentication and no API key was supplied (HTTP 401)."+ );+ assert!(crate::esclient::Es::ping_failure_is_auth(&auth));+ let down = anyhow::anyhow!("endpoint unreachable: http://localhost:9200");+ assert!(!crate::esclient::Es::ping_failure_is_auth(&down));+ }+/// The wiring: discovery only ever fires when the run has no credential of/// its own AND the target is this machine. Sending a locally readable/// admin key to a host that did not write it is the failure mode thisdiff --git a/engine/crates/xerj-autoindex/src/def.rs b/engine/crates/xerj-autoindex/src/def.rsindex 5edc78201..fcb46bf5f 100644--- a/engine/crates/xerj-autoindex/src/def.rs+++ b/engine/crates/xerj-autoindex/src/def.rs@@ -296,6 +296,15 @@ pub fn run_def_cli() -> i32 {if url.is_empty() {url = "http://localhost:9200".to_string();}+ if api_key.is_none() && xerj_common::localauth::url_is_loopback(&url) {+ if let Some((key, path)) = xerj_common::localauth::discover_local_admin_key_for_url(&url) {+ eprintln!(+ "xerj def: no --api-key/XERJ_API_KEY given; using the admin key at {}",+ path.display()+ );+ api_key = Some(key);+ }+ }let es = match Es::new(&url, api_key) {Ok(es) => es,@@ -305,6 +314,10 @@ pub fn run_def_cli() -> i32 {}};if let Err(e) = es.ping() {+ if crate::esclient::Es::ping_failure_is_auth(&e) {+ eprintln!("xerj def: the node at {url} answered, but authentication failed.\n{e:#}");+ return 2;+ }eprintln!("xerj def: no XERJ node reachable at {url} ({e}).\n\n\Start one, then index a repo:\n \diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rsindex 8c6526bff..7e3d3e1a5 100644--- a/engine/crates/xerj-autoindex/src/esclient.rs+++ b/engine/crates/xerj-autoindex/src/esclient.rs@@ -992,6 +992,13 @@ impl Es {r}+ /// True when `ping` failed because the node answered 401/403. That is not+ /// "no node reachable" — the node is up and the key is missing or wrong.+ pub fn ping_failure_is_auth(err: &anyhow::Error) -> bool {+ let text = format!("{err:#}");+ text.contains("(HTTP 401)") || text.contains("(HTTP 403)")+ }+pub fn ping(&self) -> Result<Value> {let resp = self.req(reqwest::Method::GET, "/")diff --git a/engine/crates/xerj-autoindex/src/init.rs b/engine/crates/xerj-autoindex/src/init.rsindex 345b4c972..07ec1aa80 100644--- a/engine/crates/xerj-autoindex/src/init.rs+++ b/engine/crates/xerj-autoindex/src/init.rs@@ -596,7 +596,7 @@ pub(crate) fn run_init_with(// we only tell the user which of the two worlds they are in — the key// itself is never printed or written.if xerj_common::localauth::url_is_loopback(url) {- match xerj_common::localauth::discover_local_admin_key() {+ match xerj_common::localauth::discover_local_admin_key_for_url(url) {Some((_, path)) => out.push(format!(" auth MCP authenticates with the admin key at {} (local node)",path.display()diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex dd4d3c971..8e85831f1 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -5945,6 +5945,12 @@ fn run_index_report_inner(// gets the same recipe `xerj def` already prints: start one, or aim at// an existing node.if let Err(e) = es.ping() {+ if esclient::Es::ping_failure_is_auth(&e) {+ anyhow::bail!(+ "the node at {url} answered, but authentication failed.\n{e:#}",+ url = cfg.url+ );+ }anyhow::bail!("no XERJ node reachable at {url} ({e:#})\n\n\Start one, then re-run this command:\n \diff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rsindex 4728eedd6..7ddc0bd76 100644--- a/engine/crates/xerj-autoindex/src/search.rs+++ b/engine/crates/xerj-autoindex/src/search.rs@@ -440,6 +440,15 @@ pub fn run_search_cli() -> i32 {if url.is_empty() {url = "http://localhost:9200".to_string();}+ if api_key.is_none() && xerj_common::localauth::url_is_loopback(&url) {+ if let Some((key, path)) = xerj_common::localauth::discover_local_admin_key_for_url(&url) {+ eprintln!(+ "xerj search: no --api-key/XERJ_API_KEY given; using the admin key at {}",+ path.display()+ );+ api_key = Some(key);+ }+ }let es = match Es::new(&url, api_key) {Ok(es) => es,@@ -452,6 +461,10 @@ pub fn run_search_cli() -> i32 {// Detect the node. If nothing answers, say exactly how to start one rather// than dumping a transport error — this is the most common first-run miss.if let Err(e) = es.ping() {+ if Es::ping_failure_is_auth(&e) {+ eprintln!("xerj search: the node at {url} answered, but authentication failed.\n{e:#}");+ return 2;+ }eprintln!("xerj search: no XERJ node reachable at {url} ({e}).\n\n\Start one, then index a repo:\n \diff --git a/engine/crates/xerj-autoindex/src/xc.rs b/engine/crates/xerj-autoindex/src/xc.rsindex 5a46b81fd..3031ad863 100644--- a/engine/crates/xerj-autoindex/src/xc.rs+++ b/engine/crates/xerj-autoindex/src/xc.rs@@ -15,7 +15,7 @@ use std::process::Command;use anyhow::{Context, Result};use serde_json::{json, Value};-use xerj_common::localauth::{discover_local_admin_key, url_is_loopback};+use xerj_common::localauth::{discover_local_admin_key_for_url, url_is_loopback};use xerj_common::xccode::{self, manifest, state, CodeOutcome, CodeParams, Mode, XcHttp};use crate::esclient::{Count, Es};@@ -55,7 +55,7 @@ fn build_es(url: &str, api_key: Option<String>) -> Result<Es> {Some(k) => Some(k),None => {if url_is_loopback(url) {- discover_local_admin_key().map(|(k, path)| {+ discover_local_admin_key_for_url(url).map(|(k, path)| {eprintln!("xerj code: no --api-key/XERJ_API_KEY given; using the admin \key at {}",diff --git a/engine/crates/xerj-common/src/localauth.rs b/engine/crates/xerj-common/src/localauth.rsindex 5704f1fa1..b1f6e19ab 100644--- a/engine/crates/xerj-common/src/localauth.rs+++ b/engine/crates/xerj-common/src/localauth.rs@@ -68,12 +68,81 @@ pub fn url_is_loopback(url: &str) -> bool {/// against the current directory before being returned: the announcement/// must name a path the reader can act on even when the calling process was/// spawned with an arbitrary cwd, which is exactly what MCP hosts do.+fn read_admin_key(path: &std::path::Path) -> Option<(String, PathBuf)> {+ std::fs::read_to_string(path)+ .ok()+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+ .map(|k| (k, path.to_path_buf()))+}++/// `~/.xerj/by-port/<port>` — one line, the absolute path of that listener's+/// `admin.key`. The server writes it on boot. Discovery reads the path, not+/// a second copy of the key.+fn port_pointer(port: u16) -> Option<PathBuf> {+ crate::home::home_dir().map(|home| home.join(".xerj").join("by-port").join(port.to_string()))+}++/// Record which data dir is serving `port`, so a later command on this+/// machine can find that node's admin key without guessing `--data-dir`.+/// The file holds the key's path. A missing home directory is not an error.+pub fn publish_admin_key_for_port(+ port: u16,+ admin_key_file: &std::path::Path,+) -> std::io::Result<()> {+ let Some(dest) = port_pointer(port) else {+ return Ok(());+ };+ if let Some(parent) = dest.parent() {+ std::fs::create_dir_all(parent)?;+ }+ let abs =+ std::fs::canonicalize(admin_key_file).unwrap_or_else(|_| admin_key_file.to_path_buf());+ std::fs::write(&dest, format!("{}\n", abs.display()))?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o600))?;+ }+ Ok(())+}++/// Port of a XERJ URL. An explicit port wins; a URL with none is the product+/// default `9200` (not the scheme default 80/443).+pub fn xerj_url_port(url: &str) -> u16 {+ // A schemeless `localhost:9207` parses as scheme `localhost`, so retry+ // through `http://` the same way `url_is_loopback` does. An explicit port+ // wins; a URL with none is the product default 9200, not 80/443.+ let parsed = match url::Url::parse(url) {+ Ok(u) if matches!(u.scheme(), "http" | "https") => Some(u),+ _ => url::Url::parse(&format!("http://{url}")).ok(),+ };+ parsed.and_then(|u| u.port()).unwrap_or(9200)+}++/// [`discover_local_admin_key`], but the server's per-port pointer is tried+/// first. Callers must still refuse to send the key anywhere but loopback.+pub fn discover_local_admin_key_for_url(url: &str) -> Option<(String, PathBuf)> {+ let port = xerj_url_port(url);+ if let Some(pointer) = port_pointer(port) {+ if let Ok(text) = std::fs::read_to_string(&pointer) {+ let target = PathBuf::from(text.trim());+ if let Some(found) = read_admin_key(&target) {+ return Some(found);+ }+ }+ }+ discover_local_admin_key()+}+pub fn discover_local_admin_key() -> Option<(String, PathBuf)> {// Relative candidates resolve against the current directory (the "./"- // prefix is dropped so the announced path reads cleanly); the first two- // are the quickstart's own `--data-dir ./data` and its sibling spelling.+ // prefix is dropped so the announced path reads cleanly). `./data` is the+ // quickstart; `./.xerj-data` is what `xerj search` / `xerj def` tell you+ // to start; `./xerj-data` is the same name without the dot.const CANDIDATES: &[&str] = &["data/admin.key",+ ".xerj-data/admin.key","xerj-data/admin.key","/var/lib/xerj/admin.key",];@@ -90,13 +159,9 @@ pub fn discover_local_admin_key() -> Option<(String, PathBuf)> {.collect();if let Some(home) = crate::home::home_dir() {paths.push(home.join(".xerj/brain/admin.key"));+ // llms.txt: `xerj --data-dir ~/xerj-data`.+ paths.push(home.join("xerj-data/admin.key"));paths.push(home.join(".xerj/admin.key"));}- paths.into_iter().find_map(|p| {- std::fs::read_to_string(&p)- .ok()- .map(|s| s.trim().to_string())- .filter(|s| !s.is_empty())- .map(|k| (k, p))- })+ paths.into_iter().find_map(|p| read_admin_key(&p))}diff --git a/engine/crates/xerj-hub/src/node.rs b/engine/crates/xerj-hub/src/node.rsindex 59e50e33c..302888769 100644--- a/engine/crates/xerj-hub/src/node.rs+++ b/engine/crates/xerj-hub/src/node.rs@@ -55,7 +55,7 @@ use std::time::{Duration, Instant};use anyhow::{anyhow, bail, Context, Result};use serde_json::Value;-use xerj_common::localauth::{discover_local_admin_key, url_is_loopback};+use xerj_common::localauth::{discover_local_admin_key_for_url, url_is_loopback};use xerj_common::xccode::XcHttp;use crate::flock::{held_by, FileLock, LockError};@@ -113,13 +113,15 @@ impl HubNode {Some(k) => Some(k),None => match std::env::var("XERJ_API_KEY").ok().filter(|k| !k.is_empty()) {Some(k) => Some(k),- None if url_is_loopback(&base) => discover_local_admin_key().map(|(k, path)| {- eprintln!(- "xerj hub: no --api-key/XERJ_API_KEY given; using the admin key at {}",- path.display()- );- k- }),+ None if url_is_loopback(&base) => {+ discover_local_admin_key_for_url(&base).map(|(k, path)| {+ eprintln!(+ "xerj hub: no --api-key/XERJ_API_KEY given; using the admin key at {}",+ path.display()+ );+ k+ })+ }None => None,},};diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rsindex f1bd93953..281ed49a7 100644--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@ -221,7 +221,7 @@ fn resolve_auth(if !xerj_common::localauth::url_is_loopback(base_url) {return (None, None);}- match xerj_common::localauth::discover_local_admin_key() {+ match xerj_common::localauth::discover_local_admin_key_for_url(base_url) {// `XERJ_AUTH` is a complete header value ("ApiKey <token>"), so the// discovered bare key is formatted to the same documented shape.Some((key, path)) => (Some(format!("ApiKey {key}")), Some(path)),diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 51e85ff8c..9e20473e4 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -2737,6 +2737,23 @@ async fn async_main() -> Result<()> {// 5. Admin key (first-run)ensure_admin_key(&mut cfg)?;+ // Point later loopback clients at this listener's key. The file stores+ // the path, not a second copy of the secret. A failure here does not+ // stop the node: discovery still has its path candidates.+ if cfg.auth.enabled {+ let key_path = Path::new(&cfg.server.data_dir).join("admin.key");+ if key_path.is_file() {+ if let Err(error) = xerj_common::localauth::publish_admin_key_for_port(+ cfg.server.es_compat_port,+ &key_path,+ ) {+ warn!(+ "could not publish the admin-key path for port {}: {error}",+ cfg.server.es_compat_port+ );+ }+ }+ }// 6. TLS certificate — fail closed (issue #200). The operator asked for// TLS; if the certificate step cannot deliver it, refuse to start