fiderail 2.3.1__tar.gz → 2.3.3__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,13 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fiderail
3
- Version: 2.3.1
3
+ Version: 2.3.3
4
4
  Summary: Non-custodial AI Agent payment control plane, pre-flight firewall, anti-sybil cloud client, and concurrent SQLite edge ledger (zero dependencies).
5
5
  Author-email: FideRail Contributors <founder@fiderail.com>
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://fiderail.com
8
8
  Project-URL: Documentation, https://fiderail.com/docs
9
9
  Project-URL: Repository, https://gitlab.com/fiderail/fiderail
10
- Project-URL: GitHub, https://github.com/fiderail/fiderail
11
10
  Project-URL: Issues, https://gitlab.com/fiderail/fiderail/-/issues
12
11
  Keywords: fiderail,ai-agent,payment-control-plane,firewall,x402,anti-sybil,base,solana,arbitrum,polygon,usdc,sqlite
13
12
  Classifier: Development Status :: 4 - Beta
@@ -83,6 +82,12 @@ result = client.guarded_x402_request(
83
82
 
84
83
  Omit `signer` to run a dry-run pre-flight check without executing a payment.
85
84
 
85
+ ## Important Integration Semantics
86
+
87
+ - **Strict blocking of unknown / low-trust addresses (including micro-payments)**: `DEFAULT_FIREWALL_POLICY` sets `allowUnknownMaxUsdc: 0.05` so unindexed or low-score addresses are permitted up to `$0.05 USDC` with `WARN`. **To hard-block all unknown or low-trust addresses including micro-payments, explicitly pass `allowUnknownMaxUsdc: 0` alongside `minTrustScore` in `policy`.**
88
+ - **`on_outage` scope**: **`on_outage` (`"fail-closed"` / `"fail-open-micro"`) applies only to `preflight_guard` and `guarded_x402_request`; `get_trust` always raises `RuntimeError` when the cloud oracle is unreachable and no fresh cache hit exists.**
89
+ - **Remote seller buyer-activity screening**: **Like `RemoteTrustClient.getPayerActivity` returning `null` remotely by default, remote seller-side buyer screening should call `POST /v1/trust-provider/before-settle`.**
90
+
86
91
  ## Included Modules & Helpers
87
92
 
88
93
  - `FideRailClient`: `get_health`, `get_trust`, `get_history`, `list_agents`, `discover_services`, `diagnose_endpoint`, `preflight_guard`, `guarded_x402_request`, `report_delivery_telemetry`
@@ -96,7 +101,6 @@ Omit `signer` to run a dry-run pre-flight check without executing a payment.
96
101
  - Documentation: [https://fiderail.com/docs](https://fiderail.com/docs)
97
102
  - REST API & Streamable HTTP MCP: [https://api.fiderail.com](https://api.fiderail.com)
98
103
  - Source (GitLab): [https://gitlab.com/fiderail/fiderail](https://gitlab.com/fiderail/fiderail)
99
- - Mirror (GitHub): [https://github.com/fiderail/fiderail](https://github.com/fiderail/fiderail)
100
104
  - Security & Contact: `security@fiderail.com` · `founder@fiderail.com`
101
105
 
102
106
  ## License
@@ -54,6 +54,12 @@ result = client.guarded_x402_request(
54
54
 
55
55
  Omit `signer` to run a dry-run pre-flight check without executing a payment.
56
56
 
57
+ ## Important Integration Semantics
58
+
59
+ - **Strict blocking of unknown / low-trust addresses (including micro-payments)**: `DEFAULT_FIREWALL_POLICY` sets `allowUnknownMaxUsdc: 0.05` so unindexed or low-score addresses are permitted up to `$0.05 USDC` with `WARN`. **To hard-block all unknown or low-trust addresses including micro-payments, explicitly pass `allowUnknownMaxUsdc: 0` alongside `minTrustScore` in `policy`.**
60
+ - **`on_outage` scope**: **`on_outage` (`"fail-closed"` / `"fail-open-micro"`) applies only to `preflight_guard` and `guarded_x402_request`; `get_trust` always raises `RuntimeError` when the cloud oracle is unreachable and no fresh cache hit exists.**
61
+ - **Remote seller buyer-activity screening**: **Like `RemoteTrustClient.getPayerActivity` returning `null` remotely by default, remote seller-side buyer screening should call `POST /v1/trust-provider/before-settle`.**
62
+
57
63
  ## Included Modules & Helpers
58
64
 
59
65
  - `FideRailClient`: `get_health`, `get_trust`, `get_history`, `list_agents`, `discover_services`, `diagnose_endpoint`, `preflight_guard`, `guarded_x402_request`, `report_delivery_telemetry`
@@ -67,7 +73,6 @@ Omit `signer` to run a dry-run pre-flight check without executing a payment.
67
73
  - Documentation: [https://fiderail.com/docs](https://fiderail.com/docs)
68
74
  - REST API & Streamable HTTP MCP: [https://api.fiderail.com](https://api.fiderail.com)
69
75
  - Source (GitLab): [https://gitlab.com/fiderail/fiderail](https://gitlab.com/fiderail/fiderail)
70
- - Mirror (GitHub): [https://github.com/fiderail/fiderail](https://github.com/fiderail/fiderail)
71
76
  - Security & Contact: `security@fiderail.com` · `founder@fiderail.com`
72
77
 
73
78
  ## License
@@ -8,7 +8,7 @@ import time
8
8
  import urllib.error
9
9
  import urllib.parse
10
10
  import urllib.request
11
- from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple
11
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Union
12
12
 
13
13
  from .ledger import SqliteSpendLedger
14
14
  from .policy import (
@@ -25,6 +25,7 @@ from .policy import (
25
25
  )
26
26
  from .spec import (
27
27
  API_BASE_URL,
28
+ SDK_VERSION,
28
29
  get_asset_spec,
29
30
  get_primary_asset,
30
31
  is_valid_address,
@@ -34,6 +35,15 @@ from .spec import (
34
35
  to_usd_amount,
35
36
  )
36
37
 
38
+ DEFAULT_USER_AGENT = f"FideRail-Python-SDK/{SDK_VERSION}"
39
+
40
+
41
+ def _with_default_user_agent(headers: Dict[str, str]) -> Dict[str, str]:
42
+ merged = dict(headers)
43
+ if not any(k.lower() == "user-agent" for k in merged):
44
+ merged["User-Agent"] = DEFAULT_USER_AGENT
45
+ return merged
46
+
37
47
 
38
48
  def parse_x402_challenge(headers: Dict[str, str], body_obj: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]:
39
49
  challenge = body_obj if isinstance(body_obj, dict) else None
@@ -109,7 +119,7 @@ class FideRailClient:
109
119
  def _request_json(self, method: str, path: str, body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
110
120
  url = f"{self.api_base_url}{path}"
111
121
  data = json.dumps(body).encode("utf-8") if body is not None else None
112
- headers = {"Accept": "application/json"}
122
+ headers = _with_default_user_agent({"Accept": "application/json"})
113
123
  if data is not None:
114
124
  headers["Content-Type"] = "application/json"
115
125
  req = urllib.request.Request(url, data=data, headers=headers, method=method)
@@ -309,7 +319,7 @@ class FideRailClient:
309
319
  auto_revoke_mandate_on_completion: bool = False,
310
320
  telemetry_opt_out: bool = False,
311
321
  task_id: Optional[str] = None,
312
- signer: Optional[Callable[[Dict[str, Any], Dict[str, Any]], str]] = None,
322
+ signer: Optional[Callable[[Dict[str, Any], Dict[str, Any]], Union[str, Dict[str, Any]]]] = None,
313
323
  ) -> Dict[str, Any]:
314
324
  req_headers = dict(headers or {})
315
325
  effective = clamp_policy(self.host_policy, policy) if self.host_policy else dict(policy or {})
@@ -332,7 +342,7 @@ class FideRailClient:
332
342
  return {"paid": False, "blocked": True, "decision": "BLOCK", "reason": "CIRCUIT_BREAKER_OPEN"}
333
343
 
334
344
  def _http_call(extra_headers: Optional[Dict[str, str]] = None) -> Tuple[int, Dict[str, str], str]:
335
- all_headers = {**req_headers, **(extra_headers or {})}
345
+ all_headers = _with_default_user_agent({**req_headers, **(extra_headers or {})})
336
346
  payload = serialize_body(body).encode("utf-8") if body is not None else None
337
347
  req = urllib.request.Request(url, data=payload, headers=all_headers, method=method)
338
348
  try:
@@ -442,8 +452,64 @@ class FideRailClient:
442
452
  return {"paid": False, "blocked": True, "decision": "BLOCK", "reason": "EXCEEDS_DAILY_BUDGET"}
443
453
 
444
454
  res_id = res["reservationId"]
455
+ frozen_quote = {**chosen, "quoteDigest": quote_digest}
445
456
  try:
446
- proof = signer({**chosen, "quoteDigest": quote_digest}, guard)
457
+ signed = signer(dict(frozen_quote), guard)
458
+ if isinstance(signed, dict):
459
+ top_digest = signed.get("quoteDigest") or signed.get("quote_digest")
460
+ if top_digest and str(top_digest) != quote_digest:
461
+ return {
462
+ "paid": False,
463
+ "blocked": True,
464
+ "readyToSign": False,
465
+ "decision": "BLOCK",
466
+ "reason": "QUOTE_TAMPERING_DETECTED",
467
+ "quoteDigest": quote_digest,
468
+ "paymentOption": frozen_quote,
469
+ "guard": guard,
470
+ "spentTodayUsdc": self.ledger.get_spent_today_usdc(),
471
+ }
472
+ bq = signed.get("boundQuote")
473
+ if bq is None:
474
+ bq = signed.get("bound_quote")
475
+ if isinstance(bq, dict):
476
+ bq_pay_to = bq.get("payTo") if bq.get("payTo") is not None else bq.get("pay_to")
477
+ bq_amount = bq.get("amountUsdc") if bq.get("amountUsdc") is not None else bq.get("amount_usdc")
478
+ bq_digest = bq.get("quoteDigest") or bq.get("quote_digest")
479
+ try:
480
+ amount_mismatch = bq_amount is None or abs(float(bq_amount) - float(chosen["amountUsdc"])) > 1e-12
481
+ except (TypeError, ValueError):
482
+ amount_mismatch = True
483
+ mismatch = (
484
+ normalize_chain_address(chosen["chain"], str(bq_pay_to or "")) != chosen["payTo"]
485
+ or amount_mismatch
486
+ or (bq.get("asset") or None) != (chosen["asset"] or None)
487
+ or (bool(bq_digest) and str(bq_digest) != quote_digest)
488
+ )
489
+ if mismatch:
490
+ return {
491
+ "paid": False,
492
+ "blocked": True,
493
+ "readyToSign": False,
494
+ "decision": "BLOCK",
495
+ "reason": "QUOTE_TAMPERING_DETECTED",
496
+ "quoteDigest": quote_digest,
497
+ "paymentOption": frozen_quote,
498
+ "guard": guard,
499
+ "spentTodayUsdc": self.ledger.get_spent_today_usdc(),
500
+ }
501
+ proof = (
502
+ signed.get("paymentHeader")
503
+ or signed.get("payment_header")
504
+ or signed.get("xPayment")
505
+ or signed.get("headerValue")
506
+ )
507
+ elif isinstance(signed, str):
508
+ proof = signed
509
+ else:
510
+ proof = None
511
+ if not proof or not isinstance(proof, str):
512
+ raise RuntimeError("Local signer did not return a payment proof header value.")
447
513
  t0 = time.time()
448
514
  paid_status, _, paid_body = _http_call({"X-PAYMENT": proof, "PAYMENT-SIGNATURE": proof})
449
515
  latency_ms = int((time.time() - t0) * 1000)
@@ -124,9 +124,15 @@ def compute_quote_digest(
124
124
  method: str = "GET",
125
125
  body_hash: str = "",
126
126
  asset: Optional[str] = None,
127
+ body: Any = None,
127
128
  ) -> str:
129
+ resolved_body_hash = (
130
+ body_hash
131
+ if body_hash
132
+ else (sha256_hex(serialize_body(body)) if body is not None else "")
133
+ )
128
134
  return sha256_hex(
129
- f"{method.upper()}|{url}|{body_hash or ''}|{chain}|{pay_to}|{asset or ''}|{float(amount_usdc):.6f}"
135
+ f"{method.upper()}|{url}|{resolved_body_hash}|{chain}|{pay_to}|{asset or ''}|{float(amount_usdc):.6f}"
130
136
  )
131
137
 
132
138
 
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  import re
6
6
  from typing import Any, Dict, List, Optional, Tuple
7
7
 
8
- SDK_VERSION = "2.3.1"
8
+ SDK_VERSION = "2.3.3"
9
9
  API_BASE_URL = "https://api.fiderail.com"
10
10
  EUR_USD_DEFAULT_RATE = 1.08
11
11
 
@@ -1,13 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fiderail
3
- Version: 2.3.1
3
+ Version: 2.3.3
4
4
  Summary: Non-custodial AI Agent payment control plane, pre-flight firewall, anti-sybil cloud client, and concurrent SQLite edge ledger (zero dependencies).
5
5
  Author-email: FideRail Contributors <founder@fiderail.com>
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://fiderail.com
8
8
  Project-URL: Documentation, https://fiderail.com/docs
9
9
  Project-URL: Repository, https://gitlab.com/fiderail/fiderail
10
- Project-URL: GitHub, https://github.com/fiderail/fiderail
11
10
  Project-URL: Issues, https://gitlab.com/fiderail/fiderail/-/issues
12
11
  Keywords: fiderail,ai-agent,payment-control-plane,firewall,x402,anti-sybil,base,solana,arbitrum,polygon,usdc,sqlite
13
12
  Classifier: Development Status :: 4 - Beta
@@ -83,6 +82,12 @@ result = client.guarded_x402_request(
83
82
 
84
83
  Omit `signer` to run a dry-run pre-flight check without executing a payment.
85
84
 
85
+ ## Important Integration Semantics
86
+
87
+ - **Strict blocking of unknown / low-trust addresses (including micro-payments)**: `DEFAULT_FIREWALL_POLICY` sets `allowUnknownMaxUsdc: 0.05` so unindexed or low-score addresses are permitted up to `$0.05 USDC` with `WARN`. **To hard-block all unknown or low-trust addresses including micro-payments, explicitly pass `allowUnknownMaxUsdc: 0` alongside `minTrustScore` in `policy`.**
88
+ - **`on_outage` scope**: **`on_outage` (`"fail-closed"` / `"fail-open-micro"`) applies only to `preflight_guard` and `guarded_x402_request`; `get_trust` always raises `RuntimeError` when the cloud oracle is unreachable and no fresh cache hit exists.**
89
+ - **Remote seller buyer-activity screening**: **Like `RemoteTrustClient.getPayerActivity` returning `null` remotely by default, remote seller-side buyer screening should call `POST /v1/trust-provider/before-settle`.**
90
+
86
91
  ## Included Modules & Helpers
87
92
 
88
93
  - `FideRailClient`: `get_health`, `get_trust`, `get_history`, `list_agents`, `discover_services`, `diagnose_endpoint`, `preflight_guard`, `guarded_x402_request`, `report_delivery_telemetry`
@@ -96,7 +101,6 @@ Omit `signer` to run a dry-run pre-flight check without executing a payment.
96
101
  - Documentation: [https://fiderail.com/docs](https://fiderail.com/docs)
97
102
  - REST API & Streamable HTTP MCP: [https://api.fiderail.com](https://api.fiderail.com)
98
103
  - Source (GitLab): [https://gitlab.com/fiderail/fiderail](https://gitlab.com/fiderail/fiderail)
99
- - Mirror (GitHub): [https://github.com/fiderail/fiderail](https://github.com/fiderail/fiderail)
100
104
  - Security & Contact: `security@fiderail.com` · `founder@fiderail.com`
101
105
 
102
106
  ## License
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "fiderail"
7
- version = "2.3.1"
7
+ version = "2.3.3"
8
8
  description = "Non-custodial AI Agent payment control plane, pre-flight firewall, anti-sybil cloud client, and concurrent SQLite edge ledger (zero dependencies)."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -47,7 +47,6 @@ classifiers = [
47
47
  Homepage = "https://fiderail.com"
48
48
  Documentation = "https://fiderail.com/docs"
49
49
  Repository = "https://gitlab.com/fiderail/fiderail"
50
- GitHub = "https://github.com/fiderail/fiderail"
51
50
  Issues = "https://gitlab.com/fiderail/fiderail/-/issues"
52
51
 
53
52
  [tool.setuptools.packages.find]
@@ -24,11 +24,14 @@ from fiderail import ( # noqa: E402
24
24
  FideRailClient,
25
25
  SqliteSpendLedger,
26
26
  clamp_policy,
27
+ compute_quote_digest,
27
28
  create_salted_receipt_v2,
28
29
  scan_outbound_secrets,
30
+ sha256_hex,
29
31
  validate_mandate_chain,
30
32
  verify_salted_receipt_v2,
31
33
  )
34
+ from fiderail.policy import serialize_body # noqa: E402
32
35
 
33
36
 
34
37
  class FideRailPythonSdkTests(unittest.TestCase):
@@ -384,6 +387,221 @@ class FideRailPythonSdkTests(unittest.TestCase):
384
387
  dead_closed.close()
385
388
  dead_micro.close()
386
389
 
390
+ def test_compute_quote_digest_body_and_quote_tampering_detected(self) -> None:
391
+ payload = {"task": "summarize", "count": 2}
392
+ body_hash = sha256_hex(serialize_body(payload))
393
+ digest_from_hash = compute_quote_digest(
394
+ method="POST",
395
+ url="https://api.vendor.example/run",
396
+ body_hash=body_hash,
397
+ chain="base",
398
+ pay_to="0x7284d41b5b852f2bd4c99bdf95043d84452d299c",
399
+ asset="USDC",
400
+ amount_usdc=0.05,
401
+ )
402
+ digest_from_body = compute_quote_digest(
403
+ method="POST",
404
+ url="https://api.vendor.example/run",
405
+ body=payload,
406
+ chain="base",
407
+ pay_to="0x7284d41b5b852f2bd4c99bdf95043d84452d299c",
408
+ asset="USDC",
409
+ amount_usdc=0.05,
410
+ )
411
+ self.assertEqual(digest_from_body, digest_from_hash)
412
+
413
+ custom_hash = "ab" * 32
414
+ self.assertEqual(
415
+ compute_quote_digest(
416
+ url="https://api.vendor.example/run",
417
+ body_hash=custom_hash,
418
+ body=payload,
419
+ chain="base",
420
+ pay_to="0x7284d41b5b852f2bd4c99bdf95043d84452d299c",
421
+ amount_usdc=0.05,
422
+ ),
423
+ compute_quote_digest(
424
+ url="https://api.vendor.example/run",
425
+ body_hash=custom_hash,
426
+ chain="base",
427
+ pay_to="0x7284d41b5b852f2bd4c99bdf95043d84452d299c",
428
+ amount_usdc=0.05,
429
+ ),
430
+ )
431
+
432
+ good_payee = "0x7284d41b5b852f2bd4c99bdf95043d84452d299c"
433
+ attacker_payee = "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
434
+ paid_calls = {"count": 0}
435
+
436
+ class MockHandler(http.server.BaseHTTPRequestHandler):
437
+ def log_message(self, format: str, *args) -> None: # noqa: A002
438
+ pass
439
+
440
+ def do_GET(self) -> None:
441
+ if self.path.startswith("/v1/trust/base/"):
442
+ body = json.dumps(
443
+ {
444
+ "found": True,
445
+ "chain": "base",
446
+ "address": good_payee,
447
+ "creditScore": 91,
448
+ "tier": "HIGH_TRUST",
449
+ "riskFlags": [],
450
+ }
451
+ ).encode("utf-8")
452
+ self.send_response(200)
453
+ self.send_header("Content-Type", "application/json")
454
+ self.end_headers()
455
+ self.wfile.write(body)
456
+ return
457
+
458
+ if self.path.startswith("/paid"):
459
+ if self.headers.get("X-PAYMENT") == "bound-py-proof":
460
+ paid_calls["count"] += 1
461
+ self.send_response(200)
462
+ self.send_header("Content-Type", "application/json")
463
+ self.end_headers()
464
+ self.wfile.write(json.dumps({"ok": True}).encode("utf-8"))
465
+ return
466
+ challenge = {
467
+ "x402Version": 2,
468
+ "accepts": [
469
+ {
470
+ "scheme": "exact",
471
+ "network": "eip155:8453",
472
+ "asset": CHAIN_SPECS["base"]["assets"][0]["contract"],
473
+ "payTo": good_payee,
474
+ "amount": "50000",
475
+ }
476
+ ],
477
+ }
478
+ encoded = base64.b64encode(json.dumps(challenge).encode("utf-8")).decode("utf-8")
479
+ self.send_response(402)
480
+ self.send_header("Content-Type", "application/json")
481
+ self.send_header("PAYMENT-REQUIRED", encoded)
482
+ self.end_headers()
483
+ self.wfile.write(json.dumps(challenge).encode("utf-8"))
484
+ return
485
+
486
+ self.send_response(404)
487
+ self.end_headers()
488
+
489
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), MockHandler)
490
+ port = server.server_address[1]
491
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
492
+ thread.start()
493
+ client = FideRailClient(f"http://127.0.0.1:{port}", cache_ttl_ms=60000)
494
+ try:
495
+ # 1. Tampered boundQuote.payTo -> QUOTE_TAMPERING_DETECTED, 0 paid calls, reservation released
496
+ tampered_payee = client.guarded_x402_request(
497
+ f"http://127.0.0.1:{port}/paid?case=payee",
498
+ telemetry_opt_out=True,
499
+ signer=lambda quote, guard: {
500
+ "paymentHeader": "bound-py-proof",
501
+ "boundQuote": {
502
+ "payTo": attacker_payee,
503
+ "amountUsdc": quote["amountUsdc"],
504
+ "asset": quote["asset"],
505
+ "quoteDigest": quote["quoteDigest"],
506
+ },
507
+ },
508
+ )
509
+ self.assertTrue(tampered_payee["blocked"])
510
+ self.assertEqual(tampered_payee["reason"], "QUOTE_TAMPERING_DETECTED")
511
+ self.assertEqual(paid_calls["count"], 0)
512
+ self.assertEqual(client.ledger.get_effective_spent_today_usdc(), 0.0)
513
+
514
+ # 2. Tampered boundQuote.amountUsdc -> QUOTE_TAMPERING_DETECTED
515
+ tampered_amt = client.guarded_x402_request(
516
+ f"http://127.0.0.1:{port}/paid?case=amount",
517
+ telemetry_opt_out=True,
518
+ signer=lambda quote, guard: {
519
+ "paymentHeader": "bound-py-proof",
520
+ "boundQuote": {
521
+ "payTo": quote["payTo"],
522
+ "amountUsdc": 0.99,
523
+ "asset": quote["asset"],
524
+ },
525
+ },
526
+ )
527
+ self.assertTrue(tampered_amt["blocked"])
528
+ self.assertEqual(tampered_amt["reason"], "QUOTE_TAMPERING_DETECTED")
529
+ self.assertEqual(paid_calls["count"], 0)
530
+
531
+ # 3. Tampered top-level quoteDigest -> QUOTE_TAMPERING_DETECTED
532
+ tampered_digest = client.guarded_x402_request(
533
+ f"http://127.0.0.1:{port}/paid?case=digest",
534
+ telemetry_opt_out=True,
535
+ signer=lambda quote, guard: {
536
+ "paymentHeader": "bound-py-proof",
537
+ "quoteDigest": "0" * 64,
538
+ },
539
+ )
540
+ self.assertTrue(tampered_digest["blocked"])
541
+ self.assertEqual(tampered_digest["reason"], "QUOTE_TAMPERING_DETECTED")
542
+ self.assertEqual(paid_calls["count"], 0)
543
+
544
+ # 4. Exact boundQuote & quoteDigest match succeeds
545
+ ok = client.guarded_x402_request(
546
+ f"http://127.0.0.1:{port}/paid?case=ok",
547
+ telemetry_opt_out=True,
548
+ signer=lambda quote, guard: {
549
+ "paymentHeader": "bound-py-proof",
550
+ "quoteDigest": quote["quoteDigest"],
551
+ "boundQuote": {
552
+ "payTo": quote["payTo"],
553
+ "amountUsdc": quote["amountUsdc"],
554
+ "asset": quote["asset"],
555
+ "quoteDigest": quote["quoteDigest"],
556
+ },
557
+ },
558
+ )
559
+ self.assertTrue(ok["paid"])
560
+ self.assertTrue(ok["delivered"])
561
+ self.assertEqual(paid_calls["count"], 1)
562
+ finally:
563
+ client.close()
564
+ server.shutdown()
565
+ server.server_close()
566
+
567
+ def test_09_custom_user_agent_header(self) -> None:
568
+ observed_uas = []
569
+
570
+ class UaHandler(http.server.BaseHTTPRequestHandler):
571
+ def log_message(self, format: str, *args) -> None: # noqa: A002
572
+ pass
573
+
574
+ def do_GET(self) -> None:
575
+ observed_uas.append((self.path, self.headers.get("User-Agent")))
576
+ if self.path == "/healthz":
577
+ self.send_response(200)
578
+ self.send_header("Content-Type", "application/json")
579
+ self.end_headers()
580
+ self.wfile.write(json.dumps({"status": "ok"}).encode("utf-8"))
581
+ return
582
+ self.send_response(200)
583
+ self.send_header("Content-Type", "application/json")
584
+ self.end_headers()
585
+ self.wfile.write(json.dumps({"ok": True}).encode("utf-8"))
586
+
587
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), UaHandler)
588
+ port = server.server_address[1]
589
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
590
+ thread.start()
591
+ client = FideRailClient(f"http://127.0.0.1:{port}")
592
+ try:
593
+ client.get_health()
594
+ client.guarded_x402_request(f"http://127.0.0.1:{port}/free", telemetry_opt_out=True)
595
+ expected_ua = f"FideRail-Python-SDK/{fiderail.SDK_VERSION}"
596
+ self.assertEqual(len(observed_uas), 2)
597
+ for req_path, ua in observed_uas:
598
+ self.assertEqual(ua, expected_ua, f"Unexpected User-Agent on {req_path}: {ua}")
599
+ self.assertFalse((ua or "").startswith("Python-urllib/"))
600
+ finally:
601
+ client.close()
602
+ server.shutdown()
603
+ server.server_close()
604
+
387
605
 
388
606
  if __name__ == "__main__":
389
607
  unittest.main()
File without changes
File without changes
File without changes
File without changes
File without changes