From f91ea7de23c0d64357c4d8ce72c13e836dcc3757 Mon Sep 17 00:00:00 2001 From: RejectModders Date: Sat, 28 Nov 2026 20:59:48 -0600 Subject: [PATCH 1/3] feat!: follow background scans and read the v3 results scan() and scan_crawl() now start the job, poll it and return the finished result. client.scans starts, reports, waits for and cancels scans. An unfinished or failed scan raises, so it can never read as a clean one. Results and findings match what the server sends, keep unknown fields in raw, and show what was not checked or was marked a false positive. An unfamiliar severity is "unknown" instead of "info". Scanner names are checked before sending, because older servers run nothing for a misspelt one. Targets without a scheme are accepted. --- tests/live/test_live.py | 191 ++++---------- tests/samples.py | 109 ++++++++ tests/test_client.py | 37 --- tests/test_models.py | 105 ++++++-- tests/test_replies.py | 50 ++-- tests/test_scans.py | 365 ++++++++++++++++++++++++++ tests/test_url_validation.py | 19 +- vulnradar/__init__.py | 16 +- vulnradar/client.py | 80 ++++-- vulnradar/constants.py | 16 ++ vulnradar/enums.py | 37 +++ vulnradar/exceptions.py | 34 ++- vulnradar/models/__init__.py | 6 +- vulnradar/models/crawl.py | 63 ++--- vulnradar/models/fields.py | 52 ++++ vulnradar/models/findings.py | 73 +++--- vulnradar/models/scan_result.py | 81 +++--- vulnradar/models/scan_status.py | 75 ++++++ vulnradar/replies.py | 16 -- vulnradar/services/__init__.py | 5 +- vulnradar/services/crawl_service.py | 35 --- vulnradar/services/history_service.py | 11 +- vulnradar/services/scan_service.py | 207 +++++++++++++-- vulnradar/utils/scan_id.py | 18 ++ vulnradar/utils/url_validation.py | 71 ++--- 25 files changed, 1312 insertions(+), 460 deletions(-) create mode 100644 tests/samples.py create mode 100644 tests/test_scans.py create mode 100644 vulnradar/models/fields.py create mode 100644 vulnradar/models/scan_status.py delete mode 100644 vulnradar/services/crawl_service.py create mode 100644 vulnradar/utils/scan_id.py diff --git a/tests/live/test_live.py b/tests/live/test_live.py index bbb3783..d609e5b 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -1,187 +1,112 @@ from __future__ import annotations from datetime import datetime -from typing import Any import pytest from vulnradar import ( CrawlResult, - DiscoveryResult, - FindingTypesResult, NotFoundError, + ScanFailedError, + Scanner, ScanResult, Severity, - VersionInfo, VulnRadar, ) pytestmark = pytest.mark.live +SCANNERS = [Scanner.HEADERS, Scanner.SSL] -def _assert_summary(summary: Any) -> None: - assert hasattr(summary, "critical") - assert hasattr(summary, "high") - assert hasattr(summary, "medium") - assert hasattr(summary, "low") - assert hasattr(summary, "info") - assert hasattr(summary, "total") - assert summary.total >= 0 - -@pytest.fixture(scope="module") -def scan_for_history(client: VulnRadar, target_url: str, created_scan_ids: list[int]) -> ScanResult: - result = client.scan(target_url, scanners=["headers", "ssl"]) - assert result.scan_history_id is not None - created_scan_ids.append(result.scan_history_id) - return result +def _assert_finished(result: ScanResult) -> None: + assert result.url + assert isinstance(result.scanned_at, datetime) + assert result.duration_ms is not None + assert result.summary.total >= 0 + for finding in result.findings: + assert finding.id + assert finding.title + assert finding.severity is not Severity.UNKNOWN @pytest.fixture(scope="module") -def discovered_urls(client: VulnRadar, target_url: str) -> DiscoveryResult: - result = client.discover_urls(target_url) - assert isinstance(result, DiscoveryResult) - assert result.total >= 0 - assert isinstance(result.urls, list) - return result +def finished_scan(client: VulnRadar, target_url: str, created_scan_ids: list[int]) -> ScanResult: + job = client.scans.start(target_url, scanners=SCANNERS, public=False) + created_scan_ids.append(job.id) + return client.scans.wait(job.id, timeout=360) -def test_endpoint_version_public(client: VulnRadar) -> None: +def test_version(client: VulnRadar) -> None: result = client.version() - assert isinstance(result, VersionInfo) assert result.current - assert result.latest assert result.engine - assert result.status in {"up-to-date", "behind", "ahead"} -def test_endpoint_finding_types_public(client: VulnRadar) -> None: - result = client.metadata.finding_types() +def test_finding_types(client: VulnRadar) -> None: + catalog = client.metadata.finding_types() - assert isinstance(result, FindingTypesResult) - assert result.count >= 1 - assert len(result.types) >= 1 - assert isinstance(result.version, str) + assert catalog.count >= 1 + assert catalog.types - sample = result.types[0] - assert sample.id - assert sample.title - assert sample.category - assert isinstance(sample.severity, Severity) +def test_a_scan_finishes_with_a_result(finished_scan: ScanResult) -> None: + _assert_finished(finished_scan) + assert finished_scan.scan_history_id is not None -def test_endpoint_scan_create_default_scanners( - client: VulnRadar, - target_url: str, - created_scan_ids: list[int], -) -> None: - result = client.scan(target_url) - assert isinstance(result, ScanResult) - assert result.url - assert isinstance(result.scanned_at, datetime) - assert result.duration >= 0 - _assert_summary(result.summary) - - assert isinstance(result.findings, list) - for finding in result.findings: - assert finding.type - assert finding.title - assert isinstance(finding.severity, Severity) - assert isinstance(finding.description, str) - assert isinstance(finding.remediation, str) - - assert result.scan_history_id is not None - created_scan_ids.append(result.scan_history_id) +def test_a_finished_scan_is_in_the_history(client: VulnRadar, finished_scan: ScanResult) -> None: + assert finished_scan.scan_history_id is not None + stored = client.history.get(finished_scan.scan_history_id) -def test_endpoint_scan_create_with_explicit_scanners(scan_for_history: ScanResult) -> None: - assert isinstance(scan_for_history, ScanResult) - assert scan_for_history.url - assert isinstance(scan_for_history.scanned_at, datetime) - _assert_summary(scan_for_history.summary) - assert scan_for_history.scan_history_id is not None + assert stored.scan_history_id == finished_scan.scan_history_id + assert stored.summary.total == finished_scan.summary.total -def test_endpoint_history_list_contains_recent_scan( - client: VulnRadar, - scan_for_history: ScanResult, -) -> None: - history = client.history.list() - - assert len(history.scans) >= 1 - - ids = {entry.id for entry in history.scans} - assert scan_for_history.scan_history_id in ids - - for entry in history.scans: - assert entry.id > 0 - assert entry.url - assert isinstance(entry.scanned_at, datetime) - assert entry.findings_count >= 0 - assert entry.duration >= 0 - _assert_summary(entry.summary) - - -def test_endpoint_history_get_by_id(client: VulnRadar, scan_for_history: ScanResult) -> None: - assert scan_for_history.scan_history_id is not None - - detail = client.history.get(scan_for_history.scan_history_id) +def test_discover_urls(client: VulnRadar, target_url: str) -> None: + result = client.discover_urls(target_url) - assert isinstance(detail, ScanResult) - assert detail.url - assert isinstance(detail.scanned_at, datetime) - assert detail.duration >= 0 - _assert_summary(detail.summary) - assert isinstance(detail.findings, list) + assert result.total == len(result.urls) -def test_endpoint_scan_crawl_discover(discovered_urls: DiscoveryResult, target_url: str) -> None: - assert discovered_urls.total == len(discovered_urls.urls) +def test_a_crawl_finishes_with_pages( + client: VulnRadar, target_url: str, created_scan_ids: list[int] +) -> None: + result = client.scan_crawl(target_url, urls=[target_url], scanners=SCANNERS, public=False) - if discovered_urls.urls: - assert any(url.startswith("http") for url in discovered_urls.urls) - assert any( - target_url.split("//", 1)[1].split("/", 1)[0] in url for url in discovered_urls.urls - ) + assert isinstance(result, CrawlResult) + _assert_finished(result) + assert result.pages + created_scan_ids.extend( + page.scan_history_id for page in result.pages if page.scan_history_id is not None + ) + if result.scan_history_id is not None: + created_scan_ids.append(result.scan_history_id) -def test_endpoint_scan_crawl( - client: VulnRadar, target_url: str, discovered_urls: DiscoveryResult +def test_a_cancelled_scan_ends_as_failed( + client: VulnRadar, target_url: str, created_scan_ids: list[int] ) -> None: - if not discovered_urls.urls: - pytest.skip("no discovered URLs") - - selected = discovered_urls.urls[:3] - result = client.scan_crawl(target_url, urls=selected) + job = client.scans.start(target_url, public=False) + created_scan_ids.append(job.id) - assert isinstance(result, CrawlResult) - assert result.crawl.total_pages >= 0 - assert result.crawl.total_findings >= 0 - assert result.crawl.duration >= 0 - assert isinstance(result.pages, list) + client.scans.cancel(job.id) - for page in result.pages: - assert page.url - assert page.duration >= 0 - _assert_summary(page.summary) - assert isinstance(page.findings, list) + with pytest.raises(ScanFailedError): + client.scans.wait(job.id, timeout=60) -def test_endpoint_history_delete( +def test_a_deleted_scan_is_gone( client: VulnRadar, target_url: str, created_scan_ids: list[int] ) -> None: - created = client.scan(target_url, scanners=["headers"]) - assert created.scan_history_id is not None - created_scan_ids.append(created.scan_history_id) - - deleted = client.history.delete(created.scan_history_id) - assert deleted.success is True - assert deleted.message + result = client.scan(target_url, scanners=[Scanner.HEADERS], public=False) + assert result.scan_history_id is not None + created_scan_ids.append(result.scan_history_id) - if created.scan_history_id in created_scan_ids: - created_scan_ids.remove(created.scan_history_id) + assert client.history.delete(result.scan_history_id).success + created_scan_ids.remove(result.scan_history_id) with pytest.raises(NotFoundError): - client.history.get(created.scan_history_id) + client.history.get(result.scan_history_id) diff --git a/tests/samples.py b/tests/samples.py new file mode 100644 index 0000000..0e88806 --- /dev/null +++ b/tests/samples.py @@ -0,0 +1,109 @@ +"""Reply bodies shaped like the server's, for versions 3.9.2 and 4.0.""" + +from __future__ import annotations + +from typing import Any + + +def finding(severity: str = "high", **extra: Any) -> dict[str, Any]: + return { + "id": "hsts-missing--1a2b3c", + "title": "Missing HTTP Strict Transport Security (HSTS)", + "severity": severity, + "category": "headers", + "description": "The Strict-Transport-Security header is not set.", + "evidence": "No Strict-Transport-Security header in the response.", + "riskImpact": "Connections can be downgraded.", + "explanation": "HSTS tells browsers to use HTTPS only.", + "fixSteps": ["Send the header.", "Include subdomains."], + "codeExamples": [{"label": "nginx", "language": "nginx", "code": "add_header ..."}], + "references": ["https://developer.mozilla.org/docs/Web/HTTP"], + **extra, + } + + +def summary(**counts: int) -> dict[str, int]: + base = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0} + base.update(counts) + return {**base, "total": sum(base.values())} + + +def started(version: str = "3.9.2", scan_id: int = 4711) -> dict[str, Any]: + body: dict[str, Any] = {"scanId": scan_id, "status": "running"} + if version == "4.0.0": + body |= {"publicId": "0123456789abcdef0123456789abcdef", "quota": {"scans": None}} + return body + + +def progress(status: str = "running", done: int = 3) -> dict[str, Any]: + return { + "status": status, + "currentCategory": "headers", + "categoriesCompleted": done, + "categoriesTotal": 17, + "elapsedMs": 1200, + "partialFindings": [{"severity": "high", "title": "Missing HSTS"}], + } + + +def result(version: str = "3.9.2", **extra: Any) -> dict[str, Any]: + body: dict[str, Any] = { + "url": "https://example.com", + "scannedAt": "2026-11-28T12:00:00.000Z", + "duration": 8450, + "findings": [finding()], + "summary": summary(high=1), + "responseHeaders": {"server": "nginx"}, + "scanHistoryId": 4711, + "scanPublicId": "0123456789abcdef0123456789abcdef", + "tags": [{"tag": "nginx", "source": "auto"}], + "dangerScore": 42, + "siteGrade": "B", + } + if version == "4.0.0": + body |= {"safetyRating": "caution", "erroredChecks": [], "somethingNew": {"a": 1}} + return body | extra + + +def completed(version: str = "3.9.2", **extra: Any) -> dict[str, Any]: + body: dict[str, Any] = { + "status": "completed", + "currentCategory": None, + "categoriesCompleted": 17, + "categoriesTotal": 17, + "elapsedMs": 8450, + "result": result(version, **extra), + } + if version == "4.0.0": + body["publicId"] = "0123456789abcdef0123456789abcdef" + return body + + +def failed(version: str = "3.9.2", message: str = "The target did not answer.") -> dict[str, Any]: + body: dict[str, Any] = {**progress("failed"), "error": message} + del body["partialFindings"] + if version == "4.0.0": + body |= {"errorMessage": message, "failureKind": "unreachable"} + return body + + +def crawl(version: str = "3.9.2") -> dict[str, Any]: + page = { + "url": "https://example.com/login", + "scanHistoryId": 4712, + "findings": [finding("medium")], + "findings_count": 1, + "summary": summary(medium=1), + "duration": 900, + } + details: dict[str, Any] = { + "pagesDiscovered": 3, + "pagesScanned": 1, + "pagesSkipped": 2, + "pages": [page], + } + if version == "4.0.0": + details["pagesUnreachable"] = [{"url": "https://example.com/gone", "reason": "404"}] + return completed( + version, crawl=details, findings=[finding("medium")], summary=summary(medium=1) + ) diff --git a/tests/test_client.py b/tests/test_client.py index c30e4e9..9782773 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -33,43 +33,6 @@ def test_version_is_read_from_the_unversioned_path( assert info.message is None -@pytest.mark.parametrize( - ("scanners", "expected"), - [ - (None, {"url": "https://example.com"}), - (["headers", "ssl"], {"url": "https://example.com", "scanners": ["headers", "ssl"]}), - ], -) -def test_scan_posts_the_target_and_chosen_scanners( - client: VulnRadar, - transport: FakeTransport, - scanners: list[str] | None, - expected: dict[str, object], -) -> None: - transport.reply(body={"url": "https://example.com", "findings": [], "summary": {"total": 0}}) - - client.scan("https://example.com", scanners=scanners) - - assert transport.sent[0].method == "POST" - assert transport.sent[0].url == f"{BASE_URL}/scan" - assert transport.sent_json() == expected - assert transport.sent[0].headers["Content-Type"] == "application/json" - - -def test_crawl_posts_the_target_and_extra_pages( - client: VulnRadar, transport: FakeTransport -) -> None: - transport.reply(body={"crawl": {"pages": []}}) - - client.scan_crawl("https://example.com", urls=["https://example.com/login"]) - - assert transport.sent[0].url == f"{BASE_URL}/scan/crawl" - assert transport.sent_json() == { - "url": "https://example.com", - "urls": ["https://example.com/login"], - } - - def test_discover_posts_the_target(client: VulnRadar, transport: FakeTransport) -> None: transport.reply(body={"urls": ["https://example.com/"]}) diff --git a/tests/test_models.py b/tests/test_models.py index 9c10f6d..8efad06 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -4,36 +4,58 @@ from datetime import UTC, datetime -from vulnradar import DeleteScanResult, Finding, ScanResult, Severity - - -def test_a_finished_scan_is_parsed() -> None: - result = ScanResult.from_dict( - { - "url": "https://example.com", - "scannedAt": "2026-11-28T12:00:00.000Z", - "duration": 1500, - "findings": [ - { - "id": "hsts-missing--abc", - "title": "Missing HSTS", - "severity": "high", - "description": "No Strict-Transport-Security header.", - "fixSteps": ["Send the header.", "Include subdomains."], - } - ], - "summary": {"total": 1, "high": 1}, - "scanHistoryId": 42, - } - ) +import pytest + +from tests import samples +from vulnradar import CrawlResult, DeleteScanResult, Finding, ScanResult, Severity + + +@pytest.mark.parametrize("version", ["3.9.2", "4.0.0"]) +def test_a_finished_scan_is_parsed(version: str) -> None: + result = ScanResult.from_dict(samples.result(version)) + assert result.url == "https://example.com" assert result.scanned_at == datetime(2026, 11, 28, 12, tzinfo=UTC) + assert result.duration_ms == 8450 assert (result.summary.total, result.summary.high, result.summary.critical) == (1, 1, 0) - assert result.scan_history_id == 42 - finding = result.findings[0] - assert finding.type == "hsts-missing--abc" + assert result.scan_history_id == 4711 + assert result.public_id == "0123456789abcdef0123456789abcdef" + assert result.tags == ["nginx"] + assert result.response_headers == {"server": "nginx"} + assert result.incomplete == [] + assert result.raw["siteGrade"] == "B" + + +def test_a_finding_keeps_what_the_server_said() -> None: + finding = Finding.from_dict( + samples.finding( + suppressed=True, + remediation={"status": "accepted_risk", "note": "known"}, + cvssScore=5.3, + ) + ) + + assert finding.id == "hsts-missing--1a2b3c" assert finding.severity is Severity.HIGH - assert finding.remediation == "Send the header. Include subdomains." + assert finding.category == "headers" + assert finding.risk_impact == "Connections can be downgraded." + assert finding.fix_steps == ["Send the header.", "Include subdomains."] + assert finding.references == ["https://developer.mozilla.org/docs/Web/HTTP"] + assert finding.suppressed is True + assert finding.remediation_status == "accepted_risk" + assert finding.raw["cvssScore"] == 5.3 + + +def test_a_sparse_finding_is_still_read() -> None: + finding = Finding.from_dict({"title": "Something"}) + + assert (finding.title, finding.id, finding.description) == ("Something", "", "") + assert (finding.fix_steps, finding.suppressed, finding.remediation_status) == ([], False, None) + + +@pytest.mark.parametrize("value", ["urgent", "", None, 5]) +def test_an_unfamiliar_severity_is_not_passed_off_as_harmless(value: object) -> None: + assert Finding.from_dict({"severity": value}).severity is Severity.UNKNOWN def test_severity_is_read_without_regard_to_case() -> None: @@ -45,6 +67,37 @@ def test_severity_prints_as_its_value() -> None: assert Severity("low") is Severity.LOW +def test_areas_that_were_not_checked_are_listed() -> None: + result = ScanResult.from_dict(samples.result(incomplete=["dns", "bot-challenge"])) + + assert result.incomplete == ["dns", "bot-challenge"] + + +def test_an_unfamiliar_incomplete_marker_is_not_dropped() -> None: + assert ScanResult.from_dict(samples.result(incomplete="tls")).incomplete == ["tls"] + + +def test_missing_details_stay_missing() -> None: + result = ScanResult.from_dict({"findings": [], "summary": samples.summary()}) + + assert (result.scanned_at, result.duration_ms, result.scan_history_id) == (None, None, None) + assert (result.public_id, result.url, result.tags, result.notes) == (None, "", [], None) + + +def test_a_history_entry_names_the_scan_by_its_id() -> None: + result = ScanResult.from_dict({"id": 99, "findings": [], "summary": samples.summary()}) + + assert result.scan_history_id == 99 + + +def test_a_crawl_result_is_a_scan_result_with_pages() -> None: + result = CrawlResult.from_dict(samples.crawl()["result"]) + + assert isinstance(result, ScanResult) + assert len(result.pages) == 1 + assert result.pages_unreachable == [] + + def test_a_delete_without_a_message_gets_one() -> None: assert DeleteScanResult.from_dict({"success": True}).message == "Scan deleted successfully" assert DeleteScanResult.from_dict({"success": False}).message == "" diff --git a/tests/test_replies.py b/tests/test_replies.py index a6265c4..9d2ce2b 100644 --- a/tests/test_replies.py +++ b/tests/test_replies.py @@ -8,7 +8,8 @@ import pytest from tests.fake import FakeTransport -from vulnradar import UnexpectedResponseError, VulnRadar +from vulnradar import CrawlResult, UnexpectedResponseError, VulnRadar +from vulnradar.replies import read_reply Call = Callable[[VulnRadar], Any] @@ -21,6 +22,9 @@ "history delete": lambda sdk: sdk.history.delete(1), "finding types": lambda sdk: sdk.metadata.finding_types(), "version": lambda sdk: sdk.version(), + "start": lambda sdk: sdk.scans.start("https://example.com"), + "status": lambda sdk: sdk.scans.status(1), + "cancel": lambda sdk: sdk.scans.cancel(1), } @@ -34,18 +38,6 @@ def test_an_empty_object_is_not_a_result( call(client) -@pytest.mark.parametrize("method", ["scan", "scan_crawl"]) -def test_a_scan_started_in_the_background_names_its_id( - client: VulnRadar, transport: FakeTransport, method: str -) -> None: - transport.reply(body={"scanId": 4711, "status": "running"}) - - with pytest.raises(UnexpectedResponseError, match="4711"): - getattr(client, method)("https://example.com") - - assert len(transport.sent) == 1 - - @pytest.mark.parametrize( "body", [ @@ -73,23 +65,6 @@ def test_a_finished_scan_without_findings_is_still_a_result( assert client.history.get(1).summary.total == 0 -@pytest.mark.parametrize( - "page", - [ - {"url": "https://example.com/a"}, - {"url": "https://example.com/a", "findings": []}, - {"url": "https://example.com/a", "findings": [], "summary": {}}, - ], -) -def test_a_crawled_page_without_a_result_is_not_a_clean_one( - client: VulnRadar, transport: FakeTransport, page: dict[str, object] -) -> None: - transport.reply(body={"crawl": {"pages": [page]}}) - - with pytest.raises(UnexpectedResponseError): - client.scan_crawl("https://example.com") - - @pytest.mark.parametrize( "body", [ @@ -129,3 +104,18 @@ def test_an_impossible_history_id_is_read_as_missing( transport.reply(raw=b'{"findings": [], "summary": {"total": 0}, "scanHistoryId": 1e999}') assert client.history.get(1).scan_history_id is None + + +@pytest.mark.parametrize( + "page", + [ + {"url": "https://example.com/a"}, + {"url": "https://example.com/a", "findings": []}, + {"url": "https://example.com/a", "findings": [], "summary": {}}, + ], +) +def test_a_crawled_page_without_a_result_is_not_a_clean_one(page: dict[str, object]) -> None: + body = {"findings": [], "summary": {"total": 0}, "crawl": {"pages": [page]}} + + with pytest.raises(UnexpectedResponseError): + read_reply(CrawlResult.from_dict, body) diff --git a/tests/test_scans.py b/tests/test_scans.py new file mode 100644 index 0000000..1a1d561 --- /dev/null +++ b/tests/test_scans.py @@ -0,0 +1,365 @@ +"""Starting scans, waiting for them and stopping them.""" + +from __future__ import annotations + +import time +from typing import Any + +import pytest +import requests + +from tests import samples +from tests.conftest import BASE_URL +from tests.fake import FakeTransport +from vulnradar import ( + CrawlResult, + NetworkError, + NotFoundError, + RateLimitError, + ScanFailedError, + Scanner, + ScanState, + ScanTimeoutError, + ServerError, + UnexpectedResponseError, + VulnRadar, + VulnRadarError, +) + +VERSIONS = ["3.9.2", "4.0.0"] + + +class Clock: + """Time that passes only when someone sleeps.""" + + def __init__(self) -> None: + self.now = 1000.0 + self.sleeps: list[float] = [] + + def monotonic(self) -> float: + return self.now + + def sleep(self, seconds: float) -> None: + self.sleeps.append(seconds) + self.now += seconds + + +@pytest.fixture +def clock(monkeypatch: pytest.MonkeyPatch) -> Clock: + fake = Clock() + monkeypatch.setattr(time, "monotonic", fake.monotonic) + monkeypatch.setattr(time, "sleep", fake.sleep) + return fake + + +def methods(transport: FakeTransport) -> list[str]: + return [str(request.method) for request in transport.sent] + + +@pytest.mark.parametrize("version", VERSIONS) +def test_scan_starts_a_job_and_returns_its_finished_result( + client: VulnRadar, transport: FakeTransport, clock: Clock, version: str +) -> None: + transport.reply(body=samples.started(version)) + transport.reply(body=samples.progress("pending", 0)) + transport.reply(body=samples.progress()) + transport.reply(body=samples.completed(version)) + + result = client.scan("https://example.com") + + assert result.scan_history_id == 4711 + assert result.summary.high == 1 + assert result.findings[0].title.startswith("Missing HTTP Strict") + assert methods(transport) == ["POST", "GET", "GET", "GET"] + assert transport.sent[1].url == f"{BASE_URL}/scan/status/4711" + assert clock.sleeps == [3.0, 3.0] + + +def test_start_sends_only_what_was_chosen(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.started("4.0.0")) + + job = client.scans.start("example.com") + + assert (job.id, job.public_id) == (4711, "0123456789abcdef0123456789abcdef") + assert transport.sent_json() == {"url": "example.com"} + + +def test_start_sends_the_chosen_options(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.started()) + + client.scans.start( + "https://example.com", + scanners=[Scanner.HEADERS, "ssl", "active-probes:xss"], + public=False, + capture_screenshot=True, + port_scan=True, + team_ids=[7, 8], + ) + + assert transport.sent_json() == { + "url": "https://example.com", + "scanners": ["headers", "ssl", "active-probes:xss"], + "isPublic": False, + "captureScreenshot": True, + "portScan": True, + "teamIds": [7, 8], + } + + +def test_a_crawl_returns_its_pages( + client: VulnRadar, transport: FakeTransport, clock: Clock +) -> None: + transport.reply(body=samples.started()) + transport.reply(body=samples.crawl("4.0.0")) + + result = client.scan_crawl( + "https://example.com", urls=["https://example.com/login"], scanners=["headers"] + ) + + assert transport.sent[0].url == f"{BASE_URL}/scan/crawl" + assert transport.sent_json(0) == { + "url": "https://example.com", + "urls": ["https://example.com/login"], + "scanners": ["headers"], + } + assert isinstance(result, CrawlResult) + assert (result.pages_discovered, result.pages_scanned, result.pages_skipped) == (3, 1, 2) + assert result.pages[0].url == "https://example.com/login" + assert result.pages[0].summary.medium == 1 + assert result.pages[0].scan_history_id == 4712 + assert result.pages_unreachable[0]["reason"] == "404" + assert result.summary.medium == 1 + + +def test_a_crawl_without_crawl_details_is_an_error( + client: VulnRadar, transport: FakeTransport, clock: Clock +) -> None: + transport.reply(body=samples.started()) + transport.reply(body=samples.completed()) + + with pytest.raises(UnexpectedResponseError) as caught: + client.scan_crawl("https://example.com") + + assert caught.value.scan_id == 4711 + + +@pytest.mark.parametrize( + "scanners", + [["header"], ["headers", "Headers"], ["active-probes:nope"], [], "headers", [5]], +) +def test_an_unknown_scanner_is_refused_before_anything_is_sent( + client: VulnRadar, transport: FakeTransport, scanners: Any +) -> None: + with pytest.raises(ValueError, match="scanner"): + client.scan("https://example.com", scanners=scanners) + with pytest.raises(ValueError, match="scanner"): + client.scan_crawl("https://example.com", scanners=scanners) + + assert transport.sent == [] + + +def test_every_listed_scanner_is_accepted(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.started()) + + client.scans.start("https://example.com", scanners=list(Scanner)) + + assert len(transport.sent_json()["scanners"]) == len(Scanner) == 18 + + +@pytest.mark.parametrize("version", VERSIONS) +def test_a_failed_scan_raises_with_the_reason( + client: VulnRadar, transport: FakeTransport, clock: Clock, version: str +) -> None: + transport.reply(body=samples.started(version)) + transport.reply(body=samples.failed(version)) + + with pytest.raises(ScanFailedError) as caught: + client.scan("https://example.com") + + error = caught.value + assert error.scan_id == 4711 + assert "The target did not answer." in error.message + assert error.failure_kind == ("unreachable" if version == "4.0.0" else None) + + +def test_a_scan_still_running_at_the_deadline_is_not_cancelled( + client: VulnRadar, transport: FakeTransport, clock: Clock +) -> None: + transport.reply(body=samples.progress()) + + with pytest.raises(ScanTimeoutError) as caught: + client.scans.wait(4711, timeout=10, poll_interval=4) + + assert caught.value.scan_id == 4711 + assert clock.sleeps == [4, 4, 2] + assert set(methods(transport)) == {"GET"} + + +def test_an_unknown_state_keeps_the_wait_going( + client: VulnRadar, transport: FakeTransport, clock: Clock +) -> None: + transport.reply(body=samples.progress("queued")) + transport.reply(body=samples.completed()) + + assert client.scans.wait(4711).summary.high == 1 + + +def test_a_few_failed_polls_are_tolerated(transport: FakeTransport, clock: Clock) -> None: + sdk = VulnRadar(api_key="test-key", base_url=BASE_URL, retries=0) + sdk._http._session.mount("https://", transport) + transport.fail(requests.exceptions.ConnectionError()) + transport.reply(502, {"error": "bad gateway"}) + transport.reply(429, {"error": "slow down"}, headers={"Retry-After": "20"}) + transport.reply(body=samples.completed()) + + assert sdk.scans.wait(4711).summary.high == 1 + assert clock.sleeps == [3.0, 3.0, 20.0] + + +@pytest.mark.parametrize(("status", "error"), [(502, ServerError), (None, NetworkError)]) +def test_polls_that_keep_failing_end_the_wait_with_the_scan_id( + transport: FakeTransport, + clock: Clock, + status: int | None, + error: type[VulnRadarError], +) -> None: + sdk = VulnRadar(api_key="test-key", base_url=BASE_URL, retries=0) + sdk._http._session.mount("https://", transport) + if status is None: + transport.fail(requests.exceptions.ConnectionError()) + else: + transport.reply(status, {"error": "bad gateway"}) + + with pytest.raises(error) as caught: + sdk.scans.wait(4711) + + assert caught.value.scan_id == 4711 + assert len(transport.sent) == 5 + + +def test_a_wait_longer_than_the_deadline_is_reported_at_once( + client: VulnRadar, transport: FakeTransport, clock: Clock +) -> None: + transport.reply(429, {"error": "slow down"}, headers={"Retry-After": "600"}) + + with pytest.raises(RateLimitError) as caught: + client.scans.wait(4711, timeout=60) + + assert caught.value.scan_id == 4711 + assert clock.sleeps == [] + + +def test_a_poll_the_server_refuses_ends_the_wait( + client: VulnRadar, transport: FakeTransport, clock: Clock +) -> None: + transport.reply(404, {"error": "Scan not found"}) + + with pytest.raises(NotFoundError) as caught: + client.scans.wait(4711) + + assert caught.value.scan_id == 4711 + assert len(transport.sent) == 1 + + +@pytest.mark.parametrize( + "body", + [ + {"status": "completed"}, + {"status": "completed", "result": None}, + {"status": "completed", "result": {"url": "https://example.com"}}, + {"status": "completed", "result": {"findings": [], "summary": {}}}, + {"status": None}, + ], +) +def test_a_completed_scan_without_a_result_is_never_clean( + client: VulnRadar, transport: FakeTransport, clock: Clock, body: dict[str, object] +) -> None: + transport.reply(body=body) + + with pytest.raises(UnexpectedResponseError) as caught: + client.scans.wait(4711) + + assert caught.value.scan_id == 4711 + + +@pytest.mark.parametrize(("timeout", "poll_interval"), [(0, 1), (-1, 1), (10, 0), (10, -1)]) +def test_impossible_waiting_settings_are_refused( + client: VulnRadar, transport: FakeTransport, timeout: float, poll_interval: float +) -> None: + with pytest.raises(ValueError, match="greater than zero"): + client.scans.wait(4711, timeout=timeout, poll_interval=poll_interval) + + assert transport.sent == [] + + +@pytest.mark.parametrize("method", ["scan", "scan_crawl"]) +def test_an_impossible_timeout_starts_no_scan( + client: VulnRadar, transport: FakeTransport, method: str +) -> None: + with pytest.raises(ValueError, match="greater than zero"): + getattr(client, method)("https://example.com", timeout=0) + + assert transport.sent == [] + + +def test_an_unknown_option_starts_no_scan(client: VulnRadar, transport: FakeTransport) -> None: + with pytest.raises(TypeError, match="verbose"): + client.scans.start("https://example.com", verbose=True) # type: ignore[call-arg] + + assert transport.sent == [] + + +@pytest.mark.parametrize("version", VERSIONS) +def test_status_reports_progress(client: VulnRadar, transport: FakeTransport, version: str) -> None: + transport.reply(body=samples.progress()) + + status = client.scans.status(4711) + + assert status.state == ScanState.RUNNING + assert not status.finished + assert (status.categories_completed, status.categories_total) == (3, 17) + assert status.current_category == "headers" + assert status.elapsed_ms == 1200 + assert status.partial_findings[0]["title"] == "Missing HSTS" + assert status.result is None + + +def test_cancel_stops_a_scan(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body={"status": "failed", "cancelled": True}) + + client.scans.cancel(4711) + + assert (methods(transport), transport.sent[0].url) == ( + ["DELETE"], + f"{BASE_URL}/scan/status/4711", + ) + + +def test_cancelling_a_finished_scan_raises(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(409, {"error": "This scan has already finished."}) + + with pytest.raises(VulnRadarError) as caught: + client.scans.cancel(4711) + + assert caught.value.status_code == 409 + + +@pytest.mark.parametrize("scan_id", ["../4711", "4711?x=1", ""]) +def test_a_scan_id_cannot_change_the_status_address( + client: VulnRadar, transport: FakeTransport, scan_id: str +) -> None: + for call in (client.scans.status, client.scans.wait, client.scans.cancel): + with pytest.raises(ValueError, match="scan id"): + call(scan_id) + + assert transport.sent == [] + + +@pytest.mark.parametrize("body", [{"scanId": "4711"}, {"scanId": True}, {"status": "running"}]) +def test_a_start_reply_without_a_scan_number_is_an_error( + client: VulnRadar, transport: FakeTransport, body: dict[str, object] +) -> None: + transport.reply(body=body) + + with pytest.raises(UnexpectedResponseError): + client.scans.start("https://example.com") diff --git a/tests/test_url_validation.py b/tests/test_url_validation.py index 98644ed..74b0e36 100644 --- a/tests/test_url_validation.py +++ b/tests/test_url_validation.py @@ -12,6 +12,13 @@ "https://example.com", "http://sub.example.co.uk/path?query=1", "https://192.0.2.10:8443/", + "ssh://example.com", + "mongodb://db.example.com:27017", + "example.com", + "example.com/path", + "https://xn--bcher-kva.xn--p1ai", + "http://my_host.example.com", + "https://[2001:db8::1]/", ], ) def test_web_addresses_are_accepted(url: str) -> None: @@ -20,7 +27,17 @@ def test_web_addresses_are_accepted(url: str) -> None: @pytest.mark.parametrize( "url", - ["", "not a url", "https://", "javascript:alert(1)", "file:///etc/passwd", "https://[oops"], + [ + "", + "not a url", + "https://", + "javascript:alert(1)", + "file:///etc/passwd", + "https://[oops", + "https://exa mple.com", + "https://example.com/\n", + "https://" + "a" * 2048, + ], ) def test_other_input_is_rejected(url: str) -> None: with pytest.raises(InvalidURLError) as caught: diff --git a/vulnradar/__init__.py b/vulnradar/__init__.py index 896064d..ec6d7a9 100644 --- a/vulnradar/__init__.py +++ b/vulnradar/__init__.py @@ -1,6 +1,6 @@ from ._version import __version__ as __version__ from .client import VulnRadar -from .enums import RateLimitKind, Severity +from .enums import RateLimitKind, Scanner, ScanState, Severity from .exceptions import ( AuthenticationError, BadRequestError, @@ -11,13 +11,14 @@ RateLimitError, RateLimitInfo, RequestTimeoutError, + ScanFailedError, + ScanTimeoutError, ServerError, UnexpectedResponseError, UnprocessableEntityError, VulnRadarError, ) from .models import ( - CrawlInfo, CrawlPage, CrawlResult, DeleteScanResult, @@ -27,15 +28,17 @@ FindingTypesResult, HistoryList, HistoryScan, + ScanJob, ScanResult, + ScanStatus, Summary, VersionInfo, ) +from .services.scan_service import ScanOptions __all__ = [ "AuthenticationError", "BadRequestError", - "CrawlInfo", "CrawlPage", "CrawlResult", "DeleteScanResult", @@ -53,7 +56,14 @@ "RateLimitInfo", "RateLimitKind", "RequestTimeoutError", + "ScanFailedError", + "ScanJob", + "ScanOptions", "ScanResult", + "ScanState", + "ScanStatus", + "ScanTimeoutError", + "Scanner", "ServerError", "Severity", "Summary", diff --git a/vulnradar/client.py b/vulnradar/client.py index d94aa08..35511f6 100644 --- a/vulnradar/client.py +++ b/vulnradar/client.py @@ -1,6 +1,8 @@ from __future__ import annotations import os +from collections.abc import Sequence +from typing import Unpack from .config import VulnRadarConfig from .constants import ( @@ -9,17 +11,18 @@ BASE_URL_ENV, DEFAULT_RETRIES, DEFAULT_TIMEOUT, + DEFAULT_WAIT_TIMEOUT, ) +from .exceptions import UnexpectedResponseError from .http import HTTPClient from .models.crawl import CrawlResult, DiscoveryResult from .models.scan_result import ScanResult from .models.version import VersionInfo from .replies import read_reply -from .services.crawl_service import CrawlService from .services.discovery_service import DiscoveryService from .services.history_service import HistoryService from .services.metadata_service import MetadataService -from .services.scan_service import ScanService +from .services.scan_service import ScanOptions, ScanService, check_positive class VulnRadar: @@ -44,7 +47,7 @@ class VulnRadar: >>> from vulnradar import VulnRadar >>> client = VulnRadar(api_key="your-api-key") >>> result = client.scan("https://example.com") - >>> print(result.summary.total) + >>> print(result.summary.total, result.incomplete) """ def __init__( @@ -69,10 +72,14 @@ def __init__( self._scan_service = ScanService(self._http) self._history_service = HistoryService(self._http) - self._crawl_service = CrawlService(self._http) self._discovery_service = DiscoveryService(self._http) self._metadata_service = MetadataService(self._http) + @property + def scans(self) -> ScanService: + """Start, follow and cancel scans.""" + return self._scan_service + @property def history(self) -> HistoryService: """Access scan history operations.""" @@ -83,34 +90,69 @@ def metadata(self) -> MetadataService: """Access API metadata such as finding type definitions.""" return self._metadata_service - def scan(self, url: str, scanners: list[str] | None = None) -> ScanResult: - """Run a security scan against a single URL. + def scan( + self, + url: str, + scanners: Sequence[str] | None = None, + *, + timeout: float = DEFAULT_WAIT_TIMEOUT, + **options: Unpack[ScanOptions], + ) -> ScanResult: + """Scan one address and wait for the result. + + Use ``scans.start`` instead to return as soon as the scan has begun. Args: - url: The target URL to scan. - scanners: Optional list of scanner IDs to run. If omitted, all scanners run. + url: The target, with or without a scheme. + scanners: Scanner names to run; see Scanner. All the default ones if None. + timeout: Seconds to wait for the result. The scan keeps running afterwards. + **options: See ScanOptions. Returns: - A ScanResult containing findings, summary, and scan metadata. + The finished result. Check ``incomplete`` before calling it clean. Raises: - InvalidURLError: If the URL is malformed. - AuthenticationError: If the API key is invalid. - RateLimitError: If the rate limit is exceeded. + InvalidURLError: If the target cannot be scanned. + ValueError: If a scanner name or the timeout is unusable. + ScanFailedError: If the scan failed. + ScanTimeoutError: If it did not finish in time. + RateLimitError: If a limit or quota is used up. """ - return self._scan_service.scan(url, scanners=scanners) + check_positive(timeout=timeout) # before a scan is started and counted + job = self.scans.start(url, scanners, **options) + return self.scans.wait(job.id, timeout=timeout) + + def scan_crawl( + self, + url: str, + urls: Sequence[str] | None = None, + *, + scanners: Sequence[str] | None = None, + timeout: float = DEFAULT_WAIT_TIMEOUT, + **options: Unpack[ScanOptions], + ) -> CrawlResult: + """Crawl a site and wait for the result. - def scan_crawl(self, url: str, urls: list[str] | None = None) -> CrawlResult: - """Run a deep crawl scan across multiple pages of a target. + Each page counts as one scan against the daily quota. Args: - url: The root URL to crawl. - urls: Optional additional URLs to include in the crawl. + url: Where the crawl starts. + urls: Pages to scan, on the same origin. The server finds them if None. + scanners: Scanner names to run; see Scanner. + timeout: Seconds to wait for the result. The crawl keeps running afterwards. + **options: See ScanOptions. Returns: - A CrawlResult with per-page findings and aggregate crawl info. + The merged result, with each page in ``pages``. """ - return self._crawl_service.scan_crawl(url, urls=urls) + check_positive(timeout=timeout) + job = self.scans.start_crawl(url, urls, scanners, **options) + result = self.scans.wait(job.id, timeout=timeout) + if not isinstance(result, CrawlResult): + error = UnexpectedResponseError("The finished scan carries no crawl details.") + error.scan_id = job.id + raise error + return result def discover_urls(self, url: str) -> DiscoveryResult: """Discover all crawlable URLs for a given target. diff --git a/vulnradar/constants.py b/vulnradar/constants.py index 8700a74..c01adeb 100644 --- a/vulnradar/constants.py +++ b/vulnradar/constants.py @@ -9,3 +9,19 @@ DEFAULT_RETRY_BACKOFF: float = 0.5 # A server asking for a longer wait than this is reported to the caller instead. MAX_RETRY_WAIT: float = 30.0 + +DEFAULT_WAIT_TIMEOUT: float = 900.0 # the longest the server lets a crawl run +DEFAULT_POLL_INTERVAL: float = 3.0 +MAX_FAILED_POLLS: int = 5 + +ACTIVE_PROBES: tuple[str, ...] = ( + "xss", + "sqli", + "ssti", + "command-injection", + "open-redirect", + "graphql", + "cors", + "http-methods", + "x-forwarded-host", +) diff --git a/vulnradar/enums.py b/vulnradar/enums.py index b345b5a..f882b71 100644 --- a/vulnradar/enums.py +++ b/vulnradar/enums.py @@ -7,6 +7,43 @@ class Severity(StrEnum): MEDIUM = "medium" LOW = "low" INFO = "info" + UNKNOWN = "unknown" + """A level this version of the SDK does not know.""" + + +class ScanState(StrEnum): + PENDING = "pending" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + """Also the state of a cancelled scan.""" + + +class Scanner(StrEnum): + """Scanner categories. All but ACTIVE_PROBES run by default. + + ACTIVE_PROBES needs a verified domain. A single probe is chosen with a name + such as ``active-probes:xss``. + """ + + HEADERS = "headers" + SSL = "ssl" + TLS = "tls" + CONTENT = "content" + COOKIES = "cookies" + CONFIGURATION = "configuration" + INFORMATION_DISCLOSURE = "information-disclosure" + DNS = "dns" + EMAIL = "email" + API = "api" + CODE = "code" + SECRETS_EXTENDED = "secrets-extended" + VIBE_CODE = "vibe-code" + CLIENT_SIDE = "client-side" + SUPPLY_CHAIN = "supply-chain" + HOST_VALIDATION = "host-validation" + REPUTATION = "reputation" + ACTIVE_PROBES = "active-probes" class RateLimitKind(StrEnum): diff --git a/vulnradar/exceptions.py b/vulnradar/exceptions.py index 8338893..a81624f 100644 --- a/vulnradar/exceptions.py +++ b/vulnradar/exceptions.py @@ -18,6 +18,7 @@ class VulnRadarError(Exception): request_id: The server's id for the request, useful when reporting a problem. retry_after: Seconds the server asked the caller to wait. body: The server's error reply, for fields without an attribute of their own. + scan_id: The scan being followed, if the error happened while waiting for one. """ default_message = "The VulnRadar request failed." @@ -40,6 +41,7 @@ def __init__( self.request_id = request_id self.retry_after = retry_after self.body: dict[str, Any] = dict(body or {}) + self.scan_id: int | str | None = None class AuthenticationError(VulnRadarError): @@ -149,14 +151,38 @@ class UnexpectedResponseError(VulnRadarError): default_message = "The server's reply could not be understood." +class ScanFailedError(VulnRadarError): + """Raised when a scan ends without a result, including when it is cancelled.""" + + def __init__( + self, + scan_id: int | str, + reason: str | None = None, + *, + failure_kind: str | None = None, + body: Mapping[str, Any] | None = None, + ) -> None: + super().__init__(f"Scan {scan_id} failed: {reason or 'no reason was given'}", body=body) + self.scan_id = scan_id + self.failure_kind = failure_kind + + +class ScanTimeoutError(VulnRadarError): + """Raised when a scan is not finished in the time allowed. It keeps running.""" + + def __init__(self, scan_id: int | str, timeout: float) -> None: + super().__init__( + f"Scan {scan_id} was not finished after {timeout} seconds. It has not been " + "cancelled: wait for it again, or cancel it." + ) + self.scan_id = scan_id + + class InvalidURLError(VulnRadarError): """Raised when a provided URL fails validation.""" def __init__(self, url: str) -> None: - super().__init__( - f"Invalid URL: '{url}'. Must be a valid URL using one of: " - "http://, https://, ws://, wss://, ftp://, ftps://." - ) + super().__init__(f"Invalid URL: {url!r}. Give an address such as https://example.com.") self.url = url diff --git a/vulnradar/models/__init__.py b/vulnradar/models/__init__.py index 3625558..c1e5b31 100644 --- a/vulnradar/models/__init__.py +++ b/vulnradar/models/__init__.py @@ -1,13 +1,13 @@ -from .crawl import CrawlInfo, CrawlPage, CrawlResult, DiscoveryResult +from .crawl import CrawlPage, CrawlResult, DiscoveryResult from .finding_types import FindingType, FindingTypesResult from .findings import Finding from .history import DeleteScanResult, HistoryList, HistoryScan from .scan_result import ScanResult +from .scan_status import ScanJob, ScanStatus from .summary import Summary from .version import VersionInfo __all__ = [ - "CrawlInfo", "CrawlPage", "CrawlResult", "DeleteScanResult", @@ -17,7 +17,9 @@ "FindingTypesResult", "HistoryList", "HistoryScan", + "ScanJob", "ScanResult", + "ScanStatus", "Summary", "VersionInfo", ] diff --git a/vulnradar/models/crawl.py b/vulnradar/models/crawl.py index 483352e..ed7e9de 100644 --- a/vulnradar/models/crawl.py +++ b/vulnradar/models/crawl.py @@ -3,7 +3,9 @@ from dataclasses import dataclass, field from typing import Any +from .fields import integer, objects, required_list, text from .findings import Finding +from .scan_result import ScanResult from .summary import Summary @@ -14,46 +16,47 @@ class CrawlPage: url: str findings: list[Finding] summary: Summary - duration: float - response_headers: dict[str, str] = field(default_factory=dict) + duration_ms: int | None + scan_history_id: int | None + raw: dict[str, Any] = field(repr=False) @classmethod def from_dict(cls, data: dict[str, Any]) -> CrawlPage: return cls( - url=data.get("url", ""), - findings=[Finding.from_dict(f) for f in data["findings"]], + url=text(data.get("url")) or "", + findings=[Finding.from_dict(item) for item in required_list(data, "findings")], summary=Summary.of_finished_scan(data["summary"]), - duration=float(data.get("duration", 0.0)), - response_headers=data.get("responseHeaders", {}), + duration_ms=integer(data.get("duration")), + scan_history_id=integer(data.get("scanHistoryId")), + raw=data, ) @dataclass -class CrawlInfo: - """Metadata about a crawl operation.""" +class CrawlResult(ScanResult): + """A finished crawl: the merged result, and each page on its own.""" - total_pages: int - total_findings: int - duration: float - - -@dataclass -class CrawlResult: - """Full result of a deep crawl scan.""" - - crawl: CrawlInfo - pages: list[CrawlPage] = field(default_factory=list) + pages: list[CrawlPage] + pages_discovered: int + pages_scanned: int + pages_skipped: int + pages_unreachable: list[dict[str, Any]] + """Pages that could not be fetched, as ``url`` and ``reason``. Newer servers only.""" @classmethod - def from_dict(cls, data: dict[str, Any]) -> CrawlResult: - crawl_data = data["crawl"] - pages = [CrawlPage.from_dict(p) for p in crawl_data["pages"]] - crawl = CrawlInfo( - total_pages=int(crawl_data.get("totalPages", len(pages))), - total_findings=sum(p.summary.total for p in pages), - duration=float(data.get("duration", 0.0)), - ) - return cls(crawl=crawl, pages=pages) + def _fields(cls, data: dict[str, Any]) -> dict[str, Any]: + crawl = data["crawl"] + pages = [CrawlPage.from_dict(page) for page in required_list(crawl, "pages")] + discovered = integer(crawl.get("pagesDiscovered")) + scanned = integer(crawl.get("pagesScanned")) + return { + **super()._fields(data), + "pages": pages, + "pages_discovered": len(pages) if discovered is None else discovered, + "pages_scanned": len(pages) if scanned is None else scanned, + "pages_skipped": integer(crawl.get("pagesSkipped")) or 0, + "pages_unreachable": objects(crawl.get("pagesUnreachable")), + } @dataclass @@ -65,9 +68,7 @@ class DiscoveryResult: @classmethod def from_dict(cls, data: dict[str, Any]) -> DiscoveryResult: - urls = data["urls"] - if not isinstance(urls, list): - raise TypeError("urls") + urls = required_list(data, "urls") return cls( urls=urls, total=data.get("total", len(urls)), diff --git a/vulnradar/models/fields.py b/vulnradar/models/fields.py new file mode 100644 index 0000000..dc43e5e --- /dev/null +++ b/vulnradar/models/fields.py @@ -0,0 +1,52 @@ +"""Reading single fields of a reply. A value of the wrong type counts as missing.""" + +from __future__ import annotations + +import math +from datetime import datetime +from typing import Any + + +def text(value: object) -> str | None: + return value if isinstance(value, str) else None + + +def integer(value: object) -> int | None: + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, float) and math.isfinite(value): + return int(value) + if isinstance(value, str) and value.isdecimal() and len(value) <= 18: + return int(value) + return None + + +def strings(value: object) -> list[str]: + return [item for item in value if isinstance(item, str)] if isinstance(value, list) else [] + + +def objects(value: object) -> list[dict[str, Any]]: + return [item for item in value if isinstance(item, dict)] if isinstance(value, list) else [] + + +def mapping(value: object) -> dict[str, Any]: + return value if isinstance(value, dict) else {} + + +def timestamp(value: object) -> datetime | None: + if not isinstance(value, str): + return None + try: + return datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + + +def required_list(data: dict[str, Any], key: str) -> list[Any]: + """A list the model cannot do without, so that its absence never reads as empty.""" + value = data[key] + if not isinstance(value, list): + raise TypeError(key) + return value diff --git a/vulnradar/models/findings.py b/vulnradar/models/findings.py index e42265c..c2d171f 100644 --- a/vulnradar/models/findings.py +++ b/vulnradar/models/findings.py @@ -1,49 +1,60 @@ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any from ..enums import Severity +from .fields import mapping, objects, strings, text @dataclass class Finding: - """A single security finding from a scan.""" + """A single security finding from a scan. - type: str + Only the commonly used fields are attributes. Everything the server sent, + including fields newer than this SDK, is in ``raw``. + """ + + id: str title: str severity: Severity description: str - remediation: str - - @staticmethod - def _parse_severity(value: str | None) -> Severity: - raw = (value or "info").strip().lower() - try: - return Severity(raw) - except ValueError: - return Severity.INFO - - @staticmethod - def _parse_remediation(data: dict[str, Any]) -> str: - remediation = data.get("remediation") - if isinstance(remediation, str) and remediation.strip(): - return remediation - - fix_steps = data.get("fixSteps") - if isinstance(fix_steps, list): - steps = [str(step).strip() for step in fix_steps if str(step).strip()] - if steps: - return " ".join(steps) - - return "" + category: str | None + evidence: str | None + explanation: str | None + risk_impact: str | None + fix_steps: list[str] + code_examples: list[dict[str, Any]] + references: list[str] + suppressed: bool + """True if the account marked this finding as a false positive.""" + remediation_status: str | None + """The account's triage of the finding, such as ``fixed`` or ``accepted_risk``.""" + raw: dict[str, Any] = field(repr=False) @classmethod def from_dict(cls, data: dict[str, Any]) -> Finding: return cls( - type=str(data.get("type") or data.get("id") or ""), - title=data.get("title", ""), - severity=cls._parse_severity(data.get("severity")), - description=data.get("description", ""), - remediation=cls._parse_remediation(data), + id=text(data.get("id")) or "", + title=text(data.get("title")) or "", + severity=_severity(data.get("severity")), + description=text(data.get("description")) or "", + category=text(data.get("category")), + evidence=text(data.get("evidence")), + explanation=text(data.get("explanation")), + risk_impact=text(data.get("riskImpact")), + fix_steps=strings(data.get("fixSteps")), + code_examples=objects(data.get("codeExamples")), + references=strings(data.get("references")), + suppressed=data.get("suppressed") is True, + remediation_status=text(mapping(data.get("remediation")).get("status")), + raw=data, ) + + +def _severity(value: object) -> Severity: + # An unfamiliar value must not be filed under a harmless level. + try: + return Severity(str(value).strip().lower()) + except ValueError: + return Severity.UNKNOWN diff --git a/vulnradar/models/scan_result.py b/vulnradar/models/scan_result.py index 74d5aa4..42a4b05 100644 --- a/vulnradar/models/scan_result.py +++ b/vulnradar/models/scan_result.py @@ -1,49 +1,68 @@ from __future__ import annotations -from dataclasses import dataclass -from datetime import UTC, datetime -from typing import Any +from dataclasses import dataclass, field +from datetime import datetime +from typing import Any, Self +from .fields import integer, mapping, required_list, text, timestamp from .findings import Finding from .summary import Summary @dataclass class ScanResult: - """Full result of a single URL scan.""" + """A finished scan. + + Check ``incomplete`` before treating a scan without findings as clean: it + lists the areas the server could not check. Everything the server sent, + such as ``siteGrade`` or ``dnsRecords``, is in ``raw``. + """ url: str - scanned_at: datetime - duration: float findings: list[Finding] summary: Summary - response_headers: dict[str, str] + scanned_at: datetime | None + duration_ms: int | None scan_history_id: int | None + public_id: str | None + response_headers: dict[str, str] notes: str | None + incomplete: list[str] + tags: list[str] + raw: dict[str, Any] = field(repr=False) - @staticmethod - def _parse_int(value: Any) -> int | None: - if value is None or isinstance(value, bool): - return None - try: - return int(value) - except (OverflowError, TypeError, ValueError): - return None + @classmethod + def from_dict(cls, data: dict[str, Any]) -> Self: + return cls(**cls._fields(data)) @classmethod - def from_dict(cls, data: dict[str, Any]) -> ScanResult: - raw_ts = data.get("scannedAt", "") - scanned_at = ( - datetime.fromisoformat(raw_ts.replace("Z", "+00:00")) if raw_ts else datetime.now(UTC) - ) - - return cls( - url=data.get("url", ""), - scanned_at=scanned_at, - duration=float(data.get("duration", 0.0)), - findings=[Finding.from_dict(f) for f in data["findings"]], - summary=Summary.of_finished_scan(data["summary"]), - response_headers=data.get("responseHeaders", {}), - scan_history_id=cls._parse_int(data.get("scanHistoryId")), - notes=data.get("notes"), - ) + def _fields(cls, data: dict[str, Any]) -> dict[str, Any]: + return { + "url": text(data.get("url")) or "", + "findings": [Finding.from_dict(item) for item in required_list(data, "findings")], + "summary": Summary.of_finished_scan(data["summary"]), + "scanned_at": timestamp(data.get("scannedAt")), + "duration_ms": integer(data.get("duration")), + # A history entry calls the same number "id". + "scan_history_id": integer(data.get("scanHistoryId", data.get("id"))), + "public_id": text(data.get("scanPublicId")) or text(data.get("publicId")), + "response_headers": mapping(data.get("responseHeaders")), + "notes": text(data.get("notes")), + "incomplete": _incomplete(data.get("incomplete")), + "tags": _tags(data.get("tags")), + "raw": data, + } + + +def _incomplete(value: object) -> list[str]: + # Anything here means part of the scan is missing, whatever shape it takes. + if not value: + return [] + return [str(item) for item in value] if isinstance(value, list) else [str(value)] + + +def _tags(value: object) -> list[str]: + if not isinstance(value, list): + return [] + names = (item.get("tag") if isinstance(item, dict) else item for item in value) + return [name for name in names if isinstance(name, str)] diff --git a/vulnradar/models/scan_status.py b/vulnradar/models/scan_status.py new file mode 100644 index 0000000..95db3b8 --- /dev/null +++ b/vulnradar/models/scan_status.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from ..enums import ScanState +from .crawl import CrawlResult +from .fields import integer, mapping, objects, text +from .scan_result import ScanResult + + +@dataclass +class ScanJob: + """A scan the server has started.""" + + id: int + public_id: str | None + """The text id newer servers also give a scan.""" + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> ScanJob: + scan_id = data["scanId"] + if type(scan_id) is not int: + raise TypeError("scanId") + return cls(id=scan_id, public_id=text(data.get("publicId"))) + + +@dataclass +class ScanStatus: + """Where a scan stands. + + ``state`` is normally one of the ScanState values. ``result`` is set only + when the scan has completed. + """ + + state: str + current_category: str | None + categories_completed: int + categories_total: int + """0 while a crawl is still finding its pages.""" + elapsed_ms: int + partial_findings: list[dict[str, Any]] + """Severity and title of findings so far. The final list may differ.""" + result: ScanResult | None + error: str | None + failure_kind: str | None + raw: dict[str, Any] = field(repr=False) + + @property + def finished(self) -> bool: + return self.state in (ScanState.COMPLETED, ScanState.FAILED) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> ScanStatus: + state = data["status"] + if not isinstance(state, str): + raise TypeError("status") + completed = state == ScanState.COMPLETED + return cls( + state=state, + current_category=text(data.get("currentCategory")), + categories_completed=integer(data.get("categoriesCompleted")) or 0, + categories_total=integer(data.get("categoriesTotal")) or 0, + elapsed_ms=integer(data.get("elapsedMs")) or 0, + partial_findings=objects(data.get("partialFindings")), + result=_result(data["result"]) if completed else None, + error=text(data.get("errorMessage")) or text(data.get("error")), + failure_kind=text(data.get("failureKind")), + raw=data, + ) + + +def _result(data: dict[str, Any]) -> ScanResult: + crawled = bool(mapping(data.get("crawl"))) + return CrawlResult.from_dict(data) if crawled else ScanResult.from_dict(data) diff --git a/vulnradar/replies.py b/vulnradar/replies.py index e3c3738..06337bf 100644 --- a/vulnradar/replies.py +++ b/vulnradar/replies.py @@ -22,19 +22,3 @@ def read_reply(model: Callable[[dict[str, Any]], T], data: dict[str, Any]) -> T: raise UnexpectedResponseError( f"The server's reply could not be read ({type(error).__name__}).", body=data ) from error - - -def read_scan_reply(model: Callable[[dict[str, Any]], T], data: dict[str, Any]) -> T: - """Like read_reply, but explain a scan the server has only started. - - Raises: - UnexpectedResponseError: If the reply is not a finished scan. - """ - if "scanId" in data and "findings" not in data and "crawl" not in data: - raise UnexpectedResponseError( - f"The server started scan {data['scanId']} and is running it in the " - "background. This version of the SDK cannot follow background scans yet; " - "the result will appear in your scan history.", - body=data, - ) - return read_reply(model, data) diff --git a/vulnradar/services/__init__.py b/vulnradar/services/__init__.py index fda72b1..0686910 100644 --- a/vulnradar/services/__init__.py +++ b/vulnradar/services/__init__.py @@ -1,13 +1,12 @@ -from .crawl_service import CrawlService from .discovery_service import DiscoveryService from .history_service import HistoryService from .metadata_service import MetadataService -from .scan_service import ScanService +from .scan_service import ScanOptions, ScanService __all__ = [ - "CrawlService", "DiscoveryService", "HistoryService", "MetadataService", + "ScanOptions", "ScanService", ] diff --git a/vulnradar/services/crawl_service.py b/vulnradar/services/crawl_service.py deleted file mode 100644 index a883b72..0000000 --- a/vulnradar/services/crawl_service.py +++ /dev/null @@ -1,35 +0,0 @@ -from __future__ import annotations - -from ..http import HTTPClient -from ..models.crawl import CrawlResult -from ..replies import read_scan_reply -from ..utils.url_validation import validate_url - - -class CrawlService: - """Handles deep crawl scanning across multiple pages of a target.""" - - def __init__(self, http: HTTPClient) -> None: - self._http = http - - def scan_crawl(self, url: str, urls: list[str] | None = None) -> CrawlResult: - """Run a deep crawl scan on a target URL. - - Args: - url: The root URL to crawl and scan. - urls: Optional list of additional URLs to include in the crawl. - - Returns: - A CrawlResult containing per-page findings and aggregate crawl info. - - Raises: - InvalidURLError: If any URL is malformed. - AuthenticationError: If the API key is invalid. - RateLimitError: If the rate limit is exceeded. - """ - validate_url(url) - payload: dict[str, object] = {"url": url} - if urls is not None: - payload["urls"] = urls - data = self._http.post("/scan/crawl", payload) - return read_scan_reply(CrawlResult.from_dict, data) diff --git a/vulnradar/services/history_service.py b/vulnradar/services/history_service.py index 86da25b..e02db80 100644 --- a/vulnradar/services/history_service.py +++ b/vulnradar/services/history_service.py @@ -1,21 +1,14 @@ from __future__ import annotations -import re - from ..http import HTTPClient from ..models.history import DeleteScanResult, HistoryList from ..models.scan_result import ScanResult from ..replies import read_reply - -# Numbers, and the longer text ids newer servers hand out. -_SCAN_ID = re.compile(r"[A-Za-z0-9_-]+") +from ..utils.scan_id import scan_id_segment def _scan_path(scan_id: int | str) -> str: - text = str(scan_id) - if not _SCAN_ID.fullmatch(text): - raise ValueError(f"Not a valid scan id: {text!r}") - return f"/history/{text}" + return f"/history/{scan_id_segment(scan_id)}" class HistoryService: diff --git a/vulnradar/services/scan_service.py b/vulnradar/services/scan_service.py index 24b4550..1fb5b66 100644 --- a/vulnradar/services/scan_service.py +++ b/vulnradar/services/scan_service.py @@ -1,35 +1,210 @@ from __future__ import annotations +import time +from collections.abc import Sequence +from typing import Any, TypedDict, Unpack + +from ..constants import ( + ACTIVE_PROBES, + DEFAULT_POLL_INTERVAL, + DEFAULT_WAIT_TIMEOUT, + MAX_FAILED_POLLS, +) +from ..enums import Scanner, ScanState +from ..exceptions import ( + NetworkError, + RateLimitError, + ScanFailedError, + ScanTimeoutError, + ServerError, + VulnRadarError, +) from ..http import HTTPClient from ..models.scan_result import ScanResult -from ..replies import read_scan_reply +from ..models.scan_status import ScanJob, ScanStatus +from ..replies import read_reply +from ..utils.scan_id import scan_id_segment from ..utils.url_validation import validate_url +class ScanOptions(TypedDict, total=False): + """Optional settings of a scan. Anything left out follows the account's own.""" + + public: bool + """List the result in the public directory, or keep it out.""" + capture_screenshot: bool + port_scan: bool + """Needs a verified domain.""" + team_ids: Sequence[int] + + +_FIELD_NAMES = { + "public": "isPublic", + "capture_screenshot": "captureScreenshot", + "port_scan": "portScan", + "team_ids": "teamIds", +} + +_SCANNER_NAMES = frozenset( + [scanner.value for scanner in Scanner] + [f"active-probes:{probe}" for probe in ACTIVE_PROBES] +) + + class ScanService: - """Handles single-URL security scans.""" + """Starts scans, follows them and cancels them.""" def __init__(self, http: HTTPClient) -> None: self._http = http - def scan(self, url: str, scanners: list[str] | None = None) -> ScanResult: - """Run a security scan against a single URL. + def start( + self, + url: str, + scanners: Sequence[str] | None = None, + **options: Unpack[ScanOptions], + ) -> ScanJob: + """Start a scan of one address and return without waiting for it. + + Args: + url: The target, with or without a scheme. + scanners: Scanner names to run; see Scanner. All the default ones if None. + + Raises: + InvalidURLError: If the target cannot be scanned. + ValueError: If a scanner name is unknown. + RateLimitError: If a limit or quota is used up. + """ + return self._start("/scan", _payload(url, scanners, options)) + + def start_crawl( + self, + url: str, + urls: Sequence[str] | None = None, + scanners: Sequence[str] | None = None, + **options: Unpack[ScanOptions], + ) -> ScanJob: + """Start a crawl of a site and return without waiting for it. + + Args: + url: Where the crawl starts. + urls: Pages to scan, on the same origin. The server finds them if None. + scanners: Scanner names to run; see Scanner. + """ + payload = _payload(url, scanners, options) + if urls is not None: + payload["urls"] = [validate_url(page) for page in urls] + return self._start("/scan/crawl", payload) + + def status(self, scan_id: int | str) -> ScanStatus: + """Ask where a scan stands. Asking does not use up any quota. + + Servers before 4.0 accept only the numeric id. + """ + return read_reply(ScanStatus.from_dict, self._http.get(_status_path(scan_id))) + + def wait( + self, + scan_id: int | str, + *, + timeout: float = DEFAULT_WAIT_TIMEOUT, + poll_interval: float = DEFAULT_POLL_INTERVAL, + ) -> ScanResult: + """Wait for a scan to finish and return its result. + + A few failed status requests in a row are tolerated. Every error raised + here carries the scan's id in ``scan_id``. Args: - url: The target URL to scan. Must be a valid supported URL. - scanners: Optional list of scanner IDs to run. If omitted, all scanners run. + scan_id: The scan to follow. + timeout: Seconds to wait before giving up. The scan keeps running. + poll_interval: Seconds between status requests. Returns: - A ScanResult containing findings, summary, and metadata. + A ScanResult, or a CrawlResult for a crawl. Raises: - InvalidURLError: If the URL is malformed. - AuthenticationError: If the API key is invalid. - RateLimitError: If the rate limit is exceeded. + ScanFailedError: If the scan failed or was cancelled. + ScanTimeoutError: If it is still unfinished after ``timeout``. """ - validate_url(url) - payload: dict[str, object] = {"url": url} - if scanners is not None: - payload["scanners"] = scanners - data = self._http.post("/scan", payload) - return read_scan_reply(ScanResult.from_dict, data) + check_positive(timeout=timeout, poll_interval=poll_interval) + deadline = time.monotonic() + timeout + failures = 0 + while True: + pause = poll_interval + try: + status = self.status(scan_id) + except (NetworkError, ServerError, RateLimitError) as error: + failures += 1 + asked = error.retry_after or 0 + pause = max(pause, asked) + if failures >= MAX_FAILED_POLLS or asked > deadline - time.monotonic(): + error.scan_id = scan_id + raise + except VulnRadarError as error: + error.scan_id = scan_id + raise + else: + failures = 0 + if status.result is not None: + return status.result + if status.state == ScanState.FAILED: + raise ScanFailedError( + scan_id, + status.error, + failure_kind=status.failure_kind, + body=status.raw, + ) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ScanTimeoutError(scan_id, timeout) + time.sleep(min(pause, remaining)) + + def cancel(self, scan_id: int | str) -> None: + """Stop a running scan. + + Raises: + VulnRadarError: With status 409 if the scan has already finished. + """ + read_reply(_confirm_cancelled, self._http.delete(_status_path(scan_id))) + + def _start(self, path: str, payload: dict[str, Any]) -> ScanJob: + return read_reply(ScanJob.from_dict, self._http.post(path, payload)) + + +def check_positive(**settings: float) -> None: + for name, value in settings.items(): + if value <= 0: + raise ValueError(f"{name} must be greater than zero.") + + +def _status_path(scan_id: int | str) -> str: + return f"/scan/status/{scan_id_segment(scan_id)}" + + +def _payload(url: str, scanners: Sequence[str] | None, options: ScanOptions) -> dict[str, Any]: + payload: dict[str, Any] = {"url": validate_url(url)} + if scanners is not None: + payload["scanners"] = _check_scanners(scanners) + for name, value in options.items(): + if name not in _FIELD_NAMES: + raise TypeError(f"Unknown scan option: {name}") + if value is not None: + payload[_FIELD_NAMES[name]] = list(value) if isinstance(value, Sequence) else value + return payload + + +def _check_scanners(scanners: Sequence[str]) -> list[str]: + # Older servers accept an unknown name and then run nothing, which looks clean. + if isinstance(scanners, str) or not scanners: + raise ValueError("scanners must be a non-empty list of scanner names, or None.") + unknown = [name for name in scanners if name not in _SCANNER_NAMES] + if unknown: + raise ValueError( + f"Unknown scanner: {', '.join(map(repr, unknown))}. Valid names are " + f"{', '.join(scanner.value for scanner in Scanner)} and active-probes:." + ) + return [str(name) for name in scanners] + + +def _confirm_cancelled(data: dict[str, Any]) -> None: + if data["cancelled"] is not True: + raise ValueError("cancelled") diff --git a/vulnradar/utils/scan_id.py b/vulnradar/utils/scan_id.py new file mode 100644 index 0000000..cb176bb --- /dev/null +++ b/vulnradar/utils/scan_id.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +import re + +# Numbers, and the longer text ids newer servers hand out. +_SCAN_ID = re.compile(r"[A-Za-z0-9_-]+") + + +def scan_id_segment(scan_id: int | str) -> str: + """Return a scan id that is safe to put in an address. + + Raises: + ValueError: If it holds anything that could change the address. + """ + text = str(scan_id) + if not _SCAN_ID.fullmatch(text): + raise ValueError(f"Not a valid scan id: {text!r}") + return text diff --git a/vulnradar/utils/url_validation.py b/vulnradar/utils/url_validation.py index 1d29723..cca1045 100644 --- a/vulnradar/utils/url_validation.py +++ b/vulnradar/utils/url_validation.py @@ -1,54 +1,59 @@ from __future__ import annotations -import re -from urllib.parse import urlparse +from urllib.parse import urlsplit from ..exceptions import InvalidURLError -_DOMAIN_RE = re.compile( - r"^(?:[a-zA-Z0-9]" - r"(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?" - r"\.)+[a-zA-Z]{2,}$" +# Everything any server version knows. Servers before 4.0 scan only http and https. +_SUPPORTED_SCHEMES = frozenset( + { + "http", + "https", + "ws", + "wss", + "ftp", + "ftps", + "ssh", + "sftp", + "smtp", + "smtps", + "imap", + "imaps", + "pop3", + "pop3s", + "mongodb", + } ) - -_SUPPORTED_SCHEMES = ("http", "https", "ws", "wss", "ftp", "ftps") +_MAX_LENGTH = 2048 def validate_url(url: str) -> str: - """Validate that a URL is a well-formed supported URL with a valid domain. + """Reject a target no server could scan. The server has the final say. + + An address without a scheme, such as ``example.com``, is accepted. Which + schemes can be scanned depends on the server's version. Args: - url: The URL string to validate. + url: The target address. Returns: - The original URL if validation passes. + The address unchanged. Raises: - InvalidURLError: If the URL is malformed or uses an unsupported scheme. + InvalidURLError: If the address is empty, too long, holds blanks, has no + host or uses an unsupported scheme. """ + if ( + not url + or len(url) > _MAX_LENGTH + or any(char.isspace() or not char.isprintable() for char in url) + ): + raise InvalidURLError(url) try: - parsed = urlparse(url) + parsed = urlsplit(url if "://" in url else f"https://{url}") + _ = parsed.port # raises ValueError for a port that is not a number except ValueError: raise InvalidURLError(url) from None - - if parsed.scheme not in _SUPPORTED_SCHEMES: - raise InvalidURLError(url) - - host = parsed.hostname or "" - if not host: - raise InvalidURLError(url) - - if not _DOMAIN_RE.match(host) and not _is_valid_ip(host): + if parsed.scheme not in _SUPPORTED_SCHEMES or not parsed.hostname: raise InvalidURLError(url) - return url - - -def _is_valid_ip(host: str) -> bool: - import ipaddress - - try: - ipaddress.ip_address(host) - return True - except ValueError: - return False From 46d0ade547b5de2b61e7c5f716cc494830c197b6 Mon Sep 17 00:00:00 2001 From: RejectModders Date: Sat, 28 Nov 2026 21:00:07 -0600 Subject: [PATCH 2/3] docs: describe scans, crawls and the new results --- CHANGELOG.md | 28 ++++++++++-- README.md | 124 ++++++++++++++++++++++++++++++++++----------------- 2 files changed, 106 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ebcebae..f79d98a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,12 +16,28 @@ dates on PyPI (UTC). `RateLimitKind`. `RateLimitInfo` is exported. - Errors carry `code`, `request_id`, `retry_after` and `body`, and a `RateLimitError` says which limit was reached in `kind`. +- `client.scans` starts scans and crawls, reports their progress, waits for them + and cancels them, with `ScanJob`, `ScanStatus`, `ScanState` and `ScanOptions`. +- `ScanFailedError` and `ScanTimeoutError`. An error raised while waiting names + the scan in `scan_id`. +- Scan options: `public`, `capture_screenshot`, `port_scan` and `team_ids`. +- `Scanner` lists the scanner names. +- Results keep the server's whole reply in `raw`, and have `public_id`, + `incomplete` and `tags`. Findings have their category, evidence, fix steps, + `suppressed` and `remediation_status` among other details. ### Changed -- The client calls the v3 API. Scans there run in the background, which it - cannot follow yet: `scan()` and `scan_crawl()` raise - `UnexpectedResponseError` naming the scan they started. +- The client calls the v3 API. `scan()` and `scan_crawl()` wait for the + background scan to finish, for 900 seconds unless `timeout` says otherwise. +- Scanner names are checked before a scan is sent. +- `ScanResult.duration` is now `duration_ms`, in milliseconds, and + `scanned_at` is `None` when the server gives no time. +- `CrawlResult` is a `ScanResult` with `pages`, `pages_discovered`, + `pages_scanned`, `pages_skipped` and `pages_unreachable`. +- An unfamiliar severity is `Severity.UNKNOWN`, not `info`. +- Targets without a scheme, with punycode or underscore host names, or using any + scheme the server knows are no longer rejected. - `retries` counts the attempts after the first, with a default of 2, and only reads are retried. - A web page in reply raises `UnexpectedResponseError`, not @@ -40,11 +56,14 @@ dates on PyPI (UTC). `high`. - `__version__` is read from the installed package, and is `unknown` when the source is used without being installed. -- The timestamp filled in when a reply has none is timezone-aware (UTC). +- The timestamp filled in when a history entry has none is timezone-aware (UTC). - The README now says that no published release works with the current API. ### Removed +- `Finding.type`, which the server never sends, and `Finding.remediation`; use + `fix_steps` and `remediation_status`. +- `CrawlInfo` and `CrawlResult.crawl`. - `vulnradar.utils.parse_rate_limit_headers`, and the `VERSION_URL` and `RATE_LIMIT_*_HEADER` constants. @@ -54,6 +73,7 @@ dates on PyPI (UTC). - Network failures, unreadable replies and odd rate limit headers raise SDK errors instead of other exceptions. - The version address keeps the path prefix of a self-hosted `base_url`. +- `history.get()` sets `scan_history_id`. ### Security diff --git a/README.md b/README.md index 1854c8e..a3eb489 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,10 @@ A Python SDK for the [VulnRadar](https://vulnradar.dev) security scanning API. > the console, so avoid it. Until a new release is out, call the > [v3 API](https://vulnradar.dev/docs/api) directly. > -> The code on `main` calls the v3 API but cannot yet follow a scan to its end: -> `scan()` and `scan_crawl()` start the scan and then raise `UnexpectedResponseError`, -> and `history.list()` cannot read the current reply. The sections on authentication, -> configuration, errors and rate limits describe `main`. The others still describe the -> old releases. +> The code on `main` calls the v3 API and runs scans and crawls, but `history.list()` +> cannot yet read the current reply. This page describes `main`, apart from the sections +> on listing history, finding types and the version check, which still describe the old +> releases. --- @@ -96,55 +95,102 @@ client = VulnRadar( ### Single URL Scan +The server runs a scan in the background. `scan()` starts it, asks every few seconds how +it is going, and returns the finished result. Asking does not use up any quota. + ```python +from vulnradar import Scanner + result = client.scan("https://example.com") -# Optional: run only selected scanners. -result = client.scan("https://example.com", scanners=["headers", "ssl"]) +# Optional: run only some scanners, keep the result out of the public directory, +# and wait no longer than two minutes. +result = client.scan( + "https://example.com", + scanners=[Scanner.HEADERS, Scanner.SSL], + public=False, + timeout=120, +) -print(result.url) -print(result.scanned_at) -print(result.duration) -print(result.scan_history_id) +print(result.url, result.scanned_at, result.duration_ms, result.scan_history_id) for finding in result.findings: - print(finding.type, finding.severity, finding.title) + print(finding.severity, finding.title) print(finding.description) - print(finding.remediation) + for step in finding.fix_steps: + print(" -", step) + +if result.incomplete: + print("Not everything was checked:", ", ".join(result.incomplete)) ``` -Supported target protocols: `http://`, `https://`, `ws://`, `wss://`, `ftp://`, `ftps://`. +A scan without findings is not necessarily clean: check `result.incomplete`, which lists +the areas the server could not check. Findings your account marked as false positives are +included, with `finding.suppressed` set. -**ScanResult fields:** +Scanner names are checked before anything is sent, because some servers accept a misspelt +one and then check nothing. The other options are `capture_screenshot`, `port_scan` (needs +a verified domain) and `team_ids`. -| Field | Type | Description | -|--------------------|-----------------------|------------------------------------| -| `url` | `str` | Scanned URL | -| `scanned_at` | `datetime` | Timestamp of the scan | -| `duration` | `float` | Scan duration in seconds | -| `findings` | `list[Finding]` | List of security findings | -| `summary` | `Summary` | Aggregated finding counts | -| `response_headers` | `dict[str, str]` | HTTP headers from the target | -| `scan_history_id` | `int \| None` | ID in scan history | -| `notes` | `str \| None` | Optional scan notes | +A target may be written without a scheme (`example.com`). Servers before 4.0 scan only +`http` and `https`. + +### Without waiting + +```python +job = client.scans.start("https://example.com") + +status = client.scans.status(job.id) +print(status.state, status.categories_completed, status.categories_total) + +result = client.scans.wait(job.id, timeout=600) # or client.scans.cancel(job.id) +``` + +`wait()` raises `ScanFailedError` if the scan fails or is cancelled, and `ScanTimeoutError` +if it is still running after `timeout` seconds. A scan that times out keeps running, so you +can wait for it again. Errors raised while waiting carry the scan's id in `scan_id`. + +### ScanResult fields + +| Field | Type | Description | +|---|---|---| +| `url` | `str` | Scanned address | +| `findings` | `list[Finding]` | Security findings | +| `summary` | `Summary` | Finding counts by severity | +| `incomplete` | `list[str]` | Areas that were not checked | +| `scanned_at` | `datetime \| None` | When the scan ran | +| `duration_ms` | `int \| None` | How long it took, in milliseconds | +| `scan_history_id` | `int \| None` | Id in your scan history | +| `public_id` | `str \| None` | Text id of the scan | +| `response_headers` | `dict[str, str]` | HTTP headers from the target | +| `tags` | `list[str]` | Tags on the scan | +| `notes` | `str \| None` | Your notes | +| `raw` | `dict` | Everything the server sent, such as `siteGrade` or `dnsRecords` | + +A `Finding` has `id`, `title`, `severity`, `description`, `category`, `evidence`, +`explanation`, `risk_impact`, `fix_steps`, `code_examples`, `references`, `suppressed`, +`remediation_status` and `raw`. --- ## Crawl Scans -Perform a deep crawl across multiple pages of a target: +Scan several pages of a site. Each page counts as one scan against your daily quota, and +your plan caps how many pages one crawl may take. ```python result = client.scan_crawl("https://example.com") -print(f"Pages scanned: {result.crawl.total_pages}") -print(f"Total findings: {result.crawl.total_findings}") +print(f"Pages scanned: {result.pages_scanned}, skipped: {result.pages_skipped}") +print(f"Total findings: {result.summary.total}") for page in result.pages: print(f"{page.url}: {page.summary.total} findings") ``` -You can also provide a list of specific URLs to include: +A `CrawlResult` is a `ScanResult` for the whole site, plus `pages`, `pages_discovered`, +`pages_scanned`, `pages_skipped` and `pages_unreachable`. You can name the pages to scan, +and start a crawl without waiting with `client.scans.start_crawl()`. ```python result = client.scan_crawl( @@ -278,6 +324,8 @@ Every error has `message`, `status_code`, `code` (the server's error code), `req | `NetworkError` | none | No complete reply arrived | | `RequestTimeoutError` | none | A `NetworkError`: no answer in time. A change may still have happened | | `UnexpectedResponseError` | any | A redirect, or a reply that cannot be understood | +| `ScanFailedError` | none | A scan failed or was cancelled | +| `ScanTimeoutError` | none | A scan did not finish in the time allowed | | `InvalidURLError` | none | A target failed the check made before sending | | `VulnRadarError` | other | The base class, also used for statuses such as 402, 409 and 413 | @@ -313,6 +361,7 @@ Severity.HIGH # "high" Severity.MEDIUM # "medium" Severity.LOW # "low" Severity.INFO # "info" +Severity.UNKNOWN # a level this version of the SDK does not know ``` Filter findings by severity: @@ -346,22 +395,13 @@ def read_scan(scan_id: int): return client.history.get(scan_id) ``` -**Use history to avoid redundant scans:** - -```python -history = client.history.list() -already_scanned = {s.url for s in history.scans} - -if target_url not in already_scanned: - result = client.scan(target_url) -``` - -**Pre-discover URLs before crawling:** +**Pre-discover pages before crawling:** ```python discovery = client.discover_urls("https://example.com") if discovery.total > 0: - result = client.scan_crawl("https://example.com", urls=discovery.urls) + # Keep within your plan's pages per crawl. + result = client.scan_crawl("https://example.com", urls=discovery.urls[:25]) ``` --- @@ -388,7 +428,7 @@ uv run pytest -m live ``` `VULNRADAR_API_BASE` points them at another server and `VULNRADAR_TEST_URL` changes the scan -target. Until the rebuild is finished they are expected to fail. +target. --- From 31b35bebc14809dda5711e6d15833b5b123a5390 Mon Sep 17 00:00:00 2001 From: RejectModders Date: Sat, 28 Nov 2026 21:44:08 -0600 Subject: [PATCH 3/3] fix: never let a partly checked scan look complete Servers before 4.0 do not mark a scan incomplete when checks fail to run, or a crawl incomplete when the quota cuts it short, so the SDK adds those marks itself. Waiting for a scan now makes one request per poll and gives none longer than the time left. Targets with a scheme later in the address or with surrounding blanks are accepted, summary counts that are not numbers are an error, and the default wait outlasts the server's crawl limit. --- CHANGELOG.md | 10 +++- README.md | 7 ++- tests/fake.py | 2 + tests/samples.py | 4 +- tests/test_client.py | 8 +++ tests/test_models.py | 71 +++++++++++++++++++++++++ tests/test_scans.py | 55 ++++++++++++++++++- tests/test_url_validation.py | 8 ++- vulnradar/constants.py | 3 +- vulnradar/http.py | 56 ++++++++++++------- vulnradar/models/crawl.py | 21 ++++++-- vulnradar/models/scan_result.py | 18 ++++--- vulnradar/models/summary.py | 23 +++++--- vulnradar/services/discovery_service.py | 3 +- vulnradar/services/scan_service.py | 13 ++++- vulnradar/utils/url_validation.py | 16 +++--- 16 files changed, 263 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f79d98a..a439647 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,12 +29,18 @@ dates on PyPI (UTC). ### Changed - The client calls the v3 API. `scan()` and `scan_crawl()` wait for the - background scan to finish, for 900 seconds unless `timeout` says otherwise. + background scan to finish, for 960 seconds unless `timeout` says otherwise. - Scanner names are checked before a scan is sent. - `ScanResult.duration` is now `duration_ms`, in milliseconds, and `scanned_at` is `None` when the server gives no time. - `CrawlResult` is a `ScanResult` with `pages`, `pages_discovered`, `pages_scanned`, `pages_skipped` and `pages_unreachable`. +- `CrawlPage.duration` is now `duration_ms`, and `ScanResult`, `Finding` and + `CrawlPage` take different constructor arguments. +- `incomplete` also holds `page-checks` when checks failed to run, and + `crawl-pages-not-scanned` when a crawl left pages out, for servers that do not + say so themselves. +- Summary counts that are not numbers are an error. - An unfamiliar severity is `Severity.UNKNOWN`, not `info`. - Targets without a scheme, with punycode or underscore host names, or using any scheme the server knows are no longer rejected. @@ -63,7 +69,7 @@ dates on PyPI (UTC). - `Finding.type`, which the server never sends, and `Finding.remediation`; use `fix_steps` and `remediation_status`. -- `CrawlInfo` and `CrawlResult.crawl`. +- `CrawlInfo`, `CrawlResult.crawl` and `CrawlPage.response_headers`. - `vulnradar.utils.parse_rate_limit_headers`, and the `VERSION_URL` and `RATE_LIMIT_*_HEADER` constants. diff --git a/README.md b/README.md index a3eb489..bafe4d8 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,9 @@ if result.incomplete: ``` A scan without findings is not necessarily clean: check `result.incomplete`, which lists -the areas the server could not check. Findings your account marked as false positives are +what was not checked. `page-checks` means some checks failed to run, and +`crawl-pages-not-scanned` means a crawl left pages out, for example when your quota ran +out. Findings your account marked as false positives are included, with `finding.suppressed` set. Scanner names are checked before anything is sent, because some servers accept a misspelt @@ -146,6 +148,7 @@ print(status.state, status.categories_completed, status.categories_total) result = client.scans.wait(job.id, timeout=600) # or client.scans.cancel(job.id) ``` +`scan()` and `wait()` wait 960 seconds unless you pass `timeout`. `wait()` raises `ScanFailedError` if the scan fails or is cancelled, and `ScanTimeoutError` if it is still running after `timeout` seconds. A scan that times out keeps running, so you can wait for it again. Errors raised while waiting carry the scan's id in `scan_id`. @@ -157,7 +160,7 @@ can wait for it again. Errors raised while waiting carry the scan's id in `scan_ | `url` | `str` | Scanned address | | `findings` | `list[Finding]` | Security findings | | `summary` | `Summary` | Finding counts by severity | -| `incomplete` | `list[str]` | Areas that were not checked | +| `incomplete` | `list[str]` | What was not checked | | `scanned_at` | `datetime \| None` | When the scan ran | | `duration_ms` | `int \| None` | How long it took, in milliseconds | | `scan_history_id` | `int \| None` | Id in your scan history | diff --git a/tests/fake.py b/tests/fake.py index fdcf703..588fbc6 100644 --- a/tests/fake.py +++ b/tests/fake.py @@ -19,6 +19,7 @@ def __init__(self) -> None: super().__init__() self.sent: list[PreparedRequest] = [] self.proxies_used: list[dict[str, str]] = [] + self.timeouts_used: list[float] = [] self._outcomes: list[Response | Exception] = [] def reply( @@ -50,6 +51,7 @@ def send( ) -> Response: self.sent.append(request) self.proxies_used.append(dict(proxies or {})) + self.timeouts_used.append(timeout) assert self._outcomes, f"no reply queued for {request.method} {request.url}" outcome = self._outcomes.pop(0) if len(self._outcomes) > 1 else self._outcomes[0] if isinstance(outcome, Exception): diff --git a/tests/samples.py b/tests/samples.py index 0e88806..3ae2f30 100644 --- a/tests/samples.py +++ b/tests/samples.py @@ -80,7 +80,7 @@ def completed(version: str = "3.9.2", **extra: Any) -> dict[str, Any]: def failed(version: str = "3.9.2", message: str = "The target did not answer.") -> dict[str, Any]: - body: dict[str, Any] = {**progress("failed"), "error": message} + body: dict[str, Any] = {**progress("failed"), "currentCategory": None, "error": message} del body["partialFindings"] if version == "4.0.0": body |= {"errorMessage": message, "failureKind": "unreachable"} @@ -97,7 +97,7 @@ def crawl(version: str = "3.9.2") -> dict[str, Any]: "duration": 900, } details: dict[str, Any] = { - "pagesDiscovered": 3, + "pagesDiscovered": 4, "pagesScanned": 1, "pagesSkipped": 2, "pages": [page], diff --git a/tests/test_client.py b/tests/test_client.py index 9782773..06b9de5 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -92,3 +92,11 @@ def test_an_invalid_target_is_rejected_before_anything_is_sent( getattr(client, method)("not a url") assert transport.sent == [] + + +def test_the_trimmed_target_is_what_gets_sent(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body={"urls": []}) + + client.discover_urls(" https://example.com ") + + assert transport.sent_json() == {"url": "https://example.com"} diff --git a/tests/test_models.py b/tests/test_models.py index 8efad06..3d0d389 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -101,3 +101,74 @@ def test_a_crawl_result_is_a_scan_result_with_pages() -> None: def test_a_delete_without_a_message_gets_one() -> None: assert DeleteScanResult.from_dict({"success": True}).message == "Scan deleted successfully" assert DeleteScanResult.from_dict({"success": False}).message == "" + + +def crawled(**counts: object) -> CrawlResult: + body = samples.crawl()["result"] + body["crawl"] |= counts + return CrawlResult.from_dict(body) + + +@pytest.mark.parametrize( + "counts", + [ + # The daily quota cut the page list short before the crawl began. + {"pagesDiscovered": 10, "pagesScanned": 2, "pagesSkipped": 8}, + # It ran out partway: the dropped pages are counted nowhere. + {"pagesDiscovered": 10, "pagesScanned": 2, "pagesSkipped": 0}, + {"pagesDiscovered": 1, "pagesScanned": 1, "pagesSkipped": 1}, + { + "pagesDiscovered": 1, + "pagesScanned": 1, + "pagesSkipped": 0, + "pagesUnreachable": [{"url": "https://example.com/gone", "reason": "404"}], + }, + ], +) +def test_a_crawl_that_left_pages_out_is_incomplete(counts: dict[str, object]) -> None: + assert crawled(**counts).incomplete == ["crawl-pages-not-scanned"] + + +def test_a_crawl_of_every_page_is_complete() -> None: + assert crawled(pagesDiscovered=1, pagesScanned=1, pagesSkipped=0).incomplete == [] + + +def test_the_servers_own_crawl_marker_is_enough() -> None: + body = samples.crawl("4.0.0")["result"] | {"incomplete": ["crawl-quota-limit"]} + + assert CrawlResult.from_dict(body).incomplete == ["crawl-quota-limit"] + + +@pytest.mark.parametrize( + ("extra", "incomplete"), + [ + ({"checksErrored": 3}, ["page-checks"]), + ({"checksErrored": 0}, []), + ({"checksErrored": 2, "incomplete": ["dns", "page-checks"]}, ["dns", "page-checks"]), + ({"checksErrored": 1, "incomplete": ["dns"]}, ["dns", "page-checks"]), + ], +) +def test_checks_that_failed_to_run_make_a_scan_incomplete( + extra: dict[str, object], incomplete: list[str] +) -> None: + assert ScanResult.from_dict(samples.result() | extra).incomplete == incomplete + + +@pytest.mark.parametrize( + "counts", + [ + {"total": None}, + {"total": "many"}, + {"total": 1, "critical": "one"}, + {"total": 1, "high": None}, + ], +) +def test_a_summary_with_unreadable_counts_is_refused(counts: dict[str, object]) -> None: + with pytest.raises(TypeError): + ScanResult.from_dict(samples.result(summary=counts)) + + +def test_counts_written_as_text_become_numbers() -> None: + result = ScanResult.from_dict(samples.result(summary={"total": "2", "high": "2"})) + + assert (result.summary.total, result.summary.high, result.summary.low) == (2, 2, 0) diff --git a/tests/test_scans.py b/tests/test_scans.py index 1a1d561..4461f7a 100644 --- a/tests/test_scans.py +++ b/tests/test_scans.py @@ -123,7 +123,8 @@ def test_a_crawl_returns_its_pages( "scanners": ["headers"], } assert isinstance(result, CrawlResult) - assert (result.pages_discovered, result.pages_scanned, result.pages_skipped) == (3, 1, 2) + assert (result.pages_discovered, result.pages_scanned, result.pages_skipped) == (4, 1, 2) + assert result.incomplete == ["crawl-pages-not-scanned"] assert result.pages[0].url == "https://example.com/login" assert result.pages[0].summary.medium == 1 assert result.pages[0].scan_history_id == 4712 @@ -363,3 +364,55 @@ def test_a_start_reply_without_a_scan_number_is_an_error( with pytest.raises(UnexpectedResponseError): client.scans.start("https://example.com") + + +@pytest.mark.parametrize( + "failure", + [ + requests.exceptions.ConnectionError(), + requests.exceptions.ReadTimeout(), + ], +) +def test_a_poll_is_not_retried_underneath_the_wait( + client: VulnRadar, transport: FakeTransport, clock: Clock, failure: Exception +) -> None: + transport.fail(failure) + + with pytest.raises(NetworkError): + client.scans.wait(4711, timeout=600) + + assert len(transport.sent) == 5 + + +def test_a_busy_server_is_asked_once_per_poll( + client: VulnRadar, transport: FakeTransport, clock: Clock +) -> None: + transport.reply(503, {"error": "paused"}, headers={"Retry-After": "30"}) + + with pytest.raises(ServerError): + client.scans.wait(4711, timeout=600) + + assert len(transport.sent) == 5 + assert clock.sleeps == [30.0, 30.0, 30.0, 30.0] + + +def test_a_request_is_not_given_longer_than_the_wait_has_left( + client: VulnRadar, transport: FakeTransport, clock: Clock +) -> None: + transport.reply(body=samples.progress()) + + with pytest.raises(ScanTimeoutError): + client.scans.wait(4711, timeout=40, poll_interval=15) + + # 40, 25 and 10 seconds were left; the last look happens at the deadline. + assert transport.timeouts_used == [30.0, 25.0, 10.0, 1.0] + + +def test_asking_for_status_directly_still_retries( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(502, {"error": "bad gateway"}) + transport.reply(body=samples.progress()) + + assert client.scans.status(4711).state == ScanState.RUNNING + assert len(transport.sent) == 2 diff --git a/tests/test_url_validation.py b/tests/test_url_validation.py index 74b0e36..f15263e 100644 --- a/tests/test_url_validation.py +++ b/tests/test_url_validation.py @@ -15,6 +15,7 @@ "ssh://example.com", "mongodb://db.example.com:27017", "example.com", + "example.com/?next=https://elsewhere.example", "example.com/path", "https://xn--bcher-kva.xn--p1ai", "http://my_host.example.com", @@ -35,7 +36,7 @@ def test_web_addresses_are_accepted(url: str) -> None: "file:///etc/passwd", "https://[oops", "https://exa mple.com", - "https://example.com/\n", + "https://example.com/a b", "https://" + "a" * 2048, ], ) @@ -44,3 +45,8 @@ def test_other_input_is_rejected(url: str) -> None: validate_url(url) assert caught.value.url == url + + +@pytest.mark.parametrize("url", [" https://example.com ", "https://example.com/\n"]) +def test_surrounding_blanks_are_trimmed(url: str) -> None: + assert validate_url(url) == url.strip() diff --git a/vulnradar/constants.py b/vulnradar/constants.py index c01adeb..1ec2d87 100644 --- a/vulnradar/constants.py +++ b/vulnradar/constants.py @@ -10,7 +10,8 @@ # A server asking for a longer wait than this is reported to the caller instead. MAX_RETRY_WAIT: float = 30.0 -DEFAULT_WAIT_TIMEOUT: float = 900.0 # the longest the server lets a crawl run +# A minute past the longest the server lets a crawl run, to hear how it ended. +DEFAULT_WAIT_TIMEOUT: float = 960.0 DEFAULT_POLL_INTERVAL: float = 3.0 MAX_FAILED_POLLS: int = 5 diff --git a/vulnradar/http.py b/vulnradar/http.py index 4e8843a..1b7f2dd 100644 --- a/vulnradar/http.py +++ b/vulnradar/http.py @@ -78,9 +78,20 @@ def __init__(self, config: VulnRadarConfig) -> None: # would receive the request, key and all, unencrypted. self._session.trust_env = False - def get(self, path: str) -> dict[str, Any]: - """Read from an API path such as '/history'.""" - return self._request("GET", self._config.base_url + path) + @property + def timeout(self) -> float: + """Seconds a request is given by default.""" + return self._config.timeout + + def get( + self, path: str, *, retries: int | None = None, timeout: float | None = None + ) -> dict[str, Any]: + """Read from an API path such as '/history'. + + ``retries`` and ``timeout`` replace the client's own for this request. + """ + url = self._config.base_url + path + return self._request("GET", url, retries=retries, timeout=timeout) def get_version(self) -> dict[str, Any]: """Read the version endpoint, which sits beside the versioned API. @@ -103,13 +114,19 @@ def _request( method: str, url: str, json: dict[str, Any] | None = None, + retries: int | None = None, + timeout: float | None = None, ) -> dict[str, Any]: + if retries is None: + retries = self._config.retries + if timeout is None: + timeout = self._config.timeout # Only reads are repeated: sending a scan twice runs it, and counts it, twice. - attempts = 1 + (self._config.retries if method == "GET" else 0) + attempts = 1 + (retries if method == "GET" else 0) attempt = 1 while True: try: - return self._send(method, url, json) + return self._send(method, url, json, timeout) except (NetworkError, ServerError) as error: wait = error.retry_after if wait is None: @@ -119,34 +136,37 @@ def _request( time.sleep(wait) attempt += 1 - def _send(self, method: str, url: str, json: dict[str, Any] | None) -> dict[str, Any]: + def _send( + self, method: str, url: str, json: dict[str, Any] | None, timeout: float + ) -> dict[str, Any]: try: response = self._session.request( method, url, json=json, - timeout=self._config.timeout, + timeout=timeout, # A redirect could carry the key somewhere it was never meant to go. allow_redirects=False, ) except requests.exceptions.RequestException as error: - failure = self._network_failure(method, error) + failure = _network_failure(method, error, timeout) else: return _read(response) # Raised outside the except block so the requests error is not attached # to it: that error holds the request, and the request holds the key. raise failure - def _network_failure( - self, method: str, error: requests.exceptions.RequestException - ) -> NetworkError: - name = type(error).__name__ - if not isinstance(error, requests.exceptions.Timeout): - return NetworkError(f"The request did not complete ({name}).") - message = f"No answer within {self._config.timeout} seconds ({name})." - if method != "GET": - message += " The request may still have been carried out." - return RequestTimeoutError(message) + +def _network_failure( + method: str, error: requests.exceptions.RequestException, timeout: float +) -> NetworkError: + name = type(error).__name__ + if not isinstance(error, requests.exceptions.Timeout): + return NetworkError(f"The request did not complete ({name}).") + message = f"No answer within {timeout:g} seconds ({name})." + if method != "GET": + message += " The request may still have been carried out." + return RequestTimeoutError(message) def _read(response: Response) -> dict[str, Any]: diff --git a/vulnradar/models/crawl.py b/vulnradar/models/crawl.py index ed7e9de..59eec21 100644 --- a/vulnradar/models/crawl.py +++ b/vulnradar/models/crawl.py @@ -49,13 +49,24 @@ def _fields(cls, data: dict[str, Any]) -> dict[str, Any]: pages = [CrawlPage.from_dict(page) for page in required_list(crawl, "pages")] discovered = integer(crawl.get("pagesDiscovered")) scanned = integer(crawl.get("pagesScanned")) + discovered = len(pages) if discovered is None else discovered + scanned = len(pages) if scanned is None else scanned + skipped = integer(crawl.get("pagesSkipped")) or 0 + unreachable = objects(crawl.get("pagesUnreachable")) + + fields = super()._fields(data) + # Servers before 4.0 do not say a crawl is incomplete when the quota cuts + # it short, and pages dropped partway appear only as a lower scanned count. + left_out = scanned < discovered or skipped > 0 or bool(unreachable) + if left_out and not any(area.startswith("crawl-") for area in fields["incomplete"]): + fields["incomplete"].append("crawl-pages-not-scanned") return { - **super()._fields(data), + **fields, "pages": pages, - "pages_discovered": len(pages) if discovered is None else discovered, - "pages_scanned": len(pages) if scanned is None else scanned, - "pages_skipped": integer(crawl.get("pagesSkipped")) or 0, - "pages_unreachable": objects(crawl.get("pagesUnreachable")), + "pages_discovered": discovered, + "pages_scanned": scanned, + "pages_skipped": skipped, + "pages_unreachable": unreachable, } diff --git a/vulnradar/models/scan_result.py b/vulnradar/models/scan_result.py index 42a4b05..cae03ff 100644 --- a/vulnradar/models/scan_result.py +++ b/vulnradar/models/scan_result.py @@ -14,8 +14,8 @@ class ScanResult: """A finished scan. Check ``incomplete`` before treating a scan without findings as clean: it - lists the areas the server could not check. Everything the server sent, - such as ``siteGrade`` or ``dnsRecords``, is in ``raw``. + lists what was not checked. Everything the server sent, such as + ``siteGrade`` or ``dnsRecords``, is in ``raw``. """ url: str @@ -48,17 +48,21 @@ def _fields(cls, data: dict[str, Any]) -> dict[str, Any]: "public_id": text(data.get("scanPublicId")) or text(data.get("publicId")), "response_headers": mapping(data.get("responseHeaders")), "notes": text(data.get("notes")), - "incomplete": _incomplete(data.get("incomplete")), + "incomplete": _incomplete(data), "tags": _tags(data.get("tags")), "raw": data, } -def _incomplete(value: object) -> list[str]: +def _incomplete(data: dict[str, Any]) -> list[str]: # Anything here means part of the scan is missing, whatever shape it takes. - if not value: - return [] - return [str(item) for item in value] if isinstance(value, list) else [str(value)] + value = data.get("incomplete") + items = value if isinstance(value, list) else [value] + areas = [str(item) for item in items] if value else [] + # Servers before 4.0 count the checks that failed to run without listing them here. + if (integer(data.get("checksErrored")) or 0) > 0 and "page-checks" not in areas: + areas.append("page-checks") + return areas def _tags(value: object) -> list[str]: diff --git a/vulnradar/models/summary.py b/vulnradar/models/summary.py index 0386fdb..75ccecb 100644 --- a/vulnradar/models/summary.py +++ b/vulnradar/models/summary.py @@ -3,6 +3,8 @@ from dataclasses import dataclass from typing import Any +from .fields import integer + @dataclass class Summary: @@ -25,10 +27,19 @@ def of_finished_scan(cls, data: dict[str, Any]) -> Summary: @classmethod def from_dict(cls, data: dict[str, Any]) -> Summary: return cls( - total=data.get("total", 0), - critical=data.get("critical", 0), - high=data.get("high", 0), - medium=data.get("medium", 0), - low=data.get("low", 0), - info=data.get("info", 0), + total=_count(data, "total"), + critical=_count(data, "critical"), + high=_count(data, "high"), + medium=_count(data, "medium"), + low=_count(data, "low"), + info=_count(data, "info"), ) + + +def _count(data: dict[str, Any], name: str) -> int: + if name not in data: + return 0 + value = integer(data[name]) + if value is None: # reading it as zero could hide findings + raise TypeError(name) + return value diff --git a/vulnradar/services/discovery_service.py b/vulnradar/services/discovery_service.py index cb271a6..19397ff 100644 --- a/vulnradar/services/discovery_service.py +++ b/vulnradar/services/discovery_service.py @@ -25,6 +25,5 @@ def discover_urls(self, url: str) -> DiscoveryResult: InvalidURLError: If the URL is malformed. AuthenticationError: If the API key is invalid. """ - validate_url(url) - data = self._http.post("/scan/crawl/discover", {"url": url}) + data = self._http.post("/scan/crawl/discover", {"url": validate_url(url)}) return read_reply(DiscoveryResult.from_dict, data) diff --git a/vulnradar/services/scan_service.py b/vulnradar/services/scan_service.py index 1fb5b66..b9de681 100644 --- a/vulnradar/services/scan_service.py +++ b/vulnradar/services/scan_service.py @@ -99,7 +99,7 @@ def status(self, scan_id: int | str) -> ScanStatus: Servers before 4.0 accept only the numeric id. """ - return read_reply(ScanStatus.from_dict, self._http.get(_status_path(scan_id))) + return self._status(scan_id) def wait( self, @@ -130,8 +130,11 @@ def wait( failures = 0 while True: pause = poll_interval + # This loop does the retrying, so that one poll is one request and + # none is given longer than the wait has left (but at least a second). + allowed = min(self._http.timeout, max(deadline - time.monotonic(), 1.0)) try: - status = self.status(scan_id) + status = self._status(scan_id, retries=0, timeout=allowed) except (NetworkError, ServerError, RateLimitError) as error: failures += 1 asked = error.retry_after or 0 @@ -166,6 +169,12 @@ def cancel(self, scan_id: int | str) -> None: """ read_reply(_confirm_cancelled, self._http.delete(_status_path(scan_id))) + def _status( + self, scan_id: int | str, *, retries: int | None = None, timeout: float | None = None + ) -> ScanStatus: + reply = self._http.get(_status_path(scan_id), retries=retries, timeout=timeout) + return read_reply(ScanStatus.from_dict, reply) + def _start(self, path: str, payload: dict[str, Any]) -> ScanJob: return read_reply(ScanJob.from_dict, self._http.post(path, payload)) diff --git a/vulnradar/utils/url_validation.py b/vulnradar/utils/url_validation.py index cca1045..072ed23 100644 --- a/vulnradar/utils/url_validation.py +++ b/vulnradar/utils/url_validation.py @@ -1,5 +1,6 @@ from __future__ import annotations +import re from urllib.parse import urlsplit from ..exceptions import InvalidURLError @@ -25,6 +26,8 @@ } ) _MAX_LENGTH = 2048 +# The servers add https:// to anything that does not start with a scheme. +_HAS_SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://") def validate_url(url: str) -> str: @@ -37,23 +40,24 @@ def validate_url(url: str) -> str: url: The target address. Returns: - The address unchanged. + The address without surrounding blanks. Raises: InvalidURLError: If the address is empty, too long, holds blanks, has no host or uses an unsupported scheme. """ + target = url.strip() if ( - not url - or len(url) > _MAX_LENGTH - or any(char.isspace() or not char.isprintable() for char in url) + not target + or len(target) > _MAX_LENGTH + or any(char.isspace() or not char.isprintable() for char in target) ): raise InvalidURLError(url) try: - parsed = urlsplit(url if "://" in url else f"https://{url}") + parsed = urlsplit(target if _HAS_SCHEME.match(target) else f"https://{target}") _ = parsed.port # raises ValueError for a port that is not a number except ValueError: raise InvalidURLError(url) from None if parsed.scheme not in _SUPPORTED_SCHEMES or not parsed.hostname: raise InvalidURLError(url) - return url + return target