#!/usr/bin/env python3
"""HTTP server for the POC.

Serves a.test (target) and b.test (thirdparty/attacker) content on port 18080.
The thirdparty page is sent with `Content-Security-Policy: frame-src 'none'`
so its grandchild iframe to a.test commits as an error document in b.test's
renderer process.
"""
import http.server
import os
import socketserver
import sys

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18080
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'www')


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=ROOT, **kw)

    def end_headers(self):
        # Attacker-controlled CSP on the thirdparty page: forbid all child
        # frames so the grandchild navigation to a.test fails browser-side
        # with ERR_BLOCKED_BY_CSP.
        if self.path.startswith('/thirdparty.html'):
            self.send_header('Content-Security-Policy', "frame-src 'none'")
        self.send_header('Cache-Control', 'no-store')
        super().end_headers()

    def log_message(self, fmt, *args):
        pass


class ReuseTCPServer(socketserver.TCPServer):
    allow_reuse_address = True


if __name__ == '__main__':
    with ReuseTCPServer(('127.0.0.1', PORT), Handler) as httpd:
        print(f'Serving on http://127.0.0.1:{PORT}/')
        httpd.serve_forever()
