#!/usr/bin/env python3 """tests/mockd.py -- the offline harness the plugin_ntfy suite talks to. One process, three jobs, zero internet: 1. a mock ntfy server (publish capture + the NDJSON /json stream, including our own publishes echoed back, exactly like the real server, so the anti-self-loop rule is proven against the real behaviour and not against a fixture that hides it); 2. a mock SCORPIOX BOT node API (/inbox + /conversation with a scripted assistant reply, in the exact event-file layout the real scorpiox-bot-api reads); 3. a control API the test suite uses to drive time and inject events (/__inject, /__publishes, /__inbox, /__reset, /__stats). Every inbound sender identity in the tests is created through /__inject with an explicit user/tags pair, so "approved" and "unapproved" are real states of the plugin's own pairing store, not faked return values. MIT License. Copyright (c) 2026 SCORPIOX INC. """ import json import os import re import shutil import socket import socketserver import ssl import subprocess import threading import time import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer TOPIC_RE = re.compile(r"^/[A-Za-z0-9._-]+/(json|txt)$") PUBLISH_RE = re.compile(r"^/[A-Za-z0-9._-]+$") class State: def __init__(self, root): self.root = root self.lock = threading.Lock() self.events = [] # ndjson records, per topic self.published = [] # everything POSTed to a topic (captured) self.inbox = [] # everything POSTed to /inbox self.conv_seq = 0 # conversation sequence for the session self.reply = "reply-queued" # next assistant reply text self.auto_reply = True self.session = "mock-session" self.keepalive_every = 1 self.password = "" # when set, /inbox requires X-Bot-Password self.next_id = 1 def new_id(self): with self.lock: i = self.next_id self.next_id += 1 return "m%06d" % i def add_message(self, topic, message, title=None, priority=None, tags=None, user=None, source_id=None, extra=None): rec = { "id": self.new_id(), "time": int(time.time()), "expires": int(time.time()) + 43200, "event": "message", "topic": topic, "message": message, } if title: rec["title"] = title if priority is not None: rec["priority"] = priority if tags: rec["tags"] = [t.strip() for t in str(tags).split(",") if t.strip()] if user: rec["user"] = user if source_id: rec["source-id"] = source_id if extra: rec.update(extra) with self.lock: self.events.append(rec) return rec def since(self, topic, since=0): with self.lock: out = [e for e in self.events if e.get("topic") == topic and e.get("time", 0) >= since - 1] return out # -- conversation (mirrors scorpiox-bot-api events/ layout) ---------- def conv_dir(self): return os.path.join(self.root, "sessions", self.session, "events") def append_user_event(self, text): d = self.conv_dir() os.makedirs(d, exist_ok=True) with self.lock: self.conv_seq += 1 seq = self.conv_seq with open(os.path.join(d, "%06d.json" % seq), "w") as f: json.dump({"seq": seq, "ts": int(time.time() * 1000), "type": "user", "content": text}, f) return seq def append_assistant_event(self, text): d = self.conv_dir() os.makedirs(d, exist_ok=True) with self.lock: self.conv_seq += 1 seq = self.conv_seq with open(os.path.join(d, "%06d.json" % seq), "w") as f: json.dump({"seq": seq, "ts": int(time.time() * 1000), "type": "assistant", "content": text}, f) return seq def conversation(self, after, limit=100): d = self.conv_dir() msgs = [] start = 0 if not os.path.isdir(d): return {"id": self.session, "session_id": self.session, "total": 0, "after": after, "start_index": 0, "messages": []} files = sorted(f for f in os.listdir(d) if f.endswith(".json")) seqs = [int(f.split(".")[0]) for f in files] total = max(seqs) if seqs else 0 end = total eff = after if after >= 0 else 0 if eff > end: eff = end if limit and eff + limit < end: end = eff + limit for seq in range(eff + 1, end + 1): p = os.path.join(d, "%06d.json" % seq) if not os.path.isfile(p): continue try: with open(p) as f: ev = json.load(f) except Exception: continue t = ev.get("type", "unknown") role = t m = {"role": role, "content": ev.get("content", "")} if ev.get("ts"): m["timestamp_ms"] = ev["ts"] msgs.append(m) start = seq return {"id": self.session, "session_id": self.session, "total": total, "after": after, "start_index": (eff if msgs else max(0, eff)), "messages": msgs} STATE = None class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" server_version = "sxmockntfy/1.0" # ---------------- plumbing ------------------------------------------- def log_message(self, fmt, *args): pass def _send(self, code, body=b"", ctype="application/json", extra=None, chunked=False): self.send_response(code) self.send_header("Content-Type", ctype) if chunked: self.send_header("Transfer-Encoding", "chunked") else: self.send_header("Content-Length", str(len(body))) self.send_header("Access-Control-Allow-Origin", "*") for k, v in (extra or {}).items(): self.send_header(k, v) self.end_headers() if body: self.wfile.write(body) def _send_chunk(self, data): self.wfile.write(b"%x\r\n" % len(data) + data + b"\r\n") self.wfile.flush() def _json(self, code, obj, **kw): self._send(code, json.dumps(obj).encode(), **kw) def _body(self): n = int(self.headers.get("Content-Length") or 0) if n <= 0: return b"" return self.rfile.read(n) def _authed(self): if not STATE.password: return True return self.headers.get("X-Bot-Password", "") == STATE.password # ---------------- GET ------------------------------------------------ def do_GET(self): path = self.path.split("?")[0] q = {} if "?" in self.path: for kv in self.path.split("?", 1)[1].split("&"): if "=" in kv: k, v = kv.split("=", 1) q[k] = v else: q[kv] = "" # ---- control API ---- if path == "/__stats": with STATE.lock: return self._json(200, { "ok": True, "events": len(STATE.events), "published": len(STATE.published), "inbox": len(STATE.inbox), "conv_seq": STATE.conv_seq, }) if path == "/__publishes": with STATE.lock: return self._json(200, {"ok": True, "published": list(STATE.published)}) if path == "/__inbox": with STATE.lock: return self._json(200, {"ok": True, "inbox": list(STATE.inbox)}) if path == "/__events": with STATE.lock: return self._json(200, {"ok": True, "events": list(STATE.events)}) # ---- mock node API ---- if path == "/conversation": if not self._authed(): return self._json(401, {"error": "unauthorized"}) after = int(q.get("after", "-1") or -1) limit = int(q.get("limit", "100") or 100) return self._json(200, STATE.conversation(after, limit)) if path == "/plugins": return self._json(200, {"ok": True, "count": 0, "plugins": []}) # ---- mock ntfy subscribe ---- m = TOPIC_RE.match(path) if m: topic = path[1:-len("/" + m.group(1))] topic = topic.lstrip("/") since = int(q.get("since", "0") or 0) poll = q.get("poll") in ("1", "true") recs = STATE.since(topic, since) self.send_response(200) self.send_header("Content-Type", "application/x-ndjson; charset=utf-8") self.send_header("Transfer-Encoding", "chunked") self.end_headers() try: self._send_chunk(b'{"event":"open","topic":"%s","time":%d}\n' % (topic.encode(), int(time.time()))) for r in recs: self._send_chunk((json.dumps(r) + "\n").encode()) if poll: self._send_chunk(b"") self.wfile.write(b"0\r\n\r\n") self.wfile.flush() return # live stream: keepalives + any record that arrives later seen = {r["id"] for r in recs} last_keep = time.time() while True: time.sleep(0.2) now = time.time() for r in STATE.since(topic, since): if r["id"] in seen: continue seen.add(r["id"]) self._send_chunk((json.dumps(r) + "\n").encode()) if now - last_keep > 1.0: last_keep = now self._send_chunk(b"### keepalive\n") except (BrokenPipeError, ConnectionResetError): return return return self._json(404, {"code": 404, "error": "not found"}) # ---------------- POST ---------------------------------------------- def do_POST(self): path = self.path.split("?")[0] q = {} if "?" in self.path: for kv in self.path.split("?", 1)[1].split("&"): if "=" in kv: k, v = kv.split("=", 1) q[k] = v else: q[kv] = "" # ---- control API ---- if path == "/__inject": body = self._body() try: d = json.loads(body.decode() or "{}") except Exception: return self._json(400, {"ok": False, "error": "bad json"}) rec = STATE.add_message( d.get("topic", "test-in"), d.get("message", "hello"), title=d.get("title"), priority=d.get("priority"), tags=d.get("tags"), user=d.get("user"), source_id=d.get("source-id"), extra=d.get("extra"), ) return self._json(200, {"ok": True, "id": rec["id"]}) if path == "/__reply": d = json.loads(self._body().decode() or "{}") text = d.get("content", "reply") seq = STATE.append_assistant_event(text) return self._json(200, {"ok": True, "seq": seq}) if path == "/__reset": with STATE.lock: STATE.events = [] STATE.published = [] STATE.inbox = [] shutil.rmtree(os.path.join(STATE.root, "sessions"), ignore_errors=True) STATE.conv_seq = 0 return self._json(200, {"ok": True}) if path == "/__config": d = json.loads(self._body().decode() or "{}") if "password" in d: STATE.password = d["password"] or "" if "session" in d: STATE.session = d["session"] return self._json(200, {"ok": True}) # ---- mock node inbox ---- if path == "/inbox": if not self._authed(): return self._json(401, {"error": "unauthorized"}) sid = q.get("id") or q.get("session") or "" body = self._body() try: d = json.loads(body.decode() or "{}") text = d.get("text") or d.get("content") or d.get("message") or "" except Exception: text = body.decode("utf-8", "replace") if not sid: return self._json(400, {"error": "valid id parameter is required"}) with STATE.lock: STATE.inbox.append({"id": sid, "text": text, "mode": d.get("mode") if isinstance(d, dict) else None, "at": int(time.time())}) STATE.append_user_event(text) return self._json(200, {"ok": True, "queued": True, "id": sid}) # ---- mock ntfy publish ---- if PUBLISH_RE.match(path): topic = path.lstrip("/") body = self._body() hdrs = {k.lower(): v for k, v in self.headers.items()} tags = hdrs.get("tags") tags_l = [t.strip() for t in (tags or "").split(",") if t.strip()] rec = { "id": STATE.new_id(), "time": int(time.time()), "expires": int(time.time()) + 43200, "event": "message", "topic": topic, "message": body.decode("utf-8", "replace"), } title = hdrs.get("title") or hdrs.get("x-title") if title: rec["title"] = title prio = hdrs.get("priority") or hdrs.get("x-priority") if prio: try: rec["priority"] = int(prio) except ValueError: pass if tags_l: rec["tags"] = tags_l if hdrs.get("x-markdown") or hdrs.get("markdown"): rec["content_type"] = "text/markdown" if hdrs.get("click") or hdrs.get("x-click"): rec["click"] = hdrs.get("click") or hdrs.get("x-click") auth = hdrs.get("authorization", "") rec["_authorization"] = auth rec["_x_source_id"] = hdrs.get("x-source-id", "") rec["_user_header"] = hdrs.get("user", "") # auth simulation: when a token is expected, require it if STATE.password and topic.endswith("-auth"): if not auth.startswith("Bearer "): return self._json(401, {"code": 40101, "http": 401, "error": "unauthorized"}) with STATE.lock: STATE.published.append(rec) STATE.events.append({k: v for k, v in rec.items() if not k.startswith("_")}) out = {k: v for k, v in rec.items() if not k.startswith("_")} return self._json(200, out) return self._json(404, {"code": 404, "error": "not found"}) class Server(ThreadingHTTPServer): daemon_threads = True allow_reuse_address = True def handle_error(self, request, client_address): # A client that aborts the handshake (which is exactly what a # failing-closed TLS client does when it refuses our self-signed # leaf) lands here as an SSLError. It is a result, not a crash. return def serve_tls(port, backend_cert_dir, bind="127.0.0.1"): """Same handler over TLS. The leaf is self-signed for 127.0.0.1, so the plugin's bundled root store never trusts it: it can only be accepted through an explicit SPKI pin, and only rejected (never silently downgraded) without one. That is the property the pinning tests assert. ThreadingHTTPServer wraps the listener, so every accepted connection gets its own SSL socket and its own thread -- the long-lived NDJSON stream never shares a record buffer with a handshake. `bind` lets the suite stand a second front on another loopback address with the SAME certificate. Reaching that leaf at an address outside its only IP SAN is how the hostname-mismatch rule gets tested without DNS: this container has no /etc/hosts, so a name would only exercise the resolver error path and prove nothing about verification. """ os.makedirs(backend_cert_dir, exist_ok=True) key = os.path.join(backend_cert_dir, "mock-key.pem") crt = os.path.join(backend_cert_dir, "mock-cert.pem") if not (os.path.exists(key) and os.path.exists(crt)): subprocess.run( ["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-out", crt, "-days", "2", "-subj", "/CN=127.0.0.1/O=SCORPIOX BOT test", "-addext", "subjectAltName=IP:127.0.0.1"], check=True, capture_output=True) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain(crt, key) srv = Server((bind, port), Handler) srv.socket = ctx.wrap_socket(srv.socket, server_side=True) threading.Thread(target=srv.serve_forever, kwargs={"poll_interval": 0.2}, daemon=True).start() def main(): import argparse global STATE ap = argparse.ArgumentParser() ap.add_argument("--port", type=int, default=18199) ap.add_argument("--root", default="/tmp/sx-ntfy-mock") ap.add_argument("--tls-port", type=int, default=0, help="also serve HTTPS on this port with a self-signed leaf") ap.add_argument("--tls-mismatch-port", type=int, default=0, help="a second HTTPS front on 127.0.0.2 with the SAME " "127.0.0.1-only leaf, i.e. a real hostname mismatch") args = ap.parse_args() os.makedirs(args.root, exist_ok=True) STATE = State(args.root) if args.tls_port: serve_tls(args.tls_port, os.path.join(args.root, "tls")) if args.tls_mismatch_port: serve_tls(args.tls_mismatch_port, os.path.join(args.root, "tls"), bind="127.0.0.2") srv = Server(("127.0.0.1", args.port), Handler) print("mockd listening on 127.0.0.1:%d root=%s%s%s" % (args.port, args.root, " tls=127.0.0.1:%d" % args.tls_port if args.tls_port else "", " tls-mismatch=127.0.0.2:%d" % args.tls_mismatch_port if args.tls_mismatch_port else ""), flush=True) try: srv.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()