File size: 4,155 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
"""Generate the checked-in JSONL corpus deterministically from the curation file."""

import argparse
from hashlib import sha256
import json
import getpass
import re
from pathlib import Path
import sys
from tempfile import NamedTemporaryFile
import tomllib

if __package__:
    from .validate_dataset import DATA_PATH, validate_bytes
else:
    from validate_dataset import DATA_PATH, validate_bytes


SOURCE_PATH = Path(__file__).resolve().parents[1] / "curation" / "pairs.toml"
PAIR_FIELDS = {
    "pattern", "cwe_id", "secure_fix", "secure_code", "insecure_code",
    "secure_explanation", "insecure_explanation",
}


def sanitize_log_output(text):
    """Keep captured validation diagnostics portable and free of local identities."""
    root = str(SOURCE_PATH.parents[1])
    for value in (root, root.replace('\\', '/')):
        text = text.replace(value + '\\', '').replace(value + '/', '')
    text = re.sub(r'[A-Za-z]:[\\/][^\s\"\'<>]*', '<local-path>', text)
    text = re.sub(r'(?<![\w:])/(?:[^/\s\"\'<>]+/)*[^\s\"\'<>]*', '<local-path>', text)
    text = re.sub(r'(?<![\w.-])[\w.+%-]+@[\w.-]+\.[A-Za-z]{2,}', '<email>', text)
    username = getpass.getuser()
    if username:
        text = re.sub(r'(?<!\w)' + re.escape(username) + r'(?!\w)', '<local-user>', text, flags=re.I)
    return text


def build_dataset(source=SOURCE_PATH):
    with source.open("rb") as handle:
        manifest = tomllib.load(handle)
    pairs = manifest.get("pair")
    if manifest.keys() != {"pair"} or not isinstance(pairs, list):
        raise ValueError("expected a TOML manifest containing only [[pair]] entries")

    rows = []
    for index, pair in enumerate(pairs, start=1):
        if (
            not isinstance(pair, dict)
            or pair.keys() != PAIR_FIELDS
            or any(not isinstance(value, str) for value in pair.values())
        ):
            raise ValueError(f"pair {index}: expected these string fields: {', '.join(sorted(PAIR_FIELDS))}")
        for label in ("insecure", "secure"):
            identity = f"{pair['pattern']}:{label}".encode("utf-8")
            rows.append({
                "id": "psp-" + sha256(identity).hexdigest()[:12],
                "code": pair[f"{label}_code"].rstrip() + "\n",
                "label": label,
                "cwe_id": pair["cwe_id"],
                "pattern": pair["pattern"],
                "explanation": pair[f"{label}_explanation"],
                "secure_fix": pair["secure_fix"],
                "source_type": "synthetic",
            })

    rows.sort(key=lambda row: row["id"])
    content = "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows).encode("utf-8")
    validate_bytes(content)
    return content


def write_dataset(output, content):
    output.parent.mkdir(parents=True, exist_ok=True)
    handle = NamedTemporaryFile(dir=output.parent, suffix=".tmp", delete=False)
    temporary = Path(handle.name)
    try:
        with handle:
            handle.write(content)
        temporary.replace(output)
    finally:
        temporary.unlink(missing_ok=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=DATA_PATH, help="output JSONL path")
    parser.add_argument("--check", action="store_true", help="compare bytes without writing")
    args = parser.parse_args()
    try:
        content = build_dataset()
        if args.check:
            try:
                existing = args.output.read_bytes()
            except FileNotFoundError as exc:
                raise ValueError(f"{args.output} is missing; regenerate the dataset") from exc
            if existing != content:
                raise ValueError(f"{args.output} is stale; regenerate the dataset")
            print(sanitize_log_output(f"Current: {args.output}"))
        else:
            write_dataset(args.output, content)
            print(sanitize_log_output(f"Generated: {args.output}"))
    except (OSError, ValueError) as exc:
        print(sanitize_log_output(f"Generation failed: {exc}"), file=sys.stderr)
        return 1
    return 0


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