Add SAST evaluation runner and validation artifacts
- Add run_sast_eval.py with SQLite/CSV result storage, retries, JSON repair, resumability, and expected-label scoring - Add exact SAST prompt and full benchmark expected-results CSV - Add mock-API end-to-end tests and uv/bandit dev requirements - Record Bandit parity and DeepSeek original-vs-obfuscated comparisons
This commit is contained in:
15 files changed
+26580
No files matched your search
@@ -2,3 +2,4 @@ __pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
venv/
|
||||
results/
|
||||
@@ -0,0 +1,151 @@
|
||||
# SAST evaluation runner
|
||||
|
||||
`run_sast_eval.py` sends benchmark samples to an OpenCode-hosted model, parses
|
||||
the model's JSON answer, and records every attempt in SQLite plus a per-run CSV.
|
||||
|
||||
It uses only the Python standard library, so there is nothing to install.
|
||||
|
||||
## Setup
|
||||
|
||||
Use an OpenCode Console or OpenCode Go API key (copy one from
|
||||
<https://opencode.ai/console>). The script looks for it in
|
||||
`OPENCODE_API_KEY` or `--api-key-file`; `--api-key` also works but may appear in
|
||||
shell history. If none is found and the script is interactive, it prompts
|
||||
securely.
|
||||
|
||||
```bash
|
||||
export OPENCODE_API_KEY="..."
|
||||
```
|
||||
|
||||
## Model names and endpoints
|
||||
|
||||
The API base URL is selected from the model prefix:
|
||||
|
||||
| Model argument | Endpoint |
|
||||
| --- | --- |
|
||||
| `deepseek-v4.1-flash` | `https://opencode.ai/inference/openai/v1` |
|
||||
| `opencode/deepseek-v4.1-flash` | `https://opencode.ai/inference/openai/v1` |
|
||||
| `opencode-go/deepseek-v4.1-flash` | `https://opencode.ai/inference/go/openai/v1` |
|
||||
|
||||
Use `--base-url` to point at another OpenAI-compatible endpoint. Listing models
|
||||
does not require a key:
|
||||
|
||||
```bash
|
||||
python3 run_sast_eval.py --list-models --search deepseek
|
||||
python3 run_sast_eval.py --list-models --model opencode-go/deepseek-v4.1-flash --search deepseek
|
||||
```
|
||||
|
||||
Free Console models may only be available through the OpenCode client itself.
|
||||
For this standalone runner, use paid Console models or models available through
|
||||
OpenCode Go.
|
||||
|
||||
## Running
|
||||
|
||||
One sample:
|
||||
|
||||
```bash
|
||||
python3 run_sast_eval.py \
|
||||
--input Samples_Obfuscated_v2/BenchmarkTest00002.py \
|
||||
--model deepseek-v4.1-flash
|
||||
```
|
||||
|
||||
The 200-sample obfuscated condition:
|
||||
|
||||
```bash
|
||||
python3 run_sast_eval.py \
|
||||
--input Samples_Obfuscated_v2 \
|
||||
--model deepseek-v4.1-flash \
|
||||
--run-id obfuscated-v2-deepseek
|
||||
```
|
||||
|
||||
For the original condition, use `--input Samples --run-id original-deepseek`.
|
||||
Run the two conditions as separate runs so their summaries do not mix.
|
||||
|
||||
The full 1,230-sample benchmark:
|
||||
|
||||
```bash
|
||||
python3 run_sast_eval.py \
|
||||
--input /home/joren/cloned/BenchmarkPython/testcode \
|
||||
--model deepseek-v4.1-flash \
|
||||
--run-id full-original-deepseek
|
||||
```
|
||||
|
||||
Preview without sending anything:
|
||||
|
||||
```bash
|
||||
python3 run_sast_eval.py \
|
||||
--input Samples_Obfuscated_v2 \
|
||||
--model deepseek-v4.1-flash \
|
||||
--dry-run
|
||||
```
|
||||
|
||||
Resume an interrupted batch (already-parsed samples are skipped):
|
||||
|
||||
```bash
|
||||
python3 run_sast_eval.py \
|
||||
--input Samples_Obfuscated_v2 \
|
||||
--model deepseek-v4.1-flash \
|
||||
--run-id obfuscated-v2-deepseek \
|
||||
--resume
|
||||
```
|
||||
|
||||
## Outputs
|
||||
|
||||
- `results/sast_runs.sqlite3` — all run metadata, prompts, and every API attempt
|
||||
- `results/<run-id>.csv` — one row per sample (the final attempt), for analysis
|
||||
|
||||
The SQLite `attempts` table records the raw response, parsed JSON, predicted
|
||||
flag/category/CWE, token usage, latency, HTTP status, errors, expected label,
|
||||
and whether the expected category is in the prompt's 9-category target scope.
|
||||
|
||||
Run original and obfuscated conditions as separate runs so the summary is not
|
||||
mixed; the `condition` column in the database/CSV lets you combine them later.
|
||||
|
||||
Use `--no-csv` to skip the CSV export or `--csv PATH` to choose its location.
|
||||
To reprint a finished run's summary and CSV without making API calls:
|
||||
|
||||
```bash
|
||||
python3 run_sast_eval.py --report obfuscated-v2-deepseek
|
||||
```
|
||||
|
||||
## Expected labels
|
||||
|
||||
The runner defaults to `data/expectedresults-0.1.csv` (the full 1,230-test
|
||||
benchmark label set) and falls back to `sample_expected.csv`. Override with
|
||||
`--expected-csv PATH`.
|
||||
|
||||
The prompt targets nine categories, but the benchmark also contains five
|
||||
out-of-scope categories: `hash`, `codeinj`, `securecookie`, `redirect`, and
|
||||
`ldapi`. The summary excludes those from flag/category metrics and reports the
|
||||
out-of-scope count separately.
|
||||
|
||||
## Useful runtime options
|
||||
|
||||
- `--workers 4` — parallel API calls (default 1)
|
||||
- `--max-retries 4` — retry 429/5xx/network errors
|
||||
- `--repair-attempts 1` — retry malformed JSON once
|
||||
- `--code-in user` — send the code as a user message
|
||||
- `--no-temperature` — omit `temperature` entirely
|
||||
- `--no-csv` — skip the CSV export
|
||||
- `--verbose` — show prompt/database details
|
||||
|
||||
## Prompt handling
|
||||
|
||||
The default system prompt is `prompts/sast_v1.txt`; `[INSERT_CODE_HERE]` is
|
||||
replaced with each sample. Pass `--prompt-file` to use another text file or a
|
||||
JSON file with a `prompt` field. `--code-in user` sends the code as a separate
|
||||
user message instead of embedding it in the system prompt.
|
||||
|
||||
Invalid JSON is retried once with a repair instruction by default
|
||||
(`--repair-attempts 0` disables this). Reasoning models that reject the
|
||||
`temperature` parameter are retried automatically without it; use
|
||||
`--no-temperature` to omit it from the start.
|
||||
|
||||
## Validation
|
||||
|
||||
The reproducible mock-API test and the executed Bandit/DeepSeek validation
|
||||
artifacts live in `validation/`. See `validation/README.md` for details.
|
||||
|
||||
```bash
|
||||
python3 -m unittest validation/test_pipeline.py -v
|
||||
```
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
||||
You are an expert Static Application Security Testing (SAST) code analyzer. Evaluate the provided Python code snippet for security vulnerabilities strictly within the designated target categories.
|
||||
|
||||
Target Vulnerability Categories:
|
||||
- Path Traversal (CWE-22)
|
||||
- SQL Injection (CWE-89)
|
||||
- XPath Injection (CWE-643)
|
||||
- XML External Entity / XXE (CWE-611)
|
||||
- Command Injection (CWE-78)
|
||||
- Insecure Deserialization (CWE-502)
|
||||
- Cross-Site Scripting / XSS (CWE-79)
|
||||
- Weak Randomness (CWE-330)
|
||||
- Trust Boundary Violation (CWE-501)
|
||||
|
||||
Evaluation Instructions:
|
||||
1. Analyze the data flow from untrusted input sources to sensitive sinks.
|
||||
2. Verify whether adequate validation or sanitization exists.
|
||||
3. Determine if a vulnerability from the target list is present.
|
||||
|
||||
Output strictly a valid JSON object matching the schema below. Do not wrap in markdown code blocks or include introductory/concluding text.
|
||||
|
||||
JSON Schema:
|
||||
{
|
||||
"reasoning": "<step-by-step technical analysis of data flow and sinks>",
|
||||
"flagged": "<'Yes' if a vulnerability from the target list is detected, otherwise 'No'>",
|
||||
"category": "<Exact category name from the list above if flagged, otherwise 'None'>",
|
||||
"cwe": "<Associated CWE string like 'CWE-89' if flagged, otherwise 'None'>"
|
||||
}
|
||||
|
||||
Code to analyze:
|
||||
[INSERT_CODE_HERE]
|
||||
@@ -0,0 +1 @@
|
||||
bandit==1.9.4
|
||||
+1927
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,106 @@
|
||||
# Validation artifacts
|
||||
|
||||
This directory contains reproducible checks and the executed results used to
|
||||
validate the obfuscated dataset condition.
|
||||
|
||||
## Automated pipeline test
|
||||
|
||||
The test starts a local mock OpenAI-compatible API and runs the real
|
||||
`run_sast_eval.py` CLI against four benchmark samples. It covers:
|
||||
|
||||
- valid JSON
|
||||
- fenced JSON
|
||||
- malformed JSON followed by a repair request
|
||||
- a `429` retry
|
||||
- SQLite persistence
|
||||
- CSV export
|
||||
- `--report` without API calls
|
||||
- dry-run without an API key
|
||||
|
||||
Run it with the standard library only:
|
||||
|
||||
```bash
|
||||
python3 -m unittest validation/test_pipeline.py -v
|
||||
```
|
||||
|
||||
Current result: **3 tests passed**.
|
||||
|
||||
## Bandit comparison
|
||||
|
||||
Bandit was installed in a `uv` virtual environment:
|
||||
|
||||
```bash
|
||||
uv venv --python 3.14 .venv
|
||||
uv pip install --python .venv/bin/python -r requirements-dev.txt
|
||||
```
|
||||
|
||||
Commands:
|
||||
|
||||
```bash
|
||||
.venv/bin/bandit -r Samples -f json -o validation/bandit/samples.json
|
||||
.venv/bin/bandit -r Samples_Obfuscated_v2 -f json -o validation/bandit/obfuscated_v2.json
|
||||
```
|
||||
|
||||
Result:
|
||||
|
||||
- Original: **89 findings**
|
||||
- Obfuscated v2: **86 findings**
|
||||
- **86 findings identical** by file, rule, severity, and confidence
|
||||
- **No new findings**
|
||||
- The only difference is **3 B608** findings in
|
||||
`BenchmarkTest00192.py`, `BenchmarkTest00284.py`, and
|
||||
`BenchmarkTest00286.py`
|
||||
|
||||
B608 is a string-pattern rule for SQL-looking text. The obfuscator replaces SQL
|
||||
strings with generic `msg` tokens, so those findings disappear. The SQL sink
|
||||
and data flow remain. With B608 skipped, both directories produce exactly
|
||||
**86/86** identical findings.
|
||||
|
||||
See `bandit_comparison.txt` for the full report and `bandit/*.json` for raw
|
||||
Bandit output.
|
||||
|
||||
## DeepSeek comparison
|
||||
|
||||
Two runs were executed with `opencode-go/deepseek-v4.1-flash` and
|
||||
`prompts/sast_v1.txt`:
|
||||
|
||||
| Metric | Original | Obfuscated v2 |
|
||||
|---|---:|---:|
|
||||
| TP | 46 | 46 |
|
||||
| FP | 13 | 18 |
|
||||
| TN | 98 | 93 |
|
||||
| FN | 0 | 0 |
|
||||
| Accuracy | 91.7% | 88.5% |
|
||||
| Precision | 78.0% | 71.9% |
|
||||
| Recall | 100% | 100% |
|
||||
| Category accuracy (TP) | 100% | 100% |
|
||||
| CWE accuracy (TP) | 100% | 100% |
|
||||
| Total tokens | 381,410 | 472,990 |
|
||||
| API calls | 201 | 202 |
|
||||
|
||||
Paired McNemar test on the 157 in-scope samples: **p = 0.125**, so the +5
|
||||
false-positive difference is not statistically significant in this single run.
|
||||
|
||||
Caveat: the original run used `--workers 4` and the obfuscated run used
|
||||
`--workers 1`, so wall-clock times are not comparable. See
|
||||
`deepseek_comparison.md` for the per-category breakdown, new false positives,
|
||||
and the recommended replication.
|
||||
|
||||
Raw per-sample outputs are in `deepseek/*.csv`; `deepseek/summary.csv` contains
|
||||
the comparison table in machine-readable form.
|
||||
|
||||
## Contents
|
||||
|
||||
```text
|
||||
validation/
|
||||
├── test_pipeline.py # mock-API end-to-end test
|
||||
├── bandit_comparison.txt # human-readable Bandit diff
|
||||
├── bandit/
|
||||
│ ├── samples.json # raw Bandit JSON, original
|
||||
│ └── obfuscated_v2.json # raw Bandit JSON, obfuscated
|
||||
├── deepseek_comparison.md # original vs obfuscated analysis
|
||||
└── deepseek/
|
||||
├── deepseek-original.csv # per-sample original results
|
||||
├── deepseek-v4.1-flash.csv # per-sample obfuscated results
|
||||
└── summary.csv # comparison metrics
|
||||
```
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
||||
Bandit comparison: Samples vs Samples_Obfuscated_v2
|
||||
Bandit 1.9.4, Python 3.14.9, run inside .venv created with uv
|
||||
|
||||
Original findings: 89
|
||||
Obfuscated findings: 86
|
||||
Identical finding keys: 86
|
||||
Only in original: 3
|
||||
Only in obfuscated: 0
|
||||
|
||||
Differences (file, rule, severity, confidence):
|
||||
only original: ('BenchmarkTest00192.py', 'B608', 'MEDIUM', 'LOW') x1
|
||||
only original: ('BenchmarkTest00284.py', 'B608', 'MEDIUM', 'LOW') x1
|
||||
only original: ('BenchmarkTest00286.py', 'B608', 'MEDIUM', 'LOW') x1
|
||||
|
||||
All other rules match exactly. Line numbers were not compared because ast.unparse reformats the code.
|
||||
The 3 missing findings are Bandit B608 (hardcoded SQL expression) on:
|
||||
BenchmarkTest00192.py: Possible SQL injection vector through string-based query construction.
|
||||
BenchmarkTest00284.py: Possible SQL injection vector through string-based query construction.
|
||||
BenchmarkTest00286.py: Possible SQL injection vector through string-based query construction.
|
||||
|
||||
Reason: v2 replaces SQL text with generic msg tokens, so Bandit no longer recognises the string as SQL. The execute() sink and data flow remain.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
||||
metric,original,obfuscated_v2
|
||||
true_positives,46,46
|
||||
false_positives,13,18
|
||||
true_negatives,98,93
|
||||
false_negatives,0,0
|
||||
flag_accuracy,0.917,0.885
|
||||
precision,0.780,0.719
|
||||
recall,1.000,1.000
|
||||
category_accuracy_tp,1.000,1.000
|
||||
cwe_accuracy_tp,1.000,1.000
|
||||
prompt_tokens,166504,145474
|
||||
completion_tokens,214906,327516
|
||||
total_tokens,381410,472990
|
||||
api_calls,201,202
|
||||
workers,4,1
|
||||
|
@@ -0,0 +1,101 @@
|
||||
# DeepSeek comparison: original vs obfuscated v2
|
||||
|
||||
Model: `opencode-go/deepseek-v4.1-flash`
|
||||
Prompt: `prompts/sast_v1.txt`
|
||||
Labels: `data/expectedresults-0.1.csv`
|
||||
In-scope samples: 157 (43 out-of-scope samples excluded from flag metrics)
|
||||
|
||||
| Metric | Original (`Samples`) | Obfuscated v2 |
|
||||
|---|---:|---:|
|
||||
| TP | 46 | 46 |
|
||||
| FP | 13 | 18 |
|
||||
| TN | 98 | 93 |
|
||||
| FN | 0 | 0 |
|
||||
| Flag accuracy | 91.7% | 88.5% |
|
||||
| Precision | 78.0% | 71.9% |
|
||||
| Recall | 100% | 100% |
|
||||
| Category accuracy (TP) | 100% (46/46) | 100% (46/46) |
|
||||
| CWE accuracy (TP) | 100% (46/46) | 100% (46/46) |
|
||||
| Calls | 201 | 202 |
|
||||
| Prompt tokens | 166,504 | 145,474 |
|
||||
| Completion tokens | 214,906 | 327,516 |
|
||||
| Total tokens | 381,410 | 472,990 |
|
||||
| Workers | 4 | 1 |
|
||||
| Wall time | ~11 min | ~56 min |
|
||||
|
||||
Wall time is not comparable because the original run used four workers and the
|
||||
obfuscated run used one.
|
||||
|
||||
## Paired prediction analysis
|
||||
|
||||
Restricting to the 157 in-scope samples:
|
||||
|
||||
| Outcome | Count |
|
||||
|---|---:|
|
||||
| Both correct | 138 |
|
||||
| Original correct, obfuscated wrong | 6 |
|
||||
| Original wrong, obfuscated correct | 1 |
|
||||
| Both wrong | 12 |
|
||||
|
||||
Net change: +5 false positives in the obfuscated condition.
|
||||
Exact McNemar test: **p = 0.125** (not statistically significant at α = 0.05).
|
||||
|
||||
## Per-category results (obfuscated v2)
|
||||
|
||||
| Category | TP | FP | TN | FN |
|
||||
|---|---:|---:|---:|---:|
|
||||
| weakrand | 14 | 1 | 43 | 0 |
|
||||
| pathtraver | 13 | 5 | 8 | 0 |
|
||||
| xss | 8 | 2 | 8 | 0 |
|
||||
| deserialization | 4 | 2 | 5 | 0 |
|
||||
| xpathi | 4 | 4 | 20 | 0 |
|
||||
| sqli | 1 | 0 | 2 | 0 |
|
||||
| trustbound | 1 | 2 | 3 | 0 |
|
||||
| xxe | 1 | 2 | 3 | 0 |
|
||||
| cmdi | 0 | 0 | 1 | 0 |
|
||||
|
||||
## New in-scope false positives in the obfuscated run
|
||||
|
||||
These six samples changed from correct `No` to `Yes`:
|
||||
|
||||
- `BenchmarkTest00024` (xpathi)
|
||||
- `BenchmarkTest00293` (xxe)
|
||||
- `BenchmarkTest00477` (weakrand)
|
||||
- `BenchmarkTest00539` (xxe)
|
||||
- `BenchmarkTest00677` (xpathi)
|
||||
- `BenchmarkTest01023` (xpathi)
|
||||
|
||||
One original false positive became correct:
|
||||
|
||||
- `BenchmarkTest00498` (trustbound)
|
||||
|
||||
Qualitative review suggests the difference is mixed:
|
||||
|
||||
- `00024`: the model confused two obfuscated ConfigParser keys (`m009-57764` vs `m00a-57764`) and lost the constant-propagation fact that the XPath value comes from the hardcoded key, not the cookie.
|
||||
- `01023`: the original safe reasoning relied on the fixed first path segment of `/benchmark/xpathi-01/...`; the generic `/route_153` route removed that cue.
|
||||
- `00293`, `00539`, `00477`, `00677`: the model changed its judgment on essentially the same code structure (e.g. ExpatParser defaults, `secrets.randbits(32)`, `replace("'", "'")`). These look like run-to-run reasoning variance rather than a direct obfuscation effect.
|
||||
|
||||
## Interpretation
|
||||
|
||||
- Obfuscation did **not** reduce detection: TP, FN, category accuracy, and CWE accuracy are identical.
|
||||
- The obfuscated condition produced five additional false positives, reducing flag accuracy by 3.2 percentage points and precision by 6.1 points.
|
||||
- The paired difference is not statistically significant in this single run (McNemar p = 0.125).
|
||||
- Completion-token use was substantially higher in the obfuscated run, but this may reflect both harder-to-read identifiers and run variance.
|
||||
- The two runs also differed in worker count, so a replication with identical settings is needed before attributing the difference to obfuscation.
|
||||
|
||||
## Recommended next step
|
||||
|
||||
Run at least one replicate of each condition with identical settings, for example:
|
||||
|
||||
```bash
|
||||
python3 run_sast_eval.py --input Samples \
|
||||
--model opencode-go/deepseek-v4.1-flash \
|
||||
--run-id deepseek-original-rep2 --workers 4
|
||||
|
||||
python3 run_sast_eval.py --input Samples_Obfuscated_v2 \
|
||||
--model opencode-go/deepseek-v4.1-flash \
|
||||
--run-id deepseek-v2-rep2 --workers 4
|
||||
```
|
||||
|
||||
Then compare the replicate spread before making a claim about obfuscation
|
||||
degrading performance.
|
||||
@@ -0,0 +1,293 @@
|
||||
#!/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(flagged: str, category: str, cwe: str) -> dict[str, str]:
|
||||
return {
|
||||
"reasoning": "mock analysis",
|
||||
"flagged": flagged,
|
||||
"category": category,
|
||||
"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("No", "None", "None")) + "\n```"
|
||||
elif sample == "BenchmarkTest00002":
|
||||
text = json.dumps(_result("Yes", "Path Traversal", "CWE-22"))
|
||||
else:
|
||||
text = json.dumps(_result("No", "None", "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)
|
||||
|
||||
def test_json_parser_and_normalisation(self) -> None:
|
||||
parsed = parse_result(
|
||||
'Here is the result:\n'
|
||||
'{"reasoning": "x", "flagged": "Yes", '
|
||||
'"category": "Path Traversal (CWE-22)", "cwe": "22",}'
|
||||
)
|
||||
self.assertTrue(parsed.ok)
|
||||
self.assertEqual(parsed.flagged, "Yes")
|
||||
self.assertEqual(parsed.category, "pathtraver")
|
||||
self.assertEqual(parsed.cwe, "CWE-22")
|
||||
|
||||
fenced = parse_result(
|
||||
'```json\n{"reasoning": "x", "flagged": "No", '
|
||||
'"category": "None", "cwe": "None"}\n```'
|
||||
)
|
||||
self.assertTrue(fenced.ok)
|
||||
self.assertEqual(fenced.flagged, "No")
|
||||
|
||||
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()
|
||||
Reference in new issue
Block a user