From 81efaa5d3f9c2a6ff4b6ce54814f3bb7de4f1598 Mon Sep 17 00:00:00 2001 From: RejectModders Date: Sun, 29 Nov 2026 04:52:27 -0600 Subject: [PATCH 1/2] feat: add the remaining endpoints and webhook verification Bulk and signed-in scans, AI review and summaries, subdomain search, host reputation, the demo scan and a webhook signature check. A lost login marks the result incomplete, and addresses get a scheme where the server needs one. --- CHANGELOG.md | 6 + README.md | 57 ++++++ tests/test_extras.py | 257 ++++++++++++++++++++++++ tests/test_webhooks.py | 81 ++++++++ vulnradar/__init__.py | 2 + vulnradar/client.py | 34 +++- vulnradar/constants.py | 3 + vulnradar/http.py | 12 +- vulnradar/models/scan_result.py | 4 + vulnradar/replies.py | 11 + vulnradar/services/discovery_service.py | 38 +++- vulnradar/services/history_service.py | 18 +- vulnradar/services/scan_service.py | 92 ++++++++- vulnradar/utils/scan_id.py | 4 +- vulnradar/utils/url_validation.py | 6 + vulnradar/webhooks.py | 61 ++++++ 16 files changed, 673 insertions(+), 13 deletions(-) create mode 100644 tests/test_extras.py create mode 100644 tests/test_webhooks.py create mode 100644 vulnradar/webhooks.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 11a7b20..75cbba3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,11 @@ dates on PyPI (UTC). `ReportFormat`. - `client.me()` returns the `Account` behind the key, and `metadata.plan_limits()` the published plan limits. +- Bulk and signed-in scans (`scans.bulk()`, `scans.authenticated()`), AI review + (`scans.verify()`, `verify_batch()`, `history.summary()`), subdomain search + (`discovery.subdomains()`, `subdomain_progress()`), `reputation()`, + `demo_scan()` and `verify_webhook()`. +- `incomplete` holds `authenticated-session` when a login was lost. - `NoResultError` for a stored scan that is still running or failed, raised by `history.get()` and `history.report()`. A `Report` says what the scan did not check in `incomplete`. @@ -67,6 +72,7 @@ dates on PyPI (UTC). 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. +- `discover_urls()` adds `https://` to an address without a scheme. - A web page in reply raises `UnexpectedResponseError`, not `AuthenticationError`. - A reply without the fields a result needs raises `UnexpectedResponseError` diff --git a/README.md b/README.md index 3dc5def..85dab2e 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,63 @@ for url in discovery.urls: --- +## More Scanning + +```python +# Queue many addresses. Wait for each with client.scans.wait(entry["scanId"]). +queued = client.scans.bulk(["https://example.com", "https://example.org"]) +for entry in queued["results"]: + print(entry["url"], entry.get("scanId") or entry.get("error")) + +# Scan while signed in. This returns when the scan is done. +result = client.scans.authenticated( + "https://example.com/account", + {"method": "header", "headerName": "Authorization", "headerValue": "Bearer ..."}, +) +print(result.summary.total, result.incomplete) + +names = client.discovery.subdomains("example.com")["subdomains"] +verdict = client.reputation("example.com") +demo = client.demo_scan("example.com") # a few per day per network address +``` + +The login is sent to the server as you give it: `form` with `username` and `password` +(your domain must be verified; `loginUrl` and the field names are optional), `header` +with `headerValue`, or `cookie` with `cookies` as a list of `name` and `value`. If the +session was lost, `result.incomplete` includes `authenticated-session`. + +`bulk()`, `subdomains()` and `reputation()` return the server's reply as a dictionary. +A reputation that is not `known` does not mean a host is safe. + +With the server's AI turned on, you can review findings and summarise a scan: + +```python +reviewed = client.scans.verify(123) +text = client.history.summary(123) +``` + +--- + +## Webhooks + +Check each delivery against your webhook's secret, using the raw request body: + +```python +from vulnradar import verify_webhook + + +def handle(body: bytes, headers: dict[str, str]) -> int: + if not verify_webhook("your-webhook-secret", body, headers): + return 401 + return 204 +``` + +Servers from 4.0 also sign a timestamp. If yours does, pass `require_timestamp=True`, so +an old delivery cannot be sent to you again. Deliveries can be repeated, so make your +handler safe to run twice. Before 4.0, test deliveries are not signed. + +--- + ## Scan History GitHub repository scans are not part of this history. diff --git a/tests/test_extras.py b/tests/test_extras.py new file mode 100644 index 0000000..ffa9c76 --- /dev/null +++ b/tests/test_extras.py @@ -0,0 +1,257 @@ +"""Bulk and signed-in scans, subdomains, reputation, AI review, the demo scan.""" + +from __future__ import annotations + +from collections.abc import Callable +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 ( + AuthenticationError, + Finding, + InvalidURLError, + RequestTimeoutError, + Severity, + UnexpectedResponseError, + VulnRadar, +) + +LOGIN = {"method": "form", "username": "demo", "password": "hunter2-secret"} + + +def sent(transport: FakeTransport) -> tuple[str, str]: + return str(transport.sent[-1].method), str(transport.sent[-1].url).removeprefix(BASE_URL) + + +def test_bulk_scans_are_queued(client: VulnRadar, transport: FakeTransport) -> None: + reply = { + "total": 1, + "queued": 1, + "failed": 0, + "skipped": 0, + "results": [{"url": "https://example.com/", "success": True, "scanId": 5}], + } + transport.reply(body=reply) + + queued = client.scans.bulk([" example.com "], public=False, team_ids=[3]) + + assert queued == reply + assert sent(transport) == ("POST", "/scan/bulk") + assert transport.sent_json() == { + "urls": ["https://example.com"], + "isPublic": False, + "teamIds": [3], + } + + +@pytest.mark.parametrize("urls", [[], "https://example.com", ["a.com"] * 101]) +def test_an_impossible_bulk_request_is_not_sent( + client: VulnRadar, transport: FakeTransport, urls: Any +) -> None: + with pytest.raises(ValueError, match="urls"): + client.scans.bulk(urls) + with pytest.raises(InvalidURLError): + client.scans.bulk(["not a url"]) + + assert transport.sent == [] + + +def signed_in(status: str, **extra: Any) -> dict[str, Any]: + report = {"status": status, "method": "form"} + return samples.result(authReport=report, persisted=True, **extra) + + +def test_a_signed_in_scan_returns_its_result_at_once( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body=signed_in("authenticated")) + + result = client.scans.authenticated("https://example.com", LOGIN, scanners=["headers"]) + + assert sent(transport) == ("POST", "/scan/authenticated") + assert transport.sent_json() == { + "url": "https://example.com", + "auth": LOGIN, + "scanners": ["headers"], + } + assert result.incomplete == [] + assert result.raw["authReport"]["status"] == "authenticated" + assert transport.timeouts_used == [330.0] + + +@pytest.mark.parametrize("status", ["lost", "failed"]) +def test_a_scan_that_lost_its_session_is_incomplete( + client: VulnRadar, transport: FakeTransport, status: str +) -> None: + transport.reply(body=signed_in(status)) + + result = client.scans.authenticated("https://example.com", LOGIN) + + assert result.incomplete == ["authenticated-session"] + + +def test_a_signed_in_scan_is_sent_once_and_keeps_the_password_to_itself( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.fail(requests.exceptions.ReadTimeout()) + + with pytest.raises(RequestTimeoutError) as caught: + client.scans.authenticated("https://example.com", LOGIN) + + assert len(transport.sent) == 1 + assert "hunter2" not in f"{caught.value!r} {caught.value.body}" + assert caught.value.__context__ is None + + +@pytest.mark.parametrize("auth", [{}, {"method": "magic"}, None]) +def test_a_login_without_a_known_method_is_not_sent( + client: VulnRadar, transport: FakeTransport, auth: Any +) -> None: + with pytest.raises(ValueError, match="method"): + client.scans.authenticated("https://example.com", auth) + + assert transport.sent == [] + + +def test_findings_can_be_reviewed_by_scan(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body={"success": True, "findings": [samples.finding(aiVerdict="confirmed")]}) + + findings = client.scans.verify(4711) + + assert sent(transport) == ("POST", "/scan/verify") + assert transport.sent_json() == {"scanHistoryId": 4711} + assert findings[0].raw["aiVerdict"] == "confirmed" + + +def test_findings_can_be_reviewed_on_their_own(client: VulnRadar, transport: FakeTransport) -> None: + finding = Finding.from_dict(samples.finding()) + transport.reply(body={"findings": [samples.finding("low")]}) + + reviewed = client.scans.verify_batch("https://example.com", [finding]) + + assert transport.sent_json() == {"url": "https://example.com", "findings": [finding.raw]} + assert reviewed[0].severity is Severity.LOW + + +@pytest.mark.parametrize("count", [0, 51]) +def test_a_review_of_none_or_too_many_findings_is_not_sent( + client: VulnRadar, transport: FakeTransport, count: int +) -> None: + findings = [Finding.from_dict(samples.finding())] * count + + with pytest.raises(ValueError, match="findings"): + client.scans.verify_batch("https://example.com", findings) + + assert transport.sent == [] + + +@pytest.mark.parametrize(("regenerate", "query"), [(False, ""), (True, "?regenerate=true")]) +def test_a_scan_can_be_summarised( + client: VulnRadar, transport: FakeTransport, regenerate: bool, query: str +) -> None: + transport.reply(body={"success": True, "summary": "Two problems."}) + + assert client.history.summary(4711, regenerate=regenerate) == "Two problems." + assert sent(transport) == ("POST", f"/history/4711/summary{query}") + + +def test_subdomains_and_their_progress(client: VulnRadar, transport: FakeTransport) -> None: + found = {"domain": "example.com", "subdomains": [], "total": 0} + transport.reply(body=found) + transport.reply(body={"stage": "done", "stageIndex": 4, "stagesTotal": 4}) + + assert ( + client.discovery.subdomains("https://example.com", force_refresh=True, request_id="job-1") + == found + ) + assert transport.sent_json(0) == { + "url": "https://example.com", + "forceRefresh": True, + "requestId": "job-1", + } + assert client.discovery.subdomain_progress("job-1")["stage"] == "done" + assert sent(transport) == ("GET", "/scan/discover/progress/job-1") + + +@pytest.mark.parametrize( + ("url", "query"), + [ + (None, "?host=example.com"), + ("https://example.com/a", "?host=example.com&url=https%3A%2F%2Fexample.com%2Fa"), + ], +) +def test_reputation( + client: VulnRadar, transport: FakeTransport, url: str | None, query: str +) -> None: + transport.reply(body={"known": False, "host": "example.com"}) + + assert client.reputation("example.com", url=url)["known"] is False + assert sent(transport) == ("GET", f"/scan/reputation{query}") + + +def test_the_demo_scan(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.result() | {"remaining": 4, "limit": 5}) + + result = client.demo_scan("example.com") + + assert sent(transport) == ("POST", "/demo-scan") + assert (result.summary.high, result.raw["remaining"]) == (1, 4) + + +CALLS: dict[str, Callable[[VulnRadar], object]] = { + "bulk": lambda sdk: sdk.scans.bulk(["example.com"]), + "authenticated": lambda sdk: sdk.scans.authenticated("example.com", LOGIN), + "verify": lambda sdk: sdk.scans.verify(1), + "verify batch": lambda sdk: sdk.scans.verify_batch( + "example.com", [Finding.from_dict(samples.finding())] + ), + "summary": lambda sdk: sdk.history.summary(1), + "subdomains": lambda sdk: sdk.discovery.subdomains("https://example.com"), + "progress": lambda sdk: sdk.discovery.subdomain_progress("a"), + "reputation": lambda sdk: sdk.reputation("example.com"), + "demo": lambda sdk: sdk.demo_scan("example.com"), +} + + +@pytest.mark.parametrize("call", CALLS.values(), ids=CALLS.keys()) +def test_an_empty_reply_is_never_a_result( + client: VulnRadar, transport: FakeTransport, call: Callable[[VulnRadar], object] +) -> None: + transport.reply(body={}) + + with pytest.raises(UnexpectedResponseError): + call(client) + + +@pytest.mark.parametrize( + "call", + [ + lambda sdk: sdk.scans.authenticated("example.com", LOGIN), + lambda sdk: sdk.discovery.subdomains("example.com"), + lambda sdk: sdk.discover_urls("example.com"), + lambda sdk: sdk.demo_scan("example.com"), + ], +) +def test_a_scheme_is_added_where_the_server_needs_one( + client: VulnRadar, transport: FakeTransport, call: Callable[[VulnRadar], object] +) -> None: + transport.reply(401, {"error": "stop here"}) + + with pytest.raises(AuthenticationError): + call(client) + + assert transport.sent_json()["url"] == "https://example.com" + + +def test_a_progress_id_cannot_change_the_address( + client: VulnRadar, transport: FakeTransport +) -> None: + with pytest.raises(ValueError, match="request id"): + client.discovery.subdomain_progress("../keys") + + assert transport.sent == [] diff --git a/tests/test_webhooks.py b/tests/test_webhooks.py new file mode 100644 index 0000000..236ca7a --- /dev/null +++ b/tests/test_webhooks.py @@ -0,0 +1,81 @@ +"""Checking that a webhook really came from the server.""" + +from __future__ import annotations + +import hashlib +import hmac +import time + +import pytest + +from vulnradar import verify_webhook + +SECRET = "ab" * 32 +BODY = b'{"event":"scan.completed","data":{"scan_id":5}}' +NOW = 1_800_000_000 + + +@pytest.fixture(autouse=True) +def frozen_time(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(time, "time", lambda: float(NOW)) + + +def sign(data: bytes, secret: str = SECRET) -> str: + return hmac.new(secret.encode(), data, hashlib.sha256).hexdigest() + + +def v1() -> dict[str, str]: + return {"X-VulnRadar-Signature": f"sha256={sign(BODY)}"} + + +def v2(at: int = NOW) -> dict[str, str]: + return {"X-VulnRadar-Signature-V2": f"t={at},v1={sign(f'{at}.'.encode() + BODY)}"} + + +def test_a_known_signature_is_accepted() -> None: + # Computed outside the code under test: HMAC-SHA256 keyed with the secret as text. + headers = {"x-vulnradar-signature": f"sha256={sign(BODY)}"} + + assert verify_webhook(SECRET, BODY, headers) is True + + +@pytest.mark.parametrize("headers", [v1(), v2(), v1() | v2(), v2(NOW - 299), v2(NOW + 299)]) +def test_genuine_deliveries_are_accepted(headers: dict[str, str]) -> None: + assert verify_webhook(SECRET, BODY, headers) + + +@pytest.mark.parametrize( + "headers", + [ + {}, + {"X-VulnRadar-Signature": ""}, + {"X-VulnRadar-Signature": sign(BODY)}, + {"X-VulnRadar-Signature": f"sha256={sign(BODY, 'other')}"}, + {"X-VulnRadar-Signature": "sha256=é"}, + {"X-VulnRadar-Signature-V2": "t=,v1="}, + {"X-VulnRadar-Signature-V2": f"t={'9' * 5000},v1=00"}, + {"X-VulnRadar-Signature-V2": "nonsense"}, + v2(NOW - 301), + v2(NOW + 301), + # A bad timestamped signature is not rescued by the older one. + v1() | v2(NOW - 301), + ], +) +def test_everything_else_is_refused(headers: dict[str, str]) -> None: + assert verify_webhook(SECRET, BODY, headers) is False + + +def test_a_changed_body_is_refused() -> None: + assert not verify_webhook(SECRET, BODY + b" ", v1()) + assert not verify_webhook(SECRET, BODY + b" ", v2()) + + +def test_a_timestamp_can_be_insisted_on() -> None: + assert verify_webhook(SECRET, BODY, v2(), require_timestamp=True) + # Otherwise dropping the newer header would let an old delivery be replayed. + assert not verify_webhook(SECRET, BODY, v1(), require_timestamp=True) + + +def test_an_empty_secret_is_a_mistake() -> None: + with pytest.raises(ValueError, match="secret"): + verify_webhook("", BODY, v1()) diff --git a/vulnradar/__init__.py b/vulnradar/__init__.py index 9bb06da..199eaeb 100644 --- a/vulnradar/__init__.py +++ b/vulnradar/__init__.py @@ -39,6 +39,7 @@ VersionInfo, ) from .services.scan_service import ScanOptions +from .webhooks import verify_webhook __all__ = [ "Account", @@ -81,4 +82,5 @@ "VersionInfo", "VulnRadar", "VulnRadarError", + "verify_webhook", ] diff --git a/vulnradar/client.py b/vulnradar/client.py index fe53369..566d7b7 100644 --- a/vulnradar/client.py +++ b/vulnradar/client.py @@ -2,7 +2,7 @@ import os from collections.abc import Sequence -from typing import Unpack +from typing import Any, Unpack from .config import VulnRadarConfig from .constants import ( @@ -12,6 +12,7 @@ DEFAULT_RETRIES, DEFAULT_TIMEOUT, DEFAULT_WAIT_TIMEOUT, + SLOW_REQUEST_TIMEOUT, ) from .exceptions import UnexpectedResponseError from .http import HTTPClient @@ -19,11 +20,12 @@ from .models.crawl import CrawlResult, DiscoveryResult from .models.scan_result import ScanResult from .models.version import VersionInfo -from .replies import read_reply +from .replies import read_reply, require from .services.discovery_service import DiscoveryService from .services.history_service import HistoryService from .services.metadata_service import MetadataService from .services.scan_service import ScanOptions, ScanService, check_positive +from .utils.url_validation import with_scheme class VulnRadar: @@ -166,6 +168,34 @@ def discover_urls(self, url: str) -> DiscoveryResult: """ return self._discovery_service.discover_urls(url) + @property + def discovery(self) -> DiscoveryService: + """Find a site's pages and subdomains.""" + return self._discovery_service + + def reputation(self, host: str, *, url: str | None = None) -> dict[str, Any]: + """What public scans say about a host. + + Args: + host: A host name such as ``example.com``. + url: A page, to look for a scan of exactly that address. + + Returns: + The server's reply. ``known`` is False if there is nothing to go on, + which does not mean the host is safe. + """ + params = {"host": host} if url is None else {"host": host, "url": url} + return read_reply(require("known", bool), self._http.get("/scan/reputation", params=params)) + + def demo_scan(self, url: str) -> ScanResult: + """The public demo scan, a few per day for each network address. + + ``raw`` holds how many are left in ``remaining``. + """ + payload = {"url": with_scheme(url)} + reply = self._http.post("/demo-scan", payload, timeout=SLOW_REQUEST_TIMEOUT) + return read_reply(ScanResult.from_dict, reply) + def me(self) -> Account: """The account the API key belongs to. A good way to test a key.""" return read_reply(Account.from_dict, self._http.get("/auth/me")) diff --git a/vulnradar/constants.py b/vulnradar/constants.py index 1ec2d87..73f21b4 100644 --- a/vulnradar/constants.py +++ b/vulnradar/constants.py @@ -26,3 +26,6 @@ "http-methods", "x-forwarded-host", ) + +# For the calls the server answers only when the work is done, which can take minutes. +SLOW_REQUEST_TIMEOUT: float = 330.0 diff --git a/vulnradar/http.py b/vulnradar/http.py index 81c3d7e..3b46dcd 100644 --- a/vulnradar/http.py +++ b/vulnradar/http.py @@ -121,9 +121,17 @@ def get_version(self) -> dict[str, Any]: parent = self._config.base_url.rsplit("/", 1)[0] return _json(self._request("GET", parent + "/version")) - def post(self, path: str, json: dict[str, Any]) -> dict[str, Any]: + def post( + self, + path: str, + json: dict[str, Any], + *, + params: dict[str, str] | None = None, + timeout: float | None = None, + ) -> dict[str, Any]: """Send a JSON body to an API path. Never retried.""" - return _json(self._request("POST", self._config.base_url + path, json=json)) + url = self._config.base_url + path + return _json(self._request("POST", url, json=json, params=params, timeout=timeout)) def patch(self, path: str, json: dict[str, Any]) -> dict[str, Any]: """Change what an API path names. Never retried.""" diff --git a/vulnradar/models/scan_result.py b/vulnradar/models/scan_result.py index bae454a..f250846 100644 --- a/vulnradar/models/scan_result.py +++ b/vulnradar/models/scan_result.py @@ -62,4 +62,8 @@ def _incomplete(data: dict[str, Any]) -> list[str]: # 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") + # A login that failed or dropped out means signed-in pages were not all checked. + session = mapping(data.get("authReport")).get("status") + if session in ("lost", "failed") and "authenticated-session" not in areas: + areas.append("authenticated-session") return areas diff --git a/vulnradar/replies.py b/vulnradar/replies.py index 06337bf..f0630cf 100644 --- a/vulnradar/replies.py +++ b/vulnradar/replies.py @@ -22,3 +22,14 @@ 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 require(key: str, kind: type) -> Callable[[dict[str, Any]], dict[str, Any]]: + """A reader for replies used as they are, which must still hold their main field.""" + + def check(data: dict[str, Any]) -> dict[str, Any]: + if not isinstance(data[key], kind): + raise TypeError(key) + return data + + return check diff --git a/vulnradar/services/discovery_service.py b/vulnradar/services/discovery_service.py index 19397ff..4463dce 100644 --- a/vulnradar/services/discovery_service.py +++ b/vulnradar/services/discovery_service.py @@ -1,9 +1,13 @@ from __future__ import annotations +from typing import Any + +from ..constants import SLOW_REQUEST_TIMEOUT from ..http import HTTPClient from ..models.crawl import DiscoveryResult -from ..replies import read_reply -from ..utils.url_validation import validate_url +from ..replies import read_reply, require +from ..utils.scan_id import scan_id_segment +from ..utils.url_validation import with_scheme class DiscoveryService: @@ -25,5 +29,33 @@ def discover_urls(self, url: str) -> DiscoveryResult: InvalidURLError: If the URL is malformed. AuthenticationError: If the API key is invalid. """ - data = self._http.post("/scan/crawl/discover", {"url": validate_url(url)}) + data = self._http.post("/scan/crawl/discover", {"url": with_scheme(url)}) return read_reply(DiscoveryResult.from_dict, data) + + def subdomains( + self, url: str, *, force_refresh: bool = False, request_id: str | None = None + ) -> dict[str, Any]: + """Find a domain's subdomains. Returns when the search is done. + + Args: + url: An address of the domain. + force_refresh: Ignore the cached answer. Needs a paid plan and costs a scan. + request_id: An id of your choosing, to ask subdomain_progress() about the + search from another thread. + + Returns: + The server's reply, with the names in ``subdomains``. + """ + payload: dict[str, Any] = {"url": with_scheme(url)} + if force_refresh: + payload["forceRefresh"] = True + if request_id is not None: + payload["requestId"] = scan_id_segment(request_id, "request id") + reply = self._http.post("/scan/discover", payload, timeout=SLOW_REQUEST_TIMEOUT) + return read_reply(require("subdomains", list), reply) + + def subdomain_progress(self, request_id: str) -> dict[str, Any]: + """How far a subdomain search is. An unknown id reads as ``queued``.""" + segment = scan_id_segment(request_id, "request id") + reply = self._http.get(f"/scan/discover/progress/{segment}") + return read_reply(require("stage", str), reply) diff --git a/vulnradar/services/history_service.py b/vulnradar/services/history_service.py index 0871a8a..f00a38c 100644 --- a/vulnradar/services/history_service.py +++ b/vulnradar/services/history_service.py @@ -3,13 +3,14 @@ from collections.abc import Iterator, Sequence from typing import Any +from ..constants import SLOW_REQUEST_TIMEOUT from ..enums import ReportFormat from ..exceptions import NoResultError, UnexpectedResponseError from ..http import HTTPClient from ..models.crawl import parse_result from ..models.history import DeleteScanResult, HistoryList, HistoryScan, Report, ScanSettings from ..models.scan_result import ScanResult -from ..replies import read_reply +from ..replies import read_reply, require from ..utils.scan_id import scan_id_segment _PAGE_SIZE = 100 # the most the server returns at once @@ -130,6 +131,21 @@ def update( reply = self._http.patch(_scan_path(scan_id), changes) return read_reply(ScanSettings.from_dict, reply) + def summary(self, scan_id: int | str, *, regenerate: bool = False) -> str: + """A short written summary of a scan by the server's AI. + + Args: + scan_id: The numeric or the text id. + regenerate: Write it again instead of returning the stored one. + """ + reply = self._http.post( + f"{_scan_path(scan_id)}/summary", + {}, + params={"regenerate": "true"} if regenerate else None, + timeout=SLOW_REQUEST_TIMEOUT, + ) + return read_reply(require("summary", str), reply)["summary"] # type: ignore[no-any-return] + def delete(self, scan_id: int | str) -> DeleteScanResult: """Delete one scan. The key needs the ``scan:delete`` permission. diff --git a/vulnradar/services/scan_service.py b/vulnradar/services/scan_service.py index b9de681..ff2d791 100644 --- a/vulnradar/services/scan_service.py +++ b/vulnradar/services/scan_service.py @@ -1,7 +1,7 @@ from __future__ import annotations import time -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from typing import Any, TypedDict, Unpack from ..constants import ( @@ -9,6 +9,7 @@ DEFAULT_POLL_INTERVAL, DEFAULT_WAIT_TIMEOUT, MAX_FAILED_POLLS, + SLOW_REQUEST_TIMEOUT, ) from ..enums import Scanner, ScanState from ..exceptions import ( @@ -20,11 +21,13 @@ VulnRadarError, ) from ..http import HTTPClient +from ..models.fields import required_list +from ..models.findings import Finding from ..models.scan_result import ScanResult from ..models.scan_status import ScanJob, ScanStatus -from ..replies import read_reply +from ..replies import read_reply, require from ..utils.scan_id import scan_id_segment -from ..utils.url_validation import validate_url +from ..utils.url_validation import validate_url, with_scheme class ScanOptions(TypedDict, total=False): @@ -45,6 +48,10 @@ class ScanOptions(TypedDict, total=False): "team_ids": "teamIds", } +_LOGIN_METHODS = ("form", "header", "cookie") +_MAX_BULK = 100 +_MAX_REVIEW = 50 + _SCANNER_NAMES = frozenset( [scanner.value for scanner in Scanner] + [f"active-probes:{probe}" for probe in ACTIVE_PROBES] ) @@ -94,6 +101,81 @@ def start_crawl( payload["urls"] = [validate_url(page) for page in urls] return self._start("/scan/crawl", payload) + def bulk( + self, + urls: Sequence[str], + *, + public: bool | None = None, + team_ids: Sequence[int] | None = None, + ) -> dict[str, Any]: + """Queue a scan of each address, with the default scanners. + + Args: + urls: 1 to 100 targets; your plan may allow fewer. + + Returns: + The server's reply. Each entry of ``results`` has ``success`` and either + ``scanId``, to pass to wait(), or ``error``. + """ + if isinstance(urls, str) or not 1 <= len(urls) <= _MAX_BULK: + raise ValueError(f"urls must be a list of 1 to {_MAX_BULK} addresses.") + payload: dict[str, Any] = {"urls": [with_scheme(url) for url in urls]} + if public is not None: + payload["isPublic"] = public + if team_ids is not None: + payload["teamIds"] = [*team_ids] + return read_reply(require("results", list), self._http.post("/scan/bulk", payload)) + + def authenticated( + self, + url: str, + auth: Mapping[str, Any], + scanners: Sequence[str] | None = None, + *, + public: bool | None = None, + team_ids: Sequence[int] | None = None, + ) -> ScanResult: + """Scan one address while signed in. Returns when the scan is done. + + Args: + url: The target. + auth: How to sign in, sent to the server as given. ``method`` is ``form`` + (``username``, ``password``), ``header`` (``headerValue``) or + ``cookie`` (``cookies``). + scanners: Scanner names to run; see Scanner. + + Returns: + The result. ``incomplete`` says if the signed-in session was not kept. + """ + if not isinstance(auth, Mapping) or auth.get("method") not in _LOGIN_METHODS: + raise ValueError(f"auth needs a method: one of {', '.join(_LOGIN_METHODS)}.") + options: ScanOptions = {} + if public is not None: + options["public"] = public + if team_ids is not None: + options["team_ids"] = team_ids + payload = _payload(with_scheme(url), scanners, options) + payload["auth"] = dict(auth) + reply = self._http.post("/scan/authenticated", payload, timeout=SLOW_REQUEST_TIMEOUT) + return read_reply(ScanResult.from_dict, reply) + + def verify(self, scan_id: int | str) -> list[Finding]: + """Have the server's AI review a stored scan's findings. + + Each returned finding carries the verdict in ``raw`` (``aiVerdict``). + """ + payload = {"scanHistoryId": scan_id} + reply = self._http.post("/scan/verify", payload, timeout=SLOW_REQUEST_TIMEOUT) + return read_reply(_findings, reply) + + def verify_batch(self, url: str, findings: Sequence[Finding]) -> list[Finding]: + """Have the server's AI review up to 50 findings of one address.""" + if not 1 <= len(findings) <= _MAX_REVIEW: + raise ValueError(f"findings must hold 1 to {_MAX_REVIEW} findings.") + payload = {"url": with_scheme(url), "findings": [item.raw for item in findings]} + reply = self._http.post("/scan/verify-batch", payload, timeout=SLOW_REQUEST_TIMEOUT) + return read_reply(_findings, reply) + def status(self, scan_id: int | str) -> ScanStatus: """Ask where a scan stands. Asking does not use up any quota. @@ -217,3 +299,7 @@ def _check_scanners(scanners: Sequence[str]) -> list[str]: def _confirm_cancelled(data: dict[str, Any]) -> None: if data["cancelled"] is not True: raise ValueError("cancelled") + + +def _findings(data: dict[str, Any]) -> list[Finding]: + return [Finding.from_dict(item) for item in required_list(data, "findings")] diff --git a/vulnradar/utils/scan_id.py b/vulnradar/utils/scan_id.py index cb176bb..0d8770e 100644 --- a/vulnradar/utils/scan_id.py +++ b/vulnradar/utils/scan_id.py @@ -6,7 +6,7 @@ _SCAN_ID = re.compile(r"[A-Za-z0-9_-]+") -def scan_id_segment(scan_id: int | str) -> str: +def scan_id_segment(scan_id: int | str, name: str = "scan id") -> str: """Return a scan id that is safe to put in an address. Raises: @@ -14,5 +14,5 @@ def scan_id_segment(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}") + raise ValueError(f"Not a valid {name}: {text!r}") return text diff --git a/vulnradar/utils/url_validation.py b/vulnradar/utils/url_validation.py index 072ed23..57a7e5d 100644 --- a/vulnradar/utils/url_validation.py +++ b/vulnradar/utils/url_validation.py @@ -30,6 +30,12 @@ _HAS_SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://") +def with_scheme(url: str) -> str: + """Like validate_url, adding ``https://`` for the calls that need a scheme.""" + target = validate_url(url) + return target if _HAS_SCHEME.match(target) else f"https://{target}" + + def validate_url(url: str) -> str: """Reject a target no server could scan. The server has the final say. diff --git a/vulnradar/webhooks.py b/vulnradar/webhooks.py new file mode 100644 index 0000000..90a6027 --- /dev/null +++ b/vulnradar/webhooks.py @@ -0,0 +1,61 @@ +"""Checking that a webhook delivery really came from the server.""" + +from __future__ import annotations + +import hashlib +import hmac +import time +from collections.abc import Mapping + +TOLERANCE_SECONDS = 300.0 + + +def verify_webhook( + secret: str, + body: bytes, + headers: Mapping[str, str], + *, + require_timestamp: bool = False, + tolerance: float = TOLERANCE_SECONDS, +) -> bool: + """Say whether a delivery carries a valid signature. + + Deliveries a server sends as a test are unsigned before 4.0. + + Args: + secret: The webhook's secret, exactly as shown. + body: The raw request body. A parsed and re-encoded body will not match. + headers: The request headers, in any case. + require_timestamp: Accept only the timestamped signature of servers from + 4.0. Set it if your server is one: it stops an old delivery being + sent again without that header. + tolerance: How many seconds old a timestamped delivery may be. + + Returns: + True only if the signature matches. + + Raises: + ValueError: If the secret is empty. + """ + if not secret: + raise ValueError("The webhook secret is empty.") + sent = {name.lower(): value for name, value in headers.items()} + timed = sent.get("x-vulnradar-signature-v2") + if timed is not None: + # Never fall back to the older signature when this one is wrong. + parts = dict(part.split("=", 1) for part in timed.split(",") if "=" in part) + stamp = parts.get("t", "") + if not (stamp.isdecimal() and len(stamp) <= 12): + return False + if abs(time.time() - int(stamp)) > tolerance: + return False + return _matches(secret, f"{stamp}.".encode() + body, parts.get("v1", "")) + scheme, _, signature = sent.get("x-vulnradar-signature", "").partition("=") + if require_timestamp or scheme != "sha256": + return False + return _matches(secret, body, signature) + + +def _matches(secret: str, signed: bytes, signature: str) -> bool: + expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest() + return hmac.compare_digest(expected.encode(), signature.encode()) From 11e9690f53244e3feb11e5818699d02005263aae Mon Sep 17 00:00:00 2001 From: RejectModders Date: Sun, 29 Nov 2026 05:04:29 -0600 Subject: [PATCH 2/2] fix: do not pass off a missing AI review as a result A server without working AI returns the findings unchanged, which looked like a review that found nothing wrong, so verify() and verify_batch() now raise when no finding got a verdict. Webhook checking refuses a tolerance that would accept any age and no longer crashes on an odd header, and the README shows what a subdomain entry holds. --- README.md | 9 +++++++-- tests/test_extras.py | 19 ++++++++++++++++++- tests/test_webhooks.py | 7 +++++++ vulnradar/services/scan_service.py | 23 ++++++++++++++++++----- vulnradar/webhooks.py | 8 ++++++-- 5 files changed, 56 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 85dab2e..91c57e0 100644 --- a/README.md +++ b/README.md @@ -232,7 +232,8 @@ result = client.scans.authenticated( ) print(result.summary.total, result.incomplete) -names = client.discovery.subdomains("example.com")["subdomains"] +found = client.discovery.subdomains("example.com")["subdomains"] +names = [entry["subdomain"] for entry in found] verdict = client.reputation("example.com") demo = client.demo_scan("example.com") # a few per day per network address ``` @@ -243,7 +244,8 @@ with `headerValue`, or `cookie` with `cookies` as a list of `name` and `value`. session was lost, `result.incomplete` includes `authenticated-session`. `bulk()`, `subdomains()` and `reputation()` return the server's reply as a dictionary. -A reputation that is not `known` does not mean a host is safe. +A reputation that is not `known` does not mean a host is safe. Servers before 4.0 do not +say in a signed-in or demo scan's reply when some checks failed to run. With the server's AI turned on, you can review findings and summarise a scan: @@ -252,6 +254,9 @@ reviewed = client.scans.verify(123) text = client.history.summary(123) ``` +A reviewed finding has `raw["aiVerdict"]`. If none got a verdict, the call raises +`UnexpectedResponseError` instead of returning findings that look approved. + --- ## Webhooks diff --git a/tests/test_extras.py b/tests/test_extras.py index ffa9c76..d7346fc 100644 --- a/tests/test_extras.py +++ b/tests/test_extras.py @@ -130,7 +130,7 @@ def test_findings_can_be_reviewed_by_scan(client: VulnRadar, transport: FakeTran def test_findings_can_be_reviewed_on_their_own(client: VulnRadar, transport: FakeTransport) -> None: finding = Finding.from_dict(samples.finding()) - transport.reply(body={"findings": [samples.finding("low")]}) + transport.reply(body={"findings": [samples.finding("low", aiVerdict="possible_fp")]}) reviewed = client.scans.verify_batch("https://example.com", [finding]) @@ -255,3 +255,20 @@ def test_a_progress_id_cannot_change_the_address( client.discovery.subdomain_progress("../keys") assert transport.sent == [] + + +@pytest.mark.parametrize("call", ["verify", "verify batch"]) +@pytest.mark.parametrize("extra", [{}, {"ai": {"configured": False, "verdicts": 0}}]) +def test_a_review_that_never_ran_is_not_a_pass( + client: VulnRadar, transport: FakeTransport, call: str, extra: dict[str, object] +) -> None: + transport.reply(body={"success": True, "findings": [samples.finding()], **extra}) + + with pytest.raises(UnexpectedResponseError, match="no AI verdicts"): + CALLS[call](client) + + +def test_a_scan_with_nothing_to_review(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body={"success": True, "findings": []}) + + assert client.scans.verify(4711) == [] diff --git a/tests/test_webhooks.py b/tests/test_webhooks.py index 236ca7a..be160f6 100644 --- a/tests/test_webhooks.py +++ b/tests/test_webhooks.py @@ -55,6 +55,7 @@ def test_genuine_deliveries_are_accepted(headers: dict[str, str]) -> None: {"X-VulnRadar-Signature-V2": "t=,v1="}, {"X-VulnRadar-Signature-V2": f"t={'9' * 5000},v1=00"}, {"X-VulnRadar-Signature-V2": "nonsense"}, + {"X-VulnRadar-Signature": "sha256=\udcff"}, v2(NOW - 301), v2(NOW + 301), # A bad timestamped signature is not rescued by the older one. @@ -79,3 +80,9 @@ def test_a_timestamp_can_be_insisted_on() -> None: def test_an_empty_secret_is_a_mistake() -> None: with pytest.raises(ValueError, match="secret"): verify_webhook("", BODY, v1()) + + +@pytest.mark.parametrize("tolerance", [float("nan"), float("inf"), -1.0]) +def test_a_tolerance_that_would_accept_any_age_is_refused(tolerance: float) -> None: + with pytest.raises(ValueError, match="tolerance"): + verify_webhook(SECRET, BODY, v2(NOW - 10_000), tolerance=tolerance) diff --git a/vulnradar/services/scan_service.py b/vulnradar/services/scan_service.py index ff2d791..c95b776 100644 --- a/vulnradar/services/scan_service.py +++ b/vulnradar/services/scan_service.py @@ -18,6 +18,7 @@ ScanFailedError, ScanTimeoutError, ServerError, + UnexpectedResponseError, VulnRadarError, ) from ..http import HTTPClient @@ -162,11 +163,15 @@ def authenticated( def verify(self, scan_id: int | str) -> list[Finding]: """Have the server's AI review a stored scan's findings. - Each returned finding carries the verdict in ``raw`` (``aiVerdict``). + A reviewed finding carries the verdict in ``raw`` (``aiVerdict``); one + without it was not reviewed. + + Raises: + UnexpectedResponseError: If no finding got a verdict. """ payload = {"scanHistoryId": scan_id} reply = self._http.post("/scan/verify", payload, timeout=SLOW_REQUEST_TIMEOUT) - return read_reply(_findings, reply) + return read_reply(_reviewed, reply) def verify_batch(self, url: str, findings: Sequence[Finding]) -> list[Finding]: """Have the server's AI review up to 50 findings of one address.""" @@ -174,7 +179,7 @@ def verify_batch(self, url: str, findings: Sequence[Finding]) -> list[Finding]: raise ValueError(f"findings must hold 1 to {_MAX_REVIEW} findings.") payload = {"url": with_scheme(url), "findings": [item.raw for item in findings]} reply = self._http.post("/scan/verify-batch", payload, timeout=SLOW_REQUEST_TIMEOUT) - return read_reply(_findings, reply) + return read_reply(_reviewed, reply) def status(self, scan_id: int | str) -> ScanStatus: """Ask where a scan stands. Asking does not use up any quota. @@ -301,5 +306,13 @@ def _confirm_cancelled(data: dict[str, Any]) -> None: raise ValueError("cancelled") -def _findings(data: dict[str, Any]) -> list[Finding]: - return [Finding.from_dict(item) for item in required_list(data, "findings")] +def _reviewed(data: dict[str, Any]) -> list[Finding]: + findings = [Finding.from_dict(item) for item in required_list(data, "findings")] + # A server without working AI hands the findings back untouched. + if findings and not any(item.raw.get("aiVerdict") for item in findings): + raise UnexpectedResponseError( + "The server returned no AI verdicts: its AI is not set up, failed, or had " + "nothing it could review.", + body=data, + ) + return findings diff --git a/vulnradar/webhooks.py b/vulnradar/webhooks.py index 90a6027..7a2113c 100644 --- a/vulnradar/webhooks.py +++ b/vulnradar/webhooks.py @@ -4,6 +4,7 @@ import hashlib import hmac +import math import time from collections.abc import Mapping @@ -35,10 +36,12 @@ def verify_webhook( True only if the signature matches. Raises: - ValueError: If the secret is empty. + ValueError: If the secret is empty or the tolerance is not a usable number. """ if not secret: raise ValueError("The webhook secret is empty.") + if not (math.isfinite(tolerance) and tolerance >= 0): + raise ValueError("tolerance must be a number of seconds, zero or more.") sent = {name.lower(): value for name, value in headers.items()} timed = sent.get("x-vulnradar-signature-v2") if timed is not None: @@ -58,4 +61,5 @@ def verify_webhook( def _matches(secret: str, signed: bytes, signature: str) -> bool: expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest() - return hmac.compare_digest(expected.encode(), signature.encode()) + # Headers can hold anything, including text that plain encoding refuses. + return hmac.compare_digest(expected.encode(), signature.encode("utf-8", "surrogatepass"))