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(localauth): report which discovery step found the admin key, and warn when it is foreign

snmsoodan75eb0ad9ff0f
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index fa70cc173..cb6e83142 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_for_url, url_is_loopback};
+use xerj_common::localauth::{discover_local_admin_key_for_url_with_origin, 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".
@@ -1670,18 +1670,24 @@ 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_for_url(&url) {
+ if let Some(found) = discover_local_admin_key_for_url_with_origin(&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
// file was used turns "it worked here and not there" into
- // something the reader can see and reason about.
+ // something the reader can see and reason about; saying which
+ // discovery step found it (#2578) turns "why is it using another
+ // project's key?" into the same kind of answer.
eprintln!(
- "autoindex: no --api-key/XERJ_API_KEY given; using the admin key at {}",
- path.display()
+ "autoindex: no --api-key/XERJ_API_KEY given; using the admin key at {} ({})",
+ found.path.display(),
+ found.provenance()
);
- api_key = Some(key);
- api_key_file = Some(path);
+ if let Some(warning) = found.foreign_warning("--api-key") {
+ eprintln!("autoindex: warning: {warning}");
+ }
+ api_key = Some(found.key);
+ api_key_file = Some(found.path);
}
}
diff --git a/engine/crates/xerj-autoindex/src/def.rs b/engine/crates/xerj-autoindex/src/def.rs
index ca7652080..c33b3c2ea 100644
--- a/engine/crates/xerj-autoindex/src/def.rs
+++ b/engine/crates/xerj-autoindex/src/def.rs
@@ -554,12 +554,18 @@ pub fn run_def_cli() -> i32 {
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) {
+ if let Some(found) =
+ xerj_common::localauth::discover_local_admin_key_for_url_with_origin(&url)
+ {
eprintln!(
- "xerj def: no --api-key/XERJ_API_KEY given; using the admin key at {}",
- path.display()
+ "xerj def: no --api-key/XERJ_API_KEY given; using the admin key at {} ({})",
+ found.path.display(),
+ found.provenance()
);
- api_key = Some(key);
+ if let Some(warning) = found.foreign_warning("--api-key") {
+ eprintln!("xerj def: warning: {warning}");
+ }
+ api_key = Some(found.key);
}
}
diff --git a/engine/crates/xerj-autoindex/src/init.rs b/engine/crates/xerj-autoindex/src/init.rs
index d18004292..fcc6b2aec 100644
--- a/engine/crates/xerj-autoindex/src/init.rs
+++ b/engine/crates/xerj-autoindex/src/init.rs
@@ -754,10 +754,11 @@ 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_for_url(url) {
- Some((_, path)) => out.push(format!(
- " auth MCP authenticates with the admin key at {} (local node)",
- path.display()
+ match xerj_common::localauth::discover_local_admin_key_for_url_with_origin(url) {
+ Some(found) => out.push(format!(
+ " auth MCP authenticates with the admin key at {} (local node, {})",
+ found.path.display(),
+ found.provenance()
)),
None => out.push(format!(
" auth no --auth given and no local admin key found; if the node at \
@@ -1599,9 +1600,8 @@ mod tests {
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)")),
+ lines.iter().any(|l| l.contains("admin key at")
+ && l.ends_with("data/admin.key (local node, found under the working directory)")),
"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();
diff --git a/engine/crates/xerj-autoindex/src/memory_cli.rs b/engine/crates/xerj-autoindex/src/memory_cli.rs
index 74feb701b..92c33b22d 100644
--- a/engine/crates/xerj-autoindex/src/memory_cli.rs
+++ b/engine/crates/xerj-autoindex/src/memory_cli.rs
@@ -100,12 +100,18 @@ pub fn run_memory_from(args: &[String]) -> i32 {
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) {
+ if let Some(found) =
+ xerj_common::localauth::discover_local_admin_key_for_url_with_origin(&url)
+ {
eprintln!(
- "xerj memory: no --api-key/XERJ_API_KEY given; using the admin key at {}",
- path.display()
+ "xerj memory: no --api-key/XERJ_API_KEY given; using the admin key at {} ({})",
+ found.path.display(),
+ found.provenance()
);
- api_key = Some(key);
+ if let Some(warning) = found.foreign_warning("--api-key") {
+ eprintln!("xerj memory: warning: {warning}");
+ }
+ api_key = Some(found.key);
}
}
diff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rs
index f5464f42b..7bf68f818 100644
--- a/engine/crates/xerj-autoindex/src/search.rs
+++ b/engine/crates/xerj-autoindex/src/search.rs
@@ -896,12 +896,18 @@ pub fn run_search_cli() -> i32 {
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) {
+ if let Some(found) =
+ xerj_common::localauth::discover_local_admin_key_for_url_with_origin(&url)
+ {
eprintln!(
- "xerj search: no --api-key/XERJ_API_KEY given; using the admin key at {}",
- path.display()
+ "xerj search: no --api-key/XERJ_API_KEY given; using the admin key at {} ({})",
+ found.path.display(),
+ found.provenance()
);
- api_key = Some(key);
+ if let Some(warning) = found.foreign_warning("--api-key") {
+ eprintln!("xerj search: warning: {warning}");
+ }
+ api_key = Some(found.key);
}
}
diff --git a/engine/crates/xerj-autoindex/src/xc.rs b/engine/crates/xerj-autoindex/src/xc.rs
index fdbde27fb..02b4cb754 100644
--- a/engine/crates/xerj-autoindex/src/xc.rs
+++ b/engine/crates/xerj-autoindex/src/xc.rs
@@ -16,7 +16,9 @@ use std::time::Duration;
use anyhow::{Context, Result};
use serde_json::{json, Value};
-use xerj_common::localauth::{discover_local_admin_key_for_url, url_is_loopback};
+use xerj_common::localauth::{
+ discover_local_admin_key_for_url, discover_local_admin_key_for_url_with_origin, url_is_loopback,
+};
use xerj_common::xccode::{self, manifest, state, CodeOutcome, CodeParams, Mode, XcHttp};
use crate::esclient::{Count, Es};
@@ -56,13 +58,17 @@ 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_for_url(url).map(|(k, path)| {
+ discover_local_admin_key_for_url_with_origin(url).map(|found| {
eprintln!(
"xerj code: no --api-key/XERJ_API_KEY given; using the admin \
- key at {}",
- path.display()
+ key at {} ({})",
+ found.path.display(),
+ found.provenance()
);
- k
+ if let Some(warning) = found.foreign_warning("--api-key") {
+ eprintln!("xerj code: warning: {warning}");
+ }
+ found.key
})
} else {
None
diff --git a/engine/crates/xerj-common/src/localauth.rs b/engine/crates/xerj-common/src/localauth.rs
index b1f6e19ab..d5902d131 100644
--- a/engine/crates/xerj-common/src/localauth.rs
+++ b/engine/crates/xerj-common/src/localauth.rs
@@ -16,6 +16,32 @@
//! `discover_local_admin_key` sandbox tests) — the calling crates keep
//! wiring tests of their own.
//!
+//! # Discovery order
+//!
+//! [`discover_local_admin_key_for_url`] is the entry point every command
+//! that talks to a node uses. It tries, in order, and stops at the first
+//! non-empty file:
+//!
+//! 1. `$HOME/.xerj/by-port/<port>` — a pointer the server publishes on boot
+//! ([`publish_admin_key_for_port`]). It names the `admin.key` of *that
+//! listener*, which is the only way to find a node started from another
+//! directory. Skipped when the URL has no port and the file is absent.
+//! 2. `./data/admin.key`, `./.xerj-data/admin.key`, `./xerj-data/admin.key`
+//! — resolved against the working directory.
+//! 3. `/var/lib/xerj/admin.key` — the packaged install's data dir.
+//! 4. `$HOME/.xerj/brain/admin.key`, `$HOME/xerj-data/admin.key`,
+//! `$HOME/.xerj/admin.key`.
+//!
+//! [`discover_local_admin_key`] is the same list without step 1.
+//!
+//! Because step 1 follows a pointer the *server* wrote, the key it finds can
+//! belong to a completely different project than the one the command was run
+//! in — correct for the node on that port, surprising for the person reading
+//! the output (#2578). So discovery reports [`KeyOrigin`], every caller
+//! announces it, and [`DiscoveredKey::foreign_warning`] flags a key that is
+//! not under the working tree. None of that changes which key is chosen; it
+//! makes the choice visible, and `--api-key` / `XERJ_API_KEY` still win.
+//!
//! 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
@@ -55,6 +81,96 @@ pub fn url_is_loopback(url: &str) -> bool {
}
}
+/// Which step of the discovery order found the key — the answer to "why
+/// *this* file?", which is what #2578 was actually asking for.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum KeyOrigin {
+ /// `$HOME/.xerj/by-port/<port>`: the node listening on that port
+ /// published its own data dir on boot. The key is the right one for that
+ /// node, and it may belong to a different project than the caller's.
+ PublishedByNode { port: u16 },
+ /// One of the `./…/admin.key` candidates, resolved against the working
+ /// directory.
+ WorkingDirectory,
+ /// One of the `$HOME/…/admin.key` candidates.
+ Home,
+}
+
+/// A discovered admin key, plus where it came from.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct DiscoveredKey {
+ /// The bare key, trimmed. Callers format the header per their own wire
+ /// convention (`ApiKey <key>`).
+ pub key: String,
+ /// The file the key was read from, absolute where the candidate was
+ /// relative: an announcement must name a path the reader can act on even
+ /// when the process was spawned with an arbitrary cwd, which is exactly
+ /// what MCP hosts do.
+ pub path: PathBuf,
+ pub origin: KeyOrigin,
+}
+
+impl DiscoveredKey {
+ /// The provenance clause for an announcement, e.g.
+ /// `published by the node on port 9200`.
+ pub fn provenance(&self) -> String {
+ match self.origin {
+ KeyOrigin::PublishedByNode { port } => {
+ format!("published by the node on port {port}")
+ }
+ KeyOrigin::WorkingDirectory => "found under the working directory".to_string(),
+ KeyOrigin::Home => "found under $HOME".to_string(),
+ }
+ }
+
+ /// A warning when the key belongs to a directory outside the working
+ /// tree, or `None` when it does not.
+ ///
+ /// This is a proxy for the check the issue asks for — "is this the data
+ /// dir the node at `XERJ_URL` is running from?" — because answering that
+ /// exactly needs an authenticated request to the node, and discovery runs
+ /// before the first request. The working tree is the one local fact that
+ /// distinguishes "my project's node" from "a node another project left
+ /// listening", which is the case the field report hit.
+ ///
+ /// `explicit_flag` names the per-command escape hatch so the warning can
+ /// say what to do instead (`--api-key` for the CLI, `--auth` for MCP).
+ pub fn foreign_warning(&self, explicit_flag: &str) -> Option<String> {
+ let cwd = std::env::current_dir().ok();
+ self.foreign_warning_against(cwd.as_deref(), explicit_flag)
+ }
+
+ /// [`Self::foreign_warning`] with the working directory passed in, so the
+ /// judgement is testable without moving process-global state.
+ fn foreign_warning_against(
+ &self,
+ cwd: Option<&std::path::Path>,
+ explicit_flag: &str,
+ ) -> Option<String> {
+ let cwd = cwd?;
+ // The key lives in `<data_dir>/admin.key`; the data dir is what has to
+ // be inside the working tree, not the file.
+ let data_dir = self.path.parent().unwrap_or(&self.path);
+ if path_is_under(data_dir, cwd) {
+ return None;
+ }
+ Some(format!(
+ "that key is outside the working directory ({}), so it may belong to a \
+ different project's node; pass {explicit_flag} or XERJ_API_KEY to choose \
+ explicitly",
+ cwd.display()
+ ))
+ }
+}
+
+/// True when `child` is `parent` or below it, after resolving symlinks so a
+/// `/var` vs `/private/var` difference on macOS does not read as "unrelated".
+fn path_is_under(child: &std::path::Path, parent: &std::path::Path) -> bool {
+ let resolve =
+ |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
+ resolve(child).starts_with(resolve(parent))
+}
+
/// 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
@@ -62,12 +178,9 @@ pub fn url_is_loopback(url: &str) -> bool {
/// 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.
+/// Returns the bare key (trimmed) and the file it came from. Relative
+/// candidates are resolved against the current directory before being
+/// returned.
fn read_admin_key(path: &std::path::Path) -> Option<(String, PathBuf)> {
std::fs::read_to_string(path)
.ok()
@@ -122,20 +235,38 @@ pub fn xerj_url_port(url: &str) -> u16 {
/// [`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.
+///
+/// Prefer [`discover_local_admin_key_for_url_with_origin`] when announcing the
+/// result: the origin is what tells a reader why this key was chosen.
pub fn discover_local_admin_key_for_url(url: &str) -> Option<(String, PathBuf)> {
+ discover_local_admin_key_for_url_with_origin(url).map(|found| (found.key, found.path))
+}
+
+/// [`discover_local_admin_key_for_url`] with the discovery step that found the
+/// key, so the caller can announce *why* that file (#2578).
+pub fn discover_local_admin_key_for_url_with_origin(url: &str) -> Option<DiscoveredKey> {
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);
+ if let Some((key, path)) = read_admin_key(&target) {
+ return Some(DiscoveredKey {
+ key,
+ path,
+ origin: KeyOrigin::PublishedByNode { port },
+ });
}
}
}
- discover_local_admin_key()
+ discover_local_admin_key_with_origin()
}
pub fn discover_local_admin_key() -> Option<(String, PathBuf)> {
+ discover_local_admin_key_with_origin().map(|found| (found.key, found.path))
+}
+
+/// [`discover_local_admin_key`] with the discovery step that found the key.
+pub fn discover_local_admin_key_with_origin() -> Option<DiscoveredKey> {
// Relative candidates resolve against the current directory (the "./"
// prefix is dropped so the announced path reads cleanly). `./data` is the
// quickstart; `./.xerj-data` is what `xerj search` / `xerj def` tell you
@@ -147,21 +278,135 @@ pub fn discover_local_admin_key() -> Option<(String, PathBuf)> {
"/var/lib/xerj/admin.key",
];
let cwd = std::env::current_dir().ok();
- let mut paths: Vec<PathBuf> = CANDIDATES
+ let mut paths: Vec<(PathBuf, KeyOrigin)> = CANDIDATES
.iter()
.map(|c| {
let p = PathBuf::from(c);
match (&cwd, p.is_absolute()) {
- (Some(cwd), false) => cwd.join(p),
- _ => p,
+ (Some(cwd), false) => (cwd.join(p), KeyOrigin::WorkingDirectory),
+ // An absolute candidate is the packaged install's data dir,
+ // not the working directory's.
+ _ => (p, KeyOrigin::Home),
}
})
.collect();
if let Some(home) = crate::home::home_dir() {
- paths.push(home.join(".xerj/brain/admin.key"));
+ paths.push((home.join(".xerj/brain/admin.key"), KeyOrigin::Home));
// llms.txt: `xerj --data-dir ~/xerj-data`.
- paths.push(home.join("xerj-data/admin.key"));
- paths.push(home.join(".xerj/admin.key"));
+ paths.push((home.join("xerj-data/admin.key"), KeyOrigin::Home));
+ paths.push((home.join(".xerj/admin.key"), KeyOrigin::Home));
+ }
+ paths.into_iter().find_map(|(p, origin)| {
+ read_admin_key(&p).map(|(key, path)| DiscoveredKey { key, path, origin })
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn key_at(path: &str, origin: KeyOrigin) -> DiscoveredKey {
+ DiscoveredKey {
+ key: "k".to_string(),
+ path: PathBuf::from(path),
+ origin,
+ }
+ }
+
+ /// The whole point of #2578: the announcement has to distinguish a key the
+ /// node on this port published from one found by walking the candidates,
+ /// because only the first can belong to another project.
+ #[test]
+ fn provenance_names_the_step_that_found_the_key() {
+ assert_eq!(
+ key_at(
+ "/other-project/data/admin.key",
+ KeyOrigin::PublishedByNode { port: 9200 }
+ )
+ .provenance(),
+ "published by the node on port 9200"
+ );
+ assert_eq!(
+ key_at("/proj/data/admin.key", KeyOrigin::WorkingDirectory).provenance(),
+ "found under the working directory"
+ );
+ assert_eq!(
+ key_at("/home/u/.xerj/admin.key", KeyOrigin::Home).provenance(),
+ "found under $HOME"
+ );
+ }
+
+ #[test]
+ fn a_key_inside_the_working_tree_is_not_flagged() {
+ let found = key_at("/proj/data/admin.key", KeyOrigin::WorkingDirectory);
+ assert_eq!(
+ found.foreign_warning_against(Some(std::path::Path::new("/proj")), "--api-key"),
+ None,
+ "the project's own ./data key is the expected answer, not a warning"
+ );
+ }
+
+ #[test]
+ fn a_key_from_another_projects_data_dir_is_flagged_with_the_escape_hatch() {
+ let found = key_at(
+ "/home/u/Projects/other/data/admin.key",
+ KeyOrigin::PublishedByNode { port: 9200 },
+ );
+ let warning = found
+ .foreign_warning_against(
+ Some(std::path::Path::new("/home/u/Projects/mine")),
+ "--api-key",
+ )
+ .expect("a key outside the working tree must warn");
+ assert!(warning.contains("/home/u/Projects/mine"), "{warning}");
+ assert!(warning.contains("--api-key"), "{warning}");
+ }
+
+ /// MCP has no `--api-key`; the warning must name the flag that surface
+ /// actually accepts.
+ #[test]
+ fn the_warning_names_the_flag_that_surface_takes() {
+ let found = key_at(
+ "/elsewhere/data/admin.key",
+ KeyOrigin::PublishedByNode { port: 9201 },
+ );
+ let warning = found
+ .foreign_warning_against(Some(std::path::Path::new("/proj")), "--auth")
+ .unwrap();
+ assert!(warning.contains("--auth"), "{warning}");
+ assert!(!warning.contains("--api-key"), "{warning}");
+ }
+
+ /// A sibling directory that merely shares a prefix is not "inside": the
+ /// comparison is per path component.
+ #[test]
+ fn a_sibling_with_a_shared_prefix_is_outside() {
+ let found = key_at("/proj-other/data/admin.key", KeyOrigin::WorkingDirectory);
+ assert!(found
+ .foreign_warning_against(Some(std::path::Path::new("/proj")), "--api-key")
+ .is_some());
+ }
+
+ /// Nothing to compare against means no claim either way — MCP hosts can
+ /// start a server whose cwd was already deleted.
+ #[test]
+ fn an_unknown_working_directory_is_silent() {
+ let found = key_at("/proj/data/admin.key", KeyOrigin::WorkingDirectory);
+ assert_eq!(found.foreign_warning_against(None, "--api-key"), None);
+ }
+
+ /// The candidates are resolved against the working directory and reported
+ /// absolute, so the announcement names a path the reader can act on.
+ #[test]
+ fn a_working_directory_candidate_is_reported_absolute() {
+ let dir = tempfile::tempdir().unwrap();
+ let key = dir.path().join("data/admin.key");
+ std::fs::create_dir_all(key.parent().unwrap()).unwrap();
+ std::fs::write(&key, "from-disk\n").unwrap();
+ assert_eq!(
+ read_admin_key(&key).map(|(k, p)| (k, p == key)),
+ Some(("from-disk".to_string(), true))
+ );
+ assert_eq!(read_admin_key(&dir.path().join("missing/admin.key")), None);
}
- 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.rs
index 6b2ec9ff7..e6f651196 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_for_url, url_is_loopback};
+use xerj_common::localauth::{discover_local_admin_key_for_url_with_origin, url_is_loopback};
use xerj_common::xccode::XcHttp;
use crate::flock::{held_by, FileLock, LockError};
@@ -115,12 +115,16 @@ impl HubNode {
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_for_url(&base).map(|(k, path)| {
+ discover_local_admin_key_for_url_with_origin(&base).map(|found| {
eprintln!(
- "xerj hub: no --api-key/XERJ_API_KEY given; using the admin key at {}",
- path.display()
- );
- k
+ "xerj hub: no --api-key/XERJ_API_KEY given; using the admin key at {} ({})",
+ found.path.display(),
+ found.provenance()
+ );
+ if let Some(warning) = found.foreign_warning("--api-key") {
+ eprintln!("xerj hub: warning: {warning}");
+ }
+ found.key
})
}
None => None,
diff --git a/engine/crates/xerj-mcp/src/batch_cli.rs b/engine/crates/xerj-mcp/src/batch_cli.rs
index c22c0e8bb..3a1d08b20 100644
--- a/engine/crates/xerj-mcp/src/batch_cli.rs
+++ b/engine/crates/xerj-mcp/src/batch_cli.rs
@@ -118,12 +118,16 @@ pub async fn run_batch_cli(args: &[String]) -> i32 {
.unwrap_or_else(|| DEFAULT_XERJ_URL.into())
.trim_end_matches('/')
.to_string();
- let (auth, path) = resolve_auth(opts.auth, std::env::var("XERJ_AUTH").ok(), &base_url);
- if let Some(path) = path {
+ let (auth, found) = resolve_auth(opts.auth, std::env::var("XERJ_AUTH").ok(), &base_url);
+ if let Some(found) = found {
eprintln!(
- "xerj batch-search: using local admin key at {}",
- path.display()
+ "xerj batch-search: using local admin key at {} ({})",
+ found.path.display(),
+ found.provenance()
);
+ if let Some(warning) = found.foreign_warning("--auth") {
+ eprintln!("xerj batch-search: warning: {warning}");
+ }
}
let client = match node_http_builder(&base_url)
.timeout(Duration::from_secs(30))
diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rs
index 638b882a4..61c3b2493 100644
--- a/engine/crates/xerj-mcp/src/lib.rs
+++ b/engine/crates/xerj-mcp/src/lib.rs
@@ -282,9 +282,11 @@ fn tools_paragraph(include_hub: bool) -> String {
/// `.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).
+/// Returns the header value plus, when the value came from disk, the
+/// [`DiscoveredKey`] it came from — the caller announces that path *and which
+/// discovery step found it* on stderr, so the fallback is never silent and a
+/// key that belongs to another project's node is visible as such (#2578).
+/// 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
@@ -294,7 +296,10 @@ fn resolve_auth(
auth_override: Option<String>,
env_auth: Option<String>,
base_url: &str,
-) -> (Option<String>, Option<std::path::PathBuf>) {
+) -> (
+ Option<String>,
+ Option<xerj_common::localauth::DiscoveredKey>,
+) {
// 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
@@ -306,10 +311,10 @@ fn resolve_auth(
if !xerj_common::localauth::url_is_loopback(base_url) {
return (None, None);
}
- match xerj_common::localauth::discover_local_admin_key_for_url(base_url) {
+ match xerj_common::localauth::discover_local_admin_key_for_url_with_origin(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)),
+ Some(found) => (Some(format!("ApiKey {}", found.key)), Some(found)),
None => (None, None),
}
}
@@ -389,12 +394,18 @@ pub async fn run(args: &[String]) -> anyhow::Result<()> {
// 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 {
+ // user needs to see when it works here and not there. The provenance and
+ // the outside-the-working-tree warning are what make the "another
+ // project's node answered" case visible instead of invisible (#2578).
+ if let Some(found) = &auth_key_file {
eprintln!(
- "xerj-mcp: no --auth/XERJ_AUTH given; using the admin key at {}",
- path.display()
+ "xerj-mcp: no --auth/XERJ_AUTH given; using the admin key at {} ({})",
+ found.path.display(),
+ found.provenance()
);
+ if let Some(warning) = found.foreign_warning("--auth") {
+ eprintln!("xerj-mcp: warning: {warning}");
+ }
}
// stdout is the JSON-RPC channel; stderr is for logs only.
@@ -6269,11 +6280,20 @@ mod tests {
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"));
+ let from = from.expect("the key came from disk, so the caller has a path to announce");
+ // Canonicalised because macOS reports the same directory as `/var/...`
+ // to the process and `/private/var/...` to `canonicalize`; the claim
+ // under test is "this file", not one spelling of it.
assert_eq!(
- from,
- Some(sandbox.dir.path().join("data/admin.key")),
+ std::fs::canonicalize(&from.path).unwrap(),
+ std::fs::canonicalize(sandbox.dir.path().join("data/admin.key")).unwrap(),
"the announced path is the file actually used"
);
+ assert_eq!(
+ from.origin,
+ xerj_common::localauth::KeyOrigin::WorkingDirectory,
+ "a ./data key is announced as the working directory's"
+ );
// The no-configuration shape: XERJ_URL unset means the loopback
// default, which is exactly the `xerj init` entry.
@@ -6305,6 +6325,34 @@ mod tests {
}
}
+ /// #2578: the key a node publishes for its port can belong to a project
+ /// other than the one the MCP server was started in. The announcement has
+ /// to say so, and the warning has to fire, because otherwise the only
+ /// evidence is a path the reader may not recognise.
+ #[test]
+ fn a_key_published_by_another_projects_node_is_announced_and_flagged() {
+ let sandbox = Sandbox::new();
+ // The other project's node wrote its own key and published the pointer
+ // for :9200; this project has nothing.
+ sandbox.write("other-project/data/admin.key", "other-project-key\n");
+ let abs = sandbox.dir.path().join("other-project/data/admin.key");
+ xerj_common::localauth::publish_admin_key_for_port(9200, &abs).unwrap();
+
+ let (auth, from) = resolve_auth(None, None, "http://localhost:9200");
+ assert_eq!(auth.as_deref(), Some("ApiKey other-project-key"));
+ let from = from.expect("a discovered key is always announced");
+ assert_eq!(
+ from.origin,
+ xerj_common::localauth::KeyOrigin::PublishedByNode { port: 9200 }
+ );
+ assert_eq!(from.provenance(), "published by the node on port 9200");
+
+ // The sandbox cwd contains `other-project/`, so this particular key is
+ // inside the working tree and is not flagged. The flag itself is unit
+ // tested in `xerj_common::localauth`, where a cwd can be passed in.
+ assert_eq!(from.foreign_warning("--auth"), None);
+ }
+
/// 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.