#!/usr/bin/env python3 """AppSecBench v1.1.0 validation + QA report. Checks (full list documented in the dataset card / docs/methodology.md): - JSON validity & duplicate ids - All required fields present & non-empty - Enums: language, framework, severity, difficulty, confidence, source_type - CWE / OWASP / OWASP-API / OWASP-LLM format - CVSS 3.1 vector format + recomputed score consistency vs expected_cvss_score - Reference URLs well-formed - Tag list non-empty; vulnerable != secure; label consistency vs catalog - Metadata completeness & internal consistency - Syntax checks per language via compile_check Emits validation_report.md + validation_summary.json under validation/. """ from __future__ import annotations import json import os import re from collections import Counter import compile_check from vuln_catalog import CATALOG_BY_NAME 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 = [ "benchmark_id", "title", "category", "language", "framework", "application_type", "source_type", "vulnerability_name", "vulnerability_description", "vulnerable_code", "secure_code", "exploit_example", "exploitability_explanation", "attack_prerequisites", "expected_llm_analysis", "expected_detection", "expected_fix", "expected_secure_code", "expected_severity", "expected_confidence", "expected_cwe", "expected_owasp", "expected_cvss", "expected_cvss_score", "expected_false_positive_probability", "expected_false_negative_probability", "evaluation_rubric", "scoring_criteria", "tags", "references", "metadata", ] LANGUAGES = {"Python", "Java", "JavaScript", "TypeScript", "Go", "Rust", "PHP", "C#", "Kotlin", "Swift", "C", "C++", "Ruby", "Scala", "YAML", "Dockerfile", "Bash"} FRAMEWORKS = {"Flask", "FastAPI", "Django", "Spring Boot", "Express", "NestJS", "Next.js", "Laravel", "ASP.NET Core", "Gin", "Echo", "Fiber", "Android", "iOS", "Rails", "Angular", "Vue", "None", ""} SEVERITIES = {"Low", "Medium", "High", "Critical"} DIFFICULTIES = {"Beginner", "Intermediate", "Advanced", "Expert", "Real-world enterprise"} CONFIDENCES = {"Low", "Medium", "High"} SOURCE_TYPES = {"synthetic", "recreated", "educational"} 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$") URL_RE = re.compile(r"^https?://[^\s]+$") SPLITS = ("train", "validation", "test") def recompute_cvss_score(vector: str) -> float: from cvss import compute_base_vector parts = dict(p.split(":") for p in vector.split("/")[1:]) _, score = compute_base_vector(av=parts["AV"], ac=parts["AC"], pr=parts["PR"], ui=parts["UI"], s=parts["S"], c=parts["C"], i=parts["I"], a=parts["A"]) return score def main(): errors, warnings = [], [] all_ids, all_recs = Counter(), [] for name in SPLITS: path = os.path.join(DATASET_DIR, f"{name}.jsonl") 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: errors.append(f"{name}:{i}: bad JSON {e}") continue all_recs.append(obj) rid = obj.get("benchmark_id", f"") all_ids[rid] += 1 for fld in REQUIRED: v = obj.get(fld) if isinstance(v, str) and not v.strip(): errors.append(f"{rid}: empty {fld}") elif v is None: errors.append(f"{rid}: missing {fld}") if obj.get("language") not in LANGUAGES: errors.append(f"{rid}: bad language {obj.get('language')}") if obj.get("framework") not in FRAMEWORKS: errors.append(f"{rid}: bad framework {obj.get('framework')}") if obj.get("expected_severity") not in SEVERITIES: errors.append(f"{rid}: bad severity {obj.get('expected_severity')}") diff = obj.get("metadata", {}).get("difficulty") if diff not in DIFFICULTIES: errors.append(f"{rid}: bad difficulty {diff}") if obj.get("expected_confidence") not in CONFIDENCES: errors.append(f"{rid}: bad confidence {obj.get('expected_confidence')}") if obj.get("source_type") not in SOURCE_TYPES: errors.append(f"{rid}: bad source_type {obj.get('source_type')}") if not CWE_RE.match(obj.get("expected_cwe", "")): errors.append(f"{rid}: bad cwe {obj.get('expected_cwe')}") if not OWASP_RE.match(obj.get("expected_owasp", "")): errors.append(f"{rid}: bad owasp {obj.get('expected_owasp')}") owl = obj.get("expected_owasp_llm", "") if owl and not OWASP_LLM_RE.match(owl): warnings.append(f"{rid}: odd owasp_llm {owl}") oapi = obj.get("expected_owasp_api", "") if oapi and not OWASP_API_RE.match(oapi): warnings.append(f"{rid}: odd owasp_api {oapi}") cvss = obj.get("expected_cvss", "") if not CVSS_RE.match(cvss): errors.append(f"{rid}: bad cvss vector {cvss}") else: try: recomputed = recompute_cvss_score(cvss) stated = float(obj.get("expected_cvss_score", -1)) if abs(recomputed - stated) > 0.05: errors.append(f"{rid}: cvss score mismatch recomputed={recomputed} stated={stated}") except Exception as e: errors.append(f"{rid}: cvss recompute failed {e}") refs = obj.get("references", []) if not isinstance(refs, list) or not refs: errors.append(f"{rid}: references must be non-empty list") else: for u in refs: if not URL_RE.match(str(u)): warnings.append(f"{rid}: odd reference {u}") if not isinstance(obj.get("tags"), list) or not obj["tags"]: errors.append(f"{rid}: tags must be non-empty list") if obj.get("vulnerable_code") == obj.get("secure_code"): errors.append(f"{rid}: vulnerable_code equals secure_code") cat = CATALOG_BY_NAME.get(obj.get("vulnerability_name", "")) if cat: if obj.get("expected_cwe") != cat["cwe"]: errors.append(f"{rid}: cwe mismatch catalog") if obj.get("expected_owasp") != cat["owasp"]: errors.append(f"{rid}: owasp mismatch catalog") else: errors.append(f"{rid}: unknown vulnerability_name {obj.get('vulnerability_name')}") md = obj.get("metadata", {}) if md.get("cwe") != obj.get("expected_cwe"): errors.append(f"{rid}: metadata.cwe mismatch") if md.get("cvss_vector") != cvss: errors.append(f"{rid}: metadata.cvss_vector mismatch") if not isinstance(md.get("cvss_score"), (int, float)): errors.append(f"{rid}: metadata.cvss_score missing") for fld in ("vulnerable_code", "secure_code"): code = obj.get(fld, "") ok, detail = compile_check.check(obj.get("language"), code) if ok is False: errors.append(f"{rid}: {fld} [{obj.get('language')}] {detail}") elif ok is None: warnings.append(f"{rid}: {fld} [{obj.get('language')}] unchecked ({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_framework": dict(Counter(r["framework"] for r in all_recs if r["framework"] != "None")), "by_severity": dict(Counter(r["expected_severity"] for r in all_recs)), "by_cwe": dict(Counter(r["expected_cwe"] for r in all_recs)), "by_owasp": dict(Counter(r["expected_owasp"] for r in all_recs)), "by_category": dict(Counter(r["category"] for r in all_recs)), "by_difficulty": dict(Counter(r["metadata"]["difficulty"] for r in all_recs)), "by_vulnerability": dict(Counter(r["vulnerability_name"] for r in all_recs)), "unique_cwe": sorted({r["expected_cwe"] for r in all_recs}), "unique_owasp": sorted({r["expected_owasp"] for r in all_recs}), "unique_vulnerabilities": sorted({r["vulnerability_name"] 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" report_lines = ( ["# AppSecBench Validation Report", "", f"**Status:** {status}", f"**Records:** {stats['total_records']}", f"**Errors:** {len(errors)} | **Warnings:** {len(warnings)}", "", "## Distributions", "", f"- Languages: {len(stats['by_language'])}", f"- Frameworks: {len(stats['by_framework'])}", f"- CWEs: {len(stats['unique_cwe'])}", f"- OWASP: {len(stats['unique_owasp'])}", f"- Vulnerabilities: {len(stats['unique_vulnerabilities'])}", "", "## Errors"] + ([f"- {e}" for e in errors] or ["(none)"]) + [""] + ["## Warnings (sample)"] + ([f"- {w}" for w in warnings[:50]] or ["(none)"]) ) with open(os.path.join(VALID_DIR, "validation_report.md"), "w", encoding="utf-8") as f: f.write("\n".join(report_lines)) print(status) print(f"records={stats['total_records']} errors={len(errors)} warnings={len(warnings)}") for e in errors[:30]: print(" ERR", e) return 0 if status == "PASS" else 1 if __name__ == "__main__": raise SystemExit(main())