|
| 1 | +import aiohttp |
| 2 | +import json |
| 3 | +import re |
| 4 | + |
| 5 | +from asgiref.sync import sync_to_async |
| 6 | +from queue import Empty, Queue |
| 7 | +from threading import Thread |
| 8 | + |
| 9 | +from pulpcore.plugin.util import get_domain |
| 10 | +from pulpcore.plugin.models import CreatedResource, VulnerabilityReport |
| 11 | +from pulpcore.constants import OSV_QUERY_URL, VULNERABILITY_TASK_THREAD_TIMEOUT |
| 12 | + |
| 13 | + |
| 14 | +# Create a thread-safe queue to share Content units between threads |
| 15 | +content_queue = Queue() |
| 16 | + |
| 17 | +# CPE prefix from Red Hat packages |
| 18 | +cpe_prefix = re.compile(r"^cpe:\/[oa]:redhat") |
| 19 | + |
| 20 | + |
| 21 | +async def check_content(func, args=None): |
| 22 | + """ |
| 23 | + Start the background_thread and make the API requests (scan) to osv.dev with the packages |
| 24 | + from Queue. |
| 25 | +
|
| 26 | + Args: |
| 27 | + func (callable | str): The function to populate content_queue Queue with the osv.dev |
| 28 | + expected request data format. |
| 29 | + args (tuple): The positional arguments to pass on to the func. |
| 30 | + """ |
| 31 | + if not args: |
| 32 | + args = () |
| 33 | + background_thread = Thread(target=func, args=args) |
| 34 | + await _scan_packages(background_thread) |
| 35 | + background_thread.join() |
| 36 | + |
| 37 | + |
| 38 | +async def _scan_packages(background_thread): |
| 39 | + """ |
| 40 | + Makes a request to the osv.dev API and store the results in VulnerabilityReport model. |
| 41 | +
|
| 42 | + Args: |
| 43 | + background_thread (Thread): We need to pass the thread object used to populate the queue to |
| 44 | + prevent deadlock issues. |
| 45 | + """ |
| 46 | + scanned_packages = await _scan_packages_from_queue( |
| 47 | + background_thread=background_thread, |
| 48 | + ) |
| 49 | + await _save_vulnerability_report(scanned_packages) |
| 50 | + |
| 51 | + |
| 52 | +async def _scan_packages_from_queue(background_thread, http_client=None): |
| 53 | + """ |
| 54 | + Scans packages from a queue by making HTTP requests to OSV API. |
| 55 | +
|
| 56 | + Args: |
| 57 | + background_thread (Thread): Thread populating the queue |
| 58 | + http_client (Optional[aiohttp.ClientSession]): HTTP client for making requests |
| 59 | +
|
| 60 | + Returns: |
| 61 | + Dict[str, Any]: Dictionary mapping package names to vulnerability data |
| 62 | + """ |
| 63 | + |
| 64 | + # Use provided client or create a new one |
| 65 | + if http_client: |
| 66 | + return await _process_queue_with_client(background_thread, http_client) |
| 67 | + |
| 68 | + async with aiohttp.ClientSession() as session: |
| 69 | + return await _process_queue_with_client(background_thread, session) |
| 70 | + |
| 71 | + |
| 72 | +async def _process_queue_with_client(background_thread, session): |
| 73 | + """ |
| 74 | + Process queue items using the provided HTTP client session. |
| 75 | +
|
| 76 | + Args: |
| 77 | + background_thread (Thread): Thread populating the queue |
| 78 | + session (aiohttp.ClientSession): HTTP client session |
| 79 | +
|
| 80 | + Returns: |
| 81 | + Dict[str, Any]: Dictionary mapping package names to vulnerability data |
| 82 | + """ |
| 83 | + scanned_packages = {} |
| 84 | + try: |
| 85 | + for osv_data in iter( |
| 86 | + lambda: content_queue.get(timeout=VULNERABILITY_TASK_THREAD_TIMEOUT), None |
| 87 | + ): |
| 88 | + if isinstance(osv_data, Exception): |
| 89 | + raise RuntimeError(f"Background vuln report task failed to execute: {osv_data}") |
| 90 | + |
| 91 | + vulnerability_data = await _query_osv_api(session, osv_data) |
| 92 | + package_name = _get_package_name(osv_data) |
| 93 | + |
| 94 | + if vulnerability_data.get("vulns"): |
| 95 | + scanned_packages[package_name] = vulnerability_data["vulns"] |
| 96 | + |
| 97 | + # Handle pagination |
| 98 | + if next_page_token := vulnerability_data.get("next_page_token"): |
| 99 | + osv_data["page_token"] = next_page_token |
| 100 | + content_queue.put(osv_data) |
| 101 | + |
| 102 | + except Empty: |
| 103 | + if not background_thread.is_alive(): |
| 104 | + raise RuntimeError("Vuln report task thread died unexpectedly.") |
| 105 | + else: |
| 106 | + raise RuntimeError("Background vuln report thread took too long.") |
| 107 | + |
| 108 | + return scanned_packages |
| 109 | + |
| 110 | + |
| 111 | +async def _query_osv_api(session, osv_data): |
| 112 | + """ |
| 113 | + Make a single request to the OSV API. |
| 114 | +
|
| 115 | + Args: |
| 116 | + session (aiohttp.ClientSession): HTTP client session |
| 117 | + osv_data (Dict[str, Any]): OSV query data |
| 118 | +
|
| 119 | + Returns: |
| 120 | + Dict[str, Any]: JSON response from OSV API |
| 121 | + """ |
| 122 | + data = json.dumps(osv_data) |
| 123 | + async with session.post(url=OSV_QUERY_URL, data=data) as response: |
| 124 | + response_body = await response.text() |
| 125 | + return json.loads(response_body) |
| 126 | + |
| 127 | + |
| 128 | +def _get_package_name(osv_data): |
| 129 | + """ |
| 130 | + Extract package name from OSV data. |
| 131 | +
|
| 132 | + Args: |
| 133 | + osv_data (Dict[str, Any]): OSV query data |
| 134 | +
|
| 135 | + Returns: |
| 136 | + str: Formatted package name |
| 137 | + """ |
| 138 | + osv_package_name = osv_data["package"]["name"] |
| 139 | + if osv_package_version := osv_data.get("version", ""): |
| 140 | + return f"{osv_package_name}-{osv_package_version}" |
| 141 | + return f"{osv_package_name}" |
| 142 | + |
| 143 | + |
| 144 | +async def _save_vulnerability_report(scanned_packages): |
| 145 | + """ |
| 146 | + Save vulnerability report to the database. |
| 147 | +
|
| 148 | + Args: |
| 149 | + scanned_packages (Dict[str, Any]): Dictionary mapping package names to vulnerability data |
| 150 | + """ |
| 151 | + vuln_report, created = await sync_to_async(VulnerabilityReport.objects.get_or_create)( |
| 152 | + vulns=scanned_packages, pulp_domain=get_domain() |
| 153 | + ) |
| 154 | + if created: |
| 155 | + await CreatedResource.objects.acreate(content_object=vuln_report) |
0 commit comments