ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
fix(bench): validate judge verdicts before scoring
APZN214b1b322b53
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d28c17d..1c5e25d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -159,3 +159,4 @@ jobs:with:python-version: "3.12"- run: python3 scripts/posture_check_test.py+ - run: python3 -m unittest discover -s scripts/benchmark -p 'test_*.py' -vdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c6ced3..fbdf1ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b### Fixed+- **Benchmark judge validation**: grading and the judge's falsification battery require one verdict per ground-truth ID, actual boolean decisions and gates, and matches to the supplied scanner findings. Invalid grading responses use the existing three-attempt budget and abort without writing scores, rather than counting duplicate IDs or truthy strings such as `"false"`.- **Live log subscribers can no longer crash the process**: a client disconnect closes its log channel. The sink now delivers a line while it still holds the subscriber lock, so that close cannot land in the middle of the send.- **Notification delivery ignores HTTP_PROXY**: the dial guard checks the address it connects to. An environment proxy made that address the proxy, so a link-local target could still be reached. Notification HTTP now connects directly.- **Captured traffic blobs are owner-only**: HTTP and raw-stream bodies spilled out of the database are written `0600`, and their bucket directory is `0700`. An existing blob is tightened when it is seen again.diff --git a/scripts/benchmark/run_bench.py b/scripts/benchmark/run_bench.pyindex 8fc4728..79447d8 100755--- a/scripts/benchmark/run_bench.py+++ b/scripts/benchmark/run_bench.py@@ -254,10 +254,55 @@ For each ground-truth entry also grade four gates against the matched scanner fi- keywords: the scanner's text uses at least two terms describing the specific mechanism (1 point)- proof: the scanner's PoC/steps describe a route that would actually work for this ground truth (1 point)+When detected is true, copy matched_finding_id exactly from the scanner finding's id (preserve its JSON type). When detected is false, matched_finding_id must be null and all four gates must be false.+Output ONLY a valid JSON array, one object per ground-truth entry:[{"gt_id": "...", "detected": true|false, "confidence": "high"|"medium"|"low", "matched_finding_id": <scanner finding id or null>, "gates": {"component": bool, "class": bool, "keywords": bool, "proof": bool}, "reason": "1-2 sentences"}]"""+def parse_judge_verdicts(raw: str, gt_ids: list[str], scanner_findings: list[dict]) -> list[dict]:+ """Refuse malformed verdicts before Python truthiness or duplicate IDs can affect a score."""+ # Keep accepting code-fenced JSON from otherwise compatible judge endpoints.+ if not isinstance(raw, str):+ raise ValueError("expected a JSON array")+ start, end = raw.find("["), raw.rfind("]")+ if start == -1 or end <= start:+ raise ValueError("expected a JSON array")+ verdicts = json.loads(raw[start:end + 1])+ if not isinstance(verdicts, list) or len(verdicts) != len(gt_ids):+ raise ValueError("expected one verdict per ground-truth entry")++ expected_ids, seen = set(gt_ids), set()+ # JSON integer IDs and string IDs are distinct; bool/float must not alias an integer.+ finding_ids = {(type(f["id"]), f["id"]) for f in scanner_findings if type(f.get("id")) in (int, str)}+ gate_keys = ("component", "class", "keywords", "proof")+ for v in verdicts:+ if not isinstance(v, dict):+ raise ValueError("each verdict must be an object")+ gt_id = v.get("gt_id")+ if not isinstance(gt_id, str) or gt_id not in expected_ids or gt_id in seen:+ raise ValueError("ground-truth IDs must be known and unique")+ seen.add(gt_id)+ if type(v.get("detected")) is not bool:+ raise ValueError("detected must be a boolean")+ gates = v.get("gates")+ if not isinstance(gates, dict) or any(type(gates.get(k)) is not bool for k in gate_keys):+ raise ValueError("all four gates must be booleans")+ if "matched_finding_id" not in v:+ raise ValueError("matched_finding_id is required")+ matched_id = v["matched_finding_id"]+ if v["detected"]:+ if type(matched_id) not in (int, str) or (type(matched_id), matched_id) not in finding_ids:+ raise ValueError("a detection must reference a provided scanner finding ID")+ elif matched_id is not None or any(gates[k] for k in gate_keys):+ raise ValueError("a non-detection must have a null match and false gates")+ if v.get("reason") is not None and not isinstance(v["reason"], str):+ raise ValueError("reason must be a string when provided")+ if seen != expected_ids:+ raise ValueError("ground-truth IDs must be complete")+ return verdicts++def judge_battery(args) -> None:"""The judge must pass a falsification battery before grading (capability-matrix rule:assume the grader is the broken part)."""@@ -280,10 +325,10 @@ def judge_battery(args) -> None:user = f"## Scanner findings\n{json.dumps(findings, indent=1)}\n\n## Ground truth\n### {gt_text}\n\nRespond with the JSON array."raw = llm(args.judge_url, args.judge_key, args.judge_model, JUDGE_SYSTEM, user, 2000, args.judge_timeout)try:- verdict = json.loads(raw[raw.find("["): raw.rfind("]") + 1])[0]- got = bool(verdict.get("detected"))- except Exception:- raise SystemExit(f"judge battery case '{label}': unparseable output; grader not trusted:\n{raw[:300]}")+ verdict = parse_judge_verdicts(raw, [gt_id], findings)[0]+ except ValueError as exc:+ raise SystemExit(f"judge battery case '{label}': invalid output ({exc}); grader not trusted:\n{str(raw)[:300]}") from None+ got = verdict["detected"]if got != expect:raise SystemExit(f"judge battery FAILED on '{label}' (expected detected={expect}, got {got}); a grader that cannot fail the wrong answers does not run")@@ -298,16 +343,11 @@ def run_judge(args, gt_findings: list[dict], scanner_findings: list[dict]) -> li"For EACH ground-truth entry, respond in the JSON array.")for attempt in range(3):raw = llm(args.judge_url, args.judge_key, args.judge_model, JUDGE_SYSTEM, user, 4000, args.judge_timeout)- start, end = raw.find("["), raw.rfind("]")- if start != -1 and end > start:- try:- verdicts = json.loads(raw[start:end + 1])- if isinstance(verdicts, list) and len(verdicts) == len(gt_findings):- return verdicts- except json.JSONDecodeError:- pass- print(f"[judge] unparseable output (attempt {attempt + 1}/3), retrying")- raise SystemExit("judge output unparseable after 3 attempts; grader not trusted")+ try:+ return parse_judge_verdicts(raw, [g["id"] for g in gt_findings], scanner_findings)+ except ValueError as exc:+ print(f"[judge] invalid output ({exc}; attempt {attempt + 1}/3), retrying")+ raise SystemExit("judge output invalid after 3 attempts; grader not trusted")# ---------------------------------------------------------------- scoringdiff --git a/scripts/benchmark/test_run_bench.py b/scripts/benchmark/test_run_bench.pynew file mode 100644index 0000000..54cc6b7--- /dev/null+++ b/scripts/benchmark/test_run_bench.py@@ -0,0 +1,265 @@+#!/usr/bin/env python3+"""Benchmark judge contract tests; no model, server or Docker calls.++Run: python3 -m unittest discover -s scripts/benchmark -p 'test_*.py' -v+"""+from __future__ import annotations++import copy+import json+import pathlib+import tempfile+import types+import unittest+from unittest import mock++import run_bench+++def verdict(gt_id, detected=True, matched_id=1):+ return {+ "gt_id": gt_id,+ "detected": detected,+ "matched_finding_id": matched_id if detected else None,+ "gates": {key: detected for key in ("component", "class", "keywords", "proof")},+ "reason": "fixture",+ }+++class JudgeTests(unittest.TestCase):+ def setUp(self):+ self.args = types.SimpleNamespace(+ judge_url="", judge_key="", judge_model="judge", judge_timeout=1,+ gt_version="fixture", subject_model="subject",+ )+ self.gt = [{+ "id": gt_id, "title": "fixture", "cwe": "CWE-0", "classes": [],+ "components": [], "mechanism_keywords": [], "proof_hint": "fixture",+ } for gt_id in ("GT-A", "GT-B")]+ self.findings = [{"id": 1, "name": "match"}, {"id": 2, "name": "candidate"}]+ self.verdicts = [verdict("GT-A"), verdict("GT-B", False)]+ llm_patch = mock.patch.object(run_bench, "llm")+ self.llm = llm_patch.start()+ self.addCleanup(llm_patch.stop)+ print_patch = mock.patch("builtins.print")+ print_patch.start()+ self.addCleanup(print_patch.stop)++ def assert_refused(self, response):+ self.llm.reset_mock()+ self.llm.return_value = json.dumps(response)+ with self.assertRaisesRegex(SystemExit, "after 3 attempts; grader not trusted"):+ run_bench.run_judge(self.args, self.gt, self.findings)+ self.assertEqual(self.llm.call_count, 3)++ def test_valid_verdicts_keep_order_and_scores(self):+ # Output order need not match ground truth, and a match may earn partial gates.+ response = list(reversed(self.verdicts))+ response[1]["gates"]["proof"] = False+ self.llm.return_value = json.dumps(response)+ result = run_bench.run_judge(self.args, self.gt, self.findings)+ self.assertEqual(result, response)+ self.assertEqual(self.llm.call_count, 1)+ scores = run_bench.tally(self.gt, result, self.findings, [])+ self.assertEqual(scores["detected"], 1)+ self.assertEqual(scores["detection_rate"], 0.5)+ self.assertEqual(scores["gate_totals_over_detected"], {+ "component": 1, "class": 1, "keywords": 1, "proof": 0,+ })+ self.assertEqual(scores["discovery_candidates"], [{"id": 2, "name": "candidate"}])++ def test_code_fenced_json_still_works(self):+ self.llm.return_value = "```json\n" + json.dumps(self.verdicts) + "\n```"+ self.assertEqual(run_bench.run_judge(self.args, self.gt, self.findings), self.verdicts)++ def test_string_finding_ids_still_work(self):+ self.verdicts[0]["matched_finding_id"] = "finding-1"+ self.llm.return_value = json.dumps(self.verdicts)+ result = run_bench.run_judge(self.args, self.gt, [{"id": "finding-1"}])+ self.assertEqual(result, self.verdicts)++ def test_duplicate_ground_truth_cannot_inflate_detection(self):+ self.assert_refused([verdict("GT-A"), verdict("GT-A")])++ def test_ground_truth_ids_must_be_complete_and_known(self):+ for response in (+ self.verdicts[:1], self.verdicts + [verdict("GT-C")],+ [verdict("GT-A"), verdict("GT-C")],+ [verdict("GT-A"), verdict(None)],+ [verdict("GT-A"), verdict(["GT-B"])],+ ):+ with self.subTest(response=response):+ self.assert_refused(response)++ def test_response_must_be_an_array_of_objects(self):+ for response in (None, {}, True, [1, 2], [self.verdicts[0], None], [[], {}]):+ with self.subTest(response=response):+ self.assert_refused(response)++ def test_detected_must_be_a_boolean(self):+ for value in ("false", "true", 0, 1, None, [], {}):+ with self.subTest(value=value):+ response = copy.deepcopy(self.verdicts)+ response[0]["detected"] = value+ self.assert_refused(response)+ response = copy.deepcopy(self.verdicts)+ del response[0]["detected"]+ self.assert_refused(response)++ def test_each_gate_must_be_a_boolean(self):+ for key in ("component", "class", "keywords", "proof"):+ for value in ("false", 0, 1, None):+ with self.subTest(key=key, value=value):+ response = copy.deepcopy(self.verdicts)+ response[0]["gates"][key] = value+ self.assert_refused(response)+ with self.subTest(missing_gate=key):+ response = copy.deepcopy(self.verdicts)+ del response[0]["gates"][key]+ self.assert_refused(response)+ for value in (None, [], "false"):+ with self.subTest(gates=value):+ response = copy.deepcopy(self.verdicts)+ response[0]["gates"] = value+ self.assert_refused(response)++ def test_detected_match_must_reference_a_provided_finding(self):+ # bool and float compare equal to integer 1 in Python; neither is an ID.+ for value in (None, 99, "1", True, 1.0, [], {}):+ with self.subTest(matched_id=value):+ response = copy.deepcopy(self.verdicts)+ response[0]["matched_finding_id"] = value+ self.assert_refused(response)+ response = copy.deepcopy(self.verdicts)+ del response[0]["matched_finding_id"]+ self.assert_refused(response)++ def test_non_detection_has_no_match_or_true_gates(self):+ response = copy.deepcopy(self.verdicts)+ response[1]["matched_finding_id"] = 2+ self.assert_refused(response)+ response = copy.deepcopy(self.verdicts)+ del response[1]["matched_finding_id"]+ self.assert_refused(response)+ for key in ("component", "class", "keywords", "proof"):+ with self.subTest(key=key):+ response = copy.deepcopy(self.verdicts)+ response[1]["gates"][key] = True+ self.assert_refused(response)++ def test_non_text_reason_is_refused_before_report_rendering(self):+ for value in (123, True, [], {}):+ with self.subTest(reason=value):+ response = copy.deepcopy(self.verdicts)+ response[0]["reason"] = value+ self.assert_refused(response)++ def test_empty_or_missing_reason_still_renders(self):+ del self.verdicts[0]["reason"]+ for value in (None, ""):+ with self.subTest(reason=value), tempfile.TemporaryDirectory() as tmp:+ self.verdicts[1]["reason"] = value+ self.llm.return_value = json.dumps(self.verdicts)+ result = run_bench.run_judge(self.args, self.gt, self.findings)+ self.assertEqual(result, self.verdicts)+ scores = run_bench.tally(self.gt, result, self.findings, [])+ out = pathlib.Path(tmp)+ run_bench.write_report(out, "fixture", self.args, {"id": 1}, "done",+ self.findings, result, scores)+ self.assertEqual(json.loads((out / "results.json").read_text())["verdicts"], result)+ self.assertIn("| GT-A | True |", (out / "report.md").read_text())++ def test_invalid_responses_can_recover_within_existing_retry_budget(self):+ self.llm.side_effect = [+ "not JSON", json.dumps([verdict("GT-A"), verdict("GT-A")]),+ json.dumps(self.verdicts),+ ]+ self.assertEqual(run_bench.run_judge(self.args, self.gt, self.findings), self.verdicts)+ self.assertEqual(self.llm.call_count, 3)++ def test_malformed_json_exhausts_retry_budget(self):+ self.llm.return_value = '[{"gt_id":'+ with self.assertRaisesRegex(SystemExit, "after 3 attempts; grader not trusted"):+ run_bench.run_judge(self.args, self.gt, self.findings)+ self.assertEqual(self.llm.call_count, 3)++ def test_non_text_model_content_exhausts_retry_budget(self):+ for value in (None, [], {}):+ with self.subTest(content=value):+ self.llm.reset_mock()+ self.llm.return_value = value+ with self.assertRaisesRegex(SystemExit, "after 3 attempts; grader not trusted"):+ run_bench.run_judge(self.args, self.gt, self.findings)+ self.assertEqual(self.llm.call_count, 3)++ def test_valid_battery_still_passes(self):+ self.llm.side_effect = [json.dumps([v]) for v in (+ verdict("GT-X"), verdict("GT-Y", False), verdict("GT-Z", False),+ )]+ run_bench.judge_battery(self.args)+ self.assertEqual(self.llm.call_count, 3)++ def test_battery_rejects_string_false_instead_of_treating_it_as_true(self):+ positive = verdict("GT-X")+ positive["detected"] = "false"+ self.llm.side_effect = [json.dumps([v]) for v in (+ positive, verdict("GT-Y", False), verdict("GT-Z", False),+ )]+ with self.assertRaisesRegex(SystemExit, "grader not trusted"):+ run_bench.judge_battery(self.args)+ self.assertEqual(self.llm.call_count, 1)++ def test_battery_checks_the_same_id_and_gate_contract(self):+ for invalid in (+ verdict("GT-WRONG"),+ {**verdict("GT-X"), "gates": {"component": True}},+ {**verdict("GT-X"), "matched_finding_id": 99},+ ):+ with self.subTest(invalid=invalid):+ self.llm.reset_mock()+ self.llm.side_effect = [json.dumps([v]) for v in (+ invalid, verdict("GT-Y", False), verdict("GT-Z", False),+ )]+ with self.assertRaisesRegex(SystemExit, "grader not trusted"):+ run_bench.judge_battery(self.args)+ self.assertEqual(self.llm.call_count, 1)++ def test_battery_refuses_non_text_content_without_crashing(self):+ self.llm.return_value = None+ with self.assertRaisesRegex(SystemExit, "grader not trusted"):+ run_bench.judge_battery(self.args)+ self.assertEqual(self.llm.call_count, 1)++ def test_battery_still_refuses_a_well_formed_wrong_answer(self):+ self.llm.return_value = json.dumps([verdict("GT-X", False)])+ with self.assertRaisesRegex(SystemExit, "battery FAILED on 'positive'"):+ run_bench.judge_battery(self.args)++ def test_exhausted_invalid_grading_never_writes_results(self):+ bad_reason = copy.deepcopy(self.verdicts)+ bad_reason[0]["reason"] = 123+ for response in ([verdict("GT-A"), verdict("GT-A")], bad_reason):+ with self.subTest(response=response):+ self.llm.reset_mock()+ self.llm.return_value = json.dumps(response)+ findings = [{**f, "summary": "fixture", "report": "fixture"} for f in self.findings]+ argv = ["run_bench.py", "--subject-model", "subject", "--corpus-url", "http://fixture.test"]+ env = {"ARTEX_TOKEN": "fixture", "JUDGE_BASE_URL": "http://judge.test",+ "JUDGE_MODEL": "judge", "JUDGE_API_KEY": "fixture"}+ with mock.patch.object(run_bench.sys, "argv", argv), \+ mock.patch.dict(run_bench.os.environ, env, clear=True), \+ mock.patch.object(run_bench.pathlib.Path, "read_text", return_value=json.dumps({"findings": self.gt})), \+ mock.patch.object(run_bench, "deploy_corpus", return_value={"url": "http://fixture.test"}), \+ mock.patch.object(run_bench, "create_task", return_value={"id": 1}), \+ mock.patch.object(run_bench, "wait_task", return_value="done"), \+ mock.patch.object(run_bench, "fetch_findings", return_value=findings), \+ mock.patch.object(run_bench, "judge_battery"), \+ mock.patch.object(run_bench, "write_report") as write_report:+ with self.assertRaisesRegex(SystemExit, "after 3 attempts; grader not trusted"):+ run_bench.main()+ write_report.assert_not_called()+ self.assertEqual(self.llm.call_count, 3)+++if __name__ == "__main__":+ unittest.main()diff --git a/scripts/verify.sh b/scripts/verify.shindex b6fb56c..c0c3680 100755--- a/scripts/verify.sh+++ b/scripts/verify.sh@@ -149,6 +149,7 @@ if [ "$GO_ONLY" -eq 0 ] && [ "$WEB_ONLY" -eq 0 ]; thenprintf 'note: shellcheck is not installed; skipping the shellcheck step\n'firun_step "posture check" python3 scripts/posture_check_test.py+ run_step "benchmark tests" python3 -m unittest discover -s scripts/benchmark -p 'test_*.py' -vrun_step "changelog section tests" bash scripts/test-extract-changelog-section.shrun_step "bot context tests" bash scripts/test-bot-context.shfi