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
feat(ast-vuln): multi-language tree-sitter taint scanner + real-WP scale test
Xerj Squad A47d1117041cf
diff --git a/docs/examples/ast-vuln-graph/README.md b/docs/examples/ast-vuln-graph/README.mdindex a6db5e6b6..b5fe8aa39 100644--- a/docs/examples/ast-vuln-graph/README.md+++ b/docs/examples/ast-vuln-graph/README.md@@ -1,10 +1,19 @@# AST + graph vulnerability finding (prototype)-Finds interprocedural vulnerabilities in PHP/WordPress that per-file tools miss,-and hands an AI only the code on each taint path — far fewer tokens. Full-write-up: [`docs/research/ast-graph-vuln-detection.md`](../../research/ast-graph-vuln-detection.md).+Finds interprocedural vulnerabilities that per-file tools miss, and hands an AI+only the code on each taint path — far fewer tokens. Full write-up:+[`docs/research/ast-graph-vuln-detection.md`](../../research/ast-graph-vuln-detection.md).-## Run it+Two extractors live here:++- **`extract_ast.py`** — the original PHP/WordPress extractor (uses `phply`).+ Richest WP taint model: hook graph (`wp_ajax_nopriv` → unauthenticated),+ nonce-absence CSRF, sanitizer-on-path.+- **`scan_multilang.py`** — one tree-sitter engine, five languages+ (PHP, Python, Go, Rust, Java). Same interprocedural source→sink idea, driven+ by a per-language taint config. This is the path that scales to real code.++## Run the PHP/WordPress demo```bashpip install phply@@ -18,11 +27,65 @@ XSS, and the missing-nonce CSRF — none of which a single-file scan produces.`ast_facts.json` holds the per-function facts (index these into XERJ for theFTS/semantic navigation layer described in the research doc).+## Run the multi-language scanner++```bash+pip install -r requirements.txt+python3 scan_multilang.py python samples/py+python3 scan_multilang.py go samples/go+python3 scan_multilang.py rust samples/rs+python3 scan_multilang.py java samples/java+python3 scan_multilang.py php ./acme-plugin+```++Each `samples/<lang>/` file plants one interprocedural bug (a request/argv+**source** in a handler that reaches a dangerous **sink** in a *different*+function). All five are found:++| language | planted flow | found |+|---|---|:--:|+| Python | `handler → do_query` (SQLi via `.execute`), plus a sanitized negative case | ✅ |+| Go | `handler → run` (command injection via `exec.Command`) | ✅ |+| Rust | `handler → run` (command injection via `Command::new`) | ✅ |+| Java | `handler → query` (SQLi via `executeQuery`) | ✅ |+| PHP | 5 flows incl. interprocedural SQLi + XSS, LFI, unsafe deser | ✅ |++The taint model is **data, not code** — the `LANGS` dict in `scan_multilang.py`+lists each language's sources / sinks / sanitizers. Add a framework by adding a+row, not by touching the engine.++## Why tree-sitter, not phply, for real scale++`extract_ast.py` uses `phply` (pure-Python PHP). It is fine for the demo plugin,+but on **real WordPress core it fails to parse ~37% of files** (newer syntax) and+silently skips them — unacceptable for a security audit. `scan_multilang.py` uses+`tree-sitter-php`, which parses **100%** of the same tree. Measured on a full+WordPress checkout (1,492 PHP files, ~619k lines):++| | phply | tree-sitter-php |+|---|--:|--:|+| files parsed | ~63% | **100%** |+| full-tree scan time | — | **~3.6 s** |+| functions/methods indexed | — | 11,940 |+| whole-tree tokens (load-it-all) | — | ~5.2 M (unreviewable) |+| candidate findings to triage | — | **129** |++129 candidates from a 5.2M-token tree is the whole point: the graph decides+*what* to look at, the AI reviews only those paths. **These are candidates, not+confirmed bugs** — WP core is heavily audited, so most `echo`/`include` hits are+already escaped or path-validated in ways the name-based sanitizer list doesn't+yet recognize. Tightening the WP sanitizer model (context-aware escapers,+`plugins_url`/`get_template_part` path allow-lists) is what drops 129 toward the+true positives. That work is real, but it starts from a tractable 129, not 5.2M.+## What each file does- `make_demo_plugin.py` — reproducible vulnerable WordPress plugin (ground truth).-- `extract_ast.py` — parses PHP with phply, builds per-function taint facts and- the call graph, and reports interprocedural source→sink findings + CSRF.+- `extract_ast.py` — phply PHP/WP extractor: taint facts, call graph, hook graph,+ nonce-absence CSRF.+- `scan_multilang.py` — tree-sitter engine for PHP/Python/Go/Rust/Java; the+ `LANGS` config carries each language's taint lists.+- `samples/<lang>/` — minimal planted-vuln files, one per language.This is triage: it surfaces real, reachable patterns so an AI can confirmexploitability with minimal context. See the research doc for the honest limits.diff --git a/docs/examples/ast-vuln-graph/requirements.txt b/docs/examples/ast-vuln-graph/requirements.txtnew file mode 100644index 000000000..d355b5cde--- /dev/null+++ b/docs/examples/ast-vuln-graph/requirements.txt@@ -0,0 +1,8 @@+# Multi-language AST taint scanner (scan_multilang.py) — tree-sitter grammars.+# The original PHP-only extractor (extract_ast.py) uses phply; see README.+tree-sitter==0.26.0+tree-sitter-python==0.25.0+tree-sitter-go==0.25.0+tree-sitter-rust==0.24.2+tree-sitter-java==0.23.5+tree-sitter-php==0.24.1diff --git a/docs/examples/ast-vuln-graph/samples/go/main.go b/docs/examples/ast-vuln-graph/samples/go/main.gonew file mode 100644index 000000000..a550cf78f--- /dev/null+++ b/docs/examples/ast-vuln-graph/samples/go/main.go@@ -0,0 +1,3 @@+package main+func handler(r *http.Request) { run(r.FormValue("cmd")) }+func run(c string) { exec.Command("sh", "-c", c) }diff --git a/docs/examples/ast-vuln-graph/samples/java/App.java b/docs/examples/ast-vuln-graph/samples/java/App.javanew file mode 100644index 000000000..e106411ac--- /dev/null+++ b/docs/examples/ast-vuln-graph/samples/java/App.java@@ -0,0 +1,4 @@+class App {+ void handler(HttpServletRequest request) { query(request.getParameter("id")); }+ void query(String id) { stmt.executeQuery("SELECT * FROM t WHERE id=" + id); }+}diff --git a/docs/examples/ast-vuln-graph/samples/py/app.py b/docs/examples/ast-vuln-graph/samples/py/app.pynew file mode 100644index 000000000..b5146ac2f--- /dev/null+++ b/docs/examples/ast-vuln-graph/samples/py/app.py@@ -0,0 +1,8 @@+def handler(request):+ uid = request.args.get("id") # source+ return do_query(uid) # -> sink in another function+def do_query(v):+ cur.execute("SELECT * FROM u WHERE id=" + v) # sql sink+def safe(request):+ v = html.escape(request.args.get("x")) # sanitized -> not a finding+ cur.execute("SELECT " + v)diff --git a/docs/examples/ast-vuln-graph/samples/rs/main.rs b/docs/examples/ast-vuln-graph/samples/rs/main.rsnew file mode 100644index 000000000..ac6248898--- /dev/null+++ b/docs/examples/ast-vuln-graph/samples/rs/main.rs@@ -0,0 +1,2 @@+fn handler() { let a = std::env::args().nth(1).unwrap(); run(a); }+fn run(a: String) { Command::new("sh").arg("-c").arg(a); }diff --git a/docs/examples/ast-vuln-graph/scan_multilang.py b/docs/examples/ast-vuln-graph/scan_multilang.pynew file mode 100644index 000000000..83e3a31dd--- /dev/null+++ b/docs/examples/ast-vuln-graph/scan_multilang.py@@ -0,0 +1,148 @@+#!/usr/bin/env python3+"""Multi-language AST taint scanner (tree-sitter). One engine; per-language+taint config. Finds interprocedural source->sink flows the same way the PHP+extractor does, for Python / Go / Rust / Java.+"""+import glob, importlib, json, os, re, sys+from tree_sitter import Language, Parser++# per-language: parser module, file globs, AST node types, and the taint lists+# (matched as substrings against each function's own source text — the AST gives+# the function SCOPING and call edges; the patterns give the vuln signatures).+LANGS = {+ "python": dict(mod="tree_sitter_python", ext=[".py"],+ func=["function_definition"], call=["call"],+ sources=["request.args","request.form","request.values","request.GET","request.POST",+ "os.environ","sys.argv","input("],+ sinks={"sql":[".execute(",".executemany(",".raw("],+ "cmd":["os.system(","os.popen(","subprocess"],+ "code":["eval(","exec("],+ "deser":["pickle.load","yaml.load(","marshal.load"]},+ sanit=["shlex.quote","html.escape","escape(","parameterize"]),+ "go": dict(mod="tree_sitter_go", ext=[".go"],+ func=["function_declaration","method_declaration"], call=["call_expression"],+ sources=["r.URL.Query()","r.FormValue","r.PostFormValue","r.Header.Get","os.Getenv","os.Args"],+ sinks={"sql":[".Query(",".Exec(",".QueryRow("],+ "cmd":["exec.Command(","os/exec"],+ "deser":["gob.NewDecoder"]},+ sanit=["html/template","QueryContext",".Prepare("]),+ "rust": dict(mod="tree_sitter_rust", ext=[".rs"],+ func=["function_item"], call=["call_expression","macro_invocation"],+ sources=["env::var","env::args","std::env"],+ sinks={"cmd":['Command::new','process::Command'],+ "sql":["sqlx::query(","format!"],+ "unsafe":["unsafe {","unsafe{"]},+ sanit=["query!","shell_escape"]),+ "java": dict(mod="tree_sitter_java", ext=[".java"],+ func=["method_declaration"], call=["method_invocation"],+ sources=["request.getParameter","request.getHeader","getQueryString","System.getenv"],+ sinks={"sql":[".executeQuery(",".executeUpdate(",".execute("],+ "cmd":["Runtime.getRuntime().exec(","ProcessBuilder("],+ "deser":[".readObject(","ObjectInputStream"]},+ sanit=["PreparedStatement",".setString(","ESAPI"]),+ "php": dict(mod="tree_sitter_php", ext=[".php"], lang_fn="language_php",+ func=["function_definition","method_declaration"],+ call=["function_call_expression","member_call_expression","scoped_call_expression"],+ sources=["$_GET","$_POST","$_REQUEST","$_COOKIE","$_SERVER","$_FILES"],+ sinks={"sql":["->query(","->get_results(","->get_var(","->get_row(","->get_col("],+ "cmd":["exec(","system(","shell_exec(","passthru(","popen("],+ "code":["eval("],+ "deser":["unserialize("]},+ stmt_sinks={"echo_statement":"xss","include_expression":"lfi","require_expression":"lfi","include_once_expression":"lfi","require_once_expression":"lfi"},+ sanit=["esc_html","esc_attr","esc_url","sanitize_","wp_verify_nonce",+ "check_admin_referer","->prepare(","absint","intval","wp_kses"]),+}++def node_name(n):+ f=n.child_by_field_name("name")+ if f: return f.text.decode("utf8","replace")+ for c in n.children:+ if c.type in ("identifier","name","field_identifier"): return c.text.decode()+ return "<anon>"++def callee_text(call):+ """Best-effort dotted callee of a call node: os.system, $wpdb->query,+ request.getParameter, pickle.loads, etc."""+ fn = call.child_by_field_name("function") or call.child_by_field_name("name") \+ or (call.child_by_field_name("macro") if call.type=="macro_invocation" else None)+ node = fn or (call.children[0] if call.children else None)+ if node is None: return "", ""+ txt = node.text.decode("utf8","replace")+ last = re.split(r"->|::|\.", txt)[-1].strip()+ return txt, last++def calls_in(fnode, call_types):+ out=[]+ def w(n):+ if n.type in call_types:+ out.append(callee_text(n))+ for c in n.children: w(c)+ w(fnode)+ return out++def scan_lang(root_dir, lang):+ cfg=LANGS[lang]; m=importlib.import_module(cfg["mod"])+ parser=Parser(Language(getattr(m, cfg.get("lang_fn","language"))()))+ # sink/sanitizer name sets = last-segment of each configured pattern (strip . -> :: ( )+ def names(pats): return {re.split(r"->|::|\.", p.rstrip("(").strip())[-1] for p in pats}+ sink_names={k:names(v) for k,v in cfg["sinks"].items()}+ sanit_names=names(cfg["sanit"])+ raw={} # (file,name)->fact ; also collect name multiplicity+ name_count={}+ files=[p for e in cfg["ext"] for p in glob.glob(f"{root_dir}/**/*{e}", recursive=True)]+ for path in files:+ try: src=open(path,"rb").read()+ except Exception: continue+ root=parser.parse(src).root_node+ rel=os.path.relpath(path, root_dir)+ def walk(n):+ if n.type in cfg["func"]:+ nm=node_name(n); txt=n.text.decode("utf8","replace")+ cs=calls_in(n, cfg["call"])+ sinks=set()+ for full,last in cs:+ for k,ns in sink_names.items():+ if last in ns: sinks.add(k)+ stmt_map=cfg.get("stmt_sinks",{})+ if stmt_map:+ def find_stmt(nn):+ if nn.type in stmt_map: sinks.add(stmt_map[nn.type])+ for cc in nn.children: find_stmt(cc)+ find_stmt(n)+ sanit=any(last in sanit_names or any(sp in full for sp in cfg["sanit"]) for full,last in cs)+ srcs=[x for x in cfg["sources"] if x in txt]+ key=(rel,nm)+ raw[key]={"file":rel,"func":nm,"line":n.start_point[0]+1,+ "sources":srcs,"sinks":sorted(sinks),"sanit":sanit,+ "callee_last":[last for _,last in cs]}+ name_count[nm]=name_count.get(nm,0)+1+ for c in n.children: walk(c)+ walk(root)+ # resolve edges: only to names defined exactly once (unambiguous)+ byname={}+ for k,f in raw.items(): byname.setdefault(f["func"],[]).append(k)+ for k,f in raw.items():+ f["calls"]=[byname[c][0] for c in f["callee_last"]+ if c in byname and name_count.get(c,0)==1]+ # interprocedural taint+ findings=[]+ for key,f in raw.items():+ if not f["sources"]: continue+ stack=[(key,[f["func"]],f["sanit"])]; seen=set()+ while stack:+ cur,path,san=stack.pop()+ if cur in seen: continue+ seen.add(cur); cf=raw[cur]+ if cf["sinks"] and not san:+ findings.append({"sink":cf["sinks"],"path":path,"file":cf["file"]})+ for cal in cf["calls"]:+ stack.append((cal,path+[raw[cal]["func"]],san or raw[cal]["sanit"]))+ uniq={(x["path"][0],x["path"][-1],tuple(x["sink"])):x for x in findings}+ return raw, list(uniq.values())++if __name__=="__main__":+ lang=sys.argv[1]; root=sys.argv[2]+ funcs,findings=scan_lang(root, lang)+ print(f"[{lang}] parsed {len(funcs)} functions, {len(findings)} findings")+ for x in findings:+ print(f" {'/'.join(x['sink'])}: {' -> '.join(x['path'])} (sink in {x['file']})")diff --git a/docs/research/ast-graph-vuln-detection.md b/docs/research/ast-graph-vuln-detection.mdindex be6903eda..054bcda93 100644--- a/docs/research/ast-graph-vuln-detection.md+++ b/docs/research/ast-graph-vuln-detection.md@@ -1,6 +1,9 @@# Research: AST + graph + FTS for AI vulnerability finding, at codebase scale-**Status:** working prototype, verified on a realistic WordPress plugin. See+**Status:** working prototype. Verified on a realistic WordPress plugin (PHP,+6/6 planted bugs) and extended to **five languages** (PHP, Python, Go, Rust,+Java) on a single tree-sitter engine, then run against **real WordPress core**+(1,492 files, ~619k lines) to test the design at scale. See`docs/examples/ast-vuln-graph/` to reproduce every number below.## The problem@@ -107,6 +110,35 @@ language comes from XERJ. Neither alone is enough.- **This** → 6/6 including the interprocedural, unauth, and absence cases, andit hands the AI ~13× less to read.+## Multi-language, and the scale test on real WordPress++The taint model being *data, not code* was the claim; `scan_multilang.py` proves+it. One tree-sitter engine, a `LANGS` config with per-language sources / sinks /+sanitizers, and the same interprocedural walk finds the planted handler→sink bug+in **Python, Go, Rust, Java, and PHP** — a new language is a new config row, not+new engine code.++The switch to tree-sitter also fixed the parser-coverage limitation below. On a+full WordPress checkout, `phply` fails to parse ~37% of files (newer syntax) and+silently skips them — the worst failure mode for an audit. `tree-sitter-php`+parses 100%:++| | phply | tree-sitter-php |+|---|--:|--:|+| files parsed (real WP core) | ~63% | **100%** |+| full-tree scan time | — | **~3.6 s** for ~619k lines |+| functions/methods indexed | — | 11,940 |+| whole-tree tokens ("load it all") | — | ~5.2 M (unreviewable) |+| candidate findings to triage | — | **129** |++The headline is the last two rows: the graph turns a 5.2M-token tree no context+window can hold into **129 candidate paths** an AI can actually work through.+Honesty check — these are *candidates, not confirmed bugs*: WP core is heavily+audited, so most of the 129 (largely `echo`/`include` hits) are already escaped+or path-validated in ways the name-based sanitizer list doesn't yet recognize.+The follow-on work is a context-aware WP sanitizer model, and it starts from a+tractable 129, not from 5.2M tokens.+## Design for real WordPress scaleThe prototype is a plugin; core + plugins is the target. The design carries over:@@ -142,9 +174,17 @@ analyzer. Be clear about what it is not:classic real bug: `esc_html` on a value placed inside an HTML attribute).- **CSRF/nonce is heuristic** — "state change reachable from an entry with nononce call anywhere on the path." Real nonce logic can be conditional.-- **Parser coverage.** phply is solid but not 100% on the newest PHP syntax;- a file that fails to parse is skipped (and should be reported, not silently- dropped — the same loud-skip rule autoindex needs).+- **Parser coverage.** Solved for PHP by moving to tree-sitter (100% of real WP+ core vs phply's ~63%). The rule stands for any parser: a file that fails to+ parse must be reported, not silently dropped — the same loud-skip rule+ autoindex needs.+- **Precision on real code needs a per-framework sanitizer model.** The 5-language+ demo is clean because the samples are minimal. On real WP core the same+ substring/name-based sinks over-report (129 candidates, most already escaped).+ Two concrete fixes, both known: match sinks on the AST *callee node* (done —+ no more `exec(` matching `fsockopen(`), and resolve call edges only to+ unambiguously-defined names (done — no more collisions across 11,940+ functions). What remains is context-aware sanitizer recognition per framework.- **Every finding needs confirmation.** The point is to shrink what the AI (andhuman) read so they *can* reason about exploitability — not to auto-file CVEs.@@ -155,7 +195,12 @@ analyzer. Be clear about what it is not:`xerj autoindex ./code` produces the graph-ready index directly.2. **Findings as a first-class index** with a severity/route schema, so theagent loop is "query findings → pull path code → confirm."-3. **Multi-language via tree-sitter**, reusing the per-framework taint lists.+3. ~~**Multi-language via tree-sitter**, reusing the per-framework taint lists.~~+ **Done** — `scan_multilang.py` covers PHP/Python/Go/Rust/Java on one engine;+ adding a language is a config row.4. **Loud skips** — a file that fails to parse must be reported (a silentlydropped file in a security audit is the worst-case), matching theautoindex honesty rule.+5. **Per-framework sanitizer model** — the next precision lever, to drop the real+ WordPress candidate set from 129 toward its true positives (context-aware+ escaper matching, path allow-lists for `include`/template loaders).