Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,30 @@ 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. `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
Expand All @@ -22,9 +43,27 @@ 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.
- 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, 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.
- A scan id cannot change the address of a request.

## 2.0.0b2 - 2026-03-16

Expand Down
138 changes: 78 additions & 60 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

---

Expand Down Expand Up @@ -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")
```

Expand All @@ -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 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.
- Redirects are never followed.
- Settings that cannot work, such as a missing key, raise `ValueError`.

---

## Running Scans
Expand Down Expand Up @@ -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).

---

Expand Down Expand Up @@ -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:**
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions tests/fake.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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):
Expand Down
11 changes: 5 additions & 6 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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"])

Expand All @@ -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)
Expand Down
Loading