From a87de854f4b58c913042885bd0ad4bfbbc211b4a Mon Sep 17 00:00:00 2001 From: Ivanli Trading Date: Wed, 18 Nov 2026 19:10:59 -0300 Subject: [PATCH] feat(sdk-python): pre-sign x402 policy hook with the same guarantees as the TS SDK --- packages/sdk-python/src/nirium/__init__.py | 12 + packages/sdk-python/src/nirium/client.py | 83 ++++- packages/sdk-python/src/nirium/x402_policy.py | 345 ++++++++++++++++++ packages/sdk-python/tests/test_x402_policy.py | 302 +++++++++++++++ .../tests/test_x402_policy_client.py | 127 +++++++ 5 files changed, 864 insertions(+), 5 deletions(-) create mode 100644 packages/sdk-python/src/nirium/x402_policy.py create mode 100644 packages/sdk-python/tests/test_x402_policy.py create mode 100644 packages/sdk-python/tests/test_x402_policy_client.py diff --git a/packages/sdk-python/src/nirium/__init__.py b/packages/sdk-python/src/nirium/__init__.py index 35f7b7a7..80762c70 100644 --- a/packages/sdk-python/src/nirium/__init__.py +++ b/packages/sdk-python/src/nirium/__init__.py @@ -9,6 +9,13 @@ X402NetworkMismatchError, X402SpendCapError, ) +from .x402_policy import ( # type: ignore + PolicyContext, + PolicyDecision, + PolicyResult, + X402PolicyError, + run_policy_gate, +) if TYPE_CHECKING: from .langchain_tools import NiriumX402Tool, create_nirium_x402_tool @@ -20,6 +27,11 @@ "WebSocketStatus", "X402NetworkMismatchError", "X402SpendCapError", + "X402PolicyError", + "PolicyContext", + "PolicyDecision", + "PolicyResult", + "run_policy_gate", "NiriumX402Tool", "create_nirium_x402_tool", ] diff --git a/packages/sdk-python/src/nirium/client.py b/packages/sdk-python/src/nirium/client.py index b053953a..42575858 100644 --- a/packages/sdk-python/src/nirium/client.py +++ b/packages/sdk-python/src/nirium/client.py @@ -18,7 +18,9 @@ from stellar_sdk import Keypair, Network, Server, TransactionBuilder, Asset # type: ignore from stellar_sdk import Account, Address, SorobanServer, scval # type: ignore from stellar_sdk.xdr import SorobanTransactionData # type: ignore -from stellar_sdk.auth import authorize_entry # type: ignore +from stellar_sdk.auth import authorize_entry + +from .x402_policy import X402PolicyError, build_context, run_policy_gate # type: ignore import base64 as _b64 import math as _math @@ -743,6 +745,7 @@ def init_x402( rpc_url: str = "", max_amount_per_payment: Any = _X402_DEFAULT_MAX_AMOUNT, approve: Optional[X402Approver] = None, + policy: Optional[Any] = None, ): """ Initialize the x402 pay-per-request client (protocol v2). @@ -761,6 +764,14 @@ def init_x402( approve: Optional callback (sync or async). It receives the payment option (url, network, asset, payTo, amount) whenever the cap cannot accept it on its own, and must return True to sign. + policy: Optional pre-sign policy hook, the same guarantees as the + TypeScript SDK. Either an object with ``evaluate(context)`` + (plus optional ``current_version`` / ``on_decision`` / + ``timeout_ms`` / ``require_expires_at``) or a plain callable + receiving the context. It runs after the spend-cap check and + immediately before signing; DENY, WAIT, a stale or unbound + answer and a timeout all raise ``X402PolicyError`` without + touching the signer. A 402 whose options are all on a different network than ``network`` is always refused: the client never falls back to another network. @@ -772,10 +783,16 @@ def init_x402( ) if approve is not None and not callable(approve): raise ValueError("approve must be a callable or None") + if policy is not None and not (callable(policy) or callable(getattr(policy, "evaluate", None))): + raise ValueError("policy must be a callable or expose a callable evaluate()") cap = _parse_usd_cap(max_amount_per_payment) self._x402_cap_label = f"${cap.normalize():f}" self._x402_cap_atomic = int(cap * (10 ** _X402_USDC_DECIMALS)) self._x402_approve = approve + self._x402_policy = policy + self._x402_policy_require_expires = ( + None if policy is None else getattr(policy, "require_expires_at", None) + ) is_testnet = network == "stellar:testnet" self._x402_keypair = Keypair.from_secret(secret_key) self._x402_network = network @@ -801,6 +818,7 @@ async def _x402_select_requirement( is signed only if the ``approve`` callback returns True. """ network = self._x402_network + self._x402_pending_url = url on_network = [ a for a in accepts if isinstance(a, dict) and a.get("network") == network @@ -911,10 +929,7 @@ def _x402_build_transaction(self, accepted: Dict[str, Any]) -> str: prepared = soroban.prepare_transaction(tx) op = prepared.transaction.operations[0] - op.auth = [ - authorize_entry(e, self._x402_keypair, max_ledger, self._x402_passphrase) - for e in (op.auth or []) - ] + op.auth = self._x402_authorize_entries(list(op.auth or []), accepted, max_ledger) sim = soroban.simulate_transaction(prepared) if getattr(sim, "error", None): @@ -926,6 +941,64 @@ def _x402_build_transaction(self, accepted: Dict[str, Any]) -> str: prepared.transaction.fee = 100 + int(sim.min_resource_fee) return prepared.to_xdr() + def _x402_authorize_entries( + self, + entries: List[Any], + accepted: Dict[str, Any], + max_ledger: int, + ) -> List[Any]: + """Sign the Soroban authorization entries, or refuse without signing. + + Without a policy this is exactly the previous behaviour. With a policy + every entry goes through :func:`nirium.x402_policy.run_policy_gate`, so + a DENY, a WAIT, a stale/unbound answer or a timeout raises + ``X402PolicyError`` and the signer is never called. + """ + policy = getattr(self, "_x402_policy", None) + signed: List[Any] = [] + for entry in entries: + def sign_one(e: Any = entry) -> Any: + return authorize_entry( + e, self._x402_keypair, max_ledger, self._x402_passphrase + ) + + if policy is None: + signed.append(sign_one()) + continue + to_xdr = getattr(entry, "to_xdr", None) + payload_hash = hashlib.sha256( + to_xdr() if callable(to_xdr) else repr(entry).encode("utf-8") + ).hexdigest() + context = build_context( + url=getattr(self, "_x402_pending_url", ""), + method=getattr(self, "_x402_pending_method", "GET"), + requirements={ + "scheme": accepted.get("scheme"), + "network": accepted.get("network"), + "asset": accepted.get("asset"), + "payTo": accepted.get("payTo"), + "amount": accepted.get("amount"), + "maxTimeoutSeconds": accepted.get("maxTimeoutSeconds"), + }, + authorization={ + "payloadHash": payload_hash, + "payloadType": "soroban-authorization-entry", + "from": self._x402_keypair.public_key, + "to": accepted.get("payTo"), + "amount": accepted.get("amount"), + "maxLedger": max_ledger, + }, + signer=self._x402_keypair.public_key, + ) + gate = run_policy_gate( + policy, + context, + sign_one, + require_expires_at=getattr(self, "_x402_policy_require_expires", None), + ) + signed.append(gate.value) + return signed + def _x402_http_payload(self, body: Optional[Any]) -> Dict[str, Any]: if body is None: return {} diff --git a/packages/sdk-python/src/nirium/x402_policy.py b/packages/sdk-python/src/nirium/x402_policy.py new file mode 100644 index 00000000..bbe02f91 --- /dev/null +++ b/packages/sdk-python/src/nirium/x402_policy.py @@ -0,0 +1,345 @@ +"""Pre-sign policy gate for x402 payments. + +Python parity with ``packages/sdk/src/x402-policy.ts``: a decision engine +(``ALLOW`` / ``DENY`` / ``WAIT``) runs **before** the Stellar authorization +entry is signed and can refuse it without ever touching the signer. + +The guarantees, in the same order the TypeScript hook applies them: + +1. ``DENY`` and ``WAIT`` never reach the signer. +2. An ``ALLOW`` is bound to the exact authorization it approved: the + decision must echo the ``context_hash`` it was given (``UNBOUND`` + otherwise), so an answer cached for a different payment cannot sign. +3. ``expires_at`` is enforced: a decision that is already expired at + signing time is refused (``EXPIRED``), and equality counts as expired. +4. Malformed answers (``None``, unknown verdict, non-numeric ``expires_at``, + missing ``policy_version`` when a version is expected) are refused + (``MALFORMED``) instead of being coerced. +5. A hard deadline covers ``evaluate`` *and* the freshness check (``TIMEOUT``). +6. The policy version is re-read after the ``ALLOW`` and right before + signing; a mismatch (``STALE``), a failure to read it + (``VERSION_UNAVAILABLE``) or an empty value also refuses. + +This module is standard library only on purpose: the policy engine must be +importable (and testable) without ``stellar-sdk`` installed. +""" + +from __future__ import annotations + +import asyncio +import concurrent.futures +import hashlib +import inspect +import time +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence + +CONTEXT_VERSION = 1 +DEFAULT_TIMEOUT_MS = 5000 + +VERDICTS = ("ALLOW", "DENY", "WAIT") + +ALLOWED = "ALLOWED" +SIGNED = "SIGNED" +SIGNER_ERROR = "SIGNER_ERROR" +DENY = "DENY" +WAIT = "WAIT" +TIMEOUT = "TIMEOUT" +EXPIRED = "EXPIRED" +UNBOUND = "UNBOUND" +MALFORMED = "MALFORMED" +STALE = "STALE" +VERSION_UNAVAILABLE = "VERSION_UNAVAILABLE" + +OUTCOMES = ( + ALLOWED, + SIGNED, + SIGNER_ERROR, + DENY, + WAIT, + TIMEOUT, + EXPIRED, + UNBOUND, + MALFORMED, + STALE, + VERSION_UNAVAILABLE, +) + + +class X402PolicyError(RuntimeError): + """Raised when the policy refuses to sign. + + ``outcome`` is one of :data:`OUTCOMES` and is stable enough to assert on. + """ + + def __init__(self, outcome: str, message: str = "", records: Optional[Sequence[str]] = None): + super().__init__(message or f"x402 policy refused the authorization: {outcome}") + self.outcome = outcome + self.records = list(records or []) + + +def context_hash(url: str, method: str, payload_hash: str) -> str: + """Hash an authorization context the same way the TypeScript hook does.""" + + raw = "{}|{}|{}".format(url, (method or "GET").upper(), payload_hash) + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + + +@dataclass(frozen=True) +class PolicyContext: + """What the policy is asked to approve. Mirrors ``X402PolicyContext``.""" + + url: str + method: str + requirements: Mapping[str, Any] + authorization: Mapping[str, Any] + signer: str + context_hash: str + context_version: int = CONTEXT_VERSION + + @property + def amount(self) -> Any: + return self.requirements.get("amount") + + @property + def asset(self) -> Any: + return self.requirements.get("asset") + + @property + def payee(self) -> Any: + return self.requirements.get("payTo") + + @property + def network(self) -> Any: + return self.requirements.get("network") + + @property + def resource(self) -> str: + return self.url + + def as_dict(self) -> Dict[str, Any]: + """Plain mapping, for callables that prefer dictionaries.""" + + return { + "contextVersion": self.context_version, + "url": self.url, + "method": self.method, + "requirements": dict(self.requirements), + "authorization": dict(self.authorization), + "signer": self.signer, + "contextHash": self.context_hash, + "amount": self.amount, + "asset": self.asset, + "payee": self.payee, + "network": self.network, + } + + +@dataclass +class PolicyDecision: + """What the policy answered. Mirrors ``X402PolicyDecision``.""" + + decision: str + context_hash: Optional[str] = None + reason: str = "" + policy_version: Optional[str] = None + expires_at: Optional[int] = None + decision_id: Optional[str] = None + + @classmethod + def from_raw(cls, raw: Any) -> "PolicyDecision": + if isinstance(raw, cls): + return raw + if isinstance(raw, str): + return cls(decision=raw) + if not isinstance(raw, Mapping): + raise X402PolicyError(MALFORMED, f"policy answered {type(raw).__name__}, expected a decision") + verdict = raw.get("decision", raw.get("verdict")) + if not isinstance(verdict, str): + raise X402PolicyError(MALFORMED, "policy decision has no string `decision`") + expires_at = raw.get("expiresAt", raw.get("expires_at")) + if expires_at is not None and not isinstance(expires_at, (int, float)): + raise X402PolicyError(MALFORMED, "policy decision has a non-numeric `expiresAt`") + version = raw.get("policyVersion", raw.get("policy_version")) + return cls( + decision=verdict, + context_hash=raw.get("contextHash", raw.get("context_hash")), + reason=str(raw.get("reason") or ""), + policy_version=None if version is None else str(version), + expires_at=None if expires_at is None else int(expires_at), + decision_id=raw.get("decisionId", raw.get("decision_id")), + ) + + +@dataclass +class PolicyResult: + """Successful gate: the signed artifact plus the audit trail.""" + + value: Any + records: List[str] = field(default_factory=list) + decision: Optional[PolicyDecision] = None + + +def build_context( + *, + url: str, + method: str, + requirements: Mapping[str, Any], + authorization: Mapping[str, Any], + signer: str, +) -> PolicyContext: + """Build a context whose hash binds url + method + the signed payload.""" + + payload_hash = str(authorization.get("payloadHash") or authorization.get("payload_hash") or "") + if not payload_hash: + raise X402PolicyError(MALFORMED, "authorization without payloadHash cannot be bound") + return PolicyContext( + url=url or "", + method=(method or "GET").upper(), + requirements=dict(requirements), + authorization=dict(authorization), + signer=signer or "", + context_hash=context_hash(url or "", method or "GET", payload_hash), + ) + + +def _supports(policy: Any, name: str) -> bool: + if isinstance(policy, Mapping): + return name in policy + return callable(getattr(policy, name, None)) + + +def _member(policy: Any, name: str) -> Any: + if isinstance(policy, Mapping): + return policy.get(name) + return getattr(policy, name, None) + + +def _resolve(value: Any) -> Any: + """Run an awaitable to completion so sync callers see a plain value.""" + + if inspect.isawaitable(value): + return asyncio.run(value) + return value + + +def _call_with_deadline(fn: Callable[[], Any], deadline: float) -> Any: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise X402PolicyError(TIMEOUT, "policy deadline expired before the answer arrived") + pool = concurrent.futures.ThreadPoolExecutor(max_workers=1) + try: + future = pool.submit(fn) + try: + return future.result(timeout=remaining) + except concurrent.futures.TimeoutError: + raise X402PolicyError(TIMEOUT, "policy answer arrived after the deadline") from None + finally: + # Never block the gate on a policy that is still sleeping: the answer is + # already useless once the deadline passed. + pool.shutdown(wait=False) + + +def timeout_ms_of(policy: Any, default: Optional[int] = None) -> int: + """Hook timeout, in milliseconds (``timeout`` on the TS side).""" + + for name in ("timeout_ms", "timeoutMs", "timeout"): + value = _member(policy, name) + if isinstance(value, (int, float)) and value > 0: + return int(value) + return int(default or DEFAULT_TIMEOUT_MS) + + +def run_policy_gate( + policy: Any, + ctx: PolicyContext, + sign: Callable[[], Any], + *, + default_timeout_ms: Optional[int] = None, + require_expires_at: Optional[bool] = None, + now_ms: Optional[int] = None, +) -> PolicyResult: + """Run the policy and sign **only** with a valid, fresh ``ALLOW``. + + ``policy`` may be an object with ``evaluate(ctx)`` (plus the optional + ``current_version`` / ``on_decision`` / ``timeout_ms`` / + ``require_expires_at`` members, as in the TypeScript SDK) or a plain + callable that receives the context and returns ``ALLOW``, ``DENY`` or + ``WAIT``. + """ + + if policy is None: + raise X402PolicyError(MALFORMED, "run_policy_gate called without a policy") + structured = _supports(policy, "evaluate") + evaluate = _member(policy, "evaluate") if structured else policy + if not callable(evaluate): + raise X402PolicyError(MALFORMED, "policy has no callable evaluate") + + records: List[str] = [] + deadline = time.monotonic() + timeout_ms_of(policy, default_timeout_ms) / 1000.0 + require_exp = ( + bool(require_expires_at) + if require_expires_at is not None + else bool(_member(policy, "require_expires_at") or _member(policy, "requireExpiresAt")) + ) + + raw = _call_with_deadline(lambda: _resolve(evaluate(ctx)), deadline) + decision = PolicyDecision.from_raw(raw) + verdict = decision.decision.strip() + if verdict not in VERDICTS: + raise X402PolicyError(MALFORMED, f"unknown policy verdict {decision.decision!r}", records) + + if verdict == DENY: + raise X402PolicyError(DENY, decision.reason or "policy denied the payment", records) + if verdict == WAIT: + raise X402PolicyError(WAIT, decision.reason or "policy asked to wait", records) + + records.append(ALLOWED) + + observer = _member(policy, "on_decision") or _member(policy, "onDecision") + if callable(observer): + try: + observer(decision, list(records)) + except Exception: # an observer must never break the gate + pass + + # A structured hook must echo the hash it approved. A plain callable was + # handed the context itself, so its ALLOW is already bound to it. + if structured and (not decision.context_hash or str(decision.context_hash) != ctx.context_hash): + raise X402PolicyError(UNBOUND, "ALLOW is not bound to this authorization", records) + + version_reader = _member(policy, "current_version") or _member(policy, "currentVersion") + if callable(version_reader): + if not decision.policy_version: + raise X402PolicyError( + MALFORMED, "ALLOW must carry policyVersion when a version is expected", records + ) + try: + current = _call_with_deadline(lambda: _resolve(version_reader(ctx)), deadline) + except X402PolicyError: + raise + except Exception as exc: + raise X402PolicyError( + VERSION_UNAVAILABLE, f"policy version unreadable: {exc}", records + ) from None + if current is None or str(current) == "": + raise X402PolicyError(VERSION_UNAVAILABLE, "policy version is empty", records) + if str(current) != str(decision.policy_version): + raise X402PolicyError(STALE, "policy version changed before signing", records) + + now = int(time.time() * 1000) if now_ms is None else int(now_ms) + if decision.expires_at is not None and decision.expires_at <= now: + raise X402PolicyError(EXPIRED, "ALLOW expired before signing", records) + if require_exp and decision.expires_at is None: + raise X402PolicyError(MALFORMED, "ALLOW without expiresAt is not signable", records) + + try: + value = _call_with_deadline(lambda: _resolve(sign()), deadline) + except X402PolicyError: + raise + except Exception as exc: + records.append(SIGNER_ERROR) + raise X402PolicyError(SIGNER_ERROR, f"signer failed: {exc}", records) from exc + + records.append(SIGNED) + return PolicyResult(value=value, records=records, decision=decision) diff --git a/packages/sdk-python/tests/test_x402_policy.py b/packages/sdk-python/tests/test_x402_policy.py new file mode 100644 index 00000000..87c02910 --- /dev/null +++ b/packages/sdk-python/tests/test_x402_policy.py @@ -0,0 +1,302 @@ +"""Conformance tests for the Python pre-sign policy hook. + +Mirrors ``packages/sdk/src/x402-policy-conformance.ts``: every case asserts +that the signer is **not** called when the policy refuses, which is the whole +point of the gate. +""" + +from __future__ import annotations + +import time + +import pytest + +from nirium.x402_policy import ( + ALLOWED, + DENY, + EXPIRED, + MALFORMED, + SIGNED, + SIGNER_ERROR, + STALE, + TIMEOUT, + UNBOUND, + VERSION_UNAVAILABLE, + WAIT, + PolicyDecision, + X402PolicyError, + build_context, + run_policy_gate, +) + +URL = "https://api.example.com/paid/quote" +METHOD = "POST" +PAYLOAD = "0f" * 32 +SIGNER_KEY = "G" + "A" * 55 + + +def context(**overrides): + authorization = { + "payloadHash": PAYLOAD, + "from": SIGNER_KEY, + "to": "G" + "B" * 55, + "amount": 250, + "nonce": 7, + } + authorization.update(overrides) + return build_context( + url=URL, + method=METHOD, + requirements={ + "scheme": "exact", + "network": "stellar:testnet", + "asset": "C" + "C" * 55, + "payTo": "G" + "B" * 55, + "amount": 250, + "maxTimeoutSeconds": 300, + }, + authorization=authorization, + signer=SIGNER_KEY, + ) + + +class Signer: + """Mock signer: counts calls and fails loudly if it should not run.""" + + def __init__(self, result="signed-xdr", boom=None): + self.calls = 0 + self.result = result + self.boom = boom + + def __call__(self): + self.calls += 1 + if self.boom: + raise self.boom + return self.result + + +class Allow: + """Policy object shaped like the TypeScript ``X402PolicyHook``.""" + + def __init__(self, echo=True, verdict="ALLOW", version=None, expires_in_ms=60_000, timeout_ms=None): + self.echo = echo + self.verdict = verdict + self.version = version + self.expires_in_ms = expires_in_ms + self.timeout_ms = timeout_ms + self.seen = [] + + def evaluate(self, ctx): + self.seen.append(ctx) + return PolicyDecision( + decision=self.verdict, + context_hash=ctx.context_hash if self.echo else "0" * 64, + policy_version=self.version, + expires_at=( + None + if self.expires_in_ms is None + else int(time.time() * 1000) + self.expires_in_ms + ), + ) + + +def expect_refused(outcome, fn, signer): + with pytest.raises(X402PolicyError) as excinfo: + fn() + assert excinfo.value.outcome == outcome, (excinfo.value.outcome, str(excinfo.value)) + assert signer.calls == 0, "the signer must never run on a refusal" + return excinfo.value + + +def test_allow_with_the_exact_context_hash_signs_exactly_once(): + signer = Signer() + policy = Allow() + result = run_policy_gate(policy, context(), signer) + assert signer.calls == 1 + assert result.value == "signed-xdr" + assert result.records == [ALLOWED, SIGNED] + assert policy.seen[0].resource == URL + assert policy.seen[0].amount == 250 + + +def test_context_hash_changes_with_the_payload(): + a = context() + b = context(payloadHash="ff" * 32) + assert a.context_hash != b.context_hash + + +def test_deny_signs_nothing(): + signer = Signer() + expect_refused(DENY, lambda: run_policy_gate(Allow(verdict="DENY"), context(), signer), signer) + + +def test_wait_signs_nothing(): + signer = Signer() + expect_refused(WAIT, lambda: run_policy_gate(Allow(verdict="WAIT"), context(), signer), signer) + + +def test_allow_with_a_wrong_context_hash_signs_nothing(): + signer = Signer() + expect_refused(UNBOUND, lambda: run_policy_gate(Allow(echo=False), context(), signer), signer) + + +def test_allow_with_an_expired_expires_at_signs_nothing(): + signer = Signer() + now = int(time.time() * 1000) + + def expired(ctx): + return { + "decision": "ALLOW", + "contextHash": ctx.context_hash, + "expiresAt": now - 1, + } + + expect_refused(EXPIRED, lambda: run_policy_gate(expired, context(), signer, now_ms=now), signer) + + +def test_expires_at_equal_to_the_clock_counts_as_expired(): + signer = Signer() + now = int(time.time() * 1000) + + def boundary(ctx): + return {"decision": "ALLOW", "contextHash": ctx.context_hash, "expiresAt": now} + + expect_refused(EXPIRED, lambda: run_policy_gate(boundary, context(), signer, now_ms=now), signer) + + +@pytest.mark.parametrize( + "answer", + [ + None, + "allow", # lowercase is not a verdict + {"decision": "ALLOW", "contextHash": "x" * 64, "expiresAt": "soon"}, + {"verdict": 3}, + ], +) +def test_malformed_answers_sign_nothing(answer): + signer = Signer() + expect_refused(MALFORMED, lambda: run_policy_gate(lambda ctx: answer, context(), signer), signer) + + +def test_an_answer_after_the_timeout_signs_nothing(): + signer = Signer() + + def slow(ctx): + time.sleep(0.3) + return {"decision": "ALLOW", "contextHash": ctx.context_hash} + + started = time.monotonic() + expect_refused( + TIMEOUT, + lambda: run_policy_gate(slow, context(), signer, default_timeout_ms=50), + signer, + ) + assert time.monotonic() - started < 3 + + +def test_stale_policy_version_signs_nothing(): + signer = Signer() + + class Stale(Allow): + def current_version(self, ctx): + return "v2" + + expect_refused(STALE, lambda: run_policy_gate(Stale(version="v1"), context(), signer), signer) + + +def test_unreadable_policy_version_signs_nothing(): + signer = Signer() + + class Broken(Allow): + def current_version(self, ctx): + raise RuntimeError("version store offline") + + expect_refused( + VERSION_UNAVAILABLE, + lambda: run_policy_gate(Broken(version="v1"), context(), signer), + signer, + ) + + +def test_allow_without_policy_version_signs_nothing_when_a_version_is_expected(): + signer = Signer() + + class Versioned(Allow): + def current_version(self, ctx): + return "v1" + + expect_refused( + MALFORMED, + lambda: run_policy_gate(Versioned(version=None), context(), signer), + signer, + ) + + +def test_matching_policy_version_signs(): + signer = Signer() + + class Versioned(Allow): + def current_version(self, ctx): + return "v1" + + result = run_policy_gate(Versioned(version="v1"), context(), signer) + assert signer.calls == 1 + assert result.records == [ALLOWED, SIGNED] + + +def test_allow_without_expires_at_is_refused_when_required(): + signer = Signer() + expect_refused( + MALFORMED, + lambda: run_policy_gate(Allow(expires_in_ms=None), context(), signer, require_expires_at=True), + signer, + ) + + +def test_plain_callable_policy_is_supported(): + signer = Signer() + seen = [] + + def policy(ctx): + seen.append(ctx.as_dict()) + return "ALLOW" + + result = run_policy_gate(policy, context(), signer) + assert signer.calls == 1 + assert result.records == [ALLOWED, SIGNED] + assert seen[0]["payee"] == "G" + "B" * 55 + assert seen[0]["network"] == "stellar:testnet" + + +def test_observer_sees_the_allowance_before_the_version_check(): + order = [] + + class Observed(Allow): + def on_decision(self, decision, records): + order.append(("decision", decision.decision, tuple(records))) + + def current_version(self, ctx): + order.append(("version",)) + return "v1" + + signer = Signer() + run_policy_gate(Observed(version="v1"), context(), signer) + assert order == [("decision", "ALLOW", (ALLOWED,)), ("version",)] + + +def test_observer_errors_never_block_a_valid_allow(): + class Noisy(Allow): + def on_decision(self, decision, records): + raise RuntimeError("telemetry down") + + signer = Signer() + assert run_policy_gate(Noisy(), context(), signer).records == [ALLOWED, SIGNED] + + +def test_signer_failure_is_reported_as_signer_error(): + signer = Signer(boom=RuntimeError("HSM locked")) + with pytest.raises(X402PolicyError) as excinfo: + run_policy_gate(Allow(), context(), signer) + assert excinfo.value.outcome == SIGNER_ERROR + assert signer.calls == 1 + assert excinfo.value.records == [ALLOWED, SIGNER_ERROR] diff --git a/packages/sdk-python/tests/test_x402_policy_client.py b/packages/sdk-python/tests/test_x402_policy_client.py new file mode 100644 index 00000000..d4a0cf4b --- /dev/null +++ b/packages/sdk-python/tests/test_x402_policy_client.py @@ -0,0 +1,127 @@ +"""Client-level wiring of the x402 policy hook. + +These tests never touch the network: they exercise +``Agent._x402_authorize_entries`` with fake authorization entries and a +monkeypatched ``authorize_entry``, which is the exact step that signs. +""" + +from __future__ import annotations + +import time + +import pytest + +pytest.importorskip("stellar_sdk") + +import nirium.client as client_mod # noqa: E402 +from nirium.x402_policy import X402PolicyError # noqa: E402 + +ACCEPTED = { + "scheme": "exact", + "network": "stellar:testnet", + "asset": "C" + "C" * 55, + "payTo": "G" + "B" * 55, + "amount": "250", + "maxTimeoutSeconds": 300, +} + + +class FakeEntry: + def __init__(self, name: str): + self.name = name + + def to_xdr(self) -> bytes: + return ("entry:" + self.name).encode() + + +class FakeKeypair: + public_key = "G" + "A" * 55 + + +def make_agent(policy=None): + agent = client_mod.Agent.__new__(client_mod.Agent) + agent._x402_keypair = FakeKeypair() + agent._x402_passphrase = "Test SDF Network ; September 2015" + agent._x402_policy = policy + agent._x402_policy_require_expires = getattr(policy, "require_expires_at", None) + agent._x402_pending_url = "https://api.example.com/paid/quote" + return agent + + +class SignerSpy: + def __init__(self): + self.seen = [] + + def __call__(self, entry, keypair, max_ledger, passphrase): + self.seen.append(entry.name) + return "signed:" + entry.name + + +class AllowAll: + def __init__(self, verdict="ALLOW"): + self.verdict = verdict + + def evaluate(self, ctx): + return { + "decision": self.verdict, + "contextHash": ctx.context_hash, + "expiresAt": int(time.time() * 1000) + 60_000, + } + + +def test_without_a_policy_every_entry_is_signed_like_before(monkeypatch): + spy = SignerSpy() + monkeypatch.setattr(client_mod, "authorize_entry", spy) + out = make_agent()._x402_authorize_entries([FakeEntry("a"), FakeEntry("b")], ACCEPTED, 123) + assert out == ["signed:a", "signed:b"] + assert spy.seen == ["a", "b"] + + +def test_allow_policy_signs_each_entry_exactly_once(monkeypatch): + spy = SignerSpy() + monkeypatch.setattr(client_mod, "authorize_entry", spy) + agent = make_agent(AllowAll()) + out = agent._x402_authorize_entries([FakeEntry("a")], ACCEPTED, 123) + assert out == ["signed:a"] + assert spy.seen == ["a"] + + +def test_deny_policy_never_reaches_the_signer(monkeypatch): + spy = SignerSpy() + monkeypatch.setattr(client_mod, "authorize_entry", spy) + agent = make_agent(AllowAll("DENY")) + with pytest.raises(X402PolicyError) as excinfo: + agent._x402_authorize_entries([FakeEntry("a")], ACCEPTED, 123) + assert excinfo.value.outcome == "DENY" + assert spy.seen == [] + + +def test_policy_context_carries_the_payment_details(monkeypatch): + seen = [] + + class Spy: + require_expires_at = False + + def evaluate(self, ctx): + seen.append(ctx) + return { + "decision": "ALLOW", + "contextHash": ctx.context_hash, + "expiresAt": int(time.time() * 1000) + 60_000, + } + + monkeypatch.setattr(client_mod, "authorize_entry", SignerSpy()) + make_agent(Spy())._x402_authorize_entries([FakeEntry("a")], ACCEPTED, 123) + ctx = seen[0] + assert ctx.payee == ACCEPTED["payTo"] + assert ctx.amount == ACCEPTED["amount"] + assert ctx.network == "stellar:testnet" + assert ctx.resource == "https://api.example.com/paid/quote" + assert ctx.authorization["payloadType"] == "soroban-authorization-entry" + + +def test_init_x402_rejects_a_non_callable_policy(): + keypair = client_mod.Keypair.random() + agent = client_mod.Agent.__new__(client_mod.Agent) + with pytest.raises(ValueError): + agent.init_x402(keypair.secret, policy=object())