File size: 10,961 Bytes
1340dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()