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(ast-vuln): finish core — file-scope wp-admin handlers + map_meta_cap engine

Xerj Squad Ab6f8d4f872fd
diff --git a/docs/examples/ast-vuln-graph/wp_admin_pages.py b/docs/examples/ast-vuln-graph/wp_admin_pages.py
new file mode 100644
index 000000000..0482ead9f
--- /dev/null
+++ b/docs/examples/ast-vuln-graph/wp_admin_pages.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python3
+"""Close the biggest substrate gap: direct wp-admin page handlers live at FILE
+SCOPE (a top-level switch($action){case ...}), not inside functions, so the
+function-only index never saw them. Extract each case block as a handler unit and
+run the same authz analysis: object-scoped cap? object-scoped nonce? state change
+on a request-identified object?"""
+import glob, os, re, sys
+from tree_sitter import Language, Parser
+import tree_sitter_php as tsphp
+parser=Parser(Language(tsphp.language_php()))
+WP=sys.argv[1]
+def txt(n): return n.text.decode("utf8","replace")
+
+CAP=("current_user_can","current_user_can_for_blog","user_can","author_can")
+NONCE=("check_admin_referer","check_ajax_referer","wp_verify_nonce")
+STATE=("wp_trash_post","wp_delete_post","wp_untrash_post","wp_update_post","wp_insert_post",
+ "update_option","delete_option","wp_delete_user","wp_update_user","update_post_meta",
+ "delete_post_meta","update_user_meta","wp_set_object_terms","wp_delete_attachment",
+ "wp_delete_comment","wp_set_comment_status","edit_post","bulk_edit_posts","wp_delete_term",
+ "wp_update_term","update_metadata","delete_metadata","wp_trash_comment","wp_update_link")
+
+def top_level_switch_cases(root):
+ """Yield case blocks of switch statements that are NOT inside a function."""
+ out=[]
+ def walk(n, in_fn):
+ infn = in_fn or n.type in ("function_definition","method_declaration")
+ if n.type=="switch_statement" and not in_fn:
+ body=n.child_by_field_name("body") or n
+ for c in body.children:
+ if c.type in ("case_statement","default_statement"):
+ out.append(c)
+ for ch in n.children: walk(ch, infn)
+ walk(root, False)
+ return out
+
+def calls_of(node, names):
+ hits=[]
+ def w(n):
+ if n.type in ("function_call_expression","member_call_expression","scoped_call_expression"):
+ fn=n.child_by_field_name("function") or n.child_by_field_name("name")
+ if fn is not None:
+ nm=txt(fn).split("->")[-1].split("::")[-1]
+ if nm in names:
+ args=n.child_by_field_name("arguments")
+ ac=[a for a in (args.children if args else []) if a.type=="argument"]
+ hits.append((nm,ac))
+ for ch in n.children: w(ch)
+ w(node); return hits
+
+rows=[]
+for path in glob.glob(f"{WP}/wp-admin/**/*.php", recursive=True):
+ root=parser.parse(open(path,"rb").read()).root_node
+ rel=os.path.relpath(path,WP)
+ for case in top_level_switch_cases(root):
+ body=txt(case)
+ label=re.match(r"\s*case\s+([^:]+):",body)
+ name=label.group(1).strip() if label else "default"
+ capcalls=calls_of(case,CAP); noncecalls=calls_of(case,NONCE); statecalls=calls_of(case,STATE)
+ obj_cap=any(len(ac)>=2 for nm,ac in capcalls)
+ dyn_nonce=any(any('$' in txt(a) or txt(a).count('.') for a in ac) for nm,ac in noncecalls)
+ reads_id=bool(re.search(r"\$_(?:GET|POST|REQUEST)\[\s*['\"](?:id|post|post_id|user_id|comment)['\"]",body)) \
+ or "$post_id" in body or "$post_ID" in body
+ if statecalls: # only handlers that mutate state matter for authz
+ rows.append(dict(file=rel,case=name,obj_cap=obj_cap,has_cap=bool(capcalls),
+ has_nonce=bool(noncecalls),dyn_nonce=dyn_nonce,reads_id=reads_id,
+ state=[nm for nm,_ in statecalls]))
+
+print(f"file-scope wp-admin state-changing action handlers: {len(rows)}")
+susp=[r for r in rows if not r["obj_cap"]]
+print(f"\n[cap-presence] state-changing handlers with NO object-scoped cap: {len(susp)}")
+for r in sorted(susp,key=lambda x:x['file']):
+ tag="no-cap" if not r["has_cap"] else "generic-cap"
+ print(f" {r['file']:26} case {r['case']:22} [{tag}] nonce={r['has_nonce']}(dyn={r['dyn_nonce']}) state={r['state'][:3]}")
diff --git a/docs/research/wordpress-authz-agentic-audit.md b/docs/research/wordpress-authz-agentic-audit.md
index 6c6be164a..fef0d9740 100644
--- a/docs/research/wordpress-authz-agentic-audit.md
+++ b/docs/research/wordpress-authz-agentic-audit.md
@@ -293,12 +293,67 @@ is the whole point:
> detector flags that shape directly. Core survives by adding the consistency
> guard; plugins routinely omit it.
+## Finishing core: the file-scope handlers and the authz engine
+
+Three surfaces remained. Two exposed the last substrate gap.
+
+**`admin_post_*`** — core registers essentially none by literal string (it is a
+plugin surface); the hook extractor found 0. Noted, not a gap in core.
+
+**Direct `wp-admin` page handlers** — the real gap. `wp-admin/post.php`,
+`users.php`, `comment.php`, etc. handle requests in a **top-level
+`switch($action)` at file scope**, not inside any function — so the
+function-only index never saw a single one of them. `wp_admin_pages.py` extends
+the substrate to extract each `case` block as a handler unit. It found 41
+state-changing file-scope handlers; the cap-presence sweep flagged 24 without an
+object-scoped cap. Reading the top ones showed **core is correctly gated** and
+the flags are an extractor artifact — the guard lives in **shared preamble,
+fall-through group heads, or a different nested switch**, not co-located with the
+`case`:
+
+- `users.php case 'delete'` → the real handler has
+ `check_admin_referer('delete-users')` + `current_user_can('delete_user', $id)`
+ per user; the extractor matched the *nested* `switch($_REQUEST['delete_option'])`
+ `case 'delete'` (what to do with the deleted user's posts), not the authz case.
+- `comment.php` delete/trash cases fall through to shared code guarded by
+ `current_user_can('edit_comment', $comment->comment_ID)`.
+
+The lesson repeats one level out: **authorization is frequently in shared scope,
+not beside the action** — a file-scope handler analyzer must gather guards from
+the enclosing switch/preamble, exactly as the interprocedural one gathers them
+across call edges.
+
+**`map_meta_cap` (the authz engine)** — fails safe. Meta-cap checked with no
+object arg → `do_not_allow`; non-existent post → `do_not_allow`; revision →
+resolve to parent, missing → `do_not_allow`. The single non-fail-closed fallback
+(unregistered post type → `edit_others_posts`) still requires an editor-level
+cap. Fail-closed by construction.
+
+## Core is verified hardened; the detectors are ready
+
+Every core authorization and SQL-escaping flow tested is object-scoped,
+relationship-checked, and fail-safe:
+
+| surface | result |
+|---|---|
+| authenticated AJAX (95) | object-scoped, 0 IDOR |
+| REST mutating (33) + read (57) | object-scoped, 0 IDOR |
+| file-scope wp-admin handlers (41) | object-scoped (guards in shared scope) |
+| `map_meta_cap` engine | fails closed |
+| check-vs-use (revisions) | defended by explicit consistency guard |
+| double-prepare SQL de-escape | neutralized by `placeholder_escape` |
+
+Getting these negatives *trustworthy* required 3 model refinements and 3
+substrate-bug fixes (infra boundary, OOP method-name collision, file-scope
+handler extraction) — each found by the agent noticing an impossible result and
+reading the real code. That is the whole method: XERJ holds the system as
+external memory; the agent builds a model, tests it, and repairs the model *and*
+the substrate when reality disagrees.
+
## What's next
-The reasoning loop and its detectors (object-scoped cap-presence, check-vs-use
-mismatch, double-prepare de-escape) are now built and validated against a core
-that is — verifiably — hardened on all of them. The place they will actually
-fire is the **plugin ecosystem**, where object-scoped caps, relationship
-re-verification, and placeholder-escape are the exact defenses most often missing.
-Remaining core surfaces for completeness: `admin_post_*`, direct `wp-admin` page
-handlers, and `map_meta_cap` edge cases.
+The detectors (object-scoped cap-presence, check-vs-use mismatch, double-prepare
+de-escape, file-scope handler authz) are built and proven against a maximally
+hardened core. They will actually fire on the **plugin ecosystem**, where
+object-scoped caps, relationship re-verification, and placeholder-escape are the
+exact defenses most often missing.