#!/usr/bin/env python3 """Normalize audited source subsets into consistent Hugging Face JSONL splits.""" from __future__ import annotations import argparse import hashlib import json from collections import Counter, defaultdict from pathlib import Path from prepare_benchmarkjava import ( CASES as BENCHMARKJAVA_CASES, COMMIT as BENCHMARKJAVA_COMMIT, EXPECTED_RESULTS_SHA256 as BENCHMARKJAVA_RESULTS_SHA256, LICENSE_SHA256 as BENCHMARKJAVA_LICENSE_SHA256, check_sample_license, ) SOURCE_FILES = ( "openzeppelin_solidity_references.jsonl", "juice_shop_codefix_pairs.jsonl", "webgoat_review_examples.jsonl", "benchmarkjava_review_examples.jsonl", ) FIELDS = ( "id", "source", "task_type", "domain", "language", "instruction", "input", "output", "split", "labels_json", "provenance_json", ) CORE = {"id", "task_type", "domain", "language", "instruction", "input", "output", "split"} EXPECTED_SOURCE_COUNTS = { "OWASP Juice Shop": 83, "OpenZeppelin Contracts v5.7.0": 5, "OWASP WebGoat": 3, "OWASP BenchmarkJava v1.2": 22, } EXPECTED_SPLIT_COUNTS = { "challenge_fix": 83, "reference": 5, "webgoat_review": 3, "benchmarkjava_review": 22, } WEBGOAT_COMMIT = "4e98f1cbbf896fdd06edcc9930515ebe0ade7c69" WEBGOAT_LICENSE_SHA256 = "2fea812568866fdb6ff99671ad70465bfc25ab77f86129795d08d961c30d2ca1" WEBGOAT_LICENSE_TEXT_SHA256 = "aaf135472f81c5b4a0dca9367e5bb5e9750032b5bebe5442b36e4c0a47430df3" WEBGOAT_EXPECTED = { "webgoat-sqli-dynamic-order-by": "12edc65052421ffb180ef9b9137c5ef33bf4c7e65e7a575f76766da7e6be67e7", "webgoat-sqli-lesson-5a": "c9e59f1accc15d5b5b8161d7c5727ab46201f417005d8783e9e3cccebd1ca9fa", "webgoat-sqli-prepared-statement-reference": "60a88672f13a18f6c436aa962eaab426563014bd6b1015b3290a95f6c39f4f3f", } def read_jsonl(path: Path) -> list[dict]: rows = [] with path.open(encoding="utf-8") as handle: for line_number, line in enumerate(handle, 1): if not line.strip(): continue value = json.loads(line) if not isinstance(value, dict): raise ValueError(f"{path}:{line_number}: expected a JSON object") rows.append(value) return rows def parse_label_output(row: dict) -> dict: try: parsed = json.loads(row["output"]) if isinstance(parsed, dict): return parsed except (json.JSONDecodeError, TypeError): pass return {"reference_summary": row["output"]} def source_name(row: dict) -> str: if row.get("source_repo") == "juice-shop/juice-shop": return "OWASP Juice Shop" if row.get("source_version") == "v5.7.0": return "OpenZeppelin Contracts v5.7.0" if row.get("source_repo") == "WebGoat/WebGoat" and row.get("source_commit") == WEBGOAT_COMMIT: return "OWASP WebGoat" if ( row.get("source_repo") == "OWASP-Benchmark/BenchmarkJava" and row.get("source_commit") == BENCHMARKJAVA_COMMIT ): return "OWASP BenchmarkJava v1.2" raise ValueError(f"Unsupported source record: {row.get('id')}") def validate_source_record(row: dict, source: str) -> None: for key in CORE: if key not in row: raise ValueError(f"Record {row.get('id')} lacks {key}") if not all(isinstance(row[key], str) for key in ("id", "input", "output", "language", "instruction")): raise TypeError(f"Record {row['id']} has a non-string core field") if source == "OpenZeppelin Contracts v5.7.0": if hashlib.sha256(row["input"].encode("utf-8")).hexdigest() != row["source_sha256"]: raise ValueError(f"OpenZeppelin source hash mismatch: {row['id']}") if row["split"] != "reference": raise ValueError(f"Unexpected OpenZeppelin split: {row['id']}") elif source == "OWASP Juice Shop": if hashlib.sha256(row["input"].encode("utf-8")).hexdigest() != row["candidate_sha256"]: raise ValueError(f"Juice Shop candidate hash mismatch: {row['id']}") output = json.loads(row["output"]) if hashlib.sha256(output["approved_code"].encode("utf-8")).hexdigest() != row["correct_sha256"]: raise ValueError(f"Juice Shop approved-code hash mismatch: {row['id']}") if output.get("candidate_label") != "not_marked_correct_by_upstream_challenge": raise ValueError(f"Unexpected candidate label: {row['id']}") if output.get("approved_label") != "marked_correct_by_upstream_challenge": raise ValueError(f"Unexpected approved label: {row['id']}") if row["split"] != "challenge_fix": raise ValueError(f"Unexpected Juice Shop split: {row['id']}") elif source == "OWASP WebGoat": actual_hash = hashlib.sha256(row["input"].encode("utf-8")).hexdigest() if actual_hash != row.get("source_sha256") or actual_hash != WEBGOAT_EXPECTED.get(row["id"]): raise ValueError(f"WebGoat source hash mismatch: {row['id']}") if row.get("source_license") != "GPL-2.0-or-later" or row.get("source_spdx") != "GPL-2.0-or-later": raise ValueError(f"Unexpected WebGoat license metadata: {row['id']}") if row.get("source_license_file_sha256") != WEBGOAT_LICENSE_SHA256: raise ValueError(f"WebGoat upstream license hash mismatch: {row['id']}") if row.get("full_license_text_sha256") != WEBGOAT_LICENSE_TEXT_SHA256: raise ValueError(f"WebGoat GPL text hash mismatch: {row['id']}") if "SPDX-License-Identifier: GPL-2.0-or-later" not in "\n".join(row["input"].splitlines()[:8]): raise ValueError(f"WebGoat file-level license notice missing: {row['id']}") if row["split"] != "webgoat_review" or row["language"] != "Java": raise ValueError(f"Unexpected WebGoat split/language: {row['id']}") if row.get("curation_modified_at") != "2026-11-24": raise ValueError(f"WebGoat record lacks the curation modification date: {row['id']}") notice = row.get("modification_notice", "") if "curated or modified on 2026-11-24" not in notice or "GPL-2.0-or-later" not in notice: raise ValueError(f"WebGoat record lacks a clear modification/license notice: {row['id']}") if not row.get("verification_test_url") or not row.get("verification_test_sha256"): raise ValueError(f"WebGoat record lacks test provenance: {row['id']}") output = json.loads(row["output"]) expected_labels = { "webgoat-sqli-dynamic-order-by": "intentionally_vulnerable_sql_injection_example", "webgoat-sqli-lesson-5a": "intentionally_vulnerable_sql_injection_example", "webgoat-sqli-prepared-statement-reference": "secure_reference_pattern", } if output.get("classification") != expected_labels.get(row["id"]): raise ValueError(f"Unexpected WebGoat label: {row['id']}") if row["id"] == "webgoat-sqli-dynamic-order-by" and not output.get("fix_snippet"): raise ValueError("Dynamic ORDER BY sample lacks its curator-authored fix snippet") elif source == "OWASP BenchmarkJava v1.2": test_name = Path(row.get("source_file", "")).stem spec = BENCHMARKJAVA_CASES.get(test_name) if spec is None: raise ValueError(f"Unexpected BenchmarkJava source file: {row.get('source_file')}") category, expected_vulnerable, cwe, expected_hash = spec actual_hash = hashlib.sha256(row["input"].encode("utf-8")).hexdigest() if actual_hash != expected_hash or actual_hash != row.get("source_sha256"): raise ValueError(f"BenchmarkJava source hash mismatch: {row['id']}") if row.get("source_license") != "GPL-2.0-only" or row.get("source_spdx") != "GPL-2.0-only": raise ValueError(f"Unexpected BenchmarkJava sample license: {row['id']}") if row.get("source_license_file_sha256") != BENCHMARKJAVA_LICENSE_SHA256: raise ValueError(f"BenchmarkJava GPLv2 license hash mismatch: {row['id']}") if row.get("expected_results_sha256") != BENCHMARKJAVA_RESULTS_SHA256: raise ValueError(f"BenchmarkJava expected-results hash mismatch: {row['id']}") check_sample_license(row["input"], test_name) if row.get("source_version") != "v1.2": raise ValueError(f"Unexpected BenchmarkJava version: {row['id']}") if row["split"] != "benchmarkjava_review" or row["language"] != "Java": raise ValueError(f"Unexpected BenchmarkJava split/language: {row['id']}") if row["id"] != f"owasp-benchmarkjava-{test_name.lower()}": raise ValueError(f"BenchmarkJava record ID does not match source file: {row['id']}") output = json.loads(row["output"]) expected_classification = ( "benchmark_expected_vulnerable" if expected_vulnerable else "benchmark_expected_not_vulnerable" ) if ( output.get("classification") != expected_classification or output.get("expected_vulnerability") is not expected_vulnerable or output.get("benchmark_category") != category or output.get("cwe") != f"CWE-{cwe}" ): raise ValueError(f"BenchmarkJava label mismatch: {row['id']}") def normalize(row: dict) -> dict: source = source_name(row) validate_source_record(row, source) provenance = {key: value for key, value in row.items() if key not in CORE} return { "id": row["id"], "source": source, "task_type": row["task_type"], "domain": row["domain"], "language": row["language"], "instruction": row["instruction"], "input": row["input"], "output": row["output"], "split": row["split"], "labels_json": json.dumps(parse_label_output(row), ensure_ascii=False, sort_keys=True), "provenance_json": json.dumps(provenance, ensure_ascii=False, sort_keys=True), } def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--staging", type=Path, default=Path("staging")) parser.add_argument("--out", type=Path, default=Path("data")) args = parser.parse_args() normalized = [] for filename in SOURCE_FILES: source_path = args.staging / filename if not source_path.exists(): raise FileNotFoundError(source_path) normalized.extend(normalize(row) for row in read_jsonl(source_path)) ids = [row["id"] for row in normalized] if len(ids) != len(set(ids)): raise ValueError("Duplicate record IDs in merged dataset") counts = Counter(row["source"] for row in normalized) if dict(counts) != EXPECTED_SOURCE_COUNTS: raise ValueError(f"Unexpected source counts; expected {EXPECTED_SOURCE_COUNTS}, got {dict(counts)}") if {row["id"] for row in normalized if row["source"] == "OWASP WebGoat"} != set(WEBGOAT_EXPECTED): raise ValueError("Unexpected WebGoat record set") expected_benchmarkjava_ids = { f"owasp-benchmarkjava-{test_name.lower()}" for test_name in BENCHMARKJAVA_CASES } if { row["id"] for row in normalized if row["source"] == "OWASP BenchmarkJava v1.2" } != expected_benchmarkjava_ids: raise ValueError("Unexpected BenchmarkJava record set") for row in normalized: if set(row) != set(FIELDS): raise ValueError(f"Schema mismatch in {row['id']}") by_split: dict[str, list[dict]] = defaultdict(list) for row in normalized: by_split[row["split"]].append(row) actual_splits = {name: len(rows) for name, rows in by_split.items()} if actual_splits != EXPECTED_SPLIT_COUNTS: raise ValueError(f"Unexpected split counts; expected {EXPECTED_SPLIT_COUNTS}, got {actual_splits}") args.out.mkdir(parents=True, exist_ok=True) for obsolete in ("train.jsonl", "validation.jsonl", "test.jsonl"): (args.out / obsolete).unlink(missing_ok=True) file_manifest = {} for split, rows in sorted(by_split.items()): rows.sort(key=lambda item: item["id"]) path = args.out / f"{split}.jsonl" with path.open("w", encoding="utf-8", newline="\n") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n") file_manifest[str(path)] = { "records": len(rows), "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), } languages = Counter(row["language"] for row in normalized) manifest = { "dataset": "security-code-curated-v1", "record_count": len(normalized), "sources": { "OWASP Juice Shop": { "records": 83, "commit": "c9f99228d9d56afb5f5ca7925376292f7fa44b13", "languages": {"TypeScript": 71, "YAML": 12}, "split": "challenge_fix", "license": "MIT", "license_file": "LICENSES/OWASP-JUICE-SHOP-MIT.txt", }, "OpenZeppelin Contracts v5.7.0": { "records": 5, "version": "v5.7.0", "language": "Solidity", "split": "reference", "license": "MIT", "license_file": "OPENZEPPELIN-MIT.txt", }, "OWASP WebGoat": { "records": 3, "commit": WEBGOAT_COMMIT, "languages": {"Java": 3}, "split": "webgoat_review", "license": "GPL-2.0-or-later", "license_files": [ "LICENSES/WEBGOAT-UPSTREAM-LICENSE.txt", "LICENSES/GPL-2.0-or-later.txt", ], "ai_ml_terms_review": "No AI/ML-specific grant or restriction was located in the inspected upstream license and selected file headers; applicable GPL conditions remain in force.", }, "OWASP BenchmarkJava v1.2": { "records": 22, "commit": BENCHMARKJAVA_COMMIT, "language": "Java", "split": "benchmarkjava_review", "license": "GPL-2.0-only", "license_file": "LICENSES/OWASP-BENCHMARK-GPL-2.0.txt", "license_file_sha256": BENCHMARKJAVA_LICENSE_SHA256, "expected_results_file": "expectedresults-1.2.csv", "expected_results_sha256": BENCHMARKJAVA_RESULTS_SHA256, "labels": {"expected_vulnerable": 11, "expected_not_vulnerable": 11}, "categories": sorted({spec[0] for spec in BENCHMARKJAVA_CASES.values()}), "ai_ml_terms_review": "No AI/ML-specific grant or restriction was located in the selected sample headers or GPL-2.0 text; applicable GPL conditions remain in force, and this is not a separate legal determination about training.", }, }, "by_language": dict(sorted(languages.items())), "by_split": {split: len(rows) for split, rows in sorted(by_split.items())}, "files": file_manifest, "schema_fields": list(FIELDS), "license_scope": "Each source subset retains its own license and provenance; no single license is asserted for the complete dataset.", } manifest_path = args.out.parent / "MANIFEST.json" manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8") print(json.dumps(manifest, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()