- Add private SQLite feed indexing, publisher-attributed advisory search and scoped HTTP routes. - Exercise supported proxy protocols, cancellation, version applicability and the stdio lifecycle. - Gate Docker builds on Python 3.12/3.13 tests and branch-aware coverage.
245 lines
12 KiB
Python
245 lines
12 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from contextlib import closing
|
|
from pathlib import Path
|
|
import sqlite3
|
|
|
|
from filelock import Timeout
|
|
import pytest
|
|
|
|
from vuln_mcp.models import Doc, Issue
|
|
from vuln_mcp.store import Store
|
|
|
|
pytestmark = pytest.mark.anyio
|
|
|
|
|
|
@pytest.fixture
|
|
def anyio_backend() -> str:
|
|
return "asyncio"
|
|
|
|
|
|
def record(
|
|
identifier: str, *, source: str = "cvelist", title: str = "Controller update",
|
|
updated: str | None = None, state: str = "published", issues: list[Issue] | None = None,
|
|
artifact: str | None = None,
|
|
) -> Doc:
|
|
return Doc(
|
|
source=source, native_id=identifier, publisher="Example vendor", title=title,
|
|
url="https://example.test/advisory", updated=updated, state=state, artifact=artifact,
|
|
issues=[Issue(id=identifier)] if issues is None else issues,
|
|
)
|
|
|
|
|
|
async def publish(store: Store, source: str, docs: list[Doc]) -> None:
|
|
async with store.staging(source) as stage:
|
|
await stage.add("base", docs)
|
|
await stage.publish({"revision": "base"}, layers={"base": "replace"})
|
|
|
|
|
|
async def test_delta_tombstone_and_validator_are_published_together(tmp_path: Path) -> None:
|
|
key = "CVE-2025-1234"
|
|
async with Store(tmp_path) as store:
|
|
await publish(store, "cvelist", [record(key)])
|
|
before = await store.generation()
|
|
async with store.staging("cvelist") as stage:
|
|
await stage.add("delta", [record(key, state="rejected")])
|
|
assert [doc.state for doc in await store.by_id(key)] == ["published"]
|
|
assert await store.generation() == before
|
|
await stage.publish({"revision": "hourly"}, layers={"delta": "replace"}, validators={"etag": "delta"})
|
|
assert await store.generation() != before
|
|
assert [doc.state for doc in await store.by_id(key)] == ["rejected"]
|
|
assert await store.lookup("Controller update") == []
|
|
assert (await store.state("cvelist"))["checkpoint"] == {"revision": "hourly"}
|
|
await store.checked("cvelist")
|
|
state = await store.state("cvelist")
|
|
assert state["validators"] == {"etag": "delta"}
|
|
assert 0 < state["published_at"] <= state["last_success"]
|
|
async with store.staging("cvelist") as stage:
|
|
await stage.publish({"revision": "empty-delta"}, layers={"delta": "replace"})
|
|
assert [doc.state for doc in await store.by_id(key)] == ["published"]
|
|
|
|
|
|
async def test_import_failure_retains_snapshot_and_collects_orphan(tmp_path: Path) -> None:
|
|
key = "CVE-2025-1234"
|
|
async with Store(tmp_path) as store:
|
|
await publish(store, "cvelist", [record(key)])
|
|
previous = await store.state("cvelist")
|
|
generation = await store.generation()
|
|
with pytest.raises(ValueError, match="conflicting documents"):
|
|
async with store.staging("cvelist") as stage:
|
|
raw = stage.directory / "fixture.zip"
|
|
raw.write_bytes(b"raw-stage-artifact")
|
|
digest = await stage.artifact(raw)
|
|
assert stage.artifact_path(digest).read_bytes() == b"raw-stage-artifact"
|
|
await stage.add("base", [record(key, title="First title", artifact=f"{digest}#cves/CVE-2025-1234.json")])
|
|
await stage.add("base", [record(key, title="Different title", artifact=digest)])
|
|
assert not store.artifact_path(digest).exists()
|
|
await store.failed("cvelist", "invalid_data")
|
|
assert await store.generation() == generation
|
|
assert [doc.title for doc in await store.by_id(key)] == ["Controller update"]
|
|
current = await store.state("cvelist")
|
|
assert current["status"] == "invalid_data"
|
|
assert current["last_success"] == previous["last_success"]
|
|
assert current["checkpoint"] == previous["checkpoint"]
|
|
|
|
|
|
async def test_checkpoint_preserves_only_reachable_artifacts(tmp_path: Path) -> None:
|
|
key = "CVE-2025-1234"
|
|
async with Store(tmp_path) as store:
|
|
async with store.staging("cvelist") as stage:
|
|
contents = {"advisory": b"archive", "manifest": b"release manifest", "unused": b"unused"}
|
|
digests = {}
|
|
for name, content in contents.items():
|
|
file = stage.directory / name
|
|
file.write_bytes(content)
|
|
digests[name] = await stage.artifact(file)
|
|
ref = f"{digests['advisory']}#cves/{key}.json"
|
|
await stage.add("base", [record(key, artifact=ref)])
|
|
await stage.publish({"manifest": digests["manifest"]}, layers={"base": "replace"}, artifacts=[digests["manifest"]])
|
|
assert not store.artifact_path(digests["unused"]).exists()
|
|
assert (await store.by_id(key))[0].artifact == ref
|
|
assert store.artifact_path(digests["advisory"]).read_bytes() == contents["advisory"]
|
|
assert store.artifact_path(digests["manifest"]).exists()
|
|
await store.checked("cvelist", {}, artifacts=[])
|
|
assert not store.artifact_path(digests["manifest"]).exists()
|
|
assert store.artifact_path(digests["advisory"]).exists()
|
|
|
|
|
|
async def test_nonempty_base_is_required_before_any_layer_can_change(tmp_path: Path) -> None:
|
|
key = "CVE-2025-1234"
|
|
async with Store(tmp_path) as store:
|
|
await publish(store, "cvelist", [record(key)])
|
|
before = await store.generation()
|
|
with pytest.raises(ValueError, match="empty full snapshot"):
|
|
async with store.staging("cvelist") as stage:
|
|
await stage.add("delta", [record(key, state="rejected")])
|
|
await stage.publish({"revision": "lost"}, layers={"delta": "replace", "base": "replace"})
|
|
assert await store.generation() == before
|
|
assert [doc.state for doc in await store.by_id(key)] == ["published"]
|
|
|
|
|
|
async def test_osv_revision_overlay_keeps_newest_and_other_rows(tmp_path: Path) -> None:
|
|
key, unrelated = "GHSA-1111-2222-3333", "GHSA-aaaa-bbbb-cccc"
|
|
alias = "CVE-2025-1234"
|
|
original = record(key, source="osv", updated="2025-02-01T01:00:00+01:00", issues=[Issue(id=key, aliases=[alias])])
|
|
async with Store(tmp_path) as store:
|
|
await publish(store, "osv", [original, record(unrelated, source="osv")])
|
|
async with store.staging("osv") as stage:
|
|
await stage.add("delta", [record(key, source="osv", updated="2025-01-31T22:55:00Z", title="Older")])
|
|
await stage.publish({}, layers={"delta": "overlay"})
|
|
assert (await store.by_id(alias))[0].title == "Controller update"
|
|
async with store.staging("osv") as stage:
|
|
await stage.add("delta", [record(key, source="osv", updated="2025-02-01T00:01:00Z", state="withdrawn")])
|
|
await stage.publish({}, layers={"delta": "overlay"})
|
|
assert await store.by_id(alias) == []
|
|
assert [doc.state for doc in await store.by_id(key)] == ["withdrawn"]
|
|
assert [doc.native_id for doc in await store.lookup("Controller update")] == [unrelated]
|
|
|
|
|
|
async def test_lookup_reports_only_active_rows_before_pagination(tmp_path: Path) -> None:
|
|
async with Store(tmp_path) as store:
|
|
expected = [record(f"CVE-2025-{number}") for number in range(1000, 1005)]
|
|
await publish(store, "cvelist", expected)
|
|
order = await store.ranked_ids('controller "update"')
|
|
before = await store.generation()
|
|
async with store.staging("cvelist") as stage:
|
|
await stage.add("base", [record(f"CVE-2024-{number}") for number in range(1000, 1010)])
|
|
page = await store.lookup('controller "update"', offset=2, limit=2)
|
|
assert [doc.native_id for doc in page] == ["CVE-2025-1002", "CVE-2025-1003"]
|
|
assert await store.lookup("CVE-2024-1000") == []
|
|
assert await store.generation() == before
|
|
assert [doc.native_id for doc in await store.by_rows(order[2:4][::-1])] == ["CVE-2025-1003", "CVE-2025-1002"]
|
|
await stage.publish({}, layers={"base": "replace"})
|
|
assert await store.generation() != before
|
|
assert await store.by_rows(order[:2]) == []
|
|
|
|
|
|
async def test_exact_keys_and_issue_local_data_roundtrip(tmp_path: Path) -> None:
|
|
primary = Issue(
|
|
id="CVE-2025-1234", aliases=["GHSA-1111-2222-3333"],
|
|
facts={"mentions": ["CVE-2025-5678"]},
|
|
products=[{"product_id": "p1", "model": "ABC-001", "purl": "pkg:pypi/example",
|
|
"repo": "https://example.test/source.git", "events": [{"fixed": "a" * 40}]}],
|
|
fixes=[{"product_ids": ["p1"], "details": "Upgrade", "category": "vendor_fix", "version": "2.0"}],
|
|
)
|
|
other = Issue(id="CVE-2025-1235", products=[{"product_id": "p1", "model": "ABC-002"}])
|
|
advisory = record("SSA-123456", source="siemens", issues=[primary, other])
|
|
async with Store(tmp_path) as store:
|
|
await publish(store, "siemens", [advisory])
|
|
for query in ("ABC-001", "pkg:pypi/example@1.0", "https://example.test/source/", "a" * 40):
|
|
assert [doc.native_id for doc in await store.lookup(query)] == ["SSA-123456"]
|
|
assert (await store.by_id("GHSA-1111-2222-3333"))[0].issues == [primary, other]
|
|
assert await store.by_id("CVE-2025-5678") == []
|
|
|
|
|
|
async def test_quota_and_normalized_cache_survive_restart(tmp_path: Path) -> None:
|
|
key, alias = "GHSA-1111-2222-3333", "CVE-2025-1234"
|
|
older = record(key, source="osv", updated="2025-01-01T00:00:00Z", issues=[Issue(id=key, aliases=[alias])])
|
|
newer = record(key, source="osv", updated="2025-01-02T00:00:00Z", title="New revision")
|
|
async with Store(tmp_path) as store:
|
|
await store.pause("nvd", "proxy:1", 500.0)
|
|
await store.pause("nvd", "proxy:1", 400.0)
|
|
await store.pause("nvd", "direct", 250.0)
|
|
await store.cache([older, newer, older])
|
|
assert await store.lookup(key) == []
|
|
async with Store(tmp_path) as store:
|
|
assert await store.quota("nvd") == 500.0
|
|
assert await store.quota("nvd", route="proxy:1") == 500.0
|
|
assert await store.quota("nvd", route="direct") == 250.0
|
|
assert await store.quota("cvelist") == 0.0
|
|
assert await store.cached_by_id(alias) == []
|
|
assert [doc.title for doc in await store.cached_by_id(key)] == ["New revision"]
|
|
|
|
|
|
async def test_metric_zero_is_not_absence_or_a_search_hit(tmp_path: Path) -> None:
|
|
key = "CVE-2025-1234"
|
|
metric = record(key, source="epss", issues=[Issue(id=key, facts={"epss": {"epss": 0.0, "percentile": 0.0}})])
|
|
async with Store(tmp_path) as store:
|
|
await publish(store, "epss", [metric])
|
|
assert await store.lookup(key) == []
|
|
assert (await store.by_id(key))[0].issues[0].facts["epss"]["epss"] == 0.0
|
|
assert await store.by_id("CVE-2025-1235") == []
|
|
|
|
|
|
async def test_directory_is_exclusive_until_closed(tmp_path: Path) -> None:
|
|
async with Store(tmp_path):
|
|
with pytest.raises(Timeout):
|
|
await Store(tmp_path).open()
|
|
async with Store(tmp_path) as reopened:
|
|
assert await reopened.generation() == "0"
|
|
|
|
|
|
async def test_cancelled_stage_does_not_publish_after_restart(tmp_path: Path) -> None:
|
|
key = "CVE-2025-1234"
|
|
entered = asyncio.Event()
|
|
async with Store(tmp_path) as store:
|
|
await publish(store, "cvelist", [record(key)])
|
|
|
|
async def refresh() -> None:
|
|
async with store.staging("cvelist") as stage:
|
|
await stage.add("base", [record(key, title="Unpublished revision")])
|
|
entered.set()
|
|
await asyncio.Future()
|
|
|
|
pending = asyncio.create_task(refresh())
|
|
try:
|
|
await asyncio.wait_for(entered.wait(), timeout=2)
|
|
finally:
|
|
pending.cancel()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await pending
|
|
async with Store(tmp_path) as store:
|
|
assert [doc.title for doc in await store.by_id(key)] == ["Controller update"]
|
|
assert (await store.state("cvelist"))["checkpoint"] == {"revision": "base"}
|
|
|
|
|
|
async def test_unknown_schema_is_reported_without_reset(tmp_path: Path) -> None:
|
|
path = tmp_path / "index.sqlite3"
|
|
with closing(sqlite3.connect(path)) as db:
|
|
db.execute("PRAGMA user_version=99")
|
|
with pytest.raises(RuntimeError, match="unsupported SQLite index schema: 99"):
|
|
await Store(tmp_path).open()
|
|
with closing(sqlite3.connect(path)) as db:
|
|
assert db.execute("PRAGMA user_version").fetchone() == (99,)
|