340 lines
12 KiB
Python
340 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""End-to-end tests for run_sast_eval.py using a local mock OpenAI API.
|
|
|
|
Run with:
|
|
python3 -m unittest validation/test_pipeline.py -v
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
SCRIPT = ROOT / "run_sast_eval.py"
|
|
SAMPLES = ROOT / "Samples"
|
|
SAMPLE_NAMES = [
|
|
"BenchmarkTest00002",
|
|
"BenchmarkTest00007",
|
|
"BenchmarkTest00014",
|
|
"BenchmarkTest00015",
|
|
]
|
|
|
|
sys.path.insert(0, str(ROOT))
|
|
from run_sast_eval import normalize_category, normalize_cwe, parse_result # noqa: E402
|
|
|
|
|
|
def _result(vulnerable: bool, cwe: str) -> dict[str, object]:
|
|
return {
|
|
"reasoning": "mock analysis",
|
|
"vulnerable": vulnerable,
|
|
"cwe": cwe,
|
|
}
|
|
|
|
|
|
class MockHandler(BaseHTTPRequestHandler):
|
|
counts: dict[tuple[str | None, bool], int] = {}
|
|
|
|
def log_message(self, *args: object) -> None:
|
|
pass
|
|
|
|
def do_POST(self) -> None:
|
|
if self.path != "/v1/chat/completions":
|
|
self.send_error(404)
|
|
return
|
|
length = int(self.headers.get("Content-Length", 0))
|
|
payload = json.loads(self.rfile.read(length) or b"{}")
|
|
messages = payload.get("messages", [])
|
|
blob = "\n".join(str(message.get("content", "")) for message in messages)
|
|
|
|
sample = next((name for name in SAMPLE_NAMES if name in blob), None)
|
|
is_repair = "Your previous response was not valid JSON" in blob
|
|
key = (sample, is_repair)
|
|
self.counts[key] = self.counts.get(key, 0) + 1
|
|
|
|
if sample == "BenchmarkTest00015" and self.counts[key] == 1:
|
|
body = json.dumps({"error": {"message": "rate limited"}}).encode()
|
|
self.send_response(429)
|
|
self.send_header("Retry-After", "0")
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
|
|
if sample == "BenchmarkTest00014" and not is_repair:
|
|
text = "this is not json at all"
|
|
elif sample == "BenchmarkTest00007":
|
|
text = "```json\n" + json.dumps(_result(False, "None")) + "\n```"
|
|
elif sample == "BenchmarkTest00002":
|
|
text = json.dumps(_result(True, "CWE-22"))
|
|
else:
|
|
text = json.dumps(_result(False, "None"))
|
|
|
|
response = {
|
|
"id": "mock",
|
|
"object": "chat.completion",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"message": {"role": "assistant", "content": text},
|
|
"finish_reason": "stop",
|
|
}
|
|
],
|
|
"usage": {
|
|
"prompt_tokens": 100,
|
|
"completion_tokens": 20,
|
|
"total_tokens": 120,
|
|
},
|
|
}
|
|
body = json.dumps(response).encode()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
|
|
class PipelineTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls) -> None:
|
|
cls.server = ThreadingHTTPServer(("127.0.0.1", 0), MockHandler)
|
|
cls.port = cls.server.server_address[1]
|
|
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
|
cls.thread.start()
|
|
|
|
@classmethod
|
|
def tearDownClass(cls) -> None:
|
|
cls.server.shutdown()
|
|
cls.server.server_close()
|
|
cls.thread.join(timeout=5)
|
|
|
|
def setUp(self) -> None:
|
|
MockHandler.counts.clear()
|
|
|
|
def test_end_to_end_pipeline(self) -> None:
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
temp = Path(temp_dir)
|
|
input_dir = temp / "samples"
|
|
input_dir.mkdir()
|
|
for name in SAMPLE_NAMES:
|
|
(input_dir / f"{name}.py").write_text(
|
|
(SAMPLES / f"{name}.py").read_text(encoding="utf-8"),
|
|
encoding="utf-8",
|
|
)
|
|
|
|
db = temp / "results.sqlite3"
|
|
csv_path = temp / "results.csv"
|
|
command = [
|
|
sys.executable,
|
|
str(SCRIPT),
|
|
"--input",
|
|
str(input_dir),
|
|
"--model",
|
|
"mock-model",
|
|
"--base-url",
|
|
f"http://127.0.0.1:{self.port}/v1",
|
|
"--api-key",
|
|
"dummy",
|
|
"--run-id",
|
|
"test-run",
|
|
"--db",
|
|
str(db),
|
|
"--csv",
|
|
str(csv_path),
|
|
"--repair-attempts",
|
|
"1",
|
|
"--max-retries",
|
|
"2",
|
|
"--timeout",
|
|
"10",
|
|
]
|
|
result = subprocess.run(
|
|
command,
|
|
cwd=ROOT,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=60,
|
|
)
|
|
self.assertEqual(
|
|
result.returncode,
|
|
0,
|
|
f"runner failed\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}",
|
|
)
|
|
|
|
connection = sqlite3.connect(db)
|
|
connection.row_factory = sqlite3.Row
|
|
try:
|
|
rows = connection.execute(
|
|
"""
|
|
SELECT a.*
|
|
FROM attempts a
|
|
JOIN (
|
|
SELECT sample_path, MAX(call_index) AS max_index
|
|
FROM attempts WHERE run_id = ?
|
|
GROUP BY sample_path
|
|
) latest
|
|
ON latest.sample_path = a.sample_path
|
|
AND latest.max_index = a.call_index
|
|
WHERE a.run_id = ?
|
|
ORDER BY a.sample_name
|
|
""",
|
|
("test-run", "test-run"),
|
|
).fetchall()
|
|
self.assertEqual(len(rows), 4)
|
|
self.assertTrue(all(row["parse_ok"] == 1 for row in rows))
|
|
by_name = {row["sample_name"]: row for row in rows}
|
|
self.assertEqual(by_name["BenchmarkTest00002"]["flagged"], "Yes")
|
|
self.assertEqual(by_name["BenchmarkTest00002"]["category"], "pathtraver")
|
|
self.assertEqual(by_name["BenchmarkTest00002"]["cwe"], "CWE-22")
|
|
for name in SAMPLE_NAMES[1:]:
|
|
self.assertEqual(by_name[name]["flagged"], "No")
|
|
|
|
attempts_14 = connection.execute(
|
|
"""
|
|
SELECT phase FROM attempts
|
|
WHERE run_id = 'test-run' AND sample_name = 'BenchmarkTest00014'
|
|
ORDER BY call_index
|
|
"""
|
|
).fetchall()
|
|
self.assertEqual([row["phase"] for row in attempts_14], ["initial", "repair"])
|
|
|
|
attempts_15 = connection.execute(
|
|
"""
|
|
SELECT http_status FROM attempts
|
|
WHERE run_id = 'test-run' AND sample_name = 'BenchmarkTest00015'
|
|
ORDER BY call_index
|
|
"""
|
|
).fetchall()
|
|
self.assertEqual([row["http_status"] for row in attempts_15], [429, 200])
|
|
finally:
|
|
connection.close()
|
|
|
|
with csv_path.open(newline="", encoding="utf-8") as handle:
|
|
csv_rows = list(csv.DictReader(handle))
|
|
self.assertEqual(len(csv_rows), 4)
|
|
self.assertIn("expected_category", csv_rows[0])
|
|
|
|
report = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
str(SCRIPT),
|
|
"--report",
|
|
"test-run",
|
|
"--db",
|
|
str(db),
|
|
"--no-csv",
|
|
],
|
|
cwd=ROOT,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=30,
|
|
)
|
|
self.assertEqual(report.returncode, 0, report.stderr)
|
|
self.assertIn("TP=1 FP=0 TN=3 FN=0", report.stdout)
|
|
self.assertIn("Strict accuracy (flag + CWE): 1.000", report.stdout)
|
|
self.assertIn("wrong-category TPs=0", report.stdout)
|
|
|
|
def test_json_parser_and_normalisation(self) -> None:
|
|
# v2 schema: boolean flag plus CWE; category is derived from the CWE.
|
|
parsed = parse_result(
|
|
'Here is the result:\n'
|
|
'{"reasoning": "x", "vulnerable": true, "cwe": "22",}'
|
|
)
|
|
self.assertTrue(parsed.ok)
|
|
self.assertEqual(parsed.flagged, "Yes")
|
|
self.assertEqual(parsed.category, "pathtraver")
|
|
self.assertEqual(parsed.cwe, "CWE-22")
|
|
|
|
# Legacy v1 schema remains parseable.
|
|
legacy = parse_result(
|
|
'{"reasoning": "x", "flagged": "Yes", '
|
|
'"category": "Path Traversal (CWE-22)", "cwe": "CWE-22"}'
|
|
)
|
|
self.assertTrue(legacy.ok)
|
|
self.assertEqual(legacy.flagged, "Yes")
|
|
self.assertEqual(legacy.category, "pathtraver")
|
|
self.assertEqual(legacy.cwe, "CWE-22")
|
|
|
|
# A false flag must discard any supplied CWE.
|
|
fenced = parse_result(
|
|
'```json\n{"reasoning": "x", "vulnerable": false, '
|
|
'"cwe": "CWE-79"}\n```'
|
|
)
|
|
self.assertTrue(fenced.ok)
|
|
self.assertEqual(fenced.flagged, "No")
|
|
self.assertEqual(fenced.category, "None")
|
|
self.assertEqual(fenced.cwe, "None")
|
|
|
|
# Category-only responses still work; the CWE is inferred.
|
|
inferred = parse_result(
|
|
'{"reasoning": "x", "vulnerable": true, '
|
|
'"category": "Open Redirect"}'
|
|
)
|
|
self.assertTrue(inferred.ok)
|
|
self.assertEqual(inferred.category, "redirect")
|
|
self.assertEqual(inferred.cwe, "CWE-601")
|
|
|
|
# Some models emit Python-style \' escapes, which are invalid JSON.
|
|
repaired_escape = parse_result(
|
|
r'{"reasoning": "path = f\'{bar}\'", '
|
|
'"vulnerable": true, "cwe": "CWE-22"}'
|
|
)
|
|
self.assertTrue(repaired_escape.ok)
|
|
self.assertEqual(repaired_escape.category, "pathtraver")
|
|
self.assertEqual(repaired_escape.cwe, "CWE-22")
|
|
|
|
for cwe, category in (
|
|
("CWE-94", "codeinj"),
|
|
("CWE-328", "hash"),
|
|
("CWE-614", "securecookie"),
|
|
("CWE-601", "redirect"),
|
|
("CWE-90", "ldapi"),
|
|
):
|
|
result = parse_result(
|
|
f'{{"reasoning": "x", "vulnerable": true, "cwe": "{cwe}"}}'
|
|
)
|
|
self.assertTrue(result.ok)
|
|
self.assertEqual(result.category, category)
|
|
self.assertEqual(result.cwe, cwe)
|
|
|
|
self.assertEqual(normalize_category("Cross-Site Scripting / XSS"), "xss")
|
|
self.assertEqual(normalize_category("CWE-643"), "xpathi")
|
|
self.assertEqual(normalize_cwe("89"), "CWE-89")
|
|
|
|
def test_dry_run_needs_no_api_key(self) -> None:
|
|
env = os.environ.copy()
|
|
env.pop("OPENCODE_API_KEY", None)
|
|
result = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
str(SCRIPT),
|
|
"--input",
|
|
str(SAMPLES / "BenchmarkTest00002.py"),
|
|
"--model",
|
|
"mock-model",
|
|
"--dry-run",
|
|
"--no-csv",
|
|
],
|
|
cwd=ROOT,
|
|
capture_output=True,
|
|
text=True,
|
|
env=env,
|
|
timeout=30,
|
|
)
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
self.assertIn("Dry run only", result.stdout)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|