#!/usr/bin/env python3 """TSEP TS02 synthetic redirect playground. CC BY 4.0 — Edikka. Python 3, standard library only. Loopback only; no external fetch or files served. Run: python3 ts02-local.py Stop: Ctrl+C. These fictional routes are not a TSEP assessment. """ import argparse from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer class Redirects(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def do_GET(self): routes = { "/chain": (301, "/step"), "/step": (301, "/destination"), "/direct": (301, "/destination"), "/temporary": (302, "/destination"), "/loop-a": (301, "/loop-b"), "/loop-b": (301, "/loop-a"), "/broken": (301, "/missing"), "/relative/start": (301, "../destination"), } status, location = routes.get( self.path, (200 if self.path == "/destination" else 404, None)) if self.path.startswith("/long/"): suffix = self.path.removeprefix("/long/") if suffix.isdecimal() and len(suffix) <= 2: step = int(suffix) status, location = (301, "/long/" + str(step + 1)) if step < 12 else (200, None) body = b"Synthetic destination\n" if status == 200 else b"Synthetic redirect or error\n" self.send_response(status) if location is not None: self.send_header("Location", location) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(body) def log_message(self, *args): pass def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--port", type=int, default=0, help="Loopback port; 0 chooses a free port") args = parser.parse_args() with ThreadingHTTPServer(("127.0.0.1", args.port), Redirects) as server: origin = "http://127.0.0.1:" + str(server.server_port) print("Synthetic local server:", origin, flush=True) for route, expected in [ ("/chain", "2 redirects, HTTP 200, curl exit 0"), ("/direct", "1 redirect, HTTP 200, curl exit 0"), ("/temporary", "1 redirect (302), HTTP 200, curl exit 0"), ("/relative/start", "1 relative redirect, HTTP 200, curl exit 0"), ("/broken", "1 redirect, HTTP 404, curl exit 0 WITHOUT --fail"), ("/loop-a", "with --max-redirs 10: HTTP 301, curl exit 47"), ("/long/0", "with --max-redirs 10: HTTP 301, curl exit 47"), ]: print(origin + route, "=>", expected, flush=True) print("Use the guide's GET command with one of these URLs. Stop with Ctrl+C.", flush=True) try: server.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()