AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
security(audit): server-derived machine-traffic class in audit entries (#1109)
xerj-org44d8ce89b6b5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eb6bb7508..6aa82557b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Security++- **Audit records now carry a server-derived `actor` class (`user`/`machine`)** (issue+ [#1109](https://github.com/xerj-org/xerj/issues/1109)) — the audit log's+ search entries said WHO ran a query but not WHO IT SERVED, so the only way+ `xerj gain` could exclude autoindex's own machine traffic (#1105) was to+ re-derive it client-side from the note string (`size=0` probes) and the+ resource name (catalog sweeps): a heuristic a future note-format change+ would silently break, and one any caller writing audit-shaped entries could+ satisfy. Every audit entry now carries an `actor` field derived at append+ time by the SERVER from what the request itself is — a `size:0` counting+ probe or a search of the `autoindex-catalog` maintenance index is+ `machine`; everything else is `user`. Nothing a client can set (header,+ principal, body) is consulted — the spoofable `X-Xerj-Internal` header+ proposal from #1107 stays rejected. The class is part of the hash chain:+ flipping an entry from `user` to `machine` — the dodge that would remove+ unfavourable traffic from the `xerj gain` hit-rate denominator — breaks the+ chain like any other edit. Entries written by older binaries deserialize+ with `actor: "user"` (which is what they all were), so mixed-version logs+ still verify, and `xerj gain` prefers the field on new entries while+ keeping the note/resource derivation as the documented legacy fallback for+ old ones.+### Fixed- **`embedding.mode = "proxy"` with an unusable endpoint silently randiff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 4bc537dce..efb96a80b 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -10094,6 +10094,33 @@ fn mapping_source_disabled(state: &AppState, index: &str) -> bool {.unwrap_or(false)}+/// Who a search served: `"machine"` or `"user"` (#1109). Decided by the+/// server from what the request itself IS, so no client input can mark its+/// own traffic machine and dodge the `xerj gain` user hit-rate stat:+///+/// * `size == 0` — a counting probe. It asks for no hits back; the canonical+/// issuer is autoindex's verification step, which reads back exact group+/// counts that way (#1105). A human looking for documents always wants+/// hits, and the ES-YAML suite's `size: 0` aggregation requests are tool+/// traffic by the same definition.+/// * the target is the autoindex catalog — a maintenance index no person+/// searches; every query against it comes from `xerj autoindex`'s sweeps+/// (`xerj gain` itself reads it the same way).+///+/// Everything a client CAN set — headers, principal, query body apart from+/// these two semantics — is deliberately not consulted. The spoofable+/// `X-Xerj-Internal` header proposal was rejected during #1107 and this is+/// the replacement: classification from request shape, not request claim.+/// A superuser running `size: 10` against a data index is classified user,+/// because that is what the request is.+fn search_actor_class(size: usize, index: &str) -> &'static str {+ if size == 0 || index == xerj_common::AUTOINDEX_CATALOG_INDEX {+ "machine"+ } else {+ "user"+ }+}+async fn search_impl(state: AppState,index: String,@@ -13185,7 +13212,13 @@ async fn search_impl(// "anonymous" until issue #329 — the API-key operations had been passing a// real `principal.label()` since #201, so the plumbing existed and this one// site simply did not use it.- state.engine.audit.append(+ state.engine.audit.append_as(+ // #1109: the machine/user split is decided HERE, server-side, from+ // what the request itself is — never from anything a client can set+ // (the spoofable `X-Xerj-Internal` header was considered and+ // rejected during #1107, and that decision stands). See+ // `search_actor_class` for exactly which requests are machine.+ search_actor_class(body.size, index.as_str()),"search",principal.label(),index.as_str(),@@ -45831,3 +45864,34 @@ mod cluster_topology_honesty_tests {assert_eq!(body["number_of_nodes"], 1);}}++#[cfg(test)]+mod search_actor_class_tests {+ use super::*;++ /// #1109: the two machine classes, pinned. `size == 0` is a counting+ /// probe; the catalog index is a maintenance index. Both classifications+ /// hold regardless of who issued the request — the server cannot see+ /// intent, only shape, and shape is what these tests fix.+ #[test]+ fn counting_probes_and_catalog_sweeps_are_machine() {+ assert_eq!(search_actor_class(0, "ax-logs"), "machine");+ assert_eq!(search_actor_class(10, "autoindex-catalog"), "machine");+ assert_eq!(search_actor_class(0, "autoindex-catalog"), "machine");+ }++ /// The anti-spoof property, stated as a test: a superuser-scale page on+ /// an ordinary data index is USER traffic, and nothing about the+ /// principal, headers, or query body changes that — the function's+ /// signature literally has no room for client input beyond page size and+ /// target index, which is the point.+ #[test]+ fn ordinary_searches_stay_user_no_matter_the_caller() {+ assert_eq!(search_actor_class(10, "ax-logs"), "user");+ assert_eq!(search_actor_class(1, "ax-logs"), "user");+ assert_eq!(search_actor_class(10_000, "ax-logs"), "user");+ // A catalog-named DATA index must not be caught by the exact-name+ // match — only the maintenance index itself is machine.+ assert_eq!(search_actor_class(10, "autoindex-catalog-copy"), "user");+ }+}diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rsindex d28070ab0..f684a4fb3 100644--- a/engine/crates/xerj-autoindex/src/catalog.rs+++ b/engine/crates/xerj-autoindex/src/catalog.rs@@ -6,7 +6,7 @@ use crate::correlate::KeyCorr;use crate::state::PlanDataset;use serde_json::{json, Value};-pub const CATALOG_INDEX: &str = "autoindex-catalog";+pub const CATALOG_INDEX: &str = xerj_common::AUTOINDEX_CATALOG_INDEX;/// The corpus-scope field the #737/#693 exclusion sweeps term-query (#755).///diff --git a/engine/crates/xerj-autoindex/src/gain.rs b/engine/crates/xerj-autoindex/src/gain.rsindex 5f5bc2864..a027db724 100644--- a/engine/crates/xerj-autoindex/src/gain.rs+++ b/engine/crates/xerj-autoindex/src/gain.rs@@ -77,6 +77,14 @@ pub(crate) fn parse_note(note: &str) -> (u64, u64, Option<u64>) {/// Pull search events out of the audit snapshot (`{entries: [...]}`),/// separating the user's searches from autoindex's machine traffic.+///+/// Two sources of truth, in order (#1109): an entry carrying the server-set+/// `actor` field is classified by it — the server derived the class from the+/// request itself at append time, which a client cannot influence; entries+/// written by a binary older than #1109 carry no `actor`, and for those the+/// note/resource heuristics below remain the (only) derivation. The two agree+/// on everything the heuristics could see; the field's value is that it is+/// authoritative rather than inferred.pub(crate) fn search_events(audit: &Value) -> SearchWindow {let mut out = SearchWindow::default();let Some(entries) = audit.get("entries").and_then(Value::as_array) else {@@ -93,13 +101,35 @@ pub(crate) fn search_events(audit: &Value) -> SearchWindow {.to_string();let note = e.get("note").and_then(Value::as_str).unwrap_or("");let (took_ms, hits, size) = parse_note(note);- if size == Some(0) {- out.counting_probes += 1;- continue;- }- if resource == "autoindex-catalog" {- out.catalog_sweeps += 1;- continue;+ match e.get("actor").and_then(Value::as_str) {+ // Written by a post-#1109 server: trust the server-side class.+ // Within "machine", keep the probe/sweep split for the honesty+ // line: the two machine classes are exactly size:0 probes and+ // catalog sweeps, so the size alone disambiguates them.+ Some("machine") => {+ if size == Some(0) {+ out.counting_probes += 1;+ } else {+ out.catalog_sweeps += 1;+ }+ continue;+ }+ Some(_) => {}+ // No actor field: a log written before #1109. The note/resource+ // heuristics that shipped with #1105 stay as the legacy+ // derivation — an old log read by a new client must still+ // separate machine traffic, or every upgraded install would+ // report a hit-rate dip that is really a version skew.+ None => {+ if size == Some(0) {+ out.counting_probes += 1;+ continue;+ }+ if resource == crate::catalog::CATALOG_INDEX {+ out.catalog_sweeps += 1;+ continue;+ }+ }}out.user.push(SearchEvent {index: resource,@@ -408,7 +438,9 @@ mod tests {fn counting_probes_and_catalog_sweeps_are_not_user_searches() {// #1105, verbatim from the rc.80 harness run: 179 size-0 verification// probes on the dataset index, catalog reconcile sweeps, three real- // searches — gain must report the three.+ // searches — gain must report the three. These entries carry no+ // `actor` field (pre-#1109 shape), so they also pin the legacy+ // note/resource derivation an upgraded client reads an old log with.let probe = |hits: u64| {json!({ "op": "search", "subject": "superuser", "resource": "ax-docs","outcome": "ok", "note": format!("took=0ms hits={hits} size=0") })@@ -432,6 +464,66 @@ mod tests {assert_eq!(s["hit_rate"], 100.0);}+ /// #1109: entries written by a post-#1109 server carry the server-set+ /// `actor` field, and THAT classifies — not the note heuristics. This is+ /// the anti-spoof half of the feature living where its consumer reads it:+ /// the classification was derived from the request itself at append time,+ /// so a note that says `size=10` on machine traffic (or vice versa) is+ /// data, not a verdict.+ #[test]+ fn actor_field_is_authoritative_when_present() {+ let a = audit(vec![+ // Machine by the field, and the note would agree — normal case.+ json!({ "op": "search", "subject": "superuser", "resource": "ax-docs",+ "outcome": "ok", "actor": "machine",+ "note": "took=0ms hits=0 size=0" }),+ // Machine by the field with a note the legacy heuristic could NOT+ // parse a class from (no size, data index): still excluded, split+ // into catalog_sweeps as the non-probe machine class.+ json!({ "op": "search", "subject": "superuser", "resource": "ax-docs",+ "outcome": "ok", "actor": "machine",+ "note": "took=1ms hits=5" }),+ // User by the field even where the heuristic would have said+ // machine: a post-#1109 server never writes this combination, and+ // pinning that the field wins is what makes one classifier — the+ // server's — authoritative instead of two half-trusted ones.+ json!({ "op": "search", "subject": "superuser", "resource": "ax-docs",+ "outcome": "ok", "actor": "user",+ "note": "took=2ms hits=1 size=0" }),+ ]);+ let w = search_events(&a);+ assert_eq!(w.user.len(), 1);+ assert_eq!(w.user[0].hits, 1);+ assert_eq!(w.counting_probes, 1);+ assert_eq!(w.catalog_sweeps, 1);+ }++ /// A mixed-version audit window — an upgraded install whose ring still+ /// holds pre-#1109 entries — must classify both halves correctly in one+ /// pass: the fieldless tail by the legacy derivation, the new head by the+ /// field.+ #[test]+ fn mixed_version_log_classifies_both_halves() {+ let a = audit(vec![+ // Old-shape entry (no actor): heuristic must still exclude it.+ json!({ "op": "search", "subject": "superuser", "resource": "ax-docs",+ "outcome": "ok", "note": "took=0ms hits=0 size=0" }),+ // New-shape machine entry.+ json!({ "op": "search", "subject": "superuser", "resource": "autoindex-catalog",+ "outcome": "ok", "actor": "machine",+ "note": "took=0ms hits=40 size=100" }),+ // New-shape user entry.+ json!({ "op": "search", "subject": "superuser", "resource": "ax-docs",+ "outcome": "ok", "actor": "user",+ "note": "took=8ms hits=4 size=10" }),+ ]);+ let w = search_events(&a);+ assert_eq!(w.user.len(), 1);+ assert_eq!(w.user[0].took_ms, 8);+ assert_eq!(w.counting_probes, 1, "the legacy entry");+ assert_eq!(w.catalog_sweeps, 1, "the fielded entry");+ }+#[test]fn stats_count_hit_rate_and_percentiles() {let ev: Vec<SearchEvent> = (0..10)diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rsindex 103374065..d28e176b8 100644--- a/engine/crates/xerj-common/src/lib.rs+++ b/engine/crates/xerj-common/src/lib.rs@@ -49,5 +49,14 @@ pub use config::Config;pub use error::XerjError;pub use types::{DocId, Document, FieldConfig, FieldType, IndexName, Schema, SegmentId, SeqNo};+/// Name of the catalog index `xerj autoindex` maintains on every node it+/// onboards (`xerj-autoindex/src/catalog.rs` defines it; this copy is the+/// one the SERVER side reads). Single source of truth in xerj-common+/// because the two crates do not depend on each other, and both need the+/// exact spelling: the server classifies searches of this index as+/// machine traffic in the audit record (#1109), the client reads it back+/// from `xerj gain`.+pub const AUTOINDEX_CATALOG_INDEX: &str = "autoindex-catalog";+/// Crate-level result alias — uses [`XerjError`] as the error type.pub type Result<T> = std::result::Result<T, XerjError>;diff --git a/engine/crates/xerj-engine/src/audit.rs b/engine/crates/xerj-engine/src/audit.rsindex caf11ff30..2569a1e01 100644--- a/engine/crates/xerj-engine/src/audit.rs+++ b/engine/crates/xerj-engine/src/audit.rs@@ -112,6 +112,16 @@ pub struct AuditEntry {pub resource: String,/// Outcome: "ok", "denied", "error".pub outcome: String,+ /// Who the traffic served: `"user"` or `"machine"` (#1109). Derived at+ /// append time by the SERVER from what the request itself is (a counting+ /// probe, a sweep of a maintenance index) — never from anything a client+ /// can set, so no principal can mark its own traffic machine to dodge+ /// the `xerj gain` hit-rate stat. Stability: the field is part of the+ /// record shape and of the hash input for new entries; entries written+ /// before it existed deserialize with `"user"`, which is what every+ /// such entry was.+ #[serde(default = "default_actor")]+ pub actor: String,/// Optional short context (e.g. "took=12ms hits=3").pub note: String,/// SHA-256 hex digest over: prev_hash || serialised(this_entry_minus_hash).@@ -121,6 +131,13 @@ pub struct AuditEntry {pub hash: String,}+/// Entries persisted before the `actor` field existed (#1109) carry no+/// actor; they were all user-path traffic by construction (machine traffic+/// only became distinguishable when this field did).+fn default_actor() -> String {+ "user".to_string()+}+/// The first line of a persisted log: the hash the first retained entry/// chains over. Written whenever the log is (re)created from a ring that has/// already dropped entries, so verification has a real anchor.@@ -208,6 +225,22 @@ impl AuditLog {/// alternative is a chain that is silently wrong under load, which is the/// worst possible failure mode for evidence.pub fn append(&self, op: &str, subject: &str, resource: &str, outcome: &str, note: &str) {+ self.append_as("user", op, subject, resource, outcome, note);+ }++ /// Append with an explicit actor class (#1109). `append` is the+ /// every-call-site default (`"user"`); only the sites that can derive+ /// machine traffic from the request itself may pass `"machine"` —+ /// see the search handler, which owns the only such derivation today.+ pub fn append_as(+ &self,+ actor: &str,+ op: &str,+ subject: &str,+ resource: &str,+ outcome: &str,+ note: &str,+ ) {let seq = self.next_seq.fetch_add(1, Ordering::Relaxed);let at_ms = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -220,6 +253,7 @@ impl AuditLog {subject: subject.to_string(),resource: resource.to_string(),outcome: outcome.to_string(),+ actor: actor.to_string(),note: note.to_string(),hash: String::new(),};@@ -476,6 +510,13 @@ fn compute_hash(prev_hash: &str, entry: &AuditEntry) -> String {h.update(b"\0");h.update(entry.outcome.as_bytes());h.update(b"\0");+ // #1109: the actor class is part of the evidence — flipping an entry+ // from user to machine (the dodge `xerj gain` exists to prevent) must+ // break the chain like any other edit. Entries restored from a log+ // written before the field existed hash with the deserialized default+ // ("user"), which is what they were, so mixed-version logs still verify.+ h.update(entry.actor.as_bytes());+ h.update(b"\0");h.update(entry.note.as_bytes());let bytes = h.finalize();bytes.iter().map(|b| format!("{:02x}", b)).collect()@@ -681,4 +722,111 @@ mod tests {assert_eq!(log.snapshot().len(), 2);assert!(log.verify().is_ok());}++ /// #1109: entries persisted before the `actor` field existed deserialize+ /// as `"user"` — which is what every such entry was, machine traffic not+ /// being distinguishable before the field — and a log mixing pre-field+ /// and post-field entries still verifies, because the deserialized+ /// default is exactly what the recomputed hash uses.+ #[test]+ fn pre_actor_entries_load_as_user_and_mixed_logs_verify() {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().join("audit.jsonl");+ {+ let log = AuditLog::open(8, &path);+ log.append(+ "search",+ "alice",+ "ax-docs",+ "ok",+ "took=1ms hits=2 size=10",+ );+ log.append_as(+ "machine",+ "search",+ "superuser",+ "ax-docs",+ "ok",+ "took=0ms hits=0 size=0",+ );+ log.append_as(+ "user",+ "search",+ "bob",+ "ax-docs",+ "ok",+ "took=3ms hits=1 size=10",+ );+ }+ // Strip the actor field from the FIRST entry only — the exact shape a+ // pre-#1109 binary leaves on disk — then reopen over the mixed file.+ let text = std::fs::read_to_string(&path).expect("read");+ let mut lines = text.lines();+ let seed = lines.next().expect("seed line");+ let mut entries: Vec<String> = lines.map(str::to_string).collect();+ assert!(+ entries[0].contains("\"actor\":\"user\""),+ "new entries persist the field: {}",+ entries[0]+ );+ entries[0] = entries[0].replace(",\"actor\":\"user\"", "");+ let mixed = format!("{seed}\n{}\n", entries.join("\n"));+ std::fs::write(&path, mixed).expect("write");++ let log = AuditLog::open(8, &path);+ let snap = log.snapshot();+ assert_eq!(snap.len(), 3);+ assert_eq!(snap[0].actor, "user", "a fieldless entry loads as user");+ assert_eq!(snap[1].actor, "machine");+ assert!(+ log.verify().is_ok(),+ "a mixed-version log must still verify end to end"+ );+ // And the chain keeps extending from the mixed state.+ log.append_as(+ "user",+ "search",+ "carol",+ "ax-docs",+ "ok",+ "took=1ms hits=1 size=5",+ );+ assert!(log.verify().is_ok());+ }++ /// #1109: the actor class is inside the hash input — flipping an entry+ /// from user to machine (the dodge `xerj gain` exists to prevent: marking+ /// your own traffic machine removes it from the hit-rate denominator)+ /// must break the chain exactly like any other edit.+ #[test]+ fn flipping_the_actor_breaks_the_chain() {+ let log = AuditLog::new(8);+ log.append(+ "search",+ "alice",+ "ax-docs",+ "ok",+ "took=1ms hits=2 size=10",+ );+ log.append_as(+ "machine",+ "search",+ "auto",+ "ax-docs",+ "ok",+ "took=0ms hits=0 size=0",+ );+ assert!(log.verify().is_ok());+ {+ let mut buf = log.buf.write();+ buf[0].actor = "machine".into();+ }+ let r = log.verify();+ assert!(+ r.is_err(),+ "an actor flip is a tamper, not a reclassification"+ );+ let (seq, _, _) = r.unwrap_err();+ assert_eq!(seq, 1);+ }}