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.

fix(mcp): fall back to the local admin key on loopback so init's MCP entry works on an auth-on node

xerj-org6e0bf1dd899a
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index 9a8e3b60e..b104bb34b 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -7403,6 +7403,7 @@ dependencies = [
"thiserror 2.0.18",
"toml",
"tracing",
+ "url",
"uuid",
]
@@ -7561,6 +7562,7 @@ dependencies = [
"anyhow",
"reqwest",
"serde_json",
+ "tempfile",
"tokio",
"xerj-common",
"xerj-rerank",
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index e8603c706..1f9546205 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -5,6 +5,13 @@ use crate::ignore_rules::IgnoreOptions;
use crate::progress::ProgressMode;
use std::path::PathBuf;
use std::time::Duration;
+// Loopback guard + local admin-key discovery, shared with `xerj mcp` (which
+// hit the identical 401 failure mode, #961). The invariants — a false
+// positive on `url_is_loopback` is a credential leak, not a cosmetic bug —
+// 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};
/// Largest `--max-minutes` accepted: one week. Past that the flag is a typo,
/// and `--max-minutes 0` already exists to mean "never ask".
@@ -1432,68 +1439,6 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
}
}
-/// True when `url`'s host is this machine, so a locally readable admin key is
-/// the right credential to send. Anything else — a LAN address, a hostname, a
-/// remote deployment — must be given a key explicitly.
-///
-/// Parsed with a real URL parser rather than string surgery, because the
-/// hand-rolled version of this was wrong in a way that leaked credentials:
-/// splitting on the last `:` treats the userinfo in
-/// `http://localhost:[email protected]/` as a host:port pair, judges it loopback,
-/// and sends the admin key to `evil.com`. `Url::host_str` resolves that to
-/// `evil.com`, which is the whole point of using it.
-fn url_is_loopback(url: &str) -> bool {
- // A schemeless `localhost:9200` parses as scheme `localhost`, path `9200`,
- // with no host at all, so retry those through `http://`. The retry still
- // goes through the parser: `localhost:[email protected]` becomes
- // `http://localhost:[email protected]`, whose host is `evil.com`, not loopback.
- let parsed = match reqwest::Url::parse(url) {
- Ok(u) if matches!(u.scheme(), "http" | "https") => u,
- _ => match reqwest::Url::parse(&format!("http://{url}")) {
- Ok(u) => u,
- // Unparseable is not loopback. Failing closed here costs a user
- // with an exotic URL one explicit --api-key; failing open costs
- // them the key itself.
- Err(_) => return false,
- },
- };
- match parsed.host_str() {
- // `host_str` strips the brackets from `[::1]` and does not lowercase
- // an IPv6 literal, so compare case-insensitively and cover both forms.
- Some(h) => {
- let h = h.trim_start_matches('[').trim_end_matches(']');
- h.eq_ignore_ascii_case("localhost") || h == "127.0.0.1" || h == "::1" || h == "0.0.0.0"
- }
- None => false,
- }
-}
-
-/// The admin key a local server wrote for itself, if we can find it.
-///
-/// Checked in the order a user is most likely to have created them: the
-/// working directory's data dir (what the quickstart tells you to use), then
-/// the documented package install location. Absent or unreadable is not an
-/// error — the caller falls back to the actionable 401 message.
-fn discover_local_admin_key() -> Option<(String, PathBuf)> {
- const CANDIDATES: &[&str] = &[
- "./data/admin.key",
- "./xerj-data/admin.key",
- "/var/lib/xerj/admin.key",
- ];
- let mut paths: Vec<PathBuf> = CANDIDATES.iter().map(PathBuf::from).collect();
- if let Some(home) = std::env::var_os("HOME") {
- paths.push(PathBuf::from(&home).join(".xerj/brain/admin.key"));
- paths.push(PathBuf::from(&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))
- })
-}
-
#[cfg(test)]
mod tests {
use super::{parse, Approval, Cmd, Duration, ProgressMode, DEFAULT_MAX_MINUTES};
diff --git a/engine/crates/xerj-autoindex/src/init.rs b/engine/crates/xerj-autoindex/src/init.rs
index 4a8481c1f..0f152443d 100644
--- a/engine/crates/xerj-autoindex/src/init.rs
+++ b/engine/crates/xerj-autoindex/src/init.rs
@@ -39,6 +39,11 @@ OPTIONS:
After init: restart the agent session so it picks up the new tools, then
`xerj autoindex <folder>` anything you want searchable.
+
+Auth: nothing secret is written (`.mcp.json` is meant to be committed). For a
+loopback node the MCP server reads <data-dir>/admin.key by itself and says so
+on stderr; for any other node add \"XERJ_AUTH\": \"ApiKey <key>\" to the env
+block — init prints which case you are in.
";
/// The ten-line teaching file. One idea per line, no filler: what the tools
@@ -247,6 +252,36 @@ pub(crate) fn run_init_in(cwd: &Path, url: &str, dry: bool) -> Result<Vec<String
}
}
+ // 5) Auth note — say plainly what will happen at tool-call time (#961).
+ //
+ // `.mcp.json` is Claude Code *project* scope, i.e. a file meant to be
+ // committed, so init deliberately writes no credential into it; auth is
+ // ON by default, and the gap between "ran xerj init" and "tools work"
+ // used to be a silent 401 on the first tool call. The MCP server now
+ // falls back to the local admin key for loopback nodes by itself; here
+ // 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() {
+ Some((_, path)) => out.push(format!(
+ " auth MCP authenticates with the admin key at {} (local node)",
+ path.display()
+ )),
+ None => out.push(
+ " auth no --auth given and no local admin key found; if the node at \
+ {url} runs with auth on, add \"XERJ_AUTH\": \"ApiKey <key>\" to the \
+ .mcp.json env — the key is the node's <data-dir>/admin.key"
+ .to_string(),
+ ),
+ }
+ } else {
+ out.push(format!(
+ " auth {url} is not local, so no admin key is auto-discovered for it; \
+ if the node runs with auth on, add \"XERJ_AUTH\": \"ApiKey <key>\" to \
+ the .mcp.json env — the key is the node's <data-dir>/admin.key"
+ ));
+ }
+
Ok(out)
}
@@ -302,7 +337,14 @@ mod tests {
let lines = run_init_in(d.path(), "http://x:1", false).unwrap();
let second = fs::read_to_string(d.path().join("AGENTS.md")).unwrap();
assert_eq!(first, second, "AGENTS.md must not grow on re-run");
- assert!(lines.iter().all(|l| l.contains("kept")), "{lines:?}");
+ // "kept" for every surface; the only other line init emits is the
+ // auth note (section 5), which rewrites nothing.
+ assert!(
+ lines
+ .iter()
+ .all(|l| l.contains("kept") || l.contains("auth")),
+ "{lines:?}"
+ );
}
#[test]
@@ -334,4 +376,107 @@ mod tests {
run_init_in(d.path(), "http://x:1", false).unwrap();
assert!(d.path().join(".cursor/rules/xerj.mdc").exists());
}
+
+ // ── auth note (#961) ────────────────────────────────────────────────
+
+ /// The auth note reads the working directory and `HOME` (that is what
+ /// admin-key discovery does), so its tests sandbox both — serialised,
+ /// because they are per-process state.
+ static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+ struct Sandbox {
+ _lock: std::sync::MutexGuard<'static, ()>,
+ dir: tempfile::TempDir,
+ previous_dir: PathBuf,
+ previous_home: Option<std::ffi::OsString>,
+ }
+
+ impl Sandbox {
+ fn new() -> Self {
+ let lock = ENV_LOCK.lock().unwrap_or_else(|poison| poison.into_inner());
+ let dir = tempfile::tempdir().unwrap();
+ let previous_dir = std::env::current_dir().unwrap();
+ let previous_home = std::env::var_os("HOME");
+ std::env::set_current_dir(dir.path()).unwrap();
+ std::env::set_var("HOME", dir.path().join("home"));
+ Self {
+ _lock: lock,
+ dir,
+ previous_dir,
+ previous_home,
+ }
+ }
+
+ fn write(&self, relative: &str, contents: &str) {
+ let path = self.dir.path().join(relative);
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(path, contents).unwrap();
+ }
+ }
+
+ impl Drop for Sandbox {
+ fn drop(&mut self) {
+ std::env::set_current_dir(&self.previous_dir).unwrap();
+ match &self.previous_home {
+ Some(home) => std::env::set_var("HOME", home),
+ None => std::env::remove_var("HOME"),
+ }
+ }
+ }
+
+ /// The happy path of #961: a local node's key exists, init says the MCP
+ /// server will use it — and the secret still goes nowhere near the
+ /// committable `.mcp.json`.
+ #[test]
+ fn auth_note_names_the_discovered_key_and_writes_no_secret() {
+ let sandbox = Sandbox::new();
+ sandbox.write("data/admin.key", "local-admin-key\n");
+ let lines = run_init_in(sandbox.dir.path(), "http://localhost:9200", false).unwrap();
+ assert!(
+ lines
+ .iter()
+ .any(|l| l.contains("admin key at") && l.ends_with("data/admin.key (local node)")),
+ "the note must name the file the MCP server will use: {lines:?}"
+ );
+ let mcp = fs::read_to_string(sandbox.dir.path().join(".mcp.json")).unwrap();
+ assert!(
+ !mcp.contains("local-admin-key") && !mcp.contains("XERJ_AUTH"),
+ "a credential must never be written into a committable file: {mcp}"
+ );
+ }
+
+ /// No key on disk: the note must say the manual step plainly instead of
+ /// letting the first tool call be the user's first 401.
+ #[test]
+ fn auth_note_gives_the_manual_step_when_no_key_exists() {
+ let sandbox = Sandbox::new();
+ let lines = run_init_in(sandbox.dir.path(), "http://localhost:9200", false).unwrap();
+ let note = lines
+ .iter()
+ .find(|l| l.contains("auth"))
+ .expect("the auth note is always present");
+ assert!(
+ note.contains("XERJ_AUTH") && note.contains("admin.key"),
+ "the fallback note must name the env var and the key file: {note}"
+ );
+ }
+
+ /// A non-loopback URL never triggers discovery, even with a local key
+ /// sitting right there — reading it would only encourage sending it
+ /// off-box.
+ #[test]
+ fn remote_url_gets_no_discovery_even_with_a_local_key_present() {
+ let sandbox = Sandbox::new();
+ sandbox.write("data/admin.key", "local-admin-key\n");
+ let lines =
+ run_init_in(sandbox.dir.path(), "http://search.example.com:9200", false).unwrap();
+ let note = lines
+ .iter()
+ .find(|l| l.contains("auth"))
+ .expect("the auth note is always present");
+ assert!(
+ note.contains("XERJ_AUTH") && !note.contains("admin key at"),
+ "a remote node gets the manual step, never a local key: {note}"
+ );
+ }
}
diff --git a/engine/crates/xerj-common/Cargo.toml b/engine/crates/xerj-common/Cargo.toml
index b729f08c7..34470983c 100644
--- a/engine/crates/xerj-common/Cargo.toml
+++ b/engine/crates/xerj-common/Cargo.toml
@@ -26,6 +26,12 @@ prometheus.workspace = true
# Machine probes for `resource`: sysconf/sysctl/setpriority. No abstraction
# layer buys anything here — the calls differ per platform by design.
libc = "0.2"
+# `localauth`: real URL parsing for the loopback guard. Already in the graph
+# via reqwest (which re-exports this exact type as `reqwest::Url`), so this
+# adds an edge, not a second URL parser. Hand-rolled host surgery is how the
+# `http://localhost:[email protected]/` userinfo leak happened — see
+# src/localauth.rs.
+url = "2"
[dev-dependencies]
tempfile.workspace = true
diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rs
index e6887a416..51092503b 100644
--- a/engine/crates/xerj-common/src/lib.rs
+++ b/engine/crates/xerj-common/src/lib.rs
@@ -23,12 +23,15 @@
//! - [`metrics`] — Prometheus counters, histograms, and gauges
//! - [`net`] — Network trust primitives (trusted-proxy CIDR matching)
//! - [`resource`] — The machine-resource policy: cores, memory budget, thread priority
+//! - [`localauth`] — Loopback guard + `<data_dir>/admin.key` discovery for
+//! same-machine CLI/MCP commands (`xerj mcp`, `xerj autoindex`, `xerj init`)
pub mod config;
pub mod error;
pub mod feedback;
pub mod field_coercion;
pub mod fsio;
+pub mod localauth;
pub mod metrics;
pub mod net;
pub mod resource;
diff --git a/engine/crates/xerj-common/src/localauth.rs b/engine/crates/xerj-common/src/localauth.rs
new file mode 100644
index 000000000..4f1635546
--- /dev/null
+++ b/engine/crates/xerj-common/src/localauth.rs
@@ -0,0 +1,102 @@
+//! Local admin-key discovery and the loopback guard that makes it safe.
+//!
+//! The shipped default config has `[auth] enabled = true`, and the server
+//! mints `<data_dir>/admin.key` on first start. Commands that talk to a
+//! node from the same machine (`xerj mcp`, `xerj autoindex`, `xerj init`'s
+//! advice) can read that file instead of demanding the user paste a key —
+//! but only when the target is provably loopback, because a locally
+//! readable key sent anywhere else is a credential leak, not a
+//! convenience.
+//!
+//! Both helpers started life in `xerj-autoindex/src/cli.rs` (the autoindex
+//! 401 fix); `xerj mcp` hit the identical failure mode (#961), so they
+//! moved here rather than being duplicated. The invariants live with the
+//! tests in `xerj-autoindex` (`url_is_loopback_is_true_only_for_this_machine`,
+//! `userinfo_cannot_disguise_a_remote_host_as_loopback`, and the
+//! `discover_local_admin_key` sandbox tests) — the calling crates keep
+//! wiring tests of their own.
+//!
+//! The URL parsing uses a real parser (`url::Url`, the same type reqwest
+//! re-exports) rather than string surgery, because the hand-rolled version
+//! of this was wrong in a way that leaked credentials: splitting on the
+//! last `:` treats the userinfo in `http://localhost:[email protected]/` as a
+//! host:port pair, judges it loopback, and sends the admin key to
+//! `evil.com`. `Url::host_str` resolves that to `evil.com`, which is the
+//! whole point of using it.
+
+use std::path::PathBuf;
+
+/// True when `url`'s host is this machine, so a locally readable admin key
+/// is the right credential to send. Anything else — a LAN address, a
+/// hostname, a remote deployment — must be given a key explicitly.
+pub fn url_is_loopback(url: &str) -> bool {
+ // A schemeless `localhost:9200` parses as scheme `localhost`, path `9200`,
+ // with no host at all, so retry those through `http://`. The retry still
+ // goes through the parser: `localhost:[email protected]` becomes
+ // `http://localhost:[email protected]`, whose host is `evil.com`, not loopback.
+ let parsed = match url::Url::parse(url) {
+ Ok(u) if matches!(u.scheme(), "http" | "https") => u,
+ _ => match url::Url::parse(&format!("http://{url}")) {
+ Ok(u) => u,
+ // Unparseable is not loopback. Failing closed here costs a user
+ // with an exotic URL one explicit --api-key; failing open costs
+ // them the key itself.
+ Err(_) => return false,
+ },
+ };
+ match parsed.host_str() {
+ // `host_str` strips the brackets from `[::1]` and does not lowercase
+ // an IPv6 literal, so compare case-insensitively and cover both forms.
+ Some(h) => {
+ let h = h.trim_start_matches('[').trim_end_matches(']');
+ h.eq_ignore_ascii_case("localhost") || h == "127.0.0.1" || h == "::1" || h == "0.0.0.0"
+ }
+ None => false,
+ }
+}
+
+/// The admin key a local server wrote for itself, if we can find it.
+///
+/// Checked in the order a user is most likely to have created them: the
+/// working directory's data dir (what the quickstart tells you to use), then
+/// the documented package install location. Absent or unreadable is not an
+/// error — the caller falls back to the actionable 401 message.
+///
+/// Returns the bare key (trimmed) and the file it came from, so the caller
+/// can announce the path — never silently — and format the header per its
+/// own wire convention (`ApiKey <key>`). Relative candidates are resolved
+/// 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.
+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.
+ const CANDIDATES: &[&str] = &[
+ "data/admin.key",
+ "xerj-data/admin.key",
+ "/var/lib/xerj/admin.key",
+ ];
+ let cwd = std::env::current_dir().ok();
+ let mut paths: Vec<PathBuf> = CANDIDATES
+ .iter()
+ .map(|c| {
+ let p = PathBuf::from(c);
+ match (&cwd, p.is_absolute()) {
+ (Some(cwd), false) => cwd.join(p),
+ _ => p,
+ }
+ })
+ .collect();
+ if let Some(home) = std::env::var_os("HOME") {
+ paths.push(PathBuf::from(&home).join(".xerj/brain/admin.key"));
+ paths.push(PathBuf::from(&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))
+ })
+}
diff --git a/engine/crates/xerj-mcp/Cargo.toml b/engine/crates/xerj-mcp/Cargo.toml
index 939c338e6..4da38292a 100644
--- a/engine/crates/xerj-mcp/Cargo.toml
+++ b/engine/crates/xerj-mcp/Cargo.toml
@@ -38,3 +38,9 @@ xerj-common = { path = "../xerj-common" }
# ceilings and the builder refuses exactly what the node would refuse — the
# two cannot drift. A light leaf: it adds no dependency this crate lacks.
xerj-rerank = { path = "../xerj-rerank" }
+
+[dev-dependencies]
+# The loopback admin-key fallback tests sandbox cwd + HOME so discovery sees
+# only the key files the test wrote (same pattern as xerj-autoindex's cli
+# tests, where the helper was born).
+tempfile = { workspace = true }
diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rs
index e2b71a691..d0061fac4 100644
--- a/engine/crates/xerj-mcp/src/lib.rs
+++ b/engine/crates/xerj-mcp/src/lib.rs
@@ -60,6 +60,15 @@
//! * `XERJ_AUTH` — optional; if set, sent verbatim as the `Authorization`
//! header on every proxied request (e.g. `ApiKey <token>`).
//!
+//! When neither `XERJ_AUTH` nor `--auth` is given **and** the target is
+//! loopback, the server falls back to the admin key a local node wrote for
+//! itself (`<data_dir>/admin.key` — the same discovery `xerj autoindex`
+//! uses) and announces the file it used on stderr. Auth is on by default, so
+//! this fallback is what makes the documented `xerj init` one-command setup
+//! work against a default node instead of 401-ing on every tool call (#961).
+//! It never fires for a non-loopback URL: a locally readable key sent to
+//! another host is a credential leak, not a convenience.
+//!
//! Both have a flag form — `--url` and `--auth` — which wins over the
//! environment. MCP client configs usually set the `env` block, so the
//! environment stays the documented path; the flags exist for hosts that only
@@ -132,6 +141,9 @@ default is ~/.local/bin/xerj. An MCP host launched from a desktop icon does
not inherit your shell's PATH, so a bare \"xerj\" fails there with no useful
error. When the node is not running --insecure, add
\"XERJ_AUTH\": \"ApiKey <key>\" beside XERJ_URL; the key is <data-dir>/admin.key.
+For a loopback node (localhost / 127.0.0.1 / [::1]) that step is optional:
+with no XERJ_AUTH given, the server reads <data-dir>/admin.key itself (the
+same locations `xerj autoindex` checks) and says which file on stderr.
Diagnostics go to stderr; stdout carries only the JSON-RPC stream.
";
@@ -152,6 +164,46 @@ pub fn help_text(feedback: bool) -> String {
)
}
+/// Resolve the `Authorization` header value every proxied request will carry.
+///
+/// Precedence: `--auth` > `XERJ_AUTH` >, for a loopback base URL only, the
+/// admin key a local node wrote for itself. The fallback exists because auth
+/// is ON by default and `xerj init` deliberately writes no credential into
+/// `.mcp.json` (project scope, meant to be committed) — without it, the
+/// documented one-command setup 401s on every tool call (#961).
+///
+/// Returns the header value plus, when the value came from disk, the file it
+/// came from — the caller announces that path on stderr so the fallback is
+/// never silent (stdout stays JSON-RPC-only).
+///
+/// The loopback guard is the security boundary: discovery only ever runs for
+/// a URL whose host is this machine, so a locally readable key can never be
+/// sent off-box (including via the `http://localhost:[email protected]/` userinfo
+/// trick — see `xerj_common::localauth`).
+fn resolve_auth(
+ auth_override: Option<String>,
+ env_auth: Option<String>,
+ base_url: &str,
+) -> (Option<String>, Option<std::path::PathBuf>) {
+ // Empty strings count as unset: an empty XERJ_AUTH in a committed
+ // .mcp.json must not shadow discovery and turn into `Authorization: `.
+ if let Some(explicit) = auth_override
+ .filter(|s| !s.is_empty())
+ .or_else(|| env_auth.filter(|s| !s.is_empty()))
+ {
+ return (Some(explicit), None);
+ }
+ if !xerj_common::localauth::url_is_loopback(base_url) {
+ return (None, None);
+ }
+ match xerj_common::localauth::discover_local_admin_key() {
+ // `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)),
+ None => (None, None),
+ }
+}
+
/// Library entry point. `args` are the arguments *after* the subcommand
/// (`xerj mcp <args>`) or after the program name (`xerj-mcp <args>`).
///
@@ -205,9 +257,8 @@ pub async fn run(args: &[String]) -> anyhow::Result<()> {
.unwrap_or_else(|| DEFAULT_XERJ_URL.to_string())
.trim_end_matches('/')
.to_string();
- let auth = auth_override
- .or_else(|| std::env::var("XERJ_AUTH").ok())
- .filter(|s| !s.is_empty());
+ let (auth, auth_key_file) =
+ resolve_auth(auth_override, std::env::var("XERJ_AUTH").ok(), &base_url);
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(30))
@@ -225,6 +276,17 @@ pub async fn run(args: &[String]) -> anyhow::Result<()> {
ctx.base_url
);
+ // Announced, never silent (same rule as `xerj autoindex`): MCP hosts
+ // spawn this server with an arbitrary cwd, so which `admin.key` the
+ // relative candidates resolved to is exactly the thing an onboarding
+ // user needs to see when it works here and not there.
+ if let Some(path) = auth_key_file {
+ eprintln!(
+ "xerj-mcp: no --auth/XERJ_AUTH given; using the admin key at {}",
+ path.display()
+ );
+ }
+
// stdout is the JSON-RPC channel; stderr is for logs only.
let mut lines = BufReader::new(tokio::io::stdin()).lines();
let mut stdout = tokio::io::stdout();
@@ -1776,4 +1838,153 @@ mod tests {
);
}
}
+
+ // ── loopback admin-key fallback (#961) ──────────────────────────────
+
+ /// Serialises the tests that move process-global state. Discovery reads
+ /// the working directory and `HOME`, both per-process.
+ static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+ /// A temporary working directory and `HOME`, restored on drop (including
+ /// on panic) so the discovery tests see only the key files they wrote —
+ /// the same sandbox shape as `xerj-autoindex`'s cli tests, where the
+ /// helper this exercises was born.
+ struct Sandbox {
+ _lock: std::sync::MutexGuard<'static, ()>,
+ dir: tempfile::TempDir,
+ previous_dir: std::path::PathBuf,
+ previous_home: Option<std::ffi::OsString>,
+ }
+
+ impl Sandbox {
+ fn new() -> Self {
+ let lock = ENV_LOCK.lock().unwrap_or_else(|poison| poison.into_inner());
+ let dir = tempfile::tempdir().unwrap();
+ let previous_dir = std::env::current_dir().unwrap();
+ let previous_home = std::env::var_os("HOME");
+ std::env::set_current_dir(dir.path()).unwrap();
+ std::env::set_var("HOME", dir.path().join("home"));
+ Self {
+ _lock: lock,
+ dir,
+ previous_dir,
+ previous_home,
+ }
+ }
+
+ fn write(&self, relative: &str, contents: &str) {
+ let path = self.dir.path().join(relative);
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(path, contents).unwrap();
+ }
+ }
+
+ impl Drop for Sandbox {
+ fn drop(&mut self) {
+ std::env::set_current_dir(&self.previous_dir).unwrap();
+ match &self.previous_home {
+ Some(home) => std::env::set_var("HOME", home),
+ None => std::env::remove_var("HOME"),
+ }
+ }
+ }
+
+ /// The gap #961 is about: `xerj init` writes only XERJ_URL, auth is on by
+ /// default, and the documented setup 401'd on every tool call. With a
+ /// loopback URL and a key on disk, discovery closes that gap.
+ #[test]
+ fn loopback_url_with_no_auth_picks_up_the_local_admin_key() {
+ let sandbox = Sandbox::new();
+ sandbox.write("data/admin.key", "local-admin-key\n");
+ let (auth, from) = resolve_auth(None, None, "http://localhost:9200");
+ assert_eq!(auth.as_deref(), Some("ApiKey local-admin-key"));
+ assert_eq!(
+ from,
+ Some(sandbox.dir.path().join("data/admin.key")),
+ "the announced path is the file actually used"
+ );
+
+ // The no-configuration shape: XERJ_URL unset means the loopback
+ // default, which is exactly the `xerj init` entry.
+ let (auth, _) = resolve_auth(None, None, DEFAULT_XERJ_URL);
+ assert_eq!(auth.as_deref(), Some("ApiKey local-admin-key"));
+ }
+
+ /// Discovery is loopback-only. A locally readable admin key sent to a
+ /// host that did not write it is a credential leak — including via the
+ /// userinfo trick, where everything before `@` is credentials and the
+ /// host is `evil.com`.
+ #[test]
+ fn non_loopback_urls_never_receive_a_discovered_key() {
+ let sandbox = Sandbox::new();
+ sandbox.write("data/admin.key", "local-admin-key\n");
+ for url in [
+ "http://search.example.com:9200",
+ "http://192.168.1.5:9200",
+ "https://localhost.evil.com:9200",
+ "http://localhost:[email protected]/",
+ "http://127.0.0.1:[email protected]/",
+ "localhost:[email protected]",
+ ] {
+ let (auth, from) = resolve_auth(None, None, url);
+ assert!(
+ auth.is_none() && from.is_none(),
+ "{url} must never be sent a key found on this disk"
+ );
+ }
+ }
+
+ /// A credential the user supplied is never overwritten by one found on
+ /// disk — and an *empty* value is unset, not a credential: shadowing
+ /// discovery with `Authorization: ` would reproduce the silent 401.
+ #[test]
+ fn explicit_auth_wins_over_loopback_discovery() {
+ let sandbox = Sandbox::new();
+ sandbox.write("data/admin.key", "local-admin-key\n");
+
+ let (auth, from) = resolve_auth(
+ Some("Bearer token".into()),
+ Some("ApiKey env".into()),
+ "http://localhost:9200",
+ );
+ assert_eq!(auth.as_deref(), Some("Bearer token"));
+ assert!(
+ from.is_none(),
+ "an explicit --auth is never re-sourced from disk"
+ );
+
+ let (auth, from) = resolve_auth(None, Some("ApiKey env".into()), "http://localhost:9200");
+ assert_eq!(auth.as_deref(), Some("ApiKey env"));
+ assert!(from.is_none(), "XERJ_AUTH also wins over discovery");
+
+ let (auth, _) = resolve_auth(Some(String::new()), None, "http://localhost:9200");
+ assert_eq!(
+ auth.as_deref(),
+ Some("ApiKey local-admin-key"),
+ "an empty --auth/XERJ_AUTH must fall through to discovery"
+ );
+ }
+
+ /// A server that has not finished writing its key, or a file truncated
+ /// by hand, must not become `Authorization: ApiKey ` — the same 401 with
+ /// none of the diagnosis.
+ #[test]
+ fn empty_key_files_are_skipped_not_turned_into_empty_headers() {
+ let sandbox = Sandbox::new();
+ sandbox.write("data/admin.key", " \n\t\n");
+ sandbox.write("xerj-data/admin.key", "");
+ let (auth, from) = resolve_auth(None, None, "http://localhost:9200");
+ assert!(
+ auth.is_none() && from.is_none(),
+ "whitespace-only and zero-byte files are not credentials"
+ );
+
+ sandbox.write("home/.xerj/admin.key", "real-key\n");
+ let (auth, _) = resolve_auth(None, None, "http://localhost:9200");
+ assert_eq!(
+ auth.as_deref(),
+ Some("ApiKey real-key"),
+ "an empty candidate must be skipped over, not stop the search"
+ );
+ }
}
diff --git a/landing/docs/cli.html b/landing/docs/cli.html
index 3efac9996..43381ad90 100644
--- a/landing/docs/cli.html
+++ b/landing/docs/cli.html
@@ -311,7 +311,7 @@ OPTIONS:
}
}</pre>
- <p>Use an <em>absolute</em> path — the installer puts <code class="inline">xerj</code> in <code class="inline">~/.local/bin</code> by default (<code class="inline">command -v xerj</code> confirms), and an MCP host launched from a desktop icon does not inherit your shell's <code class="inline">PATH</code>. When the node is not running <code class="inline">--insecure</code>, add <code class="inline">"XERJ_AUTH": "ApiKey &lt;key&gt;"</code> next to <code class="inline">XERJ_URL</code>; the key lives in <code class="inline">&lt;data-dir&gt;/admin.key</code>.</p>
+ <p>Use an <em>absolute</em> path — the installer puts <code class="inline">xerj</code> in <code class="inline">~/.local/bin</code> by default (<code class="inline">command -v xerj</code> confirms), and an MCP host launched from a desktop icon does not inherit your shell's <code class="inline">PATH</code>. When the node is not running <code class="inline">--insecure</code>, add <code class="inline">"XERJ_AUTH": "ApiKey &lt;key&gt;"</code> next to <code class="inline">XERJ_URL</code>; the key lives in <code class="inline">&lt;data-dir&gt;/admin.key</code>. For a loopback node that manual step is optional: with no <code class="inline">XERJ_AUTH</code> given, the server reads <code class="inline">&lt;data-dir&gt;/admin.key</code> itself (the same locations <code class="inline">xerj autoindex</code> checks) and announces the file it used on stderr — it never does this for a non-loopback URL.</p>
<p>Ten tools are served, each a thin proxy over an endpoint the engine already exposes — nothing is added, and engine errors come back verbatim: <code class="inline">xerj_search</code>, <code class="inline">xerj_semantic_search</code>, <code class="inline">xerj_vector_search</code>, <code class="inline">xerj_hybrid_search</code>, <code class="inline">xerj_memory_store</code>, <code class="inline">xerj_memory_recall</code>, <code class="inline">xerj_brain_overview</code>, <code class="inline">xerj_brain_ego</code>, <code class="inline">xerj_brain_link</code>, <code class="inline">xerj_brain_unlink</code>. Two caveats the tool descriptions carry themselves: <code class="inline">xerj_semantic_search</code> embeds server-side with the <em>lexical</em> feature-hashing embedder unless the node runs <code class="inline">--embed-mode neural</code>, and the <code class="inline">xerj_brain_*</code> tools work a deterministic link index, not a graph database.</p>