Files
vuln-mcp/tests/test_applicability.py
T
omar 25e90432d1
CI / Python 3.12 (push) Failing after 1m54s
CI / Python 3.13 (push) Failing after 2m1s
CI / Build and smoke-test image (push) Skipped
Ship advisory search MCP with direct and proxied networking, Docker and Gitea CI
- 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.
2026-11-28 10:06:59 +03:00

309 lines
16 KiB
Python

from __future__ import annotations
from pathlib import Path
import pytest
from vuln_mcp.config import Settings
from vuln_mcp.matching import Product, Verdict, make_asset, nvd_affected, parse_cpe, product_match, product_status
from vuln_mcp.models import AssetFacts, Doc
from vuln_mcp.search import Search
from vuln_mcp.sources.parsers import parse
from vuln_mcp.store import Store
from vuln_mcp.transport import HttpClients
CVE = 'CVE-2025-99999'
MODEL = 'fixture-controller'
VENDOR = 'example'
DAY = '2025-08-12'
CVE_URL = f'https://www.cve.org/CVERecord?id={CVE}'
NVD_URL = 'https://services.nvd.nist.gov/rest/json/cves/2.0'
@pytest.fixture
def anyio_backend() -> str:
return 'asyncio'
def _cve(versions: list[Product]) -> Doc:
return parse('cvelist', {
'dataType': 'CVE_RECORD', 'dataVersion': '5.1',
'cveMetadata': {'cveId': CVE, 'state': 'PUBLISHED', 'dateUpdated': DAY},
'containers': {'cna': {
'providerMetadata': {'shortName': 'Example CNA'},
'affected': [{'vendor': VENDOR, 'product': MODEL, 'versions': versions}],
}},
}, CVE_URL)
@pytest.mark.parametrize(('version', 'expected'), [
pytest.param('1.1.9', 'unknown', id='before-declared-start'),
pytest.param('1.2', 'affected', id='inclusive-intdot-start'),
pytest.param('1.9', 'affected', id='numeric-not-lexical-order'),
pytest.param('1.10', 'not_affected', id='change-applies-at-boundary'),
pytest.param('1.11', 'unknown', id='explicit-unknown-interval'),
pytest.param('1.12', 'affected', id='affected-again-at-inclusive-end'),
pytest.param('1.13', 'unknown', id='outside-inclusive-end'),
])
def test_cve_version_changes_are_scoped_to_declared_interval(version: str, expected: Verdict) -> None:
doc = _cve([{
'version': '1.2.0', 'status': 'affected', 'versionType': 'intdot', 'lessThanOrEqual': '1.12.0',
'changes': [
{'at': '1.10.0', 'status': 'unaffected'}, {'at': '1.11.0', 'status': 'unknown'},
{'at': '1.12.0', 'status': 'affected'},
],
}])
asset = make_asset('text', MODEL, AssetFacts(version=version))
assert product_status(doc.issues[0].products[0], asset) == expected
@pytest.mark.parametrize(('version_type', 'end', 'version', 'expected'), [
pytest.param('semver', '2.0.0', '2.0.0-rc.1', 'affected', id='prerelease-before-release'),
pytest.param('semver', '2.0.0', '2.0.0', 'unknown', id='exclusive-upper-bound'),
pytest.param('semver', '*', '1.2.0', 'affected', id='known-scheme-with-open-endpoints'),
pytest.param('semver', '*', '1.2', 'unknown', id='open-endpoints-still-require-valid-semver'),
pytest.param('custom', '*', '1.2.0', 'unknown', id='open-endpoints-do-not-validate-unknown-scheme'),
])
def test_cve_range_requires_understood_version_ordering(
version_type: str, end: str, version: str, expected: Verdict,
) -> None:
doc = _cve([{'version': '0', 'status': 'affected', 'versionType': version_type, 'lessThan': end}])
asset = make_asset('text', MODEL, AssetFacts(version=version))
assert product_status(doc.issues[0].products[0], asset) == expected
@pytest.mark.parametrize(('version', 'expected'), [
pytest.param('1.0.0-rc.1', 'affected', id='introduced-is-inclusive'),
pytest.param('1.0.0', 'fixed', id='explicit-fixed-release'),
pytest.param('1.0.0+other', 'unknown', id='no-fixed-assertion-for-another-build'),
pytest.param('1.5.0', 'unknown', id='not-all-subsequent-versions-are-fixed'),
pytest.param('2.5.0', 'affected', id='last-affected-is-inclusive'),
pytest.param('2.5.1', 'unknown', id='last-affected-is-not-fix'),
pytest.param('3.1.9', 'affected', id='affected-before-limit'),
pytest.param('3.2.0', 'unknown', id='limit-is-exclusive-and-not-fix'),
pytest.param('v3.1.9', 'unknown', id='strict-semver-does-not-accept-v-prefix'),
])
def test_osv_events_do_not_treat_later_releases_as_fixed(version: str, expected: Verdict) -> None:
product = {
'scheme': 'SEMVER', 'events': [
{'introduced': '1.0.0-rc.1'}, {'fixed': '1.0.0'},
{'introduced': '2.0.0'}, {'last_affected': '2.5.0'},
{'introduced': '3.0.0'}, {'limit': '3.2.0'},
],
}
assert product_status(product, make_asset('text', MODEL, AssetFacts(version=version))) == expected
@pytest.mark.parametrize(('ecosystem', 'version', 'listed', 'expected'), [
pytest.param('PyPI', '1!2.0.dev1', [], 'affected', id='pep-440-epoch-and-dev-release'),
pytest.param('PyPI', '2.0', [], 'unknown', id='epoch-zero-is-before-introduction'),
pytest.param('PyPI', '1!2.0rc1', [], 'fixed', id='pep-440-exact-fix'),
pytest.param('FixtureOS', '1!2.0.dev1', [], 'unknown', id='no-guessing-order-for-unknown-ecosystem'),
pytest.param('FixtureOS', '1!2.0.dev1', ['1!2.0.dev1'], 'affected', id='unknown-ecosystem-allows-exact-list'),
])
def test_osv_uses_ecosystem_order_only_when_supported(
ecosystem: str, version: str, listed: list[str], expected: Verdict,
) -> None:
product = {'status': 'affected', 'ecosystem': ecosystem, 'scheme': 'ECOSYSTEM', 'versions': listed,
'events': [{'introduced': '1!1.0'}, {'fixed': '1!2.0rc1'}]}
assert product_status(product, make_asset('text', MODEL, AssetFacts(version=version))) == expected
@pytest.mark.parametrize(('version', 'expected'), [
pytest.param('1.2', 'affected', id='percent-encoded-inclusive-bound'),
pytest.param('1.3.0', 'unknown', id='excluded-build'),
pytest.param('1.10.0', 'unknown', id='exclusive-numeric-upper-bound'),
pytest.param('1.4-hotfix', 'unknown', id='uncomparable-build'),
])
def test_intdot_constraints_intersect_instead_of_selecting_a_single_bound(version: str, expected: Verdict) -> None:
product = {'status': 'affected', 'scheme': 'INTDOT', 'range': 'vers:intdot/%3E%3D1.2|!=1.3|<1.10'}
assert product_status(product, make_asset('text', MODEL, AssetFacts(version=version))) == expected
@pytest.mark.parametrize(('query', 'expected'), [
pytest.param('pkg:generic/fixture-controller@1.2?arch=arm64&flavor=full', True, id='required-qualifier-with-extra'),
pytest.param('pkg:generic/fixture-controller@1.2?arch=amd64', False, id='wrong-architecture-qualifier'),
pytest.param('pkg:generic/fixture-controller@1.2', False, id='missing-required-qualifier'),
pytest.param('pkg:npm/fixture-controller@1.2?arch=arm64', False, id='same-name-different-package-type'),
])
def test_purl_match_requires_candidate_qualifiers(query: str, expected: bool) -> None:
product = {'name': MODEL, 'purl': f'pkg:generic/{MODEL}?arch=arm64'}
asset = make_asset('purl', query, AssetFacts(version='9.9'))
assert asset.version == '1.2'
assert product_match(product, asset) == (expected, set())
def test_percent_encoded_purl_scope_does_not_match_a_bare_or_differently_scoped_name() -> None:
asset = make_asset('purl', f'pkg:npm/%40fixture/{MODEL}@1.2.3', None)
assert product_match({'purl': f'pkg:npm/%40fixture/{MODEL}', 'name': MODEL}, asset) == (True, set())
assert product_match({'purl': f'pkg:npm/%40another/{MODEL}', 'name': MODEL}, asset) == (False, set())
assert product_match({'name': MODEL}, asset) == (False, set())
assert product_match({'name': f'@fixture/{MODEL}', 'ecosystem': 'npm'}, asset) == (True, set())
@pytest.mark.parametrize(('facts', 'expected'), [
pytest.param(AssetFacts(architecture='ARM64', revision='R1'), (True, set()), id='architecture-alias'),
pytest.param(AssetFacts(), (True, {'architecture', 'revision'}), id='missing-qualifiers'),
pytest.param(AssetFacts(architecture='x64', revision='R1'), (False, set()), id='wrong-architecture'),
pytest.param(AssetFacts(architecture='arm64', revision='R2'), (False, set()), id='wrong-revision'),
pytest.param(AssetFacts(vendor='other', architecture='arm64', revision='R1'), (False, set()), id='wrong-vendor'),
])
def test_product_identity_is_separate_from_required_asset_qualifiers(
facts: AssetFacts, expected: tuple[bool, set[str]],
) -> None:
product = {'name': MODEL, 'vendor': VENDOR, 'architecture': 'aarch64', 'revision': 'r1'}
assert product_match(product, make_asset('text', MODEL, facts)) == expected
def _cpe(version: str = '*', *, name: str = MODEL, part: str = 'a', arch: str = '*') -> str:
return f'cpe:2.3:{part}:{VENDOR}:{name}:{version}:*:*:*:*:*:{arch}:*'
def _nvd(configurations: list[Product]) -> Doc:
return parse('nvd', {'id': CVE, 'vulnStatus': 'Analyzed', 'lastModified': DAY,
'configurations': configurations}, NVD_URL)
def _leaf(criteria: str, *, vulnerable: bool, **bounds: str) -> Product:
return {'criteria': criteria, 'vulnerable': vulnerable, **bounds}
@pytest.mark.parametrize(('version', 'key', 'expected'), [
pytest.param('1.2.0', 'versionStartIncluding', True, id='inclusive-start'),
pytest.param('1.2.0', 'versionStartExcluding', False, id='exclusive-start'),
pytest.param('1.2.0', 'versionEndIncluding', True, id='inclusive-end'),
pytest.param('1.2.0', 'versionEndExcluding', False, id='exclusive-end'),
pytest.param('1.10', 'versionStartIncluding', True, id='numeric-not-lexical-order'),
pytest.param('1.2p1', 'versionEndIncluding', False, id='unknown-version-order-not-positive'),
])
def test_nvd_version_boundaries_are_not_lexicographic(version: str, key: str, expected: bool) -> None:
configurations = [{'cpeMatch': [_leaf(_cpe(), vulnerable=True, **{key: '1.2'})]}]
issue = _nvd(configurations).issues[0]
assert nvd_affected(configurations, make_asset('cpe', _cpe(version), None), issue.products) is expected
@pytest.mark.parametrize(('operator', 'negate', 'conditions', 'expected'), [
pytest.param('AND', False, ['1.2'], True, id='known-platform-constraint-is-satisfied'),
pytest.param('AND', False, ['*other*'], False, id='unknown-platform-constraint-does-not-prove-and'),
pytest.param('AND', True, ['2.0', '1.2'], True, id='negated-and-with-a-false-operand'),
pytest.param('OR', True, ['2.0', '1.2'], False, id='negated-or-with-a-true-operand'),
pytest.param('OR', True, ['2.0', '*other*'], False, id='negating-unknown-does-not-make-it-true'),
])
def test_nvd_nested_platform_logic(
operator: str, negate: bool, conditions: list[str], expected: bool,
) -> None:
configurations = [{'operator': 'AND', 'nodes': [
{'operator': 'OR', 'cpeMatch': [_leaf(_cpe('1.2'), vulnerable=True)]},
{'operator': operator, 'negate': negate,
'cpeMatch': [_leaf(_cpe(version), vulnerable=False) for version in conditions]},
]}]
issue = _nvd(configurations).issues[0]
assert nvd_affected(configurations, make_asset('cpe', _cpe('1.2'), None), issue.products) is expected
def test_nvd_requires_a_positive_affected_leaf_not_just_a_satisfied_condition() -> None:
configurations = [{'operator': 'OR', 'nodes': [
{'cpeMatch': [_leaf(_cpe('1.2'), vulnerable=False)]},
{'negate': True, 'cpeMatch': [_leaf(_cpe('2.0'), vulnerable=True)]},
]}]
issue = _nvd(configurations).issues[0]
assert not nvd_affected(configurations, make_asset('cpe', _cpe('1.2'), None), issue.products)
def test_nvd_or_can_confirm_product_without_confirming_another_platform_branch() -> None:
configurations = [{'operator': 'OR', 'cpeMatch': [
_leaf(_cpe('1.2'), vulnerable=True), _leaf(_cpe(name='platform', part='o'), vulnerable=False),
]}]
issue = _nvd(configurations).issues[0]
assert nvd_affected(configurations, make_asset('cpe', _cpe('1.2'), None), issue.products)
def test_nvd_does_not_infer_a_cpe_from_an_ambiguous_product_name() -> None:
application = {'cpeMatch': [_leaf(_cpe(), vulnerable=True)]}
hardware = {'cpeMatch': [_leaf(_cpe('2.0', part='h'), vulnerable=True)]}
asset = make_asset('text', MODEL, AssetFacts(vendor=VENDOR, version='1.2'))
assert nvd_affected([application], asset, _nvd([application]).issues[0].products)
combined = [application, hardware]
assert not nvd_affected(combined, asset, _nvd(combined).issues[0].products)
def test_escaped_cpe_separators_and_literal_wildcard_survive_matching() -> None:
query = _cpe(r'build\*', name=r'fixture\:controller', arch='x64')
criteria = _cpe(r'build\*', name=r'fixture\:controller', arch='amd64')
configurations = [{'cpeMatch': [_leaf(criteria, vulnerable=True)]}]
issue = _nvd(configurations).issues[0]
asset = make_asset('cpe', query, None)
assert asset.product == 'fixture:controller'
assert asset.version == 'build*'
assert product_match(issue.products[0], asset) == (True, set())
assert nvd_affected(configurations, asset, issue.products)
assert not nvd_affected(configurations, make_asset('cpe', query.replace('x64', 'arm64'), None), issue.products)
def test_explicit_architecture_can_resolve_an_unspecified_cpe_architecture() -> None:
configurations = [{'cpeMatch': [_leaf(_cpe('1.2', arch='aarch64'), vulnerable=True)]}]
issue = _nvd(configurations).issues[0]
query = _cpe('1.2')
assert not nvd_affected(configurations, make_asset('cpe', query, None), issue.products)
assert nvd_affected(configurations, make_asset('cpe', query, AssetFacts(architecture='arm64')), issue.products)
def test_backslash_pair_does_not_escape_an_unbound_cpe_wildcard() -> None:
wildcard = make_asset('cpe', _cpe(r'build\\*'), None)
escaped = make_asset('cpe', _cpe(r'build\\\*'), None)
assert wildcard.version is None
assert escaped.version == r'build\*'
criteria = _cpe('1.2', arch=r'board\*')
configurations = [{'cpeMatch': [_leaf(criteria, vulnerable=True)]}]
issue = _nvd(configurations).issues[0]
assert not nvd_affected(configurations, make_asset('cpe', _cpe('1.2', arch='board*'), None), issue.products)
@pytest.mark.parametrize('value', [
pytest.param(_cpe().replace('2.3', '2.2'), id='wrong-binding'),
pytest.param(_cpe(name=r'fixture\c'), id='escaped-alphanumeric'),
pytest.param(_cpe(name='fixture/controller'), id='unescaped-reserved-character'),
pytest.param(_cpe() + '\\', id='dangling-escape'),
])
def test_malformed_cpe_does_not_turn_into_a_broader_match(value: str) -> None:
with pytest.raises(ValueError, match='invalid_cpe'):
parse_cpe(value)
def _vendor_advisory() -> Doc:
return parse('siemens', {
'document': {'csaf_version': '2.0', 'title': 'Fixture build', 'publisher': {'name': 'Fixture Vendor'},
'tracking': {'id': 'SSA-999999', 'current_release_date': DAY}},
'product_tree': {'branches': [
{'category': 'product_name', 'name': MODEL, 'branches': [
{'category': 'architecture', 'name': 'aarch64', 'branches': [
{'category': 'product_version', 'name': '1.2', 'product': {'name': MODEL, 'product_id': 'P1'}},
]},
]},
]},
'vulnerabilities': [{'cve': CVE, 'product_status': {'known_not_affected': ['P1']}}],
}, 'https://cert-portal.siemens.com/productcert/csaf/ssa-999999.json')
@pytest.mark.anyio
@pytest.mark.parametrize(('architecture', 'expected'), [
pytest.param('arm64', 'not_affected', id='matching-vendor-build-takes-precedence'),
pytest.param('x64', 'unknown', id='another-architecture-does-not-break-peer-conflict'),
pytest.param(None, 'unknown', id='missing-architecture-does-not-break-peer-conflict'),
])
async def test_search_publisher_conflict_and_matching_vendor_build(
tmp_path: Path, architecture: str | None, expected: Verdict,
) -> None:
cve = _cve([{'version': '1.2', 'status': 'unaffected'}])
nvd = _nvd([{'cpeMatch': [_leaf(_cpe('1.2'), vulnerable=True)]}])
async with Store(tmp_path) as store, HttpClients(Settings(tmp_path), store) as clients:
await store.cache([cve, nvd, _vendor_advisory()])
page = await Search(store, clients.live).search(
CVE, AssetFacts(product=MODEL, vendor=VENDOR, version='1.2', architecture=architecture),
)
(hit,) = page.hits
assert hit.applicability == expected
assert {item['via'] for item in hit.evidence} == {'cvelist', 'nvd', 'siemens'}
assert hit.missing_fields == (['architecture'] if architecture is None else [])