"""Check DVSentry's public scanner benchmark yourself (https://dvsentry.com/benchmarks).

One standard-library file. It needs Python 3.10+, git and, for the stock-tool rows, Semgrep 1.186.0
(and Bandit 1.9.4 for the Bandit row of the Python set).

Test sets (--suite): owasp-java (OWASP Benchmark for Java 1.2, the default), owasp-python (OWASP
Benchmark for Python 0.1), ossf-cve (OpenSSF CVE Benchmark: 223 real JavaScript/TypeScript CVEs, each
project checked out at the commit before and after its fix).

    python dvsentry_benchmark.py fetch --work ./bench [--with-cves]
        Clone the public test sets at the exact commits the page names (--with-cves also checks out
        every CVE's project before and after its fix: about 440 shallow clones).

    python dvsentry_benchmark.py stock --work ./bench --suite owasp-java --out stock.json [--engine bandit]
        Run Semgrep 1.186.0 with the open-source semgrep-rules folder for that language (java/,
        python/, javascript/ + typescript/) over the test set and score it; --engine bandit runs
        Bandit with its default rules instead (Python set). This reproduces the stock rows.

    python dvsentry_benchmark.py score --work ./bench --suite owasp-java --dvsentry-export report.json --out dvsentry.json
        Score a DVSentry scan of the same test set. Scan the test set's repository at the pinned commit
        with any DVSentry account, open the finished report and download Export > JSON. Only findings
        of DVSentry's code scanners are counted, as on the page (DVSENTRY_SCANNERS). For ossf-cve,
        --dvsentry-export is a folder of exports named <CVE>-pre.json and <CVE>-post.json.

    python dvsentry_benchmark.py compare --published results.json --mine stock.json [--suite S] [--tool NAME]
        Print the published numbers beside yours (results.json: https://dvsentry.com/benchmarks/results.json).

Scoring, the same code DVSentry's own harness uses (scripts/public_benchmark/run.py imports it):
  strict   a case counts only when a finding in the case's file names the case's CWE
           (the way OWASP Benchmark's own scorecard matches categories)
  lenient  any finding in the case's file
  score    true-positive rate minus false-positive rate (Youden's index, the Benchmark's headline)

Nothing here sends anything anywhere: the only network use is `git fetch` of the public test sets.
Code Owner: Aslam Jabri.
"""

from __future__ import annotations

import argparse
import csv
import json
import os
import re
import subprocess  # nosec B404 -- runs git and semgrep, named in full, never a shell
import sys
import time
from pathlib import Path

FORMAT = "dvsentry-public-benchmark/v1"
TARGETS = {
    "owasp-java": {"name": "OWASP Benchmark for Java 1.2", "url": "https://github.com/OWASP-Benchmark/BenchmarkJava",
                   "commit": "10dfcc54ad02dcfcb358b0ba4a0fef8c919a6d17", "licence": "GPL-2.0", "dir": "BenchmarkJava"},
    "owasp-python": {"name": "OWASP Benchmark for Python 0.1", "url": "https://github.com/OWASP-Benchmark/BenchmarkPython",
                     "commit": "f1291485808b66e20ddb6b01b10dc71b3df8c8ba", "licence": "GPL-3.0", "dir": "BenchmarkPython"},
    "ossf-cve": {"name": "OpenSSF CVE Benchmark (JavaScript and TypeScript)",
                 "url": "https://github.com/ossf-cve-benchmark/ossf-cve-benchmark",
                 "commit": "91c59fd54b2b768c0f310bb0027d2ac59cdf74d4", "licence": "MIT (metadata); each CVE's project keeps its own licence",
                 "dir": "ossf-cve-benchmark"},
    "semgrep-rules": {"name": "semgrep-rules (stock Semgrep rules)", "url": "https://github.com/semgrep/semgrep-rules",
                      "commit": "a5ad1714f00c9f7fde980cab0ea1d6dc6d414fd2", "licence": "Semgrep Rules License v1.0 (run, not redistributed)",
                      "dir": "semgrep-rules"},
}
SEMGREP_VERSION = "1.186.0"
BANDIT_VERSION = "1.9.4"
STOCK_TOOL = "Semgrep + semgrep-rules java/"
DVSENTRY_TOOL = "DVSentry (semgrep-local)"
DVSENTRY_SCANNER = "semgrep-local"
# Per test set: the row names and the folders of semgrep-rules the stock row runs, and which DVSentry
# scanners count (the code scanners DVSentry plans for a repository in that language).
STOCK_RULES = {"owasp-java": ("java",), "owasp-python": ("python",), "ossf-cve": ("javascript", "typescript")}
STOCK_TOOLS = {"owasp-java": STOCK_TOOL, "owasp-python": "Semgrep + semgrep-rules python/",
               "ossf-cve": "Semgrep + semgrep-rules javascript/ + typescript/"}
BANDIT_TOOL = "Bandit 1.9.4 (default rules)"
DVSENTRY_SCANNERS = {"owasp-java": ("semgrep-local",), "owasp-python": ("semgrep-local", "bandit-python", "dvsentry-review"),
                     "ossf-cve": ("semgrep-local",)}
DVSENTRY_TOOLS = {"owasp-java": DVSENTRY_TOOL, "owasp-python": "DVSentry (semgrep-local + bandit-python + dvsentry-review)",
                  "ossf-cve": DVSENTRY_TOOL}
SOURCES = {"owasp-java": ("src", "main", "java"), "owasp-python": ("testcode",)}
_CWE = re.compile(r"CWE-(\d+)", re.IGNORECASE)


def cwe_numbers(value) -> set[str]:
    """CWE numbers in a rule's `cwe` value ("CWE-89: SQL Injection", a list of those, or "CWE-89")."""
    values = value if isinstance(value, list) else [value]
    return {match for item in values if isinstance(item, str) for match in _CWE.findall(item)}


def fetch(work: Path) -> None:
    """Clone every pinned target at its exact commit (idempotent); refuse a checkout at another commit."""
    work.mkdir(parents=True, exist_ok=True)
    for target in TARGETS.values():
        folder = work / target["dir"]
        if not folder.is_dir():
            subprocess.run(["git", "init", "-q", str(folder)], check=True)  # nosec B603 B607 -- fixed git command
            subprocess.run(["git", "-C", str(folder), "fetch", "-q", "--depth", "1", target["url"], target["commit"]],  # nosec B603 B607
                           check=True)
            subprocess.run(["git", "-C", str(folder), "checkout", "-q", "FETCH_HEAD"], check=True)  # nosec B603 B607
        head = subprocess.run(["git", "-C", str(folder), "rev-parse", "HEAD"], capture_output=True, text=True,  # nosec B603 B607
                              check=True).stdout.strip()
        if head != target["commit"]:
            raise SystemExit(f"{folder} is at {head}, expected the pinned {target['commit']}")


ANSWER_KEYS = {"owasp-java": "expectedresults-1.2.csv", "owasp-python": "expectedresults-0.1.csv"}
CVE_FOLDER = "ossf-cves"


def load_truth(bench: Path, suite: str = "owasp-java") -> dict[str, tuple[bool, str, str]]:
    """OWASP Benchmark's own answer key: case -> (vulnerable, category, CWE number)."""
    truth: dict[str, tuple[bool, str, str]] = {}
    with (bench / ANSWER_KEYS[suite]).open() as stream:
        for row in csv.reader(stream):
            if row and row[0].startswith("BenchmarkTest"):
                truth[row[0]] = (row[2].strip() == "true", row[1].strip(), row[3].strip())
    return truth


def cve_cases(work: Path) -> list[dict]:
    """The OpenSSF CVE Benchmark's cases, from its pinned metadata: CVE, repository, the commit before
    and after the fix, and the lines the benchmark names as the weakness (on the commit before)."""
    cases = []
    for path in sorted((work / TARGETS["ossf-cve"]["dir"] / "CVEs").glob("*.json")):
        data = json.loads(path.read_text())
        weaknesses = [(item["location"]["file"], int(item["location"]["line"]))
                      for item in (data.get("prePatch") or {}).get("weaknesses") or [] if item.get("location")]
        if not weaknesses:
            continue
        cases.append({"cve": data["CVE"], "repository": data["repository"], "pre": data["prePatch"]["commit"],
                      "post": data["postPatch"]["commit"], "weaknesses": weaknesses, "cwes": data.get("CWEs") or []})
    return cases


def fetch_cves(work: Path, jobs: int = 6) -> dict[str, str]:
    """Check out every CVE's project at the commit before and after its fix (work/ossf-cves/<CVE>/pre|post).
    A project that can no longer be fetched is left out and named; returns {CVE: reason}."""
    from concurrent.futures import ThreadPoolExecutor

    def one(case: dict) -> tuple[str, str | None]:
        for side in ("pre", "post"):
            folder = work / CVE_FOLDER / case["cve"] / side
            marker = folder / ".dvsentry-commit"
            if marker.is_file() and marker.read_text().strip() == case[side]:
                continue
            if folder.exists():
                subprocess.run(["rm", "-rf", str(folder)], check=True)  # nosec B603 B607 -- fixed command, own folder
            folder.mkdir(parents=True)
            environment = {**os.environ, "GIT_TERMINAL_PROMPT": "0"}
            steps = (["git", "init", "-q", str(folder)],
                     ["git", "-C", str(folder), "fetch", "-q", "--depth", "1", case["repository"], case[side]],
                     ["git", "-C", str(folder), "checkout", "-q", "FETCH_HEAD"])
            for step in steps:
                done = subprocess.run(step, capture_output=True, text=True, timeout=1800, env=environment, check=False)  # nosec B603
                if done.returncode != 0:
                    subprocess.run(["rm", "-rf", str(folder)], check=False)  # nosec B603 B607
                    return case["cve"], f"{side} commit could not be fetched"
            head = subprocess.run(["git", "-C", str(folder), "rev-parse", "HEAD"], capture_output=True, text=True,  # nosec B603 B607
                                  check=True).stdout.strip()
            if head != case[side]:
                return case["cve"], f"{side} checkout is at {head}"
            subprocess.run(["rm", "-rf", str(folder / ".git")], check=True)  # nosec B603 B607
            marker.write_text(case[side] + "\n")
        return case["cve"], None

    with ThreadPoolExecutor(max_workers=jobs) as pool:
        results = list(pool.map(one, cve_cases(work)))
    return {cve: reason for cve, reason in results if reason}


def score_cves(cases: list[dict], findings: dict[str, dict[str, list[tuple[str, int, str]]]]) -> dict:
    """Score (file, line, rule) findings per CVE and side ("pre"/"post") the way the OpenSSF CVE Benchmark
    reports a tool: *detected* = a finding on the exact file and line it names as the weakness, on the
    commit before the fix; *fix recognised* = for a detected CVE, the rules that hit the weakness report
    fewer findings in those files on the commit after the fix. Also *lenient*: any finding in a weakness
    file before the fix."""
    detected, lenient, recognised, scored = [], [], [], 0
    for case in cases:
        if case["cve"] not in findings:
            continue
        scored += 1
        pre, post = findings[case["cve"]].get("pre", []), findings[case["cve"]].get("post", [])
        spots = set(case["weaknesses"])
        files = {path for path, _line in spots}
        rules = {rule for path, line, rule in pre if (path, line) in spots}
        if any(path in files for path, _line, _rule in pre):
            lenient.append(case["cve"])
        if not rules:
            continue
        detected.append(case["cve"])
        before = sum(1 for path, _line, rule in pre if path in files and rule in rules)
        after = sum(1 for path, _line, rule in post if path in files and rule in rules)
        if after < before:
            recognised.append(case["cve"])

    def pct(part, whole):
        return round(100.0 * len(part) / max(whole, 1), 1)

    return {"cves": scored, "detected": len(detected), "detected_percent": pct(detected, scored),
            "fix_recognised": len(recognised), "fix_recognised_percent_of_detected": pct(recognised, len(detected)),
            "still_flagged_after_fix": len(detected) - len(recognised),
            "lenient_file_hit": len(lenient), "lenient_file_hit_percent": pct(lenient, scored),
            "detected_cves": sorted(detected)}


def rates(flagged: set[str], real: set[str], safe: set[str]) -> dict:
    tpr = 100.0 * len(flagged & real) / max(len(real), 1)
    fpr = 100.0 * len(flagged & safe) / max(len(safe), 1)
    return {"true_positive_percent": round(tpr, 1), "false_positive_percent": round(fpr, 1),
            "score": round(tpr - fpr, 1), "true_positives": len(flagged & real), "false_positives": len(flagged & safe)}


def score(findings: list[tuple[str, set[str]]], truth: dict[str, tuple[bool, str, str]]) -> dict:
    """Score (file path, CWE numbers) pairs against the answer key, strict, lenient and per category."""
    real = {case for case, (vulnerable, _c, _w) in truth.items() if vulnerable}
    safe = set(truth) - real
    lenient = {Path(path).stem for path, _cwes in findings if Path(path).stem in truth}
    strict = {Path(path).stem for path, cwes in findings if Path(path).stem in truth and truth[Path(path).stem][2] in cwes}
    per_category = {}
    for category in sorted({c for _v, c, _w in truth.values()}):
        members = {case for case, (_v, c, _w) in truth.items() if c == category}
        per_category[category] = rates(strict & members, real & members, safe & members)
    return {"strict": rates(strict, real, safe), "lenient": rates(lenient, real, safe), "by_category_strict": per_category}


def semgrep_json_findings(report: dict) -> list[tuple[str, set[str]]]:
    """(file name, CWE numbers) from `semgrep scan --json` output."""
    return [(Path(result.get("path", "")).name, cwe_numbers(((result.get("extra") or {}).get("metadata") or {}).get("cwe")))
            for result in report.get("results", [])]


def dvsentry_export_findings(export: dict, scanners: tuple[str, ...] = (DVSENTRY_SCANNER,)) -> list[tuple[str, set[str]]]:
    """(file name, CWE numbers) of the code scanners' findings in a DVSentry report JSON export."""
    rows = []
    for item in export.get("findings") or []:
        if not set(scanners) & set(item.get("scanners") or []):
            continue
        metadata = item.get("metadata") or {}
        cwes = cwe_numbers(metadata.get("cwe_ids")) | cwe_numbers((metadata.get("metadata") or {}).get("cwe"))
        rows.append((Path(str(item.get("target") or "")).name, cwes))
    return rows


def dvsentry_export_rows(export: dict, scanners: tuple[str, ...] = (DVSENTRY_SCANNER,)) -> list[tuple[str, int, str]]:
    """(path, line, rule) of the code scanners' findings in a DVSentry report JSON export."""
    rows = []
    for item in export.get("findings") or []:
        if not set(scanners) & set(item.get("scanners") or []):
            continue
        line = re.search(r"(\d+)", str(item.get("location") or ""))
        rows.append((str(item.get("target") or ""), int(line.group(1)) if line else 0, str(item.get("rule_id") or "")))
    return rows


def _semgrep(source: Path, rules: list[Path]) -> dict:
    version = subprocess.run(["semgrep", "--version"], capture_output=True, text=True, timeout=120, check=False).stdout.strip()  # nosec B603 B607
    if version != SEMGREP_VERSION:
        raise SystemExit(f"semgrep {version or 'not installed'} found; this benchmark is pinned to {SEMGREP_VERSION}")
    environment = {**os.environ, "SEMGREP_ENABLE_VERSION_CHECK": "0", "SEMGREP_SEND_METRICS": "off"}
    command = ["semgrep", "scan", "--json", "--quiet", "--metrics=off", "--timeout", "30"]
    for folder in rules:
        command += ["--config", str(folder)]
    answer = subprocess.run(command + ["--", str(source)], capture_output=True, text=True, timeout=7200,  # nosec B603 B607
                            env=environment, check=False)
    return json.loads(answer.stdout or "{}")


def run_stock_semgrep(source: Path, rules: Path | list[Path]) -> list[tuple[str, set[str]]]:
    return semgrep_json_findings(_semgrep(source, rules if isinstance(rules, list) else [rules]))


def stock_semgrep_rows(source: Path, rules: list[Path]) -> list[tuple[str, int, str]]:
    """(path relative to source, line, rule id) of a stock Semgrep run, for the CVE set."""
    rows = []
    for result in _semgrep(source, rules).get("results", []):
        path = Path(result.get("path", ""))
        try:
            path = path.resolve().relative_to(source.resolve())
        except ValueError:
            pass
        rows.append((path.as_posix(), int((result.get("start") or {}).get("line") or 0), str(result.get("check_id") or "")))
    return rows


def run_bandit(source: Path) -> list[tuple[str, set[str]]]:
    """Bandit with its default rules: (file name, CWE numbers)."""
    version = subprocess.run(["bandit", "--version"], capture_output=True, text=True, timeout=120, check=False).stdout  # nosec B603 B607
    if not version.startswith(f"bandit {BANDIT_VERSION}"):
        raise SystemExit(f"bandit {version.split(chr(10))[0] or 'not installed'} found; this benchmark is pinned to {BANDIT_VERSION}")
    answer = subprocess.run(["bandit", "-r", "-q", "-f", "json", str(source)], capture_output=True, text=True,  # nosec B603 B607
                            timeout=7200, check=False)
    report = json.loads(answer.stdout or "{}")
    return [(Path(item.get("filename", "")).name, {str((item.get("issue_cwe") or {}).get("id", ""))} - {""})
            for item in report.get("results", [])]


def stock_cves(work: Path) -> dict:
    """The stock Semgrep row of the CVE set: findings per CVE and side."""
    rules = [work / TARGETS["semgrep-rules"]["dir"] / folder for folder in STOCK_RULES["ossf-cve"]]
    found: dict[str, dict[str, list]] = {}
    for case in cve_cases(work):
        for side in ("pre", "post"):
            folder = work / CVE_FOLDER / case["cve"] / side
            if folder.is_dir():
                found.setdefault(case["cve"], {})[side] = stock_semgrep_rows(folder, rules)
    return found


def suite_result(name: str, findings: list[tuple[str, set[str]]], truth: dict, seconds: int = 0) -> dict:
    real = sum(1 for vulnerable, _c, _w in truth.values() if vulnerable)
    return {"cases": len(truth), "real": real, "safe": len(truth) - real,
            "tools": {name: {**score(findings, truth), "seconds": seconds}}}


def _write(result: dict, out: Path | None) -> None:
    text = json.dumps(result, indent=2, sort_keys=True) + "\n"
    if out:
        out.write_text(text)
    strict, lenient = next(iter(result["tools"].values()))["strict"], next(iter(result["tools"].values()))["lenient"]
    print(f"strict: found {strict['true_positive_percent']} %, false alarms {strict['false_positive_percent']} %, score {strict['score']:+}")
    print(f"lenient: found {lenient['true_positive_percent']} %, false alarms {lenient['false_positive_percent']} %, score {lenient['score']:+}")


def compare(published: dict, mine: dict, tool: str | None, suite_name: str = "owasp-java") -> int:
    suite = published["suites"][suite_name]["tools"]
    name = tool or next(iter(mine["tools"]))
    theirs = suite.get(name)
    if theirs is None:
        print(f"the published result has no row named {name!r}; rows: {', '.join(suite)}")
        return 2
    ours = mine["tools"][next(iter(mine["tools"]))]
    if suite_name == "ossf-cve":
        for key in ("detected", "detected_percent", "fix_recognised", "lenient_file_hit_percent"):
            print(f"{key:36} published {theirs[key]:>7}  yours {ours[key]:>7}")
        return 0
    for mode in ("strict", "lenient"):
        for key in ("true_positive_percent", "false_positive_percent", "score"):
            print(f"{mode:8} {key:24} published {theirs[mode][key]:>7}  yours {ours[mode][key]:>7}")
    return 0


def cve_result(name: str, cases: list[dict], findings: dict, seconds: int = 0) -> dict:
    scored = score_cves(cases, findings)
    return {"cves": len(cases), "tools": {name: {**scored, "seconds": seconds}}}


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    sub = parser.add_subparsers(dest="command", required=True)
    for name in ("fetch", "stock", "score"):
        command = sub.add_parser(name)
        command.add_argument("--work", type=Path, required=True)
        command.add_argument("--out", type=Path)
        command.add_argument("--suite", choices=sorted(STOCK_RULES), default="owasp-java")
        if name == "fetch":
            command.add_argument("--with-cves", action="store_true")
        if name == "stock":
            command.add_argument("--engine", choices=("semgrep", "bandit"), default="semgrep")
        if name == "score":
            command.add_argument("--dvsentry-export", type=Path, required=True)
    command = sub.add_parser("compare")
    command.add_argument("--published", type=Path, required=True)
    command.add_argument("--mine", type=Path, required=True)
    command.add_argument("--suite", choices=sorted(STOCK_RULES), default="owasp-java")
    command.add_argument("--tool")
    options = parser.parse_args(argv)
    if options.command == "compare":
        return compare(json.loads(options.published.read_text()), json.loads(options.mine.read_text()), options.tool, options.suite)
    fetch(options.work)
    if options.command == "fetch":
        if options.with_cves:
            for cve, reason in sorted(fetch_cves(options.work).items()):
                print(f"{cve}: {reason} (left out)")
        return 0
    suite, started = options.suite, time.monotonic()
    scanners = DVSENTRY_SCANNERS[suite]
    if suite == "ossf-cve":
        cases = cve_cases(options.work)
        if options.command == "stock":
            result = cve_result(STOCK_TOOLS[suite], cases, stock_cves(options.work), round(time.monotonic() - started))
        else:
            found = {}
            for case in cases:
                for side in ("pre", "post"):
                    export = options.dvsentry_export / f"{case['cve']}-{side}.json"
                    if export.is_file():
                        found.setdefault(case["cve"], {})[side] = dvsentry_export_rows(json.loads(export.read_text()), scanners)
            result = cve_result(DVSENTRY_TOOLS[suite], cases, found)
        text = json.dumps({"format": FORMAT, **result}, indent=2, sort_keys=True) + "\n"
        if options.out:
            options.out.write_text(text)
        tool = next(iter(result["tools"].values()))
        print(f"detected {tool['detected']} of {tool['cves']} CVEs ({tool['detected_percent']} %), fix recognised for {tool['fix_recognised']}")
        return 0
    bench = options.work / TARGETS[suite]["dir"]
    truth = load_truth(bench, suite)
    if options.command == "stock":
        source = bench.joinpath(*SOURCES[suite])
        if options.engine == "bandit":
            findings, name = run_bandit(source), BANDIT_TOOL
        else:
            folders = [options.work / TARGETS["semgrep-rules"]["dir"] / folder for folder in STOCK_RULES[suite]]
            findings, name = run_stock_semgrep(source, folders), STOCK_TOOLS[suite]
        result = suite_result(name, findings, truth, round(time.monotonic() - started))
    else:
        findings = dvsentry_export_findings(json.loads(options.dvsentry_export.read_text()), scanners)
        if not findings:
            print(f"the export holds no findings from {', '.join(scanners)}; was the report a repository scan of the test set?", file=sys.stderr)
            return 2
        result = suite_result(DVSENTRY_TOOLS[suite], findings, truth)
    _write({"format": FORMAT, **result}, options.out)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
