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
34 changes: 30 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,34 @@ dates on PyPI (UTC).
`RateLimitKind`. `RateLimitInfo` is exported.
- Errors carry `code`, `request_id`, `retry_after` and `body`, and a
`RateLimitError` says which limit was reached in `kind`.
- `client.scans` starts scans and crawls, reports their progress, waits for them
and cancels them, with `ScanJob`, `ScanStatus`, `ScanState` and `ScanOptions`.
- `ScanFailedError` and `ScanTimeoutError`. An error raised while waiting names
the scan in `scan_id`.
- Scan options: `public`, `capture_screenshot`, `port_scan` and `team_ids`.
- `Scanner` lists the scanner names.
- Results keep the server's whole reply in `raw`, and have `public_id`,
`incomplete` and `tags`. Findings have their category, evidence, fix steps,
`suppressed` and `remediation_status` among other details.

### Changed

- The client calls the v3 API. Scans there run in the background, which it
cannot follow yet: `scan()` and `scan_crawl()` raise
`UnexpectedResponseError` naming the scan they started.
- The client calls the v3 API. `scan()` and `scan_crawl()` wait for the
background scan to finish, for 960 seconds unless `timeout` says otherwise.
- Scanner names are checked before a scan is sent.
- `ScanResult.duration` is now `duration_ms`, in milliseconds, and
`scanned_at` is `None` when the server gives no time.
- `CrawlResult` is a `ScanResult` with `pages`, `pages_discovered`,
`pages_scanned`, `pages_skipped` and `pages_unreachable`.
- `CrawlPage.duration` is now `duration_ms`, and `ScanResult`, `Finding` and
`CrawlPage` take different constructor arguments.
- `incomplete` also holds `page-checks` when checks failed to run, and
`crawl-pages-not-scanned` when a crawl left pages out, for servers that do not
say so themselves.
- Summary counts that are not numbers are an error.
- An unfamiliar severity is `Severity.UNKNOWN`, not `info`.
- Targets without a scheme, with punycode or underscore host names, or using any
scheme the server knows are no longer rejected.
- `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
Expand All @@ -40,11 +62,14 @@ dates on PyPI (UTC).
`high`.
- `__version__` is read from the installed package, and is `unknown` when the
source is used without being installed.
- The timestamp filled in when a reply has none is timezone-aware (UTC).
- The timestamp filled in when a history entry has none is timezone-aware (UTC).
- The README now says that no published release works with the current API.

### Removed

- `Finding.type`, which the server never sends, and `Finding.remediation`; use
`fix_steps` and `remediation_status`.
- `CrawlInfo`, `CrawlResult.crawl` and `CrawlPage.response_headers`.
- `vulnradar.utils.parse_rate_limit_headers`, and the `VERSION_URL` and
`RATE_LIMIT_*_HEADER` constants.

Expand All @@ -54,6 +79,7 @@ dates on PyPI (UTC).
- Network failures, unreadable replies and odd rate limit headers raise SDK
errors instead of other exceptions.
- The version address keeps the path prefix of a self-hosted `base_url`.
- `history.get()` sets `scan_history_id`.

### Security

Expand Down
127 changes: 85 additions & 42 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,10 @@ A Python SDK for the [VulnRadar](https://vulnradar.dev) security scanning API.
> the console, so avoid it. Until a new release is out, call the
> [v3 API](https://vulnradar.dev/docs/api) directly.
>
> The code on `main` calls the v3 API but cannot yet follow a scan to its end:
> `scan()` and `scan_crawl()` start the scan and then raise `UnexpectedResponseError`,
> and `history.list()` cannot read the current reply. The sections on authentication,
> configuration, errors and rate limits describe `main`. The others still describe the
> old releases.
> The code on `main` calls the v3 API and runs scans and crawls, but `history.list()`
> cannot yet read the current reply. This page describes `main`, apart from the sections
> on listing history, finding types and the version check, which still describe the old
> releases.

---

Expand Down Expand Up @@ -96,55 +95,105 @@ client = VulnRadar(

### Single URL Scan

The server runs a scan in the background. `scan()` starts it, asks every few seconds how
it is going, and returns the finished result. Asking does not use up any quota.

```python
from vulnradar import Scanner

result = client.scan("https://example.com")

# Optional: run only selected scanners.
result = client.scan("https://example.com", scanners=["headers", "ssl"])
# Optional: run only some scanners, keep the result out of the public directory,
# and wait no longer than two minutes.
result = client.scan(
"https://example.com",
scanners=[Scanner.HEADERS, Scanner.SSL],
public=False,
timeout=120,
)

print(result.url)
print(result.scanned_at)
print(result.duration)
print(result.scan_history_id)
print(result.url, result.scanned_at, result.duration_ms, result.scan_history_id)

for finding in result.findings:
print(finding.type, finding.severity, finding.title)
print(finding.severity, finding.title)
print(finding.description)
print(finding.remediation)
for step in finding.fix_steps:
print(" -", step)

if result.incomplete:
print("Not everything was checked:", ", ".join(result.incomplete))
```

Supported target protocols: `http://`, `https://`, `ws://`, `wss://`, `ftp://`, `ftps://`.
A scan without findings is not necessarily clean: check `result.incomplete`, which lists
what was not checked. `page-checks` means some checks failed to run, and
`crawl-pages-not-scanned` means a crawl left pages out, for example when your quota ran
out. Findings your account marked as false positives are
included, with `finding.suppressed` set.

**ScanResult fields:**
Scanner names are checked before anything is sent, because some servers accept a misspelt
one and then check nothing. The other options are `capture_screenshot`, `port_scan` (needs
a verified domain) and `team_ids`.

| Field | Type | Description |
|--------------------|-----------------------|------------------------------------|
| `url` | `str` | Scanned URL |
| `scanned_at` | `datetime` | Timestamp of the scan |
| `duration` | `float` | Scan duration in seconds |
| `findings` | `list[Finding]` | List of security findings |
| `summary` | `Summary` | Aggregated finding counts |
| `response_headers` | `dict[str, str]` | HTTP headers from the target |
| `scan_history_id` | `int \| None` | ID in scan history |
| `notes` | `str \| None` | Optional scan notes |
A target may be written without a scheme (`example.com`). Servers before 4.0 scan only
`http` and `https`.

### Without waiting

```python
job = client.scans.start("https://example.com")

status = client.scans.status(job.id)
print(status.state, status.categories_completed, status.categories_total)

result = client.scans.wait(job.id, timeout=600) # or client.scans.cancel(job.id)
```

`scan()` and `wait()` wait 960 seconds unless you pass `timeout`.
`wait()` raises `ScanFailedError` if the scan fails or is cancelled, and `ScanTimeoutError`
if it is still running after `timeout` seconds. A scan that times out keeps running, so you
can wait for it again. Errors raised while waiting carry the scan's id in `scan_id`.

### ScanResult fields

| Field | Type | Description |
|---|---|---|
| `url` | `str` | Scanned address |
| `findings` | `list[Finding]` | Security findings |
| `summary` | `Summary` | Finding counts by severity |
| `incomplete` | `list[str]` | What was not checked |
| `scanned_at` | `datetime \| None` | When the scan ran |
| `duration_ms` | `int \| None` | How long it took, in milliseconds |
| `scan_history_id` | `int \| None` | Id in your scan history |
| `public_id` | `str \| None` | Text id of the scan |
| `response_headers` | `dict[str, str]` | HTTP headers from the target |
| `tags` | `list[str]` | Tags on the scan |
| `notes` | `str \| None` | Your notes |
| `raw` | `dict` | Everything the server sent, such as `siteGrade` or `dnsRecords` |

A `Finding` has `id`, `title`, `severity`, `description`, `category`, `evidence`,
`explanation`, `risk_impact`, `fix_steps`, `code_examples`, `references`, `suppressed`,
`remediation_status` and `raw`.

---

## Crawl Scans

Perform a deep crawl across multiple pages of a target:
Scan several pages of a site. Each page counts as one scan against your daily quota, and
your plan caps how many pages one crawl may take.

```python
result = client.scan_crawl("https://example.com")

print(f"Pages scanned: {result.crawl.total_pages}")
print(f"Total findings: {result.crawl.total_findings}")
print(f"Pages scanned: {result.pages_scanned}, skipped: {result.pages_skipped}")
print(f"Total findings: {result.summary.total}")

for page in result.pages:
print(f"{page.url}: {page.summary.total} findings")
```

You can also provide a list of specific URLs to include:
A `CrawlResult` is a `ScanResult` for the whole site, plus `pages`, `pages_discovered`,
`pages_scanned`, `pages_skipped` and `pages_unreachable`. You can name the pages to scan,
and start a crawl without waiting with `client.scans.start_crawl()`.

```python
result = client.scan_crawl(
Expand Down Expand Up @@ -278,6 +327,8 @@ Every error has `message`, `status_code`, `code` (the server's error code), `req
| `NetworkError` | none | No complete reply arrived |
| `RequestTimeoutError` | none | A `NetworkError`: no answer in time. A change may still have happened |
| `UnexpectedResponseError` | any | A redirect, or a reply that cannot be understood |
| `ScanFailedError` | none | A scan failed or was cancelled |
| `ScanTimeoutError` | none | A scan did not finish in the time allowed |
| `InvalidURLError` | none | A target failed the check made before sending |
| `VulnRadarError` | other | The base class, also used for statuses such as 402, 409 and 413 |

Expand Down Expand Up @@ -313,6 +364,7 @@ Severity.HIGH # "high"
Severity.MEDIUM # "medium"
Severity.LOW # "low"
Severity.INFO # "info"
Severity.UNKNOWN # a level this version of the SDK does not know
```

Filter findings by severity:
Expand Down Expand Up @@ -346,22 +398,13 @@ def read_scan(scan_id: int):
return client.history.get(scan_id)
```

**Use history to avoid redundant scans:**

```python
history = client.history.list()
already_scanned = {s.url for s in history.scans}

if target_url not in already_scanned:
result = client.scan(target_url)
```

**Pre-discover URLs before crawling:**
**Pre-discover pages before crawling:**

```python
discovery = client.discover_urls("https://example.com")
if discovery.total > 0:
result = client.scan_crawl("https://example.com", urls=discovery.urls)
# Keep within your plan's pages per crawl.
result = client.scan_crawl("https://example.com", urls=discovery.urls[:25])
```

---
Expand All @@ -388,7 +431,7 @@ uv run pytest -m live
```

`VULNRADAR_API_BASE` points them at another server and `VULNRADAR_TEST_URL` changes the scan
target. Until the rebuild is finished they are expected to fail.
target.

---

Expand Down
2 changes: 2 additions & 0 deletions tests/fake.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def __init__(self) -> None:
super().__init__()
self.sent: list[PreparedRequest] = []
self.proxies_used: list[dict[str, str]] = []
self.timeouts_used: list[float] = []
self._outcomes: list[Response | Exception] = []

def reply(
Expand Down Expand Up @@ -50,6 +51,7 @@ def send(
) -> Response:
self.sent.append(request)
self.proxies_used.append(dict(proxies or {}))
self.timeouts_used.append(timeout)
assert self._outcomes, f"no reply queued for {request.method} {request.url}"
outcome = self._outcomes.pop(0) if len(self._outcomes) > 1 else self._outcomes[0]
if isinstance(outcome, Exception):
Expand Down
Loading