Files
vuln-mcp/tests/test_certcc.py
T
omar 41d6bb4163
CI / Python 3.13 (push) Successful in 27s
CI / Python 3.12 (push) Successful in 33s
CI / Build and smoke-test image (push) Successful in 10s
Index publisher advisory catalogues and distinguish public PoCs from observed exploitation
2026-11-28 15:14:06 +03:00

261 lines
13 KiB
Python

"""CERT/CC archive and public API contracts, using reduced publisher-shaped records."""
from __future__ import annotations
import json
from collections.abc import Mapping
from io import BytesIO
from pathlib import Path
from zipfile import ZipFile
import pytest
from vuln_mcp.sources import feed_certcc, feeds_common
from vuln_mcp.sources.feed_certcc import allowed, allowed_live, lookup_certcc
from vuln_mcp.store import Store
from vuln_mcp.sync import Sync
from vuln_mcp.transport import HttpError
pytestmark = pytest.mark.anyio
ARCHIVE_URL = "https://codeload.github.com/CERTCC/Vulnerability-Data-Archive/zip/refs/heads/main"
API = "https://kb.cert.org/vuls/api/"
ROOT = "Vulnerability-Data-Archive-main"
IGNORED = "fixture text outside the allowed CERT/CC metadata fields"
# Reduced vuls/api/495801/ and vuls/api/495801/vendors/vuls/ responses.
NOTE = {
"vuid": "VU#495801", "idnumber": "495801", "name": "muhttpd security advisory",
"cveids": ["CVE-2022-31793"], "datefirstpublished": "2022-08-04T18:22:26.080953Z",
"dateupdated": "2022-08-05T20:02:52.605648Z", "overview": IGNORED,
}
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
def archived_report(number: str, title: str, cves: str | list[str], **fields: str) -> dict:
return {"ID": f"VU#{number}", "IDNumber": number, "Title": title, "CVEIDs": cves,
"DateCreated": "2015-03-02T12:18:48-05:00", "Description": IGNORED, **fields}
def archived_vendor(number: str, record_id: str, name: str, status: str) -> dict:
return {"ID": f"VU#{number}", "VendorRecordID": record_id, "Vendor": name, "Status": status,
"DateLastUpdated": "2015-06-15T17:07:00-04:00", "VendorInformation": IGNORED,
"VendorStatement": IGNORED, "VendorReferences": ["https://example.invalid/untrusted"]}
def entry(number: str, leaf: str) -> str:
return f"{ROOT}/data/{int(number) % 100}/vu_{number}/{leaf}"
def archive(*members: tuple[str, object]) -> bytes:
data = BytesIO()
with ZipFile(data, "w") as out:
for path, body in members:
out.writestr(path, body if isinstance(body, bytes) else json.dumps(body).encode())
return data.getvalue()
def historical_members() -> list[tuple[str, object]]:
# Reduced fields from CERTCC/Vulnerability-Data-Archive's vu_101500 group.
single = "101500"
multi = "176200"
old = "1001201"
return [
(entry(single, "vendor_gwan-9xds5m.json"), archived_vendor(single, "GWAN-9XDS5M", "Retrospect, Inc.", "Affected")),
(entry(multi, f"vu_{multi}.json"), archived_report(multi, "Security advisory for multiple issues",
["CVE-2004-1382", "CVE-2004-0967", "CVE-2004-1382"])),
(entry(single, f"vu_{single}.json"), archived_report(single, "Retrospect Backup Client security advisory",
"CVE-2015-2864", DateFirstPublished="2015-06-15T17:08:35-04:00")),
(entry(multi, "vendor_jmpl-3wel46.json"), archived_vendor(multi, "JMPL-3WEL46", "Example Vendor", "Not Vulnerable")),
(entry(multi, "attachments.txt"), IGNORED.encode()),
(entry(old, f"vu_{old}.json"), archived_report(old, "Archive record without CVE", "")),
(entry("986240", "vendor_jmpl-3wel46.json"), archived_vendor("986240", "JMPL-3WEL46", "Orphan vendor", "Unknown")),
]
class IndexWire:
def __init__(self, body: bytes) -> None:
self.body = body
self.status = 200
self.etag = '"first"'
self.requests: list[tuple[str, dict[str, str]]] = []
async def download(
self, source: str, url: str, path: Path, *, headers: Mapping[str, str] | None = None, limit: int,
) -> tuple[int, Mapping[str, str]]:
assert source == "certcc" and url == ARCHIVE_URL and len(self.body) <= limit
self.requests.append((url, dict(headers or {})))
if self.status == 200:
path.write_bytes(self.body)
return self.status, {"ETag": self.etag}
async def json(
self, source: str, url: str, *, params: dict[str, str] | None = None,
headers: Mapping[str, str] | None = None,
) -> tuple[object, Mapping[str, str]]:
raise AssertionError("the offline importer may only fetch the archive")
async def test_official_archive_keeps_native_ids_and_vendor_scopes(tmp_path: Path) -> None:
wire = IndexWire(archive(*historical_members()))
async with Store(tmp_path) as store:
sync = Sync(store, wire)
assert await sync.refresh_once("certcc")
[single] = await store.by_id("CVE-2015-2864")
assert single.native_id == "VU#101500"
assert single.url == "https://kb.cert.org/vuls/id/101500"
assert single.issues[0].facts["vendor_status"] == [{
"vendor": "Retrospect, Inc.", "status": "affected", "scope": "advisory",
"date": "2015-06-15T21:07:00+00:00",
}]
assert single.issues[0].facts["dates"]["published"] == "2015-06-15T21:08:35+00:00"
[multi] = await store.by_id("VU#176200")
assert {issue.id for issue in multi.issues} == {"CVE-2004-1382", "CVE-2004-0967"}
assert multi.url == "https://github.com/CERTCC/Vulnerability-Data-Archive"
for issue in multi.issues:
assert issue.aliases == [] and issue.products == []
assert issue.facts["vendor_status"] == [{
"vendor": "Example Vendor", "status": "not_affected", "scope": "advisory",
"date": "2015-06-15T21:07:00+00:00",
}]
[old] = await store.by_id("VU#1001201")
assert [issue.id for issue in old.issues] == ["VU#1001201"]
assert not await store.by_id("VU#986240")
for doc in (single, multi, old):
assert doc.artifact is None
assert IGNORED not in doc.model_dump_json()
assert all(not issue.refs and not issue.fixes and not issue.summary for issue in doc.issues)
assert not list((tmp_path / "staging").iterdir())
assert not list((tmp_path / "artifacts").rglob("*"))
generation = await store.generation()
wire.status = 304
assert await sync.refresh_once("certcc")
assert await store.generation() == generation
assert wire.requests == [(ARCHIVE_URL, {}), (ARCHIVE_URL, {"If-None-Match": '"first"'})]
@pytest.mark.parametrize("invalid", ["empty", "traversal", "large_member", "wrong_join"])
async def test_broken_archive_preserves_last_good_index_and_etag(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, invalid: str,
) -> None:
wire = IndexWire(archive(*historical_members()))
async with Store(tmp_path) as store:
sync = Sync(store, wire)
assert await sync.refresh_once("certcc")
before = await store.generation()
wire.etag = '"broken"'
monkeypatch.setattr(feeds_common, "BATCH_SIZE", 1)
valid = (entry("70010", "vu_70010.json"), archived_report("70010", "Replacement title", ""))
if invalid == "empty":
wire.body = archive((f"{ROOT}/README.md", b"README"))
elif invalid == "traversal":
wire.body = archive(valid, (f"{ROOT}/data/../notes.txt", b"unexpected"))
elif invalid == "large_member":
monkeypatch.setattr(feed_certcc, "JSON_LIMIT", 512)
wire.body = archive(valid, (entry("70011", "vu_70011.json"), b" " * 513))
else:
wire.body = archive(valid, (entry("70011", "vendor_abcd-123456.json"),
archived_vendor("70010", "ABCD-123456", "Wrong VU", "Unknown")))
assert not await sync.refresh_once("certcc")
assert await store.generation() == before
assert (await store.state("certcc"))["validators"] == {"archive": {"etag": '"first"'}}
assert not await store.by_id("VU#70010")
assert (await store.by_id("VU#101500"))[0].native_id == "VU#101500"
assert not list((tmp_path / "staging").iterdir())
class LiveWire:
def __init__(self, replies: dict[str, tuple[object, Mapping[str, str]] | HttpError]) -> None:
self.replies = replies
self.requests: list[tuple[str, float]] = []
async def json(self, source: str, url: str, *, deadline: float) -> tuple[object, Mapping[str, str]]:
assert source == "certcc"
self.requests.append((url, deadline))
reply = self.replies[url]
if isinstance(reply, HttpError):
raise reply
return reply
def live_vendor(cve: str | None, name: str, status: str) -> dict:
return {"vul": cve, "vendor": name, "status": status, "statement": IGNORED, "references": IGNORED}
async def test_public_native_lookup_keeps_per_cve_vendor_evidence_separate() -> None:
first = "CVE-2020-11907"
second = "CVE-2020-0594"
url = API + "257161/"
note = NOTE | {"vuid": "VU#257161", "idnumber": "257161", "cveids": [first, "CVE-2020\u20110594"]}
wire = LiveWire({url: (note, {}), url + "vendors/vuls/": ([
live_vendor(first, "QNAP", "Not Affected"), live_vendor("CVE- 2020-0594", "QNAP", "Affected"),
live_vendor(None, "Example Vendor", "Unknown"),
], {"Cache-Control": "max-age=0, no-store"})})
page = await lookup_certcc("vu#257161", http=wire, deadline=42)
assert page.status.status == "ok" and not page.cacheable
assert wire.requests == [(url, 42), (url + "vendors/vuls/", 42)]
[doc] = page.docs
assert doc.native_id == "VU#257161"
assert {issue.id: issue.facts["vendor_status"] for issue in doc.issues} == {
first: [{"vendor": "Example Vendor", "status": "unknown", "scope": "advisory"},
{"vendor": "QNAP", "status": "not_affected", "scope": "cve"}],
second: [{"vendor": "Example Vendor", "status": "unknown", "scope": "advisory"},
{"vendor": "QNAP", "status": "affected", "scope": "cve"}],
}
assert IGNORED not in doc.model_dump_json()
assert all(not issue.aliases and not issue.products for issue in doc.issues)
async def test_public_cve_lookup_validates_note_join_and_scopes_status() -> None:
cve = "CVE-2022-31793"
sibling = "CVE-2022-31794"
url = API + "vuls/cve/2022-31793/"
all_vendors = API + "495801/vendors/vuls/"
vulnerability = {"uid": cve, "cve": "2022-31793", "note": "495801", "description": IGNORED}
wrapped = {"vulnerability": vulnerability, "note": NOTE | {"cveids": [cve, sibling]},
"vendors": [live_vendor(cve, "AT&T", "Not Affected")]}
wire = LiveWire({url: (wrapped, {}), all_vendors: ([
live_vendor(cve, "AT&T", "Not Affected"), live_vendor(sibling, "AT&T", "Affected"),
], {})})
page = await lookup_certcc(cve, http=wire, deadline=42)
assert page.status.status == "ok" and wire.requests == [(url, 42), (all_vendors, 42)]
[doc] = page.docs
assert len(doc.issues) == 2
assert doc.issues[0].facts["vendor_status"] == [{"vendor": "AT&T", "status": "not_affected", "scope": "cve"}]
assert doc.issues[1].facts["vendor_status"] == [{"vendor": "AT&T", "status": "affected", "scope": "cve"}]
assert IGNORED not in doc.model_dump_json()
wire.replies[url] = (wrapped | {"vulnerability": vulnerability | {"note": "999999"}}, {})
mismatch = await lookup_certcc(cve, http=wire, deadline=42)
assert mismatch.docs == [] and mismatch.status.status == "invalid_data"
@pytest.mark.parametrize(("reply", "expected"), [
(HttpError("not_found"), "ok"),
(({"error": "Content requested either does not exist or you do not have permissions to view it!"}, {}), "ok"),
(HttpError("rate_limited", "2022-08-15T21:00:00+00:00"), "rate_limited"),
(({"error": "unexpected service response"}, {}), "invalid_data"),
])
async def test_public_lookup_distinguishes_missing_note_from_failure(reply, expected: str) -> None:
page = await lookup_certcc("VU#999999", http=LiveWire({API + "999999/": reply}), deadline=42)
assert page.docs == [] and page.status.status == expected
if expected == "rate_limited":
assert page.status.retry_at == "2022-08-15T21:00:00+00:00"
def test_endpoint_allowlists_do_not_admit_arbitrary_paths() -> None:
assert allowed("codeload.github.com", "/CERTCC/Vulnerability-Data-Archive/zip/refs/heads/main")
assert not allowed("kb.cert.org", "/vuls/api/2020/06/")
assert not allowed("kb.cert.org", "/vuls/api/2020/05/")
assert not allowed("kb.cert.org", "/vuls/api/2026/13/")
assert not allowed("kb.cert.org", "/vuls/api/257161/vendors/vuls/")
assert allowed_live("kb.cert.org", "/vuls/api/257161/vendors/vuls/")
assert allowed_live("kb.cert.org", "/vuls/api/1001201/")
assert allowed_live("kb.cert.org", "/vuls/api/vuls/cve/2022-31793/")
assert not allowed_live("kb.cert.org", "/vuls/api/495801/csaf/")
assert not allowed_live("kb.cert.org", "/vuls/api/2022/08/")
assert not allowed_live("kb.cert.org.example.invalid", "/vuls/api/495801/")