botsrated 0.2.1__tar.gz → 0.3.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: botsrated
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: Payment guard for x402 agents: checks facts BotsRated measured about a seller before paying (advice-only by default), adds a payment-identifier retry key where supported, and checks on chain, read-only, whether a payment settled once. Not affiliated with Coinbase or the x402 Foundation.
5
5
  Project-URL: Homepage, https://botsrated.com
6
6
  Project-URL: Repository, https://github.com/botsrated/botsrated
@@ -30,12 +30,11 @@ The BotsRated **payment guard** for x402 clients, plus a simpler pre-payment che
30
30
 
31
31
  It lowers the chance of paying the wrong address or paying twice; it can't rule either out.
32
32
 
33
- **Status: 0.2.1 is not released yet. The latest version on PyPI is
34
- [`botsrated` 0.1.6](https://pypi.org/project/botsrated/), which does not include the payment guard.**
33
+ **Status: published on PyPI as [`botsrated` 0.2.1](https://pypi.org/project/botsrated/).** 0.3.0 (adds `remotePolicy` / `remote_policy`) is pending release.
35
34
 
36
35
  **What this does and doesn't do.** This package checks facts BotsRated measured about a seller before your agent signs, adds a retry key to the payment request, and reads the blockchain to see whether a payment already settled. It can't promise that a payment is right, that a seller will deliver, or that you'll never pay twice: a retry key only stops a second charge if the seller supports the x402 `payment-identifier` extension, and on-chain reads can be late or fail. You choose the rules that stop a payment, and you remain responsible for what your agent pays. Provided under the MIT license, "as is", without warranty.
37
36
 
38
- **Hosted checks.** By default (`hosted=True`) this package calls BotsRated's free API (`https://botsrated.com/v1/preflight`) and sends it **only the seller's host name** (never the path, query, wallet, amount, nonce, payment header or request body). Those calls are covered by the BotsRated Terms (https://botsrated.com/terms) and Privacy Policy (https://botsrated.com/privacy), not by the MIT license. `hosted=False` turns hosted checks off: nothing is then sent to botsrated.com, and only the local checks, the retry key and the on-chain check (which goes only to the RPCs you set) run.
37
+ **Hosted checks.** By default (`hosted=True`) this package calls BotsRated's preflight (`https://botsrated.com/v1/preflight`; free, no key, rate limits) and sends it **only the seller's host name** (never the path, query, wallet, amount, nonce, payment header or request body). Those calls are covered by the BotsRated Terms (https://botsrated.com/terms) and Privacy Policy (https://botsrated.com/privacy), not by the MIT license. `hosted=False` turns hosted checks off: nothing is then sent to botsrated.com, and only the local checks, the retry key and the on-chain check (which goes only to the RPCs you set) run.
39
38
 
40
39
  ## Install
41
40
 
@@ -162,6 +161,7 @@ smaller local bundle and does not copy a score out of it, because the response h
162
161
  | `timeout` / `cache_ttl` | 3 s / 5 min | Hosted lookup timeout and per-host cache |
163
162
  | `preflight` | hosted call | Your own lookup `(host) -> (found, body)` |
164
163
  | `on_decision` | none | Receives every decision (errors in it are ignored) |
164
+ | `remote_policy` | unset | Private policy check. See below. Unset: local presets only |
165
165
 
166
166
  ### Fail-Open Or Fail-Closed
167
167
 
@@ -172,16 +172,34 @@ smaller local bundle and does not copy a score out of it, because the response h
172
172
  for you than a missed call.
173
173
  - Local checks (`resource_host_mismatch`, `payto_invalid`) and the on-chain check never depend on botsrated.com.
174
174
 
175
+ ### Remote Policy
176
+
177
+ Optional. Set `remote_policy` to ask your private policy on BotsRated before a payment. The guard merges that answer with the local rules. A remote block stops the payment. A remote pass does not clear a local block. `PrePaymentGuard(..., remote_policy=...)` uses the same check.
178
+
179
+ This is the path that makes `BOTSRATED_TOKEN` work in framework attaches. The token is optional. The guard defaults to advice-only with no key, so anyone can install it as a default. The client enforces. BotsRated holds no funds, signs nothing, and has no escrow.
180
+
181
+ ```python
182
+ guard = PaymentGuard(
183
+ preset="carefulBuyer",
184
+ remote_policy={"token": "<bearer>", "fail_mode": "closed"}, # base_url defaults to https://botsrated.com
185
+ )
186
+ ```
187
+
188
+ `fail_mode` is yours: `open` or `closed`. The guard `POST`s `/v1/policy/check` with the seller host and the quote (`payTo`, `amount`, `asset`, `network`). On HTTP 503, HTTP 404, or `"decision": null`, it applies `fail_mode` (`open`: an info reason, payment continues unless a local rule stops it; `closed`: the payment stops). It does not turn a missing decision into a pass. `decided_by` and `not_a_botsrated_rating` are kept when the server sends them. The last `policy_version` is remembered on the guard. The policy decision is not signed. Leave `remote_policy` unset and local presets behave as before.
189
+
175
190
  ### What The Guard Sends, And To Whom
176
191
 
177
- - **botsrated.com:** `GET /v1/preflight?url=<host name>` with `User-Agent: botsrated-python/<version>`.
192
+ - **botsrated.com (preflight):** `GET /v1/preflight?url=<host name>` with `User-Agent: botsrated-python/<version>`.
178
193
  Never the path, query, wallet, amount, nonce, tx hash, payment header or request body. No install id. Covered by
179
194
  the [Terms](https://botsrated.com/terms) and [Privacy Policy](https://botsrated.com/privacy). Turn it off with
180
195
  `hosted=False`.
196
+ - **botsrated.com (only when `remote_policy` is set):** `POST /v1/policy/check` with the host, the quote
197
+ (`payTo`, `amount`, `asset`, `network`) and your bearer token. Not the path, query, payer wallet, nonce or a
198
+ payment header. The decision is not signed. `hosted=False` does not turn this off.
181
199
  - **Base RPCs (only when you call `payment_state`; nothing calls them automatically):** JSON-RPC reads that include
182
200
  the payer address and the payment's nonce, sent straight from your machine to the RPCs, never to BotsRated.
183
201
  See the privacy note under "Did It Settle Once?".
184
- - No remote configuration, feature flags or auto-update: behavior changes only with a new package version.
202
+ - No feature flags or auto-update: behavior changes only with a new package version, or with `remote_policy` when you set it.
185
203
 
186
204
  ### Retry Key (`payment-identifier`)
187
205
 
@@ -320,8 +338,8 @@ botsrated = BotsRatedClient(budget_usd="0.05", x402_client=client) # signs onl
320
338
  guard = PrePaymentGuard(botsrated, paid_check_at_or_above_usd=0.25)
321
339
  client.on_before_payment_creation(guard.x402_hook)
322
340
 
323
- botsrated.check("seller.example") # $0.001 (first 25 per UTC day free)
324
- botsrated.report("seller.example") # $0.002 (first 3 per UTC day free)
341
+ botsrated.check("seller.example") # $0.001 (first 25 per client IP per UTC day free)
342
+ botsrated.report("seller.example") # $0.002 (first 3 per client IP per UTC day free)
325
343
  botsrated.best("web search") # $0.01
326
344
  ```
327
345
 
@@ -333,11 +351,11 @@ the allowlisted fields only (scheme, network, asset, amount, payTo, maxTimeoutSe
333
351
  itself, so register the guard on the same x402 client so the re-served 402 is checked again before signing.
334
352
 
335
353
  How paid calls work:
336
- - Free daily quota (`FREE_DAILY_QUOTA`): the first 25 `/v1/check` and 3 `/v1/report` calls per client per UTC day are
354
+ - Free daily quota (`FREE_DAILY_QUOTA`): the first 25 `/v1/check` and 3 `/v1/report` calls per client IP per UTC day are
337
355
  served free (200 with `charged: false` and a `free_quota` block). The client asks unpaid first, so
338
356
  inside the quota nothing is paid and the budget is untouched; `check()`/`report()` also work without
339
357
  a budget until the quota is used up (then `paid_disabled`). `client.last_free_quota` shows what is left.
340
- `/v1/best` has no free quota. Preflight stays free and unlimited.
358
+ `/v1/best` has no free quota. Preflight stays free, no key, rate limits.
341
359
  - Otherwise the client reads the 402 quote unpaid first. It accepts the quote only if **every** option is `exact` USDC on Base to BotsRated's payTo
342
360
  `0x7F936f42F46B6c4Cbd3242cF8A1759dfe829E349`, at or below the published price.
343
361
  - The amount is reserved from the budget before paying. If the paid call fails or raises, it stays counted
@@ -11,12 +11,11 @@ The BotsRated **payment guard** for x402 clients, plus a simpler pre-payment che
11
11
 
12
12
  It lowers the chance of paying the wrong address or paying twice; it can't rule either out.
13
13
 
14
- **Status: 0.2.1 is not released yet. The latest version on PyPI is
15
- [`botsrated` 0.1.6](https://pypi.org/project/botsrated/), which does not include the payment guard.**
14
+ **Status: published on PyPI as [`botsrated` 0.2.1](https://pypi.org/project/botsrated/).** 0.3.0 (adds `remotePolicy` / `remote_policy`) is pending release.
16
15
 
17
16
  **What this does and doesn't do.** This package checks facts BotsRated measured about a seller before your agent signs, adds a retry key to the payment request, and reads the blockchain to see whether a payment already settled. It can't promise that a payment is right, that a seller will deliver, or that you'll never pay twice: a retry key only stops a second charge if the seller supports the x402 `payment-identifier` extension, and on-chain reads can be late or fail. You choose the rules that stop a payment, and you remain responsible for what your agent pays. Provided under the MIT license, "as is", without warranty.
18
17
 
19
- **Hosted checks.** By default (`hosted=True`) this package calls BotsRated's free API (`https://botsrated.com/v1/preflight`) and sends it **only the seller's host name** (never the path, query, wallet, amount, nonce, payment header or request body). Those calls are covered by the BotsRated Terms (https://botsrated.com/terms) and Privacy Policy (https://botsrated.com/privacy), not by the MIT license. `hosted=False` turns hosted checks off: nothing is then sent to botsrated.com, and only the local checks, the retry key and the on-chain check (which goes only to the RPCs you set) run.
18
+ **Hosted checks.** By default (`hosted=True`) this package calls BotsRated's preflight (`https://botsrated.com/v1/preflight`; free, no key, rate limits) and sends it **only the seller's host name** (never the path, query, wallet, amount, nonce, payment header or request body). Those calls are covered by the BotsRated Terms (https://botsrated.com/terms) and Privacy Policy (https://botsrated.com/privacy), not by the MIT license. `hosted=False` turns hosted checks off: nothing is then sent to botsrated.com, and only the local checks, the retry key and the on-chain check (which goes only to the RPCs you set) run.
20
19
 
21
20
  ## Install
22
21
 
@@ -143,6 +142,7 @@ smaller local bundle and does not copy a score out of it, because the response h
143
142
  | `timeout` / `cache_ttl` | 3 s / 5 min | Hosted lookup timeout and per-host cache |
144
143
  | `preflight` | hosted call | Your own lookup `(host) -> (found, body)` |
145
144
  | `on_decision` | none | Receives every decision (errors in it are ignored) |
145
+ | `remote_policy` | unset | Private policy check. See below. Unset: local presets only |
146
146
 
147
147
  ### Fail-Open Or Fail-Closed
148
148
 
@@ -153,16 +153,34 @@ smaller local bundle and does not copy a score out of it, because the response h
153
153
  for you than a missed call.
154
154
  - Local checks (`resource_host_mismatch`, `payto_invalid`) and the on-chain check never depend on botsrated.com.
155
155
 
156
+ ### Remote Policy
157
+
158
+ Optional. Set `remote_policy` to ask your private policy on BotsRated before a payment. The guard merges that answer with the local rules. A remote block stops the payment. A remote pass does not clear a local block. `PrePaymentGuard(..., remote_policy=...)` uses the same check.
159
+
160
+ This is the path that makes `BOTSRATED_TOKEN` work in framework attaches. The token is optional. The guard defaults to advice-only with no key, so anyone can install it as a default. The client enforces. BotsRated holds no funds, signs nothing, and has no escrow.
161
+
162
+ ```python
163
+ guard = PaymentGuard(
164
+ preset="carefulBuyer",
165
+ remote_policy={"token": "<bearer>", "fail_mode": "closed"}, # base_url defaults to https://botsrated.com
166
+ )
167
+ ```
168
+
169
+ `fail_mode` is yours: `open` or `closed`. The guard `POST`s `/v1/policy/check` with the seller host and the quote (`payTo`, `amount`, `asset`, `network`). On HTTP 503, HTTP 404, or `"decision": null`, it applies `fail_mode` (`open`: an info reason, payment continues unless a local rule stops it; `closed`: the payment stops). It does not turn a missing decision into a pass. `decided_by` and `not_a_botsrated_rating` are kept when the server sends them. The last `policy_version` is remembered on the guard. The policy decision is not signed. Leave `remote_policy` unset and local presets behave as before.
170
+
156
171
  ### What The Guard Sends, And To Whom
157
172
 
158
- - **botsrated.com:** `GET /v1/preflight?url=<host name>` with `User-Agent: botsrated-python/<version>`.
173
+ - **botsrated.com (preflight):** `GET /v1/preflight?url=<host name>` with `User-Agent: botsrated-python/<version>`.
159
174
  Never the path, query, wallet, amount, nonce, tx hash, payment header or request body. No install id. Covered by
160
175
  the [Terms](https://botsrated.com/terms) and [Privacy Policy](https://botsrated.com/privacy). Turn it off with
161
176
  `hosted=False`.
177
+ - **botsrated.com (only when `remote_policy` is set):** `POST /v1/policy/check` with the host, the quote
178
+ (`payTo`, `amount`, `asset`, `network`) and your bearer token. Not the path, query, payer wallet, nonce or a
179
+ payment header. The decision is not signed. `hosted=False` does not turn this off.
162
180
  - **Base RPCs (only when you call `payment_state`; nothing calls them automatically):** JSON-RPC reads that include
163
181
  the payer address and the payment's nonce, sent straight from your machine to the RPCs, never to BotsRated.
164
182
  See the privacy note under "Did It Settle Once?".
165
- - No remote configuration, feature flags or auto-update: behavior changes only with a new package version.
183
+ - No feature flags or auto-update: behavior changes only with a new package version, or with `remote_policy` when you set it.
166
184
 
167
185
  ### Retry Key (`payment-identifier`)
168
186
 
@@ -301,8 +319,8 @@ botsrated = BotsRatedClient(budget_usd="0.05", x402_client=client) # signs onl
301
319
  guard = PrePaymentGuard(botsrated, paid_check_at_or_above_usd=0.25)
302
320
  client.on_before_payment_creation(guard.x402_hook)
303
321
 
304
- botsrated.check("seller.example") # $0.001 (first 25 per UTC day free)
305
- botsrated.report("seller.example") # $0.002 (first 3 per UTC day free)
322
+ botsrated.check("seller.example") # $0.001 (first 25 per client IP per UTC day free)
323
+ botsrated.report("seller.example") # $0.002 (first 3 per client IP per UTC day free)
306
324
  botsrated.best("web search") # $0.01
307
325
  ```
308
326
 
@@ -314,11 +332,11 @@ the allowlisted fields only (scheme, network, asset, amount, payTo, maxTimeoutSe
314
332
  itself, so register the guard on the same x402 client so the re-served 402 is checked again before signing.
315
333
 
316
334
  How paid calls work:
317
- - Free daily quota (`FREE_DAILY_QUOTA`): the first 25 `/v1/check` and 3 `/v1/report` calls per client per UTC day are
335
+ - Free daily quota (`FREE_DAILY_QUOTA`): the first 25 `/v1/check` and 3 `/v1/report` calls per client IP per UTC day are
318
336
  served free (200 with `charged: false` and a `free_quota` block). The client asks unpaid first, so
319
337
  inside the quota nothing is paid and the budget is untouched; `check()`/`report()` also work without
320
338
  a budget until the quota is used up (then `paid_disabled`). `client.last_free_quota` shows what is left.
321
- `/v1/best` has no free quota. Preflight stays free and unlimited.
339
+ `/v1/best` has no free quota. Preflight stays free, no key, rate limits.
322
340
  - Otherwise the client reads the 402 quote unpaid first. It accepts the quote only if **every** option is `exact` USDC on Base to BotsRated's payTo
323
341
  `0x7F936f42F46B6c4Cbd3242cF8A1759dfe829E349`, at or below the published price.
324
342
  - The amount is reserved from the budget before paying. If the paid call fails or raises, it stays counted
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "botsrated"
3
- version = "0.2.1"
3
+ version = "0.3.0"
4
4
  description = "Payment guard for x402 agents: checks facts BotsRated measured about a seller before paying (advice-only by default), adds a payment-identifier retry key where supported, and checks on chain, read-only, whether a payment settled once. Not affiliated with Coinbase or the x402 Foundation."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -20,6 +20,7 @@ from botsrated.payment_guard import (
20
20
  GuardReason,
21
21
  PaymentGuard,
22
22
  PaymentGuardPolicy,
23
+ RemotePolicy,
23
24
  dry_run_only,
24
25
  )
25
26
  from botsrated.util import (
@@ -133,6 +134,7 @@ __all__ = [
133
134
  "PrePaymentGuard",
134
135
  "PreflightResult",
135
136
  "Reason",
137
+ "RemotePolicy",
136
138
  "SellerFacts",
137
139
  "acheck_payment_state",
138
140
  "check_payment_state",
@@ -226,6 +226,10 @@ class BotsRatedClient:
226
226
  except httpx.HTTPError as e:
227
227
  raise BotsRatedError(f"BotsRated unreachable: {clean_text(e, 80)}", "unreachable") from e
228
228
 
229
+ def unpaid_http(self) -> httpx.Client:
230
+ """HTTP client for unpaid calls. A remote policy check uses this and does not create a payment."""
231
+ return self._http
232
+
229
233
  def preflight(self, url_or_host: str) -> PreflightResult:
230
234
  """Free. Latest stored probe for a seller; ``found=False`` when the host is not covered.
231
235
 
@@ -254,11 +258,11 @@ class BotsRatedClient:
254
258
  return result
255
259
 
256
260
  def check(self, url_or_host: str) -> dict[str, Any]:
257
- """Paid ($0.001; first 25 per UTC day free). Facts, paid test-buys and recent receipts for one host."""
261
+ """Paid ($0.001; first 25 per client IP per UTC day free). Facts, paid test-buys and recent receipts for one host."""
258
262
  return self._paid(f"/v1/check?host={quote(host_of(url_or_host), safe='')}", "check")
259
263
 
260
264
  def report(self, url_or_host: str) -> dict[str, Any]:
261
- """Paid ($0.002; first 3 per UTC day free). Full receipt history for one host."""
265
+ """Paid ($0.002; first 3 per client IP per UTC day free). Full receipt history for one host."""
262
266
  return self._paid(f"/v1/report/{quote(host_of(url_or_host), safe='')}", "report")
263
267
 
264
268
  def best(self, task: str, sort: str | None = None, max_price_usd: float | None = None) -> dict[str, Any]:
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from collections.abc import Awaitable, Callable
5
+ from collections.abc import Awaitable, Callable, Mapping
6
6
  from dataclasses import dataclass, field
7
7
  from typing import Any, Literal, TypeVar
8
8
  from urllib.parse import urlsplit
@@ -15,6 +15,12 @@ from botsrated.client import (
15
15
  paying_request,
16
16
  usd_to_atomic,
17
17
  )
18
+ from botsrated.payment_guard import (
19
+ RemotePolicy,
20
+ fetch_remote_policy,
21
+ interpret_policy_body,
22
+ parse_remote_policy,
23
+ )
18
24
  from botsrated.util import (
19
25
  DISPUTE_URL,
20
26
  clean_text,
@@ -62,6 +68,11 @@ class Decision:
62
68
  reasons: list[Reason]
63
69
  facts: SellerFacts | None = None
64
70
  dispute_url: str = DISPUTE_URL
71
+ # Set when a remote policy check ran. ``remote_decision`` stays None when the server sent none.
72
+ decided_by: str | None = None
73
+ not_a_botsrated_rating: bool | None = None
74
+ policy_version: str | None = None
75
+ remote_decision: Literal["pass", "warn", "block"] | None = None
65
76
 
66
77
  def summary(self) -> str:
67
78
  """Fact-only text with the dispute link. Seller text is never echoed beyond a parsed host name."""
@@ -223,6 +234,10 @@ class PrePaymentGuard:
223
234
  paid_check_at_or_above_usd: Run a check for payments at or above this: free within the daily quota
224
235
  (25 per UTC day), then a $0.001 paid check with a paid-enabled client (skipped otherwise).
225
236
  on_decision: Called with every decision.
237
+ remote_policy: Optional private policy check (``token``, ``fail_mode`` ``open`` or ``closed``, optional
238
+ ``base_url``). Before paying, ``POST /v1/policy/check`` with the host and quote. A remote block stops
239
+ the payment. HTTP 503, 404 or ``decision: null`` follows ``fail_mode`` and is never read as a pass.
240
+ The last ``policy_version`` is kept on ``remote_policy_version``. Unset: local rules only.
226
241
  """
227
242
 
228
243
  def __init__(
@@ -233,12 +248,15 @@ class PrePaymentGuard:
233
248
  fail_open: bool = True,
234
249
  paid_check_at_or_above_usd: float | None = None,
235
250
  on_decision: Callable[[Decision], None] | None = None,
251
+ remote_policy: RemotePolicy | Mapping[str, Any] | None = None,
236
252
  ) -> None:
237
253
  self.client = client or BotsRatedClient()
238
254
  self.policy = policy or GuardPolicy()
239
255
  self.fail_open = fail_open
240
256
  self.paid_threshold = paid_check_at_or_above_usd
241
257
  self.on_decision = on_decision
258
+ self.remote_policy = parse_remote_policy(remote_policy)
259
+ self.remote_policy_version: str | None = None
242
260
 
243
261
  def _open_or_closed(self, code: str, detail: str, host: str | None = None) -> Decision:
244
262
  eff: Effect = "info" if self.fail_open else "block"
@@ -257,9 +275,33 @@ class PrePaymentGuard:
257
275
  difference (a redirect between the two) is tolerated. Only host names are sent to BotsRated.
258
276
  """
259
277
  try:
260
- return self._decide(resource_url, requirements, request_url)
278
+ decision = self._decide(resource_url, requirements, request_url)
279
+ except Exception: # noqa: BLE001
280
+ decision = self._open_or_closed("hook_error", "the pre-payment check could not evaluate this payment.")
281
+ return self._merge_remote(decision, requirements)
282
+
283
+ def _merge_remote(self, decision: Decision, requirements: Any) -> Decision:
284
+ """POST /v1/policy/check when configured. A remote block wins. A missing decision follows fail_mode."""
285
+ policy = self.remote_policy
286
+ host = decision.host
287
+ if policy is None or not host:
288
+ return decision
289
+ try:
290
+ effect = fetch_remote_policy(self.client.unpaid_http(), policy, host, requirements)
261
291
  except Exception: # noqa: BLE001
262
- return self._open_or_closed("hook_error", "the pre-payment check could not evaluate this payment.")
292
+ effect = interpret_policy_body(None, {}, policy.fail_mode, host)
293
+ version = effect.policy_version or self.remote_policy_version
294
+ if effect.policy_version:
295
+ self.remote_policy_version = effect.policy_version
296
+ if effect.effect and effect.code and effect.fact:
297
+ decision.reasons.append(Reason(effect.code, effect.fact, effect.effect))
298
+ if effect.effect == "block":
299
+ decision.action = "block"
300
+ decision.decided_by = effect.decided_by
301
+ decision.not_a_botsrated_rating = effect.not_a_botsrated_rating
302
+ decision.policy_version = version
303
+ decision.remote_decision = effect.decision
304
+ return decision
263
305
 
264
306
  def _decide(self, resource_url: str | None, requirements: Any, request_url: str | None) -> Decision:
265
307
  req = as_requirements(requirements)
@@ -6,6 +6,9 @@ What it does, and nothing more:
6
6
  botsrated.com) and compares them locally with the payment request. Advice-only by default: it reports facts and
7
7
  stops a payment only when you choose a blocking policy (e.g. ``POLICIES["carefulBuyer"]``, an alias of
8
8
  ``POLICIES["strict"]``).
9
+ - When ``remote_policy`` is set: ``POST /v1/policy/check`` with that host and the quote, merged with the local rules
10
+ (a remote block stops the payment). HTTP 503 or ``decision: null`` follows your ``fail_mode``. The policy decision
11
+ is not signed.
9
12
  - While the payload is built: adds a random x402 ``payment-identifier`` retry key, only when the seller advertises
10
13
  that extension, through x402's extension mechanism.
11
14
  - After: records the payment locally (never the signature) and offers a read-only on-chain check of whether it
@@ -26,12 +29,13 @@ import json
26
29
  import secrets
27
30
  import threading
28
31
  import time
29
- from collections.abc import Awaitable, Callable, Iterator
32
+ from collections.abc import Awaitable, Callable, Iterator, Mapping
30
33
  from contextlib import contextmanager
31
34
  from contextvars import ContextVar
32
35
  from dataclasses import asdict, dataclass, field, replace
33
36
  from datetime import datetime, timezone
34
37
  from typing import Any, Literal, TypeVar
38
+ from urllib.parse import urlsplit
35
39
 
36
40
  import httpx
37
41
 
@@ -149,6 +153,11 @@ class GuardDecision:
149
153
  policy_rule: str | None = None
150
154
  facts: GuardFacts | None = None
151
155
  dispute_url: str = DISPUTE_URL
156
+ # Present only after a remote policy check. ``remote_decision`` stays None when the server sent none.
157
+ decided_by: str | None = None
158
+ not_a_botsrated_rating: bool | None = None
159
+ policy_version: str | None = None
160
+ remote_decision: Literal["pass", "warn", "block"] | None = None
152
161
 
153
162
 
154
163
  def _effect(e: RuleEffect, fallback: Effect) -> Effect:
@@ -193,6 +202,204 @@ def _get(obj: Any, *names: str) -> Any:
193
202
  return None
194
203
 
195
204
 
205
+ # ----------------------------------------------------------------------------------------------------------------
206
+ # Remote policy. The client enforces. A missing decision is never turned into a pass.
207
+
208
+
209
+ FailMode = Literal["open", "closed"]
210
+ RemoteDecision = Literal["pass", "warn", "block"]
211
+
212
+
213
+ def _ascii_label(text: str, extra: str) -> bool:
214
+ return all(c.isascii() and (c.isalnum() or c in extra) for c in text)
215
+
216
+
217
+ def _policy_origin(base: str) -> str:
218
+ """Origin only. A path on ``base_url`` is not a prefix (the check path is always ``/v1/policy/check``)."""
219
+ if not isinstance(base, str) or any(c.isspace() for c in base):
220
+ raise ValueError("remote_policy.base_url must be an http(s) URL.")
221
+ parts = urlsplit(base.strip())
222
+ if parts.scheme not in ("http", "https") or not parts.hostname or parts.username or parts.password:
223
+ raise ValueError("remote_policy.base_url must be an http(s) URL.")
224
+ host = f"[{parts.hostname}]" if ":" in parts.hostname else parts.hostname
225
+ netloc = host if parts.port is None else f"{host}:{parts.port}"
226
+ return f"{parts.scheme}://{netloc}"
227
+
228
+
229
+ def _token_ok(token: str) -> bool:
230
+ if not isinstance(token, str) or not token or len(token) > 4096:
231
+ return False
232
+ return all(c.isascii() and not c.isspace() and ord(c) >= 33 for c in token)
233
+
234
+
235
+ def _version_of(value: Any) -> str | None:
236
+ if isinstance(value, bool) or value is None:
237
+ return None
238
+ text = str(value) if isinstance(value, int) else value.strip() if isinstance(value, str) else None
239
+ if not text or len(text) > 80 or not _ascii_label(text, "._:-"):
240
+ return None
241
+ return text
242
+
243
+
244
+ @dataclass(frozen=True)
245
+ class RemotePolicy:
246
+ """Your private policy check. ``fail_mode`` is required: ``open`` or ``closed``.
247
+
248
+ ``base_url`` defaults to https://botsrated.com when omitted. A mapping may use ``fail_mode`` or
249
+ ``failMode``, and ``base_url`` or ``baseUrl``.
250
+ """
251
+
252
+ token: str
253
+ fail_mode: FailMode
254
+ base_url: str | None = None
255
+
256
+ def __post_init__(self) -> None:
257
+ token = self.token[7:].strip() if isinstance(self.token, str) and self.token.lower().startswith("bearer ") else self.token
258
+ if token is not self.token:
259
+ object.__setattr__(self, "token", token)
260
+ if not _token_ok(token if isinstance(token, str) else ""):
261
+ raise ValueError("remote_policy.token must be a non-empty bearer token without whitespace.")
262
+ if self.fail_mode not in ("open", "closed"):
263
+ raise ValueError('remote_policy.fail_mode must be "open" or "closed".')
264
+ if self.base_url is None:
265
+ return
266
+ object.__setattr__(self, "base_url", _policy_origin(self.base_url))
267
+
268
+
269
+ def parse_remote_policy(value: RemotePolicy | Mapping[str, Any] | None) -> RemotePolicy | None:
270
+ """Accept a :class:`RemotePolicy` or a mapping. ``None`` leaves the guard on local rules only."""
271
+ if value is None:
272
+ return None
273
+ if isinstance(value, RemotePolicy):
274
+ return value
275
+ if not isinstance(value, Mapping):
276
+ raise TypeError("remote_policy must be a RemotePolicy or a mapping.")
277
+ if "fail_mode" in value and "failMode" in value and value.get("fail_mode") != value.get("failMode"):
278
+ raise ValueError("remote_policy.fail_mode and failMode disagree.")
279
+ if "base_url" in value and "baseUrl" in value and value.get("base_url") != value.get("baseUrl"):
280
+ raise ValueError("remote_policy.base_url and baseUrl disagree.")
281
+ fail_mode = value.get("fail_mode", value.get("failMode"))
282
+ base_url = value.get("base_url", value.get("baseUrl"))
283
+ return RemotePolicy(str(value.get("token") or ""), fail_mode, base_url) # type: ignore[arg-type]
284
+
285
+
286
+ @dataclass(frozen=True)
287
+ class RemotePolicyEffect:
288
+ """One policy-check outcome. ``decision`` is set only when the server named pass, warn or block."""
289
+
290
+ decision: RemoteDecision | None
291
+ effect: Effect | None
292
+ code: str | None
293
+ fact: str | None
294
+ decided_by: str | None = None
295
+ not_a_botsrated_rating: bool | None = None
296
+ policy_version: str | None = None
297
+
298
+
299
+ def policy_quote(req: Any) -> dict[str, str]:
300
+ """Quote fields sent to ``/v1/policy/check``: payTo, amount, asset, network. Nothing else."""
301
+ quote: dict[str, str] = {}
302
+ pay_to = _get(req, "payTo", "pay_to")
303
+ if is_address(pay_to):
304
+ quote["payTo"] = pay_to
305
+ amount = _get(req, "amount")
306
+ if isinstance(amount, bool):
307
+ amount_s = None
308
+ elif isinstance(amount, int):
309
+ amount_s = str(amount)
310
+ elif isinstance(amount, str):
311
+ amount_s = amount
312
+ else:
313
+ amount_s = None
314
+ if is_atomic_amount(amount_s):
315
+ quote["amount"] = amount_s
316
+ asset = _get(req, "asset")
317
+ if is_address(asset):
318
+ quote["asset"] = asset
319
+ network = _get(req, "network")
320
+ if isinstance(network, str) and network.strip():
321
+ quote["network"] = clean_text(network, 40)
322
+ return quote
323
+
324
+
325
+ def _framing(body: Any) -> tuple[str | None, bool | None, str | None]:
326
+ if not isinstance(body, dict):
327
+ return None, None, None
328
+ decided = body.get("decided_by")
329
+ decided_by = decided.strip() if isinstance(decided, str) else None
330
+ if decided_by is not None and (not decided_by or len(decided_by) > 80 or not _ascii_label(decided_by, "_.:-")):
331
+ decided_by = None
332
+ rating = body.get("not_a_botsrated_rating")
333
+ return decided_by, rating if isinstance(rating, bool) else None, _version_of(body.get("policy_version"))
334
+
335
+
336
+ def _named_decision(body: Any) -> RemoteDecision | None:
337
+ """pass, warn or block. ``allow`` is read as pass. Any other label, including null, is no decision."""
338
+ if not isinstance(body, dict) or "decision" not in body:
339
+ return None
340
+ raw = body.get("decision")
341
+ if not isinstance(raw, str):
342
+ return None
343
+ key = raw.strip().lower()
344
+ if key == "block":
345
+ return "block"
346
+ if key == "warn":
347
+ return "warn"
348
+ if key in ("pass", "allow"):
349
+ return "pass"
350
+ return None
351
+
352
+
353
+ def interpret_policy_body(status: int | None, body: Any, fail_mode: FailMode, host: str) -> RemotePolicyEffect:
354
+ """Map a policy-check response. 503, 404, transport failure and ``decision: null`` use ``fail_mode``."""
355
+ decided_by, rating, version = _framing(body)
356
+ if status is not None and 200 <= status < 300:
357
+ decision = _named_decision(body)
358
+ if decision == "block":
359
+ return RemotePolicyEffect("block", "block", "remote_policy", f"your policy returned block for {host}.", decided_by, rating, version)
360
+ if decision == "warn":
361
+ return RemotePolicyEffect("warn", "warn", "remote_policy", f"your policy returned warn for {host}.", decided_by, rating, version)
362
+ if decision == "pass":
363
+ return RemotePolicyEffect("pass", None, None, None, decided_by, rating, version)
364
+ effect: Effect = "block" if fail_mode == "closed" else "info"
365
+ fact = f"your policy check returned no decision; fail_mode is {fail_mode}."
366
+ return RemotePolicyEffect(None, effect, "remote_policy_unavailable", fact, decided_by, rating, version)
367
+
368
+
369
+ def _policy_headers(token: str) -> dict[str, str]:
370
+ return {
371
+ "accept": "application/json",
372
+ "content-type": "application/json",
373
+ "user-agent": USER_AGENT,
374
+ "authorization": f"Bearer {token}",
375
+ }
376
+
377
+
378
+ def _read_policy_response(resp: httpx.Response) -> tuple[int, Any]:
379
+ if len(resp.content) > 1_000_000:
380
+ return resp.status_code, {}
381
+ try:
382
+ body = resp.json()
383
+ except ValueError:
384
+ body = {}
385
+ return resp.status_code, body if isinstance(body, dict) else {}
386
+
387
+
388
+ def fetch_remote_policy(http: httpx.Client, policy: RemotePolicy, host: str, req: Any, timeout: float | None = None) -> RemotePolicyEffect:
389
+ """POST /v1/policy/check. Transport errors and non-decisions follow ``policy.fail_mode``."""
390
+ url = f"{(policy.base_url or BOTSRATED_BASE_URL)}/v1/policy/check"
391
+ payload = {"host": host, "quote": policy_quote(req)}
392
+ try:
393
+ kwargs: dict[str, Any] = {"json": payload, "headers": _policy_headers(policy.token), "follow_redirects": False}
394
+ if timeout is not None:
395
+ kwargs["timeout"] = timeout
396
+ resp = http.post(url, **kwargs)
397
+ status, body = _read_policy_response(resp)
398
+ except Exception: # noqa: BLE001 - a failed check is fail_mode, not a pass
399
+ status, body = None, {}
400
+ return interpret_policy_body(status, body, policy.fail_mode, host)
401
+
402
+
196
403
  def evaluate_facts(facts: GuardFacts, req: Any, paid_url: str | None, policy: PaymentGuardPolicy) -> list[GuardReason]:
197
404
  """Pure, local comparison of one payment option with BotsRated facts."""
198
405
  out: list[GuardReason] = []
@@ -376,6 +583,10 @@ class PaymentGuard:
376
583
  http / async_http: Optional ``httpx.Client`` / ``httpx.AsyncClient`` for the hosted lookup.
377
584
  preflight: Replace the hosted lookup: ``(host) -> (found, body)``. Receives a host name only.
378
585
  on_decision: Receives every decision. Errors raised in it are ignored.
586
+ remote_policy: Optional private policy check (``token``, ``fail_mode`` ``open`` or ``closed``, optional
587
+ ``base_url``). Before paying, ``POST /v1/policy/check`` with the host and quote. A remote block stops
588
+ the payment. HTTP 503, 404 or ``decision: null`` follows ``fail_mode`` and is never read as a pass.
589
+ The last ``policy_version`` is kept on ``remote_policy_version``. Unset: local rules only.
379
590
  """
380
591
 
381
592
  def __init__(
@@ -395,6 +606,7 @@ class PaymentGuard:
395
606
  async_http: httpx.AsyncClient | None = None,
396
607
  preflight: Callable[[str], tuple[bool, dict[str, Any]]] | None = None,
397
608
  on_decision: Callable[[GuardDecision], None] | None = None,
609
+ remote_policy: RemotePolicy | Mapping[str, Any] | None = None,
398
610
  ) -> None:
399
611
  if preset is not None and preset not in PRESETS:
400
612
  raise ValueError(f'Unknown payment guard preset "{preset}". Expected warn, carefulBuyer, or dry-run-only.')
@@ -418,6 +630,8 @@ class PaymentGuard:
418
630
  self._async_http = async_http
419
631
  self._preflight = preflight
420
632
  self.on_decision = on_decision
633
+ self.remote_policy = parse_remote_policy(remote_policy)
634
+ self.remote_policy_version: str | None = None
421
635
  self._records: dict[str, PaymentRecord] = {}
422
636
  self._retry_keys: dict[str, tuple[str, int]] = {}
423
637
  self._lock = threading.Lock()
@@ -495,7 +709,14 @@ class PaymentGuard:
495
709
  except Exception: # noqa: BLE001, S110 - caller callback errors are ignored
496
710
  pass
497
711
 
498
- def _finish(self, phase: Literal["before_payment", "payment_response"], reasons: list[GuardReason], host: str | None, facts: GuardFacts | None = None) -> GuardDecision:
712
+ def _finish(
713
+ self,
714
+ phase: Literal["before_payment", "payment_response"],
715
+ reasons: list[GuardReason],
716
+ host: str | None,
717
+ facts: GuardFacts | None = None,
718
+ remote: RemotePolicyEffect | None = None,
719
+ ) -> GuardDecision:
499
720
  stopping = next((r for r in reasons if r.effect == "block"), None)
500
721
  d = GuardDecision(
501
722
  phase=phase,
@@ -507,10 +728,50 @@ class PaymentGuard:
507
728
  host=host,
508
729
  policy_rule=(stopping.rule or stopping.code) if stopping else None,
509
730
  facts=facts,
731
+ decided_by=remote.decided_by if remote else None,
732
+ not_a_botsrated_rating=remote.not_a_botsrated_rating if remote else None,
733
+ policy_version=remote.policy_version if remote else None,
734
+ remote_decision=remote.decision if remote else None,
510
735
  )
511
736
  d.message = _summarize(d)
512
737
  return d
513
738
 
739
+ def _remember_remote(self, reasons: list[GuardReason], effect: RemotePolicyEffect | None) -> RemotePolicyEffect | None:
740
+ if effect is None:
741
+ return None
742
+ version = effect.policy_version or self.remote_policy_version
743
+ if effect.policy_version:
744
+ self.remote_policy_version = effect.policy_version
745
+ if version != effect.policy_version:
746
+ effect = replace(effect, policy_version=version)
747
+ if effect.effect and effect.code and effect.fact:
748
+ rule = "remotePolicy" if effect.decision else "failMode"
749
+ reasons.append(GuardReason(effect.code, effect.effect, effect.fact, rule))
750
+ return effect
751
+
752
+ def _remote_sync(self, host: str, req: Any) -> RemotePolicyEffect:
753
+ assert self.remote_policy is not None
754
+ if self._http is not None:
755
+ return fetch_remote_policy(self._http, self.remote_policy, host, req, self._timeout)
756
+ with httpx.Client(timeout=self._timeout, follow_redirects=False) as client:
757
+ return fetch_remote_policy(client, self.remote_policy, host, req, self._timeout)
758
+
759
+ async def _remote_async(self, host: str, req: Any) -> RemotePolicyEffect:
760
+ assert self.remote_policy is not None
761
+ url = f"{(self.remote_policy.base_url or BOTSRATED_BASE_URL)}/v1/policy/check"
762
+ headers = _policy_headers(self.remote_policy.token)
763
+ payload = {"host": host, "quote": policy_quote(req)}
764
+ try:
765
+ if self._async_http is not None:
766
+ resp = await self._async_http.post(url, json=payload, headers=headers, timeout=self._timeout, follow_redirects=False)
767
+ else:
768
+ async with httpx.AsyncClient(timeout=self._timeout, follow_redirects=False) as c:
769
+ resp = await c.post(url, json=payload, headers=headers)
770
+ status, body = _read_policy_response(resp)
771
+ except Exception: # noqa: BLE001 - a failed check is fail_mode, not a pass
772
+ status, body = None, {}
773
+ return interpret_policy_body(status, body, self.remote_policy.fail_mode, host)
774
+
514
775
  def _local(self, ctx: Any) -> tuple[list[GuardReason], str | None, str | None, Any, str | None]:
515
776
  pr = _get(ctx, "payment_required", "paymentRequired")
516
777
  req = _get(ctx, "selected_requirements", "selectedRequirements")
@@ -644,7 +905,8 @@ class PaymentGuard:
644
905
  try:
645
906
  reasons, host, lookup, req, paid_url = self._local(ctx)
646
907
  facts = self._with_facts(reasons, lookup, self._lookup_sync(lookup), req, paid_url) if lookup else None
647
- return self._finish("before_payment", reasons, host, facts)
908
+ remote = self._remember_remote(reasons, self._remote_sync(host, req) if self.remote_policy and host else None)
909
+ return self._finish("before_payment", reasons, host, facts, remote)
648
910
  except Exception: # noqa: BLE001
649
911
  return self._hook_error()
650
912
 
@@ -653,7 +915,8 @@ class PaymentGuard:
653
915
  try:
654
916
  reasons, host, lookup, req, paid_url = self._local(ctx)
655
917
  facts = self._with_facts(reasons, lookup, await self._lookup_async(lookup), req, paid_url) if lookup else None
656
- return self._finish("before_payment", reasons, host, facts)
918
+ remote = self._remember_remote(reasons, await self._remote_async(host, req) if self.remote_policy and host else None)
919
+ return self._finish("before_payment", reasons, host, facts, remote)
657
920
  except Exception: # noqa: BLE001
658
921
  return self._hook_error()
659
922
 
@@ -868,4 +1131,7 @@ def decision_as_dict(d: GuardDecision) -> dict[str, Any]:
868
1131
  out = asdict(d)
869
1132
  if out.get("facts"):
870
1133
  out["facts"].pop("probed", None)
1134
+ for key in ("decided_by", "not_a_botsrated_rating", "policy_version", "remote_decision"):
1135
+ if out.get(key) is None:
1136
+ out.pop(key, None)
871
1137
  return out
@@ -6,7 +6,7 @@ import re
6
6
  from typing import Any
7
7
  from urllib.parse import urlsplit
8
8
 
9
- VERSION = "0.2.1"
9
+ VERSION = "0.3.0"
10
10
  # Sent on hosted BotsRated calls. No install id, wallet or other user identifier.
11
11
  USER_AGENT = f"botsrated-python/{VERSION}"
12
12
  BOTSRATED_BASE_URL = "https://botsrated.com"
@@ -0,0 +1,301 @@
1
+ """Remote policy on PaymentGuard and PrePaymentGuard.
2
+
3
+ A remote block stops the payment. HTTP 503, 404 and decision null follow fail_mode.
4
+ A missing decision is never stored as a pass, and the check is not signed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+
11
+ import httpx
12
+ import pytest
13
+
14
+ from botsrated import (
15
+ POLICIES,
16
+ STRICT_GUARD_POLICY,
17
+ PaymentGuard,
18
+ PrePaymentGuard,
19
+ RemotePolicy,
20
+ )
21
+ from botsrated.client import BotsRatedClient
22
+ from botsrated.payment_guard import interpret_policy_body
23
+
24
+ DEAD = "0x000000000000000000000000000000000000dEaD"
25
+
26
+
27
+ def req(found, **over):
28
+ row = {
29
+ "scheme": "exact",
30
+ "network": "eip155:8453",
31
+ "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
32
+ "payTo": found["latest_probe"]["live_payTo"],
33
+ "amount": found["latest_probe"]["live_amount"],
34
+ "maxTimeoutSeconds": 60,
35
+ "extra": {"name": "USD Coin", "version": "2"},
36
+ }
37
+ row.update(over)
38
+ return row
39
+
40
+
41
+ def ctx(resource_url, row):
42
+ return {"payment_required": {"x402Version": 2, "resource": {"url": resource_url}, "accepts": [row]}, "selected_requirements": row}
43
+
44
+ TOKEN = "policy-token-1"
45
+ FRAMING = {"decided_by": "your_policy", "not_a_botsrated_rating": True, "policy_version": "7"}
46
+
47
+
48
+ def _answer(found, policy):
49
+ seen: list[httpx.Request] = []
50
+
51
+ def respond(request: httpx.Request) -> httpx.Response:
52
+ seen.append(request)
53
+ path = request.url.path
54
+ if path.endswith("/policy/check"):
55
+ status, body = policy(request)
56
+ return httpx.Response(status, json=body)
57
+ return httpx.Response(200, json=found)
58
+
59
+ return seen, respond
60
+
61
+
62
+ def _payment_guard(found, handler, **kw):
63
+ seen, respond = _answer(found, handler)
64
+ guard = PaymentGuard(http=httpx.Client(transport=httpx.MockTransport(respond)), **kw)
65
+ return guard, seen
66
+
67
+
68
+ def _pre(found, handler, **kw):
69
+ seen, respond = _answer(found, handler)
70
+ client = BotsRatedClient(http=httpx.Client(transport=httpx.MockTransport(respond)))
71
+ return PrePaymentGuard(client, **kw), seen
72
+
73
+
74
+ def _policy_bodies(seen: list[httpx.Request]) -> list[dict]:
75
+ out = []
76
+ for request in seen:
77
+ if request.url.path.endswith("/policy/check"):
78
+ out.append(json.loads(request.content))
79
+ return out
80
+
81
+
82
+ def test_unset_remote_policy_keeps_local_presets_and_does_not_post(found):
83
+ guard, seen = _payment_guard(found, lambda r: (200, {}), policy=POLICIES["carefulBuyer"])
84
+ url = found["latest_probe"]["url"]
85
+ with guard.request(url):
86
+ decision = guard.decide(ctx(url, req(found, payTo=DEAD)))
87
+ assert decision.action == "block" and decision.policy_rule == "payToMismatch"
88
+ assert decision.remote_decision is None
89
+ assert _policy_bodies(seen) == []
90
+ assert all("/v1/preflight" in str(r.url) for r in seen)
91
+
92
+
93
+ def test_remote_block_wins_over_a_local_allow(found):
94
+ def policy(_request):
95
+ return 200, {"decision": "block", **FRAMING}
96
+
97
+ guard, seen = _payment_guard(found, policy, remote_policy={"token": TOKEN, "fail_mode": "open"})
98
+ url = found["latest_probe"]["url"]
99
+ with guard.request(url):
100
+ decision = guard.decide(ctx(url, req(found)))
101
+ assert decision.action == "block"
102
+ assert decision.policy_rule == "remotePolicy"
103
+ assert decision.remote_decision == "block"
104
+ assert decision.decided_by == "your_policy"
105
+ assert decision.not_a_botsrated_rating is True
106
+ assert decision.policy_version == "7"
107
+ assert guard.remote_policy_version == "7"
108
+ body = _policy_bodies(seen)[0]
109
+ assert body["host"] == "blockrun.ai"
110
+ assert set(body) == {"host", "quote"}
111
+ assert set(body["quote"]) <= {"payTo", "amount", "asset", "network"}
112
+ assert body["quote"]["payTo"] == found["latest_probe"]["live_payTo"]
113
+ assert body["quote"]["amount"] == found["latest_probe"]["live_amount"]
114
+ posted = next(r for r in seen if r.url.path.endswith("/policy/check"))
115
+ assert posted.headers["authorization"] == f"Bearer {TOKEN}"
116
+ assert str(posted.url) == "https://botsrated.com/v1/policy/check"
117
+
118
+
119
+ def test_remote_pass_does_not_clear_a_local_block(found):
120
+ def policy(_request):
121
+ return 200, {"decision": "pass", **FRAMING}
122
+
123
+ guard, _seen = _payment_guard(found, policy, policy=POLICIES["strict"], remote_policy=RemotePolicy(TOKEN, "open"))
124
+ url = found["latest_probe"]["url"]
125
+ with guard.request(url):
126
+ decision = guard.decide(ctx(url, req(found, payTo=DEAD)))
127
+ assert decision.action == "block" and decision.policy_rule == "payToMismatch"
128
+ assert decision.remote_decision == "pass"
129
+ assert decision.decided_by == "your_policy"
130
+
131
+
132
+ def test_503_and_null_decision_follow_fail_mode_and_do_not_invent_a_pass(found):
133
+ url = found["latest_probe"]["url"]
134
+ cases = [
135
+ (503, {"decision": None, **FRAMING}),
136
+ (200, {"decision": None, "decided_by": "your_policy", "not_a_botsrated_rating": True}),
137
+ (404, {}),
138
+ (200, {"decision": "safe"}),
139
+ ]
140
+ for status, body in cases:
141
+ closed, _ = _payment_guard(found, lambda r, s=status, b=body: (s, b), remote_policy={"token": TOKEN, "fail_mode": "closed"})
142
+ with closed.request(url):
143
+ blocked = closed.decide(ctx(url, req(found)))
144
+ assert blocked.action == "block", (status, body)
145
+ assert blocked.remote_decision is None
146
+ assert any(r.code == "remote_policy_unavailable" and r.effect == "block" and "fail_mode is closed" in r.fact for r in blocked.reasons)
147
+ assert blocked.remote_decision != "pass"
148
+
149
+ opened, _ = _payment_guard(found, lambda r, s=status, b=body: (s, b), remote_policy={"token": TOKEN, "failMode": "open"})
150
+ with opened.request(url):
151
+ allowed = opened.decide(ctx(url, req(found)))
152
+ assert allowed.action == "allow", (status, body)
153
+ assert allowed.remote_decision is None
154
+ assert any(r.code == "remote_policy_unavailable" and r.effect == "info" and "fail_mode is open" in r.fact for r in allowed.reasons)
155
+
156
+ # A local block still stops the payment when fail_mode is open and the check returns nothing.
157
+ strict, _ = _payment_guard(
158
+ found,
159
+ lambda r: (503, {"decision": None}),
160
+ policy=POLICIES["strict"],
161
+ remote_policy={"token": TOKEN, "fail_mode": "open"},
162
+ )
163
+ with strict.request(url):
164
+ decision = strict.decide(ctx(url, req(found, payTo=DEAD)))
165
+ assert decision.action == "block" and decision.policy_rule == "payToMismatch"
166
+ assert decision.remote_decision is None
167
+
168
+
169
+ def test_null_decision_keeps_server_framing(found):
170
+ def policy(_request):
171
+ return 200, {"decision": None, "decided_by": "your_policy", "not_a_botsrated_rating": True, "policy_version": "4"}
172
+
173
+ guard, _seen = _payment_guard(found, policy, remote_policy={"token": TOKEN, "fail_mode": "open"})
174
+ url = found["latest_probe"]["url"]
175
+ with guard.request(url):
176
+ decision = guard.decide(ctx(url, req(found)))
177
+ assert decision.decided_by == "your_policy"
178
+ assert decision.not_a_botsrated_rating is True
179
+ assert decision.policy_version == "4"
180
+ assert decision.remote_decision is None
181
+
182
+
183
+ def test_policy_check_is_not_signed_and_ignores_a_returned_signature(found):
184
+ def policy(_request):
185
+ return 200, {"decision": "block", "signature": "PRODKEYSIG", **FRAMING}
186
+
187
+ guard, seen = _payment_guard(found, policy, remote_policy={"token": TOKEN, "fail_mode": "closed"})
188
+ url = found["latest_probe"]["url"] + "?api_key=SECRET123"
189
+ with guard.request(url):
190
+ decision = guard.decide(ctx(url, req(found)))
191
+ posted = [r for r in seen if r.url.path.endswith("/policy/check")]
192
+ assert len(posted) == 1
193
+ headers = {k.lower(): v for k, v in posted[0].headers.items()}
194
+ assert "payment-signature" not in headers
195
+ assert "x-payment" not in headers
196
+ raw = posted[0].content.decode()
197
+ assert "PRODKEYSIG" not in raw and "SECRET123" not in raw and "signature" not in raw
198
+ assert "PRODKEYSIG" not in decision.message
199
+ assert not hasattr(decision, "signature")
200
+ blob = json.dumps({"message": decision.message, "reasons": [r.fact for r in decision.reasons]})
201
+ assert TOKEN not in blob
202
+
203
+
204
+ def test_last_policy_version_is_remembered_when_the_next_check_fails(found):
205
+ calls = {"n": 0}
206
+
207
+ def policy(_request):
208
+ calls["n"] += 1
209
+ if calls["n"] == 1:
210
+ return 200, {"decision": "pass", "policy_version": "9", "decided_by": "your_policy", "not_a_botsrated_rating": True}
211
+ return 503, {"decision": None}
212
+
213
+ guard, _seen = _payment_guard(found, policy, remote_policy={"token": TOKEN, "fail_mode": "closed"})
214
+ url = found["latest_probe"]["url"]
215
+ with guard.request(url):
216
+ first = guard.decide(ctx(url, req(found)))
217
+ second = guard.decide(ctx(url, req(found)))
218
+ assert first.remote_decision == "pass" and first.policy_version == "9"
219
+ assert second.remote_decision is None and second.action == "block"
220
+ assert second.policy_version == "9"
221
+ assert guard.remote_policy_version == "9"
222
+
223
+
224
+ def test_custom_base_url_and_bad_config(found):
225
+ def policy(_request):
226
+ return 200, {"decision": "warn"}
227
+
228
+ guard, seen = _payment_guard(found, policy, remote_policy={"token": TOKEN, "fail_mode": "open", "baseUrl": "https://policy.example/v1/"})
229
+ url = found["latest_probe"]["url"]
230
+ with guard.request(url):
231
+ decision = guard.decide(ctx(url, req(found)))
232
+ assert decision.action == "allow"
233
+ assert any(r.code == "remote_policy" and r.effect == "warn" for r in decision.reasons)
234
+ posted = next(r for r in seen if r.url.path.endswith("/policy/check"))
235
+ assert str(posted.url) == "https://policy.example/v1/policy/check"
236
+
237
+ with pytest.raises(ValueError, match="fail_mode"):
238
+ PaymentGuard(hosted=False, remote_policy={"token": TOKEN})
239
+ with pytest.raises(ValueError, match="token"):
240
+ RemotePolicy("has space", "open")
241
+
242
+
243
+ def test_pre_payment_guard_block_wins_503_and_does_not_sign(found):
244
+ url = found["latest_probe"]["url"]
245
+
246
+ def block(_request):
247
+ return 200, {"decision": "block", **FRAMING, "signature": "PRODKEYSIG"}
248
+
249
+ guard, seen = _pre(found, block, remote_policy={"token": TOKEN, "fail_mode": "open"})
250
+ decision = guard.decide(url, req(found), request_url=url)
251
+ assert decision.action == "block"
252
+ assert decision.remote_decision == "block"
253
+ assert decision.decided_by == "your_policy" and decision.not_a_botsrated_rating is True
254
+ posted = next(r for r in seen if r.url.path.endswith("/policy/check"))
255
+ assert "payment-signature" not in {k.lower() for k in posted.headers}
256
+ assert "PRODKEYSIG" not in posted.content.decode()
257
+
258
+ def down(_request):
259
+ return 503, {"decision": None, "decided_by": "your_policy", "not_a_botsrated_rating": True}
260
+
261
+ closed, _ = _pre(found, down, remote_policy={"token": TOKEN, "fail_mode": "closed"})
262
+ blocked = closed.decide(url, req(found), request_url=url)
263
+ assert blocked.action == "block" and blocked.remote_decision is None
264
+ assert any("fail_mode is closed" in r.detail for r in blocked.reasons)
265
+
266
+ opened, _ = _pre(found, down, remote_policy={"token": TOKEN, "fail_mode": "open"})
267
+ allowed = opened.decide(url, req(found), request_url=url)
268
+ assert allowed.action == "allow" and allowed.remote_decision is None
269
+ assert any(r.effect == "info" and "fail_mode is open" in r.detail for r in allowed.reasons)
270
+
271
+ # Remote pass does not clear a local block.
272
+ passed, _ = _pre(found, lambda r: (200, {"decision": "pass"}), policy=STRICT_GUARD_POLICY, remote_policy={"token": TOKEN, "fail_mode": "open"})
273
+ still = passed.decide(url, req(found, payTo=DEAD), request_url=url)
274
+ assert still.action == "block" and still.remote_decision == "pass"
275
+
276
+
277
+ def test_interpret_policy_body_never_maps_a_null_to_pass():
278
+ effect = interpret_policy_body(503, {"decision": None}, "open", "blockrun.ai")
279
+ assert effect.decision is None and effect.effect == "info"
280
+ effect = interpret_policy_body(200, {"decision": None}, "closed", "blockrun.ai")
281
+ assert effect.decision is None and effect.effect == "block"
282
+ effect = interpret_policy_body(200, {"decision": "block"}, "open", "blockrun.ai")
283
+ assert effect.decision == "block"
284
+ effect = interpret_policy_body(None, {}, "closed", "blockrun.ai")
285
+ assert effect.decision is None and effect.effect == "block"
286
+
287
+
288
+ def test_async_payment_guard_applies_fail_mode(found):
289
+ import asyncio
290
+
291
+ seen, respond = _answer(found, lambda r: (503, {"decision": None}))
292
+ guard = PaymentGuard(async_http=httpx.AsyncClient(transport=httpx.MockTransport(respond)), remote_policy={"token": TOKEN, "fail_mode": "closed"})
293
+ url = found["latest_probe"]["url"]
294
+
295
+ async def run():
296
+ with guard.request(url):
297
+ return await guard.adecide(ctx(url, req(found)))
298
+
299
+ decision = asyncio.run(run())
300
+ assert decision.action == "block" and decision.remote_decision is None
301
+ assert any(r.url.path.endswith("/policy/check") for r in seen)
File without changes
File without changes
File without changes
File without changes