| 1 | #!/usr/bin/env python3 |
| 2 | """tests/mockrecv.py - a recording HTTP receiver for the webhook suite. |
| 3 | |
| 4 | It is deliberately not a "returns 200" stub. It writes one JSON object per |
| 5 | request to a log file, capturing the method, path, query string and EVERY |
| 6 | header it received, plus the raw body. That is what makes it possible to assert |
| 7 | the thing that actually matters: that the plugin sent the request the operator |
| 8 | configured - right method, right path, right custom headers, right |
| 9 | HMAC signature over the right bytes - rather than merely that something came |
| 10 | back. |
| 11 | |
| 12 | Modes are selected by the path: |
| 13 | |
| 14 | POST /hook -> 200 {"ok":true} (the normal case) |
| 15 | POST /echo -> 200 with the body echoed back |
| 16 | POST /status/418 -> 418 with a short body |
| 17 | POST /slow -> 200 after --delay seconds |
| 18 | POST /chunked -> 200, chunked transfer encoding |
| 19 | POST /redirect -> 302 Location: /hook |
| 20 | POST /big -> 200 with a body larger than the plugin's preview cap |
| 21 | |
| 22 | Usage: |
| 23 | python3 tests/mockrecv.py --port 0 --log /tmp/recv.jsonl [--delay 1] |
| 24 | Prints "PORT <n>" on stdout as soon as it is listening. |
| 25 | """ |
| 26 | |
| 27 | import argparse |
| 28 | import base64 |
| 29 | import json |
| 30 | import os |
| 31 | import sys |
| 32 | import threading |
| 33 | import time |
| 34 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 35 | |
| 36 | BIG = 200 * 1024 |
| 37 | |
| 38 | |
| 39 | class Handler(BaseHTTPRequestHandler): |
| 40 | protocol_version = "HTTP/1.1" |
| 41 | log_path = None |
| 42 | delay = 0.0 |
| 43 | lock = threading.Lock() |
| 44 | |
| 45 | def log_message(self, fmt, *args): |
| 46 | pass |
| 47 | |
| 48 | def _record(self, body): |
| 49 | """Append the request as one JSON line. Every header, verbatim.""" |
| 50 | if not self.log_path: |
| 51 | return |
| 52 | headers = {k: v for k, v in self.headers.items()} |
| 53 | # Preserve duplicates (rare, but a duplicate header is exactly what a |
| 54 | # signature bug looks like). |
| 55 | raw = [] |
| 56 | for k, v in self.headers.items(): |
| 57 | raw.append([k, v]) |
| 58 | entry = { |
| 59 | "method": self.command, |
| 60 | "path": self.path, |
| 61 | "headers": headers, |
| 62 | "header_list": raw, |
| 63 | "body": body.decode("utf-8", "replace"), |
| 64 | "body_b64": base64.b64encode(body).decode(), |
| 65 | "body_len": len(body), |
| 66 | "at": time.time(), |
| 67 | } |
| 68 | with Handler.lock: |
| 69 | with open(self.log_path, "a", encoding="utf-8") as f: |
| 70 | f.write(json.dumps(entry) + "\n") |
| 71 | |
| 72 | def _route(self, body): |
| 73 | path = self.path.split("?")[0] |
| 74 | if path == "/slow": |
| 75 | time.sleep(Handler.delay) |
| 76 | return 200, b'{"ok":true,"slow":true}' |
| 77 | if path == "/echo": |
| 78 | return 200, body |
| 79 | if path.startswith("/status/"): |
| 80 | try: |
| 81 | code = int(path.rsplit("/", 1)[1]) |
| 82 | except ValueError: |
| 83 | code = 500 |
| 84 | return code, b'{"ok":false,"error":"requested"}' |
| 85 | if path == "/big": |
| 86 | return 200, b"x" * BIG |
| 87 | return 200, b'{"ok":true}' |
| 88 | |
| 89 | def _handle(self): |
| 90 | try: |
| 91 | n = int(self.headers.get("Content-Length") or 0) |
| 92 | except ValueError: |
| 93 | n = 0 |
| 94 | body = self.rfile.read(n) if n > 0 else b"" |
| 95 | self._record(body) |
| 96 | |
| 97 | path = self.path.split("?")[0] |
| 98 | if path == "/redirect": |
| 99 | self.send_response(302) |
| 100 | self.send_header("Location", "/hook") |
| 101 | self.send_header("Content-Length", "0") |
| 102 | self.end_headers() |
| 103 | return |
| 104 | |
| 105 | if path == "/chunked": |
| 106 | self.send_response(200) |
| 107 | self.send_header("Content-Type", "application/json") |
| 108 | self.send_header("Transfer-Encoding", "chunked") |
| 109 | self.end_headers() |
| 110 | for piece in (b'{"chunked":', b"true", b'}'): |
| 111 | self.wfile.write(b"%x\r\n" % len(piece) + piece + b"\r\n") |
| 112 | self.wfile.write(b"0\r\n\r\n") |
| 113 | return |
| 114 | |
| 115 | code, payload = self._route(body) |
| 116 | self.send_response(code) |
| 117 | self.send_header("Content-Type", "application/json") |
| 118 | self.send_header("Content-Length", str(len(payload))) |
| 119 | self.end_headers() |
| 120 | if self.command != "HEAD": |
| 121 | self.wfile.write(payload) |
| 122 | |
| 123 | do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = _handle |
| 124 | |
| 125 | |
| 126 | def main(): |
| 127 | ap = argparse.ArgumentParser() |
| 128 | ap.add_argument("--port", type=int, default=0) |
| 129 | ap.add_argument("--log", required=True) |
| 130 | ap.add_argument("--delay", type=float, default=1.0) |
| 131 | args = ap.parse_args() |
| 132 | |
| 133 | Handler.log_path = args.log |
| 134 | Handler.delay = args.delay |
| 135 | open(args.log, "w", encoding="utf-8").close() |
| 136 | |
| 137 | srv = ThreadingHTTPServer(("127.0.0.1", args.port), Handler) |
| 138 | print("PORT %d" % srv.server_address[1], flush=True) |
| 139 | try: |
| 140 | srv.serve_forever() |
| 141 | except KeyboardInterrupt: |
| 142 | pass |
| 143 | return 0 |
| 144 | |
| 145 | |
| 146 | if __name__ == "__main__": |
| 147 | sys.exit(main()) |