Files
vuln-mcp/tests/test_prod_osv.py
T
omar 0b285c7608
CI / Python 3.13 (push) Successful in 23s
CI / Python 3.12 (push) Successful in 26s
CI / Build and smoke-test image (push) Successful in 10s
Accept single-segment OSV record IDs with embedded spaces
2026-11-28 14:51:30 +03:00

131 lines
5.5 KiB
Python

from __future__ import annotations
import io
import json
from pathlib import Path
from time import monotonic
from zipfile import ZipFile
import httpx
import pytest
from vuln_mcp import transport
from vuln_mcp.config import Settings
from vuln_mcp.sources import feeds_archive, feeds_bulk
from vuln_mcp.sources.feeds_bulk import OSV_ARCHIVE, OSV_MANIFEST, OSV_ROOT
from vuln_mcp.sources.live import lookup
from vuln_mcp.sources.parsers import InvalidData
from vuln_mcp.store import Store
from vuln_mcp.sync import Sync
from vuln_mcp.transport import HttpClients, HttpError
RHSA = "RHSA-2026:103406"
ALBA = "ALBA-2019:0973"
MODIFIED = "2026-11-28T10:28:21.764951231Z"
EARLIER = "2026-11-27T10:28:21Z"
RECORD_URL = f"{OSV_ROOT}/Red%20Hat/RHSA-2026%3A103406.json"
DETAIL_URL = "https://api.osv.dev/v1/vulns/RHSA-2026%3A103406"
QUERY_URL = "https://api.osv.dev/v1/query"
def _records() -> dict[str, dict[str, str]]:
return {
ALBA: {"id": ALBA, "modified": EARLIER},
RHSA: {"id": RHSA, "modified": MODIFIED, "schema_version": "1.9.2"},
'SUSE-SU-403 Forbidden-1': {'id': 'SUSE-SU-403 Forbidden-1', 'modified': EARLIER},
}
def _zip(entries: list[tuple[str, dict[str, str]]]) -> bytes:
target = io.BytesIO()
with ZipFile(target, "w") as archive:
for name, row in entries:
archive.writestr(name, json.dumps(row))
return target.getvalue()
def _manifest() -> bytes:
return f"{MODIFIED},Red Hat/{RHSA}\n{EARLIER},AlmaLinux/{ALBA}\n{EARLIER},SUSE/SUSE-SU-403 Forbidden-1\n".encode()
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
@pytest.mark.anyio
async def test_osv_public_ids_survive_bootstrap_and_both_live_lookup_paths(tmp_path, monkeypatch):
# Two rows and members emulate the production feed exceeding the generic cap.
monkeypatch.setattr(feeds_archive, "RECORD_LIMIT", 1)
monkeypatch.setattr(feeds_archive, "OSV_RECORD_LIMIT", 3)
monkeypatch.setattr(feeds_bulk, "OSV_RECORD_LIMIT", 3)
monkeypatch.setattr(feeds_bulk, "OSV_BOOTSTRAP_SPACE", 1)
records = _records()
archive = _zip([(f"{native}.json", row) for native, row in records.items()])
calls = []
original = httpx.AsyncClient
def offline_client(*, proxy: str | None, trust_env: bool) -> httpx.AsyncClient:
assert not trust_env
def respond(request: httpx.Request) -> httpx.Response:
url = str(request.url)
calls.append((proxy is not None, request.method, url))
if url == OSV_MANIFEST:
return httpx.Response(200, content=_manifest())
if url == OSV_ARCHIVE:
return httpx.Response(200, content=archive)
if url in {RECORD_URL, DETAIL_URL}:
return httpx.Response(200, json=records[RHSA])
if url == QUERY_URL:
return httpx.Response(200, json={"vulns": [records[RHSA]]})
pytest.fail(f"Unexpected OSV request: {url}")
return original(trust_env=False, transport=httpx.MockTransport(respond))
monkeypatch.setattr(transport.httpx, "AsyncClient", offline_client)
settings = Settings(tmp_path, proxies=("http://proxy.test:8080",), max_retries=0)
async with Store(tmp_path) as store, HttpClients(settings, store) as http:
assert await Sync(store, http.index).refresh_once("osv")
[suse] = await store.by_id('SUSE-SU-403 Forbidden-1')
assert suse.native_id == 'SUSE-SU-403 Forbidden-1'
[old] = await store.by_id(ALBA)
assert old.artifact is not None and old.artifact.endswith(f"#{ALBA}.json")
[recent] = await store.by_id(RHSA)
assert recent.updated == MODIFIED
for kind, value in [("id", RHSA), ("purl", "pkg:rpm/example")]:
page = await lookup("osv", kind, value, http=http.live, deadline=monotonic() + 10)
assert page.status.status == "ok"
assert [doc.native_id for doc in page.docs] == [RHSA]
with pytest.raises(HttpError, match="invalid_data"):
await http.index.json("osv", RECORD_URL.replace("Red%20Hat/", "Red%3AHat/"))
with pytest.raises(HttpError, match="invalid_data"):
await http.index.json("osv", RECORD_URL.replace("%3A", "%2F"))
assert calls == [
(False, "GET", OSV_MANIFEST), (False, "GET", OSV_ARCHIVE),
(False, "GET", OSV_MANIFEST), (False, "GET", RECORD_URL),
(True, "GET", DETAIL_URL), (True, "POST", QUERY_URL),
]
def test_osv_count_limits_remain_finite(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(feeds_archive, "OSV_RECORD_LIMIT", 1)
monkeypatch.setattr(feeds_bulk, "OSV_RECORD_LIMIT", 1)
csv_path = tmp_path / "manifest.csv"
csv_path.write_bytes(_manifest())
with pytest.raises(InvalidData, match="invalid OSV modified_id.csv record"):
feeds_bulk._osv_changes(csv_path, None)
zip_path = tmp_path / "feed.zip"
zip_path.write_bytes(_zip([(f"{native}.json", row) for native, row in _records().items()]))
with pytest.raises(InvalidData, match="ZIP central directory exceeds limits"):
list(feeds_archive.archive_docs(zip_path, "osv", "fixture"))
@pytest.mark.parametrize("prefix", ["C:", "C:/", "Red:Hat/", "../", "/"])
def test_osv_colons_in_ids_do_not_permit_unsafe_zip_paths(tmp_path: Path, prefix: str):
zip_path = tmp_path / "feed.zip"
zip_path.write_bytes(_zip([(f"{prefix}{RHSA}.json", _records()[RHSA])]))
with pytest.raises(InvalidData, match="unsafe ZIP member"):
list(feeds_archive.archive_docs(zip_path, "osv", "fixture"))