diff --git a/CHANGELOG.md b/CHANGELOG.md index a439647..11a7b20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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. @@ -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 @@ -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 diff --git a/README.md b/README.md index bafe4d8..3dc5def 100644 --- a/README.md +++ b/README.md @@ -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. --- @@ -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 @@ -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 @@ -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: @@ -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) ``` @@ -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 | diff --git a/tests/live/test_live.py b/tests/live/test_live.py index d609e5b..e131043 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -7,6 +7,7 @@ from vulnradar import ( CrawlResult, NotFoundError, + ReportFormat, ScanFailedError, Scanner, ScanResult, @@ -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() @@ -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) diff --git a/tests/samples.py b/tests/samples.py index 3ae2f30..0670e69 100644 --- a/tests/samples.py +++ b/tests/samples.py @@ -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]} diff --git a/tests/test_account.py b/tests/test_account.py new file mode 100644 index 0000000..80f1f6b --- /dev/null +++ b/tests/test_account.py @@ -0,0 +1,113 @@ +"""The account, plan limits, finding types and version.""" + +from __future__ import annotations + +import pytest + +from tests import samples +from tests.conftest import BASE_URL +from tests.fake import FakeTransport +from vulnradar import Severity, VulnRadar + + +@pytest.mark.parametrize("version", ["3.9.2", "4.0.0"]) +def test_the_account_behind_the_key( + client: VulnRadar, transport: FakeTransport, version: str +) -> None: + transport.reply(body=samples.account(version)) + + account = client.me() + + assert transport.sent[0].url == f"{BASE_URL}/auth/me" + assert (account.user_id, account.email, account.plan) == ( + 7, + "owner@example.com", + "pro_supporter", + ) + assert (account.scans_private_by_default, account.bulk_scan_urls) == (True, 25) + expected = ["scan:read", "scan:write"] if version == "4.0.0" else None + assert account.scopes == expected + assert (account.quota is None) == (version == "3.9.2") + + +def test_printing_the_account_shows_no_email(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.account()) + + assert "owner@example.com" not in repr(client.me()) + + +def test_plan_limits_are_returned_as_sent(client: VulnRadar, transport: FakeTransport) -> None: + limits = {"free": {"dailyScans": 25}} + transport.reply(body=limits) + + assert client.metadata.plan_limits() == limits + assert transport.sent[0].url == f"{BASE_URL}/billing/plan-limits" + + +def test_finding_types(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.finding_types()) + + catalog = client.metadata.finding_types() + + assert (catalog.count, catalog.categories) == (2, {"headers": 2}) + first, second = catalog.types + assert (first.id, first.type, first.severity) == ( + "hsts-missing", + "header-missing", + Severity.HIGH, + ) + assert first.description == "No Strict-Transport-Security header." + assert first != second + assert len({first, second, first}) == 2 + + +def test_extra_fields_of_a_finding_type_are_kept( + client: VulnRadar, transport: FakeTransport +) -> None: + body = samples.finding_types() + body["data"][0] |= {"type": "async-probe", "idPrefix": "async-x", "severity": "new"} + transport.reply(body=body) + + kind = client.metadata.finding_types().types[0] + + assert (kind.raw["idPrefix"], kind.severity) == ("async-x", Severity.UNKNOWN) + + +def test_version_without_a_known_latest_release( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply( + body={ + "current": "3.9.2", + "engine": "3.3.2", + "latest": None, + "status": "unknown", + "release_url": "https://example.com/release", + } + ) + + info = client.version() + + assert (info.latest, info.status, info.api) == (None, "unknown", None) + assert info.release_url == "https://example.com/release" + + +def test_newer_servers_list_their_api_versions(client: VulnRadar, transport: FakeTransport) -> None: + api = {"current": "v3", "supported": ["v3"], "deprecated": {}} + transport.reply(body={"current": "4.0.0", "api": api}) + + assert client.version().api == api + + +def test_a_key_without_listed_scopes_is_not_shown_as_having_none( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body=samples.account("4.0.0") | {"key": {"id": 3, "scopes": None}}) + + assert client.me().scopes is None + + +def test_category_counts_are_numbers(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.finding_types() | {"categories": {"headers": 2, "dns": "many"}}) + + assert client.metadata.finding_types().categories == {"headers": 2} diff --git a/tests/test_history.py b/tests/test_history.py new file mode 100644 index 0000000..9420b33 --- /dev/null +++ b/tests/test_history.py @@ -0,0 +1,397 @@ +"""Listing, reading, changing, deleting and downloading past scans.""" + +from __future__ import annotations + +from datetime import UTC, datetime + +import pytest + +from tests import samples +from tests.conftest import BASE_URL +from tests.fake import FakeTransport +from vulnradar import ( + CrawlResult, + NoResultError, + ReportFormat, + ServerError, + UnexpectedResponseError, + VulnRadar, +) + + +def query(transport: FakeTransport, index: int = -1) -> str: + return str(transport.sent[index].url).partition("?")[2] + + +def test_a_page_of_history_is_parsed(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.history_page(samples.history_row(), matched=3)) + + page = client.history.list() + + assert transport.sent[0].url == f"{BASE_URL}/history" + assert (page.total, page.matched, page.offset, page.truncated) == (3, 3, 0, True) + scan = page.scans[0] + assert scan.id == "a" * 32 + assert scan.status == "completed" + assert scan.summary is not None + assert (scan.summary.high, scan.findings_count, scan.duration_ms) == (1, 1, 8450) + assert scan.scanned_at == datetime(2026, 11, 28, 12, tzinfo=UTC) + assert (scan.source, scan.tags) == ("api", ["nginx"]) + + +@pytest.mark.parametrize("status", ["pending", "running", "failed"]) +def test_an_unfinished_scan_has_no_counts( + client: VulnRadar, transport: FakeTransport, status: str +) -> None: + transport.reply(body=samples.history_page(samples.history_row(status=status))) + + scan = client.history.list().scans[0] + + assert (scan.status, scan.summary, scan.findings_count) == (status, None, None) + + +def test_a_finished_row_without_a_summary_has_no_counts( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body=samples.history_page(samples.history_row(summary={}))) + + scan = client.history.list().scans[0] + + assert (scan.summary, scan.findings_count) == (None, None) + + +def test_newer_rows_say_what_went_wrong(client: VulnRadar, transport: FakeTransport) -> None: + row = samples.history_row(status="failed", error_message="No answer.", incomplete=False) + transport.reply(body=samples.history_page(row)) + + scan = client.history.list().scans[0] + + assert (scan.error, scan.incomplete) == ("No answer.", False) + + +def test_older_rows_do_not_say_whether_they_are_complete( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body=samples.history_page(samples.history_row())) + + assert client.history.list().scans[0].incomplete is None + + +def test_the_list_can_be_searched_and_paged(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.history_page()) + + client.history.list(limit=10, offset=20, query="a&b=c", tag="nginx") + + assert query(transport) == "limit=10&offset=20&q=a%26b%3Dc&tag=nginx" + + +@pytest.mark.parametrize(("limit", "offset"), [(0, 0), (101, 0), (None, -1)]) +def test_impossible_paging_is_refused( + client: VulnRadar, transport: FakeTransport, limit: int | None, offset: int +) -> None: + with pytest.raises(ValueError, match=r"limit|offset"): + client.history.list(limit=limit, offset=offset) + + assert transport.sent == [] + + +def test_iterating_reads_every_page_once(client: VulnRadar, transport: FakeTransport) -> None: + first = [samples.history_row("1" * 32), samples.history_row("2" * 32)] + # A new scan arrived in between, so the second page repeats a row. + second = [samples.history_row("2" * 32), samples.history_row("3" * 32)] + transport.reply(body=samples.history_page(*first, matched=4)) + transport.reply(body=samples.history_page(*second, offset=2, matched=4)) + + ids = [scan.id[0] for scan in client.history.iterate(tag="nginx")] + + assert ids == ["1", "2", "3"] + assert [query(transport, index) for index in (0, 1)] == [ + "limit=100&tag=nginx", + "limit=100&offset=2&tag=nginx", + ] + + +def test_iterating_stops_if_the_server_sends_an_empty_page( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body=samples.history_page(matched=5)) + + assert list(client.history.iterate()) == [] + assert len(transport.sent) == 1 + + +def test_iterating_asks_only_as_far_as_it_is_read( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body=samples.history_page(samples.history_row(), matched=500)) + + next(iter(client.history.iterate())) + + assert len(transport.sent) == 1 + + +def test_a_scan_is_read_back_by_either_id(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.history_entry()) + + result = client.history.get("a" * 32) + + assert transport.sent[0].url == f"{BASE_URL}/history/{'a' * 32}" + assert (result.scan_history_id, result.summary.high, result.notes) == (4711, 1, "") + + +def test_a_stored_crawl_comes_back_with_its_pages( + client: VulnRadar, transport: FakeTransport +) -> None: + crawl = samples.crawl()["result"]["crawl"] + transport.reply(body=samples.history_entry(crawl=crawl)) + + result = client.history.get(4711) + + assert isinstance(result, CrawlResult) + assert result.incomplete == ["crawl-pages-not-scanned"] + + +@pytest.mark.parametrize("findings", [[], [samples.finding()]]) +def test_reading_a_scan_without_a_result_says_so( + client: VulnRadar, transport: FakeTransport, findings: list[object] +) -> None: + transport.reply(body=samples.history_entry(summary={}, findings=findings)) + + with pytest.raises(NoResultError) as caught: + client.history.get(4711) + + assert isinstance(caught.value, UnexpectedResponseError) + assert caught.value.scan_id == 4711 + assert "still running or it failed" in caught.value.message + + +def test_notes_visibility_and_teams_can_be_changed( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body={"notes": "seen", "isPublic": False, "teamId": 3, "teamIds": [3, 4]}) + + settings = client.history.update(4711, notes="seen", public=False, team_ids=[3, 4]) + + assert transport.sent[0].method == "PATCH" + assert transport.sent[0].url == f"{BASE_URL}/history/4711" + assert transport.sent_json() == {"notes": "seen", "isPublic": False, "teamIds": [3, 4]} + assert (settings.notes, settings.is_public, settings.team_ids) == ("seen", False, [3, 4]) + + +def test_a_change_can_empty_a_field(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body={"notes": "", "isPublic": True, "teamIds": []}) + + client.history.update(4711, notes="", team_ids=[]) + + assert transport.sent_json() == {"notes": "", "teamIds": []} + + +@pytest.mark.parametrize("changes", [{}, {"notes": "x" * 2001}]) +def test_a_change_the_server_would_refuse_or_cut_is_not_sent( + client: VulnRadar, transport: FakeTransport, changes: dict[str, str] +) -> None: + with pytest.raises(ValueError, match=r"notes|change"): + client.history.update(4711, **changes) # type: ignore[arg-type] + + assert transport.sent == [] + + +def test_a_change_is_sent_once(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(502, {"error": "bad gateway"}) + + with pytest.raises(ServerError): + client.history.update(4711, public=True) + + assert len(transport.sent) == 1 + + +@pytest.mark.parametrize("confirm", [False, None, "yes", 1]) +def test_deleting_everything_has_to_be_confirmed( + client: VulnRadar, transport: FakeTransport, confirm: object +) -> None: + with pytest.raises(ValueError, match="confirm=True"): + client.history.delete_all(confirm=confirm) # type: ignore[arg-type] + + assert transport.sent == [] + + +def test_deleting_everything(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body={"message": "Resource deleted successfully"}) + + message = client.history.delete_all(confirm=True) + + assert (transport.sent[0].method, transport.sent[0].url) == ("DELETE", f"{BASE_URL}/history") + assert message == "Resource deleted successfully" + + +def test_a_report_is_returned_as_the_server_sent_it( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body=samples.history_entry()) + transport.reply( + raw=b"%PDF-1.7 \x00\xff", + content_type="application/pdf", + headers={"Content-Disposition": 'attachment; filename="vulnradar-example.com.pdf"'}, + ) + + report = client.history.report(4711, ReportFormat.PDF) + + assert transport.sent[1].url == f"{BASE_URL}/history/4711/report?format=pdf" + assert transport.sent[1].headers["Accept"] == "*/*" + assert report.content == b"%PDF-1.7 \x00\xff" + assert report.content_type == "application/pdf" + assert report.filename == "vulnradar-example.com.pdf" + + +def test_a_report_can_be_adjusted(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.history_entry()) + transport.reply(raw=b"{}", content_type="application/json") + + report = client.history.report(4711, "json", include_suppressed=True, apply_triage=True) + + assert query(transport) == "format=json&includeSuppressed=true&applyTriage=true" + assert (report.content, report.filename) == (b"{}", None) + + +@pytest.mark.parametrize("name", ["../../etc/passwd", "a\\b.pdf", "..", ""]) +def test_a_report_name_that_is_a_path_is_dropped( + client: VulnRadar, transport: FakeTransport, name: str +) -> None: + transport.reply(body=samples.history_entry()) + transport.reply( + raw=b"x", + content_type="text/csv", + headers={"Content-Disposition": f'attachment; filename="{name}"'}, + ) + + assert client.history.report(4711, ReportFormat.CSV).filename is None + + +def test_an_unknown_report_format_is_refused(client: VulnRadar, transport: FakeTransport) -> None: + with pytest.raises(ValueError, match="docx"): + client.history.report(4711, "docx") + + assert transport.sent == [] + + +@pytest.mark.parametrize( + ("raw", "content_type"), [(b"", "application/pdf"), (b"", "text/html")] +) +def test_an_empty_or_web_page_report_is_an_error( + client: VulnRadar, transport: FakeTransport, raw: bytes, content_type: str +) -> None: + transport.reply(body=samples.history_entry()) + transport.reply(raw=raw, content_type=content_type) + + with pytest.raises(UnexpectedResponseError): + client.history.report(4711) + + +def test_a_report_download_is_retried(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.history_entry()) + transport.reply(502, {"error": "bad gateway"}) + transport.reply(raw=b"{}", content_type="application/json") + + assert client.history.report(4711).content == b"{}" + assert len(transport.sent) == 3 + + +def test_report_headers_are_read_in_any_case(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(body=samples.history_entry()) + transport.reply( + raw=b"x", + content_type="text/csv", + headers={"content-disposition": 'attachment; filename="vulnradar-example.com.csv"'}, + ) + + report = client.history.report(4711, ReportFormat.CSV) + + assert (report.filename, report.content_type) == ("vulnradar-example.com.csv", "text/csv") + + +@pytest.mark.parametrize("report_format", list(ReportFormat)) +def test_there_is_no_report_of_a_scan_without_a_result( + client: VulnRadar, transport: FakeTransport, report_format: ReportFormat +) -> None: + # The server would answer with a report that lists no findings. + transport.reply(body=samples.history_entry(summary={}, findings=[])) + + with pytest.raises(NoResultError): + client.history.report(4711, report_format) + + assert [sent.url for sent in transport.sent] == [f"{BASE_URL}/history/4711"] + + +def test_a_report_says_what_the_scan_did_not_check( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body=samples.history_entry(incomplete=["dns"])) + transport.reply(raw=b"{}", content_type="application/json") + + assert client.history.report(4711).incomplete == ["dns"] + + +@pytest.mark.parametrize("echoed_offset", [0, None]) +def test_iterating_does_not_loop_on_a_server_without_paging( + client: VulnRadar, transport: FakeTransport, echoed_offset: int | None +) -> None: + rows = [samples.history_row("1" * 32), samples.history_row("2" * 32)] + first = samples.history_page(*rows, matched=500) + transport.reply(body=first) + again = samples.history_page(*rows, offset=2, matched=500) + if echoed_offset is not None: + again["offset"] = echoed_offset + transport.reply(body=again) + seen = [] + + with pytest.raises(UnexpectedResponseError, match="moving through"): + for scan in client.history.iterate(): + seen.append(scan.id[0]) + + assert seen == ["1", "2"] + assert len(transport.sent) == 2 + + +def test_iterating_goes_on_after_a_full_page_even_if_the_count_is_wrong( + client: VulnRadar, transport: FakeTransport +) -> None: + # A server that cannot count reports the page size as the total. + first = samples.history_page(samples.history_row("1" * 32)) | {"limit": 1} + second = samples.history_page(samples.history_row("2" * 32), offset=1) | {"limit": 1} + transport.reply(body=first) + transport.reply(body=second) + transport.reply(body=samples.history_page(offset=2) | {"limit": 1}) + + assert [scan.id[0] for scan in client.history.iterate()] == ["1", "2"] + assert len(transport.sent) == 3 + + +def test_notes_are_measured_the_way_the_server_cuts_them( + client: VulnRadar, transport: FakeTransport +) -> None: + transport.reply(body={"notes": "", "isPublic": True, "teamIds": []}) + + with pytest.raises(ValueError, match="notes"): + client.history.update(4711, notes="\U0001f512" * 1001) + client.history.update(4711, notes="\U0001f512" * 1000) + + assert len(transport.sent) == 1 + + +def test_deleting_everything_is_sent_once(client: VulnRadar, transport: FakeTransport) -> None: + transport.reply(502, {"error": "bad gateway"}) + + with pytest.raises(ServerError): + client.history.delete_all(confirm=True) + + assert len(transport.sent) == 1 + + +@pytest.mark.parametrize("success", ["false", 0, None]) +def test_a_delete_reply_must_say_yes_or_no( + client: VulnRadar, transport: FakeTransport, success: object +) -> None: + transport.reply(body={"success": success}) + + with pytest.raises(UnexpectedResponseError): + client.history.delete(4711) diff --git a/tests/test_replies.py b/tests/test_replies.py index 9d2ce2b..691caed 100644 --- a/tests/test_replies.py +++ b/tests/test_replies.py @@ -22,6 +22,9 @@ "history delete": lambda sdk: sdk.history.delete(1), "finding types": lambda sdk: sdk.metadata.finding_types(), "version": lambda sdk: sdk.version(), + "me": lambda sdk: sdk.me(), + "history update": lambda sdk: sdk.history.update(1, public=True), + "delete all": lambda sdk: sdk.history.delete_all(confirm=True), "start": lambda sdk: sdk.scans.start("https://example.com"), "status": lambda sdk: sdk.scans.status(1), "cancel": lambda sdk: sdk.scans.cancel(1), @@ -68,7 +71,8 @@ def test_a_finished_scan_without_findings_is_still_a_result( @pytest.mark.parametrize( "body", [ - {"scans": [{"id": "0123abcd", "summary": {}}]}, + {"scans": [{"summary": {}}]}, + {"scans": [{"id": None}]}, {"scans": "none"}, {"scans": [5]}, ], @@ -82,17 +86,10 @@ def test_a_reply_of_the_wrong_shape_raises_an_sdk_error( 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 + client: VulnRadar, transport: FakeTransport ) -> None: - transport.reply(raw=raw) + transport.reply(raw=b'{"scans": [{"id": 1e999, "summary": {}}]}') with pytest.raises(UnexpectedResponseError): client.history.list() diff --git a/vulnradar/__init__.py b/vulnradar/__init__.py index ec6d7a9..9bb06da 100644 --- a/vulnradar/__init__.py +++ b/vulnradar/__init__.py @@ -1,12 +1,13 @@ from ._version import __version__ as __version__ from .client import VulnRadar -from .enums import RateLimitKind, Scanner, ScanState, Severity +from .enums import RateLimitKind, ReportFormat, Scanner, ScanState, Severity from .exceptions import ( AuthenticationError, BadRequestError, ForbiddenError, InvalidURLError, NetworkError, + NoResultError, NotFoundError, RateLimitError, RateLimitInfo, @@ -19,6 +20,7 @@ VulnRadarError, ) from .models import ( + Account, CrawlPage, CrawlResult, DeleteScanResult, @@ -28,8 +30,10 @@ FindingTypesResult, HistoryList, HistoryScan, + Report, ScanJob, ScanResult, + ScanSettings, ScanStatus, Summary, VersionInfo, @@ -37,6 +41,7 @@ from .services.scan_service import ScanOptions __all__ = [ + "Account", "AuthenticationError", "BadRequestError", "CrawlPage", @@ -51,15 +56,19 @@ "HistoryScan", "InvalidURLError", "NetworkError", + "NoResultError", "NotFoundError", "RateLimitError", "RateLimitInfo", "RateLimitKind", + "Report", + "ReportFormat", "RequestTimeoutError", "ScanFailedError", "ScanJob", "ScanOptions", "ScanResult", + "ScanSettings", "ScanState", "ScanStatus", "ScanTimeoutError", diff --git a/vulnradar/client.py b/vulnradar/client.py index 35511f6..fe53369 100644 --- a/vulnradar/client.py +++ b/vulnradar/client.py @@ -15,6 +15,7 @@ ) from .exceptions import UnexpectedResponseError from .http import HTTPClient +from .models.account import Account from .models.crawl import CrawlResult, DiscoveryResult from .models.scan_result import ScanResult from .models.version import VersionInfo @@ -165,6 +166,10 @@ def discover_urls(self, url: str) -> DiscoveryResult: """ return self._discovery_service.discover_urls(url) + def me(self) -> Account: + """The account the API key belongs to. A good way to test a key.""" + return read_reply(Account.from_dict, self._http.get("/auth/me")) + def version(self) -> VersionInfo: """Retrieve the current API version and engine status. diff --git a/vulnradar/enums.py b/vulnradar/enums.py index f882b71..0b77722 100644 --- a/vulnradar/enums.py +++ b/vulnradar/enums.py @@ -61,3 +61,14 @@ class RateLimitKind(StrEnum): """Too many bulk requests.""" OTHER = "other" """A short-term limit, or one the server did not name.""" + + +class ReportFormat(StrEnum): + """What a scan report can be downloaded as.""" + + JSON = "json" + SARIF = "sarif" + PDF = "pdf" + MARKDOWN = "md" + COMPLIANCE = "compliance" + CSV = "csv" diff --git a/vulnradar/exceptions.py b/vulnradar/exceptions.py index a81624f..b70f49e 100644 --- a/vulnradar/exceptions.py +++ b/vulnradar/exceptions.py @@ -178,6 +178,18 @@ def __init__(self, scan_id: int | str, timeout: float) -> None: self.scan_id = scan_id +class NoResultError(UnexpectedResponseError): + """Raised for a stored scan that has no result: it is running, or it failed.""" + + def __init__(self, scan_id: int | str, *, body: Mapping[str, Any] | None = None) -> None: + super().__init__( + f"Scan {scan_id} has no result: it is still running or it failed. " + "client.scans.status() says which; servers before 4.0 need the numeric id.", + body=body, + ) + self.scan_id = scan_id + + class InvalidURLError(VulnRadarError): """Raised when a provided URL fails validation.""" diff --git a/vulnradar/http.py b/vulnradar/http.py index 1b7f2dd..81c3d7e 100644 --- a/vulnradar/http.py +++ b/vulnradar/http.py @@ -3,6 +3,7 @@ import platform import re import time +from collections.abc import Mapping from typing import Any from urllib.parse import urlsplit @@ -84,14 +85,33 @@ def timeout(self) -> float: return self._config.timeout def get( - self, path: str, *, retries: int | None = None, timeout: float | None = None + self, + path: str, + *, + params: dict[str, str] | None = None, + retries: int | None = None, + timeout: float | None = None, ) -> dict[str, Any]: """Read from an API path such as '/history'. ``retries`` and ``timeout`` replace the client's own for this request. """ url = self._config.base_url + path - return self._request("GET", url, retries=retries, timeout=timeout) + reply = self._request("GET", url, params=params, retries=retries, timeout=timeout) + return _json(reply) + + def get_file( + self, path: str, *, params: dict[str, str] | None = None + ) -> tuple[bytes, Mapping[str, str]]: + """Download what an API path names, with the reply's headers. + + The headers can be looked up in any case. + """ + url = self._config.base_url + path + reply = self._request("GET", url, params=params, headers={"Accept": "*/*"}) + if not reply.content: + raise _unreadable(reply, "The server sent an empty file.") + return reply.content, reply.headers def get_version(self) -> dict[str, Any]: """Read the version endpoint, which sits beside the versioned API. @@ -99,24 +119,30 @@ def get_version(self) -> dict[str, Any]: For a base address ending in '/api/v3' this is '/api/version'. """ parent = self._config.base_url.rsplit("/", 1)[0] - return self._request("GET", parent + "/version") + return _json(self._request("GET", parent + "/version")) def post(self, path: str, json: dict[str, Any]) -> dict[str, Any]: """Send a JSON body to an API path. Never retried.""" - return self._request("POST", self._config.base_url + path, json=json) + return _json(self._request("POST", self._config.base_url + path, json=json)) + + def patch(self, path: str, json: dict[str, Any]) -> dict[str, Any]: + """Change what an API path names. Never retried.""" + return _json(self._request("PATCH", self._config.base_url + path, json=json)) def delete(self, path: str) -> dict[str, Any]: """Delete what an API path names. Never retried.""" - return self._request("DELETE", self._config.base_url + path) + return _json(self._request("DELETE", self._config.base_url + path)) def _request( self, method: str, url: str, json: dict[str, Any] | None = None, + params: dict[str, str] | None = None, + headers: dict[str, str] | None = None, retries: int | None = None, timeout: float | None = None, - ) -> dict[str, Any]: + ) -> Response: if retries is None: retries = self._config.retries if timeout is None: @@ -126,7 +152,9 @@ def _request( attempt = 1 while True: try: - return self._send(method, url, json, timeout) + return self._send( + method, url, json=json, params=params, headers=headers, timeout=timeout + ) except (NetworkError, ServerError) as error: wait = error.retry_after if wait is None: @@ -137,13 +165,22 @@ def _request( attempt += 1 def _send( - self, method: str, url: str, json: dict[str, Any] | None, timeout: float - ) -> dict[str, Any]: + self, + method: str, + url: str, + *, + json: dict[str, Any] | None, + params: dict[str, str] | None, + headers: dict[str, str] | None, + timeout: float, + ) -> Response: try: response = self._session.request( method, url, json=json, + params=params, + headers=headers, timeout=timeout, # A redirect could carry the key somewhere it was never meant to go. allow_redirects=False, @@ -151,7 +188,7 @@ def _send( except requests.exceptions.RequestException as error: failure = _network_failure(method, error, timeout) else: - return _read(response) + return _checked(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 @@ -169,34 +206,42 @@ def _network_failure( return RequestTimeoutError(message) -def _read(response: Response) -> dict[str, Any]: - """Return the JSON object of a successful reply, or raise.""" +def _checked(response: Response) -> Response: + """Return a successful reply that carries data, 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( + raise _unreadable( + response, f"The server redirected the request to '{location}'. Redirects are not " - "followed, so that the key stays where it was sent. Check base_url." + "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.") + raise _unreadable( + response, "The server answered with a web page instead of data. Check base_url." + ) + return response + + +def _json(response: Response) -> dict[str, Any]: + """Return the JSON object a reply holds, or raise.""" try: data = response.json() except _BAD_JSON: - raise unreadable("The server's reply was empty or was not JSON.") from None + raise _unreadable(response, "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.") + raise _unreadable(response, "The server's reply was not a JSON object.") return data +def _unreadable(response: Response, message: str) -> UnexpectedResponseError: + return UnexpectedResponseError( + message, response.status_code, request_id=response.headers.get("x-request-id") + ) + + def _error(response: Response) -> VulnRadarError: """Build the exception for a reply with an error status.""" status = response.status_code diff --git a/vulnradar/models/__init__.py b/vulnradar/models/__init__.py index c1e5b31..900fc1d 100644 --- a/vulnradar/models/__init__.py +++ b/vulnradar/models/__init__.py @@ -1,13 +1,15 @@ +from .account import Account from .crawl import CrawlPage, CrawlResult, DiscoveryResult from .finding_types import FindingType, FindingTypesResult from .findings import Finding -from .history import DeleteScanResult, HistoryList, HistoryScan +from .history import DeleteScanResult, HistoryList, HistoryScan, Report, ScanSettings from .scan_result import ScanResult from .scan_status import ScanJob, ScanStatus from .summary import Summary from .version import VersionInfo __all__ = [ + "Account", "CrawlPage", "CrawlResult", "DeleteScanResult", @@ -17,8 +19,10 @@ "FindingTypesResult", "HistoryList", "HistoryScan", + "Report", "ScanJob", "ScanResult", + "ScanSettings", "ScanStatus", "Summary", "VersionInfo", diff --git a/vulnradar/models/account.py b/vulnradar/models/account.py new file mode 100644 index 0000000..85dee52 --- /dev/null +++ b/vulnradar/models/account.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from .fields import integer, mapping, strings, text + + +@dataclass +class Account: + """The account the API key belongs to.""" + + user_id: int + email: str | None = field(repr=False) + name: str | None + plan: str | None + role: str | None + scans_private_by_default: bool + bulk_scan_urls: int | None + """Addresses allowed in one bulk request, or -1 for no limit.""" + scopes: list[str] | None + """What the key may do. None from servers before 4.0.""" + quota: dict[str, Any] | None + """Scans and requests used and left. None from servers before 4.0.""" + raw: dict[str, Any] = field(repr=False) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> Account: + user_id = data["userId"] + if type(user_id) is not int: + raise TypeError("userId") + scopes = mapping(data.get("key")).get("scopes") + quota = data.get("quota") + return cls( + user_id=user_id, + email=text(data.get("email")), + name=text(data.get("name")), + plan=text(data.get("plan")), + role=text(data.get("role")), + scans_private_by_default=data.get("scansPrivateByDefault") is True, + bulk_scan_urls=integer(data.get("bulkScanUrls")), + scopes=strings(scopes) if isinstance(scopes, list) else None, + quota=quota if isinstance(quota, dict) else None, + raw=data, + ) diff --git a/vulnradar/models/crawl.py b/vulnradar/models/crawl.py index 59eec21..4240d35 100644 --- a/vulnradar/models/crawl.py +++ b/vulnradar/models/crawl.py @@ -3,7 +3,7 @@ from dataclasses import dataclass, field from typing import Any -from .fields import integer, objects, required_list, text +from .fields import integer, mapping, objects, required_list, text from .findings import Finding from .scan_result import ScanResult from .summary import Summary @@ -70,6 +70,12 @@ def _fields(cls, data: dict[str, Any]) -> dict[str, Any]: } +def parse_result(data: dict[str, Any]) -> ScanResult: + """A CrawlResult if the finished scan was a crawl, otherwise a ScanResult.""" + crawled = bool(mapping(data.get("crawl"))) + return CrawlResult.from_dict(data) if crawled else ScanResult.from_dict(data) + + @dataclass class DiscoveryResult: """Result of URL discovery for a target domain.""" diff --git a/vulnradar/models/fields.py b/vulnradar/models/fields.py index dc43e5e..dbf3c1a 100644 --- a/vulnradar/models/fields.py +++ b/vulnradar/models/fields.py @@ -6,6 +6,8 @@ from datetime import datetime from typing import Any +from ..enums import Severity + def text(value: object) -> str | None: return value if isinstance(value, str) else None @@ -44,6 +46,28 @@ def timestamp(value: object) -> datetime | None: return None +def counts(value: object) -> dict[str, int]: + """Names with a whole number each; anything else is left out.""" + pairs = ((name, integer(number)) for name, number in mapping(value).items()) + return {name: number for name, number in pairs if number is not None} + + +def severity(value: object) -> Severity: + # An unfamiliar value must not be filed under a harmless level. + try: + return Severity(str(value).strip().lower()) + except ValueError: + return Severity.UNKNOWN + + +def tags(value: object) -> list[str]: + """Tag names, whether sent as text or as objects with a ``tag``.""" + if not isinstance(value, list): + return [] + names = (item.get("tag") if isinstance(item, dict) else item for item in value) + return [name for name in names if isinstance(name, str)] + + def required_list(data: dict[str, Any], key: str) -> list[Any]: """A list the model cannot do without, so that its absence never reads as empty.""" value = data[key] diff --git a/vulnradar/models/finding_types.py b/vulnradar/models/finding_types.py index 26df76d..2ade56c 100644 --- a/vulnradar/models/finding_types.py +++ b/vulnradar/models/finding_types.py @@ -4,58 +4,53 @@ from typing import Any from ..enums import Severity +from .fields import counts, integer, required_list, severity, text -@dataclass +@dataclass(frozen=True) class FindingType: - """A classification type for security findings.""" + """One check in the catalogue. + + ``type`` says how the check works and is shared by many checks; ``id`` + identifies this one. + """ id: str type: str title: str category: str severity: Severity - - @staticmethod - def _parse_severity(value: str | None) -> Severity: - raw = (value or "info").strip().lower() - try: - return Severity(raw) - except ValueError: - return Severity.INFO + description: str + raw: dict[str, Any] = field(repr=False, compare=False) @classmethod def from_dict(cls, data: dict[str, Any]) -> FindingType: return cls( - id=data.get("id", ""), - type=data.get("type", ""), - title=data.get("title", ""), - category=data.get("category", ""), - severity=cls._parse_severity(data.get("severity")), + id=text(data.get("id")) or "", + type=text(data.get("type")) or "", + title=text(data.get("title")) or "", + category=text(data.get("category")) or "", + severity=severity(data.get("severity")), + description=text(data.get("description")) or "", + raw=data, ) - def __eq__(self, other: object) -> bool: - if not isinstance(other, FindingType): - return NotImplemented - return self.id == other.id or self.type == other.type or self.title == other.title - @dataclass class FindingTypesResult: """The full catalog of supported finding types.""" - version: str count: int - types: list[FindingType] = field(default_factory=list) + categories: dict[str, int] + """Checks per category.""" + types: list[FindingType] @classmethod def from_dict(cls, data: dict[str, Any]) -> FindingTypesResult: - raw_types = data.get("types") - if not isinstance(raw_types, list): - raw_types = data["data"] - types = [FindingType.from_dict(t) for t in raw_types] + types = [FindingType.from_dict(item) for item in required_list(data, "data")] + count = integer(data.get("count")) return cls( - version=data.get("version", ""), - count=data.get("count", len(types)), + count=len(types) if count is None else count, + categories=counts(data.get("categories")), types=types, ) diff --git a/vulnradar/models/findings.py b/vulnradar/models/findings.py index c2d171f..574ecd2 100644 --- a/vulnradar/models/findings.py +++ b/vulnradar/models/findings.py @@ -4,7 +4,7 @@ from typing import Any from ..enums import Severity -from .fields import mapping, objects, strings, text +from .fields import mapping, objects, severity, strings, text @dataclass @@ -37,7 +37,7 @@ def from_dict(cls, data: dict[str, Any]) -> Finding: return cls( id=text(data.get("id")) or "", title=text(data.get("title")) or "", - severity=_severity(data.get("severity")), + severity=severity(data.get("severity")), description=text(data.get("description")) or "", category=text(data.get("category")), evidence=text(data.get("evidence")), @@ -50,11 +50,3 @@ def from_dict(cls, data: dict[str, Any]) -> Finding: remediation_status=text(mapping(data.get("remediation")).get("status")), raw=data, ) - - -def _severity(value: object) -> Severity: - # An unfamiliar value must not be filed under a harmless level. - try: - return Severity(str(value).strip().lower()) - except ValueError: - return Severity.UNKNOWN diff --git a/vulnradar/models/history.py b/vulnradar/models/history.py index d408ef9..d4bbb26 100644 --- a/vulnradar/models/history.py +++ b/vulnradar/models/history.py @@ -1,56 +1,93 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import dataclass, field -from datetime import UTC, datetime +from datetime import datetime +from email.message import Message from typing import Any +from .fields import integer, required_list, tags, text, timestamp from .summary import Summary @dataclass class HistoryScan: - """A scan entry from the scan history list.""" + """One scan in the history list. - id: int + ``summary`` and ``findings_count`` are None unless the scan has a result, so + that a pending or failed scan never reads as one without findings. + """ + + id: str + """The text id. history.get() takes it; scans.status() needs 4.0 or later.""" url: str - summary: Summary - findings_count: int - duration: float - scanned_at: datetime - source: str - notes: str | None + status: str + summary: Summary | None + findings_count: int | None + duration_ms: int | None + scanned_at: datetime | None + source: str | None tags: list[str] + incomplete: bool | None + """Whether part of the scan is missing. None if the server does not say.""" + error: str | None + """Why the scan failed, from servers that say.""" + raw: dict[str, Any] = field(repr=False) @classmethod def from_dict(cls, data: dict[str, Any]) -> HistoryScan: - raw_ts = data.get("scanned_at", "") - scanned_at = ( - datetime.fromisoformat(raw_ts.replace("Z", "+00:00")) if raw_ts else datetime.now(UTC) + scan_id = data["id"] + if type(scan_id) not in (str, int): + raise TypeError("id") + status = text(data.get("status")) or "" + summary = data.get("summary") + has_result = ( + status in ("", "completed") and isinstance(summary, dict) and "total" in summary ) - + incomplete = data.get("incomplete") return cls( - id=int(data.get("id", 0)), - url=data.get("url", ""), - summary=Summary.from_dict(data.get("summary", {})), - findings_count=int(data.get("findings_count", 0)), - duration=float(data.get("duration", 0.0)), - scanned_at=scanned_at, - source=data.get("source", ""), - notes=data.get("notes"), - tags=data.get("tags", []), + id=str(scan_id), + url=text(data.get("url")) or "", + status=status, + summary=Summary.from_dict(data["summary"]) if has_result else None, + findings_count=integer(data.get("findings_count")) if has_result else None, + duration_ms=integer(data.get("duration")), + scanned_at=timestamp(data.get("scanned_at")), + source=text(data.get("source")), + tags=tags(data.get("tags")), + incomplete=incomplete if isinstance(incomplete, bool) else None, + error=text(data.get("error_message")), + raw=data, ) @dataclass class HistoryList: - """Paginated list of scan history entries.""" + """One page of scan history, newest first.""" - scans: list[HistoryScan] = field(default_factory=list) + scans: list[HistoryScan] + total: int + """Scans in the account's history.""" + matched: int + """Scans that match the search.""" + limit: int + offset: int + truncated: bool + """True if there are more matching scans after this page.""" @classmethod def from_dict(cls, data: dict[str, Any]) -> HistoryList: + scans = [HistoryScan.from_dict(item) for item in required_list(data, "scans")] + total = integer(data.get("total")) + matched = integer(data.get("matched")) + limit = integer(data.get("limit")) return cls( - scans=[HistoryScan.from_dict(s) for s in data["scans"]], + scans=scans, + total=len(scans) if total is None else total, + matched=len(scans) if matched is None else matched, + limit=len(scans) if limit is None else limit, + offset=integer(data.get("offset")) or 0, + truncated=data.get("truncated") is True, ) @@ -63,7 +100,9 @@ class DeleteScanResult: @classmethod def from_dict(cls, data: dict[str, Any]) -> DeleteScanResult: - success = bool(data["success"]) + success = data["success"] + if not isinstance(success, bool): + raise TypeError("success") message = str(data.get("message", "")).strip() if success and not message: message = "Scan deleted successfully" @@ -71,3 +110,47 @@ def from_dict(cls, data: dict[str, Any]) -> DeleteScanResult: success=success, message=message, ) + + +@dataclass +class ScanSettings: + """What can be changed about a stored scan, as it now stands.""" + + notes: str | None + is_public: bool + team_ids: list[int] + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> ScanSettings: + is_public = data["isPublic"] + if not isinstance(is_public, bool): + raise TypeError("isPublic") + return cls( + notes=text(data.get("notes")), + is_public=is_public, + team_ids=required_list(data, "teamIds"), + ) + + +@dataclass +class Report: + """A downloaded report.""" + + content: bytes = field(repr=False) + content_type: str + filename: str | None + """The name the server suggests, if it is a plain file name.""" + incomplete: list[str] + """What the scan did not check. The report itself may not say.""" + + @classmethod + def from_headers( + cls, content: bytes, headers: Mapping[str, str], incomplete: list[str] + ) -> Report: + message = Message() + message["content-disposition"] = headers.get("Content-Disposition", "") + name = message.get_filename() + # Never hand back something that could write outside the chosen folder. + if name and (name in (".", "..") or not name.isprintable() or set(name) & set("/\\:")): + name = None + return cls(content, headers.get("Content-Type", ""), name or None, incomplete) diff --git a/vulnradar/models/scan_result.py b/vulnradar/models/scan_result.py index cae03ff..bae454a 100644 --- a/vulnradar/models/scan_result.py +++ b/vulnradar/models/scan_result.py @@ -4,7 +4,7 @@ from datetime import datetime from typing import Any, Self -from .fields import integer, mapping, required_list, text, timestamp +from .fields import integer, mapping, required_list, tags, text, timestamp from .findings import Finding from .summary import Summary @@ -49,7 +49,7 @@ def _fields(cls, data: dict[str, Any]) -> dict[str, Any]: "response_headers": mapping(data.get("responseHeaders")), "notes": text(data.get("notes")), "incomplete": _incomplete(data), - "tags": _tags(data.get("tags")), + "tags": tags(data.get("tags")), "raw": data, } @@ -63,10 +63,3 @@ def _incomplete(data: dict[str, Any]) -> list[str]: if (integer(data.get("checksErrored")) or 0) > 0 and "page-checks" not in areas: areas.append("page-checks") return areas - - -def _tags(value: object) -> list[str]: - if not isinstance(value, list): - return [] - names = (item.get("tag") if isinstance(item, dict) else item for item in value) - return [name for name in names if isinstance(name, str)] diff --git a/vulnradar/models/scan_status.py b/vulnradar/models/scan_status.py index 95db3b8..5c8c6fc 100644 --- a/vulnradar/models/scan_status.py +++ b/vulnradar/models/scan_status.py @@ -4,8 +4,8 @@ from typing import Any from ..enums import ScanState -from .crawl import CrawlResult -from .fields import integer, mapping, objects, text +from .crawl import parse_result +from .fields import integer, objects, text from .scan_result import ScanResult @@ -63,13 +63,8 @@ def from_dict(cls, data: dict[str, Any]) -> ScanStatus: categories_total=integer(data.get("categoriesTotal")) or 0, elapsed_ms=integer(data.get("elapsedMs")) or 0, partial_findings=objects(data.get("partialFindings")), - result=_result(data["result"]) if completed else None, + result=parse_result(data["result"]) if completed else None, error=text(data.get("errorMessage")) or text(data.get("error")), failure_kind=text(data.get("failureKind")), raw=data, ) - - -def _result(data: dict[str, Any]) -> ScanResult: - crawled = bool(mapping(data.get("crawl"))) - return CrawlResult.from_dict(data) if crawled else ScanResult.from_dict(data) diff --git a/vulnradar/models/version.py b/vulnradar/models/version.py index 4e94d2a..eec4562 100644 --- a/vulnradar/models/version.py +++ b/vulnradar/models/version.py @@ -1,25 +1,40 @@ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any +from .fields import text + @dataclass class VersionInfo: - """API version and engine metadata.""" + """The server's version.""" current: str - latest: str - engine: str + latest: str | None + """None when the server could not find out.""" + engine: str | None status: str + """``up-to-date``, ``behind``, ``ahead`` or ``unknown``.""" message: str | None + release_url: str | None + api: dict[str, Any] | None + """The API versions the server offers. None from servers before 4.0.""" + raw: dict[str, Any] = field(repr=False) @classmethod def from_dict(cls, data: dict[str, Any]) -> VersionInfo: + current = data["current"] + if not isinstance(current, str): + raise TypeError("current") + api = data.get("api") return cls( - current=data["current"], - latest=data.get("latest", ""), - engine=data.get("engine", ""), - status=data.get("status", ""), - message=data.get("message"), + current=current, + latest=text(data.get("latest")), + engine=text(data.get("engine")), + status=text(data.get("status")) or "unknown", + message=text(data.get("message")), + release_url=text(data.get("release_url")), + api=api if isinstance(api, dict) else None, + raw=data, ) diff --git a/vulnradar/services/history_service.py b/vulnradar/services/history_service.py index e02db80..0871a8a 100644 --- a/vulnradar/services/history_service.py +++ b/vulnradar/services/history_service.py @@ -1,56 +1,194 @@ from __future__ import annotations +from collections.abc import Iterator, Sequence +from typing import Any + +from ..enums import ReportFormat +from ..exceptions import NoResultError, UnexpectedResponseError from ..http import HTTPClient -from ..models.history import DeleteScanResult, HistoryList +from ..models.crawl import parse_result +from ..models.history import DeleteScanResult, HistoryList, HistoryScan, Report, ScanSettings from ..models.scan_result import ScanResult from ..replies import read_reply from ..utils.scan_id import scan_id_segment +_PAGE_SIZE = 100 # the most the server returns at once +_MAX_NOTES = 2000 + def _scan_path(scan_id: int | str) -> str: return f"/history/{scan_id_segment(scan_id)}" class HistoryService: - """Access and retrieve past scan history.""" + """Your past scans. GitHub repository scans are not included.""" def __init__(self, http: HTTPClient) -> None: self._http = http - def list(self) -> HistoryList: - """Retrieve the last 100 scans. + def list( + self, + *, + limit: int | None = None, + offset: int = 0, + query: str | None = None, + tag: str | None = None, + ) -> HistoryList: + """One page of history, newest first. - Returns: - A HistoryList containing scan summaries. + Args: + limit: Scans per page, 1 to 100. The server's default is 100. + offset: Scans to skip. + query: Only scans whose address contains this. + tag: Only scans with this tag. + """ + if limit is not None and not 1 <= limit <= _PAGE_SIZE: + raise ValueError(f"limit must be between 1 and {_PAGE_SIZE}.") + if offset < 0: + raise ValueError("offset cannot be negative.") + wanted = {"limit": limit, "offset": offset or None, "q": query, "tag": tag} + params = {name: str(value) for name, value in wanted.items() if value is not None} + return read_reply(HistoryList.from_dict, self._http.get("/history", params=params)) + + def iterate(self, *, query: str | None = None, tag: str | None = None) -> Iterator[HistoryScan]: + """Every matching scan, newest first, fetching pages as they are needed. + + Each page uses one request of the key's quota. The server orders scans by + when they finished, so one that finishes, or is deleted, while you iterate + can move to another page and be missed. + + Raises: + UnexpectedResponseError: If the server keeps sending the same page. """ - return read_reply(HistoryList.from_dict, self._http.get("/history")) + offset = 0 + seen: set[str] = set() + while True: + page = self.list(limit=_PAGE_SIZE, offset=offset, query=query, tag=tag) + if not page.scans: + return + # A scan made in the meantime pushes one onto the next page again. + new = [scan for scan in page.scans if scan.id not in seen] + if page.offset != offset or not new: + # Carrying on would spend the key's quota on one page for ever. + raise UnexpectedResponseError( + f"The server is not moving through the history (asked for scans from {offset})." + ) + for scan in new: + seen.add(scan.id) + yield scan + # A full page means there may be more, whatever the server's count says. + if not page.truncated and len(page.scans) < page.limit: + return + offset += len(page.scans) def get(self, scan_id: int | str) -> ScanResult: - """Retrieve the full details of a specific scan. + """The full result of a past scan. Args: - scan_id: The unique identifier of the scan in history. + scan_id: The numeric or the text id. Returns: - A ScanResult with complete findings and metadata. + A ScanResult, or a CrawlResult for a crawl. Raises: - NotFoundError: If no scan with the given ID exists. + NotFoundError: If no scan with the given id exists. + NoResultError: If the scan is still running or failed. + """ + data = self._http.get(_scan_path(scan_id)) + if data.get("summary") == {}: + raise NoResultError(scan_id, body=data) + return read_reply(parse_result, data) + + def update( + self, + scan_id: int | str, + *, + notes: str | None = None, + public: bool | None = None, + team_ids: Sequence[int] | None = None, + ) -> ScanSettings: + """Change a stored scan. Anything left as None stays as it is. + + Args: + scan_id: The numeric or the text id. + notes: Your notes, at most 2000 characters. An empty text clears them. + public: List the result publicly or not. False also ends its share link. + team_ids: The teams that can see it. An empty list removes them all. """ - return read_reply(ScanResult.from_dict, self._http.get(_scan_path(scan_id))) + changes: dict[str, Any] = {} + if notes is not None: + # The server cuts longer notes without saying so, counting as JavaScript does. + if len(notes.encode("utf-16-le", "surrogatepass")) // 2 > _MAX_NOTES: + raise ValueError(f"notes can be at most {_MAX_NOTES} characters.") + changes["notes"] = notes + if public is not None: + changes["isPublic"] = public + if team_ids is not None: + changes["teamIds"] = [*team_ids] + if not changes: + raise ValueError("Nothing to change: give notes, public or team_ids.") + reply = self._http.patch(_scan_path(scan_id), changes) + return read_reply(ScanSettings.from_dict, reply) def delete(self, scan_id: int | str) -> DeleteScanResult: - """Delete a scan from history. + """Delete one scan. The key needs the ``scan:delete`` permission. + + Raises: + NotFoundError: If no scan with the given id exists. + ForbiddenError: If the key may not delete it. + """ + return read_reply(DeleteScanResult.from_dict, self._http.delete(_scan_path(scan_id))) + + def delete_all(self, *, confirm: bool = False) -> str: + """Delete every scan in your history. It cannot be undone. Args: - scan_id: The identifier of the scan to delete. + confirm: Must be True, so this cannot happen by accident. Returns: - A DeleteScanResult confirming deletion. + The server's message. + """ + if confirm is not True: + raise ValueError( + "delete_all removes every scan in your history. Pass confirm=True to do it." + ) + return read_reply(_message, self._http.delete("/history")) + + def report( + self, + scan_id: int | str, + format: ReportFormat | str = ReportFormat.JSON, + *, + include_suppressed: bool = False, + apply_triage: bool = False, + ) -> Report: + """Download a report of a finished scan. + + The scan is read first, using a second request of the key's quota: the + server also makes reports of scans that are running or failed, and those + list no findings. + + Args: + scan_id: The numeric or the text id. + format: A ReportFormat. + include_suppressed: Keep findings marked as false positives. + apply_triage: Apply your triage of the findings. + + Returns: + The report. Check its ``incomplete`` before calling the scan clean. Raises: - AuthenticationError: If the API key is invalid. - NotFoundError: If no scan with the given ID exists. - VulnRadarError: If permission is denied or request fails. + NoResultError: If the scan is still running or failed. """ - return read_reply(DeleteScanResult.from_dict, self._http.delete(_scan_path(scan_id))) + params = {"format": ReportFormat(format).value} + if include_suppressed: + params["includeSuppressed"] = "true" + if apply_triage: + params["applyTriage"] = "true" + incomplete = self.get(scan_id).incomplete + content, headers = self._http.get_file(f"{_scan_path(scan_id)}/report", params=params) + return Report.from_headers(content, headers, incomplete) + + +def _message(data: dict[str, Any]) -> str: + return str(data["message"]) diff --git a/vulnradar/services/metadata_service.py b/vulnradar/services/metadata_service.py index 9d3fc2b..d5e5910 100644 --- a/vulnradar/services/metadata_service.py +++ b/vulnradar/services/metadata_service.py @@ -1,5 +1,7 @@ from __future__ import annotations +from typing import Any + from ..http import HTTPClient from ..models.finding_types import FindingTypesResult from ..replies import read_reply @@ -22,3 +24,7 @@ def finding_types(self) -> FindingTypesResult: """ data = self._http.get("/finding-types") return read_reply(FindingTypesResult.from_dict, data) + + def plan_limits(self) -> dict[str, Any]: + """Every plan's limits, as the server publishes them. No key is needed.""" + return self._http.get("/billing/plan-limits")