From 78a300fb192d5a66fa4ef68f805cb7318382092f Mon Sep 17 00:00:00 2001 From: RejectModders Date: Sat, 28 Nov 2026 19:36:22 -0600 Subject: [PATCH 1/3] feat!: move to the v3 API and tighten the connection The client calls /api/v3. It refuses redirects and plain http to other computers, sends a scan or delete only once, keeps the key out of printed objects and away from .netrc, and reads VULNRADAR_TOKEN like the command line tool does. Errors carry the server's code and request id, each rate limit is named, and every network failure is an SDK error. Scans on v3 run in the background and this does not follow them yet, so a reply that is not a finished result now raises instead of reading as a scan with no findings. --- tests/conftest.py | 2 +- tests/test_client.py | 11 +- tests/test_config.py | 136 +++++++++++ tests/test_errors.py | 195 ++++++++++++++-- tests/test_replies.py | 107 +++++++++ tests/test_transport.py | 210 +++++++++++++++++ vulnradar/__init__.py | 20 +- vulnradar/_version.py | 6 + vulnradar/client.py | 38 ++- vulnradar/config.py | 69 +++++- vulnradar/constants.py | 18 +- vulnradar/enums.py | 17 ++ vulnradar/exceptions.py | 126 +++++++--- vulnradar/http.py | 293 +++++++++++++----------- vulnradar/models/crawl.py | 12 +- vulnradar/models/finding_types.py | 2 +- vulnradar/models/history.py | 4 +- vulnradar/models/scan_result.py | 4 +- vulnradar/models/summary.py | 7 + vulnradar/models/version.py | 2 +- vulnradar/replies.py | 40 ++++ vulnradar/services/crawl_service.py | 3 +- vulnradar/services/discovery_service.py | 3 +- vulnradar/services/history_service.py | 22 +- vulnradar/services/metadata_service.py | 3 +- vulnradar/services/scan_service.py | 3 +- vulnradar/utils/__init__.py | 4 +- vulnradar/utils/rate_limit.py | 106 ++++++--- 28 files changed, 1179 insertions(+), 284 deletions(-) create mode 100644 tests/test_config.py create mode 100644 tests/test_replies.py create mode 100644 tests/test_transport.py create mode 100644 vulnradar/_version.py create mode 100644 vulnradar/replies.py diff --git a/tests/conftest.py b/tests/conftest.py index d6eb8c7..150d5dc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -40,7 +40,7 @@ def transport() -> FakeTransport: @pytest.fixture def client(transport: FakeTransport) -> VulnRadar: - sdk = VulnRadar(api_key="test-key", base_url=BASE_URL, retries=3) + sdk = VulnRadar(api_key="test-key", base_url=BASE_URL, retries=2) sdk._config.retry_backoff = 0 sdk._http._session.trust_env = False sdk._http._session.mount("https://", transport) diff --git a/tests/test_client.py b/tests/test_client.py index c676896..c30e4e9 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -9,16 +9,13 @@ from vulnradar import InvalidURLError, Severity, VulnRadar -def test_requests_carry_the_key_and_json_content_type( - client: VulnRadar, transport: FakeTransport -) -> None: +def test_requests_carry_the_key(client: VulnRadar, transport: FakeTransport) -> None: transport.reply(body={"scans": []}) client.history.list() headers = transport.sent[0].headers assert headers["Authorization"] == "Bearer test-key" - assert headers["Content-Type"] == "application/json" def test_version_is_read_from_the_unversioned_path( @@ -49,19 +46,20 @@ def test_scan_posts_the_target_and_chosen_scanners( scanners: list[str] | None, expected: dict[str, object], ) -> None: - transport.reply() + 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() + transport.reply(body={"crawl": {"pages": []}}) client.scan_crawl("https://example.com", urls=["https://example.com/login"]) @@ -85,6 +83,7 @@ def test_discover_posts_the_target(client: VulnRadar, transport: FakeTransport) def test_history_get_and_delete_address_one_scan( client: VulnRadar, transport: FakeTransport ) -> None: + transport.reply(body={"url": "https://example.com", "findings": [], "summary": {"total": 0}}) transport.reply(body={"success": True}) client.history.get(123) diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..c3ea6a1 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,136 @@ +"""Where the client sends requests and how it holds the key.""" + +from __future__ import annotations + +import pytest + +from tests.fake import FakeTransport +from vulnradar import VulnRadar + +DEFAULT_URL = "https://vulnradar.dev/api/v3" + + +@pytest.fixture(autouse=True) +def clean_environment(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("VULNRADAR_TOKEN", raising=False) + monkeypatch.delenv("VULNRADAR_API_BASE", raising=False) + + +def sent_to(sdk: VulnRadar, transport: FakeTransport) -> tuple[str, str]: + sdk._http._session.mount("https://", transport) + sdk._http._session.mount("http://", transport) + transport.reply(body={"scans": []}) + sdk.history.list() + request = transport.sent[-1] + return str(request.url), request.headers["Authorization"] + + +def test_the_default_address_is_the_v3_api(transport: FakeTransport) -> None: + url, _ = sent_to(VulnRadar(api_key="test-key"), transport) + + assert url == f"{DEFAULT_URL}/history" + + +def test_the_key_and_address_can_come_from_the_environment( + transport: FakeTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("VULNRADAR_TOKEN", "env-key") + monkeypatch.setenv("VULNRADAR_API_BASE", "https://scanner.example.test/api/v3/") + + assert sent_to(VulnRadar(), transport) == ( + "https://scanner.example.test/api/v3/history", + "Bearer env-key", + ) + + +def test_arguments_win_over_the_environment( + transport: FakeTransport, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("VULNRADAR_TOKEN", "env-key") + monkeypatch.setenv("VULNRADAR_API_BASE", "https://scanner.example.test/api/v3") + + sdk = VulnRadar(api_key="given-key", base_url=DEFAULT_URL) + + assert sent_to(sdk, transport) == (f"{DEFAULT_URL}/history", "Bearer given-key") + + +def test_whitespace_around_the_key_is_dropped(transport: FakeTransport) -> None: + _, authorization = sent_to(VulnRadar(api_key=" file-key\n"), transport) + + assert authorization == "Bearer file-key" + + +@pytest.mark.parametrize("key", [None, "", " "]) +def test_a_missing_key_is_refused(key: str | None) -> None: + with pytest.raises(ValueError, match="VULNRADAR_TOKEN"): + VulnRadar(api_key=key) + + +@pytest.mark.parametrize("key", ["sec ret", "sec\nret", "sec\tret", "sec\x00ret", "sécret"]) +def test_a_malformed_key_is_refused_without_being_repeated(key: str) -> None: + with pytest.raises(ValueError, match="API key") as caught: + VulnRadar(api_key=key) + + assert "sec" not in str(caught.value).replace("secret key", "") + assert key not in str(caught.value) + + +@pytest.mark.parametrize( + "base_url", + [ + "http://vulnradar.dev/api/v3", + "http://192.0.2.10/api/v3", + "http://localhost.example.test/api/v3", + "ftp://vulnradar.dev/api/v3", + "vulnradar.dev/api/v3", + "https:///api/v3", + "https://user:pass@vulnradar.dev/api/v3", + "https://vulnradar.dev/api/v3?x=1", + "https://vulnradar.dev/api/v3#part", + "https://vulnradar.dev:port/api/v3", + "", + ], +) +def test_unsafe_or_broken_addresses_are_refused(base_url: str) -> None: + with pytest.raises(ValueError, match="base_url"): + VulnRadar(api_key="test-key", base_url=base_url) + + +@pytest.mark.parametrize( + "base_url", + [ + "http://localhost:3000/api/v3", + "http://127.0.0.1:3000/api/v3", + "http://[::1]:3000/api/v3", + ], +) +def test_plain_http_is_allowed_to_this_computer_only( + transport: FakeTransport, base_url: str +) -> None: + url, _ = sent_to(VulnRadar(api_key="test-key", base_url=base_url), transport) + + assert url == f"{base_url}/history" + + +def test_the_version_address_keeps_a_path_prefix(transport: FakeTransport) -> None: + sdk = VulnRadar(api_key="test-key", base_url="https://host.example.test/scanner/api/v3") + sdk._http._session.mount("https://", transport) + transport.reply(body={"current": "3.9.2"}) + + sdk.version() + + assert transport.sent[0].url == "https://host.example.test/scanner/api/version" + + +@pytest.mark.parametrize(("option", "value"), [("retries", -1), ("timeout", 0), ("timeout", -2.5)]) +def test_impossible_settings_are_refused(option: str, value: float) -> None: + with pytest.raises(ValueError, match=option): + VulnRadar(api_key="test-key", **{option: value}) # type: ignore[arg-type] + + +def test_the_key_does_not_appear_when_objects_are_printed() -> None: + sdk = VulnRadar(api_key="do-not-print") + + shown = " ".join(repr(item) for item in (sdk, sdk._config, sdk._http, sdk._http._session.auth)) + + assert "do-not-print" not in shown diff --git a/tests/test_errors.py b/tests/test_errors.py index e5346b8..89007ef 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -3,6 +3,7 @@ from __future__ import annotations from datetime import UTC, datetime +from email.utils import format_datetime import pytest import requests @@ -14,6 +15,7 @@ ForbiddenError, NotFoundError, RateLimitError, + RateLimitKind, ServerError, UnprocessableEntityError, VulnRadar, @@ -26,10 +28,13 @@ [ (400, BadRequestError), (401, AuthenticationError), + (402, VulnRadarError), (403, ForbiddenError), (404, NotFoundError), - (422, UnprocessableEntityError), + (409, VulnRadarError), + (413, VulnRadarError), (418, VulnRadarError), + (422, UnprocessableEntityError), (500, ServerError), (503, ServerError), ], @@ -43,11 +48,75 @@ def test_status_codes_map_to_exceptions( transport.reply(status, {"error": "the server said no"}) with pytest.raises(error) as caught: - client.history.list() + client.history.delete(1) assert type(caught.value) is error assert caught.value.status_code == status assert caught.value.message == "the server said no" + assert str(caught.value) == "the server said no" + assert caught.value.code is None + + +def test_the_code_request_id_and_body_are_kept(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply( + 403, + {"error": "Missing scope", "code": "SCOPE_MISSING", "requestId": "req-1", "extra": 5}, + headers={"x-request-id": "req-from-header"}, + ) + + with pytest.raises(ForbiddenError) as caught: + client.history.list() + + assert caught.value.code == "SCOPE_MISSING" + assert caught.value.request_id == "req-1" + assert caught.value.body["extra"] == 5 + + +def test_the_older_status_code_field_and_header_id_are_read( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply( + 403, + {"error": "Blocked", "statusCode": "BLOCKED"}, + headers={"x-request-id": "req-2"}, + ) + + with pytest.raises(ForbiddenError) as caught: + client.history.list() + + assert (caught.value.code, caught.value.request_id) == ("BLOCKED", "req-2") + + +@pytest.mark.parametrize( + ("body", "message"), + [ + ({"error": {"message": "nested"}}, "nested"), + ({"message": "plain"}, "plain"), + ({}, "The server answered with status 404."), + ({"error": 5}, "The server answered with status 404."), + ], +) +def test_the_message_is_always_text( + client: VulnRadar, transport: FakeTransport, body: dict[str, object], message: str +) -> None: + transport.reply(404, body) + + with pytest.raises(NotFoundError) as caught: + client.history.list() + + assert caught.value.message == message + + +def test_an_error_page_is_not_copied_into_the_message( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(404, raw=b"

nope

", content_type="text/html") + + with pytest.raises(NotFoundError) as caught: + client.history.list() + + assert caught.value.message == "The server answered with status 404." + assert caught.value.body == {} def test_client_errors_are_not_retried(client: VulnRadar, transport: FakeTransport) -> None: @@ -72,7 +141,7 @@ def test_a_read_is_retried_after_a_server_error( @pytest.mark.parametrize( "failure", [requests.exceptions.ConnectionError(), requests.exceptions.ReadTimeout()] ) -def test_network_failures_become_sdk_errors( +def test_a_read_is_retried_after_a_network_failure( client: VulnRadar, transport: FakeTransport, failure: Exception ) -> None: transport.fail(failure) @@ -83,26 +152,56 @@ def test_network_failures_become_sdk_errors( assert len(transport.sent) == 3 -def test_a_sign_in_page_is_reported_as_an_authentication_error( - client: VulnRadar, transport: FakeTransport +LIMIT_HEADERS = { + "X-RateLimit-Limit": "25", + "X-RateLimit-Remaining": "0", + "X-RateLimit-Used": "25", + "X-RateLimit-Reset": "2026-11-28T12:00:00.000Z", + "X-RateLimit-Policy": "daily", +} + + +@pytest.mark.parametrize( + ("body", "headers", "kind"), + [ + # 3.9.2 sends no code; only the key's own budget comes with Retry-After. + ({"error": "x"}, {**LIMIT_HEADERS, "Retry-After": "3600"}, RateLimitKind.API_QUOTA), + ({"error": "x"}, LIMIT_HEADERS, RateLimitKind.DAILY_SCANS), + ({"error": "x", "statusCode": "DAILY_LIMIT"}, {}, RateLimitKind.DAILY_SCANS), + ( + {"error": "x", "statusCode": "CONCURRENT_SCAN_LIMIT"}, + {}, + RateLimitKind.CONCURRENT_SCANS, + ), + ({"error": "x", "statusCode": "TARGET_RATE_LIMIT"}, {}, RateLimitKind.TARGET), + ({"error": "x"}, {}, RateLimitKind.OTHER), + # 4.0.0 names each one. + ({"error": "x", "code": "API_QUOTA_EXCEEDED"}, {}, RateLimitKind.API_QUOTA), + ({"error": "x", "code": "BULK_RATE_LIMIT"}, {}, RateLimitKind.BULK), + ({"error": "x", "code": "RATE_LIMITED"}, {"Retry-After": "9"}, RateLimitKind.OTHER), + ], +) +def test_each_rate_limit_is_told_apart( + client: VulnRadar, + transport: FakeTransport, + body: dict[str, object], + headers: dict[str, str], + kind: RateLimitKind, ) -> None: - transport.reply(raw=b"", content_type="text/html; charset=utf-8") + transport.reply(429, body, headers=headers) - with pytest.raises(AuthenticationError): + with pytest.raises(RateLimitError) as caught: client.history.list() + assert caught.value.kind is kind + assert len(transport.sent) == 1 + def test_rate_limit_details_come_from_the_headers( client: VulnRadar, transport: FakeTransport ) -> None: transport.reply( - 429, - {"error": "Rate limit exceeded"}, - headers={ - "X-RateLimit-Limit": "25", - "X-RateLimit-Remaining": "0", - "X-RateLimit-Reset": "2026-11-28T12:00:00.000Z", - }, + 429, {"error": "Rate limit exceeded"}, headers={**LIMIT_HEADERS, "Retry-After": "60"} ) with pytest.raises(RateLimitError) as caught: @@ -111,16 +210,78 @@ def test_rate_limit_details_come_from_the_headers( limit = caught.value assert (limit.limit, limit.used, limit.remaining) == (25, 25, 0) assert limit.resets_at == datetime(2026, 11, 28, 12, tzinfo=UTC) - assert len(transport.sent) == 1 + assert limit.retry_after == 60 -def test_a_rate_limit_without_headers_still_raises( +def test_rate_limit_details_fall_back_to_the_body( client: VulnRadar, transport: FakeTransport ) -> None: - transport.reply(429, {"error": "slow down"}) + transport.reply( + 429, + { + "error": "Rate limit exceeded", + "limit": 100, + "used": 100, + "remaining": 0, + "resets_at": "2026-11-29T00:00:00Z", + }, + ) with pytest.raises(RateLimitError) as caught: client.history.list() + assert (caught.value.limit, caught.value.used) == (100, 100) + assert caught.value.resets_at == datetime(2026, 11, 29, tzinfo=UTC) + + +def test_retry_after_alone_is_enough(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(429, {"error": "slow down"}, headers={"Retry-After": "60"}) + + with pytest.raises(RateLimitError) as caught: + client.history.list() + + assert caught.value.retry_after == 60 assert caught.value.rate_limit is None assert caught.value.resets_at is None + + +def test_retry_after_may_be_a_date(client: VulnRadar, transport: FakeTransport) -> None: + past = format_datetime(datetime(2020, 1, 1, tzinfo=UTC), usegmt=True) + transport.reply(429, {"error": "slow down"}, headers={"Retry-After": past}) + + with pytest.raises(RateLimitError) as caught: + client.history.list() + + assert caught.value.retry_after == 0 + + +@pytest.mark.parametrize("value", ["soon", "-5", "nan", "inf", ""]) +def test_a_useless_retry_after_is_ignored( + client: VulnRadar, transport: FakeTransport, value: str +) -> None: + transport.reply(429, {"error": "slow down"}, headers={"Retry-After": value}) + + with pytest.raises(RateLimitError) as caught: + client.history.list() + + assert caught.value.retry_after is None + + +def test_unreadable_limit_values_do_not_hide_the_error( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply( + 429, + {"error": "slow down", "used": "many"}, + headers={ + "X-RateLimit-Limit": "unlimited", + "X-RateLimit-Remaining": "3", + "X-RateLimit-Reset": "later", + }, + ) + + with pytest.raises(RateLimitError) as caught: + client.history.list() + + limit = caught.value + assert (limit.limit, limit.used, limit.remaining, limit.resets_at) == (None, None, 3, None) diff --git a/tests/test_replies.py b/tests/test_replies.py new file mode 100644 index 0000000..f01ed02 --- /dev/null +++ b/tests/test_replies.py @@ -0,0 +1,107 @@ +"""A reply that cannot be understood must never pass for a clean result.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +import pytest + +from tests.fake import FakeTransport +from vulnradar import UnexpectedResponseError, VulnRadar + +Call = Callable[[VulnRadar], Any] + +CALLS: dict[str, Call] = { + "scan": lambda sdk: sdk.scan("https://example.com"), + "crawl": lambda sdk: sdk.scan_crawl("https://example.com"), + "discover": lambda sdk: sdk.discover_urls("https://example.com"), + "history list": lambda sdk: sdk.history.list(), + "history get": lambda sdk: sdk.history.get(1), + "history delete": lambda sdk: sdk.history.delete(1), + "finding types": lambda sdk: sdk.metadata.finding_types(), + "version": lambda sdk: sdk.version(), +} + + +@pytest.mark.parametrize("call", CALLS.values(), ids=CALLS.keys()) +def test_an_empty_object_is_not_a_result( + client: VulnRadar, transport: FakeTransport, call: Call +) -> None: + transport.reply(body={}) + + with pytest.raises(UnexpectedResponseError): + 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", + [ + {"findings": [], "summary": {}}, + {"findings": [], "summary": None}, + {"findings": None, "summary": {"total": 0}}, + {"summary": {"total": 0}}, + {"findings": []}, + ], +) +def test_an_unfinished_scan_is_not_a_clean_one( + client: VulnRadar, transport: FakeTransport, body: dict[str, object] +) -> None: + transport.reply(body=body) + + with pytest.raises(UnexpectedResponseError): + client.history.get(1) + + +def test_a_finished_scan_without_findings_is_still_a_result( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body={"url": "https://example.com", "findings": [], "summary": {"total": 0}}) + + 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", + [ + {"scans": [{"id": "0123abcd", "summary": {}}]}, + {"scans": "none"}, + {"scans": [5]}, + ], +) +def test_a_reply_of_the_wrong_shape_raises_an_sdk_error( + client: VulnRadar, transport: FakeTransport, body: dict[str, object] +) -> None: + transport.reply(body=body) + + with pytest.raises(UnexpectedResponseError): + client.history.list() diff --git a/tests/test_transport.py b/tests/test_transport.py new file mode 100644 index 0000000..c7c5259 --- /dev/null +++ b/tests/test_transport.py @@ -0,0 +1,210 @@ +"""How requests travel: what is refused, what is retried and what is sent.""" + +from __future__ import annotations + +import time +from pathlib import Path + +import pytest +import requests + +import vulnradar +from tests.conftest import BASE_URL +from tests.fake import FakeTransport +from vulnradar import ( + NetworkError, + RequestTimeoutError, + ServerError, + UnexpectedResponseError, + VulnRadar, + VulnRadarError, +) + + +@pytest.fixture +def sleeps(monkeypatch: pytest.MonkeyPatch) -> list[float]: + waited: list[float] = [] + monkeypatch.setattr(time, "sleep", waited.append) + return waited + + +@pytest.mark.parametrize("status", [301, 302, 303, 307, 308]) +def test_redirects_are_refused_and_not_followed( + client: VulnRadar, transport: FakeTransport, status: int +) -> None: + transport.reply(status, headers={"Location": "https://elsewhere.example.test/login"}) + + with pytest.raises(UnexpectedResponseError) as caught: + client.history.list() + + assert caught.value.status_code == status + assert "elsewhere.example.test" in caught.value.message + assert len(transport.sent) == 1 + + +@pytest.mark.parametrize( + ("status", "raw", "content_type"), + [ + (200, b"", "text/html; charset=utf-8"), + (200, b"", "application/json"), + (204, b"", "application/json"), + (200, b"<>", "application/json"), + (200, b"[1, 2]", "application/json"), + (200, b'"text"', "application/json"), + ], +) +def test_a_success_reply_that_is_not_a_json_object_is_an_error( + client: VulnRadar, transport: FakeTransport, status: int, raw: bytes, content_type: str +) -> None: + transport.reply(status, raw=raw, content_type=content_type) + + with pytest.raises(UnexpectedResponseError): + client.history.list() + + assert len(transport.sent) == 1 + + +@pytest.mark.parametrize( + "failure", + [requests.exceptions.ReadTimeout(), requests.exceptions.ConnectionError()], +) +def test_a_scan_is_never_sent_twice( + client: VulnRadar, transport: FakeTransport, failure: Exception +) -> None: + transport.fail(failure) + + with pytest.raises(NetworkError): + client.scan("https://example.com") + + assert len(transport.sent) == 1 + + +@pytest.mark.parametrize("status", [500, 502, 503, 504]) +def test_writes_are_not_retried_after_a_server_error( + client: VulnRadar, transport: FakeTransport, status: int +) -> None: + transport.reply(status, {"error": "busy"}) + + with pytest.raises(ServerError): + client.scan("https://example.com") + with pytest.raises(ServerError): + client.history.delete(1) + + assert len(transport.sent) == 2 + + +@pytest.mark.parametrize(("retries", "attempts"), [(0, 1), (1, 2), (3, 4)]) +def test_retries_counts_the_attempts_after_the_first( + transport: FakeTransport, sleeps: list[float], retries: int, attempts: int +) -> None: + sdk = VulnRadar(api_key="test-key", base_url=BASE_URL, retries=retries) + sdk._http._session.mount("https://", transport) + transport.reply(502, {"error": "bad gateway"}) + + with pytest.raises(ServerError): + sdk.history.list() + + assert len(transport.sent) == attempts + assert len(sleeps) == attempts - 1 + + +def test_a_short_retry_after_is_honoured( + client: VulnRadar, transport: FakeTransport, sleeps: list[float] +) -> None: + transport.reply(503, {"error": "busy"}, headers={"Retry-After": "7"}) + transport.reply(200, {"scans": []}) + + client.history.list() + + assert sleeps == [7.0] + + +def test_a_long_retry_after_is_left_to_the_caller( + client: VulnRadar, transport: FakeTransport, sleeps: list[float] +) -> None: + transport.reply(503, {"error": "paused", "paused": True}, headers={"Retry-After": "300"}) + + with pytest.raises(ServerError) as caught: + client.history.list() + + assert caught.value.retry_after == 300 + assert caught.value.body["paused"] is True + assert len(transport.sent) == 1 + assert sleeps == [] + + +def test_a_timeout_is_told_apart_from_other_network_failures( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.fail(requests.exceptions.ConnectTimeout()) + + with pytest.raises(RequestTimeoutError): + client.scan("https://example.com") + + +@pytest.mark.parametrize( + "failure", + [ + requests.exceptions.TooManyRedirects(), + requests.exceptions.ChunkedEncodingError(), + requests.exceptions.ContentDecodingError(), + requests.exceptions.SSLError(), + ], +) +def test_every_requests_failure_becomes_an_sdk_error( + client: VulnRadar, transport: FakeTransport, failure: Exception +) -> None: + transport.fail(failure) + + with pytest.raises(VulnRadarError): + client.history.list() + + +def test_requests_identify_the_sdk(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body={"scans": []}) + + client.history.list() + + headers = transport.sent[0].headers + assert headers["User-Agent"].startswith(f"vulnradar-python/{vulnradar.__version__}") + assert headers["x-vulnradar-client"] == f"python-sdk/{vulnradar.__version__}" + assert headers["Accept"] == "application/json" + assert "Content-Type" not in headers + assert "Origin" not in headers + assert "Referer" not in headers + + +def test_a_netrc_entry_cannot_replace_the_key( + transport: FakeTransport, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + netrc = tmp_path / "netrc" + netrc.write_text("machine api.example.test login someone password other\n", encoding="utf-8") + netrc.chmod(0o600) + monkeypatch.setenv("NETRC", str(netrc)) + sdk = VulnRadar(api_key="test-key", base_url=BASE_URL) + sdk._http._session.mount("https://", transport) + transport.reply(body={"scans": []}) + + sdk.history.list() + + assert transport.sent[0].headers["Authorization"] == "Bearer test-key" + + +@pytest.mark.parametrize("scan_id", ["../keys", "1/delete", "1?x=2", "", ".", ".."]) +def test_a_scan_id_cannot_change_the_address( + client: VulnRadar, transport: FakeTransport, scan_id: str +) -> None: + with pytest.raises(ValueError, match="scan id"): + client.history.get(scan_id) + with pytest.raises(ValueError, match="scan id"): + client.history.delete(scan_id) + + assert transport.sent == [] + + +def test_a_text_scan_id_is_accepted(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body={"success": True}) + + client.history.delete("0123456789abcdef0123456789abcdef") + + assert transport.sent[0].url == f"{BASE_URL}/history/0123456789abcdef0123456789abcdef" diff --git a/vulnradar/__init__.py b/vulnradar/__init__.py index 7fcedb3..896064d 100644 --- a/vulnradar/__init__.py +++ b/vulnradar/__init__.py @@ -1,15 +1,18 @@ -from importlib.metadata import PackageNotFoundError, version - +from ._version import __version__ as __version__ from .client import VulnRadar -from .enums import Severity +from .enums import RateLimitKind, Severity from .exceptions import ( AuthenticationError, BadRequestError, ForbiddenError, InvalidURLError, + NetworkError, NotFoundError, RateLimitError, + RateLimitInfo, + RequestTimeoutError, ServerError, + UnexpectedResponseError, UnprocessableEntityError, VulnRadarError, ) @@ -29,12 +32,6 @@ VersionInfo, ) -try: - __version__ = version("vulnradar") -except PackageNotFoundError: # running from a source tree that was never installed - __version__ = "unknown" -del version - __all__ = [ "AuthenticationError", "BadRequestError", @@ -50,12 +47,17 @@ "HistoryList", "HistoryScan", "InvalidURLError", + "NetworkError", "NotFoundError", "RateLimitError", + "RateLimitInfo", + "RateLimitKind", + "RequestTimeoutError", "ScanResult", "ServerError", "Severity", "Summary", + "UnexpectedResponseError", "UnprocessableEntityError", "VersionInfo", "VulnRadar", diff --git a/vulnradar/_version.py b/vulnradar/_version.py new file mode 100644 index 0000000..551a94d --- /dev/null +++ b/vulnradar/_version.py @@ -0,0 +1,6 @@ +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("vulnradar") +except PackageNotFoundError: # running from a source tree that was never installed + __version__ = "unknown" diff --git a/vulnradar/client.py b/vulnradar/client.py index aa61d13..d94aa08 100644 --- a/vulnradar/client.py +++ b/vulnradar/client.py @@ -1,13 +1,20 @@ from __future__ import annotations -from typing import Any +import os from .config import VulnRadarConfig -from .constants import BASE_URL, DEFAULT_RETRIES, DEFAULT_TIMEOUT +from .constants import ( + API_KEY_ENV, + BASE_URL, + BASE_URL_ENV, + DEFAULT_RETRIES, + DEFAULT_TIMEOUT, +) 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 @@ -22,10 +29,16 @@ class VulnRadar: typed interface. Args: - api_key: Your VulnRadar API key. - base_url: Override the default API base URL. - timeout: HTTP request timeout in seconds. Default: 30. - retries: Number of retry attempts for transient server errors. Default: 3. + api_key: Your VulnRadar API key. Read from VULNRADAR_TOKEN if not given. + base_url: The API address. Read from VULNRADAR_API_BASE if not given, else + https://vulnradar.dev/api/v3. It must use https unless it points at this + computer. + timeout: Seconds to wait for the server. Default: 30. + retries: Extra attempts for a read that fails on the network or with a server + error. Requests that change something are never repeated. Default: 2. + + Raises: + ValueError: If there is no usable key or address. Example: >>> from vulnradar import VulnRadar @@ -36,12 +49,16 @@ class VulnRadar: def __init__( self, - api_key: str, + api_key: str | None = None, *, - base_url: str = BASE_URL, - timeout: int = DEFAULT_TIMEOUT, + base_url: str | None = None, + timeout: float = DEFAULT_TIMEOUT, retries: int = DEFAULT_RETRIES, ) -> None: + if api_key is None: + api_key = os.environ.get(API_KEY_ENV, "") + if base_url is None: + base_url = os.environ.get(BASE_URL_ENV) or BASE_URL self._config = VulnRadarConfig( api_key=api_key, base_url=base_url, @@ -112,5 +129,4 @@ def version(self) -> VersionInfo: Returns: A VersionInfo object with version strings and status fields. """ - data: dict[str, Any] = self._http.get_unversioned("/api/version") - return VersionInfo.from_dict(data) + return read_reply(VersionInfo.from_dict, self._http.get_version()) diff --git a/vulnradar/config.py b/vulnradar/config.py index 473b0ed..3c982c6 100644 --- a/vulnradar/config.py +++ b/vulnradar/config.py @@ -1,16 +1,71 @@ from __future__ import annotations from dataclasses import dataclass, field +from urllib.parse import urlsplit -from .constants import BASE_URL, DEFAULT_RETRIES, DEFAULT_RETRY_BACKOFF, DEFAULT_TIMEOUT +from .constants import ( + API_KEY_ENV, + BASE_URL, + DEFAULT_RETRIES, + DEFAULT_RETRY_BACKOFF, + DEFAULT_TIMEOUT, +) + +_THIS_COMPUTER = frozenset({"localhost", "127.0.0.1", "::1"}) @dataclass class VulnRadarConfig: - """Configuration for the VulnRadar SDK client.""" + """Settings for the VulnRadar client, checked when they are created. + + Raises: + ValueError: If the key, the address or a number cannot be used. + """ + + api_key: str = field(repr=False) + base_url: str = BASE_URL + timeout: float = DEFAULT_TIMEOUT + retries: int = DEFAULT_RETRIES + retry_backoff: float = DEFAULT_RETRY_BACKOFF + + def __post_init__(self) -> None: + self.api_key = _clean_api_key(self.api_key) + self.base_url = _clean_base_url(self.base_url) + if self.timeout <= 0: + raise ValueError("timeout must be greater than zero.") + if self.retries < 0: + raise ValueError("retries cannot be negative.") + + +def _clean_api_key(api_key: str) -> str: + key = api_key.strip() + if not key: + raise ValueError(f"No API key. Pass api_key or set {API_KEY_ENV}.") + # Only visible ASCII can go in a header. The message must not repeat the key. + if not all("!" <= char <= "~" for char in key): + raise ValueError("The API key contains spaces or characters a header cannot carry.") + return key + + +def _clean_base_url(base_url: str) -> str: + """Accept only an address the key can safely be sent to. - api_key: str - base_url: str = field(default=BASE_URL) - timeout: int = field(default=DEFAULT_TIMEOUT) - retries: int = field(default=DEFAULT_RETRIES) - retry_backoff: float = field(default=DEFAULT_RETRY_BACKOFF) + The messages never repeat the address, which could hold a password. + """ + url = base_url.strip().rstrip("/") + example = f"base_url must be a full https address such as {BASE_URL}." + # Parsers disagree about backslashes and blanks, so neither is accepted. + if any(char == "\\" or char.isspace() for char in url): + raise ValueError(example) + try: + parts = urlsplit(url) + _ = parts.port # raises ValueError for a port that is not a number + except ValueError: + raise ValueError(example) from None + if parts.scheme not in ("https", "http") or not parts.hostname: + raise ValueError(example) + if parts.scheme == "http" and parts.hostname not in _THIS_COMPUTER: + raise ValueError("base_url must use https. Plain http is only for this computer.") + if parts.username is not None or parts.password is not None or parts.query or parts.fragment: + raise ValueError("base_url cannot hold a user name, password, query or fragment.") + return url diff --git a/vulnradar/constants.py b/vulnradar/constants.py index 8301f70..8700a74 100644 --- a/vulnradar/constants.py +++ b/vulnradar/constants.py @@ -1,11 +1,11 @@ -BASE_URL: str = "https://vulnradar.dev/api/v2" -VERSION_URL: str = "https://vulnradar.dev/api/version" +BASE_URL: str = "https://vulnradar.dev/api/v3" -DEFAULT_TIMEOUT: int = 30 -DEFAULT_RETRIES: int = 3 -DEFAULT_RETRY_BACKOFF: float = 0.5 +# The same names the vulnradar command line tool reads. +API_KEY_ENV: str = "VULNRADAR_TOKEN" +BASE_URL_ENV: str = "VULNRADAR_API_BASE" -RATE_LIMIT_HEADER: str = "X-RateLimit-Limit" -RATE_LIMIT_REMAINING_HEADER: str = "X-RateLimit-Remaining" -RATE_LIMIT_RESET_HEADER: str = "X-RateLimit-Reset" -RETRY_AFTER_HEADER: str = "Retry-After" +DEFAULT_TIMEOUT: float = 30.0 +DEFAULT_RETRIES: int = 2 +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 diff --git a/vulnradar/enums.py b/vulnradar/enums.py index a7e68b5..b345b5a 100644 --- a/vulnradar/enums.py +++ b/vulnradar/enums.py @@ -7,3 +7,20 @@ class Severity(StrEnum): MEDIUM = "medium" LOW = "low" INFO = "info" + + +class RateLimitKind(StrEnum): + """Which limit a RateLimitError ran into.""" + + API_QUOTA = "api_quota" + """The key's requests per 24 hours.""" + DAILY_SCANS = "daily_scans" + """The plan's scans per day.""" + CONCURRENT_SCANS = "concurrent_scans" + """Too many scans running at once.""" + TARGET = "target" + """Too many scans of one target domain.""" + BULK = "bulk" + """Too many bulk requests.""" + OTHER = "other" + """A short-term limit, or one the server did not name.""" diff --git a/vulnradar/exceptions.py b/vulnradar/exceptions.py index 5b01ac3..8338893 100644 --- a/vulnradar/exceptions.py +++ b/vulnradar/exceptions.py @@ -1,65 +1,108 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import dataclass from datetime import datetime +from typing import Any + +from .enums import RateLimitKind class VulnRadarError(Exception): - """Base exception for all VulnRadar SDK errors.""" + """Base exception for all VulnRadar SDK errors. + + Attributes: + message: What went wrong, as text. + status_code: The HTTP status, if the server answered. + code: The server's own error code, if it sent one. + 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. + """ - def __init__(self, message: str, status_code: int | None = None) -> None: - super().__init__(message) - self.message = message - self.status_code = status_code + default_message = "The VulnRadar request failed." + default_status: int | None = None + + def __init__( + self, + message: str | None = None, + status_code: int | None = None, + *, + code: str | None = None, + request_id: str | None = None, + retry_after: float | None = None, + body: Mapping[str, Any] | None = None, + ) -> None: + self.message = message or self.default_message + super().__init__(self.message) + self.status_code = status_code if status_code is not None else self.default_status + self.code = code + self.request_id = request_id + self.retry_after = retry_after + self.body: dict[str, Any] = dict(body or {}) class AuthenticationError(VulnRadarError): """Raised when the API key is invalid or missing.""" - def __init__(self, message: str = "Invalid or missing API key.") -> None: - super().__init__(message, status_code=401) + default_message = "Invalid or missing API key." + default_status = 401 class BadRequestError(VulnRadarError): """Raised when the API rejects the request due to invalid parameters.""" - def __init__(self, message: str = "Bad request. Check your parameters.") -> None: - super().__init__(message, status_code=400) + default_message = "Bad request. Check your parameters." + default_status = 400 -class NotFoundError(VulnRadarError): - """Raised when the requested resource does not exist.""" +class ForbiddenError(VulnRadarError): + """Raised when access to a resource is forbidden.""" - def __init__(self, message: str = "Resource not found.") -> None: - super().__init__(message, status_code=404) + default_message = "You do not have permission to access this resource." + default_status = 403 -class ForbiddenError(VulnRadarError): - """Raised when access to a resource is forbidden.""" +class NotFoundError(VulnRadarError): + """Raised when the requested resource does not exist.""" - def __init__( - self, message: str = "You do not have permission to access this resource." - ) -> None: - super().__init__(message, status_code=403) + default_message = "Resource not found." + default_status = 404 class UnprocessableEntityError(VulnRadarError): """Raised when a target is unreachable or request cannot be processed.""" - def __init__(self, message: str = "The request could not be processed.") -> None: - super().__init__(message, status_code=422) + default_message = "The request could not be processed." + default_status = 422 class RateLimitError(VulnRadarError): - """Raised when the API rate limit is exceeded.""" + """Raised when a rate limit or quota is exceeded. + + ``kind`` says which one. ``retry_after`` and the limit figures are set only + when the server sends them. + """ + + default_message = "Rate limit exceeded. Please wait before retrying." + default_status = 429 def __init__( self, - message: str = "Rate limit exceeded. Please wait before retrying.", + message: str | None = None, rate_limit: RateLimitInfo | None = None, + *, + kind: RateLimitKind = RateLimitKind.OTHER, + code: str | None = None, + request_id: str | None = None, + retry_after: float | None = None, + body: Mapping[str, Any] | None = None, ) -> None: - super().__init__(message, status_code=429) + super().__init__( + message, code=code, request_id=request_id, retry_after=retry_after, body=body + ) self.rate_limit = rate_limit + self.kind = kind @property def limit(self) -> int | None: @@ -81,10 +124,29 @@ def resets_at(self) -> datetime | None: class ServerError(VulnRadarError): """Raised when the API returns a 5xx server error.""" - def __init__( - self, message: str = "An internal server error occurred.", status_code: int = 500 - ) -> None: - super().__init__(message, status_code=status_code) + default_message = "An internal server error occurred." + default_status = 500 + + +class NetworkError(VulnRadarError): + """Raised when no complete reply arrived.""" + + default_message = "Could not reach the server." + + +class RequestTimeoutError(NetworkError): + """Raised when the server did not answer in time. + + A request that changes something may still have been carried out. + """ + + default_message = "The server did not answer in time." + + +class UnexpectedResponseError(VulnRadarError): + """Raised when a reply cannot be understood, including any redirect.""" + + default_message = "The server's reply could not be understood." class InvalidURLError(VulnRadarError): @@ -100,9 +162,9 @@ def __init__(self, url: str) -> None: @dataclass(frozen=True) class RateLimitInfo: - """Rate limit metadata exposed through RateLimitError.""" + """Rate limit figures exposed through RateLimitError. Unknown ones are None.""" - limit: int - used: int - remaining: int + limit: int | None + used: int | None + remaining: int | None resets_at: datetime | None diff --git a/vulnradar/http.py b/vulnradar/http.py index 69febf6..6b627aa 100644 --- a/vulnradar/http.py +++ b/vulnradar/http.py @@ -1,93 +1,94 @@ from __future__ import annotations +import platform +import re import time from typing import Any -from urllib.parse import urlsplit import requests -from requests import Response, Session +from requests import PreparedRequest, Response, Session +from requests.auth import AuthBase +from ._version import __version__ from .config import VulnRadarConfig +from .constants import MAX_RETRY_WAIT from .exceptions import ( AuthenticationError, BadRequestError, ForbiddenError, + NetworkError, NotFoundError, RateLimitError, + RequestTimeoutError, ServerError, + UnexpectedResponseError, UnprocessableEntityError, VulnRadarError, ) -from .utils.rate_limit import RateLimitInfo, parse_rate_limit_headers +from .utils.rate_limit import parse_rate_limit, parse_retry_after, rate_limit_kind + +_ERROR_BY_STATUS: dict[int, type[VulnRadarError]] = { + 400: BadRequestError, + 401: AuthenticationError, + 403: ForbiddenError, + 404: NotFoundError, + 422: UnprocessableEntityError, +} + +# The server records this per key and accepts only these characters. +_CLIENT_NAME = re.sub(r"[^A-Za-z0-9._/-]", "-", f"python-sdk/{__version__}")[:64] + + +class _BearerAuth(AuthBase): + """Adds the key to a request. + + Set as the session's auth so that a .netrc entry cannot replace the header. + """ + + def __init__(self, api_key: str) -> None: + self._api_key = api_key + + def __call__(self, request: PreparedRequest) -> PreparedRequest: + request.headers["Authorization"] = f"Bearer {self._api_key}" + return request class HTTPClient: - """Low-level HTTP client that wraps requests with auth, retries, and error handling.""" + """Sends requests with the key, retries reads and turns failures into exceptions.""" def __init__(self, config: VulnRadarConfig) -> None: self._config = config self._session = Session() + self._session.auth = _BearerAuth(config.api_key) self._session.headers.update( { - "Authorization": f"Bearer {config.api_key}", - "Content-Type": "application/json", + "Accept": "application/json", + "User-Agent": ( + f"vulnradar-python/{__version__} python/{platform.python_version()}" + ), + "x-vulnradar-client": _CLIENT_NAME, } ) - def get(self, path: str, *, versioned: bool = True) -> dict[str, Any]: - """Perform an authenticated GET request. - - Args: - path: The API path (e.g. '/history'). - versioned: If False, uses the unversioned base URL for paths like /api/version. - - Returns: - Parsed JSON response as a dict. - """ - url = (self._config.base_url if versioned else self._base_origin()) + path - return self._request("GET", url) - - def get_unversioned(self, path: str) -> dict[str, Any]: - """Perform a GET request against an unversioned endpoint. - - The path is appended directly to the domain root (no /api/v2 prefix). + 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) - Args: - path: Full path from domain root (e.g. '/api/version'). + def get_version(self) -> dict[str, Any]: + """Read the version endpoint, which sits beside the versioned API. - Returns: - Parsed JSON response as a dict. + For a base address ending in '/api/v3' this is '/api/version'. """ - return self._request("GET", self._base_origin() + path) + parent = self._config.base_url.rsplit("/", 1)[0] + return self._request("GET", parent + "/version") def post(self, path: str, json: dict[str, Any]) -> dict[str, Any]: - """Perform an authenticated POST request. - - Args: - path: The API path (e.g. '/scan'). - json: Request body as a dict. - - Returns: - Parsed JSON response as a dict. - """ - url = self._config.base_url + path - return self._request("POST", url, json=json) + """Send a JSON body to an API path. Never retried.""" + return self._request("POST", self._config.base_url + path, json=json) def delete(self, path: str) -> dict[str, Any]: - """Perform an authenticated DELETE request. - - Args: - path: The API path (e.g. '/history/123'). - - Returns: - Parsed JSON response as a dict. - """ - url = self._config.base_url + path - return self._request("DELETE", url) - - def _base_origin(self) -> str: - parsed = urlsplit(self._config.base_url) - return f"{parsed.scheme}://{parsed.netloc}" + """Delete what an API path names. Never retried.""" + return self._request("DELETE", self._config.base_url + path) def _request( self, @@ -95,90 +96,108 @@ def _request( url: str, json: dict[str, Any] | None = None, ) -> dict[str, Any]: - last_exc: Exception | None = None - - for attempt in range(max(1, self._config.retries)): + # Only reads are repeated: sending a scan twice runs it, and counts it, twice. + attempts = 1 + (self._config.retries if method == "GET" else 0) + attempt = 1 + while True: try: - response = self._session.request( - method, - url, - json=json, - timeout=self._config.timeout, - ) - self._raise_for_status(response) - - if response.status_code == 204: - return {} - - if not response.content or not response.content.strip(): - return {} - - try: - data: dict[str, Any] = response.json() - except ValueError: - return {} - return data - except RateLimitError: - raise - except (AuthenticationError, BadRequestError, NotFoundError): - raise - except ServerError as exc: - last_exc = exc - if attempt < self._config.retries - 1: - time.sleep(self._config.retry_backoff * (2**attempt)) - except requests.exceptions.Timeout: - last_exc = VulnRadarError(f"Request timed out after {self._config.timeout}s.") - if attempt < self._config.retries - 1: - time.sleep(self._config.retry_backoff * (2**attempt)) - except requests.exceptions.ConnectionError as exc: - last_exc = VulnRadarError(f"Connection error: {exc}") - if attempt < self._config.retries - 1: - time.sleep(self._config.retry_backoff * (2**attempt)) - - raise last_exc or VulnRadarError("Request failed after retries.") - - def _raise_for_status(self, response: Response) -> None: - status = response.status_code - if status < 400: - # Detect redirect-to-login: response is 2xx but content is HTML (not JSON) - content_type = response.headers.get("Content-Type", "") - if "text/html" in content_type: - raise AuthenticationError( - "API returned an HTML login page instead of JSON. " - "The Authorization header may not be accepted for this endpoint." - ) - return - + return self._send(method, url, json) + except (NetworkError, ServerError) as error: + wait = error.retry_after + if wait is None: + wait = self._config.retry_backoff * 2 ** (attempt - 1) + if attempt >= attempts or wait > MAX_RETRY_WAIT: + raise + time.sleep(wait) + attempt += 1 + + def _send(self, method: str, url: str, json: dict[str, Any] | None) -> dict[str, Any]: try: - body = response.json() - message = body.get("message") or body.get("error") or response.text - except Exception: - message = response.text - - if status == 400: - raise BadRequestError(message) - elif status == 401: - raise AuthenticationError(message) - elif status == 404: - raise NotFoundError(message) - elif status == 403: - raise ForbiddenError(message) - elif status == 422: - raise UnprocessableEntityError(message) - elif status == 429: - rate_limit = parse_rate_limit_headers(response.headers) - rl_info = ( - RateLimitInfo( - limit=rate_limit.limit, - used=rate_limit.used, - remaining=rate_limit.remaining, - resets_at=rate_limit.resets_at, - ) - if rate_limit - else None + response = self._session.request( + method, + url, + json=json, + timeout=self._config.timeout, + # A redirect could carry the key somewhere it was never meant to go. + allow_redirects=False, ) - raise RateLimitError(message, rate_limit=rl_info) - elif status >= 500: - raise ServerError(message, status_code=status) - else: - raise VulnRadarError(message, status_code=status) + except requests.exceptions.Timeout as error: + message = f"No answer within {self._config.timeout} seconds." + if method != "GET": + message += " The request may still have been carried out." + raise RequestTimeoutError(message) from error + except requests.exceptions.RequestException as error: + raise NetworkError(f"The request did not complete ({type(error).__name__}).") from error + return _read(response) + + +def _read(response: Response) -> dict[str, Any]: + """Return the JSON object of a successful reply, or raise.""" + status = response.status_code + if status >= 400: + raise _error(response) + + request_id = response.headers.get("x-request-id") + + def unreadable(message: str) -> UnexpectedResponseError: + return UnexpectedResponseError(message, status, request_id=request_id) + + if status >= 300: + location = response.headers.get("Location", "")[:200] + raise unreadable( + f"The server redirected the request to '{location}'. Redirects are not " + "followed, so that the key stays where it was sent. Check base_url." + ) + if "text/html" in response.headers.get("Content-Type", "").lower(): + raise unreadable("The server answered with a web page instead of data. Check base_url.") + try: + data = response.json() + except ValueError: + raise unreadable("The server's reply was empty or was not JSON.") from None + if not isinstance(data, dict): + raise unreadable("The server's reply was not a JSON object.") + return data + + +def _error(response: Response) -> VulnRadarError: + """Build the exception for a reply with an error status.""" + status = response.status_code + try: + parsed = response.json() + except ValueError: + parsed = None + body: dict[str, Any] = parsed if isinstance(parsed, dict) else {} + + error = body.get("error") + if isinstance(error, dict): + error = error.get("message") + message = _first_text(error, body.get("message")) + message = message or f"The server answered with status {status}." + code = _first_text(body.get("code"), body.get("statusCode")) + request_id = _first_text(body.get("requestId"), response.headers.get("x-request-id")) + retry_after = parse_retry_after(response.headers.get("Retry-After")) + + if status == 429: + rate_limit = parse_rate_limit(response.headers, body) + return RateLimitError( + message, + rate_limit, + kind=rate_limit_kind(code, rate_limit, retry_after), + code=code, + request_id=request_id, + retry_after=retry_after, + body=body, + ) + error_type = ServerError if status >= 500 else _ERROR_BY_STATUS.get(status, VulnRadarError) + return error_type( + message, + status, + code=code, + request_id=request_id, + retry_after=retry_after, + body=body, + ) + + +def _first_text(*values: object) -> str | None: + return next((value for value in values if isinstance(value, str) and value.strip()), None) diff --git a/vulnradar/models/crawl.py b/vulnradar/models/crawl.py index 06517ba..483352e 100644 --- a/vulnradar/models/crawl.py +++ b/vulnradar/models/crawl.py @@ -21,8 +21,8 @@ class CrawlPage: def from_dict(cls, data: dict[str, Any]) -> CrawlPage: return cls( url=data.get("url", ""), - findings=[Finding.from_dict(f) for f in data.get("findings", [])], - summary=Summary.from_dict(data.get("summary", {})), + findings=[Finding.from_dict(f) for f in data["findings"]], + summary=Summary.of_finished_scan(data["summary"]), duration=float(data.get("duration", 0.0)), response_headers=data.get("responseHeaders", {}), ) @@ -46,8 +46,8 @@ class CrawlResult: @classmethod def from_dict(cls, data: dict[str, Any]) -> CrawlResult: - crawl_data = data.get("crawl", {}) - pages = [CrawlPage.from_dict(p) for p in crawl_data.get("pages", [])] + 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), @@ -65,7 +65,9 @@ class DiscoveryResult: @classmethod def from_dict(cls, data: dict[str, Any]) -> DiscoveryResult: - urls = data.get("urls", []) + urls = data["urls"] + if not isinstance(urls, list): + raise TypeError("urls") return cls( urls=urls, total=data.get("total", len(urls)), diff --git a/vulnradar/models/finding_types.py b/vulnradar/models/finding_types.py index ee6a718..26df76d 100644 --- a/vulnradar/models/finding_types.py +++ b/vulnradar/models/finding_types.py @@ -52,7 +52,7 @@ class FindingTypesResult: def from_dict(cls, data: dict[str, Any]) -> FindingTypesResult: raw_types = data.get("types") if not isinstance(raw_types, list): - raw_types = data.get("data", []) + raw_types = data["data"] types = [FindingType.from_dict(t) for t in raw_types] return cls( version=data.get("version", ""), diff --git a/vulnradar/models/history.py b/vulnradar/models/history.py index 30e377b..d408ef9 100644 --- a/vulnradar/models/history.py +++ b/vulnradar/models/history.py @@ -50,7 +50,7 @@ class HistoryList: @classmethod def from_dict(cls, data: dict[str, Any]) -> HistoryList: return cls( - scans=[HistoryScan.from_dict(s) for s in data.get("scans", [])], + scans=[HistoryScan.from_dict(s) for s in data["scans"]], ) @@ -63,7 +63,7 @@ class DeleteScanResult: @classmethod def from_dict(cls, data: dict[str, Any]) -> DeleteScanResult: - success = bool(data.get("success", False)) + success = bool(data["success"]) message = str(data.get("message", "")).strip() if success and not message: message = "Scan deleted successfully" diff --git a/vulnradar/models/scan_result.py b/vulnradar/models/scan_result.py index b73b8c6..f2c2289 100644 --- a/vulnradar/models/scan_result.py +++ b/vulnradar/models/scan_result.py @@ -41,8 +41,8 @@ def from_dict(cls, data: dict[str, Any]) -> ScanResult: url=data.get("url", ""), scanned_at=scanned_at, duration=float(data.get("duration", 0.0)), - findings=[Finding.from_dict(f) for f in data.get("findings", [])], - summary=Summary.from_dict(data.get("summary", {})), + 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"), diff --git a/vulnradar/models/summary.py b/vulnradar/models/summary.py index 368bea0..0386fdb 100644 --- a/vulnradar/models/summary.py +++ b/vulnradar/models/summary.py @@ -15,6 +15,13 @@ class Summary: low: int info: int + @classmethod + def of_finished_scan(cls, data: dict[str, Any]) -> Summary: + """Like from_dict, but refuse the empty summary of an unfinished scan.""" + if "total" not in data: + raise KeyError("summary.total") + return cls.from_dict(data) + @classmethod def from_dict(cls, data: dict[str, Any]) -> Summary: return cls( diff --git a/vulnradar/models/version.py b/vulnradar/models/version.py index 22561c0..4e94d2a 100644 --- a/vulnradar/models/version.py +++ b/vulnradar/models/version.py @@ -17,7 +17,7 @@ class VersionInfo: @classmethod def from_dict(cls, data: dict[str, Any]) -> VersionInfo: return cls( - current=data.get("current", ""), + current=data["current"], latest=data.get("latest", ""), engine=data.get("engine", ""), status=data.get("status", ""), diff --git a/vulnradar/replies.py b/vulnradar/replies.py new file mode 100644 index 0000000..2de75f5 --- /dev/null +++ b/vulnradar/replies.py @@ -0,0 +1,40 @@ +"""Turning reply bodies into models without ever inventing a result.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any, TypeVar + +from .exceptions import UnexpectedResponseError + +T = TypeVar("T") + + +def read_reply(model: Callable[[dict[str, Any]], T], data: dict[str, Any]) -> T: + """Build a model from a reply. + + Raises: + UnexpectedResponseError: If the reply does not have the expected shape. + """ + try: + return model(data) + except (AttributeError, KeyError, TypeError, ValueError) as error: + 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/crawl_service.py b/vulnradar/services/crawl_service.py index d16eb67..a883b72 100644 --- a/vulnradar/services/crawl_service.py +++ b/vulnradar/services/crawl_service.py @@ -2,6 +2,7 @@ from ..http import HTTPClient from ..models.crawl import CrawlResult +from ..replies import read_scan_reply from ..utils.url_validation import validate_url @@ -31,4 +32,4 @@ def scan_crawl(self, url: str, urls: list[str] | None = None) -> CrawlResult: if urls is not None: payload["urls"] = urls data = self._http.post("/scan/crawl", payload) - return CrawlResult.from_dict(data) + return read_scan_reply(CrawlResult.from_dict, data) diff --git a/vulnradar/services/discovery_service.py b/vulnradar/services/discovery_service.py index 2dc7c44..cb271a6 100644 --- a/vulnradar/services/discovery_service.py +++ b/vulnradar/services/discovery_service.py @@ -2,6 +2,7 @@ from ..http import HTTPClient from ..models.crawl import DiscoveryResult +from ..replies import read_reply from ..utils.url_validation import validate_url @@ -26,4 +27,4 @@ def discover_urls(self, url: str) -> DiscoveryResult: """ validate_url(url) data = self._http.post("/scan/crawl/discover", {"url": url}) - return DiscoveryResult.from_dict(data) + return read_reply(DiscoveryResult.from_dict, data) diff --git a/vulnradar/services/history_service.py b/vulnradar/services/history_service.py index f12b09c..86da25b 100644 --- a/vulnradar/services/history_service.py +++ b/vulnradar/services/history_service.py @@ -1,8 +1,21 @@ 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_-]+") + + +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}" class HistoryService: @@ -17,8 +30,7 @@ def list(self) -> HistoryList: Returns: A HistoryList containing scan summaries. """ - data = self._http.get("/history") - return HistoryList.from_dict(data) + return read_reply(HistoryList.from_dict, self._http.get("/history")) def get(self, scan_id: int | str) -> ScanResult: """Retrieve the full details of a specific scan. @@ -32,8 +44,7 @@ def get(self, scan_id: int | str) -> ScanResult: Raises: NotFoundError: If no scan with the given ID exists. """ - data = self._http.get(f"/history/{scan_id}") - return ScanResult.from_dict(data) + return read_reply(ScanResult.from_dict, self._http.get(_scan_path(scan_id))) def delete(self, scan_id: int | str) -> DeleteScanResult: """Delete a scan from history. @@ -49,5 +60,4 @@ def delete(self, scan_id: int | str) -> DeleteScanResult: NotFoundError: If no scan with the given ID exists. VulnRadarError: If permission is denied or request fails. """ - data = self._http.delete(f"/history/{scan_id}") - return DeleteScanResult.from_dict(data) + return read_reply(DeleteScanResult.from_dict, self._http.delete(_scan_path(scan_id))) diff --git a/vulnradar/services/metadata_service.py b/vulnradar/services/metadata_service.py index 2a2e039..9d3fc2b 100644 --- a/vulnradar/services/metadata_service.py +++ b/vulnradar/services/metadata_service.py @@ -2,6 +2,7 @@ from ..http import HTTPClient from ..models.finding_types import FindingTypesResult +from ..replies import read_reply class MetadataService: @@ -20,4 +21,4 @@ def finding_types(self) -> FindingTypesResult: A FindingTypesResult containing all finding type definitions. """ data = self._http.get("/finding-types") - return FindingTypesResult.from_dict(data) + return read_reply(FindingTypesResult.from_dict, data) diff --git a/vulnradar/services/scan_service.py b/vulnradar/services/scan_service.py index f152931..24b4550 100644 --- a/vulnradar/services/scan_service.py +++ b/vulnradar/services/scan_service.py @@ -2,6 +2,7 @@ from ..http import HTTPClient from ..models.scan_result import ScanResult +from ..replies import read_scan_reply from ..utils.url_validation import validate_url @@ -31,4 +32,4 @@ def scan(self, url: str, scanners: list[str] | None = None) -> ScanResult: if scanners is not None: payload["scanners"] = scanners data = self._http.post("/scan", payload) - return ScanResult.from_dict(data) + return read_scan_reply(ScanResult.from_dict, data) diff --git a/vulnradar/utils/__init__.py b/vulnradar/utils/__init__.py index 2681133..1f240b5 100644 --- a/vulnradar/utils/__init__.py +++ b/vulnradar/utils/__init__.py @@ -1,4 +1,4 @@ -from .rate_limit import RateLimitInfo, parse_rate_limit_headers +from .rate_limit import RateLimitInfo, parse_rate_limit, parse_retry_after from .url_validation import validate_url -__all__ = ["RateLimitInfo", "parse_rate_limit_headers", "validate_url"] +__all__ = ["RateLimitInfo", "parse_rate_limit", "parse_retry_after", "validate_url"] diff --git a/vulnradar/utils/rate_limit.py b/vulnradar/utils/rate_limit.py index a568847..13b50aa 100644 --- a/vulnradar/utils/rate_limit.py +++ b/vulnradar/utils/rate_limit.py @@ -1,50 +1,92 @@ +"""Reading what a server says about its limits. Nothing here raises.""" + from __future__ import annotations +import math from collections.abc import Mapping -from contextlib import suppress from datetime import UTC, datetime +from email.utils import parsedate_to_datetime +from typing import Any -from ..constants import ( - RATE_LIMIT_HEADER, - RATE_LIMIT_REMAINING_HEADER, - RATE_LIMIT_RESET_HEADER, -) +from ..enums import RateLimitKind from ..exceptions import RateLimitInfo -__all__ = ["RateLimitInfo", "parse_rate_limit_headers"] +__all__ = ["RateLimitInfo", "parse_rate_limit", "parse_retry_after", "rate_limit_kind"] +_KIND_BY_CODE = { + "API_QUOTA_EXCEEDED": RateLimitKind.API_QUOTA, + "DAILY_LIMIT": RateLimitKind.DAILY_SCANS, + "CONCURRENT_SCAN_LIMIT": RateLimitKind.CONCURRENT_SCANS, + "TARGET_RATE_LIMIT": RateLimitKind.TARGET, + "BULK_RATE_LIMIT": RateLimitKind.BULK, + "RATE_LIMITED": RateLimitKind.OTHER, +} -def parse_rate_limit_headers(headers: Mapping[str, str]) -> RateLimitInfo | None: - """Parse rate limit information from HTTP response headers. - Args: - headers: HTTP response headers mapping. +def parse_rate_limit(headers: Mapping[str, str], body: Mapping[str, Any]) -> RateLimitInfo | None: + """Collect the limit figures from the headers, falling back to the body. Returns: - A RateLimitInfo instance if rate limit headers are present, otherwise None. + A RateLimitInfo, or None if the reply carried no usable figure. """ - raw_limit = headers.get(RATE_LIMIT_HEADER) - raw_remaining = headers.get(RATE_LIMIT_REMAINING_HEADER) - raw_reset = headers.get(RATE_LIMIT_RESET_HEADER) + limit = _count(headers.get("X-RateLimit-Limit"), body.get("limit")) + remaining = _count(headers.get("X-RateLimit-Remaining"), body.get("remaining")) + used = _count(headers.get("X-RateLimit-Used"), body.get("used")) + if used is None and limit is not None and remaining is not None: + used = limit - remaining + resets_at = _time(headers.get("X-RateLimit-Reset")) or _time(body.get("resets_at")) - if raw_limit is None and raw_remaining is None: + if limit is None and used is None and remaining is None and resets_at is None: return None + return RateLimitInfo(limit=limit, used=used, remaining=remaining, resets_at=resets_at) + + +def rate_limit_kind( + code: str | None, rate_limit: RateLimitInfo | None, retry_after: float | None +) -> RateLimitKind: + """Name the limit behind a 429 reply.""" + if code in _KIND_BY_CODE: + return _KIND_BY_CODE[code] + # Servers before 4.0 send no code for these two. Both come with figures, and + # only the key's request budget also says how long to wait. + if rate_limit is not None: + return RateLimitKind.API_QUOTA if retry_after is not None else RateLimitKind.DAILY_SCANS + return RateLimitKind.OTHER - limit = int(raw_limit) if raw_limit is not None else 0 - remaining = int(raw_remaining) if raw_remaining is not None else 0 - used = limit - remaining - resets_at: datetime | None = None - if raw_reset is not None: +def parse_retry_after(value: str | None) -> float | None: + """Read a Retry-After header, given in seconds or as a date.""" + if not value: + return None + try: + seconds = float(value) + except ValueError: try: - resets_at = datetime.fromtimestamp(int(raw_reset), tz=UTC) - except (ValueError, OSError): - with suppress(ValueError): - resets_at = datetime.fromisoformat(raw_reset.replace("Z", "+00:00")) - - return RateLimitInfo( - limit=limit, - used=used, - remaining=remaining, - resets_at=resets_at, - ) + when = parsedate_to_datetime(value) + except (TypeError, ValueError): + return None + if when.tzinfo is None: + when = when.replace(tzinfo=UTC) + return max(0.0, (when - datetime.now(UTC)).total_seconds()) + return seconds if math.isfinite(seconds) and seconds >= 0 else None + + +def _count(*values: object) -> int | None: + for value in values: + if isinstance(value, int) and not isinstance(value, bool): + return value + if isinstance(value, str) and value.isdecimal(): + return int(value) + return None + + +def _time(value: object) -> datetime | None: + if not isinstance(value, str): + return None + try: + if value.isdecimal(): + return datetime.fromtimestamp(int(value), tz=UTC) + when = datetime.fromisoformat(value.replace("Z", "+00:00")) + except (ValueError, OverflowError, OSError): + return None + return when if when.tzinfo else when.replace(tzinfo=UTC) From e5e4ee0b652994dffdbbb37de7ca404ab4cca0b6 Mon Sep 17 00:00:00 2001 From: RejectModders Date: Sat, 28 Nov 2026 19:36:37 -0600 Subject: [PATCH 2/3] docs: describe the new connection, errors and rate limits --- CHANGELOG.md | 30 +++++++++++ README.md | 138 +++++++++++++++++++++++++++++---------------------- 2 files changed, 108 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f775a96..0113ae5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,9 +10,27 @@ dates on PyPI (UTC). ### Added - The package ships `py.typed`, so type checkers use its annotations. +- `VULNRADAR_TOKEN` and `VULNRADAR_API_BASE` are used when `api_key` or + `base_url` is not given. +- `NetworkError`, `RequestTimeoutError`, `UnexpectedResponseError` and + `RateLimitKind`. `RateLimitInfo` is exported. +- Errors carry `code`, `request_id`, `retry_after` and `body`, and a + `RateLimitError` says which limit was reached in `kind`. ### 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. +- `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 + `AuthenticationError`. +- A reply without the fields a result needs raises `UnexpectedResponseError` + instead of giving an empty result. +- Rate limit figures the server did not send are `None`, not zero. +- A missing or unusable key, address or number raises `ValueError` when the + client is created. - Python 3.11 or newer is required. - `requests` 2.33.0 or newer is required, which leaves out PYSEC-2026-2275. - `Severity` is a `StrEnum`: `str()` and f-strings now give the value, such as @@ -25,6 +43,18 @@ dates on PyPI (UTC). ### Fixed - `vulnradar.__version__` reports the same version as the package metadata. +- 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`. + +### Security + +- A request that starts or deletes something is never sent twice. +- `base_url` must use `https`, except for this computer. +- Redirects are not followed. +- The key is not shown when the client's settings are printed, and a `.netrc` + entry cannot replace it. +- A scan id cannot change the address of a request. ## 2.0.0b2 - 2026-03-16 diff --git a/README.md b/README.md index b2cf1da..e016a3d 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,16 @@ A Python SDK for the [VulnRadar](https://vulnradar.dev) security scanning API. > **This SDK is being rebuilt and does not work yet.** Every release published so far > (0.1.0, 2.0.0b1 and 2.0.0b2) calls the retired v1 or v2 API. Against vulnradar.dev -> today, only `client.version()` succeeds. Version 0.1.0, which `pip install vulnradar` -> currently installs, also prints each successful API response to the console, so avoid it. -> Until a new release is out, call the [v3 API](https://vulnradar.dev/docs/api) directly. -> The rest of this page describes the old releases. +> today, only `client.version()` succeeds in them. Version 0.1.0, which +> `pip install vulnradar` currently installs, also prints each successful API response to +> 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. --- @@ -55,9 +61,11 @@ for finding in result.findings: ## Authentication -All requests are authenticated using a Bearer token in the `Authorization` header. Pass your API key when constructing the client: +All requests are authenticated using a Bearer token in the `Authorization` header. Set +`VULNRADAR_TOKEN` in the environment, or pass the key when constructing the client: ```python +client = VulnRadar() # reads VULNRADAR_TOKEN client = VulnRadar(api_key="your-api-key") ``` @@ -68,12 +76,20 @@ client = VulnRadar(api_key="your-api-key") ```python client = VulnRadar( api_key="your-api-key", - timeout=60, # HTTP timeout in seconds (default: 30) - retries=5, # Retry attempts on server errors (default: 3) - base_url="https://vulnradar.dev/api/v2", # Custom base URL (optional) + base_url="https://vulnradar.dev/api/v3", # or set VULNRADAR_API_BASE + timeout=30, # seconds to wait for the server + retries=2, # extra attempts for reads ) ``` +- `base_url` must use `https`. Plain `http` is accepted only for this computer + (`localhost`, `127.0.0.1` or `::1`). +- Only reads are retried, after a network failure or a 5xx reply. A request that starts or + deletes something is sent once. A `Retry-After` of up to 30 seconds is honoured; a longer + one is reported to you instead. +- Redirects are never followed. +- Settings that cannot work, such as a missing key, raise `ValueError`. + --- ## Running Scans @@ -220,71 +236,70 @@ All exceptions inherit from `VulnRadarError`: ```python from vulnradar import ( - VulnRadar, - VulnRadarError, AuthenticationError, - BadRequestError, - ForbiddenError, + NetworkError, NotFoundError, RateLimitError, - ServerError, - InvalidURLError, - UnprocessableEntityError, + VulnRadar, + VulnRadarError, ) -client = VulnRadar(api_key="your-api-key") +client = VulnRadar() try: - result = client.scan("https://example.com") -except InvalidURLError as e: - print(f"Bad URL: {e.url}") + result = client.history.get(123) except AuthenticationError: - print("Invalid or expired API key.") -except RateLimitError as e: - print(f"Rate limited. Resets at: {e.resets_at}") - print(f"Limit: {e.limit}, Remaining: {e.remaining}") + print("Invalid or revoked API key.") except NotFoundError: - print("Resource not found.") -except ServerError as e: - print(f"Server error {e.status_code}: {e.message}") + print("No such scan.") +except RateLimitError as e: + print(f"Rate limited ({e.kind}). Retry after: {e.retry_after} seconds.") +except NetworkError as e: + print(f"No reply: {e.message}") except VulnRadarError as e: - print(f"SDK error: {e.message}") + print(e.message, e.status_code, e.code, e.request_id) ``` +Every error has `message`, `status_code`, `code` (the server's error code), `request_id`, +`retry_after` and `body` (the server's reply). Those the server did not send are `None`, and +`body` is empty. + ### Exception Reference -| Exception | HTTP Status | Description | -|---------------------|-------------|--------------------------------------| -| `AuthenticationError` | 401 | Invalid or missing API key | -| `BadRequestError` | 400 | Malformed request or invalid params | -| `ForbiddenError` | 403 | Authenticated but not permitted | -| `NotFoundError` | 404 | Requested resource does not exist | -| `UnprocessableEntityError` | 422 | Target is unreachable/not processable | -| `RateLimitError` | 429 | Rate limit exceeded | -| `ServerError` | 5xx | API-side internal error | -| `InvalidURLError` | none | URL failed client-side validation | +| Exception | HTTP status | Description | +|---|---|---| +| `AuthenticationError` | 401 | Invalid or missing API key | +| `BadRequestError` | 400 | Malformed request or invalid parameters | +| `ForbiddenError` | 403 | Authenticated but not permitted | +| `NotFoundError` | 404 | Requested resource does not exist | +| `UnprocessableEntityError` | 422 | The target could not be processed | +| `RateLimitError` | 429 | A rate limit or quota is used up | +| `ServerError` | 5xx | Error on the server's side | +| `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 | +| `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 | --- ## Rate Limits -The SDK automatically parses rate limit headers from every response. When you hit a rate limit, the `RateLimitError` exception exposes: - -```python -except RateLimitError as e: - print(e.limit) # Total allowed requests - print(e.used) # Requests used - print(e.remaining) # Requests remaining - print(e.resets_at) # datetime when limit resets -``` +A `RateLimitError` says which limit was reached in `kind`: -Headers parsed: -- `X-RateLimit-Limit` -- `X-RateLimit-Remaining` -- `X-RateLimit-Reset` -- `Retry-After` +| `RateLimitKind` | Limit | +|---|---| +| `API_QUOTA` | The key's requests per 24 hours | +| `DAILY_SCANS` | The plan's scans per day | +| `CONCURRENT_SCANS` | Too many scans running at once | +| `TARGET` | Too many scans of one target domain | +| `BULK` | Too many bulk requests | +| `OTHER` | A short-term limit, or one the server did not name | -Default API key quota: `50 requests per 24 hours`. +`limit`, `used`, `remaining`, `resets_at` and `retry_after` are filled in when the server +sends them and are `None` otherwise. A rate-limited request is not retried automatically. +How large each limit is depends on your plan; see the +[API documentation](https://vulnradar.dev/docs/api). --- @@ -314,18 +329,21 @@ critical = [f for f in result.findings if f.severity == Severity.CRITICAL] ```python import time -from vulnradar import VulnRadar, RateLimitError -client = VulnRadar(api_key="your-api-key") +from vulnradar import RateLimitError, VulnRadar + +client = VulnRadar() + -def safe_scan(url: str): +def read_scan(scan_id: int): try: - return client.scan(url) + return client.history.get(scan_id) except RateLimitError as e: - if e.resets_at: - wait = (e.resets_at - datetime.now(timezone.utc)).total_seconds() - time.sleep(max(wait, 1)) - return client.scan(url) + # Wait out a short limit. A daily one can take hours, so report it. + if e.retry_after is None or e.retry_after > 60: + raise + time.sleep(e.retry_after) + return client.history.get(scan_id) ``` **Use history to avoid redundant scans:** From b77cd320a4dd270e26961528e24ca63c54ad80ff Mon Sep 17 00:00:00 2001 From: RejectModders Date: Sat, 28 Nov 2026 20:16:27 -0600 Subject: [PATCH 3/3] fix: keep the key on the configured host and off proxies A base_url without a path made version() send the key to a host named "version", and a proxy from the environment would have received plain http requests to this computer. Both are closed. Deeply nested or impossible values in a reply now raise SDK errors, and a network error no longer carries the request that holds the key. --- CHANGELOG.md | 13 ++++++++-- README.md | 4 +-- tests/fake.py | 2 ++ tests/test_config.py | 45 ++++++++++++++++++++++++++++++--- tests/test_errors.py | 17 +++++++++++++ tests/test_replies.py | 24 ++++++++++++++++++ tests/test_transport.py | 26 +++++++++++++++++++ vulnradar/config.py | 2 ++ vulnradar/http.py | 36 +++++++++++++++++++------- vulnradar/models/scan_result.py | 2 +- vulnradar/replies.py | 2 +- vulnradar/utils/rate_limit.py | 3 ++- 12 files changed, 157 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0113ae5..ebcebae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,7 +30,10 @@ dates on PyPI (UTC). instead of giving an empty result. - Rate limit figures the server did not send are `None`, not zero. - A missing or unusable key, address or number raises `ValueError` when the - client is created. + client is created. `base_url` must include the API path. +- `history.get()` and `history.delete()` raise `ValueError` for an id holding + anything but letters, digits, `_` and `-`. +- `timeout` may be a fraction of a second. - Python 3.11 or newer is required. - `requests` 2.33.0 or newer is required, which leaves out PYSEC-2026-2275. - `Severity` is a `StrEnum`: `str()` and f-strings now give the value, such as @@ -40,6 +43,11 @@ dates on PyPI (UTC). - The timestamp filled in when a reply has none is timezone-aware (UTC). - The README now says that no published release works with the current API. +### Removed + +- `vulnradar.utils.parse_rate_limit_headers`, and the `VERSION_URL` and + `RATE_LIMIT_*_HEADER` constants. + ### Fixed - `vulnradar.__version__` reports the same version as the package metadata. @@ -50,7 +58,8 @@ dates on PyPI (UTC). ### Security - A request that starts or deletes something is never sent twice. -- `base_url` must use `https`, except for this computer. +- `base_url` must use `https`, except for this computer, and a plain `http` + request never goes through a proxy. - Redirects are not followed. - The key is not shown when the client's settings are printed, and a `.netrc` entry cannot replace it. diff --git a/README.md b/README.md index e016a3d..1854c8e 100644 --- a/README.md +++ b/README.md @@ -82,8 +82,8 @@ client = VulnRadar( ) ``` -- `base_url` must use `https`. Plain `http` is accepted only for this computer - (`localhost`, `127.0.0.1` or `::1`). +- `base_url` must include the API path and use `https`. Plain `http` is accepted only for + this computer (`localhost`, `127.0.0.1` or `::1`) and never goes through a proxy. - Only reads are retried, after a network failure or a 5xx reply. A request that starts or deletes something is sent once. A `Retry-After` of up to 30 seconds is honoured; a longer one is reported to you instead. diff --git a/tests/fake.py b/tests/fake.py index e2791ba..fdcf703 100644 --- a/tests/fake.py +++ b/tests/fake.py @@ -18,6 +18,7 @@ class FakeTransport(BaseAdapter): def __init__(self) -> None: super().__init__() self.sent: list[PreparedRequest] = [] + self.proxies_used: list[dict[str, str]] = [] self._outcomes: list[Response | Exception] = [] def reply( @@ -48,6 +49,7 @@ def send( proxies: Any = None, ) -> Response: self.sent.append(request) + self.proxies_used.append(dict(proxies or {})) 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/test_config.py b/tests/test_config.py index c3ea6a1..1d472c3 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -88,6 +88,9 @@ def test_a_malformed_key_is_refused_without_being_repeated(key: str) -> None: "https://vulnradar.dev/api/v3?x=1", "https://vulnradar.dev/api/v3#part", "https://vulnradar.dev:port/api/v3", + "https://vulnradar.dev", + "https://vulnradar.dev/", + "http://localhost:8080", "", ], ) @@ -112,14 +115,50 @@ def test_plain_http_is_allowed_to_this_computer_only( assert url == f"{base_url}/history" -def test_the_version_address_keeps_a_path_prefix(transport: FakeTransport) -> None: - sdk = VulnRadar(api_key="test-key", base_url="https://host.example.test/scanner/api/v3") +@pytest.mark.parametrize( + ("base_url", "version_url"), + [ + ( + "https://host.example.test/scanner/api/v3", + "https://host.example.test/scanner/api/version", + ), + ("https://host.example.test/v3", "https://host.example.test/version"), + ], +) +def test_the_version_address_stays_on_the_same_host( + transport: FakeTransport, base_url: str, version_url: str +) -> None: + sdk = VulnRadar(api_key="test-key", base_url=base_url) sdk._http._session.mount("https://", transport) transport.reply(body={"current": "3.9.2"}) sdk.version() - assert transport.sent[0].url == "https://host.example.test/scanner/api/version" + assert transport.sent[0].url == version_url + + +@pytest.mark.parametrize( + ("base_url", "through_proxy"), + [ + ("http://localhost:8080/api/v3", False), + ("http://127.0.0.1:8080/api/v3", False), + ("https://vulnradar.dev/api/v3", True), + ], +) +def test_a_proxy_never_sees_an_unencrypted_request( + transport: FakeTransport, + monkeypatch: pytest.MonkeyPatch, + base_url: str, + through_proxy: bool, +) -> None: + for name in ("NO_PROXY", "no_proxy"): + monkeypatch.delenv(name, raising=False) + for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"): + monkeypatch.setenv(name, "http://proxy.example.test:3128") + + sent_to(VulnRadar(api_key="test-key", base_url=base_url), transport) + + assert bool(transport.proxies_used[-1]) is through_proxy @pytest.mark.parametrize(("option", "value"), [("retries", -1), ("timeout", 0), ("timeout", -2.5)]) diff --git a/tests/test_errors.py b/tests/test_errors.py index 89007ef..b81e471 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -285,3 +285,20 @@ def test_unreadable_limit_values_do_not_hide_the_error( limit = caught.value assert (limit.limit, limit.used, limit.remaining, limit.resets_at) == (None, None, 3, None) + + +@pytest.mark.parametrize("header", ["X-RateLimit-Limit", "X-RateLimit-Reset", "Retry-After"]) +def test_an_enormous_limit_header_does_not_hide_the_error( + client: VulnRadar, transport: FakeTransport, header: str +) -> None: + transport.reply(429, {"error": "slow down"}, headers={header: "9" * 5000}) + + with pytest.raises(RateLimitError) as caught: + client.history.list() + + assert caught.value.message == "slow down" + assert (caught.value.limit, caught.value.resets_at, caught.value.retry_after) == ( + None, + None, + None, + ) diff --git a/tests/test_replies.py b/tests/test_replies.py index f01ed02..a6265c4 100644 --- a/tests/test_replies.py +++ b/tests/test_replies.py @@ -105,3 +105,27 @@ def test_a_reply_of_the_wrong_shape_raises_an_sdk_error( with pytest.raises(UnexpectedResponseError): client.history.list() + + +@pytest.mark.parametrize( + "raw", + [ + b'{"scans": [{"id": 1e999, "summary": {}}]}', + b'{"scans": [{"id": 1, "findings_count": 1e999, "summary": {}}]}', + ], +) +def test_an_impossible_number_raises_an_sdk_error( + client: VulnRadar, transport: FakeTransport, raw: bytes +) -> None: + transport.reply(raw=raw) + + with pytest.raises(UnexpectedResponseError): + client.history.list() + + +def test_an_impossible_history_id_is_read_as_missing( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(raw=b'{"findings": [], "summary": {"total": 0}, "scanHistoryId": 1e999}') + + assert client.history.get(1).scan_history_id is None diff --git a/tests/test_transport.py b/tests/test_transport.py index c7c5259..ad0fb92 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -208,3 +208,29 @@ def test_a_text_scan_id_is_accepted(client: VulnRadar, transport: FakeTransport) client.history.delete("0123456789abcdef0123456789abcdef") assert transport.sent[0].url == f"{BASE_URL}/history/0123456789abcdef0123456789abcdef" + + +@pytest.mark.parametrize( + "failure", [requests.exceptions.ConnectionError(), requests.exceptions.ReadTimeout()] +) +def test_a_network_error_does_not_carry_the_request_and_its_key( + client: VulnRadar, transport: FakeTransport, failure: Exception +) -> None: + transport.fail(failure) + + with pytest.raises(NetworkError) as caught: + client.history.list() + + assert caught.value.__cause__ is None + assert caught.value.__context__ is None + assert type(failure).__name__ in caught.value.message + + +@pytest.mark.parametrize("status", [200, 400, 500]) +def test_a_deeply_nested_reply_raises_an_sdk_error( + client: VulnRadar, transport: FakeTransport, status: int +) -> None: + transport.reply(status, raw=b"[" * 200_000) + + with pytest.raises(VulnRadarError): + client.history.list() diff --git a/vulnradar/config.py b/vulnradar/config.py index 3c982c6..f58c2c2 100644 --- a/vulnradar/config.py +++ b/vulnradar/config.py @@ -68,4 +68,6 @@ def _clean_base_url(base_url: str) -> str: raise ValueError("base_url must use https. Plain http is only for this computer.") if parts.username is not None or parts.password is not None or parts.query or parts.fragment: raise ValueError("base_url cannot hold a user name, password, query or fragment.") + if not parts.path: + raise ValueError(f"base_url must include the API path, as in {BASE_URL}.") return url diff --git a/vulnradar/http.py b/vulnradar/http.py index 6b627aa..4e8843a 100644 --- a/vulnradar/http.py +++ b/vulnradar/http.py @@ -4,6 +4,7 @@ import re import time from typing import Any +from urllib.parse import urlsplit import requests from requests import PreparedRequest, Response, Session @@ -35,6 +36,9 @@ 422: UnprocessableEntityError, } +# What reading a reply as JSON can raise; the last one for absurdly deep nesting. +_BAD_JSON = (ValueError, RecursionError) + # The server records this per key and accepts only these characters. _CLIENT_NAME = re.sub(r"[^A-Za-z0-9._/-]", "-", f"python-sdk/{__version__}")[:64] @@ -69,6 +73,10 @@ def __init__(self, config: VulnRadarConfig) -> None: "x-vulnradar-client": _CLIENT_NAME, } ) + if urlsplit(config.base_url).scheme == "http": + # Plain http is for this computer only. A proxy from the environment + # 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'.""" @@ -121,14 +129,24 @@ def _send(self, method: str, url: str, json: dict[str, Any] | None) -> dict[str, # A redirect could carry the key somewhere it was never meant to go. allow_redirects=False, ) - except requests.exceptions.Timeout as error: - message = f"No answer within {self._config.timeout} seconds." - if method != "GET": - message += " The request may still have been carried out." - raise RequestTimeoutError(message) from error except requests.exceptions.RequestException as error: - raise NetworkError(f"The request did not complete ({type(error).__name__}).") from error - return _read(response) + failure = self._network_failure(method, error) + 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 _read(response: Response) -> dict[str, Any]: @@ -152,7 +170,7 @@ def unreadable(message: str) -> UnexpectedResponseError: raise unreadable("The server answered with a web page instead of data. Check base_url.") try: data = response.json() - except ValueError: + except _BAD_JSON: raise unreadable("The server's reply was empty or was not JSON.") from None if not isinstance(data, dict): raise unreadable("The server's reply was not a JSON object.") @@ -164,7 +182,7 @@ def _error(response: Response) -> VulnRadarError: status = response.status_code try: parsed = response.json() - except ValueError: + except _BAD_JSON: parsed = None body: dict[str, Any] = parsed if isinstance(parsed, dict) else {} diff --git a/vulnradar/models/scan_result.py b/vulnradar/models/scan_result.py index f2c2289..74d5aa4 100644 --- a/vulnradar/models/scan_result.py +++ b/vulnradar/models/scan_result.py @@ -27,7 +27,7 @@ def _parse_int(value: Any) -> int | None: return None try: return int(value) - except (TypeError, ValueError): + except (OverflowError, TypeError, ValueError): return None @classmethod diff --git a/vulnradar/replies.py b/vulnradar/replies.py index 2de75f5..e3c3738 100644 --- a/vulnradar/replies.py +++ b/vulnradar/replies.py @@ -18,7 +18,7 @@ def read_reply(model: Callable[[dict[str, Any]], T], data: dict[str, Any]) -> T: """ try: return model(data) - except (AttributeError, KeyError, TypeError, ValueError) as error: + except (AttributeError, KeyError, OverflowError, TypeError, ValueError) as error: raise UnexpectedResponseError( f"The server's reply could not be read ({type(error).__name__}).", body=data ) from error diff --git a/vulnradar/utils/rate_limit.py b/vulnradar/utils/rate_limit.py index 13b50aa..b8f6bff 100644 --- a/vulnradar/utils/rate_limit.py +++ b/vulnradar/utils/rate_limit.py @@ -75,7 +75,8 @@ def _count(*values: object) -> int | None: for value in values: if isinstance(value, int) and not isinstance(value, bool): return value - if isinstance(value, str) and value.isdecimal(): + # No real figure is this long, and int() refuses extremely long text. + if isinstance(value, str) and value.isdecimal() and len(value) <= 18: return int(value) return None