1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
|
"""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 threading
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_failure_on_the_windows_store_context_is_recorded(self, direct, monkeypatch):
"""The context built for a Windows store with an unreadable entry is
the one the call uses, and a failure on it is still classified."""
context = ssl.create_default_context()
monkeypatch.setattr(llm, "_store_tls_context", context)
used = []
def urlopen(*a, **k):
used.append(k.get("context"))
raise urllib.error.URLError(_cert_error(20))
monkeypatch.setattr(llm.urllib.request, "urlopen", urlopen)
assert llm._call_claude("p", {"type": "object"}, model="m") is None
assert used and all(c is context for c in used)
assert _base._net_error_metric() == 2001
def test_store_check_that_fails_is_recorded_as_tls(self, direct, monkeypatch):
"""The store check raises and Python's own default context cannot be
built either: the call raises past the retry loop."""
def check():
raise ssl.SSLError(1, "[ASN1] nested asn1 error")
monkeypatch.setattr(llm, "_store_tls_context", llm._STORE_TLS_UNSET)
monkeypatch.setattr(llm, "_context_without_unreadable_store_certs", check)
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()
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)
class TestClearedOnALaterResponse:
"""`net_err` says why the last call got no response, so a failed call
followed by one that got through leaves nothing on the review's row."""
@pytest.fixture(autouse=True)
def _clean(self, monkeypatch):
monkeypatch.setitem(_base._USAGE, "net_err", 0)
monkeypatch.setattr(llm, "_last_call_claude_http_error", None)
@pytest.fixture
def remote(self, direct, monkeypatch):
monkeypatch.setenv("CLAUDE_CODE_REMOTE", "1")
monkeypatch.delenv("NO_PROXY", raising=False)
monkeypatch.delenv("no_proxy", raising=False)
monkeypatch.setattr(llm, "_anthropic_reachable", None)
def _probes(self, monkeypatch, *outcomes):
def urlopen(request, timeout):
outcome = outcomes[len(calls)]
calls.append(request)
if isinstance(outcome, BaseException):
raise outcome
return _Reply("")
calls = []
monkeypatch.setattr(llm, "_urlopen", urlopen)
return calls
def _status(self, code):
return urllib.error.HTTPError("https://api.anthropic.com/", code, "x", {}, None)
@pytest.mark.parametrize("second", ["reply", "status"])
def test_second_probe_that_gets_through(self, remote, monkeypatch, second):
calls = self._probes(monkeypatch, urllib.error.URLError(ConnectionRefusedError()),
None if second == "reply" else self._status(404))
assert llm.ensure_anthropic_reachable() is True
assert len(calls) == 2
assert _base._net_error_metric() == 0
def test_second_probe_that_fails_keeps_its_class(self, remote, monkeypatch):
self._probes(monkeypatch, urllib.error.URLError(ConnectionRefusedError()),
urllib.error.URLError(socket.gaierror(-2, "x")))
assert llm.ensure_anthropic_reachable() is False
assert _base._net_error_metric() == llm.NET_ERR_DNS
def _race(self, monkeypatch, agentic_result):
"""A fallback that records a refused connection and has no verdict,
then an agentic run that ends with `agentic_result`."""
tried = threading.Event()
def fallback(diff_files, is_diff, previous_findings):
_base._record_net_error(llm.NET_ERR_CONNECT)
llm._last_call_claude_http_error = -1
tried.set()
return None, []
def agentic(repo_root, diff_files, rel_touched):
assert tried.wait(10)
return agentic_result
monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0")
monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
monkeypatch.setattr(hook, "analyze_code_security", fallback)
monkeypatch.setattr(hook, "agentic_review", agentic)
monkeypatch.setattr(hook.llm, "last_review_failed", lambda: True)
monkeypatch.setattr(hook.llm, "last_review_status", lambda: -1)
return hook._agentic_review_with_race(".", [], [], [])
@pytest.mark.parametrize("guidance", ["findings", None])
def test_agentic_verdict_after_a_failed_fallback(self, monkeypatch, guidance):
_, _, m = self._race(monkeypatch, (guidance, [], {"agentic": True}))
assert (m["race_winner"], m["race_started"]) == (1, 1)
assert _base._net_error_metric() == 0
assert llm._last_call_claude_http_error is None
def test_no_verdict_from_either_side_keeps_the_class(self, monkeypatch):
_, _, m = self._race(monkeypatch, (None, [], {"agentic_fallback": "investigate:x"}))
assert m["race_winner"] == 2 and m["review_failed"]
assert _base._net_error_metric() == llm.NET_ERR_CONNECT
def _dual_legs(self, monkeypatch, *replies):
"""The first leg records a refused connection before the second ends."""
lock, failed = threading.Lock(), threading.Event()
pending = list(replies)
def call(*a, **k):
with lock:
reply = pending.pop(0)
if reply is None:
_base._record_net_error(llm.NET_ERR_CONNECT)
llm._last_call_claude_http_error = -1
failed.set()
else:
assert failed.wait(10)
return reply
monkeypatch.setenv("SG_DUAL_OR", "on")
monkeypatch.setenv("SECURITY_REVIEW_MODEL", "claude-opus-5-5")
monkeypatch.setattr(llm, "_call_claude", call)
return llm._call_claude_dual_or("p", {}, bool_key="found", list_key="items")
def test_dual_review_with_one_leg_that_gets_through(self, monkeypatch):
merged = self._dual_legs(monkeypatch, None, {"found": False, "items": []})
assert merged["found"] is False
assert _base._net_error_metric() == 0
assert llm._last_call_claude_http_error is None
def test_dual_review_with_no_leg_through_keeps_the_class(self, monkeypatch):
assert self._dual_legs(monkeypatch, None, None) is None
assert _base._net_error_metric() == llm.NET_ERR_CONNECT
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
|