python-security-benchmark / scripts /generate_dataset.py
Helinity's picture
Release v0.1.0: sanitized Python security research benchmark
1340dfb
Raw History Blame Contribute Delete
4.16 kB
"""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())