From ac587e33a7d8f55f4a430452cbbe695913f4ead9 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Mon, 23 Nov 2026 23:12:12 +0000 Subject: [PATCH 1/6] [PROD-871] The CLI can carry the linked proxy gateway's streams to public destinations Co-authored-by: Cursor --- src/gumloop/linked_proxy/__init__.py | 1 + src/gumloop/linked_proxy/destinations.py | 171 +++++++++++++++++ src/gumloop/linked_proxy/frames.py | 92 +++++++++ src/gumloop/linked_proxy/tunnel.py | 228 +++++++++++++++++++++++ tests/linked_proxy/__init__.py | 1 + tests/linked_proxy/fixtures/frames.json | 24 +++ tests/linked_proxy/test_destinations.py | 67 +++++++ tests/linked_proxy/test_frames.py | 39 ++++ tests/linked_proxy/test_tunnel.py | 160 ++++++++++++++++ 9 files changed, 783 insertions(+) create mode 100644 src/gumloop/linked_proxy/__init__.py create mode 100644 src/gumloop/linked_proxy/destinations.py create mode 100644 src/gumloop/linked_proxy/frames.py create mode 100644 src/gumloop/linked_proxy/tunnel.py create mode 100644 tests/linked_proxy/__init__.py create mode 100644 tests/linked_proxy/fixtures/frames.json create mode 100644 tests/linked_proxy/test_destinations.py create mode 100644 tests/linked_proxy/test_frames.py create mode 100644 tests/linked_proxy/test_tunnel.py diff --git a/src/gumloop/linked_proxy/__init__.py b/src/gumloop/linked_proxy/__init__.py new file mode 100644 index 0000000..9d48db4 --- /dev/null +++ b/src/gumloop/linked_proxy/__init__.py @@ -0,0 +1 @@ +from __future__ import annotations diff --git a/src/gumloop/linked_proxy/destinations.py b/src/gumloop/linked_proxy/destinations.py new file mode 100644 index 0000000..05bf059 --- /dev/null +++ b/src/gumloop/linked_proxy/destinations.py @@ -0,0 +1,171 @@ +"""Which destinations the tunnel may connect to. These are the linked proxy gateway's +own checks, applied again here because names resolve on this machine, whose +network may route ranges the gateway can't see.""" + +from __future__ import annotations + +import asyncio +import enum +import ipaddress +import re +import socket +import string +from dataclasses import dataclass + +ALLOWED_PORTS = frozenset({80, 443}) +DIAL_TIMEOUT_SECONDS = 10.0 + +# Special-use IPv4 ranges (RFC 6890) that the linked proxy gateway also refuses. +_DENIED_NETWORKS = tuple( + ipaddress.IPv4Network(network) + for network in ( + "10.0.0.0/8", + "100.64.0.0/10", + "127.0.0.0/8", + "169.254.0.0/16", + "172.16.0.0/12", + "192.168.0.0/16", + "0.0.0.0/8", + "192.0.0.0/24", + "192.0.2.0/24", + "198.18.0.0/15", + "198.51.100.0/24", + "203.0.113.0/24", + "240.0.0.0/4", + ) +) +_PORT = re.compile(r"[0-9]+") +_LABEL_CHARACTERS = frozenset(string.ascii_lowercase + string.digits + "-_") + + +class Refusal(str, enum.Enum): + PORT = "port" + ADDRESS = "address" + HOST = "host" + + +class RefusedError(Exception): + """A destination the tunnel may not reach. It never carries the destination.""" + + def __init__(self, reason: Refusal) -> None: + super().__init__(f"destination refused: {reason.value}") + self.reason = reason + + +@dataclass(frozen=True) +class Target: + """A lower-case hostname, or a public IPv4 literal, on port 80 or 443.""" + + host: str + port: int + + +def parse_target(hostport: str) -> Target: + host, separator, port_text = hostport.rpartition(":") + if host.startswith("[") and host.endswith("]"): + host = host[1:-1] + elif ":" in host: + raise RefusedError(Refusal.HOST) + if not separator or not host: + raise RefusedError(Refusal.HOST) + if not _PORT.fullmatch(port_text) or int(port_text) not in ALLOWED_PORTS: + raise RefusedError(Refusal.PORT) + port = int(port_text) + + try: + address = ipaddress.ip_address(host) + except ValueError: + address = None + if address is not None: + if not is_public_ipv4(address): + raise RefusedError(Refusal.ADDRESS) + return Target(host=str(_unmap(address)), port=port) + + host = host.lower().removesuffix(".") + if not _is_hostname(host): + raise RefusedError(Refusal.HOST) + + return Target(host=host, port=port) + + +def is_public_ipv4(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: + address = _unmap(address) + if not isinstance(address, ipaddress.IPv4Address): + return False + if address.is_multicast or address == ipaddress.IPv4Address("255.255.255.255"): + return False + + return not any(address in network for network in _DENIED_NETWORKS) + + +def _unmap(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> ipaddress.IPv4Address | ipaddress.IPv6Address: + if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None: + return address.ipv4_mapped + return address + + +def _is_hostname(host: str) -> bool: + """DNS names only. A last label of digits is refused because some resolvers + read names like "2130706433" or "127.1" as addresses.""" + if not host or len(host) > 253: + return False + labels = host.split(".") + for label in labels: + if not label or len(label) > 63 or label[0] == "-" or label[-1] == "-": + return False + if not set(label) <= _LABEL_CHARACTERS: + return False + + return labels[-1].strip(string.digits) != "" + + +async def connect(target: Target) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]: + """Resolves the target here, refuses it if any address is not public, then + tries the addresses in the resolver's order.""" + addresses = await _resolve(target) + errors: list[OSError] = [] + for address in addresses: + try: + reader, writer = await asyncio.wait_for(asyncio.open_connection(address, target.port), DIAL_TIMEOUT_SECONDS) + except (OSError, asyncio.TimeoutError) as error: + errors.append(error if isinstance(error, OSError) else TimeoutError("dial timed out")) + continue + if _reaches_this_machine(writer): + writer.close() + raise RefusedError(Refusal.ADDRESS) + return reader, writer + + raise OSError(f"could not connect to any of {len(addresses)} addresses") from (errors[-1] if errors else None) + + +def _reaches_this_machine(writer: asyncio.StreamWriter) -> bool: + """A public address on one of this machine's own interfaces, such as a VPS's, would reach its local services.""" + local = writer.get_extra_info("sockname") + remote = writer.get_extra_info("peername") + return local is not None and remote is not None and local[0] == remote[0] + + +async def _resolve(target: Target) -> list[str]: + try: + literal = ipaddress.ip_address(target.host) + except ValueError: + literal = None + if literal is not None: + candidates = [literal] + else: + infos = await asyncio.get_running_loop().getaddrinfo( + target.host, target.port, family=socket.AF_INET, type=socket.SOCK_STREAM + ) + candidates = [ipaddress.ip_address(info[4][0]) for info in infos] + if not candidates: + raise OSError("no IPv4 addresses for the target") + + addresses: list[str] = [] + for candidate in candidates: + if not is_public_ipv4(candidate): + raise RefusedError(Refusal.ADDRESS) + text = str(_unmap(candidate)) + if text not in addresses: + addresses.append(text) + + return addresses diff --git a/src/gumloop/linked_proxy/frames.py b/src/gumloop/linked_proxy/frames.py new file mode 100644 index 0000000..6d579d6 --- /dev/null +++ b/src/gumloop/linked_proxy/frames.py @@ -0,0 +1,92 @@ +"""The linked proxy gateway's tunnel frames. Each binary WebSocket message is one +frame: a type byte, a big-endian uint32 stream id, then the payload. The +gateway defines the layout; ``tests/linked_proxy/fixtures/frames.json`` is a +byte copy of its fixture.""" + +from __future__ import annotations + +import enum +import struct +from dataclasses import dataclass + +MAX_DATA_LENGTH = 32 * 1024 +# How many bytes each side may send on a new stream before the other grants more. +INITIAL_WINDOW = 256 * 1024 +OPEN_FAIL_DIAL = "dial" + +_HEADER = struct.Struct(">BI") +_WINDOW = struct.Struct(">I") +_MAX_FRAME_LENGTH = _HEADER.size + MAX_DATA_LENGTH +_MAX_TARGET_LENGTH = 253 + len(":65535") +_MAX_REASON_LENGTH = 32 +_MAX_GATEWAY_TOKEN_LENGTH = 1024 + + +class FrameType(enum.IntEnum): + # The gateway asks for a connection to the "host:port" in the payload. Only the gateway opens streams. + OPEN = 1 + OPEN_OK = 2 + # The payload is a refusal ("port", "address", "host") or OPEN_FAIL_DIAL. + OPEN_FAIL = 3 + DATA = 4 + # Ends the stream both ways; the other side sends nothing back. + CLOSE = 5 + # Lets the other side send as many more bytes as the big-endian uint32 payload. + WINDOW = 6 + # A fresh gateway token, sent by the CLI only. It is the only frame on stream 0. + GATEWAY_TOKEN = 7 + + +class ProtocolError(Exception): + """The gateway sent something the tunnel protocol doesn't allow.""" + + +@dataclass(frozen=True) +class Frame: + type: FrameType + stream_id: int + payload: bytes = b"" + + def encode(self) -> bytes: + return _HEADER.pack(self.type, self.stream_id) + self.payload + + @classmethod + def decode(cls, data: bytes) -> Frame: + """Checks the layout only; whether the frame fits its stream is the tunnel's check.""" + if not _HEADER.size <= len(data) <= _MAX_FRAME_LENGTH: + raise ProtocolError(f"a {len(data)}-byte frame") + type_byte, stream_id = _HEADER.unpack_from(data) + payload = data[_HEADER.size :] + if (stream_id == 0) != (type_byte == FrameType.GATEWAY_TOKEN): + raise ProtocolError(f"frame type {type_byte} on stream {stream_id}") + try: + frame_type = FrameType(type_byte) + except ValueError: + raise ProtocolError(f"frame type {type_byte}") from None + + size = len(payload) + valid = { + FrameType.OPEN: 0 < size <= _MAX_TARGET_LENGTH, + FrameType.OPEN_OK: size == 0, + FrameType.OPEN_FAIL: 0 < size <= _MAX_REASON_LENGTH, + FrameType.DATA: size > 0, + FrameType.CLOSE: size == 0, + FrameType.WINDOW: size == _WINDOW.size and _WINDOW.unpack(payload)[0] > 0, + FrameType.GATEWAY_TOKEN: 0 < size <= _MAX_GATEWAY_TOKEN_LENGTH, + }[frame_type] + if not valid: + raise ProtocolError(f"frame type {type_byte} with a {size}-byte payload") + + return cls(type=frame_type, stream_id=stream_id, payload=payload) + + @classmethod + def window(cls, stream_id: int, increment: int) -> Frame: + return cls(type=FrameType.WINDOW, stream_id=stream_id, payload=_WINDOW.pack(increment)) + + @classmethod + def gateway_token(cls, token: str) -> Frame: + return cls(type=FrameType.GATEWAY_TOKEN, stream_id=0, payload=token.encode()) + + @property + def window_increment(self) -> int: + return _WINDOW.unpack(self.payload)[0] diff --git a/src/gumloop/linked_proxy/tunnel.py b/src/gumloop/linked_proxy/tunnel.py new file mode 100644 index 0000000..565158d --- /dev/null +++ b/src/gumloop/linked_proxy/tunnel.py @@ -0,0 +1,228 @@ +"""Serves the streams the linked proxy gateway opens over the CLI's WebSocket: each +one becomes a connection from this machine to an allowed destination.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Awaitable +from collections.abc import Callable +from typing import Protocol + +from gumloop.linked_proxy.destinations import RefusedError +from gumloop.linked_proxy.destinations import Target +from gumloop.linked_proxy.destinations import connect +from gumloop.linked_proxy.destinations import parse_target +from gumloop.linked_proxy.frames import INITIAL_WINDOW +from gumloop.linked_proxy.frames import MAX_DATA_LENGTH +from gumloop.linked_proxy.frames import OPEN_FAIL_DIAL +from gumloop.linked_proxy.frames import Frame +from gumloop.linked_proxy.frames import FrameType +from gumloop.linked_proxy.frames import ProtocolError + +# Bounds the credit the gateway may grant, so a stream's window stays sane. +_MAX_SEND_WINDOW = 64 * 1024 * 1024 + +Dial = Callable[[Target], Awaitable[tuple[asyncio.StreamReader, asyncio.StreamWriter]]] + + +class Connection(Protocol): + """The WebSocket to the gateway. ``websockets``' client connection is one.""" + + async def send(self, message: bytes) -> None: ... + + async def recv(self) -> bytes | str: ... + + +class Tunnel: + def __init__( + self, + connection: Connection, + *, + dial: Dial = connect, + on_open: Callable[[Target], None] | None = None, + ) -> None: + self._connection = connection + self._dial = dial + self._on_open = on_open + self._send_lock = asyncio.Lock() + self._streams: dict[int, _Stream] = {} + self._last_id = 0 + self._tasks: set[asyncio.Task[None]] = set() + + async def run(self) -> None: + """Serves streams until ``recv`` raises: the WebSocket closed, or the + gateway broke the protocol (``ProtocolError``). Every stream ends with it.""" + try: + while True: + message = await self._connection.recv() + if isinstance(message, str): + raise ProtocolError("a text message") + self._deliver(Frame.decode(message)) + finally: + for stream in list(self._streams.values()): + stream.shut() + for task in self._tasks: + task.cancel() + + def _deliver(self, frame: Frame) -> None: + if frame.type is FrameType.OPEN: + # Stream ids only grow, so a late frame can't reach a newer stream. + if frame.stream_id <= self._last_id: + raise ProtocolError(f"stream {frame.stream_id} opened again") + self._last_id = frame.stream_id + stream = _Stream(self, frame.stream_id) + self._streams[frame.stream_id] = stream + stream.start(self._spawn(stream.open(frame.payload.decode("utf-8", errors="replace")))) + return + if frame.type in (FrameType.OPEN_OK, FrameType.OPEN_FAIL, FrameType.GATEWAY_TOKEN): + raise ProtocolError(f"the gateway sent {frame.type.name}") + + stream = self._streams.get(frame.stream_id) + if stream is None: + if frame.stream_id <= self._last_id: + # The stream already ended here; the gateway's frames crossed its CLOSE. + return + raise ProtocolError(f"a frame for stream {frame.stream_id}, which was never opened") + if frame.type is FrameType.DATA: + stream.receive(frame.payload) + elif frame.type is FrameType.WINDOW: + stream.grant(frame.window_increment) + elif frame.type is FrameType.CLOSE: + stream.shut() + + async def send_gateway_token(self, token: str) -> None: + """The gateway checks it right away and uses it for its rechecks from then on.""" + await self._send(Frame.gateway_token(token)) + + def _spawn(self, coroutine: Awaitable[None]) -> asyncio.Task[None]: + task = asyncio.ensure_future(coroutine) + self._tasks.add(task) + task.add_done_callback(self._finished) + return task + + def _finished(self, task: asyncio.Task[None]) -> None: + self._tasks.discard(task) + # A stream fails when the WebSocket does; run() reports that once. + if not task.cancelled(): + task.exception() + + async def _send(self, frame: Frame) -> None: + async with self._send_lock: + await self._connection.send(frame.encode()) + + def _forget(self, stream_id: int) -> None: + self._streams.pop(stream_id, None) + + +class _Stream: + """One connection to a destination. Its frames arrive on the tunnel's read + loop; its own tasks dial and relay.""" + + def __init__(self, tunnel: Tunnel, stream_id: int) -> None: + self._tunnel = tunnel + self.id = stream_id + self._tasks: list[asyncio.Task[None]] = [] + self._writer: asyncio.StreamWriter | None = None + self._open = False + self._ended = False + self._send_window = INITIAL_WINDOW + self._can_send = asyncio.Event() + self._can_send.set() + self._recv_window = INITIAL_WINDOW + self._incoming: asyncio.Queue[bytes] = asyncio.Queue() + + def start(self, task: asyncio.Task[None]) -> None: + self._tasks.append(task) + + async def open(self, hostport: str) -> None: + try: + target = parse_target(hostport) + if self._tunnel._on_open is not None: + self._tunnel._on_open(target) + reader, writer = await self._tunnel._dial(target) + except RefusedError as error: + await self._fail(error.reason.value) + return + except OSError: + await self._fail(OPEN_FAIL_DIAL) + return + if self._ended: + writer.close() + return + + self._writer = writer + self._open = True + await self._tunnel._send(Frame(type=FrameType.OPEN_OK, stream_id=self.id)) + self._tasks.append(self._tunnel._spawn(self._upload(reader))) + self._tasks.append(self._tunnel._spawn(self._download(writer))) + + async def _fail(self, reason: str) -> None: + self._ended = True + self._tunnel._forget(self.id) + await self._tunnel._send(Frame(type=FrameType.OPEN_FAIL, stream_id=self.id, payload=reason.encode())) + + def receive(self, data: bytes) -> None: + if not self._open: + raise ProtocolError(f"data before OPEN_OK on stream {self.id}") + if len(data) > self._recv_window: + raise ProtocolError(f"data past the window on stream {self.id}") + self._recv_window -= len(data) + self._incoming.put_nowait(data) + + def grant(self, increment: int) -> None: + self._send_window += increment + if self._send_window > _MAX_SEND_WINDOW: + raise ProtocolError(f"a window past {_MAX_SEND_WINDOW} bytes on stream {self.id}") + self._can_send.set() + + async def _upload(self, reader: asyncio.StreamReader) -> None: + """Destination to gateway, within the gateway's window.""" + try: + while True: + await self._can_send.wait() + data = await reader.read(min(self._send_window, MAX_DATA_LENGTH)) + if not data: + break + self._send_window -= len(data) + if self._send_window == 0: + self._can_send.clear() + await self._tunnel._send(Frame(type=FrameType.DATA, stream_id=self.id, payload=data)) + except OSError: + pass + await self._close() + + async def _download(self, writer: asyncio.StreamWriter) -> None: + """Gateway to destination. Credit goes back once half the window is written.""" + unacked = 0 + try: + while True: + data = await self._incoming.get() + writer.write(data) + await writer.drain() + unacked += len(data) + if unacked >= INITIAL_WINDOW // 2: + self._recv_window += unacked + await self._tunnel._send(Frame.window(self.id, unacked)) + unacked = 0 + except OSError: + await self._close() + + async def _close(self) -> None: + """Ends the stream from this side and tells the gateway.""" + if self._ended: + return + self.shut() + await self._tunnel._send(Frame(type=FrameType.CLOSE, stream_id=self.id)) + + def shut(self) -> None: + """Ends the stream without telling the gateway: it closed the stream, or the tunnel ended.""" + if self._ended: + return + self._ended = True + self._tunnel._forget(self.id) + current = asyncio.current_task() + for task in self._tasks: + if task is not current: + task.cancel() + if self._writer is not None: + self._writer.close() diff --git a/tests/linked_proxy/__init__.py b/tests/linked_proxy/__init__.py new file mode 100644 index 0000000..bf77bdb --- /dev/null +++ b/tests/linked_proxy/__init__.py @@ -0,0 +1 @@ +"""Browser proxy tunnel tests.""" diff --git a/tests/linked_proxy/fixtures/frames.json b/tests/linked_proxy/fixtures/frames.json new file mode 100644 index 0000000..bfe55e3 --- /dev/null +++ b/tests/linked_proxy/fixtures/frames.json @@ -0,0 +1,24 @@ +{ + "valid": [ + {"name": "open", "frame": "01000000016578616d706c652e636f6d3a343433", "type": 1, "stream_id": 1, "payload": "6578616d706c652e636f6d3a343433"}, + {"name": "open_ok", "frame": "0200000001", "type": 2, "stream_id": 1, "payload": ""}, + {"name": "open_fail", "frame": "030000000261646472657373", "type": 3, "stream_id": 2, "payload": "61646472657373"}, + {"name": "data", "frame": "04000000016869", "type": 4, "stream_id": 1, "payload": "6869"}, + {"name": "data on a big-endian stream id", "frame": "040102030400ff", "type": 4, "stream_id": 16909060, "payload": "00ff"}, + {"name": "close", "frame": "0500000001", "type": 5, "stream_id": 1, "payload": ""}, + {"name": "window", "frame": "060000000100040000", "type": 6, "stream_id": 1, "payload": "00040000"}, + {"name": "gateway_token", "frame": "0700000000746f6b", "type": 7, "stream_id": 0, "payload": "746f6b"} + ], + "invalid": [ + {"name": "shorter than the header", "frame": "01000000"}, + {"name": "unknown type", "frame": "0800000001"}, + {"name": "stream 0", "frame": "04000000006869"}, + {"name": "gateway token on stream 1", "frame": "0700000001746f6b"}, + {"name": "gateway token with no payload", "frame": "0700000000"}, + {"name": "open with no target", "frame": "0100000001"}, + {"name": "open_ok with a payload", "frame": "020000000100"}, + {"name": "data with no payload", "frame": "0400000001"}, + {"name": "window of two bytes", "frame": "06000000010004"}, + {"name": "window of zero", "frame": "060000000100000000"} + ] +} diff --git a/tests/linked_proxy/test_destinations.py b/tests/linked_proxy/test_destinations.py new file mode 100644 index 0000000..d406a92 --- /dev/null +++ b/tests/linked_proxy/test_destinations.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +import asyncio + +import pytest + +from gumloop.linked_proxy.destinations import Refusal +from gumloop.linked_proxy.destinations import RefusedError +from gumloop.linked_proxy.destinations import Target +from gumloop.linked_proxy.destinations import connect +from gumloop.linked_proxy.destinations import parse_target + + +@pytest.mark.parametrize( + ("hostport", "reason"), + [ + ("example.com:22", Refusal.PORT), + ("10.0.0.1:443", Refusal.ADDRESS), + ("[::1]:443", Refusal.ADDRESS), + ("127.1:443", Refusal.HOST), + ("example.com", Refusal.HOST), + ], +) +def test_parse_target_refuses_what_the_gateway_refuses(hostport: str, reason: Refusal) -> None: + with pytest.raises(RefusedError) as refused: + parse_target(hostport) + + assert refused.value.reason is reason + + +def test_parse_target_accepts_a_hostname_and_a_public_address() -> None: + assert parse_target("Example.COM.:443") == Target(host="example.com", port=443) + assert parse_target("93.184.215.14:80") == Target(host="93.184.215.14", port=80) + + +def test_connect_refuses_a_name_that_resolves_to_a_private_address() -> None: + with pytest.raises(RefusedError) as refused: + asyncio.run(connect(Target(host="localhost", port=443))) + + assert refused.value.reason is Refusal.ADDRESS + + +class _Writer: + def __init__(self, local: str, remote: str) -> None: + self._addresses = {"sockname": (local, 50000), "peername": (remote, 443)} + self.closed = False + + def get_extra_info(self, name: str) -> tuple[str, int]: + return self._addresses[name] + + def close(self) -> None: + self.closed = True + + +def test_connect_refuses_a_public_address_of_this_machine(monkeypatch) -> None: + writer = _Writer(local="93.184.215.14", remote="93.184.215.14") + + async def open_connection(host: str, port: int) -> tuple[asyncio.StreamReader, _Writer]: + return asyncio.StreamReader(), writer + + monkeypatch.setattr(asyncio, "open_connection", open_connection) + + with pytest.raises(RefusedError) as refused: + asyncio.run(connect(Target(host="93.184.215.14", port=443))) + + assert refused.value.reason is Refusal.ADDRESS + assert writer.closed diff --git a/tests/linked_proxy/test_frames.py b/tests/linked_proxy/test_frames.py new file mode 100644 index 0000000..ad96efa --- /dev/null +++ b/tests/linked_proxy/test_frames.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import pytest + +from gumloop.linked_proxy.frames import Frame +from gumloop.linked_proxy.frames import FrameType +from gumloop.linked_proxy.frames import ProtocolError + +FIXTURE = Path(__file__).parent / "fixtures" / "frames.json" +# The linked proxy gateway pins its own copy of this file by the same hash; change both together. +FIXTURE_SHA256 = "a19bdf1ec020eeab8bbf966c0ee6e4a0eb47748b0d27983ff5b758dcf84489c1" + + +def _fixture() -> dict[str, list[dict[str, str | int]]]: + raw = FIXTURE.read_bytes() + assert hashlib.sha256(raw).hexdigest() == FIXTURE_SHA256 + return json.loads(raw) + + +@pytest.mark.parametrize("case", _fixture()["valid"], ids=lambda case: str(case["name"])) +def test_frames_decode_and_encode_like_the_gateway(case: dict[str, str | int]) -> None: + encoded = bytes.fromhex(str(case["frame"])) + + frame = Frame.decode(encoded) + + assert frame.type is FrameType(case["type"]) + assert frame.stream_id == case["stream_id"] + assert frame.payload == bytes.fromhex(str(case["payload"])) + assert frame.encode() == encoded + + +@pytest.mark.parametrize("case", _fixture()["invalid"], ids=lambda case: str(case["name"])) +def test_frames_the_gateway_refuses_are_refused(case: dict[str, str | int]) -> None: + with pytest.raises(ProtocolError): + Frame.decode(bytes.fromhex(str(case["frame"]))) diff --git a/tests/linked_proxy/test_tunnel.py b/tests/linked_proxy/test_tunnel.py new file mode 100644 index 0000000..44f6832 --- /dev/null +++ b/tests/linked_proxy/test_tunnel.py @@ -0,0 +1,160 @@ +from __future__ import annotations + +import asyncio +import os +from collections.abc import Callable + +import pytest + +from gumloop.linked_proxy.destinations import Target +from gumloop.linked_proxy.frames import INITIAL_WINDOW +from gumloop.linked_proxy.frames import MAX_DATA_LENGTH +from gumloop.linked_proxy.frames import Frame +from gumloop.linked_proxy.frames import FrameType +from gumloop.linked_proxy.frames import ProtocolError +from gumloop.linked_proxy.tunnel import Tunnel + + +class FakeGateway: + """The gateway's end of the WebSocket. Frames pushed here reach the tunnel's + ``recv``; frames the tunnel sends come back from ``next_frame``.""" + + def __init__(self) -> None: + self._inbound: asyncio.Queue[bytes | None] = asyncio.Queue() + self._sent: asyncio.Queue[Frame] = asyncio.Queue() + + async def send(self, message: bytes) -> None: + self._sent.put_nowait(Frame.decode(message)) + + async def recv(self) -> bytes: + message = await self._inbound.get() + if message is None: + raise ConnectionError("the WebSocket closed") + return message + + def push(self, frame: Frame) -> None: + self._inbound.put_nowait(frame.encode()) + + def close(self) -> None: + self._inbound.put_nowait(None) + + async def next_frame(self) -> Frame: + return await asyncio.wait_for(self._sent.get(), 5) + + +async def _echo(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + while data := await reader.read(65536): + writer.write(data) + await writer.drain() + writer.close() + + +async def _open( + gateway: FakeGateway, port: int, *, on_open: Callable[[Target], None] | None = None +) -> asyncio.Task[None]: + """Opens stream 1 to the echo server on port and returns the running tunnel.""" + + async def dial(target: Target) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]: + return await asyncio.open_connection("127.0.0.1", port) + + run = asyncio.ensure_future(Tunnel(gateway, dial=dial, on_open=on_open).run()) + gateway.push(Frame(type=FrameType.OPEN, stream_id=1, payload=b"example.com:443")) + assert (await gateway.next_frame()).type is FrameType.OPEN_OK + + return run + + +@pytest.mark.timeout(10) +def test_tunnel_relays_more_than_a_window_each_way() -> None: + async def scenario() -> None: + server = await asyncio.start_server(_echo, "127.0.0.1", 0) + gateway = FakeGateway() + opened: list[Target] = [] + run = await _open(gateway, server.sockets[0].getsockname()[1], on_open=opened.append) + + sent = os.urandom(4 * INITIAL_WINDOW) + offset, send_window, unacked = 0, INITIAL_WINDOW, 0 + received = bytearray() + while len(received) < len(sent): + while offset < len(sent) and send_window > 0: + chunk = sent[offset : offset + min(MAX_DATA_LENGTH, send_window)] + gateway.push(Frame(type=FrameType.DATA, stream_id=1, payload=chunk)) + offset, send_window = offset + len(chunk), send_window - len(chunk) + frame = await gateway.next_frame() + if frame.type is FrameType.WINDOW: + send_window += frame.window_increment + elif frame.type is FrameType.DATA: + received += frame.payload + unacked += len(frame.payload) + if unacked >= INITIAL_WINDOW // 2: + gateway.push(Frame.window(1, unacked)) + unacked = 0 + + assert bytes(received) == sent + assert opened == [Target(host="example.com", port=443)] + gateway.close() + with pytest.raises(ConnectionError): + await run + server.close() + await server.wait_closed() + + asyncio.run(scenario()) + + +@pytest.mark.timeout(10) +def test_tunnel_refuses_a_private_destination_without_dialing() -> None: + async def scenario() -> None: + dialed: list[Target] = [] + + async def dial(target: Target) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]: + dialed.append(target) + raise AssertionError("a refused destination is never dialed") + + gateway = FakeGateway() + run = asyncio.ensure_future(Tunnel(gateway, dial=dial).run()) + gateway.push(Frame(type=FrameType.OPEN, stream_id=1, payload=b"10.0.0.1:443")) + + assert await gateway.next_frame() == Frame(type=FrameType.OPEN_FAIL, stream_id=1, payload=b"address") + assert dialed == [] + gateway.close() + with pytest.raises(ConnectionError): + await run + + asyncio.run(scenario()) + + +@pytest.mark.timeout(10) +def test_tunnel_ends_when_the_gateway_sends_past_the_window() -> None: + async def scenario() -> None: + server = await asyncio.start_server(_echo, "127.0.0.1", 0) + gateway = FakeGateway() + run = await _open(gateway, server.sockets[0].getsockname()[1]) + + # Pushed without yielding, so the tunnel reads them back to back before granting anything. + for _ in range(INITIAL_WINDOW // MAX_DATA_LENGTH): + gateway.push(Frame(type=FrameType.DATA, stream_id=1, payload=bytes(MAX_DATA_LENGTH))) + gateway.push(Frame(type=FrameType.DATA, stream_id=1, payload=b"\x00")) + + with pytest.raises(ProtocolError): + await run + server.close() + await server.wait_closed() + + asyncio.run(scenario()) + + +@pytest.mark.timeout(10) +def test_tunnel_sends_a_gateway_token_and_ends_when_the_gateway_sends_one() -> None: + async def scenario() -> None: + gateway = FakeGateway() + tunnel = Tunnel(gateway) + run = asyncio.ensure_future(tunnel.run()) + + await tunnel.send_gateway_token("fresh-token") + gateway.push(Frame.gateway_token("from-the-gateway")) + + assert await gateway.next_frame() == Frame.gateway_token("fresh-token") + with pytest.raises(ProtocolError): + await run + + asyncio.run(scenario()) From 77704822d7cd7ee9a34127c6647b04fd9bf9af33 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 00:51:16 +0000 Subject: [PATCH 2/6] [PROD-871] Data the gateway sent before closing a stream still reaches the destination Co-authored-by: Cursor --- src/gumloop/linked_proxy/tunnel.py | 33 +++++++++++++++++++++++++----- tests/linked_proxy/test_tunnel.py | 28 +++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/gumloop/linked_proxy/tunnel.py b/src/gumloop/linked_proxy/tunnel.py index 565158d..9cbe778 100644 --- a/src/gumloop/linked_proxy/tunnel.py +++ b/src/gumloop/linked_proxy/tunnel.py @@ -21,6 +21,8 @@ # Bounds the credit the gateway may grant, so a stream's window stays sane. _MAX_SEND_WINDOW = 64 * 1024 * 1024 +# How long a destination gets to take the data the gateway sent before its CLOSE. +_CLOSE_WRITE_SECONDS = 10.0 Dial = Callable[[Target], Awaitable[tuple[asyncio.StreamReader, asyncio.StreamWriter]]] @@ -88,7 +90,7 @@ def _deliver(self, frame: Frame) -> None: elif frame.type is FrameType.WINDOW: stream.grant(frame.window_increment) elif frame.type is FrameType.CLOSE: - stream.shut() + stream.close_from_gateway() async def send_gateway_token(self, token: str) -> None: """The gateway checks it right away and uses it for its rechecks from then on.""" @@ -123,13 +125,15 @@ def __init__(self, tunnel: Tunnel, stream_id: int) -> None: self.id = stream_id self._tasks: list[asyncio.Task[None]] = [] self._writer: asyncio.StreamWriter | None = None + self._download_task: asyncio.Task[None] | None = None self._open = False self._ended = False self._send_window = INITIAL_WINDOW self._can_send = asyncio.Event() self._can_send.set() self._recv_window = INITIAL_WINDOW - self._incoming: asyncio.Queue[bytes] = asyncio.Queue() + # None marks the gateway's CLOSE. + self._incoming: asyncio.Queue[bytes | None] = asyncio.Queue() def start(self, task: asyncio.Task[None]) -> None: self._tasks.append(task) @@ -154,7 +158,8 @@ async def open(self, hostport: str) -> None: self._open = True await self._tunnel._send(Frame(type=FrameType.OPEN_OK, stream_id=self.id)) self._tasks.append(self._tunnel._spawn(self._upload(reader))) - self._tasks.append(self._tunnel._spawn(self._download(writer))) + self._download_task = self._tunnel._spawn(self._download(writer)) + self._tasks.append(self._download_task) async def _fail(self, reason: str) -> None: self._ended = True @@ -195,8 +200,7 @@ async def _download(self, writer: asyncio.StreamWriter) -> None: """Gateway to destination. Credit goes back once half the window is written.""" unacked = 0 try: - while True: - data = await self._incoming.get() + while (data := await self._incoming.get()) is not None: writer.write(data) await writer.drain() unacked += len(data) @@ -206,6 +210,25 @@ async def _download(self, writer: asyncio.StreamWriter) -> None: unacked = 0 except OSError: await self._close() + finally: + writer.close() + + def close_from_gateway(self) -> None: + """Stops reading from the destination but still writes it what the gateway + sent first, aborting the connection if that takes too long.""" + if self._ended: + return + if self._download_task is None or self._writer is None: + self.shut() + return + self._ended = True + self._tunnel._forget(self.id) + for task in self._tasks: + if task is not self._download_task: + task.cancel() + self._incoming.put_nowait(None) + deadline = asyncio.get_running_loop().call_later(_CLOSE_WRITE_SECONDS, self._writer.transport.abort) + self._download_task.add_done_callback(lambda _task: deadline.cancel()) async def _close(self) -> None: """Ends the stream from this side and tells the gateway.""" diff --git a/tests/linked_proxy/test_tunnel.py b/tests/linked_proxy/test_tunnel.py index 44f6832..931debf 100644 --- a/tests/linked_proxy/test_tunnel.py +++ b/tests/linked_proxy/test_tunnel.py @@ -101,6 +101,34 @@ async def scenario() -> None: asyncio.run(scenario()) +@pytest.mark.timeout(10) +def test_data_the_gateway_sent_before_its_close_still_reaches_the_destination() -> None: + async def scenario() -> None: + received: asyncio.Future[bytes] = asyncio.get_running_loop().create_future() + + async def record(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + received.set_result(await reader.read()) + writer.close() + + server = await asyncio.start_server(record, "127.0.0.1", 0) + gateway = FakeGateway() + run = await _open(gateway, server.sockets[0].getsockname()[1]) + + sent = os.urandom(INITIAL_WINDOW // 2) + for offset in range(0, len(sent), MAX_DATA_LENGTH): + gateway.push(Frame(type=FrameType.DATA, stream_id=1, payload=sent[offset : offset + MAX_DATA_LENGTH])) + gateway.push(Frame(type=FrameType.CLOSE, stream_id=1)) + + assert await asyncio.wait_for(received, 5) == sent + gateway.close() + with pytest.raises(ConnectionError): + await run + server.close() + await server.wait_closed() + + asyncio.run(scenario()) + + @pytest.mark.timeout(10) def test_tunnel_refuses_a_private_destination_without_dialing() -> None: async def scenario() -> None: From 7c17ed619ec16081f03128f1935fdab79b9dd2a8 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 01:27:18 +0000 Subject: [PATCH 3/6] [PROD-871] The CLI reads the gateway's READY frame Co-authored-by: Cursor --- src/gumloop/linked_proxy/frames.py | 13 ++++++++++--- src/gumloop/linked_proxy/tunnel.py | 10 ++++++++++ tests/linked_proxy/fixtures/frames.json | 7 +++++-- tests/linked_proxy/test_frames.py | 2 +- tests/linked_proxy/test_tunnel.py | 17 +++++++++++++++++ 5 files changed, 43 insertions(+), 6 deletions(-) diff --git a/src/gumloop/linked_proxy/frames.py b/src/gumloop/linked_proxy/frames.py index 6d579d6..8b1fbae 100644 --- a/src/gumloop/linked_proxy/frames.py +++ b/src/gumloop/linked_proxy/frames.py @@ -33,8 +33,14 @@ class FrameType(enum.IntEnum): CLOSE = 5 # Lets the other side send as many more bytes as the big-endian uint32 payload. WINDOW = 6 - # A fresh gateway token, sent by the CLI only. It is the only frame on stream 0. + # A fresh gateway token, sent by the CLI only, on stream 0. GATEWAY_TOKEN = 7 + # The gateway accepted the tunnel. Sent once by the gateway, on stream 0, with no payload. + READY = 8 + + +# Only these frame types travel on stream 0, which no connection uses. +_TUNNEL_FRAMES = frozenset({FrameType.GATEWAY_TOKEN, FrameType.READY}) class ProtocolError(Exception): @@ -57,12 +63,12 @@ def decode(cls, data: bytes) -> Frame: raise ProtocolError(f"a {len(data)}-byte frame") type_byte, stream_id = _HEADER.unpack_from(data) payload = data[_HEADER.size :] - if (stream_id == 0) != (type_byte == FrameType.GATEWAY_TOKEN): - raise ProtocolError(f"frame type {type_byte} on stream {stream_id}") try: frame_type = FrameType(type_byte) except ValueError: raise ProtocolError(f"frame type {type_byte}") from None + if (stream_id == 0) != (frame_type in _TUNNEL_FRAMES): + raise ProtocolError(f"frame type {type_byte} on stream {stream_id}") size = len(payload) valid = { @@ -73,6 +79,7 @@ def decode(cls, data: bytes) -> Frame: FrameType.CLOSE: size == 0, FrameType.WINDOW: size == _WINDOW.size and _WINDOW.unpack(payload)[0] > 0, FrameType.GATEWAY_TOKEN: 0 < size <= _MAX_GATEWAY_TOKEN_LENGTH, + FrameType.READY: size == 0, }[frame_type] if not valid: raise ProtocolError(f"frame type {type_byte} with a {size}-byte payload") diff --git a/src/gumloop/linked_proxy/tunnel.py b/src/gumloop/linked_proxy/tunnel.py index 9cbe778..b3225c2 100644 --- a/src/gumloop/linked_proxy/tunnel.py +++ b/src/gumloop/linked_proxy/tunnel.py @@ -42,10 +42,13 @@ def __init__( *, dial: Dial = connect, on_open: Callable[[Target], None] | None = None, + on_ready: Callable[[], None] | None = None, ) -> None: self._connection = connection self._dial = dial self._on_open = on_open + self._on_ready = on_ready + self._ready = False self._send_lock = asyncio.Lock() self._streams: dict[int, _Stream] = {} self._last_id = 0 @@ -67,6 +70,13 @@ async def run(self) -> None: task.cancel() def _deliver(self, frame: Frame) -> None: + if frame.type is FrameType.READY: + if self._ready: + raise ProtocolError("a second READY") + self._ready = True + if self._on_ready is not None: + self._on_ready() + return if frame.type is FrameType.OPEN: # Stream ids only grow, so a late frame can't reach a newer stream. if frame.stream_id <= self._last_id: diff --git a/tests/linked_proxy/fixtures/frames.json b/tests/linked_proxy/fixtures/frames.json index bfe55e3..cd78ae5 100644 --- a/tests/linked_proxy/fixtures/frames.json +++ b/tests/linked_proxy/fixtures/frames.json @@ -7,14 +7,17 @@ {"name": "data on a big-endian stream id", "frame": "040102030400ff", "type": 4, "stream_id": 16909060, "payload": "00ff"}, {"name": "close", "frame": "0500000001", "type": 5, "stream_id": 1, "payload": ""}, {"name": "window", "frame": "060000000100040000", "type": 6, "stream_id": 1, "payload": "00040000"}, - {"name": "gateway_token", "frame": "0700000000746f6b", "type": 7, "stream_id": 0, "payload": "746f6b"} + {"name": "gateway_token", "frame": "0700000000746f6b", "type": 7, "stream_id": 0, "payload": "746f6b"}, + {"name": "ready", "frame": "0800000000", "type": 8, "stream_id": 0, "payload": ""} ], "invalid": [ {"name": "shorter than the header", "frame": "01000000"}, - {"name": "unknown type", "frame": "0800000001"}, + {"name": "unknown type", "frame": "0900000001"}, {"name": "stream 0", "frame": "04000000006869"}, {"name": "gateway token on stream 1", "frame": "0700000001746f6b"}, {"name": "gateway token with no payload", "frame": "0700000000"}, + {"name": "ready on stream 1", "frame": "0800000001"}, + {"name": "ready with a payload", "frame": "080000000000"}, {"name": "open with no target", "frame": "0100000001"}, {"name": "open_ok with a payload", "frame": "020000000100"}, {"name": "data with no payload", "frame": "0400000001"}, diff --git a/tests/linked_proxy/test_frames.py b/tests/linked_proxy/test_frames.py index ad96efa..d87a662 100644 --- a/tests/linked_proxy/test_frames.py +++ b/tests/linked_proxy/test_frames.py @@ -12,7 +12,7 @@ FIXTURE = Path(__file__).parent / "fixtures" / "frames.json" # The linked proxy gateway pins its own copy of this file by the same hash; change both together. -FIXTURE_SHA256 = "a19bdf1ec020eeab8bbf966c0ee6e4a0eb47748b0d27983ff5b758dcf84489c1" +FIXTURE_SHA256 = "9ee8961d2453640ec7c4ab45c3592262ec66fb2be68bad34373012893d63a6e9" def _fixture() -> dict[str, list[dict[str, str | int]]]: diff --git a/tests/linked_proxy/test_tunnel.py b/tests/linked_proxy/test_tunnel.py index 931debf..7bf6510 100644 --- a/tests/linked_proxy/test_tunnel.py +++ b/tests/linked_proxy/test_tunnel.py @@ -186,3 +186,20 @@ async def scenario() -> None: await run asyncio.run(scenario()) + + +@pytest.mark.timeout(10) +def test_tunnel_reports_ready_once_and_ends_on_a_second_ready() -> None: + async def scenario() -> None: + gateway = FakeGateway() + readies: list[None] = [] + run = asyncio.ensure_future(Tunnel(gateway, on_ready=lambda: readies.append(None)).run()) + + gateway.push(Frame(type=FrameType.READY, stream_id=0)) + gateway.push(Frame(type=FrameType.READY, stream_id=0)) + + with pytest.raises(ProtocolError): + await run + assert len(readies) == 1 + + asyncio.run(scenario()) From 2dbc5b2bb648fbadf2548b0c579c313090375427 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 01:27:18 +0000 Subject: [PATCH 4/6] [PROD-871] The CLI refuses Azure's host endpoint as a destination Co-authored-by: Cursor --- src/gumloop/linked_proxy/destinations.py | 2 ++ tests/linked_proxy/test_destinations.py | 1 + 2 files changed, 3 insertions(+) diff --git a/src/gumloop/linked_proxy/destinations.py b/src/gumloop/linked_proxy/destinations.py index 05bf059..e6fa28c 100644 --- a/src/gumloop/linked_proxy/destinations.py +++ b/src/gumloop/linked_proxy/destinations.py @@ -32,6 +32,8 @@ "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", + # Azure's host endpoint, which answers VMs on that public address. + "168.63.129.16/32", ) ) _PORT = re.compile(r"[0-9]+") diff --git a/tests/linked_proxy/test_destinations.py b/tests/linked_proxy/test_destinations.py index d406a92..5e73bdb 100644 --- a/tests/linked_proxy/test_destinations.py +++ b/tests/linked_proxy/test_destinations.py @@ -16,6 +16,7 @@ [ ("example.com:22", Refusal.PORT), ("10.0.0.1:443", Refusal.ADDRESS), + ("168.63.129.16:80", Refusal.ADDRESS), ("[::1]:443", Refusal.ADDRESS), ("127.1:443", Refusal.HOST), ("example.com", Refusal.HOST), From 31604d3ff378fd4959b7d583ef0e9fb1f3580d30 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 01:35:16 +0000 Subject: [PATCH 5/6] [PROD-871] A stream the gateway closed sends it no more window credit Co-authored-by: Cursor --- src/gumloop/linked_proxy/tunnel.py | 3 ++- tests/linked_proxy/test_tunnel.py | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/gumloop/linked_proxy/tunnel.py b/src/gumloop/linked_proxy/tunnel.py index b3225c2..353aa0e 100644 --- a/src/gumloop/linked_proxy/tunnel.py +++ b/src/gumloop/linked_proxy/tunnel.py @@ -214,7 +214,8 @@ async def _download(self, writer: asyncio.StreamWriter) -> None: writer.write(data) await writer.drain() unacked += len(data) - if unacked >= INITIAL_WINDOW // 2: + # After the gateway's CLOSE the stream takes no replies. + if unacked >= INITIAL_WINDOW // 2 and not self._ended: self._recv_window += unacked await self._tunnel._send(Frame.window(self.id, unacked)) unacked = 0 diff --git a/tests/linked_proxy/test_tunnel.py b/tests/linked_proxy/test_tunnel.py index 7bf6510..6805d27 100644 --- a/tests/linked_proxy/test_tunnel.py +++ b/tests/linked_proxy/test_tunnel.py @@ -41,6 +41,12 @@ def close(self) -> None: async def next_frame(self) -> Frame: return await asyncio.wait_for(self._sent.get(), 5) + def unread_frames(self) -> list[Frame]: + frames = [] + while not self._sent.empty(): + frames.append(self._sent.get_nowait()) + return frames + async def _echo(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: while data := await reader.read(65536): @@ -120,6 +126,7 @@ async def record(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> gateway.push(Frame(type=FrameType.CLOSE, stream_id=1)) assert await asyncio.wait_for(received, 5) == sent + assert gateway.unread_frames() == [] gateway.close() with pytest.raises(ConnectionError): await run From b8adfeae6c6a503b23d3b09a946b74ff0cd7f26a Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 05:02:15 +0000 Subject: [PATCH 6/6] [PROD-871] Trim the tunnel tests to the crucial cases Co-authored-by: Cursor --- tests/linked_proxy/helpers.py | 122 +++++++++++++++ tests/linked_proxy/test_destinations.py | 35 ++--- tests/linked_proxy/test_tunnel.py | 191 ++++++------------------ 3 files changed, 184 insertions(+), 164 deletions(-) create mode 100644 tests/linked_proxy/helpers.py diff --git a/tests/linked_proxy/helpers.py b/tests/linked_proxy/helpers.py new file mode 100644 index 0000000..eb59648 --- /dev/null +++ b/tests/linked_proxy/helpers.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +import asyncio +from collections.abc import Callable +from types import ModuleType + +from gumloop.linked_proxy.destinations import Target +from gumloop.linked_proxy.frames import INITIAL_WINDOW +from gumloop.linked_proxy.frames import MAX_DATA_LENGTH +from gumloop.linked_proxy.frames import Frame +from gumloop.linked_proxy.frames import FrameType +from gumloop.linked_proxy.tunnel import Tunnel + + +class FakeGateway: + """The gateway's end of the WebSocket. Frames pushed here reach the tunnel's + ``recv``; frames the tunnel sends come back from ``next_frame``.""" + + def __init__(self) -> None: + self._inbound: asyncio.Queue[bytes | None] = asyncio.Queue() + self._sent: asyncio.Queue[Frame] = asyncio.Queue() + + async def send(self, message: bytes) -> None: + self._sent.put_nowait(Frame.decode(message)) + + async def recv(self) -> bytes: + message = await self._inbound.get() + if message is None: + raise ConnectionError("the WebSocket closed") + return message + + def push(self, frame: Frame) -> None: + self._inbound.put_nowait(frame.encode()) + + def push_data(self, stream_id: int, data: bytes) -> None: + """Pushes data as DATA frames of at most ``MAX_DATA_LENGTH`` bytes, without yielding.""" + for offset in range(0, len(data), MAX_DATA_LENGTH): + self.push(Frame(type=FrameType.DATA, stream_id=stream_id, payload=data[offset : offset + MAX_DATA_LENGTH])) + + def close(self) -> None: + self._inbound.put_nowait(None) + + async def next_frame(self) -> Frame: + return await self._sent.get() + + def unread_frames(self) -> list[Frame]: + frames = [] + while not self._sent.empty(): + frames.append(self._sent.get_nowait()) + return frames + + +async def echo(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + while data := await reader.read(65536): + writer.write(data) + await writer.drain() + writer.close() + + +async def open_stream( + gateway: FakeGateway, port: int, *, on_open: Callable[[Target], None] | None = None +) -> asyncio.Task[None]: + """Opens stream 1 to the server on port and returns the running tunnel.""" + + async def dial(target: Target) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]: + return await asyncio.open_connection("127.0.0.1", port) + + run = asyncio.ensure_future(Tunnel(gateway, dial=dial, on_open=on_open).run()) + gateway.push(Frame(type=FrameType.OPEN, stream_id=1, payload=b"example.com:443")) + opened = await gateway.next_frame() + if opened.type is not FrameType.OPEN_OK: + raise AssertionError(f"stream 1 did not open: {opened}") + return run + + +async def relay_through_stream(gateway: FakeGateway, sent: bytes) -> bytes: + """Sends ``sent`` on stream 1 as the gateway would, within the window the CLI grants, + and returns what comes back, granting window as the gateway does.""" + offset, send_window, unacked = 0, INITIAL_WINDOW, 0 + received = bytearray() + while len(received) < len(sent): + while offset < len(sent) and send_window > 0: + chunk = sent[offset : offset + min(MAX_DATA_LENGTH, send_window)] + gateway.push(Frame(type=FrameType.DATA, stream_id=1, payload=chunk)) + offset, send_window = offset + len(chunk), send_window - len(chunk) + frame = await gateway.next_frame() + if frame.type is FrameType.WINDOW: + send_window += frame.window_increment + elif frame.type is FrameType.DATA: + received += frame.payload + unacked += len(frame.payload) + if unacked >= INITIAL_WINDOW // 2: + gateway.push(Frame.window(1, unacked)) + unacked = 0 + return bytes(received) + + +class RecordingWriter: + def __init__(self, local: str, remote: str) -> None: + self._addresses = {"sockname": (local, 50000), "peername": (remote, 443)} + self.closed = False + + def get_extra_info(self, name: str) -> tuple[str, int]: + return self._addresses[name] + + def close(self) -> None: + self.closed = True + + +class AsyncioDialing(ModuleType): + """Stands in for a module's ``asyncio`` name: every attribute is the real + ``asyncio``'s except ``open_connection``, which hands back ``writer``.""" + + def __init__(self, writer: RecordingWriter) -> None: + super().__init__("asyncio") + self._writer = writer + + def __getattr__(self, name: str) -> object: + return getattr(asyncio, name) + + async def open_connection(self, host: str, port: int) -> tuple[asyncio.StreamReader, RecordingWriter]: + return asyncio.StreamReader(), self._writer diff --git a/tests/linked_proxy/test_destinations.py b/tests/linked_proxy/test_destinations.py index 5e73bdb..6a9cc6d 100644 --- a/tests/linked_proxy/test_destinations.py +++ b/tests/linked_proxy/test_destinations.py @@ -4,11 +4,14 @@ import pytest +from gumloop.linked_proxy import destinations from gumloop.linked_proxy.destinations import Refusal from gumloop.linked_proxy.destinations import RefusedError from gumloop.linked_proxy.destinations import Target from gumloop.linked_proxy.destinations import connect from gumloop.linked_proxy.destinations import parse_target +from tests.linked_proxy.helpers import AsyncioDialing +from tests.linked_proxy.helpers import RecordingWriter @pytest.mark.parametrize( @@ -29,9 +32,15 @@ def test_parse_target_refuses_what_the_gateway_refuses(hostport: str, reason: Re assert refused.value.reason is reason -def test_parse_target_accepts_a_hostname_and_a_public_address() -> None: - assert parse_target("Example.COM.:443") == Target(host="example.com", port=443) - assert parse_target("93.184.215.14:80") == Target(host="93.184.215.14", port=80) +@pytest.mark.parametrize( + ("hostport", "target"), + [ + ("Example.COM.:443", Target(host="example.com", port=443)), + ("93.184.215.14:80", Target(host="93.184.215.14", port=80)), + ], +) +def test_parse_target_accepts_a_hostname_and_a_public_address(hostport: str, target: Target) -> None: + assert parse_target(hostport) == target def test_connect_refuses_a_name_that_resolves_to_a_private_address() -> None: @@ -41,25 +50,9 @@ def test_connect_refuses_a_name_that_resolves_to_a_private_address() -> None: assert refused.value.reason is Refusal.ADDRESS -class _Writer: - def __init__(self, local: str, remote: str) -> None: - self._addresses = {"sockname": (local, 50000), "peername": (remote, 443)} - self.closed = False - - def get_extra_info(self, name: str) -> tuple[str, int]: - return self._addresses[name] - - def close(self) -> None: - self.closed = True - - def test_connect_refuses_a_public_address_of_this_machine(monkeypatch) -> None: - writer = _Writer(local="93.184.215.14", remote="93.184.215.14") - - async def open_connection(host: str, port: int) -> tuple[asyncio.StreamReader, _Writer]: - return asyncio.StreamReader(), writer - - monkeypatch.setattr(asyncio, "open_connection", open_connection) + writer = RecordingWriter(local="93.184.215.14", remote="93.184.215.14") + monkeypatch.setattr(destinations, "asyncio", AsyncioDialing(writer)) with pytest.raises(RefusedError) as refused: asyncio.run(connect(Target(host="93.184.215.14", port=443))) diff --git a/tests/linked_proxy/test_tunnel.py b/tests/linked_proxy/test_tunnel.py index 6805d27..a716035 100644 --- a/tests/linked_proxy/test_tunnel.py +++ b/tests/linked_proxy/test_tunnel.py @@ -2,114 +2,47 @@ import asyncio import os -from collections.abc import Callable import pytest from gumloop.linked_proxy.destinations import Target from gumloop.linked_proxy.frames import INITIAL_WINDOW -from gumloop.linked_proxy.frames import MAX_DATA_LENGTH from gumloop.linked_proxy.frames import Frame from gumloop.linked_proxy.frames import FrameType from gumloop.linked_proxy.frames import ProtocolError from gumloop.linked_proxy.tunnel import Tunnel +from tests.linked_proxy.helpers import FakeGateway +from tests.linked_proxy.helpers import echo +from tests.linked_proxy.helpers import open_stream +from tests.linked_proxy.helpers import relay_through_stream -class FakeGateway: - """The gateway's end of the WebSocket. Frames pushed here reach the tunnel's - ``recv``; frames the tunnel sends come back from ``next_frame``.""" - - def __init__(self) -> None: - self._inbound: asyncio.Queue[bytes | None] = asyncio.Queue() - self._sent: asyncio.Queue[Frame] = asyncio.Queue() - - async def send(self, message: bytes) -> None: - self._sent.put_nowait(Frame.decode(message)) - - async def recv(self) -> bytes: - message = await self._inbound.get() - if message is None: - raise ConnectionError("the WebSocket closed") - return message - - def push(self, frame: Frame) -> None: - self._inbound.put_nowait(frame.encode()) - - def close(self) -> None: - self._inbound.put_nowait(None) - - async def next_frame(self) -> Frame: - return await asyncio.wait_for(self._sent.get(), 5) - - def unread_frames(self) -> list[Frame]: - frames = [] - while not self._sent.empty(): - frames.append(self._sent.get_nowait()) - return frames - - -async def _echo(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: - while data := await reader.read(65536): - writer.write(data) - await writer.drain() - writer.close() - - -async def _open( - gateway: FakeGateway, port: int, *, on_open: Callable[[Target], None] | None = None -) -> asyncio.Task[None]: - """Opens stream 1 to the echo server on port and returns the running tunnel.""" - - async def dial(target: Target) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]: - return await asyncio.open_connection("127.0.0.1", port) - - run = asyncio.ensure_future(Tunnel(gateway, dial=dial, on_open=on_open).run()) - gateway.push(Frame(type=FrameType.OPEN, stream_id=1, payload=b"example.com:443")) - assert (await gateway.next_frame()).type is FrameType.OPEN_OK - - return run - - -@pytest.mark.timeout(10) def test_tunnel_relays_more_than_a_window_each_way() -> None: - async def scenario() -> None: - server = await asyncio.start_server(_echo, "127.0.0.1", 0) + async def scenario() -> tuple[bytes, list[Target]]: + server = await asyncio.start_server(echo, "127.0.0.1", 0) gateway = FakeGateway() opened: list[Target] = [] - run = await _open(gateway, server.sockets[0].getsockname()[1], on_open=opened.append) - - sent = os.urandom(4 * INITIAL_WINDOW) - offset, send_window, unacked = 0, INITIAL_WINDOW, 0 - received = bytearray() - while len(received) < len(sent): - while offset < len(sent) and send_window > 0: - chunk = sent[offset : offset + min(MAX_DATA_LENGTH, send_window)] - gateway.push(Frame(type=FrameType.DATA, stream_id=1, payload=chunk)) - offset, send_window = offset + len(chunk), send_window - len(chunk) - frame = await gateway.next_frame() - if frame.type is FrameType.WINDOW: - send_window += frame.window_increment - elif frame.type is FrameType.DATA: - received += frame.payload - unacked += len(frame.payload) - if unacked >= INITIAL_WINDOW // 2: - gateway.push(Frame.window(1, unacked)) - unacked = 0 - - assert bytes(received) == sent - assert opened == [Target(host="example.com", port=443)] + run = await open_stream(gateway, server.sockets[0].getsockname()[1], on_open=opened.append) + + received = await relay_through_stream(gateway, sent) + gateway.close() with pytest.raises(ConnectionError): await run server.close() await server.wait_closed() + return received, opened + + sent = os.urandom(4 * INITIAL_WINDOW) + + received, opened = asyncio.run(scenario()) - asyncio.run(scenario()) + assert received == sent + assert opened == [Target(host="example.com", port=443)] -@pytest.mark.timeout(10) def test_data_the_gateway_sent_before_its_close_still_reaches_the_destination() -> None: - async def scenario() -> None: + async def scenario() -> tuple[bytes, list[Frame]]: received: asyncio.Future[bytes] = asyncio.get_running_loop().create_future() async def record(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: @@ -118,29 +51,30 @@ async def record(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> server = await asyncio.start_server(record, "127.0.0.1", 0) gateway = FakeGateway() - run = await _open(gateway, server.sockets[0].getsockname()[1]) + run = await open_stream(gateway, server.sockets[0].getsockname()[1]) - sent = os.urandom(INITIAL_WINDOW // 2) - for offset in range(0, len(sent), MAX_DATA_LENGTH): - gateway.push(Frame(type=FrameType.DATA, stream_id=1, payload=sent[offset : offset + MAX_DATA_LENGTH])) + gateway.push_data(1, sent) gateway.push(Frame(type=FrameType.CLOSE, stream_id=1)) + destination_received = await received - assert await asyncio.wait_for(received, 5) == sent - assert gateway.unread_frames() == [] + unread = gateway.unread_frames() gateway.close() with pytest.raises(ConnectionError): await run server.close() await server.wait_closed() + return destination_received, unread - asyncio.run(scenario()) + sent = os.urandom(INITIAL_WINDOW // 2) + destination_received, unread = asyncio.run(scenario()) -@pytest.mark.timeout(10) -def test_tunnel_refuses_a_private_destination_without_dialing() -> None: - async def scenario() -> None: - dialed: list[Target] = [] + assert destination_received == sent + assert unread == [] + +def test_tunnel_refuses_a_private_destination_without_dialing() -> None: + async def scenario() -> Frame: async def dial(target: Target) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]: dialed.append(target) raise AssertionError("a refused destination is never dialed") @@ -149,64 +83,35 @@ async def dial(target: Target) -> tuple[asyncio.StreamReader, asyncio.StreamWrit run = asyncio.ensure_future(Tunnel(gateway, dial=dial).run()) gateway.push(Frame(type=FrameType.OPEN, stream_id=1, payload=b"10.0.0.1:443")) - assert await gateway.next_frame() == Frame(type=FrameType.OPEN_FAIL, stream_id=1, payload=b"address") - assert dialed == [] + answer = await gateway.next_frame() gateway.close() with pytest.raises(ConnectionError): await run + return answer - asyncio.run(scenario()) - - -@pytest.mark.timeout(10) -def test_tunnel_ends_when_the_gateway_sends_past_the_window() -> None: - async def scenario() -> None: - server = await asyncio.start_server(_echo, "127.0.0.1", 0) - gateway = FakeGateway() - run = await _open(gateway, server.sockets[0].getsockname()[1]) - - # Pushed without yielding, so the tunnel reads them back to back before granting anything. - for _ in range(INITIAL_WINDOW // MAX_DATA_LENGTH): - gateway.push(Frame(type=FrameType.DATA, stream_id=1, payload=bytes(MAX_DATA_LENGTH))) - gateway.push(Frame(type=FrameType.DATA, stream_id=1, payload=b"\x00")) + dialed: list[Target] = [] - with pytest.raises(ProtocolError): - await run - server.close() - await server.wait_closed() + answer = asyncio.run(scenario()) - asyncio.run(scenario()) + assert answer == Frame(type=FrameType.OPEN_FAIL, stream_id=1, payload=b"address") + assert dialed == [] -@pytest.mark.timeout(10) -def test_tunnel_sends_a_gateway_token_and_ends_when_the_gateway_sends_one() -> None: - async def scenario() -> None: - gateway = FakeGateway() - tunnel = Tunnel(gateway) - run = asyncio.ensure_future(tunnel.run()) - - await tunnel.send_gateway_token("fresh-token") - gateway.push(Frame.gateway_token("from-the-gateway")) - - assert await gateway.next_frame() == Frame.gateway_token("fresh-token") - with pytest.raises(ProtocolError): - await run - - asyncio.run(scenario()) - - -@pytest.mark.timeout(10) -def test_tunnel_reports_ready_once_and_ends_on_a_second_ready() -> None: +def test_tunnel_ends_when_the_gateway_sends_past_the_window() -> None: async def scenario() -> None: + server = await asyncio.start_server(echo, "127.0.0.1", 0) gateway = FakeGateway() - readies: list[None] = [] - run = asyncio.ensure_future(Tunnel(gateway, on_ready=lambda: readies.append(None)).run()) + run = await open_stream(gateway, server.sockets[0].getsockname()[1]) - gateway.push(Frame(type=FrameType.READY, stream_id=0)) - gateway.push(Frame(type=FrameType.READY, stream_id=0)) + # Pushed without yielding, so the tunnel reads them back to back before granting anything. + gateway.push_data(1, bytes(INITIAL_WINDOW + 1)) + gateway.close() - with pytest.raises(ProtocolError): + try: await run - assert len(readies) == 1 + finally: + server.close() + await server.wait_closed() - asyncio.run(scenario()) + with pytest.raises(ProtocolError): + asyncio.run(scenario())