From c7fb719c80726fb487cccfae3191a98417351917 Mon Sep 17 00:00:00 2001 From: CS Date: Wed, 11 Nov 2026 17:43:16 -0800 Subject: [PATCH] fix(sdk): Receipt.verify() treats a naive created_at as UTC (#358) The gateway signs created_at with an explicit offset, but on SQLite the receipt it returns from MCP, replay and GET /v1/receipts/{id} carries a naive timestamp. Receipt.verify() compared the two datetimes directly, and an aware datetime never equals a naive one, so every genuine receipt returned MISMATCH and the README short tool call example failed. Normalize both sides to an aware UTC instant before comparing. Gateway timestamps are always UTC, so a naive value is read as UTC. A different instant, or the same wall time under another offset, still mismatches. Fixes #358 Co-Authored-By: Claude Opus 5.5 Signed-off-by: CS --- sdk/python/src/b2a_sdk/models.py | 24 ++++++++--- sdk/python/tests/test_call.py | 70 ++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 5 deletions(-) diff --git a/sdk/python/src/b2a_sdk/models.py b/sdk/python/src/b2a_sdk/models.py index 9885587b4..d9f846ee7 100644 --- a/sdk/python/src/b2a_sdk/models.py +++ b/sdk/python/src/b2a_sdk/models.py @@ -5,7 +5,7 @@ import re from collections.abc import Mapping from dataclasses import dataclass, field -from datetime import datetime +from datetime import datetime, timezone from decimal import Decimal, InvalidOperation from typing import Any @@ -49,6 +49,18 @@ def _datetime(value: Any, key: str) -> datetime: return datetime.fromisoformat(value.replace("Z", "+00:00")) +def _utc_instant(value: datetime) -> datetime: + """Return an aware datetime so naive and offset forms of one instant compare equal. + + The gateway signs ``created_at`` with an explicit offset, but some storage + backends (SQLite) return the stored receipt without one. Every gateway + timestamp is UTC, so a naive value is read as UTC. + """ + if value.tzinfo is None or value.utcoffset() is None: + return value.replace(tzinfo=timezone.utc) + return value + + def _decimal(value: Any, key: str) -> Decimal: try: return Decimal(str(value)) @@ -258,9 +270,9 @@ def mismatch() -> VerificationResult: Decimal(str(result.claims.get("credits_authorized"))) == self.credits_authorized and Decimal(str(result.claims.get("credits_charged"))) == self.credits_charged ) - date_matches = ( - _datetime(result.claims.get("created_at"), "created_at") == self.created_at - ) + date_matches = _utc_instant( + _datetime(result.claims.get("created_at"), "created_at") + ) == _utc_instant(self.created_at) except (InvalidOperation, ValueError): return mismatch() if not amounts_match or not date_matches: @@ -278,7 +290,9 @@ def mismatch() -> VerificationResult: return mismatch() elif name == "created_at": try: - if _datetime(value, name) != _datetime(signed_value, name): + if _utc_instant(_datetime(value, name)) != _utc_instant( + _datetime(signed_value, name) + ): return mismatch() except ValueError: return mismatch() diff --git a/sdk/python/tests/test_call.py b/sdk/python/tests/test_call.py index 4331b0c68..f321e03f6 100644 --- a/sdk/python/tests/test_call.py +++ b/sdk/python/tests/test_call.py @@ -4,6 +4,7 @@ import asyncio import json +from datetime import datetime, timedelta from importlib import import_module from pathlib import Path @@ -277,3 +278,72 @@ async def handler(request: httpx.Request) -> httpx.Response: else VerificationStatus.UNKNOWN_KEY ) assert receipt.verify().status is expected_status + + +def _naive(timestamp: str) -> str: + """Drop the UTC offset the way a SQLite-backed gateway returns stored receipts.""" + assert timestamp.endswith("+00:00") + return timestamp.removesuffix("+00:00") + + +@pytest.mark.parametrize("sdk_name", ["b2a_sdk", "amw"]) +def test_call_verify_accepts_receipt_with_naive_created_at(sdk_name: str) -> None: + """Issue #358: a stored receipt without an offset still matches its signed claim.""" + pytest.importorskip("cryptography") + sdk = import_module(sdk_name) + payload = _receipt_payload() + payload["created_at"] = _naive(SIGNED_CLAIMS["created_at"]) + + async def handler(request: httpx.Request) -> httpx.Response: + if request.url.path != "/mcp/messages": + return _evidence_response(request) + return httpx.Response( + 200, + json={ + "jsonrpc": "2.0", + "id": request.headers["idempotency-key"], + "result": { + "content": [{"type": "text", "text": '{"ok": true}'}], + "isError": False, + "receipt": payload, + }, + }, + ) + + with sdk.Client( + "YOUR_DEMO_KEY", base_url="http://test", transport=httpx.MockTransport(handler) + ) as client: + receipt = client.call( + SIGNED_CLAIMS["tool"], + {"message": "hi"}, + key="order-123", + wallet_id=SIGNED_CLAIMS["wallet_id"], + permit_id=SIGNED_CLAIMS["permit_id"], + ) + + result = receipt.verify() + assert result.status is sdk.VerificationStatus.VERIFIED + assert result.ok + + +def test_verify_rejects_naive_created_at_for_a_different_instant() -> None: + pytest.importorskip("cryptography") + raw = _receipt_payload() + signed = datetime.fromisoformat(SIGNED_CLAIMS["created_at"]) + raw["created_at"] = (signed + timedelta(seconds=1)).replace(tzinfo=None).isoformat() + receipt = Receipt.from_dict(raw) + + result = receipt.verify(bundle=VALID_BUNDLE, keys=KEYS) + + assert result.status is VerificationStatus.MISMATCH + + +def test_verify_rejects_created_at_with_a_different_offset() -> None: + pytest.importorskip("cryptography") + raw = _receipt_payload() + raw["created_at"] = _naive(SIGNED_CLAIMS["created_at"]) + "+02:00" + receipt = Receipt.from_dict(raw) + + result = receipt.verify(bundle=VALID_BUNDLE, keys=KEYS) + + assert result.status is VerificationStatus.MISMATCH