vpndetection-fastapi 2.1.29__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,13 @@
2
2
 
3
3
  What each release changed for you, newest first. Each line is a commit's summary, linked to its full description and diff. Releases before 2.0.5 are described by their release commits.
4
4
 
5
+ ## 2.2.0 - 2026-11-23
6
+
7
+ ### Features
8
+
9
+ - Require vpndetection 5.21.0: a user agent with a lookup, and allow_bots in the middleware core ([`a7e8d80`](https://github.com/vpndetection-io/sdk-python-fastapi/commit/a7e8d80b886c987c7358a028499ff2697fe8c58c))
10
+ - Let a verified crawler through with allow_bots ([`c7dd247`](https://github.com/vpndetection-io/sdk-python-fastapi/commit/c7dd247cb47bd55acd35cadca44b5d6e4c131265))
11
+
5
12
  ## 2.1.29 - 2026-11-22
6
13
 
7
14
  ### Features
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: vpndetection-fastapi
3
- Version: 2.1.29
3
+ Version: 2.2.0
4
4
  Summary: Official FastAPI and Starlette middleware for the VPNDetection API. Detect VPNs, proxies, Tor, hosting and CDN visitors on every request.
5
5
  Project-URL: Homepage, https://vpndetection.io
6
6
  Project-URL: Source, https://github.com/vpndetection-io/sdk-python-fastapi
@@ -20,7 +20,7 @@ Classifier: Topic :: Security
20
20
  Classifier: Typing :: Typed
21
21
  Requires-Python: >=3.11
22
22
  Requires-Dist: starlette>=0.37
23
- Requires-Dist: vpndetection<6,>=5.20.0
23
+ Requires-Dist: vpndetection<6,>=5.21.0
24
24
  Provides-Extra: dev
25
25
  Requires-Dist: fastapi>=0.115; extra == 'dev'
26
26
  Requires-Dist: mypy>=1.11; extra == 'dev'
@@ -93,6 +93,21 @@ Values are matched by equality, strings without regard to case. A list means any
93
93
 
94
94
  Replace the refusal with `on_blocked`.
95
95
 
96
+ ### Letting verified crawlers through
97
+
98
+ `allow_bots=True` sends each request's own `User-Agent` header with its lookup, and a request whose answer verifies that crawler, `lookup(request).result.user_agent.verdict == "verified"`, is never refused, by `block_condition` or by `block_if`; the answer is still attached. A request with no `User-Agent` sends none. It is off by default, which keeps one cached answer per address rather than one per agent.
99
+
100
+ ```python
101
+ app.add_middleware(
102
+ VPNDetectionMiddleware,
103
+ api_key=os.environ["VPNDETECTION_API_KEY"],
104
+ block_condition={"is_hosting": True},
105
+ allow_bots=True,
106
+ )
107
+ ```
108
+
109
+ With it on, a condition can name the verdict, refusing a forged crawler and a script: `{"user_agent": {"verdict": ["spoofed", "not_bot"]}}`. Only a paid plan's answer carries `user_agent`: a keyless client, or a free key past its trial, never gets a verdict and lets no crawler through, and the middleware warns once when that happens.
110
+
96
111
  ### Blocking one endpoint
97
112
 
98
113
  `block_condition` applies to every endpoint. In FastAPI, refuse a visitor on some endpoints only with the `block_if` dependency, on a path operation, a router or the app:
@@ -63,6 +63,21 @@ Values are matched by equality, strings without regard to case. A list means any
63
63
 
64
64
  Replace the refusal with `on_blocked`.
65
65
 
66
+ ### Letting verified crawlers through
67
+
68
+ `allow_bots=True` sends each request's own `User-Agent` header with its lookup, and a request whose answer verifies that crawler, `lookup(request).result.user_agent.verdict == "verified"`, is never refused, by `block_condition` or by `block_if`; the answer is still attached. A request with no `User-Agent` sends none. It is off by default, which keeps one cached answer per address rather than one per agent.
69
+
70
+ ```python
71
+ app.add_middleware(
72
+ VPNDetectionMiddleware,
73
+ api_key=os.environ["VPNDETECTION_API_KEY"],
74
+ block_condition={"is_hosting": True},
75
+ allow_bots=True,
76
+ )
77
+ ```
78
+
79
+ With it on, a condition can name the verdict, refusing a forged crawler and a script: `{"user_agent": {"verdict": ["spoofed", "not_bot"]}}`. Only a paid plan's answer carries `user_agent`: a keyless client, or a free key past its trial, never gets a verdict and lets no crawler through, and the middleware warns once when that happens.
80
+
66
81
  ### Blocking one endpoint
67
82
 
68
83
  `block_condition` applies to every endpoint. In FastAPI, refuse a visitor on some endpoints only with the `block_if` dependency, on a path operation, a router or the app:
@@ -24,7 +24,7 @@ classifiers = [
24
24
  "Topic :: Security",
25
25
  "Typing :: Typed",
26
26
  ]
27
- dependencies = ["vpndetection>=5.20.0,<6", "starlette>=0.37"]
27
+ dependencies = ["vpndetection>=5.21.0,<6", "starlette>=0.37"]
28
28
 
29
29
  [project.urls]
30
30
  Homepage = "https://vpndetection.io"
@@ -45,7 +45,7 @@ __all__ = [
45
45
  "xff_ip_selector",
46
46
  ]
47
47
 
48
- __version__ = "2.1.29"
48
+ __version__ = "2.2.0"
49
49
 
50
50
  # Set on a request ``skip`` claimed, so block_if can tell it from one the middleware
51
51
  # never saw.
@@ -147,6 +147,8 @@ class VPNDetectionMiddleware:
147
147
  """Classify the visitor, and optionally refuse the request.
148
148
 
149
149
  Takes everything :class:`vpndetection.middleware.Options` does, plus ``on_blocked``.
150
+ ``allow_bots=True`` sends the request's own ``User-Agent`` with its lookup and never
151
+ refuses a crawler the answer verifies, here or in :func:`block_if`.
150
152
 
151
153
  Written as raw ASGI rather than on ``BaseHTTPMiddleware``, which wraps the response
152
154
  in a streaming bridge that breaks background tasks and server-sent events - a cost
@@ -162,7 +164,9 @@ class VPNDetectionMiddleware:
162
164
  ) -> None:
163
165
  self.app = app
164
166
  self._on_blocked = on_blocked or _refuse
165
- self._core: AsyncCore[Request] = AsyncCore(Options(**options), default_ip_selector)
167
+ self._core: AsyncCore[Request] = AsyncCore(
168
+ Options(**options), default_ip_selector, _user_agent
169
+ )
166
170
 
167
171
  async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
168
172
  if scope["type"] != "http":
@@ -188,5 +192,9 @@ class VPNDetectionMiddleware:
188
192
  await self.app(scope, receive, send)
189
193
 
190
194
 
195
+ def _user_agent(request: Request) -> str | None:
196
+ return request.headers.get("User-Agent")
197
+
198
+
191
199
  def _refuse(_request: Request, _lookup: Lookup) -> Response:
192
200
  return JSONResponse({"error": "access denied"}, status_code=403)
@@ -419,3 +419,119 @@ def test_the_readme_middleware_sends_its_key_for_a_public_peer(
419
419
  assert body["error"] is None and body["is_vpn"] is True
420
420
  assert len(sent) == 1 and sent[0][0].endswith(PUBLIC_IP)
421
421
  assert sent[0][1] == "Bearer a-key"
422
+
423
+
424
+ GOOGLEBOT = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
425
+
426
+
427
+ def api_answering(
428
+ monkeypatch: pytest.MonkeyPatch, verdicts: dict[str, str] | None
429
+ ) -> list[str | None]:
430
+ """The API's host, answering every lookup as a match for ``{"is_hosting": True}`` and,
431
+ for a sent agent, with the verdict ``verdicts`` holds for it (None: no verdict, as
432
+ Unlimited answers). Returns the ``user_agent`` each lookup sent."""
433
+ sent: list[str | None] = []
434
+
435
+ async def handle(
436
+ _transport: httpx.AsyncHTTPTransport, request: httpx.Request
437
+ ) -> httpx.Response:
438
+ if request.url.host != "api.vpndetection.io":
439
+ raise httpx.ConnectError("only the API's host answers here", request=request)
440
+ agent = request.url.params.get("user_agent")
441
+ sent.append(agent)
442
+ body: dict[str, Any] = {
443
+ "ip": request.url.path.lstrip("/"),
444
+ "is_vpn": False,
445
+ "is_hosting": True,
446
+ }
447
+ if agent and verdicts is not None:
448
+ verdict = verdicts.get(agent, "not_bot")
449
+ body["user_agent"] = {"agent": "Googlebot", "kind": "bot", "verdict": verdict}
450
+ return httpx.Response(200, json=body)
451
+
452
+ monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", handle)
453
+ monkeypatch.setenv("VPNDETECTION_API_KEY", "a-key")
454
+ return sent
455
+
456
+
457
+ def visit(app: Any, *requests: tuple[str | None, str, str]) -> list[int]:
458
+ """Each (User-Agent, path, peer) through one app, answering each status."""
459
+ statuses: list[int] = []
460
+ for user_agent, url, peer in requests:
461
+ with TestClient(app, client=(peer, 12345)) as client:
462
+ # The test client sends a User-Agent of its own unless told otherwise.
463
+ client.headers.pop("User-Agent", None)
464
+ headers = {} if user_agent is None else {"User-Agent": user_agent}
465
+ statuses.append(client.get(url, headers=headers).status_code)
466
+ return statuses
467
+
468
+
469
+ def readme_app(**options: Any) -> FastAPI:
470
+ """The README's build, plus ``options``, with ``/guarded`` depending on
471
+ ``block_if({"is_hosting": True})``."""
472
+ return fastapi_with(
473
+ {"condition": {"is_hosting": True}},
474
+ api_key=os.environ["VPNDETECTION_API_KEY"],
475
+ **options,
476
+ )
477
+
478
+
479
+ def test_allow_bots_sends_the_requests_own_user_agent(
480
+ monkeypatch: pytest.MonkeyPatch,
481
+ ) -> None:
482
+ sent = api_answering(monkeypatch, {GOOGLEBOT: "verified"})
483
+
484
+ visit(
485
+ readme_app(allow_bots=True),
486
+ (GOOGLEBOT, "/", PUBLIC_IP),
487
+ ("", "/", "45.83.91.2"),
488
+ (None, "/", "45.83.91.3"),
489
+ )
490
+
491
+ assert sent == [GOOGLEBOT, None, None], "an empty or absent header sent an agent"
492
+
493
+
494
+ def test_without_allow_bots_no_user_agent_is_sent(monkeypatch: pytest.MonkeyPatch) -> None:
495
+ sent = api_answering(monkeypatch, {GOOGLEBOT: "verified"})
496
+
497
+ statuses = visit(
498
+ readme_app(block_condition={"is_hosting": True}), (GOOGLEBOT, "/", PUBLIC_IP)
499
+ )
500
+
501
+ assert sent == [None]
502
+ assert statuses == [403]
503
+
504
+
505
+ @pytest.mark.parametrize(
506
+ ("verdict", "status"), [("verified", 200), ("spoofed", 403), ("not_bot", 403)]
507
+ )
508
+ @pytest.mark.parametrize("url", ["/", "/guarded"])
509
+ def test_a_verified_crawler_passes_a_condition_it_meets_and_no_other_does(
510
+ monkeypatch: pytest.MonkeyPatch, url: str, verdict: str, status: int
511
+ ) -> None:
512
+ api_answering(monkeypatch, {GOOGLEBOT: verdict})
513
+ options: dict[str, Any] = {"allow_bots": True}
514
+ if url == "/":
515
+ options["block_condition"] = {"is_hosting": True}
516
+
517
+ assert visit(readme_app(**options), (GOOGLEBOT, url, PUBLIC_IP)) == [status]
518
+
519
+
520
+ def test_a_condition_naming_the_verdict_refuses_a_forged_crawler(
521
+ monkeypatch: pytest.MonkeyPatch,
522
+ ) -> None:
523
+ api_answering(monkeypatch, {GOOGLEBOT: "spoofed"})
524
+ app = readme_app(allow_bots=True, block_condition={"user_agent": {"verdict": "spoofed"}})
525
+
526
+ assert visit(app, (GOOGLEBOT, "/", PUBLIC_IP)) == [403]
527
+
528
+
529
+ def test_an_answer_without_a_verdict_warns_once(monkeypatch: pytest.MonkeyPatch) -> None:
530
+ sent = api_answering(monkeypatch, None)
531
+ warnings: list[str] = []
532
+ app = readme_app(allow_bots=True, on_warn=warnings.append)
533
+
534
+ visit(app, (GOOGLEBOT, "/", PUBLIC_IP), (GOOGLEBOT, "/", "45.83.91.2"))
535
+
536
+ assert sent == [GOOGLEBOT, GOOGLEBOT]
537
+ assert len([w for w in warnings if "user_agent verdict" in w]) == 1, warnings