#!/usr/bin/env python3
"""HTTPS server for the StorageAccessAPITabHelper credentialless-renewal POC.

Serves top.html / embed.html over HTTPS on port 8443. Chrome is launched with
--host-resolver-rules mapping a.test and b.test to 127.0.0.1, so the same
server handles both origins.
"""
import http.server
import os
import ssl
import subprocess
import sys
import tempfile

PORT = 8443
ROOT = os.path.dirname(os.path.abspath(__file__))


def make_cert():
    d = tempfile.mkdtemp()
    key = os.path.join(d, "key.pem")
    cert = os.path.join(d, "cert.pem")
    subprocess.check_call(
        [
            "openssl", "req", "-x509", "-newkey", "rsa:2048",
            "-keyout", key, "-out", cert, "-days", "1", "-nodes",
            "-subj", "/CN=poc",
        ],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    return key, cert


def main():
    os.chdir(ROOT)
    key, cert = make_cert()
    handler = http.server.SimpleHTTPRequestHandler
    httpd = http.server.HTTPServer(("0.0.0.0", PORT), handler)
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(cert, key)
    httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
    sys.stderr.write(f"[server] HTTPS serving {ROOT} on 0.0.0.0:{PORT}\n")
    sys.stderr.flush()
    httpd.serve_forever()


if __name__ == "__main__":
    main()
