- Add private SQLite feed indexing, publisher-attributed advisory search and scoped HTTP routes. - Exercise supported proxy protocols, cancellation, version applicability and the stdio lifecycle. - Gate Docker builds on Python 3.12/3.13 tests and branch-aware coverage.
360 lines
16 KiB
Python
360 lines
16 KiB
Python
import asyncio
|
|
import gzip
|
|
import hashlib
|
|
import io
|
|
import json
|
|
from collections import defaultdict, deque
|
|
from collections.abc import Mapping
|
|
from dataclasses import dataclass, field
|
|
from datetime import UTC, datetime
|
|
from pathlib import Path
|
|
from zipfile import ZIP_DEFLATED, ZipFile
|
|
|
|
import pytest
|
|
|
|
from vuln_mcp.sources import feeds_bulk, feeds_metrics
|
|
from vuln_mcp.sources.feeds_bulk import CVE_RELEASES, OSV_ARCHIVE, OSV_MANIFEST, OSV_ROOT
|
|
from vuln_mcp.sources.feeds_csaf import MSRC_DIRECTORY, MSRC_MANIFEST, MSRC_METADATA, SIEMENS_METADATA
|
|
from vuln_mcp.sources.feeds_metrics import EPSS_ROOT, KEV_CSV
|
|
from vuln_mcp.store import Store
|
|
from vuln_mcp.sync import Sync
|
|
from vuln_mcp.transport import HttpError
|
|
|
|
pytestmark = pytest.mark.anyio
|
|
CVE = "CVE-2025-1234"
|
|
OTHER = "CVE-2025-1235"
|
|
NOW = datetime(2025, 6, 11, 12, tzinfo=UTC)
|
|
BEFORE = "2025-06-10T07:00:00Z"
|
|
AFTER = "2025-06-11T08:00:00Z"
|
|
SIEMENS = "https://cert-portal.siemens.com/productcert/csaf/"
|
|
|
|
|
|
class FixedDate(datetime):
|
|
@classmethod
|
|
def now(cls, tz=None):
|
|
return NOW.astimezone(tz) if tz else NOW.replace(tzinfo=None)
|
|
|
|
|
|
@pytest.fixture
|
|
def anyio_backend():
|
|
return "asyncio"
|
|
|
|
|
|
@dataclass
|
|
class Reply:
|
|
body: object = None
|
|
headers: dict[str, str] = field(default_factory=dict)
|
|
code: int = 200
|
|
|
|
|
|
class FeedHttp:
|
|
def __init__(self):
|
|
self.responses = defaultdict(deque)
|
|
self.calls = []
|
|
self.pause_at = None
|
|
self.paused = asyncio.Event()
|
|
self.resume = asyncio.Event()
|
|
|
|
def put(self, url, *replies):
|
|
self.responses[url].extend(replies)
|
|
|
|
def _request(self, url, headers):
|
|
self.calls.append((url, dict(headers or {})))
|
|
assert self.responses[url], f"unexpected feed request: {url}"
|
|
reply = self.responses[url].popleft()
|
|
if reply.code == 404:
|
|
raise HttpError("not_found")
|
|
return reply
|
|
|
|
async def json(self, source, url, *, params=None, headers=None):
|
|
if url == CVE_RELEASES:
|
|
assert params == {"per_page": "30"}
|
|
reply = self._request(url, headers)
|
|
return reply.body, reply.headers
|
|
|
|
async def download(self, source, url, path: Path, *, headers: Mapping | None = None, limit: int):
|
|
reply = self._request(url, headers)
|
|
if url == self.pause_at:
|
|
self.paused.set()
|
|
await self.resume.wait()
|
|
if reply.code == 200:
|
|
assert isinstance(reply.body, bytes)
|
|
if len(reply.body) > limit:
|
|
raise HttpError("invalid_data")
|
|
path.write_bytes(reply.body)
|
|
return reply.code, reply.headers
|
|
|
|
|
|
def encoded(value):
|
|
return json.dumps(value).encode()
|
|
|
|
|
|
def cve(id=CVE, title="Original advisory", state="PUBLISHED"):
|
|
return {"dataType": "CVE_RECORD", "dataVersion": "5.2.0", "cveMetadata": {
|
|
"cveId": id, "state": state, "dateUpdated": BEFORE,
|
|
}, "containers": {"cna": {"title": title, "providerMetadata": {"shortName": "Publisher"}}}}
|
|
|
|
|
|
def zipped(entries):
|
|
buffer = io.BytesIO()
|
|
with ZipFile(buffer, "w", compression=ZIP_DEFLATED) as archive:
|
|
for path, content in entries:
|
|
archive.writestr(path, content if isinstance(content, bytes) else encoded(content))
|
|
return buffer.getvalue()
|
|
|
|
|
|
def cve_release(http, day, hour, base, delta, *, send_base):
|
|
tag = f"cve_{day}_{hour}00Z"
|
|
assets = []
|
|
for name, data in [(f"{day}_all_CVEs_at_midnight.zip.zip", base),
|
|
(f"{day}_delta_CVEs_at_{hour}00Z.zip", delta)]:
|
|
url = f"https://github.com/CVEProject/cvelistV5/releases/download/{tag}/{name}"
|
|
assets.append({"name": name, "browser_download_url": url, "size": len(data),
|
|
"digest": f"sha256:{hashlib.sha256(data).hexdigest()}"})
|
|
if send_base or "delta_" in name:
|
|
http.put(url, Reply(data))
|
|
release = {"tag_name": tag, "published_at": f"{day}T{hour}:00:00Z", "assets": assets}
|
|
http.put(CVE_RELEASES, Reply([release], {"ETag": f'"{tag}"'}))
|
|
return assets[-1]["browser_download_url"]
|
|
|
|
|
|
async def test_cve_rolls_cumulative_layer_and_new_day_atomically(tmp_path):
|
|
baseline = zipped([("cves.zip", zipped([
|
|
("./cves/delta.json", {"new": [], "updated": []}),
|
|
(f"./cves/2025/1xxx/{CVE}.json", cve()),
|
|
]))])
|
|
delta1 = zipped([(f"deltaCves/{CVE}.json", cve(title="First hourly update")),
|
|
(f"deltaCves/{OTHER}.json", cve(OTHER, "Only in first delta"))])
|
|
delta2 = zipped([(f"deltaCves/{CVE}.json", cve(title="Record withdrawn", state="REJECTED"))])
|
|
next_base = zipped([("cves.zip", zipped([(f"{OTHER}.json", cve(OTHER, "New daily baseline"))]))])
|
|
empty = zipped([])
|
|
http = FeedHttp()
|
|
cve_release(http, "2025-06-10", "01", baseline, delta1, send_base=True)
|
|
cve_release(http, "2025-06-10", "02", baseline, delta2, send_base=False)
|
|
http.put(CVE_RELEASES, Reply(code=304))
|
|
delta_url = cve_release(http, "2025-06-11", "01", next_base, b"broken zip", send_base=True)
|
|
http.pause_at = delta_url
|
|
cve_release(http, "2025-06-11", "02", next_base, empty, send_base=True)
|
|
async with Store(tmp_path) as store:
|
|
sync = Sync(store, http)
|
|
assert await sync.refresh_once("cvelist")
|
|
assert [doc.title for doc in await store.by_id(CVE)] == ["First hourly update"]
|
|
assert await sync.refresh_once("cvelist")
|
|
assert [doc.state for doc in await store.by_id(CVE)] == ["rejected"]
|
|
assert not await store.by_id(OTHER)
|
|
generation = await store.generation()
|
|
assert await sync.refresh_once("cvelist")
|
|
assert await store.generation() == generation
|
|
assert (CVE_RELEASES, {"If-None-Match": '"cve_2025-06-10_0200Z"'}) in http.calls
|
|
previous = await store.state("cvelist")
|
|
task = asyncio.create_task(sync.refresh_once("cvelist"))
|
|
try:
|
|
await asyncio.wait_for(http.paused.wait(), 5)
|
|
assert [doc.state for doc in await store.by_id(CVE)] == ["rejected"]
|
|
assert await store.lookup("New daily baseline") == []
|
|
assert await store.by_id(OTHER) == []
|
|
finally:
|
|
http.resume.set()
|
|
succeeded = await task
|
|
assert not succeeded
|
|
failed = await store.state("cvelist")
|
|
assert failed["checkpoint"] == previous["checkpoint"]
|
|
assert failed["last_success"] == previous["last_success"]
|
|
assert failed["status"] == "invalid_data"
|
|
assert await sync.refresh_once("cvelist")
|
|
assert not await store.by_id(CVE)
|
|
[new] = await store.by_id(OTHER)
|
|
assert new.title == "New daily baseline"
|
|
digest, member = new.artifact.split("#", 1)
|
|
assert member == f"cves.zip!/{OTHER}.json"
|
|
assert store.artifact_path(digest).read_bytes() == next_base
|
|
|
|
|
|
@pytest.mark.parametrize("invalid", ["conflicting-id", "traversal", "second-wrapper"])
|
|
async def test_cve_rejects_invalid_archive_without_publishing(tmp_path, invalid):
|
|
if invalid == "conflicting-id":
|
|
data = zipped([(f"cves/{CVE}.json", cve()), (f"other/{CVE}.json", cve(title="Conflict"))])
|
|
elif invalid == "traversal":
|
|
data = zipped([(f"../{CVE}.json", cve())])
|
|
else:
|
|
data = zipped([("cves.zip", zipped([(f"{CVE}.json", cve())]))])
|
|
http = FeedHttp()
|
|
cve_release(http, "2025-06-10", "01", zipped([("cves.zip", data)]), zipped([]), send_base=True)
|
|
async with Store(tmp_path) as store:
|
|
assert not await Sync(store, http).refresh_once("cvelist")
|
|
assert (await store.state("cvelist"))["status"] == "invalid_data"
|
|
assert not await store.by_id(CVE)
|
|
|
|
|
|
def osv(id, modified=BEFORE, **fields):
|
|
return {"id": id, "modified": modified, "summary": f"Advisory {id}", **fields}
|
|
|
|
|
|
async def test_osv_replays_inclusive_boundary_and_retains_checkpoint_on_error(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(feeds_bulk, "datetime", FixedDate)
|
|
monkeypatch.setattr(feeds_bulk, "OSV_BOOTSTRAP_SPACE", 1)
|
|
primary, second = "GHSA-1111-2222-3333", "PYSEC-2025-22"
|
|
before = f"{BEFORE},PyPI/{primary}\n".encode()
|
|
simultaneous = f"{BEFORE},PyPI/{primary}\n{BEFORE},npm/{second}\n".encode()
|
|
changes = f"{AFTER},[EMPTY]/{primary}\n{AFTER},npm/{second}\n".encode()
|
|
first = osv(primary, affected=[{"package": {"name": "example", "ecosystem": "PyPI"}, "versions": ["1.0"]}])
|
|
other = osv(second)
|
|
http = FeedHttp()
|
|
http.put(OSV_MANIFEST, Reply(before), Reply(simultaneous, {"etag": '"boundary"'}),
|
|
Reply(changes, {"etag": '"revised"'}), Reply(changes, {"etag": '"revised"'}),
|
|
Reply(changes, {"etag": '"same-content"'}), Reply(code=304))
|
|
http.put(OSV_ARCHIVE, Reply(zipped([(f"PyPI/{primary}.json", first), (f"npm/{primary}.json", first)])))
|
|
http.put(f"{OSV_ROOT}/PyPI/{primary}.json", Reply(encoded(first)))
|
|
http.put(f"{OSV_ROOT}/npm/{second}.json", Reply(encoded(other)), Reply(b"not json"),
|
|
Reply(encoded(osv(second, AFTER))))
|
|
withdrawn = osv(primary, AFTER, withdrawn=AFTER)
|
|
http.put(f"{OSV_ROOT}/%5BEMPTY%5D/{primary}.json", Reply(encoded(withdrawn)), Reply(encoded(withdrawn)))
|
|
async with Store(tmp_path) as store:
|
|
sync = Sync(store, http)
|
|
assert await sync.refresh_once("osv")
|
|
assert [doc.native_id for doc in await store.lookup("example")] == [primary]
|
|
assert [doc.native_id for doc in await store.by_id(second)] == [second]
|
|
previous = await store.state("osv")
|
|
assert not await sync.refresh_once("osv")
|
|
assert (await store.state("osv"))["checkpoint"] == previous["checkpoint"]
|
|
assert (await store.by_id(primary))[0].state == "published"
|
|
assert await sync.refresh_once("osv")
|
|
assert [doc.state for doc in await store.by_id(primary)] == ["withdrawn"]
|
|
assert not await store.lookup("example")
|
|
assert (await store.state("osv"))["checkpoint"]["high_water"] == "2025-06-11T08:00:00+00:00"
|
|
generation = await store.generation()
|
|
assert await sync.refresh_once("osv")
|
|
assert await sync.refresh_once("osv")
|
|
assert await store.generation() == generation
|
|
assert http.calls[-1] == (OSV_MANIFEST, {"If-None-Match": '"same-content"'})
|
|
|
|
|
|
async def test_kev_handles_bom_multiline_and_304(tmp_path):
|
|
csv = ('\ufeffcveID,newColumn,dateAdded,requiredAction\r\n'
|
|
f'{CVE},extra,2025-06-10,"Apply update, if available.\r\nSee official guidance."\r\n').encode()
|
|
http = FeedHttp()
|
|
http.put(KEV_CSV, Reply(csv, {"Last-Modified": "Tue, 10 Jun 2025 14:00:00 GMT"}), Reply(code=304))
|
|
async with Store(tmp_path) as store:
|
|
sync = Sync(store, http)
|
|
assert await sync.refresh_once("kev")
|
|
assert await sync.refresh_once("kev")
|
|
[doc] = await store.by_id(CVE)
|
|
assert doc.issues[0].facts["kev"] == {
|
|
"member": True, "date_added": "2025-06-10", "as_of": "2025-06-10T14:00:00+00:00",
|
|
"required_action": "Apply update, if available.\r\nSee official guidance.",
|
|
}
|
|
assert http.calls[-1][1] == {"If-Modified-Since": "Tue, 10 Jun 2025 14:00:00 GMT"}
|
|
assert await store.by_id(OTHER) == []
|
|
|
|
|
|
async def test_epss_missing_today_uses_previous_date_and_zero_is_an_observation(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(feeds_metrics, "datetime", FixedDate)
|
|
today, yesterday = "2025-06-11", "2025-06-10"
|
|
|
|
def url(date):
|
|
return f"{EPSS_ROOT}/2025/epss_scores-{date}.csv.gz"
|
|
|
|
def score(date, value):
|
|
return gzip.compress((f"#model_version:v3,score_date:{date}\n"
|
|
f"cve,epss,percentile\n{CVE},{value},0.005\n").encode())
|
|
|
|
http = FeedHttp()
|
|
http.put(url(today), Reply(code=404), Reply(score(today, "nan")),
|
|
Reply(score(f"{yesterday}T00:00:00+0000", "0.256")),
|
|
Reply(score(f"{today}T00:00:00+0000", "0.263")))
|
|
http.put(url(yesterday), Reply(score(yesterday, "0.0")))
|
|
async with Store(tmp_path) as store:
|
|
sync = Sync(store, http)
|
|
assert await sync.refresh_once("epss")
|
|
[doc] = await store.by_id(CVE)
|
|
assert doc.issues[0].facts["epss"] == {"epss": 0.0, "percentile": 0.005,
|
|
"date": yesterday, "model_version": "v3"}
|
|
assert await store.by_id(OTHER) == []
|
|
assert not await sync.refresh_once("epss")
|
|
assert (await store.state("epss"))["checkpoint"]["date"] == yesterday
|
|
assert not await sync.refresh_once("epss")
|
|
assert (await store.state("epss"))["checkpoint"]["date"] == yesterday
|
|
assert await sync.refresh_once("epss")
|
|
assert (await store.by_id(CVE))[0].issues[0].facts["epss"]["date"] == today
|
|
|
|
|
|
def advisory(id, publisher, cve_id=CVE, revision=BEFORE):
|
|
return encoded({"document": {"csaf_version": "2.0", "tracking": {"id": id, "current_release_date": revision},
|
|
"publisher": {"name": publisher}, "title": "Controller software update"},
|
|
"vulnerabilities": [{"cve": cve_id}]})
|
|
|
|
|
|
async def test_siemens_revision_and_publisher_hash(tmp_path):
|
|
feed = f"{SIEMENS}ssa-feed-tlp-white.json"
|
|
url = f"{SIEMENS}ssa-563922.json"
|
|
hash_url = f"{url}.sha512"
|
|
old = advisory("SSA-563922", "Siemens ProductCERT")
|
|
new = advisory("SSA-563922", "Siemens ProductCERT", OTHER, AFTER)
|
|
|
|
def manifest(revision):
|
|
return encoded({"feed": {"entry": [{"id": "SSA-563922", "updated": revision,
|
|
"content": {"src": url}, "link": [{"rel": "hash", "href": hash_url}]}]}})
|
|
|
|
http = FeedHttp()
|
|
http.put(SIEMENS_METADATA, Reply({"metadata_version": "2.0", "distributions": [{"rolie": {
|
|
"feeds": [{"tlp_label": "WHITE", "url": feed}]}}]}, {"etag": '"provider"'}), Reply(code=304), Reply(code=304))
|
|
http.put(feed, Reply(manifest(BEFORE), {"etag": '"old"'}), Reply(manifest(AFTER)), Reply(manifest(AFTER)))
|
|
http.put(url, Reply(old), Reply(new), Reply(new))
|
|
http.put(hash_url, Reply(hashlib.sha512(old).hexdigest().encode()), Reply(b"0" * 128),
|
|
Reply(hashlib.sha512(new).hexdigest().encode()))
|
|
async with Store(tmp_path) as store:
|
|
sync = Sync(store, http)
|
|
assert await sync.refresh_once("siemens")
|
|
assert not await sync.refresh_once("siemens")
|
|
assert (await store.by_id(CVE))[0].native_id == "SSA-563922"
|
|
assert await store.by_id(OTHER) == []
|
|
assert await sync.refresh_once("siemens")
|
|
assert await store.by_id(CVE) == []
|
|
assert (await store.by_id(OTHER))[0].url == url
|
|
|
|
|
|
async def test_msrc_mirror_false_allows_private_cache_and_unchanged_docs_are_not_downloaded(tmp_path):
|
|
name = "2025/msrc_cve-2025-1234.json"
|
|
url = f"{MSRC_DIRECTORY}{name}"
|
|
payload = advisory("msrc_CVE-2025-1234", "Microsoft Security Response Center")
|
|
manifest = f'"{name}","{BEFORE}"\n'.encode()
|
|
http = FeedHttp()
|
|
http.put(MSRC_METADATA, Reply({"metadata_version": "2.0", "list_on_CSAF_aggregators": True,
|
|
"mirror_on_CSAF_aggregators": False, "distributions": [{"directory_url": MSRC_DIRECTORY.rstrip("/") }]}))
|
|
http.put(MSRC_MANIFEST, Reply(manifest, {"etag": '"first"'}), Reply(manifest, {"etag": '"second"'}), Reply(code=304))
|
|
http.put(url, Reply(payload))
|
|
async with Store(tmp_path) as store:
|
|
sync = Sync(store, http)
|
|
assert await sync.refresh_once("msrc")
|
|
assert await sync.refresh_once("msrc")
|
|
assert await sync.refresh_once("msrc")
|
|
[doc] = await store.by_id(CVE)
|
|
assert doc.url == url
|
|
assert store.artifact_path(doc.artifact).read_bytes() == payload
|
|
assert sum(call[0] == url for call in http.calls) == 1
|
|
async with Store(tmp_path) as reopened:
|
|
assert (await reopened.by_id(CVE))[0].url == url
|
|
|
|
|
|
async def test_cancelling_staged_feed_leaves_previous_generation(tmp_path):
|
|
first = zipped([("cves.zip", zipped([(f"{CVE}.json", cve())]))])
|
|
second = zipped([("cves.zip", zipped([(f"{OTHER}.json", cve(OTHER))]))])
|
|
http = FeedHttp()
|
|
cve_release(http, "2025-06-10", "01", first, zipped([]), send_base=True)
|
|
# Pause on the delta after the next baseline has already been staged.
|
|
http.pause_at = cve_release(http, "2025-06-11", "01", second, zipped([]), send_base=True)
|
|
async with Store(tmp_path) as store:
|
|
sync = Sync(store, http)
|
|
assert await sync.refresh_once("cvelist")
|
|
generation = await store.generation()
|
|
refresh = asyncio.create_task(sync.refresh_once("cvelist"))
|
|
try:
|
|
await asyncio.wait_for(http.paused.wait(), 5)
|
|
finally:
|
|
refresh.cancel()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await refresh
|
|
assert await store.generation() == generation
|
|
assert await store.by_id(CVE)
|
|
assert not await store.by_id(OTHER)
|