Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions sdk/python/src/b2a_sdk/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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:
Expand All @@ -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()
Expand Down
70 changes: 70 additions & 0 deletions sdk/python/tests/test_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import asyncio
import json
from datetime import datetime, timedelta
from importlib import import_module
from pathlib import Path

Expand Down Expand Up @@ -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
Loading