From 31787372b3e509bfd6191fe8e8d566bc2dcd5fde Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Tue, 25 Aug 2026 20:03:46 -0700 Subject: [PATCH 01/26] feat(security): add source-bound LLM egress firewall --- agent/llm_egress_firewall.py | 447 ++++++++++++++++++++++++ tests/agent/test_llm_egress_firewall.py | 266 ++++++++++++++ 2 files changed, 713 insertions(+) create mode 100644 agent/llm_egress_firewall.py create mode 100644 tests/agent/test_llm_egress_firewall.py diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py new file mode 100644 index 0000000000000..4ecda11c37fef --- /dev/null +++ b/agent/llm_egress_firewall.py @@ -0,0 +1,447 @@ +"""Source-bound policy checks for outbound LLM requests. + +The firewall is deliberately transport-agnostic. Callers hand it the final +logical request and resolved route immediately before invoking a provider. +It returns an immutable allow decision, or raises :class:`EgressBlocked` with +an immutable block decision. +""" + +from __future__ import annotations + +import fcntl +import ipaddress +import json +import os +import re +from dataclasses import asdict, dataclass, replace +from enum import StrEnum +from hashlib import sha256 +from pathlib import Path +from typing import Any, Mapping, Sequence +from urllib.parse import urlsplit + +from agent.file_safety import get_read_block_error +from agent.redact import redact_sensitive_text + + +class DestinationClass(StrEnum): + """Trust class for an LLM destination.""" + + LOCAL_PROCESS = "local_process" + LOOPBACK = "loopback" + REMOTE = "remote" + UNKNOWN = "unknown" + + +@dataclass(frozen=True, slots=True) +class SourceGrant: + """Immutable authorization for one exact, already-read file slice.""" + + canonical_path: Path + display_path: str + line_start: int + line_end: int + content_sha256: str + byte_count: int + session_id: str + turn_id: str + request_id: str + policy_digest: str + + +@dataclass(frozen=True, slots=True) +class EgressDecision: + """Content-free result of one egress preflight.""" + + allowed: bool + destination_class: DestinationClass + provider: str + model: str + payload_sha256: str + serialized_bytes: int + estimated_tokens: int + source_grant_count: int + session_id: str + turn_id: str + request_id: str + policy_digest: str + reason_codes: tuple[str, ...] = () + + +class EgressBlocked(RuntimeError): + """Raised when the final request is not authorized for its destination.""" + + def __init__(self, decision: EgressDecision): + self.decision = decision + reasons = ",".join(decision.reason_codes) or "policy_denied" + super().__init__(f"LLM egress blocked: {reasons}") + + +_SAFE_ID = re.compile(r"^[A-Za-z0-9_.:@/-]{0,256}$") +_LOCAL_PROCESS_MODES = frozenset({"local_process", "in_process"}) + + +def classify_destination( + provider: str, + base_url: str | None, + api_mode: str | None, +) -> DestinationClass: + """Classify without DNS, provider-name, or private-network trust. + + Only an explicit in-process mode or a numeric loopback literal is local. + LAN, Tailscale, container DNS, ``localhost``, and other hostnames retain + remote policy. Missing or malformed endpoint data is unknown. + """ + + del provider # Provider labels are not a security boundary. + mode = str(api_mode or "").strip().lower() + if mode in _LOCAL_PROCESS_MODES: + return DestinationClass.LOCAL_PROCESS + if not isinstance(base_url, str) or not base_url.strip(): + return DestinationClass.UNKNOWN + try: + parsed = urlsplit(base_url.strip()) + if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc: + return DestinationClass.UNKNOWN + host = parsed.hostname + if not host: + return DestinationClass.UNKNOWN + try: + address = ipaddress.ip_address(host) + except ValueError: + return DestinationClass.REMOTE + return DestinationClass.LOOPBACK if address.is_loopback else DestinationClass.REMOTE + except (TypeError, ValueError): + return DestinationClass.UNKNOWN + + +def _route_value(route: Any, name: str, default: Any = None) -> Any: + if isinstance(route, Mapping): + return route.get(name, default) + return getattr(route, name, default) + + +def _request_identity(request: Mapping[str, Any], name: str) -> str: + value = request.get(name, "") + return value if isinstance(value, str) else str(value) + + +def _receipt_identifier(value: str) -> str: + """Keep ordinary correlation IDs while hashing unsafe or sensitive labels.""" + + try: + safe = ( + _SAFE_ID.fullmatch(value) is not None + and not value.startswith(("/", "~")) + and redact_sensitive_text( + value, + force=True, + redact_url_credentials=True, + ) + == value + ) + except Exception: + safe = False + return value if safe else f"sha256:{sha256(value.encode('utf-8')).hexdigest()}" + + +def _contains_secret(value: Any, *, seen: set[int] | None = None) -> bool: + """Apply forced redaction semantics independently to every request string.""" + + if isinstance(value, str): + return redact_sensitive_text( + value, + force=True, + redact_url_credentials=True, + ) != value + if isinstance(value, (bytes, bytearray, memoryview)): + # Binary request material is not safely inspectable as text. + return True + if seen is None: + seen = set() + if isinstance(value, Mapping): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any( + _contains_secret(key, seen=seen) or _contains_secret(item, seen=seen) + for key, item in value.items() + ) + if isinstance(value, (list, tuple, set, frozenset)): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any(_contains_secret(item, seen=seen) for item in value) + return False + + +class LLMEgressFirewall: + """Validate a final LLM request and record a content-free receipt.""" + + def __init__( + self, + state_dir: Path | str, + *, + max_serialized_bytes: int = 262_144, + max_conservative_tokens: int = 87_382, + conservative_chars_per_token: int = 3, + ) -> None: + if max_serialized_bytes <= 0: + raise ValueError("max_serialized_bytes must be positive") + if max_conservative_tokens <= 0: + raise ValueError("max_conservative_tokens must be positive") + if conservative_chars_per_token <= 0: + raise ValueError("conservative_chars_per_token must be positive") + self._state_dir = Path(state_dir) + self._receipt_path = self._state_dir / "llm-egress-receipts.jsonl" + self._max_serialized_bytes = max_serialized_bytes + self._max_conservative_tokens = max_conservative_tokens + self._conservative_chars_per_token = conservative_chars_per_token + + def preflight( + self, + request: Mapping[str, Any], + route: Any, + *, + grants: Sequence[SourceGrant] = (), + ) -> EgressDecision: + """Authorize one final request or raise a typed, fail-closed result.""" + + provider = str(_route_value(route, "provider", "")) + model = str(_route_value(route, "model", "")) + destination = classify_destination( + provider, + _route_value(route, "base_url"), + _route_value(route, "api_mode"), + ) + session_id = _request_identity(request, "session_id") + turn_id = _request_identity(request, "turn_id") + request_id = _request_identity(request, "request_id") + policy_digest = _request_identity(request, "policy_digest") + + try: + serialized = json.dumps( + request, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + except (TypeError, ValueError, OverflowError): + decision = EgressDecision( + allowed=False, + destination_class=destination, + provider=provider, + model=model, + payload_sha256="", + serialized_bytes=0, + estimated_tokens=0, + source_grant_count=0, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + reason_codes=("serialization_failed",), + ) + self._block(decision) + + serialized_bytes = len(serialized) + estimated_tokens = ( + serialized_bytes + self._conservative_chars_per_token - 1 + ) // self._conservative_chars_per_token + reasons: list[str] = [] + valid_grants: list[SourceGrant] = [] + + if destination == DestinationClass.UNKNOWN: + reasons.append("unknown_destination") + if serialized_bytes > self._max_serialized_bytes: + reasons.append("serialized_bytes_exceeded") + if estimated_tokens > self._max_conservative_tokens: + reasons.append("token_cap_exceeded") + + if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN}: + try: + if _contains_secret(request): + reasons.append("secret_detected") + except Exception: + reasons.append("redaction_failed") + + if destination == DestinationClass.REMOTE: + grant_reasons, valid_grants = self._validate_grants( + grants, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + ) + reasons.extend(grant_reasons) + + decision = EgressDecision( + allowed=not reasons, + destination_class=destination, + provider=provider, + model=model, + payload_sha256=sha256(serialized).hexdigest(), + serialized_bytes=serialized_bytes, + estimated_tokens=estimated_tokens, + source_grant_count=len(valid_grants), + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + reason_codes=tuple(dict.fromkeys(reasons)), + ) + if not decision.allowed: + self._block(decision, valid_grants) + + try: + self._append_receipt(decision, valid_grants) + except OSError: + raise EgressBlocked( + replace(decision, allowed=False, reason_codes=("receipt_unavailable",)) + ) from None + return decision + + def _validate_grants( + self, + grants: Sequence[SourceGrant], + *, + session_id: str, + turn_id: str, + request_id: str, + policy_digest: str, + ) -> tuple[list[str], list[SourceGrant]]: + reasons: list[str] = [] + valid: list[SourceGrant] = [] + if not grants: + return ["untrusted_provenance"], valid + + for candidate in grants: + if not isinstance(candidate, SourceGrant): + reasons.append("untrusted_provenance") + continue + grant = candidate + if ( + grant.session_id != session_id + or grant.turn_id != turn_id + or grant.request_id != request_id + or grant.policy_digest != policy_digest + ): + reasons.append("grant_binding_mismatch") + continue + if ( + grant.line_start < 1 + or grant.line_end < grant.line_start + or grant.byte_count < 0 + or not re.fullmatch(r"[0-9a-f]{64}", grant.content_sha256) + ): + reasons.append("invalid_source_grant") + continue + display = Path(grant.display_path) + if display.is_absolute() or ".." in display.parts: + reasons.append("invalid_display_path") + continue + try: + canonical = Path(grant.canonical_path) + resolved = canonical.resolve(strict=True) + except (OSError, RuntimeError, ValueError, TypeError): + reasons.append("source_unavailable") + continue + if not canonical.is_absolute() or canonical != resolved: + reasons.append("source_path_not_canonical") + continue + try: + blocked = get_read_block_error(str(resolved)) + except Exception: + reasons.append("source_policy_unavailable") + continue + if blocked is not None: + reasons.append("sensitive_path") + continue + try: + lines = resolved.read_bytes().splitlines(keepends=True) + except OSError: + reasons.append("source_unavailable") + continue + if grant.line_end > len(lines): + reasons.append("source_range_mismatch") + continue + content = b"".join(lines[grant.line_start - 1 : grant.line_end]) + if len(content) != grant.byte_count or sha256(content).hexdigest() != grant.content_sha256: + reasons.append("source_hash_mismatch") + continue + valid.append(grant) + + if not valid and "untrusted_provenance" not in reasons: + reasons.append("untrusted_provenance") + return reasons, valid + + def _block( + self, + decision: EgressDecision, + grants: Sequence[SourceGrant] = (), + ) -> None: + try: + self._append_receipt(decision, grants) + except OSError: + decision = replace( + decision, + reason_codes=tuple(dict.fromkeys((*decision.reason_codes, "receipt_unavailable"))), + ) + raise EgressBlocked(decision) + + def _append_receipt( + self, + decision: EgressDecision, + grants: Sequence[SourceGrant], + ) -> None: + self._state_dir.mkdir(parents=True, exist_ok=True, mode=0o700) + receipt = asdict(decision) + receipt["destination_class"] = decision.destination_class.value + receipt["decision"] = "allow" if decision.allowed else "block" + for field in ( + "provider", + "model", + "session_id", + "turn_id", + "request_id", + "policy_digest", + ): + receipt[field] = _receipt_identifier(receipt[field]) + receipt["source_grants"] = [ + { + "line_start": grant.line_start, + "line_end": grant.line_end, + "content_sha256": grant.content_sha256, + "byte_count": grant.byte_count, + } + for grant in grants + ] + encoded = ( + json.dumps(receipt, ensure_ascii=True, separators=(",", ":"), sort_keys=True) + "\n" + ).encode("utf-8") + flags = os.O_APPEND | os.O_CREAT | os.O_WRONLY + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + fd = os.open(self._receipt_path, flags, 0o600) + try: + os.fchmod(fd, 0o600) + fcntl.flock(fd, fcntl.LOCK_EX) + if os.write(fd, encoded) != len(encoded): + raise OSError("short receipt write") + finally: + try: + fcntl.flock(fd, fcntl.LOCK_UN) + finally: + os.close(fd) + + +__all__ = [ + "DestinationClass", + "EgressBlocked", + "EgressDecision", + "LLMEgressFirewall", + "SourceGrant", + "classify_destination", +] diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py new file mode 100644 index 0000000000000..27dc3a18285b4 --- /dev/null +++ b/tests/agent/test_llm_egress_firewall.py @@ -0,0 +1,266 @@ +"""Focused contract tests for the source-bound LLM egress firewall.""" + +from __future__ import annotations + +import json +import os +import stat +from concurrent.futures import ThreadPoolExecutor +from dataclasses import FrozenInstanceError +from hashlib import sha256 +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from agent.llm_egress_firewall import ( + DestinationClass, + EgressBlocked, + LLMEgressFirewall, + SourceGrant, + classify_destination, +) + + +def _route(**overrides): + values = {"provider": "custom", "model": "test-model", "base_url": "https://llm.example.test/v1", "api_mode": None} + values.update(overrides) + return SimpleNamespace(**values) + + +def _source_grant(path: Path, *, request_id: str = "req-1", start: int = 1, end: int = 1): + content = path.read_bytes().splitlines(keepends=True)[start - 1 : end] + payload = b"".join(content) + return SourceGrant( + canonical_path=path.resolve(), + display_path="src/private.py", + line_start=start, + line_end=end, + content_sha256=sha256(payload).hexdigest(), + byte_count=len(payload), + session_id="session-1", + turn_id="turn-1", + request_id=request_id, + policy_digest="policy-1", + ) + + +def _request(payload: str = "ordinary prompt"): + return { + "messages": [{"role": "user", "content": payload}], + "session_id": "session-1", + "turn_id": "turn-1", + "request_id": "req-1", + "policy_digest": "policy-1", + } + + +def firewall(tmp_path: Path, **kwargs) -> LLMEgressFirewall: + return LLMEgressFirewall(tmp_path, **kwargs) + + +def test_lan_and_unknown_are_remote_while_numeric_loopback_is_loopback(): + assert classify_destination("ollama", "http://127.0.0.1:11434", None).value == "loopback" + assert classify_destination("custom", "http://192.168.1.9:8000", None).value == "remote" + assert classify_destination("custom", None, None).value == "unknown" + + +def test_destination_classification_does_not_trust_dns_or_provider_name(): + assert classify_destination("ollama", "http://localhost:11434", None) in { + DestinationClass.REMOTE, + DestinationClass.UNKNOWN, + } + assert classify_destination("ollama", "http://ollama:11434", None) == DestinationClass.REMOTE + assert classify_destination("custom", "not-a-url", None) == DestinationClass.UNKNOWN + assert classify_destination("custom", "http://[::1]:8000", None) == DestinationClass.LOOPBACK + assert classify_destination("custom", "http://100.64.0.1:8000", None) == DestinationClass.REMOTE + + +def test_explicit_in_process_api_mode_is_local_process(): + assert classify_destination("custom", None, "local_process") == DestinationClass.LOCAL_PROCESS + assert classify_destination("custom", None, "in_process") == DestinationClass.LOCAL_PROCESS + + +def test_source_grant_is_immutable_and_has_the_required_binding_fields(tmp_path): + path = tmp_path / "private.py" + path.write_text("private source\n", encoding="utf-8") + grant = _source_grant(path) + with pytest.raises(FrozenInstanceError): + grant.request_id = "forged" # type: ignore[misc] + assert grant.canonical_path == path.resolve() + assert grant.line_start == 1 and grant.line_end == 1 + assert grant.byte_count == len(b"private source\n") + + +def test_loopback_request_is_allowed_without_source_grant(tmp_path): + decision = firewall(tmp_path).preflight(_request("local prompt"), _route(base_url="http://127.0.0.1:11434")) + assert decision.allowed is True + assert decision.destination_class == DestinationClass.LOOPBACK + + +def test_remote_request_requires_an_exact_source_grant(tmp_path): + path = tmp_path / "private.py" + path.write_text("private source\npublic source\n", encoding="utf-8") + grant = _source_grant(path) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(_request("private source"), _route(), grants=()) + assert "untrusted_provenance" in exc_info.value.decision.reason_codes + + decision = firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + assert decision.allowed is True + + +def test_modified_source_and_adjacent_slice_are_denied(tmp_path): + path = tmp_path / "private.py" + path.write_text("private source\nneighbor\n", encoding="utf-8") + grant = _source_grant(path) + path.write_text("changed source\nneighbor\n", encoding="utf-8") + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + assert "source_hash_mismatch" in exc_info.value.decision.reason_codes + + +def test_sensitive_path_and_forged_grant_fail_closed(tmp_path, monkeypatch): + path = tmp_path / ".env" + path.write_text("API_KEY=sk-test-secret\n", encoding="utf-8") + grant = _source_grant(path) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + assert "sensitive_path" in exc_info.value.decision.reason_codes + + missing = tmp_path / "missing.py" + forged = SourceGrant( + canonical_path=missing, + display_path="src/private.py", + line_start=1, + line_end=1, + content_sha256=sha256(b"private source\n").hexdigest(), + byte_count=len(b"private source\n"), + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + with pytest.raises(EgressBlocked) as missing_exc: + firewall(tmp_path).preflight(_request("private source"), _route(), grants=(forged,)) + assert "source_unavailable" in missing_exc.value.decision.reason_codes + + +def test_forced_secret_redaction_rejects_instead_of_rewriting(tmp_path): + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(_request("token=super-secret-value"), _route(), grants=(object(),)) + assert "secret_detected" in exc_info.value.decision.reason_codes + + +def test_scanner_error_fails_closed(monkeypatch, tmp_path): + def explode(*args, **kwargs): + raise RuntimeError("scanner unavailable") + + monkeypatch.setattr("agent.llm_egress_firewall.redact_sensitive_text", explode) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(_request(), _route(), grants=(object(),)) + assert "redaction_failed" in exc_info.value.decision.reason_codes + + +def test_byte_and_token_caps_fail_closed(tmp_path): + with pytest.raises(EgressBlocked) as bytes_exc: + firewall(tmp_path, max_serialized_bytes=32).preflight(_request(), _route(), grants=(object(),)) + assert "serialized_bytes_exceeded" in bytes_exc.value.decision.reason_codes + + with pytest.raises(EgressBlocked) as token_exc: + firewall(tmp_path, max_serialized_bytes=100_000, max_conservative_tokens=2).preflight( + _request("ordinary prompt"), _route(), grants=(object(),) + ) + assert "token_cap_exceeded" in token_exc.value.decision.reason_codes + + +def test_byte_and_token_caps_allow_the_exact_boundary(tmp_path): + request = _request("boundary prompt") + serialized = json.dumps( + request, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + token_count = (len(serialized) + 2) // 3 + decision = firewall( + tmp_path, + max_serialized_bytes=len(serialized), + max_conservative_tokens=token_count, + ).preflight(request, _route(base_url="http://127.0.0.1:11434")) + assert decision.allowed is True + + +def test_allow_receipt_contains_hashes_and_counts_but_no_payload(tmp_path): + path = tmp_path / "private.py" + path.write_text("private source\n", encoding="utf-8") + grant = _source_grant(path) + decision = firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + receipt = json.loads((tmp_path / "llm-egress-receipts.jsonl").read_text().splitlines()[0]) + assert receipt["payload_sha256"] == decision.payload_sha256 + assert receipt["serialized_bytes"] == decision.serialized_bytes + assert receipt["estimated_tokens"] == decision.estimated_tokens + assert receipt["source_grants"][0]["content_sha256"] == grant.content_sha256 + assert "private source" not in json.dumps(receipt) + assert "canonical_path" not in receipt["source_grants"][0] + + +def test_receipt_hashes_unsafe_identity_and_route_labels(tmp_path): + secret_request_id = "sk-proj-abc123def456ghi789jkl012" + private_model_label = str(Path.home() / "private-model") + with pytest.raises(EgressBlocked): + firewall(tmp_path).preflight( + {**_request(), "request_id": secret_request_id}, + _route(model=private_model_label), + grants=(object(),), + ) + receipt_text = (tmp_path / "llm-egress-receipts.jsonl").read_text() + assert secret_request_id not in receipt_text + assert str(Path.home()) not in receipt_text + + +def test_receipt_is_owner_only_and_rejects_symlink_ledger(tmp_path): + path = tmp_path / "private.py" + path.write_text("private source\n", encoding="utf-8") + grant = _source_grant(path) + ledger = tmp_path / "llm-egress-receipts.jsonl" + firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + assert stat.S_IMODE(ledger.stat().st_mode) == 0o600 + + ledger.unlink() + target = tmp_path / "outside.jsonl" + target.write_text("", encoding="utf-8") + ledger.symlink_to(target) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + assert "receipt_unavailable" in exc_info.value.decision.reason_codes + + +def test_concurrent_receipt_appends_remain_complete_json_lines(tmp_path): + gate = firewall(tmp_path) + + def append(index: int) -> None: + gate.preflight( + {**_request(f"local prompt {index}"), "request_id": f"req-{index}"}, + _route(base_url="http://127.0.0.1:11434"), + ) + + with ThreadPoolExecutor(max_workers=8) as executor: + tuple(executor.map(append, range(32))) + + lines = (tmp_path / "llm-egress-receipts.jsonl").read_text().splitlines() + receipts = [json.loads(line) for line in lines] + assert len(receipts) == 32 + assert {receipt["request_id"] for receipt in receipts} == { + f"req-{index}" for index in range(32) + } + + +def test_unknown_destination_fails_closed_even_with_source_grant(tmp_path): + path = tmp_path / "private.py" + path.write_text("private source\n", encoding="utf-8") + grant = _source_grant(path) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(_request("private source"), _route(base_url=None), grants=(grant,)) + assert exc_info.value.decision.destination_class == DestinationClass.UNKNOWN + assert "unknown_destination" in exc_info.value.decision.reason_codes From c2a5dc77f06dbc9f295ee90fb4619b89ef5dd10b Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Tue, 25 Aug 2026 20:12:49 -0700 Subject: [PATCH 02/26] fix(security): bind outbound source segments --- agent/llm_egress_firewall.py | 197 ++++++++++++++++++++++++ tests/agent/test_llm_egress_firewall.py | 139 ++++++++++++++++- 2 files changed, 328 insertions(+), 8 deletions(-) diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index 4ecda11c37fef..e06728afbf1cc 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -8,6 +8,8 @@ from __future__ import annotations +import base64 +import binascii import fcntl import ipaddress import json @@ -49,6 +51,17 @@ class SourceGrant: policy_digest: str +@dataclass(frozen=True, slots=True) +class SourceSegmentBinding: + """Bind exact byte offsets in the final request to one source grant.""" + + request_path: tuple[str | int, ...] + byte_start: int + byte_end: int + content_sha256: str + source_grant_digest: str + + @dataclass(frozen=True, slots=True) class EgressDecision: """Content-free result of one egress preflight.""" @@ -61,6 +74,7 @@ class EgressDecision: serialized_bytes: int estimated_tokens: int source_grant_count: int + source_segment_count: int session_id: str turn_id: str request_id: str @@ -79,6 +93,10 @@ def __init__(self, decision: EgressDecision): _SAFE_ID = re.compile(r"^[A-Za-z0-9_.:@/-]{0,256}$") _LOCAL_PROCESS_MODES = frozenset({"local_process", "in_process"}) +_BASE64_CANDIDATE = re.compile( + r"(? str: return value if safe else f"sha256:{sha256(value.encode('utf-8')).hexdigest()}" +def source_grant_digest(grant: SourceGrant) -> str: + """Return the opaque identity used by a source-segment manifest.""" + + bound_fields = { + "canonical_path": str(grant.canonical_path), + "display_path": grant.display_path, + "line_start": grant.line_start, + "line_end": grant.line_end, + "content_sha256": grant.content_sha256, + "byte_count": grant.byte_count, + "session_id": grant.session_id, + "turn_id": grant.turn_id, + "request_id": grant.request_id, + "policy_digest": grant.policy_digest, + } + encoded = json.dumps(bound_fields, separators=(",", ":"), sort_keys=True).encode("utf-8") + return sha256(encoded).hexdigest() + + +def _canonical_base64_candidate(candidate: str) -> bool: + """Recognize bounded canonical encodings without flagging ordinary IDs.""" + + if not 24 <= len(candidate) <= _MAX_BASE64_CANDIDATE_CHARS: + return False + if len(candidate) % 4 != 0: + return False + encoded = candidate.encode("ascii") + decoded_variants: list[bytes] = [] + for altchars in (None, b"-_"): + try: + decoded = base64.b64decode(encoded, altchars=altchars, validate=True) + except (binascii.Error, ValueError): + continue + canonical = ( + base64.b64encode(decoded) + if altchars is None + else base64.urlsafe_b64encode(decoded) + ) + if canonical == encoded: + decoded_variants.append(decoded) + + for decoded in decoded_variants: + if len(decoded) < 16: + continue + # Padding or alphabet-specific symbols are strong encoding markers. + if candidate.endswith("=") or any(char in candidate for char in "+/_-"): + return True + # Unpadded all-alphanumeric strings overlap hashes and opaque IDs. + # Require canonical decoding to readable structured text so those + # common values do not become false positives. + try: + decoded_text = decoded.decode("utf-8") + except UnicodeDecodeError: + continue + printable = sum(char.isprintable() or char in "\r\n\t" for char in decoded_text) + if printable / max(len(decoded_text), 1) >= 0.9 and any( + not char.isalnum() for char in decoded_text + ): + return True + return False + + +def _contains_canonical_base64(value: Any, *, seen: set[int] | None = None) -> bool: + if isinstance(value, str): + return any(_canonical_base64_candidate(match.group(1)) for match in _BASE64_CANDIDATE.finditer(value)) + if isinstance(value, (bytes, bytearray, memoryview)): + return True + if seen is None: + seen = set() + if isinstance(value, Mapping): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any( + _contains_canonical_base64(key, seen=seen) + or _contains_canonical_base64(item, seen=seen) + for key, item in value.items() + ) + if isinstance(value, (list, tuple, set, frozenset)): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any(_contains_canonical_base64(item, seen=seen) for item in value) + return False + + def _contains_secret(value: Any, *, seen: set[int] | None = None) -> bool: """Apply forced redaction semantics independently to every request string.""" @@ -206,6 +321,7 @@ def preflight( route: Any, *, grants: Sequence[SourceGrant] = (), + source_segments: Sequence[SourceSegmentBinding] = (), ) -> EgressDecision: """Authorize one final request or raise a typed, fail-closed result.""" @@ -238,6 +354,7 @@ def preflight( serialized_bytes=0, estimated_tokens=0, source_grant_count=0, + source_segment_count=0, session_id=session_id, turn_id=turn_id, request_id=request_id, @@ -266,6 +383,11 @@ def preflight( reasons.append("secret_detected") except Exception: reasons.append("redaction_failed") + try: + if _contains_canonical_base64(request): + reasons.append("base64_payload") + except Exception: + reasons.append("base64_scan_failed") if destination == DestinationClass.REMOTE: grant_reasons, valid_grants = self._validate_grants( @@ -276,6 +398,12 @@ def preflight( policy_digest=policy_digest, ) reasons.extend(grant_reasons) + segment_reasons = self._validate_source_segments( + request, + source_segments, + valid_grants, + ) + reasons.extend(segment_reasons) decision = EgressDecision( allowed=not reasons, @@ -286,6 +414,7 @@ def preflight( serialized_bytes=serialized_bytes, estimated_tokens=estimated_tokens, source_grant_count=len(valid_grants), + source_segment_count=len(source_segments), session_id=session_id, turn_id=turn_id, request_id=request_id, @@ -377,6 +506,72 @@ def _validate_grants( reasons.append("untrusted_provenance") return reasons, valid + def _validate_source_segments( + self, + request: Mapping[str, Any], + source_segments: Sequence[SourceSegmentBinding], + valid_grants: Sequence[SourceGrant], + ) -> list[str]: + if not valid_grants: + return [] + if not source_segments: + return ["source_grant_unbound"] + + reasons: list[str] = [] + grants_by_digest = {source_grant_digest(grant): grant for grant in valid_grants} + referenced_grants: set[str] = set() + + for binding in source_segments: + if not isinstance(binding, SourceSegmentBinding): + reasons.append("invalid_source_segment") + continue + grant = grants_by_digest.get(binding.source_grant_digest) + if grant is None: + reasons.append("source_segment_grant_mismatch") + continue + if ( + binding.byte_start < 0 + or binding.byte_end <= binding.byte_start + or not re.fullmatch(r"[0-9a-f]{64}", binding.content_sha256) + ): + reasons.append("invalid_source_segment") + continue + try: + current: Any = request + for component in binding.request_path: + if isinstance(component, str) and isinstance(current, Mapping): + current = current[component] + elif ( + isinstance(component, int) + and not isinstance(component, bool) + and isinstance(current, (list, tuple)) + ): + current = current[component] + else: + raise KeyError(component) + if not isinstance(current, str): + raise TypeError("source segment target is not text") + request_bytes = current.encode("utf-8") + segment = request_bytes[binding.byte_start : binding.byte_end] + except (IndexError, KeyError, TypeError, UnicodeError): + reasons.append("source_segment_unavailable") + continue + if binding.byte_end > len(request_bytes): + reasons.append("source_segment_range_mismatch") + continue + if ( + len(segment) != grant.byte_count + or sha256(segment).hexdigest() != binding.content_sha256 + or binding.content_sha256 != grant.content_sha256 + ): + reasons.append("source_segment_hash_mismatch") + continue + referenced_grants.add(binding.source_grant_digest) + + if set(grants_by_digest) - referenced_grants: + reasons.append("source_grant_unbound") + return reasons + def _block( self, decision: EgressDecision, @@ -443,5 +638,7 @@ def _append_receipt( "EgressDecision", "LLMEgressFirewall", "SourceGrant", + "SourceSegmentBinding", "classify_destination", + "source_grant_digest", ] diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index 27dc3a18285b4..b755649f90863 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -2,6 +2,7 @@ from __future__ import annotations +import base64 import json import os import stat @@ -18,7 +19,9 @@ EgressBlocked, LLMEgressFirewall, SourceGrant, + SourceSegmentBinding, classify_destination, + source_grant_digest, ) @@ -55,6 +58,18 @@ def _request(payload: str = "ordinary prompt"): } +def _source_binding(grant: SourceGrant, request, *, path=("messages", 0, "content")): + value = request["messages"][0]["content"] + encoded = value.encode("utf-8") + return SourceSegmentBinding( + request_path=path, + byte_start=0, + byte_end=len(encoded), + content_sha256=sha256(encoded).hexdigest(), + source_grant_digest=source_grant_digest(grant), + ) + + def firewall(tmp_path: Path, **kwargs) -> LLMEgressFirewall: return LLMEgressFirewall(tmp_path, **kwargs) @@ -76,6 +91,18 @@ def test_destination_classification_does_not_trust_dns_or_provider_name(): assert classify_destination("custom", "http://100.64.0.1:8000", None) == DestinationClass.REMOTE +@pytest.mark.parametrize( + "url", + [ + "http://127.0.0.1:99999", + "http://127.0.0.1:not-a-port", + "http://[::1]:99999", + ], +) +def test_malformed_loopback_ports_are_unknown(url): + assert classify_destination("custom", url, None) == DestinationClass.UNKNOWN + + def test_explicit_in_process_api_mode_is_local_process(): assert classify_destination("custom", None, "local_process") == DestinationClass.LOCAL_PROCESS assert classify_destination("custom", None, "in_process") == DestinationClass.LOCAL_PROCESS @@ -102,21 +129,63 @@ def test_remote_request_requires_an_exact_source_grant(tmp_path): path = tmp_path / "private.py" path.write_text("private source\npublic source\n", encoding="utf-8") grant = _source_grant(path) + request = _request("private source\n") with pytest.raises(EgressBlocked) as exc_info: - firewall(tmp_path).preflight(_request("private source"), _route(), grants=()) + firewall(tmp_path).preflight(request, _route(), grants=()) assert "untrusted_provenance" in exc_info.value.decision.reason_codes - decision = firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + decision = firewall(tmp_path).preflight( + request, + _route(), + grants=(grant,), + source_segments=(_source_binding(grant, request),), + ) assert decision.allowed is True +def test_unrelated_grant_and_incomplete_source_manifest_are_denied(tmp_path): + first = tmp_path / "first.py" + second = tmp_path / "second.py" + first.write_text("first source\n", encoding="utf-8") + second.write_text("second source\n", encoding="utf-8") + first_grant = _source_grant(first) + second_grant = _source_grant(second) + request = _request("first source\n") + first_binding = _source_binding(first_grant, request) + + with pytest.raises(EgressBlocked) as unrelated_exc: + firewall(tmp_path).preflight( + request, + _route(), + grants=(second_grant,), + source_segments=(_source_binding(second_grant, request),), + ) + assert "source_segment_hash_mismatch" in unrelated_exc.value.decision.reason_codes + + with pytest.raises(EgressBlocked) as incomplete_exc: + firewall(tmp_path).preflight( + request, + _route(), + grants=(first_grant, second_grant), + source_segments=(first_binding,), + ) + assert "source_grant_unbound" in incomplete_exc.value.decision.reason_codes + + def test_modified_source_and_adjacent_slice_are_denied(tmp_path): path = tmp_path / "private.py" path.write_text("private source\nneighbor\n", encoding="utf-8") grant = _source_grant(path) + request = _request("private source\n") + binding = _source_binding(grant, request) path.write_text("changed source\nneighbor\n", encoding="utf-8") with pytest.raises(EgressBlocked) as exc_info: - firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + firewall(tmp_path).preflight( + request, + _route(), + grants=(grant,), + source_segments=(binding,), + ) assert "source_hash_mismatch" in exc_info.value.decision.reason_codes @@ -124,8 +193,14 @@ def test_sensitive_path_and_forged_grant_fail_closed(tmp_path, monkeypatch): path = tmp_path / ".env" path.write_text("API_KEY=sk-test-secret\n", encoding="utf-8") grant = _source_grant(path) + sensitive_request = _request("API_KEY=sk-test-secret\n") with pytest.raises(EgressBlocked) as exc_info: - firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + firewall(tmp_path).preflight( + sensitive_request, + _route(), + grants=(grant,), + source_segments=(_source_binding(grant, sensitive_request),), + ) assert "sensitive_path" in exc_info.value.decision.reason_codes missing = tmp_path / "missing.py" @@ -141,8 +216,14 @@ def test_sensitive_path_and_forged_grant_fail_closed(tmp_path, monkeypatch): request_id="req-1", policy_digest="policy-1", ) + missing_request = _request("private source\n") with pytest.raises(EgressBlocked) as missing_exc: - firewall(tmp_path).preflight(_request("private source"), _route(), grants=(forged,)) + firewall(tmp_path).preflight( + missing_request, + _route(), + grants=(forged,), + source_segments=(_source_binding(forged, missing_request),), + ) assert "source_unavailable" in missing_exc.value.decision.reason_codes @@ -152,6 +233,30 @@ def test_forced_secret_redaction_rejects_instead_of_rewriting(tmp_path): assert "secret_detected" in exc_info.value.decision.reason_codes +@pytest.mark.parametrize( + "payload", + [ + base64.b64encode(b"sk-proj-abc123def456ghi789jkl012").decode("ascii"), + base64.urlsafe_b64encode(b"harmless text that is still encoded").decode("ascii"), + ], +) +def test_canonical_base64_payloads_are_rejected_even_when_decoded_content_is_benign( + tmp_path, + payload, +): + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(_request(payload), _route(), grants=(object(),)) + assert "base64_payload" in exc_info.value.decision.reason_codes + + +def test_ordinary_short_base64_alphabet_words_are_not_false_positives(tmp_path): + decision = firewall(tmp_path).preflight( + _request("ordinary short words remain usable"), + _route(base_url="http://127.0.0.1:11434"), + ) + assert "base64_payload" not in decision.reason_codes + + def test_scanner_error_fails_closed(monkeypatch, tmp_path): def explode(*args, **kwargs): raise RuntimeError("scanner unavailable") @@ -195,7 +300,13 @@ def test_allow_receipt_contains_hashes_and_counts_but_no_payload(tmp_path): path = tmp_path / "private.py" path.write_text("private source\n", encoding="utf-8") grant = _source_grant(path) - decision = firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + request = _request("private source\n") + decision = firewall(tmp_path).preflight( + request, + _route(), + grants=(grant,), + source_segments=(_source_binding(grant, request),), + ) receipt = json.loads((tmp_path / "llm-egress-receipts.jsonl").read_text().splitlines()[0]) assert receipt["payload_sha256"] == decision.payload_sha256 assert receipt["serialized_bytes"] == decision.serialized_bytes @@ -223,8 +334,15 @@ def test_receipt_is_owner_only_and_rejects_symlink_ledger(tmp_path): path = tmp_path / "private.py" path.write_text("private source\n", encoding="utf-8") grant = _source_grant(path) + request = _request("private source\n") + binding = _source_binding(grant, request) ledger = tmp_path / "llm-egress-receipts.jsonl" - firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + firewall(tmp_path).preflight( + request, + _route(), + grants=(grant,), + source_segments=(binding,), + ) assert stat.S_IMODE(ledger.stat().st_mode) == 0o600 ledger.unlink() @@ -232,7 +350,12 @@ def test_receipt_is_owner_only_and_rejects_symlink_ledger(tmp_path): target.write_text("", encoding="utf-8") ledger.symlink_to(target) with pytest.raises(EgressBlocked) as exc_info: - firewall(tmp_path).preflight(_request("private source"), _route(), grants=(grant,)) + firewall(tmp_path).preflight( + request, + _route(), + grants=(grant,), + source_segments=(binding,), + ) assert "receipt_unavailable" in exc_info.value.decision.reason_codes From d15fcbaa82f9e201af594de1daa547a0c06bdf74 Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Tue, 25 Aug 2026 20:24:57 -0700 Subject: [PATCH 03/26] fix(security): construct exact remote egress payloads --- agent/llm_egress_firewall.py | 380 +++++++++++++++--------- tests/agent/test_llm_egress_firewall.py | 170 ++++++++--- 2 files changed, 367 insertions(+), 183 deletions(-) diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index e06728afbf1cc..87ca5f1b2cd62 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -17,6 +17,7 @@ import re from dataclasses import asdict, dataclass, replace from enum import StrEnum +from hmac import compare_digest from hashlib import sha256 from pathlib import Path from typing import Any, Mapping, Sequence @@ -52,16 +53,44 @@ class SourceGrant: @dataclass(frozen=True, slots=True) -class SourceSegmentBinding: - """Bind exact byte offsets in the final request to one source grant.""" +class LiteralSegment: + """Application-owned literal text for a typed outbound request.""" + + text: str + + +@dataclass(frozen=True, slots=True) +class SanitizedSegment: + """Non-source text that must still pass final secret and encoding scans.""" + + text: str + + +@dataclass(frozen=True, slots=True) +class SourceBoundSegment: + """Opaque reference whose text is loaded only from a verified grant.""" - request_path: tuple[str | int, ...] - byte_start: int - byte_end: int - content_sha256: str source_grant_digest: str +@dataclass(frozen=True, slots=True) +class OutboundText: + """Ordered typed segments that construct one outbound JSON string.""" + + segments: tuple[LiteralSegment | SanitizedSegment | SourceBoundSegment, ...] + + +@dataclass(frozen=True, slots=True) +class TypedOutboundRequest: + """Remote request recipe; no independent raw string leaf is permitted.""" + + payload: Mapping[str, Any] + session_id: str + turn_id: str + request_id: str + policy_digest: str + + @dataclass(frozen=True, slots=True) class EgressDecision: """Content-free result of one egress preflight.""" @@ -91,10 +120,46 @@ def __init__(self, decision: EgressDecision): super().__init__(f"LLM egress blocked: {reasons}") +@dataclass(frozen=True, slots=True) +class AuthorizedEgress: + """Immutable exact bytes that a provider callback is authorized to send.""" + + decision: EgressDecision + payload_bytes: bytes + + @property + def allowed(self) -> bool: + return self.decision.allowed + + @property + def destination_class(self) -> DestinationClass: + return self.decision.destination_class + + @property + def reason_codes(self) -> tuple[str, ...]: + return self.decision.reason_codes + + def verify_payload(self, candidate: bytes) -> bytes: + """Return the authorized bytes or reject a post-preflight mutation.""" + + if not isinstance(candidate, bytes) or not compare_digest( + sha256(candidate).hexdigest(), + self.decision.payload_sha256, + ): + raise EgressBlocked( + replace( + self.decision, + allowed=False, + reason_codes=("payload_digest_mismatch",), + ) + ) + return self.payload_bytes + + _SAFE_ID = re.compile(r"^[A-Za-z0-9_.:@/-]{0,256}$") _LOCAL_PROCESS_MODES = frozenset({"local_process", "in_process"}) _BASE64_CANDIDATE = re.compile( - r"(? str: def _canonical_base64_candidate(candidate: str) -> bool: """Recognize bounded canonical encodings without flagging ordinary IDs.""" - if not 24 <= len(candidate) <= _MAX_BASE64_CANDIDATE_CHARS: + if not 6 <= len(candidate) <= _MAX_BASE64_CANDIDATE_CHARS: + return False + unpadded = candidate.rstrip("=") + if "=" in unpadded or len(unpadded) % 4 == 1: return False - if len(candidate) % 4 != 0: + # A strict round-trip alone cannot distinguish an ordinary alphabet-only + # word (for example ``ordinary``) from unpadded Base64. Require an + # encoding-shaped token: canonical padding, alphabet-specific symbols, or + # the mixed alpha/numeric shape emitted by short unpadded encodings. + mixed_alphanumeric = ( + len(unpadded) >= 10 + and any(char.islower() for char in unpadded) + and any(char.isupper() for char in unpadded) + and any(char.isdigit() for char in unpadded) + ) + encoding_shape = ( + candidate.endswith("=") + or any(char in candidate for char in "+/") + or (any(char in candidate for char in "_-") and mixed_alphanumeric) + or mixed_alphanumeric + ) + if not encoding_shape: return False - encoded = candidate.encode("ascii") - decoded_variants: list[bytes] = [] + padded = unpadded + "=" * (-len(unpadded) % 4) + encoded = padded.encode("ascii") for altchars in (None, b"-_"): try: decoded = base64.b64decode(encoded, altchars=altchars, validate=True) except (binascii.Error, ValueError): continue - canonical = ( + canonical_padded = ( base64.b64encode(decoded) if altchars is None else base64.urlsafe_b64encode(decoded) - ) - if canonical == encoded: - decoded_variants.append(decoded) - - for decoded in decoded_variants: - if len(decoded) < 16: - continue - # Padding or alphabet-specific symbols are strong encoding markers. - if candidate.endswith("=") or any(char in candidate for char in "+/_-"): - return True - # Unpadded all-alphanumeric strings overlap hashes and opaque IDs. - # Require canonical decoding to readable structured text so those - # common values do not become false positives. - try: - decoded_text = decoded.decode("utf-8") - except UnicodeDecodeError: - continue - printable = sum(char.isprintable() or char in "\r\n\t" for char in decoded_text) - if printable / max(len(decoded_text), 1) >= 0.9 and any( - not char.isalnum() for char in decoded_text - ): + ).decode("ascii") + if candidate in {canonical_padded, canonical_padded.rstrip("=")} and len(decoded) >= 4: return True return False @@ -246,11 +311,9 @@ def _contains_canonical_base64(value: Any, *, seen: set[int] | None = None) -> b if identity in seen: return True seen.add(identity) - return any( - _contains_canonical_base64(key, seen=seen) - or _contains_canonical_base64(item, seen=seen) - for key, item in value.items() - ) + # Typed request keys are application-owned structure, not payload + # segments. Only values can carry caller-controlled concealment. + return any(_contains_canonical_base64(item, seen=seen) for item in value.values()) if isinstance(value, (list, tuple, set, frozenset)): identity = id(value) if identity in seen: @@ -317,13 +380,18 @@ def __init__( def preflight( self, - request: Mapping[str, Any], + request: Mapping[str, Any] | TypedOutboundRequest, route: Any, *, grants: Sequence[SourceGrant] = (), - source_segments: Sequence[SourceSegmentBinding] = (), - ) -> EgressDecision: - """Authorize one final request or raise a typed, fail-closed result.""" + ) -> AuthorizedEgress: + """Construct and authorize immutable provider bytes or fail closed. + + Remote and unknown destinations accept only ``TypedOutboundRequest``. + Source text is loaded from verified grants while constructing the + logical request, so no independent raw source-bearing payload exists + for a caller to send after preflight. + """ provider = str(_route_value(route, "provider", "")) model = str(_route_value(route, "model", "")) @@ -332,15 +400,50 @@ def preflight( _route_value(route, "base_url"), _route_value(route, "api_mode"), ) - session_id = _request_identity(request, "session_id") - turn_id = _request_identity(request, "turn_id") - request_id = _request_identity(request, "request_id") - policy_digest = _request_identity(request, "policy_digest") + typed_request = request if isinstance(request, TypedOutboundRequest) else None + if typed_request is not None: + session_id = typed_request.session_id + turn_id = typed_request.turn_id + request_id = typed_request.request_id + policy_digest = typed_request.policy_digest + else: + session_id = _request_identity(request, "session_id") + turn_id = _request_identity(request, "turn_id") + request_id = _request_identity(request, "request_id") + policy_digest = _request_identity(request, "policy_digest") + + reasons: list[str] = [] + valid_grants: list[SourceGrant] = [] + grant_contents: dict[str, tuple[SourceGrant, bytes]] = {} + source_segment_count = 0 + + if destination == DestinationClass.UNKNOWN: + reasons.append("unknown_destination") + if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN}: + if typed_request is None: + reasons.append("typed_request_required") + grant_reasons, valid_grants, grant_contents = self._validate_grants( + grants, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + ) + reasons.extend(grant_reasons) + + if typed_request is not None: + logical_request, construction_reasons, source_segment_count = ( + self._construct_typed_request(typed_request, grant_contents) + ) + reasons.extend(construction_reasons) + else: + logical_request = request try: serialized = json.dumps( - request, + logical_request, ensure_ascii=False, + allow_nan=False, separators=(",", ":"), sort_keys=True, ).encode("utf-8") @@ -353,25 +456,20 @@ def preflight( payload_sha256="", serialized_bytes=0, estimated_tokens=0, - source_grant_count=0, - source_segment_count=0, + source_grant_count=len(valid_grants), + source_segment_count=source_segment_count, session_id=session_id, turn_id=turn_id, request_id=request_id, policy_digest=policy_digest, reason_codes=("serialization_failed",), ) - self._block(decision) + self._block(decision, valid_grants) serialized_bytes = len(serialized) estimated_tokens = ( serialized_bytes + self._conservative_chars_per_token - 1 ) // self._conservative_chars_per_token - reasons: list[str] = [] - valid_grants: list[SourceGrant] = [] - - if destination == DestinationClass.UNKNOWN: - reasons.append("unknown_destination") if serialized_bytes > self._max_serialized_bytes: reasons.append("serialized_bytes_exceeded") if estimated_tokens > self._max_conservative_tokens: @@ -379,32 +477,16 @@ def preflight( if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN}: try: - if _contains_secret(request): + if _contains_secret(logical_request): reasons.append("secret_detected") except Exception: reasons.append("redaction_failed") try: - if _contains_canonical_base64(request): + if _contains_canonical_base64(logical_request): reasons.append("base64_payload") except Exception: reasons.append("base64_scan_failed") - if destination == DestinationClass.REMOTE: - grant_reasons, valid_grants = self._validate_grants( - grants, - session_id=session_id, - turn_id=turn_id, - request_id=request_id, - policy_digest=policy_digest, - ) - reasons.extend(grant_reasons) - segment_reasons = self._validate_source_segments( - request, - source_segments, - valid_grants, - ) - reasons.extend(segment_reasons) - decision = EgressDecision( allowed=not reasons, destination_class=destination, @@ -414,7 +496,7 @@ def preflight( serialized_bytes=serialized_bytes, estimated_tokens=estimated_tokens, source_grant_count=len(valid_grants), - source_segment_count=len(source_segments), + source_segment_count=source_segment_count, session_id=session_id, turn_id=turn_id, request_id=request_id, @@ -430,7 +512,7 @@ def preflight( raise EgressBlocked( replace(decision, allowed=False, reason_codes=("receipt_unavailable",)) ) from None - return decision + return AuthorizedEgress(decision=decision, payload_bytes=serialized) def _validate_grants( self, @@ -440,11 +522,12 @@ def _validate_grants( turn_id: str, request_id: str, policy_digest: str, - ) -> tuple[list[str], list[SourceGrant]]: + ) -> tuple[list[str], list[SourceGrant], dict[str, tuple[SourceGrant, bytes]]]: reasons: list[str] = [] valid: list[SourceGrant] = [] + contents: dict[str, tuple[SourceGrant, bytes]] = {} if not grants: - return ["untrusted_provenance"], valid + return ["untrusted_provenance"], valid, contents for candidate in grants: if not isinstance(candidate, SourceGrant): @@ -501,76 +584,92 @@ def _validate_grants( reasons.append("source_hash_mismatch") continue valid.append(grant) + contents[source_grant_digest(grant)] = (grant, content) if not valid and "untrusted_provenance" not in reasons: reasons.append("untrusted_provenance") - return reasons, valid + return reasons, valid, contents - def _validate_source_segments( + def _construct_typed_request( self, - request: Mapping[str, Any], - source_segments: Sequence[SourceSegmentBinding], - valid_grants: Sequence[SourceGrant], - ) -> list[str]: - if not valid_grants: - return [] - if not source_segments: - return ["source_grant_unbound"] + request: TypedOutboundRequest, + grant_contents: Mapping[str, tuple[SourceGrant, bytes]], + ) -> tuple[Mapping[str, Any], list[str], int]: + """Build a plain JSON request exclusively from typed segment nodes.""" reasons: list[str] = [] - grants_by_digest = {source_grant_digest(grant): grant for grant in valid_grants} referenced_grants: set[str] = set() - - for binding in source_segments: - if not isinstance(binding, SourceSegmentBinding): - reasons.append("invalid_source_segment") - continue - grant = grants_by_digest.get(binding.source_grant_digest) - if grant is None: - reasons.append("source_segment_grant_mismatch") - continue - if ( - binding.byte_start < 0 - or binding.byte_end <= binding.byte_start - or not re.fullmatch(r"[0-9a-f]{64}", binding.content_sha256) - ): - reasons.append("invalid_source_segment") - continue - try: - current: Any = request - for component in binding.request_path: - if isinstance(component, str) and isinstance(current, Mapping): - current = current[component] - elif ( - isinstance(component, int) - and not isinstance(component, bool) - and isinstance(current, (list, tuple)) - ): - current = current[component] - else: - raise KeyError(component) - if not isinstance(current, str): - raise TypeError("source segment target is not text") - request_bytes = current.encode("utf-8") - segment = request_bytes[binding.byte_start : binding.byte_end] - except (IndexError, KeyError, TypeError, UnicodeError): - reasons.append("source_segment_unavailable") - continue - if binding.byte_end > len(request_bytes): - reasons.append("source_segment_range_mismatch") - continue - if ( - len(segment) != grant.byte_count - or sha256(segment).hexdigest() != binding.content_sha256 - or binding.content_sha256 != grant.content_sha256 + source_segment_count = 0 + + def render_text_segment( + segment: LiteralSegment | SanitizedSegment | SourceBoundSegment, + ) -> str: + nonlocal source_segment_count + if isinstance(segment, (LiteralSegment, SanitizedSegment)): + if not isinstance(segment.text, str): + reasons.append("invalid_literal_segment") + return "" + encoded_literal = segment.text.encode("utf-8") + if any(content and content in encoded_literal for _, content in grant_contents.values()): + reasons.append("source_bytes_in_literal") + return segment.text + if isinstance(segment, SourceBoundSegment): + grant_and_content = grant_contents.get(segment.source_grant_digest) + if grant_and_content is None: + reasons.append("source_segment_grant_mismatch") + return "" + try: + text = grant_and_content[1].decode("utf-8") + except UnicodeDecodeError: + reasons.append("source_segment_not_text") + return "" + referenced_grants.add(segment.source_grant_digest) + source_segment_count += 1 + return text + reasons.append("invalid_source_segment") + return "" + + def render(value: Any) -> Any: + if isinstance(value, (LiteralSegment, SanitizedSegment, SourceBoundSegment)): + return render_text_segment(value) + if isinstance(value, OutboundText): + return "".join(render_text_segment(segment) for segment in value.segments) + if isinstance(value, Mapping): + rendered: dict[str, Any] = {} + for key, item in value.items(): + if not isinstance(key, str): + reasons.append("invalid_request_key") + continue + rendered[key] = render(item) + return rendered + if isinstance(value, (list, tuple)): + return [render(item) for item in value] + if value is None or isinstance(value, (bool, int, float)): + return value + # In particular, raw strings and bytes are not remote request + # material. Every outbound string must have a typed owner. + reasons.append("untyped_request_value") + return None + + rendered_payload = render(request.payload) + if not isinstance(rendered_payload, Mapping): + reasons.append("invalid_typed_request_root") + rendered_payload = {} + else: + bound_identities = { + "session_id": request.session_id, + "turn_id": request.turn_id, + "request_id": request.request_id, + "policy_digest": request.policy_digest, + } + if any( + field in rendered_payload and rendered_payload[field] != expected + for field, expected in bound_identities.items() ): - reasons.append("source_segment_hash_mismatch") - continue - referenced_grants.add(binding.source_grant_digest) - - if set(grants_by_digest) - referenced_grants: + reasons.append("request_identity_mismatch") + if set(grant_contents) - referenced_grants: reasons.append("source_grant_unbound") - return reasons + return rendered_payload, reasons, source_segment_count def _block( self, @@ -633,12 +732,17 @@ def _append_receipt( __all__ = [ + "AuthorizedEgress", "DestinationClass", "EgressBlocked", "EgressDecision", "LLMEgressFirewall", + "LiteralSegment", + "OutboundText", + "SanitizedSegment", + "SourceBoundSegment", "SourceGrant", - "SourceSegmentBinding", + "TypedOutboundRequest", "classify_destination", "source_grant_digest", ] diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index b755649f90863..213e82c9e6806 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -15,11 +15,16 @@ import pytest from agent.llm_egress_firewall import ( + AuthorizedEgress, DestinationClass, EgressBlocked, LLMEgressFirewall, + LiteralSegment, + OutboundText, + SanitizedSegment, SourceGrant, - SourceSegmentBinding, + SourceBoundSegment, + TypedOutboundRequest, classify_destination, source_grant_digest, ) @@ -58,15 +63,27 @@ def _request(payload: str = "ordinary prompt"): } -def _source_binding(grant: SourceGrant, request, *, path=("messages", 0, "content")): - value = request["messages"][0]["content"] - encoded = value.encode("utf-8") - return SourceSegmentBinding( - request_path=path, - byte_start=0, - byte_end=len(encoded), - content_sha256=sha256(encoded).hexdigest(), - source_grant_digest=source_grant_digest(grant), +def _typed_request(request, *, source_grant: SourceGrant | None = None): + def typed(value): + if isinstance(value, str): + return SanitizedSegment(value) + if isinstance(value, list): + return [typed(item) for item in value] + if isinstance(value, dict): + return {key: typed(item) for key, item in value.items()} + return value + + payload = typed(request) + if source_grant is not None: + payload["messages"][0]["content"] = OutboundText( + (SourceBoundSegment(source_grant_digest(source_grant)),) + ) + return TypedOutboundRequest( + payload=payload, + session_id=request["session_id"], + turn_id=request["turn_id"], + request_id=request["request_id"], + policy_digest=request["policy_digest"], ) @@ -131,19 +148,19 @@ def test_remote_request_requires_an_exact_source_grant(tmp_path): grant = _source_grant(path) request = _request("private source\n") with pytest.raises(EgressBlocked) as exc_info: - firewall(tmp_path).preflight(request, _route(), grants=()) + firewall(tmp_path).preflight(_typed_request(request), _route(), grants=()) assert "untrusted_provenance" in exc_info.value.decision.reason_codes - decision = firewall(tmp_path).preflight( - request, + authorization = firewall(tmp_path).preflight( + _typed_request(request, source_grant=grant), _route(), grants=(grant,), - source_segments=(_source_binding(grant, request),), ) - assert decision.allowed is True + assert isinstance(authorization, AuthorizedEgress) + assert authorization.allowed is True -def test_unrelated_grant_and_incomplete_source_manifest_are_denied(tmp_path): +def test_unrelated_grant_and_incomplete_typed_source_request_are_denied(tmp_path): first = tmp_path / "first.py" second = tmp_path / "second.py" first.write_text("first source\n", encoding="utf-8") @@ -151,40 +168,87 @@ def test_unrelated_grant_and_incomplete_source_manifest_are_denied(tmp_path): first_grant = _source_grant(first) second_grant = _source_grant(second) request = _request("first source\n") - first_binding = _source_binding(first_grant, request) - with pytest.raises(EgressBlocked) as unrelated_exc: firewall(tmp_path).preflight( - request, + _typed_request(request, source_grant=second_grant), _route(), - grants=(second_grant,), - source_segments=(_source_binding(second_grant, request),), + grants=(first_grant,), ) - assert "source_segment_hash_mismatch" in unrelated_exc.value.decision.reason_codes + assert "source_segment_grant_mismatch" in unrelated_exc.value.decision.reason_codes with pytest.raises(EgressBlocked) as incomplete_exc: firewall(tmp_path).preflight( - request, + _typed_request(request, source_grant=first_grant), _route(), grants=(first_grant, second_grant), - source_segments=(first_binding,), ) assert "source_grant_unbound" in incomplete_exc.value.decision.reason_codes +def test_remote_raw_request_is_never_authorized_even_with_a_valid_grant(tmp_path): + path = tmp_path / "private.py" + path.write_text("private source\n", encoding="utf-8") + grant = _source_grant(path) + raw_request = _request("private source\n") + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(raw_request, _route(), grants=(grant,)) + assert "typed_request_required" in exc_info.value.decision.reason_codes + + +def test_source_bytes_cannot_be_smuggled_as_a_sanitized_literal(tmp_path): + path = tmp_path / "private.py" + path.write_text("private source\n", encoding="utf-8") + grant = _source_grant(path) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight( + _typed_request(_request("private source\n")), + _route(), + grants=(grant,), + ) + assert "source_bytes_in_literal" in exc_info.value.decision.reason_codes + assert "source_grant_unbound" in exc_info.value.decision.reason_codes + + +def test_source_bytes_are_constructed_from_grant_and_authorized_bytes_reject_tampering(tmp_path): + path = tmp_path / "private.py" + path.write_text("verified source\n", encoding="utf-8") + grant = _source_grant(path) + raw_request = _request("ignored raw bytes") + typed_request = _typed_request(raw_request, source_grant=grant) + authorization = firewall(tmp_path).preflight(typed_request, _route(), grants=(grant,)) + authorized_payload = json.loads(authorization.payload_bytes) + assert authorized_payload["messages"][0]["content"] == "verified source\n" + assert "ignored raw bytes" not in authorization.payload_bytes.decode("utf-8") + + typed_request.payload["messages"][0]["content"] = LiteralSegment("tampered") + assert authorization.payload_bytes == authorization.verify_payload(authorization.payload_bytes) + with pytest.raises(EgressBlocked) as exc_info: + authorization.verify_payload(authorization.payload_bytes.replace(b"verified", b"tampered")) + assert "payload_digest_mismatch" in exc_info.value.decision.reason_codes + + +def test_typed_payload_identity_cannot_diverge_from_grant_binding_identity(tmp_path): + path = tmp_path / "private.py" + path.write_text("verified source\n", encoding="utf-8") + grant = _source_grant(path) + typed_request = _typed_request(_request("ignored"), source_grant=grant) + typed_request.payload["request_id"] = LiteralSegment("different-request") + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(typed_request, _route(), grants=(grant,)) + assert "request_identity_mismatch" in exc_info.value.decision.reason_codes + + def test_modified_source_and_adjacent_slice_are_denied(tmp_path): path = tmp_path / "private.py" path.write_text("private source\nneighbor\n", encoding="utf-8") grant = _source_grant(path) request = _request("private source\n") - binding = _source_binding(grant, request) path.write_text("changed source\nneighbor\n", encoding="utf-8") with pytest.raises(EgressBlocked) as exc_info: firewall(tmp_path).preflight( - request, + _typed_request(request, source_grant=grant), _route(), grants=(grant,), - source_segments=(binding,), ) assert "source_hash_mismatch" in exc_info.value.decision.reason_codes @@ -196,10 +260,9 @@ def test_sensitive_path_and_forged_grant_fail_closed(tmp_path, monkeypatch): sensitive_request = _request("API_KEY=sk-test-secret\n") with pytest.raises(EgressBlocked) as exc_info: firewall(tmp_path).preflight( - sensitive_request, + _typed_request(sensitive_request, source_grant=grant), _route(), grants=(grant,), - source_segments=(_source_binding(grant, sensitive_request),), ) assert "sensitive_path" in exc_info.value.decision.reason_codes @@ -219,17 +282,20 @@ def test_sensitive_path_and_forged_grant_fail_closed(tmp_path, monkeypatch): missing_request = _request("private source\n") with pytest.raises(EgressBlocked) as missing_exc: firewall(tmp_path).preflight( - missing_request, + _typed_request(missing_request, source_grant=forged), _route(), grants=(forged,), - source_segments=(_source_binding(forged, missing_request),), ) assert "source_unavailable" in missing_exc.value.decision.reason_codes def test_forced_secret_redaction_rejects_instead_of_rewriting(tmp_path): with pytest.raises(EgressBlocked) as exc_info: - firewall(tmp_path).preflight(_request("token=super-secret-value"), _route(), grants=(object(),)) + firewall(tmp_path).preflight( + _typed_request(_request("token=super-secret-value")), + _route(), + grants=(object(),), + ) assert "secret_detected" in exc_info.value.decision.reason_codes @@ -238,6 +304,9 @@ def test_forced_secret_redaction_rejects_instead_of_rewriting(tmp_path): [ base64.b64encode(b"sk-proj-abc123def456ghi789jkl012").decode("ascii"), base64.urlsafe_b64encode(b"harmless text that is still encoded").decode("ascii"), + base64.b64encode(b"sk-x").decode("ascii"), + base64.b64encode(b"sk-short").decode("ascii").rstrip("="), + base64.urlsafe_b64encode(b"\xfb\xffshort-secret").decode("ascii").rstrip("="), ], ) def test_canonical_base64_payloads_are_rejected_even_when_decoded_content_is_benign( @@ -245,7 +314,11 @@ def test_canonical_base64_payloads_are_rejected_even_when_decoded_content_is_ben payload, ): with pytest.raises(EgressBlocked) as exc_info: - firewall(tmp_path).preflight(_request(payload), _route(), grants=(object(),)) + firewall(tmp_path).preflight( + _typed_request(_request(payload)), + _route(), + grants=(object(),), + ) assert "base64_payload" in exc_info.value.decision.reason_codes @@ -263,18 +336,28 @@ def explode(*args, **kwargs): monkeypatch.setattr("agent.llm_egress_firewall.redact_sensitive_text", explode) with pytest.raises(EgressBlocked) as exc_info: - firewall(tmp_path).preflight(_request(), _route(), grants=(object(),)) + firewall(tmp_path).preflight( + _typed_request(_request()), + _route(), + grants=(object(),), + ) assert "redaction_failed" in exc_info.value.decision.reason_codes def test_byte_and_token_caps_fail_closed(tmp_path): with pytest.raises(EgressBlocked) as bytes_exc: - firewall(tmp_path, max_serialized_bytes=32).preflight(_request(), _route(), grants=(object(),)) + firewall(tmp_path, max_serialized_bytes=32).preflight( + _typed_request(_request()), + _route(), + grants=(object(),), + ) assert "serialized_bytes_exceeded" in bytes_exc.value.decision.reason_codes with pytest.raises(EgressBlocked) as token_exc: firewall(tmp_path, max_serialized_bytes=100_000, max_conservative_tokens=2).preflight( - _request("ordinary prompt"), _route(), grants=(object(),) + _typed_request(_request("ordinary prompt")), + _route(), + grants=(object(),), ) assert "token_cap_exceeded" in token_exc.value.decision.reason_codes @@ -301,12 +384,12 @@ def test_allow_receipt_contains_hashes_and_counts_but_no_payload(tmp_path): path.write_text("private source\n", encoding="utf-8") grant = _source_grant(path) request = _request("private source\n") - decision = firewall(tmp_path).preflight( - request, + authorization = firewall(tmp_path).preflight( + _typed_request(request, source_grant=grant), _route(), grants=(grant,), - source_segments=(_source_binding(grant, request),), ) + decision = authorization.decision receipt = json.loads((tmp_path / "llm-egress-receipts.jsonl").read_text().splitlines()[0]) assert receipt["payload_sha256"] == decision.payload_sha256 assert receipt["serialized_bytes"] == decision.serialized_bytes @@ -321,7 +404,7 @@ def test_receipt_hashes_unsafe_identity_and_route_labels(tmp_path): private_model_label = str(Path.home() / "private-model") with pytest.raises(EgressBlocked): firewall(tmp_path).preflight( - {**_request(), "request_id": secret_request_id}, + _typed_request({**_request(), "request_id": secret_request_id}), _route(model=private_model_label), grants=(object(),), ) @@ -335,13 +418,11 @@ def test_receipt_is_owner_only_and_rejects_symlink_ledger(tmp_path): path.write_text("private source\n", encoding="utf-8") grant = _source_grant(path) request = _request("private source\n") - binding = _source_binding(grant, request) ledger = tmp_path / "llm-egress-receipts.jsonl" firewall(tmp_path).preflight( - request, + _typed_request(request, source_grant=grant), _route(), grants=(grant,), - source_segments=(binding,), ) assert stat.S_IMODE(ledger.stat().st_mode) == 0o600 @@ -351,10 +432,9 @@ def test_receipt_is_owner_only_and_rejects_symlink_ledger(tmp_path): ledger.symlink_to(target) with pytest.raises(EgressBlocked) as exc_info: firewall(tmp_path).preflight( - request, + _typed_request(request, source_grant=grant), _route(), grants=(grant,), - source_segments=(binding,), ) assert "receipt_unavailable" in exc_info.value.decision.reason_codes From 5b70723bb67b81f7961d13b15b3086cb2861b8b3 Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Tue, 25 Aug 2026 20:34:17 -0700 Subject: [PATCH 04/26] fix(security): allow only policy-bound remote literals --- agent/llm_egress_firewall.py | 89 ++++++++++----- tests/agent/test_llm_egress_firewall.py | 137 ++++++++++++++++++++---- 2 files changed, 180 insertions(+), 46 deletions(-) diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index 87ca5f1b2cd62..a67401b95f99b 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -159,7 +159,7 @@ def verify_payload(self, candidate: bytes) -> bytes: _SAFE_ID = re.compile(r"^[A-Za-z0-9_.:@/-]{0,256}$") _LOCAL_PROCESS_MODES = frozenset({"local_process", "in_process"}) _BASE64_CANDIDATE = re.compile( - r"(? str: return sha256(encoded).hexdigest() +def static_literal_sha256(text: str) -> str: + """Hash one exact UTF-8 static literal for a policy allowlist.""" + + if not isinstance(text, str): + raise TypeError("static literal must be text") + return sha256(text.encode("utf-8")).hexdigest() + + def _canonical_base64_candidate(candidate: str) -> bool: """Recognize bounded canonical encodings without flagging ordinary IDs.""" - if not 6 <= len(candidate) <= _MAX_BASE64_CANDIDATE_CHARS: + if not 4 <= len(candidate) <= _MAX_BASE64_CANDIDATE_CHARS: return False unpadded = candidate.rstrip("=") if "=" in unpadded or len(unpadded) % 4 == 1: return False - # A strict round-trip alone cannot distinguish an ordinary alphabet-only - # word (for example ``ordinary``) from unpadded Base64. Require an - # encoding-shaped token: canonical padding, alphabet-specific symbols, or - # the mixed alpha/numeric shape emitted by short unpadded encodings. - mixed_alphanumeric = ( - len(unpadded) >= 10 - and any(char.islower() for char in unpadded) - and any(char.isupper() for char in unpadded) - and any(char.isdigit() for char in unpadded) - ) - encoding_shape = ( - candidate.endswith("=") - or any(char in candidate for char in "+/") - or (any(char in candidate for char in "_-") and mixed_alphanumeric) - or mixed_alphanumeric - ) - if not encoding_shape: - return False padded = unpadded + "=" * (-len(unpadded) % 4) encoded = padded.encode("ascii") for altchars in (None, b"-_"): @@ -294,7 +284,7 @@ def _canonical_base64_candidate(candidate: str) -> bool: if altchars is None else base64.urlsafe_b64encode(decoded) ).decode("ascii") - if candidate in {canonical_padded, canonical_padded.rstrip("=")} and len(decoded) >= 4: + if candidate in {canonical_padded, canonical_padded.rstrip("=")} and decoded: return True return False @@ -365,6 +355,7 @@ def __init__( max_serialized_bytes: int = 262_144, max_conservative_tokens: int = 87_382, conservative_chars_per_token: int = 3, + static_literal_hashes_by_policy: Mapping[str, Sequence[str]] | None = None, ) -> None: if max_serialized_bytes <= 0: raise ValueError("max_serialized_bytes must be positive") @@ -377,6 +368,14 @@ def __init__( self._max_serialized_bytes = max_serialized_bytes self._max_conservative_tokens = max_conservative_tokens self._conservative_chars_per_token = conservative_chars_per_token + self._static_literal_hashes_by_policy = { + str(policy_digest): frozenset( + digest + for digest in digests + if isinstance(digest, str) and re.fullmatch(r"[0-9a-f]{64}", digest) + ) + for policy_digest, digests in (static_literal_hashes_by_policy or {}).items() + } def preflight( self, @@ -384,6 +383,17 @@ def preflight( route: Any, *, grants: Sequence[SourceGrant] = (), + ) -> EgressDecision: + """Preserve the content-free Task 1 decision interface.""" + + return self.authorize(request, route, grants=grants).decision + + def authorize( + self, + request: Mapping[str, Any] | TypedOutboundRequest, + route: Any, + *, + grants: Sequence[SourceGrant] = (), ) -> AuthorizedEgress: """Construct and authorize immutable provider bytes or fail closed. @@ -432,12 +442,13 @@ def preflight( reasons.extend(grant_reasons) if typed_request is not None: - logical_request, construction_reasons, source_segment_count = ( + logical_request, construction_reasons, source_segment_count, scan_values = ( self._construct_typed_request(typed_request, grant_contents) ) reasons.extend(construction_reasons) else: logical_request = request + scan_values = request try: serialized = json.dumps( @@ -477,12 +488,12 @@ def preflight( if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN}: try: - if _contains_secret(logical_request): + if _contains_secret(scan_values): reasons.append("secret_detected") except Exception: reasons.append("redaction_failed") try: - if _contains_canonical_base64(logical_request): + if _contains_canonical_base64(scan_values): reasons.append("base64_payload") except Exception: reasons.append("base64_scan_failed") @@ -594,25 +605,43 @@ def _construct_typed_request( self, request: TypedOutboundRequest, grant_contents: Mapping[str, tuple[SourceGrant, bytes]], - ) -> tuple[Mapping[str, Any], list[str], int]: + ) -> tuple[Mapping[str, Any], list[str], int, list[str]]: """Build a plain JSON request exclusively from typed segment nodes.""" reasons: list[str] = [] referenced_grants: set[str] = set() source_segment_count = 0 + scan_values: list[str] = [] + allowed_static_hashes = self._static_literal_hashes_by_policy.get( + request.policy_digest, + frozenset(), + ) + + def require_static_literal(text: str) -> None: + if static_literal_sha256(text) not in allowed_static_hashes: + reasons.append("static_literal_not_allowed") + scan_values.append(text) def render_text_segment( segment: LiteralSegment | SanitizedSegment | SourceBoundSegment, ) -> str: nonlocal source_segment_count - if isinstance(segment, (LiteralSegment, SanitizedSegment)): + if isinstance(segment, LiteralSegment): if not isinstance(segment.text, str): reasons.append("invalid_literal_segment") return "" + require_static_literal(segment.text) encoded_literal = segment.text.encode("utf-8") if any(content and content in encoded_literal for _, content in grant_contents.values()): reasons.append("source_bytes_in_literal") return segment.text + if isinstance(segment, SanitizedSegment): + reasons.append("sanitized_segment_forbidden") + if isinstance(segment.text, str): + scan_values.append(segment.text) + return segment.text + reasons.append("invalid_literal_segment") + return "" if isinstance(segment, SourceBoundSegment): grant_and_content = grant_contents.get(segment.source_grant_digest) if grant_and_content is None: @@ -625,6 +654,7 @@ def render_text_segment( return "" referenced_grants.add(segment.source_grant_digest) source_segment_count += 1 + scan_values.append(text) return text reasons.append("invalid_source_segment") return "" @@ -640,11 +670,15 @@ def render(value: Any) -> Any: if not isinstance(key, str): reasons.append("invalid_request_key") continue + require_static_literal(key) rendered[key] = render(item) return rendered if isinstance(value, (list, tuple)): return [render(item) for item in value] if value is None or isinstance(value, (bool, int, float)): + require_static_literal( + json.dumps(value, ensure_ascii=True, allow_nan=False, separators=(",", ":")) + ) return value # In particular, raw strings and bytes are not remote request # material. Every outbound string must have a typed owner. @@ -669,7 +703,7 @@ def render(value: Any) -> Any: reasons.append("request_identity_mismatch") if set(grant_contents) - referenced_grants: reasons.append("source_grant_unbound") - return rendered_payload, reasons, source_segment_count + return rendered_payload, reasons, source_segment_count, scan_values def _block( self, @@ -745,4 +779,5 @@ def _append_receipt( "TypedOutboundRequest", "classify_destination", "source_grant_digest", + "static_literal_sha256", ] diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index 213e82c9e6806..231e43bc40a38 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -18,6 +18,7 @@ AuthorizedEgress, DestinationClass, EgressBlocked, + EgressDecision, LLMEgressFirewall, LiteralSegment, OutboundText, @@ -27,6 +28,7 @@ TypedOutboundRequest, classify_destination, source_grant_digest, + static_literal_sha256, ) @@ -66,7 +68,7 @@ def _request(payload: str = "ordinary prompt"): def _typed_request(request, *, source_grant: SourceGrant | None = None): def typed(value): if isinstance(value, str): - return SanitizedSegment(value) + return LiteralSegment(value) if isinstance(value, list): return [typed(item) for item in value] if isinstance(value, dict): @@ -87,8 +89,31 @@ def typed(value): ) -def firewall(tmp_path: Path, **kwargs) -> LLMEgressFirewall: - return LLMEgressFirewall(tmp_path, **kwargs) +_COMMON_STATIC_LITERALS = { + "messages", + "role", + "content", + "user", + "session_id", + "session-1", + "turn_id", + "turn-1", + "request_id", + "req-1", + "policy_digest", + "policy-1", +} + + +def firewall(tmp_path: Path, *, static_literals=(), **kwargs) -> LLMEgressFirewall: + allowed = _COMMON_STATIC_LITERALS | set(static_literals) + return LLMEgressFirewall( + tmp_path, + static_literal_hashes_by_policy={ + "policy-1": frozenset(static_literal_sha256(value) for value in allowed) + }, + **kwargs, + ) def test_lan_and_unknown_are_remote_while_numeric_loopback_is_loopback(): @@ -144,20 +169,21 @@ def test_loopback_request_is_allowed_without_source_grant(tmp_path): def test_remote_request_requires_an_exact_source_grant(tmp_path): path = tmp_path / "private.py" - path.write_text("private source\npublic source\n", encoding="utf-8") + path.write_text("x=1\npublic source\n", encoding="utf-8") grant = _source_grant(path) request = _request("private source\n") with pytest.raises(EgressBlocked) as exc_info: firewall(tmp_path).preflight(_typed_request(request), _route(), grants=()) assert "untrusted_provenance" in exc_info.value.decision.reason_codes - authorization = firewall(tmp_path).preflight( + decision = firewall(tmp_path).preflight( _typed_request(request, source_grant=grant), _route(), grants=(grant,), ) - assert isinstance(authorization, AuthorizedEgress) - assert authorization.allowed is True + assert isinstance(decision, EgressDecision) + assert decision.allowed is True + assert decision.payload_sha256 def test_unrelated_grant_and_incomplete_typed_source_request_are_denied(tmp_path): @@ -209,21 +235,87 @@ def test_source_bytes_cannot_be_smuggled_as_a_sanitized_literal(tmp_path): assert "source_grant_unbound" in exc_info.value.decision.reason_codes +def test_only_exact_policy_allowlisted_static_wrappers_accompany_source(tmp_path): + path = tmp_path / "private.py" + path.write_text("x=1\n", encoding="utf-8") + grant = _source_grant(path) + typed_request = _typed_request(_request("ignored"), source_grant=grant) + typed_request.payload["messages"][0]["content"] = OutboundText( + ( + LiteralSegment("\n"), + SourceBoundSegment(source_grant_digest(grant)), + LiteralSegment(""), + ) + ) + gate = firewall(tmp_path, static_literals={"\n", ""}) + authorization = gate.authorize(typed_request, _route(), grants=(grant,)) + assert json.loads(authorization.payload_bytes)["messages"][0]["content"] == ( + "\nx=1\n" + ) + + typed_request.payload["messages"][0]["content"] = OutboundText( + ( + LiteralSegment("\n"), + SourceBoundSegment(source_grant_digest(grant)), + LiteralSegment(""), + ) + ) + with pytest.raises(EgressBlocked) as changed_exc: + gate.preflight(typed_request, _route(), grants=(grant,)) + assert "static_literal_not_allowed" in changed_exc.value.decision.reason_codes + + typed_request.payload["messages"][0]["content"] = OutboundText( + ( + SanitizedSegment("\n"), + SourceBoundSegment(source_grant_digest(grant)), + LiteralSegment(""), + ) + ) + with pytest.raises(EgressBlocked) as sanitized_exc: + gate.preflight(typed_request, _route(), grants=(grant,)) + assert "sanitized_segment_forbidden" in sanitized_exc.value.decision.reason_codes + + +def test_second_source_cannot_be_mislabeled_as_allowlisted_literal(tmp_path): + first = tmp_path / "first.py" + second = tmp_path / "second.py" + first.write_text("x=1\n", encoding="utf-8") + second.write_text("y=2\n", encoding="utf-8") + first_grant = _source_grant(first) + second_grant = _source_grant(second) + typed_request = _typed_request(_request("ignored"), source_grant=first_grant) + typed_request.payload["messages"][0]["content"] = OutboundText( + ( + SourceBoundSegment(source_grant_digest(first_grant)), + LiteralSegment("y=2\n"), + ) + ) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight( + typed_request, + _route(), + grants=(first_grant, second_grant), + ) + assert "static_literal_not_allowed" in exc_info.value.decision.reason_codes + assert "source_bytes_in_literal" in exc_info.value.decision.reason_codes + assert "source_grant_unbound" in exc_info.value.decision.reason_codes + + def test_source_bytes_are_constructed_from_grant_and_authorized_bytes_reject_tampering(tmp_path): path = tmp_path / "private.py" - path.write_text("verified source\n", encoding="utf-8") + path.write_text("x=1\n", encoding="utf-8") grant = _source_grant(path) raw_request = _request("ignored raw bytes") typed_request = _typed_request(raw_request, source_grant=grant) - authorization = firewall(tmp_path).preflight(typed_request, _route(), grants=(grant,)) + authorization = firewall(tmp_path).authorize(typed_request, _route(), grants=(grant,)) authorized_payload = json.loads(authorization.payload_bytes) - assert authorized_payload["messages"][0]["content"] == "verified source\n" + assert authorized_payload["messages"][0]["content"] == "x=1\n" assert "ignored raw bytes" not in authorization.payload_bytes.decode("utf-8") typed_request.payload["messages"][0]["content"] = LiteralSegment("tampered") assert authorization.payload_bytes == authorization.verify_payload(authorization.payload_bytes) with pytest.raises(EgressBlocked) as exc_info: - authorization.verify_payload(authorization.payload_bytes.replace(b"verified", b"tampered")) + authorization.verify_payload(authorization.payload_bytes.replace(b"x=1", b"x=2")) assert "payload_digest_mismatch" in exc_info.value.decision.reason_codes @@ -290,11 +382,14 @@ def test_sensitive_path_and_forged_grant_fail_closed(tmp_path, monkeypatch): def test_forced_secret_redaction_rejects_instead_of_rewriting(tmp_path): + path = tmp_path / "secret.txt" + path.write_text("token=super-secret-value\n", encoding="utf-8") + grant = _source_grant(path) with pytest.raises(EgressBlocked) as exc_info: firewall(tmp_path).preflight( - _typed_request(_request("token=super-secret-value")), + _typed_request(_request("ignored"), source_grant=grant), _route(), - grants=(object(),), + grants=(grant,), ) assert "secret_detected" in exc_info.value.decision.reason_codes @@ -307,17 +402,22 @@ def test_forced_secret_redaction_rejects_instead_of_rewriting(tmp_path): base64.b64encode(b"sk-x").decode("ascii"), base64.b64encode(b"sk-short").decode("ascii").rstrip("="), base64.urlsafe_b64encode(b"\xfb\xffshort-secret").decode("ascii").rstrip("="), + base64.b64encode(b"\x01\x02\x03").decode("ascii"), + base64.urlsafe_b64encode(b"\xfb\xff\x00").decode("ascii").rstrip("="), ], ) def test_canonical_base64_payloads_are_rejected_even_when_decoded_content_is_benign( tmp_path, payload, ): + path = tmp_path / "encoded.txt" + path.write_text(payload + "\n", encoding="utf-8") + grant = _source_grant(path) with pytest.raises(EgressBlocked) as exc_info: firewall(tmp_path).preflight( - _typed_request(_request(payload)), + _typed_request(_request("ignored"), source_grant=grant), _route(), - grants=(object(),), + grants=(grant,), ) assert "base64_payload" in exc_info.value.decision.reason_codes @@ -381,15 +481,14 @@ def test_byte_and_token_caps_allow_the_exact_boundary(tmp_path): def test_allow_receipt_contains_hashes_and_counts_but_no_payload(tmp_path): path = tmp_path / "private.py" - path.write_text("private source\n", encoding="utf-8") + path.write_text("x=1\n", encoding="utf-8") grant = _source_grant(path) request = _request("private source\n") - authorization = firewall(tmp_path).preflight( + decision = firewall(tmp_path).preflight( _typed_request(request, source_grant=grant), _route(), grants=(grant,), ) - decision = authorization.decision receipt = json.loads((tmp_path / "llm-egress-receipts.jsonl").read_text().splitlines()[0]) assert receipt["payload_sha256"] == decision.payload_sha256 assert receipt["serialized_bytes"] == decision.serialized_bytes @@ -415,7 +514,7 @@ def test_receipt_hashes_unsafe_identity_and_route_labels(tmp_path): def test_receipt_is_owner_only_and_rejects_symlink_ledger(tmp_path): path = tmp_path / "private.py" - path.write_text("private source\n", encoding="utf-8") + path.write_text("x=1\n", encoding="utf-8") grant = _source_grant(path) request = _request("private source\n") ledger = tmp_path / "llm-egress-receipts.jsonl" From 8175516c8a2e6211805cb3c3ea61e8cf3b8f6fce Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Tue, 25 Aug 2026 20:39:55 -0700 Subject: [PATCH 05/26] fix(security): scan all authorized egress text --- agent/llm_egress_firewall.py | 15 ++++++++++++- tests/agent/test_llm_egress_firewall.py | 29 ++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index a67401b95f99b..bd256ff4bc39b 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -162,6 +162,13 @@ def verify_payload(self, candidate: bytes) -> bytes: r"(? str: def _canonical_base64_candidate(candidate: str) -> bool: """Recognize bounded canonical encodings without flagging ordinary IDs.""" + if candidate in _PROTOCOL_GRAMMAR_ATOMS: + return False if not 4 <= len(candidate) <= _MAX_BASE64_CANDIDATE_CHARS: return False unpadded = candidate.rstrip("=") @@ -618,9 +627,13 @@ def _construct_typed_request( ) def require_static_literal(text: str) -> None: + # Provenance authorization and content safety are independent. + # Every rendered text atom is scanned again immediately before + # authorization, including exact policy-bound static literals and + # structural keys/scalars. + scan_values.append(text) if static_literal_sha256(text) not in allowed_static_hashes: reasons.append("static_literal_not_allowed") - scan_values.append(text) def render_text_segment( segment: LiteralSegment | SanitizedSegment | SourceBoundSegment, diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index 231e43bc40a38..aeb3c604eff81 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -75,7 +75,9 @@ def typed(value): return {key: typed(item) for key, item in value.items()} return value - payload = typed(request) + # Request identity is control-plane metadata for grant binding and receipts, + # not provider payload. Keep only the logical provider request here. + payload = typed({"messages": request["messages"]}) if source_grant is not None: payload["messages"][0]["content"] = OutboundText( (SourceBoundSegment(source_grant_digest(source_grant)),) @@ -276,6 +278,31 @@ def test_only_exact_policy_allowlisted_static_wrappers_accompany_source(tmp_path assert "sanitized_segment_forbidden" in sanitized_exc.value.decision.reason_codes +@pytest.mark.parametrize( + ("wrapper", "reason"), + [ + ("token=super-secret-value\n", "secret_detected"), + ("AQID\n", "base64_payload"), + ], +) +def test_allowlisted_static_wrapper_still_passes_final_send_scan(tmp_path, wrapper, reason): + path = tmp_path / "private.py" + path.write_text("x=1\n", encoding="utf-8") + grant = _source_grant(path) + typed_request = _typed_request(_request("ignored"), source_grant=grant) + typed_request.payload["messages"][0]["content"] = OutboundText( + ( + LiteralSegment(wrapper), + SourceBoundSegment(source_grant_digest(grant)), + ) + ) + gate = firewall(tmp_path, static_literals={wrapper}) + with pytest.raises(EgressBlocked) as exc_info: + gate.authorize(typed_request, _route(), grants=(grant,)) + assert reason in exc_info.value.decision.reason_codes + assert not exc_info.value.decision.allowed + + def test_second_source_cannot_be_mislabeled_as_allowlisted_literal(tmp_path): first = tmp_path / "first.py" second = tmp_path / "second.py" From 06770e0438a59e83cccc55cab9acd5bd026d9d75 Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Tue, 25 Aug 2026 20:47:20 -0700 Subject: [PATCH 06/26] fix(security): block non-finite egress scalars --- agent/llm_egress_firewall.py | 4 +++ tests/agent/test_llm_egress_firewall.py | 40 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index bd256ff4bc39b..63831091804ce 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -13,6 +13,7 @@ import fcntl import ipaddress import json +import math import os import re from dataclasses import asdict, dataclass, replace @@ -688,6 +689,9 @@ def render(value: Any) -> Any: return rendered if isinstance(value, (list, tuple)): return [render(item) for item in value] + if isinstance(value, float) and not math.isfinite(value): + reasons.append("non_finite_number") + return None if value is None or isinstance(value, (bool, int, float)): require_static_literal( json.dumps(value, ensure_ascii=True, allow_nan=False, separators=(",", ":")) diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index aeb3c604eff81..65ebde9675b98 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -346,6 +346,25 @@ def test_source_bytes_are_constructed_from_grant_and_authorized_bytes_reject_tam assert "payload_digest_mismatch" in exc_info.value.decision.reason_codes +def test_dynamic_grammar_atom_still_requires_an_exact_current_source_grant(tmp_path): + path = tmp_path / "private.py" + path.write_text("user\n", encoding="utf-8") + grant = _source_grant(path) + typed_request = _typed_request(_request("ignored"), source_grant=grant) + + with pytest.raises(EgressBlocked) as missing_exc: + firewall(tmp_path).preflight(typed_request, _route(), grants=()) + assert "untrusted_provenance" in missing_exc.value.decision.reason_codes + + authorization = firewall(tmp_path).authorize(typed_request, _route(), grants=(grant,)) + assert json.loads(authorization.payload_bytes)["messages"][0]["content"] == "user\n" + + path.write_text("tool\n", encoding="utf-8") + with pytest.raises(EgressBlocked) as changed_exc: + firewall(tmp_path).preflight(typed_request, _route(), grants=(grant,)) + assert "source_hash_mismatch" in changed_exc.value.decision.reason_codes + + def test_typed_payload_identity_cannot_diverge_from_grant_binding_identity(tmp_path): path = tmp_path / "private.py" path.write_text("verified source\n", encoding="utf-8") @@ -506,6 +525,27 @@ def test_byte_and_token_caps_allow_the_exact_boundary(tmp_path): assert decision.allowed is True +@pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")]) +def test_non_finite_typed_number_is_blocked_with_content_free_receipt(tmp_path, value): + path = tmp_path / "private.py" + path.write_text("x=1\n", encoding="utf-8") + grant = _source_grant(path) + typed_request = _typed_request(_request("ignored"), source_grant=grant) + typed_request.payload["temperature"] = value + gate = firewall(tmp_path, static_literals={"temperature"}) + + with pytest.raises(EgressBlocked) as exc_info: + gate.preflight(typed_request, _route(), grants=(grant,)) + assert exc_info.value.decision.reason_codes == ("non_finite_number",) + + receipt_text = (tmp_path / "llm-egress-receipts.jsonl").read_text() + receipt = json.loads(receipt_text) + assert receipt["decision"] == "block" + assert receipt["reason_codes"] == ["non_finite_number"] + assert "NaN" not in receipt_text + assert "Infinity" not in receipt_text + + def test_allow_receipt_contains_hashes_and_counts_but_no_payload(tmp_path): path = tmp_path / "private.py" path.write_text("x=1\n", encoding="utf-8") From 6c01ee0b546e194aeaa7ca8a904dc774fae5303a Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Tue, 25 Aug 2026 21:11:39 -0700 Subject: [PATCH 07/26] feat(security): bind exact source slices to requests --- agent/context_references.py | 108 +++++++++++- agent/source_provenance.py | 224 +++++++++++++++++++++++++ agent/tool_executor.py | 73 +++++++- tests/agent/test_context_references.py | 42 +++++ tests/agent/test_source_provenance.py | 145 ++++++++++++++++ tests/tools/test_file_tools.py | 72 ++++++++ tools/file_tools.py | 68 ++++++++ 7 files changed, 725 insertions(+), 7 deletions(-) create mode 100644 agent/source_provenance.py create mode 100644 tests/agent/test_source_provenance.py diff --git a/agent/context_references.py b/agent/context_references.py index dd36e67672c3d..d2d188b3f19d3 100644 --- a/agent/context_references.py +++ b/agent/context_references.py @@ -216,6 +216,11 @@ def preprocess_context_references( context_length: int, url_fetcher: Callable[[str], str | Awaitable[str]] | None = None, allowed_root: str | Path | None = None, + source_provenance_registry=None, + session_id: str | None = None, + turn_id: str | None = None, + request_id: str | None = None, + policy_digest: str | None = None, ) -> ContextReferenceResult: coro = preprocess_context_references_async( message, @@ -223,6 +228,11 @@ def preprocess_context_references( context_length=context_length, url_fetcher=url_fetcher, allowed_root=allowed_root, + source_provenance_registry=source_provenance_registry, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, ) # Safe for both CLI (no loop) and gateway (loop already running). try: @@ -243,6 +253,11 @@ async def preprocess_context_references_async( context_length: int, url_fetcher: Callable[[str], str | Awaitable[str]] | None = None, allowed_root: str | Path | None = None, + source_provenance_registry=None, + session_id: str | None = None, + turn_id: str | None = None, + request_id: str | None = None, + policy_digest: str | None = None, ) -> ContextReferenceResult: refs = parse_context_references(message) if not refs: @@ -257,6 +272,13 @@ async def preprocess_context_references_async( warnings: list[str] = [] blocks: list[str] = [] injected_tokens = 0 + provenance_context = _build_source_provenance_context( + source_provenance_registry, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + ) # Expand all references concurrently. Each _expand_reference is independent # (no shared state during expansion) — a message with several @url: refs @@ -271,6 +293,7 @@ async def preprocess_context_references_async( cwd_path, url_fetcher=url_fetcher, allowed_root=allowed_root_path, + provenance_context=provenance_context, ) for ref in refs ) @@ -331,10 +354,16 @@ async def _expand_reference( *, url_fetcher: Callable[[str], str | Awaitable[str]] | None = None, allowed_root: Path | None = None, + provenance_context=None, ) -> tuple[str | None, str | None]: try: if ref.kind == "file": - return _expand_file_reference(ref, cwd, allowed_root=allowed_root) + return _expand_file_reference( + ref, + cwd, + allowed_root=allowed_root, + provenance_context=provenance_context, + ) if ref.kind == "folder": return _expand_folder_reference(ref, cwd, allowed_root=allowed_root) if ref.kind == "diff": @@ -370,6 +399,7 @@ def _expand_file_reference( cwd: Path, *, allowed_root: Path | None = None, + provenance_context=None, ) -> tuple[str | None, str | None]: path = _resolve_path(cwd, ref.target, allowed_root=allowed_root) _ensure_reference_path_allowed(path) @@ -387,18 +417,84 @@ def _expand_file_reference( # so it can read/convert/view the file itself. return None, _binary_reference_block(ref, path) - text = path.read_text(encoding="utf-8") if ref.line_start is not None: - lines = text.splitlines() - start_idx = max(ref.line_start - 1, 0) - end_idx = min(ref.line_end or ref.line_start, len(lines)) - text = "\n".join(lines[start_idx:end_idx]) + raw_bytes = _read_bounded_reference_slice( + path, + ref.line_start, + ref.line_end or ref.line_start, + ) + text = raw_bytes.decode("utf-8") + if provenance_context is not None: + provenance_context.registry.issue_file_slice( + path=path, + line_start=ref.line_start, + line_end=ref.line_end or ref.line_start, + content=raw_bytes, + session_id=provenance_context.session_id, + turn_id=provenance_context.turn_id, + request_id=provenance_context.request_id, + policy_digest=provenance_context.policy_digest, + ) + else: + text = path.read_text(encoding="utf-8") lang = _code_fence_language(path) label = ref.raw return None, f"📄 {label} ({estimate_tokens_rough(text)} tokens)\n```{lang}\n{text}\n```" +def _build_source_provenance_context( + registry, + *, + session_id: str | None, + turn_id: str | None, + request_id: str | None, + policy_digest: str | None, +): + """Return a trusted grant context only when the whole identity is present.""" + + if registry is None or not all( + isinstance(value, str) and value + for value in (session_id, turn_id, request_id, policy_digest) + ): + return None + from agent.source_provenance import SourceProvenanceContext, SourceProvenanceRegistry + + if not isinstance(registry, SourceProvenanceRegistry): + return None + return SourceProvenanceContext( + registry, + session_id, + turn_id, + request_id, + policy_digest, + ) + + +def _read_bounded_reference_slice(path: Path, line_start: int, line_end: int) -> bytes: + """Read only the requested exact line interval for a provenance candidate.""" + + from agent.source_provenance import MAX_SOURCE_SLICE_BYTES, MAX_SOURCE_SLICE_LINES + + if line_start < 1 or line_end < line_start or line_end - line_start + 1 > MAX_SOURCE_SLICE_LINES: + raise ValueError("file reference line range is not bounded") + selected: list[bytes] = [] + byte_count = 0 + with path.open("rb") as handle: + for line_number, raw_line in enumerate(handle, start=1): + if line_number < line_start: + continue + if line_number > line_end: + break + byte_count += len(raw_line) + if byte_count > MAX_SOURCE_SLICE_BYTES: + raise ValueError("file reference slice exceeds the byte limit") + selected.append(raw_line) + if len(selected) != line_end - line_start + 1: + raise ValueError("file reference line range is unavailable") + return b"".join(selected) + + def _expand_folder_reference( ref: ContextReference, cwd: Path, diff --git a/agent/source_provenance.py b/agent/source_provenance.py new file mode 100644 index 0000000000000..95bbdc215e34a --- /dev/null +++ b/agent/source_provenance.py @@ -0,0 +1,224 @@ +"""Trusted, request-scoped provenance for exact local file slices. + +This module deliberately has no provider-facing API. It records only grants +created by the two trusted file-read surfaces; the firewall is the later +consumer that decides whether a grant is eligible for a particular egress. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from hashlib import sha256 +from hmac import compare_digest +from pathlib import Path +from threading import RLock +from typing import Iterator + +from agent.file_safety import get_read_block_error +from agent.llm_egress_firewall import SourceGrant +from agent.redact import redact_sensitive_text + + +MAX_SOURCE_SLICE_LINES = 2_000 +MAX_SOURCE_SLICE_BYTES = 262_144 + + +class SourceProvenanceError(ValueError): + """A trusted producer could not establish file-slice provenance.""" + + +@dataclass(frozen=True, slots=True) +class SourceProvenanceContext: + """Per-call identity available only while a trusted file read executes.""" + + registry: "SourceProvenanceRegistry" + session_id: str + turn_id: str + request_id: str + policy_digest: str + + +_active_context: ContextVar[SourceProvenanceContext | None] = ContextVar( + "source_provenance_context", + default=None, +) + + +def active_source_provenance() -> SourceProvenanceContext | None: + """Return the trusted context for the current tool dispatch, if any.""" + + return _active_context.get() + + +@contextmanager +def activate_source_provenance( + registry: "SourceProvenanceRegistry", + *, + session_id: str, + turn_id: str, + request_id: str, + policy_digest: str, +) -> Iterator[SourceProvenanceContext]: + """Temporarily make an authenticated request identity available to reads.""" + + values = (session_id, turn_id, request_id, policy_digest) + if not isinstance(registry, SourceProvenanceRegistry) or not all( + isinstance(value, str) and value for value in values + ): + raise SourceProvenanceError("missing_identity") + context = SourceProvenanceContext(registry, *values) + token = _active_context.set(context) + try: + yield context + finally: + _active_context.reset(token) + + +class SourceProvenanceRegistry: + """In-memory grants keyed solely by their bound request identity.""" + + def __init__(self) -> None: + self._grants: dict[str, list[SourceGrant]] = {} + self._lock = RLock() + + def issue_file_slice( + self, + *, + path: Path, + line_start: int, + line_end: int, + content: bytes, + session_id: str, + turn_id: str, + request_id: str, + policy_digest: str, + ) -> SourceGrant: + """Grant exactly the current canonical bytes, or reject the producer. + + The caller supplies the bytes it just read, but they are never trusted + by themselves: this method re-reads the requested bounded source slice + from the resolved regular file, checks the sensitive-path policy and + forced redaction, then compares the two byte strings. + """ + + if not isinstance(path, Path): + path = Path(path) + if path.is_symlink(): + raise SourceProvenanceError("symlink_path") + if not isinstance(content, bytes): + raise SourceProvenanceError("invalid_content") + if ( + not isinstance(line_start, int) + or not isinstance(line_end, int) + or line_start < 1 + or line_end < line_start + or line_end - line_start + 1 > MAX_SOURCE_SLICE_LINES + ): + raise SourceProvenanceError("invalid_line_range") + if len(content) > MAX_SOURCE_SLICE_BYTES: + raise SourceProvenanceError("slice_too_large") + identities = (session_id, turn_id, request_id, policy_digest) + if not all(isinstance(value, str) and value for value in identities): + raise SourceProvenanceError("missing_identity") + + try: + canonical = path.expanduser().resolve(strict=True) + except OSError as exc: + raise SourceProvenanceError("canonical_path_unavailable") from exc + if not canonical.is_file(): + raise SourceProvenanceError("not_regular_file") + try: + if get_read_block_error(str(canonical)) is not None: + raise SourceProvenanceError("sensitive_path") + except SourceProvenanceError: + raise + except Exception as exc: + raise SourceProvenanceError("read_policy_unavailable") from exc + + approved = _read_bounded_slice(canonical, line_start, line_end) + if not compare_digest(sha256(content).digest(), sha256(approved).digest()): + raise SourceProvenanceError("content_mismatch") + try: + source_text = approved.decode("utf-8") + except UnicodeDecodeError as exc: + raise SourceProvenanceError("non_text_source") from exc + try: + if redact_sensitive_text( + source_text, + force=True, + file_read=True, + redact_url_credentials=True, + ) != source_text: + raise SourceProvenanceError("redaction_changed_content") + except SourceProvenanceError: + raise + except Exception as exc: + raise SourceProvenanceError("redaction_unavailable") from exc + + grant = SourceGrant( + canonical_path=canonical, + display_path=_safe_display_path(canonical), + line_start=line_start, + line_end=line_end, + content_sha256=sha256(approved).hexdigest(), + byte_count=len(approved), + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + ) + with self._lock: + self._grants.setdefault(request_id, []).append(grant) + return grant + + def grants_for_request(self, request_id: str) -> tuple[SourceGrant, ...]: + """Return an immutable snapshot of grants bound to ``request_id``.""" + + if not isinstance(request_id, str) or not request_id: + return () + with self._lock: + return tuple(self._grants.get(request_id, ())) + + def clear_request(self, request_id: str) -> None: + """Discard grants at the end of a request without touching other turns.""" + + if not isinstance(request_id, str) or not request_id: + return + with self._lock: + self._grants.pop(request_id, None) + + +def _read_bounded_slice(path: Path, line_start: int, line_end: int) -> bytes: + """Read the inclusive raw-byte line interval without materializing a file.""" + + selected: list[bytes] = [] + total = 0 + try: + with path.open("rb") as handle: + for line_number, line in enumerate(handle, start=1): + if line_number < line_start: + continue + if line_number > line_end: + break + total += len(line) + if total > MAX_SOURCE_SLICE_BYTES: + raise SourceProvenanceError("slice_too_large") + selected.append(line) + except SourceProvenanceError: + raise + except OSError as exc: + raise SourceProvenanceError("canonical_read_failed") from exc + if len(selected) != line_end - line_start + 1: + raise SourceProvenanceError("line_range_unavailable") + return b"".join(selected) + + +def _safe_display_path(path: Path) -> str: + """Keep grant metadata portable and free of an absolute home path.""" + + try: + return path.relative_to(Path.cwd().resolve()).as_posix() + except ValueError: + return path.name diff --git a/agent/tool_executor.py b/agent/tool_executor.py index 5eeef6f4d5588..1fb3dde5f9bf3 100644 --- a/agent/tool_executor.py +++ b/agent/tool_executor.py @@ -20,6 +20,7 @@ import random import threading import time +from contextlib import nullcontext from dataclasses import dataclass from typing import Any, Optional @@ -56,6 +57,73 @@ logger = logging.getLogger(__name__) +def _source_provenance_activation(agent, function_name: str): + """Activate request identity only around the trusted ``read_file`` tool.""" + + if function_name != "read_file": + return nullcontext() + try: + from agent.source_provenance import ( + SourceProvenanceRegistry, + activate_source_provenance, + ) + + session_id = str(getattr(agent, "session_id", "") or "") + turn_id = str(getattr(agent, "_current_turn_id", "") or "") + request_id = str(getattr(agent, "_current_api_request_id", "") or "") + policy_digest = str( + getattr(agent, "_llm_egress_policy_digest", "") + or getattr(agent, "llm_egress_policy_digest", "") + or "" + ) + if not all((session_id, turn_id, request_id, policy_digest)): + return nullcontext() + registry = getattr(agent, "_source_provenance_registry", None) + if registry is None: + registry = SourceProvenanceRegistry() + agent._source_provenance_registry = registry + if not isinstance(registry, SourceProvenanceRegistry): + return nullcontext() + return activate_source_provenance( + registry, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + ) + except Exception: + # Tool execution remains available; a missing identity simply cannot + # create a source grant. + return nullcontext() + + +def _attach_trusted_source_provenance_metadata(agent, function_name: str) -> None: + """Keep opaque trusted-read grant digests off the provider message path.""" + + if function_name != "read_file": + return + try: + from agent.llm_egress_firewall import source_grant_digest + from agent.source_provenance import SourceProvenanceRegistry + + registry = getattr(agent, "_source_provenance_registry", None) + request_id = str(getattr(agent, "_current_api_request_id", "") or "") + if not isinstance(registry, SourceProvenanceRegistry) or not request_id: + return + digests = tuple(source_grant_digest(grant) for grant in registry.grants_for_request(request_id)) + if not digests: + return + metadata = getattr(agent, "_source_provenance_metadata", None) + if not isinstance(metadata, dict): + metadata = {} + agent._source_provenance_metadata = metadata + metadata[request_id] = {"source_grant_digests": digests} + except Exception: + # Metadata is advisory to a later firewall consumer; never infer a + # grant from a tool error or from arbitrary terminal/general output. + return + + def _pairing_tool_call_id(tool_call: Any) -> str: """Return the canonical id used by the persisted assistant message.""" return coalesce_tool_call_id(tool_call) @@ -723,7 +791,8 @@ def _resolve_pre_tool_block(): ) _hb_thread.start() try: - return execute(final_args) + with _source_provenance_activation(agent, function_name): + return execute(final_args) finally: _hb_stop.set() _hb_thread.join(timeout=2.0) @@ -1809,6 +1878,7 @@ def _execute(next_args: dict[str, Any]) -> Any: agent._touch_activity(f"tool completed: {name} ({tool_duration:.1f}s){_status_suffix}") display_function_result = function_result + _attach_trusted_source_provenance_metadata(agent, name) function_result = maybe_persist_tool_result( content=function_result, tool_name=name, @@ -2731,6 +2801,7 @@ def _execute(next_args: dict) -> Any: logging.debug("Tool result (%d chars): %s", len(_log_result), _log_result) display_function_result = function_result + _attach_trusted_source_provenance_metadata(agent, function_name) function_result = maybe_persist_tool_result( content=function_result, tool_name=function_name, diff --git a/tests/agent/test_context_references.py b/tests/agent/test_context_references.py index b58623584b8ff..be70daedd80fb 100644 --- a/tests/agent/test_context_references.py +++ b/tests/agent/test_context_references.py @@ -72,6 +72,48 @@ def test_parse_typed_references_ignores_emails_and_handles(): assert refs[2].target == "2" +def test_exact_file_reference_issues_only_the_resolved_slice(sample_repo: Path): + from agent.context_references import preprocess_context_references + from agent.source_provenance import SourceProvenanceRegistry + + registry = SourceProvenanceRegistry() + result = preprocess_context_references( + "Review @file:src/main.py:4-5", + cwd=sample_repo, + context_length=100_000, + source_provenance_registry=registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ) + + grant = registry.grants_for_request("request-1")[0] + expected = b"".join((sample_repo / "src" / "main.py").read_bytes().splitlines(keepends=True)[3:5]) + assert result.expanded + assert (grant.line_start, grant.line_end) == (4, 5) + assert grant.content_sha256 == __import__("hashlib").sha256(expected).hexdigest() + + +def test_context_reference_without_exact_range_cannot_issue_a_grant(sample_repo: Path): + from agent.context_references import preprocess_context_references + from agent.source_provenance import SourceProvenanceRegistry + + registry = SourceProvenanceRegistry() + preprocess_context_references( + "Review @file:src/main.py", + cwd=sample_repo, + context_length=100_000, + source_provenance_registry=registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ) + + assert registry.grants_for_request("request-1") == () + + diff --git a/tests/agent/test_source_provenance.py b/tests/agent/test_source_provenance.py new file mode 100644 index 0000000000000..8893756e64471 --- /dev/null +++ b/tests/agent/test_source_provenance.py @@ -0,0 +1,145 @@ +"""Focused contracts for trusted file-slice provenance.""" + +from __future__ import annotations + +from hashlib import sha256 +from pathlib import Path +from types import SimpleNamespace + +import pytest + + +def _identity() -> dict[str, str]: + return { + "session_id": "session-1", + "turn_id": "turn-1", + "request_id": "request-1", + "policy_digest": "policy-1", + } + + +def test_registry_issues_only_an_exact_current_canonical_slice(tmp_path: Path): + from agent.source_provenance import SourceProvenanceRegistry + + source = tmp_path / "src" / "app.py" + source.parent.mkdir() + source.write_text("one\ntwo\nthree\nfour\n", encoding="utf-8") + approved = b"two\nthree\n" + + registry = SourceProvenanceRegistry() + grant = registry.issue_file_slice( + path=source, + line_start=2, + line_end=3, + content=approved, + **_identity(), + ) + + assert grant.canonical_path == source.resolve() + assert (grant.line_start, grant.line_end) == (2, 3) + assert grant.content_sha256 == sha256(approved).hexdigest() + assert registry.grants_for_request("request-1") == (grant,) + + +def test_registry_rejects_adjacent_or_mutated_bytes(tmp_path: Path): + from agent.source_provenance import SourceProvenanceError, SourceProvenanceRegistry + + source = tmp_path / "app.py" + source.write_text("one\ntwo\nthree\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + + with pytest.raises(SourceProvenanceError, match="content_mismatch"): + registry.issue_file_slice( + path=source, + line_start=2, + line_end=2, + content=b"one\ntwo\n", + **_identity(), + ) + + source.write_text("one\nchanged\nthree\n", encoding="utf-8") + with pytest.raises(SourceProvenanceError, match="content_mismatch"): + registry.issue_file_slice( + path=source, + line_start=2, + line_end=2, + content=b"two\n", + **_identity(), + ) + + assert registry.grants_for_request("request-1") == () + + +def test_registry_fails_closed_for_symlink_and_redacted_content(tmp_path: Path): + from agent.source_provenance import SourceProvenanceError, SourceProvenanceRegistry + + target = tmp_path / "target.py" + target.write_text("safe\n", encoding="utf-8") + link = tmp_path / "link.py" + link.symlink_to(target) + registry = SourceProvenanceRegistry() + + with pytest.raises(SourceProvenanceError, match="symlink"): + registry.issue_file_slice( + path=link, + line_start=1, + line_end=1, + content=b"safe\n", + **_identity(), + ) + + target.write_text("token=sk-12345678901234567890\n", encoding="utf-8") + with pytest.raises(SourceProvenanceError, match="redaction"): + registry.issue_file_slice( + path=target, + line_start=1, + line_end=1, + content=target.read_bytes(), + **_identity(), + ) + + +def test_registry_keeps_grants_request_scoped_and_clearable(tmp_path: Path): + from agent.source_provenance import SourceProvenanceRegistry + + source = tmp_path / "app.py" + source.write_text("safe\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + grant = registry.issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"safe\n", + **_identity(), + ) + + assert registry.grants_for_request("other-request") == () + registry.clear_request("request-1") + assert registry.grants_for_request(grant.request_id) == () + + +def test_tool_executor_records_only_opaque_trusted_read_grant_metadata(tmp_path: Path): + from agent.source_provenance import SourceProvenanceRegistry + from agent.tool_executor import _attach_trusted_source_provenance_metadata + + source = tmp_path / "app.py" + source.write_text("safe\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + registry.issue_file_slice(path=source, line_start=1, line_end=1, content=b"safe\n", **_identity()) + agent = SimpleNamespace( + _source_provenance_registry=registry, + _current_api_request_id="request-1", + ) + + _attach_trusted_source_provenance_metadata(agent, "read_file") + + metadata = agent._source_provenance_metadata["request-1"] + assert len(metadata["source_grant_digests"]) == 1 + assert "safe" not in repr(metadata) + + terminal_agent = SimpleNamespace( + _source_provenance_registry=registry, + _current_api_request_id="request-1", + ) + _attach_trusted_source_provenance_metadata(terminal_agent, "terminal") + assert not hasattr(terminal_agent, "_source_provenance_metadata") diff --git a/tests/tools/test_file_tools.py b/tests/tools/test_file_tools.py index 068b3d9f2b60a..2c70d42f97e21 100644 --- a/tests/tools/test_file_tools.py +++ b/tests/tools/test_file_tools.py @@ -42,6 +42,78 @@ def test_exception_returns_error_json(self, mock_get): assert "terminal not available" in result["error"] +def test_successful_bounded_read_issues_opaque_grant(tmp_path): + from agent.source_provenance import SourceProvenanceRegistry, activate_source_provenance + from tools.file_tools import read_file_tool + + source = tmp_path / "source.py" + source.write_text("one\ntwo\nthree\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + with activate_source_provenance( + registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ): + result = json.loads(read_file_tool(str(source), offset=2, limit=1)) + + assert result["content"] + grant = registry.grants_for_request("request-1")[0] + assert (grant.line_start, grant.line_end) == (2, 2) + assert grant.content_sha256 == __import__("hashlib").sha256(b"two\n").hexdigest() + + +def test_read_errors_or_untrusted_tool_text_cannot_issue_grants(tmp_path): + from agent.source_provenance import SourceProvenanceRegistry, activate_source_provenance + from tools.file_tools import read_file_tool + + registry = SourceProvenanceRegistry() + with activate_source_provenance( + registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ): + read_file_tool(str(tmp_path / "missing.py"), offset=1, limit=1) + + assert registry.grants_for_request("request-1") == () + + +def test_forged_read_result_cannot_issue_a_grant(tmp_path, monkeypatch): + from agent.source_provenance import SourceProvenanceRegistry, activate_source_provenance + from tools.file_operations import ReadResult + from tools.file_tools import read_file_tool + + source = tmp_path / "source.py" + source.write_text("actual\n", encoding="utf-8") + + class ForgedFileOps: + env = None + + @staticmethod + def read_file(*_args): + return ReadResult(content="1|forged", total_lines=1, file_size=7) + + @staticmethod + def _add_line_numbers(content, offset): + return f"{offset}|{content}" + + monkeypatch.setattr("tools.file_tools._get_file_ops", lambda _task_id: ForgedFileOps()) + registry = SourceProvenanceRegistry() + with activate_source_provenance( + registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ): + read_file_tool(str(source), offset=1, limit=1) + + assert registry.grants_for_request("request-1") == () + + class TestWriteFileHandler: @patch("tools.file_tools._get_file_ops") def test_writes_content(self, mock_get): diff --git a/tools/file_tools.py b/tools/file_tools.py index 3f3730149fe92..a31c970f1ae09 100644 --- a/tools/file_tools.py +++ b/tools/file_tools.py @@ -24,6 +24,7 @@ ) from tools import file_state from agent.redact import redact_sensitive_text +from agent.source_provenance import active_source_provenance logger = logging.getLogger(__name__) @@ -133,6 +134,62 @@ def _truncate_to_char_budget(content: str, max_chars: int) -> tuple[str, int, bo return "\n".join(kept), len(kept), True +def _issue_active_read_provenance( + *, + resolved: Path | PurePosixPath, + offset: int, + limit: int, + returned_content: str, + result_dict: dict, + file_ops, +) -> None: + """Issue provenance only for a verified local ``read_file`` result. + + A registry never treats the JSON returned by an arbitrary tool as source + evidence. For the trusted host file tool, re-read the exact bounded raw + interval and require that its line-numbered projection exactly equals the + successful, unredacted result before minting a grant. + """ + + context = active_source_provenance() + if context is None or not isinstance(resolved, Path): + return + if result_dict.get("error") or result_dict.get("truncated_by") or not returned_content: + return + try: + canonical = resolved.resolve(strict=True) + if resolved.is_symlink() or not canonical.is_file(): + return + selected: list[bytes] = [] + with canonical.open("rb") as handle: + for line_number, raw_line in enumerate(handle, start=1): + if line_number < offset: + continue + if line_number >= offset + limit: + break + selected.append(raw_line) + if not selected: + return + raw = b"".join(selected) + expected = file_ops._add_line_numbers(raw.decode("utf-8"), offset) + if returned_content != expected: + return + context.registry.issue_file_slice( + path=resolved, + line_start=offset, + line_end=offset + len(selected) - 1, + content=raw, + session_id=context.session_id, + turn_id=context.turn_id, + request_id=context.request_id, + policy_digest=context.policy_digest, + ) + except Exception: + # This is a provenance failure, never a reason to turn an ordinary + # read into a more permissive source grant. + return + + # If the total file size exceeds this AND the caller didn't specify a narrow # range (limit <= 200), we include a hint encouraging targeted reads. _LARGE_FILE_HINT_BYTES = 512_000 # 512 KB @@ -1918,6 +1975,7 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 2000, task_id: str = content_len = len(trimmed) # ── Redact secrets (after guard check to skip oversized content) ── + content_before_redaction = result.content or "" if result.content: result.content = redact_sensitive_text(result.content, file_read=True) result_dict["content"] = result.content @@ -1998,6 +2056,16 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 2000, task_id: str = "If you are stuck in a loop, stop reading and proceed with writing or responding." ) + if result.content == content_before_redaction: + _issue_active_read_provenance( + resolved=_resolved, + offset=offset, + limit=limit, + returned_content=result.content, + result_dict=result_dict, + file_ops=file_ops, + ) + return json.dumps(result_dict, ensure_ascii=False) except Exception as e: return tool_error(str(e)) From 44d631cbacccc0a43042743dd3fd46d79c40a993 Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Tue, 25 Aug 2026 21:45:06 -0700 Subject: [PATCH 08/26] fix(security): harden source provenance lifecycle --- agent/source_provenance.py | 210 ++++++++++++++++++++++---- cli.py | 15 +- run_agent.py | 11 ++ tests/agent/test_source_provenance.py | 172 +++++++++++++++++++++ tui_gateway/server.py | 6 + 5 files changed, 387 insertions(+), 27 deletions(-) diff --git a/agent/source_provenance.py b/agent/source_provenance.py index 95bbdc215e34a..aadae6939572c 100644 --- a/agent/source_provenance.py +++ b/agent/source_provenance.py @@ -12,7 +12,9 @@ from dataclasses import dataclass from hashlib import sha256 from hmac import compare_digest +import os from pathlib import Path +import stat from threading import RLock from typing import Iterator @@ -23,6 +25,8 @@ MAX_SOURCE_SLICE_LINES = 2_000 MAX_SOURCE_SLICE_BYTES = 262_144 +MAX_GRANTS_PER_REQUEST = 64 +DEFAULT_POLICY_DIGEST = sha256(b"hermes-llm-egress-policy-v1").hexdigest() class SourceProvenanceError(ValueError): @@ -105,7 +109,8 @@ def issue_file_slice( if not isinstance(path, Path): path = Path(path) - if path.is_symlink(): + original_path = Path(path).expanduser() + if _contains_symlink_component(original_path): raise SourceProvenanceError("symlink_path") if not isinstance(content, bytes): raise SourceProvenanceError("invalid_content") @@ -124,42 +129,63 @@ def issue_file_slice( raise SourceProvenanceError("missing_identity") try: - canonical = path.expanduser().resolve(strict=True) + descriptor = _open_verified_source(original_path) + except SourceProvenanceError: + raise except OSError as exc: raise SourceProvenanceError("canonical_path_unavailable") from exc - if not canonical.is_file(): - raise SourceProvenanceError("not_regular_file") try: - if get_read_block_error(str(canonical)) is not None: - raise SourceProvenanceError("sensitive_path") + canonical = original_path.resolve(strict=True) + if not canonical.is_file(): + raise SourceProvenanceError("not_regular_file") + opened_stat = os.fstat(descriptor) + named_stat = os.stat(canonical, follow_symlinks=False) + if (opened_stat.st_dev, opened_stat.st_ino) != (named_stat.st_dev, named_stat.st_ino): + raise SourceProvenanceError("source_changed") except SourceProvenanceError: + os.close(descriptor) raise - except Exception as exc: - raise SourceProvenanceError("read_policy_unavailable") from exc - - approved = _read_bounded_slice(canonical, line_start, line_end) - if not compare_digest(sha256(content).digest(), sha256(approved).digest()): - raise SourceProvenanceError("content_mismatch") - try: - source_text = approved.decode("utf-8") - except UnicodeDecodeError as exc: - raise SourceProvenanceError("non_text_source") from exc + except OSError as exc: + os.close(descriptor) + raise SourceProvenanceError("canonical_path_unavailable") from exc try: - if redact_sensitive_text( - source_text, - force=True, - file_read=True, - redact_url_credentials=True, - ) != source_text: - raise SourceProvenanceError("redaction_changed_content") + blocked = get_read_block_error(str(canonical)) except SourceProvenanceError: + os.close(descriptor) raise except Exception as exc: - raise SourceProvenanceError("redaction_unavailable") from exc + os.close(descriptor) + raise SourceProvenanceError("read_policy_unavailable") from exc + if blocked is not None: + os.close(descriptor) + raise SourceProvenanceError("sensitive_path") + + try: + approved = _read_bounded_slice_fd(descriptor, line_start, line_end) + if not compare_digest(sha256(content).digest(), sha256(approved).digest()): + raise SourceProvenanceError("content_mismatch") + try: + source_text = approved.decode("utf-8") + except UnicodeDecodeError as exc: + raise SourceProvenanceError("non_text_source") from exc + try: + if redact_sensitive_text( + source_text, + force=True, + file_read=True, + redact_url_credentials=True, + ) != source_text: + raise SourceProvenanceError("redaction_changed_content") + except SourceProvenanceError: + raise + except Exception as exc: + raise SourceProvenanceError("redaction_unavailable") from exc + finally: + os.close(descriptor) grant = SourceGrant( canonical_path=canonical, - display_path=_safe_display_path(canonical), + display_path=_safe_display_path(original_path), line_start=line_start, line_end=line_end, content_sha256=sha256(approved).hexdigest(), @@ -170,9 +196,22 @@ def issue_file_slice( policy_digest=policy_digest, ) with self._lock: + if len(self._grants.get(request_id, ())) >= MAX_GRANTS_PER_REQUEST: + raise SourceProvenanceError("grant_limit_exceeded") self._grants.setdefault(request_id, []).append(grant) return grant + @contextmanager + def request_scope(self, request_id: str) -> Iterator["SourceProvenanceRegistry"]: + """Bound grants to one request and clear them on every exit path.""" + + if not isinstance(request_id, str) or not request_id: + raise SourceProvenanceError("missing_identity") + try: + yield self + finally: + self.clear_request(request_id) + def grants_for_request(self, request_id: str) -> tuple[SourceGrant, ...]: """Return an immutable snapshot of grants bound to ``request_id``.""" @@ -189,6 +228,63 @@ def clear_request(self, request_id: str) -> None: with self._lock: self._grants.pop(request_id, None) + def clear_turn(self, turn_id: str) -> None: + """Discard every request grant belonging to one completed turn.""" + + if not isinstance(turn_id, str) or not turn_id: + return + with self._lock: + stale = [ + request_id + for request_id, grants in self._grants.items() + if any(grant.turn_id == turn_id for grant in grants) + ] + for request_id in stale: + self._grants.pop(request_id, None) + + +def provenance_kwargs_for_agent(agent, *, request_id: str | None = None) -> dict[str, object]: + """Return authenticated context-reference kwargs for a live agent turn.""" + + session_id = str(getattr(agent, "session_id", "") or "") + turn_id = str(getattr(agent, "_current_turn_id", "") or "") + resolved_request_id = str( + request_id + or getattr(agent, "_current_api_request_id", "") + or (f"{turn_id}:context" if turn_id else "") + ) + policy_digest = str( + getattr(agent, "_llm_egress_policy_digest", "") + or getattr(agent, "llm_egress_policy_digest", "") + or DEFAULT_POLICY_DIGEST + ) + if not all((session_id, turn_id, resolved_request_id, policy_digest)): + return {} + registry = getattr(agent, "_source_provenance_registry", None) + if not isinstance(registry, SourceProvenanceRegistry): + registry = SourceProvenanceRegistry() + agent._source_provenance_registry = registry + return { + "source_provenance_registry": registry, + "session_id": session_id, + "turn_id": turn_id, + "request_id": resolved_request_id, + "policy_digest": policy_digest, + } + + +def clear_agent_source_provenance(agent, *, request_id: str | None = None) -> None: + """Clear request/turn grants when a caller abandons context expansion.""" + + registry = getattr(agent, "_source_provenance_registry", None) + if not isinstance(registry, SourceProvenanceRegistry): + return + resolved_request_id = str(request_id or getattr(agent, "_current_api_request_id", "") or "") + if resolved_request_id: + registry.clear_request(resolved_request_id) + return + registry.clear_turn(str(getattr(agent, "_current_turn_id", "") or "")) + def _read_bounded_slice(path: Path, line_start: int, line_end: int) -> bytes: """Read the inclusive raw-byte line interval without materializing a file.""" @@ -215,10 +311,72 @@ def _read_bounded_slice(path: Path, line_start: int, line_end: int) -> bytes: return b"".join(selected) +def _contains_symlink_component(path: Path) -> bool: + """Check the original spelling before any resolution can erase a link.""" + + absolute = path if path.is_absolute() else Path.cwd() / path + current = Path(absolute.anchor) + for component in absolute.parts[1:]: + current /= component + try: + if current.is_symlink(): + return True + except OSError as exc: + raise SourceProvenanceError("symlink_check_failed") from exc + return False + + +def _open_verified_source(path: Path) -> int: + """Open once with no-follow semantics and reject non-regular/hardlinked files.""" + + flags = os.O_RDONLY + if hasattr(os, "O_CLOEXEC"): + flags |= os.O_CLOEXEC + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + descriptor = os.open(path, flags) + try: + file_stat = os.fstat(descriptor) + if not stat.S_ISREG(file_stat.st_mode): + raise SourceProvenanceError("not_regular_file") + if file_stat.st_nlink != 1: + raise SourceProvenanceError("unsafe_hardlink") + return descriptor + except Exception: + os.close(descriptor) + raise + + +def _read_bounded_slice_fd(descriptor: int, line_start: int, line_end: int) -> bytes: + """Read complete selected lines from the already-verified descriptor.""" + + selected: list[bytes] = [] + total = 0 + try: + with os.fdopen(os.dup(descriptor), "rb") as handle: + for line_number, line in enumerate(handle, start=1): + if line_number < line_start: + continue + if line_number > line_end: + break + total += len(line) + if total > MAX_SOURCE_SLICE_BYTES: + raise SourceProvenanceError("slice_too_large") + selected.append(line) + except SourceProvenanceError: + raise + except OSError as exc: + raise SourceProvenanceError("canonical_read_failed") from exc + if len(selected) != line_end - line_start + 1: + raise SourceProvenanceError("line_range_unavailable") + return b"".join(selected) + + def _safe_display_path(path: Path) -> str: """Keep grant metadata portable and free of an absolute home path.""" try: - return path.relative_to(Path.cwd().resolve()).as_posix() + absolute = path if path.is_absolute() else Path.cwd() / path + return absolute.relative_to(Path.cwd().resolve()).as_posix() except ValueError: return path.name diff --git a/cli.py b/cli.py index 2600a5845ccfa..7c76de288e5a1 100644 --- a/cli.py +++ b/cli.py @@ -16395,8 +16395,16 @@ def chat(self, message, images: list = None, voice_input: bool = False) -> Optio self.model, base_url=self.base_url or "", api_key=self.api_key or "", provider=self.provider or "", config_context_length=getattr(self.agent, "_config_context_length", None) if self.agent else None) + from agent.source_provenance import ( + clear_agent_source_provenance, + provenance_kwargs_for_agent, + ) _ctx_result = preprocess_context_references( - message, cwd=os.getcwd(), context_length=_ctx_len) + message, + cwd=os.getcwd(), + context_length=_ctx_len, + **provenance_kwargs_for_agent(agent), + ) if _ctx_result.expanded or _ctx_result.blocked: if _ctx_result.references: _cprint( @@ -16405,9 +16413,14 @@ def chat(self, message, images: list = None, voice_input: bool = False) -> Optio for w in _ctx_result.warnings: _cprint(f" {_DIM}⚠ {w}{_RST}") if _ctx_result.blocked: + clear_agent_source_provenance(agent) return "\n".join(_ctx_result.warnings) or "Context injection refused." message = _ctx_result.message except Exception as e: + try: + clear_agent_source_provenance(agent) + except Exception: + pass logging.debug("@ context reference expansion failed: %s", e) # Sanitize surrogate characters that can arrive via clipboard paste from diff --git a/run_agent.py b/run_agent.py index c6638b6cacde5..8aeb8ab0f5ff5 100644 --- a/run_agent.py +++ b/run_agent.py @@ -8958,6 +8958,17 @@ def _interrupt_turn(message: str) -> None: self._active_session_turn_lease_ttl_seconds = None # Always clear mid-turn labels when the turn exits — including # interrupted early returns that skip finalize_turn. Keep ts. + try: + from agent.source_provenance import SourceProvenanceRegistry + + provenance_registry = getattr(self, "_source_provenance_registry", None) + if isinstance(provenance_registry, SourceProvenanceRegistry): + provenance_registry.clear_turn(relay_turn_id) + provenance_registry.clear_turn( + str(getattr(self, "_current_turn_id", "") or "") + ) + except Exception: + logger.debug("source provenance cleanup failed", exc_info=True) try: self._reset_activity_labels_after_turn() except Exception: diff --git a/tests/agent/test_source_provenance.py b/tests/agent/test_source_provenance.py index 8893756e64471..9bad9649f486a 100644 --- a/tests/agent/test_source_provenance.py +++ b/tests/agent/test_source_provenance.py @@ -38,6 +38,7 @@ def test_registry_issues_only_an_exact_current_canonical_slice(tmp_path: Path): assert grant.canonical_path == source.resolve() assert (grant.line_start, grant.line_end) == (2, 3) assert grant.content_sha256 == sha256(approved).hexdigest() + assert grant.display_path == source.name assert registry.grants_for_request("request-1") == (grant,) @@ -99,6 +100,177 @@ def test_registry_fails_closed_for_symlink_and_redacted_content(tmp_path: Path): ) +def test_registry_rejects_symlinked_parent_before_resolution(tmp_path: Path): + from agent.source_provenance import SourceProvenanceError, SourceProvenanceRegistry + + real_dir = tmp_path / "real" + real_dir.mkdir() + source = real_dir / "source.py" + source.write_text("safe\n", encoding="utf-8") + link_dir = tmp_path / "linked" + link_dir.symlink_to(real_dir, target_is_directory=True) + + with pytest.raises(SourceProvenanceError, match="symlink"): + SourceProvenanceRegistry().issue_file_slice( + path=link_dir / "source.py", + line_start=1, + line_end=1, + content=b"safe\n", + **_identity(), + ) + + +def test_registry_rejects_unsafe_hardlink_alias(tmp_path: Path): + from agent.source_provenance import SourceProvenanceError, SourceProvenanceRegistry + + source = tmp_path / "source.py" + source.write_text("safe\n", encoding="utf-8") + alias = tmp_path / "alias.py" + alias.hardlink_to(source) + + with pytest.raises(SourceProvenanceError, match="hardlink"): + SourceProvenanceRegistry().issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"safe\n", + **_identity(), + ) + + +def test_registry_never_grants_unseen_or_line_truncated_bytes(tmp_path: Path): + from agent.source_provenance import SourceProvenanceError, SourceProvenanceRegistry + + source = tmp_path / "source.py" + source.write_text("first\nsecond\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + + with pytest.raises(SourceProvenanceError, match="content_mismatch"): + registry.issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"first", # no newline: not the complete selected line + **_identity(), + ) + with pytest.raises(SourceProvenanceError, match="line_range"): + registry.issue_file_slice( + path=source, + line_start=3, + line_end=3, + content=b"", + **_identity(), + ) + + +def test_registry_bounds_grants_per_request(tmp_path: Path): + from agent.source_provenance import SourceProvenanceError, SourceProvenanceRegistry + + source = tmp_path / "source.py" + source.write_text("safe\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + for _ in range(64): + registry.issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"safe\n", + **_identity(), + ) + with pytest.raises(SourceProvenanceError, match="grant_limit"): + registry.issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"safe\n", + **_identity(), + ) + + +def test_request_scope_clears_grants_on_success_error_and_cancel(tmp_path: Path): + from agent.source_provenance import SourceProvenanceRegistry + + source = tmp_path / "source.py" + source.write_text("safe\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + + for outcome in ("success", "error", "cancel"): + request_id = f"request-{outcome}" + with registry.request_scope(request_id): + registry.issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"safe\n", + **{**_identity(), "request_id": request_id}, + ) + assert registry.grants_for_request(request_id) + if outcome == "error": + with pytest.raises(RuntimeError): + raise RuntimeError("tool failed") + elif outcome == "cancel": + with pytest.raises(KeyboardInterrupt): + raise KeyboardInterrupt + assert registry.grants_for_request(request_id) == () + + +def test_registry_can_clear_all_request_grants_for_a_completed_turn(tmp_path: Path): + from agent.source_provenance import SourceProvenanceRegistry + + source = tmp_path / "source.py" + source.write_text("safe\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + for request_id in ("request-1", "request-2"): + registry.issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"safe\n", + **{**_identity(), "request_id": request_id}, + ) + registry.issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"safe\n", + **{**_identity(), "request_id": "other", "turn_id": "other-turn"}, + ) + + registry.clear_turn("turn-1") + assert registry.grants_for_request("request-1") == () + assert registry.grants_for_request("request-2") == () + assert registry.grants_for_request("other") + + +def test_provenance_kwargs_for_live_agent_bind_registry_and_request_identity(): + from agent.source_provenance import ( + DEFAULT_POLICY_DIGEST, + SourceProvenanceRegistry, + provenance_kwargs_for_agent, + ) + + agent = type( + "Agent", + (), + {"session_id": "session-1", "_current_turn_id": "turn-1"}, + )() + kwargs = provenance_kwargs_for_agent(agent) + + assert isinstance(kwargs["source_provenance_registry"], SourceProvenanceRegistry) + assert kwargs["session_id"] == "session-1" + assert kwargs["turn_id"] == "turn-1" + assert kwargs["request_id"] == "turn-1:context" + assert kwargs["policy_digest"] == DEFAULT_POLICY_DIGEST + + +def test_cli_and_tui_file_reference_callers_pass_authenticated_provenance(): + cli_source = Path("cli.py").read_text(encoding="utf-8") + tui_source = Path("tui_gateway/server.py").read_text(encoding="utf-8") + + assert "**provenance_kwargs_for_agent(agent)" in cli_source + assert "**provenance_kwargs_for_agent(agent)" in tui_source + + def test_registry_keeps_grants_request_scoped_and_clearable(tmp_path: Path): from agent.source_provenance import SourceProvenanceRegistry diff --git a/tui_gateway/server.py b/tui_gateway/server.py index e6a669af62890..e0f8cb899e3c1 100644 --- a/tui_gateway/server.py +++ b/tui_gateway/server.py @@ -11566,13 +11566,19 @@ def run(): agent, "_config_context_length", None ), ) + from agent.source_provenance import ( + clear_agent_source_provenance, + provenance_kwargs_for_agent, + ) ctx = preprocess_context_references( prompt, cwd=cwd, allowed_root=cwd, context_length=ctx_len, + **provenance_kwargs_for_agent(agent), ) if ctx.blocked: + clear_agent_source_provenance(agent) _emit( "error", sid, From 83ad001cbaf12609378525fd1a0396c2c82929e6 Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Tue, 25 Aug 2026 22:36:28 -0700 Subject: [PATCH 09/26] fix(security): harden source-bound egress provenance --- agent/context_references.py | 8 +- agent/llm_egress_firewall.py | 4 + agent/source_provenance.py | 54 +++++++++++-- agent/tool_executor.py | 17 +++- cli.py | 2 +- run_agent.py | 7 +- tests/agent/test_context_references.py | 48 +++++++++++ tests/agent/test_llm_egress_firewall.py | 21 +++++ tests/agent/test_source_provenance.py | 101 ++++++++++++++++++++++-- tests/tools/test_file_tools.py | 69 ++++++++++++++++ tools/file_tools.py | 23 +++++- tui_gateway/server.py | 2 +- 12 files changed, 333 insertions(+), 23 deletions(-) diff --git a/agent/context_references.py b/agent/context_references.py index d2d188b3f19d3..ab96198c1c431 100644 --- a/agent/context_references.py +++ b/agent/context_references.py @@ -401,6 +401,9 @@ def _expand_file_reference( allowed_root: Path | None = None, provenance_context=None, ) -> tuple[str | None, str | None]: + source_path = Path(os.path.expanduser(ref.target)) + if not source_path.is_absolute(): + source_path = cwd / source_path path = _resolve_path(cwd, ref.target, allowed_root=allowed_root) _ensure_reference_path_allowed(path) if not path.exists(): @@ -426,7 +429,10 @@ def _expand_file_reference( text = raw_bytes.decode("utf-8") if provenance_context is not None: provenance_context.registry.issue_file_slice( - path=path, + # Preserve the caller's original path chain. Passing the + # resolved path here would erase a symlinked leaf or ancestor + # before SourceProvenanceRegistry can reject it. + path=source_path, line_start=ref.line_start, line_end=ref.line_end or ref.line_start, content=raw_bytes, diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index 63831091804ce..ebac993a9296b 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -365,6 +365,7 @@ def __init__( max_serialized_bytes: int = 262_144, max_conservative_tokens: int = 87_382, conservative_chars_per_token: int = 3, + policy_digest: str | None = None, static_literal_hashes_by_policy: Mapping[str, Sequence[str]] | None = None, ) -> None: if max_serialized_bytes <= 0: @@ -378,6 +379,7 @@ def __init__( self._max_serialized_bytes = max_serialized_bytes self._max_conservative_tokens = max_conservative_tokens self._conservative_chars_per_token = conservative_chars_per_token + self._policy_digest = str(policy_digest or "") self._static_literal_hashes_by_policy = { str(policy_digest): frozenset( digest @@ -439,6 +441,8 @@ def authorize( if destination == DestinationClass.UNKNOWN: reasons.append("unknown_destination") + if self._policy_digest and policy_digest != self._policy_digest: + reasons.append("policy_digest_mismatch") if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN}: if typed_request is None: reasons.append("typed_request_required") diff --git a/agent/source_provenance.py b/agent/source_provenance.py index aadae6939572c..ebb3a21783478 100644 --- a/agent/source_provenance.py +++ b/agent/source_provenance.py @@ -17,6 +17,7 @@ import stat from threading import RLock from typing import Iterator +import uuid from agent.file_safety import get_read_block_error from agent.llm_egress_firewall import SourceGrant @@ -243,13 +244,36 @@ def clear_turn(self, turn_id: str) -> None: self._grants.pop(request_id, None) -def provenance_kwargs_for_agent(agent, *, request_id: str | None = None) -> dict[str, object]: +def provenance_kwargs_for_agent( + agent, + *, + request_id: str | None = None, + establish_turn: bool = False, +) -> dict[str, object]: """Return authenticated context-reference kwargs for a live agent turn.""" session_id = str(getattr(agent, "session_id", "") or "") - turn_id = str(getattr(agent, "_current_turn_id", "") or "") + registry = getattr(agent, "_source_provenance_registry", None) + if not isinstance(registry, SourceProvenanceRegistry): + registry = SourceProvenanceRegistry() + agent._source_provenance_registry = registry + + if establish_turn: + previous_turn_id = str(getattr(agent, "_current_turn_id", "") or "") + previous_request_id = str(getattr(agent, "_current_api_request_id", "") or "") + if previous_request_id: + registry.clear_request(previous_request_id) + if previous_turn_id: + registry.clear_turn(previous_turn_id) + turn_id = f"{session_id or 'session'}:context:{uuid.uuid4().hex[:8]}" + agent._source_provenance_pending_turn_id = turn_id + else: + turn_id = str(getattr(agent, "_current_turn_id", "") or "") resolved_request_id = str( request_id + # The conversation loop increments ``api_call_count`` before building + # its first provider request, so the first consuming identity is 1. + or (f"{turn_id}:api:1" if establish_turn and turn_id else "") or getattr(agent, "_current_api_request_id", "") or (f"{turn_id}:context" if turn_id else "") ) @@ -260,10 +284,6 @@ def provenance_kwargs_for_agent(agent, *, request_id: str | None = None) -> dict ) if not all((session_id, turn_id, resolved_request_id, policy_digest)): return {} - registry = getattr(agent, "_source_provenance_registry", None) - if not isinstance(registry, SourceProvenanceRegistry): - registry = SourceProvenanceRegistry() - agent._source_provenance_registry = registry return { "source_provenance_registry": registry, "session_id": session_id, @@ -279,6 +299,12 @@ def clear_agent_source_provenance(agent, *, request_id: str | None = None) -> No registry = getattr(agent, "_source_provenance_registry", None) if not isinstance(registry, SourceProvenanceRegistry): return + pending_turn_id = str( + getattr(agent, "_source_provenance_pending_turn_id", "") or "" + ) + if pending_turn_id: + registry.clear_turn(pending_turn_id) + agent._source_provenance_pending_turn_id = None resolved_request_id = str(request_id or getattr(agent, "_current_api_request_id", "") or "") if resolved_request_id: registry.clear_request(resolved_request_id) @@ -286,6 +312,22 @@ def clear_agent_source_provenance(agent, *, request_id: str | None = None) -> No registry.clear_turn(str(getattr(agent, "_current_turn_id", "") or "")) +def following_api_request_id(request_id: str, turn_id: str) -> str: + """Bind trusted tool output to the API request that will consume it.""" + + if not turn_id: + return request_id + prefix = f"{turn_id}:api:" + if request_id.startswith(prefix): + try: + return f"{prefix}{int(request_id[len(prefix):]) + 1}" + except ValueError: + pass + # An unparseable current request cannot be projected to an exact future + # request. Keep the read available but issue no usable grant. + return "" + + def _read_bounded_slice(path: Path, line_start: int, line_end: int) -> bytes: """Read the inclusive raw-byte line interval without materializing a file.""" diff --git a/agent/tool_executor.py b/agent/tool_executor.py index 1fb3dde5f9bf3..1da4ea3594fb3 100644 --- a/agent/tool_executor.py +++ b/agent/tool_executor.py @@ -64,17 +64,22 @@ def _source_provenance_activation(agent, function_name: str): return nullcontext() try: from agent.source_provenance import ( + DEFAULT_POLICY_DIGEST, SourceProvenanceRegistry, activate_source_provenance, + following_api_request_id, ) session_id = str(getattr(agent, "session_id", "") or "") turn_id = str(getattr(agent, "_current_turn_id", "") or "") - request_id = str(getattr(agent, "_current_api_request_id", "") or "") + request_id = following_api_request_id( + str(getattr(agent, "_current_api_request_id", "") or ""), + turn_id, + ) policy_digest = str( getattr(agent, "_llm_egress_policy_digest", "") or getattr(agent, "llm_egress_policy_digest", "") - or "" + or DEFAULT_POLICY_DIGEST ) if not all((session_id, turn_id, request_id, policy_digest)): return nullcontext() @@ -107,7 +112,13 @@ def _attach_trusted_source_provenance_metadata(agent, function_name: str) -> Non from agent.source_provenance import SourceProvenanceRegistry registry = getattr(agent, "_source_provenance_registry", None) - request_id = str(getattr(agent, "_current_api_request_id", "") or "") + from agent.source_provenance import following_api_request_id + + turn_id = str(getattr(agent, "_current_turn_id", "") or "") + request_id = following_api_request_id( + str(getattr(agent, "_current_api_request_id", "") or ""), + turn_id, + ) if not isinstance(registry, SourceProvenanceRegistry) or not request_id: return digests = tuple(source_grant_digest(grant) for grant in registry.grants_for_request(request_id)) diff --git a/cli.py b/cli.py index 7c76de288e5a1..f73153522ea02 100644 --- a/cli.py +++ b/cli.py @@ -16403,7 +16403,7 @@ def chat(self, message, images: list = None, voice_input: bool = False) -> Optio message, cwd=os.getcwd(), context_length=_ctx_len, - **provenance_kwargs_for_agent(agent), + **provenance_kwargs_for_agent(agent, establish_turn=True), ) if _ctx_result.expanded or _ctx_result.blocked: if _ctx_result.references: diff --git a/run_agent.py b/run_agent.py index 8aeb8ab0f5ff5..e5114f7f38000 100644 --- a/run_agent.py +++ b/run_agent.py @@ -8534,9 +8534,10 @@ def run_conversation( "task_id": effective_task_id, "platform": getattr(self, "platform", None) or "", } - relay_turn_id = ( - f"{session_id or 'session'}:{effective_task_id}:{uuid.uuid4().hex[:8]}" - ) + relay_turn_id = str( + getattr(self, "_source_provenance_pending_turn_id", "") or "" + ) or f"{session_id or 'session'}:{effective_task_id}:{uuid.uuid4().hex[:8]}" + self._source_provenance_pending_turn_id = None self._relay_pending_turn_id = relay_turn_id relay_parent_session_id = ( str(getattr(self, "_parent_session_id", None) or "") diff --git a/tests/agent/test_context_references.py b/tests/agent/test_context_references.py index be70daedd80fb..c4a2eeaee124b 100644 --- a/tests/agent/test_context_references.py +++ b/tests/agent/test_context_references.py @@ -114,6 +114,54 @@ def test_context_reference_without_exact_range_cannot_issue_a_grant(sample_repo: assert registry.grants_for_request("request-1") == () +def test_exact_file_reference_through_a_symlink_never_issues_a_grant(sample_repo: Path): + from agent.context_references import preprocess_context_references + from agent.source_provenance import SourceProvenanceRegistry + + (sample_repo / "src" / "linked.py").symlink_to(sample_repo / "src" / "main.py") + registry = SourceProvenanceRegistry() + + result = preprocess_context_references( + "Review @file:src/linked.py:1-1", + cwd=sample_repo, + context_length=100_000, + source_provenance_registry=registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ) + + assert result.expanded + assert registry.grants_for_request("request-1") == () + assert any("symlink_path" in warning for warning in result.warnings) + + +def test_exact_file_reference_through_a_symlinked_ancestor_never_issues_a_grant( + sample_repo: Path, +): + from agent.context_references import preprocess_context_references + from agent.source_provenance import SourceProvenanceRegistry + + (sample_repo / "linked-src").symlink_to(sample_repo / "src", target_is_directory=True) + registry = SourceProvenanceRegistry() + + result = preprocess_context_references( + "Review @file:linked-src/main.py:1-1", + cwd=sample_repo, + context_length=100_000, + source_provenance_registry=registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ) + + assert result.expanded + assert registry.grants_for_request("request-1") == () + assert any("symlink_path" in warning for warning in result.warnings) + + diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index 65ebde9675b98..f3ee4080b546a 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -278,6 +278,27 @@ def test_only_exact_policy_allowlisted_static_wrappers_accompany_source(tmp_path assert "sanitized_segment_forbidden" in sanitized_exc.value.decision.reason_codes +def test_firewall_binds_requests_to_its_configured_policy_digest(tmp_path): + request = TypedOutboundRequest( + payload={"messages": [LiteralSegment("ordinary prompt")]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + with pytest.raises(EgressBlocked) as exc_info: + firewall( + tmp_path, + policy_digest="policy-2", + static_literals={"ordinary prompt"}, + ).preflight( + request, + _route(base_url="http://127.0.0.1:1234"), + grants=(), + ) + assert "policy_digest_mismatch" in exc_info.value.decision.reason_codes + + @pytest.mark.parametrize( ("wrapper", "reason"), [ diff --git a/tests/agent/test_source_provenance.py b/tests/agent/test_source_provenance.py index 9bad9649f486a..73a784f6dee71 100644 --- a/tests/agent/test_source_provenance.py +++ b/tests/agent/test_source_provenance.py @@ -263,12 +263,103 @@ def test_provenance_kwargs_for_live_agent_bind_registry_and_request_identity(): assert kwargs["policy_digest"] == DEFAULT_POLICY_DIGEST -def test_cli_and_tui_file_reference_callers_pass_authenticated_provenance(): - cli_source = Path("cli.py").read_text(encoding="utf-8") - tui_source = Path("tui_gateway/server.py").read_text(encoding="utf-8") +def test_provenance_kwargs_can_prepare_and_adopt_the_next_turn_identity(tmp_path: Path): + from agent.source_provenance import ( + SourceProvenanceRegistry, + provenance_kwargs_for_agent, + ) + + source = tmp_path / "source.py" + source.write_text("safe\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + registry.issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"safe\n", + **_identity(), + ) + agent = type( + "Agent", + (), + { + "session_id": "session-1", + "_current_turn_id": "turn-1", + "_current_api_request_id": "request-1", + "_source_provenance_registry": registry, + }, + )() + + kwargs = provenance_kwargs_for_agent(agent, establish_turn=True) + + assert kwargs["turn_id"] != "turn-1" + assert kwargs["request_id"] == f"{kwargs['turn_id']}:api:1" + assert agent._source_provenance_pending_turn_id == kwargs["turn_id"] + assert registry.grants_for_request("request-1") == () + + +def test_abandoned_prepared_turn_clears_its_grants(tmp_path: Path): + from agent.source_provenance import ( + SourceProvenanceRegistry, + clear_agent_source_provenance, + provenance_kwargs_for_agent, + ) + + source = tmp_path / "source.py" + source.write_text("safe\n", encoding="utf-8") + agent = SimpleNamespace(session_id="session-1") + kwargs = provenance_kwargs_for_agent(agent, establish_turn=True) + registry = kwargs["source_provenance_registry"] + assert isinstance(registry, SourceProvenanceRegistry) + registry.issue_file_slice( + path=source, + line_start=1, + line_end=1, + content=b"safe\n", + session_id=kwargs["session_id"], + turn_id=kwargs["turn_id"], + request_id=kwargs["request_id"], + policy_digest=kwargs["policy_digest"], + ) + + clear_agent_source_provenance(agent) + + assert registry.grants_for_request(kwargs["request_id"]) == () + assert agent._source_provenance_pending_turn_id is None + + +def test_read_file_activation_uses_the_governed_default_policy_digest(): + from agent.source_provenance import DEFAULT_POLICY_DIGEST + from agent.tool_executor import _source_provenance_activation + + agent = type( + "Agent", + (), + { + "session_id": "session-1", + "_current_turn_id": "turn-1", + "_current_api_request_id": "turn-1:api:1", + }, + )() + + with _source_provenance_activation(agent, "read_file") as context: + assert context.policy_digest == DEFAULT_POLICY_DIGEST + + assert hasattr(agent, "_source_provenance_registry") + + +def test_read_file_activation_binds_the_following_api_request(): + from agent.source_provenance import active_source_provenance + from agent.tool_executor import _source_provenance_activation + + agent = SimpleNamespace( + session_id="session-1", + _current_turn_id="turn-1", + _current_api_request_id="turn-1:api:7", + ) - assert "**provenance_kwargs_for_agent(agent)" in cli_source - assert "**provenance_kwargs_for_agent(agent)" in tui_source + with _source_provenance_activation(agent, "read_file"): + assert active_source_provenance().request_id == "turn-1:api:8" def test_registry_keeps_grants_request_scoped_and_clearable(tmp_path: Path): diff --git a/tests/tools/test_file_tools.py b/tests/tools/test_file_tools.py index 2c70d42f97e21..baeaec449694d 100644 --- a/tests/tools/test_file_tools.py +++ b/tests/tools/test_file_tools.py @@ -81,6 +81,75 @@ def test_read_errors_or_untrusted_tool_text_cannot_issue_grants(tmp_path): assert registry.grants_for_request("request-1") == () +def test_symlink_read_cannot_issue_a_grant(tmp_path): + from agent.source_provenance import SourceProvenanceRegistry, activate_source_provenance + from tools.file_tools import read_file_tool + + source = tmp_path / "source.py" + source.write_text("one\n", encoding="utf-8") + linked = tmp_path / "linked.py" + linked.symlink_to(source) + registry = SourceProvenanceRegistry() + + with activate_source_provenance( + registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ): + result = json.loads(read_file_tool(str(linked), offset=1, limit=1)) + + assert result["content"] + assert registry.grants_for_request("request-1") == () + + +def test_symlinked_ancestor_read_cannot_issue_a_grant(tmp_path): + from agent.source_provenance import SourceProvenanceRegistry, activate_source_provenance + from tools.file_tools import read_file_tool + + real_dir = tmp_path / "real" + real_dir.mkdir() + source = real_dir / "source.py" + source.write_text("one\n", encoding="utf-8") + linked_dir = tmp_path / "linked" + linked_dir.symlink_to(real_dir, target_is_directory=True) + registry = SourceProvenanceRegistry() + + with activate_source_provenance( + registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ): + result = json.loads(read_file_tool(str(linked_dir / "source.py"), offset=1, limit=1)) + + assert result["content"] + assert registry.grants_for_request("request-1") == () + + +def test_line_display_truncation_cannot_issue_a_grant(tmp_path): + from agent.source_provenance import SourceProvenanceRegistry, activate_source_provenance + from tools.file_tools import read_file_tool + + source = tmp_path / "source.py" + source.write_text("x" * 20_000 + "\n", encoding="utf-8") + registry = SourceProvenanceRegistry() + + with activate_source_provenance( + registry, + session_id="session-1", + turn_id="turn-1", + request_id="request-1", + policy_digest="policy-1", + ): + result = json.loads(read_file_tool(str(source), offset=1, limit=1)) + + assert result["content"] + assert registry.grants_for_request("request-1") == () + + def test_forged_read_result_cannot_issue_a_grant(tmp_path, monkeypatch): from agent.source_provenance import SourceProvenanceRegistry, activate_source_provenance from tools.file_operations import ReadResult diff --git a/tools/file_tools.py b/tools/file_tools.py index a31c970f1ae09..ed2b0e4288ace 100644 --- a/tools/file_tools.py +++ b/tools/file_tools.py @@ -137,6 +137,7 @@ def _truncate_to_char_budget(content: str, max_chars: int) -> tuple[str, int, bo def _issue_active_read_provenance( *, resolved: Path | PurePosixPath, + source_path: Path | None, offset: int, limit: int, returned_content: str, @@ -152,7 +153,7 @@ def _issue_active_read_provenance( """ context = active_source_provenance() - if context is None or not isinstance(resolved, Path): + if context is None or not isinstance(resolved, Path) or source_path is None: return if result_dict.get("error") or result_dict.get("truncated_by") or not returned_content: return @@ -171,11 +172,21 @@ def _issue_active_read_provenance( if not selected: return raw = b"".join(selected) - expected = file_ops._add_line_numbers(raw.decode("utf-8"), offset) + decoded = raw.decode("utf-8") + from tools.tool_output_limits import get_max_line_length + + # read_file's gutter renderer truncates individual long lines for + # display. A grant must identify bytes the model actually received, + # never the undisplayed suffix of a clamped line. + if any(len(line) > get_max_line_length() for line in decoded.split("\n")): + return + expected = file_ops._add_line_numbers(decoded, offset) if returned_content != expected: return context.registry.issue_file_slice( - path=resolved, + # Keep the unresolved spelling so leaf and ancestor symlinks are + # still visible to the registry's no-follow validation. + path=source_path, line_start=offset, line_end=offset + len(selected) - 1, content=raw, @@ -1705,6 +1716,11 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 2000, task_id: str = "block or produce infinite output." ) + _source_path = None + if not _uses_container_paths(task_id): + _source_path = Path(_expand_tilde(path)) + if not _source_path.is_absolute(): + _source_path = Path(_resolve_base_dir(task_id)) / _source_path _resolved = _resolve_path_for_task(path, task_id) # ── Special-file type guard (stat-based) ────────────────────── @@ -2059,6 +2075,7 @@ def read_file_tool(path: str, offset: int = 1, limit: int = 2000, task_id: str = if result.content == content_before_redaction: _issue_active_read_provenance( resolved=_resolved, + source_path=_source_path, offset=offset, limit=limit, returned_content=result.content, diff --git a/tui_gateway/server.py b/tui_gateway/server.py index e0f8cb899e3c1..8a5c415474369 100644 --- a/tui_gateway/server.py +++ b/tui_gateway/server.py @@ -11575,7 +11575,7 @@ def run(): cwd=cwd, allowed_root=cwd, context_length=ctx_len, - **provenance_kwargs_for_agent(agent), + **provenance_kwargs_for_agent(agent, establish_turn=True), ) if ctx.blocked: clear_agent_source_provenance(agent) From e38889b5685a73d236f6b10f9db0073dcd0afa4a Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Wed, 26 Aug 2026 02:42:22 -0700 Subject: [PATCH 10/26] feat(security): enforce remote egress at provider boundaries --- agent/auxiliary_client.py | 279 ++++++++++++-- agent/chat_completion_helpers.py | 76 +++- agent/codex_runtime.py | 8 +- agent/error_classifier.py | 14 + agent/llm_egress_firewall.py | 346 +++++++++++++++++- agent/llm_egress_runtime.py | 325 ++++++++++++++++ tests/agent/test_auxiliary_client.py | 179 +++++++++ ...est_codex_request_transport_diagnostics.py | 6 +- tests/agent/test_error_classifier.py | 35 +- tests/agent/test_llm_egress_firewall.py | 188 +++++++++- .../test_llm_egress_provider_boundaries.py | 96 +++++ tests/agent/test_llm_egress_runtime.py | 188 ++++++++++ 12 files changed, 1658 insertions(+), 82 deletions(-) create mode 100644 agent/llm_egress_runtime.py create mode 100644 tests/agent/test_llm_egress_provider_boundaries.py create mode 100644 tests/agent/test_llm_egress_runtime.py diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index 4cc5016702581..e347598eec0ca 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -161,6 +161,7 @@ def aux_probe_mode(): _aux_probe_state.active = prev from agent.credential_pool import load_pool +from agent.llm_egress_firewall import EgressBlocked from agent.model_metadata import ( MINIMUM_CONTEXT_LENGTH, get_model_context_length, @@ -3309,6 +3310,101 @@ def _read_main_api_key_if_same_host(aux_base_url: str) -> str: contextvars.ContextVar("auxiliary_relay_call", default=None) ) +_AUX_EGRESS_PROVIDERS = frozenset({"openai-codex", "nous"}) + + +def _auxiliary_egress_binding( + client: Any, + *, + provider: str | None, + model: str | None, + api_mode: str | None, +) -> tuple[Any, Any] | None: + """Build the complete identity and route for protected auxiliary calls.""" + normalized_provider = _normalize_aux_provider(provider) + if normalized_provider not in _AUX_EGRESS_PROVIDERS: + return None + from agent.source_provenance import DEFAULT_POLICY_DIGEST + + runtime = _normalize_main_runtime(None) + raw_runtime = _RUNTIME_MAIN_CONTEXT.get() or {} + relay = _RELAY_AUX_CALL_CONTEXT.get() or {} + request_id = str(relay.get("request_id") or f"aux-{uuid.uuid4().hex}") + session_id = str( + runtime.get("session_id") + or raw_runtime.get("session_id") + or f"aux-session:{request_id}" + ) + turn_id = str( + raw_runtime.get("turn_id") + or f"{session_id}:aux:{str(relay.get('task') or 'call')}" + ) + policy_digest = str( + raw_runtime.get("policy_digest") + or raw_runtime.get("llm_egress_policy_digest") + or DEFAULT_POLICY_DIGEST + ) + candidate_base_url = getattr(client, "base_url", "") + if not isinstance(candidate_base_url, str) or not candidate_base_url.startswith( + ("http://", "https://") + ): + candidate_base_url = raw_runtime.get("base_url") + if not isinstance(candidate_base_url, str) or not candidate_base_url.startswith( + ("http://", "https://") + ): + candidate_base_url = ( + "https://chatgpt.com/backend-api/codex" + if normalized_provider == "openai-codex" + else _NOUS_DEFAULT_BASE_URL + ) + base_url = candidate_base_url + resolved_api_mode = str( + api_mode + or ( + "codex_responses" + if normalized_provider == "openai-codex" + else "chat_completions" + ) + ) + agent = SimpleNamespace( + provider=normalized_provider, + model=str(model or ""), + base_url=base_url, + api_mode=resolved_api_mode, + session_id=session_id, + _current_turn_id=turn_id, + _current_api_request_id=request_id, + _llm_egress_policy_digest=policy_digest, + _llm_egress_state_dir=Path(get_hermes_home()) / "egress", + ) + route = SimpleNamespace( + provider=normalized_provider, + model=str(model or ""), + base_url=base_url, + api_mode=resolved_api_mode, + ) + return agent, route + + +def _dispatch_auxiliary_request( + client: Any, + request: dict[str, Any], + callback: Callable[[dict[str, Any]], Any], + *, + provider: str | None, + model: str | None, + api_mode: str | None, +) -> Any: + binding = _auxiliary_egress_binding( + client, provider=provider, model=model or request.get("model"), api_mode=api_mode + ) + if binding is None: + return callback(request) + from agent.llm_egress_runtime import dispatch_authorized_agent_request + + agent, route = binding + return dispatch_authorized_agent_request(agent, request, callback, route=route) + def _relay_auxiliary_call(callback): """Give every physical retry in one auxiliary call a shared Relay identity.""" @@ -3417,6 +3513,15 @@ def _relay_sync_completion( create: Callable[[dict[str, Any]], Any] | None = None, ) -> Any: callback = create or (lambda request: client.chat.completions.create(**request)) + raw_callback = callback + callback = lambda request: _dispatch_auxiliary_request( + client, + request, + raw_callback, + provider=provider, + model=request.get("model"), + api_mode=api_mode, + ) route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode) # Protected compression calls isolate only the provider callback and stream # aggregation. The owning thread remains free to unwind its lease/DB @@ -3445,6 +3550,29 @@ async def _relay_async_completion( create: Callable[[dict[str, Any]], Any] | None = None, ) -> Any: callback = create or (lambda request: client.chat.completions.create(**request)) + raw_callback = callback + + async def _authorized_callback(request: dict[str, Any]) -> Any: + binding = _auxiliary_egress_binding( + client, + provider=provider, + model=request.get("model"), + api_mode=api_mode, + ) + if binding is None: + return await raw_callback(request) + from agent.llm_egress_runtime import dispatch_authorized_agent_request + + agent, route = binding + result = dispatch_authorized_agent_request( + agent, + request, + raw_callback, + route=route, + ) + return await result if inspect.isawaitable(result) else result + + callback = _authorized_callback route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode) if route is None: return await callback(kwargs) @@ -3468,15 +3596,23 @@ def _relay_sync_stream( provider: str | None = None, api_mode: str | None = None, ) -> Any: + callback = lambda request: _dispatch_auxiliary_request( + client, + request, + lambda authorized: client.chat.completions.create(**authorized), + provider=provider, + model=kwargs.get("model"), + api_mode=api_mode, + ) route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode) if route is None: - return client.chat.completions.create(**kwargs) + return callback(kwargs) provider_name, fallback_model, metadata = route from agent import relay_llm return relay_llm.stream_current( kwargs, - lambda request: client.chat.completions.create(**request), + callback, name=provider_name, model_name=str(kwargs.get("model") or fallback_model), finalizer=dict, @@ -4034,7 +4170,13 @@ def _try_anthropic(explicit_api_key: str = None) -> Tuple[Optional[Any], Optiona } _MAIN_RUNTIME_FIELDS = ("provider", "model", "base_url", "api_key", "api_mode", "auth_mode") -_MAIN_RUNTIME_CONTEXT_FIELDS = _MAIN_RUNTIME_FIELDS + ("requested_provider",) +_MAIN_RUNTIME_CONTEXT_FIELDS = _MAIN_RUNTIME_FIELDS + ( + "requested_provider", + "session_id", + "turn_id", + "policy_digest", + "llm_egress_policy_digest", +) def _normalize_main_runtime(main_runtime: Optional[Dict[str, Any]]) -> Dict[str, Any]: @@ -4369,6 +4511,20 @@ def _is_transient_transport_error(exc: Exception) -> bool: return isinstance(status, int) and (status == 408 or 500 <= status < 600) +def _is_safe_egress_fallback_candidate(client: Any, provider: str, model: str) -> bool: + """Permit a blocked remote request to fall back only to local execution. + + A blocked payload must never be retried against another remote provider; + only an explicitly local/loopback fallback is eligible, and its callback + still receives a fresh request copy at the local boundary. + """ + from agent.llm_egress_firewall import DestinationClass, classify_destination + + base_url = str(getattr(client, "base_url", "") or "") + destination = classify_destination(provider, base_url, "chat_completions") + return destination in {DestinationClass.LOCAL_PROCESS, DestinationClass.LOOPBACK} + + _DEFAULT_TRANSIENT_RETRIES = 2 # Base for exponential backoff between transient retries (seconds). Overridable # so tests can zero it out and not sleep real wall-clock time. @@ -9367,26 +9523,27 @@ def call_llm( if semaphore is not None: semaphore.acquire() try: - response = _call_llm_impl( - task=task, - provider=provider, - model=model, - base_url=base_url, - api_key=api_key, - main_runtime=main_runtime, - messages=messages, - temperature=temperature, - max_tokens=max_tokens, - tools=tools, - timeout=timeout, - extra_body=extra_body, - reasoning_config=reasoning_config, - extra_headers=extra_headers, - api_mode=api_mode, - stream=stream, - stream_options=stream_options, - route_info=route_info, - ) + with scoped_runtime_main(main_runtime): + response = _call_llm_impl( + task=task, + provider=provider, + model=model, + base_url=base_url, + api_key=api_key, + main_runtime=main_runtime, + messages=messages, + temperature=temperature, + max_tokens=max_tokens, + tools=tools, + timeout=timeout, + extra_body=extra_body, + reasoning_config=reasoning_config, + extra_headers=extra_headers, + api_mode=api_mode, + stream=stream, + stream_options=stream_options, + route_info=route_info, + ) if stream and semaphore is not None: stream_semaphore = semaphore semaphore = None @@ -9619,7 +9776,14 @@ def _call_llm_impl( # Return the provider call directly; the MoA facade converts a # completed response into a one-chunk delta iterator at its # boundary. - return client.chat.completions.create(**kwargs) + return _dispatch_auxiliary_request( + client, + kwargs, + lambda authorized: client.chat.completions.create(**authorized), + provider=request_provider, + model=final_model, + api_mode=resolved_api_mode, + ) return _relay_sync_stream( client, kwargs, @@ -10036,6 +10200,40 @@ def _call_llm_impl( # auxiliary task on the floor (silent compression failure / # message loss). Auth is NOT a capacity error: it only bypasses # the explicit-provider gate when the user is in auto mode. + # A blocked remote payload is terminal for every remote destination. + # Give only a configured/local fallback one immediate chance, without + # entering retry/backoff or the general remote provider chain. + if isinstance(first_err, EgressBlocked): + local_candidates = ( + _try_configured_fallback_chain( + task, resolved_provider or "auto", reason="egress blocked", + failed_model=final_model, + ), + _try_main_agent_model_fallback( + resolved_provider, task, reason="egress blocked", + failed_model=final_model, + ), + ) + for fb_client, fb_model, fb_label in local_candidates: + if fb_client is None or not _is_safe_egress_fallback_candidate( + fb_client, _fallback_provider_from_label(fb_label), str(fb_model or "") + ): + continue + _record_route_info( + route_info, _fallback_provider_from_label(fb_label), fb_model + ) + fb_resp = _call_fallback_candidate_sync( + fb_client, fb_model, fb_label, + task=task, messages=messages, + temperature=temperature, max_tokens=max_tokens, + tools=tools, effective_timeout=effective_timeout, + effective_extra_body=effective_extra_body, + reasoning_config=reasoning_config, + ) + if fb_resp is not None: + return fb_resp + raise + should_fallback = ( _is_auth_error(first_err) or _is_payment_error(first_err) @@ -10256,22 +10454,23 @@ async def async_call_llm( if semaphore is not None: await semaphore.acquire() try: - return await _async_call_llm_impl( - task=task, - provider=provider, - model=model, - base_url=base_url, - api_key=api_key, - main_runtime=main_runtime, - messages=messages, - temperature=temperature, - max_tokens=max_tokens, - tools=tools, - timeout=timeout, - extra_body=extra_body, - reasoning_config=reasoning_config, - route_info=route_info, - ) + with scoped_runtime_main(main_runtime): + return await _async_call_llm_impl( + task=task, + provider=provider, + model=model, + base_url=base_url, + api_key=api_key, + main_runtime=main_runtime, + messages=messages, + temperature=temperature, + max_tokens=max_tokens, + tools=tools, + timeout=timeout, + extra_body=extra_body, + reasoning_config=reasoning_config, + route_info=route_info, + ) finally: if semaphore is not None: semaphore.release() diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py index e63e28f3bd342..c26fe0888b0b7 100644 --- a/agent/chat_completion_helpers.py +++ b/agent/chat_completion_helpers.py @@ -923,6 +923,22 @@ def _bedrock_reasoning_stale_floor(model_id: object) -> "float | None": return None +_EGRESS_PROTECTED_PROVIDERS = frozenset( + {"openai-codex", "nous", "nous-portal", "nousresearch"} +) + + +def _dispatch_provider_request(agent, request, callback): + """Apply the exact provider-bound egress policy at a physical call site.""" + + provider = str(getattr(agent, "provider", "") or "").strip().lower() + if provider not in _EGRESS_PROTECTED_PROVIDERS: + return callback(request) + from agent.llm_egress_runtime import dispatch_authorized_agent_request + + return dispatch_authorized_agent_request(agent, request, callback) + + def _dispatch_nonstreaming_api_request(agent, api_kwargs: dict, *, make_client): """Run one non-streaming LLM request for the active api_mode and return it. @@ -953,7 +969,13 @@ def _dispatch_nonstreaming_api_request(agent, api_kwargs: dict, *, make_client): request_client = make_client( "anthropic_messages_request", kind="anthropic_messages" ) - return agent._anthropic_messages_create(api_kwargs, client=request_client) + return _dispatch_provider_request( + agent, + api_kwargs, + lambda request: agent._anthropic_messages_create( + request, client=request_client + ), + ) if agent.api_mode == "bedrock_converse": # Bedrock uses boto3 directly — no OpenAI client needed. # normalize_converse_response produces an OpenAI-compatible @@ -996,7 +1018,11 @@ def _dispatch_nonstreaming_api_request(agent, api_kwargs: dict, *, make_client): api_kwargs.pop("_moa_prepared_request", None) return agent.client.chat.completions.create(**api_kwargs) request_client = make_client("chat_completion_request") - return request_client.chat.completions.create(**api_kwargs) + return _dispatch_provider_request( + agent, + api_kwargs, + lambda request: request_client.chat.completions.create(**request), + ) def should_use_direct_api_call(agent) -> bool: @@ -2912,21 +2938,33 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str: def _managed_summary_call(request, callback, *, retry_count: int): from agent import relay_llm - return relay_llm.execute_current( - request, - callback, - name=str(getattr(agent, "provider", "") or "provider"), - model_name=str(getattr(agent, "model", "") or ""), - metadata={ - "api_mode": str( - getattr(agent, "api_mode", "") or "chat_completions" - ), - "api_request_id": summary_api_request_id, - "call_role": "iteration_summary", - "retry_count": retry_count, - }, - defer_logical_completion=True, + raw_callback = callback + callback = lambda payload: _dispatch_provider_request( + agent, payload, raw_callback ) + previous_request_id = str( + getattr(agent, "_current_api_request_id", "") or "" + ) + agent._current_api_request_id = summary_api_request_id + + try: + return relay_llm.execute_current( + request, + callback, + name=str(getattr(agent, "provider", "") or "provider"), + model_name=str(getattr(agent, "model", "") or ""), + metadata={ + "api_mode": str( + getattr(agent, "api_mode", "") or "chat_completions" + ), + "api_request_id": summary_api_request_id, + "call_role": "iteration_summary", + "retry_count": retry_count, + }, + defer_logical_completion=True, + ) + finally: + agent._current_api_request_id = previous_request_id # Shared constant so compaction recognizers can identify this runtime nudge # by its stable content after SessionDB projection strips metadata flags @@ -3981,7 +4019,11 @@ def _open_stream(next_api_kwargs: dict[str, Any]): attempt_request_client["value"] = request_client last_chunk_time["t"] = time.time() agent._touch_activity("waiting for provider response (streaming)") - return request_client.chat.completions.create(**stream_kwargs) + return _dispatch_provider_request( + agent, + stream_kwargs, + lambda request: request_client.chat.completions.create(**request), + ) def _stream_created(raw_stream: Any) -> None: response = getattr(raw_stream, "response", None) diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py index a1118759da3a2..ba4c527128e45 100644 --- a/agent/codex_runtime.py +++ b/agent/codex_runtime.py @@ -1631,7 +1631,13 @@ def _open_codex_stream(next_api_kwargs: dict[str, Any]): ) stream_kwargs["stream"] = True stream_kwargs = _bypass_sdk_request_transform(stream_kwargs) - return active_client.responses.create(**stream_kwargs) + from agent.llm_egress_runtime import dispatch_authorized_agent_request + + return dispatch_authorized_agent_request( + agent, + stream_kwargs, + lambda request: active_client.responses.create(**request), + ) def _codex_stream_created(_raw_stream: Any) -> None: # Claim the delta sink for THIS physical attempt. A newer attempt diff --git a/agent/error_classifier.py b/agent/error_classifier.py index 39e8ed5c5278e..fa5a3d0b1ac9d 100644 --- a/agent/error_classifier.py +++ b/agent/error_classifier.py @@ -62,6 +62,7 @@ class FailoverReason(enum.Enum): model_not_found = "model_not_found" # 404 or invalid model — fallback to different model provider_policy_blocked = "provider_policy_blocked" # Aggregator (e.g. OpenRouter) blocked the only endpoint due to account data/privacy policy content_policy_blocked = "content_policy_blocked" # Provider safety filter rejected this prompt — deterministic per-request, don't retry unchanged + egress_policy_blocked = "egress_policy_blocked" # Local privacy firewall denied remote transport — fall back locally without retry # Request format format_error = "format_error" # 400 bad request — abort or strip + retry @@ -799,6 +800,19 @@ def classify_api_error( Returns: ClassifiedError with reason and recovery action hints. """ + from agent.llm_egress_firewall import EgressBlocked + + if isinstance(error, EgressBlocked): + return ClassifiedError( + reason=FailoverReason.egress_policy_blocked, + provider=provider or None, + model=model or None, + message="remote request denied by local egress policy", + error_context={"reason_codes": error.decision.reason_codes}, + retryable=False, + should_fallback=True, + ) + status_code = _extract_status_code(error) error_type = type(error).__name__ # Copilot/GitHub Models RateLimitError may not set .status_code; force 429 diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index ebac993a9296b..b24411dfc1c5e 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -16,6 +16,7 @@ import math import os import re +import stat from dataclasses import asdict, dataclass, replace from enum import StrEnum from hmac import compare_digest @@ -110,6 +111,9 @@ class EgressDecision: request_id: str policy_digest: str reason_codes: tuple[str, ...] = () + base_url: str = "" + api_mode: str = "" + grant_digests: tuple[str, ...] = () class EgressBlocked(RuntimeError): @@ -121,6 +125,14 @@ def __init__(self, decision: EgressDecision): super().__init__(f"LLM egress blocked: {reasons}") +class SanitizedTextRejected(ValueError): + """Raised when remote text cannot earn the sanitized segment type.""" + + def __init__(self, reason_code: str): + self.reason_code = reason_code + super().__init__(f"sanitized remote text rejected: {reason_code}") + + @dataclass(frozen=True, slots=True) class AuthorizedEgress: """Immutable exact bytes that a provider callback is authorized to send.""" @@ -163,12 +175,36 @@ def verify_payload(self, candidate: bytes) -> bytes: r"(? bool: return False if not 4 <= len(candidate) <= _MAX_BASE64_CANDIDATE_CHARS: return False + # Short alphabetic words frequently round-trip mathematically as + # unpadded Base64 (for example "ordinary" and "review"). Require an + # encoding signal for short candidates; long all-alpha blobs remain + # suspicious even without padding. + if len(candidate) < 24 and not any( + character.isdigit() or character in "=+/-_" for character in candidate + ) and not candidate.isupper(): + return False + # Short, word-like URL-safe slugs are common model/provider identifiers. + # Keep genuinely encoding-shaped values such as ``-_8A`` eligible for the + # canonical decoder below. + if ( + len(candidate) < 16 + and any(character in "-_" for character in candidate) + and candidate[0].isalnum() + and candidate[-1].isalnum() + and sum(character.isalpha() for character in candidate) >= 2 + ): + return False unpadded = candidate.rstrip("=") if "=" in unpadded or len(unpadded) % 4 == 1: return False @@ -301,7 +356,29 @@ def _canonical_base64_candidate(candidate: str) -> bool: def _contains_canonical_base64(value: Any, *, seen: set[int] | None = None) -> bool: if isinstance(value, str): - return any(_canonical_base64_candidate(match.group(1)) for match in _BASE64_CANDIDATE.finditer(value)) + # Fixed Hermes/Nous attribution tags are protocol metadata, not an + # encoded source payload. They remain subject to secret/path scans. + if value.startswith(("product=hermes-agent", "client=hermes-client-")): + return False + for match in _BASE64_CANDIDATE.finditer(value): + candidate = match.group(1) + prefix = value[max(0, match.start() - 16) : match.start()].lower() + if re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", candidate.lower()): + continue + if _canonical_base64_candidate(candidate): + return True + # Providers and source-control tools sometimes wrap an otherwise + # canonical encoding at a fixed column. Normalize only bounded chunks + # so ordinary prose words are not concatenated into a false candidate. + chunked = re.compile( + r"(? bool: return False +def _contains_private_absolute_path(value: Any, *, seen: set[int] | None = None) -> bool: + """Reject common host-private absolute paths without blocking API paths.""" + + if isinstance(value, str): + return _PRIVATE_ABSOLUTE_PATH.search(value) is not None + if isinstance(value, (bytes, bytearray, memoryview)): + return True + if seen is None: + seen = set() + if isinstance(value, Mapping): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any( + _contains_private_absolute_path(key, seen=seen) + or _contains_private_absolute_path(item, seen=seen) + for key, item in value.items() + ) + if isinstance(value, (list, tuple, set, frozenset)): + identity = id(value) + if identity in seen: + return True + seen.add(identity) + return any(_contains_private_absolute_path(item, seen=seen) for item in value) + return False + + +def _contains_grant_substring(grant_content: bytes, candidate: bytes) -> bool: + """Reject source-derived proper substrings in sanitized text. + + Newline-trimmed line grants commonly appear in JSON without their source + line ending. A fixed eight-byte window detects meaningful excerpts in + linear time and avoids quadratic work on large source slices. + """ + + if not grant_content or not candidate: + return False + grant_variants = (grant_content, grant_content.rstrip(b"\r\n")) + for variant in grant_variants: + if not variant: + continue + if variant in candidate: + return True + if len(candidate) < len(variant) and candidate in variant and len(candidate) >= 4: + return True + window = min(8, len(candidate), len(variant)) + if window >= 4: + source_windows = { + variant[offset : offset + window] + for offset in range(0, len(variant) - window + 1) + } + if any( + candidate[offset : offset + window] in source_windows + for offset in range(0, len(candidate) - window + 1) + ): + return True + return False + + +def validate_sanitized_text(text: str, *, max_bytes: int = 32_768) -> str: + """Return unchanged bounded remote-safe text or reject it fail-closed. + + This is the only constructor-side admission path for SanitizedSegment. + The firewall repeats the same scans on the final rendered payload. + """ + + if not isinstance(text, str): + raise SanitizedTextRejected("invalid_sanitized_text") + if max_bytes <= 0 or len(text.encode("utf-8")) > max_bytes: + raise SanitizedTextRejected("sanitized_bytes_exceeded") + try: + if _contains_secret(text): + raise SanitizedTextRejected("secret_detected") + except SanitizedTextRejected: + raise + except Exception as exc: + raise SanitizedTextRejected("redaction_failed") from exc + try: + if _contains_canonical_base64(text): + raise SanitizedTextRejected("base64_payload") + except SanitizedTextRejected: + raise + except Exception as exc: + raise SanitizedTextRejected("base64_scan_failed") from exc + try: + if _contains_private_absolute_path(text): + raise SanitizedTextRejected("private_absolute_path") + except SanitizedTextRejected: + raise + except Exception as exc: + raise SanitizedTextRejected("private_path_scan_failed") from exc + return text + + +def _is_strict_sanitized_only_payload( + value: Any, + *, + seen: set[int] | None = None, +) -> tuple[bool, int]: + """Recognize the one grantless remote shape approved by policy. + + Every text leaf must be an explicit :class:`SanitizedSegment`. Raw text, + static literals, source references, binary values, cycles, and unsupported + containers make the entire payload ineligible. The positive count prevents + an empty structural request from acquiring grantless status. + """ + + if isinstance(value, SanitizedSegment): + return isinstance(value.text, str), 1 if isinstance(value.text, str) else 0 + if isinstance(value, LiteralSegment): + return isinstance(value.text, str), 0 + if isinstance(value, SourceBoundSegment): + return False, 0 + if isinstance(value, OutboundText): + if not value.segments: + return False, 0 + count = 0 + for segment in value.segments: + allowed, segment_count = _is_strict_sanitized_only_payload(segment, seen=seen) + if not allowed: + return False, 0 + count += segment_count + return count > 0, count + if value is None or isinstance(value, (bool, int)): + return True, 0 + if isinstance(value, float): + return math.isfinite(value), 0 + if isinstance(value, (str, bytes, bytearray, memoryview, set, frozenset)): + return False, 0 + if seen is None: + seen = set() + if isinstance(value, Mapping): + identity = id(value) + if identity in seen: + return False, 0 + seen.add(identity) + count = 0 + for key, item in value.items(): + if not isinstance(key, str): + return False, 0 + allowed, item_count = _is_strict_sanitized_only_payload(item, seen=seen) + if not allowed: + return False, 0 + count += item_count + return True, count + if isinstance(value, (list, tuple)): + identity = id(value) + if identity in seen: + return False, 0 + seen.add(identity) + count = 0 + for item in value: + allowed, item_count = _is_strict_sanitized_only_payload(item, seen=seen) + if not allowed: + return False, 0 + count += item_count + return True, count + return False, 0 + + class LLMEgressFirewall: """Validate a final LLM request and record a content-free receipt.""" @@ -363,6 +601,7 @@ def __init__( state_dir: Path | str, *, max_serialized_bytes: int = 262_144, + max_sanitized_bytes: int = 32_768, max_conservative_tokens: int = 87_382, conservative_chars_per_token: int = 3, policy_digest: str | None = None, @@ -370,6 +609,8 @@ def __init__( ) -> None: if max_serialized_bytes <= 0: raise ValueError("max_serialized_bytes must be positive") + if max_sanitized_bytes <= 0: + raise ValueError("max_sanitized_bytes must be positive") if max_conservative_tokens <= 0: raise ValueError("max_conservative_tokens must be positive") if conservative_chars_per_token <= 0: @@ -377,6 +618,7 @@ def __init__( self._state_dir = Path(state_dir) self._receipt_path = self._state_dir / "llm-egress-receipts.jsonl" self._max_serialized_bytes = max_serialized_bytes + self._max_sanitized_bytes = max_sanitized_bytes self._max_conservative_tokens = max_conservative_tokens self._conservative_chars_per_token = conservative_chars_per_token self._policy_digest = str(policy_digest or "") @@ -422,6 +664,8 @@ def authorize( _route_value(route, "base_url"), _route_value(route, "api_mode"), ) + base_url = str(_route_value(route, "base_url") or "") + api_mode = str(_route_value(route, "api_mode") or "") typed_request = request if isinstance(request, TypedOutboundRequest) else None if typed_request is not None: session_id = typed_request.session_id @@ -438,26 +682,45 @@ def authorize( valid_grants: list[SourceGrant] = [] grant_contents: dict[str, tuple[SourceGrant, bytes]] = {} source_segment_count = 0 + sanitized_only = False + if typed_request is not None: + sanitized_shape, sanitized_count = _is_strict_sanitized_only_payload( + typed_request.payload + ) + sanitized_only = sanitized_shape and sanitized_count > 0 if destination == DestinationClass.UNKNOWN: reasons.append("unknown_destination") + if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN} and not all( + (session_id, turn_id, request_id, policy_digest) + ): + reasons.append("missing_request_identity") if self._policy_digest and policy_digest != self._policy_digest: reasons.append("policy_digest_mismatch") if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN}: if typed_request is None: reasons.append("typed_request_required") - grant_reasons, valid_grants, grant_contents = self._validate_grants( - grants, - session_id=session_id, - turn_id=turn_id, - request_id=request_id, - policy_digest=policy_digest, - ) - reasons.extend(grant_reasons) + # The sole grantless remote lane is a structurally verified request + # whose every text leaf is an explicit bounded SanitizedSegment. + # Passing even one purported grant opts back into exact source + # validation so malformed or unbound authority cannot be ignored. + if grants or not sanitized_only: + grant_reasons, valid_grants, grant_contents = self._validate_grants( + grants, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + ) + reasons.extend(grant_reasons) if typed_request is not None: logical_request, construction_reasons, source_segment_count, scan_values = ( - self._construct_typed_request(typed_request, grant_contents) + self._construct_typed_request( + typed_request, + grant_contents, + allow_sanitized_segments=True, + ) ) reasons.extend(construction_reasons) else: @@ -488,6 +751,9 @@ def authorize( request_id=request_id, policy_digest=policy_digest, reason_codes=("serialization_failed",), + base_url=base_url, + api_mode=api_mode, + grant_digests=tuple(source_grant_digest(grant) for grant in valid_grants), ) self._block(decision, valid_grants) @@ -511,6 +777,11 @@ def authorize( reasons.append("base64_payload") except Exception: reasons.append("base64_scan_failed") + try: + if _contains_private_absolute_path(scan_values): + reasons.append("private_absolute_path") + except Exception: + reasons.append("private_path_scan_failed") decision = EgressDecision( allowed=not reasons, @@ -527,6 +798,9 @@ def authorize( request_id=request_id, policy_digest=policy_digest, reason_codes=tuple(dict.fromkeys(reasons)), + base_url=base_url, + api_mode=api_mode, + grant_digests=tuple(source_grant_digest(grant) for grant in valid_grants), ) if not decision.allowed: self._block(decision, valid_grants) @@ -619,12 +893,15 @@ def _construct_typed_request( self, request: TypedOutboundRequest, grant_contents: Mapping[str, tuple[SourceGrant, bytes]], + *, + allow_sanitized_segments: bool = False, ) -> tuple[Mapping[str, Any], list[str], int, list[str]]: """Build a plain JSON request exclusively from typed segment nodes.""" reasons: list[str] = [] referenced_grants: set[str] = set() source_segment_count = 0 + sanitized_bytes = 0 scan_values: list[str] = [] allowed_static_hashes = self._static_literal_hashes_by_policy.get( request.policy_digest, @@ -643,7 +920,7 @@ def require_static_literal(text: str) -> None: def render_text_segment( segment: LiteralSegment | SanitizedSegment | SourceBoundSegment, ) -> str: - nonlocal source_segment_count + nonlocal sanitized_bytes, source_segment_count if isinstance(segment, LiteralSegment): if not isinstance(segment.text, str): reasons.append("invalid_literal_segment") @@ -654,8 +931,18 @@ def render_text_segment( reasons.append("source_bytes_in_literal") return segment.text if isinstance(segment, SanitizedSegment): - reasons.append("sanitized_segment_forbidden") + if not allow_sanitized_segments: + reasons.append("sanitized_segment_forbidden") if isinstance(segment.text, str): + encoded = segment.text.encode("utf-8") + sanitized_bytes += len(encoded) + if sanitized_bytes > self._max_sanitized_bytes: + reasons.append("sanitized_bytes_exceeded") + if any( + _contains_grant_substring(content, encoded) + for _, content in grant_contents.values() + ): + reasons.append("source_bytes_in_sanitized_segment") scan_values.append(segment.text) return segment.text reasons.append("invalid_literal_segment") @@ -745,6 +1032,11 @@ def _append_receipt( decision: EgressDecision, grants: Sequence[SourceGrant], ) -> None: + try: + if self._state_dir.is_symlink(): + raise OSError("egress state directory must not be a symlink") + except OSError: + raise self._state_dir.mkdir(parents=True, exist_ok=True, mode=0o700) receipt = asdict(decision) receipt["destination_class"] = decision.destination_class.value @@ -752,6 +1044,8 @@ def _append_receipt( for field in ( "provider", "model", + "base_url", + "api_mode", "session_id", "turn_id", "request_id", @@ -767,16 +1061,34 @@ def _append_receipt( } for grant in grants ] - encoded = ( - json.dumps(receipt, ensure_ascii=True, separators=(",", ":"), sort_keys=True) + "\n" - ).encode("utf-8") - flags = os.O_APPEND | os.O_CREAT | os.O_WRONLY + flags = os.O_APPEND | os.O_CREAT | os.O_RDWR if hasattr(os, "O_NOFOLLOW"): flags |= os.O_NOFOLLOW fd = os.open(self._receipt_path, flags, 0o600) try: os.fchmod(fd, 0o600) fcntl.flock(fd, fcntl.LOCK_EX) + file_size = os.fstat(fd).st_size + previous_hash = "" + if file_size: + read_start = max(0, file_size - 131_072) + os.lseek(fd, read_start, os.SEEK_SET) + prior_chunk = os.read(fd, file_size - read_start) + prior_lines = prior_chunk.splitlines() + if prior_lines: + previous_hash = sha256(prior_lines[-1]).hexdigest() + receipt["receipt_prev_sha256"] = previous_hash + receipt_material = json.dumps( + receipt, ensure_ascii=True, separators=(",", ":"), sort_keys=True + ).encode("utf-8") + receipt["receipt_sha256"] = sha256( + previous_hash.encode("ascii") + receipt_material + ).hexdigest() + encoded = ( + json.dumps(receipt, ensure_ascii=True, separators=(",", ":"), sort_keys=True) + + "\n" + ).encode("utf-8") + os.lseek(fd, 0, os.SEEK_END) if os.write(fd, encoded) != len(encoded): raise OSError("short receipt write") finally: diff --git a/agent/llm_egress_runtime.py b/agent/llm_egress_runtime.py new file mode 100644 index 0000000000000..4c08b65bf0c5c --- /dev/null +++ b/agent/llm_egress_runtime.py @@ -0,0 +1,325 @@ +"""Final provider-boundary enforcement for source-bound LLM egress.""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +from types import MappingProxyType +from types import SimpleNamespace +from typing import Any, Callable, Mapping, Sequence + +from agent.llm_egress_firewall import ( + AuthorizedEgress, + LLMEgressFirewall, + LiteralSegment, + OutboundText, + SanitizedSegment, + SourceBoundSegment, + SourceGrant, + TypedOutboundRequest, + DestinationClass, + classify_destination, + source_grant_digest, + static_literal_sha256, + validate_sanitized_text, +) +from agent.source_provenance import DEFAULT_POLICY_DIGEST, SourceProvenanceRegistry + + +# Timeout is a non-content SDK control. Header/query values remain in the +# authorized JSON body so credentials or other caller-controlled text cannot +# be appended after the firewall receipt is written. +_SDK_CONTROL_KEYS = frozenset({"timeout"}) +_PROTOCOL_LITERAL_FIELDS = frozenset({"role", "type"}) +_PROTOCOL_LITERAL_VALUES = frozenset({ + "assistant", + "computer_call_output", + "developer", + "function_call", + "function_call_output", + "input_image", + "input_text", + "output_text", + "reasoning", + "system", + "tool", + "user", +}) +_PROTECTED_REMOTE_PROVIDERS = frozenset({ + "openai-codex", + "nous", + "nous-portal", + "nousresearch", +}) + + +def provider_uses_egress_firewall(provider: Any) -> bool: + """Return whether an exact configured provider owns a protected remote lane.""" + + return str(provider or "").strip().lower() in _PROTECTED_REMOTE_PROVIDERS + + +def _read_grant_text(grant: SourceGrant) -> str | None: + try: + lines = Path(grant.canonical_path).read_bytes().splitlines(keepends=True) + return b"".join(lines[grant.line_start - 1 : grant.line_end]).decode("utf-8") + except (OSError, UnicodeDecodeError, ValueError, TypeError): + return None + + +def _grant_texts(grants: Sequence[SourceGrant]) -> tuple[tuple[str, SourceGrant], ...]: + unique: dict[str, SourceGrant] = {} + for grant in grants: + if not isinstance(grant, SourceGrant): + continue + text = _read_grant_text(grant) + if text: + unique.setdefault(text, grant) + return tuple(sorted(unique.items(), key=lambda item: (-len(item[0]), item[0]))) + + +def _approved_sanitized(text: str, *, cap: int) -> SanitizedSegment: + # Admission is finalized by LLMEgressFirewall so every denial is reported + # as its content-free EgressBlocked decision. Keep only the local type and + # byte bound here; the firewall repeats secret/base64/path scans on the + # rendered request immediately before dispatch. + if not isinstance(text, str): + raise TypeError("sanitized segment must be text") + if cap <= 0 or len(text.encode("utf-8")) > cap: + raise ValueError("sanitized segment exceeds byte cap") + return SanitizedSegment(text) + + +def _segment_text( + text: str, + grant_texts: Sequence[tuple[str, SourceGrant]], + used_grants: dict[str, SourceGrant], + *, + sanitized_cap: int, +) -> SanitizedSegment | SourceBoundSegment | OutboundText: + matches: list[tuple[int, int, SourceGrant]] = [] + cursor = 0 + while cursor < len(text): + chosen: tuple[int, int, SourceGrant] | None = None + for granted_text, grant in grant_texts: + start = text.find(granted_text, cursor) + if start < 0: + continue + candidate = (start, start + len(granted_text), grant) + if chosen is None or candidate[:2] < chosen[:2]: + chosen = candidate + if chosen is None: + break + matches.append(chosen) + cursor = chosen[1] + + if not matches: + return _approved_sanitized(text, cap=sanitized_cap) + + segments: list[SanitizedSegment | SourceBoundSegment] = [] + cursor = 0 + for start, end, grant in matches: + if start > cursor: + segments.append(_approved_sanitized(text[cursor:start], cap=sanitized_cap)) + digest = source_grant_digest(grant) + segments.append(SourceBoundSegment(digest)) + used_grants[digest] = grant + cursor = end + if cursor < len(text): + segments.append(_approved_sanitized(text[cursor:], cap=sanitized_cap)) + return segments[0] if len(segments) == 1 else OutboundText(tuple(segments)) + + +def _typed_payload( + value: Any, + grant_texts: Sequence[tuple[str, SourceGrant]], + used_grants: dict[str, SourceGrant], + *, + sanitized_cap: int, + field_name: str | None = None, +) -> Any: + if isinstance(value, str): + if field_name in _PROTOCOL_LITERAL_FIELDS and value in _PROTOCOL_LITERAL_VALUES: + return LiteralSegment(value) + return _segment_text( + value, + grant_texts, + used_grants, + sanitized_cap=sanitized_cap, + ) + if isinstance(value, Mapping): + return { + key: _typed_payload( + item, + grant_texts, + used_grants, + sanitized_cap=sanitized_cap, + field_name=key, + ) + for key, item in value.items() + } + if isinstance(value, (list, tuple)): + return [ + _typed_payload( + item, + grant_texts, + used_grants, + sanitized_cap=sanitized_cap, + field_name=field_name, + ) + for item in value + ] + return value + + +def _structural_literal_hashes(value: Any) -> frozenset[str]: + literals: set[str] = set() + + def visit(item: Any) -> None: + if isinstance(item, Mapping): + for key, child in item.items(): + if isinstance(key, str): + literals.add(key) + if ( + key in _PROTOCOL_LITERAL_FIELDS + and isinstance(child, str) + and child in _PROTOCOL_LITERAL_VALUES + ): + literals.add(child) + visit(child) + elif isinstance(item, (list, tuple)): + for child in item: + visit(child) + elif item is None or isinstance(item, (bool, int)): + literals.add(json.dumps(item, ensure_ascii=True, separators=(",", ":"))) + elif isinstance(item, float) and math.isfinite(item): + literals.add( + json.dumps( + item, ensure_ascii=True, allow_nan=False, separators=(",", ":") + ) + ) + + visit(value) + return frozenset(static_literal_sha256(literal) for literal in literals) + + +def _route_for_agent(agent: Any, route: Any | None) -> Any: + if route is not None: + return route + provider = str(getattr(agent, "provider", "") or "") + base_url = getattr(agent, "base_url", None) + api_mode = getattr(agent, "api_mode", None) + if provider == "openai-codex" and not base_url: + base_url = "https://chatgpt.com/backend-api/codex" + api_mode = api_mode or "codex_responses" + return SimpleNamespace( + provider=provider, + model=str(getattr(agent, "model", "") or ""), + base_url=base_url, + api_mode=api_mode, + ) + + +def authorize_agent_sdk_kwargs( + agent: Any, + kwargs: Mapping[str, Any], + *, + route: Any | None = None, + sdk_control_keys: Sequence[str] = _SDK_CONTROL_KEYS, +) -> tuple[dict[str, Any], AuthorizedEgress]: + controls = {key: kwargs[key] for key in sdk_control_keys if key in kwargs} + body = {key: value for key, value in kwargs.items() if key not in controls} + session_id = str(getattr(agent, "session_id", "") or "") + turn_id = str(getattr(agent, "_current_turn_id", "") or "") + request_id = str(getattr(agent, "_current_api_request_id", "") or "") + policy_digest = str( + getattr(agent, "_llm_egress_policy_digest", "") + or getattr(agent, "llm_egress_policy_digest", "") + or DEFAULT_POLICY_DIGEST + ) + registry = getattr(agent, "_source_provenance_registry", None) + grants = ( + registry.grants_for_request(request_id) + if isinstance(registry, SourceProvenanceRegistry) + else () + ) + sanitized_cap = int(getattr(agent, "_llm_egress_max_sanitized_bytes", 32_768)) + used_grants: dict[str, SourceGrant] = {} + typed_body = _typed_payload( + body, + _grant_texts(grants), + used_grants, + sanitized_cap=sanitized_cap, + ) + request = TypedOutboundRequest( + payload=typed_body, + session_id=session_id, + turn_id=turn_id, + request_id=request_id, + policy_digest=policy_digest, + ) + state_dir = Path( + getattr(agent, "_llm_egress_state_dir", "") + or Path.home() / ".hermes" / "egress" + ) + firewall = LLMEgressFirewall( + state_dir, + policy_digest=policy_digest, + max_serialized_bytes=int( + getattr(agent, "_llm_egress_max_serialized_bytes", 262_144) + ), + max_sanitized_bytes=sanitized_cap, + static_literal_hashes_by_policy={ + policy_digest: _structural_literal_hashes(body) + }, + ) + authorization = firewall.authorize( + request, + _route_for_agent(agent, route), + grants=tuple(used_grants.values()), + ) + rebuilt = json.loads(authorization.payload_bytes) + if not isinstance(rebuilt, dict): + raise TypeError("authorized provider payload must be a JSON object") + rebuilt.update(controls) + return rebuilt, authorization + + +def dispatch_authorized_agent_request( + agent: Any, + kwargs: Mapping[str, Any], + callback: Callable[[dict[str, Any]], Any], + *, + route: Any | None = None, + sdk_control_keys: Sequence[str] = _SDK_CONTROL_KEYS, +) -> Any: + resolved_route = _route_for_agent(agent, route) + destination = classify_destination( + str(getattr(resolved_route, "provider", "") or ""), + getattr(resolved_route, "base_url", None), + getattr(resolved_route, "api_mode", None), + ) + if destination in {DestinationClass.LOCAL_PROCESS, DestinationClass.LOOPBACK}: + return callback(dict(kwargs)) + authorized, receipt = authorize_agent_sdk_kwargs( + agent, + kwargs, + route=resolved_route, + sdk_control_keys=sdk_control_keys, + ) + # Recreate the exact body digest immediately before the provider callback. + # Only explicit non-content SDK controls are excluded; headers/query are + # scanned and included in the firewall-authorized JSON body. + wire_body = { + key: value for key, value in authorized.items() if key not in sdk_control_keys + } + wire_bytes = json.dumps( + wire_body, + ensure_ascii=False, + allow_nan=False, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + receipt.verify_payload(wire_bytes) + return callback(MappingProxyType(authorized)) diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py index 1d784efa1e13a..f2000f9dde906 100644 --- a/tests/agent/test_auxiliary_client.py +++ b/tests/agent/test_auxiliary_client.py @@ -9,6 +9,7 @@ import pytest +from agent.llm_egress_firewall import EgressBlocked from agent.auxiliary_client import ( _NOUS_MODEL, CodexAuxiliaryClient, @@ -40,6 +41,184 @@ ) +def _aux_egress_response(content="ok"): + return SimpleNamespace( + choices=[SimpleNamespace(message=SimpleNamespace(content=content))], + model="gpt-5.4", + ) + + +def _run_aux_codex_call( + monkeypatch, + tmp_path, + *, + content="safe request", + provider="openai-codex", + base_url="https://chatgpt.com/backend-api/codex", + api_mode="codex_responses", + client_out=None, +): + client = MagicMock() + client.base_url = base_url + client.chat.completions.create.return_value = _aux_egress_response() + monkeypatch.setattr("agent.auxiliary_client.get_hermes_home", lambda: tmp_path) + monkeypatch.setattr( + "agent.auxiliary_client._resolve_task_provider_model", + lambda *args, **kwargs: (provider, "gpt-5.4", None, None, api_mode), + ) + monkeypatch.setattr( + "agent.auxiliary_client._get_cached_client", + lambda *args, **kwargs: (client, "gpt-5.4"), + ) + if client_out is not None: + client_out.append(client) + return client, call_llm( + task="compression", + provider=provider, + model="gpt-5.4", + main_runtime={"session_id": "session-aux"}, + messages=[{"role": "user", "content": content}], + ) + + +def test_codex_auxiliary_egress_authorizes_once_with_complete_identity( + monkeypatch, tmp_path +): + client, response = _run_aux_codex_call(monkeypatch, tmp_path) + + assert response.choices[0].message.content == "ok" + client.chat.completions.create.assert_called_once() + receipt_path = tmp_path / "egress" / "llm-egress-receipts.jsonl" + receipt = json.loads(receipt_path.read_text().splitlines()[0]) + assert receipt["decision"] == "allow" + assert receipt["provider"] == "openai-codex" + assert receipt["session_id"] == "session-aux" + assert receipt["turn_id"] + assert receipt["request_id"] + assert receipt["policy_digest"] + + +def test_codex_auxiliary_egress_blocks_secret_before_provider_callback( + monkeypatch, tmp_path +): + clients = [] + with pytest.raises(EgressBlocked): + _run_aux_codex_call( + monkeypatch, + tmp_path, + content="token=super-secret-value", + client_out=clients, + ) + + assert clients[0].chat.completions.create.call_count == 0 + + +def test_nous_auxiliary_egress_is_provider_bound(monkeypatch, tmp_path): + client, response = _run_aux_codex_call( + monkeypatch, + tmp_path, + provider="nous", + base_url="https://inference-api.nousresearch.com/v1", + api_mode="chat_completions", + ) + + assert response.choices[0].message.content == "ok" + client.chat.completions.create.assert_called_once() + receipt = json.loads( + (tmp_path / "egress" / "llm-egress-receipts.jsonl").read_text().splitlines()[0] + ) + assert receipt["provider"] == "nous" + assert receipt["destination_class"] == "remote" + + +def test_nous_auxiliary_egress_blocks_secret_before_provider_callback(monkeypatch, tmp_path): + clients = [] + with pytest.raises(EgressBlocked): + _run_aux_codex_call( + monkeypatch, + tmp_path, + content="token=super-secret-value", + provider="nous", + base_url="https://inference-api.nousresearch.com/v1", + api_mode="chat_completions", + client_out=clients, + ) + assert clients[0].chat.completions.create.call_count == 0 + + +def test_nous_anthropic_messages_auxiliary_egress_blocks_secret(monkeypatch, tmp_path): + clients = [] + with pytest.raises(EgressBlocked): + _run_aux_codex_call( + monkeypatch, + tmp_path, + content="token=super-secret-value", + provider="nous", + base_url="https://inference-api.nousresearch.com/anthropic", + api_mode="anthropic_messages", + client_out=clients, + ) + assert clients[0].chat.completions.create.call_count == 0 + + +def test_local_auxiliary_route_bypasses_remote_egress(monkeypatch, tmp_path): + dispatch = MagicMock(side_effect=AssertionError("local route must not use remote egress")) + monkeypatch.setattr("agent.llm_egress_runtime.dispatch_authorized_agent_request", dispatch) + client, response = _run_aux_codex_call( + monkeypatch, + tmp_path, + provider="custom", + base_url="http://127.0.0.1:11434/v1", + api_mode="chat_completions", + ) + + assert response.choices[0].message.content == "ok" + client.chat.completions.create.assert_called_once() + dispatch.assert_not_called() + + +def test_blocked_remote_aux_call_is_fallback_eligible_without_retry(monkeypatch, tmp_path): + primary = MagicMock() + primary.base_url = "https://chatgpt.com/backend-api/codex" + primary.chat.completions.create.return_value = _aux_egress_response() + fallback = MagicMock() + fallback.base_url = "http://127.0.0.1:11434/v1" + fallback.chat.completions.create.return_value = _aux_egress_response("fallback") + monkeypatch.setattr("agent.auxiliary_client.get_hermes_home", lambda: tmp_path) + monkeypatch.setattr( + "agent.auxiliary_client._resolve_task_provider_model", + lambda *args, **kwargs: ("openai-codex", "gpt-5.4", None, None, "codex_responses"), + ) + monkeypatch.setattr( + "agent.auxiliary_client._get_cached_client", + lambda provider, *args, **kwargs: (primary, "gpt-5.4"), + ) + monkeypatch.setattr( + "agent.auxiliary_client._try_configured_fallback_chain", + lambda *args, **kwargs: (None, None, ""), + ) + monkeypatch.setattr( + "agent.auxiliary_client._try_main_agent_model_fallback", + lambda *args, **kwargs: (fallback, "local-model", "custom"), + ) + monkeypatch.setattr( + "agent.auxiliary_client._transient_retry_count", + lambda: (_ for _ in ()).throw(AssertionError("blocked request must not retry")), + ) + + response = call_llm( + task="compression", + provider="openai-codex", + model="gpt-5.4", + main_runtime={"session_id": "session-fallback"}, + messages=[{"role": "user", "content": "token=super-secret-value"}], + ) + + assert response.choices[0].message.content == "fallback" + primary.chat.completions.create.assert_not_called() + fallback.chat.completions.create.assert_called_once() + + def _jwt_with_claims(claims: dict) -> str: header = base64.urlsafe_b64encode(b'{"alg":"none","typ":"JWT"}').decode().rstrip("=") payload = base64.urlsafe_b64encode(json.dumps(claims).encode()).decode().rstrip("=") diff --git a/tests/agent/test_codex_request_transport_diagnostics.py b/tests/agent/test_codex_request_transport_diagnostics.py index 0a65155baf5cf..50da808ad9866 100644 --- a/tests/agent/test_codex_request_transport_diagnostics.py +++ b/tests/agent/test_codex_request_transport_diagnostics.py @@ -21,7 +21,7 @@ def test_transport_failure_without_attached_request_reports_unknown_size(): assert exception_chain == "RemoteProtocolError" -def test_transport_failure_logs_exact_request_bytes_and_class_chain(caplog): +def test_transport_failure_logs_exact_request_bytes_and_class_chain(caplog, tmp_path): request_content = b'{"input":"payload"}' request = httpx.Request( "POST", @@ -43,11 +43,13 @@ def create(self, **_kwargs): agent = SimpleNamespace( _interrupt_requested=False, _current_api_request_id="request-id", + _current_turn_id="turn-id", + _llm_egress_state_dir=tmp_path, _fallback_index=0, is_subagent=False, model="gpt-5.6-sol", provider="openai-codex", - session_id="", + session_id="session-id", ) with caplog.at_level(logging.WARNING, logger="agent.codex_runtime"): diff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.py index 56817ffd69668..8fd7c7b35eaff 100644 --- a/tests/agent/test_error_classifier.py +++ b/tests/agent/test_error_classifier.py @@ -66,6 +66,7 @@ def test_enum_members_exist(self): "multimodal_tool_content_unsupported", "provider_policy_blocked", "content_policy_blocked", + "egress_policy_blocked", "thinking_signature", "long_context_tier", "oauth_long_context_beta_forbidden", "llama_cpp_grammar_pattern", @@ -74,6 +75,38 @@ def test_enum_members_exist(self): actual = {r.value for r in FailoverReason} assert expected == actual + def test_egress_policy_denial_falls_back_without_retry(self): + from agent.llm_egress_firewall import ( + DestinationClass, + EgressBlocked, + EgressDecision, + ) + + error = EgressBlocked( + EgressDecision( + allowed=False, + destination_class=DestinationClass.REMOTE, + provider="nous", + model="test-model", + payload_sha256="", + serialized_bytes=0, + estimated_tokens=0, + source_grant_count=0, + source_segment_count=0, + session_id="session", + turn_id="turn", + request_id="request", + policy_digest="policy", + reason_codes=("secret_detected",), + ) + ) + + result = classify_api_error(error, provider="nous", model="test-model") + + assert result.reason is FailoverReason.egress_policy_blocked + assert result.retryable is False + assert result.should_fallback is True + # ── Test: ClassifiedError ────────────────────────────────────────────── @@ -1577,5 +1610,3 @@ def test_other_bad_parameter_via_5xx_stays_non_retryable(self, status_code): result = classify_api_error(e, provider="custom", model="m") assert result.reason == FailoverReason.format_error assert result.retryable is False - - diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index f3ee4080b546a..58d0f1fc354e6 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -91,6 +91,16 @@ def typed(value): ) +def _sanitized_request(text: str) -> TypedOutboundRequest: + return TypedOutboundRequest( + payload={"messages": [{"role": LiteralSegment("user"), "content": SanitizedSegment(text)}]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + + _COMMON_STATIC_LITERALS = { "messages", "role", @@ -273,9 +283,96 @@ def test_only_exact_policy_allowlisted_static_wrappers_accompany_source(tmp_path LiteralSegment(""), ) ) - with pytest.raises(EgressBlocked) as sanitized_exc: - gate.preflight(typed_request, _route(), grants=(grant,)) - assert "sanitized_segment_forbidden" in sanitized_exc.value.decision.reason_codes + sanitized = gate.authorize(typed_request, _route(), grants=(grant,)) + assert json.loads(sanitized.payload_bytes)["messages"][0]["content"] == ( + "\nx=1\n" + ) + + +def test_bounded_sanitized_remote_text_needs_no_source_grant(tmp_path): + request = TypedOutboundRequest( + payload={"messages": [{"role": SanitizedSegment("user"), "content": SanitizedSegment("Fix CI now.")}]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + authorization = firewall(tmp_path).authorize(request, _route(), grants=()) + assert json.loads(authorization.payload_bytes) == { + "messages": [{"content": "Fix CI now.", "role": "user"}] + } + assert authorization.decision.source_grant_count == 0 + + +def test_remote_sanitized_request_requires_complete_request_identity(tmp_path): + request = TypedOutboundRequest( + payload={"messages": [SanitizedSegment("Fix CI now.")]}, + session_id="session-1", + turn_id="", + request_id="req-1", + policy_digest="policy-1", + ) + + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).authorize(request, _route(), grants=()) + + assert "missing_request_identity" in exc_info.value.decision.reason_codes + + +def test_sanitized_remote_text_has_an_independent_exact_byte_cap(tmp_path): + request = TypedOutboundRequest( + payload={"messages": [SanitizedSegment("CI fix!!")]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + assert firewall(tmp_path, max_sanitized_bytes=8).preflight(request, _route()).allowed + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path, max_sanitized_bytes=7).preflight(request, _route()) + assert "sanitized_bytes_exceeded" in exc_info.value.decision.reason_codes + + +@pytest.mark.parametrize( + ("text", "reason"), + [ + ("token=super-secret-value", "secret_detected"), + (base64.b64encode(b"encoded private detail").decode("ascii"), "base64_payload"), + ("Read /Users/private/repository/file.py", "private_absolute_path"), + (r"Read C:\\Users\\private\\secrets.txt", "private_absolute_path"), + ], +) +def test_sanitized_remote_text_denies_secrets_encoding_and_private_paths( + tmp_path, + text, + reason, +): + request = TypedOutboundRequest( + payload={"messages": [SanitizedSegment(text)]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(request, _route()) + assert reason in exc_info.value.decision.reason_codes + + +def test_source_bytes_cannot_be_relabelled_as_sanitized_text(tmp_path): + path = tmp_path / "private.py" + path.write_text("private source\n", encoding="utf-8") + grant = _source_grant(path) + request = TypedOutboundRequest( + payload={"messages": [SanitizedSegment("private source\n")]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(request, _route(), grants=(grant,)) + assert "source_bytes_in_sanitized_segment" in exc_info.value.decision.reason_codes def test_firewall_binds_requests_to_its_configured_policy_digest(tmp_path): @@ -489,6 +586,53 @@ def test_canonical_base64_payloads_are_rejected_even_when_decoded_content_is_ben assert "base64_payload" in exc_info.value.decision.reason_codes +def test_base64_payload_split_by_whitespace_is_still_rejected(tmp_path): + encoded = base64.b64encode(b"private source that must not leave the host").decode("ascii") + split = " ".join(encoded[index : index + 2] for index in range(0, len(encoded), 2)) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(_sanitized_request(split), _route()) + assert "base64_payload" in exc_info.value.decision.reason_codes + + +@pytest.mark.parametrize( + "text", + [ + "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + "commit 0123456789abcdef0123456789abcdef01234567 is already reviewed", + "The prose mentions commit 0123456789abcdef0123456789abcdef01234567 here.", + ], +) +def test_sha_and_commit_references_in_prose_are_not_base64_false_positives(tmp_path, text): + decision = firewall(tmp_path).preflight(_sanitized_request(text), _route()) + assert "base64_payload" not in decision.reason_codes + + +def test_sanitized_proper_substring_of_grant_text_is_rejected(tmp_path): + path = tmp_path / "source.txt" + path.write_text("private source\n", encoding="utf-8") + grant = _source_grant(path) + request = TypedOutboundRequest( + payload={"messages": [SanitizedSegment("private source")]}, + session_id=grant.session_id, + turn_id=grant.turn_id, + request_id=grant.request_id, + policy_digest=grant.policy_digest, + ) + with pytest.raises(EgressBlocked) as exc_info: + firewall(tmp_path).preflight(request, _route(), grants=(grant,)) + assert "source_bytes_in_sanitized_segment" in exc_info.value.decision.reason_codes + + +def test_symlink_state_directory_is_rejected(tmp_path): + target = tmp_path / "receipts-target" + target.mkdir() + state = tmp_path / "egress" + state.symlink_to(target, target_is_directory=True) + with pytest.raises(EgressBlocked) as exc_info: + firewall(state).preflight(_sanitized_request("safe request"), _route()) + assert "receipt_unavailable" in exc_info.value.decision.reason_codes + + def test_ordinary_short_base64_alphabet_words_are_not_false_positives(tmp_path): decision = firewall(tmp_path).preflight( _request("ordinary short words remain usable"), @@ -497,6 +641,17 @@ def test_ordinary_short_base64_alphabet_words_are_not_false_positives(tmp_path): assert "base64_payload" not in decision.reason_codes +def test_short_alphabetic_words_are_allowed_in_sanitized_remote_text(tmp_path): + request = TypedOutboundRequest( + payload={"messages": [SanitizedSegment("ordinary review carefully")]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + assert firewall(tmp_path).preflight(request, _route()).allowed + + def test_scanner_error_fails_closed(monkeypatch, tmp_path): def explode(*args, **kwargs): raise RuntimeError("scanner unavailable") @@ -600,6 +755,20 @@ def test_receipt_hashes_unsafe_identity_and_route_labels(tmp_path): assert str(Path.home()) not in receipt_text +def test_receipt_redacts_route_credentials_and_binds_route_metadata(tmp_path): + route = _route( + base_url="https://user:password@example.test/v1?api_key=route-secret", + api_mode="chat_completions", + ) + firewall(tmp_path).preflight(_sanitized_request("safe request"), route) + receipt_text = (tmp_path / "llm-egress-receipts.jsonl").read_text() + assert "password" not in receipt_text + assert "route-secret" not in receipt_text + receipt = json.loads(receipt_text.splitlines()[0]) + assert receipt["api_mode"] == "chat_completions" + assert receipt["base_url"].startswith("sha256:") + + def test_receipt_is_owner_only_and_rejects_symlink_ledger(tmp_path): path = tmp_path / "private.py" path.write_text("x=1\n", encoding="utf-8") @@ -646,6 +815,19 @@ def append(index: int) -> None: } +def test_receipts_form_a_content_free_hash_chain(tmp_path): + gate = firewall(tmp_path) + gate.preflight(_sanitized_request("first"), _route()) + gate.preflight(_sanitized_request("second"), _route()) + lines = (tmp_path / "llm-egress-receipts.jsonl").read_bytes().splitlines() + first = json.loads(lines[0]) + second = json.loads(lines[1]) + assert first["receipt_prev_sha256"] == "" + assert second["receipt_prev_sha256"] == sha256(lines[0]).hexdigest() + assert first["receipt_sha256"] + assert second["receipt_sha256"] + + def test_unknown_destination_fails_closed_even_with_source_grant(tmp_path): path = tmp_path / "private.py" path.write_text("private source\n", encoding="utf-8") diff --git a/tests/agent/test_llm_egress_provider_boundaries.py b/tests/agent/test_llm_egress_provider_boundaries.py new file mode 100644 index 0000000000000..98a9f3ab1aa58 --- /dev/null +++ b/tests/agent/test_llm_egress_provider_boundaries.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +from hashlib import sha256 +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from agent.chat_completion_helpers import ( + _dispatch_nonstreaming_api_request, + _dispatch_provider_request, +) +from agent.llm_egress_firewall import EgressBlocked + + +def _agent(tmp_path, *, provider="nous", api_mode="chat_completions"): + return SimpleNamespace( + provider=provider, + model="test-model", + base_url=( + "https://chatgpt.com/backend-api/codex" + if provider == "openai-codex" + else "https://inference-api.nousresearch.com/v1" + ), + api_mode=api_mode, + session_id="session-1", + _current_turn_id="turn-1", + _current_api_request_id="request-1", + _llm_egress_policy_digest=sha256(b"policy").hexdigest(), + _llm_egress_state_dir=tmp_path, + ) + + +@pytest.mark.parametrize( + "provider", ["openai-codex", "nous", "nous-portal", "nousresearch"] +) +def test_protected_main_provider_denies_before_callback(tmp_path, provider): + agent = _agent(tmp_path, provider=provider) + callback = MagicMock() + + with pytest.raises(EgressBlocked): + _dispatch_provider_request( + agent, + { + "model": "test-model", + "messages": [{"role": "user", "content": "token=super-secret-value"}], + }, + callback, + ) + + callback.assert_not_called() + + +def test_local_main_provider_keeps_zero_firewall_overhead(tmp_path): + agent = _agent(tmp_path, provider="ollama-launch") + agent.base_url = "http://127.0.0.1:11434/v1" + request = {"messages": [{"role": "user", "content": "/Users/private/file.py"}]} + callback = MagicMock(return_value="local") + + assert _dispatch_provider_request(agent, request, callback) == "local" + callback.assert_called_once_with(request) + + +def test_nous_chat_completions_entrypoint_uses_firewall(tmp_path): + agent = _agent(tmp_path) + client = MagicMock() + + with pytest.raises(EgressBlocked): + _dispatch_nonstreaming_api_request( + agent, + { + "model": "test-model", + "messages": [{"role": "user", "content": "/Users/private/file.py"}], + }, + make_client=lambda *_args, **_kwargs: client, + ) + + client.chat.completions.create.assert_not_called() + + +def test_nous_anthropic_entrypoint_uses_firewall(tmp_path): + agent = _agent(tmp_path, api_mode="anthropic_messages") + agent._anthropic_messages_create = MagicMock() + client = MagicMock() + + with pytest.raises(EgressBlocked): + _dispatch_nonstreaming_api_request( + agent, + { + "model": "test-model", + "messages": [{"role": "user", "content": "/Users/private/file.py"}], + }, + make_client=lambda *_args, **_kwargs: client, + ) + + agent._anthropic_messages_create.assert_not_called() diff --git a/tests/agent/test_llm_egress_runtime.py b/tests/agent/test_llm_egress_runtime.py new file mode 100644 index 0000000000000..4ec148701a541 --- /dev/null +++ b/tests/agent/test_llm_egress_runtime.py @@ -0,0 +1,188 @@ +from __future__ import annotations + +from hashlib import sha256 +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from agent.llm_egress_firewall import EgressBlocked, SanitizedTextRejected +from agent.llm_egress_runtime import ( + authorize_agent_sdk_kwargs, + dispatch_authorized_agent_request, +) +from agent.source_provenance import SourceProvenanceRegistry + + +def _agent(tmp_path: Path, registry: SourceProvenanceRegistry | None = None): + return SimpleNamespace( + provider="custom", + model="test-model", + base_url="https://llm.example.test/v1", + api_mode="chat_completions", + session_id="session-1", + _current_turn_id="turn-1", + _current_api_request_id="req-1", + _llm_egress_policy_digest=sha256(b"policy-1").hexdigest(), + _llm_egress_state_dir=tmp_path, + _source_provenance_registry=registry or SourceProvenanceRegistry(), + ) + + +def _grant(tmp_path: Path, registry: SourceProvenanceRegistry): + path = tmp_path / "source.py" + content = b"verified source\n" + path.write_bytes(content) + return registry.issue_file_slice( + path=path, + line_start=1, + line_end=1, + content=content, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest=sha256(b"policy-1").hexdigest(), + ) + + +def test_runtime_authorizes_mixed_exact_source_and_bounded_sanitized_text(tmp_path): + registry = SourceProvenanceRegistry() + _grant(tmp_path, registry) + agent = _agent(tmp_path, registry) + kwargs = { + "model": "test-model", + "messages": [ + {"role": "system", "content": "Fix CI now."}, + {"role": "user", "content": "CI:\nverified source\nDo fix."}, + ], + "temperature": 0, + } + + authorized, receipt = authorize_agent_sdk_kwargs(agent, kwargs) + + assert authorized == kwargs + assert receipt.decision.source_grant_count == 1 + assert receipt.decision.source_segment_count == 1 + wire = json.loads(receipt.payload_bytes) + assert wire == kwargs + assert "session_id" not in wire + assert "turn_id" not in wire + assert "request_id" not in wire + assert "policy_digest" not in wire + + +def test_runtime_keeps_sdk_controls_out_of_authorized_body(tmp_path): + agent = _agent(tmp_path) + timeout = object() + kwargs = { + "model": "test-model", + "messages": [{"role": "user", "content": "Fix CI now."}], + "timeout": timeout, + } + authorized, receipt = authorize_agent_sdk_kwargs(agent, kwargs) + assert authorized["timeout"] is timeout + assert "timeout" not in json.loads(receipt.payload_bytes) + + +def test_runtime_scans_extra_headers_and_query_as_request_content(tmp_path): + agent = _agent(tmp_path) + calls = [] + with pytest.raises((EgressBlocked, SanitizedTextRejected)): + dispatch_authorized_agent_request( + agent, + { + "model": "test-model", + "messages": [{"role": "user", "content": "Fix CI now."}], + "extra_headers": {"Authorization": "token=secret-value"}, + "extra_query": {"trace": "safe"}, + }, + lambda request: calls.append(request), + ) + assert calls == [] + + +def test_runtime_verifies_authorized_payload_at_provider_boundary( + tmp_path, monkeypatch +): + agent = _agent(tmp_path) + calls = [] + original = __import__( + "agent.llm_egress_firewall", fromlist=["AuthorizedEgress"] + ).AuthorizedEgress.verify_payload + verified = [] + + def _verify(self, candidate): + verified.append(candidate) + return original(self, candidate) + + monkeypatch.setattr( + "agent.llm_egress_firewall.AuthorizedEgress.verify_payload", _verify + ) + dispatch_authorized_agent_request( + agent, + { + "model": "test-model", + "messages": [{"role": "user", "content": "Fix CI now."}], + }, + lambda request: calls.append(request), + ) + assert calls + assert len(verified) == 1 + + +@pytest.mark.parametrize( + "text", + [ + "token=super-secret-value", + "Read /Users/private/repository/file.py", + "ZW5jb2RlZCBwcml2YXRlIGRldGFpbA==", + ], +) +def test_runtime_denies_unsafe_text_before_provider_callback(tmp_path, text): + agent = _agent(tmp_path) + calls = [] + with pytest.raises((EgressBlocked, SanitizedTextRejected)): + dispatch_authorized_agent_request( + agent, + {"model": "test-model", "messages": [{"role": "user", "content": text}]}, + lambda request: calls.append(request), + ) + assert calls == [] + + +def test_runtime_dispatches_exactly_once_with_authorized_bytes(tmp_path): + agent = _agent(tmp_path) + calls = [] + result = dispatch_authorized_agent_request( + agent, + { + "model": "test-model", + "messages": [{"role": "user", "content": "Fix CI now."}], + }, + lambda request: calls.append(request) or "ok", + ) + assert result == "ok" + assert calls == [ + { + "messages": [{"content": "Fix CI now.", "role": "user"}], + "model": "test-model", + } + ] + + +def test_provider_callback_cannot_mutate_authorized_request(tmp_path): + agent = _agent(tmp_path) + + def mutate(request): + request["messages"] = [{"role": "user", "content": "replacement"}] + + with pytest.raises(TypeError): + dispatch_authorized_agent_request( + agent, + { + "model": "test-model", + "messages": [{"role": "user", "content": "Fix CI now."}], + }, + mutate, + ) From 8cdefec7286a42c9d5889b001bda3a8aa0bb32c8 Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Wed, 26 Aug 2026 04:11:22 -0700 Subject: [PATCH 11/26] fix: enforce egress firewall for Claude --- agent/auxiliary_client.py | 13 +++++++------ agent/chat_completion_helpers.py | 2 +- agent/llm_egress_runtime.py | 1 + tests/agent/test_auxiliary_client.py | 15 +++++++++++++++ .../agent/test_llm_egress_provider_boundaries.py | 14 ++++++++------ 5 files changed, 32 insertions(+), 13 deletions(-) diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index e347598eec0ca..8bd7bd7b1a1fa 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -3310,7 +3310,7 @@ def _read_main_api_key_if_same_host(aux_base_url: str) -> str: contextvars.ContextVar("auxiliary_relay_call", default=None) ) -_AUX_EGRESS_PROVIDERS = frozenset({"openai-codex", "nous"}) +_AUX_EGRESS_PROVIDERS = frozenset({"anthropic", "openai-codex", "nous"}) def _auxiliary_egress_binding( @@ -3352,11 +3352,12 @@ def _auxiliary_egress_binding( if not isinstance(candidate_base_url, str) or not candidate_base_url.startswith( ("http://", "https://") ): - candidate_base_url = ( - "https://chatgpt.com/backend-api/codex" - if normalized_provider == "openai-codex" - else _NOUS_DEFAULT_BASE_URL - ) + if normalized_provider == "openai-codex": + candidate_base_url = "https://chatgpt.com/backend-api/codex" + elif normalized_provider == "anthropic": + candidate_base_url = "https://api.anthropic.com/v1" + else: + candidate_base_url = _NOUS_DEFAULT_BASE_URL base_url = candidate_base_url resolved_api_mode = str( api_mode diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py index c26fe0888b0b7..abc425d0cb39c 100644 --- a/agent/chat_completion_helpers.py +++ b/agent/chat_completion_helpers.py @@ -924,7 +924,7 @@ def _bedrock_reasoning_stale_floor(model_id: object) -> "float | None": _EGRESS_PROTECTED_PROVIDERS = frozenset( - {"openai-codex", "nous", "nous-portal", "nousresearch"} + {"anthropic", "openai-codex", "nous", "nous-portal", "nousresearch"} ) diff --git a/agent/llm_egress_runtime.py b/agent/llm_egress_runtime.py index 4c08b65bf0c5c..9a330fc3bd58e 100644 --- a/agent/llm_egress_runtime.py +++ b/agent/llm_egress_runtime.py @@ -47,6 +47,7 @@ "user", }) _PROTECTED_REMOTE_PROVIDERS = frozenset({ + "anthropic", "openai-codex", "nous", "nous-portal", diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py index f2000f9dde906..b8aae5aadef6e 100644 --- a/tests/agent/test_auxiliary_client.py +++ b/tests/agent/test_auxiliary_client.py @@ -161,6 +161,21 @@ def test_nous_anthropic_messages_auxiliary_egress_blocks_secret(monkeypatch, tmp assert clients[0].chat.completions.create.call_count == 0 +def test_direct_anthropic_auxiliary_egress_blocks_secret(monkeypatch, tmp_path): + clients = [] + with pytest.raises(EgressBlocked): + _run_aux_codex_call( + monkeypatch, + tmp_path, + content="token=super-secret-value", + provider="anthropic", + base_url="https://api.anthropic.com/v1", + api_mode="anthropic_messages", + client_out=clients, + ) + assert clients[0].chat.completions.create.call_count == 0 + + def test_local_auxiliary_route_bypasses_remote_egress(monkeypatch, tmp_path): dispatch = MagicMock(side_effect=AssertionError("local route must not use remote egress")) monkeypatch.setattr("agent.llm_egress_runtime.dispatch_authorized_agent_request", dispatch) diff --git a/tests/agent/test_llm_egress_provider_boundaries.py b/tests/agent/test_llm_egress_provider_boundaries.py index 98a9f3ab1aa58..8764ca46b6f37 100644 --- a/tests/agent/test_llm_egress_provider_boundaries.py +++ b/tests/agent/test_llm_egress_provider_boundaries.py @@ -14,14 +14,16 @@ def _agent(tmp_path, *, provider="nous", api_mode="chat_completions"): + if provider == "openai-codex": + base_url = "https://chatgpt.com/backend-api/codex" + elif provider == "anthropic": + base_url = "https://api.anthropic.com/v1" + else: + base_url = "https://inference-api.nousresearch.com/v1" return SimpleNamespace( provider=provider, model="test-model", - base_url=( - "https://chatgpt.com/backend-api/codex" - if provider == "openai-codex" - else "https://inference-api.nousresearch.com/v1" - ), + base_url=base_url, api_mode=api_mode, session_id="session-1", _current_turn_id="turn-1", @@ -32,7 +34,7 @@ def _agent(tmp_path, *, provider="nous", api_mode="chat_completions"): @pytest.mark.parametrize( - "provider", ["openai-codex", "nous", "nous-portal", "nousresearch"] + "provider", ["openai-codex", "nous", "nous-portal", "nousresearch", "anthropic"] ) def test_protected_main_provider_denies_before_callback(tmp_path, provider): agent = _agent(tmp_path, provider=provider) From 2f6cce7f80159a791a7ba12117770ad1018698a6 Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Wed, 26 Aug 2026 04:58:55 -0700 Subject: [PATCH 12/26] fix: allow JSON protocol acronym through egress scan --- agent/llm_egress_firewall.py | 1 + tests/agent/test_llm_egress_firewall.py | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index b24411dfc1c5e..b9b9f443b491e 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -197,6 +197,7 @@ def verify_payload(self, candidate: bytes) -> bytes: "function_call_output", "input_image", "input_text", + "JSON", "messages", "output_text", "reasoning", diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index 58d0f1fc354e6..014240ea2d191 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -652,6 +652,17 @@ def test_short_alphabetic_words_are_allowed_in_sanitized_remote_text(tmp_path): assert firewall(tmp_path).preflight(request, _route()).allowed +def test_json_protocol_acronym_is_not_a_base64_false_positive(tmp_path): + request = TypedOutboundRequest( + payload={"messages": [SanitizedSegment("Return JSON only.")]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + assert firewall(tmp_path).preflight(request, _route()).allowed + + def test_scanner_error_fails_closed(monkeypatch, tmp_path): def explode(*args, **kwargs): raise RuntimeError("scanner unavailable") From 86c6fc6ad6da7ca4b4788dcfb05ff51985954ef5 Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Wed, 26 Aug 2026 05:49:44 -0700 Subject: [PATCH 13/26] fix: allow bounded large-context compression egress --- agent/auxiliary_client.py | 32 ++++--- agent/llm_egress_firewall.py | 46 +++++++++- agent/llm_egress_runtime.py | 35 ++++++- tests/agent/test_auxiliary_client.py | 116 ++++++++++++++++++++++++ tests/agent/test_llm_egress_firewall.py | 99 ++++++++++++++++++++ tests/agent/test_llm_egress_runtime.py | 30 ++++++ 6 files changed, 340 insertions(+), 18 deletions(-) diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index 8bd7bd7b1a1fa..d2f8f80997a85 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -3367,17 +3367,27 @@ def _auxiliary_egress_binding( else "chat_completions" ) ) - agent = SimpleNamespace( - provider=normalized_provider, - model=str(model or ""), - base_url=base_url, - api_mode=resolved_api_mode, - session_id=session_id, - _current_turn_id=turn_id, - _current_api_request_id=request_id, - _llm_egress_policy_digest=policy_digest, - _llm_egress_state_dir=Path(get_hermes_home()) / "egress", - ) + agent_attrs = { + "provider": normalized_provider, + "model": str(model or ""), + "base_url": base_url, + "api_mode": resolved_api_mode, + "session_id": session_id, + "_current_turn_id": turn_id, + "_current_api_request_id": request_id, + "_llm_egress_policy_digest": policy_digest, + "_llm_egress_state_dir": Path(get_hermes_home()) / "egress", + } + if str(relay.get("task") or "") == "compression": + agent_attrs.update( + _llm_egress_max_serialized_bytes=2_000_000, + _llm_egress_max_conservative_tokens=666_667, + _llm_egress_max_sanitized_bytes=2_000_000, + _llm_egress_max_sanitized_segment_bytes=32_768, + _llm_egress_max_granted_serialized_bytes=2_000_000, + _llm_egress_max_granted_conservative_tokens=666_667, + ) + agent = SimpleNamespace(**agent_attrs) route = SimpleNamespace( provider=normalized_provider, model=str(model or ""), diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index b9b9f443b491e..59f9b63fc4ccb 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -603,7 +603,10 @@ def __init__( *, max_serialized_bytes: int = 262_144, max_sanitized_bytes: int = 32_768, + max_sanitized_segment_bytes: int = 32_768, max_conservative_tokens: int = 87_382, + max_granted_serialized_bytes: int | None = None, + max_granted_conservative_tokens: int | None = None, conservative_chars_per_token: int = 3, policy_digest: str | None = None, static_literal_hashes_by_policy: Mapping[str, Sequence[str]] | None = None, @@ -612,15 +615,35 @@ def __init__( raise ValueError("max_serialized_bytes must be positive") if max_sanitized_bytes <= 0: raise ValueError("max_sanitized_bytes must be positive") + if max_sanitized_segment_bytes <= 0: + raise ValueError("max_sanitized_segment_bytes must be positive") if max_conservative_tokens <= 0: raise ValueError("max_conservative_tokens must be positive") + if max_granted_serialized_bytes is not None and max_granted_serialized_bytes <= 0: + raise ValueError("max_granted_serialized_bytes must be positive") + if ( + max_granted_conservative_tokens is not None + and max_granted_conservative_tokens <= 0 + ): + raise ValueError("max_granted_conservative_tokens must be positive") if conservative_chars_per_token <= 0: raise ValueError("conservative_chars_per_token must be positive") self._state_dir = Path(state_dir) self._receipt_path = self._state_dir / "llm-egress-receipts.jsonl" self._max_serialized_bytes = max_serialized_bytes self._max_sanitized_bytes = max_sanitized_bytes + self._max_sanitized_segment_bytes = max_sanitized_segment_bytes self._max_conservative_tokens = max_conservative_tokens + self._max_granted_serialized_bytes = ( + max_serialized_bytes + if max_granted_serialized_bytes is None + else max_granted_serialized_bytes + ) + self._max_granted_conservative_tokens = ( + max_conservative_tokens + if max_granted_conservative_tokens is None + else max_granted_conservative_tokens + ) self._conservative_chars_per_token = conservative_chars_per_token self._policy_digest = str(policy_digest or "") self._static_literal_hashes_by_policy = { @@ -682,6 +705,7 @@ def authorize( reasons: list[str] = [] valid_grants: list[SourceGrant] = [] grant_contents: dict[str, tuple[SourceGrant, bytes]] = {} + grant_reasons: list[str] = [] source_segment_count = 0 sanitized_only = False if typed_request is not None: @@ -762,9 +786,25 @@ def authorize( estimated_tokens = ( serialized_bytes + self._conservative_chars_per_token - 1 ) // self._conservative_chars_per_token - if serialized_bytes > self._max_serialized_bytes: + use_granted_caps = bool( + typed_request is not None + and source_segment_count > 0 + and valid_grants + and not grant_reasons + ) + serialized_byte_cap = ( + self._max_granted_serialized_bytes + if use_granted_caps + else self._max_serialized_bytes + ) + conservative_token_cap = ( + self._max_granted_conservative_tokens + if use_granted_caps + else self._max_conservative_tokens + ) + if serialized_bytes > serialized_byte_cap: reasons.append("serialized_bytes_exceeded") - if estimated_tokens > self._max_conservative_tokens: + if estimated_tokens > conservative_token_cap: reasons.append("token_cap_exceeded") if destination in {DestinationClass.REMOTE, DestinationClass.UNKNOWN}: @@ -936,6 +976,8 @@ def render_text_segment( reasons.append("sanitized_segment_forbidden") if isinstance(segment.text, str): encoded = segment.text.encode("utf-8") + if len(encoded) > self._max_sanitized_segment_bytes: + reasons.append("sanitized_segment_bytes_exceeded") sanitized_bytes += len(encoded) if sanitized_bytes > self._max_sanitized_bytes: reasons.append("sanitized_bytes_exceeded") diff --git a/agent/llm_egress_runtime.py b/agent/llm_egress_runtime.py index 9a330fc3bd58e..c8ca02452629b 100644 --- a/agent/llm_egress_runtime.py +++ b/agent/llm_egress_runtime.py @@ -245,13 +245,18 @@ def authorize_agent_sdk_kwargs( if isinstance(registry, SourceProvenanceRegistry) else () ) - sanitized_cap = int(getattr(agent, "_llm_egress_max_sanitized_bytes", 32_768)) + sanitized_segment_cap = int( + getattr(agent, "_llm_egress_max_sanitized_segment_bytes", 32_768) + ) + sanitized_aggregate_cap = int( + getattr(agent, "_llm_egress_max_sanitized_bytes", 32_768) + ) used_grants: dict[str, SourceGrant] = {} typed_body = _typed_payload( body, _grant_texts(grants), used_grants, - sanitized_cap=sanitized_cap, + sanitized_cap=sanitized_segment_cap, ) request = TypedOutboundRequest( payload=typed_body, @@ -264,13 +269,33 @@ def authorize_agent_sdk_kwargs( getattr(agent, "_llm_egress_state_dir", "") or Path.home() / ".hermes" / "egress" ) + max_serialized_bytes = int( + getattr(agent, "_llm_egress_max_serialized_bytes", 262_144) + ) + max_conservative_tokens = int( + getattr(agent, "_llm_egress_max_conservative_tokens", 87_382) + ) firewall = LLMEgressFirewall( state_dir, policy_digest=policy_digest, - max_serialized_bytes=int( - getattr(agent, "_llm_egress_max_serialized_bytes", 262_144) + max_serialized_bytes=max_serialized_bytes, + max_conservative_tokens=max_conservative_tokens, + max_granted_serialized_bytes=int( + getattr( + agent, + "_llm_egress_max_granted_serialized_bytes", + max_serialized_bytes, + ) + ), + max_granted_conservative_tokens=int( + getattr( + agent, + "_llm_egress_max_granted_conservative_tokens", + max_conservative_tokens, + ) ), - max_sanitized_bytes=sanitized_cap, + max_sanitized_bytes=sanitized_aggregate_cap, + max_sanitized_segment_bytes=sanitized_segment_cap, static_literal_hashes_by_policy={ policy_digest: _structural_literal_hashes(body) }, diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py index b8aae5aadef6e..cadd2d7b84d6f 100644 --- a/tests/agent/test_auxiliary_client.py +++ b/tests/agent/test_auxiliary_client.py @@ -10,6 +10,7 @@ import pytest from agent.llm_egress_firewall import EgressBlocked +from agent.llm_egress_runtime import authorize_agent_sdk_kwargs from agent.auxiliary_client import ( _NOUS_MODEL, CodexAuxiliaryClient, @@ -38,6 +39,8 @@ _resolve_xai_oauth_for_aux, _CodexCompletionsAdapter, _pool_runtime_base_url, + _auxiliary_egress_binding, + _RELAY_AUX_CALL_CONTEXT, ) @@ -192,6 +195,119 @@ def test_local_auxiliary_route_bypasses_remote_egress(monkeypatch, tmp_path): dispatch.assert_not_called() +def test_only_compression_auxiliary_binding_gets_larger_exact_grant_caps(): + client = SimpleNamespace(base_url="https://chatgpt.com/backend-api/codex") + compression_token = _RELAY_AUX_CALL_CONTEXT.set({"task": "compression"}) + try: + compression_agent, _ = _auxiliary_egress_binding( + client, + provider="openai-codex", + model="gpt-5.4", + api_mode="codex_responses", + ) + finally: + _RELAY_AUX_CALL_CONTEXT.reset(compression_token) + + vision_token = _RELAY_AUX_CALL_CONTEXT.set({"task": "vision"}) + try: + vision_agent, _ = _auxiliary_egress_binding( + client, + provider="openai-codex", + model="gpt-5.4", + api_mode="codex_responses", + ) + finally: + _RELAY_AUX_CALL_CONTEXT.reset(vision_token) + + assert compression_agent._llm_egress_max_granted_serialized_bytes == 2_000_000 + assert compression_agent._llm_egress_max_granted_conservative_tokens == 666_667 + assert compression_agent._llm_egress_max_serialized_bytes == 2_000_000 + assert compression_agent._llm_egress_max_conservative_tokens == 666_667 + assert compression_agent._llm_egress_max_sanitized_bytes == 2_000_000 + assert compression_agent._llm_egress_max_sanitized_segment_bytes == 32_768 + assert not hasattr(vision_agent, "_llm_egress_max_granted_serialized_bytes") + assert not hasattr(vision_agent, "_llm_egress_max_granted_conservative_tokens") + assert not hasattr(vision_agent, "_llm_egress_max_sanitized_bytes") + assert not hasattr(vision_agent, "_llm_egress_max_sanitized_segment_bytes") + + +def _bound_aux_agent(task: str, tmp_path): + client = SimpleNamespace(base_url="https://chatgpt.com/backend-api/codex") + token = _RELAY_AUX_CALL_CONTEXT.set({"task": task}) + try: + agent, route = _auxiliary_egress_binding( + client, + provider="openai-codex", + model="gpt-5.4", + api_mode="codex_responses", + ) + finally: + _RELAY_AUX_CALL_CONTEXT.reset(token) + agent._llm_egress_state_dir = tmp_path / task + return agent, route + + +def _many_bounded_sanitized_messages(): + return [ + {"role": "user", "content": f"segment {index}. " + "ordinary sentence. " * 240} + for index in range(12) + ] + + +def test_compression_allows_many_bounded_sanitized_segments_but_vision_denies( + tmp_path, +): + request = {"model": "gpt-5.4", "messages": _many_bounded_sanitized_messages()} + compression_agent, compression_route = _bound_aux_agent("compression", tmp_path) + vision_agent, vision_route = _bound_aux_agent("vision", tmp_path) + + authorized, decision = authorize_agent_sdk_kwargs( + compression_agent, + request, + route=compression_route, + ) + assert authorized == request + assert decision.decision.serialized_bytes > 32_768 + + with pytest.raises(EgressBlocked) as exc_info: + authorize_agent_sdk_kwargs(vision_agent, request, route=vision_route) + assert "sanitized_bytes_exceeded" in exc_info.value.decision.reason_codes + + +def test_compression_still_denies_one_sanitized_segment_over_32768_bytes(tmp_path): + compression_agent, compression_route = _bound_aux_agent("compression", tmp_path) + oversized = "ordinary sentence. " * 2_000 + + with pytest.raises(ValueError, match="sanitized segment exceeds byte cap"): + authorize_agent_sdk_kwargs( + compression_agent, + {"model": "gpt-5.4", "messages": [{"role": "user", "content": oversized}]}, + route=compression_route, + ) + + +@pytest.mark.parametrize( + ("unsafe", "reason"), + [ + ("token=super-secret-value", "secret_detected"), + ("cHJpdmF0ZSBzb3VyY2UgdGhhdCBtdXN0IG5vdCBsZWF2ZQ==", "base64_payload"), + ("Read /Users/private/repository/file.py", "private_absolute_path"), + ], +) +def test_compression_aggregate_capacity_does_not_bypass_scans(tmp_path, unsafe, reason): + compression_agent, compression_route = _bound_aux_agent("compression", tmp_path) + messages = _many_bounded_sanitized_messages() + messages.append({"role": "user", "content": unsafe}) + + with pytest.raises(EgressBlocked) as exc_info: + authorize_agent_sdk_kwargs( + compression_agent, + {"model": "gpt-5.4", "messages": messages}, + route=compression_route, + ) + assert reason in exc_info.value.decision.reason_codes + + def test_blocked_remote_aux_call_is_fallback_eligible_without_retry(monkeypatch, tmp_path): primary = MagicMock() primary.base_url = "https://chatgpt.com/backend-api/codex" diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index 014240ea2d191..fc0f0f7ca866c 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -333,6 +333,19 @@ def test_sanitized_remote_text_has_an_independent_exact_byte_cap(tmp_path): assert "sanitized_bytes_exceeded" in exc_info.value.decision.reason_codes +def test_sanitized_segment_cap_remains_independent_from_larger_aggregate_cap(tmp_path): + request = _sanitized_request("ordinary sentence. " * 2_000) + with pytest.raises(EgressBlocked) as exc_info: + firewall( + tmp_path, + max_sanitized_segment_bytes=32_768, + max_sanitized_bytes=2_000_000, + max_serialized_bytes=2_000_000, + max_conservative_tokens=666_667, + ).preflight(request, _route()) + assert "sanitized_segment_bytes_exceeded" in exc_info.value.decision.reason_codes + + @pytest.mark.parametrize( ("text", "reason"), [ @@ -712,6 +725,92 @@ def test_byte_and_token_caps_allow_the_exact_boundary(tmp_path): assert decision.allowed is True +def test_larger_granted_caps_require_a_fully_valid_bound_source_segment(tmp_path): + path = tmp_path / "large-source.txt" + path.write_text("plain source sentence\n" * 24, encoding="utf-8") + grant = _source_grant(path, end=24) + request = _typed_request(_request("ignored"), source_grant=grant) + gate = firewall( + tmp_path, + max_serialized_bytes=128, + max_conservative_tokens=64, + max_sanitized_bytes=2_048, + max_granted_serialized_bytes=2_048, + max_granted_conservative_tokens=1_024, + ) + + decision = gate.preflight(request, _route(), grants=(grant,)) + + assert decision.allowed is True + assert decision.serialized_bytes > 128 + assert decision.estimated_tokens > 64 + + raw_request = _request(path.read_text(encoding="utf-8")) + with pytest.raises(EgressBlocked) as raw_exc: + gate.preflight(raw_request, _route(), grants=(grant,)) + assert "typed_request_required" in raw_exc.value.decision.reason_codes + assert "serialized_bytes_exceeded" in raw_exc.value.decision.reason_codes + + sanitized_request = _sanitized_request(path.read_text(encoding="utf-8")) + with pytest.raises(EgressBlocked) as sanitized_exc: + gate.preflight(sanitized_request, _route()) + assert "serialized_bytes_exceeded" in sanitized_exc.value.decision.reason_codes + assert "token_cap_exceeded" in sanitized_exc.value.decision.reason_codes + + +def test_invalid_grant_cannot_select_larger_granted_caps(tmp_path): + path = tmp_path / "source.txt" + path.write_text("plain source sentence\n", encoding="utf-8") + mismatched_grant = _source_grant(path, request_id="another-request") + request = _sanitized_request("bounded sanitized sentence " * 12) + gate = firewall( + tmp_path, + max_serialized_bytes=128, + max_conservative_tokens=64, + max_sanitized_bytes=2_048, + max_granted_serialized_bytes=2_048, + max_granted_conservative_tokens=1_024, + ) + + with pytest.raises(EgressBlocked) as exc_info: + gate.preflight(request, _route(), grants=(mismatched_grant,)) + + reasons = exc_info.value.decision.reason_codes + assert "grant_binding_mismatch" in reasons + assert "serialized_bytes_exceeded" in reasons + assert "token_cap_exceeded" in reasons + + +@pytest.mark.parametrize( + ("source_text", "reason"), + [ + ("token=super-secret-value\n", "secret_detected"), + ("cHJpdmF0ZSBzb3VyY2UgdGhhdCBtdXN0IG5vdCBsZWF2ZQ==\n", "base64_payload"), + ("Read /Users/private/repository/file.py\n", "private_absolute_path"), + ], +) +def test_larger_granted_caps_do_not_bypass_content_scans(tmp_path, source_text, reason): + path = tmp_path / "unsafe-source.txt" + path.write_text(source_text, encoding="utf-8") + grant = _source_grant(path) + gate = firewall( + tmp_path, + max_serialized_bytes=8, + max_conservative_tokens=4, + max_granted_serialized_bytes=2_048, + max_granted_conservative_tokens=1_024, + ) + + with pytest.raises(EgressBlocked) as exc_info: + gate.preflight( + _typed_request(_request("ignored"), source_grant=grant), + _route(), + grants=(grant,), + ) + + assert reason in exc_info.value.decision.reason_codes + + @pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")]) def test_non_finite_typed_number_is_blocked_with_content_free_receipt(tmp_path, value): path = tmp_path / "private.py" diff --git a/tests/agent/test_llm_egress_runtime.py b/tests/agent/test_llm_egress_runtime.py index 4ec148701a541..099b9bd39a4e6 100644 --- a/tests/agent/test_llm_egress_runtime.py +++ b/tests/agent/test_llm_egress_runtime.py @@ -72,6 +72,36 @@ def test_runtime_authorizes_mixed_exact_source_and_bounded_sanitized_text(tmp_pa assert "policy_digest" not in wire +def test_runtime_granted_caps_default_to_the_configured_request_caps(tmp_path): + registry = SourceProvenanceRegistry() + path = tmp_path / "large-source.txt" + content = b"plain source sentence\n" * 12 + path.write_bytes(content) + registry.issue_file_slice( + path=path, + line_start=1, + line_end=12, + content=content, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest=sha256(b"policy-1").hexdigest(), + ) + agent = _agent(tmp_path, registry) + agent._llm_egress_max_serialized_bytes = 128 + + with pytest.raises(EgressBlocked) as exc_info: + authorize_agent_sdk_kwargs( + agent, + { + "model": "test-model", + "messages": [{"role": "user", "content": content.decode("utf-8")}], + }, + ) + + assert "serialized_bytes_exceeded" in exc_info.value.decision.reason_codes + + def test_runtime_keeps_sdk_controls_out_of_authorized_body(tmp_path): agent = _agent(tmp_path) timeout = object() From d664762479d1ef150058193520c26eb26976324f Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Wed, 26 Aug 2026 12:05:12 -0700 Subject: [PATCH 14/26] fix: route protected kanban work autonomously --- agent/kanban_stop.py | 161 ++++++++++++++- agent/llm_egress_firewall.py | 99 ++++++++++ agent/llm_egress_runtime.py | 55 +++++- agent/prompt_builder.py | 16 +- agent/system_prompt.py | 100 +++++++--- hermes_cli/cli_agent_setup_mixin.py | 26 ++- hermes_cli/config_defaults.py | 10 + tests/agent/test_kanban_stop.py | 185 +++++++++++++++++- tests/agent/test_llm_egress_firewall.py | 82 ++++++++ tests/agent/test_llm_egress_runtime.py | 16 ++ tests/agent/test_system_prompt.py | 81 ++++++++ .../test_remote_kanban_private_work.py | 11 ++ tests/hermes_cli/test_set_config_value.py | 7 + tests/tools/test_kanban_tools.py | 8 + tools/file_tools.py | 2 +- tools/terminal_tool.py | 2 +- 16 files changed, 813 insertions(+), 48 deletions(-) create mode 100644 tests/hermes_cli/test_remote_kanban_private_work.py diff --git a/agent/kanban_stop.py b/agent/kanban_stop.py index e7c2eae828a6c..4de2bb88bfac4 100644 --- a/agent/kanban_stop.py +++ b/agent/kanban_stop.py @@ -1,6 +1,6 @@ """Turn-end guard for kanban workers. -Kanban workers must end with ``kanban_complete`` or ``kanban_block``. Models +Kanban workers must end with a terminal board transition. Models (especially GLM / Qwen families) sometimes narrate the next step ("Let me write the report now") and stop with ``finish_reason=stop`` and no tool calls. Hermes treats that as a clean exit → ``rc=0`` → dispatcher @@ -13,13 +13,45 @@ from __future__ import annotations +import json import os from typing import Any, Iterable, Optional -_TERMINAL_KANBAN_TOOLS = frozenset({"kanban_complete", "kanban_block"}) +_TERMINAL_KANBAN_TOOLS = frozenset( + { + "kanban_complete", + "kanban_block", + "kanban_request_review", + "kanban_request_changes", + } +) _DEFAULT_MAX_ATTEMPTS = 2 +_MAX_REVIEW_SUMMARY_CHARS = 4000 + + +def _configured_review_profile() -> str | None: + """Return an installed independent reviewer configured for stop handoffs.""" + + configured = (os.environ.get("HERMES_KANBAN_REVIEWER_PROFILE") or "").strip() + if not configured: + try: + from hermes_cli.config import load_config + + kanban = load_config().get("kanban") or {} + configured = str(kanban.get("reviewer_profile") or "").strip() + except Exception: + return None + if not configured: + return None + try: + from hermes_constants import get_default_hermes_root + + profile_dir = get_default_hermes_root() / "profiles" / configured + return configured if profile_dir.is_dir() else None + except Exception: + return None def kanban_stop_nudge_enabled() -> bool: @@ -66,6 +98,63 @@ def session_called_kanban_terminal(messages: Iterable[dict] | None) -> bool: return False +def successful_kanban_terminal_transition( + *, + messages: Iterable[dict] | None, + tool_calls: Iterable[Any] | None, +) -> bool: + """Return whether this worker's current tool batch durably transitioned it. + + The conversation loop calls this only after the executor has persisted + every tool-result row. Match the current batch by tool-call id and require + the canonical Kanban ``{"ok": true}`` response; merely attempting a + terminal tool (or receiving an error) must not stop the worker before it + can correct the handoff. + """ + if not kanban_stop_nudge_enabled(): + return False + try: + from agent.delegation_context import is_dispatcher_owned_worker_context + + if not is_dispatcher_owned_worker_context(): + return False + except Exception: + return False + + terminal_ids: set[str] = set() + for tool_call in tool_calls or []: + if _tool_call_name(tool_call) not in _TERMINAL_KANBAN_TOOLS: + continue + if isinstance(tool_call, dict): + call_id = tool_call.get("id") or tool_call.get("tool_call_id") + else: + call_id = getattr(tool_call, "id", None) + if call_id: + terminal_ids.add(str(call_id)) + if not terminal_ids: + return False + + for message in messages or []: + if not isinstance(message, dict) or message.get("role") != "tool": + continue + if str(message.get("tool_call_id") or "") not in terminal_ids: + continue + if str(message.get("name") or message.get("tool_name") or "") not in ( + _TERMINAL_KANBAN_TOOLS + ): + continue + content = message.get("content") + if not isinstance(content, str): + continue + try: + payload = json.loads(content) + except (json.JSONDecodeError, TypeError): + continue + if isinstance(payload, dict) and payload.get("ok") is True: + return True + return False + + def build_kanban_stop_nudge( *, messages: Iterable[dict] | None = None, @@ -76,7 +165,8 @@ def build_kanban_stop_nudge( """Return a synthetic follow-up when a kanban worker exits without a terminal tool. Returns ``None`` when the guard should not fire (not a kanban worker, - already completed/blocked, or nudge budget exhausted). + already completed, blocked, or handed off across review, or nudge budget + exhausted). """ if not kanban_stop_nudge_enabled(): return None @@ -101,8 +191,73 @@ def build_kanban_stop_nudge( ) +def reconcile_kanban_stop_to_review( + *, + messages: Iterable[dict] | None, + final_response: Any, + attempts: int, + max_attempts: int = _DEFAULT_MAX_ATTEMPTS, +) -> bool: + """Safely terminate a narrated worker after its nudge budget is spent. + + The stop guard already gave the model a bounded same-session opportunity + to call a terminal board tool. If it still returns useful text, route + that text through the *existing* ``kanban_request_review`` handler instead + of letting the process exit cleanly while its card remains ``running``. + + This deliberately requests review rather than completing the task: the + final prose is evidence for a reviewer, never authority to infer success. + The normal handler retains task/run ownership checks, redaction, and the + goal-mode acceptance judge. Any rejection or exception leaves lifecycle + ownership with the dispatcher and returns ``False``. + """ + if not kanban_stop_nudge_enabled(): + return False + if attempts < max_attempts: + return False + if session_called_kanban_terminal(messages): + return False + response_text = str(final_response or "").strip() + if not response_text: + return False + + bounded = response_text[:_MAX_REVIEW_SUMMARY_CHARS] + reviewer = _configured_review_profile() + if reviewer is None: + # A reviewerless handoff is not autonomous: the same implementer gets + # claimed from the review lane and tends to block while asking for a + # human verdict. Leave lifecycle ownership with the dispatcher so the + # attempt is recorded as a protocol violation and can follow normal + # bounded retry/watchdog policy instead. + return False + summary = ( + f"Automatic terminal handoff after {attempts} unanswered Kanban stop " + f"nudges. Worker final output:\n\n{bounded}" + ) + try: + from tools.kanban_tools import _handle_request_review + + raw = _handle_request_review( + { + "summary": summary, + "reviewer": reviewer, + "metadata": { + "source": "kanban_stop_guard", + "terminal_nudges": attempts, + "completion_inferred": False, + }, + } + ) + payload = json.loads(raw) if isinstance(raw, str) else raw + return bool(isinstance(payload, dict) and payload.get("ok") is True) + except Exception: + return False + + __all__ = [ "build_kanban_stop_nudge", "kanban_stop_nudge_enabled", + "reconcile_kanban_stop_to_review", "session_called_kanban_terminal", + "successful_kanban_terminal_transition", ] diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index 59f9b63fc4ccb..fcb0ef1b02d5d 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -174,6 +174,8 @@ def verify_payload(self, candidate: bytes) -> bytes: _BASE64_CANDIDATE = re.compile( r"(? bytes: # scan; this set only resolves the mathematical ambiguity in Base64 detection. _PROTOCOL_GRAMMAR_ATOMS = frozenset( { + "--result", + "-removed", + "100K", + "2000", + "2026", + "4dae", + "600s", + "BOTH", + "COVERAGE", + "EPUB", + "HERMES_KANBAN_DB", + "HERMES_KANBAN_BRANCH", + "HERMES_KANBAN_WORKSPACE", + "LAST", + "MIME", + "MODE", + "MUTUALLY", + "MUST", + "NOTE", + "ONLY", + "REPL", + "REPLACE", + "REQUIRED", + "SILENTLY", "assistant", + "assignee/profile", "computer_call_output", + "com/docs", "content", "developer", + "doc/", + "echo/cat", + "echo/heredoc", + "environment-variable", + "find-and-replace", "function_call", "function_call_output", + "github-code-review", + "grep/rg/find/ls", + "include_archived", "input_image", "input_text", "JSON", + "kanban_heartbeat", + "machine-readable", + "max_runtime_seconds", "messages", + "notification/15s", + "optional-profile", "output_text", + "parent/child", + "parents=", + "parallel_tool_calls", + "path/to/file", + "ppt/", + "prompt_cache_key", "reasoning", "role", + "sed/awk", + "servers/daemons", + "servers/watchers/daemons", + "skills/plugins/cron/memories", "system", "tool", "user", @@ -366,6 +417,15 @@ def _contains_canonical_base64(value: Any, *, seen: set[int] | None = None) -> b prefix = value[max(0, match.start() - 16) : match.start()].lower() if re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", candidate.lower()): continue + # The fixed Kanban task-id grammar carries only a 32-bit hex + # database key. It is application protocol metadata, not an + # encoded source payload. + if _HERMES_TASK_ID.fullmatch(candidate): + continue + # Content-addressed cache routing is a fixed application protocol + # value: the literal ``pck_`` prefix plus exactly 96 bits of hex. + if _PROMPT_CACHE_KEY.fullmatch(candidate): + continue if _canonical_base64_candidate(candidate): return True # Providers and source-control tools sometimes wrap an otherwise @@ -461,6 +521,45 @@ def _contains_private_absolute_path(value: Any, *, seen: set[int] | None = None) return False +def content_free_violation_locations(value: Any) -> tuple[tuple[str, tuple[str, ...]], ...]: + """Return structural indexes and reasons without returning request text.""" + + locations: list[tuple[str, tuple[str, ...]]] = [] + seen: set[int] = set() + + def visit(item: Any, path: str) -> None: + if isinstance(item, str): + reasons: list[str] = [] + if _contains_canonical_base64(item): + reasons.append("base64_payload") + if _contains_private_absolute_path(item): + reasons.append("private_absolute_path") + if reasons: + locations.append((path, tuple(reasons))) + return + if isinstance(item, Mapping): + identity = id(item) + if identity in seen: + locations.append((path, ("cyclic_container",))) + return + seen.add(identity) + for index, (key, child) in enumerate(item.items()): + visit(key, f"{path}.map[{index}].key") + visit(child, f"{path}.map[{index}].value") + return + if isinstance(item, (list, tuple, set, frozenset)): + identity = id(item) + if identity in seen: + locations.append((path, ("cyclic_container",))) + return + seen.add(identity) + for index, child in enumerate(item): + visit(child, f"{path}.sequence[{index}]") + + visit(value, "$") + return tuple(locations) + + def _contains_grant_substring(grant_content: bytes, candidate: bytes) -> bool: """Reject source-derived proper substrings in sanitized text. diff --git a/agent/llm_egress_runtime.py b/agent/llm_egress_runtime.py index c8ca02452629b..469904b718da9 100644 --- a/agent/llm_egress_runtime.py +++ b/agent/llm_egress_runtime.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import logging import math from pathlib import Path from types import MappingProxyType @@ -11,6 +12,7 @@ from agent.llm_egress_firewall import ( AuthorizedEgress, + EgressBlocked, LLMEgressFirewall, LiteralSegment, OutboundText, @@ -23,6 +25,7 @@ source_grant_digest, static_literal_sha256, validate_sanitized_text, + content_free_violation_locations, ) from agent.source_provenance import DEFAULT_POLICY_DIGEST, SourceProvenanceRegistry @@ -53,6 +56,7 @@ "nous-portal", "nousresearch", }) +logger = logging.getLogger(__name__) def provider_uses_egress_firewall(provider: Any) -> bool: @@ -92,6 +96,32 @@ def _approved_sanitized(text: str, *, cap: int) -> SanitizedSegment: return SanitizedSegment(text) +def _approved_sanitized_segments(text: str, *, cap: int) -> list[SanitizedSegment]: + """Split text without weakening the per-segment admission boundary.""" + + if not isinstance(text, str): + raise TypeError("sanitized segment must be text") + if cap <= 0: + raise ValueError("sanitized segment cap must be positive") + if not text: + return [_approved_sanitized(text, cap=cap)] + + segments: list[SanitizedSegment] = [] + start = 0 + byte_count = 0 + for index, character in enumerate(text): + character_bytes = len(character.encode("utf-8")) + if byte_count and byte_count + character_bytes > cap: + segments.append(_approved_sanitized(text[start:index], cap=cap)) + start = index + byte_count = 0 + if character_bytes > cap: + raise ValueError("sanitized character exceeds byte cap") + byte_count += character_bytes + segments.append(_approved_sanitized(text[start:], cap=cap)) + return segments + + def _segment_text( text: str, grant_texts: Sequence[tuple[str, SourceGrant]], @@ -116,19 +146,22 @@ def _segment_text( cursor = chosen[1] if not matches: - return _approved_sanitized(text, cap=sanitized_cap) + sanitized = _approved_sanitized_segments(text, cap=sanitized_cap) + return sanitized[0] if len(sanitized) == 1 else OutboundText(tuple(sanitized)) segments: list[SanitizedSegment | SourceBoundSegment] = [] cursor = 0 for start, end, grant in matches: if start > cursor: - segments.append(_approved_sanitized(text[cursor:start], cap=sanitized_cap)) + segments.extend( + _approved_sanitized_segments(text[cursor:start], cap=sanitized_cap) + ) digest = source_grant_digest(grant) segments.append(SourceBoundSegment(digest)) used_grants[digest] = grant cursor = end if cursor < len(text): - segments.append(_approved_sanitized(text[cursor:], cap=sanitized_cap)) + segments.extend(_approved_sanitized_segments(text[cursor:], cap=sanitized_cap)) return segments[0] if len(segments) == 1 else OutboundText(tuple(segments)) @@ -300,11 +333,17 @@ def authorize_agent_sdk_kwargs( policy_digest: _structural_literal_hashes(body) }, ) - authorization = firewall.authorize( - request, - _route_for_agent(agent, route), - grants=tuple(used_grants.values()), - ) + try: + authorization = firewall.authorize( + request, + _route_for_agent(agent, route), + grants=tuple(used_grants.values()), + ) + except EgressBlocked: + locations = content_free_violation_locations(body) + if locations: + logger.warning("LLM egress blocked structural locations: %s", locations) + raise rebuilt = json.loads(authorization.payload_bytes) if not isinstance(rebuilt, dict): raise TypeError("authorized provider payload must be a JSON object") diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py index 55b1f4fd87440..e6823dd97aff2 100644 --- a/agent/prompt_builder.py +++ b/agent/prompt_builder.py @@ -255,7 +255,7 @@ def _strip_yaml_frontmatter(content: str) -> str: KANBAN_GUIDANCE = ( "# Kanban task execution protocol\n" "You have been assigned ONE task from " - "the shared board at `~/.hermes/kanban.db`. Your task id is in " + "the shared board database. Your task id is in " "`$HERMES_KANBAN_TASK`; your workspace is `$HERMES_KANBAN_WORKSPACE`. " "The `kanban_*` tools in your schema are your primary coordination surface — " "they write directly to the shared SQLite DB and work regardless of terminal " @@ -268,8 +268,10 @@ def _strip_yaml_frontmatter(content: str) -> str: "metadata), any prior attempts on this task if you're a retry, the full " "comment thread, and a pre-formatted `worker_context` you can treat as " "ground truth.\n" - "2. **Work inside the workspace.** `cd $HERMES_KANBAN_WORKSPACE` before " - "any file operations. The workspace is yours for this run. Don't modify " + "2. **Work inside the workspace.** The dispatcher starts terminal and file " + "tools in the task workspace. Confirm with `pwd` or `git status`. Do not pass " + "the literal environment-variable token `$HERMES_KANBAN_WORKSPACE` as a " + "workdir or command argument. The workspace is yours for this run. Don't modify " "files outside it unless the task explicitly asks.\n" "3. **Heartbeat on long operations.** Call `kanban_heartbeat(note=...)` " "every few minutes during long subprocesses (training, encoding, crawling). " @@ -283,6 +285,12 @@ def _strip_yaml_frontmatter(content: str) -> str: "infer (missing credentials, UX choice, paywalled source, peer output you " "need first), call `kanban_block(reason=\"...\")` and stop. Don't guess. " "The user will unblock with context and the dispatcher will respawn you.\n" + "Prior `manual_reclaim`, `crashed`, `protocol_violation`, timeout, fallback, " + "and retry records are attempt-management evidence, not task blockers. Never " + "block because an earlier worker crashed or was reclaimed, and never infer that " + "the assigned work is outside your capacity from those records. Re-read the " + "current task and canonical external state, then work it. A block reason must " + "name a current concrete external blocker you directly reproduced.\n" "5. **Finish with the review model encoded by the task graph.** Always " "include the structured handoff (`summary`, `metadata`) on the lifecycle " "transition itself; never put secrets, tokens, or raw PII in these durable " @@ -329,7 +337,7 @@ def _strip_yaml_frontmatter(content: str) -> str: "\n" "## Reference details that change outcomes\n" "\n" - "- **Workspace.** `cd $HERMES_KANBAN_WORKSPACE` first. For a `worktree` kind " + "- **Workspace.** Use the dispatcher-selected current directory. For a `worktree` kind " "with no `.git`, `git worktree add " "${HERMES_KANBAN_BRANCH:-wt/$HERMES_KANBAN_TASK}` from the main repo, then " "cd there. For a project-linked task the workspace is a fresh " diff --git a/agent/system_prompt.py b/agent/system_prompt.py index fa833d72e310d..06c90d31324ce 100644 --- a/agent/system_prompt.py +++ b/agent/system_prompt.py @@ -65,6 +65,21 @@ ) +GUARDED_EXECUTION_CONTRACT = ( + "# Guarded coding execution contract\n" + "- Work only in the current session worktree. Inspect git status before edits " + "and preserve unrelated user changes.\n" + "- Ground claims in tools: read/search before changing code; use tools for " + "files, git, system state, calculations, and current facts.\n" + "- Make the requested change through tools, then verify it with the relevant " + "command and report its real result. Do not claim completion from a plan or guess.\n" + "- Batch independent read-only calls. Serialize dependent edits. Respect tool " + "permissions and confirmations for side effects.\n" + "- All listed skills remain available. Load a relevant skill with skill_view; " + "use tool discovery when a needed capability is not visible." +) + + def _ra(): """Lazy reference to the ``run_agent`` module. @@ -402,13 +417,40 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) else HERMES_AGENT_HELP_GUIDANCE_NO_SKILLS ) + # Guarded mode replaces duplicated coaching with a compact contract. + # The resolver is fail-closed: focus posture, a coding workspace, and exact + # provider/model allowlists in user config are all required. + from agent.llm_egress_runtime import provider_uses_egress_firewall + + _remote_kanban_prompt = bool( + str(os.environ.get("HERMES_KANBAN_TASK") or "").strip() + and provider_uses_egress_firewall(agent.provider) + ) + _guarded_prompt = _remote_kanban_prompt + if agent.valid_tool_names: + try: + from agent.coding_context import guarded_prompt_enabled + + if not _guarded_prompt: + _guarded_prompt = guarded_prompt_enabled( + platform=agent.platform, + cwd=resolve_context_cwd(), + provider=agent.provider, + model=agent.model, + ) + except Exception: + _guarded_prompt = False + if _guarded_prompt: + stable_parts.append(GUARDED_EXECUTION_CONTRACT) + # Universal task-completion / no-fabrication guidance. Applied to ALL # models regardless of tool_use_enforcement gating — the failure modes # this targets (stopping after a stub; fabricating output when a real # path is blocked) are not model-family specific. Gated only by # config.yaml ``agent.task_completion_guidance`` (default True) so # users who want a leaner prompt can turn it off. - if getattr(agent, "_task_completion_guidance", True) and agent.valid_tool_names: + if (getattr(agent, "_task_completion_guidance", True) + and agent.valid_tool_names): stable_parts.append(TASK_COMPLETION_GUIDANCE) # Universal parallel-tool-call guidance. Tells the model to batch @@ -419,7 +461,8 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) # round-trips and the resent-context cost that compounds over a long # conversation. Gated by config.yaml ``agent.parallel_tool_call_guidance`` # (default True) and only injected when tools are actually loaded. - if getattr(agent, "_parallel_tool_call_guidance", True) and agent.valid_tool_names: + if (not _guarded_prompt and getattr(agent, "_parallel_tool_call_guidance", True) + and agent.valid_tool_names): stable_parts.append(PARALLEL_TOOL_CALL_GUIDANCE) # Tool-aware behavioral guidance: only inject when the tools are loaded @@ -432,21 +475,21 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) # When only the user profile store is enabled, the narrower # USER_PROFILE_GUIDANCE is injected instead — the full block instructs the # model to write notes to a MEMORY.md store that does not exist. - _mem_enabled = getattr(agent, "_memory_enabled", True) - _profile_enabled = getattr(agent, "_user_profile_enabled", True) - if "memory" in agent.valid_tool_names: - if _mem_enabled: - tool_guidance.append(MEMORY_GUIDANCE) - elif _profile_enabled: - tool_guidance.append(USER_PROFILE_GUIDANCE) - if "session_search" in agent.valid_tool_names: - tool_guidance.append(SESSION_SEARCH_GUIDANCE) - if "skill_manage" in agent.valid_tool_names: - tool_guidance.append(SKILLS_GUIDANCE) - # Kanban worker/orchestrator lifecycle — only present when the - # dispatcher spawned this process (kanban_show check_fn gates on - # HERMES_KANBAN_TASK env var). Normal chat sessions never see - # this block. Resolved once at __init__ (see _kanban_worker_guidance). + if not _guarded_prompt: + _mem_enabled = getattr(agent, "_memory_enabled", True) + _profile_enabled = getattr(agent, "_user_profile_enabled", True) + if "memory" in agent.valid_tool_names: + if _mem_enabled: + tool_guidance.append(MEMORY_GUIDANCE) + elif _profile_enabled: + tool_guidance.append(USER_PROFILE_GUIDANCE) + if "session_search" in agent.valid_tool_names: + tool_guidance.append(SESSION_SEARCH_GUIDANCE) + if "skill_manage" in agent.valid_tool_names: + tool_guidance.append(SKILLS_GUIDANCE) + # Kanban worker/orchestrator lifecycle is load-bearing whenever the + # dispatcher spawned this process. Guarded local workers keep this compact, + # env-gated protocol even though ordinary tool coaching is suppressed. _kanban_guidance = getattr(agent, "_kanban_worker_guidance", None) if _kanban_guidance: tool_guidance.append(_kanban_guidance) @@ -458,7 +501,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) # Steering only lands inside tool results, so it's only reachable when the # agent has tools. Static text → byte-stable prompt (no cache hit). - if agent.valid_tool_names: + if not _guarded_prompt and agent.valid_tool_names: stable_parts.append(STEER_CHANNEL_NOTE) # Tool-use enforcement: tells the model to actually call tools instead @@ -503,7 +546,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) # list — custom model-name substrings to match # Resolved once at session start keyed on the (fixed) model name, so # the system prompt stays byte-stable for the life of the conversation. - if agent.valid_tool_names: + if not _guarded_prompt and agent.valid_tool_names: _exec_guidance = getattr(agent, "_execution_guidance", "auto") _exec_inject = False if _exec_guidance is True or (isinstance(_exec_guidance, str) and _exec_guidance.lower() in {"true", "always", "yes", "on"}): @@ -547,6 +590,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) available_tools=agent.valid_tool_names, available_toolsets=avail_toolsets, compact_categories=_compact_cats or None, + compact_all_categories=_guarded_prompt, skills_dir_override=_agent_skills_dir(agent), ) else: @@ -569,7 +613,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) # Environment hints (WSL, Termux, etc.) — tell the agent about the # execution environment so it can translate paths and adapt behavior. # Stable for the lifetime of the process. - _env_hints = _r.build_environment_hints() + _env_hints = "" if _remote_kanban_prompt else _r.build_environment_hints() if _env_hints: stable_parts.append(_env_hints) @@ -580,7 +624,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) # stay in their historical position after the workspace snapshot. coding_workspace_parts: List[str] = [] coding_trailing_parts: List[str] = [] - if agent.valid_tool_names: + if agent.valid_tool_names and not _remote_kanban_prompt: try: from agent.coding_context import coding_system_prompt_parts @@ -692,7 +736,12 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) _root_str = str(get_default_hermes_root()) else: _home_str = _root_str = str(get_hermes_home()) - if active_profile == "default": + if _remote_kanban_prompt: + post_workspace_parts.append( + f"Active Hermes profile: {active_profile}. Work only in the current " + "task workspace and use relative paths." + ) + elif active_profile == "default": post_workspace_parts.append( "Active Hermes profile: default. Other profiles (if any) live " "under " + _root_str + "/profiles//. Each profile has its own " @@ -847,9 +896,10 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) # Plugin sections are intentionally confined to one coarse anchor in the # volatile tail. This preserves deterministic ordering and lets a resumed # process reconstruct the stable cache prefix without re-running plugins. - volatile_parts.extend( - _plugin_section_blocks(_frozen_plugin_prompt_sections(agent), "after_memory") - ) + if not _remote_kanban_prompt: + volatile_parts.extend( + _plugin_section_blocks(_frozen_plugin_prompt_sections(agent), "after_memory") + ) from hermes_time import get_timezone as _hermes_tz, now as _hermes_now now = _hermes_now() diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py index 98e8f410b3f3b..129ab0d380497 100644 --- a/hermes_cli/cli_agent_setup_mixin.py +++ b/hermes_cli/cli_agent_setup_mixin.py @@ -14,6 +14,7 @@ from __future__ import annotations +import os import sys from rich.markup import escape as _escape @@ -21,6 +22,16 @@ from utils import base_url_host_matches +def _remote_kanban_private_work(provider: str | None) -> bool: + """Return whether this CLI is a protected-remote Kanban worker.""" + + if not str(os.environ.get("HERMES_KANBAN_TASK") or "").strip(): + return False + from agent.llm_egress_runtime import provider_uses_egress_firewall + + return provider_uses_egress_firewall(provider) + + class CLIAgentSetupMixin: """Agent construction + session-resume display methods for ``HermesCLI``.""" @@ -488,6 +499,9 @@ def _init_agent(self, *, model_override: str = None, runtime_override: dict = No "credential_pool": getattr(self, "_credential_pool", None), } effective_model = model_override or self.model + remote_kanban_private_work = _remote_kanban_private_work( + runtime.get("provider") + ) self.agent = AIAgent( model=effective_model, api_key=runtime.get("api_key"), @@ -531,8 +545,9 @@ def _init_agent(self, *, model_override: str = None, runtime_override: dict = No checkpoint_max_total_size_mb=self.checkpoint_max_total_size_mb, checkpoint_max_file_size_mb=self.checkpoint_max_file_size_mb, pass_session_id=self.pass_session_id, - skip_context_files=self.ignore_rules, - skip_memory=self.ignore_rules, + skip_context_files=self.ignore_rules or remote_kanban_private_work, + skip_memory=self.ignore_rules or remote_kanban_private_work, + skip_background_review=remote_kanban_private_work, tool_progress_callback=self._on_tool_progress, tool_start_callback=self._on_tool_start if self._inline_diffs_enabled else None, tool_complete_callback=self._on_tool_complete if self._inline_diffs_enabled else None, @@ -542,6 +557,13 @@ def _init_agent(self, *, model_override: str = None, runtime_override: dict = No notice_clear_callback=self._on_notice_clear, reaction_callback=self._on_reaction, ) + if remote_kanban_private_work: + # Large generated prompt fields are split into independently + # scanned 32 KiB segments. The aggregate allowance is bounded + # below the fixed request cap; secrets, encoded payloads, and + # private paths remain denied at the final provider boundary. + self.agent._llm_egress_max_sanitized_bytes = 196_608 + self.agent._llm_egress_max_sanitized_segment_bytes = 32_768 # Store reference for atexit memory provider shutdown. # NOTE: this MUST write to the ``cli`` module's global, not a # local module global. ``_run_cleanup`` (in cli.py) reads diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py index d3c36844a4d81..b75b3d27a7282 100644 --- a/hermes_cli/config_defaults.py +++ b/hermes_cli/config_defaults.py @@ -43,6 +43,11 @@ "terminal_continue": True, }, "agent": { + # Canonical per-profile reasoning depth. Runtime construction, gateway + # /reasoning persistence, and Kanban overrides all read this path. + # Keeping it in DEFAULT_CONFIG also makes `hermes config set` validate + # the key instead of incorrectly warning that the setting may be inert. + "reasoning_effort": "none", # Unlimited by default. The agent turn cap caused more problems than # it solved (silent mid-task truncation). null = unlimited; set a # positive integer to cap, or use "none"/"unlimited"/"inf"/0/-1 — @@ -2713,6 +2718,11 @@ # the assigned profile with the bundled sdlc-review skill. Disable for # boards where every review is performed manually from the dashboard. "review_dispatch": True, + # Installed independent profile used when the stop guard has useful + # evidence but a worker exhausts its terminal-transition nudges. Empty + # keeps the handoff disabled rather than creating reviewerless review + # cards that route back to the implementer and wait for a human verdict. + "reviewer_profile": "", # Seconds between dispatcher ticks (idle or not). Lower = snappier # pickup of newly-ready tasks; higher = less SQL pressure. "dispatch_interval_seconds": 60, diff --git a/tests/agent/test_kanban_stop.py b/tests/agent/test_kanban_stop.py index dbe371dd84194..17e89a0168aa3 100644 --- a/tests/agent/test_kanban_stop.py +++ b/tests/agent/test_kanban_stop.py @@ -7,7 +7,9 @@ from agent.kanban_stop import ( build_kanban_stop_nudge, kanban_stop_nudge_enabled, + reconcile_kanban_stop_to_review, session_called_kanban_terminal, + successful_kanban_terminal_transition, ) @@ -74,6 +76,185 @@ def test_no_nudge_after_kanban_complete(clear_kanban_env): assert build_kanban_stop_nudge(messages=messages) is None +def test_no_nudge_after_kanban_request_review(clear_kanban_env): + clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_review") + messages = [ + { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "id": "1", + "type": "function", + "function": {"name": "kanban_request_review", "arguments": "{}"}, + } + ], + }, + { + "role": "tool", + "name": "kanban_request_review", + "tool_call_id": "1", + "content": "moved to review", + }, + ] + assert session_called_kanban_terminal(messages) is True + assert build_kanban_stop_nudge(messages=messages) is None + + +def test_no_nudge_after_kanban_request_changes(clear_kanban_env): + clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_review") + messages = [ + { + "role": "tool", + "name": "kanban_request_changes", + "tool_call_id": "1", + "content": "returned to implementer", + } + ] + assert session_called_kanban_terminal(messages) is True + assert build_kanban_stop_nudge(messages=messages) is None + + +def test_successful_terminal_transition_matches_current_durable_result( + clear_kanban_env, +): + clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_abc") + tool_calls = [ + { + "id": "complete-current", + "function": {"name": "kanban_complete", "arguments": "{}"}, + } + ] + messages = [ + { + "role": "tool", + "name": "kanban_complete", + "tool_call_id": "complete-old", + "content": '{"ok": true}', + }, + { + "role": "tool", + "name": "kanban_complete", + "tool_call_id": "complete-current", + "content": '{"ok": true, "run_id": 715}', + }, + ] + + assert successful_kanban_terminal_transition( + messages=messages, tool_calls=tool_calls + ) is True + + +def test_failed_or_non_worker_terminal_call_does_not_stop_execution( + clear_kanban_env, +): + tool_calls = [ + { + "id": "complete-current", + "function": {"name": "kanban_complete", "arguments": "{}"}, + } + ] + messages = [ + { + "role": "tool", + "name": "kanban_complete", + "tool_call_id": "complete-current", + "content": '{"error": "completion rejected"}', + } + ] + + assert successful_kanban_terminal_transition( + messages=messages, tool_calls=tool_calls + ) is False + clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_abc") + assert successful_kanban_terminal_transition( + messages=messages, tool_calls=tool_calls + ) is False + + +def test_exhausted_nudges_handoff_useful_output_to_review( + clear_kanban_env, monkeypatch +): + clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_review_fallback") + monkeypatch.setattr( + "agent.kanban_stop._configured_review_profile", + lambda: "review-verification-steward", + ) + calls = [] + + def fake_request_review(args): + calls.append(args) + return '{"ok": true, "status": "review"}' + + monkeypatch.setattr( + "tools.kanban_tools._handle_request_review", fake_request_review + ) + + handed_off = reconcile_kanban_stop_to_review( + messages=[{"role": "user", "content": "work the task"}], + final_response="Implemented the bounded repair and ran 12 focused tests.", + attempts=2, + ) + + assert handed_off is True + assert calls == [ + { + "summary": ( + "Automatic terminal handoff after 2 unanswered Kanban stop " + "nudges. Worker final output:\n\nImplemented the bounded repair " + "and ran 12 focused tests." + ), + "reviewer": "review-verification-steward", + "metadata": { + "source": "kanban_stop_guard", + "terminal_nudges": 2, + "completion_inferred": False, + }, + } + ] + + +def test_review_handoff_is_bounded_and_never_infers_completion( + clear_kanban_env, monkeypatch +): + clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_review_fallback") + monkeypatch.setattr( + "agent.kanban_stop._configured_review_profile", + lambda: "review-verification-steward", + ) + calls = [] + monkeypatch.setattr( + "tools.kanban_tools._handle_request_review", + lambda args: calls.append(args) or '{"ok": true}', + ) + + assert reconcile_kanban_stop_to_review( + messages=[], final_response="useful evidence", attempts=1 + ) is False + assert reconcile_kanban_stop_to_review( + messages=[], final_response=" ", attempts=2 + ) is False + assert calls == [] + + +def test_review_handoff_failure_leaves_dispatcher_ownership( + clear_kanban_env, monkeypatch +): + clear_kanban_env.setenv("HERMES_KANBAN_TASK", "t_review_fallback") + monkeypatch.setattr( + "agent.kanban_stop._configured_review_profile", + lambda: "review-verification-steward", + ) + monkeypatch.setattr( + "tools.kanban_tools._handle_request_review", + lambda _args: '{"ok": false, "error": "goal evidence incomplete"}', + ) + + assert reconcile_kanban_stop_to_review( + messages=[], final_response="partial report", attempts=2 + ) is False + + @@ -84,7 +265,3 @@ def test_no_nudge_after_kanban_complete(clear_kanban_env): # without a terminal call, the dispatcher's bounded retry (streak of 3) # handles it. See also tests/hermes_cli/test_kanban_core_functionality.py # for the dispatcher-side streak tests. - - - - diff --git a/tests/agent/test_llm_egress_firewall.py b/tests/agent/test_llm_egress_firewall.py index fc0f0f7ca866c..5b02a1781af82 100644 --- a/tests/agent/test_llm_egress_firewall.py +++ b/tests/agent/test_llm_egress_firewall.py @@ -676,6 +676,88 @@ def test_json_protocol_acronym_is_not_a_base64_false_positive(tmp_path): assert firewall(tmp_path).preflight(request, _route()).allowed +@pytest.mark.parametrize( + "schema_atom", + [ + "HERMES_KANBAN_DB", + "kanban_heartbeat", + "machine-readable", + "parent/child", + "path/to/file", + "skills/plugins/cron/memories", + "MIME", + "REQUIRED", + "2000", + "2026", + "4dae", + "HERMES_KANBAN_BRANCH", + "HERMES_KANBAN_WORKSPACE", + "max_runtime_seconds", + "optional-profile", + ], +) +def test_builtin_tool_schema_atoms_are_not_base64_false_positives( + tmp_path, schema_atom +): + request = TypedOutboundRequest( + payload={"messages": [SanitizedSegment(schema_atom)]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + assert firewall(tmp_path).preflight(request, _route()).allowed + + +def test_fixed_hermes_task_id_is_not_a_base64_false_positive(tmp_path): + request = TypedOutboundRequest( + payload={"messages": [SanitizedSegment("work kanban task t_8c0aa909")]}, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + assert firewall(tmp_path).preflight(request, _route()).allowed + + +def test_fixed_prompt_cache_key_is_not_a_base64_false_positive(tmp_path): + request = TypedOutboundRequest( + payload={ + "parallel_tool_calls": True, + "prompt_cache_key": SanitizedSegment("pck_e3aec8aaa5993646a80a5660"), + }, + session_id="session-1", + turn_id="turn-1", + request_id="req-1", + policy_digest="policy-1", + ) + assert firewall( + tmp_path, + static_literals={"parallel_tool_calls", "prompt_cache_key", "true"}, + ).preflight(request, _route()).allowed + + +def test_content_free_violation_locations_never_return_keys_or_values(): + from agent.llm_egress_firewall import content_free_violation_locations + + private_path = "/Users/private/repository/file.py" + encoded = base64.b64encode(b"encoded private detail").decode("ascii") + result = content_free_violation_locations( + {"private-key-name": [{"content-key": private_path}], "metadata-key": encoded} + ) + rendered = repr(result) + assert result == ( + ("$.map[0].key", ("base64_payload",)), + ("$.map[0].value.sequence[0].map[0].value", ("private_absolute_path",)), + ("$.map[1].value", ("base64_payload",)), + ) + assert "private-key-name" not in rendered + assert "content-key" not in rendered + assert "metadata-key" not in rendered + assert private_path not in rendered + assert encoded not in rendered + + def test_scanner_error_fails_closed(monkeypatch, tmp_path): def explode(*args, **kwargs): raise RuntimeError("scanner unavailable") diff --git a/tests/agent/test_llm_egress_runtime.py b/tests/agent/test_llm_egress_runtime.py index 099b9bd39a4e6..a5720cf36f2c0 100644 --- a/tests/agent/test_llm_egress_runtime.py +++ b/tests/agent/test_llm_egress_runtime.py @@ -181,6 +181,22 @@ def test_runtime_denies_unsafe_text_before_provider_callback(tmp_path, text): assert calls == [] +def test_runtime_splits_large_sanitized_text_into_independently_scanned_segments( + tmp_path, +): + agent = _agent(tmp_path) + agent._llm_egress_max_sanitized_bytes = 128_000 + text = "ordinary bounded repair context. " * 2_000 + + authorized, receipt = authorize_agent_sdk_kwargs( + agent, + {"model": "test-model", "messages": [{"role": "system", "content": text}]}, + ) + + assert authorized["messages"][0]["content"] == text + assert receipt.decision.allowed is True + + def test_runtime_dispatches_exactly_once_with_authorized_bytes(tmp_path): agent = _agent(tmp_path) calls = [] diff --git a/tests/agent/test_system_prompt.py b/tests/agent/test_system_prompt.py index 43e7297bc33d8..fdf9e9049b25d 100644 --- a/tests/agent/test_system_prompt.py +++ b/tests/agent/test_system_prompt.py @@ -84,6 +84,87 @@ def _prompt_parts(agent): return build_system_prompt_parts(agent) +def test_guarded_prompt_replaces_verbose_coaching_and_compacts_skills(): + """The local profile is smaller, but never drops the execution contract.""" + from agent.prompt_builder import ( + OPENAI_MODEL_EXECUTION_GUIDANCE, + PARALLEL_TOOL_CALL_GUIDANCE, + TASK_COMPLETION_GUIDANCE, + TOOL_USE_ENFORCEMENT_GUIDANCE, + ) + from agent.system_prompt import GUARDED_EXECUTION_CONTRACT + + agent = _make_agent( + valid_tool_names=["read_file", "skills_list", "skill_view"], + _task_completion_guidance=True, + _parallel_tool_call_guidance=True, + _tool_use_enforcement=True, + _execution_guidance=True, + platform="desktop", + provider="ollama-launch", + model="hermes-qwen3-fast", + ) + with ( + patch("agent.coding_context.guarded_prompt_enabled", return_value=True), + patch("run_agent.build_skills_system_prompt", return_value="SKILLS") as skills, + ): + stable = _stable_prompt(agent) + + assert GUARDED_EXECUTION_CONTRACT in stable + assert "worktree" in GUARDED_EXECUTION_CONTRACT.lower() + assert "verify" in GUARDED_EXECUTION_CONTRACT.lower() + assert TASK_COMPLETION_GUIDANCE in stable + assert TOOL_USE_ENFORCEMENT_GUIDANCE in stable + assert PARALLEL_TOOL_CALL_GUIDANCE not in stable + assert OPENAI_MODEL_EXECUTION_GUIDANCE not in stable + assert skills.call_args.kwargs["compact_all_categories"] is True + + +def test_guarded_prompt_keeps_kanban_worker_lifecycle_guidance(): + agent = _make_agent( + valid_tool_names=["kanban_show", "read_file"], + _kanban_worker_guidance="KANBAN_WORKER_LIFECYCLE", + platform="desktop", + provider="ollama-launch", + model="hermes-qwen3-fast", + ) + with patch("agent.coding_context.guarded_prompt_enabled", return_value=True): + stable = _stable_prompt(agent) + + assert "KANBAN_WORKER_LIFECYCLE" in stable + + +def test_remote_kanban_worker_forces_compact_path_neutral_prompt(monkeypatch): + monkeypatch.setenv("HERMES_KANBAN_TASK", "t_remote") + agent = _make_agent( + valid_tool_names=["kanban_show", "read_file", "skill_view"], + _kanban_worker_guidance="KANBAN_WORKER_LIFECYCLE", + platform="cli", + provider="openai-codex", + model="gpt-5.4", + ) + with ( + patch("agent.coding_context.guarded_prompt_enabled", return_value=False), + patch("run_agent.build_skills_system_prompt", return_value="SKILLS") as skills, + patch("agent.system_prompt._frozen_plugin_prompt_sections") as plugins, + ): + parts = _prompt_parts(agent) + + assert "KANBAN_WORKER_LIFECYCLE" in parts["stable"] + assert "/Users/" not in "\n".join(parts.values()) + assert skills.call_args.kwargs["compact_all_categories"] is True + plugins.assert_not_called() + + +def test_computer_use_tool_does_not_require_removed_legacy_prompt_builder_api(): + """Computer-use guidance now comes from response verdicts, not prompt_builder.""" + agent = _make_agent(valid_tool_names=["computer_use"], platform="desktop") + + stable = _stable_prompt(agent) + + assert isinstance(stable, str) + + def _init_code_repo(path): """A git repo that actually holds code — the coding posture requires a source file (or manifest), not a bare ``.git`` (a prose/notes repo stays general).""" diff --git a/tests/hermes_cli/test_remote_kanban_private_work.py b/tests/hermes_cli/test_remote_kanban_private_work.py new file mode 100644 index 0000000000000..68343937ff64e --- /dev/null +++ b/tests/hermes_cli/test_remote_kanban_private_work.py @@ -0,0 +1,11 @@ +from hermes_cli.cli_agent_setup_mixin import _remote_kanban_private_work + + +def test_remote_kanban_private_work_requires_task_and_protected_provider(monkeypatch): + monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False) + assert _remote_kanban_private_work("openai-codex") is False + + monkeypatch.setenv("HERMES_KANBAN_TASK", "t_123") + assert _remote_kanban_private_work("openai-codex") is True + assert _remote_kanban_private_work("nous") is True + assert _remote_kanban_private_work("ollama-launch") is False diff --git a/tests/hermes_cli/test_set_config_value.py b/tests/hermes_cli/test_set_config_value.py index 264aa29708db6..dc168d4c4b3ee 100644 --- a/tests/hermes_cli/test_set_config_value.py +++ b/tests/hermes_cli/test_set_config_value.py @@ -118,6 +118,13 @@ def test_memory_nudge_interval_is_recognized(self, _isolated_hermes_home, capsys assert "not a recognized config key" not in capsys.readouterr().out assert "nudge_interval: 0" in _read_config(_isolated_hermes_home) + def test_agent_reasoning_effort_is_recognized(self, _isolated_hermes_home, capsys): + """The canonical per-profile reasoning knob must not be flagged as inert.""" + set_config_value("agent.reasoning_effort", "low") + + assert "not a recognized config key" not in capsys.readouterr().out + assert "reasoning_effort: low" in _read_config(_isolated_hermes_home) + def test_terminal_docker_cwd_mount_flag_goes_to_config_and_env(self, _isolated_hermes_home): set_config_value("terminal.docker_mount_cwd_to_workspace", "true") config = _read_config(_isolated_hermes_home) diff --git a/tests/tools/test_kanban_tools.py b/tests/tools/test_kanban_tools.py index b9d2a52e35389..9835695e593e5 100644 --- a/tests/tools/test_kanban_tools.py +++ b/tests/tools/test_kanban_tools.py @@ -579,6 +579,14 @@ def test_kanban_guidance_orchestrator_decision_ownership(): assert "workers cannot see sibling context" in KANBAN_GUIDANCE +def test_kanban_guidance_rejects_self_referential_reclaim_and_crash_blockers(): + from agent.prompt_builder import KANBAN_GUIDANCE + + assert "attempt-management evidence, not task blockers" in KANBAN_GUIDANCE + assert "Never block because an earlier worker crashed" in KANBAN_GUIDANCE + assert "Do not pass the literal environment-variable token" in KANBAN_GUIDANCE + + # --------------------------------------------------------------------------- # Worker task-ownership enforcement (regression tests for #19534) # --------------------------------------------------------------------------- diff --git a/tools/file_tools.py b/tools/file_tools.py index ed2b0e4288ace..e464b9d381eca 100644 --- a/tools/file_tools.py +++ b/tools/file_tools.py @@ -2752,7 +2752,7 @@ def _check_file_reqs(): "parameters": { "type": "object", "properties": { - "path": {"type": "string", "description": "Path to the file to read (absolute, relative, or ~/path)"}, + "path": {"type": "string", "description": "Path to the file to read (absolute or relative)"}, "offset": {"type": "integer", "description": "Line number to start reading from (1-indexed, default: 1)", "default": 1, "minimum": 1}, "limit": {"type": "integer", "description": "Maximum number of lines to read (default: 2000, max: 2000). Reads are additionally capped at a ~100K-character budget with a next_offset continuation.", "default": 2000, "maximum": 2000} }, diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index fe1b17039de3e..ba67e02cac32e 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -4110,7 +4110,7 @@ def check_terminal_requirements() -> bool: }, "timeout": { "type": "integer", - "description": f"Max seconds to wait (default: 180, foreground max: {FOREGROUND_MAX_TIMEOUT}). Returns INSTANTLY when command finishes — set high for long tasks, you won't wait unnecessarily. Foreground timeout above {FOREGROUND_MAX_TIMEOUT}s is rejected; use background=true for longer commands.", + "description": f"Max seconds to wait (default: 180, foreground max: {FOREGROUND_MAX_TIMEOUT}). Returns INSTANTLY when command finishes — set high for long tasks, you won't wait unnecessarily. A value above the configured foreground maximum is rejected; use background=true for longer commands.", "minimum": 1 }, "workdir": { From 3a56c7c03218f76f91452a9d30be673f922be2e0 Mon Sep 17 00:00:00 2001 From: Mike DeMott Date: Wed, 26 Aug 2026 14:10:52 -0700 Subject: [PATCH 15/26] fix(kanban): preserve protected remote worker capability --- agent/llm_egress_firewall.py | 152 +++++++++++++- agent/llm_egress_runtime.py | 189 ++++++++++++++++++ hermes_cli/cli_agent_setup_mixin.py | 23 ++- hermes_cli/kanban_db.py | 6 + tests/agent/test_llm_egress_firewall.py | 75 +++++++ tests/agent/test_llm_egress_runtime.py | 166 +++++++++++++++ tests/hermes_cli/test_kanban_db.py | 1 + .../test_remote_kanban_private_work.py | 13 +- tests/tools/test_kanban_tools.py | 136 +++++++++++++ .../test_terminal_foreground_timeout_cap.py | 8 +- tools/kanban_tools.py | 140 ++++++++++++- tools/terminal_tool.py | 2 +- 12 files changed, 895 insertions(+), 16 deletions(-) diff --git a/agent/llm_egress_firewall.py b/agent/llm_egress_firewall.py index fcb0ef1b02d5d..c5da06e08c4c9 100644 --- a/agent/llm_egress_firewall.py +++ b/agent/llm_egress_firewall.py @@ -68,6 +68,14 @@ class SanitizedSegment: text: str +@dataclass(frozen=True, slots=True) +class ValidatedToolSyntaxSegment: + """Strictly parsed syntax emitted by a protected local tool result.""" + + text: str + syntax_kind: str + + @dataclass(frozen=True, slots=True) class SourceBoundSegment: """Opaque reference whose text is loaded only from a verified grant.""" @@ -79,7 +87,10 @@ class SourceBoundSegment: class OutboundText: """Ordered typed segments that construct one outbound JSON string.""" - segments: tuple[LiteralSegment | SanitizedSegment | SourceBoundSegment, ...] + segments: tuple[ + LiteralSegment | SanitizedSegment | ValidatedToolSyntaxSegment | SourceBoundSegment, + ..., + ] @dataclass(frozen=True, slots=True) @@ -177,6 +188,28 @@ def verify_payload(self, candidate: bytes) -> bytes: _HERMES_TASK_ID = re.compile(r"^t_[0-9a-f]{8}$") _PROMPT_CACHE_KEY = re.compile(r"^pck_[0-9a-f]{24}$") _MAX_BASE64_CANDIDATE_CHARS = 262_144 +_VALIDATED_TOOL_SYNTAX = { + "github_url": re.compile( + r"https://github\.com/[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}" + r"(?:\.git|/(?:pull|issues)/[0-9]{1,10})?" + ), + "cli_option": re.compile(r"--[a-z0-9][a-z0-9-]{0,63}"), + "source_identifier": re.compile( + r"(?:[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}#[0-9]{1,10}" + r"|[0-9a-f]{40}|[0-9a-f]{64})" + ), + "git_ref": re.compile( + r"(?:refs/(?:heads|tags)/)?[A-Za-z0-9][A-Za-z0-9._-]{0,63}" + r"(?:/[A-Za-z0-9][A-Za-z0-9._-]{0,63}){1,8}" + ), + "run_counter": re.compile( + r"(?:run|run_id|attempt|attempt_id)(?:\s+|=)[0-9]{1,10}" + ), + "safe_env_counter": re.compile( + r"HERMES_(?:KANBAN_RUN_ID|TURN_LEASE_TIMEOUT|STREAM_STALE_GIVEUP)=" + r"[0-9]{1,10}" + ), +} _PRIVATE_ABSOLUTE_PATH = re.compile( r"(?:^|[\s\"'`(])(?:" r"/(?:Users|home|private|var/folders|root|Volumes)/[^\s\"'`)]+" @@ -191,6 +224,8 @@ def verify_payload(self, candidate: bytes) -> bytes: # scan; this set only resolves the mathematical ambiguity in Base64 detection. _PROTOCOL_GRAMMAR_ATOMS = frozenset( { + "--noEmit", + "--repository", "--result", "-removed", "100K", @@ -203,7 +238,15 @@ def verify_payload(self, candidate: bytes) -> bytes: "EPUB", "HERMES_KANBAN_DB", "HERMES_KANBAN_BRANCH", + "HERMES_KANBAN_CLAIM_LOCK", + "HERMES_KANBAN_RUN_ID", "HERMES_KANBAN_WORKSPACE", + "HERMES_CONTROL_HOME", + "HERMES_HOME=", + "HERMES_SESSION_ID", + "HERMES_STREAM_STALE_GIVEUP", + "HERMES_TURN_LEASE_TIMEOUT", + "HEAD", "LAST", "MIME", "MODE", @@ -216,6 +259,7 @@ def verify_payload(self, candidate: bytes) -> bytes: "REQUIRED", "SILENTLY", "assistant", + "already-resolved", "assignee/profile", "computer_call_output", "com/docs", @@ -228,6 +272,7 @@ def verify_payload(self, candidate: bytes) -> bytes: "find-and-replace", "function_call", "function_call_output", + "_force_close_actionable_pending_routes_for_cycle", "github-code-review", "grep/rg/find/ls", "include_archived", @@ -238,8 +283,10 @@ def verify_payload(self, candidate: bytes) -> bytes: "machine-readable", "max_runtime_seconds", "messages", + "n_error_", "notification/15s", "optional-profile", + "OPEN/MERGEABLE/CLEAN", "output_text", "parent/child", "parents=", @@ -247,11 +294,14 @@ def verify_payload(self, candidate: bytes) -> bytes: "path/to/file", "ppt/", "prompt_cache_key", + "protected-remote", + "repository-owned", "reasoning", "role", "sed/awk", "servers/daemons", "servers/watchers/daemons", + "session_resolver", "skills/plugins/cron/memories", "system", "tool", @@ -360,6 +410,17 @@ def static_literal_sha256(text: str) -> str: return sha256(text.encode("utf-8")).hexdigest() +def validate_tool_syntax(text: str, syntax_kind: str) -> str: + """Revalidate one complete protected tool-result syntax atom.""" + + grammar = _VALIDATED_TOOL_SYNTAX.get(syntax_kind) + if not isinstance(text, str) or grammar is None or grammar.fullmatch(text) is None: + raise ValueError("invalid_tool_syntax_segment") + if _contains_secret(text) or _contains_private_absolute_path(text): + raise ValueError("invalid_tool_syntax_segment") + return text + + def _canonical_base64_candidate(candidate: str) -> bool: """Recognize bounded canonical encodings without flagging ordinary IDs.""" @@ -415,13 +476,36 @@ def _contains_canonical_base64(value: Any, *, seen: set[int] | None = None) -> b for match in _BASE64_CANDIDATE.finditer(value): candidate = match.group(1) prefix = value[max(0, match.start() - 16) : match.start()].lower() - if re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", candidate.lower()): + if re.fullmatch( + r"[0-9a-f]{7,12}|[0-9a-f]{40}|[0-9a-f]{64}", + candidate.lower(), + ): continue + if candidate.isdigit(): + before = value[: match.start(1)].rstrip()[-1:] + after = value[match.end(1) :].lstrip()[:1] + if before in {":", ",", "["} and after in {",", "]", "}"}: + # JSON numeric values in tool results are serialized + # protocol fields, not encoded text. A quoted numeric + # string remains eligible for Base64 detection. + continue # The fixed Kanban task-id grammar carries only a 32-bit hex # database key. It is application protocol metadata, not an # encoded source payload. if _HERMES_TASK_ID.fullmatch(candidate): continue + # Provider-generated tool-call and response-item identifiers are + # opaque protocol routing metadata, not caller-supplied encoded + # content. Match their complete, fixed grammar only. + if re.fullmatch(r"(?:call|fc)_[A-Za-z0-9_-]{8,128}", candidate): + continue + if candidate in { + "HERMES_CONTROL_HOME", + "HERMES_KANBAN_DB", + "HERMES_KANBAN_WORKSPACES_ROOT", + "HERMES_PROFILE_HOME", + }: + continue # Content-addressed cache routing is a fixed application protocol # value: the literal ``pck_`` prefix plus exactly 96 bits of hex. if _PROMPT_CACHE_KEY.fullmatch(candidate): @@ -642,6 +726,12 @@ def _is_strict_sanitized_only_payload( if isinstance(value, SanitizedSegment): return isinstance(value.text, str), 1 if isinstance(value.text, str) else 0 + if isinstance(value, ValidatedToolSyntaxSegment): + try: + validate_tool_syntax(value.text, value.syntax_kind) + except (TypeError, ValueError): + return False, 0 + return True, 1 if isinstance(value, LiteralSegment): return isinstance(value.text, str), 0 if isinstance(value, SourceBoundSegment): @@ -839,7 +929,13 @@ def authorize( reasons.extend(grant_reasons) if typed_request is not None: - logical_request, construction_reasons, source_segment_count, scan_values = ( + ( + logical_request, + construction_reasons, + source_segment_count, + scan_values, + base64_scan_values, + ) = ( self._construct_typed_request( typed_request, grant_contents, @@ -850,6 +946,7 @@ def authorize( else: logical_request = request scan_values = request + base64_scan_values = request try: serialized = json.dumps( @@ -913,7 +1010,7 @@ def authorize( except Exception: reasons.append("redaction_failed") try: - if _contains_canonical_base64(scan_values): + if _contains_canonical_base64(base64_scan_values): reasons.append("base64_payload") except Exception: reasons.append("base64_scan_failed") @@ -1035,7 +1132,7 @@ def _construct_typed_request( grant_contents: Mapping[str, tuple[SourceGrant, bytes]], *, allow_sanitized_segments: bool = False, - ) -> tuple[Mapping[str, Any], list[str], int, list[str]]: + ) -> tuple[Mapping[str, Any], list[str], int, list[str], list[str]]: """Build a plain JSON request exclusively from typed segment nodes.""" reasons: list[str] = [] @@ -1043,6 +1140,7 @@ def _construct_typed_request( source_segment_count = 0 sanitized_bytes = 0 scan_values: list[str] = [] + base64_scan_values: list[str] = [] allowed_static_hashes = self._static_literal_hashes_by_policy.get( request.policy_digest, frozenset(), @@ -1054,11 +1152,17 @@ def require_static_literal(text: str) -> None: # authorization, including exact policy-bound static literals and # structural keys/scalars. scan_values.append(text) + base64_scan_values.append(text) if static_literal_sha256(text) not in allowed_static_hashes: reasons.append("static_literal_not_allowed") def render_text_segment( - segment: LiteralSegment | SanitizedSegment | SourceBoundSegment, + segment: ( + LiteralSegment + | SanitizedSegment + | ValidatedToolSyntaxSegment + | SourceBoundSegment + ), ) -> str: nonlocal sanitized_bytes, source_segment_count if isinstance(segment, LiteralSegment): @@ -1086,9 +1190,24 @@ def render_text_segment( ): reasons.append("source_bytes_in_sanitized_segment") scan_values.append(segment.text) + base64_scan_values.append(segment.text) return segment.text reasons.append("invalid_literal_segment") return "" + if isinstance(segment, ValidatedToolSyntaxSegment): + try: + text = validate_tool_syntax(segment.text, segment.syntax_kind) + except (TypeError, ValueError): + reasons.append("invalid_tool_syntax_segment") + return "" + encoded = text.encode("utf-8") + if len(encoded) > self._max_sanitized_segment_bytes: + reasons.append("sanitized_segment_bytes_exceeded") + sanitized_bytes += len(encoded) + if sanitized_bytes > self._max_sanitized_bytes: + reasons.append("sanitized_bytes_exceeded") + scan_values.append(text) + return text if isinstance(segment, SourceBoundSegment): grant_and_content = grant_contents.get(segment.source_grant_digest) if grant_and_content is None: @@ -1102,12 +1221,21 @@ def render_text_segment( referenced_grants.add(segment.source_grant_digest) source_segment_count += 1 scan_values.append(text) + base64_scan_values.append(text) return text reasons.append("invalid_source_segment") return "" def render(value: Any) -> Any: - if isinstance(value, (LiteralSegment, SanitizedSegment, SourceBoundSegment)): + if isinstance( + value, + ( + LiteralSegment, + SanitizedSegment, + ValidatedToolSyntaxSegment, + SourceBoundSegment, + ), + ): return render_text_segment(value) if isinstance(value, OutboundText): return "".join(render_text_segment(segment) for segment in value.segments) @@ -1153,7 +1281,13 @@ def render(value: Any) -> Any: reasons.append("request_identity_mismatch") if set(grant_contents) - referenced_grants: reasons.append("source_grant_unbound") - return rendered_payload, reasons, source_segment_count, scan_values + return ( + rendered_payload, + reasons, + source_segment_count, + scan_values, + base64_scan_values, + ) def _block( self, @@ -1252,7 +1386,9 @@ def _append_receipt( "SourceBoundSegment", "SourceGrant", "TypedOutboundRequest", + "ValidatedToolSyntaxSegment", "classify_destination", "source_grant_digest", "static_literal_sha256", + "validate_tool_syntax", ] diff --git a/agent/llm_egress_runtime.py b/agent/llm_egress_runtime.py index 469904b718da9..32f26870fcc6a 100644 --- a/agent/llm_egress_runtime.py +++ b/agent/llm_egress_runtime.py @@ -5,6 +5,8 @@ import json import logging import math +import os +import re from pathlib import Path from types import MappingProxyType from types import SimpleNamespace @@ -20,12 +22,14 @@ SourceBoundSegment, SourceGrant, TypedOutboundRequest, + ValidatedToolSyntaxSegment, DestinationClass, classify_destination, source_grant_digest, static_literal_sha256, validate_sanitized_text, content_free_violation_locations, + validate_tool_syntax, ) from agent.source_provenance import DEFAULT_POLICY_DIGEST, SourceProvenanceRegistry @@ -58,6 +62,76 @@ }) logger = logging.getLogger(__name__) +_TOOL_SYNTAX_TOKEN = re.compile( + r"(?Phttps://github\.com/[A-Za-z0-9_.-]{1,100}/" + r"[A-Za-z0-9_.-]{1,100}(?:\.git|/(?:pull|issues)/[0-9]{1,10})?)" + r"|(?PHERMES_(?:KANBAN_RUN_ID|TURN_LEASE_TIMEOUT|" + r"STREAM_STALE_GIVEUP)=[0-9]{1,10})" + r"|(?P\b(?:run|run_id|attempt|attempt_id)(?:\s+|=)[0-9]{1,10}\b)" + r"|(?P--[a-z0-9][a-z0-9-]{0,63})" + r"|(?P(?:refs/(?:heads|tags)/)?[A-Za-z0-9][A-Za-z0-9._-]{0,63}" + r"(?:/[A-Za-z0-9][A-Za-z0-9._-]{0,63}){1,8})" + r"|(?P\b(?:[A-Za-z0-9_.-]{1,100}/" + r"[A-Za-z0-9_.-]{1,100}#[0-9]{1,10}|[0-9a-f]{40}|[0-9a-f]{64})\b)" +) +_VALIDATED_SYNTAX_TOOL_NAMES = frozenset({"terminal"}) + +_PRIVATE_PATH_IN_TEXT = re.compile( + r"(? Any: + """Remove host paths from protected Kanban tool results before typing. + + This deliberately does not rewrite secrets or arbitrary encoded content; + those remain visible to the fail-closed firewall scans and are denied. + """ + + if isinstance(value, str): + text = value + for name in ( + "HERMES_KANBAN_CLAIM_LOCK", + "HERMES_KANBAN_RUN_ID", + "HERMES_SESSION_ID", + "HERMES_STREAM_STALE_GIVEUP", + "HERMES_TURN_LEASE_TIMEOUT", + ): + raw = os.environ.get(name) + if raw: + text = re.sub( + rf"(?m)^(?P