Secure, Fast, and Extensible Sandbox runtime for AI agents.
test(egress): add public OSEP-0025 credential resolver stub
高然316001254c78
diff --git a/components/egress/tests/resolver/__init__.py b/components/egress/tests/resolver/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/components/egress/tests/resolver/fixtures/README.md b/components/egress/tests/resolver/fixtures/README.mdnew file mode 100644index 000000000..d6099602e--- /dev/null+++ b/components/egress/tests/resolver/fixtures/README.md@@ -0,0 +1,10 @@+Test-only TLS material for the OSEP-0025 resolver stub (`../resolver.py`).++`test-localhost-cert.pem` / `test-localhost-key.pem` are a self-signed pair+for CN=localhost (SAN: DNS:localhost, IP:127.0.0.1). They certify nothing and+must never be trusted outside local egress tests; regenerate with:++ openssl req -x509 -newkey rsa:2048 -days 3650 -nodes \+ -subj "/CN=localhost" \+ -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" \+ -keyout test-localhost-key.pem -out test-localhost-cert.pemdiff --git a/components/egress/tests/resolver/resolver.py b/components/egress/tests/resolver/resolver.pynew file mode 100644index 000000000..bd0f12af9--- /dev/null+++ b/components/egress/tests/resolver/resolver.py@@ -0,0 +1,485 @@+# Copyright 2026 The OpenSandbox Authors+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""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).+"""++from __future__ import annotations++import argparse+import contextlib+import hashlib+import hmac+import http.client+import http.server+import json+import os+import random+import socket+import socketserver+import ssl+import sys+import threading+import time+from typing import Any++MAX_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.+MAX_DRAIN_BYTES = 1024 * 1024++_REQUEST_FIELDS = {"subject", "credential", "binding", "destination", "request"}+_DESTINATION_FIELDS = {"scheme", "authority", "sni"}+_REQUEST_REQUEST_FIELDS = {"method", "host", "path", "headers"}+_AUTH_ENV = "OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_AUTH"+++class _BadRequest(Exception):+ pass+++class _TooLarge(Exception):+ pass+++def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, value in pairs:+ if key in result:+ raise _BadRequest+ result[key] = value+ return result+++def _non_empty_string(value: Any) -> bool:+ return type(value) is str and bool(value)+++def _string_map(value: Any) -> bool:+ return (+ type(value) is dict+ and all(type(key) is str for key in value)+ and all(type(item) is str for item in value.values())+ )+++def parse_resolve_request(payload: dict[str, Any]) -> dict[str, str]:+ """Validate one resolver request and return its flat parts.++ ``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.+ """+ if set(payload) != _REQUEST_FIELDS:+ raise _BadRequest+ subject = payload["subject"]+ credential = payload["credential"]+ binding = payload["binding"]+ if not all(_non_empty_string(part) for part in (subject, credential, binding)):+ raise _BadRequest+ destination = payload["destination"]+ if type(destination) is not dict or set(destination) != _DESTINATION_FIELDS:+ raise _BadRequest+ scheme = destination["scheme"]+ authority = destination["authority"]+ sni = destination["sni"]+ if (+ scheme not in ("http", "https")+ or not _non_empty_string(authority)+ or not _non_empty_string(sni)+ ):+ raise _BadRequest+ request = payload["request"]+ if type(request) is not dict or set(request) != _REQUEST_REQUEST_FIELDS:+ raise _BadRequest+ method = request["method"]+ host = request["host"]+ path = request["path"]+ if (+ not _non_empty_string(method)+ or not _non_empty_string(host)+ or not _non_empty_string(path)+ or not path.startswith("/")+ or not _string_map(request["headers"])+ ):+ raise _BadRequest+ return {+ "subject": subject,+ "credential": credential,+ "binding": binding,+ "scheme": scheme,+ "authority": authority,+ "sni": sni,+ "method": method,+ "host": host,+ "path": path,+ }+++def resolve_headers(parts: dict[str, str]) -> dict[str, str]:+ """Deterministic header set derived from the verified request parts."""+ signature_source = "|".join(+ (+ parts["subject"],+ parts["credential"],+ parts["binding"],+ parts["authority"],+ parts["path"],+ )+ )+ return {+ "authorization": "Bearer test-" + parts["credential"],+ "x-test-signature": hashlib.sha256(signature_source.encode()).hexdigest(),+ "x-test-subject": parts["subject"],+ }+++def resolve_response(+ parts: dict[str, str], incomplete_redactions: bool+) -> dict[str, Any]:+ headers = resolve_headers(parts)+ redactions = {name: [value] for name, value in headers.items()}+ if incomplete_redactions:+ first = sorted(redactions)[0]+ redactions = {first: redactions[first]}+ return {"headers": headers, "redactions": redactions}+++def expected_token_for_origin(origin: str, auth_override: str | None) -> str | None:+ """Resolve the caller token for this server's origin.++ ``auth_override`` (``--auth``) wins; otherwise the token table in+ ``OPENSANDBOX_EGRESS_CREDENTIAL_RESOLVER_AUTH`` is searched for+ ``origin=token`` entries. ``None`` means no token is configured and the+ HTTPS listener must reject every caller.+ """+ if auth_override:+ return auth_override+ raw = os.environ.get(_AUTH_ENV, "")+ for entry in raw.split(","):+ entry = entry.strip()+ if not entry:+ continue+ configured_origin, separator, token = entry.partition("=")+ if separator and configured_origin.strip() == origin:+ return token.strip() or None+ return None+++class _UnixHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):+ daemon_threads = True+ allow_reuse_address = True+ address_family = socket.AF_UNIX++ def 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.+ socketserver.TCPServer.server_bind(self)+ self.server_name = "resolver.uds"+ self.server_port = 0++ def handle_error(self, _request: object, _address: object) -> None:+ pass+++class _TCPHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):+ daemon_threads = True+ allow_reuse_address = True++ def handle_error(self, _request: object, _address: object) -> None:+ pass+++class _Handler(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"+ server_version = "OpenSandboxTestResolver/1"+ sys_version = ""++ def setup(self) -> None:+ super().setup()+ self.connection.settimeout(self.server.request_timeout)++ def log_message(self, _format: str, *args: object) -> None:+ pass++ def _reply(self, status: int, value: dict[str, Any]) -> None:+ body = json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.send_header("Connection", "close")+ self.end_headers()+ self.wfile.write(body)+ self.close_connection = True++ def _authenticate(self) -> bool:+ """Bearer caller authentication; HTTPS only, fail closed."""+ expected = self.server.expected_token+ if expected is not None:+ values = self.headers.get_all("Authorization", [])+ supplied = values[0] if len(values) == 1 else ""+ if hmac.compare_digest(supplied, "Bearer " + expected):+ return True+ self._reply(401, {"error": "unauthorized"})+ return False++ def _json_body(self) -> dict[str, Any]:+ if self.headers.get_all("Transfer-Encoding", []):+ raise _BadRequest+ types = self.headers.get_all("Content-Type", [])+ lengths = self.headers.get_all("Content-Length", [])+ if (+ types != ["application/json"]+ or len(lengths) != 1+ or not lengths[0].isdigit()+ ):+ raise _BadRequest+ length = int(lengths[0])+ if length > MAX_REQUEST_BYTES:+ self._drain(length)+ raise _TooLarge+ raw = self.rfile.read(length)+ if len(raw) != length:+ raise _BadRequest+ try:+ value = json.loads(+ raw,+ object_pairs_hook=_unique_object,+ parse_constant=lambda _value: (_ for _ in ()).throw(_BadRequest()),+ )+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError, _BadRequest):+ raise _BadRequest from None+ if type(value) is not dict:+ raise _BadRequest+ return value++ def _drain(self, length: int) -> None:+ remaining = min(length, MAX_DRAIN_BYTES)+ while remaining > 0:+ chunk = self.rfile.read(min(remaining, 65536))+ if not chunk:+ break+ remaining -= len(chunk)++ def do_POST(self) -> None:+ if self.server.transport == "https" and not self._authenticate():+ return+ if self.path != "/resolve":+ self._reply(404, {"error": "not_found"})+ return+ options = self.server.options+ if options.delay > 0:+ time.sleep(options.delay / 1000.0)+ if options.fail_once:+ options.fail_once = False+ self._reply(503, {"error": "resolution_refused"})+ return+ if options.fail_rate > 0 and random.random() < options.fail_rate:+ self._reply(503, {"error": "resolution_refused"})+ return+ try:+ parts = parse_resolve_request(self._json_body())+ except _TooLarge:+ self._reply(413, {"error": "request_too_large"})+ return+ except _BadRequest:+ self._reply(400, {"error": "malformed_request"})+ return+ self._reply(+ 200, resolve_response(parts, options.incomplete_redactions)+ )++ def do_GET(self) -> None:+ if self.server.transport == "https" and not self._authenticate():+ return+ self._reply(405, {"error": "method_not_allowed"})++ def _unsupported(self) -> None:+ if self.server.transport == "https" and not self._authenticate():+ return+ self._reply(405, {"error": "method_not_allowed"})++ do_CONNECT = do_DELETE = do_HEAD = do_OPTIONS = do_PATCH = do_PUT = do_TRACE = (+ _unsupported+ )+++def build_server(+ options: argparse.Namespace,+ *,+ transport: str,+ expected_token: str | None,+) -> http.server.HTTPServer:+ """Construct (but do not start) the resolver server for one transport."""+ if transport == "uds":+ if os.path.exists(options.uds):+ os.unlink(options.uds)+ server = _UnixHTTPServer(options.uds, _Handler)+ os.chmod(options.uds, 0o660)+ else:+ host, separator, port_text = options.https.rpartition(":")+ if not separator or not host or not port_text.isdigit():+ raise SystemExit("--https requires HOST:PORT")+ server = _TCPHTTPServer((host, int(port_text)), _Handler)+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ context.load_cert_chain(options.tls_cert, options.tls_key)+ server.socket = context.wrap_socket(server.socket, server_side=True)+ server.transport = transport+ server.expected_token = expected_token+ server.options = options+ server.request_timeout = max(30.0, options.delay / 1000.0 * 2 + 5.0)+ return server+++def serve(server: http.server.HTTPServer) -> None:+ if server.transport == "uds":+ endpoint = f"uds://{server.server_address}"+ else:+ host, port = server.server_address[:2]+ endpoint = f"https://{host}:{port}"+ print(f"test resolver ready: {endpoint}", file=sys.stderr, flush=True)+ try:+ server.serve_forever()+ except KeyboardInterrupt:+ pass+ finally:+ server_close()+ if server.transport == "uds":+ with contextlib.suppress(OSError):+ os.unlink(server.server_address)+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ transport = parser.add_mutually_exclusive_group(required=True)+ transport.add_argument("--uds", metavar="PATH", help="serve HTTP over this Unix socket")+ transport.add_argument(+ "--https", metavar="HOST:PORT", help="serve HTTPS on this address"+ )+ parser.add_argument("--tls-cert", metavar="PEM", help="TLS certificate (required with --https)")+ parser.add_argument("--tls-key", metavar="PEM", help="TLS private key (required with --https)")+ parser.add_argument(+ "--auth",+ metavar="TOKEN",+ help="expected caller bearer token; defaults to the entry for this "+ f"origin in {_AUTH_ENV}",+ )+ parser.add_argument("--delay", type=int, default=0, metavar="MS", help="sleep before every response")+ parser.add_argument(+ "--fail",+ default="",+ metavar="once|RATE",+ help="refuse resolutions once or at a random rate in [0,1]",+ )+ parser.add_argument(+ "--incomplete-redactions",+ action="store_true",+ help="return redactions for only one header (R9 auto-derivation tests)",+ )+ args = parser.parse_args(argv)+ if args.https and (not args.tls_cert or not args.tls_key):+ parser.error("--https requires --tls-cert and --tls-key")+ if args.fail:+ if args.fail == "once":+ args.fail_once = True+ args.fail_rate = 0.0+ else:+ try:+ rate = float(args.fail)+ except ValueError:+ parser.error("--fail accepts 'once' or a number in [0,1]")+ if not 0 <= rate <= 1:+ parser.error("--fail accepts 'once' or a number in [0,1]")+ args.fail_once = False+ args.fail_rate = rate+ else:+ args.fail_once = False+ args.fail_rate = 0.0+ return args+++def main(argv: list[str] | None = None) -> int:+ options = parse_args(argv)+ transport = "uds" if options.uds else "https"+ origin = f"https://{options.https}" if transport == "https" else None+ server = build_server(+ options,+ transport=transport,+ expected_token=(+ expected_token_for_origin(origin, options.auth)+ if transport == "https"+ else None+ ),+ )+ serve(server)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/components/egress/tests/resolver/test_resolver.py b/components/egress/tests/resolver/test_resolver.pynew file mode 100644index 000000000..34ff83e7b--- /dev/null+++ b/components/egress/tests/resolver/test_resolver.py@@ -0,0 +1,446 @@+# Copyright 2026 The OpenSandbox Authors+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Unit tests for the OSEP-0025 public test resolver stub."""++from __future__ import annotations++import hashlib+import http.client+import json+import os+import socket+import ssl+import tempfile+import threading+import time+import unittest+from pathlib import Path+from typing import Any++from resolver import resolver++FIXTURES = Path(__file__).resolve().parent / "fixtures"+CERT = FIXTURES / "test-localhost-cert.pem"+KEY = FIXTURES / "test-localhost-key.pem"++VALID_REQUEST: dict[str, Any] = {+ "subject": "sbx_01HZYEXAMPLE",+ "credential": "spi-signer",+ "binding": "internal-api",+ "destination": {+ "scheme": "https",+ "authority": "api.internal.example.com:443",+ "sni": "api.internal.example.com",+ },+ "request": {+ "method": "GET",+ "host": "api.internal.example.com",+ "path": "/v1/foo",+ "headers": {},+ },+}++RESOLVE_PATH = "/resolve"+++def expected_parts() -> dict[str, str]:+ return {+ "subject": VALID_REQUEST["subject"],+ "credential": VALID_REQUEST["credential"],+ "binding": VALID_REQUEST["binding"],+ "authority": VALID_REQUEST["destination"]["authority"],+ "path": VALID_REQUEST["request"]["path"],+ }+++def expected_signature(parts: dict[str, str]) -> str:+ source = "|".join(+ (+ parts["subject"],+ parts["credential"],+ parts["binding"],+ parts["authority"],+ parts["path"],+ )+ )+ return hashlib.sha256(source.encode()).hexdigest()+++def dumps(document: Any) -> bytes:+ return json.dumps(document).encode()+++class _UnixConnection(http.client.HTTPConnection):+ def __init__(self, path: str, timeout: float = 10) -> None:+ super().__init__("localhost", timeout=timeout)+ self._socket_path = path++ def connect(self) -> None:+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ sock.settimeout(self.timeout)+ sock.connect(self._socket_path)+ self.sock = sock+++class _ResolverProcess:+ """Run one resolver server instance in a background thread."""++ def __init__(self, server: Any) -> None:+ self.server = server+ self._thread = threading.Thread(target=server.serve_forever, daemon=True)++ def __enter__(self) -> "_ResolverProcess":+ self._thread.start()+ return self++ def __exit__(self, *_exc: object) -> None:+ self.server.shutdown()+ self.server.server_close()+++def build_uds_server(socket_path: str, argv: list[str] | None = None) -> Any:+ options = resolver.parse_args(["--uds", socket_path, *(argv or [])])+ return resolver.build_server(options, transport="uds", expected_token=None)+++def build_https_server(port: int, expected_token: str | None) -> Any:+ options = resolver.parse_args(+ [+ "--https", f"127.0.0.1:{port}",+ "--tls-cert", str(CERT),+ "--tls-key", str(KEY),+ ]+ )+ return resolver.build_server(options, transport="https", expected_token=expected_token)+++def free_port() -> int:+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++class ResolverUDSTest(unittest.TestCase):+ """UDS transport: dual-mode coverage, happy path, and IPC discipline."""++ def setUp(self) -> None:+ self._tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self._tmp.cleanup)+ self.socket_path = os.path.join(self._tmp.name, "resolver.sock")++ def post(self, body: bytes, headers: dict[str, str] | None = None,+ timeout: float = 10) -> tuple[int, bytes]:+ connection = _UnixConnection(self.socket_path, timeout=timeout)+ try:+ connection.request("POST", RESOLVE_PATH, body=body, headers={+ "Content-Type": "application/json",+ **(headers or {}),+ })+ response = connection.getresponse()+ return response.status, response.read()+ finally:+ connection.close()++ def test_happy_path_returns_deterministic_signature_and_redactions(self) -> None:+ with _ResolverProcess(build_uds_server(self.socket_path)):+ status, payload = self.post(dumps(VALID_REQUEST))++ self.assertEqual(200, status)+ parts = expected_parts()+ signature = expected_signature(parts)+ document = json.loads(payload)+ self.assertEqual(+ {+ "headers": {+ "authorization": "Bearer test-spi-signer",+ "x-test-signature": signature,+ "x-test-subject": "sbx_01HZYEXAMPLE",+ },+ "redactions": {+ "authorization": ["Bearer test-spi-signer"],+ "x-test-signature": [signature],+ "x-test-subject": ["sbx_01HZYEXAMPLE"],+ },+ },+ document,+ )+ # D15: the subject asserted by the signature stub is the egress+ # sandboxId, mirrored verbatim into x-test-subject.+ self.assertEqual(+ VALID_REQUEST["subject"], document["headers"]["x-test-subject"]+ )++ def test_signature_tracks_sandbox_id_and_destination(self) -> None:+ with _ResolverProcess(build_uds_server(self.socket_path)):+ _, first = self.post(dumps(VALID_REQUEST))+ changed = {**VALID_REQUEST, "subject": "sbx_01HZYOTHER"}+ _, second = self.post(dumps(changed))++ first_headers = json.loads(first)["headers"]+ second_headers = json.loads(second)["headers"]+ self.assertEqual("sbx_01HZYOTHER", second_headers["x-test-subject"])+ self.assertNotEqual(+ first_headers["x-test-signature"], second_headers["x-test-signature"]+ )++ def test_fixed_service_path_rejects_other_paths_with_404(self) -> None:+ connection = _UnixConnection(self.socket_path)+ with _ResolverProcess(build_uds_server(self.socket_path)):+ for path in ("/", "/resolve/", "/v1/resolve"):+ connection.request("POST", path, body=dumps(VALID_REQUEST), headers={+ "Content-Type": "application/json",+ })+ response = connection.getresponse()+ status = response.status+ response.read()+ self.assertEqual(404, status, path)+ connection.close()++ def test_uds_mode_ignores_host_header(self) -> None:+ connection = _UnixConnection(self.socket_path)+ with _ResolverProcess(build_uds_server(self.socket_path)):+ connection.request(+ "POST",+ RESOLVE_PATH,+ body=dumps(VALID_REQUEST),+ headers={+ "Content-Type": "application/json",+ "Host": "attacker.example.com",+ },+ )+ response = connection.getresponse()+ status = response.status+ response.read()+ connection.close()+ self.assertEqual(200, status)++ def test_uds_mode_does_not_require_authorization(self) -> None:+ with _ResolverProcess(build_uds_server(self.socket_path)):+ status, _ = self.post(+ dumps(VALID_REQUEST), {"Authorization": "Bearer anything"}+ )+ self.assertEqual(200, status)++ def test_socket_permissions_are_owner_and_group_only(self) -> None:+ with _ResolverProcess(build_uds_server(self.socket_path)):+ mode = os.stat(self.socket_path).st_mode & 0o777+ self.assertEqual(0o660, mode)++ def test_protocol_discipline_failures(self) -> None:+ base = dict(VALID_REQUEST)+ duplicate = dumps(VALID_REQUEST).replace(+ b'"subject": "sbx_01HZYEXAMPLE",',+ b'"subject": "sbx_01HZYEXAMPLE", "subject": "sbx_01HZYEXAMPLE",',+ 1,+ )+ cases = {+ "duplicate-key": (duplicate, {}),+ "wrong-content-type": (dumps(base), {"Content-Type": "text/plain"}),+ "not-json": (b"{not json", {}),+ "empty-body": (b"", {}),+ "array-body": (b"[]", {}),+ "unknown-field": (dumps({**base, "extra": 1}), {}),+ "missing-destination-key": (dumps(+ {**base, "destination": {"scheme": "https", "authority": "a:443"}}+ ), {}),+ "bad-scheme": (dumps(+ {**base, "destination": {**base["destination"], "scheme": "ftp"}}+ ), {}),+ "empty-subject": (dumps({**base, "subject": ""}), {}),+ "path-not-rooted": (dumps(+ {**base, "request": {**base["request"], "path": "v1/foo"}}+ ), {}),+ "non-string-header-value": (dumps(+ {**base, "request": {**base["request"], "headers": {"x-a": 3}}}+ ), {}),+ }+ with _ResolverProcess(build_uds_server(self.socket_path)):+ for name, (body, extra_headers) in cases.items():+ with self.subTest(name=name):+ status, payload = self.post(body, extra_headers)+ self.assertEqual(400, status, payload)++ def test_oversized_body_rejected_with_413(self) -> None:+ with _ResolverProcess(build_uds_server(self.socket_path)):+ status, _ = self.post(b"x" * (resolver.MAX_REQUEST_BYTES + 1))+ self.assertEqual(413, status)++ def test_get_rejected_with_405(self) -> None:+ connection = _UnixConnection(self.socket_path)+ with _ResolverProcess(build_uds_server(self.socket_path)):+ connection.request("GET", RESOLVE_PATH)+ response = connection.getresponse()+ status = response.status+ response.read()+ connection.close()+ self.assertEqual(405, status)+++class ResolverHTTPSTest(unittest.TestCase):+ """HTTPS transport: Bearer caller authentication, fail closed."""++ def setUp(self) -> None:+ self._original_auth = os.environ.get(resolver._AUTH_ENV)+ os.environ.pop(resolver._AUTH_ENV, None)+ self.addCleanup(self._restore_auth)+ self.port = free_port()+ self.context = ssl.create_default_context(cafile=str(CERT))++ def _restore_auth(self) -> None:+ if self._original_auth is None:+ os.environ.pop(resolver._AUTH_ENV, None)+ else:+ os.environ[resolver._AUTH_ENV] = self._original_auth++ def post(self, body: bytes, headers: dict[str, str] | None = None,+ timeout: float = 10) -> tuple[int, bytes]:+ connection = http.client.HTTPSConnection(+ "127.0.0.1", self.port, context=self.context, timeout=timeout+ )+ try:+ connection.request("POST", RESOLVE_PATH, body=body, headers={+ "Content-Type": "application/json",+ **(headers or {}),+ })+ response = connection.getresponse()+ return response.status, response.read()+ finally:+ connection.close()++ def test_happy_path_with_configured_token(self) -> None:+ server = build_https_server(self.port, "caller-secret")+ with _ResolverProcess(server):+ status, _ = self.post(+ dumps(VALID_REQUEST), {"Authorization": "Bearer caller-secret"}+ )+ self.assertEqual(200, status)++ def test_wrong_token_rejected_with_401(self) -> None:+ server = build_https_server(self.port, "caller-secret")+ with _ResolverProcess(server):+ status, _ = self.post(+ dumps(VALID_REQUEST), {"Authorization": "Bearer wrong"}+ )+ self.assertEqual(401, status)++ def test_missing_authorization_rejected_with_401(self) -> None:+ server = build_https_server(self.port, "caller-secret")+ with _ResolverProcess(server):+ status, _ = self.post(dumps(VALID_REQUEST))+ self.assertEqual(401, status)++ def test_unconfigured_origin_fails_closed_with_401(self) -> None:+ server = build_https_server(self.port, None)+ with _ResolverProcess(server):+ authorized, _ = self.post(+ dumps(VALID_REQUEST), {"Authorization": "Bearer anything"}+ )+ anonymous, _ = self.post(dumps(VALID_REQUEST))+ self.assertEqual(401, authorized)+ self.assertEqual(401, anonymous)++ def test_token_lookup_from_egress_auth_environment(self) -> None:+ origin = f"https://127.0.0.1:{self.port}"+ os.environ[resolver._AUTH_ENV] = f"{origin}=env-token,https://other=unused"+ token = resolver.expected_token_for_origin(origin, None)+ self.assertEqual("env-token", token)+ server = build_https_server(self.port, token)+ with _ResolverProcess(server):+ status, _ = self.post(+ dumps(VALID_REQUEST), {"Authorization": "Bearer env-token"}+ )+ self.assertEqual(200, status)++ def test_authorization_override_wins_over_environment(self) -> None:+ os.environ[resolver._AUTH_ENV] = f"https://127.0.0.1:{self.port}=env-token"+ self.assertEqual(+ "override", resolver.expected_token_for_origin("https://x", "override")+ )+++class ResolverFaultInjectionTest(unittest.TestCase):+ def setUp(self) -> None:+ self._tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self._tmp.cleanup)+ self.socket_path = os.path.join(self._tmp.name, "resolver.sock")++ def _post(self, timeout: float = 10) -> tuple[int, bytes]:+ connection = _UnixConnection(self.socket_path, timeout=timeout)+ try:+ connection.request("POST", RESOLVE_PATH, body=dumps(VALID_REQUEST), headers={+ "Content-Type": "application/json",+ })+ response = connection.getresponse()+ return response.status, response.read()+ finally:+ connection.close()++ def test_fail_once_refuses_first_resolution_then_serves(self) -> None:+ server = build_uds_server(self.socket_path, ["--fail", "once"])+ with _ResolverProcess(server):+ first, _ = self._post()+ second, _ = self._post()+ self.assertEqual(503, first)+ self.assertEqual(200, second)++ def test_fail_rate_full_always_refuses(self) -> None:+ server = build_uds_server(self.socket_path, ["--fail", "1.0"])+ with _ResolverProcess(server):+ for _ in range(3):+ status, _ = self._post()+ self.assertEqual(503, status)++ def test_incomplete_redactions_returns_single_entry(self) -> None:+ server = build_uds_server(self.socket_path, ["--incomplete-redactions"])+ with _ResolverProcess(server):+ status, payload = self._post()+ document = json.loads(payload)+ self.assertEqual(200, status)+ self.assertEqual(+ {"authorization": ["Bearer test-spi-signer"]}, document["redactions"]+ )+ self.assertEqual(3, len(document["headers"]))++ def test_delay_exceeds_client_timeout(self) -> None:+ server = build_uds_server(self.socket_path, ["--delay", "1000"])+ with _ResolverProcess(server):+ started = time.monotonic()+ with self.assertRaises((TimeoutError, OSError)):+ self._post(timeout=0.2)+ self.assertLess(time.monotonic() - started, 1.0)+++class ResolveRequestValidationTest(unittest.TestCase):+ def test_parse_accepts_populated_header_map(self) -> None:+ payload = {+ **VALID_REQUEST,+ "request": {+ **VALID_REQUEST["request"],+ "headers": {"accept": "application/json"},+ },+ }+ parts = resolver.parse_resolve_request(payload)+ self.assertEqual("sbx_01HZYEXAMPLE", parts["subject"])++ def test_resolve_response_is_deterministic(self) -> None:+ parts = expected_parts()+ self.assertEqual(+ resolver.resolve_response(parts, False),+ resolver.resolve_response(parts, False),+ )+++if __name__ == "__main__":+ unittest.main()