| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import ssl |
| 4 |
import typing |
| 5 |
|
| 6 |
import httpx |
| 7 |
import trio |
| 8 |
from hypercorn.typing import ( |
| 9 |
ASGIReceiveCallable, |
| 10 |
ASGISendCallable, |
| 11 |
HTTPResponseBodyEvent, |
| 12 |
HTTPResponseStartEvent, |
| 13 |
HTTPScope, |
| 14 |
Scope, |
| 15 |
) |
| 16 |
|
| 17 |
|
| 18 |
async def _read_body(receive: ASGIReceiveCallable) -> bytes: |
| 19 |
body = bytearray() |
| 20 |
body_consumed = False |
| 21 |
while not body_consumed: |
| 22 |
event = await receive() |
| 23 |
if event["type"] == "http.request": |
| 24 |
body.extend(event["body"]) |
| 25 |
body_consumed = not event["more_body"] |
| 26 |
else: |
| 27 |
raise ValueError(event["type"]) |
| 28 |
return bytes(body) |
| 29 |
|
| 30 |
|
| 31 |
class ProxyApp: |
| 32 |
def __init__(self, upstream_ca_certs: str | None = None): |
| 33 |
self.ssl_context = None |
| 34 |
if upstream_ca_certs: |
| 35 |
self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) |
| 36 |
self.ssl_context.load_verify_locations(cafile=upstream_ca_certs) |
| 37 |
|
| 38 |
async def __call__( |
| 39 |
self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable |
| 40 |
) -> None: |
| 41 |
assert scope["type"] == "http" |
| 42 |
if scope["method"] in ["GET", "POST"]: |
| 43 |
await self.absolute_uri(scope, receive, send) |
| 44 |
elif scope["method"] == "CONNECT": |
| 45 |
await self.connect(scope, send) |
| 46 |
else: |
| 47 |
raise ValueError(scope["method"]) |
| 48 |
|
| 49 |
async def absolute_uri( |
| 50 |
self, |
| 51 |
scope: HTTPScope, |
| 52 |
receive: ASGIReceiveCallable, |
| 53 |
send: ASGISendCallable, |
| 54 |
) -> None: |
| 55 |
async with httpx.AsyncClient(verify=self.ssl_context or True) as client: |
| 56 |
client_response = await client.request( |
| 57 |
method=scope["method"], |
| 58 |
url=scope["path"], |
| 59 |
params=scope["query_string"].decode(), |
| 60 |
headers=list(scope["headers"]), |
| 61 |
content=await _read_body(receive), |
| 62 |
) |
| 63 |
|
| 64 |
headers = [] |
| 65 |
for header in ( |
| 66 |
"Date", |
| 67 |
"Cache-Control", |
| 68 |
"Server", |
| 69 |
"Content-Type", |
| 70 |
"Location", |
| 71 |
): |
| 72 |
v = client_response.headers.get(header) |
| 73 |
if v: |
| 74 |
headers.append((header.encode(), v.encode())) |
| 75 |
headers.append((b"Content-Length", str(len(client_response.content)).encode())) |
| 76 |
|
| 77 |
await send( |
| 78 |
HTTPResponseStartEvent( |
| 79 |
type="http.response.start", |
| 80 |
status=client_response.status_code, |
| 81 |
headers=headers, |
| 82 |
) |
| 83 |
) |
| 84 |
await send( |
| 85 |
HTTPResponseBodyEvent( |
| 86 |
type="http.response.body", |
| 87 |
body=client_response.content, |
| 88 |
more_body=False, |
| 89 |
) |
| 90 |
) |
| 91 |
|
| 92 |
async def connect(self, scope: HTTPScope, send: ASGISendCallable) -> None: |
| 93 |
async def start_forward( |
| 94 |
reader: trio.SocketStream, writer: trio.SocketStream |
| 95 |
) -> None: |
| 96 |
while True: |
| 97 |
try: |
| 98 |
data = await reader.receive_some(4096) |
| 99 |
except trio.ClosedResourceError: |
| 100 |
break |
| 101 |
if not data: |
| 102 |
break |
| 103 |
await writer.send_all(data) |
| 104 |
await writer.aclose() |
| 105 |
|
| 106 |
host, port = scope["path"].split(":") |
| 107 |
async with await trio.open_tcp_stream(host, int(port)) as upstream: |
| 108 |
await send({"type": "http.response.start", "status": 200, "headers": []}) |
| 109 |
await send({"type": "http.response.body", "body": b"", "more_body": True}) |
| 110 |
|
| 111 |
client = typing.cast(trio.SocketStream, scope["extensions"]["_transport"]) |
| 112 |
|
| 113 |
async with trio.open_nursery(strict_exception_groups=True) as nursery: |
| 114 |
nursery.start_soon(start_forward, client, upstream) |
| 115 |
nursery.start_soon(start_forward, upstream, client) |