Files
vuln-mcp/tests/test_guide_catalog.py
T
omar 5d1e5d2cac
CI / Python 3.13 (push) Successful in 28s
CI / Python 3.12 (push) Successful in 52s
CI / Build and smoke-test image (push) Successful in 14s
Ship an English-only offline ASVS catalog with searchable MCP guides
2026-11-28 17:19:58 +03:00

197 lines
8.3 KiB
Python

import pytest
from vuln_mcp import guide_catalog
from vuln_mcp.guide_catalog import GuideCatalog
@pytest.fixture(scope="module")
def catalog() -> GuideCatalog:
return GuideCatalog()
def test_empty_search_has_english_navigation_and_working_suggestions(catalog):
page = catalog.search(limit=3)
assert page["mode"] == "browse"
assert page["total"] > 3
assert page["next_offset"] == 3
assert len(page["topics"]) == 3
assert len(page["items"]) <= 3
assert [(topic["id"], topic["title"]) for topic in page["topics"]] == [
("injection", "Injection and encoding"),
("authorization", "Authorization and access control"),
("authentication", "Authentication and passwords"),
]
for topic in page["topics"]:
assert topic.keys() == {"id", "title", "count", "starter_ids"}
assert topic["starter_ids"] and topic["count"] >= len(topic["starter_ids"])
for slug in page["starter_ids"]:
assert catalog.get(slug)["kind"] == "manual"
suggestion = page["next_call"]
assert suggestion["name"] == "search_guides"
assert catalog.search(**suggestion["arguments"])["mode"] == "results"
second = catalog.search(offset=page["next_offset"], limit=3)
assert not {topic["id"] for topic in page["topics"]} & {topic["id"] for topic in second["topics"]}
@pytest.mark.parametrize(
("query", "expected"),
[
(" SQL-Injection ", "sql-injection"),
("CwE-89", "sql-injection"),
("v5.0.0-1.2.4", "v5.0.0-1.2.4"),
("V1.2.4", "v5.0.0-1.2.4"),
("password reset", "password-reset"),
("parameterized HQL and Cypher queries", "v5.0.0-1.2.4"),
("object-level authorization", "object-authorization"),
],
)
def test_exact_and_natural_language_ranking(catalog, query, expected):
page = catalog.search(query, limit=1)
assert page["mode"] == "results"
assert [item["id"] for item in page["items"]] == [expected]
assert not {"markdown", "text"} & page["items"][0].keys()
def test_query_and_topic_both_filter_rows(catalog):
query = "v5.0.0-1.2.4"
assert catalog.search(query, topic="INJECTION")["total"] == 1
for page in [catalog.search(query, topic="authorization"), catalog.search("whollyunsourcedphrase")]:
assert page["items"] == []
assert page["total"] == 0
assert page["next_offset"] is None
def test_page_continuation_keeps_query_topic_and_rank(catalog):
page = catalog.search("authentication", topic="authentication", limit=2)
assert page["total"] > 4
assert page["next_offset"] == 2
assert page["next_call"] == {
"name": "search_guides",
"arguments": {"query": "authentication", "topic": "authentication", "offset": 2, "limit": 2},
}
second = catalog.search(**page["next_call"]["arguments"])
joined = catalog.search("authentication", topic="authentication", limit=4)
assert page["items"] + second["items"] == joined["items"]
assert second["total"] == page["total"]
last = catalog.search("authentication", topic="authentication", offset=page["total"] - 1, limit=2)
assert len(last["items"]) == 1
assert last["next_offset"] is None
assert last["next_call"] == {"name": "get_guide", "arguments": {"id": last["items"][0]["id"]}}
def test_topic_browsing_covers_complete_versioned_corpus(catalog):
overview = catalog.search(limit=25)
controls, manuals = set(), set()
for topic in overview["topics"]:
offset = 0
count = 0
while offset is not None:
page = catalog.search(topic=topic["id"], limit=25, offset=offset)
assert page["total"] == topic["count"]
assert 0 < len(page["items"]) <= 25
for item in page["items"]:
assert item["topic"] == topic["id"]
if item["kind"] == "asvs":
assert item["id"] not in controls
controls.add(item["id"])
else:
assert item["kind"] == "manual" and item["id"] not in manuals
manuals.add(item["id"])
count += 1
offset = page["next_offset"]
assert count == topic["count"]
assert len(controls) == 345
assert len(manuals) == 17
def test_manual_detail_preserves_existing_markdown_and_citation(catalog):
manual = catalog.get("sql-injection")
assert manual["status"] == "found"
assert manual["kind"] == "manual"
assert manual["uri"] == "vuln://guides/sql-injection"
assert manual["cwe"] == "CWE-89"
assert manual["title"] == "SQL Injection - CWE-89"
assert manual["markdown"].startswith("# SQL Injection - CWE-89\n")
assert "**Local check.**" in manual["markdown"]
assert manual["source"]["url"] == "https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html"
assert "level" not in manual and "text" not in manual
assert catalog.get("CWE-89") == manual
def test_normative_detail_has_versioned_english_citation_and_related_manual(catalog):
control = catalog.get("ASVS V1.2.4")
assert control["status"] == "found"
assert control["id"] == "v5.0.0-1.2.4"
assert control["kind"] == "asvs"
assert control["requirement_id"] == "V1.2.4"
assert control["version"] == "5.0.0"
assert control["license"] == "CC-BY-SA-4.0"
assert control["level"] == 1
assert control["chapter"]["id"] == "V1"
assert control["section"] == {"id": "V1.2", "title": "Injection Prevention"}
assert "use parameterized queries" in control["text"]
assert control["title"] == "Injection Prevention"
assert control["text"].isascii() and control["summary"].isascii()
assert control["source"].keys() == {"name", "url"}
assert control["source"]["url"].endswith("/OWASP_Application_Security_Verification_Standard_5.0.0_en.csv")
assert {link["id"] for link in control["related_manuals"]} == {"sql-injection"}
assert "markdown" not in control
def test_manual_detail_links_related_packaged_manuals(catalog):
related = catalog.get("object-authorization")["related_manuals"]
assignment = catalog.get("mass-assignment")
assert related == [{"id": "mass-assignment", "title": assignment["title"], "uri": assignment["uri"]}]
def test_asvs_csv_skips_empty_lines_without_losing_records(tmp_path):
csv_path = tmp_path / "asvs.csv"
row = "V1,Encoding and Sanitization,V1.2,Injection Prevention,V1.2.4,Use parameterized queries.,1"
csv_path.write_text(
"chapter_id,chapter_name,section_id,section_name,req_id,req_description,L\n\n"
f"{row}\n\n",
encoding="ascii",
)
assert list(guide_catalog._control_rows(csv_path)) == [row.split(",")]
@pytest.mark.parametrize("row", [",,,,,,", "V1,Encoding", "V1,Encoding,V1.2,Injection Prevention,V1.2.4, ,1"])
def test_asvs_csv_does_not_skip_malformed_records(tmp_path, row):
csv_path = tmp_path / "asvs.csv"
csv_path.write_text(
f"chapter_id,chapter_name,section_id,section_name,req_id,req_description,L\n{row}\n",
encoding="ascii",
)
with pytest.raises(ValueError, match="Incomplete bundled ASVS row"):
list(guide_catalog._control_rows(csv_path))
@pytest.mark.parametrize(
"arguments",
[
{"query": None}, {"query": "a" * 513}, {"query": "nul\0character"}, {"query": "../private"},
{"topic": "../guides"}, {"topic": ""}, {"topic": 7}, {"topic": "no-such-topic"},
{"offset": -1}, {"offset": True}, {"offset": 1.2},
{"limit": 0}, {"limit": 26}, {"limit": False}, {"limit": "4"},
],
)
def test_invalid_raw_search_input_is_rejected(catalog, arguments):
with pytest.raises(ValueError):
catalog.search(**arguments)
def test_traversal_unknown_and_old_version_do_not_read_files(catalog, monkeypatch):
def unexpected_resource_read(*args, **kwargs):
pytest.fail("catalogue performed a file lookup after initialization")
monkeypatch.setattr(guide_catalog, "files", unexpected_resource_read)
for identifier in ["../pyproject.toml", "..\\pyproject.toml", "%2e%2e%2f", "C:/secret", "pa\u017fsword-reset", "", 123, "a" * 101]:
with pytest.raises(ValueError):
catalog.get(identifier)
for identifier in ["nonexistent-slug", "CWE-123456789", "v4.0.3-1.2.4", "V99.9.9"]:
assert catalog.get(identifier) == {"status": "not_found", "id": identifier}
assert catalog.search("v4.0.3-1.2.4")["items"] == []
assert catalog.get("V1.2.4")["status"] == "found"