Files
vuln-mcp/tests/test_paloalto.py
T
omar 04399c8d6c
CI / Python 3.13 (push) Successful in 33s
CI / Python 3.12 (push) Successful in 47s
CI / Build and smoke-test image (push) Successful in 14s
Index Palo Alto and Schneider advisories and report both CSV inventory statuses
2026-11-28 16:12:09 +03:00

275 lines
13 KiB
Python

"""Palo Alto JSON wire shapes, defensive scope, and atomic index publication."""
from __future__ import annotations
import json
from collections.abc import Mapping
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
import pytest
from vuln_mcp.matching import make_asset, product_match, product_status
from vuln_mcp.models import AssetFacts
from vuln_mcp.sources import feed_paloalto
from vuln_mcp.sources.feed_paloalto import allowed, lookup_paloalto, paloalto_fix_matches, paloalto_query
from vuln_mcp.store import Store
from vuln_mcp.sync import Sync
from vuln_mcp.transport import HttpError
ORIGIN = "https://security.paloaltonetworks.com"
HOST = "security.paloaltonetworks.com"
CATALOG = ORIGIN + "/json"
NATIVE = "PAN-SA-2024-0013"
CVE = "CVE-2024-2551"
DATE = "2024-11-20T08:00:00.000Z"
IGNORED = "fixture text outside the advisory metadata contract"
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
def listing(identifier: str, **fields: object) -> dict[str, object]:
return {"ID": identifier, "product": ["PAN-OS"], "date": DATE, "updated": DATE,
"problem": IGNORED, "solution": IGNORED, **fields}
def detail(identifier: str, **fields: object) -> dict[str, object]:
# PAN uses CVE_RECORD even when its native ID is a non-CVE advisory ID.
return {"dataType": "CVE_RECORD", "dataVersion": "5.0",
"cveMetadata": {"cveId": identifier, "state": "PUBLISHED"},
"containers": {"cna": {
"providerMetadata": {"dateUpdated": DATE}, "datePublic": DATE,
"affected": [], "descriptions": [{"lang": "en", "value": IGNORED}],
"solutions": [{"lang": "en", "value": IGNORED}], "exploits": [IGNORED],
"references": [{"url": "https://example.invalid/attachment", "tags": ["exploit"]}],
**fields,
}}}
class LiveWire:
def __init__(self, reply: object, headers: Mapping[str, str] | None = None) -> None:
self.reply = reply
self.headers = {} if headers is None else headers
self.requests: list[tuple[str, str, dict[str, str], float]] = []
async def json(self, source: str, url: str, *, params: dict[str, str] | None = None,
deadline: float) -> tuple[object, Mapping[str, str]]:
self.requests.append((source, url, params or {}, deadline))
if isinstance(self.reply, HttpError):
raise self.reply
return self.reply, self.headers
@pytest.mark.parametrize(("text", "asset", "expected"), [
("PANOS", None, ("PAN-OS", None)),
("Palo Alto Networks PAN-OS 11.2.4-h2", None, ("PAN-OS", "11.2.4-h2")),
("VPN", AssetFacts(product="GlobalProtect", version="6.2.4"), ("GlobalProtect App", "6.2.4")),
("PAN-OS", AssetFacts(vendor="Another Vendor"), None),
("PAN-OS 11.2.4", AssetFacts(product="PAN OS", version="11.2.5"), None),
("PAN-OS", AssetFacts(version="secret?branch=11"), None),
("unknown operating system", None, None),
])
def test_only_known_product_filters_and_release_syntax_are_forwarded(
text: str, asset: AssetFacts | None, expected: tuple[str, str | None] | None,
) -> None:
assert paloalto_query(text, asset) == expected
@pytest.mark.anyio
async def test_version_lookup_uses_vendor_product_qualified_version_and_continues() -> None:
rows = [listing(f"CVE-2024-{n:04}") for n in range(3000, 3022)]
wire = LiveWire(rows, {"Cache-Control": "public, no-store"})
query = ("PAN-OS", "11.2.4")
first = await lookup_paloalto("product", query, http=wire, deadline=42)
assert first.status.status == "ok" and first.continuation == "2" and not first.cacheable
assert [doc.native_id for doc in first.docs] == [f"CVE-2024-{n:04}" for n in range(3000, 3020)]
assert all(IGNORED not in doc.model_dump_json() for doc in first.docs)
second = await lookup_paloalto("product", query, http=wire, deadline=43, continuation=first.continuation)
assert [doc.native_id for doc in second.docs] == ["CVE-2024-3020", "CVE-2024-3021"]
assert second.continuation is None
assert wire.requests == [
("paloalto", CATALOG, {"product": "PAN-OS", "sort": "-updated", "version": "PAN-OS 11.2.4"}, deadline)
for deadline in (42, 43)
]
@pytest.mark.anyio
async def test_product_only_uses_vendor_pages() -> None:
wire = LiveWire([listing(f"CVE-2024-{n:04}") for n in range(3000, 3020)])
first = await lookup_paloalto("product", ("PAN-OS", None), http=wire, deadline=42)
assert len(first.docs) == 20 and first.continuation == "2"
wire.reply = [listing(NATIVE)]
second = await lookup_paloalto("product", ("PAN-OS", None), http=wire, deadline=42, continuation=first.continuation)
assert [doc.native_id for doc in second.docs] == [NATIVE] and second.continuation is None
assert [request[2] for request in wire.requests] == [
{"product": "PAN-OS", "sort": "-updated", "limit": "20", "page": page} for page in ("1", "2")
]
@pytest.mark.anyio
async def test_exact_publisher_advisory_uses_official_id_and_never_exports_raw_content() -> None:
wire = LiveWire(detail(NATIVE, affected=[{"vendor": "Palo Alto Networks", "product": "PAN-OS",
"versions": [{"version": "All", "status": "unaffected"}]}]))
result = await lookup_paloalto("id", NATIVE.lower(), http=wire, deadline=42)
assert result.status.status == "ok"
[doc] = result.docs
[issue] = doc.issues
assert (doc.native_id, doc.publisher, doc.url, doc.updated) == (
NATIVE, "Palo Alto Networks", ORIGIN + "/" + NATIVE, "2024-11-20T08:00:00+00:00",
)
assert issue.id == NATIVE and not issue.aliases and not issue.fixes
assert issue.refs == [{"type": "vendor_advisory", "url": doc.url}]
assert doc.artifact is None and IGNORED not in doc.model_dump_json()
assert "example.invalid" not in doc.model_dump_json()
assert wire.requests == [("paloalto", f"{CATALOG}/{NATIVE}", {}, 42)]
@pytest.mark.anyio
async def test_native_advisory_only_reports_official_cve_links_as_related() -> None:
wire = LiveWire(detail(NATIVE, references=[
{"url": f"{ORIGIN}/{CVE}", "tags": ["vendor-advisory"]},
{"url": "https://example.invalid/CVE-2024-9999", "tags": ["vendor-advisory"]},
{"url": f"{ORIGIN}/CVE-2024-8888/attachment", "tags": ["vendor-advisory"]},
]))
result = await lookup_paloalto("id", NATIVE, http=wire, deadline=42)
[doc] = result.docs
[issue] = doc.issues
assert issue.id == NATIVE and not issue.aliases
assert issue.facts["related"] == [CVE]
@pytest.mark.anyio
async def test_detail_does_not_apply_another_branch_fix_or_treat_later_builds_as_fixed() -> None:
wire = LiveWire(detail(CVE, affected=[
{"vendor": "Palo Alto Networks", "product": "PAN-OS", "versions": [
{"version": "11.0.0", "lessThan": "11.0.5", "status": "affected", "versionType": "custom",
"changes": [{"at": "11.0.5", "status": "unaffected"}]},
{"version": "10.2.0", "lessThan": "10.2.4-h6", "status": "affected", "versionType": "custom",
"changes": [{"at": "10.2.4-h6", "status": "unaffected"},
{"at": "10.2.5", "status": "unaffected"}]},
]},
{"vendor": "Palo Alto Networks", "product": "Cloud NGFW", "versions": [
{"version": "All", "status": "unaffected"},
]},
], configurations=[{"lang": "en", "value": "No special configuration is required to be affected by this issue."}],
x_affectedList=["PAN-OS 11.0.4", "PAN-OS 10.2.4-h5"]))
result = await lookup_paloalto("id", CVE, http=wire, deadline=42)
[doc] = result.docs
[issue] = doc.issues
assert doc.native_id == issue.id == CVE
assert [(fix["product_id"], fix["version"], fix["scope"]) for fix in issue.fixes] == [
("PAN-OS", "11.0.5", "11.0"), ("PAN-OS", "10.2.4-h6", "10.2.4"), ("PAN-OS", "10.2.5", "10.2"),
]
assert [fix["version"] for fix in issue.fixes if paloalto_fix_matches(fix, "11.0.4")] == ["11.0.5"]
assert [fix["version"] for fix in issue.fixes if paloalto_fix_matches(fix, "10.2.5")] == ["10.2.5"]
def verdicts(version: str) -> set[str]:
asset = make_asset("text", "PAN OS", AssetFacts(version=version))
return {product_status(row, asset) for row in issue.products if product_match(row, asset) == (True, set())} - {"unknown"}
assert verdicts("10.2.4-h5") == {"affected"}
assert verdicts("10.2.4-h6") == {"fixed"}
assert verdicts("11.0.4") == {"affected"}
assert verdicts("11.0.3") == {"affected"}
assert verdicts("11.0.5") == {"fixed"}
assert verdicts("11.0.6") == set()
assert verdicts("11.1.0") == set()
@pytest.mark.anyio
async def test_misaligned_vendor_table_does_not_attribute_other_branch_fixes() -> None:
wire = LiveWire([listing(CVE, version=["PAN-OS 11.0"], affected=["< 11.0.5"],
fixed=[">= 11.0.5", ">= 11.1.0"])])
result = await lookup_paloalto("product", ("PAN-OS", "11.0.4"), http=wire, deadline=42)
[doc] = result.docs
[issue] = doc.issues
assert not issue.fixes
assert {row["status"] for row in issue.products} == {"unknown"}
@pytest.mark.anyio
async def test_detail_does_not_assume_configuration_requirements() -> None:
wire = LiveWire(detail(CVE, affected=[{
"vendor": "Palo Alto Networks", "product": "PAN-OS",
"versions": [{"version": "11.0.0", "lessThan": "11.0.5", "status": "affected",
"changes": [{"at": "11.0.5", "status": "unaffected"}]}],
}], configurations=[{"lang": "en", "value": IGNORED}], x_affectedList=["PAN-OS 11.0.4"]))
result = await lookup_paloalto("id", CVE, http=wire, deadline=42)
[doc] = result.docs
[issue] = doc.issues
assert IGNORED not in doc.model_dump_json()
assert {row["status"] for row in issue.products} == {"unknown", "fixed"}
@pytest.mark.anyio
async def test_lookup_reports_missing_and_wrong_schema_differently() -> None:
missing = await lookup_paloalto("id", NATIVE, http=LiveWire(HttpError("not_found")), deadline=42)
wrong = await lookup_paloalto("id", NATIVE, http=LiveWire(detail(CVE)), deadline=42)
limited = await lookup_paloalto("id", NATIVE, http=LiveWire(HttpError("rate_limited", DATE)), deadline=42)
assert missing.status.status == "ok" and not missing.docs
assert wrong.status.status == "invalid_data" and not wrong.docs
assert limited.status.status == "rate_limited" and limited.status.retry_at == DATE
class IndexWire:
def __init__(self, pages: dict[int, tuple[int, object]]) -> None:
self.pages = pages
self.requests: list[tuple[int, 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]]:
parsed = urlsplit(url)
assert source == "paloalto" and parsed.scheme == "https" and parsed.netloc == HOST and parsed.path == "/json"
params = parse_qs(parsed.query)
assert params["sort"] == ["-updated"] and params["limit"] == ["2"]
page = int(params["page"][0])
self.requests.append((page, dict(headers or {})))
status, payload = self.pages[page]
if status == 200:
body = json.dumps(payload).encode("utf-8")
assert len(body) <= limit
path.write_bytes(body)
return status, {"ETag": f'"page-{page}"'}
async def json(self, *_args: object, **_kwargs: object) -> tuple[object, Mapping[str, str]]:
raise AssertionError("index refresh should stream only its fixed listing pages")
@pytest.mark.anyio
async def test_index_is_conditional_and_atomic_across_catalog_pages(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(feed_paloalto, "_INDEX_LIMIT", 2)
wire = IndexWire({1: (200, [listing(NATIVE), listing(CVE)]), 2: (200, [listing("CVE-2024-3033")])})
async with Store(tmp_path) as store:
sync = Sync(store, wire)
assert await sync.refresh_once("paloalto")
generation = await store.generation()
[doc] = await store.by_id(NATIVE)
assert doc.native_id == NATIVE and doc.artifact is None
assert await store.by_id("CVE-2024-3033")
wire.pages = {1: (304, None), 2: (304, None)}
assert await sync.refresh_once("paloalto")
assert await store.generation() == generation
assert wire.requests[-2:] == [(1, {"If-None-Match": '"page-1"'}), (2, {"If-None-Match": '"page-2"'})]
wire.pages = {1: (200, [listing(NATIVE), listing("CVE-2024-4044")]), 2: (200, [listing(NATIVE)])}
assert not await sync.refresh_once("paloalto")
assert await store.generation() == generation
assert not await store.by_id("CVE-2024-4044")
assert await store.by_id("CVE-2024-3033")
def test_allowlist_excludes_unapproved_origins_paths_and_document_routes() -> None:
for live in (True, False):
assert allowed(HOST, "/json", live=live)
assert not allowed(HOST + ".example.invalid", "/json", live=live)
assert not allowed(HOST, "/api", live=live)
assert not allowed(HOST, f"/{NATIVE}", live=live)
assert not allowed(HOST, f"/json/{NATIVE}/attachment", live=live)
assert not allowed(HOST, "/json/../private", live=live)
assert allowed(HOST, f"/json/{NATIVE}", live=True)
assert allowed(HOST, f"/json/{CVE}", live=True)