scorpiox-bot-plugin-ntfy
←mockd.pypython
485 lines · 18 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/mockd.py -- the offline harness the plugin_ntfy suite talks to.
3
4One process, three jobs, zero internet:
5
6 1. a mock ntfy server (publish capture + the NDJSON <topic>/json stream,
7 including our own publishes echoed back, exactly like the real server,
8 so the anti-self-loop rule is proven against the real behaviour and not
9 against a fixture that hides it);
10 2. a mock SCORPIOX BOT node API (/inbox + /conversation with a scripted
11 assistant reply, in the exact event-file layout the real
12 scorpiox-bot-api reads);
13 3. a control API the test suite uses to drive time and inject events
14 (/__inject, /__publishes, /__inbox, /__reset, /__stats).
15
16Every inbound sender identity in the tests is created through /__inject with
17an explicit user/tags pair, so "approved" and "unapproved" are real states of
18the plugin's own pairing store, not faked return values.
19
20MIT License. Copyright (c) 2026 SCORPIOX INC.
21"""
22
23import json
24import os
25import re
26import shutil
27import socket
28import socketserver
29import ssl
30import subprocess
31import threading
32import time
33import uuid
34from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
35
36TOPIC_RE = re.compile(r"^/[A-Za-z0-9._-]+/(json|txt)$")
37PUBLISH_RE = re.compile(r"^/[A-Za-z0-9._-]+$")
38
39
40class State:
41 def __init__(self, root):
42 self.root = root
43 self.lock = threading.Lock()
44 self.events = [] # ndjson records, per topic
45 self.published = [] # everything POSTed to a topic (captured)
46 self.inbox = [] # everything POSTed to /inbox
47 self.conv_seq = 0 # conversation sequence for the session
48 self.reply = "reply-queued" # next assistant reply text
49 self.auto_reply = True
50 self.session = "mock-session"
51 self.keepalive_every = 1
52 self.password = "" # when set, /inbox requires X-Bot-Password
53 self.next_id = 1
54
55 def new_id(self):
56 with self.lock:
57 i = self.next_id
58 self.next_id += 1
59 return "m%06d" % i
60
61 def add_message(self, topic, message, title=None, priority=None,
62 tags=None, user=None, source_id=None, extra=None):
63 rec = {
64 "id": self.new_id(),
65 "time": int(time.time()),
66 "expires": int(time.time()) + 43200,
67 "event": "message",
68 "topic": topic,
69 "message": message,
70 }
71 if title:
72 rec["title"] = title
73 if priority is not None:
74 rec["priority"] = priority
75 if tags:
76 rec["tags"] = [t.strip() for t in str(tags).split(",") if t.strip()]
77 if user:
78 rec["user"] = user
79 if source_id:
80 rec["source-id"] = source_id
81 if extra:
82 rec.update(extra)
83 with self.lock:
84 self.events.append(rec)
85 return rec
86
87 def since(self, topic, since=0):
88 with self.lock:
89 out = [e for e in self.events
90 if e.get("topic") == topic and e.get("time", 0) >= since - 1]
91 return out
92
93 # -- conversation (mirrors scorpiox-bot-api events/ layout) ----------
94 def conv_dir(self):
95 return os.path.join(self.root, "sessions", self.session, "events")
96
97 def append_user_event(self, text):
98 d = self.conv_dir()
99 os.makedirs(d, exist_ok=True)
100 with self.lock:
101 self.conv_seq += 1
102 seq = self.conv_seq
103 with open(os.path.join(d, "%06d.json" % seq), "w") as f:
104 json.dump({"seq": seq, "ts": int(time.time() * 1000),
105 "type": "user", "content": text}, f)
106 return seq
107
108 def append_assistant_event(self, text):
109 d = self.conv_dir()
110 os.makedirs(d, exist_ok=True)
111 with self.lock:
112 self.conv_seq += 1
113 seq = self.conv_seq
114 with open(os.path.join(d, "%06d.json" % seq), "w") as f:
115 json.dump({"seq": seq, "ts": int(time.time() * 1000),
116 "type": "assistant", "content": text}, f)
117 return seq
118
119 def conversation(self, after, limit=100):
120 d = self.conv_dir()
121 msgs = []
122 start = 0
123 if not os.path.isdir(d):
124 return {"id": self.session, "session_id": self.session, "total": 0,
125 "after": after, "start_index": 0, "messages": []}
126 files = sorted(f for f in os.listdir(d) if f.endswith(".json"))
127 seqs = [int(f.split(".")[0]) for f in files]
128 total = max(seqs) if seqs else 0
129 end = total
130 eff = after if after >= 0 else 0
131 if eff > end:
132 eff = end
133 if limit and eff + limit < end:
134 end = eff + limit
135 for seq in range(eff + 1, end + 1):
136 p = os.path.join(d, "%06d.json" % seq)
137 if not os.path.isfile(p):
138 continue
139 try:
140 with open(p) as f:
141 ev = json.load(f)
142 except Exception:
143 continue
144 t = ev.get("type", "unknown")
145 role = t
146 m = {"role": role, "content": ev.get("content", "")}
147 if ev.get("ts"):
148 m["timestamp_ms"] = ev["ts"]
149 msgs.append(m)
150 start = seq
151 return {"id": self.session, "session_id": self.session, "total": total,
152 "after": after, "start_index": (eff if msgs else max(0, eff)),
153 "messages": msgs}
154
155
156STATE = None
157
158
159class Handler(BaseHTTPRequestHandler):
160 protocol_version = "HTTP/1.1"
161 server_version = "sxmockntfy/1.0"
162
163 # ---------------- plumbing -------------------------------------------
164 def log_message(self, fmt, *args):
165 pass
166
167 def _send(self, code, body=b"", ctype="application/json", extra=None,
168 chunked=False):
169 self.send_response(code)
170 self.send_header("Content-Type", ctype)
171 if chunked:
172 self.send_header("Transfer-Encoding", "chunked")
173 else:
174 self.send_header("Content-Length", str(len(body)))
175 self.send_header("Access-Control-Allow-Origin", "*")
176 for k, v in (extra or {}).items():
177 self.send_header(k, v)
178 self.end_headers()
179 if body:
180 self.wfile.write(body)
181
182 def _send_chunk(self, data):
183 self.wfile.write(b"%x\r\n" % len(data) + data + b"\r\n")
184 self.wfile.flush()
185
186 def _json(self, code, obj, **kw):
187 self._send(code, json.dumps(obj).encode(), **kw)
188
189 def _body(self):
190 n = int(self.headers.get("Content-Length") or 0)
191 if n <= 0:
192 return b""
193 return self.rfile.read(n)
194
195 def _authed(self):
196 if not STATE.password:
197 return True
198 return self.headers.get("X-Bot-Password", "") == STATE.password
199
200 # ---------------- GET ------------------------------------------------
201 def do_GET(self):
202 path = self.path.split("?")[0]
203 q = {}
204 if "?" in self.path:
205 for kv in self.path.split("?", 1)[1].split("&"):
206 if "=" in kv:
207 k, v = kv.split("=", 1)
208 q[k] = v
209 else:
210 q[kv] = ""
211
212 # ---- control API ----
213 if path == "/__stats":
214 with STATE.lock:
215 return self._json(200, {
216 "ok": True,
217 "events": len(STATE.events),
218 "published": len(STATE.published),
219 "inbox": len(STATE.inbox),
220 "conv_seq": STATE.conv_seq,
221 })
222 if path == "/__publishes":
223 with STATE.lock:
224 return self._json(200, {"ok": True, "published": list(STATE.published)})
225 if path == "/__inbox":
226 with STATE.lock:
227 return self._json(200, {"ok": True, "inbox": list(STATE.inbox)})
228 if path == "/__events":
229 with STATE.lock:
230 return self._json(200, {"ok": True, "events": list(STATE.events)})
231
232 # ---- mock node API ----
233 if path == "/conversation":
234 if not self._authed():
235 return self._json(401, {"error": "unauthorized"})
236 after = int(q.get("after", "-1") or -1)
237 limit = int(q.get("limit", "100") or 100)
238 return self._json(200, STATE.conversation(after, limit))
239 if path == "/plugins":
240 return self._json(200, {"ok": True, "count": 0, "plugins": []})
241
242 # ---- mock ntfy subscribe ----
243 m = TOPIC_RE.match(path)
244 if m:
245 topic = path[1:-len("/" + m.group(1))]
246 topic = topic.lstrip("/")
247 since = int(q.get("since", "0") or 0)
248 poll = q.get("poll") in ("1", "true")
249 recs = STATE.since(topic, since)
250 self.send_response(200)
251 self.send_header("Content-Type", "application/x-ndjson; charset=utf-8")
252 self.send_header("Transfer-Encoding", "chunked")
253 self.end_headers()
254 try:
255 self._send_chunk(b'{"event":"open","topic":"%s","time":%d}\n'
256 % (topic.encode(), int(time.time())))
257 for r in recs:
258 self._send_chunk((json.dumps(r) + "\n").encode())
259 if poll:
260 self._send_chunk(b"")
261 self.wfile.write(b"0\r\n\r\n")
262 self.wfile.flush()
263 return
264 # live stream: keepalives + any record that arrives later
265 seen = {r["id"] for r in recs}
266 last_keep = time.time()
267 while True:
268 time.sleep(0.2)
269 now = time.time()
270 for r in STATE.since(topic, since):
271 if r["id"] in seen:
272 continue
273 seen.add(r["id"])
274 self._send_chunk((json.dumps(r) + "\n").encode())
275 if now - last_keep > 1.0:
276 last_keep = now
277 self._send_chunk(b"### keepalive\n")
278 except (BrokenPipeError, ConnectionResetError):
279 return
280 return
281
282 return self._json(404, {"code": 404, "error": "not found"})
283
284 # ---------------- POST ----------------------------------------------
285 def do_POST(self):
286 path = self.path.split("?")[0]
287 q = {}
288 if "?" in self.path:
289 for kv in self.path.split("?", 1)[1].split("&"):
290 if "=" in kv:
291 k, v = kv.split("=", 1)
292 q[k] = v
293 else:
294 q[kv] = ""
295
296 # ---- control API ----
297 if path == "/__inject":
298 body = self._body()
299 try:
300 d = json.loads(body.decode() or "{}")
301 except Exception:
302 return self._json(400, {"ok": False, "error": "bad json"})
303 rec = STATE.add_message(
304 d.get("topic", "test-in"),
305 d.get("message", "hello"),
306 title=d.get("title"),
307 priority=d.get("priority"),
308 tags=d.get("tags"),
309 user=d.get("user"),
310 source_id=d.get("source-id"),
311 extra=d.get("extra"),
312 )
313 return self._json(200, {"ok": True, "id": rec["id"]})
314
315 if path == "/__reply":
316 d = json.loads(self._body().decode() or "{}")
317 text = d.get("content", "reply")
318 seq = STATE.append_assistant_event(text)
319 return self._json(200, {"ok": True, "seq": seq})
320
321 if path == "/__reset":
322 with STATE.lock:
323 STATE.events = []
324 STATE.published = []
325 STATE.inbox = []
326 shutil.rmtree(os.path.join(STATE.root, "sessions"), ignore_errors=True)
327 STATE.conv_seq = 0
328 return self._json(200, {"ok": True})
329
330 if path == "/__config":
331 d = json.loads(self._body().decode() or "{}")
332 if "password" in d:
333 STATE.password = d["password"] or ""
334 if "session" in d:
335 STATE.session = d["session"]
336 return self._json(200, {"ok": True})
337
338 # ---- mock node inbox ----
339 if path == "/inbox":
340 if not self._authed():
341 return self._json(401, {"error": "unauthorized"})
342 sid = q.get("id") or q.get("session") or ""
343 body = self._body()
344 try:
345 d = json.loads(body.decode() or "{}")
346 text = d.get("text") or d.get("content") or d.get("message") or ""
347 except Exception:
348 text = body.decode("utf-8", "replace")
349 if not sid:
350 return self._json(400, {"error": "valid id parameter is required"})
351 with STATE.lock:
352 STATE.inbox.append({"id": sid, "text": text,
353 "mode": d.get("mode") if isinstance(d, dict) else None,
354 "at": int(time.time())})
355 STATE.append_user_event(text)
356 return self._json(200, {"ok": True, "queued": True, "id": sid})
357
358 # ---- mock ntfy publish ----
359 if PUBLISH_RE.match(path):
360 topic = path.lstrip("/")
361 body = self._body()
362 hdrs = {k.lower(): v for k, v in self.headers.items()}
363 tags = hdrs.get("tags")
364 tags_l = [t.strip() for t in (tags or "").split(",") if t.strip()]
365 rec = {
366 "id": STATE.new_id(),
367 "time": int(time.time()),
368 "expires": int(time.time()) + 43200,
369 "event": "message",
370 "topic": topic,
371 "message": body.decode("utf-8", "replace"),
372 }
373 title = hdrs.get("title") or hdrs.get("x-title")
374 if title:
375 rec["title"] = title
376 prio = hdrs.get("priority") or hdrs.get("x-priority")
377 if prio:
378 try:
379 rec["priority"] = int(prio)
380 except ValueError:
381 pass
382 if tags_l:
383 rec["tags"] = tags_l
384 if hdrs.get("x-markdown") or hdrs.get("markdown"):
385 rec["content_type"] = "text/markdown"
386 if hdrs.get("click") or hdrs.get("x-click"):
387 rec["click"] = hdrs.get("click") or hdrs.get("x-click")
388 auth = hdrs.get("authorization", "")
389 rec["_authorization"] = auth
390 rec["_x_source_id"] = hdrs.get("x-source-id", "")
391 rec["_user_header"] = hdrs.get("user", "")
392
393 # auth simulation: when a token is expected, require it
394 if STATE.password and topic.endswith("-auth"):
395 if not auth.startswith("Bearer "):
396 return self._json(401, {"code": 40101, "http": 401,
397 "error": "unauthorized"})
398 with STATE.lock:
399 STATE.published.append(rec)
400 STATE.events.append({k: v for k, v in rec.items()
401 if not k.startswith("_")})
402 out = {k: v for k, v in rec.items() if not k.startswith("_")}
403 return self._json(200, out)
404
405 return self._json(404, {"code": 404, "error": "not found"})
406class Server(ThreadingHTTPServer):
407 daemon_threads = True
408 allow_reuse_address = True
409
410 def handle_error(self, request, client_address):
411 # A client that aborts the handshake (which is exactly what a
412 # failing-closed TLS client does when it refuses our self-signed
413 # leaf) lands here as an SSLError. It is a result, not a crash.
414 return
415
416
417def serve_tls(port, backend_cert_dir, bind="127.0.0.1"):
418 """Same handler over TLS.
419
420 The leaf is self-signed for 127.0.0.1, so the plugin's bundled root store
421 never trusts it: it can only be accepted through an explicit SPKI pin,
422 and only rejected (never silently downgraded) without one. That is the
423 property the pinning tests assert. ThreadingHTTPServer wraps the listener,
424 so every accepted connection gets its own SSL socket and its own thread --
425 the long-lived NDJSON stream never shares a record buffer with a handshake.
426
427 `bind` lets the suite stand a second front on another loopback address with
428 the SAME certificate. Reaching that leaf at an address outside its only IP
429 SAN is how the hostname-mismatch rule gets tested without DNS: this
430 container has no /etc/hosts, so a name would only exercise the resolver
431 error path and prove nothing about verification.
432 """
433 os.makedirs(backend_cert_dir, exist_ok=True)
434 key = os.path.join(backend_cert_dir, "mock-key.pem")
435 crt = os.path.join(backend_cert_dir, "mock-cert.pem")
436 if not (os.path.exists(key) and os.path.exists(crt)):
437 subprocess.run(
438 ["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
439 "-keyout", key, "-out", crt, "-days", "2",
440 "-subj", "/CN=127.0.0.1/O=SCORPIOX BOT test",
441 "-addext", "subjectAltName=IP:127.0.0.1"],
442 check=True, capture_output=True)
443 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
444 ctx.load_cert_chain(crt, key)
445 srv = Server((bind, port), Handler)
446 srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
447 threading.Thread(target=srv.serve_forever, kwargs={"poll_interval": 0.2},
448 daemon=True).start()
449
450
451def main():
452 import argparse
453 global STATE
454 ap = argparse.ArgumentParser()
455 ap.add_argument("--port", type=int, default=18199)
456 ap.add_argument("--root", default="/tmp/sx-ntfy-mock")
457 ap.add_argument("--tls-port", type=int, default=0,
458 help="also serve HTTPS on this port with a self-signed leaf")
459 ap.add_argument("--tls-mismatch-port", type=int, default=0,
460 help="a second HTTPS front on 127.0.0.2 with the SAME "
461 "127.0.0.1-only leaf, i.e. a real hostname mismatch")
462 args = ap.parse_args()
463
464 os.makedirs(args.root, exist_ok=True)
465 STATE = State(args.root)
466 if args.tls_port:
467 serve_tls(args.tls_port, os.path.join(args.root, "tls"))
468 if args.tls_mismatch_port:
469 serve_tls(args.tls_mismatch_port, os.path.join(args.root, "tls"),
470 bind="127.0.0.2")
471 srv = Server(("127.0.0.1", args.port), Handler)
472 print("mockd listening on 127.0.0.1:%d root=%s%s%s" %
473 (args.port, args.root,
474 " tls=127.0.0.1:%d" % args.tls_port if args.tls_port else "",
475 " tls-mismatch=127.0.0.2:%d" % args.tls_mismatch_port
476 if args.tls_mismatch_port else ""),
477 flush=True)
478 try:
479 srv.serve_forever()
480 except KeyboardInterrupt:
481 pass
482
483
484if __name__ == "__main__":
485 main()