SecureCodePairs / scripts /validate.py
ismailtasdelen's picture
Release v1.2.0: SecureCodePairs (470 code pairs + 30 LLM security trajectories)
2ef05ec verified
Raw
History Blame Contribute Delete
5.81 kB
#!/usr/bin/env python3
"""Validate SecureCodePairs v1.1.0 JSONL splits.
Checks:
- JSON validity & duplicates
- required fields, types
- OWASP / CWE / CVSS vector format
- severity / difficulty enums
- best-effort compile/syntax checks per language (via compile_check)
Emits a Markdown report + JSON summary.
"""
import json
import os
import re
from collections import Counter
import compile_check
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATASET_DIR = os.path.join(ROOT, "dataset")
VALID_DIR = os.path.join(ROOT, "validation")
REQUIRED = [
"id", "language", "framework", "title", "description",
"owasp", "owasp_api", "owasp_llm", "cwe", "mitre_attack",
"severity", "difficulty", "vulnerable_code", "secure_code", "patch",
"root_cause", "attack", "impact", "fix", "guideline", "tags", "metadata",
"cvss_vector",
]
VALID_LANGS = {
"Python", "Java", "JavaScript", "TypeScript", "Go", "PHP", "C#",
"Kotlin", "Swift", "Rust", "Ruby", "C", "C++", "Scala", "YAML",
}
SEVERITIES = {"Low", "Medium", "High", "Critical"}
DIFFICULTIES = {"Beginner", "Intermediate", "Advanced"}
CVSS_RE = re.compile(r"^CVSS:3\.1/AV:[NALP]/AC:[LH]/PR:[NLH]/UI:[NR]/S:[CU]/C:[NLH]/I:[NLH]/A:[NLH]$")
CWE_RE = re.compile(r"^CWE-\d+$")
OWASP_RE = re.compile(r"^A\d{2}:2021")
OWASP_API_RE = re.compile(r"^API\d{1,2}:2023")
OWASP_LLM_RE = re.compile(r"^LLM\d{2}:2025")
SPLITS = ("train", "validation", "test", "benchmark")
def load_split(name):
path = os.path.join(DATASET_DIR, f"{name}.jsonl")
out = []
with open(path, encoding="utf-8") as f:
for i, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except json.JSONDecodeError as e:
out.append(("__err__", f"{name}:{i}: {e}"))
continue
out.append((obj, None))
return out
def main():
errors, warnings = [], []
all_ids, all_recs = Counter(), []
for name in SPLITS:
recs = load_split(name)
for obj, msg in recs:
if obj == "__err__":
errors.append(msg)
continue
all_recs.append(obj)
rid = obj.get("id", "<no-id>")
all_ids[rid] += 1
if not isinstance(obj.get("tags"), list) or not obj["tags"]:
errors.append(f"{rid}: tags must be non-empty list")
if not isinstance(obj.get("metadata"), dict):
errors.append(f"{rid}: metadata must be dict")
for f in REQUIRED:
if f in ("tags", "metadata"):
continue
v = obj.get(f)
if f in ("owasp_api", "owasp_llm"):
if v and not (OWASP_API_RE.match(v) or OWASP_LLM_RE.match(v)):
warnings.append(f"{rid}: odd {f}: {v}")
continue
if not isinstance(v, str) or not v.strip():
errors.append(f"{rid}: missing/empty {f}")
if obj.get("language") not in VALID_LANGS:
errors.append(f"{rid}: invalid language {obj.get('language')}")
if obj.get("severity") not in SEVERITIES:
errors.append(f"{rid}: bad severity {obj.get('severity')}")
if obj.get("difficulty") not in DIFFICULTIES:
errors.append(f"{rid}: bad difficulty {obj.get('difficulty')}")
if not CWE_RE.match(obj.get("cwe", "")):
errors.append(f"{rid}: bad cwe {obj.get('cwe')}")
if not OWASP_RE.match(obj.get("owasp", "")):
errors.append(f"{rid}: bad owasp {obj.get('owasp')}")
if not CVSS_RE.match(obj.get("cvss_vector", "")):
errors.append(f"{rid}: bad cvss_vector {obj.get('cvss_vector')}")
# compile / syntax check (best-effort, heuristics for missing toolchains)
for field in ("vulnerable_code", "secure_code"):
code = obj.get(field, "")
lang = obj.get("language")
ok, detail = compile_check.check(lang, code)
if ok is False:
warnings.append(f"{rid}: {field} [{lang}] {detail}")
for rid, c in all_ids.items():
if c > 1:
errors.append(f"duplicate id {rid} x{c}")
stats = {
"total_records": len(all_recs),
"by_language": dict(Counter(r["language"] for r in all_recs)),
"by_severity": dict(Counter(r["severity"] for r in all_recs)),
"by_framework": dict(Counter(r["framework"] for r in all_recs)),
"unique_cwe": sorted({r["cwe"] for r in all_recs}),
"unique_owasp": sorted({r["owasp"] for r in all_recs}),
}
os.makedirs(VALID_DIR, exist_ok=True)
with open(os.path.join(VALID_DIR, "validation_summary.json"), "w", encoding="utf-8") as f:
json.dump({"errors": errors, "warnings": warnings, "stats": stats}, f, indent=2, ensure_ascii=False)
status = "PASS" if not errors else "FAIL"
md = ["# SecureCodePairs Validation Report", "", f"**Status:** {status}", "",
f"- Total records: {stats['total_records']}",
f"- Errors: {len(errors)} | Warnings: {len(warnings)}", ""]
md += ["## Errors"] + ([f"- {e}" for e in errors] or ["(none)"]) + [""]
md += ["## Warnings"] + ([f"- {w}" for w in warnings] or ["(none)"])
with open(os.path.join(VALID_DIR, "validation_report.md"), "w", encoding="utf-8") as f:
f.write("\n".join(md))
print(status)
print(f"records={stats['total_records']} errors={len(errors)} warnings={len(warnings)}")
for e in errors[:20]:
print(" ERR", e)
return 0 if status == "PASS" else 1
if __name__ == "__main__":
raise SystemExit(main())