| 1 | #!/usr/bin/env python3 |
| 2 | """tests/mockd.py - the throwaway server for the plugin_fetch offline suite. |
| 3 | |
| 4 | One process, one family of loopback listeners, deterministic fixtures, and |
| 5 | nothing but the Python 3 standard library. Everything binds 127.0.0.1, and the |
| 6 | suite reaches it only through the plugin's explicit test-only private-address |
| 7 | allowance (FETCH_ALLOW_PRIVATE / the policy toggle). |
| 8 | |
| 9 | python3 tests/mockd.py http <port> |
| 10 | python3 tests/mockd.py https <port> <cert.pem> <key.pem> |
| 11 | |
| 12 | and the ready line "READY <mode> <port>" lands on stdout so the runner can |
| 13 | wait for it. |
| 14 | |
| 15 | Routes (GET, POST and HEAD all answer the same way): |
| 16 | |
| 17 | /article 200 text/html - the big fixture: headings h1..h6, links |
| 18 | (absolute, relative, query), nested lists, fenced code, |
| 19 | inline code, blockquote, table, image, hr, entities |
| 20 | (named, decimal, hex), and the boilerplate that must be |
| 21 | stripped: script, style, noscript, svg, nav, aside, header, |
| 22 | form, footer, plus a <head> that must vanish. |
| 23 | /title 200 text/html - <title> differs from <h1> (notice vs heading) |
| 24 | /plain 200 text/plain - "plain text body" (cannot be simplified) |
| 25 | /md 200 text/markdown - returned verbatim, no notice |
| 26 | /noctype 200, no Content-Type at all, body opens "<!DOCTYPE html" |
| 27 | (sniffed as HTML) |
| 28 | /noctype-text 200, no Content-Type, plain body (not sniffed as HTML) |
| 29 | /json 200 application/json |
| 30 | /big 200 text/html - 400 deterministic paragraphs (pagination) |
| 31 | /long 200 text/plain - 200000 'x' characters (chunk truncation) |
| 32 | /chunked 200 text/html, Transfer-Encoding: chunked (the article) |
| 33 | /gzip 200 text/html, Content-Encoding: gzip (only decoded when the |
| 34 | plugin was built with HAVE_ZLIB; otherwise it must refuse) |
| 35 | /noclen 200 text/plain, no Content-Length, Connection: close |
| 36 | /headonly 200 with Content-Length larger than the read cap (must be |
| 37 | refused without reading the body) |
| 38 | /r1 -> /r2 -> /article 2-hop redirect chain (302 then 301) |
| 39 | /rel 302 -> "relative" (relative Location, no leading slash) |
| 40 | /relative 200 text/html |
| 41 | /loop 302 -> /loop (redirect loop -> hop cap) |
| 42 | /selfloop 302 -> absolute self URL (loop with absolute Location) |
| 43 | /privatehop 302 -> http://127.0.0.1:<port>/plain (hop to a denied IP) |
| 44 | /badtarget 302 -> an absolute URL with a bogus scheme |
| 45 | /404 /403 /500 error pages |
| 46 | /slow sleeps 25 s then 200 (read deadline path) |
| 47 | /echo 200 application/json with the request headers we care about |
| 48 | (User-Agent, Accept-Encoding, Host) so the request shape can |
| 49 | be asserted |
| 50 | |
| 51 | HTTPS mode wraps the same routes in TLS 1.2+ with a self-signed certificate, |
| 52 | so the plugin must refuse it with no trust anchors and accept it when |
| 53 | FETCH_TLS_CA_FILE points at the matching PEM. |
| 54 | """ |
| 55 | import gzip |
| 56 | import http.server |
| 57 | import json |
| 58 | import ssl |
| 59 | import sys |
| 60 | import time |
| 61 | |
| 62 | HTML = """<!DOCTYPE html> |
| 63 | <html lang="en"> |
| 64 | <head> |
| 65 | <meta charset="utf-8"> |
| 66 | <title>Widget & Gadget \u2014 Docs</title> |
| 67 | <meta property="og:title" content="Widgets and Gadgets"> |
| 68 | <script>var tracked = "SHOULD_NOT_APPEAR_script";</script> |
| 69 | <style>.x{color:red;content:"SHOULD_NOT_APPEAR_style";}</style> |
| 70 | <noscript>SHOULD_NOT_APPEAR_noscript</noscript> |
| 71 | <svg><text>SHOULD_NOT_APPEAR_svg</text></svg> |
| 72 | <meta name="description" content="SHOULD_NOT_APPEAR_meta"> |
| 73 | </head> |
| 74 | <body> |
| 75 | <nav><a href="/nav1">SHOULD_NOT_APPEAR_nav</a></nav> |
| 76 | <aside>SHOULD_NOT_APPEAR_aside</aside> |
| 77 | <header><h1>Widgets and Gadgets</h1></header> |
| 78 | <form><button type="submit">SHOULD_NOT_APPEAR_form</button></form> |
| 79 | <h2>Installation</h2> |
| 80 | <p>Run <code>make install</code> & then <strong>restart</strong> the |
| 81 | <em>service</em>. Prices start at 5 USD — half is 1/2 <3> & 75%.</p> |
| 82 | <h3>Steps</h3> |
| 83 | <ul> |
| 84 | <li>First <a href="/a/b?x=1&y=2">relative link</a></li> |
| 85 | <li>Second |
| 86 | <ul><li>nested item</li></ul> |
| 87 | </li> |
| 88 | <li>Third</li> |
| 89 | </ul> |
| 90 | <ol><li>one</li><li>two</li><li>three</li></ol> |
| 91 | <h4>Fourth</h4><h5>Fifth</h5><h6>Sixth</h6> |
| 92 | <pre><code>int main(void) { |
| 93 | return 0; |
| 94 | } |
| 95 | </code></pre> |
| 96 | <blockquote>Quoted text |
| 97 | second line</blockquote> |
| 98 | <table><tr><th>Name</th><th>Value</th></tr><tr><td>a</td><td>1</td></tr></table> |
| 99 | <img src="/img/logo.png" alt="Logo"> |
| 100 | <hr> |
| 101 | <p>Entities: © 2026 •café — ✓ AB</p> |
| 102 | <p><a href="https://elsewhere.example/doc">external</a> and |
| 103 | <a>hrefless</a></p> |
| 104 | <footer>SHOULD_NOT_APPEAR_footer</footer> |
| 105 | <!-- SHOULD_NOT_APPEAR_comment --> |
| 106 | </body> |
| 107 | </html> |
| 108 | """ |
| 109 | |
| 110 | HTML_TITLE = """<!DOCTYPE html><html><head><title>TITLE_IS_HERE</title></head> |
| 111 | <body><h1>H1_IS_DIFFERENT</h1><p>body text under the heading</p></body></html> |
| 112 | """ |
| 113 | |
| 114 | RELATIVE_OK = "<html><body><h1>relative ok</h1><p>reached /relative</p></body></html>" |
| 115 | NOT_FOUND = "<html><body>gone</body></html>" |
| 116 | |
| 117 | |
| 118 | class H(http.server.BaseHTTPRequestHandler): |
| 119 | protocol_version = "HTTP/1.1" |
| 120 | |
| 121 | def log_message(self, *a): |
| 122 | pass |
| 123 | |
| 124 | def _send(self, code, ctype, body, extra=None): |
| 125 | if isinstance(body, str): |
| 126 | body = body.encode("utf-8") |
| 127 | self.send_response(code) |
| 128 | if ctype: |
| 129 | self.send_header("Content-Type", ctype) |
| 130 | for k, v in (extra or {}).items(): |
| 131 | self.send_header(k, v) |
| 132 | self.send_header("Content-Length", str(len(body))) |
| 133 | self.end_headers() |
| 134 | if self.command != "HEAD": |
| 135 | self.wfile.write(body) |
| 136 | |
| 137 | def _redirect(self, loc): |
| 138 | self.send_response(302) |
| 139 | self.send_header("Location", loc) |
| 140 | self.send_header("Content-Length", "0") |
| 141 | self.end_headers() |
| 142 | |
| 143 | def _base(self): |
| 144 | return "http://%s" % self.headers.get("Host", "127.0.0.1") |
| 145 | |
| 146 | def do_GET(self): |
| 147 | p = self.path.split("?")[0] |
| 148 | port = self.server.server_address[1] |
| 149 | |
| 150 | if p in ("/", "/article"): |
| 151 | self._send(200, "text/html; charset=utf-8", HTML) |
| 152 | elif p == "/title": |
| 153 | self._send(200, "text/html; charset=utf-8", HTML_TITLE) |
| 154 | elif p == "/plain": |
| 155 | self._send(200, "text/plain; charset=utf-8", "plain text body") |
| 156 | elif p == "/md": |
| 157 | self._send(200, "text/markdown; charset=utf-8", "# MD body\n\ntext stays as-is") |
| 158 | elif p == "/noctype": |
| 159 | self._send(200, None, "<!DOCTYPE html><html><body><h1>sniffed</h1><p>as html</p></body></html>") |
| 160 | elif p == "/noctype-text": |
| 161 | self._send(200, None, "just some text with no declared type") |
| 162 | elif p == "/json": |
| 163 | self._send(200, "application/json", json.dumps({"hello": "world"})) |
| 164 | elif p == "/big": |
| 165 | rows = ["<!DOCTYPE html><html><body><h1>Big Page</h1>"] |
| 166 | for i in range(400): |
| 167 | rows.append("<p>Paragraph number %03d with enough filler words " |
| 168 | "to make the document long enough to paginate." % i) |
| 169 | rows.append("</body></html>") |
| 170 | self._send(200, "text/html; charset=utf-8", "\n".join(rows)) |
| 171 | elif p == "/long": |
| 172 | self._send(200, "text/plain; charset=utf-8", "x" * 200000) |
| 173 | elif p == "/chunked": |
| 174 | body = HTML.encode("utf-8") |
| 175 | self.send_response(200) |
| 176 | self.send_header("Content-Type", "text/html; charset=utf-8") |
| 177 | self.send_header("Transfer-Encoding", "chunked") |
| 178 | self.end_headers() |
| 179 | for i in range(0, len(body), 111): |
| 180 | part = body[i:i + 111] |
| 181 | self.wfile.write(("%x\r\n" % len(part)).encode() + part + b"\r\n") |
| 182 | self.wfile.write(b"0\r\n\r\n") |
| 183 | elif p == "/gzip": |
| 184 | raw = HTML.encode("utf-8") |
| 185 | self.send_response(200) |
| 186 | self.send_header("Content-Type", "text/html; charset=utf-8") |
| 187 | self.send_header("Content-Encoding", "gzip") |
| 188 | self.send_header("Content-Length", str(len(gzip.compress(raw)))) |
| 189 | self.end_headers() |
| 190 | self.wfile.write(gzip.compress(raw)) |
| 191 | elif p == "/noclen": |
| 192 | self.send_response(200) |
| 193 | self.send_header("Content-Type", "text/plain; charset=utf-8") |
| 194 | self.send_header("Connection", "close") |
| 195 | self.end_headers() |
| 196 | self.wfile.write(b"no-content-length-body") |
| 197 | self.close_connection = True |
| 198 | elif p == "/headonly": |
| 199 | self.send_response(200) |
| 200 | self.send_header("Content-Type", "text/plain; charset=utf-8") |
| 201 | self.send_header("Content-Length", str(5 * 1024 * 1024 + 7)) |
| 202 | self.end_headers() |
| 203 | elif p == "/r1": |
| 204 | self._redirect("/r2") |
| 205 | elif p == "/r2": |
| 206 | self.send_response(301) |
| 207 | self.send_header("Location", "/article") |
| 208 | self.send_header("Content-Length", "0") |
| 209 | self.end_headers() |
| 210 | elif p == "/rel": |
| 211 | self._redirect("relative") |
| 212 | elif p == "/relative": |
| 213 | self._send(200, "text/html", RELATIVE_OK) |
| 214 | elif p == "/loop": |
| 215 | self._redirect("/loop") |
| 216 | elif p == "/selfloop": |
| 217 | self._redirect(self._base() + "/selfloop") |
| 218 | elif p == "/privatehop": |
| 219 | self._redirect("http://127.0.0.1:%d/plain" % port) |
| 220 | elif p == "/badtarget": |
| 221 | self._redirect("ftp://example.invalid/nope") |
| 222 | elif p == "/404": |
| 223 | self._send(404, "text/html", NOT_FOUND) |
| 224 | elif p == "/403": |
| 225 | self._send(403, "text/html", "<html><body>403 forbidden</body></html>") |
| 226 | elif p == "/500": |
| 227 | self._send(500, "text/html", "<html><body>500 boom</body></html>") |
| 228 | elif p == "/slow": |
| 229 | # longer than the plugin read deadline (FX_READ_MS = 15 s) |
| 230 | time.sleep(25) |
| 231 | self._send(200, "text/plain", "too late") |
| 232 | elif p == "/echo": |
| 233 | self._send(200, "application/json", json.dumps({ |
| 234 | "path": p, |
| 235 | "host": self.headers.get("Host"), |
| 236 | "ua": self.headers.get("User-Agent"), |
| 237 | "accept_encoding": self.headers.get("Accept-Encoding"), |
| 238 | "connection": self.headers.get("Connection"), |
| 239 | "accept": self.headers.get("Accept"), |
| 240 | })) |
| 241 | else: |
| 242 | self._send(404, "text/plain", "not found") |
| 243 | |
| 244 | do_POST = do_GET |
| 245 | do_HEAD = do_GET |
| 246 | |
| 247 | |
| 248 | def main(): |
| 249 | mode = sys.argv[1] |
| 250 | port = int(sys.argv[2]) |
| 251 | srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), H) |
| 252 | if mode == "https": |
| 253 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 254 | ctx.load_cert_chain(sys.argv[3], sys.argv[4]) |
| 255 | try: |
| 256 | ctx.minimum_version = ssl.TLSVersion.TLSv1_2 |
| 257 | except Exception: |
| 258 | pass |
| 259 | srv.socket = ctx.wrap_socket(srv.socket, server_side=True) |
| 260 | sys.stdout.write("READY %s %d\n" % (mode, port)) |
| 261 | sys.stdout.flush() |
| 262 | srv.serve_forever() |
| 263 | |
| 264 | |
| 265 | if __name__ == "__main__": |
| 266 | main() |