Files
apex-twin/tests/run.py
T
lotherk d7bc372208 apex-twin 0.1.0: C99/POSIX offensive-security MCP server
Scope gate is the product: deny-by-default, deny beats allow, DNS answers
must stay inside allow_ip, port and radio-transmission are separate switches.
27 tools over libmcp: recon (in-process portscan, nmap, dns, tls, banner),
web (http_request, header audit, path discovery, sqli/xss leads), ESP32
Marauder serial bridge, findings with evidence, and 12 method playbooks.

56 end-to-end checks, seen red with the no-scope branch disabled.
Not yet wired into systemd or a fleet router.
2026-11-20 21:59:09 +00:00

307 lines
12 KiB
Python
Executable File

#!/usr/bin/env python3
"""APEX TWIN end-to-end: gate, tools, store, transport.
No mocks. A temp state directory, the real binary, real DNS for the one name
that is in scope, and assertions on the files the server actually wrote. The
point of the suite is the gate: everything else is a tool, the gate is the
product.
"""
import json
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.request
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BIN = os.path.join(HERE, "apex-twin")
ROOT = tempfile.mkdtemp(prefix="apex-twin-test-")
fails = []
passes = 0
def check(name, cond, detail=""):
global passes
if cond:
passes += 1
print("PASS " + name)
else:
print("FAIL " + name + (" " + str(detail) if detail else ""))
fails.append(name)
def run(msgs, home=None, extra_env=None):
env = dict(os.environ)
env["APEX_HOME"] = home or ROOT
if extra_env:
env.update(extra_env)
proc = subprocess.run([BIN], input="\n".join(json.dumps(m) for m in msgs) + "\n",
capture_output=True, text=True, env=env, timeout=180)
out = []
for line in proc.stdout.splitlines():
if line.strip():
out.append(json.loads(line))
return out, proc
def call(i, _tool, **args):
return {"jsonrpc": "2.0", "id": i, "method": "tools/call",
"params": {"name": _tool, "arguments": args}}
def text(r):
try:
return r["result"]["content"][0]["text"]
except Exception:
return ""
def err(r):
try:
return bool(r["result"].get("isError"))
except Exception:
return False
def write_scope(home, obj):
os.makedirs(home, exist_ok=True)
with open(os.path.join(home, "scope.json"), "w") as f:
json.dump(obj, f)
SCOPE = {
"label": "suite",
"expires": "2099-12-31T23:59:59Z",
"allow_private": False,
"allow_ip": ["192.0.2.0/24", "198.51.100.7"],
"deny_ip": ["192.0.2.66"],
"allow_domain": ["example.com"],
"allow_port": ["80", "8080"],
}
print("== binary ==")
check("binary exists", os.path.isfile(BIN), BIN)
# ---------------------------------------------------------------- no scope
print("\n== no scope: everything refused ==")
empty = tempfile.mkdtemp(prefix="apex-noscope-")
res, _ = run([
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
call(2, "portscan", target="example.com", ports="80"),
call(3, "nmap", target="example.com"),
call(4, "http_request", target="example.com", path="/"),
call(5, "scope_show"),
], home=empty)
check("tools/list answers", any(r.get("id") == 1 for r in res))
tools = [r for r in res if r.get("id") == 1][0]["result"]["tools"]
check("27 tools registered", len(tools) == 27, len(tools))
names = {t["name"] for t in tools}
for need in ("portscan", "nmap", "http_request", "marauder_scan",
"method_playbook", "finding_add"):
check("tool present: " + need, need in names)
for r in res:
if r.get("id") in (2, 3, 4):
check("refused without scope (id %s)" % r["id"], err(r), text(r))
# the *reason* is the contract: a refusal that falls through to another
# deny branch (empty allow_ip) looks identical from isError alone
check("refusal names the missing scope (id %s)" % r["id"],
"no scope loaded" in text(r), text(r))
check("scope_show reports loaded=false",
'"loaded":false' in text([r for r in res if r.get("id") == 5][0]))
shutil.rmtree(empty, ignore_errors=True)
# --------------------------------------------------------------- with scope
print("\n== with scope ==")
write_scope(ROOT, SCOPE)
res, _ = run([
call(1, "scope_show"),
call(2, "portscan", target="198.51.100.5", ports="80"), # outside
call(3, "portscan", target="192.0.2.66", ports="80"), # denied ip
call(4, "nmap", target="203.0.113.9"), # outside
call(5, "marauder_cmd", command="attack"), # transmit, tx off
call(6, "marauder_cmd", command="rm -rf /"), # not allowlisted
call(7, "http_request", target="example.com", port=22, path="/"), # port
])
by_id = {r.get("id"): r for r in res}
check("scope loaded", '"loaded":true' in text(by_id[1]), text(by_id[1]))
check("out-of-scope ip refused", err(by_id[2]), text(by_id[2]))
check("refusal says outside allow_ip", "outside allow_ip" in text(by_id[2]),
text(by_id[2]))
check("denied ip refused over allow range", err(by_id[3]), text(by_id[3]))
check("deny reason names deny_ip", "deny_ip" in text(by_id[3]), text(by_id[3]))
check("out-of-scope nmap refused", err(by_id[4]), text(by_id[4]))
check("refusal says outside allow_ip (nmap)", "outside allow_ip" in text(by_id[4]),
text(by_id[4]))
check("transmitting radio command refused without serial_tx", err(by_id[5]),
text(by_id[5]))
check("refusal names serial_tx", "serial_tx" in text(by_id[5]), text(by_id[5]))
check("non-allowlisted radio command refused", err(by_id[6]), text(by_id[6]))
check("refusal names the allowlist", "allowlist" in text(by_id[6]),
text(by_id[6]))
check("port outside allow_port refused", err(by_id[7]), text(by_id[7]))
check("refusal names allow_port", "allow_port" in text(by_id[7]), text(by_id[7]))
print("\n== scope expiry ==")
expired_home = tempfile.mkdtemp(prefix="apex-expired-")
write_scope(expired_home, dict(SCOPE, expires="2000-01-01T00:00:00Z"))
res, _ = run([call(1, "portscan", target="example.com", ports="80")],
home=expired_home)
check("expired scope refuses", err(res[0]), text(res[0]))
check("refusal says expired", "expired" in text(res[0]), text(res[0]))
shutil.rmtree(expired_home, ignore_errors=True)
print("\n== allow_private off ==")
priv_home = tempfile.mkdtemp(prefix="apex-priv-")
write_scope(priv_home, {"label": "priv", "allow_private": False,
"allow_domain": ["localhost"], "allow_port": ["80"]})
res, _ = run([call(1, "portscan", target="localhost", ports="80")],
home=priv_home)
check("private address refused when allow_private is false", err(res[0]),
text(res[0]))
check("refusal names allow_private", "allow_private" in text(res[0]), text(res[0]))
write_scope(priv_home, {"label": "priv", "allow_private": True,
"allow_domain": ["localhost"], "allow_port": ["80"]})
res, _ = run([call(1, "portscan", target="localhost", ports="80",
timeout_ms=500)], home=priv_home)
check("private address allowed when allow_private is true", not err(res[0]),
text(res[0]))
shutil.rmtree(priv_home, ignore_errors=True)
# ------------------------------------------------------------------- tools
print("\n== recon that really runs ==")
res, _ = run([
call(1, "capabilities"),
call(2, "portscan", target="example.com", ports="80", timeout_ms=4000),
call(3, "http_headers", target="example.com", port=80, path="/"),
call(4, "audit_log", limit=5),
])
by_id = {r.get("id"): r for r in res}
caps = json.loads(text(by_id[1]))
check("capabilities names the state dir", caps["home"] == ROOT, caps["home"])
check("capabilities reports scope_loaded", caps["scope_loaded"] is True)
check("capabilities probes programs", isinstance(caps["programs"], dict),
caps.get("programs"))
scan = json.loads(text(by_id[2]))
check("portscan reached example.com:80", 80 in scan["open"], text(by_id[2]))
check("portscan only probed allowed ports", scan["checked"] <= 2, scan)
hdrs = json.loads(text(by_id[3]))
check("http_headers got a status line", hdrs["status"].startswith("HTTP/1.1"),
hdrs.get("status"))
check("http_headers found missing headers", hdrs["missing_count"] > 0, hdrs)
audit = json.loads(text(by_id[4]))
check("audit_log returns entries", len(audit) > 0, audit)
check("audit entries carry a decision",
all("decision" in a for a in audit), audit[:1])
# ------------------------------------------------------------------- store
print("\n== findings and evidence ==")
res, _ = run([
call(1, "evidence_save", label="suite", data="HTTP/1.1 200 OK\nServer: x"),
call(2, "finding_add", target="example.com", title="Missing CSP",
severity="medium", confidence="certain", tool="http_headers",
evidence="see evidence", cwe="CWE-693", remediation="add CSP"),
call(3, "finding_list"),
call(4, "finding_read", id="f0001"),
call(5, "finding_add", target="198.51.100.5", title="out of scope"),
])
by_id = {r.get("id"): r for r in res}
ev = json.loads(text(by_id[1]))
check("evidence file written", os.path.isfile(ev["evidence"]), ev)
check("evidence bytes recorded", ev["bytes"] == len("HTTP/1.1 200 OK\nServer: x"), ev)
fid = json.loads(text(by_id[2]))["id"]
check("finding got an id", fid.startswith("f"), fid)
listed = json.loads(text(by_id[3]))
check("finding appears in the list", any(f["id"] == fid for f in listed), listed)
read = json.loads(text(by_id[4]))
check("finding_read returns the finding", read["id"] == "f0001", read)
check("finding for an out-of-scope target is refused", err(by_id[5]),
text(by_id[5]))
# --------------------------------------------------------------- transport
print("\n== http transport ==")
def free_port():
"""Never assume a port: 18797 on this host is an SSH forward to koder and
answered a foreign serverInfo while the suite was green."""
s = socket.socket()
s.bind(("127.0.0.1", 0))
p = s.getsockname()[1]
s.close()
return p
port = free_port()
env = dict(os.environ)
env["APEX_HOME"] = ROOT
srv = subprocess.Popen([BIN, "--http", str(port)], env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
deadline = time.time() + 10
up = False
while time.time() < deadline:
probe = socket.socket()
try:
probe.connect(("127.0.0.1", port))
up = True
probe.close()
break
except OSError:
probe.close()
time.sleep(0.1)
check("http listener came up on a free port", up, port)
try:
def post(obj):
data = json.dumps(obj).encode()
req = urllib.request.Request("http://127.0.0.1:%d/mcp" % port, data=data,
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=20) as r:
return json.loads(r.read().decode())
init = post({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}})
check("http initialize", init["result"]["serverInfo"]["name"] == "apex-twin",
init)
listing = post({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
check("http tools/list", len(listing["result"]["tools"]) == 27)
shown = post(call(3, "scope_show"))
check("http scope_show", '"loaded":true' in shown["result"]["content"][0]["text"])
# the id must be the request's id, not one found inside the arguments
nested = post({"jsonrpc": "2.0", "method": "tools/call",
"params": {"name": "finding_read", "arguments": {"id": "f0001"}},
"id": "string-id"})
check("http echoes a string id", nested.get("id") == "string-id", nested)
try:
urllib.request.urlopen("http://127.0.0.1:%d/nope" % port, data=b"{}",
timeout=5)
check("wrong path rejected", False, "200 for /nope")
except urllib.error.HTTPError as e:
check("wrong path rejected", e.code == 404, e.code)
finally:
srv.terminate()
try:
srv.wait(timeout=5)
except subprocess.TimeoutExpired:
srv.kill()
# ------------------------------------------------------------- serial guard
print("\n== serial guard ==")
fake = os.path.join(ROOT, "notamodem")
with open(fake, "w") as f:
f.write("")
res, _ = run([call(1, "marauder_info")], extra_env={"APEX_SERIAL": fake})
check("a non-tty serial port fails loudly", err(res[0]), text(res[0]))
print("\n== summary ==")
print("%d passed, %d failed" % (passes, len(fails)))
if fails:
print("failed: " + ", ".join(fails))
shutil.rmtree(ROOT, ignore_errors=True)
sys.exit(1)
shutil.rmtree(ROOT, ignore_errors=True)
sys.exit(0)