File size: 5,212 Bytes
7f8e190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""Terminate trusted local TLS in front of a Harbor reference process.

The reference application's own launch contract remains HTTP on loopback.  The
Agent-facing Docker service is HTTPS only, so Secure ``__Host-`` cookies have
the same browser semantics as the source site without changing clone code.
"""

from __future__ import annotations

import asyncio
import contextlib
import os
import signal
import ssl
import subprocess
import sys
from pathlib import Path


BUFFER_SIZE = 64 * 1024
STARTUP_TIMEOUT_SECONDS = 30.0


async def _copy_stream(
    reader: asyncio.StreamReader,
    writer: asyncio.StreamWriter,
) -> None:
    while block := await reader.read(BUFFER_SIZE):
        writer.write(block)
        await writer.drain()


async def _forward(
    client_reader: asyncio.StreamReader,
    client_writer: asyncio.StreamWriter,
    *,
    upstream_port: int,
) -> None:
    try:
        upstream_reader, upstream_writer = await asyncio.open_connection(
            "127.0.0.1", upstream_port
        )
    except OSError:
        client_writer.close()
        await client_writer.wait_closed()
        return

    tasks = {
        asyncio.create_task(_copy_stream(client_reader, upstream_writer)),
        asyncio.create_task(_copy_stream(upstream_reader, client_writer)),
    }
    try:
        _done, pending = await asyncio.wait(
            tasks, return_when=asyncio.FIRST_COMPLETED
        )
        for task in pending:
            task.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)
    finally:
        upstream_writer.close()
        client_writer.close()
        with contextlib.suppress(OSError):
            await upstream_writer.wait_closed()
        with contextlib.suppress(OSError):
            await client_writer.wait_closed()


async def _wait_for_upstream(process: subprocess.Popen[bytes], port: int) -> None:
    loop = asyncio.get_running_loop()
    deadline = loop.time() + STARTUP_TIMEOUT_SECONDS
    while loop.time() < deadline:
        return_code = process.poll()
        if return_code is not None:
            raise RuntimeError(
                f"reference process exited before readiness with {return_code}"
            )
        try:
            _reader, writer = await asyncio.open_connection("127.0.0.1", port)
        except OSError:
            await asyncio.sleep(0.1)
            continue
        writer.close()
        await writer.wait_closed()
        return
    raise TimeoutError("reference process did not open its loopback port")


async def _terminate(process: subprocess.Popen[bytes]) -> None:
    if process.poll() is not None:
        return
    process.terminate()
    try:
        await asyncio.wait_for(asyncio.to_thread(process.wait), timeout=10.0)
    except TimeoutError:
        process.kill()
        await asyncio.to_thread(process.wait)


async def _serve(command: list[str]) -> int:
    external_port = int(os.environ.get("PORT", "8080"))
    upstream_port = int(
        os.environ.get("WEBSITEBENCH_REFERENCE_UPSTREAM_PORT", "18080")
    )
    if external_port == upstream_port:
        raise ValueError("reference TLS and upstream ports must differ")

    child_environment = dict(os.environ)
    child_environment["HOST"] = "127.0.0.1"
    child_environment["PORT"] = str(upstream_port)
    process = subprocess.Popen(command, env=child_environment)
    server: asyncio.AbstractServer | None = None
    try:
        await _wait_for_upstream(process, upstream_port)
        tls_root = Path(__file__).resolve().parent
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.minimum_version = ssl.TLSVersion.TLSv1_2
        context.load_cert_chain(
            certfile=tls_root / "reference.crt",
            keyfile=tls_root / "reference.key",
        )
        server = await asyncio.start_server(
            lambda reader, writer: _forward(
                reader, writer, upstream_port=upstream_port
            ),
            "0.0.0.0",
            external_port,
            ssl=context,
        )
        print(
            "WebsiteBench reference HTTPS ready on "
            f"0.0.0.0:{external_port}; upstream=127.0.0.1:{upstream_port}",
            flush=True,
        )

        stop = asyncio.Event()
        loop = asyncio.get_running_loop()
        for signum in (signal.SIGINT, signal.SIGTERM):
            loop.add_signal_handler(signum, stop.set)
        process_wait = asyncio.create_task(asyncio.to_thread(process.wait))
        stop_wait = asyncio.create_task(stop.wait())
        done, pending = await asyncio.wait(
            {process_wait, stop_wait}, return_when=asyncio.FIRST_COMPLETED
        )
        for task in pending:
            task.cancel()
        await asyncio.gather(*pending, return_exceptions=True)
        if process_wait in done:
            return process_wait.result()
        return 0
    finally:
        if server is not None:
            server.close()
            await server.wait_closed()
        await _terminate(process)


def main() -> int:
    if len(sys.argv) < 2:
        raise SystemExit("usage: tls_proxy.py COMMAND [ARG ...]")
    return asyncio.run(_serve(sys.argv[1:]))


if __name__ == "__main__":
    raise SystemExit(main())