#!/usr/bin/env python3
"""Real lighttpd + synthetic HTTP/FastCGI services; no production or real secrets."""
import http.client
import json
import os
from pathlib import Path
import shutil
import socket
import socketserver
import struct
import subprocess
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

ROOT = Path(__file__).resolve().parents[1]
LIGHTTPD = os.environ.get('LIGHTTPD', shutil.which('lighttpd') or 'lighttpd')
hits = []


class Upstream(BaseHTTPRequestHandler):
    def do_GET(self):
        hits.append((self.path, dict(self.headers)))
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Set-Cookie', 'upstream=must-not-reach-browser')
        self.end_headers()
        self.wfile.write(json.dumps({'name': 'Synthetic device'}).encode())

    def log_message(self, *args):
        pass


def exact(conn, size):
    data = b''
    while len(data) < size:
        chunk = conn.recv(size - len(data))
        if not chunk:
            raise EOFError()
        data += chunk
    return data


def record(kind, rid, body=b''):
    return struct.pack('!BBHHBB', 1, kind, rid, len(body), 0, 0) + body


class Authorizer(socketserver.BaseRequestHandler):
    def handle(self):
        params = b''
        while True:
            _, kind, rid, size, padding, _ = struct.unpack('!BBHHBB', exact(self.request, 8))
            body = exact(self.request, size)
            exact(self.request, padding)
            if kind == 4:
                if body:
                    params += body
                    continue
                # Decode FastCGI name/value pairs, including 4-byte lengths.
                values = {}
                pos = 0
                def length():
                    nonlocal pos
                    value = params[pos]
                    if value & 128:
                        value = struct.unpack('!I', params[pos:pos + 4])[0] & 0x7fffffff
                        pos += 4
                    else:
                        pos += 1
                    return value
                while pos < len(params):
                    n, v = length(), length()
                    name = params[pos:pos + n].decode()
                    pos += n
                    values[name] = params[pos:pos + v].decode()
                    pos += v
                allowed = values.get('HTTP_COOKIE') == 'session=allowed'
                output = (b'Status: 200\r\nVariable-REMOTE_USER: synthetic\r\n\r\n' if allowed
                          else b'Status: 403\r\nContent-Type: text/plain\r\n\r\nDenied')
                self.request.sendall(record(6, rid, output) + record(6, rid)
                                     + record(3, rid, b'\0' * 8))
                return


with tempfile.TemporaryDirectory(prefix='superpulse-proxy-') as directory:
    tmp = Path(directory)
    upstream = ThreadingHTTPServer(('127.0.0.1', 0), Upstream)
    auth = socketserver.ThreadingUnixStreamServer(str(tmp / 'auth.sock'), Authorizer)
    for server in (upstream, auth):
        threading.Thread(target=server.serve_forever, daemon=True).start()
    with socket.socket() as probe:
        probe.bind(('127.0.0.1', 0))
        port = probe.getsockname()[1]
    secret = tmp / 'snipeit.conf'
    secret.write_text('var.superpulse.snipeit-token = "synthetic-not-a-secret"\n')
    secret.chmod(0o600)
    # Only substitute deployment addresses; exercise the actual shipped policy.
    snippet = (ROOT / 'deploy/superpulse-proxy.conf').read_text()
    snippet = snippet.replace('/etc/superpulse/snipeit.conf', str(secret))
    snippet = snippet.replace('"port" => 81', f'"port" => {upstream.server_port}')
    (tmp / 'policy.conf').write_text(snippet)
    config = tmp / 'lighttpd.conf'
    config.write_text(f'''
server.document-root = "{tmp}"
server.bind = "127.0.0.1"
server.port = {port}
server.errorlog = "{tmp}/error.log"
server.modules = ( "mod_access", "mod_fastcgi", "mod_setenv", "mod_proxy" )
$HTTP["host"] == "logs.saikrupagas.com" {{
    fastcgi.server = ( "/" => (( "socket" => "{tmp}/auth.sock",
        "check-local" => "disable", "mode" => "authorizer" )) )
    proxy.server = ( "" => (( "host" => "127.0.0.1", "port" => {upstream.server_port} )) )
    include "{tmp}/policy.conf"
}}
''')
    command = [LIGHTTPD]
    if os.environ.get('LIGHTTPD_MODULES'):
        command += ['-m', os.environ['LIGHTTPD_MODULES']]
    subprocess.run(command + ['-tt', '-f', str(config)], check=True)
    with (tmp / 'process.log').open('w+') as log:
        process = subprocess.Popen(command + ['-D', '-f', str(config)], stdout=log, stderr=log)
        try:
            for _ in range(100):
                if process.poll() is not None:
                    raise RuntimeError((tmp / 'error.log').read_text())
                try:
                    with socket.create_connection(('127.0.0.1', port), timeout=.1):
                        break
                except OSError:
                    time.sleep(.05)
            else:
                raise RuntimeError('lighttpd startup timeout')

            def request(path, method='GET', authorized=True, host='logs.saikrupagas.com'):
                conn = http.client.HTTPConnection('127.0.0.1', port, timeout=5)
                headers = {'Host': host, 'Authorization': 'Bearer attacker-value'}
                if authorized:
                    headers['Cookie'] = 'session=allowed'
                conn.request(method, path, headers=headers)
                response = conn.getresponse()
                result = response.status, dict(response.getheaders()), response.read()
                conn.close()
                return result

            status, headers, body = request('/api/devices/TEST_1-2.3')
            assert status == 200, (status, body)
            path, received = hits[-1]
            assert path == '/api/v1/hardware/bytag/TEST_1-2.3', path
            assert received['Host'] == 'equipment.saikrupagas.com', received
            assert received['Authorization'] == 'Bearer synthetic-not-a-secret'
            assert headers['Cache-Control'] == 'no-store', headers
            assert not any(k.lower() == 'set-cookie' for k in headers), headers
            assert b'synthetic-not-a-secret' not in body

            count = len(hits)
            for path, method, allowed in [
                ('/api/devices/TEST', 'GET', False),
                ('/api/devices/TEST', 'POST', True),
                ('/api/devices/TEST', 'HEAD', True),
                ('/api/devices/TEST?search=anything', 'GET', True),
                ('/api/devices', 'GET', True),
                ('/api/devices/', 'GET', True),
                ('/api/devices/TEST/extra', 'GET', True),
                ('/api/devices/.hidden', 'GET', True),
                ('/.env.php', 'GET', True),
                ('/logs.php?id=TEST', 'GET', True),
                ('/deploy/superpulse-proxy.conf', 'GET', True),
            ]:
                status, _, _ = request(path, method, allowed)
                assert status in (400, 403, 405), (path, method, status)
                assert len(hits) == count, (path, 'unexpected upstream request')
            request('/index.html')
            assert hits[-1][0] == '/index.html'
            assert hits[-1][1]['Host'] == 'logs.saikrupagas.com'
            assert hits[-1][1]['Authorization'] == 'Bearer attacker-value'
            assert request('/api/devices/TEST', host='unrelated.example')[0] == 404
            secret.unlink()
            assert subprocess.run(command + ['-tt', '-f', str(config)],
                                  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode != 0
            print('PASS: auth gate, fixed route/host, token replacement, method/query restrictions, '
                  'private paths, no-store, cookie suppression, vhost isolation, missing-secret failure')
        finally:
            process.terminate()
            process.wait(timeout=5)
            upstream.shutdown()
            auth.shutdown()
