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(autoindex): --follow-symlinks judged links by name, so a visible name indexed a secret and escaped the root

xerj-org5f75263e31ea
diff --git a/docs/recipes/zero-config-indexing.md b/docs/recipes/zero-config-indexing.md
index 6af74c91f..1b0abdb3f 100644
--- a/docs/recipes/zero-config-indexing.md
+++ b/docs/recipes/zero-config-indexing.md
@@ -268,7 +268,10 @@ disagreement is printed, not applied; bounds both the scan and the indexing
phase), `--prefix` to namespace the indices (default `ax`),
`--no-semantic` for pure BM25+keyword without vector fields, `--dry-run` to
print the inferred plan without indexing anything, `--follow-symlinks`
-(loop-safe), `--sample N` records per file for inference (default 500).
+(loop-safe — and a followed link is judged by what it resolves to: a target
+outside the indexed folder is refused, and one inside a hidden directory is
+skipped like any dotfile, however visible the link's own name), `--sample N`
+records per file for inference (default 500).
Build output never reaches the index in the first place. The walk honours
`.xerjignore`, `.gitignore` (nested files and `!negation` included) and
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index 43c8ffc07..27f563838 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -151,7 +151,11 @@ pub fn help_text_with(feedback: bool) -> String {
--snapshot-max-gb <N> logical payload cap for sealed source+prepared records\n\
bytes (default 64); excludes filesystem/manifest overhead\n\
--fresh {fresh_help}\n\
- --follow-symlinks follow symlinks (loop-safe); off by default\n\
+ --follow-symlinks follow symlinks (loop-safe); off by default.\n\
+ A link is judged by what it RESOLVES to: a\n\
+ target outside the folder is refused, and one\n\
+ inside a hidden directory is skipped like any\n\
+ dotfile, whatever the link itself is called\n\
--stub <GLOB> index matching files as ONE existence-only name\n\
card (title + provenance); contents are never\n\
opened. Repeatable. A pattern without '/'\n\
diff --git a/engine/crates/xerj-autoindex/src/ignore_rules.rs b/engine/crates/xerj-autoindex/src/ignore_rules.rs
index 61037a0de..bd3438b62 100644
--- a/engine/crates/xerj-autoindex/src/ignore_rules.rs
+++ b/engine/crates/xerj-autoindex/src/ignore_rules.rs
@@ -102,6 +102,18 @@ pub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[
/// needs it named, so it shares the reporting.
pub const HIDDEN_RULE: &str = "hidden:dotfile";
+/// A symlink whose resolved target lies outside the folder the operator
+/// pointed at. Only reachable with `--follow-symlinks`, and refused there:
+/// "index this folder" is not consent to index whatever else the filesystem
+/// links to, and `shared -> /etc` would otherwise put `/etc/shadow` in a
+/// queryable brain under the rel path `shared/shadow`.
+///
+/// Reported like a hidden directory — pruned, never deep-counted. The contents
+/// are outside the root, so they were never candidates and counting them would
+/// inflate [`IgnoreReport::files_inside_pruned_dirs`] with work no run was
+/// going to do.
+pub const ESCAPED_ROOT_RULE: &str = "symlink:outside-root";
+
const MAX_WARNINGS: usize = 20;
/// Directory entries the `--dry-run` deep count may examine in total. A
/// pathological `node_modules` is not allowed to turn "tell me the plan" into
@@ -676,6 +688,22 @@ impl IgnoreStack {
}
}
+ /// A symlink target outside the indexed root, also decided by the walker
+ /// (it needs the canonical root, which this stack does not carry) and
+ /// reported through the same accounting. See [`ESCAPED_ROOT_RULE`].
+ pub fn record_symlink_escape(&mut self, is_dir: bool) {
+ if is_dir {
+ self.report.dirs_pruned += 1;
+ self.report
+ .by_rule
+ .entry(ESCAPED_ROOT_RULE.to_string())
+ .or_default()
+ .dirs += 1;
+ } else {
+ self.record_file(ESCAPED_ROOT_RULE);
+ }
+ }
+
/// The marker-gated generated-dir prune (`walk::MARKER_GENERATED_DIRS`)
/// is also decided by the walker — the verdict needs the SIBLING marker
/// file, which the per-directory matcher stack cannot see — and reported
diff --git a/engine/crates/xerj-autoindex/src/walk.rs b/engine/crates/xerj-autoindex/src/walk.rs
index 3e29cc388..31a57181b 100644
--- a/engine/crates/xerj-autoindex/src/walk.rs
+++ b/engine/crates/xerj-autoindex/src/walk.rs
@@ -71,6 +71,36 @@ fn marker_generated_dir(path: &Path) -> Option<&'static str> {
None
}
+/// Why a followed symlink was refused. See the call site in `walk_reporting`.
+enum SymlinkVerdict {
+ /// The resolved target is not under the indexed root.
+ OutsideRoot,
+ /// The resolved target is under the root but its real path runs through a
+ /// hidden component — the link's visible name was hiding a dotfile.
+ HiddenTarget,
+}
+
+/// Judge a followed entry by where it actually resolves.
+///
+/// `path` is the path the walk arrived by, so under `--follow-symlinks` it can
+/// name a link anywhere along its length. Canonicalising collapses every link
+/// in it at once, which is what makes a chain of links (`a -> b -> .secret/c`)
+/// and a link partway up a directory path behave the same as a direct one.
+///
+/// `None` means the entry is where it appears to be and the ordinary rules
+/// govern it. An unresolvable path is `None` too: a broken link has no target
+/// to leak, and walkdir already reports it through the error arm.
+fn escaped_or_hidden_target(root_canon: &Path, path: &Path) -> Option<SymlinkVerdict> {
+ let real = path.canonicalize().ok()?;
+ let rel = real.strip_prefix(root_canon).ok();
+ let Some(rel) = rel else {
+ return Some(SymlinkVerdict::OutsideRoot);
+ };
+ rel.components()
+ .any(|c| is_hidden_name(c.as_os_str()))
+ .then_some(SymlinkVerdict::HiddenTarget)
+}
+
/// Walk with the default ignore rules on and the report discarded.
pub fn walk(root: &Path, follow_symlinks: bool) -> Result<Vec<FileEntry>> {
walk_reporting(root, follow_symlinks, IgnoreOptions::default()).map(|(files, _)| files)
@@ -146,6 +176,39 @@ pub fn walk_reporting(
}
continue;
}
+ // The rule above judges the NAME the walk arrived by, which is the
+ // whole rule when links are not followed. Under `--follow-symlinks` it
+ // is not: a link is free to be called `notes.txt` and point at
+ // `.secretdir/k.txt`, and walkdir then yields the target's contents
+ // under the link's visible name. Both halves of the guarantee above
+ // fail that way — the secret is indexed, and a link to a directory
+ // outside the root drags in a tree the operator never pointed at
+ // (`shared -> /etc` indexes `/etc/shadow` as `shared/shadow`). The
+ // report made it worse by still saying the hidden directories were
+ // pruned, which was true of the traversal and false of the outcome.
+ //
+ // So under the flag the same two questions are asked of the RESOLVED
+ // path instead of the name. Loop-safety is walkdir's and unrelated;
+ // this is the secret rule and the root boundary.
+ if follow_symlinks && entry.depth() > 0 {
+ match escaped_or_hidden_target(&root_canon, entry.path()) {
+ Some(SymlinkVerdict::OutsideRoot) => {
+ stack.record_symlink_escape(is_dir);
+ if is_dir {
+ it.skip_current_dir();
+ }
+ continue;
+ }
+ Some(SymlinkVerdict::HiddenTarget) => {
+ stack.record_hidden(is_dir);
+ if is_dir {
+ it.skip_current_dir();
+ }
+ continue;
+ }
+ None => {}
+ }
+ }
if is_dir {
// The root is never judged by the rules below it: pointing
// autoindex at a folder is an explicit instruction, and the note
diff --git a/engine/crates/xerj-autoindex/tests/follow_symlinks_boundary.rs b/engine/crates/xerj-autoindex/tests/follow_symlinks_boundary.rs
new file mode 100644
index 000000000..05f8c9c74
--- /dev/null
+++ b/engine/crates/xerj-autoindex/tests/follow_symlinks_boundary.rs
@@ -0,0 +1,198 @@
+//! Issue #438: `--follow-symlinks` used to defeat the hidden-file rule and
+//! walk out of the indexed root entirely.
+//!
+//! The hidden-name rule in `walk.rs` judges the name the walk arrived by. With
+//! links followed that is not the file: a link called `notes.txt` pointing at
+//! `.secretdir/k.txt` passed the rule and its contents were indexed, and a link
+//! called `shared` pointing anywhere at all dragged that tree in under the
+//! root's rel paths. The run then printed `hidden:dotfile dirs: 1`, which was
+//! true of the traversal and false of the outcome — the operator was told the
+//! hidden directory had been pruned while its contents were being indexed
+//! through the link.
+//!
+//! Both halves are tested here through the public `walk_reporting`, against a
+//! real filesystem with real symlinks, because the defect is entirely about
+//! what the OS resolves and nothing about it is visible to a unit test over
+//! synthetic paths.
+
+#![cfg(unix)]
+
+use std::fs;
+use std::os::unix::fs::symlink;
+use std::path::Path;
+use xerj_autoindex::ignore_rules::{IgnoreOptions, ESCAPED_ROOT_RULE, HIDDEN_RULE};
+use xerj_autoindex::walk::walk_reporting;
+
+/// root/
+/// README.md visible, ordinary
+/// .secretdir/k.txt the secret
+/// notes.txt -> .secretdir/k.txt (visible name, hidden target)
+/// chain.txt -> hop.txt -> .secretdir/k.txt
+/// plain-link.txt -> README.md (must still be indexed)
+/// shared -> ../outside (escapes the root)
+/// sub/deep.md visible, ordinary, below a directory
+/// outside/etc/shadow must never appear
+fn fixture() -> tempfile::TempDir {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let root = dir.path().join("root");
+ let outside = dir.path().join("outside");
+
+ fs::create_dir_all(root.join(".secretdir")).unwrap();
+ fs::create_dir_all(root.join("sub")).unwrap();
+ fs::create_dir_all(outside.join("etc")).unwrap();
+
+ fs::write(root.join("README.md"), "# readme\n").unwrap();
+ fs::write(root.join("sub/deep.md"), "deep\n").unwrap();
+ fs::write(root.join(".secretdir/k.txt"), "INNER SECRET\n").unwrap();
+ fs::write(outside.join("etc/shadow"), "root:$6$OUTSIDE$hash:...\n").unwrap();
+
+ symlink(".secretdir/k.txt", root.join("notes.txt")).unwrap();
+ symlink(".secretdir/k.txt", root.join("hop.txt")).unwrap();
+ symlink("hop.txt", root.join("chain.txt")).unwrap();
+ symlink("README.md", root.join("plain-link.txt")).unwrap();
+ symlink(&outside, root.join("shared")).unwrap();
+
+ dir
+}
+
+fn walk_rels(
+ root: &Path,
+ follow: bool,
+) -> (Vec<String>, xerj_autoindex::ignore_rules::IgnoreReport) {
+ let (files, report) =
+ walk_reporting(root, follow, IgnoreOptions::default()).expect("walk succeeds");
+ let mut rels: Vec<String> = files.into_iter().map(|f| f.rel).collect();
+ rels.sort();
+ (rels, report)
+}
+
+/// The whole point: with links followed, no secret and nothing from outside.
+#[test]
+fn following_links_indexes_neither_the_secret_nor_anything_outside_the_root() {
+ let dir = fixture();
+ let root = dir.path().join("root");
+
+ let (rels, report) = walk_rels(&root, true);
+
+ // A file that is only reachable by resolving a link into a hidden
+ // directory must not be indexed under any name.
+ for leaked in ["notes.txt", "hop.txt", "chain.txt"] {
+ assert!(
+ !rels.iter().any(|r| r == leaked),
+ "`{leaked}` resolves into .secretdir and was indexed anyway: {rels:?}"
+ );
+ }
+
+ // Nothing from outside the root, under any rel path.
+ assert!(
+ !rels.iter().any(|r| r.starts_with("shared")),
+ "content from outside the indexed root was walked in: {rels:?}"
+ );
+
+ // And the ordinary files are all still there — a fix that indexes nothing
+ // also passes the two assertions above.
+ assert_eq!(
+ rels,
+ vec![
+ "README.md".to_string(),
+ "plain-link.txt".to_string(),
+ "sub/deep.md".to_string()
+ ],
+ "the visible tree must be unchanged, including a link to a VISIBLE file"
+ );
+
+ // The report has to say what happened, because "my file vanished" is
+ // answered from it. Silently correct is still a lie about the run.
+ let hidden = report.by_rule.get(HIDDEN_RULE).copied().unwrap_or_default();
+ assert!(
+ hidden.files >= 3,
+ "the three links into .secretdir must be reported as hidden, got {hidden:?} in {report:?}"
+ );
+ let escaped = report
+ .by_rule
+ .get(ESCAPED_ROOT_RULE)
+ .copied()
+ .unwrap_or_default();
+ assert_eq!(
+ escaped.dirs, 1,
+ "the link out of the root must be reported under `{ESCAPED_ROOT_RULE}`: {report:?}"
+ );
+}
+
+/// The default path must be untouched by the fix — links are not followed, so
+/// the link files themselves are the entries and nothing resolves.
+#[test]
+fn not_following_links_is_unchanged() {
+ let dir = fixture();
+ let root = dir.path().join("root");
+
+ let (rels, report) = walk_rels(&root, false);
+
+ assert_eq!(
+ rels,
+ vec!["README.md".to_string(), "sub/deep.md".to_string()],
+ "with links unfollowed only real files are entries: {report:?}"
+ );
+ assert!(
+ !report.by_rule.contains_key(ESCAPED_ROOT_RULE),
+ "nothing escapes when nothing is followed: {report:?}"
+ );
+}
+
+/// A link pointing at a visible file INSIDE the root is the case the fix must
+/// not break, and the one a blunt "refuse all symlinks" would.
+#[test]
+fn a_link_to_a_visible_file_inside_the_root_is_still_indexed() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().join("root");
+ fs::create_dir_all(root.join("docs")).unwrap();
+ fs::write(root.join("docs/real.md"), "real\n").unwrap();
+ symlink("docs/real.md", root.join("alias.md")).unwrap();
+
+ let (rels, _) = walk_rels(&root, true);
+ assert_eq!(
+ rels,
+ vec!["alias.md".to_string(), "docs/real.md".to_string()],
+ "following a link to a visible in-root file must keep indexing it"
+ );
+}
+
+/// A link to a directory inside the root: still walked, and the hidden rule
+/// still applies to what is under it.
+#[test]
+fn a_link_to_a_directory_inside_the_root_is_walked_and_still_hides_dotfiles() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().join("root");
+ fs::create_dir_all(root.join("real/.hidden")).unwrap();
+ fs::write(root.join("real/open.md"), "open\n").unwrap();
+ fs::write(root.join("real/.hidden/secret.md"), "secret\n").unwrap();
+ symlink("real", root.join("mirror")).unwrap();
+
+ let (rels, report) = walk_rels(&root, true);
+ assert!(
+ rels.contains(&"mirror/open.md".to_string()),
+ "an in-root directory link must still be walked: {rels:?}"
+ );
+ assert!(
+ !rels.iter().any(|r| r.contains(".hidden")),
+ "the hidden rule must survive the link: {rels:?} {report:?}"
+ );
+}
+
+/// A broken link has no target, so it cannot leak one. It must not abort the
+/// walk or be reported as an escape.
+#[test]
+fn a_broken_link_is_not_an_escape() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().join("root");
+ fs::create_dir_all(&root).unwrap();
+ fs::write(root.join("real.md"), "real\n").unwrap();
+ symlink("nowhere-at-all", root.join("dangling.md")).unwrap();
+
+ let (rels, report) = walk_rels(&root, true);
+ assert_eq!(rels, vec!["real.md".to_string()], "{report:?}");
+ assert!(
+ !report.by_rule.contains_key(ESCAPED_ROOT_RULE),
+ "a dangling link is not an escape: {report:?}"
+ );
+}
diff --git a/landing/docs/recipes/zero-config-autoindex.html b/landing/docs/recipes/zero-config-autoindex.html
index 4bebd2db0..7c8a9816d 100644
--- a/landing/docs/recipes/zero-config-autoindex.html
+++ b/landing/docs/recipes/zero-config-autoindex.html
@@ -266,7 +266,7 @@ xerj autoindex ~/some-folder
xerj autoindex map
curl localhost:9200/ax-*/_search -H 'Content-Type: application/json' \
-d '{"query":{"match_all":{}},"size":3}'</pre>
- <p>Useful knobs (all optional): <code class="inline">--url</code> for a non-default endpoint, <code class="inline">--workers N</code> (default: every core, reduced when the memory safe zone cannot pay for that many in-flight bulk buffers; bounds both the scan and the indexing phase), <code class="inline">--prefix</code> to namespace the indices (default <code class="inline">ax</code>), <code class="inline">--no-semantic</code> for pure BM25+keyword without vector fields, <code class="inline">--dry-run</code> to print the inferred plan without indexing anything, <code class="inline">--follow-symlinks</code> (loop-safe), <code class="inline">--sample N</code> records per file for inference (default 500).</p>
+ <p>Useful knobs (all optional): <code class="inline">--url</code> for a non-default endpoint, <code class="inline">--workers N</code> (default: every core, reduced when the memory safe zone cannot pay for that many in-flight bulk buffers; bounds both the scan and the indexing phase), <code class="inline">--prefix</code> to namespace the indices (default <code class="inline">ax</code>), <code class="inline">--no-semantic</code> for pure BM25+keyword without vector fields, <code class="inline">--dry-run</code> to print the inferred plan without indexing anything, <code class="inline">--follow-symlinks</code> (loop-safe &mdash; and a followed link is judged by what it resolves to: a target outside the indexed folder is refused, and one inside a hidden directory is skipped like any dotfile, however visible the link’s own name), <code class="inline">--sample N</code> records per file for inference (default 500).</p>
<p>Build output never reaches the index in the first place. The walk honours <code class="inline">.xerjignore</code>, <code class="inline">.gitignore</code> (nested files and <code class="inline">!negation</code> included) and <code class="inline">.git/info/exclude</code>, plus a built-in list — <code class="inline">node_modules/ vendor/ target/ dist/ build/ .venv/ __pycache__/</code> — in that order of precedence; an excluded directory is never descended, so nothing inside it is stat-ed, hashed or sent. The two git-owned kinds stop at a repository boundary the way git does: a <code class="inline">.gitignore</code> above a nested checkout has no authority over the files inside it, so a vendored or submoduled tree keeps its own rules. <code class="inline">.xerjignore</code> and the built-in list are XERJ&rsquo;s rather than git&rsquo;s and apply throughout the folder you named. Hidden files (<code class="inline">.env</code>, <code class="inline">.git/</code>) are skipped by a separate, non-optional rule. Every run prints what was dropped and by which rule (<code class="inline">ignore rules: &hellip;</code> on stderr), and <code class="inline">--dry-run</code> also counts the non-hidden files inside each pruned directory, so &ldquo;where did my file go?&rdquo; always has an answer. <code class="inline">--no-ignore</code> turns the rules off; <code class="inline">--no-default-ignores</code> keeps your ignore files and drops only the built-in list. Both apply to an indexing run only &mdash; <code class="inline">autoindex map</code> and <code class="inline">autoindex status</code> never walk a folder and refuse them rather than accepting a flag that would do nothing. The folder you point at is never excluded: if it is itself ignored &mdash; say you run this on <code class="inline">~/proj/target</code> &mdash; it is indexed anyway and the run says which rule it would have matched.</p>
<p><code class="inline">--workers</code> is a ceiling, not a promise: when the server answers <code class="inline">429 Too Many Requests</code> the run halves its own bulk concurrency on the spot and probes back up one worker at a time only after a clean streak, so a busy server is not handed the same load six times over. The run's summary records where it ended up (<code class="inline">bulk_concurrency_final</code>, <code class="inline">bulk_congestion_events</code>).</p>
<p>Your dataset names, field types, and counts will reflect <em>your</em> folder — that is the point. The behaviors shown here (decimal-comma → <code class="inline">double</code>, date strings → typed <code class="inline">date</code>, keyword inference, junk recording, resume-to-identical-counts) are the invariants.</p>