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
27 changes: 25 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ dates on PyPI (UTC).
- 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.
- History can be searched, paged and iterated, and scans changed, deleted all at
once or downloaded as reports: `history.iterate()`, `update()`,
`delete_all()` and `report()`, with `ScanSettings`, `Report` and
`ReportFormat`.
- `client.me()` returns the `Account` behind the key, and
`metadata.plan_limits()` the published plan limits.
- `NoResultError` for a stored scan that is still running or failed, raised by
`history.get()` and `history.report()`. A `Report` says what the scan did not
check in `incomplete`.

### Changed

Expand All @@ -41,6 +50,18 @@ dates on PyPI (UTC).
`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.
- `history.list()` takes keyword arguments and returns `total`, `matched`,
`limit`, `offset` and `truncated` beside the scans.
- `HistoryScan.id` is the text id, `duration` is `duration_ms`, `tags` are
names, `scanned_at` may be `None`, and `summary` and `findings_count` are
`None` without a result. `notes` is gone: the list does not send it.
- `history.get()` returns a `CrawlResult` for a crawl.
- `FindingTypesResult` has `categories` instead of `version`, and
`FindingType` has `description`, cannot be changed and compares all its fields.
- `VersionInfo.latest` and `engine` may be `None`, `status` is `unknown` when
missing, and it also has `release_url`, `api` and `raw`.
- `HistoryList` and `FindingTypesResult` have no default values, and a delete
reply must say `true` or `false`.
- 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.
Expand All @@ -62,7 +83,6 @@ 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 history entry has none is timezone-aware (UTC).
- The README now says that no published release works with the current API.

### Removed
Expand All @@ -79,7 +99,10 @@ 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`.
- `history.get()` sets `scan_history_id`, and a cut-short crawl read from
history is marked incomplete.
- `history.list()` reads the server's replies, and finding types are no longer
equal just because one field matches.

### Security

Expand Down
94 changes: 76 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ 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 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.
> The code on `main` calls the v3 API, and this page describes it. It has not been
> released yet.

---

Expand Down Expand Up @@ -127,8 +125,9 @@ if result.incomplete:
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.
out. Servers before 4.0 report failed checks for single scans only, not for the pages of a
crawl. Findings your account marked as false positives are included, with
`finding.suppressed` set.

Scanner names are checked before anything is sent, because some servers accept a misspelt
one and then check nothing. The other options are `capture_screenshot`, `port_scan` (needs
Expand Down Expand Up @@ -220,34 +219,93 @@ for url in discovery.urls:

## Scan History

### List Recent Scans
GitHub repository scans are not part of this history.

### List scans

```python
history = client.history.list()
page = client.history.list(limit=20, query="example.com")

print(f"{page.matched} scans match")
for scan in page.scans:
if scan.summary is None:
print(scan.id, scan.url, scan.status)
else:
print(scan.id, scan.url, f"{scan.summary.total} findings")
```

`summary` and `findings_count` are `None` for a scan that is still running or failed, so it
never looks like a scan without findings. A finished scan can still be partial: the list
does not say so on servers before 4.0, so check `incomplete` on `history.get()` before
calling a scan clean. Servers before 4.0 also keep each page of a crawl as its own scan
without that information, so a page that could not be fetched reads as clean.

`iterate()` goes through every page for you; each page uses one request of your key's
quota. A scan that finishes while you iterate can be missed.

for scan in history.scans:
```python
for scan in client.history.iterate(tag="nginx"):
print(scan.id, scan.url, scan.scanned_at)
print(f" Findings: {scan.findings_count}")
```

### Get a Specific Scan
### Read one scan

```python
result = client.history.get(123)
result = client.history.get(123) # the numeric or the text id

print(result.url)
for finding in result.findings:
print(finding.title, finding.severity)
```

### Delete a Scan
A crawl comes back as a `CrawlResult`. A scan that is still running or failed raises
`NoResultError`.

### Download a report

```python
deleted = client.history.delete(123)
print(deleted.success)
print(deleted.message)
from pathlib import Path

from vulnradar import ReportFormat

report = client.history.report(123, ReportFormat.PDF)

Path("report.pdf").write_bytes(report.content)
if report.incomplete:
print("Not everything was checked:", report.incomplete)
```

A report takes two requests: the scan is read first, and one that is still running or
failed raises `NoResultError`, because the server's report of it would list no findings.

The formats are `JSON`, `SARIF`, `PDF`, `MARKDOWN`, `COMPLIANCE` and `CSV`.
`include_suppressed` keeps findings marked as false positives, and `apply_triage` applies
your triage.

### Change or delete

```python
client.history.update(123, notes="Checked", public=False)

client.history.delete(123)
client.history.delete_all(confirm=True) # every scan, and it cannot be undone
```

Deleting needs a key with the `scan:delete` permission, which new keys do not have.

---

## Account

```python
account = client.me()

print(account.plan, account.scopes, account.quota)
```

`scopes` and `quota` are `None` on servers before 4.0. This is a cheap way to test a key.
`client.metadata.plan_limits()` returns every plan's limits as the server publishes them.

---

## Finding Types
Expand All @@ -257,7 +315,6 @@ Retrieve the full catalog of supported finding types:
```python
catalog = client.metadata.finding_types()

print(f"Version: {catalog.version}")
print(f"Total types: {catalog.count}")

for ft in catalog.types:
Expand All @@ -272,7 +329,7 @@ for ft in catalog.types:
info = client.version()

print(info.current)
print(info.latest)
print(info.latest) # None if the server could not find out
print(info.engine)
print(info.status)
```
Expand Down Expand Up @@ -327,6 +384,7 @@ 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 |
| `NoResultError` | none | An `UnexpectedResponseError`: a stored scan has no result |
| `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 |
Expand Down
25 changes: 25 additions & 0 deletions tests/live/test_live.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from vulnradar import (
CrawlResult,
NotFoundError,
ReportFormat,
ScanFailedError,
Scanner,
ScanResult,
Expand Down Expand Up @@ -44,6 +45,14 @@ def test_version(client: VulnRadar) -> None:
assert result.engine


def test_the_key_has_an_account(client: VulnRadar) -> None:
assert client.me().user_id > 0


def test_plan_limits(client: VulnRadar) -> None:
assert client.metadata.plan_limits()


def test_finding_types(client: VulnRadar) -> None:
catalog = client.metadata.finding_types()

Expand All @@ -65,6 +74,22 @@ def test_a_finished_scan_is_in_the_history(client: VulnRadar, finished_scan: Sca
assert stored.summary.total == finished_scan.summary.total


def test_a_finished_scan_is_listed(client: VulnRadar, finished_scan: ScanResult) -> None:
page = client.history.list(limit=20)

listed = {scan.id: scan for scan in page.scans}
assert finished_scan.public_id in listed
assert listed[finished_scan.public_id].summary is not None


def test_a_report_can_be_downloaded(client: VulnRadar, finished_scan: ScanResult) -> None:
assert finished_scan.scan_history_id is not None

report = client.history.report(finished_scan.scan_history_id, ReportFormat.JSON)

assert report.content.startswith(b"{")


def test_discover_urls(client: VulnRadar, target_url: str) -> None:
result = client.discover_urls(target_url)

Expand Down
73 changes: 73 additions & 0 deletions tests/samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,76 @@ def crawl(version: str = "3.9.2") -> dict[str, Any]:
return completed(
version, crawl=details, findings=[finding("medium")], summary=summary(medium=1)
)


def history_row(scan_id: str = "a" * 32, status: str = "completed", **extra: Any) -> dict[str, Any]:
"""A row of the history list. Rows use snake_case, unlike the rest of the API."""
done = status == "completed"
return {
"id": scan_id,
"url": "https://example.com",
"summary": summary(high=1) if done else {},
"findings_count": 1 if done else 0,
"duration": 8450 if done else 0,
"scanned_at": "2026-11-28T12:00:00.000Z",
"source": "api",
"status": status,
"tags": [{"tag": "nginx", "source": "auto"}],
**extra,
}


def history_page(
*rows: dict[str, Any], offset: int = 0, matched: int | None = None
) -> dict[str, Any]:
matched = offset + len(rows) if matched is None else matched
return {
"scans": list(rows),
"total": matched,
"matched": matched,
"q": None,
"tag": None,
"limit": 100,
"offset": offset,
"maxLimit": 100,
"truncated": offset + len(rows) < matched,
}


def history_entry(**extra: Any) -> dict[str, Any]:
"""One scan read back from history. Its numeric id is called ``id``."""
body = result(**extra)
del body["scanHistoryId"], body["scanPublicId"]
return {"id": 4711, "notes": "", "userId": 7, "isPublic": False, "teamIds": [], **body}


def account(version: str = "3.9.2") -> dict[str, Any]:
body: dict[str, Any] = {
"userId": 7,
"email": "owner@example.com",
"name": "Sam",
"plan": "pro_supporter",
"role": "user",
"totpEnabled": True,
"twoFactorMethod": "app",
"avatarUrl": None,
"scansPrivateByDefault": True,
"bulkScanUrls": 25,
}
if version == "4.0.0":
body["key"] = {"id": 3, "name": "ci", "scopes": ["scan:read", "scan:write"]}
body["quota"] = {"scans": {"limit": 150, "used": 2}, "requests": None}
return body


def finding_types() -> dict[str, Any]:
row = {
"id": "hsts-missing",
"type": "header-missing",
"title": "Missing HSTS",
"category": "headers",
"severity": "high",
"description": "No Strict-Transport-Security header.",
}
other = row | {"id": "csp-missing", "title": "Missing CSP", "severity": "medium"}
return {"success": True, "count": 2, "categories": {"headers": 2}, "data": [row, other]}
Loading