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.

Review local-auth provenance against the actual discovery paths and command environments

xerj-orga752be3e3076
diff --cc engine/crates/xerj-autoindex/src/cli.rs
index d3eee3e87,cb6e83142..b7aa4a9fa
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@@ -1675,13 -1675,19 +1675,19 @@@ pub fn parse(args: Vec<String>) -> Resu
// 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") {
++ if let Some(warning) = found.foreign_warning("--api-key or XERJ_API_KEY") {
+ eprintln!("autoindex: warning: {warning}");
+ }
+ api_key = Some(found.key);
+ api_key_file = Some(found.path);
}
}
diff --cc engine/crates/xerj-autoindex/src/def.rs
index ca7652080,c33b3c2ea..9c0639551
--- a/engine/crates/xerj-autoindex/src/def.rs
+++ b/engine/crates/xerj-autoindex/src/def.rs
@@@ -554,12 -554,18 +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") {
++ if let Some(warning) = found.foreign_warning("--api-key or XERJ_API_KEY") {
+ eprintln!("xerj def: warning: {warning}");
+ }
+ api_key = Some(found.key);
}
}
diff --cc engine/crates/xerj-autoindex/src/memory_cli.rs
index 74feb701b,92c33b22d..99d7298c4
--- a/engine/crates/xerj-autoindex/src/memory_cli.rs
+++ b/engine/crates/xerj-autoindex/src/memory_cli.rs
@@@ -100,12 -100,18 +100,18 @@@ pub fn run_memory_from(args: &[String]
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") {
++ if let Some(warning) = found.foreign_warning("--api-key or XERJ_API_KEY") {
+ eprintln!("xerj memory: warning: {warning}");
+ }
+ api_key = Some(found.key);
}
}
diff --cc engine/crates/xerj-autoindex/src/search.rs
index f5464f42b,7bf68f818..e22997d1b
--- a/engine/crates/xerj-autoindex/src/search.rs
+++ b/engine/crates/xerj-autoindex/src/search.rs
@@@ -896,12 -896,18 +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") {
++ if let Some(warning) = found.foreign_warning("--api-key or XERJ_API_KEY") {
+ eprintln!("xerj search: warning: {warning}");
+ }
+ api_key = Some(found.key);
}
}
diff --cc engine/crates/xerj-autoindex/src/xc.rs
index fdbde27fb,02b4cb754..ea72f340a
--- a/engine/crates/xerj-autoindex/src/xc.rs
+++ b/engine/crates/xerj-autoindex/src/xc.rs
@@@ -56,13 -58,17 +58,19 @@@ fn build_es(url: &str, api_key: Option<
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") {
++ if let Some(warning) =
++ found.foreign_warning("--api-key or XERJ_API_KEY")
++ {
+ eprintln!("xerj code: warning: {warning}");
+ }
+ found.key
})
} else {
None
diff --cc engine/crates/xerj-common/src/localauth.rs
index b1f6e19ab,d5902d131..0b3dc958b
--- a/engine/crates/xerj-common/src/localauth.rs
+++ b/engine/crates/xerj-common/src/localauth.rs
@@@ -16,6 -16,32 +16,33 @@@
//! `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.
++//! ([`publish_admin_key_for_port`]). It records the publishing node's
++//! `admin.key` path. The port comes from [`xerj_url_port`]; an absent or
++//! unreadable pointer falls through to the remaining candidates.
+ //! 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
++//! in. Packaged and home-directory keys may also be outside the project, and
++//! a pointer can outlive its node. Discovery therefore reports [`KeyOrigin`],
++//! without claiming that the named node is still listening. 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 +82,99 @@@ pub fn url_is_loopback(url: &str) -> bo
}
}
+ /// 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.
++ /// published its own data dir on boot. The pointer can outlive the node
++ /// and may name a different project than the caller's.
+ PublishedByNode { port: u16 },
+ /// One of the `./…/admin.key` candidates, resolved against the working
+ /// directory.
+ WorkingDirectory,
++ /// The packaged install at `/var/lib/xerj/admin.key`.
++ PackagedInstall,
+ /// 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::PackagedInstall => "found in the packaged installation".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> {
++ /// `explicit_auth` names the per-command flag and environment variable,
++ /// e.g. `--auth or XERJ_AUTH` for MCP.
++ pub fn foreign_warning(&self, explicit_auth: &str) -> Option<String> {
+ let cwd = std::env::current_dir().ok();
- self.foreign_warning_against(cwd.as_deref(), explicit_flag)
++ self.foreign_warning_against(cwd.as_deref(), explicit_auth)
+ }
+
+ /// [`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,
++ explicit_auth: &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 \
++ different project's node; pass {explicit_auth} 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
@@@ -136,32 -262,151 +266,217 @@@ pub fn discover_local_admin_key_for_url
}
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). `./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",
- ];
+ 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
- // 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",
- ];
let cwd = std::env::current_dir().ok();
- let mut paths: Vec<PathBuf> = CANDIDATES
++ let home = crate::home::home_dir();
++ local_admin_key_candidates(cwd.as_deref(), home.as_deref())
++ .into_iter()
++ .find_map(|(path, origin)| {
++ read_admin_key(&path).map(|(key, path)| DiscoveredKey { key, path, origin })
++ })
++}
++
++fn local_admin_key_candidates(
++ cwd: Option<&std::path::Path>,
++ home: Option<&std::path::Path>,
++) -> Vec<(PathBuf, KeyOrigin)> {
++ // Keep the existing discovery order and path resolution. The packaged
++ // installation has its own provenance even when no home is available.
++ const CANDIDATES: &[(&str, KeyOrigin)] = &[
++ ("data/admin.key", KeyOrigin::WorkingDirectory),
++ (".xerj-data/admin.key", KeyOrigin::WorkingDirectory),
++ ("xerj-data/admin.key", KeyOrigin::WorkingDirectory),
++ ("/var/lib/xerj/admin.key", KeyOrigin::PackagedInstall),
++ ];
+ 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),
-- }
++ .map(|(candidate, origin)| {
++ let path = PathBuf::from(candidate);
++ let path = match (cwd, path.is_absolute()) {
++ (Some(cwd), false) => cwd.join(path),
++ _ => path,
++ };
++ (path, *origin)
})
.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"));
++ if let Some(home) = home {
+ 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"), 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 })
- })
++ paths
+ }
+
+ #[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.
++ /// so a reader can distinguish the port pointer from fallback paths.
+ #[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 local_candidates_preserve_order_and_classify_the_packaged_install() {
++ let cwd = tempfile::tempdir().unwrap();
++ let home = tempfile::tempdir().unwrap();
++ let candidates = local_admin_key_candidates(Some(cwd.path()), Some(home.path()));
++ assert_eq!(candidates.len(), 7);
++ assert_eq!(
++ candidates[0],
++ (
++ cwd.path().join("data/admin.key"),
++ KeyOrigin::WorkingDirectory
++ )
++ );
++ assert_eq!(
++ candidates[1],
++ (
++ cwd.path().join(".xerj-data/admin.key"),
++ KeyOrigin::WorkingDirectory
++ )
++ );
++ assert_eq!(
++ candidates[2],
++ (
++ cwd.path().join("xerj-data/admin.key"),
++ KeyOrigin::WorkingDirectory
++ )
++ );
++ assert_eq!(candidates[3].1, KeyOrigin::PackagedInstall);
++ assert_eq!(
++ key_at("/var/lib/xerj/admin.key", candidates[3].1).provenance(),
++ "found in the packaged installation"
++ );
++ assert_eq!(
++ candidates[4],
++ (home.path().join(".xerj/brain/admin.key"), KeyOrigin::Home)
++ );
++ assert_eq!(
++ candidates[5],
++ (home.path().join("xerj-data/admin.key"), KeyOrigin::Home)
++ );
++ assert_eq!(
++ candidates[6],
++ (home.path().join(".xerj/admin.key"), KeyOrigin::Home)
++ );
++ let no_cwd = local_admin_key_candidates(None, None);
++ assert_eq!(no_cwd.len(), 4);
++ assert_eq!(no_cwd[0].1, KeyOrigin::WorkingDirectory);
++ assert_eq!(no_cwd[3].1, KeyOrigin::PackagedInstall);
++ }
++
+ #[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"),
++ found.foreign_warning_against(
++ Some(std::path::Path::new("/proj")),
++ "--api-key or XERJ_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",
++ "--api-key or XERJ_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}");
++ assert!(warning.contains("--api-key or XERJ_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")
++ .foreign_warning_against(Some(std::path::Path::new("/proj")), "--auth or XERJ_AUTH")
+ .unwrap();
- assert!(warning.contains("--auth"), "{warning}");
++ assert!(warning.contains("--auth or XERJ_AUTH"), "{warning}");
+ assert!(!warning.contains("--api-key"), "{warning}");
++ assert!(!warning.contains("XERJ_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")
++ .foreign_warning_against(
++ Some(std::path::Path::new("/proj")),
++ "--api-key or XERJ_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);
++ assert_eq!(
++ found.foreign_warning_against(None, "--api-key or XERJ_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 --cc engine/crates/xerj-hub/src/node.rs
index 6b2ec9ff7,e6f651196..3d5a8f9cf
--- a/engine/crates/xerj-hub/src/node.rs
+++ b/engine/crates/xerj-hub/src/node.rs
@@@ -115,12 -115,16 +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") {
++ if let Some(warning) = found.foreign_warning("--api-key or XERJ_API_KEY") {
+ eprintln!("xerj hub: warning: {warning}");
+ }
+ found.key
})
}
None => None,
diff --cc engine/crates/xerj-mcp/src/batch_cli.rs
index c22c0e8bb,3a1d08b20..4744cc9d6
--- a/engine/crates/xerj-mcp/src/batch_cli.rs
+++ b/engine/crates/xerj-mcp/src/batch_cli.rs
@@@ -118,12 -118,16 +118,16 @@@ pub async fn run_batch_cli(args: &[Stri
.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") {
++ if let Some(warning) = found.foreign_warning("--auth or XERJ_AUTH") {
+ eprintln!("xerj batch-search: warning: {warning}");
+ }
}
let client = match node_http_builder(&base_url)
.timeout(Duration::from_secs(30))
diff --cc engine/crates/xerj-mcp/src/lib.rs
index 0f5474078,61c3b2493..6a2c7b63c
--- a/engine/crates/xerj-mcp/src/lib.rs
+++ b/engine/crates/xerj-mcp/src/lib.rs
@@@ -282,9 -282,11 +282,11 @@@ fn tools_paragraph(include_hub: bool) -
/// `.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
++/// [`xerj_common::localauth::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
@@@ -389,12 -394,18 +394,18 @@@ pub async fn run(args: &[String]) -> an
// 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") {
++ if let Some(warning) = found.foreign_warning("--auth or XERJ_AUTH") {
+ eprintln!("xerj-mcp: warning: {warning}");
+ }
}
// stdout is the JSON-RPC channel; stderr is for logs only.
@@@ -6307,6 -6325,34 +6327,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);
++ assert_eq!(from.foreign_warning("--auth or XERJ_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.