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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ dates on PyPI (UTC).
`ReportFormat`.
- `client.me()` returns the `Account` behind the key, and
`metadata.plan_limits()` the published plan limits.
- Bulk and signed-in scans (`scans.bulk()`, `scans.authenticated()`), AI review
(`scans.verify()`, `verify_batch()`, `history.summary()`), subdomain search
(`discovery.subdomains()`, `subdomain_progress()`), `reputation()`,
`demo_scan()` and `verify_webhook()`.
- `incomplete` holds `authenticated-session` when a login was lost.
- `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`.
Expand Down Expand Up @@ -67,6 +72,7 @@ dates on PyPI (UTC).
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.
- `discover_urls()` adds `https://` to an address without a scheme.
- A web page in reply raises `UnexpectedResponseError`, not
`AuthenticationError`.
- A reply without the fields a result needs raises `UnexpectedResponseError`
Expand Down
62 changes: 62 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,68 @@ for url in discovery.urls:

---

## More Scanning

```python
# Queue many addresses. Wait for each with client.scans.wait(entry["scanId"]).
queued = client.scans.bulk(["https://example.com", "https://example.org"])
for entry in queued["results"]:
print(entry["url"], entry.get("scanId") or entry.get("error"))

# Scan while signed in. This returns when the scan is done.
result = client.scans.authenticated(
"https://example.com/account",
{"method": "header", "headerName": "Authorization", "headerValue": "Bearer ..."},
)
print(result.summary.total, result.incomplete)

found = client.discovery.subdomains("example.com")["subdomains"]
names = [entry["subdomain"] for entry in found]
verdict = client.reputation("example.com")
demo = client.demo_scan("example.com") # a few per day per network address
```

The login is sent to the server as you give it: `form` with `username` and `password`
(your domain must be verified; `loginUrl` and the field names are optional), `header`
with `headerValue`, or `cookie` with `cookies` as a list of `name` and `value`. If the
session was lost, `result.incomplete` includes `authenticated-session`.

`bulk()`, `subdomains()` and `reputation()` return the server's reply as a dictionary.
A reputation that is not `known` does not mean a host is safe. Servers before 4.0 do not
say in a signed-in or demo scan's reply when some checks failed to run.

With the server's AI turned on, you can review findings and summarise a scan:

```python
reviewed = client.scans.verify(123)
text = client.history.summary(123)
```

A reviewed finding has `raw["aiVerdict"]`. If none got a verdict, the call raises
`UnexpectedResponseError` instead of returning findings that look approved.

---

## Webhooks

Check each delivery against your webhook's secret, using the raw request body:

```python
from vulnradar import verify_webhook


def handle(body: bytes, headers: dict[str, str]) -> int:
if not verify_webhook("your-webhook-secret", body, headers):
return 401
return 204
```

Servers from 4.0 also sign a timestamp. If yours does, pass `require_timestamp=True`, so
an old delivery cannot be sent to you again. Deliveries can be repeated, so make your
handler safe to run twice. Before 4.0, test deliveries are not signed.

---

## Scan History

GitHub repository scans are not part of this history.
Expand Down
274 changes: 274 additions & 0 deletions tests/test_extras.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
"""Bulk and signed-in scans, subdomains, reputation, AI review, the demo scan."""

from __future__ import annotations

from collections.abc import Callable
from typing import Any

import pytest
import requests

from tests import samples
from tests.conftest import BASE_URL
from tests.fake import FakeTransport
from vulnradar import (
AuthenticationError,
Finding,
InvalidURLError,
RequestTimeoutError,
Severity,
UnexpectedResponseError,
VulnRadar,
)

LOGIN = {"method": "form", "username": "demo", "password": "hunter2-secret"}


def sent(transport: FakeTransport) -> tuple[str, str]:
return str(transport.sent[-1].method), str(transport.sent[-1].url).removeprefix(BASE_URL)


def test_bulk_scans_are_queued(client: VulnRadar, transport: FakeTransport) -> None:
reply = {
"total": 1,
"queued": 1,
"failed": 0,
"skipped": 0,
"results": [{"url": "https://example.com/", "success": True, "scanId": 5}],
}
transport.reply(body=reply)

queued = client.scans.bulk([" example.com "], public=False, team_ids=[3])

assert queued == reply
assert sent(transport) == ("POST", "/scan/bulk")
assert transport.sent_json() == {
"urls": ["https://example.com"],
"isPublic": False,
"teamIds": [3],
}


@pytest.mark.parametrize("urls", [[], "https://example.com", ["a.com"] * 101])
def test_an_impossible_bulk_request_is_not_sent(
client: VulnRadar, transport: FakeTransport, urls: Any
) -> None:
with pytest.raises(ValueError, match="urls"):
client.scans.bulk(urls)
with pytest.raises(InvalidURLError):
client.scans.bulk(["not a url"])

assert transport.sent == []


def signed_in(status: str, **extra: Any) -> dict[str, Any]:
report = {"status": status, "method": "form"}
return samples.result(authReport=report, persisted=True, **extra)


def test_a_signed_in_scan_returns_its_result_at_once(
client: VulnRadar, transport: FakeTransport
) -> None:
transport.reply(body=signed_in("authenticated"))

result = client.scans.authenticated("https://example.com", LOGIN, scanners=["headers"])

assert sent(transport) == ("POST", "/scan/authenticated")
assert transport.sent_json() == {
"url": "https://example.com",
"auth": LOGIN,
"scanners": ["headers"],
}
assert result.incomplete == []
assert result.raw["authReport"]["status"] == "authenticated"
assert transport.timeouts_used == [330.0]


@pytest.mark.parametrize("status", ["lost", "failed"])
def test_a_scan_that_lost_its_session_is_incomplete(
client: VulnRadar, transport: FakeTransport, status: str
) -> None:
transport.reply(body=signed_in(status))

result = client.scans.authenticated("https://example.com", LOGIN)

assert result.incomplete == ["authenticated-session"]


def test_a_signed_in_scan_is_sent_once_and_keeps_the_password_to_itself(
client: VulnRadar, transport: FakeTransport
) -> None:
transport.fail(requests.exceptions.ReadTimeout())

with pytest.raises(RequestTimeoutError) as caught:
client.scans.authenticated("https://example.com", LOGIN)

assert len(transport.sent) == 1
assert "hunter2" not in f"{caught.value!r} {caught.value.body}"
assert caught.value.__context__ is None


@pytest.mark.parametrize("auth", [{}, {"method": "magic"}, None])
def test_a_login_without_a_known_method_is_not_sent(
client: VulnRadar, transport: FakeTransport, auth: Any
) -> None:
with pytest.raises(ValueError, match="method"):
client.scans.authenticated("https://example.com", auth)

assert transport.sent == []


def test_findings_can_be_reviewed_by_scan(client: VulnRadar, transport: FakeTransport) -> None:
transport.reply(body={"success": True, "findings": [samples.finding(aiVerdict="confirmed")]})

findings = client.scans.verify(4711)

assert sent(transport) == ("POST", "/scan/verify")
assert transport.sent_json() == {"scanHistoryId": 4711}
assert findings[0].raw["aiVerdict"] == "confirmed"


def test_findings_can_be_reviewed_on_their_own(client: VulnRadar, transport: FakeTransport) -> None:
finding = Finding.from_dict(samples.finding())
transport.reply(body={"findings": [samples.finding("low", aiVerdict="possible_fp")]})

reviewed = client.scans.verify_batch("https://example.com", [finding])

assert transport.sent_json() == {"url": "https://example.com", "findings": [finding.raw]}
assert reviewed[0].severity is Severity.LOW


@pytest.mark.parametrize("count", [0, 51])
def test_a_review_of_none_or_too_many_findings_is_not_sent(
client: VulnRadar, transport: FakeTransport, count: int
) -> None:
findings = [Finding.from_dict(samples.finding())] * count

with pytest.raises(ValueError, match="findings"):
client.scans.verify_batch("https://example.com", findings)

assert transport.sent == []


@pytest.mark.parametrize(("regenerate", "query"), [(False, ""), (True, "?regenerate=true")])
def test_a_scan_can_be_summarised(
client: VulnRadar, transport: FakeTransport, regenerate: bool, query: str
) -> None:
transport.reply(body={"success": True, "summary": "Two problems."})

assert client.history.summary(4711, regenerate=regenerate) == "Two problems."
assert sent(transport) == ("POST", f"/history/4711/summary{query}")


def test_subdomains_and_their_progress(client: VulnRadar, transport: FakeTransport) -> None:
found = {"domain": "example.com", "subdomains": [], "total": 0}
transport.reply(body=found)
transport.reply(body={"stage": "done", "stageIndex": 4, "stagesTotal": 4})

assert (
client.discovery.subdomains("https://example.com", force_refresh=True, request_id="job-1")
== found
)
assert transport.sent_json(0) == {
"url": "https://example.com",
"forceRefresh": True,
"requestId": "job-1",
}
assert client.discovery.subdomain_progress("job-1")["stage"] == "done"
assert sent(transport) == ("GET", "/scan/discover/progress/job-1")


@pytest.mark.parametrize(
("url", "query"),
[
(None, "?host=example.com"),
("https://example.com/a", "?host=example.com&url=https%3A%2F%2Fexample.com%2Fa"),
],
)
def test_reputation(
client: VulnRadar, transport: FakeTransport, url: str | None, query: str
) -> None:
transport.reply(body={"known": False, "host": "example.com"})

assert client.reputation("example.com", url=url)["known"] is False
assert sent(transport) == ("GET", f"/scan/reputation{query}")


def test_the_demo_scan(client: VulnRadar, transport: FakeTransport) -> None:
transport.reply(body=samples.result() | {"remaining": 4, "limit": 5})

result = client.demo_scan("example.com")

assert sent(transport) == ("POST", "/demo-scan")
assert (result.summary.high, result.raw["remaining"]) == (1, 4)


CALLS: dict[str, Callable[[VulnRadar], object]] = {
"bulk": lambda sdk: sdk.scans.bulk(["example.com"]),
"authenticated": lambda sdk: sdk.scans.authenticated("example.com", LOGIN),
"verify": lambda sdk: sdk.scans.verify(1),
"verify batch": lambda sdk: sdk.scans.verify_batch(
"example.com", [Finding.from_dict(samples.finding())]
),
"summary": lambda sdk: sdk.history.summary(1),
"subdomains": lambda sdk: sdk.discovery.subdomains("https://example.com"),
"progress": lambda sdk: sdk.discovery.subdomain_progress("a"),
"reputation": lambda sdk: sdk.reputation("example.com"),
"demo": lambda sdk: sdk.demo_scan("example.com"),
}


@pytest.mark.parametrize("call", CALLS.values(), ids=CALLS.keys())
def test_an_empty_reply_is_never_a_result(
client: VulnRadar, transport: FakeTransport, call: Callable[[VulnRadar], object]
) -> None:
transport.reply(body={})

with pytest.raises(UnexpectedResponseError):
call(client)


@pytest.mark.parametrize(
"call",
[
lambda sdk: sdk.scans.authenticated("example.com", LOGIN),
lambda sdk: sdk.discovery.subdomains("example.com"),
lambda sdk: sdk.discover_urls("example.com"),
lambda sdk: sdk.demo_scan("example.com"),
],
)
def test_a_scheme_is_added_where_the_server_needs_one(
client: VulnRadar, transport: FakeTransport, call: Callable[[VulnRadar], object]
) -> None:
transport.reply(401, {"error": "stop here"})

with pytest.raises(AuthenticationError):
call(client)

assert transport.sent_json()["url"] == "https://example.com"


def test_a_progress_id_cannot_change_the_address(
client: VulnRadar, transport: FakeTransport
) -> None:
with pytest.raises(ValueError, match="request id"):
client.discovery.subdomain_progress("../keys")

assert transport.sent == []


@pytest.mark.parametrize("call", ["verify", "verify batch"])
@pytest.mark.parametrize("extra", [{}, {"ai": {"configured": False, "verdicts": 0}}])
def test_a_review_that_never_ran_is_not_a_pass(
client: VulnRadar, transport: FakeTransport, call: str, extra: dict[str, object]
) -> None:
transport.reply(body={"success": True, "findings": [samples.finding()], **extra})

with pytest.raises(UnexpectedResponseError, match="no AI verdicts"):
CALLS[call](client)


def test_a_scan_with_nothing_to_review(client: VulnRadar, transport: FakeTransport) -> None:
transport.reply(body={"success": True, "findings": []})

assert client.scans.verify(4711) == []
Loading