File size: 20,579 Bytes
f459705
 
 
 
 
157d7a8
f459705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157d7a8
f459705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157d7a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b861a3e
 
 
 
157d7a8
 
 
f459705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157d7a8
f459705
 
 
 
 
 
 
 
 
 
 
 
 
157d7a8
 
f459705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157d7a8
f459705
157d7a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f459705
 
 
 
157d7a8
f459705
 
 
 
 
 
 
 
 
b861a3e
157d7a8
f459705
 
 
157d7a8
f459705
 
 
 
 
 
 
 
 
 
 
157d7a8
f459705
 
 
157d7a8
f459705
 
 
 
 
 
 
157d7a8
f459705
 
 
 
 
 
 
 
 
 
 
 
157d7a8
 
 
 
 
 
 
 
 
 
f459705
 
157d7a8
 
 
 
f459705
157d7a8
 
 
 
 
 
f459705
157d7a8
 
 
 
 
 
 
 
f459705
 
 
 
 
 
157d7a8
 
f459705
 
 
 
 
 
 
 
 
 
 
 
 
 
157d7a8
 
 
 
 
 
 
 
 
 
 
 
 
 
f459705
157d7a8
 
 
 
 
 
 
 
 
 
 
 
1add04d
 
b861a3e
1add04d
157d7a8
f459705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157d7a8
f459705
 
 
 
 
 
 
 
 
157d7a8
 
 
 
 
 
f459705
157d7a8
f459705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157d7a8
f459705
 
 
157d7a8
 
f459705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/usr/bin/env python3
"""Run and score the public Perch method-pair benchmarks.

Standard-library only. The command adapter is a persistent NDJSON process: it
receives one JSON object per line and returns one {"score": probability} per line.
Current scan mode uses question-pack.json exported from public Perch scan.yaml.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import shlex
import subprocess
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


DATASET_URL = {
    domain: f"https://huggingface.co/datasets/perchscan/{domain}-pairs-public/resolve/main/benchmark.jsonl"
    for domain in ("bug", "security")
}
LEGACY_QUESTION = {
    "bug": {
        "type": "noul",
        "instructions": "Does this method contain a concrete behavioral bug a caller can reach?",
        "criteria": {
            "true": "A reachable input makes the method violate its visible contract by returning a wrong result, leaving wrong state, or causing an unintended failure.",
            "false": "No concrete reachable case is supported by the method and supplied context. A possible-looking pattern alone is not enough.",
        },
    },
    "security": {
        "type": "noul",
        "instructions": "Does this method contain a concrete security vulnerability an attacker can reach?",
        "criteria": {
            "true": "A concrete path crosses a security boundary and can be exploited; name a reachable source, sensitive operation, and missing or incorrect protection.",
            "false": "No concrete reachable case is supported by the method and supplied context. A possible-looking pattern alone is not enough.",
        },
    },
}


def load_pack(path: Path) -> dict:
    pack = json.loads(path.read_text())
    body = {key: pack[key] for key in ("schema_version", "source", "source_sha256", "domains")}
    digest = hashlib.sha256(json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
    if (pack.get("schema_version") != 1 or pack.get("pack_sha256") != digest
            or pack.get("protocol_id") != f"perch-scan-{digest[:12]}"
            or pack.get("binary_protocol_id") != f"perch-scan-binary-{digest[:12]}"):
        raise ValueError("Question pack checksum or protocol ID does not match its contents")
    for domain in ("bug", "security"):
        if not pack["domains"].get(domain):
            raise ValueError(f"Question pack has no {domain} questions")
        for question in pack["domains"][domain]:
            if question["where"] != "**/*":
                raise ValueError(f"Benchmark does not yet support path selector {question['where']}")
    return pack


def scan_questions(pack: dict, domain: str, language: str) -> list[dict]:
    if not language:
        raise ValueError("Benchmark pair has no language for question selection")
    normalized = {"csharp": "c_sharp"}.get(language, language)
    return [q for q in pack["domains"][domain]
            if q["language"] is None or normalized in ([q["language"]] if isinstance(q["language"], str) else q["language"])]


def detection_questions(questions: list[dict], domain: str) -> list[dict]:
    issue_type = "defect" if domain == "bug" else "security"
    return [q for q in questions if q["type"] == "noul" and q["issue"] and q["issue"]["type"] == issue_type]


def raised_score(question: dict, true_probability: object) -> float:
    score = probability(true_probability)
    return 1 - score if question["issue"].get("on") is False else score


def scan_result(question_scores: dict[str, float], questions: list[dict], domain: str, threshold: float) -> tuple[float, bool]:
    relevant = detection_questions(questions, domain)
    expected = {q["name"] for q in relevant}
    if set(question_scores) != expected:
        raise ValueError(f"Question scores differ from selected scan pack: {expected ^ set(question_scores)}")
    score = max(question_scores.values(), default=0.0)
    # Use the same per-question floor as a Perch scan. --threshold can only
    # raise that floor for the whole run.
    alert = any(question_scores[q["name"]] > max(threshold, (q.get("min") or 0) / 100)
                for q in relevant)
    return score, alert


def dataset_bytes(domain: str, path: Path | None) -> bytes:
    if path is not None:
        return (path / "benchmark.jsonl" if path.is_dir() else path).read_bytes()
    with urlopen(DATASET_URL[domain], timeout=120) as response:
        return response.read()


def load_pairs(domain: str, path: Path | None) -> tuple[list[dict], str]:
    raw = dataset_bytes(domain, path)
    pairs = [json.loads(line) for line in raw.splitlines() if line]
    if not pairs:
        raise ValueError("Benchmark contains no pairs")
    ids = set()
    for pair in pairs:
        if pair["domain"] != domain or pair["pair_id"] in ids:
            raise ValueError("Wrong domain or duplicate pair ID in benchmark")
        ids.add(pair["pair_id"])
        for role in ("before", "after"):
            if pair[role]["labels"][domain] not in (0, 1):
                raise ValueError(f"Invalid {domain} label for {pair['pair_id']}:{role}")
    return pairs, hashlib.sha256(raw).hexdigest()


def probability(value: object) -> float:
    if isinstance(value, bool):
        raise ValueError("Score must be a number, not a boolean")
    score = float(value)
    if not math.isfinite(score) or not 0 <= score <= 1:
        raise ValueError(f"Score must be a finite probability in [0, 1]: {value!r}")
    return score


def prediction_scores(path: Path, pairs: list[dict], domain: str,
                      require_complete: bool) -> dict[tuple[str, str], dict]:
    expected = {(pair["pair_id"], role) for pair in pairs for role in ("before", "after")}
    scores = {}
    if not path.exists():
        if require_complete:
            raise FileNotFoundError(path)
        return scores
    for line in path.read_text().splitlines():
        if not line:
            continue
        row = json.loads(line)
        key = (row["pair_id"], row["role"])
        if key not in expected or key in scores or row.get("domain", domain) != domain:
            raise ValueError(f"Unexpected or duplicate prediction: {key}")
        row["score"] = probability(row["score"])
        scores[key] = row
    if require_complete and scores.keys() != expected:
        missing = expected - scores.keys()
        raise ValueError(f"Predictions are missing {len(missing)} method sides")
    return scores


def average_precision(items: list[tuple[int, float]]) -> float:
    positives = sum(label for label, _ in items)
    if not positives:
        return 0.0
    ordered = sorted(items, key=lambda item: item[1], reverse=True)
    found = total = 0
    i = 0
    while i < len(ordered):
        j = i + 1
        while j < len(ordered) and ordered[j][1] == ordered[i][1]:
            j += 1
        positives_at_score = sum(label for label, _ in ordered[i:j])
        found += positives_at_score
        total += found / j * positives_at_score
        i = j
    return total / positives


def report(pairs: list[dict], scores: dict[tuple[str, str], dict], domain: str,
           digest: str, model_revision: str, protocol_id: str,
           threshold: float, pack: dict | None = None) -> dict:
    items = []
    for pair in pairs:
        for role in ("before", "after"):
            row = scores[pair["pair_id"], role]
            if pack and protocol_id in (pack["protocol_id"], pack["binary_protocol_id"]):
                if row.get("pack_sha256") != pack["pack_sha256"]:
                    raise ValueError("Prediction was made with a different question pack")
                questions = scan_questions(pack, domain, pair["language"])
                score, alert = scan_result(row.get("question_scores", {}), questions, domain, threshold)
                if abs(score - row["score"]) > 1e-9:
                    raise ValueError("Prediction's aggregate score does not match its question scores")
            else:
                score, alert = row["score"], row["score"] >= threshold
            items.append((pair[role]["labels"][domain], score, alert))
    tp = sum(label == 1 and alert for label, _, alert in items)
    fp = sum(label == 0 and alert for label, _, alert in items)
    fn = sum(label == 1 and not alert for label, _, alert in items)
    tn = sum(label == 0 and not alert for label, _, alert in items)
    eligible = correct = ties = 0
    for pair in pairs:
        if pair["before"]["labels"][domain] == 1 and pair["after"]["labels"][domain] == 0:
            eligible += 1
            before, after = scores[pair["pair_id"], "before"]["score"], scores[pair["pair_id"], "after"]["score"]
            correct += before > after
            ties += before == after
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    return {
        "domain": domain,
        "model_revision": model_revision,
        "protocol_id": protocol_id,
        "threshold": threshold,
        "alert_rule": "any issue score > max(run threshold, question min)" if pack and protocol_id in (pack["protocol_id"], pack["binary_protocol_id"]) else "score >= threshold",
        "question_pack_sha256": pack["pack_sha256"] if pack and protocol_id in (pack["protocol_id"], pack["binary_protocol_id"]) else None,
        "benchmark_sha256": digest,
        "benchmark_pairs": len(pairs),
        "benchmark_methods": len(items),
        "average_precision": average_precision([(label, score) for label, score, _ in items]),
        "precision": precision,
        "recall": recall,
        "f1": 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0,
        "false_positives_per_true_positive": fp / tp if tp else None,
        "confusion": {"tp": tp, "fp": fp, "tn": tn, "fn": fn},
        "vulnerable_or_buggy_before_above_fixed_after": {
            "correct": correct, "ties": ties, "eligible": eligible,
        },
    }


def jev_answers(state: dict, questions: dict, model: str, api_url: str) -> dict:
    key = os.getenv("TYPESAFE_API_KEY") or os.getenv("PERCH_API_KEY")
    if not key:
        raise RuntimeError("Set TYPESAFE_API_KEY or PERCH_API_KEY to run Jev")
    payload = json.dumps({"model": model, "state": state, "questions": questions}).encode()
    for attempt in range(4):
        request = Request(api_url, data=payload, method="POST", headers={
            "Authorization": f"Bearer {key}", "Content-Type": "application/json",
        })
        try:
            with urlopen(request, timeout=120) as response:
                answer = json.load(response)
            return answer["answers"]
        except HTTPError as exc:
            if exc.code not in (429, 500, 502, 503, 504) or attempt == 3:
                raise RuntimeError(f"Jev request failed with HTTP {exc.code}") from None
            delay = exc.headers.get("Retry-After")
            time.sleep(float(delay) if delay and delay.isdigit() else 2 ** attempt)
        except URLError:
            if attempt == 3:
                raise RuntimeError("Jev request failed after four network attempts") from None
            time.sleep(2 ** attempt)
    raise AssertionError("unreachable")


def command_score(command: subprocess.Popen, request: dict) -> float:
    assert command.stdin and command.stdout
    command.stdin.write(json.dumps(request, ensure_ascii=False) + "\n")
    command.stdin.flush()
    line = command.stdout.readline()
    if not line:
        raise RuntimeError("Model adapter stopped before returning a score")
    return probability(json.loads(line)["score"])


def run(args: argparse.Namespace) -> None:
    pairs, digest = load_pairs(args.domain, args.dataset)
    pack = load_pack(args.question_pack)
    scan_protocols = (pack["protocol_id"], pack["binary_protocol_id"])
    mode = args.mode or ("broad" if args.protocol_id == "perch-broad-v1" else
                         "native" if args.protocol_id and args.protocol_id not in scan_protocols else "scan")
    if args.scorer == "jev":
        if mode == "native":
            raise ValueError("Jev requires scan or broad question mode")
        revision = args.model_revision or "jev-1.13.0"
        protocol = pack["protocol_id"] if mode == "scan" else "perch-broad-v1"
        if args.protocol_id and args.protocol_id != protocol:
            raise ValueError("Jev protocol ID does not match the selected question mode")
    else:
        if not args.command or not args.model_revision:
            raise ValueError("Command scorer requires --command and --model-revision")
        revision = args.model_revision
        protocol = args.protocol_id or (pack["binary_protocol_id"] if mode == "scan" else "perch-broad-v1")
        if mode == "scan" and protocol != pack["binary_protocol_id"]:
            raise ValueError("Scan protocol ID must match the question pack")
        if mode == "native" and not args.protocol_id:
            raise ValueError("Native scorer requires its own --protocol-id")
    if args.predictions.exists():
        for line in args.predictions.read_text().splitlines():
            if line:
                row = json.loads(line)
                if row.get("model_revision") != revision or row.get("protocol_id") != protocol:
                    raise ValueError("Existing prediction file uses another model or protocol")
                if mode == "scan" and row.get("pack_sha256") != pack["pack_sha256"]:
                    raise ValueError("Existing predictions use another scan question pack")
    existing = prediction_scores(args.predictions, pairs, args.domain, False)
    pending = [(pair, role) for pair in pairs for role in ("before", "after")
               if (pair["pair_id"], role) not in existing]
    if args.limit:
        pending = pending[:args.limit]
    command = None
    if args.scorer == "command" and pending:
        command = subprocess.Popen(shlex.split(args.command), stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE, text=True, bufsize=1)
    args.predictions.parent.mkdir(parents=True, exist_ok=True)
    try:
        with args.predictions.open("a") as output:
            for index, (pair, role) in enumerate(pending, 1):
                state = pair[role]["state"]
                if mode == "scan":
                    selected = scan_questions(pack, args.domain, pair["language"])
                    if args.scorer == "jev":
                        answers = jev_answers(state, {q["name"]: q["question"] for q in selected}, revision, args.api_url)
                        question_scores = {q["name"]: raised_score(q, answers[q["name"]]["noul"])
                                           for q in detection_questions(selected, args.domain)}
                    else:
                        question_scores = {}
                        for q in detection_questions(selected, args.domain):
                            request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
                                       "language": pair["language"], "source": pair[role]["source"],
                                       "state": state, "question": q["question"], "question_name": q["name"]}
                            question_scores[q["name"]] = raised_score(q, command_score(command, request))
                    score, alert = scan_result(question_scores, selected, args.domain, args.threshold)
                else:
                    question = LEGACY_QUESTION[args.domain]
                    if args.scorer == "jev":
                        name = "bug_any" if args.domain == "bug" else "security_any"
                        score = probability(jev_answers(state, {name: question}, revision, args.api_url)[name]["noul"])
                    else:
                        request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
                                   "language": pair.get("language"), "source": pair[role]["source"],
                                   "state": state, "question": question}
                        score = command_score(command, request)
                result = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
                          "score": score, "model_revision": revision, "protocol_id": protocol}
                if mode == "scan":
                    result.update(question_scores=question_scores, alert=alert,
                                  threshold=args.threshold,
                                  alert_rule="any issue score > max(run threshold, question min)",
                                  pack_sha256=pack["pack_sha256"])
                output.write(json.dumps(result) + "\n")
                output.flush()
                if index % 100 == 0 or index == len(pending):
                    print(f"Scored {len(existing) + index}/{2 * len(pairs)} method sides", file=sys.stderr)
    finally:
        if command:
            command.stdin.close()
            try:
                command.wait(timeout=30)
            except subprocess.TimeoutExpired:
                command.terminate()
                command.wait(timeout=5)
            finally:
                command.stdout.close()
    scores = prediction_scores(args.predictions, pairs, args.domain, False)
    if len(scores) != 2 * len(pairs):
        print(f"Incomplete: {len(scores)}/{2 * len(pairs)} sides; rerun to resume", file=sys.stderr)
        return
    result = report(pairs, scores, args.domain, digest, revision, protocol, args.threshold, pack)
    args.report.parent.mkdir(parents=True, exist_ok=True)
    args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
    print(json.dumps(result, sort_keys=True))


def score_saved(args: argparse.Namespace) -> None:
    pairs, digest = load_pairs(args.domain, args.dataset)
    scores = prediction_scores(args.predictions, pairs, args.domain, True)
    first = json.loads(next(line for line in args.predictions.read_text().splitlines() if line))
    pack = load_pack(args.question_pack)
    revision = args.model_revision or first.get("model_revision", "unspecified")
    protocol = args.protocol_id or first.get("protocol_id", "unspecified")
    if any((row.get("model_revision", revision) != revision or row.get("protocol_id", protocol) != protocol)
           for row in scores.values()):
        raise ValueError("Predictions mix model revisions or protocols")
    result = report(pairs, scores, args.domain, digest,
                    revision, protocol, args.threshold, pack)
    args.report.parent.mkdir(parents=True, exist_ok=True)
    args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
    print(json.dumps(result, sort_keys=True))


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest="action", required=True)
    for name in ("run", "score"):
        command = sub.add_parser(name)
        command.add_argument("--domain", choices=("bug", "security"), required=True)
        command.add_argument("--dataset", type=Path, help="Local benchmark.jsonl; default downloads public pairs")
        command.add_argument("--predictions", type=Path, required=True)
        command.add_argument("--report", type=Path, required=True)
        command.add_argument("--threshold", type=float, default=0.5)
        command.add_argument("--question-pack", type=Path, default=Path(__file__).with_name("question-pack.json"))
        command.add_argument("--model-revision")
        command.add_argument("--protocol-id")
        if name == "run":
            command.add_argument("--mode", choices=("scan", "broad", "native"),
                                 help="Default: scan; old broad/native protocol IDs infer their historical mode")
            command.add_argument("--scorer", choices=("jev", "command"), required=True)
            command.add_argument("--command", help="Persistent NDJSON scorer command")
            command.add_argument("--api-url", default="https://api.typesafe.ai/v1/systemone")
            command.add_argument("--limit", type=int, default=0, help="Score at most N new sides, then resume later")
    args = parser.parse_args()
    if not 0 <= args.threshold <= 1:
        parser.error("--threshold must be in [0, 1]")
    if args.action == "run":
        if args.limit < 0:
            parser.error("--limit must be nonnegative")
        run(args)
    else:
        score_saved(args)


if __name__ == "__main__":
    main()