Files
vuln-mcp/tests/test_industrial.py
T
omar 710b2e068c
CI / Python 3.13 (push) Successful in 36s
CI / Python 3.12 (push) Successful in 45s
CI / Build and smoke-test image (push) Successful in 12s
Rotate the proxy on every route failure and make the live timeout configurable
2026-11-29 07:32:44 +03:00

229 lines
11 KiB
Python

"""Wire fixtures reduced from Schneider Electric CPCERT's public CSAF directory."""
from copy import deepcopy
from time import monotonic
from types import SimpleNamespace
import httpx
import pytest
from vuln_mcp.sources.feed_industrial import allowed, lookup_industrial
from vuln_mcp.sources.live import lookup
from vuln_mcp.store import Store
from vuln_mcp.sync import Sync
from vuln_mcp.transport import HttpClients
_ROOT = "https://www.se.com/.well-known/csaf/"
_METADATA = _ROOT + "provider-metadata.json"
_MANIFEST = _ROOT + "changes.csv"
_NATIVE = "SEVD-2025-252-01"
_BULLETIN = "SESB-2021-347-01"
_ADVISORY_URL = _ROOT + "2025/sevd-2025-252-01.json"
_BULLETIN_URL = _ROOT + "2021/sesb-2021-347-01.json"
_INITIAL = "2026-10-13T07:00:00Z"
_REVISED = "2026-11-14T07:00:00Z"
_BULLETIN_REVISION = "2025-11-20T05:00:00Z"
_CVE = "CVE-2025-7746"
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
def _metadata() -> dict:
return {
"metadata_version": "2.0",
"canonical_url": _METADATA,
"role": "csaf_trusted_provider",
"list_on_CSAF_aggregators": True,
"mirror_on_CSAF_aggregators": False,
"distributions": [{"directory_url": _ROOT}],
"publisher": {"category": "vendor", "name": "Schneider Electric CPCERT",
"namespace": "https://www.se.com/ww/en"},
}
def _advisory(native: str, revision: str, cve: str = _CVE, *, details: str = "Apply the mitigation.") -> dict:
return {
"document": {
"csaf_version": "2.0", "category": "csaf_security_advisory",
"title": "Altivar Process Communication Modules security notice",
"publisher": {
"category": "vendor", "name": "Schneider Electric CPCERT",
"namespace": "https://www.se.com/ww/en/work/support/cybersecurity/security-notifications.jsp",
},
"tracking": {"id": native, "current_release_date": revision.replace("Z", ".000Z")},
"distribution": {"tlp": {"label": "WHITE"}},
"references": [{"category": "external", "url": "https://public.example/attachment.pdf",
"summary": "Archive attachment"}],
},
"product_tree": {"branches": [{
"category": "vendor", "name": "Schneider Electric",
"branches": [{
"category": "product_name", "name": "Altivar Process Communication Modules",
"branches": [{
"category": "product_version_range", "name": "vers:all/*",
"product": {"product_id": "26", "name": "Altivar Process Communication Modules All Versions",
"product_identification_helper": {"model_numbers": ["VW3A3721"]}},
}],
}],
}]},
"vulnerabilities": [{
"cve": cve,
"notes": [{"category": "description", "text": "Vulnerability narrative omitted by this adapter."}],
"product_status": {"known_affected": ["26"]},
"remediations": [
{"category": "mitigation", "details": details, "product_ids": ["26"],
"url": "https://www.se.com/ww/en/download/document/PRODUCT_GUIDE/"},
{"category": "workaround", "details": "Follow the documented workaround.",
"product_ids": ["26"], "url": "https://www.se.com/public/attachment.pdf"},
{"category": "mitigation", "details": "Review the device configuration.",
"product_ids": ["26"], "url": "https://public.example/technical-report"},
],
}],
}
def _manifest(advisory_revision: str, *, include_bulletin: bool = True) -> bytes:
advisory = f'"2025/sevd-2025-252-01.json","{advisory_revision}"\r\n'
bulletin = f'"2021/sesb-2021-347-01.json","{_BULLETIN_REVISION}"\r\n'
return (advisory + (bulletin if include_bulletin else "")).encode()
@pytest.mark.anyio
async def test_schneider_catalog_refresh_and_live_revalidation(tmp_path, monkeypatch) -> None:
advisory = _advisory(_NATIVE, _INITIAL)
bulletin = _advisory(_BULLETIN, _BULLETIN_REVISION, "CVE-2021-9001")
manifest, etag = _manifest(_INITIAL), '"catalog-1"'
calls: list[tuple[str, str, str | None]] = []
original_client = httpx.AsyncClient
def make_client(*, proxy: str | None, trust_env: bool) -> httpx.AsyncClient:
assert not trust_env
route = "proxy" if proxy else "direct"
def respond(request: httpx.Request) -> httpx.Response:
url = str(request.url)
validator = request.headers.get("If-None-Match")
calls.append((route, url, validator))
if url == _MANIFEST:
if etag == validator:
return httpx.Response(304)
return httpx.Response(200, content=manifest, headers={"ETag": etag})
if url == _METADATA:
return httpx.Response(200, json=_metadata())
if url == _BULLETIN_URL:
return httpx.Response(200, json=bulletin)
assert url == _ADVISORY_URL
if route == "proxy":
if validator == '"advisory"':
return httpx.Response(304, headers={"ETag": '"advisory"'})
return httpx.Response(200, json=advisory, headers={"ETag": '"advisory"'})
return httpx.Response(200, json=advisory)
return original_client(transport=httpx.MockTransport(respond), trust_env=False)
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:
sync = Sync(store, clients.index)
assert await sync.refresh_once("industrial")
[doc] = await store.by_id(_CVE)
assert (doc.native_id, doc.publisher, doc.url) == (_NATIVE, "Schneider Electric CPCERT", _ADVISORY_URL)
[issue] = doc.issues
assert issue.summary == ""
assert issue.refs == [{"type": "vendor_advisory", "url": _ADVISORY_URL}]
[product] = issue.products
assert (product["model"], product["range"], product["status"]) == ("VW3A3721", "vers:all/*", "affected")
assert issue.fixes[0]["product_ids"] == ["26"]
assert issue.fixes[0]["url"] == "https://www.se.com/ww/en/download/document/PRODUCT_GUIDE/"
assert all("url" not in fix for fix in issue.fixes[1:])
assert await store.by_id(_BULLETIN)
cold = await lookup("industrial", "id", _NATIVE.lower(), http=clients.live, deadline=monotonic() + 5)
checked = await lookup("industrial", "url", (_NATIVE, _ADVISORY_URL),
http=clients.live, deadline=monotonic() + 5)
assert cold.status.status == checked.status.status == "ok"
assert cold.docs[0].issues == checked.docs[0].issues == doc.issues
assert await sync.refresh_once("industrial")
assert calls == [("direct", _METADATA, None), ("direct", _MANIFEST, None),
("direct", _ADVISORY_URL, None), ("direct", _BULLETIN_URL, None),
("proxy", _ADVISORY_URL, None), ("proxy", _ADVISORY_URL, '"advisory"'),
("direct", _MANIFEST, '"catalog-1"')]
state = await store.state("industrial")
manifest, etag = _manifest(_REVISED), '"catalog-2"'
assert not await sync.refresh_once("industrial") # The document still carries the preceding revision.
failed = await store.state("industrial")
assert failed["status"] == "invalid_data"
assert failed["checkpoint"] == state["checkpoint"] and failed["validators"] == state["validators"]
assert (await store.by_id(_CVE))[0].issues[0].fixes[0]["details"] == "Apply the mitigation."
advisory = _advisory(_NATIVE, _REVISED, details="Apply the revised mitigation.")
assert await sync.refresh_once("industrial")
assert calls[-2:] == [("direct", _MANIFEST, '"catalog-1"'), ("direct", _ADVISORY_URL, None)]
assert (await store.by_id(_CVE))[0].issues[0].fixes[0]["details"] == "Apply the revised mitigation."
assert await store.by_id(_BULLETIN)
manifest, etag = _manifest(_REVISED, include_bulletin=False), '"catalog-3"'
assert await sync.refresh_once("industrial")
assert not await store.by_id(_BULLETIN)
assert await store.by_id(_CVE)
@pytest.mark.parametrize(("host", "path", "index", "live"), [
("www.se.com", "/.well-known/csaf/provider-metadata.json", True, False),
("www.se.com", "/.well-known/csaf/changes.csv", True, False),
("www.se.com", "/.well-known/csaf/2025/sevd-2025-252-01.json", True, True),
("www.se.com", "/.well-known/csaf/2021/sesb-2021-347-01.json", True, True),
("www.se.com", "/.well-known/csaf/2024/sevd-2025-252-01.json", False, False),
("www.se.com", "/.well-known/csaf/2025/vde-2025-252.json", False, False),
("www.se.com", "/.well-known/csaf/2025/sevd-2025-252-01.json.zip", False, False),
("www.se.com", "/files/2025/sevd-2025-252-01.json", False, False),
("www.se.com.example", "/.well-known/csaf/2025/sevd-2025-252-01.json", False, False),
])
def test_schneider_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
@pytest.mark.anyio
@pytest.mark.parametrize(("kind", "value"), [
("id", "CVE-2025-7746"),
("id", "VDE-2025-123"),
("id", _ADVISORY_URL),
("url", (_BULLETIN, _ADVISORY_URL)),
("url", (_NATIVE, _ADVISORY_URL + "?download=true")),
("url", (_NATIVE, _ADVISORY_URL.replace("www.se.com", "subdomain.example"))),
])
async def test_schneider_rejects_unregistered_detail_targets(kind, value) -> None:
class Unreachable:
async def json(self, *args, **kwargs):
pytest.fail("invalid target must not make an HTTP request")
page = await lookup_industrial(kind, value, http=Unreachable(), deadline=monotonic() + 5)
assert page.status.status == "invalid_data" and not page.docs
@pytest.mark.anyio
@pytest.mark.parametrize("defect", ["publisher", "tracking_id", "distribution"])
async def test_schneider_rejects_misattributed_or_nonpublic_details(defect: str) -> None:
result = deepcopy(_advisory(_BULLETIN, _BULLETIN_REVISION))
document = result["document"]
if defect == "publisher":
document["publisher"]["namespace"] = "https://third-party.example"
elif defect == "tracking_id":
document["tracking"]["id"] = _NATIVE
else:
document["distribution"]["tlp"]["label"] = "AMBER"
class Publisher:
async def json(self, source: str, url: str, *, deadline: float):
assert source == "industrial"
assert url == _BULLETIN_URL
return result, {}
page = await lookup_industrial("id", _BULLETIN, http=Publisher(), deadline=monotonic() + 5)
assert page.status.status == "invalid_data" and not page.docs