Files
vuln-mcp/tests/test_nuclei.py
T
omar dbcd91eae0
CI / Python 3.12 (push) Successful in 37s
CI / Python 3.13 (push) Successful in 48s
CI / Build and smoke-test image (push) Successful in 11s
Select published exploit artifacts and report exploitation preconditions
2026-11-28 18:50:52 +03:00

167 lines
7.1 KiB
Python

"""Detection-template coverage from the public nuclei-templates repository."""
from __future__ import annotations
from collections import deque
from collections.abc import Mapping
from time import monotonic
import pytest
from vuln_mcp.sources.feed_nuclei import _PROTOCOLS, allowed, lookup_nuclei
from vuln_mcp.transport import HttpError
pytestmark = pytest.mark.anyio
CVE = "CVE-2021-41773"
BASE = "https://raw.githubusercontent.com/projectdiscovery/nuclei-templates/main/"
def url(protocol: str, cve: str = CVE) -> str:
return f"{BASE}{protocol}/cves/{cve[4:8]}/{cve}.yaml"
def template(cve: str = CVE, name: str = "Apache 2.4.49 - Path Traversal") -> bytes:
return (f"id: {cve}\n\ninfo:\n name: {name}\n author: daffainfo\n severity: high\n description: |\n"
f" line one\n\n line two\n").encode()
class Wire:
def __init__(self) -> None:
self.replies: dict[str, deque[tuple[int, bytes, str | None]]] = {}
self.requests: list[tuple[str, float]] = []
def put(self, address: str, body: bytes = b"", *, status: int = 200,
retry_at: str | None = None) -> None:
self.replies.setdefault(address, deque()).append((status, body, retry_at))
async def bytes(
self, source: str, address: str, *, deadline: float, limit: int,
) -> tuple[bytes, Mapping[str, str]]:
assert source == "nuclei"
self.requests.append((address, deadline))
queued = self.replies.get(address)
status, body, retry_at = queued.popleft() if queued else (404, b"", None)
if status == 404:
raise HttpError("not_found")
if status != 200:
raise HttpError("unavailable" if status >= 500 else "access_denied", retry_at)
assert len(body) <= limit
return body, {"cache-control": "max-age=300"}
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
def refs(page) -> list[dict[str, str]]:
assert len(page.docs) == 1
[issue] = page.docs[0].issues
return issue.facts["exploit_refs"]
async def test_http_template_is_a_detection_ref() -> None:
wire = Wire()
body = (b"---\nid: CVE-2021-41773\ninfo:\n name: \"Apache: Path Traversal\"\n"
b" severity: high\n")
wire.put(url("http"), body)
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
assert page.status.status == "ok" and page.continuation is None
[doc] = page.docs
assert (doc.source, doc.native_id, doc.publisher) == ("nuclei", CVE, "ProjectDiscovery nuclei-templates")
assert doc.url == url("http")
assert refs(page) == [{
"type": "detection_template", "url": url("http"), "protocol": "http",
"template_name": "Apache: Path Traversal",
}]
assert [address for address, _ in wire.requests] == [url("http")]
async def test_stops_at_first_protocol_hit() -> None:
wire = Wire()
wire.put(url("http"), status=404)
wire.put(url("network"), template(), status=200)
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
assert [address for address, _ in wire.requests] == [url("http"), url("network")]
assert refs(page)[0]["protocol"] == "network"
assert refs(page)[0]["template_name"] == "Apache 2.4.49 - Path Traversal"
async def test_miss_probes_every_protocol_once_then_succeeds_empty() -> None:
wire = Wire()
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 30)
assert page.docs == [] and page.status.status == "ok"
assert page.status.as_of is not None
assert [address for address, _ in wire.requests] == [url(protocol) for protocol in _PROTOCOLS]
assert len(wire.requests) == 4
assert _PROTOCOLS == ("http", "network", "javascript", "headless")
async def test_identifier_mismatch_and_malformed_yaml_are_skipped() -> None:
wire = Wire()
wire.put(url("http"), template("CVE-1999-0001"))
wire.put(url("network"), b"\xff\xfe id: CVE-2021-41773\n")
wire.put(url("javascript"), b"info:\n name: No identifier\n")
wire.put(url("headless"), template(name="Real template"))
page = await lookup_nuclei("id", CVE.lower(), http=wire, deadline=monotonic() + 5)
assert len(wire.requests) == 4
assert refs(page)[0]["protocol"] == "headless"
assert page.docs[0].native_id == CVE
assert url("headless") in page.docs[0].url
async def test_missing_name_falls_back_to_identifier() -> None:
wire = Wire()
wire.put(url("http"), b"id: CVE-2021-41773\ninfo:\n severity: high\n")
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
assert refs(page)[0]["template_name"] == CVE
async def test_expired_deadline_makes_no_request() -> None:
wire = Wire()
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() - 1)
assert wire.requests == [] and page.docs == []
assert page.status.status == "timeout"
async def test_error_stops_probing_and_keeps_retry_hint() -> None:
wire = Wire()
wire.put(url("http"), status=404)
wire.put(url("network"), status=500, retry_at="2026-01-01T00:00:00+00:00")
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
assert page.docs == [] and page.status.status == "unavailable"
assert page.status.retry_at == "2026-01-01T00:00:00+00:00"
assert [address for address, _ in wire.requests] == [url("http"), url("network")]
async def test_access_denied_is_not_treated_as_a_miss() -> None:
wire = Wire()
wire.put(url("http"), status=403)
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
assert page.status.status == "access_denied" and len(wire.requests) == 1
async def test_rejects_wrong_kind_and_malformed_identifier() -> None:
wire = Wire()
for kind, value in (("text", CVE), ("id", "CVE-2021-417"), ("id", "GHSA-xxxx"), ("id", 7)):
page = await lookup_nuclei(kind, value, http=wire, deadline=monotonic() + 5)
assert page.status.status == "invalid_data", (kind, value)
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5, continuation="1")
assert page.status.status == "invalid_data"
assert wire.requests == []
def test_allowed_paths_cover_only_protocol_cve_files() -> None:
for protocol in _PROTOCOLS:
path = f"/projectdiscovery/nuclei-templates/main/{protocol}/cves/2021/{CVE}.yaml"
assert allowed("raw.githubusercontent.com", path, live=True)
assert not allowed("raw.githubusercontent.com",
f"/projectdiscovery/nuclei-templates/main/dns/cves/2021/{CVE}.yaml", live=True)
assert not allowed("raw.githubusercontent.com",
f"/projectdiscovery/nuclei-templates/main/file/cves/2021/{CVE}.yaml", live=True)
assert not allowed("raw.githubusercontent.com",
"/projectdiscovery/nuclei-templates/main/http/cves/2021/CVE-2021-417.yaml", live=True)
assert not allowed("raw.githubusercontent.com",
f"/projectdiscovery/nuclei-templates/main/http/cves/2021/{CVE}.yaml", live=False)
assert not allowed("example.invalid",
f"/projectdiscovery/nuclei-templates/main/http/cves/2021/{CVE}.yaml", live=True)