Files
vuln-mcp/tests/test_search.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

401 lines
20 KiB
Python

from __future__ import annotations
from datetime import UTC, datetime
from pathlib import Path
import pytest
from vuln_mcp.models import AssetFacts, Doc, Issue
from vuln_mcp.search import Search
from vuln_mcp.sources.parsers import parse
from vuln_mcp.store import Store
from vuln_mcp.transport import HttpError
pytestmark = pytest.mark.anyio
CVE = 'CVE-2025-43715'
OTHER = 'CVE-2025-43999'
GHSA = 'GHSA-abcd-1234-wxyz'
SSA = 'SSA-563922'
SA_URL = 'https://cert-portal.siemens.com/productcert/csaf/ssa-563922.json'
MODEL = '6ES7823-0FE30-1AA0'
OTHER_MODEL = '6AU1820-3DA20-0AB0'
REPO = 'https://github.com/example/controller'
COMMIT = 'f' * 40
DAY = '2025-07-08'
@pytest.fixture
def anyio_backend() -> str:
return 'asyncio'
def _csaf(updated: str = DAY, fixed: str = '1.3.1') -> dict:
def family(name: str, identifier: str, model: str, range_text: str) -> dict:
return {'category': 'product_name', 'name': name, 'branches': [{
'category': 'product_version_range', 'name': range_text,
'product': {'name': name, 'product_id': identifier,
'product_identification_helper': {'model_numbers': [model]}},
}]}
return {
'document': {'csaf_version': '2.0', 'tracking': {'id': SSA, 'current_release_date': updated},
'title': 'Siemens engineering tools update', 'publisher': {'name': 'Siemens'}},
'product_tree': {'branches': [{'category': 'vendor', 'name': 'Siemens', 'branches': [
family('TIA Administrator', 'P1', MODEL, 'vers:intdot/<' + fixed),
family('Motion components', 'P2', OTHER_MODEL, 'vers:intdot/<3.0.0'),
]}], 'product_groups': [{'group_id': 'Group1', 'product_ids': ['P1']}]},
'vulnerabilities': [
{'cve': CVE, 'product_status': {'known_affected': ['P1', 'P2']}, 'remediations': [
{'category': 'vendor_fix', 'group_ids': ['Group1'], 'details': f'Update to V{fixed} or later version'},
{'category': 'workaround', 'product_ids': ['P2'], 'details': 'Disable the optional component'},
]},
{'cve': OTHER, 'product_status': {'known_affected': ['P2']}, 'remediations': [
{'category': 'vendor_fix', 'product_ids': ['P2'], 'details': 'Update to V3.0.0 or later version'},
]},
],
}
def _cve(ident: str = CVE, *, updated: str = DAY, state: str = 'PUBLISHED') -> dict:
return {
'dataType': 'CVE_RECORD', 'dataVersion': '5.1',
'cveMetadata': {'cveId': ident, 'state': state, 'dateUpdated': updated},
'containers': {'cna': {'providerMetadata': {'shortName': 'Example CNA'}, 'title': 'Fixture library advisory',
'descriptions': [{'lang': 'en', 'value': 'A published controller library advisory.'}]}},
}
def _osv(aliases: list[str] | None = None, *, ident: str = GHSA) -> dict:
return {
'id': ident, 'modified': DAY, 'aliases': [CVE] if aliases is None else aliases,
'summary': 'Library advisory',
'affected': [{'package': {'purl': 'pkg:pypi/advisory-fixture', 'name': 'advisory-fixture', 'ecosystem': 'PyPI'},
'ranges': [{'type': 'GIT', 'repo': REPO, 'events': [{'introduced': '0'}, {'fixed': COMMIT}]},
{'type': 'ECOSYSTEM', 'events': [{'introduced': '1.0'}, {'fixed': '1.3.1'},
{'introduced': '2.0'}, {'limit': '2.3'}]}]}],
'references': [{'type': 'WEB', 'url': 'https://example.test/PoC/attachment'}],
}
def _nvd(ident: str, *, configurations: list | None = None) -> dict:
return {
'id': ident, 'vulnStatus': 'Analyzed', 'lastModified': DAY,
'descriptions': [{'lang': 'en', 'value': 'Test advisory description'}],
'configurations': configurations or [],
'metrics': {'cvssMetricV31': [{'source': 'nvd@nist.gov', 'cvssData': {
'version': '3.1', 'baseScore': 5.3, 'vectorString': 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L',
}}]},
}
class PublisherHTTP:
def __init__(self) -> None:
self.calls: list[tuple[str, str, dict, dict]] = []
self.cves: dict[str, dict] = {}
self.vars_by_page: dict[int, tuple[int, list[dict]]] = {}
self.nvd: dict[str, dict] = {}
self.nvd_discovery: list[dict] = []
self.csaf: dict[str, dict] = {}
self.osv: dict[str, dict] = {}
self.osv_pages: dict[str, dict] = {}
self.failures: dict[tuple[str, str], HttpError] = {}
self.no_store: set[str] = set()
# A parsed Metasploit index needs at least one CVE reference; keep it off the fixture CVEs.
self.metasploit: dict = {'fixture/module': {
'path': '/modules/exploits/fixture/module.rb', 'references': ['CVE-2025-0001'], 'rank': 300,
}}
self.templates: set[str] = set()
self.timeout = 9.5
@property
def budget(self) -> float:
return self.timeout + 0.5
async def json(self, source: str, url: str, *, params=None, body=None, deadline=None, headers=None,
budget=None):
assert deadline is not None
params, body = params or {}, body or {}
self.calls.append((source, url, params, body))
ident = url.rsplit('/', 1)[-1]
if failure := self.failures.get((source, ident)):
raise failure
response_headers = {'Cache-Control': 'private, no-store'} if source in self.no_store else {}
if source == 'cvelist':
response = self.cves.get(ident)
elif source == 'certcc':
raise HttpError('not_found')
elif source == 'circl' and ident == 'fulltext':
page = params['page']
count, docs = self.vars_by_page.get(page, (0, []))
response = {'metadata': {'count': count, 'page': page, 'per_page': 20}, 'data': docs}
elif source == 'circl':
response = self.cves.get(ident) if ident.startswith('CVE-') else None
if ident.startswith('VAR-'):
response = {'id': ident, 'title': {'data': 'Test controller'}}
elif source == 'nvd':
ids = params.get('cveIds')
docs = [self.nvd[ident] for ident in ids.split(',') if ident in self.nvd] if ids else self.nvd_discovery
response = {'vulnerabilities': [{'cve': doc} for doc in docs], 'totalResults': len(docs),
'resultsPerPage': len(docs), 'startIndex': params.get('startIndex', 0)}
elif source == 'epss':
response = {'status': 'OK', 'data': [{'cve': ident, 'epss': '0.0', 'percentile': '0.1', 'date': DAY}
for ident in params['cve'].split(',')]}
elif source in {'siemens', 'msrc'}:
response = self.csaf.get(url)
elif source == 'metasploit':
response = self.metasploit
elif source == 'osv':
response = self.osv_pages.get(body.get('page_token', ''), {}) if ident == 'query' else self.osv.get(ident)
else:
raise AssertionError(f'unexpected publisher {source}')
if response is None:
raise HttpError('not_found')
return response, response_headers
async def bytes(self, source: str, url: str, *, deadline: float, limit: int):
self.calls.append((source, url, {}, {}))
ident = url.rsplit('/', 1)[-1]
if failure := self.failures.get((source, ident)):
raise failure
if source == 'pocs':
return (b'[]' if url.endswith('.json') else b''), {}
if source == 'nuclei':
cve = ident.removesuffix('.yaml')
if cve not in self.templates:
raise HttpError('not_found')
return f'id: {cve}\n\ninfo:\n name: Fixture template\n'.encode(), {}
raise AssertionError(f'unexpected publisher {source}')
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': DAY}, layers={'base': 'replace'})
async def _ready(store: Store) -> None:
for source in ('cvelist', 'osv', 'siemens', 'msrc', 'kev', 'epss', 'zdi', 'certcc', 'projectzero', 'exploitdb',
'paloalto', 'industrial', 'android', 'fortinet', 'web', 'exploitdb_inventory'):
await store.checked(source, {'as_of': datetime.now(UTC).date().isoformat()})
def _document(ident: str, title: str) -> Doc:
return Doc(source='cvelist', native_id=ident, publisher='Example CNA',
title=title, url=f'https://www.cve.org/CVERecord?id={ident}', issues=[Issue(id=ident)])
async def test_warm_exact_search_and_detail_recheck_all_publishers_and_replace_revision(tmp_path: Path) -> None:
http = PublisherHTTP()
http.cves[CVE] = _cve()
http.nvd[CVE] = _nvd(CVE)
http.templates.add(CVE)
http.osv[GHSA] = _osv()
http.csaf[SA_URL] = _csaf()
async with Store(tmp_path) as store:
await _publish(store, 'cvelist', [parse('cvelist', _cve(), 'https://www.cve.org/CVERecord')])
await _publish(store, 'osv', [parse('osv', _osv(), f'https://api.osv.dev/v1/vulns/{GHSA}')])
await _publish(store, 'siemens', [parse('siemens', _csaf(), SA_URL)])
await _ready(store)
search = Search(store, http)
asset = AssetFacts(product=MODEL, version='1.3.0')
page = await search.search(CVE, asset)
assert [hit.id for hit in page.hits] == [CVE]
hit = page.hits[0]
assert hit.aliases == [GHSA]
assert hit.fixed_versions == ['1.3.1']
assert hit.applicability == 'affected'
assert hit.epss and hit.epss['epss'] == 0.0
assert hit.kev and hit.kev['member'] is False
assert any(fact['type'] == 'cvss' and fact['value']['publisher'] == 'nvd@nist.gov' for fact in hit.facts)
assert any(ref['type'] == 'fix_commit' and ref['url'] == REPO and ref['commit'] == COMMIT for ref in hit.source_refs)
assert not any('/PoC/' in ref['url'] for ref in hit.source_refs)
assert [ref for ref in hit.exploit_refs if ref['type'] == 'detection_template'] == [
{'type': 'detection_template', 'url': 'https://raw.githubusercontent.com/projectdiscovery/nuclei-templates'
'/main/http/cves/2025/CVE-2025-43715.yaml', 'protocol': 'http', 'template_name': 'Fixture template'},
]
assert {status.source for status in hit.coverage if status.channel == 'live'} == {
'cvelist', 'circl', 'nvd', 'epss', 'osv', 'siemens', 'certcc', 'pocs', 'nuclei', 'metasploit',
}
assert not page.partial
first = {source for source, *_ in http.calls}
http.calls.clear()
http.csaf[SA_URL] = _csaf('2025-07-09', '1.3.2')
second = await search.search(CVE, asset)
assert second.hits[0].fixed_versions == ['1.3.2']
assert {source for source, *_ in http.calls} == first
http.calls.clear()
http.failures[('siemens', 'ssa-563922.json')] = HttpError('rate_limited', '2027-01-01T00:00:00Z')
detail = await search.get_advisory(CVE)
assert detail.status == 'found' and detail.partial
assert [fix['version'] for fix in detail.issues[0].remediations if fix['category'] == 'vendor_fix'] == ['1.3.2']
assert any(status.source == 'siemens' and status.status == 'rate_limited' and status.retry_at
for status in detail.issues[0].coverage)
assert {source for source, *_ in http.calls} == first
async def test_siemens_exact_model_keeps_related_products_and_issues_separate(tmp_path: Path) -> None:
http = PublisherHTTP()
http.csaf[SA_URL] = _csaf()
async with Store(tmp_path) as store:
await _publish(store, 'siemens', [parse('siemens', _csaf(), SA_URL)])
search = Search(store, http)
unversioned_result = await search.search(MODEL)
assert len(unversioned_result.hits) == 1
unversioned = unversioned_result.hits[0]
assert unversioned.id == CVE
assert unversioned.applicability == 'unknown' and unversioned.missing_fields == ['version']
primary = (await search.search(MODEL, AssetFacts(version='1.3.0'))).hits[0]
assert primary.applicability == 'affected' and primary.fixed_versions == ['1.3.1']
assert primary.remediations[0]['product_ids'] == ['P1']
assert 'or later' in primary.remediations[0]['details']
secondary = await search.search(OTHER_MODEL, AssetFacts(version='1.3.0'))
assert {hit.id for hit in secondary.hits} == {CVE, OTHER}
for hit in secondary.hits:
assert '1.3.1' not in hit.fixed_versions
assert all(remediation['product_ids'] == ['P2'] for remediation in hit.remediations)
detail = await search.get_advisory(SSA)
assert {hit.id for hit in detail.issues} == {CVE, OTHER}
assert {hit.id: hit.fixed_versions for hit in detail.issues} == {CVE: ['1.3.1'], OTHER: ['3.0.0']}
async def test_every_page_batches_all_cves_and_checks_unseen_live_candidates(tmp_path: Path) -> None:
http = PublisherHTTP()
ids = [f'CVE-2025-{number}' for number in range(3000, 3024)]
live_only = 'CVE-2025-9999'
http.vars_by_page = {
1: (61, [{'id': f'VAR-2025-{i}', 'title': {'data': 'Test controller'}} for i in range(20)]),
2: (61, [_cve(live_only)]),
3: (61, []),
}
http.cves[live_only] = _cve(live_only)
async with Store(tmp_path) as store:
await _publish(store, 'cvelist', [_document(ident, 'Fixture controller') for ident in ids])
search = Search(store, http)
first = await search.search('Fixture controller')
assert len(first.hits) == 20 and first.next_cursor
assert {hit.id for hit in first.hits} == set(ids[:20])
assert [params['cveIds'] for source, _, params, _ in http.calls if source == 'nvd' and 'cveIds' in params] == [','.join(ids[:20])]
assert [params['cve'] for source, _, params, _ in http.calls if source == 'epss'] == [','.join(ids[:20])]
http.calls.clear()
second = await search.search('Fixture controller', cursor=first.next_cursor)
assert set(ids[20:]) <= {hit.id for hit in second.hits}
assert not {hit.id for hit in first.hits} & {hit.id for hit in second.hits}
assert any(source == 'circl' and params.get('page') == 2 for source, _, params, _ in http.calls)
assert any(source == 'nvd' and set(params.get('cveIds', '').split(',')) >= set(ids[20:]) for source, _, params, _ in http.calls)
assert second.next_cursor
third = await search.search('Fixture controller', cursor=second.next_cursor)
assert live_only in {hit.id for hit in third.hits}
assert third.next_cursor
await _publish(store, 'cvelist', [_document('CVE-2025-4000', 'Fixture controller')])
http.calls.clear()
with pytest.raises(ValueError, match='cursor_expired'):
await search.search('Fixture controller', cursor=third.next_cursor)
assert not http.calls
async def test_purl_empty_osv_page_continues_and_never_duplicates_version(tmp_path: Path) -> None:
http = PublisherHTTP()
http.osv_pages = {'': {'next_page_token': 'upstream-token'}, 'upstream-token': {'vulns': [_osv()]}}
http.cves[CVE] = _cve()
async with Store(tmp_path) as store:
search = Search(store, http)
first = await search.search('pkg:pypi/advisory-fixture@2.1')
assert not first.hits and first.next_cursor
second = await search.search('pkg:pypi/advisory-fixture@2.1', cursor=first.next_cursor)
assert [hit.id for hit in second.hits] == [CVE]
assert second.hits[0].applicability == 'affected'
assert [body for source, _, _, body in http.calls if source == 'osv'] == [
{'package': {'purl': 'pkg:pypi/advisory-fixture@2.1'}},
{'package': {'purl': 'pkg:pypi/advisory-fixture@2.1'}, 'page_token': 'upstream-token'},
]
async def test_nvd_unchecked_platform_constraint_returns_unknown(tmp_path: Path) -> None:
naked = 'cpe:2.3:a:example:controller:*:*:*:*:*:*:*:*'
target = naked.replace(':controller:*', ':controller:1.1')
platform = 'cpe:2.3:o:example:platform:*:*:*:*:*:*:*:*'
http = PublisherHTTP()
configurations = [{'operator': 'AND', 'nodes': [
{'operator': 'OR', 'cpeMatch': [{'criteria': naked, 'vulnerable': True, 'versionEndExcluding': '1.2'}]},
{'operator': 'OR', 'cpeMatch': [{'criteria': platform, 'vulnerable': False}]},
]}]
http.nvd_discovery = [_nvd(CVE, configurations=configurations)]
async with Store(tmp_path) as store:
response = await Search(store, http).search(target)
assert [(hit.id, hit.applicability) for hit in response.hits] == [(CVE, 'unknown')]
assert any(fact['type'] == 'configurations' and fact['value'] == configurations for fact in response.hits[0].facts)
assert len([1 for source, *_ in http.calls if source == 'nvd']) == 1
async def test_per_id_failure_does_not_mark_another_hit_rate_limited(tmp_path: Path) -> None:
http = PublisherHTTP()
failure = 'CVE-2025-43716'
http.cves[CVE] = _cve()
http.failures[('cvelist', failure)] = HttpError('rate_limited', '2027-01-01T00:00:00Z')
async with Store(tmp_path) as store:
await _publish(store, 'cvelist', [_document(CVE, 'Fixture controller'), _document(failure, 'Fixture controller')])
await _ready(store)
result = await Search(store, http).search('Fixture controller')
by_id = {hit.id: hit for hit in result.hits}
assert result.partial
assert any(item.source == 'cvelist' and item.channel == 'live' and item.status == 'ok' for item in by_id[CVE].coverage)
assert any(item.source == 'cvelist' and item.status == 'rate_limited' for item in by_id[failure].coverage)
async def test_shared_osv_alias_does_not_join_distinct_cves(tmp_path: Path) -> None:
http = PublisherHTTP()
http.cves.update({CVE: _cve(), OTHER: _cve(OTHER)})
http.osv[GHSA] = _osv([CVE, OTHER])
async with Store(tmp_path) as store:
detail = await Search(store, http).get_advisory(GHSA)
assert {hit.id for hit in detail.issues} == {CVE, OTHER}
assert all(GHSA not in hit.aliases for hit in detail.issues)
assert all(not any(ref['type'] == 'fix_commit' for ref in hit.source_refs) for hit in detail.issues)
async def test_cve_rejection_keeps_independent_siemens_evidence(tmp_path: Path) -> None:
http = PublisherHTTP()
http.cves[CVE] = _cve(updated='2025-07-09', state='REJECTED')
http.csaf[SA_URL] = _csaf()
async with Store(tmp_path) as store:
await _publish(store, 'cvelist', [parse('cvelist', _cve(), 'https://www.cve.org/CVERecord')])
await _publish(store, 'siemens', [parse('siemens', _csaf(), SA_URL)])
hit = (await Search(store, http).search(CVE, AssetFacts(product=MODEL, version='1.3.0'))).hits[0]
assert hit.record_state == 'rejected'
assert hit.applicability == 'affected'
assert hit.fixed_versions == ['1.3.1']
async def test_no_store_response_is_not_a_fallback(tmp_path: Path) -> None:
http = PublisherHTTP()
http.cves[CVE] = _cve()
http.no_store = {'cvelist', 'circl'}
async with Store(tmp_path) as store:
search = Search(store, http)
first = await search.get_advisory(CVE)
assert first.status == 'found'
assert not any(doc.source in http.no_store for doc in await store.cached_by_id(CVE))
http.cves.clear()
http.failures[('cvelist', CVE)] = HttpError('unavailable')
second = await search.get_advisory(CVE)
assert second.status == 'inconclusive' and not second.issues
@pytest.mark.parametrize('query', ['', 'cpe:2.3:a:only', 'pkg:missing-name', 'https://a:b@github.com/a/b',
'https://192.0.2.10/device/path', 'keyword 192.0.2.5', 'x' * 513])
async def test_invalid_search_never_calls_network(tmp_path: Path, query: str) -> None:
http = PublisherHTTP()
async with Store(tmp_path) as store:
with pytest.raises(ValueError):
await Search(store, http).search(query)
assert not http.calls
async def test_foreign_cursor_never_calls_network(tmp_path: Path) -> None:
http = PublisherHTTP()
async with Store(tmp_path) as store:
with pytest.raises(ValueError, match='invalid_cursor'):
await Search(store, http).search('Fixture controller', cursor='not-a-cursor')
assert not http.calls