|
| 1 | +import aiohttp |
| 2 | +import json |
| 3 | + |
| 4 | +from asgiref.sync import sync_to_async |
| 5 | +from queue import Empty, Queue |
| 6 | +from threading import Thread |
| 7 | +from typing import Callable, Optional, Tuple, Dict, Any |
| 8 | + |
| 9 | + |
| 10 | +from pulpcore.plugin.util import get_domain |
| 11 | +from pulpcore.plugin.models import CreatedResource |
| 12 | +from pulpcore.constants import ( |
| 13 | + OSV_QUERY_URL, |
| 14 | + VULNERABILITY_TASK_THREAD_TIMEOUT, |
| 15 | +) |
| 16 | +from pulpcore.app.models.vulnerability_report import VulnerabilityReport |
| 17 | + |
| 18 | +# Create a thread-safe queue to share Content units between threads |
| 19 | +content_queue = Queue() |
| 20 | + |
| 21 | + |
| 22 | +async def check_content(func: Callable, args: Optional[Tuple] = None) -> None: |
| 23 | + """ |
| 24 | + Start the background_thread and make the API requests (scan) to osv.dev with the packages |
| 25 | + from Queue. |
| 26 | +
|
| 27 | + Args: |
| 28 | + func (callable | str): The function to populate content_queue Queue with the content_units. |
| 29 | + Each item in the queue must follow the osv.dev request data format. |
| 30 | + args (tuple): The positional arguments to pass on to the func. |
| 31 | + """ |
| 32 | + if not args: |
| 33 | + args = () |
| 34 | + background_thread = Thread(target=func, args=args) |
| 35 | + await _scan_packages(background_thread) |
| 36 | + background_thread.join() |
| 37 | + |
| 38 | + |
| 39 | +async def _scan_packages(background_thread: Thread) -> None: |
| 40 | + """ |
| 41 | + Makes a request to the osv.dev API and store the results in VulnerabilityReport model. |
| 42 | +
|
| 43 | + Args: |
| 44 | + background_thread (Thread): We need to pass the thread object used to populate the queue to |
| 45 | + prevent deadlock issues. |
| 46 | + """ |
| 47 | + scanned_packages = await _scan_packages_from_queue( |
| 48 | + background_thread=background_thread, |
| 49 | + ) |
| 50 | + await _save_vulnerability_report(scanned_packages) |
| 51 | + |
| 52 | + |
| 53 | +async def _scan_packages_from_queue( |
| 54 | + background_thread: Thread, http_client: Optional[aiohttp.ClientSession] = None |
| 55 | +) -> Dict[str, Any]: |
| 56 | + """ |
| 57 | + Scans packages from a queue by making HTTP requests to OSV API. |
| 58 | +
|
| 59 | + Args: |
| 60 | + background_thread (Thread): Thread populating the queue |
| 61 | + http_client (Optional[aiohttp.ClientSession]): HTTP client for making requests |
| 62 | +
|
| 63 | + Returns: |
| 64 | + Dict[str, Any]: Dictionary mapping package names to vulnerability data |
| 65 | + """ |
| 66 | + |
| 67 | + # Use provided client or create a new one |
| 68 | + if http_client: |
| 69 | + return await _process_queue_with_client(background_thread, http_client) |
| 70 | + |
| 71 | + async with aiohttp.ClientSession() as session: |
| 72 | + return await _process_queue_with_client(background_thread, session) |
| 73 | + |
| 74 | + |
| 75 | +async def _process_queue_with_client( |
| 76 | + background_thread: Thread, |
| 77 | + session: aiohttp.ClientSession, |
| 78 | +) -> Dict[str, Any]: |
| 79 | + """ |
| 80 | + Process queue items using the provided HTTP client session. |
| 81 | +
|
| 82 | + Args: |
| 83 | + background_thread (Thread): Thread populating the queue |
| 84 | + session (aiohttp.ClientSession): HTTP client session |
| 85 | +
|
| 86 | + Returns: |
| 87 | + Dict[str, Any]: Dictionary mapping package names to vulnerability data |
| 88 | + """ |
| 89 | + scanned_packages = {} |
| 90 | + try: |
| 91 | + for osv_data in iter( |
| 92 | + lambda: content_queue.get(timeout=VULNERABILITY_TASK_THREAD_TIMEOUT), None |
| 93 | + ): |
| 94 | + if isinstance(osv_data, Exception): |
| 95 | + raise RuntimeError(f"Background vuln report task failed to execute: {osv_data}") |
| 96 | + |
| 97 | + vulnerability_data = await _query_osv_api(session, osv_data) |
| 98 | + package_name = _get_package_name(osv_data) |
| 99 | + |
| 100 | + if vulnerability_data.get("vulns"): |
| 101 | + scanned_packages[package_name] = vulnerability_data["vulns"] |
| 102 | + |
| 103 | + # Handle pagination |
| 104 | + if next_page_token := vulnerability_data.get("next_page_token"): |
| 105 | + next_page_request = build_osv_data( |
| 106 | + osv_data["package"]["name"], |
| 107 | + osv_data["package"]["ecosystem"], |
| 108 | + osv_data.get("version"), |
| 109 | + next_page_token, |
| 110 | + ) |
| 111 | + content_queue.put(next_page_request) |
| 112 | + |
| 113 | + except Empty: |
| 114 | + if not background_thread.is_alive(): |
| 115 | + raise RuntimeError("Vuln report task thread died unexpectedly.") |
| 116 | + else: |
| 117 | + raise RuntimeError("Background vuln report thread took too long.") |
| 118 | + |
| 119 | + return scanned_packages |
| 120 | + |
| 121 | + |
| 122 | +async def _query_osv_api( |
| 123 | + session: aiohttp.ClientSession, osv_data: Dict[str, Any] |
| 124 | +) -> Dict[str, Any]: |
| 125 | + """ |
| 126 | + Make a single request to the OSV API. |
| 127 | +
|
| 128 | + Args: |
| 129 | + session (aiohttp.ClientSession): HTTP client session |
| 130 | + osv_data (Dict[str, Any]): OSV query data |
| 131 | +
|
| 132 | + Returns: |
| 133 | + Dict[str, Any]: JSON response from OSV API |
| 134 | + """ |
| 135 | + data = json.dumps(osv_data) |
| 136 | + async with session.post(url=OSV_QUERY_URL, data=data) as response: |
| 137 | + response_body = await response.text() |
| 138 | + return json.loads(response_body) |
| 139 | + |
| 140 | + |
| 141 | +def _get_package_name(osv_data: Dict[str, Any]) -> str: |
| 142 | + """ |
| 143 | + Extract package name from OSV data. |
| 144 | +
|
| 145 | + Args: |
| 146 | + osv_data (Dict[str, Any]): OSV query data |
| 147 | +
|
| 148 | + Returns: |
| 149 | + str: Formatted package name |
| 150 | + """ |
| 151 | + osv_package_name = osv_data["package"]["name"] |
| 152 | + osv_package_version = osv_data.get("version", "") |
| 153 | + return "{package}-{version}".format( |
| 154 | + package=osv_package_name, |
| 155 | + version=osv_package_version, |
| 156 | + ) |
| 157 | + |
| 158 | + |
| 159 | +async def _save_vulnerability_report(scanned_packages: Dict[str, Any]) -> None: |
| 160 | + """ |
| 161 | + Save vulnerability report to the database. |
| 162 | +
|
| 163 | + Args: |
| 164 | + scanned_packages (Dict[str, Any]): Dictionary mapping package names to vulnerability data |
| 165 | + """ |
| 166 | + vuln_report, created = await sync_to_async(VulnerabilityReport.objects.get_or_create)( |
| 167 | + vulns=scanned_packages, pulp_domain=get_domain() |
| 168 | + ) |
| 169 | + if created: |
| 170 | + await CreatedResource.objects.acreate(content_object=vuln_report) |
| 171 | + |
| 172 | + |
| 173 | +def build_osv_data( |
| 174 | + name: str, ecosystem: str, version: Optional[str] = None, next_page_token: Optional[str] = None |
| 175 | +) -> Dict[str, Any]: |
| 176 | + """ |
| 177 | + Helper function to build the osv.dev request data based on content object |
| 178 | +
|
| 179 | + Args: |
| 180 | + name (str): Name of the package. Should match the name used in the package ecosystem. |
| 181 | + ecosystem (str): The ecosystem for this package. Check osv.dev documentation for |
| 182 | + the complete list of valid ecosystem names. |
| 183 | + version (str): The version string to query for. |
| 184 | + next_page_token (Optional[str]): If the previous query fetched a large number of results, |
| 185 | + the response will be paginated. |
| 186 | +
|
| 187 | + Returns (Dict[str, Any]): The package which vulnerability will be checked. A dicitonary following the |
| 188 | + expected payload format from osv.dev. |
| 189 | + """ |
| 190 | + osv_data: Dict[str, Any] = {"package": {"name": name, "ecosystem": ecosystem}} |
| 191 | + if version: |
| 192 | + osv_data["version"] = version |
| 193 | + if next_page_token: |
| 194 | + osv_data["page_token"] = next_page_token |
| 195 | + return osv_data |
0 commit comments