#!/usr/bin/env python3
"""HTTP server for the cross-NetworkContext NetLog leak POC.

Serves poc.html and a /secret endpoint that the page fetches with a cookie and
an Authorization header. Those requests are issued by the *renderer* and travel
through the user's *profile* NetworkContext — a completely different
NetworkContext from the one brokered to the sandboxed Mirroring utility.

If the utility's NetLogExporter (started on its own NetworkContext) can see
these cookies / auth headers, the cross-context leak is proven.
"""
import http.server
import socketserver
import sys

PORT = 8765


class Handler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):  # noqa: N802
        if self.path.startswith("/secret"):
            body = b'{"ok": true, "marker": "PROFILE_CONTEXT_RESPONSE"}'
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            # The browser stores this cookie in the *profile* cookie jar and
            # sends it back on subsequent /secret requests.
            self.send_header(
                "Set-Cookie",
                "session=SECRET_PROFILE_COOKIE_9f3d; Path=/; SameSite=Lax",
            )
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            self.wfile.write(body)
            return
        return super().do_GET()

    def log_message(self, fmt, *args):  # noqa: N802
        sys.stderr.write("[server] " + (fmt % args) + "\n")


if __name__ == "__main__":
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(("127.0.0.1", PORT), Handler) as httpd:
        sys.stderr.write(f"[server] listening on http://127.0.0.1:{PORT}\n")
        httpd.serve_forever()
