hermes-agent/tests/tools/test_osv_check.py
Teknium 39975613b1
test: prune wave 2 + speed fixes — 28,106 → 19,757 test functions, suite wall 315s → 294s
Second, deeper pass over tools/gateway/hermes_cli plus first pass over
the trees wave 1 missed (acp, acp_adapter, skills, computer_use, docker,
dashboard, conformance, monitoring, secret_sources, hermes_state,
providers). Same rubric as wave 1 (AGENTS.md test policy); security,
alternation/caching invariants, issue-number regressions, and E2E kept.

Real test-quality fixes found and rooted out along the way:
- tests/tools/test_command_guards.py made real auxiliary-LLM HTTPS calls
  (DEFAULT_CONFIG smart-approval leaked in) — pinned approval
  mode=manual via autouse fixture: 17.4s → 0.4s.
- test_model_switch_custom_providers.py / test_user_providers_model_switch.py
  silently probed live provider catalogs (~2s/test) — stubbed
  cached_provider_model_ids/provider_model_ids/fetch_api_models.
- test_telegram_noise_filter.py: 15-platform copy-paste matrix over
  shared gateway.run logic → 3 representative platforms (55s → 3.9s).
- test_gateway_shutdown.py: stop()'s 5s interrupt-deadline loop spun on
  MagicMock agents — interrupt.side_effect now clears _running_agents
  (22s → 1.0s).
- test_gateway_inactivity_timeout.py poll-harness timings shrunk 3-5x
  (24s → 1.1s); test_mcp_stability.py backoff/SIGTERM-grace sleeps
  patched (15.4s → 2.5s); test_async_delegation.py negative-drain wait
  5s → 0.5s.
- test_telegram_init_deadline.py: loop-block margin restored to 1.0s
  with rationale comment — the watchdog-dump assertion needs the loop
  blocked well past deadline+grace under parallel load (flaked once in
  the 40-worker verification run at a 0.2s margin).

Verification: full hermetic suite via scripts/run_tests.sh —
2,438 files, 21,718 tests passed, 0 failed, 293.9s wall.
Suite totals vs original baseline: 46,820 → 19,757 test functions
(−57.8%), wall 583.5s → 293.9s (−50%), subprocess CPU 13,564s → 11,623s.
2026-07-29 13:39:40 -07:00

140 lines
4.9 KiB
Python

"""Tests for OSV malware check on MCP extension packages."""
import json
import pytest
from unittest.mock import patch, MagicMock
from tools.osv_check import (
check_package_for_malware,
_infer_ecosystem,
_parse_package_from_args,
_parse_npm_package,
_parse_pypi_package,
_query_osv,
)
class TestInferEcosystem:
def test_npx(self):
assert _infer_ecosystem("npx") == "npm"
assert _infer_ecosystem("/usr/bin/npx") == "npm"
def test_unknown(self):
assert _infer_ecosystem("node") is None
assert _infer_ecosystem("python") is None
assert _infer_ecosystem("/bin/bash") is None
class TestParseNpmPackage:
def test_simple(self):
assert _parse_npm_package("react") == ("react", None)
def test_latest_ignored(self):
assert _parse_npm_package("react@latest") == ("react", None)
class TestParsePypiPackage:
def test_simple(self):
assert _parse_pypi_package("requests") == ("requests", None)
def test_extras_no_version(self):
assert _parse_pypi_package("mcp[cli]") == ("mcp", None)
class TestParsePackageFromArgs:
def test_npm_skips_flags(self):
name, ver = _parse_package_from_args(["-y", "@scope/pkg@1.0"], "npm")
assert name == "@scope/pkg"
assert ver == "1.0"
def test_pypi_skips_flags(self):
name, ver = _parse_package_from_args(["--from", "mcp[cli]"], "PyPI")
# --from is a flag, mcp[cli] is the package
# Actually --from is a flag so it gets skipped, mcp[cli] is found
assert name == "mcp"
def test_plain_positional_still_works(self):
# Regression guard: bare positional with no --package flag is the pkg.
name, ver = _parse_package_from_args(["-y", "react@18.3.1"], "npm")
assert name == "react"
assert ver == "18.3.1"
class TestCheckPackageForMalware:
def test_clean_package(self):
"""Clean package returns None (allow)."""
mock_response = MagicMock()
mock_response.read.return_value = json.dumps({"vulns": []}).encode()
mock_response.__enter__ = lambda s: s
mock_response.__exit__ = MagicMock(return_value=False)
with patch("tools.osv_check.urllib.request.urlopen", return_value=mock_response):
result = check_package_for_malware("npx", ["-y", "@modelcontextprotocol/server-filesystem"])
assert result is None
def test_malware_blocked(self):
"""Known malware package returns error string."""
mock_response = MagicMock()
mock_response.read.return_value = json.dumps({
"vulns": [
{"id": "MAL-2023-7938", "summary": "Malicious code in evil-pkg"},
{"id": "CVE-2023-1234", "summary": "Regular vulnerability"}, # should be filtered
]
}).encode()
mock_response.__enter__ = lambda s: s
mock_response.__exit__ = MagicMock(return_value=False)
with patch("tools.osv_check.urllib.request.urlopen", return_value=mock_response):
result = check_package_for_malware("npx", ["evil-pkg"])
assert result is not None
assert "BLOCKED" in result
assert "MAL-2023-7938" in result
assert "CVE-2023-1234" not in result # regular CVEs filtered
def test_uvx_pypi(self):
"""uvx commands check PyPI ecosystem."""
mock_response = MagicMock()
mock_response.read.return_value = json.dumps({"vulns": []}).encode()
mock_response.__enter__ = lambda s: s
mock_response.__exit__ = MagicMock(return_value=False)
with patch("tools.osv_check.urllib.request.urlopen", return_value=mock_response) as mock_url:
check_package_for_malware("uvx", ["mcp-server-fetch"])
# Verify PyPI ecosystem was sent
call_data = json.loads(mock_url.call_args[0][0].data)
assert call_data["package"]["ecosystem"] == "PyPI"
assert call_data["package"]["name"] == "mcp-server-fetch"
class TestLiveOsvQuery:
"""Live integration test against the real OSV API. Skipped if offline."""
@pytest.mark.skipif(
not pytest.importorskip("urllib.request", reason="no network"),
reason="network required",
)
def test_known_malware_package(self):
"""node-hide-console-windows has a real MAL- advisory."""
try:
result = _query_osv("node-hide-console-windows", "npm")
assert len(result) >= 1
assert result[0]["id"].startswith("MAL-")
except Exception:
pytest.skip("OSV API unreachable")
@pytest.mark.skipif(
not pytest.importorskip("urllib.request", reason="no network"),
reason="network required",
)
def test_clean_package(self):
"""react should have zero MAL- advisories."""
try:
result = _query_osv("react", "npm")
assert len(result) == 0
except Exception:
pytest.skip("OSV API unreachable")