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.

docs(case-study): five-stage instruction/data pass — all 8 findings, methodology, website

xerj-org64012929ac53
diff --git a/docs/case-studies/xerj-self-audit/FINDINGS-V2.md b/docs/case-studies/xerj-self-audit/FINDINGS-V2.md
new file mode 100644
index 000000000..f3918da75
--- /dev/null
+++ b/docs/case-studies/xerj-self-audit/FINDINGS-V2.md
@@ -0,0 +1,219 @@
+# Findings — five-stage instruction/data pass
+
+Eight findings survived adversarial verification (each proposed by a lens agent,
+then attacked by a separate verifier whose default was "this is wrong"; most were
+confirmed by exploiting a live server). Ranked by verifier-corrected severity.
+
+**Reporting note (honesty).** The workflow's automatic synthesis step wrote up
+only the first two of these and reported "2 confirmed, 1 refuted." That was an
+under-count: the per-finding verifiers marked **8** findings `refuted=false`. The
+discrepancy was caught by reconciling the synthesis against the raw verifier
+verdicts, and the four HIGH findings were then re-verified by hand against current
+code before publication. This document is the reconciled, complete set.
+
+**Shared reachability qualifier.** XERJ has no enforced role model — every minted
+key authenticates as the single superuser (`auth.rs:182`; `role_descriptors` are
+accepted but not enforced). And `--insecure` or an empty `admin_api_key`
+(`auth.rs:96`) disables auth entirely, which promotes every "authenticated"
+finding below to **unauthenticated**.
+
+| ID | Severity | Reachability | Status |
+|---|---|---|---|
+| INJ-01 | High | authenticated (app-mediated) | **fixed** `58fc73f` |
+| F-PATH-02 | High | authenticated (unauth under `--insecure`) | **fixed** `58fc73f` |
+| S5-1 | High | authenticated (valid session cookie) | **fixed** `58fc73f` |
+| DESER-EGRESS-01 | High | unauth on the cluster port (operator-gated by `cluster.enabled`) | tracked (Raft-auth Phase-2) |
+| S5-4 | Medium | unauthenticated | open |
+| S5-3 | Medium | unauthenticated (needs a valid magic-link token) | open |
+| S5-5 | Low | authenticated (superuser-equivalent) | open |
+| AUTHZ-2 | Info | unauthenticated | open |
+
+---
+
+## INJ-01 — Search-template params spliced unescaped into the query, then re-parsed · High · FIXED
+
+`crates/xerj-api/src/es_compat.rs:23160` (`render_template`).
+
+**Instruction/data.** The template is the instruction channel (JSON that defines
+the query structure); the params are the data channel. `render_template` merged
+them with a raw `String::replace` and **zero escaping**, then
+`serde_json::from_str` re-parsed the merged string — so a param value carrying
+JSON tokens (`"`, `,`, an extra `"query"` key) was interpreted as query
+*structure*. A param in a numeric position (`"size": {{size}}`) needed no quote
+break-out at all.
+
+**Taint path.** `POST /:index/_search/template` → `search_template` (`Json<SearchTemplateBody>`)
+→ `render_template(&tmpl, &params)` → `serde_json::from_str(&rendered)` →
+`parse_request` → `idx.search()`. Same sink via `POST /_render/template` and
+`POST /_msearch/template`.
+
+**Attacker input / live proof.** Template encodes an ACL filter and takes an
+untrusted `size`: `{"query":{"bool":{"filter":[{"term":{"visibility":"public"}}]}},"size":{{size}}}`.
+Params `{"size":"50,\"query\":{\"match_all\":{}}"}`. On a throwaway server the
+benign `size:50` returned only the public doc; the injected value returned **both
+docs including the private `{"secret":"CEO-comp-4.2M"}`** — the visibility filter
+was dropped (serde keeps the last of duplicate `query` keys).
+
+**Fix (`58fc73f`).** String replacements are JSON-escaped (the escaped inner
+content is emitted), so a value is always one JSON token: transparent inside a
+string literal, and in a bare value position a malicious value becomes an invalid
+`\"` sequence that fails the re-parse. **Re-proven:** the same payload now returns
+`template rendered to invalid JSON` and leaks nothing; 4 regression tests.
+
+---
+
+## F-PATH-02 — Snapshot repository `settings.location` is an unvalidated root · High · FIXED
+
+`crates/xerj-engine/src/engine.rs:1562` (`create_snapshot` / `restore_snapshot` →
+`validate_snapshot_path`).
+
+**Instruction/data.** The three filters guarding the snapshot *name* are real and
+well-written — they prove the snapshot stays inside its repository. But the
+*repository location* itself is an absolute path the client supplies via
+`PUT /_snapshot/{repo}` and none of the name-filters look at it. The containment
+check is vacuous when the root it contains against is attacker-chosen.
+
+**Attacker input / live proof.** `PUT /_snapshot/evil {"type":"fs","settings":{"location":"/tmp/EVIL"}}`
+then `PUT /_snapshot/evil/s1` → previously `state: SUCCESS`, and every index's
+segment files (postings for a field literally named `secret`) were copied to
+`/tmp/EVIL`, outside `data_dir`. `restore_snapshot` is the mirror: read
+attacker-staged files from anywhere into an index.
+
+**Fix (`58fc73f`).** New `limits.snapshot_repo_allowlist` (ES `path.repo`
+equivalent; default empty = only `data_dir`). `validate_snapshot_path` rejects a
+location that canonicalizes outside `data_dir` or the allowlist. **Re-proven:** the
+external location is now refused (`location … is outside data_dir`); an
+in-`data_dir` repo still snapshots fine; 4 regression tests. This is the item PR
+#69 explicitly deferred ("no `path.repo` equivalent").
+
+---
+
+## S5-1 — Session-revocation lost update (best-effort `last_seen` bump clobbers a revoke) · High · FIXED
+
+`crates/xerj-console-api/src/auth/sessions.rs:186`.
+
+**Instruction/data (state machine).** The *check* (session is valid) is the
+instruction; the *session record* is the data. The auth extractor read the
+session at the top of the request, then at the end blind-wrote a clone with
+`last_seen` bumped. A `revoke_session()` that landed in between was overwritten by
+the stale copy (`revoked_at: None`) — the record was resurrected and the
+revocation silently undone. `put_session` is delete-then-create with no CAS, so
+the stale write wins.
+
+**Reachability.** Any session-protected console endpoint (the router is mounted
+unconditionally on both listeners) triggers the bump; the attacker needs a valid —
+e.g. stolen — cookie and a concurrent admin revoke. Verifier reproduced it with an
+integration test against a real engine.
+
+**Fix (`58fc73f`).** `bump_last_seen()` re-reads immediately before writing and
+skips entirely if the session is now gone or revoked, writing only the fresh
+record — a revocation can no longer be undone. 2 regression tests
+(`bump_does_not_resurrect_a_revoked_session`, `bump_refreshes_a_live_session`).
+
+---
+
+## DESER-EGRESS-01 — Unauthenticated Raft control messages on the cluster port · High · tracked
+
+`crates/xerj-cluster/src/transport.rs:59` (`read_frame` → `handle_connection`).
+
+**Instruction/data.** The bytes off a raw TCP socket *are* the control
+instruction: `serde_json::from_slice` reconstructs a `RaftMessage` whose variant
+tag (`AppendEntries`/`RequestVote`/…) and fields become consensus instructions,
+with **no authentication of any kind** before or after the parse. (There is a
+10 MiB frame cap, so this is not an unbounded-alloc DoS, and serde_json is not a
+gadget-chain deserializer — the risk is forged consensus, not RCE.)
+
+**Attacker input.** One TCP connection to the cluster port (default `9300`):
+`[len][node_id]` then `[len]{"RequestVote":{"term":999999999,"candidate_id":"attacker",…}}`
+— a term-bump can disrupt/steer the cluster's consensus.
+
+**Reachability.** Operator-gated: only active when `cluster.enabled=true`; then the
+port binds `0.0.0.0` and trusts any peer. This is exactly PR #69's deferred
+"cluster Raft auth" item.
+
+**Status.** Not fixed in `58fc73f` — the fix (a shared cluster secret / per-frame
+HMAC, or mTLS peer-cert pinning before deserialize) is a design change tracked as
+the Raft-auth Phase-2 item. Source-verified, not exploited on a live cluster.
+
+---
+
+## S5-4 — `x-forwarded-for` trusted as identity for rate-limiting and audit · Medium · open
+
+`crates/xerj-console-api/src/auth/magic.rs:360`, `rate_limit.rs:58`.
+
+**Instruction/data.** An attacker-controlled header is consumed as an identity
+instruction with no trust boundary: it is interpolated into the rate-limit bucket
+key (`format!("{ip}:{endpoint}:m")`) and recorded as the audit-log source IP.
+
+**Attacker input / live proof.** `POST …/auth/magic/redeem` with a rotating
+`x-forwarded-for: 1.2.3.$RANDOM` resets the quota every request (brute-force the
+magic-link/bootstrap token unthrottled) and writes attacker-chosen source IPs into
+the audit log. Confirmed unauthenticated (the endpoint is registered
+"unauthenticated" and the handler body runs for anonymous callers).
+
+**Fix.** Derive the caller address from `ConnectInfo<SocketAddr>` (the transport),
+and consult `x-forwarded-for` only when the socket peer is a trusted proxy in an
+operator-configured CIDR.
+
+---
+
+## S5-3 — Magic-link single-use / bootstrap-claim is TOCTOU · Medium · open
+
+`crates/xerj-console-api/src/auth/magic.rs:221`.
+
+**Instruction/data (state machine).** "This link may be consumed at most once" is
+checked against state read at `magic.rs:210` and only committed at `:299`, several
+awaits later, with no exclusive lock — a concurrent request re-reads the un-consumed
+state in the window. Two redeems of the same token in one TCP burst can both
+succeed; on the bootstrap-claim path that can mean two admin claims. The per-IP
+limiter that would cap parallelism is itself bypassable (see S5-4).
+
+**Fix.** Make consumption an atomic state transition performed first, under a
+per-token exclusive lock, before any purpose-specific work.
+
+---
+
+## S5-5 — `max_fields_per_index` bypassed on the explicit-mapping path · Low · open
+
+`crates/xerj-engine/src/index.rs:14198` (`Index::add_fields`).
+
+**Instruction/data (missing-guard).** This is the "where is PR #69's pattern
+missing" result. #69 added the field-cap guard (and a re-check under the write
+lock) to both *dynamic-mapping* paths, but the *explicit* path —
+`PUT /:index/_mapping` and `POST /v1/schema/:name/evolve` → `add_fields` — never
+checks the cap. Send the fields explicitly instead of letting them be inferred and
+the mapping-explosion limit does not apply.
+
+**Severity.** Low: reachable only by a superuser-equivalent credential that already
+holds destructive powers (delete index, unbounded bulk). It is an operator-limit
+bypass / ES-compat divergence, not a privilege escalation.
+
+**Fix.** Move the invariant to the mutation point — make `add_field`/`ManagedSchema`
+enforce the limit the way `apply_document(value, limit)` already does.
+
+---
+
+## AUTHZ-2 — `/_xerj-console/api/v1/cluster/info` unauthenticated disclosure · Info · open
+
+`crates/xerj-console-api/src/router.rs:49` (`cluster::info`).
+
+**Privilege-map gap** (not an instruction/data bug). `cluster::info` takes only
+`State`, no `AuthSession`, so unlike every other console endpoint it applies no
+auth check — and the console router is merged onto both listeners. Live, with
+`auth.enabled=true` and a non-empty admin key, `curl http://host:9200/_xerj-console/api/v1/cluster/info`
+returns `node_id`, exact `version` (`1.0.0-rc.6`), and uptime with no credential.
+
+**Fix.** Drop `version`/`node_id` from the pre-auth response and gate the full
+payload behind `AuthSession`, or accept and document it as an intentional pre-auth
+health probe.
+
+---
+
+## Refuted (the load-bearing number)
+
+Eight proposed findings did **not** survive verification — a 50% cull. The most
+instructive was a path-traversal candidate (`F-PATH-01`) where every code
+observation the finder made was correct and the finding was still wrong: the
+guard it claimed was missing lived in the caller. A finder without an independent,
+refutation-first verifier would have published it. That is why every number here
+comes from the surviving half, and every HIGH was additionally re-verified by hand.
diff --git a/docs/case-studies/xerj-self-audit/ISSUES.md b/docs/case-studies/xerj-self-audit/ISSUES.md
new file mode 100644
index 000000000..d5afd177c
--- /dev/null
+++ b/docs/case-studies/xerj-self-audit/ISSUES.md
@@ -0,0 +1,223 @@
+# Issue drafts — five-stage instruction/data audit pass
+
+**DRAFTS ONLY. Not filed.** Both findings below are network-reachable and
+**unfixed** on `main`. Public disclosure before a fix ships is a security
+decision for a human to make, not an agent — nothing here was posted via `gh`.
+Full detail, taint paths and live-reproduction transcripts:
+[FINDINGS-V2.md](FINDINGS-V2.md).
+
+Suggested handling: fix both on a private branch, then open these as public
+issues (or a security advisory) once a release carries the fix.
+
+**Shared caveat for both severity labels.** Both routes sit behind
+`auth_middleware`, but `crates/xerj-api/src/auth.rs:96` short-circuits to fully
+open when `admin_api_key` is empty, and `--insecure` disables auth outright. In
+either configuration both issues are **unauthenticated**.
+
+---
+
+## Draft 1 of 2
+
+**Title:** `security: search-template params are spliced into the query JSON unescaped and re-parsed (a param can drop the template's security filter)`
+
+**Labels:** `security`, `es-compat`, `bug`
+**Severity:** High
+**Reachability:** authenticated-network — app-mediated (the application supplies
+the trusted template; the untrusted party supplies only `params`)
+
+### Summary
+
+`render_template` merges untrusted `params` into a trusted query template with a
+raw `String::replace` and no escaping, then re-parses the merged string as JSON.
+A param value carrying JSON structural tokens is re-interpreted as query
+structure, so a param can **delete a security filter the template encoded**.
+This defeats the exact contract search templates exist to provide.
+
+### Code
+
+`crates/xerj-api/src/es_compat.rs:23160`
+
+```rust
+fn render_template(source: &str, params: &serde_json::Map<String, Value>) -> String {
+ let mut result = source.to_string();
+ for (key, val) in params {
+ let placeholder = format!("{{{{{}}}}}", key);
+ let replacement = match val {
+ Value::String(s) => s.clone(),
+ Value::Number(n) => n.to_string(),
+ Value::Bool(b) => b.to_string(),
+ Value::Null => "null".to_string(),
+ other => other.to_string(),
+ };
+ result = result.replace(&placeholder, &replacement); // no escaping
+ }
+ result
+}
+```
+
+Consumed at `es_compat.rs:23205-23206` (`search_template`), `23408`
+(`msearch_template_impl`), `23520` (`render_template_api`) — each one
+`render_template(...)` then `serde_json::from_str(&rendered)` then
+`xerj_query::parse_request`.
+
+Routes: `POST /:index/_search/template` (`router.rs:543`),
+`POST /_msearch/template` (`router.rs:545`), `POST /_render/template`
+(`router.rs:553`).
+
+### Reproduction
+
+```bash
+# application's trusted template encodes an ACL filter
+TMPL='{"query":{"bool":{"filter":[{"term":{"visibility":"public"}}]}},"size":{{size}}}'
+
+# benign: 1 hit (public doc only)
+curl -s localhost:9200/idx/_search/template -H 'Content-Type: application/json' \
+ -d "{\"source\":\"$(echo "$TMPL" | sed 's/"/\\"/g')\",\"params\":{\"size\":50}}"
+
+# injected: 2 hits, including the private doc — the filter is gone
+curl -s localhost:9200/idx/_search/template -H 'Content-Type: application/json' \
+ -d "{\"source\":\"...\",\"params\":{\"size\":\"50,\\\"query\\\":{\\\"match_all\\\":{}}\"}}"
+```
+
+Rendered output is `... "size":50,"query":{"match_all":{}}}` — a duplicate
+`query` key; `serde_json` keeps the last, dropping the filter.
+`POST /_render/template` with the same params echoes
+`{"query":{"match_all":{}},"size":50}`, which shows the rewrite with no index
+state at all.
+
+Verified on two independent throwaway servers (ports 9317 and 9319).
+
+### Scope note
+
+The **stored-id** path (`PUT /_scripts/{id}` then `{"id":...}`) double-encodes and
+returns `template rendered to invalid JSON` — it breaks rather than executes. The
+exploitable vector is inline `source` + untrusted `params`.
+
+### Suggested fix
+
+Stop substituting-then-parsing. Preferred: parse `source` into a
+`serde_json::Value` first and substitute **whole leaf `Value`s** by key, so a
+param is always exactly one JSON node and can never emit structural tokens.
+
+Acceptable alternative: JSON-escape every `String` replacement, reject params in
+non-string positions unless they parse as a standalone JSON scalar, and implement
+the Mustache distinction — `{{x}}` escaped, `{{{x}}}` raw.
+
+Add regression tests for: a param containing `"`, a param containing
+`,"query":{...}`, a numeric-position param containing `,`, and `{{{x}}}` still
+allowing intentional raw injection.
+
+---
+
+## Draft 2 of 2
+
+**Title:** `security: snapshot repository settings.location is unvalidated — snapshots write and copy every index outside data_dir (no path.repo equivalent)`
+
+**Labels:** `security`, `es-compat`, `bug`
+**Severity:** High
+**Reachability:** authenticated-network
+
+### Summary
+
+`PUT /_snapshot/{repo}` stores `settings.location` verbatim, and
+`Engine::create_snapshot` uses it as the **root** of the snapshot path. The
+containment check derives its reference point from that same attacker-supplied
+string, so it is tautologically satisfied. Result: a caller can make the server
+`create_dir_all` + recursively copy **every user index** into any directory the
+process can write.
+
+Elasticsearch requires the location to be inside a `path.repo` allowlist in
+`elasticsearch.yml` and refuses the registration otherwise. XERJ has no
+equivalent — `grep -rnE 'path\.repo|repo_allowlist|snapshot_root' crates`
+returns **0 lines**.
+
+### Code
+
+`crates/xerj-engine/src/engine.rs:1562`
+
+```rust
+let snap_dir = std::path::Path::new(repo_path).join(name);
+let snap_dir = validate_snapshot_path(repo_path, name, &snap_dir)?;
+std::fs::create_dir_all(&snap_dir).map_err(EngineError::Io)?;
+```
+
+The check, `engine.rs:1877` inside `validate_snapshot_path` — note `repo_canon`
+comes from `repo_path`, i.e. from the request:
+
+```rust
+let repo_canon = std::path::Path::new(repo_path)
+ .canonicalize()
+ .unwrap_or_else(|_| std::path::PathBuf::from(repo_path));
+if let Ok(snap_canon) = snap_dir.canonicalize() {
+ if !snap_canon.starts_with(&repo_canon) { /* refuse */ }
+```
+
+Where `repo_path` originates, `crates/xerj-api/src/es_compat.rs:22098`:
+
+```rust
+let repo_path = repo_config
+ .pointer("/settings/location")
+ .and_then(Value::as_str)
+ .unwrap_or("/tmp/xerj-snapshots");
+```
+
+And the registration that stores it unmodified, `es_compat.rs:22024`
+(`put_snapshot_repo`) — it validates the repo **name** only, then
+`state.engine.snapshot_repos.insert(repo, body);`.
+
+Three filters exist (`validate_snapshot_repo_name` `es_compat.rs:21991`,
+`validate_snapshot_name` `es_compat.rs:22004`, `validate_snapshot_path`
+`engine.rs:1852`) and **all three guard names, none guards the location.**
+
+### Reproduction
+
+```bash
+curl -XPUT localhost:9200/_snapshot/evil \
+ -H 'Content-Type: application/json' \
+ -d '{"type":"fs","settings":{"location":"/tmp/OUTSIDE_DATADIR"}}'
+curl -XPUT localhost:9200/_snapshot/evil/s1 -d '{}'
+# -> {"accepted":true, ... "state":"SUCCESS"}
+find /tmp/OUTSIDE_DATADIR
+```
+
+Observed on disk, entirely outside `data_dir`:
+
+```
+/s1/manifest.json
+/s1/myindex/{schema.json,snapshot.json,xerj_meta.json}
+/s1/myindex/wal/{s0..s15}
+/s1/myindex/segments/<uuid>.{seg,sidx,ids,dv}
+/s1/myindex/segments/<uuid>.secret.{fst,post,meta,norms}
+```
+
+`"location":"../../../../tmp/pwn"` works identically: `canonicalize()` either
+resolves the traversal (and `repo_canon` becomes the escaped path) or fails and
+the code falls back to `PathBuf::from(repo_path)` verbatim — in **both** branches
+`repo_canon` is the attacker's root.
+
+### Impact
+
+1. Arbitrary recursive directory creation and file write anywhere the process uid
+ can write (docroot, log dir, watched/import dir).
+2. Exfiltration of every index's raw stored fields, doc values and postings to a
+ path the attacker can read by other means.
+3. Unbounded disk fill on any mounted filesystem.
+
+### Suggested fix
+
+1. Add an operator allowlist to `Config` — e.g.
+ `snapshot.allowed_repo_roots: Vec<PathBuf>`, **default empty = snapshots
+ disabled**, mirroring ES's `path.repo` posture.
+2. Validate `settings.location` in `put_snapshot_repo` at **registration** time:
+ require absolute, `canonicalize()`, require `starts_with` a configured root,
+ else reject the registration.
+3. Change `validate_snapshot_path` to take its containment root from **config**,
+ never from `repo_path`. A check whose reference point comes from the request is
+ not a check.
+4. Apply the same root on the read side (`Engine::restore_snapshot`,
+ `engine.rs:1654`, which reads `manifest.json` from the same chosen directory).
+
+Regression tests: absolute location outside every configured root -> rejected at
+registration; `..` location -> rejected; empty allowlist -> snapshot API returns a
+clear "snapshots not configured" error; a location inside a configured root ->
+still works.
diff --git a/docs/case-studies/xerj-self-audit/METHODOLOGY.md b/docs/case-studies/xerj-self-audit/METHODOLOGY.md
new file mode 100644
index 000000000..5f824d26d
--- /dev/null
+++ b/docs/case-studies/xerj-self-audit/METHODOLOGY.md
@@ -0,0 +1,303 @@
+# The instruction/data whitebox methodology
+
+A reusable five-stage playbook for auditing a large codebase, and the measured
+cost of running it **with** an AST/call-graph substrate versus **with grep on the
+raw tree**. Run here against XERJ's own Rust engine (197 files, ~201k lines, 16
+crates); the method is language-agnostic.
+
+## The principle
+
+> **A function is dangerous when INSTRUCTION and DATA share one channel with no
+> separator.**
+
+That is the whole test. It is sharper than a category checklist because it tells
+you *why* something is a sink and *what* would actually fix it:
+
+| Channel | Instruction component | Data component | Separated (safe) form |
+|---|---|---|---|
+| SQL string | `SELECT`, `WHERE`, `,`, `'` | identifiers, literals | bound parameter `?` — a structural placeholder the parser resolves *after* parsing. Identifiers cannot be bound, so the only safe forms are dialect quoting with escape-doubling, or a schema allowlist. |
+| Filesystem path | `/`, `..`, an absolute prefix | a name component | a validated opaque token, plus canonicalize-then-contain **before** any destructive op |
+| Process argv | a leading `-` (option) | an argument value | `--` end-of-options, or `arg("--opt=VALUE")`, or a child that does no getopt parsing at all |
+| Serialized bytes | type / construction tags | field values | a fixed target type with no polymorphic tag, plus a size/depth budget |
+| Query DSL / template | JSON structure, query keys | user params | parse-then-substitute-whole-nodes; never substitute-then-parse |
+
+And the corollary that catches most real bugs:
+
+> **A filter is only real if it removes the INSTRUCTION power from the DATA
+> channel.** "It calls `escape()`" is not enough. Shell-escaping quotes
+> metacharacters and does **nothing** against option injection. A containment
+> check is not real if its reference point is attacker-supplied.
+
+The two worked examples below (INJ-01, F-PATH-02) are corollary failures, not
+missing-filter failures. Every one of the three filters guarding the snapshot path
+is real, well-written, and tested — and the vulnerability is in the un-validated
+sibling
+field none of them look at.
+
+## Two structural reasons grep loses, before any token count
+
+1. **The unit of a hit.** An AST hit is a **function**. A grep hit is a **line**,
+ which forces you to read the whole **file** to judge it. In this codebase the
+ ratio is brutal: `render_template` is 20 lines inside
+ `crates/xerj-api/src/es_compat.rs`, a **31,221-line / 273,864-token** file.
+ The substrate hands you the 20 lines and the 8 call edges into them.
+2. **Absence is not greppable.** Stage 4's whole job is finding a check that is
+ *not there*. `grep -rnE 'path\.repo|repo_allowlist|snapshot_root' crates`
+ returns **0 lines** on this tree — and that zero is exactly the F-PATH-02
+ vulnerability (no snapshot-location allowlist exists). A `must_not` clause
+ over a validator field expresses it in one query; a regex cannot express it at
+ all. This is the same class as PR #69's F7/F8, which grep also could not reach.
+
+## The five stages
+
+Substrate: three indices over the current tree — `rustfns` (5,098 functions),
+`rustcalls` (87,150 caller→callee edges), `rustroutes` (477 axum registrations).
+Non-test function population: **3,437**; handler-shaped: **298**.
+
+### Stage 1 — Flag every dangerous END function (sink), by the instruction/data test
+
+Enumerate sinks per channel class, then judge each by whether the data component
+retains instruction power.
+
+```bash
+curl -s "http://127.0.0.1:9310/rustfns/_search" -H 'Content-Type: application/json' -d '{
+ "query":{"bool":{"filter":[{"term":{"is_test":false}}],
+ "should":[{"term":{"sinks":"fs_path_join"}},{"term":{"sinks":"fs_write"}},
+ {"term":{"sinks":"fs_delete"}},{"term":{"sinks":"fs_rename"}},
+ {"term":{"sinks":"process"}},{"term":{"sinks":"deserialize"}},
+ {"term":{"sinks":"sql_ish"}},{"term":{"sinks":"net_egress"}}],
+ "minimum_should_match":1}},
+ "_source":["crate","file","fn_name","line_start","sinks","validators","path_join_from_param","signature"],
+ "size":1000}'
+```
+
+→ **318 functions**, 40,623 tokens of projected metadata.
+
+Sink census (non-test functions), with the verdict the instruction/data test produced:
+
+| sink class | functions | verdict |
+|---|---|---|
+| `log_secret` | 210 | heuristic, mostly benign logging |
+| `fs_path_join` | 149 | **the productive class** — 22 join from a parameter |
+| `deserialize` | 147 | fixed target types, no polymorphic tag → informational |
+| `fs_write` | 49 | filenames internally generated except the snapshot path |
+| `spawn` | 31 | internal task spawn, no argv |
+| `fs_rename` | 16 | internal segment/WAL tokens only |
+| `fs_delete` | 14 | all under a validated or reserved-prefix directory |
+| `net_egress` | 13 | operator-config endpoints |
+| `sql_ish` | 4 | **1 real, 3 false positives** (see the precision note) |
+| `process` | 2 | 1 real, and it is safe by child design (see below) |
+
+**Precision note, stated because a case study that hides it is worthless:**
+`sinks:sql_ish` is **noisy — 4 hits, 1 real**. The three
+`crates/xerj-fts/src/search.rs` hits (`search_bounded:503`, `execute_bool:1019`,
+`execute_dis_max:1124`) are false positives triggered by the English word
+"union" in the comment `// If no must clauses, candidate set is the union of
+should docs`. Do not treat `sql_ish` as a trustworthy filter. The substrate is a
+strong **filter** and a mediocre **ranker** — every candidate was read.
+
+**Grep baseline** (the union of sink regexes an auditor would actually write):
+
+```bash
+grep -rn --include='*.rs' -E 'Command::new|process::Command|fs::(read|write|remove_file|remove_dir_all|rename|create_dir_all|File::(open|create))|\.join\(|from_str|from_slice|from_reader|reqwest|TcpStream|format!\(.*(SELECT|WHERE|FROM)' crates
+```
+
+→ **1,132 match lines across 110 distinct files = 1,585,177 tokens** to read.
+That is 88% of the entire codebase, returned by one stage-1 sweep.
+
+### Stage 2 — Trace each sink back to user input (the call graph)
+
+```bash
+curl -s "http://127.0.0.1:9310/rustcalls/_search" -H 'Content-Type: application/json' \
+ -d '{"query":{"term":{"callee":"render_template"}},
+ "_source":["caller","file","line","kind","resolvable"],"size":100}'
+```
+
+Walk callers until you hit a `rustroutes` handler. For the two injection/path
+examples that walk was: `render_template` (8 caller edges) → `search_template` /
+`msearch_template_impl` / `render_template_api`; `create_snapshot` (3) and
+`validate_snapshot_path` (2) → `es_compat::create_snapshot` → route.
+
+→ **13 caller edges across 4 queries, 1,232 tokens.** The result is a *directed*
+answer: these callers, at these lines.
+
+**Grep baseline:** `grep -rn 'render_template|create_snapshot|validate_snapshot_path'`
+→ 23 lines / 5 files / **374,872 tokens** — and it is undirected (callers and
+the definition and the tests, indistinguishable). More importantly it only works
+**if you already know the function name**, which is the thing stage 1 had to tell
+you. Discovering `render_template` by grep instead means the generic
+"data merged into a parsed string" sweep: `grep -rln 'serde_json::from_str'` → 20
+files / **772,182 tokens**.
+
+### Stage 3 — Map the privilege model and where each check applies
+
+```bash
+# every route registration
+curl -s ".../rustroutes/_search" -d '{"query":{"match_all":{}},"_source":["method","path","handler","file","line"],"size":500}'
+# every function that performs an auth check
+curl -s ".../rustfns/_search" -d '{"query":{"bool":{"filter":[{"term":{"is_test":false}},{"term":{"validators":"auth"}}]}}}'
+```
+
+→ **477 routes + 24 auth-validating functions, 40,218 tokens.** This is what
+lets you say "authenticated-network" rather than guessing: the route table maps
+path → handler → file:line, and the auth set shows the check lives in
+middleware, not per-handler.
+
+It also surfaces the **most important qualifier in this whole report**, at
+`crates/xerj-api/src/auth.rs:96`:
+
+```rust
+// Skip auth when disabled or no admin key is configured.
+if !cfg.enabled || cfg.admin_api_key.is_empty() {
+ return true;
+}
+```
+
+`auth.enabled = true` is the shipped default (`xerj.default.toml:47`), but an
+**empty** `admin_api_key` short-circuits to fully open — and the documented
+`--insecure` quickstart flag disables auth outright. Every
+"authenticated-network" severity below becomes unauthenticated in those two
+configurations.
+
+**Grep baseline:** `grep -rnE 'auth|api_key|require_admin|is_admin|role|permission|middleware'`
+→ 874 lines / 73 files / **1,271,510 tokens**, and it produces no route table at
+all — the `.route()` calls are what you actually need, and they are one grep
+further on.
+
+### Stage 4 — Validate every filter for BYPASSES
+
+The stage where absence-queries earn their keep: **sink present, filter absent.**
+
+```bash
+curl -s "http://127.0.0.1:9310/rustfns/_search" -H 'Content-Type: application/json' -d '{
+ "query":{"bool":{
+ "filter":[{"term":{"is_test":false}},{"term":{"path_join_from_param":true}}],
+ "must_not":[{"term":{"validators":"containment"}},
+ {"term":{"validators":"explicit_validate"}},
+ {"term":{"validators":"typed_name"}}]}},
+ "_source":["crate","file","fn_name","line_start","sinks","validators","path_join_args"],"size":500}'
+```
+
+→ **18 functions** (out of 22 that join a path from a parameter), **1,940
+tokens**. Then read all 18 and ask the corollary question, not the presence
+question. The four bypass sub-classes to test:
+
+1. **Wrong reference point.** The check is real but measured against
+ attacker-supplied data. → **F-PATH-02**: `snap_dir.starts_with(repo_canon)`
+ where `repo_canon` derives from the same request field, making the assertion
+ tautological.
+2. **Wrong channel.** Every check is on the field you expected the attack in;
+ the attack goes in the un-validated sibling. → F-PATH-02 again: three filters
+ harden the repo **name** and snapshot **name**; nothing validates
+ `settings.location`.
+3. **Escaping the wrong alphabet.** Shell-metacharacter escaping vs option
+ injection; HTML escaping vs JSON structure. → **INJ-01**: `String::replace`
+ with no JSON escaping at all, then a re-parse.
+4. **Order of operations.** Validate-after-destroy. Checked explicitly here:
+ `guard_after_destructive_op` is `true` for exactly **1** non-test function in
+ the tree, and that one is a detector false positive — PR #69's
+ validate-after-`remove_dir_all` bug in `restore_snapshot` is genuinely gone.
+
+**Grep baseline:** there is no grep for "has a join and no containment check".
+The honest substitute is to read every file containing the sink:
+`grep -rnE '\.join\(|Path::new|PathBuf::from|canonicalize'` → 711 lines / **66
+files / 1,317,109 tokens**. Narrowed to just the write sinks
+(`create_dir_all|fs::write|copy_dir_recursive`) it is still 137 lines / 27 files
+/ **622,709 tokens**. And for the *absent* allowlist, grep returns 0 lines —
+there is nothing to match.
+
+### Stage 5 — State machines: TOCTOU, deadlock, lock-across-await
+
+```bash
+curl -s "http://127.0.0.1:9310/rustfns/_search" -H 'Content-Type: application/json' -d '{
+ "query":{"bool":{"filter":[{"term":{"is_test":false}}],
+ "should":[{"term":{"lock_across_await":true}},{"term":{"guard_after_destructive_op":true}}],
+ "minimum_should_match":1}},
+ "_source":["crate","file","fn_name","line_start","concurrency","lock_across_await","guard_after_destructive_op","is_async"],"size":500}'
+```
+
+→ **16 functions, 1,814 tokens** (15 `lock_across_await`, 1
+`guard_after_destructive_op`). A complete, readable population.
+
+**Grep baseline:** `grep -rnE '\.(lock|write|read)\(\)|\.await|Atomic|Ordering::Relaxed|exists\(\)|spawn_blocking|block_on'`
+→ **3,377 lines / 96 files / 1,381,258 tokens** — and it is structurally the
+wrong shape: "a guard held *across* an await" is a relationship between two lines
+in one function body, which a line-scoped regex cannot express. You get the
+`.lock()` lines and the `.await` lines as separate unordered sets.
+
+## Measured with/without comparison
+
+Every token figure is measured with **tiktoken `cl100k_base`** (a public
+GPT-4-class BPE used as an LLM-token proxy) — not a chars÷4 estimate. The XERJ
+column is the actual projected result payload; the grep column is the sum of the
+distinct files each grep forces you to open, because a grep hit is a line and a
+judgment needs the file.
+
+| Stage | XERJ query returns | XERJ tokens | grep lines | grep files | grep tokens | ratio |
+|---|---:|---:|---:|---:|---:|---:|
+| 1 · Flag dangerous sinks | 318 functions | 40,623 | 1,132 | 110 | 1,585,177 | **39×** |
+| 2 · Trace to user input | 13 caller edges | 1,232 | 23 | 5 | 374,872 | **304×** |
+| 3 · Privilege model + flows | 477 routes + 24 auth fns | 40,218 | 874 | 73 | 1,271,510 | **32×** |
+| 4 · Validate filters for bypass | 18 functions | 1,940 | 711 | 66 | 1,317,109 | **679×** |
+| 5 · State machines | 16 functions | 1,814 | 3,377 | 96 | 1,381,258 | **761×** |
+| **Total, per-stage sum** | | **85,827** | **6,117** | — | **5,929,926** | **69×** |
+| **Total, deduplicated file union** | | **85,827** | | **153** | **1,685,346** | **19.6×** |
+
+Two totals, deliberately. The per-stage sum (69×) is what an auditor working
+stage by stage actually pays. The **deduplicated union (19.6×) is the honest
+floor** — and it carries the more damning number: the five grep sweeps together
+touch **153 of the 197 `.rs` files**, i.e. **1,685,346 of the 1,805,277 tokens in
+the entire engine (93%)**. Grepping the five stages *is* reading the codebase,
+just in a worse order and without the call graph. For reference, reading all 197
+files outright is 1,805,277 tokens — only 7% more than the grep union, and ~9× a
+200k context window.
+
+### Recall on this pass
+
+| | XERJ substrate | grep baseline |
+|---|---|---|
+| Confirmed findings reached | **2 / 2** | 1 / 2 discoverable in principle |
+| Refuted before publication | 1 | — |
+
+- **INJ-01** is reachable by grep *only if you already know the name*
+ `render_template` (2 files, cheap). Discovering it without the name costs the
+ generic 20-file / 772,182-token sweep, and the defect is at line 23,160 of a
+ 273,864-token file.
+- **F-PATH-02**'s *sink* is greppable (`create_dir_all` is in the 27-file set).
+ The *defect* is not: it is (a) an allowlist that does not exist —
+ `grep -rnE 'path\.repo|repo_allowlist|snapshot_root'` = **0 lines** — and (b)
+ the judgment that a real containment check is measured against attacker data.
+ Neither is expressible as a regex. We count this as grep-unreachable and say
+ why, rather than claiming grep cannot see `create_dir_all`.
+
+Prior calibration on labelled ground truth (PR #69's six known bugs) is in
+[DETECTION-QUALITY.md](DETECTION-QUALITY.md): **6/6 vs grep's 4/6**, at 84,122 vs
+2,715,003 triage tokens. That run's first attempt scored 3/6 — worse than grep —
+and the test set is what exposed three real extractor defects. Recall claims
+without a labelled set are worth nothing.
+
+## What the method does not cover
+
+- **Macro-generated code, trait-object dynamic dispatch, and `build.rs` codegen**
+ are invisible to the substrate (see [COVERAGE.md](COVERAGE.md)).
+- **Callee resolution is name-based.** Method-call edges (`is_method: true`) are
+ unresolved; only free/path calls (`resolvable: true`) form a reliable graph. A
+ taint path through a trait object will be missed.
+- **Precision is the weak axis.** The five stages' candidates yielded 8 confirmed
+ findings across sixteen that reached verification. The substrate filters
+ thousands of functions down to a readable set; it does not rank, and it produces
+ confident false positives (the `sql_ish`/"union" case). A finder without a
+ verifier would have published them.
+- **Half of the proposed findings were refuted** at the verify stage (8 confirmed,
+ 8 refuted). That 50% cull — including one where every code observation was
+ correct and the finding was still wrong — is the argument for the
+ adversarial-refutation step, not a footnote to it. The synthesis layer needs the
+ same scrutiny: its auto-summary under-counted the confirmed set as 2, caught only
+ by reconciling against the raw per-finding verdicts.
+
+## Reproducing
+
+Substrate build: **~3.2s extract + ~1.9s ingest**, 31 MB on disk. Extractor,
+cycle-finder, quality harness and the full query cookbook:
+[`../../examples/rust-ast-audit/`](../../examples/rust-ast-audit/). Step-by-step:
+[REPRODUCE.md](REPRODUCE.md).
diff --git a/docs/case-studies/xerj-self-audit/README.md b/docs/case-studies/xerj-self-audit/README.md
index 355cdcdea..2044efb9e 100644
--- a/docs/case-studies/xerj-self-audit/README.md
+++ b/docs/case-studies/xerj-self-audit/README.md
@@ -140,3 +140,60 @@ flagged.
three functions with no depth guard anywhere in it," or "a `.join()` of a
request parameter with no containment check in the same function." The call
graph makes both a single query.
+
+## Five-stage methodology (second pass)
+
+A second, deeper pass (24 Fable-5 agents, adversarially verified) replaced the
+category checklist with a single organizing principle and ran five stages against
+it. Full reusable playbook — principle, taxonomy, the XERJ query and the grep
+baseline for every stage: **[METHODOLOGY.md](METHODOLOGY.md)**. All eight findings,
+severity-ranked: **[FINDINGS-V2.md](FINDINGS-V2.md)**. Issue drafts:
+**[ISSUES.md](ISSUES.md)**.
+
+> **A function is dangerous when INSTRUCTION and DATA share one channel with no
+> separator** — and a filter is only real if it removes the instruction power
+> from the data channel. "It calls `escape()`" is not enough.
+
+The strongest findings are failures of that corollary rather than missing filters:
+in F-PATH-02 all three filters guarding the snapshot *name* are real, well-written
+and tested, and the vulnerability is in the un-validated sibling field (the repo
+*location*) none of them look at.
+
+| Stage | XERJ query returns | XERJ tokens | grep lines | grep files | grep tokens | ratio |
+|---|---:|---:|---:|---:|---:|---:|
+| 1 · Flag dangerous sinks | 318 functions | 40,623 | 1,132 | 110 | 1,585,177 | **39×** |
+| 2 · Trace to user input | 13 caller edges | 1,232 | 23 | 5 | 374,872 | **304×** |
+| 3 · Privilege model + flows | 477 routes + 24 auth fns | 40,218 | 874 | 73 | 1,271,510 | **32×** |
+| 4 · Validate filters for bypass | 18 functions | 1,940 | 711 | 66 | 1,317,109 | **679×** |
+| 5 · State machines (TOCTOU/locks) | 16 functions | 1,814 | 3,377 | 96 | 1,381,258 | **761×** |
+| **Total, per-stage sum** | | **85,827** | **6,117** | — | **5,929,926** | **69×** |
+| **Total, deduplicated file union** | | **85,827** | | **153** | **1,685,346** | **19.6×** |
+
+All figures measured with tiktoken `cl100k_base`. Two totals on purpose: the
+per-stage sum (69×) is what an auditor working stage by stage pays; the
+deduplicated union (**19.6×**) is the honest floor, and it carries the sharper
+point — the five grep sweeps together touch **153 of 197 `.rs` files, 93% of the
+engine's 1,805,277 tokens**. Grepping the five stages *is* reading the codebase,
+in a worse order and without the call graph.
+
+**Result: 8 confirmed, 8 refuted (a 50% cull).** By verifier-corrected severity:
+**4 High** (INJ-01 search-template injection, F-PATH-02 snapshot-location
+traversal, S5-1 session-revocation lost-update, DESER-EGRESS-01 unauthenticated
+Raft control messages), **2 Medium** (S5-4 `x-forwarded-for` trust, S5-3
+magic-link TOCTOU), **1 Low** (S5-5 field-limit bypass on the explicit path), **1
+Info** (AUTHZ-2 unauth `cluster/info` disclosure). The three application-layer
+Highs are **fixed** on this branch (`58fc73f`, with regression tests and live
+before/after proof); DESER-EGRESS-01 is tracked as the cluster Raft-auth Phase-2
+item.
+
+An honesty note carried into [FINDINGS-V2.md](FINDINGS-V2.md): the workflow's
+auto-synthesis under-reported this as "2 confirmed, 1 refuted." The eight
+per-finding verifiers had actually confirmed eight; the gap was caught by
+reconciling the synthesis against the raw verdicts, and each High was re-verified
+by hand before publication — a reminder that the synthesis layer needs auditing
+too.
+
+The refuted half is load-bearing: the most instructive miss (`F-PATH-01`) had
+every code observation correct and was still wrong, because the guard it thought
+was missing lived in the caller. A finder without an independent,
+refutation-first verifier would have shipped it.
diff --git a/docs/examples/rust-ast-audit/whitebox_methodology_wf.js b/docs/examples/rust-ast-audit/whitebox_methodology_wf.js
new file mode 100644
index 000000000..7cf358905
--- /dev/null
+++ b/docs/examples/rust-ast-audit/whitebox_methodology_wf.js
@@ -0,0 +1,393 @@
+export const meta = {
+ name: 'xerj-whitebox-methodology',
+ description: 'Five-stage instruction/data whitebox audit of XERJ with vs without XERJ, adversarially verified, with a measured comparison and issue drafts',
+ phases: [
+ { title: 'Taxonomy', detail: 'instruction/data dangerous-sink taxonomy + per-category XERJ query and grep baseline' },
+ { title: 'Lenses', detail: 'sinks, taint-trace, privilege/filters, filter-bypass, concurrency — each WITH and WITHOUT XERJ' },
+ { title: 'Verify', detail: 'adversarial refutation of every finding, empirical where possible' },
+ { title: 'Synthesize', detail: 'with/without comparison, findings report, case-study section, issue drafts' },
+ ],
+}
+
+const WT = '/home/claude/ai/xerj-rust-audit-wt'
+const SCRATCH = '/tmp/claude-1001/-home-claude-ai-xerj/e36b8c4c-3a94-4a76-80f1-2119380319c6/scratchpad'
+const XERJ = 'http://127.0.0.1:9310'
+const VENV = `${SCRATCH}/astvenv/bin/python`
+
+const GROUND = `
+## The mission (the user's own methodology — follow it precisely)
+
+A single packed WHITEBOX security methodology, run on the XERJ Rust engine, measured
+WITH XERJ (the AST/call-graph substrate) vs WITHOUT (grep + read the raw tree). The
+organizing principle is the user's, and it is sharper than a category list:
+
+ A function is DANGEROUS when INSTRUCTION and DATA share one channel with no separator.
+ - SQL built by string concatenation/format! (instruction+data mixed) vs a prepared
+ statement with bound params (separated). Dangerous = the mixed one.
+ - A filesystem open/join where '/' and '..' in the DATA are interpreted as path
+ INSTRUCTIONS to leave the intended directory.
+ - A shell/process call where argument DATA can carry option INSTRUCTIONS
+ (e.g. a value "-o/tmp/exploit" becomes a flag), even if each arg is shell-escaped —
+ shell-escaping quotes metacharacters but does NOT stop argument/option injection.
+ - Deserialization where DATA bytes carry type/'construction INSTRUCTIONS.
+ A filter/sanitizer is only real if it removes the INSTRUCTION power from the DATA
+ channel. "It calls escape()" is not enough — escape() for shell metacharacters does
+ nothing against option injection.
+
+The five stages (each is a lens below):
+ 1. Flag all dangerous END functions (sinks) by category, by the instruction/data test.
+ 2. Trace each dangerous sink back to user input / taint sources (the call graph).
+ 3. Map the privilege model + flows: which roles/checks/filters apply, and WHERE.
+ 4. Validate every filter/protection for BYPASSES (the shell-escape-vs-option-injection
+ class, path-canonicalization gaps, order-of-check bugs, partial escaping).
+ 5. State machines: race conditions (TOCTOU), transaction/lock deadlocks, lock-across-await.
+
+## The live substrate (USE IT — this is the WITH-XERJ path)
+
+XERJ is running at ${XERJ} (ES-compatible wire). Three indices over CURRENT main:
+ rustfns — one doc per function (5,098 docs). Queryable fields:
+ crate, file, line_start, line_end, fn_name, module_path, owner, trait_impl,
+ is_test, is_async, is_unsafe_fn, is_pub, is_handler_shaped, extractors[],
+ sinks[] (fs_read fs_write fs_delete fs_path_join fs_rename process deserialize
+ net_egress spawn sql_ish log_secret),
+ validators[] (explicit_validate typed_name checked_arith saturating try_convert
+ containment bounds auth),
+ concurrency[] (lock_acquire relaxed_atomic spawn_blocking block_on dashmap),
+ lock_across_await, guard_after_destructive_op, path_join_from_param, path_join_args[],
+ alloc_product, alloc_from_param_count, alloc_args_all[], panic_ops[], has_narrowing_cast,
+ calls_self, has_depth_guard, reads_config_limit, body (the source, up to 12k chars),
+ body_truncated, params, signature, return_type.
+ rustcalls — caller->callee edges (87,150). Fields: caller_id, caller, callee,
+ callee_path, file, line, kind (call|macro), is_method, resolvable.
+ NOTE: method-call edges (is_method:true) are unresolved by name; free/path calls
+ (resolvable:true) are the reliable graph.
+ rustroutes — axum route registrations (477). Fields: method, path, handler, handler_path, file, line.
+Plus *_pre69 mirror indices over the PRE-#69 tree (contains 6 known-fixed bugs — your
+calibration/recall set).
+
+Query examples (agents run these with curl via Bash):
+ curl -s "${XERJ}/rustfns/_search" -H 'Content-Type: application/json' -d '{"query":{"bool":{"filter":[{"term":{"sinks":"process"}},{"term":{"is_test":false}}]}},"_source":["file","fn_name","line_start","body"],"size":50}'
+ curl -s "${XERJ}/rustcalls/_search" -d '{"query":{"term":{"callee":"process_bulk_with_opts"}},"_source":["caller","file","line"],"size":100}' (who calls X → walk toward handlers)
+Boolean terms work as true/false (the old string-only quirk is fixed).
+
+## The WITHOUT-XERJ baseline (measure it honestly, same lens)
+
+For each lens ALSO run the grep an auditor would use on the raw tree at ${WT}/engine, e.g.
+ grep -rn --include='*.rs' -E 'Command::new|process::Command' ${WT}/engine/crates
+Record: how many match LINES, how many distinct FILES (a grep hit forces reading the whole
+file), and whether the true finding is reachable that way at all. The AST hit is a FUNCTION;
+the grep hit is a FILE — that unit difference is the core of the comparison.
+Token measurement helper (use it for both sides): ${VENV} -c "import tiktoken;print(len(tiktoken.get_encoding('cl100k_base').encode(open('F').read())))"
+
+## Environment / how to work
+
+- Repo (read the real code here): ${WT} (branch feat/rust-self-audit; do NOT switch branches)
+- tree-sitter venv python: ${VENV}
+- Existing tooling you may reuse: ${WT}/docs/examples/rust-ast-audit/{rust_ast_index.py,find_recursion_cycles.py,detection_quality.py,QUERY_COOKBOOK.md}
+- You have Bash, Read, Grep. Use curl for XERJ, Read for source, grep for the baseline.
+- To PROVE an exploit you may boot a throwaway server: write a toml with a unique
+ es_compat_port in 9314..9330 and data_dir under ${SCRATCH}, boot it with the Bash
+ tool's run_in_background (NEVER foreground — it gets reaped), poll readiness with
+ \`until curl -s -o /dev/null -w '%{http_code}' localhost:PORT/ | grep -q 200; do sleep 2; done\`,
+ hit it, then \`pkill -f 'es_compat_port = PORT'\`-style cleanup by data_dir path. The
+ server binary is ${WT}/engine/target/release/xerj. Exit 134/139 on a crash IS the proof.
+
+## Known calibration set (do NOT re-report these as new — use them to sanity-check your queries)
+
+PR #69 fixed 6 bugs; the /_sql WHERE-parser stack-overflow (sql.rs) was found by THIS
+project and is already FIXED on this branch. Anything you report must be NEW (present on
+current main) or a genuinely missed sibling. If a lens finds nothing new, "nothing new,
+here is what I swept" is the correct, honest result.
+
+## Honesty rules (public dogfooding case study — truth over headline)
+
+- Every finding cites a real file:line and quotes real code you READ. No invented lines.
+- Distinguish unauthenticated-network vs authenticated vs operator-config vs internal-only.
+ Severity without reachability is noise.
+- A filter-bypass claim must name the concrete bypass input (e.g. an arg value "-oFILE").
+- If you cannot reach a sink from user input, say so — an unreachable dangerous sink is
+ informational, not a vulnerability.
+- Measure both sides of every comparison or omit the claim.
+`
+
+phase('Taxonomy')
+
+const TAX_SCHEMA = {
+ type: 'object', additionalProperties: false,
+ required: ['categories', 'notes'],
+ properties: {
+ notes: { type: 'string' },
+ categories: {
+ type: 'array',
+ items: {
+ type: 'object', additionalProperties: false,
+ required: ['category', 'instruction_data_rationale', 'xerj_query', 'xerj_candidate_count', 'grep_baseline', 'grep_file_count', 'separated_safe_form'],
+ properties: {
+ category: { type: 'string' },
+ instruction_data_rationale: { type: 'string', description: 'why mixing instruction+data here is dangerous, and what the separated safe form is' },
+ separated_safe_form: { type: 'string' },
+ xerj_query: { type: 'string', description: 'the exact curl/query body used' },
+ xerj_candidate_count: { type: 'integer' },
+ grep_baseline: { type: 'string' },
+ grep_file_count: { type: 'integer' },
+ },
+ },
+ },
+ },
+}
+
+const taxonomy = await agent(
+`STAGE 1 — DANGEROUS-SINK TAXONOMY by the instruction/data principle.
+
+${GROUND}
+
+Build the taxonomy that the five lenses will use. Enumerate the categories of dangerous
+END function in THIS codebase where instruction and data share a channel:
+ - injection: SQL/DSL built by string concat/format! (vs prepared/bound) — the /_sql and
+ query DSL paths; also any query built into another system.
+ - path: filesystem open/join/create/delete where '..' or '/' in data is a path instruction.
+ - process/argv: Command::new + args where data can carry option instructions (the
+ shell-escape-doesn't-stop-option-injection class).
+ - deserialization: bytes carrying type/construction instructions (serde_json::from_*,
+ bincode, rmp, etc).
+ - egress/SSRF: a URL/host from data steering a network instruction.
+ - format/log injection if present.
+For EACH category: state the instruction/data rationale and the separated-safe form;
+give the XERJ query that enumerates that category's sinks (run it, record the live
+candidate count); give the equivalent grep on ${WT}/engine and its file count. This is
+also the first with/without data point.
+
+Run every query for real against ${XERJ} and grep for real against the tree. Return the
+structured taxonomy.`,
+ { label: 'taxonomy', phase: 'Taxonomy', schema: TAX_SCHEMA }
+)
+
+phase('Lenses')
+
+const FINDING_SCHEMA = {
+ type: 'object', additionalProperties: false,
+ required: ['lens', 'with_xerj', 'without_xerj', 'swept', 'findings'],
+ properties: {
+ lens: { type: 'string' },
+ swept: { type: 'string', description: 'what surface was covered and what came back clean' },
+ with_xerj: {
+ type: 'object', additionalProperties: false,
+ required: ['queries', 'candidate_count', 'functions_read', 'approx_tokens'],
+ properties: {
+ queries: { type: 'array', items: { type: 'string' } },
+ candidate_count: { type: 'integer' },
+ functions_read: { type: 'integer' },
+ approx_tokens: { type: 'integer', description: 'tokens actually needed to reach the findings via XERJ' },
+ },
+ },
+ without_xerj: {
+ type: 'object', additionalProperties: false,
+ required: ['greps', 'match_files', 'approx_tokens', 'reachable'],
+ properties: {
+ greps: { type: 'array', items: { type: 'string' } },
+ match_files: { type: 'integer' },
+ approx_tokens: { type: 'integer', description: 'tokens to triage the grep hits (whole files)' },
+ reachable: { type: 'string', description: 'could the no-XERJ path find these findings, and at what cost / not at all' },
+ },
+ },
+ findings: {
+ type: 'array',
+ items: {
+ type: 'object', additionalProperties: false,
+ required: ['id', 'title', 'severity', 'file', 'line', 'code_quote', 'instruction_data_explanation', 'taint_path', 'reachability', 'attacker_input', 'existing_filter', 'bypass', 'impact', 'suggested_fix'],
+ properties: {
+ id: { type: 'string' },
+ title: { type: 'string' },
+ severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'info'] },
+ file: { type: 'string' },
+ line: { type: 'integer' },
+ code_quote: { type: 'string' },
+ instruction_data_explanation: { type: 'string', description: 'exactly how instruction and data mix here' },
+ taint_path: { type: 'string', description: 'source -> ... -> sink, with the call-graph hops' },
+ reachability: { type: 'string', enum: ['unauthenticated-network', 'authenticated-network', 'operator-config', 'internal-only', 'unclear'] },
+ attacker_input: { type: 'string', description: 'the concrete malicious input' },
+ existing_filter: { type: 'string', description: 'what validation exists on the path, if any' },
+ bypass: { type: 'string', description: 'for a filter-bypass finding, the concrete bypassing input; else "n/a"' },
+ impact: { type: 'string' },
+ suggested_fix: { type: 'string' },
+ },
+ },
+ },
+ },
+}
+
+const LENSES = [
+ { key: 'sinks-injection', title: 'Stage 1+2 — injection sinks (SQL/DSL mixing) traced to user input',
+ brief: `Enumerate injection-class sinks (query/DSL/SQL built by concat/format!, not bound).
+Use the taxonomy's injection query as the start. For each, use rustcalls to trace toward a
+handler (is_handler_shaped / a rustroutes entry) — the taint path from request to sink. The
+/_sql stack-overflow is already fixed; look for OTHER query-building paths that mix data into
+an instruction string without separation (e.g. building an ES query, a Lucene string, a regex,
+a stored-script, an aggregation script, a routing key). Report the mix and whether request
+data reaches it.` },
+ { key: 'path-traversal', title: 'Stage 1+2+4 — path sinks + traversal-filter bypasses',
+ brief: `Enumerate path sinks (fs_path_join / fs_write / fs_delete / fs_rename / create_dir_all)
+where a data component is joined into a path. For each: is the joined component attacker-
+influenced (path_join_args, trace via rustcalls)? Is there a containment filter, and is it
+LEXICAL (defeatable by symlink or by an absolute component that .join swallows) or canonicalized?
+Validate the filter for BYPASS: does trim_start_matches('/') still allow '..'? does starts_with
+run BEFORE or AFTER the destructive op (guard_after_destructive_op)? PR #69 fixed index/snapshot
+names — find siblings it missed (put_index_mapping, storage backend abs(), autoindex).` },
+ { key: 'process-argv', title: 'Stage 1+4 — process/exec sinks + argument/option-injection bypasses',
+ brief: `Enumerate process sinks (Command::new / process::Command / spawn of an external binary —
+e.g. the PDF worker in xerj-autoindex, any subprocess). For each: what arguments are built, and
+can DATA flow into an argument that the child interprets as an OPTION (the "-o/tmp/exploit" /
+"--output=" class)? Shell-escaping does NOT stop this. Check for a '--' argument terminator and
+for values that start with '-'. Report the concrete injecting input. Also flag any command whose
+program name or path is data-derived.` },
+ { key: 'privilege-filters', title: 'Stage 3 — privilege model + which checks/filters apply where',
+ brief: `Map the auth/privilege surface: query rustfns for validators:auth and the console/api-key/
+role paths; cross-reference rustroutes against which handlers sit behind an auth layer. Find:
+routes that mutate or read data with NO auth check on the path; auth checks that fail OPEN on
+error; timing-unsafe secret comparison (== on tokens vs constant-time); any-valid-key-acts-on-
+any-object (IDOR) shapes; secrets in logs/responses (sinks:log_secret). State, per sensitive
+route, what check applies and where — and where none does.` },
+ { key: 'deser-egress', title: 'Stage 1+2 — deserialization + SSRF/egress sinks traced to input',
+ brief: `Enumerate deserialization sinks (serde_json::from_*, bincode, rmp, from_slice/from_reader)
+and network-egress sinks (reqwest, hyper client, TcpStream::connect). For deserialization: are
+bytes attacker-controlled and is there a size/type bound before the parse (the bulk-amplification
+class)? For egress: can a URL/host from request data steer the client to an internal address
+(cloud metadata 169.254.169.254, localhost, link-local) — the SSRF the WordPress study found in
+wp_http_validate_url? Trace each to its source.` },
+ { key: 'concurrency', title: 'Stage 5 — state machines: races, TOCTOU, lock-across-await, deadlock',
+ brief: `Query lock_across_await:true, concurrency:relaxed_atomic, concurrency:dashmap, and
+guard_after_destructive_op. Find: a lock guard held across an .await (starvation/deadlock under
+load); TOCTOU where a check and its use straddle a lock boundary (PR #69 added a re-check-under-
+write-lock for the field limit — find where that pattern is MISSING); Ordering::Relaxed guarding
+a non-trivial invariant; ack-implies-durable violations; soft-delete paths that leave data
+readable; error paths that leave a structure half-updated. Use find_recursion_cycles.py for
+mutual-recursion / lock-cycle shapes.` },
+]
+
+const lensResults = await pipeline(
+ LENSES,
+ (lens) => agent(
+`WHITEBOX LENS — ${lens.title}
+
+${GROUND}
+
+## Taxonomy from stage 1 (your starting queries)
+${JSON.stringify(taxonomy).slice(0, 3500)}
+
+## Your assignment
+${lens.brief}
+
+## Method (measured, not optional)
+1. WITH XERJ: run the queries against ${XERJ}, narrow to candidates, READ the real code for
+ each with Read, trace reachability via rustcalls/rustroutes. Record queries, candidate count,
+ functions read, and approx tokens you actually consumed to reach the findings.
+2. WITHOUT XERJ: run the equivalent grep on ${WT}/engine, record match files and the approx
+ tokens to triage them (whole files), and whether the no-XERJ path could reach the same findings.
+3. Every finding: real file:line + quoted code, the instruction/data explanation, the taint path,
+ reachability class, the concrete attacker input, the existing filter and its bypass (if any).
+4. Prefer FEW solid findings over many speculative ones. This engine was already audited; the
+ easy things are fixed. Zero findings + an honest sweep summary is a valid, valuable result.
+Return the structured result.`,
+ { label: `lens:${lens.key}`, phase: 'Lenses', effort: 'high', schema: FINDING_SCHEMA }
+ ),
+ (result, lens) => {
+ if (!result || !result.findings || result.findings.length === 0) return result
+ const capped = result.findings.slice(0, 6)
+ return parallel(capped.map((f) => () =>
+ agent(
+`ADVERSARIAL VERIFIER. Your DEFAULT is that this finding is WRONG. Refute it.
+
+${GROUND}
+
+## The claim (lens: ${lens.title})
+${JSON.stringify(f, null, 2)}
+
+## How to refute
+1. Open the file at the cited line and confirm the quoted code EXISTS there. A wrong line = refuted.
+2. Find the guard the auditor missed: validation earlier in the fn, in the caller (read rustcalls
+ to find callers, then Read them), in a middleware layer, in the type system, or a config default.
+3. Test the reachability: does the route/handler actually exist and sit OUTSIDE auth? For an
+ injection/traversal/argv claim, is the data really attacker-controlled at that point?
+4. For a filter-BYPASS claim, the bypass input must actually work — reason it through or, better,
+ BOOT A THROWAWAY SERVER (port 9314..9330, background) and try it. A curl that triggers it is
+ proof; a curl that fails to is a refutation.
+5. Check it is not already fixed on current main (this branch has PR #69 + the /_sql fix).
+Refuted=true if wrong, misattributed, guarded, unreachable, already-fixed, or severity is
+materially overstated. When genuinely unsure, refute — a false positive in a public case study
+costs more than a missed finding.`,
+ { label: `verify:${f.id}`, phase: 'Verify', effort: 'high',
+ schema: {
+ type: 'object', additionalProperties: false,
+ required: ['finding_id', 'refuted', 'reason', 'code_at_line_confirmed', 'corrected_severity', 'corrected_reachability', 'empirical_test'],
+ properties: {
+ finding_id: { type: 'string' },
+ refuted: { type: 'boolean' },
+ reason: { type: 'string' },
+ code_at_line_confirmed: { type: 'boolean' },
+ corrected_severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'info', 'not-a-bug'] },
+ corrected_reachability: { type: 'string' },
+ empirical_test: { type: 'string', description: 'what you ran and the result; "none" if not tested' },
+ },
+ },
+ }
+ ).then((v) => ({ finding: f, verdict: v }))
+ )).then((verdicts) => ({ ...result, verdicts: verdicts.filter(Boolean) }))
+ }
+)
+
+phase('Synthesize')
+
+const clean = lensResults.filter(Boolean)
+const confirmed = clean.flatMap((r) => (r.verdicts || []).filter((v) => v.verdict && v.verdict.refuted === false).map((v) => ({ lens: r.lens, ...v })))
+const refuted = clean.flatMap((r) => (r.verdicts || []).filter((v) => v.verdict && v.verdict.refuted === true).map((v) => ({ lens: r.lens, id: v.finding.id, title: v.finding.title, why: v.verdict.reason })))
+log(`lenses done: ${clean.length} lenses, ${confirmed.length} confirmed, ${refuted.length} refuted`)
+
+const synthesis = await agent(
+`STAGE 6 — SYNTHESIS. Turn the audit into the deliverables.
+
+${GROUND}
+
+## Taxonomy
+${JSON.stringify(taxonomy).slice(0, 4000)}
+
+## Per-lens results (with/without XERJ measured per lens)
+${JSON.stringify(clean.map((r) => ({ lens: r.lens, swept: r.swept, with_xerj: r.with_xerj, without_xerj: r.without_xerj, n_findings: (r.findings || []).length }))).slice(0, 8000)}
+
+## CONFIRMED findings (survived adversarial refutation)
+${JSON.stringify(confirmed).slice(0, 14000)}
+
+## REFUTED (report the count + the lesson, not the claims)
+${JSON.stringify(refuted).slice(0, 4000)}
+
+## Write these files (in ${WT})
+1. docs/case-studies/xerj-self-audit/METHODOLOGY.md — the five-stage instruction/data whitebox
+ methodology as a reusable playbook: the principle, the taxonomy, the XERJ query per stage, the
+ grep baseline per stage, and the with/without comparison table (recall + tokens per lens,
+ summed). Lead with the principle ("dangerous = instruction+data share a channel"). This is the
+ dogfooding methodology section the website links to.
+2. docs/case-studies/xerj-self-audit/FINDINGS-V2.md — every confirmed finding in full
+ (file:line, quoted code, instruction/data explanation, taint path, reachability, attacker input,
+ filter+bypass, impact, fix), then the refuted-count + lesson.
+3. Append a "Five-stage methodology" section to docs/case-studies/xerj-self-audit/README.md linking
+ METHODOLOGY.md and summarizing the with/without result in one table.
+4. ISSUES.md (in the same dir) — a GitHub-issue DRAFT per confirmed finding that needs a fix
+ (title, severity, reachability, the code, the fix). Do NOT create issues via gh — leave drafts
+ for the human to review (public disclosure of an unfixed network-reachable bug is sensitive).
+
+## Rules
+- Do not invent numbers; every figure traces to the data above. Label any estimate.
+- If confirmed findings are few or zero, that is the honest headline — the METHODOLOGY and the
+ measured with/without comparison are the product, exactly as the WordPress study concluded.
+- Do NOT commit. Return: files written, the with/without summary table (as text), the confirmed
+ count by severity, and how many issue drafts you wrote.`,
+ { label: 'synthesize', phase: 'Synthesize', effort: 'high' }
+)
+
+return {
+ taxonomy_categories: (taxonomy && taxonomy.categories || []).map((c) => ({ category: c.category, xerj: c.xerj_candidate_count, grep_files: c.grep_file_count })),
+ lenses: clean.map((r) => ({ lens: r.lens, findings: (r.findings || []).length })),
+ confirmed_count: confirmed.length,
+ refuted_count: refuted.length,
+ confirmed,
+ synthesis,
+}
diff --git a/landing/case-studies/xerj-self-audit.html b/landing/case-studies/xerj-self-audit.html
index eecd468c7..215678432 100644
--- a/landing/case-studies/xerj-self-audit.html
+++ b/landing/case-studies/xerj-self-audit.html
@@ -197,6 +197,17 @@ $ python3 ingest.py ./ast-out --url $XERJ <span class="comment"># s
<span class="comment"># server still answering 200 afterwards.</span></pre>
</section>
+<section class="scene-section">
+ <h2 class="scene" style="font-size:var(--fs-56);">SECOND PASS: ONE <span class="accent">PRINCIPLE.</span></h2>
+ <p class="wide">A deeper pass (24 verified agents) replaced the category checklist with a single test — <strong>a function is dangerous when instruction and data share one channel with no separator, and a filter is only real if it strips the instruction power from the data channel</strong>. Five stages: flag the dangerous sinks, trace each to user input, map the privilege model, validate every filter for bypasses, and check the state machines for races. Full playbook: <a href="https://github.com/xerj-org/xerj/blob/main/docs/case-studies/xerj-self-audit/METHODOLOGY.md" rel="external">METHODOLOGY.md</a>.</p>
+ <div class="proof-row" style="margin-top:var(--sp-6);">
+ <div class="stat"><div class="num">8 / 8</div><div class="label">CONFIRMED / REFUTED</div><div class="ctx">a 50% cull at the adversarial-verify stage — the refuted half is the point</div></div>
+ <div class="stat"><div class="num">4 High</div><div class="label">CONFIRMED SEVERITY</div><div class="ctx">+ 2 Medium, 1 Low, 1 Info · the 3 app-layer Highs are fixed on the branch, live-proven</div></div>
+ <div class="stat"><div class="num">19.6×</div><div class="label">FEWER TOKENS (FLOOR)</div><div class="ctx">the five grep sweeps touch 153 of 197 files — grepping the stages is reading the codebase</div></div>
+ </div>
+ <p class="wide" style="margin-top:var(--sp-5);">The two sharpest findings are corollary failures, not missing filters. <strong>INJ-01</strong>: a search-template param was spliced into the query JSON unescaped and re-parsed, so a value could drop the template's own ACL filter — live-proven leaking a private document, now fixed. <strong>F-PATH-02</strong>: the three filters guarding a snapshot's <em>name</em> are all real and tested; the hole is the un-validated sibling field, the repo <em>location</em> — a snapshot wrote index data outside <code class="inline">data_dir</code>, now bounded by a <code class="inline">path.repo</code>-style allowlist. Both, plus a session-revocation lost-update, ship fixed with regression tests. Every finding, severity-ranked with its instruction/data analysis: <a href="https://github.com/xerj-org/xerj/blob/main/docs/case-studies/xerj-self-audit/FINDINGS-V2.md" rel="external">FINDINGS-V2.md</a>.</p>
+</section>
+
<section class="scene-section">
<h2 class="scene" style="font-size:var(--fs-56);">WHAT THIS <span class="accent">DOES NOT SHOW.</span></h2>
<div class="laws">