from collections import defaultdict, deque
from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from pathlib import Path
import pytest
from vuln_mcp.sources import feed_zdi
from vuln_mcp.store import Store
from vuln_mcp.sync import Sync
pytestmark = pytest.mark.anyio
ORIGIN = "https://www.zerodayinitiative.com"
CURRENT = ORIGIN + "/advisories/published/"
ARCHIVE = CURRENT + "2005/"
OLD = "ZDI-05-001"
ACTIVE = "ZDI-06-042"
WITHOUT_CVE = "ZDI-06-099"
CVE_A = "CVE-2006-1001"
CVE_B = "CVE-2006-1002"
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
@pytest.fixture
def clock(monkeypatch: pytest.MonkeyPatch) -> type[datetime]:
class FrozenDateTime(datetime):
current = datetime(2006, 12, 31, 23, tzinfo=UTC)
@classmethod
def now(cls, tz=None):
return cls.current.astimezone(tz) if tz else cls.current.replace(tzinfo=None)
monkeypatch.setattr(feed_zdi, "datetime", FrozenDateTime)
return FrozenDateTime
@dataclass
class Reply:
body: bytes = b""
headers: dict[str, str] = field(default_factory=dict)
status: int = 200
class CatalogueHttp:
def __init__(self) -> None:
self.responses: dict[str, deque[Reply]] = defaultdict(deque)
self.calls: list[tuple[str, dict[str, str]]] = []
async def json(self, source, url, *, params=None, headers=None):
pytest.fail(f"unexpected JSON request: {source} {url}")
async def download(
self, source: str, url: str, path: Path, *,
headers: Mapping[str, str] | None = None, limit: int,
) -> tuple[int, Mapping[str, str]]:
assert source == "zdi"
self.calls.append((url, dict(headers or {})))
assert self.responses[url], f"unexpected catalogue request: {url}"
reply = self.responses[url].popleft()
if reply.status == 200:
assert len(reply.body) < limit
path.write_bytes(reply.body)
return reply.status, reply.headers
def row(native: str, cves: str = " ", *, title: str = "Example Product advisory", updated: str = "") -> str:
return f"""
{native}
case bookkeeping
Example & Company
{cves}
9.8
2006-01-01
{updated}
{title} discarded payload
discarded link
"""
def page(selected: int, *rows: str, latest: int = 2006, etag: str | None = None) -> Reply:
years = "".join(f'{year} '
for year in range(latest, 2004, -1))
body = f"""{years}
ZDI ID Vendor/Product CVE
{"".join(rows)}
"""
return Reply(body.encode(), {"ETag": etag} if etag else {})
async def test_indexes_historical_native_ids_and_separate_cves(tmp_path):
http = CatalogueHttp()
http.responses[CURRENT].append(page(2006, row(ACTIVE, f"{CVE_B}, {CVE_A}", updated="2006-02-25"),
row(WITHOUT_CVE)))
http.responses[ARCHIVE].append(page(2005, row(OLD, "CVE-2005-2715")))
async with Store(tmp_path) as store:
assert await Sync(store, http).refresh_once("zdi")
[history] = await store.by_id(OLD)
assert [issue.id for issue in history.issues] == ["CVE-2005-2715"]
[multi] = await store.by_id(ACTIVE)
assert (multi.publisher, multi.url, multi.title, multi.updated) == (
"Zero Day Initiative", f"{ORIGIN}/advisories/{ACTIVE}/", "Example Product advisory",
"2006-02-25T00:00:00+00:00",
)
assert {issue.id for issue in multi.issues} == {CVE_A, CVE_B}
assert [doc.native_id for doc in await store.by_id(CVE_A)] == [ACTIVE]
assert [doc.native_id for doc in await store.by_id(CVE_B)] == [ACTIVE]
[fallback] = await store.by_id(WITHOUT_CVE)
[issue] = fallback.issues
assert issue.id == WITHOUT_CVE
assert issue.products == [{"name": "Example & Company", "status": "unknown"}]
assert issue.facts == {"published": "2006-01-01"}
assert issue.refs == issue.fixes == []
assert not issue.summary and fallback.artifact is None
assert http.calls == [(CURRENT, {}), (ARCHIVE, {})]
async def test_conditional_and_unchanged_metadata_preserve_generation(tmp_path, clock):
http = CatalogueHttp()
http.responses[CURRENT].extend((page(2006, row(ACTIVE), etag='"current-v1"'), Reply(status=304),
page(2006, row(ACTIVE), etag='"current-v2"')))
http.responses[ARCHIVE].append(page(2005, row(OLD), etag='"archive-v1"'))
async with Store(tmp_path) as store:
sync = Sync(store, http)
assert await sync.refresh_once("zdi")
generation = await store.generation()
assert await sync.refresh_once("zdi")
assert await store.generation() == generation
assert await sync.refresh_once("zdi")
assert await store.generation() == generation
assert http.calls == [(CURRENT, {}), (ARCHIVE, {}),
(CURRENT, {"If-None-Match": '"current-v1"'}),
(CURRENT, {"If-None-Match": '"current-v1"'})]
state = await store.state("zdi")
assert state["validators"]["current"] == {"etag": '"current-v2"'}
async def test_year_rollover_keeps_archived_ids_and_revalidates_retired_year(tmp_path, clock):
http = CatalogueHttp()
next_id = "ZDI-07-001"
http.responses[CURRENT].extend((page(2006, row(ACTIVE), etag='"current-2006"'),
page(2007, row(next_id), latest=2007, etag='"current-2007"')))
http.responses[ARCHIVE].extend((page(2005, row(OLD), etag='"archive-2005"'), Reply(status=304)))
former_current = CURRENT + "2006/"
http.responses[former_current].append(page(2006, row(ACTIVE, title="Final archived title"), latest=2007))
async with Store(tmp_path) as store:
sync = Sync(store, http)
assert await sync.refresh_once("zdi")
assert await sync.refresh_once("zdi")
assert [doc.title for doc in await store.by_id(ACTIVE)] == ["Final archived title"]
assert await store.by_id(OLD)
assert await store.by_id(next_id)
assert http.calls[2:] == [(CURRENT, {"If-None-Match": '"current-2006"'}),
(ARCHIVE, {"If-None-Match": '"archive-2005"'}),
(former_current, {})]
@pytest.mark.parametrize("broken", ["missing_cve", "misdirected", "empty", "partial", "duplicate", "foreign_link"])
async def test_archive_drift_does_not_publish_part_of_refresh(tmp_path, clock, broken):
second_old = "ZDI-05-002"
good = row(OLD)
if broken == "missing_cve":
malformed = good.replace('data-label="CVE"', 'data-label="Changed"')
response = page(2005, malformed, row(second_old))
elif broken == "misdirected":
response = page(2006, good, row(second_old))
elif broken == "empty":
response = page(2005)
elif broken == "partial":
response = page(2005, good)
elif broken == "duplicate":
response = page(2005, good, good)
else:
foreign = good.replace(f'href="/advisories/{OLD}/"', f'href="https://example.test/{OLD}/"')
response = page(2005, foreign, row(second_old))
http = CatalogueHttp()
http.responses[CURRENT].extend((page(2006, row(ACTIVE), etag='"current-v1"'),
page(2006, row(ACTIVE, title="Unpublished change"), etag='"current-v2"')))
http.responses[ARCHIVE].extend((page(2005, good, row(second_old)), response))
async with Store(tmp_path) as store:
sync = Sync(store, http)
assert await sync.refresh_once("zdi")
previous = await store.state("zdi")
generation = await store.generation()
clock.current += timedelta(days=8)
assert not await sync.refresh_once("zdi")
assert await store.generation() == generation
failed = await store.state("zdi")
assert failed["status"] == "invalid_data"
assert failed["validators"] == previous["validators"]
assert failed["checkpoint"] == previous["checkpoint"]
assert failed["last_success"] == previous["last_success"]
assert [doc.title for doc in await store.by_id(ACTIVE)] == ["Example Product advisory"]
assert await store.by_id(second_old)
async def test_revalidates_history_when_current_is_not_modified(tmp_path, clock):
http = CatalogueHttp()
http.responses[CURRENT].extend((page(2006, row(ACTIVE), etag='"current"'), Reply(status=304)))
http.responses[ARCHIVE].extend((page(2005, row(OLD), etag='"archive-v1"'),
page(2005, row(OLD, CVE_A), etag='"archive-v2"')))
async with Store(tmp_path) as store:
sync = Sync(store, http)
assert await sync.refresh_once("zdi")
clock.current += timedelta(days=8)
assert await sync.refresh_once("zdi")
assert http.calls[-1] == (ARCHIVE, {"If-None-Match": '"archive-v1"'})
assert [doc.native_id for doc in await store.by_id(CVE_A)] == [OLD]
def test_only_official_catalogue_endpoints_are_allowed():
host = "www.zerodayinitiative.com"
assert feed_zdi.allowed(host, "/advisories/published/")
assert feed_zdi.allowed(host, "/advisories/published/2005/")
assert not feed_zdi.allowed(host, "/advisories/published/2004/")
assert not feed_zdi.allowed(host, "/advisories/published/2025/extra/")
assert not feed_zdi.allowed(host, "/advisories/upcoming/")
assert not feed_zdi.allowed(host, "/advisories/ZDI-05-001/")
assert not feed_zdi.allowed(host, "/rss/published/")
assert not feed_zdi.allowed("zerodayinitiative.com.example.test", "/advisories/published/")