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): add step-by-step PLAYBOOK (with agent prompts) + IMPROVEMENTS roadmap

Xerj Squad Aca5d3824e918
diff --git a/docs/case-studies/wordpress-security-audit/IMPROVEMENTS.md b/docs/case-studies/wordpress-security-audit/IMPROVEMENTS.md
new file mode 100644
index 000000000..9a18d2ff6
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/IMPROVEMENTS.md
@@ -0,0 +1,95 @@
+# Improvement ideas — where this goes next
+
+The audit is honest about being a *first cut*. Everything below is a concrete,
+scoped improvement, ordered by leverage. Each is something a contributor can pick
+up; several were surfaced by the audit itself.
+
+## A. Engine (XERJ) — make the structured index trustworthy
+
+These are the highest leverage: they turn XERJ from "sometimes worse than grep for
+reachability" into "strictly better — structured *and* complete."
+
+1. **Multi-valued keyword `term`** *(bug the audit found; PR in progress).* A
+ keyword array matches only element `[0]` on the `term` path. Fix: make
+ `KeywordColumn` multi-valued (or route array fields to the source scan on every
+ fast path). Restores reverse call-graph reachability. → `../../research/xerj-keyword-array-term-fix.md`
+2. **Boolean `term` coercion.** `{term:{f:true}}` (JSON bool) returns 0;
+ `"true"` works. Coerce JSON booleans to the stored form. Small, self-contained.
+3. **Code-aware text analyzer.** The default analyzer splits identifiers on `_`
+ (`esc_like` → `esc`+`like`) and drops `->`, so code search is imprecise. A
+ `code` analyzer that keeps `_`, `.`, `->` as token characters makes identifiers
+ searchable whole — a big precision win for the security use-case.
+
+## B. Substrate / extractor — precision and recall
+
+The audit's false positives all trace to a few known modeling gaps:
+
+4. **Receiver-typed sinks.** `->query()` is dangerous on `$wpdb`, safe on
+ `WP_Query`/`WP_User_Query`/`DOMXPath`. Resolve the receiver's type before
+ calling a method a SQL sink. Removes essentially all SQLi false positives.
+5. **Constant-path `include`/`require` are not LFI.** `require ABSPATH . '...'`
+ flagged as LFI. Treat literal/const-rooted paths as safe.
+6. **Self-scoped writes.** `update_user_meta(get_current_user_id(), …)` needs no
+ capability — recognize the current-user object and stop flagging it.
+7. **Polymorphic & delegated authorization.** Caps hide behind
+ `$table->ajax_user_can()` and `$this->check_update_permission($obj)`. Follow
+ these edges (class-qualified) so authz-presence isn't a false gap.
+8. **Class-qualified call resolution.** Bare method names collide across classes
+ (40+ controllers define `get_item_permissions_check`). Resolve `$this->m()` to
+ the same class/file. *(The audit hit this as an OOP substrate bug.)*
+9. **File-scope handlers.** `wp-admin/*.php` handle requests in a top-level
+ `switch($action)` outside any function; index those case blocks (with guards
+ gathered from the enclosing scope). *(The audit's biggest recall gap.)*
+10. **Deeper taint.** Model flow through arrays/`$GLOBALS`, aliasing, and
+ variable-variables — today taint follows direct call edges only.
+
+## C. Detector coverage — more classes, more frameworks
+
+11. **Completeness detectors for every validator class**, generalizing
+ `wp_ssrf_ranges.py`: SSRF ranges, redirect allow-lists, upload MIME/extension
+ lists, CORS origins, `wp_kses` tag/attr sets. The bug class is *"a defense
+ that's present but incomplete"* — compile each as a queryable coverage check.
+12. **Deserialization sinks** — untrusted `unserialize`/`pickle.loads`/
+ `yaml.load`/`ObjectInputStream` reaching a source, with the HMAC-gate
+ recognized as a defense.
+13. **Path traversal** — `include`/file-open with a request-derived path lacking a
+ normalization/allow-list.
+14. **More frameworks** — Laravel, Symfony, Django, Rails, Express/Next, Spring.
+ The taint model is data; add framework fact-lists, reuse the engine.
+
+## D. Product / workflow — where XERJ should meet the auditor
+
+15. **AST-aware `autoindex`.** Ship the function-level extractor *inside*
+ `xerj autoindex ./code` so the graph-ready index is one command, not a
+ separate script. (The research doc's original "next step.")
+16. **Findings as a first-class index.** Store confirmed findings with a
+ severity/route schema so the agent loop is "query findings → pull path code →
+ confirm," and re-audits diff against the last run.
+17. **MCP-native auditing.** Expose the audit queries via `xerj-mcp` so an AI
+ agent runs the whole playbook through native tools — no hand-written curl.
+18. **CI mode.** Run the fingerprint queries on every PR; fail on a *new*
+ escaper-last violation, incomplete validator, or unguarded object-scoped op.
+ The fingerprints make this O(diff), not O(codebase).
+
+## E. Rigor — trust the automation less, verify more
+
+19. **Adversarial verification pass** — for each surviving finding, an independent
+ agent whose only job is to refute it; keep only what survives.
+20. **Sandbox execution harness** — where the audit ported `wp_http_validate_url`
+ to Python by hand, wire a real PHP/Node/Python sandbox so candidate flows are
+ *executed* automatically, not transcribed.
+
+---
+
+## The one-paragraph close
+
+This case study started as "can an AI audit real WordPress cheaply?" and ended as
+something more useful: a **method** — index once, interrogate, read only what the
+graph points to, verify by execution, and compile every invariant you learn into a
+fingerprint the next audit queries for free. It found one real (known-class) SSRF
+gap, verified core is otherwise hardened without manufacturing a single finding,
+and — most tellingly — surfaced and fixed a bug in XERJ itself. The token
+economics (~199× vs reading everything, ~2,700× on a compiled invariant) are real,
+but the durable output is the growing library of detectors and the honesty
+discipline. Point it at your own codebase, add your framework's fact-lists, and
+improve the loop — that is the invitation.
diff --git a/docs/case-studies/wordpress-security-audit/PLAYBOOK.md b/docs/case-studies/wordpress-security-audit/PLAYBOOK.md
new file mode 100644
index 000000000..a78c5b215
--- /dev/null
+++ b/docs/case-studies/wordpress-security-audit/PLAYBOOK.md
@@ -0,0 +1,150 @@
+# Playbook: run this security audit yourself, with an AI + XERJ
+
+This is the step-by-step guide to reproduce the audit **the way the agent did it**
+— not just running the scripts, but driving an AI (Claude, or any model with tool
+access) to use XERJ as its reasoning substrate. Copy the prompts, point them at
+your own codebase, improve them.
+
+The method in one line: **index the code once, then make the AI *interrogate* the
+index — query → read only what it points to → reason → next query — instead of
+loading the whole codebase.**
+
+---
+
+## Step 0 — Setup (≈2 minutes)
+
+```bash
+pip install -r ../../examples/ast-vuln-graph/requirements.txt
+git clone --depth 1 https://github.com/WordPress/WordPress.git ./wordpress
+xerj --insecure --data-dir ./wpdata & # ES-compatible wire on :9200
+cd ../../examples/ast-vuln-graph
+python3 wp_audit_index.py ./wordpress # wpaudit + wphooks
+python3 wp_authz_graph.py ./wordpress # wpauthz
+python3 wp_compose_index.py ./wordpress # wpcompose
+```
+
+You now have a searchable **security substrate**: one document per function
+(code + taint facts), one per hook, plus fingerprint indices. This is what the AI
+thinks against.
+
+---
+
+## Step 1 — The master prompt
+
+Give your AI agent tool access to shell/curl against `http://127.0.0.1:9200`, then
+paste this. It encodes the whole method, including the honesty rules that make the
+result trustworthy.
+
+> **You are a security code auditor. XERJ (Elasticsearch-compatible, on
+> `127.0.0.1:9200`) is your second brain: it holds every function of the target
+> codebase as a searchable document with taint facts (`sources`, `sinks`,
+> `sanit`, `calls`), plus a hook index (`wphooks`) and fingerprint indices
+> (`wpauthz`, `wpcompose`). Do NOT load whole files. Instead: form a hypothesis,
+> query XERJ to find the relevant functions, pull ONLY those bodies, read them,
+> reason, and query again.**
+>
+> **Rules that make your findings trustworthy:**
+> 1. **Precision from the graph, navigation from search.** Let the taint/authz
+> facts decide what is a candidate; use full-text only to navigate. FTS over
+> raw code is noisy for security.
+> 2. **Verify by reading, then by executing.** Every candidate must be confirmed
+> by reading the real implementation. For a claimed bug, reconstruct and run
+> the exact logic (port it to a runnable language if needed) before asserting
+> it.
+> 3. **Trace reachability to real input.** A sink or gap only matters if
+> attacker-controlled input reaches it — find the caller chain.
+> 4. **No manufactured findings.** If the code is correctly defended, say so and
+> show why. A clean negative is a valid result.
+> 5. **Report substrate bugs.** If a query result is impossible (e.g. a function
+> with a call that grep finds but the index doesn't), suspect the index/engine,
+> not reality — investigate and report it.
+> 6. **Cite `file:line` from pulled code for every claim.** Never reason from
+> memory of the framework.
+>
+> **Caveats for querying XERJ today (two known engine bugs):** `term` on a keyword
+> *array* matches only the first element — for reverse call-graph reachability,
+> pull `_source` and traverse the `calls` arrays in code, or use `match`. Boolean
+> `term` matches as a string — use `{"term":{"has_source":"true"}}`, not `true`.
+>
+> **Begin by mapping the attack surface: query `wphooks` for unauthenticated entry
+> points, and enumerate the framework's request handlers. Then work inward.**
+
+---
+
+## Step 2 — Phase prompts (what the agent does, and the queries)
+
+Run these as follow-ups. Each is a hypothesis + the XERJ query + what to look for.
+
+### 2a. Unauthenticated attack surface
+> *"List every unauthenticated entry point and what it reaches."*
+```bash
+curl -s "$XERJ/wphooks/_search" -H 'Content-Type: application/json' \
+ -d '{"query":{"term":{"unauth":true}},"_source":["hook","callback","file"]}'
+```
+Read each callback. Ask: does raw input reach a sink or dispatch to a filter?
+(In WP core: 2 of 1,343 hooks; the only unauth data path is `heartbeat_nopriv_received`.)
+
+### 2b. Injection reachable from request input
+> *"Find functions that read a request source AND hit a SQL sink AND are not
+> sanitized in-function; read all of them."*
+```bash
+curl -s "$XERJ/wpaudit/_search" -H 'Content-Type: application/json' \
+ -d '{"query":{"bool":{"filter":[{"term":{"has_source":"true"}},{"term":{"sinks":"sql"}},{"term":{"sanit":"false"}}]}}}'
+```
+11,990 functions → a handful of candidates. Read each; check the *receiver type*
+of the sink (`$wpdb->query` is raw; `WP_Query->query` is safe).
+
+### 2c. Authorization / IDOR
+> *"Are privileged operations gated by an OBJECT-SCOPED capability, or a generic
+> one? The bug is a generic cap (or none) on an object named by request input."*
+Read the gatekeepers first (`current_user_can`, `wp_verify_nonce`,
+`check_ajax_referer`) to learn the correct pattern, then classify every handler.
+`wp_authz_graph.py` and `wp_checkuse_idor.py` automate the classification.
+
+### 2d. Completeness of a defense (the class pattern scanners miss)
+> *"For each security VALIDATOR (SSRF host check, escaper, allow-list), enumerate
+> what it covers and find what it MISSES."*
+```bash
+python3 wp_ssrf_ranges.py # flags wp_http_validate_url missing 169.254 / metadata
+python3 verify_ssrf.py # then EXECUTE the flow to confirm
+```
+
+### 2e. Sanitizer composition (one filter breaking another)
+> *"Find any function where a de-escaper runs AFTER an escaper before a sink."*
+```bash
+curl -s "$XERJ/wpcompose/_search" -H 'Content-Type: application/json' \
+ -d '{"query":{"bool":{"filter":[{"term":{"compose_danger":"true"}},{"term":{"sink_raw":"true"}}]}},"_source":["func","file","sanitizer_seq"]}'
+```
+The `sanitizer_seq` fingerprint self-triages most; read the survivors.
+
+---
+
+## Step 3 — Point it at YOUR codebase
+
+The taint model is **data, not code**. To audit a different stack:
+
+1. **Add the language** — `scan_multilang.py` already covers PHP/Python/Go/Rust/
+ Java via tree-sitter; add a `LANGS` row (sources / sinks / sanitizers) for
+ yours.
+2. **Edit the framework lists** — replace WP's `$_GET`/`$wpdb`/`esc_*`/
+ `current_user_can` with your framework's request objects, DB sinks, escapers,
+ and auth primitives (Django `.raw()`/`@login_required`, Express `req.query`/
+ `knex.raw`, Rails `params`/`where("...#{}")`, etc.).
+3. **Re-index and re-prompt** — the master prompt is framework-agnostic; only the
+ fact lists change.
+
+---
+
+## Step 4 — Improve the loop
+
+- Add a **completeness critic** pass: after each phase, prompt *"what did we NOT
+ check — a surface, a validator, a sink class?"* and turn the answer into the
+ next query.
+- Add **adversarial verification**: for each surviving finding, spawn a second
+ read whose only job is to *refute* it; keep it only if refutation fails.
+- **Compile every new invariant into a fingerprint** (like `sanitizer_seq`), so
+ the next audit queries it for ~free instead of re-reading. This is the
+ compounding win.
+
+See [`IMPROVEMENTS.md`](IMPROVEMENTS.md) for the roadmap that closes this case
+study.
diff --git a/docs/case-studies/wordpress-security-audit/README.md b/docs/case-studies/wordpress-security-audit/README.md
index 33a06bcb1..7797d9444 100644
--- a/docs/case-studies/wordpress-security-audit/README.md
+++ b/docs/case-studies/wordpress-security-audit/README.md
@@ -93,10 +93,15 @@ read; scale and durability come from XERJ.
## Contents
+- [`PLAYBOOK.md`](PLAYBOOK.md) — **step-by-step guide with the copy-paste prompts**
+ to drive an AI + XERJ through this audit, and to point it at your own codebase.
- [`FINDINGS.md`](FINDINGS.md) — the SSRF vulnerability, with verification and
reachability.
-- [`REPRODUCE.md`](REPRODUCE.md) — exact steps to rebuild the index and rerun
+- [`REPRODUCE.md`](REPRODUCE.md) — exact commands to rebuild the index and rerun
every result.
+- [`IMPROVEMENTS.md`](IMPROVEMENTS.md) — the roadmap: engine, extractor, detector,
+ and workflow improvements that close the case study.
+- [`verify_ssrf.py`](verify_ssrf.py) — self-contained, executes the finding.
- Detectors and scripts: [`../../examples/ast-vuln-graph/`](../../examples/ast-vuln-graph/)
(`wp_audit_index.py`, `wp_authz_graph.py`, `wp_checkuse_idor.py`,
`wp_admin_pages.py`, `wp_ssrf_ranges.py`, `wp_compose_index.py`).
@@ -116,3 +121,15 @@ read; scale and durability come from XERJ.
sinks, self-scoped writes, polymorphic caps) — every candidate still needs a
human/AI read to confirm. The value is that there are few enough to read them
all.
+
+## Run it yourself, then improve it
+
+Start with [`PLAYBOOK.md`](PLAYBOOK.md) — it has the exact prompts to drive an AI
+through this audit and to retarget it at your own stack (the taint model is data,
+not code). Then see [`IMPROVEMENTS.md`](IMPROVEMENTS.md) for the roadmap: the
+engine fixes that make the structured index strictly better than grep, the
+extractor precision levers, the detector classes still to add, and the workflow
+(AST-aware `autoindex`, findings-as-index, MCP-native auditing, CI mode) that
+would make this a one-command capability. The invitation is to point it at your
+code, add your framework's fact-lists, and compile every invariant you learn into
+a fingerprint the next audit gets for free.