File size: 18,219 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
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
"""Build and validate the structured research annotations."""

import ast
from collections import defaultdict
from hashlib import sha256
import json
from pathlib import Path
import re
import tomllib

from scripts.generate_dataset import build_dataset
from scripts.validate_dataset import DATA_PATH, CWE_IDS, read_records
from .verify import FIXTURE_LOCK, WORKER


ROOT = Path(__file__).resolve().parent
ANNOTATIONS = ROOT / "annotations.toml"
FIXTURES = ROOT / "fixtures"
BASELINE_SHA256 = "c36be954f003d107ec98ba48863ce5c4575d1660de26f75f38f148eb17633ccf"
FAMILIES = {
    "CWE-22": ("restricted-path-selection", "path_traversal"),
    "CWE-78": ("os-process-arguments", "command_injection"),
    "CWE-79": ("html-output-encoding", "cross_site_scripting"),
    "CWE-89": ("sql-statement-construction", "sql_injection"),
    "CWE-117": ("line-log-framing", "log_output_neutralization"),
    "CWE-209": ("public-error-details", "error_information_exposure"),
    "CWE-295": ("tls-peer-authentication", "improper_certificate_validation"),
    "CWE-338": ("prng-security-context", "cryptographically_weak_prng"),
    "CWE-378": ("temporary-file-modes", "insecure_temporary_file_permissions"),
    "CWE-502": ("deserialization-provenance", "untrusted_deserialization"),
    "CWE-532": ("private-operational-logs", "sensitive_information_in_logs"),
    "CWE-598": ("secret-request-location", "sensitive_query_string"),
    "CWE-614": ("https-cookie-policy", "missing_secure_cookie_attribute"),
    "CWE-798": ("credential-provisioning", "hardcoded_credentials"),
    "CWE-862": ("resource-authorization", "missing_authorization"),
    "CWE-916": ("password-work-factors", "insufficient_password_hash_effort"),
}
STATUSES = {"behavior_verified", "reviewed_static", "unverified", "ambiguous"}
DIFFICULTIES = {"introductory", "intermediate", "advanced"}
LABEL_ORDER = ("insecure", "secure")
SLUG = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)+")
SAMPLE_ID = re.compile(r"psp-[0-9a-f]{12}")
PATH_NAME = re.compile(r"[a-z][a-z0-9_]*\.py")
ANNOTATION_FIELDS = {
    "id", "cwe", "source", "sink", "flow", "control", "review", "difficulty", "framework",
    "insecure", "secure", "secure_status", "status", "finding", "weak_control", "secure_flow",
}
RECORD_FIELDS = {
    "id", "sample_id", "pair_id", "scenario_family_id", "cwe_id", "vulnerability_type",
    "label", "code", "code_files", "language", "framework", "source_location", "sink_location",
    "source_type", "taint_path", "sanitization", "vulnerable_lines", "expected_finding",
    "fix_explanation", "verification_status", "verification_method", "evidence_reference",
    "difficulty", "provenance", "split", "leakage_group_id", "hard_negative", "pattern",
    "explanation", "secure_fix", "review_note",
}


def legacy_rows():
    baseline = build_dataset()
    if sha256(baseline).hexdigest() != BASELINE_SHA256 or DATA_PATH.read_bytes() != baseline:
        raise ValueError("The audited 64-row compatibility baseline has changed")
    return {(row["pattern"], row["label"]): row for _, row in read_records(baseline)}


def read_annotations(source):
    with source.open("rb") as handle:
        return tomllib.load(handle)


def select(anchor, label):
    if isinstance(anchor, list):
        if len(anchor) != 2 or any(not isinstance(item, str) for item in anchor):
            raise ValueError("A per-variant anchor needs two strings in insecure/secure order")
        return anchor[LABEL_ORDER.index(label)]
    return anchor


def resolve_location(files, entry, anchor):
    if anchor is None or anchor == "":
        return None
    if not isinstance(anchor, str):
        raise ValueError("Location anchor must be text")
    path, _, fragment = anchor.partition("::")
    if not fragment:
        path, fragment = entry, path
    lines = [
        number
        for file in files if file["path"] == path
        for number, line in enumerate(file["code"].splitlines(), start=1) if fragment in line
    ]
    if len(lines) != 1:
        raise ValueError(f"Anchor {anchor!r} in {path} matches {len(lines)} lines")
    return {"path": path, "start_line": lines[0], "end_line": lines[0]}


def fixture_files(kind, slug, label, locked):
    group = {"legacy": "legacy", "scenario": "scenarios", "negative": "negatives"}[kind]
    directory = FIXTURES / group / slug
    if kind != "negative":
        directory /= label
    files = []
    for path in sorted(directory.glob("*.py")):
        source = path.read_bytes()
        name = path.relative_to(FIXTURES).as_posix()
        if sha256(source).hexdigest() != locked.get(name):
            raise ValueError(f"Fixture source {name!r} differs from its reviewed hash")
        files.append({"path": path.name, "code": source.decode("utf-8")})
    return files


def display_code(files):
    if len(files) == 1:
        return files[0]["code"]
    return "\n".join(f"# file: {item['path']}\n{item['code']}" for item in files)


def check_annotation(spec, kind):
    if not isinstance(spec, dict) or spec.keys() - ANNOTATION_FIELDS:
        raise ValueError("Invalid annotation fields")
    if not isinstance(spec.get("id"), str) or not SLUG.fullmatch(spec["id"]):
        raise ValueError("Invalid scenario ID")
    for name in ("sink", "review", "control"):
        if not spec.get(name):
            raise ValueError(f"{spec['id']}: missing {name}")
    for name in ("status", "secure_status"):
        if name in spec and spec[name] not in {"reviewed_static", "unverified", "ambiguous"}:
            raise ValueError(f"{spec['id']}: executable status must come from the verifier")
    if kind == "legacy" and spec.keys() & {"cwe", "secure", "insecure"}:
        raise ValueError("Legacy identity and text come from the compatibility baseline")
    if kind != "legacy":
        required = {"cwe", "secure"} | ({"insecure"} if kind == "scenario" else set())
        if required - spec.keys() or spec["cwe"] not in CWE_IDS:
            raise ValueError(f"{spec['id']}: new example needs a known CWE and rationale(s)")
    for field in ("flow", "secure_flow"):
        flow = spec.get(field)
        if flow is not None and (
            not isinstance(flow, list) or len(flow) < 2
            or any(not isinstance(step, str) or not step.strip() for step in flow)
        ):
            raise ValueError(f"{spec['id']}: malformed source-to-sink description")


def make_row(kind, spec, label, baseline, case, files):
    slug = spec["id"]
    if baseline:
        if files and files != [{"path": "subject.py", "code": baseline["code"]}]:
            raise ValueError(f"{slug}: mirrored legacy fixture differs from the baseline")
        files = [{"path": "snippet.py", "code": baseline["code"]}]
        entry = "snippet.py"
    else:
        entry = "subject.py"
    if entry not in {item["path"] for item in files}:
        raise ValueError(f"{slug}: missing {entry}")
    sink = resolve_location(files, entry, select(spec["sink"], label))
    source = resolve_location(files, entry, select(spec.get("source"), label))
    hit = label == "insecure"
    finding = spec.get("finding")
    if hit and finding:
        anchors = finding if isinstance(finding, list) else [finding]
        findings = [resolve_location(files, entry, anchor) for anchor in anchors]
    else:
        findings = [sink] if hit else []
    default_status = spec.get("status", "reviewed_static")
    if label == "secure":
        default_status = spec.get("secure_status", default_status)
    if case and default_status != "reviewed_static":
        raise ValueError(f"{slug}: the observation conflicts with its source-review status")
    status = "behavior_verified" if case else default_status
    sample_id = (
        baseline["id"] if baseline else "psp-" + sha256(f"{slug}:{label}".encode()).hexdigest()[:12]
    )
    cwe = baseline["cwe_id"] if baseline else spec["cwe"]
    family, weakness = FAMILIES[cwe]
    explanation = baseline["explanation"] if baseline else spec[label]
    fix = baseline["secure_fix"] if baseline else spec["control"]
    return {
        "id": sample_id,
        "sample_id": sample_id,
        "pair_id": None if kind == "negative" else slug,
        "scenario_family_id": family,
        "cwe_id": cwe,
        "vulnerability_type": weakness,
        "label": label,
        "code": display_code(files),
        "code_files": files,
        "language": "python",
        "framework": spec.get("framework"),
        "source_location": source,
        "sink_location": sink,
        "source_type": "synthetic",
        "taint_path": spec.get("flow" if hit else "secure_flow"),
        "sanitization": spec["control"] if not hit else spec.get("weak_control"),
        "vulnerable_lines": findings,
        "expected_finding": hit,
        "fix_explanation": fix,
        "verification_status": status,
        "verification_method": case["method"] if case else (
            "ai_assisted_static_review" if status in {"reviewed_static", "ambiguous"} else None
        ),
        "evidence_reference": f"data/research/evidence.json::cases/{slug}" if case else None,
        "difficulty": spec.get("difficulty", "introductory"),
        "provenance": {
            "origin": "original_synthetic",
            "collection": {"legacy": "preserved_baseline", "scenario": "research_pair", "negative": "hard_negative"}[kind],
            "authoring": "ai_assisted",
            "independent_human_review": False,
        },
        "split": None,
        "leakage_group_id": None,
        "hard_negative": kind == "negative",
        "pattern": slug,
        "explanation": explanation,
        "secure_fix": fix,
        "review_note": spec["review"],
    }


def build_records(evidence, annotations=ANNOTATIONS):
    source = read_annotations(annotations)
    if set(source) != {"legacy", "scenario", "negative"}:
        raise ValueError("Annotations must contain legacy, scenario, and negative lists")
    old = legacy_rows()
    lock = FIXTURE_LOCK.read_bytes()
    if (
        evidence.get("version") != 1
        or evidence.get("fixture_lock_sha256") != sha256(lock).hexdigest()
        or evidence.get("suite_sha256") != sha256(WORKER.read_bytes()).hexdigest()
    ):
        raise ValueError("Evidence was produced for different verifier or fixture sources")
    locked = json.loads(lock)
    cases = evidence["cases"]
    declared, used, legacy_seen = set(), set(), set()
    rows = []
    for kind, specs in source.items():
        for spec in specs:
            check_annotation(spec, kind)
            slug = spec["id"]
            if slug in declared:
                raise ValueError(f"Duplicate annotation for {slug}")
            declared.add(slug)
            labels = ("secure",) if kind == "negative" else LABEL_ORDER
            case = cases.get(slug)
            sources = {label: fixture_files(kind, slug, label, locked) for label in labels}
            checked = any(sources.values())
            if (checked or kind != "legacy") and case is None:
                raise ValueError(f"{slug}: missing executable evidence")
            if case is not None:
                observations = case.get("observations")
                if (
                    not checked or case.get("result") != "pass" or not case.get("method")
                    or not isinstance(observations, dict) or not observations
                    or (kind != "negative" and set(observations) != {"secure", "insecure", "normal"})
                    or (kind != "negative" and not all(observations.values()))
                ):
                    raise ValueError(f"{slug}: missing or invalid evidence observations")
                used.add(slug)
            for label in labels:
                key = (slug, label)
                baseline = old.get(key) if kind == "legacy" else None
                if kind == "legacy":
                    if baseline is None or (case and not sources[label]):
                        raise ValueError(f"{slug}: missing legacy sample or executable mirror")
                    legacy_seen.add(key)
                try:
                    rows.append(make_row(kind, spec, label, baseline, case, sources[label]))
                except ValueError as error:
                    raise ValueError(f"{slug} ({label}): {error}") from error
    if legacy_seen != set(old) or used != set(cases):
        raise ValueError("The catalog must cover the entire baseline and every evidence entry")
    return sorted(rows, key=lambda row: row["sample_id"])


def validate_location(location, files, sample_id):
    if location is None:
        return
    if not isinstance(location, dict) or location.keys() != {"path", "start_line", "end_line"}:
        raise ValueError(f"{sample_id}: malformed location")
    start, end = location["start_line"], location["end_line"]
    if type(start) is not int or type(end) is not int or not 1 <= start <= end <= files.get(location["path"], 0):
        raise ValueError(f"{sample_id}: location is outside its source file")


def validate_rows(rows, evidence):
    ids = set()
    pairs = defaultdict(list)
    for row in rows:
        if row.keys() != RECORD_FIELDS:
            raise ValueError("Research schema fields do not match")
        sample_id = row["sample_id"]
        if not isinstance(sample_id, str) or not SAMPLE_ID.fullmatch(sample_id) or row["id"] != sample_id or sample_id in ids:
            raise ValueError(f"Duplicate or invalid sample identity {sample_id}")
        ids.add(sample_id)
        if row["cwe_id"] not in CWE_IDS or (
            row["scenario_family_id"], row["vulnerability_type"]
        ) != FAMILIES[row["cwe_id"]]:
            raise ValueError(f"{sample_id}: invalid CWE, family, or type")
        if row["label"] not in LABEL_ORDER or row["language"] != "python" or row["source_type"] != "synthetic":
            raise ValueError(f"{sample_id}: invalid label, language, or source type")
        if row["difficulty"] not in DIFFICULTIES or row["verification_status"] not in STATUSES:
            raise ValueError(f"{sample_id}: invalid difficulty or verification status")
        if row["framework"] is not None and not isinstance(row["framework"], str):
            raise ValueError(f"{sample_id}: invalid framework")
        for field in ("code", "pattern", "explanation", "secure_fix", "fix_explanation", "review_note"):
            if not isinstance(row[field], str) or not row[field].strip():
                raise ValueError(f"{sample_id}: {field} must be non-empty text")
        if row["secure_fix"] != row["fix_explanation"]:
            raise ValueError(f"{sample_id}: compatibility and research fixes disagree")
        if not isinstance(row["vulnerable_lines"], list) or None in row["vulnerable_lines"]:
            raise ValueError(f"{sample_id}: invalid finding locations")
        hit = row["label"] == "insecure"
        if row["expected_finding"] is not hit or bool(row["vulnerable_lines"]) != hit:
            raise ValueError(f"{sample_id}: finding disagrees with label")
        if type(row["hard_negative"]) is not bool or row["hard_negative"] != (row["pair_id"] is None):
            raise ValueError(f"{sample_id}: hard negative and pair disagree")
        if row["hard_negative"] and hit:
            raise ValueError(f"{sample_id}: hard negative marked insecure")
        if row["pair_id"] is not None:
            if row["pair_id"] != row["pattern"]:
                raise ValueError(f"{sample_id}: pair identity differs from its scenario")
            pairs[row["pair_id"]].append(row)
        if not SLUG.fullmatch(row["pattern"]):
            raise ValueError(f"{sample_id}: invalid pattern")
        provenance = row["provenance"]
        if not isinstance(provenance, dict) or provenance.keys() != {
            "origin", "collection", "authoring", "independent_human_review",
        } or provenance["origin"] != "original_synthetic" or provenance["authoring"] != "ai_assisted":
            raise ValueError(f"{sample_id}: invalid provenance")
        if provenance["independent_human_review"] is not False:
            raise ValueError(f"{sample_id}: unsupported independent review claim")

        files = {}
        for item in row["code_files"]:
            if item.keys() != {"path", "code"} or not PATH_NAME.fullmatch(item["path"]) or item["path"] in files:
                raise ValueError(f"{sample_id}: invalid or repeated source file")
            tree = ast.parse(item["code"], filename=item["path"], feature_version=(3, 11))
            if not tree.body:
                raise ValueError(f"{sample_id}: empty source file")
            compile(tree, item["path"], "exec", dont_inherit=True)
            files[item["path"]] = len(item["code"].splitlines())
        if not files or row["code"] != display_code(row["code_files"]):
            raise ValueError(f"{sample_id}: code and source files disagree")
        for location in (row["source_location"], row["sink_location"], *row["vulnerable_lines"]):
            validate_location(location, files, sample_id)
        if row["sink_location"] is None:
            raise ValueError(f"{sample_id}: responsible operation location required")
        case = evidence["cases"].get(row["pattern"])
        if row["verification_status"] == "behavior_verified":
            if (
                not case or case["result"] != "pass" or not case["observations"]
                or row["verification_method"] != case["method"]
                or row["evidence_reference"] != f"data/research/evidence.json::cases/{row['pattern']}"
            ):
                raise ValueError(f"{sample_id}: verified record lacks matching executable evidence")
        elif case is not None or row["evidence_reference"] is not None:
            raise ValueError(f"{sample_id}: nonverified record claims executable evidence")
    for pair_id, members in pairs.items():
        if len(members) != 2 or {row["label"] for row in members} != set(LABEL_ORDER):
            raise ValueError(f"{pair_id}: exactly one secure and one insecure row required")
        for field in ("cwe_id", "scenario_family_id", "fix_explanation"):
            if members[0][field] != members[1][field]:
                raise ValueError(f"{pair_id}: members disagree on {field}")