The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): bound Azure detect response reads
luyifan43127a86ea5d
diff --git a/hermes_cli/azure_detect.py b/hermes_cli/azure_detect.pyindex 179a38f92b6..83288e54b29 100644--- a/hermes_cli/azure_detect.py+++ b/hermes_cli/azure_detect.py@@ -31,6 +31,8 @@ _AZURE_OPENAI_PROBE_API_VERSIONS = (# Matches the value ``agent/anthropic_adapter.py`` uses when building the Anthropic client._AZURE_ANTHROPIC_API_VERSION = "2025-04-15"+_AZURE_DETECT_JSON_BODY_MAX_BYTES = 1024 * 1024+_AZURE_DETECT_ERROR_BODY_MAX_BYTES = 64 * 1024@dataclass@@ -86,14 +88,23 @@ def _authed_request(url: str, api_key: Any, token_provider, *, method: str = "GEreturn req+def _read_limited_response_body(resp: Any, limit: int, *, label: str) -> bytes:+ body = resp.read(limit + 1)+ if len(body) > limit:+ raise ValueError(f"{label} exceeded {limit} bytes")+ return body++def _http_get_json(url: str, api_key: Any, timeout: float = 6.0, *,token_provider: TokenProvider = None) -> tuple[int, Optional[dict]]:"""GET with auth headers; return ``(status_code, parsed_json_or_None)``. Never raises."""req = _authed_request(url, api_key, token_provider)try:with open_credentialed_url(req, timeout=timeout) as resp:- body = resp.read()try:+ body = _read_limited_response_body(+ resp, _AZURE_DETECT_JSON_BODY_MAX_BYTES, label="Azure detection JSON response body",+ )return resp.status, json.loads(body.decode("utf-8", errors="replace"))except Exception:return resp.status, None@@ -171,7 +182,11 @@ def _probe_anthropic_messages(base_url: str, api_key: Any, *, token_provider: Toreturn resp.status < 500except HTTPError as exc:try:- lowered = exc.read().decode("utf-8", errors="replace").lower()+ with exc:+ body = _read_limited_response_body(+ exc, _AZURE_DETECT_ERROR_BODY_MAX_BYTES, label="Azure Anthropic probe error response body",+ )+ lowered = body.decode("utf-8", errors="replace").lower()if "anthropic" in lowered or '"type"' in lowered and '"error"' in lowered:return True# Pre-Azure-v1 Foundry returns a plain 404 for Anthropic-style calls on non-Anthropicdiff --git a/tests/hermes_cli/test_azure_detect.py b/tests/hermes_cli/test_azure_detect.pyindex 449719ec9b5..c2ef00e5bd6 100644--- a/tests/hermes_cli/test_azure_detect.py+++ b/tests/hermes_cli/test_azure_detect.py@@ -2,7 +2,9 @@from __future__ import annotations+import http.serverimport json+import threadingfrom unittest.mock import MagicMock, patchimport pytest@@ -112,9 +114,62 @@ def test_probe_openai_models_tries_multiple_api_versions():+def probe_server():+ bodies = {}++ class Handler(http.server.BaseHTTPRequestHandler):+ def log_message(self, format, *args):+ pass++ def do_GET(self):+ self.respond(200, bodies["models"])++ def do_POST(self):+ self.rfile.read(int(self.headers["Content-Length"]))+ self.respond(400, bodies["error"])++ def respond(self, status, body):+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ try:+ self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError):+ pass # The bounded reader may close before the oversized body is sent.++ with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:+ worker = threading.Thread(target=server.serve_forever, daemon=True)+ worker.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}", bodies+ finally:+ server.shutdown()+ worker.join(timeout=5)+++def test_http_get_json_bounds_success_body(probe_server):+ """The real credential-safe HTTP path parses small models, not oversized JSON."""+ url, bodies = probe_server+ bodies["models"] = _openai_models_body("test-deployment")+ assert azure_detect._http_get_json(url + "/models", "synthetic-key") == (+ 200, json.loads(bodies["models"]),+ )+ bodies["models"] += b" " * azure_detect._AZURE_DETECT_JSON_BODY_MAX_BYTES+ assert azure_detect._http_get_json(url + "/models", "synthetic-key") == (200, None)+++def test_probe_anthropic_messages_bounds_error_body(probe_server):+ """Oversized real HTTPError bodies cannot supply the detection signal."""+ url, bodies = probe_server+ bodies["error"] = _anthropic_error_body()+ assert azure_detect._probe_anthropic_messages(url, "synthetic-key") is True+ bodies["error"] += b" " * azure_detect._AZURE_DETECT_ERROR_BODY_MAX_BYTES+ assert azure_detect._probe_anthropic_messages(url, "synthetic-key") is False++# ----------------------------------------------------------------------# lookup_context_length# ------------------------------------------------------------------------