|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +import os |
| 5 | +from typing import TYPE_CHECKING, Any |
| 6 | + |
| 7 | +import orjson |
| 8 | + |
| 9 | +from vunnel.tool import fixdate |
| 10 | +from vunnel.utils import http_wrapper as http |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from collections.abc import Generator |
| 14 | + from types import TracebackType |
| 15 | + |
| 16 | + from vunnel.workspace import Workspace |
| 17 | + |
| 18 | + |
| 19 | +namespace = "rootio" |
| 20 | + |
| 21 | + |
| 22 | +class Parser: |
| 23 | + _api_base_url_ = "https://api.root.io/external/osv" |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + ws: Workspace, |
| 28 | + api_base_url: str | None = None, |
| 29 | + download_timeout: int = 125, |
| 30 | + fixdater: fixdate.Finder | None = None, |
| 31 | + logger: logging.Logger | None = None, |
| 32 | + ): |
| 33 | + if not fixdater: |
| 34 | + fixdater = fixdate.default_finder(ws) |
| 35 | + self.fixdater = fixdater |
| 36 | + self.workspace = ws |
| 37 | + self.api_base_url = api_base_url or self._api_base_url_ |
| 38 | + self.download_timeout = download_timeout |
| 39 | + self.urls = [self.api_base_url] |
| 40 | + if not logger: |
| 41 | + logger = logging.getLogger(self.__class__.__name__) |
| 42 | + self.logger = logger |
| 43 | + |
| 44 | + def __enter__(self) -> Parser: |
| 45 | + self.fixdater.__enter__() |
| 46 | + return self |
| 47 | + |
| 48 | + def __exit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) -> None: |
| 49 | + self.fixdater.__exit__(exc_type, exc_val, exc_tb) |
| 50 | + |
| 51 | + def _fetch_osv_ids(self) -> list[str]: |
| 52 | + """Fetch the list of OSV record IDs from the Root IO API.""" |
| 53 | + self.logger.info("fetching list of OSV IDs from Root IO") |
| 54 | + url = f"{self.api_base_url}/all.json" |
| 55 | + response = http.get(url, self.logger, timeout=self.download_timeout) |
| 56 | + |
| 57 | + # Parse the response - it's an array of objects with "id" and "modified" fields |
| 58 | + id_objects = response.json() |
| 59 | + |
| 60 | + # Extract just the ID strings from each object |
| 61 | + id_list = [obj["id"] for obj in id_objects] |
| 62 | + |
| 63 | + # Save the full response to workspace for debugging/reproducibility |
| 64 | + os.makedirs(self.workspace.input_path, exist_ok=True) |
| 65 | + ids_file = os.path.join(self.workspace.input_path, "osv_ids.json") |
| 66 | + with open(ids_file, "wb") as f: |
| 67 | + f.write(orjson.dumps(id_objects)) |
| 68 | + |
| 69 | + self.logger.info(f"found {len(id_list)} OSV records") |
| 70 | + return id_list |
| 71 | + |
| 72 | + def _fetch_osv_record(self, osv_id: str) -> dict[str, Any]: |
| 73 | + """Fetch an individual OSV record from the Root IO API.""" |
| 74 | + self.logger.debug(f"fetching OSV record: {osv_id}") |
| 75 | + url = f"{self.api_base_url}/{osv_id}.json" |
| 76 | + response = http.get(url, self.logger, timeout=self.download_timeout) |
| 77 | + |
| 78 | + record = response.json() |
| 79 | + |
| 80 | + # Save the record to workspace for reproducibility |
| 81 | + record_dir = os.path.join(self.workspace.input_path, "osv") |
| 82 | + os.makedirs(record_dir, exist_ok=True) |
| 83 | + record_file = os.path.join(record_dir, f"{osv_id}.json") |
| 84 | + with open(record_file, "wb") as f: |
| 85 | + f.write(orjson.dumps(record)) |
| 86 | + |
| 87 | + return record |
| 88 | + |
| 89 | + def _normalize(self, vuln_entry: dict[str, Any]) -> tuple[str, str, dict[str, Any]]: |
| 90 | + """Normalize a vulnerability entry into the expected tuple format.""" |
| 91 | + self.logger.trace("normalizing vulnerability data") # type: ignore[attr-defined] |
| 92 | + |
| 93 | + # Extract the OSV record as-is (using OSV schema) |
| 94 | + # Transformation to Grype-specific schema happens in grype-db |
| 95 | + vuln_id = vuln_entry["id"] |
| 96 | + vuln_schema = vuln_entry["schema_version"] |
| 97 | + |
| 98 | + # Transform ecosystem format: Root IO API returns "Root:Alpine:3.18" format, |
| 99 | + # but grype-db expects "Alpine:3.18" (without "Root:" prefix) |
| 100 | + for affected in vuln_entry.get("affected", []): |
| 101 | + package = affected.get("package", {}) |
| 102 | + ecosystem = package.get("ecosystem", "") |
| 103 | + if ecosystem.startswith("Root:"): |
| 104 | + package["ecosystem"] = ecosystem[5:] # Strip "Root:" prefix |
| 105 | + self.logger.debug(f"normalized ecosystem: {ecosystem} -> {package['ecosystem']}") |
| 106 | + |
| 107 | + return vuln_id, vuln_schema, vuln_entry |
| 108 | + |
| 109 | + def get(self) -> Generator[tuple[str, str, dict[str, Any]]]: |
| 110 | + """ |
| 111 | + Fetch and yield OSV records from Root IO API. |
| 112 | +
|
| 113 | + Yields: |
| 114 | + Tuples of (vulnerability_id, schema_version, record_dict) |
| 115 | + """ |
| 116 | + # Fetch the list of OSV IDs |
| 117 | + osv_ids = self._fetch_osv_ids() |
| 118 | + |
| 119 | + # Download fixdate information if needed |
| 120 | + # TEMPORARILY DISABLED: self.fixdater.download() |
| 121 | + # Fix date patching is optional and requires authentication |
| 122 | + |
| 123 | + # Fetch and process each OSV record |
| 124 | + for osv_id in osv_ids: |
| 125 | + try: |
| 126 | + vuln_entry = self._fetch_osv_record(osv_id) |
| 127 | + |
| 128 | + # Apply fix date patching for published/modified dates |
| 129 | + # TEMPORARILY DISABLED: osv.patch_fix_date(vuln_entry, self.fixdater) |
| 130 | + # Fix date patching is optional and requires authentication |
| 131 | + |
| 132 | + # Normalize and yield the record |
| 133 | + yield self._normalize(vuln_entry) |
| 134 | + except Exception as e: |
| 135 | + self.logger.error(f"failed to process OSV record {osv_id}: {e}") |
| 136 | + continue |
0 commit comments