#!/usr/bin/env python3 """tests/mockrecv.py - a recording HTTP receiver for the webhook suite. It is deliberately not a "returns 200" stub. It writes one JSON object per request to a log file, capturing the method, path, query string and EVERY header it received, plus the raw body. That is what makes it possible to assert the thing that actually matters: that the plugin sent the request the operator configured - right method, right path, right custom headers, right HMAC signature over the right bytes - rather than merely that something came back. Modes are selected by the path: POST /hook -> 200 {"ok":true} (the normal case) POST /echo -> 200 with the body echoed back POST /status/418 -> 418 with a short body POST /slow -> 200 after --delay seconds POST /chunked -> 200, chunked transfer encoding POST /redirect -> 302 Location: /hook POST /big -> 200 with a body larger than the plugin's preview cap Usage: python3 tests/mockrecv.py --port 0 --log /tmp/recv.jsonl [--delay 1] Prints "PORT " on stdout as soon as it is listening. """ import argparse import base64 import json import os import sys import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer BIG = 200 * 1024 class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" log_path = None delay = 0.0 lock = threading.Lock() def log_message(self, fmt, *args): pass def _record(self, body): """Append the request as one JSON line. Every header, verbatim.""" if not self.log_path: return headers = {k: v for k, v in self.headers.items()} # Preserve duplicates (rare, but a duplicate header is exactly what a # signature bug looks like). raw = [] for k, v in self.headers.items(): raw.append([k, v]) entry = { "method": self.command, "path": self.path, "headers": headers, "header_list": raw, "body": body.decode("utf-8", "replace"), "body_b64": base64.b64encode(body).decode(), "body_len": len(body), "at": time.time(), } with Handler.lock: with open(self.log_path, "a", encoding="utf-8") as f: f.write(json.dumps(entry) + "\n") def _route(self, body): path = self.path.split("?")[0] if path == "/slow": time.sleep(Handler.delay) return 200, b'{"ok":true,"slow":true}' if path == "/echo": return 200, body if path.startswith("/status/"): try: code = int(path.rsplit("/", 1)[1]) except ValueError: code = 500 return code, b'{"ok":false,"error":"requested"}' if path == "/big": return 200, b"x" * BIG return 200, b'{"ok":true}' def _handle(self): try: n = int(self.headers.get("Content-Length") or 0) except ValueError: n = 0 body = self.rfile.read(n) if n > 0 else b"" self._record(body) path = self.path.split("?")[0] if path == "/redirect": self.send_response(302) self.send_header("Location", "/hook") self.send_header("Content-Length", "0") self.end_headers() return if path == "/chunked": self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Transfer-Encoding", "chunked") self.end_headers() for piece in (b'{"chunked":', b"true", b'}'): self.wfile.write(b"%x\r\n" % len(piece) + piece + b"\r\n") self.wfile.write(b"0\r\n\r\n") return code, payload = self._route(body) self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(payload))) self.end_headers() if self.command != "HEAD": self.wfile.write(payload) do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = _handle def main(): ap = argparse.ArgumentParser() ap.add_argument("--port", type=int, default=0) ap.add_argument("--log", required=True) ap.add_argument("--delay", type=float, default=1.0) args = ap.parse_args() Handler.log_path = args.log Handler.delay = args.delay open(args.log, "w", encoding="utf-8").close() srv = ThreadingHTTPServer(("127.0.0.1", args.port), Handler) print("PORT %d" % srv.server_address[1], flush=True) try: srv.serve_forever() except KeyboardInterrupt: pass return 0 if __name__ == "__main__": sys.exit(main())