Files
vuln-mcp/tests/test_sources.py
T
omar 25e90432d1
CI / Python 3.12 (push) Failing after 1m54s
CI / Python 3.13 (push) Failing after 2m1s
CI / Build and smoke-test image (push) Skipped
Ship advisory search MCP with direct and proxied networking, Docker and Gitea CI
- 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.
2026-11-28 10:06:59 +03:00

375 lines
19 KiB
Python

"""Wire-contract and normalization tests using safe subsets of advisory formats."""
from collections.abc import Mapping
from typing import Any
from urllib.parse import parse_qs, urlsplit
import pytest
from vuln_mcp.sources.live import lookup
from vuln_mcp.sources.parsers import InvalidData, parse
from vuln_mcp.transport import HttpError
_CVE = "CVE-2025-43715"
_OTHER = "CVE-2025-1234"
_SIEMENS_URL = "https://cert-portal.siemens.com/productcert/csaf/ssa-563922.json"
_MSRC_URL = "https://msrc.microsoft.com/csaf/advisories/2025/msrc_cve-2025-1234.json"
_SHA = "1" * 40
_FIX_SHA = "2" * 40
_REPO = "https://github.com/example/defensive-test"
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
class _Http:
def __init__(self, *responses: object):
self.responses = iter(responses)
self.calls: list[tuple[str, str, Mapping[str, str | int] | None, dict[str, Any] | None, float | None]] = []
async def json(
self, source: str, url: str, *, params: Mapping[str, str | int] | None = None,
body: dict[str, Any] | None = None, deadline: float | None = None,
) -> tuple[object, Mapping[str, str]]:
self.calls.append((source, url, params, body, deadline))
result = next(self.responses)
if isinstance(result, Exception):
raise result
if isinstance(result, tuple):
return result
return result, {}
def _product(product_id: str, name: str, model: str, branch: str, value: str) -> dict[str, Any]:
return {
"category": "product_name", "name": name, "branches": [{
"category": branch, "name": value,
"product": {"product_id": product_id, "name": name,
"product_identification_helper": {"model_numbers": [model]}},
}],
}
@pytest.fixture
def siemens() -> dict[str, Any]:
# Safe subset of SSA-563922's product and remediation information, with a second
# synthetic issue added to exercise explicit groups and issue-level isolation.
return {
"document": {
"csaf_version": "2.0", "title": "Siemens product advisory", "publisher": {"name": "Siemens ProductCERT"},
"tracking": {"id": "SSA-563922", "current_release_date": "2026-10-13T00:00:00Z"},
},
"product_tree": {
"branches": [{"category": "vendor", "name": "Siemens", "branches": [
_product("1", "SIMATIC TPCamGen", "6ES7823-0FE30-1AA0", "product_version_range", "vers:intdot/<1.3.1"),
_product("2", "SIMOTION OA MIIF", "6AU1820-3DA20-0AB0", "product_version_range", "vers:all/*"),
_product("3", "SIMOTION OA MIIF", "6AU1820-3DA20-0AB0", "product_version", "2.0.1"),
]}],
"product_groups": [{"group_id": "MIIF", "product_ids": ["3"]}],
},
"vulnerabilities": [
{"cve": _CVE, "product_status": {"known_affected": ["1", "2"]}, "remediations": [
{"category": "vendor_fix", "product_ids": ["1"], "details": "Update to V1.3.1 or later version"},
{"category": "no_fix_planned", "product_ids": ["2"], "details": "No fix planned"},
]},
{"cve": _OTHER, "product_status": {"fixed": ["3"]}, "remediations": [
{"category": "vendor_fix", "group_ids": ["MIIF"], "details": "Upgrade to 2.0.1"},
]},
],
}
def test_csaf_versions_and_remediations_stay_with_issue_and_model(siemens: dict[str, Any]) -> None:
doc = parse("siemens", siemens, _SIEMENS_URL)
assert doc.native_id == "SSA-563922"
assert doc.publisher == "Siemens ProductCERT"
assert doc.updated == "2026-10-13T00:00:00Z"
first, second = doc.issues
assert (first.id, second.id) == (_CVE, _OTHER)
assert first.aliases == second.aliases == []
assert [(p["model"], p["range"], p["scheme"], p["status"]) for p in first.products] == [
("6ES7823-0FE30-1AA0", "vers:intdot/<1.3.1", "INTDOT", "affected"),
("6AU1820-3DA20-0AB0", "vers:all/*", "UNKNOWN", "affected"),
]
assert first.fixes[0] == {
"category": "vendor_fix", "details": "Update to V1.3.1 or later version", "version": "1.3.1", "product_ids": ["1"],
}
assert first.fixes[1]["product_ids"] == ["2"]
assert "version" not in first.fixes[1]
assert [(p["version"], p["status"]) for p in second.products] == [("2.0.1", "fixed")]
assert [f["product_ids"] for f in second.fixes] == [["3"]]
assert second.refs == [{"type": "vendor_advisory", "url": _SIEMENS_URL}]
def test_csaf_relationship_and_unresolved_product(siemens: dict[str, Any]) -> None:
siemens["product_tree"]["relationships"] = [{
"category": "installed_on", "product_reference": "1", "relates_to_product_reference": "2",
"full_product_name": {"name": "TPCamGen on MIIF", "product_id": "relationship"},
}]
statuses = siemens["vulnerabilities"][0]["product_status"]
statuses["known_affected"].append("relationship")
statuses["under_investigation"] = ["3"]
doc = parse("siemens", siemens, _SIEMENS_URL)
assert [(p["product_id"], p["status"]) for p in doc.issues[0].products] == [
("1", "affected"), ("2", "affected"), ("relationship", "unknown"), ("3", "unknown"),
]
statuses["known_affected"].append("not-in-product-tree")
with pytest.raises(InvalidData, match="unresolved CSAF status product"):
parse("siemens", siemens, _SIEMENS_URL)
def _cve_record(cve: str = _CVE) -> dict[str, Any]:
return {
"dataType": "CVE_RECORD", "dataVersion": "5.2", "cveMetadata": {"cveId": cve, "state": "PUBLISHED"},
"containers": {"cna": {
"providerMetadata": {"shortName": "Vendor"}, "title": "A public advisory",
"descriptions": [{"lang": "en", "value": "Upgrade the affected package. <pre>UNSAFE_PAYLOAD_MARKER</pre>"}],
"affected": [{"vendor": "Vendor", "product": "Package", "versions": [{
"status": "affected", "version": "1.0.0", "lessThan": "1.1.0", "versionType": "semver",
}]}],
"references": [
{"url": _REPO + "/commit/" + _FIX_SHA + "?token=SECRET", "tags": ["patch"]},
{"url": "https://username:password@github.com/example/private", "tags": ["source"]},
{"url": "https://127.0.0.1/repo", "tags": ["source"]},
{"url": "https://github.com/example/exploits", "tags": ["exploit", "source"]},
{"url": "https://github.com/example/archive.zip", "tags": ["technical-description"]},
],
}, "adp": [{
"providerMetadata": {"shortName": "ADP"},
"metrics": [{"cvssV3_1": {"version": "3.1", "vectorString": "CVSS:3.1/AV:N", "baseScore": 4.1}}],
}]},
}
def test_cve_attribution_and_reference_privacy() -> None:
raw = _cve_record()
doc = parse("cvelist", raw, "https://cveawg.mitre.org/api/cve/" + _CVE)
issue = doc.issues[0]
assert issue.summary == "Upgrade the affected package."
assert issue.products[0]["range"] == {"lessThan": "1.1.0"}
assert issue.products[0]["publisher"] == doc.publisher == "Vendor"
assert issue.facts["cvss"] == [{"vector": "CVSS:3.1/AV:N", "version": "3.1", "score": 4.1, "publisher": "ADP"}]
assert issue.refs == [{"type": "fix_commit", "url": _REPO + "/commit/" + _FIX_SHA,
"commit": _FIX_SHA, "publisher": "Vendor"}]
mirror = parse("circl", raw, "https://vulnerability.circl.lu/api/vulnerability/" + _CVE)
assert mirror.publisher == doc.publisher
assert mirror.issues == doc.issues
def test_rejected_cve_has_no_active_assertions() -> None:
raw = _cve_record()
raw["cveMetadata"]["state"] = "REJECTED"
raw["containers"]["cna"]["rejectedReasons"] = [{"lang": "en", "value": "Duplicate identifier"}]
doc = parse("cvelist", raw, "https://cveawg.mitre.org/api/cve/" + _CVE)
assert doc.state == "rejected"
assert doc.issues[0].summary == "Duplicate identifier"
assert doc.issues[0].products == doc.issues[0].refs == []
def _osv_record() -> dict[str, Any]:
return {
"id": "GHSA-2345-2345-2345", "modified": "2025-09-10T00:00:00Z", "summary": "Update a test package",
"aliases": [_CVE], "related": [_OTHER], "affected": [{
"package": {"ecosystem": "PyPI", "name": "example", "purl": "pkg:pypi/example"}, "versions": ["1.2.dev0"],
"ranges": [{"type": "GIT", "repo": _REPO, "events": [{"introduced": "0"}, {"fixed": _FIX_SHA}]}],
}],
}
def test_osv_does_not_treat_withdrawn_entry_as_current() -> None:
doc = parse("osv", _osv_record() | {"withdrawn": "2025-10-02T00:00:00Z"},
"https://api.osv.dev/v1/vulns/GHSA-2345-2345-2345")
assert doc.state == "withdrawn"
assert doc.issues[0].products == doc.issues[0].refs == []
def test_osv_empty_ecosystem_export_record_is_not_withdrawn() -> None:
raw = _osv_record() | {"summary": "[EMPTY]", "details": ""}
raw["affected"][0]["package"].pop("ecosystem")
doc = parse("osv", raw, "https://api.osv.dev/v1/vulns/GHSA-2345-2345-2345")
assert doc.state == "published" and doc.issues[0].summary == ""
assert doc.issues[0].products[0]["name"] == "example" and "ecosystem" not in doc.issues[0].products[0]
@pytest.mark.anyio
async def test_osv_queries_purl_once_and_advances_empty_page() -> None:
http = _Http({"next_page_token": "opaque-next"}, {"vulns": [_osv_record()]})
purl = "pkg:pypi/example@1.2.dev0"
page = await lookup("osv", "purl", purl, http=http, deadline=10)
assert page.docs == [] and page.status.status == "ok" and page.continuation == "opaque-next"
second = await lookup("osv", "purl", purl, http=http, deadline=10, continuation=page.continuation)
assert second.continuation is None and second.docs[0].issues[0].aliases == [_CVE]
assert second.docs[0].issues[0].facts["related"] == [_OTHER]
assert http.calls == [
("osv", "https://api.osv.dev/v1/query", None, {"package": {"purl": purl}}, 10),
("osv", "https://api.osv.dev/v1/query", None, {"package": {"purl": purl}, "page_token": "opaque-next"}, 10),
]
@pytest.mark.anyio
@pytest.mark.parametrize(("kind", "value", "body"), [
("commit", _SHA, {"commit": _SHA}),
("repo", {"repo": _REPO, "version": "v1.0"}, {"package": {"name": _REPO, "ecosystem": "GIT"}, "version": "v1.0"}),
("package", {"name": "example", "ecosystem": "PyPI", "version": "1.2.dev0"},
{"package": {"name": "example", "ecosystem": "PyPI"}, "version": "1.2.dev0"}),
])
async def test_osv_official_query_shapes_and_git_fix_pair(kind: str, value: Any, body: dict[str, Any]) -> None:
http = _Http({"vulns": [_osv_record()]})
page = await lookup("osv", kind, value, http=http, deadline=10)
assert http.calls[0][3] == body
issue = page.docs[0].issues[0]
assert {"type": "fix_commit", "url": _REPO, "commit": _FIX_SHA} in issue.refs
assert issue.facts.get("matched_commit") == (_SHA if kind == "commit" else None)
def _nvd_record() -> dict[str, Any]:
return {
"id": _CVE, "vulnStatus": "Analyzed", "descriptions": [{"lang": "en", "value": "Update the affected product."}],
"configurations": [{"operator": "AND", "negate": False, "nodes": [
{"operator": "OR", "negate": False, "cpeMatch": [{
"criteria": r"cpe:2.3:a:acme:control\:suite:*:*:*:*:*:*:*:*", "vulnerable": True,
"versionStartIncluding": "1.0", "versionEndExcluding": "2.0",
}]},
{"operator": "OR", "negate": True, "cpeMatch": [{
"criteria": "cpe:2.3:o:acme:platform:2.0:*:*:*:*:*:*:*", "vulnerable": False,
}]},
]}],
}
def test_nvd_configuration_keeps_logical_and_platform_conditions() -> None:
record = _nvd_record()
doc = parse("nvd", record, "https://nvd.nist.gov/vuln/detail/" + _CVE)
issue = doc.issues[0]
assert issue.facts["configurations"] == record["configurations"]
assert issue.facts["attribution"] == "This product uses data from the NVD API but is not endorsed or certified by the NVD."
assert issue.products[0]["name"] == "control:suite"
assert issue.products[0]["range"] == {"versionStartIncluding": "1.0", "versionEndExcluding": "2.0"}
assert issue.products[1]["vulnerable"] is False
assert issue.products[1]["status"] == "unknown"
@pytest.mark.anyio
async def test_nvd_cpe_modes_offsets_and_id_batches() -> None:
record = _nvd_record()
http = _Http({"vulnerabilities": [{"cve": record}], "startIndex": 0, "resultsPerPage": 1, "totalResults": 2},
{"vulnerabilities": [], "startIndex": 1, "resultsPerPage": 0, "totalResults": 1},
{"vulnerabilities": [{"cve": record}], "startIndex": 0, "resultsPerPage": 1, "totalResults": 1})
full_cpe = "cpe:2.3:a:acme:control_suite:1.0:*:*:*:*:*:*:*"
virtual = "cpe:2.3:a:acme:control_suite:*:*:*:*:*:*:*:*"
page = await lookup("nvd", "cpe", full_cpe, http=http, deadline=10)
query = urlsplit(http.calls[0][1]).query
assert query.split("&")[-1] == "isVulnerable"
assert parse_qs(query)["cpeName"] == [full_cpe]
assert page.docs[0].native_id == _CVE and page.continuation == "1"
page = await lookup("nvd", "cpe", virtual, http=http, deadline=10, continuation="1")
assert http.calls[1][2] == {"startIndex": 1, "resultsPerPage": 20, "virtualMatchString": virtual}
assert page.status.status == "ok" and page.continuation is None
page = await lookup("nvd", "ids", [_CVE, _OTHER], http=http, deadline=10)
assert http.calls[2][2] == {"startIndex": 0, "resultsPerPage": 2, "cveIds": _CVE + "," + _OTHER}
assert page.docs[0].url == "https://nvd.nist.gov/vuln/detail/" + _CVE
@pytest.mark.anyio
async def test_circl_fulltext_searches_both_collections_and_advances() -> None:
variot = {
"id": "VAR-201605-0671", "affected_products": {"data": [
{"vendor": "Acme", "model": "Gateway", "version": "1.0", "scope": "firmware"},
]}, "title": {"data": "Gateway"},
}
http = _Http({"metadata": {"count": 3, "page": 1, "per_page": 2}, "data": [_cve_record(), variot]},
HttpError("unavailable"))
page = await lookup("circl", "text", "gateway", http=http, deadline=10)
assert http.calls[0][1] == "https://vulnerability.circl.lu/api/vulnerability/fulltext"
assert http.calls[0][2] == {"q": "gateway", "sources": "cvelistv5,variot", "page": 1, "per_page": 20}
assert page.continuation == "2"
assert [doc.native_id for doc in page.docs] == [_CVE, "VAR-201605-0671"]
assert page.docs[1].issues[0].products == [{"vendor": "Acme", "model": "Gateway", "version": "1.0",
"scope": "firmware", "status": "unknown", "scheme": "UNKNOWN"}]
page = await lookup("circl", "text", "gateway", http=http, deadline=10, continuation=page.continuation)
assert http.calls[1][2]["page"] == 2
assert page.status.status == "unavailable"
@pytest.mark.anyio
async def test_indexed_msrc_checks_official_url_identity_and_cache_directive(siemens: dict[str, Any]) -> None:
siemens["document"]["tracking"]["id"] = "msrc_" + _OTHER
siemens["document"]["publisher"]["name"] = "Microsoft Security Response Center"
branch = siemens["product_tree"]["branches"][0]
branch["name"] = "Microsoft"
branch["branches"][0]["branches"][0]["name"] = "<16.0.14334.21048"
http = _Http((siemens, {"Cache-Control": "private, NO-STORE"}), siemens)
page = await lookup("msrc", "url", ("msrc_" + _OTHER, _MSRC_URL), http=http, deadline=10)
assert len(http.calls) == 1 and http.calls[0][1] == _MSRC_URL
assert not page.cacheable and page.status.status == "ok"
assert page.docs[0].url == _MSRC_URL
assert page.docs[0].issues[0].products[0]["range"] == "<16.0.14334.21048"
assert page.docs[0].issues[0].products[0]["scheme"] == "INTDOT"
page = await lookup("msrc", "url", ("msrc_" + _CVE, _MSRC_URL), http=http, deadline=10)
assert page.status.status == "invalid_data" and not page.docs
@pytest.mark.anyio
@pytest.mark.parametrize("url", [
"https://private.example/2025/msrc_cve-2025-1234.json",
"https://msrc.microsoft.com/account/secrets.json",
"https://user:secret@msrc.microsoft.com/csaf/advisories/internal.json",
"https://msrc.microsoft.com/csaf/advisories/%2e%2e/internal.json",
])
async def test_indexed_msrc_does_not_request_unregistered_url(url: str) -> None:
http = _Http()
page = await lookup("msrc", "url", ("msrc_" + _OTHER, url), http=http, deadline=10)
assert page.status.status == "invalid_data" and not page.docs
assert http.calls == []
@pytest.mark.anyio
async def test_siemens_live_detail_uses_official_path_and_requires_tracking_id(siemens: dict[str, Any]) -> None:
http = _Http(siemens, siemens)
page = await lookup("siemens", "id", "ssa-563922", http=http, deadline=10)
assert page.docs[0].native_id == "SSA-563922" and http.calls[0][1] == _SIEMENS_URL
page = await lookup("siemens", "id", "SSA-444444", http=http, deadline=10)
assert page.status.status == "invalid_data" and not page.docs
@pytest.mark.anyio
@pytest.mark.parametrize(("source", "identifier", "url", "raw"), [
("cvelist", _CVE, "https://cveawg.mitre.org/api/cve/" + _CVE, _cve_record()),
("circl", _CVE, "https://vulnerability.circl.lu/api/vulnerability/" + _CVE, _cve_record()),
("osv", "GHSA-2345-2345-2345", "https://api.osv.dev/v1/vulns/GHSA-2345-2345-2345", _osv_record()),
])
async def test_detail_distinguishes_absence_error_and_valid_record(source: str, identifier: str, url: str, raw: object) -> None:
http = _Http(raw, HttpError("not_found"), HttpError("rate_limited", "2025-10-01T00:00:00Z"), {"unexpected": True})
found = await lookup(source, "id", identifier, http=http, deadline=10)
missing = await lookup(source, "id", identifier, http=http, deadline=10)
throttled = await lookup(source, "id", identifier, http=http, deadline=10)
invalid = await lookup(source, "id", identifier, http=http, deadline=10)
assert [call[1] for call in http.calls] == [url] * 4
assert found.status.status == "ok" and found.docs[0].native_id == identifier
assert missing.status.status == "ok" and not missing.docs
assert (throttled.status.status, throttled.status.retry_at) == ("rate_limited", "2025-10-01T00:00:00Z")
assert invalid.status.status == "invalid_data" and not invalid.docs
@pytest.mark.anyio
async def test_epss_batch_limit_keeps_explicit_zero_distinct_from_missing() -> None:
ids = [f"CVE-2025-{1000 + index}" for index in range(160)]
http = _Http({"status": "OK", "data": [{"cve": ids[0], "epss": "0", "percentile": "0.25", "date": "2025-10-02"}]},
{"status": "OK", "data": [{"cve": ids[-1], "epss": "0.7", "percentile": "0.88", "date": "2025-10-02"}]})
page = await lookup("epss", "ids", ids, http=http, deadline=10)
assert [doc.native_id for doc in page.docs] == [ids[0], ids[-1]]
assert page.docs[0].issues[0].facts["epss"] == {"epss": 0.0, "percentile": 0.25, "date": "2025-10-02"}
batch_values = [str(call[2]["cve"]) for call in http.calls]
assert len(batch_values) == 2 and all(len(value) <= 2000 for value in batch_values)
assert ",".join(batch_values).split(",") == ids
@pytest.mark.anyio
@pytest.mark.parametrize("invalid", ["NaN", "Infinity", "1.01", "-0.01", True])
async def test_epss_rejects_invalid_probabilities(invalid: str | bool) -> None:
http = _Http({"data": [{"cve": _CVE, "epss": invalid, "percentile": "0.1", "date": "2025-10-02"}]})
page = await lookup("epss", "id", _CVE, http=http, deadline=10)
assert page.status.status == "invalid_data" and not page.docs