diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-10-20 23:14:37 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-20 23:15:10 +0000 |
| commit | 073448767f5ef6ea935cded3d6f712e843f5d268 (patch) | |
| tree | 800cced9e46f4a4b3763c1ab5013d926a716231b /plugins | |
| parent | 6e50442cd64387efad73bab72a47f277b88d8662 (diff) | |
security-guidance: report why a review call got no HTTP response
A review call that never gets an HTTP response is reported as api_error -1
whatever the cause, so a certificate failure, a refused connection and a
timeout look the same. Rows whose last call failed that way now carry a
count-only net_err key: the failure class, the TLS verify code, and whether
CA files, a proxy or TLS variables are in play. No behaviour change.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 28 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 121 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 8 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/conftest.py | 9 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_network_failure_class.py | 329 |
5 files changed, 492 insertions, 3 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 59e8e569..ed5bbff2 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -212,6 +212,7 @@ _USAGE = { # reported it manually. "http_err_last": 0, # most recent HTTP error code this invocation "http_err_count": 0, # total HTTP errors (4xx + 5xx + network) + "net_err": 0, # why the last call got no HTTP response, 0 if it got one # For the usage log line only: model ids as recorded (the requested alias # on the Agent SDK path), and whether any call had no price-table entry. "models": [], @@ -300,6 +301,33 @@ def _record_http_error(status): _USAGE["http_err_count"] += 1 +def _record_net_error(code): + """Record why an LLM API call got no HTTP response: the packed code from + llm._net_error_code. `api_error` -1 cannot tell a certificate failure + from a refused connection or a timeout, and a failure the HTTP client + raises outside its own error type (a default TLS context that cannot be + built, a connection closed before the reply) has no `api_error` at all. + Emitted as `net_err` on the row of a hook whose last call failed this + way; a later call clears it.""" + try: + c = int(code) + except (TypeError, ValueError): + return + if c > 0: + with _USAGE_LOCK: + _USAGE["net_err"] = c + + +def _clear_net_error(): + with _USAGE_LOCK: + _USAGE["net_err"] = 0 + + +def _net_error_metric(): + with _USAGE_LOCK: + return _USAGE.get("net_err", 0) + + # Set by main() and the review handlers: which review this invocation runs # and for which Claude Code session, so the usage log line can be attributed. _USAGE_CONTEXT = {"session_id": "", "review": "stop"} diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 76d04c54..94e398e2 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -34,7 +34,7 @@ from typing import Optional, Tuple, Dict, Any, List, Callable import extensibility import review_api -from _base import debug_log, _record_usage, _record_http_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401 +from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401 from session_state import load_state, with_locked_state from gitutil import git_config_env, SAFE_GIT_CONFIG @@ -203,10 +203,120 @@ def _probe_anthropic(timeout: float = 5.0) -> bool: return True except urllib.error.HTTPError: return True # got a status code → connected - except (urllib.error.URLError, TimeoutError, OSError): + except (urllib.error.URLError, TimeoutError, OSError) as e: + _record_net_error(_net_error_code(e)) return False +# ===================================================================== +# Why a call got no HTTP response +# ===================================================================== +# Classes for the `net_err` metric. Measure only: nothing reads these to +# decide what the plugin does. +NET_ERR_CERT_VERIFY = 1 # the server certificate did not verify +NET_ERR_TLS = 2 # any other TLS failure, including a default context that cannot be built +NET_ERR_DNS = 3 # the host name did not resolve +NET_ERR_CONNECT = 4 # refused, reset, closed early or unreachable +NET_ERR_TIMEOUT = 5 +NET_ERR_PROXY = 6 # the proxy refused the tunnel +NET_ERR_OTHER = 7 # another failure from the HTTP client +NET_ERR_INNER_CLI = 9 # the review ran through a CLI, which failed +NET_ERR_INNER_CLI_TIMEOUT = 10 +NET_ERR_NO_SDK = 11 # the review needed the agent SDK, which could not be imported + +_NET_FLAG_NO_CA_ON_DISK = 1 # Python's default CA file and directory are missing or empty +_NET_FLAG_PROXY = 2 # the request would go through a proxy +_NET_FLAG_NODE_EXTRA_CA = 4 # NODE_EXTRA_CA_CERTS is set (Python does not read it) +_NET_FLAG_SSL_CERT_ENV = 8 # SSL_CERT_FILE or SSL_CERT_DIR is set + + +def _net_error_class(exc) -> Tuple[int, int]: + """(class, X.509 verify code) for an exception from an API call; class 0 + for one that is not a network failure. The verify code is OpenSSL's + (20 = issuer not found locally, 19 = self-signed certificate in the + chain, 10 = expired), 0 when the class is not NET_ERR_CERT_VERIFY.""" + import errno + import http.client + import socket + try: + import ssl + cert_error, tls_error = ssl.SSLCertVerificationError, ssl.SSLError + except ImportError: + cert_error = tls_error = () + reason = getattr(exc, "reason", None) + err = reason if isinstance(reason, BaseException) else exc + if isinstance(err, cert_error): + code = getattr(err, "verify_code", 0) + return NET_ERR_CERT_VERIFY, code if isinstance(code, int) and 0 < code < 100 else 0 + if isinstance(err, tls_error): + return NET_ERR_TLS, 0 + if isinstance(err, socket.gaierror): + return NET_ERR_DNS, 0 + if isinstance(err, OSError): + text = str(err).lower() + if "tunnel connection failed" in text: + return NET_ERR_PROXY, 0 + if isinstance(err, TimeoutError) or "timed out" in text: + return NET_ERR_TIMEOUT, 0 + if isinstance(err, ConnectionError) or err.errno in ( + errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN, + errno.EHOSTDOWN, errno.EADDRNOTAVAIL): + return NET_ERR_CONNECT, 0 + return NET_ERR_OTHER, 0 + if isinstance(err, http.client.HTTPException) or isinstance(exc, urllib.error.URLError): + return NET_ERR_OTHER, 0 + return 0, 0 + + +def _net_error_flags(tls: bool) -> int: + """What the machine's setup says about a failed call. Each check is + best effort: one that cannot be made leaves its flag off.""" + flags = 0 + if tls: + try: + import ssl + paths = ssl.get_default_verify_paths() + has_file = bool(paths.cafile) and os.path.getsize(paths.cafile) > 0 + has_dir = False + if paths.capath: + with os.scandir(paths.capath) as it: + has_dir = any(True for _ in it) + # Windows also reads the system store, which this cannot see. + if not has_file and not has_dir and sys.platform != "win32": + flags |= _NET_FLAG_NO_CA_ON_DISK + except Exception: + pass + if os.environ.get("NODE_EXTRA_CA_CERTS"): + flags |= _NET_FLAG_NODE_EXTRA_CA + if os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR"): + flags |= _NET_FLAG_SSL_CERT_ENV + try: + url = urllib.parse.urlsplit(_anthropic_base_url()) + # As urllib chooses: the proxy for the URL's scheme, bypass by host:port. + if (urllib.request.getproxies().get(url.scheme) + and not urllib.request.proxy_bypass(url.netloc.rpartition("@")[2])): + flags |= _NET_FLAG_PROXY + except Exception: + pass + return flags + + +def _net_error_code(exc) -> int: + """`net_err` for an exception: class + 100 * verify code + 10000 * flags, + or 0 for an exception that is not a network failure.""" + try: + cls, verify = _net_error_class(exc) + except Exception: + return 0 + if not cls: + return 0 + try: + flags = _net_error_flags(cls in (NET_ERR_CERT_VERIFY, NET_ERR_TLS)) + except Exception: + flags = 0 + return cls + 100 * verify + 10000 * flags + + def _strip_anthropic_from_no_proxy() -> None: for var in ("NO_PROXY", "no_proxy"): val = os.environ.get(var) @@ -750,6 +860,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, """ global _last_call_claude_http_error, _gateway_review_timed_out _last_call_claude_http_error = None + _clear_net_error() route = "gateway" if cli_path else "3P" try: @@ -778,6 +889,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, debug_log(f"{route} sdk-single-turn: SDK unavailable ({e})") _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(NET_ERR_NO_SDK) return None _send_sdk_logs_to_debug_log() @@ -862,12 +974,14 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, _gateway_review_timed_out = True _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(NET_ERR_INNER_CLI_TIMEOUT) return None except Exception as e: debug_log(f"{route} sdk-single-turn: query failed ({e})") _log_child_stderr() _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(NET_ERR_INNER_CLI) return None @@ -890,6 +1004,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, """ global _last_call_claude_http_error _last_call_claude_http_error = None + _clear_net_error() if _is_3p_provider(): # On Bedrock/Vertex/Foundry/Mantle the api.anthropic.com path below @@ -1008,6 +1123,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, debug_log(f"Request failed after retries: {e}") _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(_net_error_code(e)) return None if not response_data: @@ -1506,6 +1622,7 @@ Respond with a JSON object. If vulnerabilities are found, set hasVulnerabilities cacheable_prefix=_CODE_REVIEW_RUBRIC) except Exception as e: debug_log(f"LLM code review: call raised {type(e).__name__}: {e}") + _record_net_error(_net_error_code(e)) analysis = None # A reply without the schema's required flag is not a verdict either. if not isinstance(analysis, dict) or "hasVulnerabilities" not in analysis: diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 99b00ce0..8ff92bef 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -84,7 +84,7 @@ from _base import ( # noqa: E402,F401 DEBUG_LOG_FILE, DEBUG_LOG_MAX_BYTES, debug_log, PROVENANCE_TAG, PROVENANCE_BANNER, _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, - _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, + _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, _net_error_metric, _USAGE_CONTEXT, _log_usage, state_dir as _resolve_state_dir, write_hook_output as _write_hook_output, @@ -294,6 +294,12 @@ def emit_metrics( head["launcher_fallback"] = 1 usage = _usage_metrics() head.update(usage) + # Why the last call got no HTTP response (api_error -1 says only that it + # did not). Ahead of the row's own keys: on a failed review this is the + # key that says what failed, so it is not the one to lose to the key cap. + net_err = _net_error_metric() + if net_err: + head["net_err"] = net_err if head: metrics = {**head, **metrics} # Diagnostic keys go last, so they are the first dropped when a row is diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index f1addb9b..464f4695 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -68,6 +68,15 @@ VULN_PY = ( ) +@pytest.fixture(autouse=True) +def _no_net_err_from_an_earlier_test(): + """A hook is one process per event; tests that call it in-process share + the module's record of the last failed call.""" + import _base + _base._USAGE["net_err"] = 0 + yield + + @pytest.fixture def workspace(tmp_path): ws = tmp_path / "ws" diff --git a/plugins/security-guidance/tests/test_network_failure_class.py b/plugins/security-guidance/tests/test_network_failure_class.py new file mode 100644 index 00000000..2f0112a7 --- /dev/null +++ b/plugins/security-guidance/tests/test_network_failure_class.py @@ -0,0 +1,329 @@ +"""A call that got no HTTP response reports why, as `net_err`.""" +import asyncio +import errno +import http.client +import socket +import ssl +import sys +import types +import urllib.error + +import pytest + +from conftest import VULN_PY, metrics_of, run_hook, stop_payload, ups_payload + +import _base +import llm +import security_reminder_hook as hook + + +def _cert_error(code): + e = ssl.SSLCertVerificationError(1, "certificate verify failed") + e.verify_code = code + return e + + +class TestClass: + @pytest.mark.parametrize("exc, expected", [ + (urllib.error.URLError(_cert_error(20)), (llm.NET_ERR_CERT_VERIFY, 20)), + (urllib.error.URLError(_cert_error(19)), (llm.NET_ERR_CERT_VERIFY, 19)), + (urllib.error.URLError(_cert_error(0)), (llm.NET_ERR_CERT_VERIFY, 0)), + (urllib.error.URLError(ssl.SSLError(1, "wrong version number")), (llm.NET_ERR_TLS, 0)), + # A default context that cannot be built is raised bare, before any connection. + (ssl.SSLError(1, "[ASN1] nested asn1 error"), (llm.NET_ERR_TLS, 0)), + (urllib.error.URLError(socket.gaierror(-2, "Name or service not known")), (llm.NET_ERR_DNS, 0)), + (urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")), (llm.NET_ERR_CONNECT, 0)), + (urllib.error.URLError(OSError(errno.ENETUNREACH, "unreachable")), (llm.NET_ERR_CONNECT, 0)), + (http.client.RemoteDisconnected("closed without response"), (llm.NET_ERR_CONNECT, 0)), + (TimeoutError("The read operation timed out"), (llm.NET_ERR_TIMEOUT, 0)), + (urllib.error.URLError(socket.timeout("timed out")), (llm.NET_ERR_TIMEOUT, 0)), + (urllib.error.URLError(OSError("Tunnel connection failed: 403 Forbidden")), (llm.NET_ERR_PROXY, 0)), + (urllib.error.URLError(OSError("Tunnel connection failed: 504 Gateway Timed Out")), + (llm.NET_ERR_PROXY, 0)), + (urllib.error.URLError("unknown url type"), (llm.NET_ERR_OTHER, 0)), + (http.client.IncompleteRead(b"x"), (llm.NET_ERR_OTHER, 0)), + (http.client.BadStatusLine("x"), (llm.NET_ERR_OTHER, 0)), + (ValueError("step timed out"), (0, 0)), + (UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte"), (0, 0)), + ]) + def test_class_and_verify_code(self, exc, expected): + assert llm._net_error_class(exc) == expected + + def test_code_packs_class_verify_code_and_flags(self, monkeypatch): + monkeypatch.setattr(llm, "_net_error_flags", lambda tls: 5 if tls else 2) + assert llm._net_error_code(urllib.error.URLError(_cert_error(20))) == 1 + 2000 + 50000 + assert llm._net_error_code(urllib.error.URLError(socket.gaierror(-2, "x"))) == 3 + 20000 + + def test_no_code_and_no_setup_checks_for_an_exception_that_is_not_a_network_failure( + self, monkeypatch): + monkeypatch.setattr(llm, "_net_error_flags", lambda tls: pytest.fail("checked")) + assert llm._net_error_code(ValueError("x")) == 0 + + def test_a_setup_check_that_raises_keeps_the_class(self, monkeypatch): + def boom(tls): + raise RuntimeError("x") + monkeypatch.setattr(llm, "_net_error_flags", boom) + assert llm._net_error_code(urllib.error.URLError(_cert_error(20))) == 2001 + + +class TestFlags: + @pytest.fixture(autouse=True) + def _clean(self, monkeypatch, tmp_path): + for name in ("NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "SSL_CERT_DIR"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://api.example.com") + monkeypatch.setattr(llm.urllib.request, "getproxies", lambda: {}) + monkeypatch.setattr(llm.sys, "platform", "darwin") + self.cafile = tmp_path / "cert.pem" + self.cafile.write_text("-----BEGIN CERTIFICATE-----\n") + self.capath = tmp_path / "certs" + self.capath.mkdir() + + def _paths(self, monkeypatch, cafile, capath): + monkeypatch.setattr(ssl, "get_default_verify_paths", lambda: ssl.DefaultVerifyPaths( + cafile, capath, "SSL_CERT_FILE", str(self.cafile), "SSL_CERT_DIR", str(self.capath))) + + def test_no_ca_file_and_an_empty_directory(self, monkeypatch): + self._paths(monkeypatch, None, str(self.capath)) + assert llm._net_error_flags(True) == 1 + self._paths(monkeypatch, None, None) + assert llm._net_error_flags(True) == 1 + + def test_an_empty_ca_file_counts_as_none(self, monkeypatch): + self.cafile.write_text("") + self._paths(monkeypatch, str(self.cafile), None) + assert llm._net_error_flags(True) == 1 + + def test_a_ca_file_or_a_filled_directory_is_not_flagged(self, monkeypatch): + self._paths(monkeypatch, str(self.cafile), str(self.capath)) + assert llm._net_error_flags(True) == 0 + (self.capath / "0a1b2c3d.0").write_text("x") + self._paths(monkeypatch, None, str(self.capath)) + assert llm._net_error_flags(True) == 0 + + def test_windows_is_not_flagged_for_its_files(self, monkeypatch): + monkeypatch.setattr(llm.sys, "platform", "win32") + self._paths(monkeypatch, None, None) + assert llm._net_error_flags(True) == 0 + + def test_tls_variables(self, monkeypatch): + self._paths(monkeypatch, str(self.cafile), None) + monkeypatch.setenv("NODE_EXTRA_CA_CERTS", "/x/ca.pem") + assert llm._net_error_flags(True) == 4 + monkeypatch.setenv("SSL_CERT_DIR", "/x") + assert llm._net_error_flags(True) == 12 + # Not read for a failure that is not about TLS. + assert llm._net_error_flags(False) == 0 + + def test_proxy_for_the_url_scheme(self, monkeypatch): + monkeypatch.setattr(llm.urllib.request, "proxy_bypass", lambda host: False) + monkeypatch.setattr(llm.urllib.request, "getproxies", lambda: {"https": "http://proxy:8080"}) + assert llm._net_error_flags(False) == 2 + monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://gateway.internal:4000") + assert llm._net_error_flags(False) == 0 + monkeypatch.setattr(llm.urllib.request, "getproxies", lambda: {"http": "http://proxy:8080"}) + assert llm._net_error_flags(False) == 2 + + def test_proxy_bypass_is_asked_with_the_port(self, monkeypatch): + asked = [] + monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://gw.internal:8443/base") + monkeypatch.setattr(llm.urllib.request, "getproxies", lambda: {"https": "http://proxy:8080"}) + monkeypatch.setattr(llm.urllib.request, "proxy_bypass", lambda host: asked.append(host) or True) + assert llm._net_error_flags(False) == 0 + assert asked == ["gw.internal:8443"] + + +@pytest.fixture +def direct(monkeypatch, tmp_path): + """In-process calls with a credential, no real state dir, no model + lookup, no waiting between retries and a plain machine setup.""" + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + for var in llm._PROVIDER_ENV_VARS: + monkeypatch.delenv(var, raising=False) + monkeypatch.setattr(llm, "HAS_API_CREDENTIALS", True) + monkeypatch.setattr(llm, "ANTHROPIC_API_KEY", "k") + monkeypatch.setattr(llm, "default_review_model", lambda: "claude-opus-5-5") + monkeypatch.setattr(llm, "debug_log", lambda *a, **k: None) + monkeypatch.setattr(llm, "_net_error_flags", lambda tls: 0) + monkeypatch.setattr("time.sleep", lambda s: None) + monkeypatch.setitem(_base._USAGE, "http_err_count", 0) + monkeypatch.setitem(_base._USAGE, "http_err_last", 0) + + +class _Reply: + def __init__(self, text): + self._body = ('{"content": [{"type": "text", "text": %s}], "usage": {}}' + % __import__("json").dumps(text)).encode() + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def read(self): + return self._body + + +class TestRecorded: + def _urlopen(self, monkeypatch, *outcomes): + """Each call takes the next outcome (the last one repeats): an + exception is raised, anything else is the reply text.""" + calls = [] + + def urlopen(*a, **k): + outcome = outcomes[min(len(calls), len(outcomes) - 1)] + calls.append(outcome) + if isinstance(outcome, BaseException): + raise outcome + return _Reply(outcome) + monkeypatch.setattr(llm.urllib.request, "urlopen", urlopen) + return calls + + def test_call_that_never_connects(self, direct, monkeypatch): + self._urlopen(monkeypatch, urllib.error.URLError(_cert_error(20))) + assert llm._call_claude("p", {"type": "object"}, model="m") is None + assert llm._last_call_claude_http_error == -1 + assert _base._net_error_metric() == 2001 + + def test_http_error_records_nothing(self, direct, monkeypatch): + self._urlopen(monkeypatch, urllib.error.HTTPError("u", 400, "bad", {}, None)) + assert llm._call_claude("p", {"type": "object"}, model="m") is None + assert llm._last_call_claude_http_error == 400 + assert _base._net_error_metric() == 0 + + def test_a_later_call_that_gets_a_response_clears_it(self, direct, monkeypatch): + refused = urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) + self._urlopen(monkeypatch, refused, refused, refused, '{"ok": true}') + assert llm._call_claude("p", {"type": "object"}, model="m") is None + assert _base._net_error_metric() == llm.NET_ERR_CONNECT + assert llm._call_claude("p", {"type": "object"}, model="fallback") == {"ok": True} + assert _base._net_error_metric() == 0 + + def test_a_later_call_refused_with_a_status_clears_it(self, direct, monkeypatch): + refused = urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) + self._urlopen(monkeypatch, refused, refused, refused, + urllib.error.HTTPError("u", 400, "bad", {}, None)) + llm._call_claude("p", {"type": "object"}, model="m") + llm._call_claude("p", {"type": "object"}, model="fallback") + assert llm._last_call_claude_http_error == 400 + assert _base._net_error_metric() == 0 + + def test_tls_context_that_cannot_be_built(self, direct, monkeypatch): + """Raised bare by the HTTP client, so the review sees an exception + and no api_error.""" + self._urlopen(monkeypatch, ssl.SSLError(1, "[ASN1] nested asn1 error")) + assert llm.analyze_code_security([("a.py", "+x = 1\n")]) == (None, []) + assert llm.last_review_failed() and llm.last_review_status() is None + assert _base._net_error_metric() == llm.NET_ERR_TLS + + def test_reply_that_is_not_json_records_nothing(self, direct, monkeypatch): + self._urlopen(monkeypatch, "<html>sign in</html>") + assert llm.analyze_code_security([("a.py", "+x = 1\n")]) == (None, []) + assert llm.last_review_failed() + assert _base._net_error_metric() == 0 + + def test_only_a_positive_code_is_kept(self): + _base._record_net_error(None) + _base._record_net_error(0) + assert _base._net_error_metric() == 0 + _base._record_net_error(4) + _base._record_net_error(20003) + assert _base._net_error_metric() == 20003 + + def test_probe_that_cannot_connect(self, direct, monkeypatch): + self._urlopen(monkeypatch, urllib.error.URLError(socket.gaierror(-2, "x"))) + assert llm._probe_anthropic() is False + assert _base._net_error_metric() == llm.NET_ERR_DNS + + +class TestInnerCli: + @pytest.fixture + def sdk(self, direct, monkeypatch): + mod = types.ModuleType("claude_agent_sdk") + for name in ("AssistantMessage", "ClaudeAgentOptions", "ResultMessage"): + setattr(mod, name, type(name, (), {"__init__": lambda self, **k: None})) + mod.query = None + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + monkeypatch.setattr(llm, "_send_sdk_logs_to_debug_log", lambda: None) + return mod + + def _run(self, monkeypatch, exc): + def run(start, stderr_lines): + raise exc + monkeypatch.setattr(llm, "_run_inner_cli", run) + assert llm._call_claude_via_sdk("p", {"type": "object"}) is None + assert llm._last_call_claude_http_error == -1 + return _base._net_error_metric() + + def test_cli_failed(self, sdk, monkeypatch): + assert self._run(monkeypatch, RuntimeError("exit code 1")) == llm.NET_ERR_INNER_CLI + + def test_cli_timed_out(self, sdk, monkeypatch): + assert self._run(monkeypatch, asyncio.TimeoutError()) == llm.NET_ERR_INNER_CLI_TIMEOUT + + def test_no_sdk(self, direct, monkeypatch): + monkeypatch.setitem(sys.modules, "claude_agent_sdk", None) + monkeypatch.setattr(llm, "_inject_agent_sdk_venv_into_syspath", lambda d: None) + assert llm._call_claude_via_sdk("p", {"type": "object"}) is None + assert _base._net_error_metric() == llm.NET_ERR_NO_SDK + + +class TestEmittedRow: + @pytest.fixture(autouse=True) + def _clean(self, monkeypatch): + monkeypatch.setattr(hook, "_TAIL_METRICS", {}) + monkeypatch.setattr(hook, "_log_usage", lambda usage: None) + monkeypatch.setattr(hook.llm, "gateway_cfg", lambda: 0) + + def _row(self, capsys): + return __import__("json").loads(capsys.readouterr().out)["metrics"] + + def test_ahead_of_the_rows_own_keys(self, capsys, monkeypatch): + monkeypatch.setitem(_base._USAGE, "http_err_count", 2) + monkeypatch.setitem(_base._USAGE, "http_err_last", -1) + _base._record_net_error(2001) + hook.emit_metrics({"review_failed": True, "vulns_found": 0, "review_ms": 18000, + "api_error": -1}) + keys = list(self._row(capsys)) + at = keys.index("net_err") + assert keys[at - 1] == "http_err_count" and keys[at + 1] == "review_failed" + + def test_kept_on_a_row_over_the_key_cap(self, capsys): + _base._record_net_error(2001) + hook.emit_metrics({f"k{i}": i for i in range(25)}) + assert "net_err" in list(self._row(capsys))[:20] + + def test_absent_without_a_failure(self, capsys): + hook.emit_metrics({"vulns_found": 0, "review_ms": 10}) + assert "net_err" not in self._row(capsys) + + +def _free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def test_stop_review_that_cannot_connect(workspace, hook_env): + """Through the real hook: nothing listens at the endpoint.""" + _, repo = workspace + env = dict(hook_env) + env["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{_free_port()}" + env["SECURITY_REVIEW_MODEL"] = "claude-sonnet-4-6" # one model: one round of retries + run_hook(ups_payload(repo), env) + (repo / "app.py").write_text(VULN_PY) + _, out, _ = run_hook(stop_payload(repo), env) + m = metrics_of(out) + assert m["api_error"] == -1 and m["review_failed"] is True + assert m["net_err"] % 100 == llm.NET_ERR_CONNECT + assert "net_err" in list(m)[:20] + + +def test_stop_review_that_ran_has_no_class(workspace, hook_env): + _, repo = workspace + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + _, out, _ = run_hook(stop_payload(repo), hook_env) + m = metrics_of(out) + assert "review_ms" in m and "net_err" not in m |
