Secure, Fast, and Extensible Sandbox runtime for AI agents.
test(egress): trim resolver and addon comments to match repo terseness
高然b214dae4a14b
diff --git a/components/egress/mitmscripts/system.py b/components/egress/mitmscripts/system.pyindex d58b5cab9..eccbb6997 100644--- a/components/egress/mitmscripts/system.py+++ b/components/egress/mitmscripts/system.py@@ -119,10 +119,8 @@ ACTIVE_VAULT_HEADER_RESERVED_NAMES = {_ACTIVE_VAULT_HEADER_NAME_RE = re.compile(r"^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$")_ACTIVE_VAULT_HOST_LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")_PERCENT_ESCAPE_RE = re.compile(r"%([0-9A-Fa-f]{2})")-# Strict snapshot key sets (OSEP-0025 version-skew gate). The addon rejects-# any snapshot carrying fields outside these sets instead of silently-# dropping them, so a newer egress must never degrade to an empty static-# binding on an older addon.+# Strict snapshot key sets: unknown fields reject the whole snapshot+# (OSEP-0025 version-skew gate) instead of silently degrading bindings._ACTIVE_VAULT_TOP_LEVEL_FIELDS = {"revision", "bindings", "redactions"}_ACTIVE_VAULT_BINDING_FIELDS = {"name",@@ -131,8 +129,8 @@ _ACTIVE_VAULT_BINDING_FIELDS = {"substitutions","exchange",}-# `ports` is deprecated upstream (accepted but ignored) and still rendered by-# the Go snapshot for legacy vaults; it stays allowed and ignored here.+# `ports` is deprecated upstream but still rendered by the Go snapshot for+# legacy vaults; allowed and ignored here._ACTIVE_VAULT_MATCH_FIELDS = {"schemes", "ports", "hosts", "methods", "paths"}_ACTIVE_VAULT_HEADER_FIELDS = {"name", "value"}_ACTIVE_VAULT_SUBSTITUTION_FIELDS = {"placeholder", "value", "in"}@@ -865,13 +863,9 @@ def _parse_active_vault(payload: Any) -> ActiveVault:def _parse_active_vault_exchange(binding: dict[str, Any], index: int) -> dict[str, str] | None:- """Validate the optional exchange marker of one snapshot binding.-- Exchange bindings carry no rendered material: ``headers`` and- ``substitutions`` must be explicitly present and empty, and the marker- itself must be exactly ``{"credential": <non-empty name>}``. Anything- else fails the snapshot closed instead of silently degrading to a static- binding that would forward the request uncredentialed.+ """Validate the optional exchange marker: exactly ``{"credential": name}``+ with explicitly empty ``headers``/``substitutions``; anything else fails+ the snapshot closed."""raw_exchange = binding.get("exchange")if raw_exchange is None:@@ -1888,10 +1882,8 @@ def _apply_vault_binding(if not binding:return- # Exchange bindings resolve per request against the egress process; until- # that resolve path is wired in (OSEP-0025 T3b), a selected exchange- # binding must fail closed instead of forwarding the request without- # credentials.+ # Until the T3b resolve path exists, exchange bindings must fail closed+ # rather than forward uncredentialed.if "exchange" in binding:_reject_request(flow, b"credential exchange unavailable\n", status_code=503)ctx.log.warn(diff --git a/components/egress/tests/resolver/resolver.py b/components/egress/tests/resolver/resolver.pyindex 2e684d330..7de64a93e 100644--- a/components/egress/tests/resolver/resolver.py+++ b/components/egress/tests/resolver/resolver.py@@ -14,58 +14,29 @@"""Standalone credential header-resolver stub for OSEP-0025 tests.-Implements the egress-to-resolver contract: one POSTed JSON document-(subject, credential, binding, destination, request) answered with a header-map plus optional incremental redactions. It serves as the public reference-peer for egress conformance tests, e2e smoke flows, and as a development-stub that can run before the egress resolver client exists.--Framing (D15): the service is fixed at ``POST /resolve``; requests on any-other path answer 404. UDS mode never inspects the Host header — the socket-path selects the service — and HTTPS mode carries the origin in TLS SNI plus-the Authorization header, so no virtual-host dispatch exists.--The ``subject`` field is the egress-authoritative sandboxId (sidecar: the-sandbox's configured ID; fast-sandbox: the clientIp-mapped subject); the-deterministic signature stub exists so e2e tests can assert that egress sent-the expected sandboxId and verified destination.--Transports-------------``--uds PATH``- HTTP over a Unix domain socket. No caller authentication: the socket's- file permissions (the stub binds with 0660) are the trust boundary.--``--https HOST:PORT --tls-cert PEM --tls-key PEM``- TLS with ``Authorization: Bearer <token>`` caller authentication. The- expected token is ``--auth`` or is looked up by this server's origin- (``https://HOST:PORT``) in ``OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_AUTH``- (format ``origin=token,origin=token``). Without a configured token every- request is rejected with 401 (fail closed).--Deterministic resolution---------------------------Every response carries ``authorization: Bearer test-<credential>``,-``x-test-subject: <subject>``, and ``x-test-signature`` — the SHA-256 hex-digest of ``subject|credential|binding|authority|path`` — so e2e tests can-assert that egress derived the right subject and verified destination.--Fault injection------------------``--delay MS``- Sleep before every response (resolver timeout tests).--``--fail once|RATE``- ``once`` refuses the first resolution and serves afterwards; ``RATE`` in- ``[0,1]`` refuses that random fraction. Refusals answer ``503- resolution_refused`` so tests can pin egress fail-closed behavior.--``--incomplete-redactions``- Return redactions for only the first header (OSEP-0025 R9: egress must- auto-derive the rest and never trust resolver redactions as authority).+Serves the egress-to-resolver contract (one POSTed JSON document answered+with a header map plus optional incremental redactions) as the conformance+peer for egress tests and a development stub that runs before the egress+client exists.++Transports:++- ``--uds PATH``: HTTP over a Unix domain socket (bound 0660); no caller+ authentication — the socket permissions are the trust boundary.+- ``--https HOST:PORT --tls-cert PEM --tls-key PEM``: TLS with Bearer caller+ authentication; the token is ``--auth`` or is looked up by origin in+ ``OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_AUTH``. Without a configured+ token every request is rejected with 401 (fail closed).++Framing (D15): fixed at ``POST /resolve``; other paths answer 404; UDS mode+never inspects Host. ``subject`` is the egress-authoritative sandboxId, and+``x-test-signature`` is the SHA-256 hex of+``subject|credential|binding|authority|path`` so tests can assert both.++Fault injection: ``--delay MS`` sleeps before every response; ``--fail+once|RATE`` answers ``503 resolution_refused``; ``--incomplete-redactions``+returns redactions for only one header (egress must auto-derive the rest,+R9)."""from __future__ import annotations@@ -89,9 +60,8 @@ import tracebackfrom typing import AnyMAX_REQUEST_BYTES = 64 * 1024-# Bodies beyond the request cap are drained up to this bound before the 413-# is written, so well-behaved clients finish sending instead of dying on a-# broken pipe; anything larger may still be disconnected mid-upload.+# Bodies over the cap are drained up to this bound before the 413, so+# clients finish sending instead of dying on a broken pipe.MAX_DRAIN_BYTES = 1024 * 1024_REQUEST_FIELDS = {"subject", "credential", "binding", "destination", "request"}@@ -130,12 +100,9 @@ def _string_map(value: Any) -> bool:def parse_resolve_request(payload: dict[str, Any]) -> dict[str, str]:- """Validate one resolver request and return its flat parts.+ """Validate one resolver request (``subject`` is the egress sandboxId).- ``subject`` is the egress-authoritative sandboxId; ``destination`` is the- verified outbound destination. Raises ``_BadRequest`` for anything that- does not exactly match the OSEP-0025 resolver contract so shape drift- fails loudly in tests.+ Raises ``_BadRequest`` for anything off the OSEP-0025 contract."""if set(payload) != _REQUEST_FIELDS:raise _BadRequest@@ -239,16 +206,13 @@ class _UnixHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):address_family = socket.AF_UNIXdef server_bind(self) -> None:- # HTTPServer.server_bind derives server_name/server_port from an- # AF_INET address tuple; a Unix socket path is already the identity.+ # HTTPServer.server_bind expects an AF_INET address tuple.socketserver.TCPServer.server_bind(self)self.server_name = "resolver.uds"self.server_port = 0def handle_error(self, _request: object, _address: object) -> None:- # Record instead of swallow: tests assert this list stays empty, so- # handler bugs surface as server-side failures instead of mystery- # client errors such as BrokenPipeError on a socket we closed.+ # Recorded, not swallowed: tests assert this stays empty.self.exceptions.append(traceback.format_exc())diff --git a/components/egress/tests/resolver/test_resolver.py b/components/egress/tests/resolver/test_resolver.pyindex 87e8509f1..36026f414 100644--- a/components/egress/tests/resolver/test_resolver.py+++ b/components/egress/tests/resolver/test_resolver.py@@ -95,14 +95,13 @@ class _UnixConnection(http.client.HTTPConnection):class _ResolverProcess:- """Run one resolver server instance in a background thread.-- Every response carries ``Connection: close`` (mirroring the revision IPC- discipline: one request per connection), so clients must open a fresh- connection per request; reusing one trips over the server-side close.- Handler-side exceptions are recorded on the server instead of being- swallowed and are asserted here unless they belong to the expected- client-abort class (``allow_client_aborts``, e.g. the delay test).+ """Run one resolver server in a background thread.++ Responses are ``Connection: close`` (one request per connection), so+ open a fresh connection per request. Handler exceptions are recorded on+ the server and asserted here; ``allow_client_aborts`` tolerates+ BrokenPipe/ConnectionReset records (the delay test disconnects+ mid-handler by design)."""CLIENT_ABORT_ERRORS = ("BrokenPipeError", "ConnectionResetError")@@ -198,8 +197,7 @@ class ResolverUDSTest(unittest.TestCase):},document,)- # D15: the subject asserted by the signature stub is the egress- # sandboxId, mirrored verbatim into x-test-subject.+ # D15: x-test-subject mirrors the egress sandboxId verbatim.self.assertEqual(VALID_REQUEST["subject"], document["headers"]["x-test-subject"])@@ -218,9 +216,7 @@ class ResolverUDSTest(unittest.TestCase):)def test_fixed_service_path_rejects_other_paths_with_404(self) -> None:- # One fresh connection per request: the resolver replies with- # ``Connection: close`` and closes the socket, so reusing a- # connection across requests races the server-side close.+ # One fresh connection per request: every response closes the socket.with _ResolverProcess(build_uds_server(self.socket_path)):for path in ("/", "/resolve/", "/v1/resolve"):status, _ = self.post(dumps(VALID_REQUEST), path=path)@@ -433,9 +429,8 @@ class ResolverFaultInjectionTest(unittest.TestCase):def test_delay_exceeds_client_timeout(self) -> None:server = build_uds_server(self.socket_path, ["--delay", "1000"])- # The client aborts at 0.2s while the handler is still sleeping, so- # the handler's eventual write raises a client-abort error that the- # harness tolerates; anything else still fails the test.+ # The client aborts mid-handler; the harness tolerates the resulting+ # client-abort records only.with _ResolverProcess(server, allow_client_aborts=True):started = time.monotonic()with self.assertRaises((TimeoutError, OSError)):diff --git a/components/egress/tests/test_decision_snapshot.py b/components/egress/tests/test_decision_snapshot.pyindex 19274a856..e8f601f71 100644--- a/components/egress/tests/test_decision_snapshot.py+++ b/components/egress/tests/test_decision_snapshot.py@@ -167,9 +167,8 @@ class DecisionSnapshotTest(unittest.TestCase):self.assert_rejected(candidate)def test_rejects_exchange_marker_from_newer_egress(self):- """Version-skew gate: this validator predates OSEP-0025 exchange- markers, so a snapshot emitted by a newer egress must fail closed- here instead of degrading to an empty static binding."""+ """Version-skew gate: snapshots carrying OSEP-0025 exchange markers+ must fail closed on this (unextended) validator."""candidate = self.active()candidate["fullRenderedBindings"][0]["exchange"] = {"credential": "spi-signer"