File size: 5,809 Bytes
2ef05ec | 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 | #!/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())
|