File size: 5,853 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
"""Validate the JSONL corpus without importing or executing its snippets."""

import argparse
import ast
from collections import Counter, defaultdict
from dataclasses import dataclass
from hashlib import sha256
import json
from pathlib import Path
import re
import sys


DATA_PATH = Path(__file__).resolve().parents[1] / "data" / "examples.jsonl"
FIELDS = {
    "id", "code", "label", "cwe_id", "pattern", "explanation", "secure_fix", "source_type",
}
LABELS = {"secure", "insecure"}
CWE_IDS = {
    "CWE-22", "CWE-78", "CWE-79", "CWE-89", "CWE-117", "CWE-209", "CWE-295",
    "CWE-338", "CWE-378", "CWE-502", "CWE-532", "CWE-598", "CWE-614", "CWE-798",
    "CWE-862", "CWE-916",
}
MIN_ROWS = 60
MIN_PAIRS_PER_CWE = 2
ID_FORMAT = re.compile(r"psp-[0-9a-f]{12}")
PATTERN_FORMAT = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)+")


class DatasetError(ValueError):
    """An input violates a dataset invariant."""


@dataclass(frozen=True)
class Summary:
    rows: int
    patterns: int
    cwes: int
    labels: dict[str, int]
    digest: str


def reject_duplicate_keys(pairs):
    obj = {}
    for key, value in pairs:
        if key in obj:
            raise DatasetError(f"duplicate JSON key {key!r}")
        obj[key] = value
    return obj


def read_records(data):
    try:
        content = data.decode("utf-8")
    except UnicodeDecodeError as exc:
        raise DatasetError("expected UTF-8 JSONL") from exc

    for line_number, line in enumerate(content.removesuffix("\n").split("\n"), start=1):
        if not line.strip():
            raise DatasetError(f"line {line_number}: blank record")
        try:
            row = json.loads(line, object_pairs_hook=reject_duplicate_keys)
        except json.JSONDecodeError as exc:
            raise DatasetError(f"line {line_number}: invalid JSON ({exc.msg})") from exc
        except DatasetError as exc:
            raise DatasetError(f"line {line_number}: {exc}") from exc
        yield line_number, row


def check_fields(row):
    if not isinstance(row, dict):
        raise DatasetError("expected a JSON object")
    if row.keys() != FIELDS:
        missing = sorted(FIELDS - row.keys())
        unexpected = sorted(row.keys() - FIELDS)
        raise DatasetError(f"incorrect fields (missing={missing}, unexpected={unexpected})")
    for field, value in row.items():
        if not isinstance(value, str) or not value.strip():
            raise DatasetError(f"{field} must be a non-empty string")
    if not ID_FORMAT.fullmatch(row["id"]):
        raise DatasetError(f"invalid id {row['id']!r}")
    if not PATTERN_FORMAT.fullmatch(row["pattern"]):
        raise DatasetError(f"invalid pattern {row['pattern']!r}")
    if row["label"] not in LABELS:
        raise DatasetError(f"unknown label {row['label']!r}")
    if row["cwe_id"] not in CWE_IDS:
        raise DatasetError(f"unsupported CWE {row['cwe_id']!r}")
    if row["source_type"] != "synthetic":
        raise DatasetError("source_type must be synthetic")


def code_fingerprint(row):
    try:
        tree = ast.parse(row["code"], filename=row["id"], feature_version=(3, 11))
        # Compilation catches context errors that parsing alone accepts.
        compile(tree, row["id"], "exec", dont_inherit=True)
    except (SyntaxError, ValueError) as exc:
        raise DatasetError(f"invalid Python syntax ({exc})") from exc
    if not tree.body:
        raise DatasetError("code has no Python statements")
    return ast.dump(tree, include_attributes=False)


def validate_bytes(data):
    labels = Counter()
    groups = defaultdict(list)
    id_lines = {}
    code_lines = {}

    for line, row in read_records(data):
        try:
            check_fields(row)
            row_id = row["id"]
            if row_id in id_lines:
                raise DatasetError(f"duplicate id {row_id!r} (first seen on line {id_lines[row_id]})")
            fingerprint = code_fingerprint(row)
            if fingerprint in code_lines:
                raise DatasetError(f"duplicate code (first seen on line {code_lines[fingerprint]})")
        except DatasetError as exc:
            raise DatasetError(f"line {line}: {exc}") from exc

        id_lines[row_id] = line
        code_lines[fingerprint] = line
        groups[row["pattern"]].append(row)
        labels[row["label"]] += 1

    if len(id_lines) < MIN_ROWS:
        raise DatasetError(f"expected at least {MIN_ROWS} rows, found {len(id_lines)}")

    cwes = Counter()
    for pattern, pair in groups.items():
        if len(pair) != 2 or {row["label"] for row in pair} != LABELS:
            raise DatasetError(f"{pattern}: expected one secure and one insecure example")
        for field in ("cwe_id", "secure_fix"):
            if pair[0][field] != pair[1][field]:
                raise DatasetError(f"{pattern}: pair disagrees on {field}")
        cwes[pair[0]["cwe_id"]] += 1

    for cwe_id in sorted(CWE_IDS):
        if cwes[cwe_id] < MIN_PAIRS_PER_CWE:
            raise DatasetError(f"{cwe_id} needs at least two pairs (found {cwes[cwe_id]})")
    return Summary(len(id_lines), len(groups), len(cwes), dict(labels), sha256(data).hexdigest())


def validate(path):
    return validate_bytes(path.read_bytes())


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("path", nargs="?", default=DATA_PATH, type=Path, help="JSONL file to validate")
    args = parser.parse_args()
    try:
        summary = validate(args.path)
    except (OSError, DatasetError) as exc:
        print(f"Validation failed: {exc}", file=sys.stderr)
        return 1
    print(
        f"Valid: {summary.rows} rows ({summary.labels['secure']} secure, "
        f"{summary.labels['insecure']} insecure), {summary.patterns} pairs, {summary.cwes} CWEs."
    )
    print(f"SHA-256: {summary.digest}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())