Update benchmark runners for current Perch scan questions

#17
Files changed (6) hide show
  1. README.md +4 -3
  2. adapters/README.md +2 -2
  3. adapters/clm.py +6 -4
  4. adapters/securebert.py +2 -0
  5. benchmark.py +147 -39
  6. question-pack.json +797 -0
README.md CHANGED
@@ -76,7 +76,8 @@ Inference cost is for scoring the method sides in that table. Jev uses API-repor
76
 
77
  ## Files
78
 
79
- - [`benchmark.py`](https://huggingface.co/datasets/perchscan/benchmark-results/blob/main/benchmark.py): run a model on the public pairs and calculate the metrics in these tables.
 
80
  - [`adapters/`](https://huggingface.co/datasets/perchscan/benchmark-results/tree/main/adapters): example runners for the unmodified open-source models in the tables.
81
  - `results.jsonl`: one aggregate report per domain, track, model, and protocol.
82
  - `benchmark-costs.json`: token usage, GPU timing, rates, and per-track cost calculations.
@@ -85,14 +86,14 @@ Inference cost is for scoring the method sides in that table. Jev uses API-repor
85
 
86
  ## Run the public benchmark
87
 
88
- The Python 3 script downloads the selected public pair dataset, scores both method versions independently, saves resumable predictions, and writes a JSON metric report. To run Jev, set `TYPESAFE_API_KEY` or `PERCH_API_KEY` in your environment:
89
 
90
  ```sh
91
  python3 benchmark.py run --domain bug --scorer jev --predictions bug-jev.jsonl --report bug-jev.json
92
  python3 benchmark.py run --domain security --scorer jev --predictions security-jev.jsonl --report security-jev.json
93
  ```
94
 
95
- To score a different model, use `--scorer command --command 'python3 your_adapter.py' --model-revision YOUR_MODEL --protocol-id YOUR_INPUT_FORMAT`. The adapter stays running, reads one JSON line containing `state`, `domain`, `role`, and `question` per method, and writes one JSON line containing `score` (a number from 0 to 1). `--limit N` performs a small resumable run; the report is written only when every method side has a score.
96
 
97
  Recalculate a published public result without model calls:
98
 
 
76
 
77
  ## Files
78
 
79
+ - [`benchmark.py`](https://huggingface.co/datasets/perchscan/benchmark-results/blob/main/benchmark.py): run and score models on the public pairs with the current scan questions or the historical broad protocol.
80
+ - [`question-pack.json`](https://huggingface.co/datasets/perchscan/benchmark-results/blob/main/question-pack.json): the current bug and security questions exported from Perch's public `scan.yaml`, including language selectors and alert floors.
81
  - [`adapters/`](https://huggingface.co/datasets/perchscan/benchmark-results/tree/main/adapters): example runners for the unmodified open-source models in the tables.
82
  - `results.jsonl`: one aggregate report per domain, track, model, and protocol.
83
  - `benchmark-costs.json`: token usage, GPU timing, rates, and per-track cost calculations.
 
86
 
87
  ## Run the public benchmark
88
 
89
+ The tables above used the historical broad-question protocol. The runner now defaults to the current Perch scan pack in `question-pack.json`; new results carry a different protocol ID and should be reported separately. It scores both method versions independently, saves resumable predictions, and writes a JSON metric report. To run Jev, set `TYPESAFE_API_KEY` or `PERCH_API_KEY` in your environment:
90
 
91
  ```sh
92
  python3 benchmark.py run --domain bug --scorer jev --predictions bug-jev.jsonl --report bug-jev.json
93
  python3 benchmark.py run --domain security --scorer jev --predictions security-jev.jsonl --report security-jev.json
94
  ```
95
 
96
+ To score a different model on the scan pack, use `--scorer command --command 'python3 your_adapter.py' --model-revision YOUR_MODEL`. The persistent adapter receives one JSON line per score-bearing question, with `state`, `language`, `question_name`, and `question`, and returns `score` as the probability of the question's true answer. Jev also receives the companion `kind` and `severity` questions in its batched scan request; command adapters score the binary detection questions that determine bug or security alerts. Each prediction stores the per-question scores and pack hash. An alert requires a score strictly above that question's floor and the run's `--threshold`. `--limit N` performs a small resumable run; the report is written only when every method side has a score.
97
 
98
  Recalculate a published public result without model calls:
99
 
adapters/README.md CHANGED
@@ -1,6 +1,6 @@
1
  # Released-model benchmark adapters
2
 
3
- These scripts connect the [Perch benchmark runner](../benchmark.py) to the unmodified, publicly released models in the results table. Each process reads one JSON request per line and writes `{"score": probability}` per line. Scores are for the supplied method side; the adapter never sees its paired repair or label.
4
 
5
  Install the relevant model's upstream dependencies before running it. A small smoke run uses `--limit 2`; rerunning the same command resumes the prediction file. Remove `--limit` to finish and write the metric report.
6
 
@@ -39,4 +39,4 @@ vllm serve Qwen/Qwen3-8B --runner pooling --max-model-len 6144 --port 8090
39
  python3 benchmark.py run --domain bug --scorer command --command 'python3 adapters/clm.py' --model-revision 'Contrastive-LM/CLM-v0.1-8B@sha256:b2b4a8c9c2d39263eff78a351eb909a342ce9b3bf21a3f07c1d1bf15f1c4eda5' --protocol-id clm-native-choice-6144-v1 --predictions bug-clm.jsonl --report bug-clm.json --limit 2
40
  ```
41
 
42
- The CLM adapter uses its native choice prompts, while the other adapters use the broad bug or security question where the model accepts one. Input length and model revisions affect results. These scripts contain no benchmark labels, API keys, private data, or fine-tuned weights.
 
1
  # Released-model benchmark adapters
2
 
3
+ These scripts connect the [Perch benchmark runner](../benchmark.py) to unmodified, publicly released models. Each process reads one JSON request per line and writes `{"score": probability}` per line. The adapter never sees its paired repair or label. By default, the runner asks each binary detection question in the current Perch scan pack and combines scores using that question's alert floor. `kind` and `severity` accompany Jev's batched scan request but do not change the binary benchmark result.
4
 
5
  Install the relevant model's upstream dependencies before running it. A small smoke run uses `--limit 2`; rerunning the same command resumes the prediction file. Remove `--limit` to finish and write the metric report.
6
 
 
39
  python3 benchmark.py run --domain bug --scorer command --command 'python3 adapters/clm.py' --model-revision 'Contrastive-LM/CLM-v0.1-8B@sha256:b2b4a8c9c2d39263eff78a351eb909a342ce9b3bf21a3f07c1d1bf15f1c4eda5' --protocol-id clm-native-choice-6144-v1 --predictions bug-clm.jsonl --report bug-clm.json --limit 2
40
  ```
41
 
42
+ The JevK5 and jev-lite commands above reproduce the historical broad-question protocol. Omit `--protocol-id perch-broad-v1` and choose new prediction filenames to run the current scan pack; the runner supplies each applicable binary question and records its pack hash. CLM can also use the scan pack when its native protocol ID is omitted; it then embeds each distinct question's choice text. The SecureBERT adapter accepts only its native protocol because its classifier has no question input. Input length and model revisions affect results. These scripts contain no benchmark labels, API keys, private data, or fine-tuned weights.
adapters/clm.py CHANGED
@@ -111,15 +111,17 @@ with torch.inference_mode():
111
  for line in sys.stdin:
112
  row = json.loads(line)
113
  domain = row["domain"]
114
- state_text, keys, candidates = build_pairs(context_text(row), {domain: QUESTIONS[domain]})[domain]
 
115
  if keys != ["false", "true"] or len(candidates) != 2:
116
  raise RuntimeError("CLM option order changed")
117
- if domain not in candidate_vectors:
118
- candidate_vectors[domain] = torch.stack([
 
119
  embed(recipe.text_ids(text, keep="head")) for text in candidates])
120
  state = embed(recipe.text_ids(state_text, keep="tail")).unsqueeze(0)
121
  state_z = F.normalize(state_head(state), dim=-1)
122
- action_z = F.normalize(action_head(candidate_vectors[domain]), dim=-1)
123
  logits = scale * torch.einsum("bd,kd->bk", state_z, action_z)
124
  score = torch.softmax(logits.float(), dim=-1)[0, 1].item()
125
  print(json.dumps({"score": score}), flush=True)
 
111
  for line in sys.stdin:
112
  row = json.loads(line)
113
  domain = row["domain"]
114
+ question = row.get("question", QUESTIONS[domain])
115
+ state_text, keys, candidates = build_pairs(context_text(row), {domain: question})[domain]
116
  if keys != ["false", "true"] or len(candidates) != 2:
117
  raise RuntimeError("CLM option order changed")
118
+ question_key = json.dumps(question, sort_keys=True)
119
+ if question_key not in candidate_vectors:
120
+ candidate_vectors[question_key] = torch.stack([
121
  embed(recipe.text_ids(text, keep="head")) for text in candidates])
122
  state = embed(recipe.text_ids(state_text, keep="tail")).unsqueeze(0)
123
  state_z = F.normalize(state_head(state), dim=-1)
124
+ action_z = F.normalize(action_head(candidate_vectors[question_key]), dim=-1)
125
  logits = scale * torch.einsum("bd,kd->bk", state_z, action_z)
126
  score = torch.softmax(logits.float(), dim=-1)[0, 1].item()
127
  print(json.dumps({"score": score}), flush=True)
adapters/securebert.py CHANGED
@@ -49,6 +49,8 @@ with torch.inference_mode():
49
  row = json.loads(line)
50
  if row["domain"] != "security":
51
  raise ValueError("SecureBERT adapter supports security only")
 
 
52
  parts = sections(row)
53
  ids = [tokenizer.cls_token_id]
54
  for name, cap in CAPS:
 
49
  row = json.loads(line)
50
  if row["domain"] != "security":
51
  raise ValueError("SecureBERT adapter supports security only")
52
+ if "question_name" in row:
53
+ raise ValueError("SecureBERT does not accept CWE questions; use its native protocol ID")
54
  parts = sections(row)
55
  ids = [tokenizer.cls_token_id]
56
  for name, cap in CAPS:
benchmark.py CHANGED
@@ -3,6 +3,7 @@
3
 
4
  Standard-library only. The command adapter is a persistent NDJSON process: it
5
  receives one JSON object per line and returns one {"score": probability} per line.
 
6
  """
7
 
8
  from __future__ import annotations
@@ -25,7 +26,7 @@ DATASET_URL = {
25
  domain: f"https://huggingface.co/datasets/perchscan/{domain}-pairs-public/resolve/main/benchmark.jsonl"
26
  for domain in ("bug", "security")
27
  }
28
- QUESTION = {
29
  "bug": {
30
  "type": "noul",
31
  "instructions": "Does this method contain a concrete behavioral bug a caller can reach?",
@@ -45,6 +46,52 @@ QUESTION = {
45
  }
46
 
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  def dataset_bytes(domain: str, path: Path | None) -> bytes:
49
  if path is not None:
50
  return (path / "benchmark.jsonl" if path.is_dir() else path).read_bytes()
@@ -78,7 +125,7 @@ def probability(value: object) -> float:
78
 
79
 
80
  def prediction_scores(path: Path, pairs: list[dict], domain: str,
81
- require_complete: bool) -> dict[tuple[str, str], float]:
82
  expected = {(pair["pair_id"], role) for pair in pairs for role in ("before", "after")}
83
  scores = {}
84
  if not path.exists():
@@ -92,7 +139,8 @@ def prediction_scores(path: Path, pairs: list[dict], domain: str,
92
  key = (row["pair_id"], row["role"])
93
  if key not in expected or key in scores or row.get("domain", domain) != domain:
94
  raise ValueError(f"Unexpected or duplicate prediction: {key}")
95
- scores[key] = probability(row["score"])
 
96
  if require_complete and scores.keys() != expected:
97
  missing = expected - scores.keys()
98
  raise ValueError(f"Predictions are missing {len(missing)} method sides")
@@ -117,20 +165,32 @@ def average_precision(items: list[tuple[int, float]]) -> float:
117
  return total / positives
118
 
119
 
120
- def report(pairs: list[dict], scores: dict[tuple[str, str], float], domain: str,
121
  digest: str, model_revision: str, protocol_id: str,
122
- threshold: float) -> dict:
123
- items = [(pair[role]["labels"][domain], scores[pair["pair_id"], role])
124
- for pair in pairs for role in ("before", "after")]
125
- tp = sum(label == 1 and score >= threshold for label, score in items)
126
- fp = sum(label == 0 and score >= threshold for label, score in items)
127
- fn = sum(label == 1 and score < threshold for label, score in items)
128
- tn = sum(label == 0 and score < threshold for label, score in items)
 
 
 
 
 
 
 
 
 
 
 
 
129
  eligible = correct = ties = 0
130
  for pair in pairs:
131
  if pair["before"]["labels"][domain] == 1 and pair["after"]["labels"][domain] == 0:
132
  eligible += 1
133
- before, after = scores[pair["pair_id"], "before"], scores[pair["pair_id"], "after"]
134
  correct += before > after
135
  ties += before == after
136
  precision = tp / (tp + fp) if tp + fp else 0.0
@@ -140,10 +200,12 @@ def report(pairs: list[dict], scores: dict[tuple[str, str], float], domain: str,
140
  "model_revision": model_revision,
141
  "protocol_id": protocol_id,
142
  "threshold": threshold,
 
 
143
  "benchmark_sha256": digest,
144
  "benchmark_pairs": len(pairs),
145
  "benchmark_methods": len(items),
146
- "average_precision": average_precision(items),
147
  "precision": precision,
148
  "recall": recall,
149
  "f1": 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0,
@@ -155,12 +217,11 @@ def report(pairs: list[dict], scores: dict[tuple[str, str], float], domain: str,
155
  }
156
 
157
 
158
- def jev_score(state: dict, domain: str, model: str, api_url: str) -> float:
159
  key = os.getenv("TYPESAFE_API_KEY") or os.getenv("PERCH_API_KEY")
160
  if not key:
161
  raise RuntimeError("Set TYPESAFE_API_KEY or PERCH_API_KEY to run Jev")
162
- name = "bug_any" if domain == "bug" else "security_any"
163
- payload = json.dumps({"model": model, "state": state, "questions": {name: QUESTION[domain]}}).encode()
164
  for attempt in range(4):
165
  request = Request(api_url, data=payload, method="POST", headers={
166
  "Authorization": f"Bearer {key}", "Content-Type": "application/json",
@@ -168,7 +229,7 @@ def jev_score(state: dict, domain: str, model: str, api_url: str) -> float:
168
  try:
169
  with urlopen(request, timeout=120) as response:
170
  answer = json.load(response)
171
- return probability(answer["answers"][name]["noul"])
172
  except HTTPError as exc:
173
  if exc.code not in (429, 500, 502, 503, 504) or attempt == 3:
174
  raise RuntimeError(f"Jev request failed with HTTP {exc.code}") from None
@@ -181,20 +242,46 @@ def jev_score(state: dict, domain: str, model: str, api_url: str) -> float:
181
  raise AssertionError("unreachable")
182
 
183
 
 
 
 
 
 
 
 
 
 
 
184
  def run(args: argparse.Namespace) -> None:
185
  pairs, digest = load_pairs(args.domain, args.dataset)
 
 
 
 
186
  if args.scorer == "jev":
187
- revision, protocol = args.model_revision or "jev-1.13.0", "perch-broad-v1"
 
 
 
 
 
188
  else:
189
- if not args.command or not args.model_revision or not args.protocol_id:
190
- raise ValueError("Command scorer requires --command, --model-revision, and --protocol-id")
191
- revision, protocol = args.model_revision, args.protocol_id
 
 
 
 
 
192
  if args.predictions.exists():
193
  for line in args.predictions.read_text().splitlines():
194
  if line:
195
  row = json.loads(line)
196
  if row.get("model_revision") != revision or row.get("protocol_id") != protocol:
197
  raise ValueError("Existing prediction file uses another model or protocol")
 
 
198
  existing = prediction_scores(args.predictions, pairs, args.domain, False)
199
  pending = [(pair, role) for pair in pairs for role in ("before", "after")
200
  if (pair["pair_id"], role) not in existing]
@@ -209,22 +296,35 @@ def run(args: argparse.Namespace) -> None:
209
  with args.predictions.open("a") as output:
210
  for index, (pair, role) in enumerate(pending, 1):
211
  state = pair[role]["state"]
212
- if args.scorer == "jev":
213
- score = jev_score(state, args.domain, revision, args.api_url)
 
 
 
 
 
 
 
 
 
 
 
 
214
  else:
215
- request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
216
- "language": pair.get("language"), "source": pair[role]["source"],
217
- "state": state, "question": QUESTION[args.domain]}
218
- assert command and command.stdin and command.stdout
219
- command.stdin.write(json.dumps(request, ensure_ascii=False) + "\n")
220
- command.stdin.flush()
221
- line = command.stdout.readline()
222
- if not line:
223
- raise RuntimeError("Model adapter stopped before returning a score")
224
- score = probability(json.loads(line)["score"])
225
- output.write(json.dumps({"domain": args.domain, "pair_id": pair["pair_id"],
226
- "role": role, "score": score, "model_revision": revision,
227
- "protocol_id": protocol}) + "\n")
 
228
  output.flush()
229
  if index % 100 == 0 or index == len(pending):
230
  print(f"Scored {len(existing) + index}/{2 * len(pairs)} method sides", file=sys.stderr)
@@ -242,7 +342,7 @@ def run(args: argparse.Namespace) -> None:
242
  if len(scores) != 2 * len(pairs):
243
  print(f"Incomplete: {len(scores)}/{2 * len(pairs)} sides; rerun to resume", file=sys.stderr)
244
  return
245
- result = report(pairs, scores, args.domain, digest, revision, protocol, args.threshold)
246
  args.report.parent.mkdir(parents=True, exist_ok=True)
247
  args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
248
  print(json.dumps(result, sort_keys=True))
@@ -252,9 +352,14 @@ def score_saved(args: argparse.Namespace) -> None:
252
  pairs, digest = load_pairs(args.domain, args.dataset)
253
  scores = prediction_scores(args.predictions, pairs, args.domain, True)
254
  first = json.loads(next(line for line in args.predictions.read_text().splitlines() if line))
 
 
 
 
 
 
255
  result = report(pairs, scores, args.domain, digest,
256
- args.model_revision or first.get("model_revision", "unspecified"),
257
- args.protocol_id or first.get("protocol_id", "unspecified"), args.threshold)
258
  args.report.parent.mkdir(parents=True, exist_ok=True)
259
  args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
260
  print(json.dumps(result, sort_keys=True))
@@ -270,9 +375,12 @@ def main() -> None:
270
  command.add_argument("--predictions", type=Path, required=True)
271
  command.add_argument("--report", type=Path, required=True)
272
  command.add_argument("--threshold", type=float, default=0.5)
 
273
  command.add_argument("--model-revision")
274
  command.add_argument("--protocol-id")
275
  if name == "run":
 
 
276
  command.add_argument("--scorer", choices=("jev", "command"), required=True)
277
  command.add_argument("--command", help="Persistent NDJSON scorer command")
278
  command.add_argument("--api-url", default="https://api.typesafe.ai/v1/systemone")
 
3
 
4
  Standard-library only. The command adapter is a persistent NDJSON process: it
5
  receives one JSON object per line and returns one {"score": probability} per line.
6
+ Current scan mode uses question-pack.json exported from public Perch scan.yaml.
7
  """
8
 
9
  from __future__ import annotations
 
26
  domain: f"https://huggingface.co/datasets/perchscan/{domain}-pairs-public/resolve/main/benchmark.jsonl"
27
  for domain in ("bug", "security")
28
  }
29
+ LEGACY_QUESTION = {
30
  "bug": {
31
  "type": "noul",
32
  "instructions": "Does this method contain a concrete behavioral bug a caller can reach?",
 
46
  }
47
 
48
 
49
+ def load_pack(path: Path) -> dict:
50
+ pack = json.loads(path.read_text())
51
+ body = {key: pack[key] for key in ("schema_version", "source", "source_sha256", "domains")}
52
+ digest = hashlib.sha256(json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
53
+ if (pack.get("schema_version") != 1 or pack.get("pack_sha256") != digest
54
+ or pack.get("protocol_id") != f"perch-scan-{digest[:12]}"
55
+ or pack.get("binary_protocol_id") != f"perch-scan-binary-{digest[:12]}"):
56
+ raise ValueError("Question pack checksum or protocol ID does not match its contents")
57
+ for domain in ("bug", "security"):
58
+ if not pack["domains"].get(domain):
59
+ raise ValueError(f"Question pack has no {domain} questions")
60
+ for question in pack["domains"][domain]:
61
+ if question["where"] != "**/*":
62
+ raise ValueError(f"Benchmark does not yet support path selector {question['where']}")
63
+ return pack
64
+
65
+
66
+ def scan_questions(pack: dict, domain: str, language: str) -> list[dict]:
67
+ if not language:
68
+ raise ValueError("Benchmark pair has no language for question selection")
69
+ normalized = {"csharp": "c_sharp"}.get(language, language)
70
+ return [q for q in pack["domains"][domain]
71
+ if q["language"] is None or normalized in ([q["language"]] if isinstance(q["language"], str) else q["language"])]
72
+
73
+
74
+ def detection_questions(questions: list[dict], domain: str) -> list[dict]:
75
+ issue_type = "defect" if domain == "bug" else "security"
76
+ return [q for q in questions if q["type"] == "noul" and q["issue"] and q["issue"]["type"] == issue_type]
77
+
78
+
79
+ def raised_score(question: dict, true_probability: object) -> float:
80
+ score = probability(true_probability)
81
+ return 1 - score if question["issue"].get("on") is False else score
82
+
83
+
84
+ def scan_result(question_scores: dict[str, float], questions: list[dict], domain: str, threshold: float) -> tuple[float, bool]:
85
+ relevant = detection_questions(questions, domain)
86
+ expected = {q["name"] for q in relevant}
87
+ if set(question_scores) != expected:
88
+ raise ValueError(f"Question scores differ from selected scan pack: {expected ^ set(question_scores)}")
89
+ score = max(question_scores.values(), default=0.0)
90
+ alert = any(question_scores[q["name"]] > max(threshold, (q["min"] or 0) / 100)
91
+ for q in relevant)
92
+ return score, alert
93
+
94
+
95
  def dataset_bytes(domain: str, path: Path | None) -> bytes:
96
  if path is not None:
97
  return (path / "benchmark.jsonl" if path.is_dir() else path).read_bytes()
 
125
 
126
 
127
  def prediction_scores(path: Path, pairs: list[dict], domain: str,
128
+ require_complete: bool) -> dict[tuple[str, str], dict]:
129
  expected = {(pair["pair_id"], role) for pair in pairs for role in ("before", "after")}
130
  scores = {}
131
  if not path.exists():
 
139
  key = (row["pair_id"], row["role"])
140
  if key not in expected or key in scores or row.get("domain", domain) != domain:
141
  raise ValueError(f"Unexpected or duplicate prediction: {key}")
142
+ row["score"] = probability(row["score"])
143
+ scores[key] = row
144
  if require_complete and scores.keys() != expected:
145
  missing = expected - scores.keys()
146
  raise ValueError(f"Predictions are missing {len(missing)} method sides")
 
165
  return total / positives
166
 
167
 
168
+ def report(pairs: list[dict], scores: dict[tuple[str, str], dict], domain: str,
169
  digest: str, model_revision: str, protocol_id: str,
170
+ threshold: float, pack: dict | None = None) -> dict:
171
+ items = []
172
+ for pair in pairs:
173
+ for role in ("before", "after"):
174
+ row = scores[pair["pair_id"], role]
175
+ if pack and protocol_id in (pack["protocol_id"], pack["binary_protocol_id"]):
176
+ if row.get("pack_sha256") != pack["pack_sha256"]:
177
+ raise ValueError("Prediction was made with a different question pack")
178
+ questions = scan_questions(pack, domain, pair["language"])
179
+ score, alert = scan_result(row.get("question_scores", {}), questions, domain, threshold)
180
+ if abs(score - row["score"]) > 1e-9:
181
+ raise ValueError("Prediction's aggregate score does not match its question scores")
182
+ else:
183
+ score, alert = row["score"], row["score"] >= threshold
184
+ items.append((pair[role]["labels"][domain], score, alert))
185
+ tp = sum(label == 1 and alert for label, _, alert in items)
186
+ fp = sum(label == 0 and alert for label, _, alert in items)
187
+ fn = sum(label == 1 and not alert for label, _, alert in items)
188
+ tn = sum(label == 0 and not alert for label, _, alert in items)
189
  eligible = correct = ties = 0
190
  for pair in pairs:
191
  if pair["before"]["labels"][domain] == 1 and pair["after"]["labels"][domain] == 0:
192
  eligible += 1
193
+ before, after = scores[pair["pair_id"], "before"]["score"], scores[pair["pair_id"], "after"]["score"]
194
  correct += before > after
195
  ties += before == after
196
  precision = tp / (tp + fp) if tp + fp else 0.0
 
200
  "model_revision": model_revision,
201
  "protocol_id": protocol_id,
202
  "threshold": threshold,
203
+ "alert_rule": "per-question scan floor, strict >" if pack and protocol_id in (pack["protocol_id"], pack["binary_protocol_id"]) else "score >= threshold",
204
+ "question_pack_sha256": pack["pack_sha256"] if pack and protocol_id in (pack["protocol_id"], pack["binary_protocol_id"]) else None,
205
  "benchmark_sha256": digest,
206
  "benchmark_pairs": len(pairs),
207
  "benchmark_methods": len(items),
208
+ "average_precision": average_precision([(label, score) for label, score, _ in items]),
209
  "precision": precision,
210
  "recall": recall,
211
  "f1": 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0,
 
217
  }
218
 
219
 
220
+ def jev_answers(state: dict, questions: dict, model: str, api_url: str) -> dict:
221
  key = os.getenv("TYPESAFE_API_KEY") or os.getenv("PERCH_API_KEY")
222
  if not key:
223
  raise RuntimeError("Set TYPESAFE_API_KEY or PERCH_API_KEY to run Jev")
224
+ payload = json.dumps({"model": model, "state": state, "questions": questions}).encode()
 
225
  for attempt in range(4):
226
  request = Request(api_url, data=payload, method="POST", headers={
227
  "Authorization": f"Bearer {key}", "Content-Type": "application/json",
 
229
  try:
230
  with urlopen(request, timeout=120) as response:
231
  answer = json.load(response)
232
+ return answer["answers"]
233
  except HTTPError as exc:
234
  if exc.code not in (429, 500, 502, 503, 504) or attempt == 3:
235
  raise RuntimeError(f"Jev request failed with HTTP {exc.code}") from None
 
242
  raise AssertionError("unreachable")
243
 
244
 
245
+ def command_score(command: subprocess.Popen, request: dict) -> float:
246
+ assert command.stdin and command.stdout
247
+ command.stdin.write(json.dumps(request, ensure_ascii=False) + "\n")
248
+ command.stdin.flush()
249
+ line = command.stdout.readline()
250
+ if not line:
251
+ raise RuntimeError("Model adapter stopped before returning a score")
252
+ return probability(json.loads(line)["score"])
253
+
254
+
255
  def run(args: argparse.Namespace) -> None:
256
  pairs, digest = load_pairs(args.domain, args.dataset)
257
+ pack = load_pack(args.question_pack)
258
+ scan_protocols = (pack["protocol_id"], pack["binary_protocol_id"])
259
+ mode = args.mode or ("broad" if args.protocol_id == "perch-broad-v1" else
260
+ "native" if args.protocol_id and args.protocol_id not in scan_protocols else "scan")
261
  if args.scorer == "jev":
262
+ if mode == "native":
263
+ raise ValueError("Jev requires scan or broad question mode")
264
+ revision = args.model_revision or "jev-1.13.0"
265
+ protocol = pack["protocol_id"] if mode == "scan" else "perch-broad-v1"
266
+ if args.protocol_id and args.protocol_id != protocol:
267
+ raise ValueError("Jev protocol ID does not match the selected question mode")
268
  else:
269
+ if not args.command or not args.model_revision:
270
+ raise ValueError("Command scorer requires --command and --model-revision")
271
+ revision = args.model_revision
272
+ protocol = args.protocol_id or (pack["binary_protocol_id"] if mode == "scan" else "perch-broad-v1")
273
+ if mode == "scan" and protocol != pack["binary_protocol_id"]:
274
+ raise ValueError("Scan protocol ID must match the question pack")
275
+ if mode == "native" and not args.protocol_id:
276
+ raise ValueError("Native scorer requires its own --protocol-id")
277
  if args.predictions.exists():
278
  for line in args.predictions.read_text().splitlines():
279
  if line:
280
  row = json.loads(line)
281
  if row.get("model_revision") != revision or row.get("protocol_id") != protocol:
282
  raise ValueError("Existing prediction file uses another model or protocol")
283
+ if mode == "scan" and row.get("pack_sha256") != pack["pack_sha256"]:
284
+ raise ValueError("Existing predictions use another scan question pack")
285
  existing = prediction_scores(args.predictions, pairs, args.domain, False)
286
  pending = [(pair, role) for pair in pairs for role in ("before", "after")
287
  if (pair["pair_id"], role) not in existing]
 
296
  with args.predictions.open("a") as output:
297
  for index, (pair, role) in enumerate(pending, 1):
298
  state = pair[role]["state"]
299
+ if mode == "scan":
300
+ selected = scan_questions(pack, args.domain, pair["language"])
301
+ if args.scorer == "jev":
302
+ answers = jev_answers(state, {q["name"]: q["question"] for q in selected}, revision, args.api_url)
303
+ question_scores = {q["name"]: raised_score(q, answers[q["name"]]["noul"])
304
+ for q in detection_questions(selected, args.domain)}
305
+ else:
306
+ question_scores = {}
307
+ for q in detection_questions(selected, args.domain):
308
+ request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
309
+ "language": pair["language"], "source": pair[role]["source"],
310
+ "state": state, "question": q["question"], "question_name": q["name"]}
311
+ question_scores[q["name"]] = raised_score(q, command_score(command, request))
312
+ score, alert = scan_result(question_scores, selected, args.domain, args.threshold)
313
  else:
314
+ question = LEGACY_QUESTION[args.domain]
315
+ if args.scorer == "jev":
316
+ name = "bug_any" if args.domain == "bug" else "security_any"
317
+ score = probability(jev_answers(state, {name: question}, revision, args.api_url)[name]["noul"])
318
+ else:
319
+ request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
320
+ "language": pair.get("language"), "source": pair[role]["source"],
321
+ "state": state, "question": question}
322
+ score = command_score(command, request)
323
+ result = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
324
+ "score": score, "model_revision": revision, "protocol_id": protocol}
325
+ if mode == "scan":
326
+ result.update(question_scores=question_scores, alert=alert, pack_sha256=pack["pack_sha256"])
327
+ output.write(json.dumps(result) + "\n")
328
  output.flush()
329
  if index % 100 == 0 or index == len(pending):
330
  print(f"Scored {len(existing) + index}/{2 * len(pairs)} method sides", file=sys.stderr)
 
342
  if len(scores) != 2 * len(pairs):
343
  print(f"Incomplete: {len(scores)}/{2 * len(pairs)} sides; rerun to resume", file=sys.stderr)
344
  return
345
+ result = report(pairs, scores, args.domain, digest, revision, protocol, args.threshold, pack)
346
  args.report.parent.mkdir(parents=True, exist_ok=True)
347
  args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
348
  print(json.dumps(result, sort_keys=True))
 
352
  pairs, digest = load_pairs(args.domain, args.dataset)
353
  scores = prediction_scores(args.predictions, pairs, args.domain, True)
354
  first = json.loads(next(line for line in args.predictions.read_text().splitlines() if line))
355
+ pack = load_pack(args.question_pack)
356
+ revision = args.model_revision or first.get("model_revision", "unspecified")
357
+ protocol = args.protocol_id or first.get("protocol_id", "unspecified")
358
+ if any((row.get("model_revision", revision) != revision or row.get("protocol_id", protocol) != protocol)
359
+ for row in scores.values()):
360
+ raise ValueError("Predictions mix model revisions or protocols")
361
  result = report(pairs, scores, args.domain, digest,
362
+ revision, protocol, args.threshold, pack)
 
363
  args.report.parent.mkdir(parents=True, exist_ok=True)
364
  args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
365
  print(json.dumps(result, sort_keys=True))
 
375
  command.add_argument("--predictions", type=Path, required=True)
376
  command.add_argument("--report", type=Path, required=True)
377
  command.add_argument("--threshold", type=float, default=0.5)
378
+ command.add_argument("--question-pack", type=Path, default=Path(__file__).with_name("question-pack.json"))
379
  command.add_argument("--model-revision")
380
  command.add_argument("--protocol-id")
381
  if name == "run":
382
+ command.add_argument("--mode", choices=("scan", "broad", "native"),
383
+ help="Default: scan; old broad/native protocol IDs infer their historical mode")
384
  command.add_argument("--scorer", choices=("jev", "command"), required=True)
385
  command.add_argument("--command", help="Persistent NDJSON scorer command")
386
  command.add_argument("--api-url", default="https://api.typesafe.ai/v1/systemone")
question-pack.json ADDED
@@ -0,0 +1,797 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "source": "lakeday-org/perch/scan.yaml",
4
+ "source_sha256": "093bbc7ce61c7bd1049b42e3c1bb8ee783a729adec44f26c7024760c9192a187",
5
+ "domains": {
6
+ "bug": [
7
+ {
8
+ "name": "has_bug",
9
+ "type": "noul",
10
+ "language": null,
11
+ "where": "**/*",
12
+ "issue": {
13
+ "type": "defect",
14
+ "label": "kind",
15
+ "pick": "strongest"
16
+ },
17
+ "min": 60,
18
+ "when": null,
19
+ "question": {
20
+ "type": "noul",
21
+ "instructions": "Does `method` contain a concrete behavioral defect that a caller can reach?",
22
+ "criteria": {
23
+ "true": "For some input a caller can pass, the method returns a wrong result, leaves wrong state, throws when it should not, or fails to throw when it should\n",
24
+ "false": "The method behaves correctly for every input its callers can pass; style, performance, and hypothetical misuse do not count\n"
25
+ }
26
+ }
27
+ },
28
+ {
29
+ "name": "kind",
30
+ "type": "choice",
31
+ "language": null,
32
+ "where": "**/*",
33
+ "issue": null,
34
+ "min": null,
35
+ "when": null,
36
+ "question": {
37
+ "type": "choice",
38
+ "instructions": "If `method` has a defect, which kind is it?",
39
+ "criteria": {
40
+ "boundary": "An off-by-one, a wrong comparison, or a mishandled edge of a range",
41
+ "missing_null_handling": "A null, undefined, empty, or absent value is not handled",
42
+ "wrong_return": "The wrong value, or a value of the wrong shape, is returned for some input",
43
+ "swallowed_error": "An error is caught, ignored, or turned into a misleading result",
44
+ "state_mutation": "Shared or input state is mutated when it should not be, or left stale when it should change",
45
+ "ordering": "Operations run in the wrong order, or rely on an order that is not guaranteed",
46
+ "resource_leak": "A handle, lock, timer, process, or connection is not released on some path",
47
+ "inverted_condition": "A condition, sign, or boolean is the wrong way round"
48
+ }
49
+ }
50
+ },
51
+ {
52
+ "name": "severity",
53
+ "type": "score",
54
+ "language": null,
55
+ "where": "**/*",
56
+ "issue": null,
57
+ "min": null,
58
+ "when": null,
59
+ "question": {
60
+ "type": "score",
61
+ "instructions": "If something is wrong with `method`, how much would a caller feel it?",
62
+ "criteria": [
63
+ "No caller would notice",
64
+ "A wrong result in a rare case, or one the caller can see and recover from",
65
+ "A wrong result or wrong state in ordinary use",
66
+ "Data lost, corrupted, or exposed, or a check that should stop someone bypassed"
67
+ ]
68
+ }
69
+ },
70
+ {
71
+ "name": "does_what_it_claims",
72
+ "type": "noul",
73
+ "language": null,
74
+ "where": "**/*",
75
+ "issue": {
76
+ "type": "defect",
77
+ "label": "does_not_do_what_it_claims",
78
+ "on": false,
79
+ "pick": "strongest"
80
+ },
81
+ "min": 70,
82
+ "when": null,
83
+ "question": {
84
+ "type": "noul",
85
+ "instructions": "Does `method` do what its name, its parameters and its `leading_comment` say it does?",
86
+ "criteria": {
87
+ "true": "It behaves the way its name and its comment say it does",
88
+ "false": "It does something different from, less than, or more than its name and comment say, so one of the two is wrong"
89
+ }
90
+ }
91
+ }
92
+ ],
93
+ "security": [
94
+ {
95
+ "name": "severity",
96
+ "type": "score",
97
+ "language": null,
98
+ "where": "**/*",
99
+ "issue": null,
100
+ "min": null,
101
+ "when": null,
102
+ "question": {
103
+ "type": "score",
104
+ "instructions": "If something is wrong with `method`, how much would a caller feel it?",
105
+ "criteria": [
106
+ "No caller would notice",
107
+ "A wrong result in a rare case, or one the caller can see and recover from",
108
+ "A wrong result or wrong state in ordinary use",
109
+ "Data lost, corrupted, or exposed, or a check that should stop someone bypassed"
110
+ ]
111
+ }
112
+ },
113
+ {
114
+ "name": "cwe_79",
115
+ "type": "noul",
116
+ "language": null,
117
+ "where": "**/*",
118
+ "issue": {
119
+ "type": "security",
120
+ "label": "xss",
121
+ "pick": "strongest"
122
+ },
123
+ "min": 60,
124
+ "when": null,
125
+ "question": {
126
+ "type": "noul",
127
+ "instructions": "Is `method` vulnerable to cross-site scripting?",
128
+ "criteria": {
129
+ "true": "Outside text reaches HTML or script output without escaping. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
130
+ "false": "Its output is escaped, or no attacker-controlled text reaches it."
131
+ }
132
+ }
133
+ },
134
+ {
135
+ "name": "cwe_89",
136
+ "type": "noul",
137
+ "language": null,
138
+ "where": "**/*",
139
+ "issue": {
140
+ "type": "security",
141
+ "label": "sql_injection",
142
+ "pick": "strongest"
143
+ },
144
+ "min": 60,
145
+ "when": null,
146
+ "question": {
147
+ "type": "noul",
148
+ "instructions": "Is `method` vulnerable to SQL injection?",
149
+ "criteria": {
150
+ "true": "Outside text becomes part of the SQL it runs. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
151
+ "false": "Its SQL is fixed, or outside values are bound as parameters."
152
+ }
153
+ }
154
+ },
155
+ {
156
+ "name": "cwe_352",
157
+ "type": "noul",
158
+ "language": null,
159
+ "where": "**/*",
160
+ "issue": {
161
+ "type": "security",
162
+ "label": "csrf",
163
+ "pick": "strongest"
164
+ },
165
+ "min": 70,
166
+ "when": null,
167
+ "question": {
168
+ "type": "noul",
169
+ "instructions": "Is `method` vulnerable to cross-site request forgery?",
170
+ "criteria": {
171
+ "true": "A browser request that changes state is accepted without a CSRF token or origin check.",
172
+ "false": "It checks for forgery, or changes nothing a browser request can trigger."
173
+ }
174
+ }
175
+ },
176
+ {
177
+ "name": "cwe_862",
178
+ "type": "noul",
179
+ "language": null,
180
+ "where": "**/*",
181
+ "issue": {
182
+ "type": "security",
183
+ "label": "missing_authorization",
184
+ "pick": "strongest"
185
+ },
186
+ "min": 70,
187
+ "when": null,
188
+ "question": {
189
+ "type": "noul",
190
+ "instructions": "Does `method` skip an authorization check it needs?",
191
+ "criteria": {
192
+ "true": "Its name, documentation or callers show its action must be limited to certain users, and it performs it without checking who is calling.",
193
+ "false": "It checks permission, or its action needs none."
194
+ }
195
+ }
196
+ },
197
+ {
198
+ "name": "cwe_787",
199
+ "type": "noul",
200
+ "language": [
201
+ "c",
202
+ "cpp",
203
+ "rust",
204
+ "zig"
205
+ ],
206
+ "where": "**/*",
207
+ "issue": {
208
+ "type": "security",
209
+ "label": "out_of_bounds_write",
210
+ "pick": "strongest"
211
+ },
212
+ "min": 70,
213
+ "when": null,
214
+ "question": {
215
+ "type": "noul",
216
+ "instructions": "Can `method` write past the end of a buffer?",
217
+ "criteria": {
218
+ "true": "An index, pointer or length lets it write outside the memory it owns.",
219
+ "false": "Every write stays inside its buffer."
220
+ }
221
+ }
222
+ },
223
+ {
224
+ "name": "cwe_22",
225
+ "type": "noul",
226
+ "language": null,
227
+ "where": "**/*",
228
+ "issue": {
229
+ "type": "security",
230
+ "label": "path_traversal",
231
+ "pick": "strongest"
232
+ },
233
+ "min": 70,
234
+ "when": null,
235
+ "question": {
236
+ "type": "noul",
237
+ "instructions": "Is `method` vulnerable to path traversal?",
238
+ "criteria": {
239
+ "true": "A path built from outside input can reach files beyond the directory it should be limited to. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
240
+ "false": "Its paths are fixed or confined to their directory."
241
+ }
242
+ }
243
+ },
244
+ {
245
+ "name": "cwe_416",
246
+ "type": "noul",
247
+ "language": [
248
+ "c",
249
+ "cpp",
250
+ "rust",
251
+ "zig"
252
+ ],
253
+ "where": "**/*",
254
+ "issue": {
255
+ "type": "security",
256
+ "label": "use_after_free",
257
+ "pick": "strongest"
258
+ },
259
+ "min": 70,
260
+ "when": null,
261
+ "question": {
262
+ "type": "noul",
263
+ "instructions": "Can `method` use memory after it is freed?",
264
+ "criteria": {
265
+ "true": "It reads or writes through a pointer or reference after the memory is released.",
266
+ "false": "It never uses memory after release."
267
+ }
268
+ }
269
+ },
270
+ {
271
+ "name": "cwe_125",
272
+ "type": "noul",
273
+ "language": [
274
+ "c",
275
+ "cpp",
276
+ "rust",
277
+ "zig"
278
+ ],
279
+ "where": "**/*",
280
+ "issue": {
281
+ "type": "security",
282
+ "label": "out_of_bounds_read",
283
+ "pick": "strongest"
284
+ },
285
+ "min": 60,
286
+ "when": null,
287
+ "question": {
288
+ "type": "noul",
289
+ "instructions": "Can `method` read past the end of a buffer?",
290
+ "criteria": {
291
+ "true": "An index, pointer or length lets it read outside the memory it owns.",
292
+ "false": "Every read stays inside its buffer."
293
+ }
294
+ }
295
+ },
296
+ {
297
+ "name": "cwe_78",
298
+ "type": "noul",
299
+ "language": null,
300
+ "where": "**/*",
301
+ "issue": {
302
+ "type": "security",
303
+ "label": "os_command_injection",
304
+ "pick": "strongest"
305
+ },
306
+ "min": 70,
307
+ "when": null,
308
+ "question": {
309
+ "type": "noul",
310
+ "instructions": "Is `method` vulnerable to OS command injection?",
311
+ "criteria": {
312
+ "true": "Outside text becomes part of a shell command. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
313
+ "false": "Its commands are fixed, or pass arguments without a shell."
314
+ }
315
+ }
316
+ },
317
+ {
318
+ "name": "cwe_94",
319
+ "type": "noul",
320
+ "language": null,
321
+ "where": "**/*",
322
+ "issue": {
323
+ "type": "security",
324
+ "label": "code_injection",
325
+ "pick": "strongest"
326
+ },
327
+ "min": 70,
328
+ "when": null,
329
+ "question": {
330
+ "type": "noul",
331
+ "instructions": "Is `method` vulnerable to code injection?",
332
+ "criteria": {
333
+ "true": "Outside text is evaluated or compiled as code. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
334
+ "false": "It never runs outside input as code."
335
+ }
336
+ }
337
+ },
338
+ {
339
+ "name": "cwe_120",
340
+ "type": "noul",
341
+ "language": [
342
+ "c",
343
+ "cpp",
344
+ "rust",
345
+ "zig"
346
+ ],
347
+ "where": "**/*",
348
+ "issue": {
349
+ "type": "security",
350
+ "label": "buffer_overflow",
351
+ "pick": "strongest"
352
+ },
353
+ "min": 70,
354
+ "when": null,
355
+ "question": {
356
+ "type": "noul",
357
+ "instructions": "Can `method` copy more into a buffer than it holds?",
358
+ "criteria": {
359
+ "true": "A copy's length is not checked against the size of its destination.",
360
+ "false": "Every copy is bounded by its destination."
361
+ }
362
+ }
363
+ },
364
+ {
365
+ "name": "cwe_434",
366
+ "type": "noul",
367
+ "language": null,
368
+ "where": "**/*",
369
+ "issue": {
370
+ "type": "security",
371
+ "label": "unsafe_file_upload",
372
+ "pick": "strongest"
373
+ },
374
+ "min": 70,
375
+ "when": null,
376
+ "question": {
377
+ "type": "noul",
378
+ "instructions": "Does `method` accept a dangerous file upload?",
379
+ "criteria": {
380
+ "true": "An uploaded file of any type can be stored where it can be run or served. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
381
+ "false": "Uploads are checked, or stored where they cannot do harm."
382
+ }
383
+ }
384
+ },
385
+ {
386
+ "name": "cwe_476",
387
+ "type": "noul",
388
+ "language": [
389
+ "c",
390
+ "cpp",
391
+ "zig"
392
+ ],
393
+ "where": "**/*",
394
+ "issue": {
395
+ "type": "security",
396
+ "label": "null_dereference",
397
+ "pick": "strongest"
398
+ },
399
+ "min": 70,
400
+ "when": null,
401
+ "question": {
402
+ "type": "noul",
403
+ "instructions": "Can `method` dereference a null pointer?",
404
+ "criteria": {
405
+ "true": "A null pointer or reference is used on some path.",
406
+ "false": "Nulls are checked before use."
407
+ }
408
+ }
409
+ },
410
+ {
411
+ "name": "cwe_121",
412
+ "type": "noul",
413
+ "language": [
414
+ "c",
415
+ "cpp",
416
+ "rust",
417
+ "zig"
418
+ ],
419
+ "where": "**/*",
420
+ "issue": {
421
+ "type": "security",
422
+ "label": "stack_buffer_overflow",
423
+ "pick": "strongest"
424
+ },
425
+ "min": 70,
426
+ "when": null,
427
+ "question": {
428
+ "type": "noul",
429
+ "instructions": "Can `method` overflow a buffer on the stack?",
430
+ "criteria": {
431
+ "true": "A write can go past the end of a stack buffer.",
432
+ "false": "Its stack buffers are never overrun."
433
+ }
434
+ }
435
+ },
436
+ {
437
+ "name": "cwe_502",
438
+ "type": "noul",
439
+ "language": null,
440
+ "where": "**/*",
441
+ "issue": {
442
+ "type": "security",
443
+ "label": "unsafe_deserialization",
444
+ "pick": "strongest"
445
+ },
446
+ "min": 70,
447
+ "when": null,
448
+ "question": {
449
+ "type": "noul",
450
+ "instructions": "Does `method` deserialize untrusted data unsafely?",
451
+ "criteria": {
452
+ "true": "Outside data is deserialized in a way that can create arbitrary objects or run code. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
453
+ "false": "It deserializes only trusted data, or only plain values."
454
+ }
455
+ }
456
+ },
457
+ {
458
+ "name": "cwe_122",
459
+ "type": "noul",
460
+ "language": [
461
+ "c",
462
+ "cpp",
463
+ "rust",
464
+ "zig"
465
+ ],
466
+ "where": "**/*",
467
+ "issue": {
468
+ "type": "security",
469
+ "label": "heap_buffer_overflow",
470
+ "pick": "strongest"
471
+ },
472
+ "min": 70,
473
+ "when": null,
474
+ "question": {
475
+ "type": "noul",
476
+ "instructions": "Can `method` overflow a buffer on the heap?",
477
+ "criteria": {
478
+ "true": "A write can go past the end of a heap buffer.",
479
+ "false": "Its heap buffers are never overrun."
480
+ }
481
+ }
482
+ },
483
+ {
484
+ "name": "cwe_863",
485
+ "type": "noul",
486
+ "language": null,
487
+ "where": "**/*",
488
+ "issue": {
489
+ "type": "security",
490
+ "label": "incorrect_authorization",
491
+ "pick": "strongest"
492
+ },
493
+ "min": 70,
494
+ "when": null,
495
+ "question": {
496
+ "type": "noul",
497
+ "instructions": "Does `method` check authorization wrongly?",
498
+ "criteria": {
499
+ "true": "Its name, documentation or callers show who may perform its action, and its check lets through someone who should be refused.",
500
+ "false": "Its permission check is right."
501
+ }
502
+ }
503
+ },
504
+ {
505
+ "name": "cwe_284",
506
+ "type": "noul",
507
+ "language": null,
508
+ "where": "**/*",
509
+ "issue": {
510
+ "type": "security",
511
+ "label": "broken_access_control",
512
+ "pick": "strongest"
513
+ },
514
+ "min": 70,
515
+ "when": null,
516
+ "question": {
517
+ "type": "noul",
518
+ "instructions": "Does `method` let someone use something they should not have access to?",
519
+ "criteria": {
520
+ "true": "Its name, documentation or callers show a resource or action is protected, and it lets the wrong actor use it.",
521
+ "false": "Its access control is right."
522
+ }
523
+ }
524
+ },
525
+ {
526
+ "name": "cwe_200",
527
+ "type": "noul",
528
+ "language": null,
529
+ "where": "**/*",
530
+ "issue": {
531
+ "type": "security",
532
+ "label": "information_exposure",
533
+ "pick": "strongest"
534
+ },
535
+ "min": 70,
536
+ "when": null,
537
+ "question": {
538
+ "type": "noul",
539
+ "instructions": "Does `method` expose sensitive information?",
540
+ "criteria": {
541
+ "true": "It returns, logs or sends secrets, tokens or personal data to someone who should not see them.",
542
+ "false": "It exposes nothing sensitive."
543
+ }
544
+ }
545
+ },
546
+ {
547
+ "name": "cwe_306",
548
+ "type": "noul",
549
+ "language": null,
550
+ "where": "**/*",
551
+ "issue": {
552
+ "type": "security",
553
+ "label": "missing_authentication",
554
+ "pick": "strongest"
555
+ },
556
+ "min": 70,
557
+ "when": null,
558
+ "question": {
559
+ "type": "noul",
560
+ "instructions": "Does `method` skip authentication it needs?",
561
+ "criteria": {
562
+ "true": "Its name, documentation or callers show a sensitive action that needs a known caller, and it runs without authenticating one.",
563
+ "false": "It authenticates the caller, or needs no authentication."
564
+ }
565
+ }
566
+ },
567
+ {
568
+ "name": "cwe_918",
569
+ "type": "noul",
570
+ "language": null,
571
+ "where": "**/*",
572
+ "issue": {
573
+ "type": "security",
574
+ "label": "ssrf",
575
+ "pick": "strongest"
576
+ },
577
+ "min": 70,
578
+ "when": null,
579
+ "question": {
580
+ "type": "noul",
581
+ "instructions": "Is `method` vulnerable to server-side request forgery?",
582
+ "criteria": {
583
+ "true": "A destination taken from outside input decides where the server sends a request. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
584
+ "false": "Its destinations are fixed or checked against an allow list."
585
+ }
586
+ }
587
+ },
588
+ {
589
+ "name": "cwe_77",
590
+ "type": "noul",
591
+ "language": null,
592
+ "where": "**/*",
593
+ "issue": {
594
+ "type": "security",
595
+ "label": "command_injection",
596
+ "pick": "strongest"
597
+ },
598
+ "min": 70,
599
+ "when": null,
600
+ "question": {
601
+ "type": "noul",
602
+ "instructions": "Is `method` vulnerable to command injection?",
603
+ "criteria": {
604
+ "true": "Outside text changes a command passed to an interpreter. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
605
+ "false": "Its commands are fixed, or outside input is passed as data."
606
+ }
607
+ }
608
+ },
609
+ {
610
+ "name": "cwe_639",
611
+ "type": "noul",
612
+ "language": null,
613
+ "where": "**/*",
614
+ "issue": {
615
+ "type": "security",
616
+ "label": "idor",
617
+ "pick": "strongest"
618
+ },
619
+ "min": 70,
620
+ "when": null,
621
+ "question": {
622
+ "type": "noul",
623
+ "instructions": "Can a user reach someone else's data by changing an ID that `method` receives?",
624
+ "criteria": {
625
+ "true": "It looks up a record by an ID taken from outside input without checking the record belongs to the caller. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
626
+ "false": "It checks ownership, or its records are not per user."
627
+ }
628
+ }
629
+ },
630
+ {
631
+ "name": "cwe_770",
632
+ "type": "noul",
633
+ "language": null,
634
+ "where": "**/*",
635
+ "issue": {
636
+ "type": "security",
637
+ "label": "resource_exhaustion",
638
+ "pick": "strongest"
639
+ },
640
+ "min": 70,
641
+ "when": null,
642
+ "question": {
643
+ "type": "noul",
644
+ "instructions": "Can a request or other untrusted input make `method` use unbounded memory or work?",
645
+ "criteria": {
646
+ "true": "A size, count or depth taken from outside input sets how much it allocates or loops, with no limit. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
647
+ "false": "Its work is fixed, limited, or set only by the program's own data."
648
+ }
649
+ }
650
+ },
651
+ {
652
+ "name": "cwe_327",
653
+ "type": "noul",
654
+ "language": null,
655
+ "where": "**/*",
656
+ "issue": {
657
+ "type": "security",
658
+ "label": "weak_crypto",
659
+ "pick": "strongest"
660
+ },
661
+ "min": 70,
662
+ "when": null,
663
+ "question": {
664
+ "type": "noul",
665
+ "instructions": "Does `method` use weak cryptography?",
666
+ "criteria": {
667
+ "true": "It protects a password, token or secret with a broken algorithm such as MD5 or SHA-1, or uses predictable randomness where a value must be unguessable.",
668
+ "false": "Its cryptography is sound, or it uses none."
669
+ }
670
+ }
671
+ },
672
+ {
673
+ "name": "cwe_295",
674
+ "type": "noul",
675
+ "language": null,
676
+ "where": "**/*",
677
+ "issue": {
678
+ "type": "security",
679
+ "label": "disabled_certificate_check",
680
+ "pick": "strongest"
681
+ },
682
+ "min": 70,
683
+ "when": null,
684
+ "question": {
685
+ "type": "noul",
686
+ "instructions": "Does `method` turn off certificate checking?",
687
+ "criteria": {
688
+ "true": "TLS certificate or hostname verification is disabled or bypassed.",
689
+ "false": "It keeps certificate checking on, or makes no TLS connection."
690
+ }
691
+ }
692
+ },
693
+ {
694
+ "name": "cwe_798",
695
+ "type": "noul",
696
+ "language": null,
697
+ "where": "**/*",
698
+ "issue": {
699
+ "type": "security",
700
+ "label": "hardcoded_secret",
701
+ "pick": "strongest"
702
+ },
703
+ "min": 70,
704
+ "when": null,
705
+ "question": {
706
+ "type": "noul",
707
+ "instructions": "Does `method` contain a hard-coded credential?",
708
+ "criteria": {
709
+ "true": "A password, API key or private key is written in the source.",
710
+ "false": "It contains no credential."
711
+ }
712
+ }
713
+ },
714
+ {
715
+ "name": "cwe_190",
716
+ "type": "noul",
717
+ "language": [
718
+ "c",
719
+ "cpp",
720
+ "zig",
721
+ "rust",
722
+ "go",
723
+ "java",
724
+ "kotlin",
725
+ "c_sharp",
726
+ "swift",
727
+ "solidity"
728
+ ],
729
+ "where": "**/*",
730
+ "issue": {
731
+ "type": "security",
732
+ "label": "integer_overflow",
733
+ "pick": "strongest"
734
+ },
735
+ "min": 70,
736
+ "when": null,
737
+ "question": {
738
+ "type": "noul",
739
+ "instructions": "Can arithmetic in `method` overflow in a way that matters?",
740
+ "criteria": {
741
+ "true": "A calculation wraps or overflows and the result is used as a size, index, amount or security check.",
742
+ "false": "Its arithmetic cannot overflow, or an overflow does no harm."
743
+ }
744
+ }
745
+ },
746
+ {
747
+ "name": "cwe_908",
748
+ "type": "noul",
749
+ "language": [
750
+ "c",
751
+ "cpp",
752
+ "zig"
753
+ ],
754
+ "where": "**/*",
755
+ "issue": {
756
+ "type": "security",
757
+ "label": "uninitialized_use",
758
+ "pick": "strongest"
759
+ },
760
+ "min": 70,
761
+ "when": null,
762
+ "question": {
763
+ "type": "noul",
764
+ "instructions": "Can `method` read memory before it is written?",
765
+ "criteria": {
766
+ "true": "A variable, field or buffer is read before it is set on some path.",
767
+ "false": "Everything it reads is set first."
768
+ }
769
+ }
770
+ },
771
+ {
772
+ "name": "cwe_601",
773
+ "type": "noul",
774
+ "language": null,
775
+ "where": "**/*",
776
+ "issue": {
777
+ "type": "security",
778
+ "label": "open_redirect",
779
+ "pick": "strongest"
780
+ },
781
+ "min": 70,
782
+ "when": null,
783
+ "question": {
784
+ "type": "noul",
785
+ "instructions": "Is `method` vulnerable to an open redirect?",
786
+ "criteria": {
787
+ "true": "A redirect target taken from outside input can send users to any site. `method` or its callers show that input comes from a request, a message, or a file or argument a user supplied.",
788
+ "false": "Its redirect targets are fixed or checked."
789
+ }
790
+ }
791
+ }
792
+ ]
793
+ },
794
+ "pack_sha256": "bb53c8a6ca30920140e2bf33b2905d159e7b1709b29d1ea896637905dbf9047d",
795
+ "protocol_id": "perch-scan-bb53c8a6ca30",
796
+ "binary_protocol_id": "perch-scan-binary-bb53c8a6ca30"
797
+ }