Helinity's picture
Release v0.1.0: sanitized Python security research benchmark
1340dfb
Raw History Blame Contribute Delete
11 kB
"""Score JSON predictions or static-analysis findings against one research split."""
import argparse
from collections import Counter, defaultdict
from hashlib import sha256
import json
from pathlib import Path
import re
from scripts.generate_dataset import write_dataset
from scripts.validate_dataset import read_records, reject_duplicate_keys
from .build import OUTPUT, json_bytes
from .leakage import SPLITS
LABELS = {"secure", "insecure"}
CWE_FORMAT = re.compile(r"CWE-[1-9][0-9]*")
KEYWORDS = re.compile(
r"shell\s*=\s*True|\bpickle\.loads\(|\bshelve\.open\(|\bCERT_NONE\b"
r"|\brandom\.(?:randbytes|randrange|Random)\b|\btoken=%s|headers=%r"
r"|\baccess_token\b|return 5\d\d,\s*\{[^\n]+str\(|"
r"""f["'][^\n]*SELECT\b[^\n]*\{""",
)
def lexical_baseline(rows):
"""An intentionally simple code-only smoke-test baseline."""
return {"predictions": [
{"sample_id": row["sample_id"], "label": "insecure" if KEYWORDS.search(row["code"]) else "secure"}
for row in rows
]}
def location_matches(finding, locations):
return any(
finding.get("path") == position["path"]
and type(finding.get("line")) is int
and position["start_line"] <= finding["line"] <= position["end_line"]
for position in locations
)
def predictions_for(rows, document, match_location):
if not isinstance(document, dict) or set(document) not in ({"predictions"}, {"findings"}):
raise ValueError("Input must contain exactly one 'predictions' or 'findings' list")
mode = next(iter(document))
entries = document[mode]
if not isinstance(entries, list):
raise ValueError(f"'{mode}' must be a list")
by_id = {row["sample_id"]: row for row in rows}
labels = {}
ignored = []
seen = set()
if mode == "predictions" and match_location:
raise ValueError("Location matching requires findings input")
for entry in entries:
if not isinstance(entry, dict) or not isinstance(entry.get("sample_id"), str):
raise ValueError("Each entry requires a sample_id string")
sample_id = entry["sample_id"]
if sample_id not in by_id:
raise ValueError(f"Unknown or out-of-split sample_id {sample_id!r}")
if mode == "predictions":
if entry.keys() != {"sample_id", "label"} or not isinstance(entry["label"], str) or entry["label"] not in LABELS:
raise ValueError(f"{sample_id}: invalid prediction")
if sample_id in labels:
raise ValueError(f"{sample_id}: duplicate prediction")
labels[sample_id] = entry["label"]
continue
fields = {"sample_id", "cwe_id"}
with_position = entry.keys() == fields | {"path", "line"}
if entry.keys() != fields and not with_position:
raise ValueError(f"{sample_id}: invalid finding fields")
cwe = entry["cwe_id"]
if not isinstance(cwe, str) or not CWE_FORMAT.fullmatch(cwe):
raise ValueError(f"{sample_id}: invalid finding CWE ID")
if with_position and (
not isinstance(entry["path"], str) or not entry["path"].strip()
or type(entry["line"]) is not int or entry["line"] < 1
):
raise ValueError(f"{sample_id}: invalid finding location")
key = sample_id, cwe, entry.get("path"), entry.get("line")
if key in seen:
raise ValueError(f"{sample_id}: duplicate finding")
seen.add(key)
row = by_id[sample_id]
expected = row["vulnerable_lines"]
if cwe != row["cwe_id"]:
ignored.append({**entry, "reason": "out_of_scope_cwe"})
elif match_location and expected and not location_matches(entry, expected):
ignored.append({**entry, "reason": "missing_or_nonmatching_location"})
else:
labels[sample_id] = "insecure"
if mode == "predictions" and labels.keys() != by_id.keys():
raise ValueError(f"Missing predictions for {len(by_id.keys() - labels.keys())} selected samples")
return {sample_id: labels.get(sample_id, "secure") for sample_id in by_id}, ignored, mode
def ratio(numerator, denominator):
return numerator / denominator if denominator else None
def metrics(observations):
counts = Counter({"tp": 0, "tn": 0, "fp": 0, "fn": 0})
for expected, predicted in observations:
if expected == "insecure":
counts["tp" if predicted == "insecure" else "fn"] += 1
else:
counts["fp" if predicted == "insecure" else "tn"] += 1
tp, tn, fp, fn = (counts[key] for key in ("tp", "tn", "fp", "fn"))
recall = ratio(tp, tp + fn)
specificity = ratio(tn, tn + fp)
return {
"confusion": dict(counts),
"positive_support": tp + fn,
"negative_support": tn + fp,
"precision": ratio(tp, tp + fp),
"recall": recall,
"f1": ratio(2 * tp, 2 * tp + fp + fn),
"balanced_accuracy": (recall + specificity) / 2 if recall is not None and specificity is not None else None,
"false_positive_rate": ratio(fp, fp + tn),
"false_negative_rate": ratio(fn, fn + tp),
}
def evaluate(rows, document, match_location=False):
if not rows or len({row["sample_id"] for row in rows}) != len(rows):
raise ValueError("Ground truth must have distinct sample IDs and at least one record")
labels, ignored, mode = predictions_for(rows, document, match_location)
by_cwe = defaultdict(list)
pairs = defaultdict(dict)
per_sample = []
negatives = []
for row in rows:
sample_id = row["sample_id"]
comparison = row["label"], labels[sample_id]
by_cwe[row["cwe_id"]].append(comparison)
if row["pair_id"]:
if comparison[0] in pairs[row["pair_id"]]:
raise ValueError(f"Repeated label for evaluation pair {row['pair_id']!r}")
pairs[row["pair_id"]][comparison[0]] = comparison[1]
if row["hard_negative"]:
negatives.append(comparison)
per_sample.append({
"sample_id": sample_id, "cwe_id": row["cwe_id"], "pair_id": row["pair_id"],
"hard_negative": row["hard_negative"],
"verification_status": row["verification_status"],
"expected_locations": row["vulnerable_lines"],
"expected": comparison[0], "predicted": comparison[1],
"outcome": "correct" if comparison[0] == comparison[1] else (
"false_negative" if comparison[0] == "insecure" else "false_positive"
),
})
pair_outcomes = Counter({"both_correct": 0, "both_flagged": 0, "both_missed": 0, "inverted": 0})
pair_details = []
for pair_id, predictions in sorted(pairs.items()):
if predictions.keys() != LABELS:
raise ValueError(f"Incomplete evaluation pair {pair_id!r}")
outcome = {
("insecure", "secure"): "both_correct",
("insecure", "insecure"): "both_flagged",
("secure", "secure"): "both_missed",
("secure", "insecure"): "inverted",
}[predictions["insecure"], predictions["secure"]]
pair_outcomes[outcome] += 1
pair_details.append({"pair_id": pair_id, "outcome": outcome})
return {
"input_mode": mode,
"location_matching": match_location,
"sample_count": len(rows),
"overall": metrics((row["expected"], row["predicted"]) for row in per_sample),
"per_cwe": {cwe: metrics(items) for cwe, items in sorted(by_cwe.items())},
"paired_consistency": {
"support": len(pairs),
"both_correct_rate": ratio(pair_outcomes["both_correct"], len(pairs)),
"outcomes": dict(pair_outcomes),
"details": pair_details,
},
"hard_negatives": {
"support": len(negatives),
"false_positives": sum(predicted == "insecure" for _, predicted in negatives),
"false_positive_rate": metrics(negatives)["false_positive_rate"],
},
"samples": per_sample,
"errors": [row for row in per_sample if row["outcome"] != "correct"],
"ignored_findings": ignored,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--scope", choices=("official", "official_3c1", "benchmark", "corpus"), default="official",
help="official enforces Phase 3B evidence; other scopes are historical or exploratory")
parser.add_argument("--split", choices=tuple(SPLITS), default="test")
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument("--input", type=Path, help="JSON predictions or findings")
source.add_argument("--baseline", action="store_true", help="run the code-only lexical baseline")
parser.add_argument("--match-location", action="store_true", help="require positive finding offsets when known")
parser.add_argument("--output", type=Path, help="save report JSON instead of writing it to stdout")
args = parser.parse_args()
try:
eligibility_hash = None
if args.scope == "official_3c1":
from .expansion.release import official_data
source_data, eligibility_hash = official_data(args.split)
elif args.scope == "official":
from .harden import official_data
source_data, eligibility_hash = official_data(args.split)
else:
source_data = (OUTPUT / args.scope / f"{args.split}.jsonl").read_bytes()
rows = [row for _, row in read_records(source_data)]
document = lexical_baseline(rows) if args.baseline else json.loads(
args.input.read_text(encoding="utf-8"), object_pairs_hook=reject_duplicate_keys,
)
report = {
"scope": args.scope,
"split": args.split,
"ground_truth_sha256": sha256(source_data).hexdigest(),
"baseline": "lexical_keywords_v1" if args.baseline else None,
**evaluate(rows, document, args.match_location),
}
if args.scope == "official_3c1":
report["eligibility_sha256"] = eligibility_hash
report["evidence_policy"] = "phase3c1"
report["scenario_family_count"] = len({row["scenario_family_id"] for row in rows})
report["leakage_group_count"] = len({row["leakage_group_id"] for row in rows})
elif args.scope == "official":
report["eligibility_sha256"] = eligibility_hash
report["evidence_policy"] = "phase3b"
elif args.scope == "corpus":
report["evaluation_use"] = "exploratory_includes_unverified_labels"
content = json_bytes(report)
if args.output:
write_dataset(args.output, content)
else:
print(content.decode("utf-8"), end="")
except (OSError, ValueError) as error:
parser.exit(1, f"{error}\n")
if __name__ == "__main__":
main()