From 51081949663293f28835d6788d97dd1ce445ae81 Mon Sep 17 00:00:00 2001 From: Adam Crocker <77861255+captcrock@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:12:51 +0000 Subject: [PATCH] TD-5305: the sandbox's egress proxy and its audit rows sandboxing.md R3, first PR of two (signed off ahead of the work): an asyncio HTTP proxy for CONNECT and plain http:// with no listener of its own. A request needs the command's own token (407 otherwise); the host must be on the grant's list from boundary.network (a bare name is ports 80 and 443, an IP literal only when listed); the proxy resolves names itself, refuses loopback, link-local and own-host answers, and dials the address it checked. Plain HTTP is one request per connection. Every allow and deny is a network_egress audit row (schema v8) with the tool call id. Nothing uses it yet: TD-5306 adds the setting and the bridge from inside the sandbox's network namespace. Network stays off. Co-Authored-By: Claude Opus 5.5 --- DECISIONS.md | 26 ++ core/tests/test_audit.py | 4 +- core/tests/test_outbound_hosts.py | 4 + core/tests/test_sandbox_proxy.py | 266 +++++++++++++++++ core/tstd/audit.py | 49 ++++ core/tstd/audit_writer.py | 18 ++ core/tstd/sandbox/proxy.py | 459 ++++++++++++++++++++++++++++++ docs/architecture.md | 1 + docs/tst-desk-backlog.md | 25 ++ 9 files changed, 851 insertions(+), 1 deletion(-) create mode 100644 core/tests/test_sandbox_proxy.py create mode 100644 core/tstd/sandbox/proxy.py diff --git a/DECISIONS.md b/DECISIONS.md index a3c43788..b31761e9 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -20570,3 +20570,29 @@ dropped when the command changes. all); keeping the scrub as a mode switch (two behaviours to support for one safety property); filtering named variables through the scrub (the person named them for this server). + +## 2026-11-24 — TD-5305: the sandbox egress proxy (Class B) + +**Decision:** `core/tstd/sandbox/proxy.py`, built as sandboxing.md R3 has +it (signed off ahead of the work): an asyncio HTTP proxy for `CONNECT` and +plain `http://`, no SOCKS, no TLS interception, no new dependency. It has +no listener; the daemon will hand it connections (TD-5306, over a socket +pair from inside the network namespace). Per-command `ProxyGrant`s carry a +random token, checked from Basic `Proxy-Authorization` (password part). +Host rules: exact names from `boundary.network`, case-blind, trailing dot +ignored; a bare entry is ports 80 and 443, `host:port` names a port; an IP +literal must itself be listed. The proxy resolves and checks every answer +(loopback, IPv4-mapped loopback, link-local, unspecified, multicast, +reserved, own addresses) and dials the first checked address. Plain HTTP is +one request per connection. Decisions go to a new append-only audit table, +`network_egress` (schema v8). + +**Rationale:** the owner signed off on R3 as written. Ports default to the +web ones because a host entry today means "the agent may fetch from it"; +opening every port on it would widen what an existing list allows. One +request per plain-HTTP connection is what keeps the host check honest +without parsing every later request on a kept-alive connection. + +**Rejected:** wildcard host entries (the list's meaning stays the same as +the classifier's `network-new-host` rule); a TCP listener on the host for +Linux (R3: "not TCP at all on the host side"). diff --git a/core/tests/test_audit.py b/core/tests/test_audit.py index 1dccff2b..cc153806 100644 --- a/core/tests/test_audit.py +++ b/core/tests/test_audit.py @@ -39,7 +39,7 @@ def store(tmp_path: Path) -> Iterator[AuditStore]: def test_schema_has_the_audit_tables(store: AuditStore) -> None: """The set grew by judgments (TD-708), allowed_calls (TD-5103), steers (TD-5112) - and questions (TD-5121).""" + and questions (TD-5121), hook_runs (TD-5134) and network_egress (TD-5305).""" rows = store._conn.execute( "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" " AND name != 'schema_migrations'" @@ -57,6 +57,7 @@ def test_schema_has_the_audit_tables(store: AuditStore) -> None: "steers", "questions", "hook_runs", + "network_egress", } assert views == {"costs"} @@ -119,6 +120,7 @@ def test_store_exposes_no_update_methods(store: AuditStore) -> None: "append_hook_run", "append_judgment", "append_model_call", + "append_network_egress", "append_question", "append_session", "append_steer", diff --git a/core/tests/test_outbound_hosts.py b/core/tests/test_outbound_hosts.py index c75897af..6233a167 100644 --- a/core/tests/test_outbound_hosts.py +++ b/core/tests/test_outbound_hosts.py @@ -257,6 +257,10 @@ def test_the_literal_scan_catches_a_planted_remote_host(tmp_path: Path) -> None: "refuses unless it is loopback; only on the person's set_fast or their next turn" ), "provider.py": "the one chat client; base_url is a constructor argument from config", + "sandbox/proxy.py": ( + "TD-5305: the sandbox egress proxy; it dials only a host the person put on " + "boundary.network, for a command they ran, and names no host itself" + ), "net.py": ( "TD-5181: builds a proxy-free transport for a caller's loopback URL; it sends " "nothing itself and has no destination of its own" diff --git a/core/tests/test_sandbox_proxy.py b/core/tests/test_sandbox_proxy.py new file mode 100644 index 00000000..5971a41a --- /dev/null +++ b/core/tests/test_sandbox_proxy.py @@ -0,0 +1,266 @@ +"""The sandbox's egress proxy (TD-5305, sandboxing R3). + +Every test runs on this computer: the "allowed host" is a local test +server, reached through a connect seam from a public test address +(203.0.113.0/24, RFC 5737), so no outside host is contacted. +""" + +from __future__ import annotations + +import asyncio +import base64 +from collections.abc import AsyncIterator +from pathlib import Path +from typing import Any + +import pytest + +from tstd.audit import AuditStore +from tstd.audit_writer import AuditWriter +from tstd.sandbox.proxy import EgressDecision, EgressProxy, listed, split_entry + +ALLOWED = "203.0.113.5" +OWN = "198.51.100.7" +ANSWERS = { + "allowed.test": [ALLOWED], + "rebind.test": ["127.0.0.1"], + "mapped.test": ["::ffff:127.0.0.1"], + "linklocal.test": ["169.254.169.254"], + "own.test": [OWN], + "mixed.test": [ALLOWED, "127.0.0.1"], +} + + +class Rig: + def __init__(self) -> None: + self.decisions: list[EgressDecision] = [] + self.upstream_seen: list[bytes] = [] + self.upstream_port = 0 + self.dialled: list[tuple[str, int]] = [] + self.proxy = EgressProxy( + self._record, resolve=self._resolve, connect=self._connect, own={OWN} + ) + self.proxy_port = 0 + + async def _record(self, decision: EgressDecision) -> None: + self.decisions.append(decision) + + async def _resolve(self, host: str, port: int) -> list[str]: + if host not in ANSWERS: + raise OSError("no such name") + return ANSWERS[host] + + async def _connect(self, address: str, port: int) -> Any: + self.dialled.append((address, port)) + assert address == ALLOWED, "the proxy dialled an address it should have refused" + return await asyncio.open_connection("127.0.0.1", self.upstream_port) + + async def _upstream(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + data = await reader.read(65536) + self.upstream_seen.append(data) + if data.startswith(b"GET "): + writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi") + else: + writer.write(b"echo:" + data) + await writer.drain() + writer.close() + + def grant(self, *hosts: str) -> str: + return self.proxy.grant("s1", "call-1", hosts).token + + async def ask(self, head: str, token: str | None, body: bytes = b"") -> bytes: + reader, writer = await asyncio.open_connection("127.0.0.1", self.proxy_port) + auth = "" + if token is not None: + cred = base64.b64encode(f"tst:{token}".encode()).decode() + auth = f"Proxy-Authorization: Basic {cred}\r\n" + first, _, rest = head.partition("\r\n") + writer.write(f"{first}\r\n{auth}{rest}".encode() + body) + await writer.drain() + out = await asyncio.wait_for( + reader.read(-1) if not body else self._after(reader, writer, body), 10 + ) + writer.close() + return out + + async def _after( + self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, body: bytes + ) -> bytes: + established = await reader.readuntil(b"\r\n\r\n") + if b" 200 " not in established: + return established + await reader.read(-1) + writer.write(body) + await writer.drain() + writer.write_eof() + return established + await reader.read(-1) + + +@pytest.fixture +async def rig() -> AsyncIterator[Rig]: + r = Rig() + upstream = await asyncio.start_server(r._upstream, "127.0.0.1", 0) + r.upstream_port = upstream.sockets[0].getsockname()[1] + proxy = await asyncio.start_server(r.proxy.serve, "127.0.0.1", 0) + r.proxy_port = proxy.sockets[0].getsockname()[1] + try: + yield r + finally: + proxy.close() + upstream.close() + + +def _status(reply: bytes) -> int: + return int(reply.split(b" ", 2)[1]) + + +async def test_connect_to_a_listed_host_relays(rig: Rig) -> None: + token = rig.grant(f"allowed.test:{8443}") + reply = await rig.ask( + "CONNECT allowed.test:8443 HTTP/1.1\r\nHost: allowed.test\r\n\r\n", token, b"ping" + ) + assert reply.startswith(b"HTTP/1.1 200 ") + assert reply.endswith(b"echo:ping") + assert rig.dialled == [(ALLOWED, 8443)] + [d] = rig.decisions + assert (d.verdict, d.host, d.port, d.address, d.tool_call_id) == ( + "allow", + "allowed.test", + 8443, + ALLOWED, + "call-1", + ) + + +async def test_plain_http_goes_upstream_without_the_token_and_closes(rig: Rig) -> None: + token = rig.grant("allowed.test") + reply = await rig.ask( + "GET http://allowed.test/path?q=1 HTTP/1.1\r\nHost: allowed.test\r\n" + "Connection: keep-alive\r\n\r\n", + token, + ) + assert reply.endswith(b"hi") + [sent] = rig.upstream_seen + assert sent.startswith(b"GET /path?q=1 HTTP/1.1\r\n") + assert b"Proxy-Authorization" not in sent and token.encode() not in sent + assert b"Connection: close" in sent and b"keep-alive" not in sent + assert rig.dialled == [(ALLOWED, 80)] + + +@pytest.mark.parametrize( + ("target", "listed_as", "why"), + [ + ("elsewhere.test:443", "allowed.test", "not on this workspace's network allowlist"), + ("allowed.test:8080", "allowed.test", "allowed.test:8080 is not on"), + ("203.0.113.9:443", "allowed.test", "not on this workspace's network allowlist"), + ("127.0.0.1:443", "127.0.0.1", "loopback"), + ("[::1]:443", "::1", "loopback"), + ("rebind.test:443", "rebind.test", "loopback"), + ("mapped.test:443", "mapped.test", "loopback"), + ("linklocal.test:443", "linklocal.test", "link-local"), + ("own.test:443", "own.test", "this computer's own addresses"), + ("mixed.test:443", "mixed.test", "loopback"), + ("nowhere.test:443", "nowhere.test", "did not resolve"), + ], +) +async def test_refused_destinations(rig: Rig, target: str, listed_as: str, why: str) -> None: + token = rig.grant(listed_as) + reply = await rig.ask(f"CONNECT {target} HTTP/1.1\r\n\r\n", token) + assert _status(reply) in (403, 502) + assert why in reply.decode() + assert rig.dialled == [] + [d] = rig.decisions + assert d.verdict == "deny" and why in d.reason and d.tool_call_id == "call-1" + + +async def test_a_listed_public_literal_connects(rig: Rig) -> None: + token = rig.grant(f"{ALLOWED}:9000") + reply = await rig.ask(f"CONNECT {ALLOWED}:9000 HTTP/1.1\r\n\r\n", token, b"x") + assert reply.endswith(b"echo:x") + + +@pytest.mark.parametrize("token", [None, "wrong", ""]) +async def test_no_token_or_a_wrong_one_is_407_and_dials_nothing( + rig: Rig, token: str | None +) -> None: + rig.grant("allowed.test") + reply = await rig.ask("CONNECT allowed.test:443 HTTP/1.1\r\n\r\n", token) + assert _status(reply) == 407 + assert b'Proxy-Authenticate: Basic realm="tst-sandbox"' in reply + assert rig.dialled == [] and rig.decisions == [] + + +async def test_a_revoked_grant_is_407(rig: Rig) -> None: + token = rig.grant("allowed.test") + rig.proxy.revoke(token) + assert rig.proxy.live_grants() == 0 + reply = await rig.ask("CONNECT allowed.test:443 HTTP/1.1\r\n\r\n", token) + assert _status(reply) == 407 + + +async def test_one_commands_token_is_not_anothers(rig: Rig) -> None: + rig.proxy.grant("s1", "call-a", ["allowed.test"]) + other = rig.proxy.grant("s1", "call-b", ["elsewhere.test"]).token + reply = await rig.ask("CONNECT allowed.test:443 HTTP/1.1\r\n\r\n", other) + assert _status(reply) == 403 + assert rig.decisions[0].tool_call_id == "call-b" + + +@pytest.mark.parametrize( + "head", + [ + "GET https://allowed.test/ HTTP/1.1\r\n\r\n", + "GET /relative HTTP/1.1\r\nHost: allowed.test\r\n\r\n", + "CONNECT allowed.test HTTP/1.1\r\n\r\n", + "NONSENSE\r\n\r\n", + ], +) +async def test_what_is_not_a_proxy_request_is_400(rig: Rig, head: str) -> None: + token = rig.grant("allowed.test") + reply = await rig.ask(head, token) + assert _status(reply) == 400 + assert rig.dialled == [] + + +async def test_an_audit_failure_does_not_open_or_hang_anything(rig: Rig) -> None: + async def broken(_d: EgressDecision) -> None: + raise RuntimeError("disk full") + + rig.proxy._on_decision = broken + token = rig.grant("allowed.test") + reply = await rig.ask("CONNECT elsewhere.test:443 HTTP/1.1\r\n\r\n", token) + assert _status(reply) == 403 + + +def test_list_entries() -> None: + assert split_entry("Example.COM.") == ("example.com", None) + assert split_entry("example.com:8443") == ("example.com", 8443) + assert split_entry("[::1]:443") == ("::1", 443) + assert split_entry("::1") == ("::1", None) + assert listed("example.com", 443, ["example.com"]) + assert listed("example.com", 80, ["example.com"]) + assert not listed("example.com", 22, ["example.com"]) + assert listed("example.com", 22, ["example.com:22"]) + assert not listed("sub.example.com", 443, ["example.com"]) + + +async def test_decisions_reach_the_audit_log_with_the_tool_call(tmp_path: Path) -> None: + store = AuditStore(tmp_path / "audit.db") + store.append_session("s1", str(tmp_path), 1.0) + writer = AuditWriter(store) + writer.start() + writer.record_network_egress( + EgressDecision("s1", "call-9", "elsewhere.test", 443, "deny", "not listed") + ) + writer.record_network_egress( + EgressDecision("s1", "call-9", "allowed.test", 443, "allow", "on the allowlist", ALLOWED) + ) + await writer.close() + check = AuditStore(tmp_path / "audit.db") + rows = check._conn.execute( + "SELECT tool_call_id, host, port, address, verdict, reason FROM network_egress ORDER BY id" + ).fetchall() + check.close() + assert rows == [ + ("call-9", "elsewhere.test", 443, "", "deny", "not listed"), + ("call-9", "allowed.test", 443, ALLOWED, "allow", "on the allowlist"), + ] diff --git a/core/tstd/audit.py b/core/tstd/audit.py index 21547fc7..dc43fd38 100644 --- a/core/tstd/audit.py +++ b/core/tstd/audit.py @@ -246,6 +246,25 @@ CREATE INDEX idx_hook_runs_session ON hook_runs(session_id, ts); """ +# v8 records every connection a sandboxed command asked the egress proxy +# for (TD-5305): the host and port it named, the address dialled, allow or +# deny, and why, keyed to the tool call that ran the command. No traffic +# and no URL path is kept: the proxy sees only the host and port. +_SCHEMA_V8 = """ +CREATE TABLE network_egress ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL REFERENCES sessions(session_id), + tool_call_id TEXT NOT NULL, + host TEXT NOT NULL, + port INTEGER NOT NULL, + address TEXT NOT NULL, + verdict TEXT NOT NULL CHECK(verdict IN ('allow', 'deny')), + reason TEXT NOT NULL, + ts REAL NOT NULL +); +CREATE INDEX idx_network_egress_session ON network_egress(session_id, ts); +""" + # Ordered migration steps; index + 1 is the schema version that step # produces. Every release that changes the schema appends one entry. MIGRATIONS: tuple[str, ...] = ( @@ -256,6 +275,7 @@ _SCHEMA_V5, _SCHEMA_V6, _SCHEMA_V7, + _SCHEMA_V8, ) @@ -620,6 +640,35 @@ def append_hook_run( self._conn.commit() return int(cur.lastrowid or 0) + def append_network_egress( + self, + session_id: str, + tool_call_id: str, + host: str, + port: int, + address: str, + verdict: str, + reason: str, + ts: float | None = None, + ) -> int: + """Record one egress proxy decision (TD-5305), scrubbed.""" + cur = self._conn.execute( + "INSERT INTO network_egress (session_id, tool_call_id, host, port, address," + " verdict, reason, ts) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + ( + session_id, + tool_call_id, + redact_secrets(host), + port, + address, + verdict, + redact_secrets(reason), + ts or time.time(), + ), + ) + self._conn.commit() + return int(cur.lastrowid or 0) + def append_judgment( self, session_id: str, diff --git a/core/tstd/audit_writer.py b/core/tstd/audit_writer.py index 7a5fe858..e1ac6363 100644 --- a/core/tstd/audit_writer.py +++ b/core/tstd/audit_writer.py @@ -43,6 +43,7 @@ UserTurn, ) from .protocol import ToolCall as ToolCallEvent +from .sandbox.proxy import EgressDecision from .session import EventSubscriber, Session, SessionEventLog if TYPE_CHECKING: @@ -190,6 +191,23 @@ def record_judgment(self, session_id: str, record: JudgmentAudit) -> None: ), ) + def record_network_egress(self, decision: EgressDecision) -> None: + """Enqueue one egress proxy allow or deny (TD-5305). Never blocks.""" + d = decision + self._enqueue( + d.session_id, + lambda: self._store.append_network_egress( + session_id=d.session_id, + tool_call_id=d.tool_call_id, + host=d.host, + port=d.port, + address=d.address, + verdict=d.verdict, + reason=d.reason, + ts=d.ts, + ), + ) + def record_model_call(self, session_id: str, record: CallRecord, is_classifier: bool) -> None: """Sink for ``CostTracker`` listeners (TD-902 feed 2). diff --git a/core/tstd/sandbox/proxy.py b/core/tstd/sandbox/proxy.py new file mode 100644 index 00000000..c76b2fe0 --- /dev/null +++ b/core/tstd/sandbox/proxy.py @@ -0,0 +1,459 @@ +"""The sandbox's way out: an allow-listing HTTP proxy (TD-5305, sandboxing R3). + +A sandboxed shell command has no network: every namespace is unshared. +With ``sandbox.network: allowlist`` (TD-5306) it gets one way out, this +proxy, and only to the hosts on ``boundary.network``. The proxy is the +check; the namespace with no other route is the boundary. + +- ``CONNECT host:port`` (HTTPS, git over https) and plain ``http://`` URLs. + No SOCKS, no TLS interception: the proxy sees the host and port, never + the traffic. +- A host must be on the grant's list. A bare name allows ports 80 and + 443; ``host:port`` allows that port. An IP literal is refused unless it + is listed itself. +- The proxy resolves the name itself and connects to the address it + checked, so an answer cannot change between the check and the dial. An + answer that is loopback, link-local, unspecified, multicast or one of + this computer's own addresses is refused, so a listed name cannot be + pointed at the daemon or another local service. +- Each command has its own token (``ProxyGrant``); a request without a + known one is answered 407. That keeps another local process, or another + command, from borrowing a command's grant. +- Every allow and deny is reported to ``on_decision``, which the daemon + writes to the audit log with the tool call id. + +This module holds no listener. The daemon hands it one connection at a +time (``serve``): on Linux over a socket pair from inside the sandbox, so +nothing on the host listens at all. +""" + +from __future__ import annotations + +import asyncio +import base64 +import binascii +import contextlib +import ipaddress +import secrets +import socket +import time +from collections.abc import Awaitable, Callable, Collection +from dataclasses import dataclass, field +from typing import Literal +from urllib.parse import urlsplit + +from ..logging import get_logger + +log = get_logger("tstd.sandbox.proxy") + +Verdict = Literal["allow", "deny"] + +#: The longest request head the proxy reads before it answers 400. +HEAD_LIMIT = 16 * 1024 +#: Seconds to read a request head, to resolve, and to connect. +HEAD_TIMEOUT = 15.0 +CONNECT_TIMEOUT = 15.0 +#: Ports a bare host entry allows. +WEB_PORTS = frozenset({80, 443}) +_RELAY_CHUNK = 64 * 1024 + + +@dataclass(frozen=True) +class EgressDecision: + """One allow or deny, for the audit log.""" + + session_id: str + tool_call_id: str + host: str + port: int + verdict: Verdict + reason: str + address: str = "" + ts: float = field(default_factory=time.time) + + +OnDecision = Callable[[EgressDecision], Awaitable[None]] +Resolve = Callable[[str, int], Awaitable[list[str]]] +Connect = Callable[[str, int], Awaitable[tuple[asyncio.StreamReader, asyncio.StreamWriter]]] + + +@dataclass(frozen=True) +class ProxyGrant: + """What one sandboxed command may reach, and the token that proves it is that command.""" + + token: str + session_id: str + tool_call_id: str + hosts: frozenset[str] + + +class Refused(Exception): + """A request the proxy answers itself: a status and a one-line reason.""" + + def __init__(self, status: int, reason: str, *, host: str = "", port: int = 0) -> None: + super().__init__(reason) + self.status = status + self.reason = reason + self.host = host + self.port = port + + +def normalize_host(host: str) -> str: + """Lower case, no brackets, no trailing dot.""" + host = host.strip().lower() + if host.startswith("[") and host.endswith("]"): + host = host[1:-1] + return host.rstrip(".") + + +def _ip(text: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None: + try: + return ipaddress.ip_address(text) + except ValueError: + return None + + +def listed(host: str, port: int, hosts: Collection[str]) -> bool: + """Whether ``host:port`` is on the list: a bare entry is the web ports only.""" + name = normalize_host(host) + for entry in hosts: + entry_host, entry_port = split_entry(entry) + if entry_host != name: + continue + if entry_port is None and port in WEB_PORTS: + return True + if entry_port == port: + return True + return False + + +def split_entry(entry: str) -> tuple[str, int | None]: + """``host`` or ``host:port`` (``[v6]:port`` for an IPv6 literal).""" + text = entry.strip() + if text.startswith("["): + inside, _, rest = text[1:].partition("]") + port = rest[1:] if rest.startswith(":") else "" + return normalize_host(inside), int(port) if port.isdigit() else None + if text.count(":") == 1: + name, _, port = text.partition(":") + if port.isdigit(): + return normalize_host(name), int(port) + return normalize_host(text), None + + +def refused_address(address: str, own: Collection[str]) -> str | None: + """Why the proxy will not connect to *address*, or None.""" + ip = _ip(address) + if ip is None: + return "not an address" + if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None: + ip = ip.ipv4_mapped + if ip.is_loopback: + return "it resolves to this computer (loopback)" + if ip.is_link_local: + return "it resolves to a link-local address" + if ip.is_unspecified or ip.is_multicast or ip.is_reserved: + return "it resolves to an address that is not a host" + if str(ip) in own: + return "it resolves to one of this computer's own addresses" + return None + + +def own_addresses() -> frozenset[str]: + """This computer's own addresses, as far as its name resolves.""" + found: set[str] = set() + for name in {socket.gethostname(), socket.getfqdn()}: + with contextlib.suppress(OSError): + for info in socket.getaddrinfo(name, None): + found.add(str(info[4][0]).split("%")[0]) + return frozenset(found) + + +async def _resolve(host: str, port: int) -> list[str]: + loop = asyncio.get_running_loop() + infos = await loop.getaddrinfo(host, port, type=socket.SOCK_STREAM) + seen: list[str] = [] + for info in infos: + address = str(info[4][0]).split("%")[0] + if address not in seen: + seen.append(address) + return seen + + +class EgressProxy: + """The grants, the checks, and one connection at a time.""" + + def __init__( + self, + on_decision: OnDecision, + *, + resolve: Resolve = _resolve, + connect: Connect = asyncio.open_connection, + own: Collection[str] | None = None, + ) -> None: + self._on_decision = on_decision + self._resolve = resolve + self._connect = connect + self._own = frozenset(own) if own is not None else own_addresses() + self._grants: dict[str, ProxyGrant] = {} + + # ── grants ───────────────────────────────────────────────────────── + + def grant(self, session_id: str, tool_call_id: str, hosts: Collection[str]) -> ProxyGrant: + """A new token for one command. Revoke it when the command is reaped.""" + token = secrets.token_urlsafe(24) + grant = ProxyGrant(token, session_id, tool_call_id, frozenset(hosts)) + self._grants[token] = grant + return grant + + def revoke(self, token: str) -> None: + self._grants.pop(token, None) + + def live_grants(self) -> int: + return len(self._grants) + + # ── one connection ──────────────────────────────────────────────── + + async def serve(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + """Answer one client connection, then close it. Never raises.""" + try: + await self._serve(reader, writer) + except Exception as exc: # the connection is the client's; the daemon carries on + log.warning( + "egress proxy connection failed", extra={"extra_fields": {"error": str(exc)}} + ) + finally: + with contextlib.suppress(Exception): + writer.close() + await writer.wait_closed() + + async def _serve(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + try: + head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), HEAD_TIMEOUT) + except (asyncio.IncompleteReadError, asyncio.LimitOverrunError, TimeoutError): + await _answer(writer, 400, "The request head was incomplete or too long.") + return + if len(head) > HEAD_LIMIT: + await _answer(writer, 400, "The request head was too long.") + return + try: + method, target, version, headers = _parse_head(head) + except ValueError as exc: + await _answer(writer, 400, str(exc)) + return + grant = self._grants.get(_token(headers) or "") + if grant is None: + await _answer(writer, 407, "This proxy needs the command's own token.", auth=True) + return + try: + host, port, upstream_head = _destination(method, target, version, headers) + address = await self._check(grant, host, port) + except Refused as refused: + await self._decide(grant, refused.host, refused.port, "deny", refused.reason) + await _answer(writer, refused.status, refused.reason) + return + try: + up_reader, up_writer = await asyncio.wait_for( + self._connect(address, port), CONNECT_TIMEOUT + ) + except (OSError, TimeoutError) as exc: + reason = f"Could not connect to {host}:{port}: {exc.__class__.__name__}" + await self._decide(grant, host, port, "deny", reason, address) + await _answer(writer, 502, reason) + return + await self._decide(grant, host, port, "allow", "on the allowlist", address) + if upstream_head is None: + writer.write(b"HTTP/1.1 200 Connection established\r\n\r\n") + await writer.drain() + else: + up_writer.write(upstream_head) + await up_writer.drain() + await _relay(reader, writer, up_reader, up_writer) + + async def _check(self, grant: ProxyGrant, host: str, port: int) -> str: + """The address to dial for *host*, or ``Refused``.""" + name = normalize_host(host) + if not 0 < port < 65536: + raise Refused(400, f"Port {port} is not a port.", host=name, port=port) + if not listed(name, port, grant.hosts): + where = name if port in WEB_PORTS else f"{name}:{port}" + raise Refused( + 403, + f"{where} is not on this workspace's network allowlist (boundary.network).", + host=name, + port=port, + ) + literal = _ip(name) + if literal is not None: + why = refused_address(name, self._own) + if why is not None: + raise Refused(403, f"{name} is refused: {why}.", host=name, port=port) + return name + try: + answers = await asyncio.wait_for(self._resolve(name, port), CONNECT_TIMEOUT) + except (OSError, TimeoutError) as exc: + raise Refused(502, f"{name} did not resolve: {exc}", host=name, port=port) from exc + if not answers: + raise Refused(502, f"{name} did not resolve.", host=name, port=port) + for answer in answers: + why = refused_address(answer, self._own) + if why is not None: + raise Refused(403, f"{name} is refused: {why}.", host=name, port=port) + return answers[0] + + async def _decide( + self, + grant: ProxyGrant, + host: str, + port: int, + verdict: Verdict, + reason: str, + address: str = "", + ) -> None: + decision = EgressDecision( + session_id=grant.session_id, + tool_call_id=grant.tool_call_id, + host=host, + port=port, + verdict=verdict, + reason=reason, + address=address, + ) + try: + await self._on_decision(decision) + except Exception as exc: # an audit failure must not open or hang the connection + fields = {"error": str(exc)} + log.warning("egress decision not recorded", extra={"extra_fields": fields}) + + +# ── HTTP plumbing ──────────────────────────────────────────────────────── + +Headers = list[tuple[str, str]] +_HOP_BY_HOP = frozenset( + { + "proxy-authorization", + "proxy-connection", + "proxy-authenticate", + "connection", + "keep-alive", + "te", + "trailer", + "upgrade", + } +) + + +def _parse_head(head: bytes) -> tuple[str, str, str, Headers]: + try: + text = head.decode("latin-1") + except UnicodeDecodeError as exc: # latin-1 decodes every byte; kept for clarity + raise ValueError("The request head is not text.") from exc + lines = text.split("\r\n") + parts = lines[0].split(" ") + if len(parts) != 3 or not parts[2].startswith("HTTP/1."): + raise ValueError("The request line is not HTTP/1.x.") + headers: Headers = [] + for line in lines[1:]: + if not line: + continue + name, sep, value = line.partition(":") + if not sep or not name or name != name.strip(): + raise ValueError("A request header is malformed.") + headers.append((name, value.strip())) + return parts[0].upper(), parts[1], parts[2], headers + + +def _header(headers: Headers, name: str) -> str | None: + wanted = name.lower() + return next((value for key, value in headers if key.lower() == wanted), None) + + +def _token(headers: Headers) -> str | None: + """The password of a Basic ``Proxy-Authorization``; the user name is ignored.""" + value = _header(headers, "Proxy-Authorization") + if value is None: + return None + scheme, _, encoded = value.partition(" ") + if scheme.lower() != "basic": + return None + try: + decoded = base64.b64decode(encoded.strip(), validate=True).decode("utf-8") + except (binascii.Error, UnicodeDecodeError): + return None + _, sep, password = decoded.partition(":") + return password if sep else None + + +def _destination( + method: str, target: str, version: str, headers: Headers +) -> tuple[str, int, bytes | None]: + """Host, port and, for plain HTTP, the head to send upstream.""" + if method == "CONNECT": + host, port = split_entry(target) + if port is None: + raise Refused(400, "CONNECT needs host:port.") + return host, port, None + url = urlsplit(target) + if url.scheme != "http" or not url.hostname: + raise Refused(400, "Only http:// URLs and CONNECT go through this proxy.", host="", port=0) + try: + port = url.port or 80 + except ValueError as exc: + raise Refused(400, "The URL's port is not a number.") from exc + path = url.path or "/" + if url.query: + path += f"?{url.query}" + kept = [(k, v) for k, v in headers if k.lower() not in _HOP_BY_HOP] + if _header(kept, "Host") is None: + kept.insert(0, ("Host", url.netloc.rpartition("@")[2])) + # One request per connection: a second one on a kept-alive connection + # could name another host and would not be checked. + kept.append(("Connection", "close")) + lines = [f"{method} {path} {version}", *(f"{k}: {v}" for k, v in kept), "", ""] + return normalize_host(url.hostname), port, "\r\n".join(lines).encode("latin-1") + + +async def _answer( + writer: asyncio.StreamWriter, status: int, reason: str, *, auth: bool = False +) -> None: + phrase = { + 400: "Bad Request", + 403: "Forbidden", + 407: "Proxy Authentication Required", + 502: "Bad Gateway", + }.get(status, "Error") + body = (reason + "\n").encode("utf-8") + lines = [ + f"HTTP/1.1 {status} {phrase}", + "Content-Type: text/plain; charset=utf-8", + f"Content-Length: {len(body)}", + "Connection: close", + ] + if auth: + lines.append('Proxy-Authenticate: Basic realm="tst-sandbox"') + with contextlib.suppress(ConnectionError): + writer.write(("\r\n".join(lines) + "\r\n\r\n").encode("latin-1") + body) + await writer.drain() + + +async def _relay( + a_reader: asyncio.StreamReader, + a_writer: asyncio.StreamWriter, + b_reader: asyncio.StreamReader, + b_writer: asyncio.StreamWriter, +) -> None: + async def pump(src: asyncio.StreamReader, dst: asyncio.StreamWriter) -> None: + with contextlib.suppress(ConnectionError, asyncio.IncompleteReadError): + while chunk := await src.read(_RELAY_CHUNK): + dst.write(chunk) + await dst.drain() + with contextlib.suppress(Exception): + if dst.can_write_eof(): + dst.write_eof() + + try: + await asyncio.gather(pump(a_reader, b_writer), pump(b_reader, a_writer)) + finally: + with contextlib.suppress(Exception): + b_writer.close() + await b_writer.wait_closed() diff --git a/docs/architecture.md b/docs/architecture.md index d59db615..6369df85 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -898,6 +898,7 @@ change; changing the same behaviour anywhere else usually is not. | `stage_paths` | `core/tstd/git_stage.py` | How the daemon puts files into an index: `hash-object --no-filters` and `update-index --index-info`, never `git add`, so no filter driver an in-tree `.gitattributes` names runs (TD-5157). Line endings follow git's own rules, redone in `core/tstd/git_eol.py`. The checkpointer stages with it, and the memory commit and charter sign commit with `commit_on_head` beside it. Revert writes blobs back with `restore_blobs` (`core/tstd/git_restore.py`), and so does "Restore files to here" (`core/tstd/file_rewind.py`, TD-5125; it reads the session branch with `core/tstd/file_rewind_log.py`, TD-5161), which also stages a file just before an agent write when the person changed it, so the branch keeps their copy. A git call that must read the working tree or write the user's index (`git status`, the validator's `git diff`) adds `filter_pins` from `core/tstd/git_raw.py`. | | `sandbox_start_error` | `core/tstd/autonomy/sandbox.py` | Why an autonomous run may not start: missing / down / rootful runtime. Interactive sessions do not import this module (TD-4301). | | `build_plan` | `core/tstd/shell_sandbox.py` | The bubblewrap argv an interactive shell command runs under when the workspace turns `sandbox.enabled` on: read-only root, writable workspace, private `/tmp`, no network, a seccomp filter refusing `socket(AF_UNIX)` and io_uring (no host sockets), `.git` and steering files read-only, keys and keyrings masked; `guard_snapshot`/`guard_restore` move aside anything a command put at a guarded name a bind could not pin. `promote` is the one place a sandboxed command's ask may become `auto`; the dispatcher records the promise and the shell tool refuses a promised call it cannot sandbox (TD-5138). | +| `EgressProxy` | `core/tstd/sandbox/proxy.py` | The one way out a sandboxed command will get with `sandbox.network: allowlist` (TD-5305; wired in by TD-5306): an HTTP proxy for `CONNECT` and plain `http://`, with no listener of its own (the daemon hands it one connection at a time). A request needs the command's own token as Basic `Proxy-Authorization` (else 407). The host must be on the grant's list, from `boundary.network`: a bare name allows ports 80 and 443, `host:port` that port, and an IP literal only when listed. The proxy resolves the name itself, refuses an answer that is loopback, link-local, unspecified, multicast or this computer's own, and dials the address it checked. Plain HTTP goes upstream without the proxy headers and with `Connection: close`, so a second request cannot name another host. Each allow and deny is a row in the audit database's `network_egress` table (schema v8) with the tool call id, host, port, address dialled and reason; no traffic or URL path is kept. | | `Precedence` | `core/tstd/context/discover.py` | The steering hierarchy: `user global` < `workspace` < `rules` < `nested`. Adding a scope means adding a level here, and `docs/steering.md` documents each one. | | `ToolDispatcher` | `core/tstd/tools/dispatch.py` | The single chokepoint every tool call passes through: schema validation, classifier, path guard, policy gate, handler, after-write hooks (TD-5135), language-server diagnostics on the written files (TD-5139), checkpoint, ledger. Prime directive §2.6 lives here, and reaching a handler unclassified raises rather than executing. | | `LspPool` | `core/tstd/lsp/pool.py` | The daemon's running language servers (TD-5139), one per workspace and `lsp.servers` entry, each an `LspClient` (`core/tstd/lsp/client.py`) speaking LSP over the child's stdin and stdout, never a socket. The dispatcher's after-write diagnostics (`core/tstd/lsp/diagnostics.py`) and the `lsp_definition`, `lsp_references` and `lsp_symbols` tools (`core/tstd/tools/lsp.py`) ask it for a server; the daemon closes it on shutdown. | diff --git a/docs/tst-desk-backlog.md b/docs/tst-desk-backlog.md index 6ed5fc32..e85b37de 100644 --- a/docs/tst-desk-backlog.md +++ b/docs/tst-desk-backlog.md @@ -14832,3 +14832,28 @@ Linux, and the bundle runs build without MCP servers. The base list is the SDKs' own for those systems, the environment SDK-based clients already start servers with there. The computer-use MCP driver (`desktop/`) is the product's own process and keeps its own environment. + +### TD-5305 — The sandbox's egress proxy and its audit rows + +Owner decision on the full sandbox (brief section 4), design sandboxing.md +R3, first of two PRs: the proxy and the audit, before the bridge that puts +a sandboxed command in front of it (TD-5306). Network stays fully off by +default; nothing uses this proxy until TD-5306 adds the setting. + +- [x] `CONNECT host:port` and plain `http://` requests to a listed host are + relayed; anything else is answered 400 (`test_sandbox_proxy.py`). +- [x] A host not on the grant's list is 403; a bare entry allows ports 80 + and 443 only; an IP literal is refused unless listed. +- [x] The proxy resolves the name itself and refuses loopback (including + IPv4-mapped), link-local, and this computer's own addresses, and an + answer list with any of them; it dials only the address it checked. +- [x] A missing, wrong or revoked token is 407 with `Proxy-Authenticate`, + and dials nothing; one command's token does not carry another's grant. +- [x] Plain HTTP goes upstream without `Proxy-Authorization` and with + `Connection: close`. +- [x] Every allow and deny is a `network_egress` audit row with the tool + call id (schema v8); an audit failure neither opens nor hangs the + connection. +- [x] No outside host is contacted by the tests. + +**Size:** 5 · **Depends on:** TD-5138, TD-5294 · **Status:** Done