Files
vuln-mcp/tests/test_fortinet.py
T
omar 9c1638b5b8
CI / Python 3.13 (push) Successful in 40s
CI / Python 3.12 (push) Successful in 46s
CI / Build and smoke-test image (push) Successful in 13s
Resolve a Fortinet id through the feed instead of the blocked page
2026-11-29 15:11:12 +03:00

370 lines
18 KiB
Python

"""Fortinet PSIRT wire formats, scoped remediation, and rolling index preservation."""
from __future__ import annotations
import json
from time import monotonic
from collections.abc import Mapping
from pathlib import Path
from urllib.parse import urlsplit
import pytest
from vuln_mcp.matching import make_asset, product_match, product_status
from vuln_mcp.models import AssetFacts
from vuln_mcp.sources.feed_fortinet import _csaf, allowed, fortinet_fix_matches, lookup_fortinet
from vuln_mcp.store import Store
from vuln_mcp.sync import Sync
from vuln_mcp.transport import HttpError
RSS = "https://filestore.fortinet.com/fortiguard/rss/ir.xml"
FEED = RSS
HOST = "fortiguard.fortinet.com"
FILESTORE = "filestore.fortinet.com"
NATIVE = "FG-IR-26-141"
OTHER = "FG-IR-26-100"
CVE = "CVE-2026-25089"
SECOND_CVE = "CVE-2026-39808"
DATE = "2026-06-09T00:00:00"
IGNORED = "Untrusted paragraph must not be retained."
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
def advisory_url(native: str = NATIVE) -> str:
return f"https://{HOST}/psirt/{native}"
def artifact_url(native: str = NATIVE) -> str:
return f"https://{FILESTORE}/fortiguard/psirt/csaf_advisory-example_{native.lower()}.json"
def advisory(native: str = NATIVE) -> bytes:
return (f'<h1>{IGNORED}</h1><a href="/psirt/cvrf/{native}">CVRF</a>'
f'<a href="{artifact_url(native)}">CSAF</a>').encode()
def rss(*items: tuple[str, str]) -> bytes:
entries = "".join(
f"<item><title>{IGNORED}</title><description>{revision}</description>"
f"<link>https://www.fortiguard.com/psirt/{native}</link>"
"<pubDate>Tue, 09 Jun 2026 00:00:00 GMT</pubDate></item>"
for native, revision in items
)
return f'<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel>{entries}</channel></rss>'.encode()
def csaf(native: str = NATIVE, *, date: str = DATE, fixed: str = "5.0.6") -> bytes:
# Reduced Fortinet format, using FG-IR-26-141's on-premises CSAF product branches.
# The Cloud and second-CVE rows exercise independent scope without copying advisory prose.
affected_id = "FortiSandbox >=5.0.0|<=5.0.5"
old_id = "FortiSandbox/ 4.2 all versions"
newer_id = "FortiSandbox/ 5.2 all versions"
cloud_id = "FortiSandbox Cloud >=5.0.4|<=5.0.5"
body = {
"document": {"title": IGNORED, "csaf_version": "2.0", "publisher": {"name": "Fortinet PSIRT"},
"tracking": {"id": native, "status": "final", "version": "0", "current_release_date": date}},
"product_tree": {
"branches": [{"category": "vendor", "name": "Fortinet PSIRT", "branches": [
{"category": "product", "name": "FortiSandbox", "branches": [
{"category": "product_version_range", "name": "FortiSandbox/>=5.0.0|<=5.0.5",
"product": {"product_id": affected_id, "name": "FortiSandbox"}},
{"category": "product_version_range", "name": old_id,
"product": {"product_id": old_id, "name": "FortiSandbox"}},
{"category": "product_version_range", "name": newer_id,
"product": {"product_id": newer_id, "name": "FortiSandbox"}},
]},
{"category": "product_name", "name": "FortiSandbox Cloud", "branches": [
{"category": "product_version_range", "name": ">=5.0.4|<=5.0.5",
"product": {"product_id": cloud_id, "name": "FortiSandbox Cloud"}},
]},
]}],
"product_groups": [{"group_id": "On-premises 5.0", "product_ids": [affected_id]}],
},
"vulnerabilities": [
{"cve": CVE if native == NATIVE else SECOND_CVE,
"notes": [{"category": "description", "text": IGNORED}],
"references": [{"url": "https://example.invalid/attachment"}],
"product_status": {"known_affected": [affected_id, old_id], "known_not_affected": [newer_id]},
"remediations": [
{"category": "vendor_fix", "details": f"FortiSandbox 5.0: Upgrade to {fixed} or above.",
"group_ids": ["On-premises 5.0"], "product_ids": [old_id]},
{"category": "vendor_fix", "details": "FortiSandbox 4.2: Migrate to a fixed release.",
"product_ids": [old_id]},
{"category": "workaround", "details": IGNORED, "product_ids": [old_id]},
]},
],
}
if native == NATIVE:
body["vulnerabilities"].append({
"cve": SECOND_CVE, "product_status": {"under_investigation": [cloud_id]},
"remediations": [{"category": "vendor_fix", "details": "Upgrade to 5.0.9.",
"product_ids": [cloud_id, affected_id]}],
})
return json.dumps(body).encode()
class LiveWire:
def __init__(self, responses: dict[str, bytes | HttpError], *, no_store: bool = False) -> None:
self.responses = responses
self.no_store = no_store
self.requests: list[tuple[str, str, float]] = []
async def bytes(self, source: str, url: str, *, deadline: float, limit: int) -> tuple[bytes, Mapping[str, str]]:
self.requests.append((source, url, deadline))
body = self.responses[url]
if isinstance(body, HttpError):
raise body
assert len(body) <= limit
return body, {"Cache-Control": "no-store"} if self.no_store and url == artifact_url() else {}
@pytest.mark.anyio
async def test_lookup_prefers_csaf_and_preserves_issue_product_and_branch_scope() -> None:
wire = LiveWire({RSS: linked_rss((NATIVE, "first")), artifact_url(): csaf()}, no_store=True)
first = await lookup_fortinet("id", NATIVE.lower(), http=wire, deadline=42)
assert first.status.status == "ok" and not first.cacheable
[doc] = first.docs
assert (doc.native_id, doc.publisher, doc.updated, doc.url) == (NATIVE, "Fortinet", DATE + "+00:00", artifact_url())
on_premises, cloud = doc.issues
assert [issue.id for issue in doc.issues] == [CVE, SECOND_CVE]
assert not on_premises.aliases and not cloud.aliases
assert on_premises.refs == [{"type": "vendor_advisory", "url": artifact_url()}]
assert IGNORED not in doc.model_dump_json() and "example.invalid" not in doc.model_dump_json()
def verdicts(version: str) -> set[str]:
asset = make_asset("text", "FortiSandbox", AssetFacts(version=version, vendor="Fortinet"))
return {product_status(row, asset) for row in on_premises.products
if product_match(row, asset) == (True, set()) and fortinet_fix_matches(row, version)}
assert verdicts("5.0.5") == {"affected"}
assert verdicts("5.0.7") == {"unknown"}
assert verdicts("4.2.12") == {"affected"}
assert verdicts("5.2.0") == {"not_affected"}
assert verdicts("5.0") == set()
assert verdicts("5.4.1") == set()
assert on_premises.fixes == [
{"category": "vendor_fix", "details": "Upgrade to 5.0.6 or later.", "scope": "5.0", "version": "5.0.6",
"product_ids": ["FortiSandbox >=5.0.0|<=5.0.5"]},
{"category": "vendor_fix", "details": "Migrate to a fixed release.", "scope": "4.2",
"product_ids": ["FortiSandbox/ 4.2 all versions"]},
]
assert not fortinet_fix_matches(on_premises.fixes[0], "5.2.1")
assert [fix["product_ids"] for fix in cloud.fixes] == [["FortiSandbox Cloud >=5.0.4|<=5.0.5"]]
wire.responses[artifact_url()] = csaf(date="2026-06-10T00:00:00", fixed="5.0.8")
updated = await lookup_fortinet("id", NATIVE, http=wire, deadline=43)
assert updated.docs[0].issues[0].fixes[0]["version"] == "5.0.8"
assert wire.requests == [("fortinet", url, deadline) for deadline in (42, 43)
for url in (RSS, artifact_url())]
@pytest.mark.anyio
async def test_legacy_cvrf_returns_identity_without_suspect_product_status() -> None:
url = f"https://{HOST}/psirt/cvrf/{NATIVE}"
payload = f'''<cvrfdoc xmlns="http://www.icasi.org/CVRF/schema/cvrf/1.1"
xmlns:v="http://www.icasi.org/CVRF/schema/vuln/1.1">
<DocumentTracking><Identification><ID>{NATIVE}</ID></Identification>
<CurrentReleaseDate>{DATE}Z</CurrentReleaseDate></DocumentTracking>
<v:Vulnerability Ordinal="1"><v:CVE>{CVE}</v:CVE><v:ProductStatuses>
<v:Status Type="Known Affected"><v:ProductID>FortiSandbox newer branch</v:ProductID></v:Status>
</v:ProductStatuses></v:Vulnerability></cvrfdoc>'''.encode()
wire = LiveWire({RSS: linked_rss_cvrf((NATIVE, "first"), url), url: payload})
result = await lookup_fortinet("id", NATIVE, http=wire, deadline=42)
assert result.status.status == "ok"
[doc] = result.docs
[issue] = doc.issues
assert (doc.native_id, issue.id) == (NATIVE, CVE)
assert not issue.products and not issue.fixes
@pytest.mark.anyio
@pytest.mark.parametrize("link", [
"https://example.invalid/fortiguard/psirt/csaf_named_fg-ir-26-141.json",
"https://filestore.fortinet.com/fortiguard/psirt/csaf_wrong_fg-ir-26-100.json",
"https://filestore.fortinet.com/fortiguard/psirt/csaf_named_fg-ir-26-141.json?token=value",
"https://fortiguard.fortinet.com/psirt/cvrf/FG-IR-26-141/attachment",
])
async def test_unrecognized_download_never_goes_outbound(link: str) -> None:
wire = LiveWire({RSS: linked_rss((NATIVE, "first"), link=link)})
result = await lookup_fortinet("id", NATIVE, http=wire, deadline=42)
assert result.status.status == "invalid_data" and not result.docs
assert [url for _source, url, _deadline in wire.requests] == [RSS]
@pytest.mark.anyio
async def test_transport_failure_and_missing_advisory_are_distinguished() -> None:
bad_value = await lookup_fortinet("id", advisory_url(), http=LiveWire({}), deadline=42)
missing = await lookup_fortinet("id", NATIVE,
http=LiveWire({RSS: rss((OTHER, "x"))}), deadline=42)
limited = await lookup_fortinet("id", NATIVE, http=LiveWire({RSS: linked_rss((NATIVE, "first")),
artifact_url(): HttpError("rate_limited", DATE)}), deadline=42)
assert bad_value.status.status == "invalid_data" and not bad_value.docs
assert missing.status.status == "ok" and not missing.docs
assert limited.status.status == "rate_limited" and limited.status.retry_at == DATE
class IndexWire:
def __init__(self, responses: dict[str, bytes | HttpError | None]) -> None:
self.responses = responses
self.etag = '"rev1"'
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, via: str = "direct") -> tuple[int, Mapping[str, str]]:
assert source == "fortinet"
self.requests.append((url, dict(headers or {})))
body = self.responses[url]
if isinstance(body, HttpError):
raise body
if body is None:
return 304, {"ETag": self.etag}
assert len(body) <= limit
path.write_bytes(body)
return 200, {"ETag": self.etag}
@pytest.mark.anyio
async def test_rolling_index_does_not_drop_aged_records_or_publish_a_bad_revision(tmp_path: Path) -> None:
wire = IndexWire({RSS: rss((NATIVE, "first")), advisory_url(): advisory(), artifact_url(): csaf()})
async with Store(tmp_path) as store:
sync = Sync(store, wire)
assert await sync.refresh_once("fortinet")
generation = await store.generation()
wire.responses = {RSS: None}
assert await sync.refresh_once("fortinet")
assert await store.generation() == generation
assert wire.requests[-1] == (RSS, {"If-None-Match": '"rev1"'})
wire.responses = {RSS: rss((OTHER, "new")), advisory_url(OTHER): advisory(OTHER), artifact_url(OTHER): csaf(OTHER)}
wire.etag = '"rev2"'
assert await sync.refresh_once("fortinet")
assert await store.by_id(OTHER) and await store.by_id(NATIVE)
generation = await store.generation()
wire.responses = {RSS: rss((NATIVE, "changed"), (OTHER, "changed")), advisory_url(): advisory(),
artifact_url(): csaf(fixed="5.0.8"), advisory_url(OTHER): advisory(OTHER),
artifact_url(OTHER): b"{}"}
assert not await sync.refresh_once("fortinet")
assert await store.generation() == generation
[original] = await store.by_id(NATIVE)
assert original.issues[0].fixes[0]["version"] == "5.0.6"
def test_allowlist_only_permits_psirt_resources_on_the_assigned_route() -> None:
for url in (advisory_url(), artifact_url(), f"https://www.fortiguard.com/psirt/cvrf/{NATIVE}"):
parts = urlsplit(url)
assert allowed(parts.hostname or "", parts.path, live=True)
assert allowed(parts.hostname or "", parts.path, live=False)
assert allowed(FILESTORE, "/fortiguard/rss/ir.xml", live=False)
assert allowed(FILESTORE, "/fortiguard/rss/ir.xml", live=True)
assert not allowed(HOST + ".example.invalid", f"/psirt/{NATIVE}", live=True)
assert not allowed(HOST, f"/psirt/{NATIVE}/attachment", live=True)
assert not allowed(FILESTORE, "/fortiguard/rss/irdataex.xml", live=False)
@pytest.mark.anyio
async def test_xml_declarations_and_empty_feeds_never_publish(tmp_path: Path) -> None:
wire = IndexWire({RSS: b'<!DOCTYPE rss><rss version="2.0"><channel/></rss>'})
async with Store(tmp_path) as store:
sync = Sync(store, wire)
assert not await sync.refresh_once("fortinet")
wire.responses = {RSS: rss()}
assert not await sync.refresh_once("fortinet")
assert wire.requests == [(RSS, {}), (RSS, {})]
assert not (await store.state("fortinet"))["checkpoint"]
def linked_rss(*items: tuple[str, str], link: str | None = None, cvrf: bool = False) -> bytes:
entries = "".join(
f"<item><title>{IGNORED}</title><description>{revision}</description>"
f"<link>https://www.fortiguard.com/psirt/{native}</link>"
f'<{"cvrf" if cvrf else "csaf"}:link>{link or artifact_url(native)}</{"cvrf" if cvrf else "csaf"}:link>'
"<pubDate>Tue, 09 Jun 2026 00:00:00 GMT</pubDate></item>"
for native, revision in items
)
return ('<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" '
'xmlns:csaf="https://fortiguard.fortinet.com/rss/ns/csaf" '
'xmlns:cvrf="https://fortiguard.fortinet.com/rss/ns/cvrf">'
f'<channel>{entries}</channel></rss>').encode()
def linked_rss_cvrf(items: tuple[str, str], link: str) -> bytes:
return linked_rss(items, link=link, cvrf=True)
@pytest.mark.anyio
async def test_feed_supplied_document_skips_the_blocked_advisory_page(tmp_path: Path) -> None:
# The publisher's HTML pages are denied to some egress IPs; the feed names the
# structured document, so the page must not be requested at all.
wire = IndexWire({RSS: linked_rss((NATIVE, "first")), artifact_url(): csaf()})
async with Store(tmp_path) as store:
assert await Sync(store, wire).refresh_once("fortinet")
assert await store.by_id(NATIVE)
assert [url for url, _headers in wire.requests] == [RSS, artifact_url()]
@pytest.mark.anyio
async def test_a_mismatched_feed_link_is_rejected(tmp_path: Path) -> None:
body = linked_rss((NATIVE, "first")).replace(artifact_url(NATIVE).encode(), artifact_url(OTHER).encode())
wire = IndexWire({RSS: body})
async with Store(tmp_path) as store:
assert not await Sync(store, wire).refresh_once("fortinet")
def test_stub_document_without_vulnerabilities_still_parses() -> None:
body = json.loads(csaf())
del body["vulnerabilities"]
doc = _csaf(json.dumps(body).encode(), NATIVE)
# parse() still yields the advisory identity; no product claims exist yet.
assert doc.native_id == NATIVE and [issue.id for issue in doc.issues] == [NATIVE]
assert doc.issues[0].products == []
def test_inline_fixed_version_in_product_status_is_recovered() -> None:
body = json.loads(csaf())
status = body["vulnerabilities"][0]["product_status"]
status.setdefault("known_not_affected", []).append("FortiSandbox-5.0.5")
doc = _csaf(json.dumps(body).encode(), NATIVE)
recovered = [p for issue in doc.issues for p in issue.products if p["product_id"] == "FortiSandbox-5.0.5"]
[product] = recovered
assert (product["name"], product["version"], product["status"]) == ("FortiSandbox", "5.0.5", "not_affected")
def test_repeated_cve_entry_is_merged_into_one_issue() -> None:
body = json.loads(csaf())
first = body["vulnerabilities"][0]
second = json.loads(json.dumps(first))
second["product_status"] = {"known_not_affected": ["FortiSandbox-5.2.0"]}
body["vulnerabilities"].append(second)
doc = _csaf(json.dumps(body).encode(), NATIVE)
assert [issue.id for issue in doc.issues].count(first["cve"]) == 1
issue = next(i for i in doc.issues if i.id == first["cve"])
assert any(p["product_id"] == "FortiSandbox-5.2.0" for p in issue.products)
def test_spaced_range_operators_are_valid_product_labels() -> None:
from vuln_mcp.sources.feed_fortinet import _PRODUCT_ID, _label
assert _label("FortiMail >= 8.0.0 and <= 8.0.1", _PRODUCT_ID) == "FortiMail >= 8.0.0 and <= 8.0.1"
with pytest.raises(Exception):
_label("<b>FortiMail</b>", _PRODUCT_ID)
@pytest.mark.anyio
async def test_lookup_with_the_indexed_document_skips_the_page() -> None:
wire = LiveWire({artifact_url(): csaf()})
page = await lookup_fortinet("url", (NATIVE, artifact_url()), http=wire, deadline=monotonic() + 5)
assert page.status.status == "ok" and page.docs[0].native_id == NATIVE
# The blocked landing page is never requested.
assert [url for _source, url, _deadline in wire.requests] == [artifact_url()]
@pytest.mark.anyio
async def test_lookup_reports_a_document_url_for_another_identifier() -> None:
page = await lookup_fortinet("url", (NATIVE, artifact_url(OTHER)), http=LiveWire({}), deadline=monotonic() + 5)
assert page.status.status == "invalid_data" and not page.docs