Files
vuln-mcp/tests/test_web.py
T
omar aca8e5da1a
CI / Python 3.13 (push) Successful in 43s
CI / Python 3.12 (push) Successful in 46s
CI / Build and smoke-test image (push) Successful in 12s
Follow two upstream catalogue shifts: release rows and bare branch bounds
2026-11-29 08:39:57 +03:00

252 lines
12 KiB
Python

"""Reduced fixtures from the Apache HTTP Server project's CVE JSON files."""
from pathlib import Path
from time import monotonic
from types import SimpleNamespace
import httpx
import pytest
from vuln_mcp.matching import make_asset, product_match, product_status
from vuln_mcp.models import AssetFacts
from vuln_mcp.search import Search
from vuln_mcp.sources.feed_web import allowed, lookup_web
from vuln_mcp.store import Store
from vuln_mcp.sync import Sync
from vuln_mcp.transport import HttpClients
_BASE = "https://httpd.apache.org/security/"
_CATALOG = _BASE + "vulnerabilities-httpd.json"
_MODERN = "CVE-2024-38475"
_LEGACY = "CVE-2016-4975"
_MODERN_DETAIL = _BASE + "json/CVE-2024-38475.json"
_LEGACY_DETAIL = _BASE + "json/CVE-2016-4975.json"
_ORG = "f0158376-9dc2-43b6-827c-5f631a4d8d09"
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
def _modern() -> dict:
# https://httpd.apache.org/security/json/CVE-2024-38475.json
return {
"dataType": "CVE_RECORD",
"dataVersion": "5.0",
"cveMetadata": {"cveId": _MODERN, "state": "PUBLISHED", "assignerOrgId": _ORG, "serial": 1},
"containers": {"cna": {
"providerMetadata": {"orgId": _ORG},
"affected": [{"vendor": "Apache Software Foundation", "product": "Apache HTTP Server",
"defaultStatus": "unaffected", "versions": [
{"version": "2.4.0", "lessThanOrEqual": "2.4.59", "status": "affected", "versionType": "semver"},
]}],
"timeline": [{"lang": "eng", "time": "2024-07-01", "value": "2.4.60 released"}],
"descriptions": [{"lang": "en", "value": "Untrusted free text must not be exposed."}],
"references": [{"url": "https://untrusted.invalid/private", "tags": ["vendor-advisory"]}],
}},
}
def _legacy(state: str = "PUBLIC", *, published: str = "2018-08-14") -> dict:
# https://httpd.apache.org/security/json/CVE-2016-4975.json
return {
"data_format": "MITRE", "data_version": "4.0", "data_type": "CVE",
"CVE_data_meta": {"ID": _LEGACY, "ASSIGNER": "security@apache.org", "STATE": state,
"DATE_PUBLIC": published},
"affects": {"vendor": {"vendor_data": [{
"vendor_name": "Apache Software Foundation", "product": {"product_data": [{
"product_name": "Apache HTTP Server", "version": {"version_data": [
{"version_name": "2.2", "version_affected": "=", "version_value": "2.2.31"},
{"version_name": "2.4", "version_affected": "=", "version_value": "2.4.23"},
]},
}]},
}]}},
"timeline": [
{"lang": "eng", "time": "2016-12-20", "value": "2.4.25 released"},
{"lang": "eng", "time": "2017-01-13", "value": "2.2.32 released"},
],
}
@pytest.mark.anyio
async def test_apache_refresh_preserves_published_generation_on_bad_catalog(tmp_path: Path, monkeypatch) -> None:
etag, catalog = '"apache-1"', [_modern(), _legacy()]
requests = []
client = httpx.AsyncClient
def make_client(*, proxy: str | None, trust_env: bool) -> httpx.AsyncClient:
assert proxy is None and not trust_env
def respond(request: httpx.Request) -> httpx.Response:
assert request.method == "GET" and str(request.url) == _CATALOG
requests.append(request.headers.get("If-None-Match"))
if requests[-1] == etag:
return httpx.Response(304)
return httpx.Response(200, json=catalog, headers={"ETag": etag})
return client(transport=httpx.MockTransport(respond))
monkeypatch.setattr(httpx, "AsyncClient", make_client)
settings = SimpleNamespace(proxies=(), max_retries=0, live_route="proxy", live_timeout=9.5)
async with Store(tmp_path) as store, HttpClients(settings, store) as clients:
sync = Sync(store, clients.index)
assert await sync.refresh_once("web")
[doc] = await store.by_id(_MODERN)
assert (doc.source, doc.publisher, doc.url) == ("web", "Apache Software Foundation", _MODERN_DETAIL)
[issue] = doc.issues
assert issue.summary == ""
assert issue.refs == [{"type": "vendor_advisory", "url": _MODERN_DETAIL}]
assert "untrusted.invalid" not in doc.model_dump_json()
assert issue.fixes[0]["version"] == "2.4.60"
originals = await store.state("web")
assert doc.artifact == originals["checkpoint"]["catalog"]
assert await sync.refresh_once("web")
assert (await store.state("web"))["checkpoint"] == originals["checkpoint"]
etag = '"apache-2"'
conflicting = _modern()
conflicting["containers"]["cna"]["timeline"][0]["value"] = "2.4.61 released"
catalog = [_modern(), conflicting]
assert not await sync.refresh_once("web")
failed = await store.state("web")
assert failed["status"] == "invalid_data"
assert (failed["checkpoint"], failed["validators"]) == (originals["checkpoint"], originals["validators"])
assert (await store.by_id(_MODERN))[0].issues[0].fixes[0]["version"] == "2.4.60"
assert await store.by_id(_LEGACY)
catalog = [_modern(), _legacy("REVIEW")]
assert await sync.refresh_once("web")
assert not await store.by_id(_LEGACY)
assert requests == [None, '"apache-1"', '"apache-1"', '"apache-1"']
@pytest.mark.anyio
async def test_apache_detail_revalidates_through_proxy(tmp_path: Path, monkeypatch) -> None:
requests = []
client = httpx.AsyncClient
def make_client(*, proxy: str | None, trust_env: bool) -> httpx.AsyncClient:
def respond(request: httpx.Request) -> httpx.Response:
assert proxy == "http://proxy.test:8080" and not trust_env
assert request.method == "GET" and str(request.url) == _MODERN_DETAIL
requests.append(request.headers.get("If-None-Match"))
if requests[-1] == '"apache-detail"':
return httpx.Response(304)
return httpx.Response(200, json=_modern(), headers={"ETag": '"apache-detail"'})
return client(transport=httpx.MockTransport(respond))
monkeypatch.setattr(httpx, "AsyncClient", make_client)
settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy", live_timeout=9.5)
async with Store(tmp_path) as store, HttpClients(settings, store) as clients:
first = await lookup_web("id", "cve-2024-38475", http=clients.live, deadline=monotonic() + 5)
second = await lookup_web("id", _MODERN, http=clients.live, deadline=monotonic() + 5)
assert requests == [None, '"apache-detail"']
assert first.status.status == second.status.status == "ok"
assert first.docs[0].issues == second.docs[0].issues
@pytest.mark.anyio
async def test_apache_upstream_ranges_keep_their_inclusive_bound() -> None:
class Detail:
async def json(self, source: str, url: str, *, deadline: float) -> tuple[object, dict[str, str]]:
assert (source, url) == ("web", _MODERN_DETAIL)
return _modern(), {"Cache-Control": "private, no-store"}
page = await lookup_web("id", _MODERN, http=Detail(), deadline=monotonic() + 5)
assert not page.cacheable
products = page.docs[0].issues[0].products
for version, expected in (("2.4.9", {"affected"}), ("2.4.59", {"affected"}), ("2.4.60", {"fixed"}),
("2.4.61", set()), ("2.4.60-1ubuntu1", set()), ("2.2.34", set())):
target = make_asset("text", "Apache HTTP Server", AssetFacts(version=version))
assert {status for product in products if product_match(product, target)[0]
and (status := product_status(product, target)) != "unknown"} == expected
distribution = make_asset("text", "httpd", AssetFacts(version="2.4.59", ecosystem="rpm"))
assert not any(product_match(product, distribution)[0] for product in products)
@pytest.mark.anyio
async def test_apache_search_filters_fixes_to_legacy_branch(tmp_path: Path, monkeypatch) -> None:
client = httpx.AsyncClient
def make_client(*, proxy: str | None, trust_env: bool) -> httpx.AsyncClient:
assert proxy is None and not trust_env
def respond(request: httpx.Request) -> httpx.Response:
assert str(request.url) == _CATALOG
return httpx.Response(200, json=[_legacy(published="")])
return client(transport=httpx.MockTransport(respond))
monkeypatch.setattr(httpx, "AsyncClient", make_client)
settings = SimpleNamespace(proxies=(), max_retries=0, live_route="proxy", live_timeout=9.5)
async with Store(tmp_path) as store, HttpClients(settings, store) as clients:
assert await Sync(store, clients.index).refresh_once("web")
search = Search(store, clients.live)
page = await search.search("httpd", AssetFacts(version="2.2.31"))
[hit] = page.hits
assert (hit.id, hit.applicability, hit.fixed_versions) == (_LEGACY, "affected", ["2.2.32"])
assert [fix["url"] for fix in hit.remediations] == [_LEGACY_DETAIL]
advisory = await search.get_advisory(_LEGACY)
assert advisory.issues[0].fixed_versions == ["2.2.32", "2.4.25"]
assert any(status.source == "web" and status.status == "proxy_unavailable" for status in advisory.sources)
@pytest.mark.anyio
@pytest.mark.parametrize(("kind", "value", "continuation"), [
("url", _MODERN_DETAIL, None), ("text", "httpd", None), ("id", "CVE-2024-38475/", None),
("id", _MODERN, "next"),
])
async def test_apache_rejects_non_detail_inputs(kind: str, value: str, continuation: str | None) -> None:
class Unreachable:
async def json(self, *args: object, **kwargs: object) -> tuple[object, dict[str, str]]:
pytest.fail("unexpected outbound request")
page = await lookup_web(kind, value, http=Unreachable(), deadline=monotonic() + 5, continuation=continuation)
assert page.status.status == "invalid_data" and not page.docs
@pytest.mark.anyio
@pytest.mark.parametrize("defect", ["foreign_id", "foreign_publisher", "foreign_product"])
async def test_apache_rejects_wrong_detail_identity(defect: str) -> None:
result = _modern()
if defect == "foreign_id":
result["cveMetadata"]["cveId"] = _LEGACY
elif defect == "foreign_publisher":
result["containers"]["cna"]["providerMetadata"]["orgId"] = "other"
else:
result["containers"]["cna"]["affected"][0]["product"] = "Tomcat"
class Detail:
async def json(self, source: str, url: str, *, deadline: float) -> tuple[object, dict[str, str]]:
return result, {}
page = await lookup_web("id", _MODERN, http=Detail(), deadline=monotonic() + 5)
assert page.status.status == "invalid_data" and not page.docs
@pytest.mark.parametrize(("host", "path", "index", "live"), [
("httpd.apache.org", "/security/vulnerabilities-httpd.json", True, False),
("httpd.apache.org", "/security/json/CVE-2024-38475.json", False, True),
("httpd.apache.org", "/security/json/CVE-2024-38475.json/extra", False, False),
("httpd.apache.org", "/security/json/../vulnerabilities-httpd.json", False, False),
("other.apache.org", "/security/json/CVE-2024-38475.json", False, False),
])
def test_apache_allowlist(host: str, path: str, index: bool, live: bool) -> None:
assert allowed(host, path, live=False) is index
assert allowed(host, path, live=True) is live
def test_modern_record_may_bound_a_whole_branch_from_its_start():
from vuln_mcp.sources.feed_web import _advisory
raw = _modern()
versions = raw["containers"]["cna"]["affected"][0]["versions"]
versions[:] = [{"version": "2.4", "lessThanOrEqual": "2.4.54", "status": "affected", "versionType": "semver"}]
doc = _advisory(raw)
issue, = doc.issues
ranged = [item for item in issue.products if item.get("range")]
assert [(item["version"], item["range"], item["status"]) for item in ranged] == [
("2.4.0", {"lessThanOrEqual": "2.4.54"}, "affected")]