"""Download raw upstream cybersecurity feeds and record SHA-256 provenance.""" from __future__ import annotations import argparse import hashlib import json import os import sys import time import urllib.error import urllib.parse import urllib.request from datetime import datetime, timezone from pathlib import Path from typing import Any _REPO_ROOT = Path(__file__).resolve().parent.parent.parent if str(_REPO_ROOT) not in sys.path: sys.path.insert(0, str(_REPO_ROOT)) from scripts.ingest.sources import SOURCES, SourceSpec USER_AGENT = "CCRB-DatasetBuilder/0.1 (+https://huggingface.co/datasets/continuum-oss/ccrb)" def sha256_file(path: Path) -> str: """Compute SHA-256 hex digest of a file.""" digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(65536), b""): digest.update(chunk) return digest.hexdigest() def download_file(url: str, dest: Path, *, timeout: int = 60) -> int: """Stream-download a URL to `dest`, returning byte count.""" dest.parent.mkdir(parents=True, exist_ok=True) tmp_path = dest.with_suffix(dest.suffix + ".part") req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) total_bytes = 0 with urllib.request.urlopen(req, timeout=timeout) as resp, tmp_path.open("wb") as out: while True: chunk = resp.read(65536) if not chunk: break out.write(chunk) total_bytes += len(chunk) tmp_path.replace(dest) return total_bytes def fetch_nvd_pages( raw_dir: Path, *, max_pages: int = 5, results_per_page: int = 2000, pub_start_date: str | None = None, pub_end_date: str | None = None, ) -> list[dict[str, Any]]: """Fetch paginated CVE JSON 2.0 pages from the NVD API.""" nvd_dir = raw_dir / "nvd" nvd_dir.mkdir(parents=True, exist_ok=True) api_key = os.environ.get("NVD_API_KEY", "").strip() sleep_seconds = 0.8 if api_key else 6.2 records: list[dict[str, Any]] = [] start_index = 0 for page in range(max_pages): params: dict[str, str] = { "startIndex": str(start_index), "resultsPerPage": str(results_per_page), } if pub_start_date and pub_end_date: params["pubStartDate"] = pub_start_date params["pubEndDate"] = pub_end_date url = "https://services.nvd.nist.gov/rest/json/cves/2.0?" + urllib.parse.urlencode(params) headers = {"User-Agent": USER_AGENT} if api_key: headers["apiKey"] = api_key req = urllib.request.Request(url, headers=headers) with urllib.request.urlopen(req, timeout=60) as resp: payload = json.loads(resp.read().decode("utf-8")) out_path = nvd_dir / f"nvd_page_{page:04d}.json" out_path.write_text(json.dumps(payload), encoding="utf-8") total_results = int(payload.get("totalResults", 0)) vulns = payload.get("vulnerabilities", []) records.append( { "key": f"nvd_page_{page:04d}", "file": str(out_path.relative_to(raw_dir)), "count": len(vulns), "total_results": total_results, "sha256": sha256_file(out_path), } ) start_index += len(vulns) if not vulns or start_index >= total_results: break if page + 1 < max_pages: time.sleep(sleep_seconds) return records def fetch_sources( raw_dir: Path, *, tier: str = "core", keys: list[str] | None = None, force: bool = False, nvd_pages: int = 0, ) -> dict[str, Any]: """Download selected feeds into `raw_dir` and update `SOURCE_MANIFEST.json`.""" raw_dir.mkdir(parents=True, exist_ok=True) manifest_path = raw_dir / "SOURCE_MANIFEST.json" manifest: dict[str, Any] = ( json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else {"sources": {}, "nvd_pages": []} ) selected: list[SourceSpec] = [] if keys: for key in keys: if key not in SOURCES: raise KeyError(f"Unknown source key {key!r}. Available: {sorted(SOURCES)}") selected.append(SOURCES[key]) else: for spec in SOURCES.values(): if tier == "all" or spec.tier == tier: selected.append(spec) for spec in selected: dest = raw_dir / spec.filename if dest.exists() and not force: size_bytes = dest.stat().st_size print(f"[skip] {spec.key} already exists ({size_bytes:,} bytes)") else: print(f"[fetch] {spec.key} <- {spec.url}") size_bytes = download_file(spec.url, dest) print(f"[done] {spec.key} ({size_bytes:,} bytes)") manifest["sources"][spec.key] = { "url": spec.url, "file": spec.filename, "license": spec.license, "tracks": list(spec.tracks), "bytes": size_bytes, "sha256": sha256_file(dest), "fetched_at": datetime.now(timezone.utc).isoformat(), } if nvd_pages > 0: print(f"[fetch] NVD API 2.0 ({nvd_pages} page(s))") manifest["nvd_pages"] = fetch_nvd_pages(raw_dir, max_pages=nvd_pages) manifest["updated_at"] = datetime.now(timezone.utc).isoformat() manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") return manifest def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Fetch raw upstream cybersecurity feeds for CCRB.") parser.add_argument("--raw-dir", type=Path, default=Path("data/raw")) parser.add_argument( "--tier", choices=("core", "bulk", "code_rem", "all"), default="core", help="Source tier to download when --sources is omitted (default: core).", ) parser.add_argument( "--sources", nargs="+", default=None, help="Specific source keys to fetch (overrides --tier).", ) parser.add_argument("--nvd-pages", type=int, default=0, help="Number of NVD API 2.0 pages to fetch.") parser.add_argument("--force", action="store_true", help="Re-download existing files.") args = parser.parse_args(argv) try: fetch_sources( args.raw_dir, tier=args.tier, keys=args.sources, force=args.force, nvd_pages=args.nvd_pages, ) except urllib.error.URLError as exc: print(f"Network error while fetching sources: {exc}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main())