From 500169a4e2e2ef6fe2d8a661f8ae65f5ae5d398c Mon Sep 17 00:00:00 2001 From: comandanto <89469777+comandanto@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:27:13 +0300 Subject: [PATCH 1/6] feat(sdk-python): add pre-sign policy hook matching TypeScript SDK guarantees --- packages/sdk-python/CHANGELOG.md | 2 + packages/sdk-python/README.md | 40 ++ packages/sdk-python/src/nirium/__init__.py | 6 + packages/sdk-python/src/nirium/client.py | 392 +++++++++++++++- packages/sdk-python/tests/test_x402_policy.py | 444 ++++++++++++++++++ 5 files changed, 879 insertions(+), 5 deletions(-) create mode 100644 packages/sdk-python/tests/test_x402_policy.py diff --git a/packages/sdk-python/CHANGELOG.md b/packages/sdk-python/CHANGELOG.md index 3493874d..0b877518 100644 --- a/packages/sdk-python/CHANGELOG.md +++ b/packages/sdk-python/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes to the `nirium` (PyPI) package are documented here. ## Unreleased +- Pre-sign policy hook (`init_x402(policy=...)`): parity with TypeScript SDK pre-sign policy hook (#355). Evaluates policy before signing; DENY and WAIT never call the signer; fail closed on exceptions; stale ALLOW invalidation via `current_version`. + ## 0.12.7 - 2026-11-19 README: the hosted signal stream (wss://nirium-agent.fly.dev/ws/signals) did not accept connections when checked on 18 Nov 2026; the WebSocket section and the endpoint table now say so. No code change. diff --git a/packages/sdk-python/README.md b/packages/sdk-python/README.md index 15ea4899..859e7b99 100644 --- a/packages/sdk-python/README.md +++ b/packages/sdk-python/README.md @@ -168,6 +168,46 @@ agent.init_x402(secret_key="S...", network="stellar:pubnet", approve=approve) Why the default stays low: an agent pays whatever a server's 402 asks for, so a low cap limits the damage from a mispriced or malicious endpoint. `NiriumX402Tool` accepts the same `max_amount_per_payment` and `approve` options. +#### Pre-sign policy hook + +Pass `policy` to `init_x402()` and every `x402_fetch()` asks your policy before anything is signed. The question is asked before signing, so the policy sees exactly what would be signed: amount, destination, asset, resource URL, and network. + +The policy can be a simple callable (sync or async) or an object implementing `evaluate(ctx)`: + +```python +from nirium import Agent, X402PolicyError + +async def policy(ctx): + # ctx provides amount, asset, payee, resource, network, contextHash, etc. + if int(ctx.amount) <= 1_000_000: # 0.1 USDC + return { + "decision": "ALLOW", + "contextHash": ctx.contextHash, + "policyVersion": "v1", + "expiresAt": (time.time() + 2) * 1000, + } + return {"decision": "DENY", "reason": "over limit"} + +agent = Agent() +agent.init_x402( + secret_key="S...", + network="stellar:pubnet", + policy=policy, + current_version=lambda ctx: "v1", # optional: source of current policy version +) + +try: + res = await agent.x402_fetch(url) +except X402PolicyError as e: + print(e.outcome) # 'DENY', 'WAIT', 'STALE', 'EXPIRED', 'TIMEOUT', 'ENGINE_ERROR', ... +``` + +Only an `ALLOW` reaches the signer. Everything else signs nothing: `DENY`, `WAIT`, an unhandled exception (fails closed), no answer before the deadline (`policy_timeout_ms`, default 5000 ms, never more than half the payment's `maxTimeoutSeconds`), a malformed answer, or an `ALLOW` past its `expiresAt`. Without `policy`, `x402_fetch()` behaves exactly as before. + +**Stale ALLOW.** With `current_version` set, it is read after the `ALLOW` and right before signing, and the `ALLOW` signs only if its `policyVersion` matches. A rejected, empty or late read signs nothing. This check narrows the window to the step between the read and the signer call. + +**What this does not do.** It is a check on the agent side, not account-level enforcement: code in the same process that holds the raw secret key can still sign directly, and nothing on-chain enforces the policy. It does not solve pending-capacity reservation (concurrent requests that observe the same remaining capacity): two calls evaluated at the same time can each fit a limit that together they exceed, and an aggregate cap must be held by your policy store. + ### LangChain tool - pay x402 from any agent `NiriumX402Tool` is a LangChain `BaseTool` that wraps the same `init_x402` / `x402_fetch` client. A ReAct-style agent can pay a protected Stellar endpoint as a normal tool call. The Stellar secret is constructor/env configuration only: it never appears in the tool description, args schema, error text, or return value. diff --git a/packages/sdk-python/src/nirium/__init__.py b/packages/sdk-python/src/nirium/__init__.py index 01f16b98..04b228db 100644 --- a/packages/sdk-python/src/nirium/__init__.py +++ b/packages/sdk-python/src/nirium/__init__.py @@ -8,6 +8,9 @@ WebSocketStatus, X402NetworkMismatchError, X402SpendCapError, + X402PolicyError, + X402PolicyContext, + X402PolicyDecision, ) if TYPE_CHECKING: @@ -20,6 +23,9 @@ "WebSocketStatus", "X402NetworkMismatchError", "X402SpendCapError", + "X402PolicyError", + "X402PolicyContext", + "X402PolicyDecision", "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..67c62339 100644 --- a/packages/sdk-python/src/nirium/client.py +++ b/packages/sdk-python/src/nirium/client.py @@ -13,8 +13,9 @@ import aiohttp # type: ignore import websockets # type: ignore import inspect +import time from decimal import Decimal, InvalidOperation -from typing import Awaitable, Callable, Dict, Any, List, Optional, Union +from typing import Awaitable, Callable, Dict, Any, List, Optional, Union, NoReturn 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 @@ -97,6 +98,142 @@ def __init__(self, url: str, requirement: Dict[str, Any], cap: str, reason: str) ) +class X402PolicyError(RuntimeError): + """Raised when an x402 payment is refused by the pre-sign policy hook. + + Raised before signing, so no signature was released. + """ + + code = "X402_POLICY_REFUSED" + signer_called = False + + def __init__( + self, + outcome: str, + message: str, + decision: Optional[Any] = None, + context_hash: Optional[str] = None, + ): + self.outcome = outcome + self.message = message + self.decision = decision + self.context_hash = context_hash + super().__init__(f"x402 policy {outcome}: {message}") + + +class X402PolicyDecision: + """Normalized policy decision returned by or parsed from the policy hook.""" + + def __init__( + self, + decision: str, + context_hash: Optional[str] = None, + reason: Optional[str] = None, + policy_version: Optional[str] = None, + expires_at: Optional[float] = None, + decision_id: Optional[str] = None, + ): + self.decision = decision.upper().strip() + self.context_hash = context_hash + self.contextHash = context_hash + self.reason = reason + self.policy_version = policy_version + self.policyVersion = policy_version + self.expires_at = expires_at + self.expiresAt = expires_at + self.decision_id = decision_id + self.decisionId = decision_id + + def __repr__(self) -> str: + return ( + f"X402PolicyDecision(decision={self.decision!r}, " + f"contextHash={self.contextHash!r}, " + f"policyVersion={self.policyVersion!r}, " + f"expiresAt={self.expiresAt!r}, " + f"reason={self.reason!r})" + ) + + +class X402PolicyContext(dict): + """Context object passed to the policy evaluation callback.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if "payTo" in self and "payee" not in self: + self["payee"] = self["payTo"] + if "payee" in self and "payTo" not in self: + self["payTo"] = self["payee"] + if "url" in self and "resource" not in self: + self["resource"] = self["url"] + if "resource" in self and "url" not in self: + self["url"] = self["resource"] + if "contextHash" in self and "context_hash" not in self: + self["context_hash"] = self["contextHash"] + if "context_hash" in self and "contextHash" not in self: + self["contextHash"] = self["context_hash"] + if "contextVersion" in self and "context_version" not in self: + self["context_version"] = self["contextVersion"] + if "context_version" in self and "contextVersion" not in self: + self["contextVersion"] = self["context_version"] + + def __getattr__(self, name: str) -> Any: + if name in self: + return self[name] + alternatives = { + "context_version": "contextVersion", + "contextVersion": "context_version", + "context_hash": "contextHash", + "contextHash": "context_hash", + "pay_to": "payTo", + "payTo": "pay_to", + "payee": "payTo", + "resource": "url", + "url": "resource", + } + if name in alternatives and alternatives[name] in self: + return self[alternatives[name]] + raise AttributeError(f"'X402PolicyContext' object has no attribute {name!r}") + + def __setattr__(self, name: str, value: Any) -> None: + self[name] = value + + +def _sha256_hex(val: Union[str, bytes]) -> str: + if isinstance(val, str): + val = val.encode("utf-8") + return hashlib.sha256(val).hexdigest() + + +def _parse_decision(val: Any) -> Optional[X402PolicyDecision]: + if val is None: + return None + if isinstance(val, str): + v = val.upper().strip() + return X402PolicyDecision(decision=v) + if isinstance(val, dict): + d = val.get("decision") + if not d or not isinstance(d, str): + return None + return X402PolicyDecision( + decision=d, + context_hash=val.get("contextHash") or val.get("context_hash"), + reason=val.get("reason"), + policy_version=val.get("policyVersion") or val.get("policy_version"), + expires_at=val.get("expiresAt") or val.get("expires_at"), + decision_id=val.get("decisionId") or val.get("decision_id"), + ) + if hasattr(val, "decision") and isinstance(val.decision, str): + return X402PolicyDecision( + decision=val.decision, + context_hash=getattr(val, "contextHash", getattr(val, "context_hash", None)), + reason=getattr(val, "reason", None), + policy_version=getattr(val, "policyVersion", getattr(val, "policy_version", None)), + expires_at=getattr(val, "expiresAt", getattr(val, "expires_at", None)), + decision_id=getattr(val, "decisionId", getattr(val, "decision_id", None)), + ) + return None + + def _parse_usd_cap(value: Any) -> Decimal: """'$5', '5', 5 or 0.5 -> Decimal. Must be a positive amount.""" if isinstance(value, bool) or value is None: @@ -743,6 +880,12 @@ def init_x402( rpc_url: str = "", max_amount_per_payment: Any = _X402_DEFAULT_MAX_AMOUNT, approve: Optional[X402Approver] = None, + policy: Optional[Any] = None, + current_version: Optional[Any] = None, + policy_timeout_ms: Optional[int] = None, + on_decision: Optional[Callable[[Dict[str, Any]], None]] = None, + now: Optional[Callable[[], float]] = None, + signer: Optional[Callable[..., Any]] = None, ): """ Initialize the x402 pay-per-request client (protocol v2). @@ -761,6 +904,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 (callable or object with evaluate). + Receives the payment context and returns ALLOW, DENY, or WAIT. + DENY and WAIT refuse the payment without calling the signer. + current_version: Optional callable returning current policy version for stale-check. + policy_timeout_ms: Hard deadline for pre-sign policy evaluation in ms (default 5000). + on_decision: Optional observer callback receiving record of policy outcome. + now: Optional callable returning epoch milliseconds, for testing. + signer: Optional custom signer override (e.g. for testing without keypair). 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 +923,27 @@ 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) and not hasattr(policy, "evaluate"): + raise ValueError("init_x402: policy must be a callable or an object with an evaluate method.") + if current_version is not None and not callable(current_version): + raise ValueError("init_x402: current_version must be a callable or None.") + if policy_timeout_ms is not None and (not isinstance(policy_timeout_ms, int) or policy_timeout_ms <= 0): + raise ValueError("init_x402: policy_timeout_ms must be a positive integer (ms).") + if on_decision is not None and not callable(on_decision): + raise ValueError("init_x402: on_decision must be a callable or None.") + if now is not None and not callable(now): + raise ValueError("init_x402: now must be a callable returning epoch milliseconds.") + 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_current_version = current_version + self._x402_policy_timeout_ms = policy_timeout_ms or 5000 + self._x402_on_decision = on_decision + self._x402_now = now + self._x402_signer = signer is_testnet = network == "stellar:testnet" self._x402_keypair = Keypair.from_secret(secret_key) self._x402_network = network @@ -865,6 +1033,196 @@ def amount_of(a: Dict[str, Any]) -> Optional[int]: return candidate raise X402SpendCapError(url, candidate, cap_label, reason) + def _x402_sign_auth_entry(self, entry: Any, max_ledger: int) -> Any: + signer = getattr(self, "_x402_signer", None) + if signer is not None and callable(signer): + return signer(entry, self._x402_keypair, max_ledger, self._x402_passphrase) + return authorize_entry(entry, self._x402_keypair, max_ledger, self._x402_passphrase) + + def _x402_report_decision( + self, + outcome: str, + context: Optional[X402PolicyContext] = None, + decision: Optional[X402PolicyDecision] = None, + err: Optional[str] = None, + ) -> None: + policy = getattr(self, "_x402_policy", None) + cb = getattr( + policy, + "on_decision", + getattr(policy, "onDecision", getattr(self, "_x402_on_decision", None)), + ) + if cb and callable(cb): + try: + rec = { + "outcome": outcome, + "context": context, + "decision": decision, + "error": err, + } + res = cb(rec) + if inspect.isawaitable(res): + try: + loop = asyncio.get_running_loop() + loop.create_task(res) + except RuntimeError: + pass + except Exception: + pass + + async def _x402_run_policy( + self, + url: str, + method: str, + accepted: Dict[str, Any], + ) -> X402PolicyDecision: + policy = getattr(self, "_x402_policy", None) + if policy is None: + return X402PolicyDecision(decision="ALLOW") + + now_fn = getattr(self, "_x402_now", None) or (lambda: time.time() * 1000.0) + account = self._x402_keypair.public_key + + timeout_sec = accepted.get("maxTimeoutSeconds", 300) + base_timeout_ms = getattr( + policy, + "timeout_ms", + getattr(policy, "timeoutMs", getattr(self, "_x402_policy_timeout_ms", 5000)), + ) + if timeout_sec and timeout_sec > 0: + effective_timeout_ms = max(1, min(base_timeout_ms, int((timeout_sec * 1000) / 2))) + else: + effective_timeout_ms = base_timeout_ms + + payload_hash = _sha256_hex( + f"{accepted.get('asset')}:{accepted.get('payTo')}:{accepted.get('amount')}:{self._x402_network}" + ) + context_hash = _sha256_hex( + json.dumps({"v": 1, "url": url, "method": method, "payloadHash": payload_hash}, sort_keys=True) + ) + + auth_view = { + "payloadHash": payload_hash, + "contractId": accepted.get("asset", ""), + "functionName": "transfer", + "from": account, + "to": accepted.get("payTo", ""), + "amount": str(accepted.get("amount", "")), + "networkPassphrase": self._x402_passphrase, + } + + context = X402PolicyContext( + contextVersion=1, + context_version=1, + url=url, + method=method, + resource=url, + network=self._x402_network, + asset=accepted.get("asset", ""), + payTo=accepted.get("payTo", ""), + payee=accepted.get("payTo", ""), + amount=str(accepted.get("amount", "")), + signer=account, + contextHash=context_hash, + context_hash=context_hash, + requirements=accepted, + authorization=auth_view, + ) + + def read_clock() -> float: + try: + t = now_fn() + except Exception as e: + refuse("CLOCK_INVALID", f"clock threw ({e})") + if not isinstance(t, (int, float)) or _math.isnan(t) or _math.isinf(t): + refuse("CLOCK_INVALID", f"clock returned {t!r}, not epoch milliseconds") + return float(t) + + def refuse(outcome: str, msg: str, decision: Optional[X402PolicyDecision] = None) -> NoReturn: + self._x402_report_decision(outcome, context=context, decision=decision, err=msg) + raise X402PolicyError(outcome, msg, decision=decision, context_hash=context_hash) + + start_time = read_clock() + deadline = start_time + effective_timeout_ms + + eval_fn = getattr(policy, "evaluate", policy if callable(policy) else None) + if eval_fn is None: + refuse("MALFORMED", "policy is neither callable nor has evaluate method") + + try: + eval_res = eval_fn(context) + if inspect.isawaitable(eval_res): + raw_decision = await asyncio.wait_for(eval_res, timeout=effective_timeout_ms / 1000.0) + else: + raw_decision = eval_res + except asyncio.TimeoutError: + refuse("TIMEOUT", f"no decision within {effective_timeout_ms} ms") + except Exception as e: + refuse("ENGINE_ERROR", f"policy evaluation failed: {e}") + + decision = _parse_decision(raw_decision) + if decision is None or decision.decision not in ("ALLOW", "DENY", "WAIT"): + refuse("MALFORMED", f"unknown or missing verdict: {raw_decision!r}") + + if decision.decision == "DENY": + refuse("DENY", decision.reason or "payment denied by policy", decision=decision) + + if decision.decision == "WAIT": + refuse("WAIT", decision.reason or "payment waiting on approval", decision=decision) + + # Verdict is ALLOW + if decision.contextHash and decision.contextHash != context_hash: + refuse("UNBOUND", "ALLOW is not bound to this authorization", decision=decision) + + now_t = read_clock() + if now_t >= deadline: + refuse("TIMEOUT", "decision arrived after the deadline", decision=decision) + + if decision.expiresAt is not None: + exp_t = decision.expiresAt + if exp_t < 1e11: + exp_t *= 1000.0 + if now_t >= exp_t: + refuse("EXPIRED", "ALLOW expired before signing", decision=decision) + + ver_fn = getattr( + policy, + "current_version", + getattr(policy, "currentVersion", getattr(self, "_x402_current_version", None)), + ) + if ver_fn is not None: + if not decision.policyVersion: + refuse("MALFORMED", "ALLOW has no policyVersion to check against currentVersion", decision=decision) + try: + ver_res = ver_fn(context) + if inspect.isawaitable(ver_res): + curr_ver = await asyncio.wait_for(ver_res, timeout=effective_timeout_ms / 1000.0) + else: + curr_ver = ver_res + except asyncio.TimeoutError: + refuse("TIMEOUT", f"currentVersion timed out after {effective_timeout_ms} ms", decision=decision) + except Exception as e: + refuse("VERSION_UNAVAILABLE", f"currentVersion failed: {e}", decision=decision) + + if not curr_ver: + refuse("VERSION_UNAVAILABLE", "currentVersion returned empty version", decision=decision) + + if str(curr_ver) != str(decision.policyVersion): + refuse("STALE", f"ALLOW was issued under policy {decision.policyVersion}, current is {curr_ver}", decision=decision) + + now_t = read_clock() + if decision.expiresAt is not None: + exp_t = decision.expiresAt + if exp_t < 1e11: + exp_t *= 1000.0 + if now_t >= exp_t: + refuse("EXPIRED", "ALLOW expired before signing", decision=decision) + + self._x402_report_decision("ALLOWED", context=context, decision=decision) + self._x402_last_policy_context = context + self._x402_last_policy_decision = decision + return decision + def _x402_build_transaction(self, accepted: Dict[str, Any]) -> str: """ Build the signed payment transaction for one payment requirement. @@ -912,7 +1270,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) + self._x402_sign_auth_entry(e, max_ledger) for e in (op.auth or []) ] @@ -991,7 +1349,8 @@ async def x402_fetch( async with aiohttp.ClientSession() as session: async with session.request(method, url, **payload) as resp: if resp.status != 402: - return await self._x402_read_payload(resp) + res = self._x402_read_payload(resp) + return (await res) if inspect.isawaitable(res) else res # v2 entrega los requirements en un header base64; el body va vacío. raw = resp.headers.get("payment-required") @@ -1008,10 +1367,32 @@ async def x402_fetch( accepted = await self._x402_select_requirement(url, accepts) + policy_decision = None + if getattr(self, "_x402_policy", None) is not None: + policy_decision = await self._x402_run_policy(url=url, method=method, accepted=accepted) + + try: + tx_xdr = self._x402_build_transaction(accepted) + if policy_decision is not None: + self._x402_report_decision( + "SIGNED", + context=getattr(self, "_x402_last_policy_context", None), + decision=policy_decision, + ) + except Exception as e: + if policy_decision is not None and not isinstance(e, X402PolicyError): + self._x402_report_decision( + "SIGNER_ERROR", + context=getattr(self, "_x402_last_policy_context", None), + decision=policy_decision, + err=str(e), + ) + raise + payment = { "x402Version": challenge.get("x402Version", 2), "accepted": accepted, - "payload": {"transaction": self._x402_build_transaction(accepted)}, + "payload": {"transaction": tx_xdr}, } header = _b64.b64encode(json.dumps(payment).encode("utf-8")).decode("ascii") @@ -1026,7 +1407,8 @@ async def x402_fetch( f"x402 payment rejected (HTTP {paid.status}): {rejected[:300]}" ) self._x402_store_settlement(paid.headers) - return await self._x402_read_payload(paid) + res = self._x402_read_payload(paid) + return (await res) if inspect.isawaitable(res) else res # ─── MPP Protocol (Charge Mode) ───────────────────────── 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..2d97606d --- /dev/null +++ b/packages/sdk-python/tests/test_x402_policy.py @@ -0,0 +1,444 @@ +"""Pre-sign policy hook tests for x402_fetch (#355). + +Verifies the Python SDK provides the exact same policy hook guarantees +as the TypeScript SDK (x402-policy.ts): +- Policy receives the context (amount, asset, payee, resource, network, contextHash, authorization, etc.) +- ALLOW signs and pays +- DENY and WAIT never call the signer (verified with a failing signer mock) +- Fail closed when policy raises an exception +- Stale ALLOW refused when policyVersion != currentVersion +- Expired ALLOW refused when expiresAt has passed +- Unbound ALLOW refused when contextHash does not match +- Timeout enforced +- on_decision observer receives expected records +""" + +from __future__ import annotations + +import base64 +import json +import time +from typing import Any, Dict, List + +import pytest +from stellar_sdk import Keypair + +import nirium.client as client_mod +from nirium import ( + Agent, + X402PolicyContext, + X402PolicyDecision, + X402PolicyError, +) + +TESTNET_USDC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA" +ATTACKER = "GAZ3P265JVAFAG3IS3FBGWKWUGNIUR4HY7FNUM63MHEL3YPV3QVWULEP" +SECRET = Keypair.random().secret +URL = "https://example.com/api/premium" + + +def option(network: str = "stellar:testnet", asset: str = TESTNET_USDC, amount: str = "500000") -> Dict[str, Any]: + return { + "scheme": "exact", + "network": network, + "asset": asset, + "payTo": ATTACKER, + "amount": amount, + "maxTimeoutSeconds": 60, + "extra": {"areFeesSponsored": True}, + } + + +class FakeResponse: + def __init__(self, status: int, headers: Dict[str, str], body: Any = None): + self.status = status + self.headers = headers + self._body = body or {} + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def json(self, *a, **k): + return self._body + + async def text(self): + return json.dumps(self._body) + + +class FakeSession: + def __init__(self, accepts: List[Dict[str, Any]]): + challenge = base64.b64encode( + json.dumps({"x402Version": 2, "accepts": accepts}).encode() + ).decode() + self.responses = [ + FakeResponse(402, {"payment-required": challenge}), + FakeResponse(200, {"content-type": "application/json"}, {"ok": True, "data": "paid_content"}), + ] + self.requests: List[Dict[str, Any]] = [] + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + def request(self, method, url, **kwargs): + self.requests.append({"method": method, "url": url, **kwargs}) + return self.responses.pop(0) + + +@pytest.fixture +def make_policy_agent(monkeypatch): + def _make(policy=None, accepts=None, fail_signer=False, **init_kwargs): + if accepts is None: + accepts = [option()] + session = FakeSession(accepts) + monkeypatch.setattr(client_mod.aiohttp, "ClientSession", lambda *a, **k: session) + + agent = Agent(api_url="http://localhost:3002") + + signer_calls = [] + + def mock_signer(entry, keypair, max_ledger, passphrase): + if fail_signer: + pytest.fail("SIGNER MUST NEVER BE CALLED ON DENY/WAIT/ERROR") + signer_calls.append({"entry": entry, "keypair": keypair, "max_ledger": max_ledger}) + return "SIGNED_AUTH_ENTRY" + + def fake_build(accepted): + # When build_transaction is called, it simulates the signer invocation + if fail_signer: + pytest.fail("SIGNER / BUILD_TRANSACTION MUST NEVER BE CALLED ON DENY/WAIT/ERROR") + mock_signer(None, None, 100, "") + return "MOCK_SIGNED_TX_XDR" + + async def fake_read(resp): + return resp._body + + monkeypatch.setattr(agent, "_x402_build_transaction", fake_build) + monkeypatch.setattr(agent, "_x402_read_payload", fake_read) + monkeypatch.setattr(agent, "_x402_store_settlement", lambda h: None) + + agent.init_x402( + SECRET, + network="stellar:testnet", + policy=policy, + signer=mock_signer, + **init_kwargs, + ) + return agent, session, signer_calls + + return _make + + +# 1. ALLOW cases + + +async def test_allow_callable_signs_and_settles(make_policy_agent): + seen_context = [] + + def allow_policy(ctx: X402PolicyContext): + seen_context.append(ctx) + return "ALLOW" + + agent, session, signer_calls = make_policy_agent(policy=allow_policy) + res = await agent.x402_fetch(URL) + + assert res == {"ok": True, "data": "paid_content"} + assert len(signer_calls) == 1 + assert len(session.requests) == 2 # 402 challenge + paid retry + assert "PAYMENT-SIGNATURE" in session.requests[1]["headers"] + + ctx = seen_context[0] + assert ctx.amount == "500000" + assert ctx.asset == TESTNET_USDC + assert ctx.payee == ATTACKER + assert ctx.payTo == ATTACKER + assert ctx.resource == URL + assert ctx.url == URL + assert ctx.network == "stellar:testnet" + assert ctx.method == "GET" + assert ctx.contextHash is not None + + +async def test_allow_dict_with_conformance_fields(make_policy_agent): + def allow_policy(ctx): + return { + "decision": "ALLOW", + "contextHash": ctx.contextHash, + "policyVersion": "v1", + "expiresAt": time.time() * 1000 + 10000, + } + + agent, _, signer_calls = make_policy_agent(policy=allow_policy) + res = await agent.x402_fetch(URL) + assert res["ok"] is True + assert len(signer_calls) == 1 + + +async def test_async_policy_allow(make_policy_agent): + async def async_policy(ctx): + return "ALLOW" + + agent, _, signer_calls = make_policy_agent(policy=async_policy) + res = await agent.x402_fetch(URL) + assert res["ok"] is True + assert len(signer_calls) == 1 + + +# 2. DENY and WAIT cases (Signer mock MUST FAIL if called) + + +async def test_deny_never_calls_signer(make_policy_agent): + def deny_policy(ctx): + return "DENY" + + agent, session, signer_calls = make_policy_agent(policy=deny_policy, fail_signer=True) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "DENY" + assert exc_info.value.signer_called is False + assert len(signer_calls) == 0 + assert len(session.requests) == 1 # No paid retry sent + + +async def test_deny_with_reason(make_policy_agent): + def deny_policy(ctx): + return {"decision": "DENY", "reason": "daily budget exceeded"} + + agent, session, signer_calls = make_policy_agent(policy=deny_policy, fail_signer=True) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "DENY" + assert "daily budget exceeded" in exc_info.value.message + assert len(signer_calls) == 0 + + +async def test_wait_never_calls_signer(make_policy_agent): + def wait_policy(ctx): + return "WAIT" + + agent, session, signer_calls = make_policy_agent(policy=wait_policy, fail_signer=True) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "WAIT" + assert exc_info.value.signer_called is False + assert len(signer_calls) == 0 + assert len(session.requests) == 1 + + +async def test_wait_with_reason(make_policy_agent): + def wait_policy(ctx): + return {"decision": "WAIT", "reason": "requires human approval"} + + agent, session, signer_calls = make_policy_agent(policy=wait_policy, fail_signer=True) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "WAIT" + assert "requires human approval" in exc_info.value.message + assert len(signer_calls) == 0 + + +# 3. Fail Closed on Policy Exception + + +async def test_policy_exception_fails_closed(make_policy_agent): + def crashing_policy(ctx): + raise RuntimeError("database connection failed") + + agent, session, signer_calls = make_policy_agent(policy=crashing_policy, fail_signer=True) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "ENGINE_ERROR" + assert "database connection failed" in exc_info.value.message + assert len(signer_calls) == 0 + assert len(session.requests) == 1 + + +# 4. Stale ALLOW Refusal + + +async def test_stale_allow_refused(make_policy_agent): + # Policy returns version v1, but currentVersion returns v2 + def allow_policy(ctx): + return { + "decision": "ALLOW", + "contextHash": ctx.contextHash, + "policyVersion": "v1", + } + + agent, session, signer_calls = make_policy_agent( + policy=allow_policy, + current_version=lambda ctx: "v2", + fail_signer=True, + ) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "STALE" + assert "v1" in exc_info.value.message + assert "v2" in exc_info.value.message + assert len(signer_calls) == 0 + + +async def test_matching_version_allows_and_signs(make_policy_agent): + def allow_policy(ctx): + return { + "decision": "ALLOW", + "contextHash": ctx.contextHash, + "policyVersion": "v2", + } + + agent, _, signer_calls = make_policy_agent( + policy=allow_policy, + current_version=lambda ctx: "v2", + ) + + res = await agent.x402_fetch(URL) + assert res["ok"] is True + assert len(signer_calls) == 1 + + +async def test_missing_version_with_current_version_configured(make_policy_agent): + def allow_policy(ctx): + return {"decision": "ALLOW"} + + agent, _, _ = make_policy_agent( + policy=allow_policy, + current_version=lambda ctx: "v1", + fail_signer=True, + ) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "MALFORMED" + + +# 5. Expired and Unbound ALLOW + + +async def test_expired_allow_refused(make_policy_agent): + def expired_policy(ctx): + return { + "decision": "ALLOW", + "contextHash": ctx.contextHash, + "expiresAt": 1000, # Far past epoch + } + + agent, _, signer_calls = make_policy_agent(policy=expired_policy, fail_signer=True) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "EXPIRED" + assert len(signer_calls) == 0 + + +async def test_unbound_allow_refused(make_policy_agent): + def unbound_policy(ctx): + return { + "decision": "ALLOW", + "contextHash": "0000000000000000000000000000000000000000000000000000000000000000", + } + + agent, _, signer_calls = make_policy_agent(policy=unbound_policy, fail_signer=True) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "UNBOUND" + assert len(signer_calls) == 0 + + +# 6. Object Hook with evaluate() Method + + +class BudgetPolicyHook: + def __init__(self, max_allowed: int, version: str = "v1"): + self.max_allowed = max_allowed + self.ver = version + + def evaluate(self, ctx: X402PolicyContext) -> Dict[str, Any]: + if int(ctx.amount) <= self.max_allowed: + return { + "decision": "ALLOW", + "contextHash": ctx.contextHash, + "policyVersion": self.ver, + } + return {"decision": "DENY", "reason": f"amount exceeds {self.max_allowed}"} + + def current_version(self, ctx: X402PolicyContext) -> str: + return self.ver + + +async def test_object_hook_allows_within_budget(make_policy_agent): + hook = BudgetPolicyHook(max_allowed=1000000) + agent, _, signer_calls = make_policy_agent(policy=hook) + + res = await agent.x402_fetch(URL) + assert res["ok"] is True + assert len(signer_calls) == 1 + + +async def test_object_hook_denies_over_budget(make_policy_agent): + hook = BudgetPolicyHook(max_allowed=100000) # 0.01 USDC, challenge asks for 0.05 + agent, _, signer_calls = make_policy_agent(policy=hook, fail_signer=True) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "DENY" + assert len(signer_calls) == 0 + + +# 7. on_decision Observer + + +async def test_on_decision_observer_tracks_lifecycle(make_policy_agent): + records = [] + + def observer(record): + records.append(record) + + def allow_policy(ctx): + return "ALLOW" + + agent, _, _ = make_policy_agent(policy=allow_policy, on_decision=observer) + await agent.x402_fetch(URL) + + outcomes = [r["outcome"] for r in records] + assert "ALLOWED" in outcomes + assert "SIGNED" in outcomes + + +async def test_on_decision_observer_on_deny(make_policy_agent): + records = [] + + def observer(record): + records.append(record) + + def deny_policy(ctx): + return "DENY" + + agent, _, _ = make_policy_agent(policy=deny_policy, on_decision=observer, fail_signer=True) + + with pytest.raises(X402PolicyError): + await agent.x402_fetch(URL) + + outcomes = [r["outcome"] for r in records] + assert outcomes == ["DENY"] From 82d4c4119b2ccbffed8797ecba543cc406e2a024 Mon Sep 17 00:00:00 2001 From: comandanto <89469777+comandanto@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:26:02 +0300 Subject: [PATCH 2/6] feat(sdk-python): address review comments on pre-sign policy hook --- packages/sdk-python/src/nirium/client.py | 224 ++++++++++-------- packages/sdk-python/tests/test_x402_policy.py | 136 +++++++++-- 2 files changed, 245 insertions(+), 115 deletions(-) diff --git a/packages/sdk-python/src/nirium/client.py b/packages/sdk-python/src/nirium/client.py index 67c62339..d1159d73 100644 --- a/packages/sdk-python/src/nirium/client.py +++ b/packages/sdk-python/src/nirium/client.py @@ -19,7 +19,8 @@ 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, build_authorization_preimage, authorization_payload_hash # type: ignore +import stellar_sdk.xdr as stellar_xdr # type: ignore import base64 as _b64 import math as _math @@ -885,7 +886,6 @@ def init_x402( policy_timeout_ms: Optional[int] = None, on_decision: Optional[Callable[[Dict[str, Any]], None]] = None, now: Optional[Callable[[], float]] = None, - signer: Optional[Callable[..., Any]] = None, ): """ Initialize the x402 pay-per-request client (protocol v2). @@ -911,7 +911,6 @@ def init_x402( policy_timeout_ms: Hard deadline for pre-sign policy evaluation in ms (default 5000). on_decision: Optional observer callback receiving record of policy outcome. now: Optional callable returning epoch milliseconds, for testing. - signer: Optional custom signer override (e.g. for testing without keypair). A 402 whose options are all on a different network than ``network`` is always refused: the client never falls back to another network. @@ -943,7 +942,6 @@ def init_x402( self._x402_policy_timeout_ms = policy_timeout_ms or 5000 self._x402_on_decision = on_decision self._x402_now = now - self._x402_signer = signer is_testnet = network == "stellar:testnet" self._x402_keypair = Keypair.from_secret(secret_key) self._x402_network = network @@ -1033,12 +1031,6 @@ def amount_of(a: Dict[str, Any]) -> Optional[int]: return candidate raise X402SpendCapError(url, candidate, cap_label, reason) - def _x402_sign_auth_entry(self, entry: Any, max_ledger: int) -> Any: - signer = getattr(self, "_x402_signer", None) - if signer is not None and callable(signer): - return signer(entry, self._x402_keypair, max_ledger, self._x402_passphrase) - return authorize_entry(entry, self._x402_keypair, max_ledger, self._x402_passphrase) - def _x402_report_decision( self, outcome: str, @@ -1070,47 +1062,78 @@ def _x402_report_decision( except Exception: pass - async def _x402_run_policy( + async def _x402_authorize_entry_with_policy( self, + entry: Any, + max_ledger: int, + accepted: Dict[str, Any], url: str, method: str, - accepted: Dict[str, Any], - ) -> X402PolicyDecision: + ) -> Any: policy = getattr(self, "_x402_policy", None) - if policy is None: - return X402PolicyDecision(decision="ALLOW") - - now_fn = getattr(self, "_x402_now", None) or (lambda: time.time() * 1000.0) account = self._x402_keypair.public_key - - timeout_sec = accepted.get("maxTimeoutSeconds", 300) - base_timeout_ms = getattr( - policy, - "timeout_ms", - getattr(policy, "timeoutMs", getattr(self, "_x402_policy_timeout_ms", 5000)), - ) - if timeout_sec and timeout_sec > 0: - effective_timeout_ms = max(1, min(base_timeout_ms, int((timeout_sec * 1000) / 2))) + network_passphrase = self._x402_passphrase + + if self._x402_keypair.public_key != account: + self._x402_report_decision("SIGNER_CHANGED", err="base signer address changed before gate evaluation") + raise X402PolicyError("SIGNER_CHANGED", "base signer address changed before gate evaluation") + + preimage = build_authorization_preimage(entry, max_ledger, network_passphrase) + payload_hash = authorization_payload_hash(preimage).hex() + + if preimage.type == stellar_xdr.EnvelopeType.ENVELOPE_TYPE_SOROBAN_AUTHORIZATION: + auth = preimage.soroban_authorization + preimage_type = "legacy" + elif preimage.type == stellar_xdr.EnvelopeType.ENVELOPE_TYPE_SOROBAN_AUTHORIZATION_WITH_ADDRESS: + auth = preimage.soroban_authorization_with_address + preimage_type = "cap71" + bound_address = Address.from_xdr_sc_address(auth.address).address + if bound_address != account: + raise X402PolicyError("CONTEXT_MISMATCH", "CAP-71 preimage is bound to a different address than the signer") else: - effective_timeout_ms = base_timeout_ms - - payload_hash = _sha256_hex( - f"{accepted.get('asset')}:{accepted.get('payTo')}:{accepted.get('amount')}:{self._x402_network}" - ) - context_hash = _sha256_hex( - json.dumps({"v": 1, "url": url, "method": method, "payloadHash": payload_hash}, sort_keys=True) - ) + raise X402PolicyError("CONTEXT_MISMATCH", f"unsupported preimage type {preimage.type}") + + fn = auth.invocation.function + if fn.type != stellar_xdr.SorobanAuthorizedFunctionType.SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN: + raise X402PolicyError("CONTEXT_MISMATCH", f"unexpected authorized function {fn.type}") + + contract_fn = fn.contract_fn + contract_id = Address.from_xdr_sc_address(contract_fn.contract_address).address + function_name = contract_fn.function_name.sc_symbol.decode() + if function_name != "transfer" or len(contract_fn.args) != 3: + raise X402PolicyError("CONTEXT_MISMATCH", f"expected transfer(from,to,amount), got {function_name}/{len(contract_fn.args)}") + + from_addr = Address.from_xdr_sc_val(contract_fn.args[0]).address + to_addr = Address.from_xdr_sc_val(contract_fn.args[1]).address + amount_val = str(scval.from_int128(contract_fn.args[2])) + + if contract_id != accepted.get("asset"): + raise X402PolicyError("CONTEXT_MISMATCH", "asset contract differs from requirements.asset") + if to_addr != accepted.get("payTo"): + raise X402PolicyError("CONTEXT_MISMATCH", "destination differs from requirements.payTo") + if str(amount_val) != str(accepted.get("amount")): + raise X402PolicyError("CONTEXT_MISMATCH", "amount differs from requirements.amount") + if from_addr != account: + raise X402PolicyError("CONTEXT_MISMATCH", "from differs from signer address") auth_view = { + "preimageXdr": preimage.to_xdr(), + "preimageType": preimage_type, "payloadHash": payload_hash, - "contractId": accepted.get("asset", ""), - "functionName": "transfer", - "from": account, - "to": accepted.get("payTo", ""), - "amount": str(accepted.get("amount", "")), - "networkPassphrase": self._x402_passphrase, + "networkPassphrase": network_passphrase, + "nonce": str(auth.nonce.int64), + "signatureExpirationLedger": int(auth.signature_expiration_ledger.uint32), + "contractId": contract_id, + "functionName": function_name, + "from": from_addr, + "to": to_addr, + "amount": amount_val, } + context_hash = _sha256_hex( + json.dumps({"v": 1, "url": url, "method": method, "payloadHash": payload_hash}, sort_keys=True) + ) + context = X402PolicyContext( contextVersion=1, context_version=1, @@ -1129,20 +1152,35 @@ async def _x402_run_policy( authorization=auth_view, ) - def read_clock() -> float: + now_fn = getattr(self, "_x402_now", None) or (lambda: time.time() * 1000.0) + + def read_clock(decision: Optional[X402PolicyDecision] = None) -> float: try: t = now_fn() except Exception as e: - refuse("CLOCK_INVALID", f"clock threw ({e})") + refuse("CLOCK_INVALID", f"clock threw ({e})", decision=decision) if not isinstance(t, (int, float)) or _math.isnan(t) or _math.isinf(t): - refuse("CLOCK_INVALID", f"clock returned {t!r}, not epoch milliseconds") + refuse("CLOCK_INVALID", f"clock returned {t!r}, not epoch milliseconds", decision=decision) return float(t) def refuse(outcome: str, msg: str, decision: Optional[X402PolicyDecision] = None) -> NoReturn: self._x402_report_decision(outcome, context=context, decision=decision, err=msg) raise X402PolicyError(outcome, msg, decision=decision, context_hash=context_hash) + if self._x402_keypair.public_key != account: + refuse("SIGNER_CHANGED", "signer address changed before policy evaluation") + start_time = read_clock() + timeout_sec = accepted.get("maxTimeoutSeconds", 300) + base_timeout_ms = getattr( + policy, + "timeout_ms", + getattr(policy, "timeoutMs", getattr(self, "_x402_policy_timeout_ms", 5000)), + ) + if timeout_sec and timeout_sec > 0: + effective_timeout_ms = max(1, min(base_timeout_ms, int((timeout_sec * 1000) / 2))) + else: + effective_timeout_ms = base_timeout_ms deadline = start_time + effective_timeout_ms eval_fn = getattr(policy, "evaluate", policy if callable(policy) else None) @@ -1170,11 +1208,11 @@ def refuse(outcome: str, msg: str, decision: Optional[X402PolicyDecision] = None if decision.decision == "WAIT": refuse("WAIT", decision.reason or "payment waiting on approval", decision=decision) - # Verdict is ALLOW - if decision.contextHash and decision.contextHash != context_hash: + # Verdict is ALLOW: Must echo the exact contextHash (otherwise UNBOUND) + if not decision.contextHash or decision.contextHash != context_hash: refuse("UNBOUND", "ALLOW is not bound to this authorization", decision=decision) - now_t = read_clock() + now_t = read_clock(decision=decision) if now_t >= deadline: refuse("TIMEOUT", "decision arrived after the deadline", decision=decision) @@ -1210,7 +1248,7 @@ def refuse(outcome: str, msg: str, decision: Optional[X402PolicyDecision] = None if str(curr_ver) != str(decision.policyVersion): refuse("STALE", f"ALLOW was issued under policy {decision.policyVersion}, current is {curr_ver}", decision=decision) - now_t = read_clock() + now_t = read_clock(decision=decision) if decision.expiresAt is not None: exp_t = decision.expiresAt if exp_t < 1e11: @@ -1221,31 +1259,26 @@ def refuse(outcome: str, msg: str, decision: Optional[X402PolicyDecision] = None self._x402_report_decision("ALLOWED", context=context, decision=decision) self._x402_last_policy_context = context self._x402_last_policy_decision = decision - return decision - def _x402_build_transaction(self, accepted: Dict[str, Any]) -> str: - """ - Build the signed payment transaction for one payment requirement. + # Check identity before signing: SIGNER_CHANGED if account changed + if self._x402_keypair.public_key != account: + refuse("SIGNER_CHANGED", "signer address changed while the policy was evaluated", decision=decision) - Mirrors the canonical @x402/stellar client. Three details are what make - it settle, each verified against a TypeScript-generated reference: - - 1. The source account is the NULL account, not the payer. The - facilitator replaces it with its own when it submits and pays the - fee. Using the payer's account makes the simulator emit - source-account credentials, which the facilitator cannot honour. - 2. The auth entry must therefore carry ADDRESS credentials, signed with - an expiration ledger. - 3. The transaction must be re-simulated AFTER signing: the signature - adds bytes, and the resource fee computed before it is too low. - """ + try: + signed_entry = authorize_entry(entry, self._x402_keypair, max_ledger, network_passphrase) + self._x402_report_decision("SIGNED", context=context, decision=decision) + return signed_entry + except Exception as e: + self._x402_report_decision("SIGNER_ERROR", context=context, decision=decision, err=str(e)) + raise + + def _x402_prepare_transaction(self, accepted: Dict[str, Any]) -> tuple[Any, int, SorobanServer]: extra = accepted.get("extra") or {} if not extra.get("areFeesSponsored"): raise RuntimeError("x402 exact scheme requires areFeesSponsored to be true") soroban = SorobanServer(self._x402_rpc_url) timeout = int(accepted.get("maxTimeoutSeconds", 300)) - # ~5 s por ledger, el mismo supuesto del cliente canónico. max_ledger = soroban.get_latest_ledger().sequence + _math.ceil(timeout / 5) tx = ( @@ -1268,11 +1301,38 @@ def _x402_build_transaction(self, accepted: Dict[str, Any]) -> str: ) prepared = soroban.prepare_transaction(tx) + return prepared, max_ledger, soroban + + async def _x402_build_transaction( + self, + accepted: Dict[str, Any], + url: str = "", + method: str = "GET", + ) -> str: + """ + Build the signed payment transaction for one payment requirement. + + Prepares the Soroban transaction first, evaluates pre-sign policy over + the actual authorization entry (if configured), signs the entry, and + re-simulates for fee estimation. + """ + prepared, max_ledger, soroban = self._x402_prepare_transaction(accepted) op = prepared.transaction.operations[0] - op.auth = [ - self._x402_sign_auth_entry(e, max_ledger) - for e in (op.auth or []) - ] + + signed_auth = [] + for e in (op.auth or []): + if getattr(self, "_x402_policy", None) is not None: + signed_e = await self._x402_authorize_entry_with_policy( + entry=e, + max_ledger=max_ledger, + accepted=accepted, + url=url, + method=method, + ) + else: + signed_e = authorize_entry(e, self._x402_keypair, max_ledger, self._x402_passphrase) + signed_auth.append(signed_e) + op.auth = signed_auth sim = soroban.simulate_transaction(prepared) if getattr(sim, "error", None): @@ -1349,8 +1409,7 @@ async def x402_fetch( async with aiohttp.ClientSession() as session: async with session.request(method, url, **payload) as resp: if resp.status != 402: - res = self._x402_read_payload(resp) - return (await res) if inspect.isawaitable(res) else res + return await self._x402_read_payload(resp) # v2 entrega los requirements en un header base64; el body va vacío. raw = resp.headers.get("payment-required") @@ -1367,27 +1426,7 @@ async def x402_fetch( accepted = await self._x402_select_requirement(url, accepts) - policy_decision = None - if getattr(self, "_x402_policy", None) is not None: - policy_decision = await self._x402_run_policy(url=url, method=method, accepted=accepted) - - try: - tx_xdr = self._x402_build_transaction(accepted) - if policy_decision is not None: - self._x402_report_decision( - "SIGNED", - context=getattr(self, "_x402_last_policy_context", None), - decision=policy_decision, - ) - except Exception as e: - if policy_decision is not None and not isinstance(e, X402PolicyError): - self._x402_report_decision( - "SIGNER_ERROR", - context=getattr(self, "_x402_last_policy_context", None), - decision=policy_decision, - err=str(e), - ) - raise + tx_xdr = await self._x402_build_transaction(accepted, url=url, method=method) payment = { "x402Version": challenge.get("x402Version", 2), @@ -1407,8 +1446,7 @@ async def x402_fetch( f"x402 payment rejected (HTTP {paid.status}): {rejected[:300]}" ) self._x402_store_settlement(paid.headers) - res = self._x402_read_payload(paid) - return (await res) if inspect.isawaitable(res) else res + return await self._x402_read_payload(paid) # ─── MPP Protocol (Charge Mode) ───────────────────────── diff --git a/packages/sdk-python/tests/test_x402_policy.py b/packages/sdk-python/tests/test_x402_policy.py index 2d97606d..c3de14b9 100644 --- a/packages/sdk-python/tests/test_x402_policy.py +++ b/packages/sdk-python/tests/test_x402_policy.py @@ -3,12 +3,13 @@ Verifies the Python SDK provides the exact same policy hook guarantees as the TypeScript SDK (x402-policy.ts): - Policy receives the context (amount, asset, payee, resource, network, contextHash, authorization, etc.) -- ALLOW signs and pays +- ALLOW signs and pays only when bound to the authorization preimage contextHash - DENY and WAIT never call the signer (verified with a failing signer mock) - Fail closed when policy raises an exception - Stale ALLOW refused when policyVersion != currentVersion - Expired ALLOW refused when expiresAt has passed -- Unbound ALLOW refused when contextHash does not match +- Unbound ALLOW refused when contextHash does not match or is missing +- Signer identity changed between decision and signing refused as SIGNER_CHANGED - Timeout enforced - on_decision observer receives expected records """ @@ -21,7 +22,8 @@ from typing import Any, Dict, List import pytest -from stellar_sdk import Keypair +from stellar_sdk import Keypair, Address, scval +import stellar_sdk.xdr as stellar_xdr import nirium.client as client_mod from nirium import ( @@ -102,23 +104,77 @@ def _make(policy=None, accepts=None, fail_signer=False, **init_kwargs): signer_calls = [] - def mock_signer(entry, keypair, max_ledger, passphrase): - if fail_signer: - pytest.fail("SIGNER MUST NEVER BE CALLED ON DENY/WAIT/ERROR") - signer_calls.append({"entry": entry, "keypair": keypair, "max_ledger": max_ledger}) - return "SIGNED_AUTH_ENTRY" + orig_authorize = client_mod.authorize_entry - def fake_build(accepted): - # When build_transaction is called, it simulates the signer invocation + def mock_authorize(entry, keypair, max_ledger, passphrase): if fail_signer: - pytest.fail("SIGNER / BUILD_TRANSACTION MUST NEVER BE CALLED ON DENY/WAIT/ERROR") - mock_signer(None, None, 100, "") - return "MOCK_SIGNED_TX_XDR" + pytest.fail("SIGNER / authorize_entry MUST NEVER BE CALLED ON DENY/WAIT/ERROR") + signer_calls.append({"entry": entry, "keypair": keypair, "max_ledger": max_ledger}) + return orig_authorize(entry, keypair, max_ledger, passphrase) + + monkeypatch.setattr(client_mod, "authorize_entry", mock_authorize) + + def fake_prepare(accepted): + entry = stellar_xdr.SorobanAuthorizationEntry( + credentials=stellar_xdr.SorobanCredentials( + type=stellar_xdr.SorobanCredentialsType.SOROBAN_CREDENTIALS_ADDRESS, + address=stellar_xdr.SorobanAddressCredentials( + address=Address(agent._x402_keypair.public_key).to_xdr_sc_address(), + nonce=stellar_xdr.Int64(1), + signature_expiration_ledger=stellar_xdr.Uint32(100), + signature=stellar_xdr.SCVal(type=stellar_xdr.SCValType.SCV_VOID), + ), + ), + root_invocation=stellar_xdr.SorobanAuthorizedInvocation( + function=stellar_xdr.SorobanAuthorizedFunction( + type=stellar_xdr.SorobanAuthorizedFunctionType.SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN, + contract_fn=stellar_xdr.InvokeContractArgs( + contract_address=Address(accepted["asset"]).to_xdr_sc_address(), + function_name=stellar_xdr.SCSymbol("transfer".encode()), + args=[ + Address(agent._x402_keypair.public_key).to_xdr_sc_val(), + Address(accepted["payTo"]).to_xdr_sc_val(), + scval.to_int128(int(accepted["amount"])), + ], + ), + ), + sub_invocations=[], + ), + ) + + class FakeOp: + def __init__(self, auth): + self.auth = auth + + class FakeTx: + def __init__(self, op): + self.operations = [op] + self.soroban_data = None + self.fee = 100 + + class FakePrepared: + def __init__(self, op): + self.transaction = FakeTx(op) + + def to_xdr(self): + return "MOCK_SIGNED_TX_XDR" + + class FakeSoroban: + def simulate_transaction(self, prep): + class FakeSim: + error = None + min_resource_fee = 100 + transaction_data = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" + + return FakeSim() + + return FakePrepared(FakeOp([entry])), 100, FakeSoroban() + + monkeypatch.setattr(agent, "_x402_prepare_transaction", fake_prepare) async def fake_read(resp): return resp._body - monkeypatch.setattr(agent, "_x402_build_transaction", fake_build) monkeypatch.setattr(agent, "_x402_read_payload", fake_read) monkeypatch.setattr(agent, "_x402_store_settlement", lambda h: None) @@ -126,7 +182,6 @@ async def fake_read(resp): SECRET, network="stellar:testnet", policy=policy, - signer=mock_signer, **init_kwargs, ) return agent, session, signer_calls @@ -142,7 +197,7 @@ async def test_allow_callable_signs_and_settles(make_policy_agent): def allow_policy(ctx: X402PolicyContext): seen_context.append(ctx) - return "ALLOW" + return {"decision": "ALLOW", "contextHash": ctx.contextHash} agent, session, signer_calls = make_policy_agent(policy=allow_policy) res = await agent.x402_fetch(URL) @@ -162,6 +217,8 @@ def allow_policy(ctx: X402PolicyContext): assert ctx.network == "stellar:testnet" assert ctx.method == "GET" assert ctx.contextHash is not None + assert ctx.authorization["functionName"] == "transfer" + assert ctx.authorization["payloadHash"] is not None async def test_allow_dict_with_conformance_fields(make_policy_agent): @@ -181,7 +238,7 @@ def allow_policy(ctx): async def test_async_policy_allow(make_policy_agent): async def async_policy(ctx): - return "ALLOW" + return {"decision": "ALLOW", "contextHash": ctx.contextHash} agent, _, signer_calls = make_policy_agent(policy=async_policy) res = await agent.x402_fetch(URL) @@ -272,7 +329,6 @@ def crashing_policy(ctx): async def test_stale_allow_refused(make_policy_agent): - # Policy returns version v1, but currentVersion returns v2 def allow_policy(ctx): return { "decision": "ALLOW", @@ -315,7 +371,7 @@ def allow_policy(ctx): async def test_missing_version_with_current_version_configured(make_policy_agent): def allow_policy(ctx): - return {"decision": "ALLOW"} + return {"decision": "ALLOW", "contextHash": ctx.contextHash} agent, _, _ = make_policy_agent( policy=allow_policy, @@ -365,7 +421,43 @@ def unbound_policy(ctx): assert len(signer_calls) == 0 -# 6. Object Hook with evaluate() Method +async def test_allow_without_context_hash_is_unbound(make_policy_agent): + """Bare 'ALLOW' string or ALLOW dict without contextHash must be refused as UNBOUND.""" + # Case A: Bare string "ALLOW" + agent, _, signer_calls = make_policy_agent(policy=lambda ctx: "ALLOW", fail_signer=True) + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + assert exc_info.value.outcome == "UNBOUND" + assert len(signer_calls) == 0 + + # Case B: Dict with decision ALLOW but no contextHash + agent2, _, signer_calls2 = make_policy_agent(policy=lambda ctx: {"decision": "ALLOW"}, fail_signer=True) + with pytest.raises(X402PolicyError) as exc_info2: + await agent2.x402_fetch(URL) + assert exc_info2.value.outcome == "UNBOUND" + assert len(signer_calls2) == 0 + + +# 6. SIGNER_CHANGED refusal + + +async def test_signer_changed_between_decision_and_signing(make_policy_agent): + """If the agent's keypair address changes during policy evaluation, refuse with SIGNER_CHANGED.""" + def mutating_policy(ctx): + # Maliciously or concurrently change the signer keypair + agent._x402_keypair = Keypair.random() + return {"decision": "ALLOW", "contextHash": ctx.contextHash} + + agent, _, signer_calls = make_policy_agent(policy=mutating_policy, fail_signer=True) + + with pytest.raises(X402PolicyError) as exc_info: + await agent.x402_fetch(URL) + + assert exc_info.value.outcome == "SIGNER_CHANGED" + assert len(signer_calls) == 0 + + +# 7. Object Hook with evaluate() Method class BudgetPolicyHook: @@ -406,7 +498,7 @@ async def test_object_hook_denies_over_budget(make_policy_agent): assert len(signer_calls) == 0 -# 7. on_decision Observer +# 8. on_decision Observer async def test_on_decision_observer_tracks_lifecycle(make_policy_agent): @@ -416,7 +508,7 @@ def observer(record): records.append(record) def allow_policy(ctx): - return "ALLOW" + return {"decision": "ALLOW", "contextHash": ctx.contextHash} agent, _, _ = make_policy_agent(policy=allow_policy, on_decision=observer) await agent.x402_fetch(URL) From bf91008d6181d764ddafda8ea5efb7dbc8d1adad Mon Sep 17 00:00:00 2001 From: comandanto <89469777+comandanto@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:19:44 +0300 Subject: [PATCH 3/6] fix(python-sdk): align contextHash with TS SDK and raise stellar-sdk floor --- packages/sdk-python/CHANGELOG.md | 2 ++ packages/sdk-python/pyproject.toml | 2 +- packages/sdk-python/src/nirium/client.py | 6 ++++-- packages/sdk-python/tests/test_x402_policy.py | 19 +++++++++++++++++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/packages/sdk-python/CHANGELOG.md b/packages/sdk-python/CHANGELOG.md index 0b877518..05b26d98 100644 --- a/packages/sdk-python/CHANGELOG.md +++ b/packages/sdk-python/CHANGELOG.md @@ -5,6 +5,8 @@ All notable changes to the `nirium` (PyPI) package are documented here. ## Unreleased - Pre-sign policy hook (`init_x402(policy=...)`): parity with TypeScript SDK pre-sign policy hook (#355). Evaluates policy before signing; DENY and WAIT never call the signer; fail closed on exceptions; stale ALLOW invalidation via `current_version`. +- Raised `stellar-sdk` dependency floor to `>=15.0.0` for Soroban authorization preimage and payload hash support (`build_authorization_preimage`, `authorization_payload_hash`, and address envelope constants). +- Aligned `contextHash` wire formatting with the TypeScript SDK (`{"v":1,"url":"...","method":"...","payloadHash":"..."}` with exact key ordering and no whitespace separators). ## 0.12.7 - 2026-11-19 diff --git a/packages/sdk-python/pyproject.toml b/packages/sdk-python/pyproject.toml index 9c5182d1..107e05c0 100644 --- a/packages/sdk-python/pyproject.toml +++ b/packages/sdk-python/pyproject.toml @@ -14,7 +14,7 @@ keywords = ["stellar", "x402", "usdc", "payments", "pay-per-request", "ai-agents dependencies = [ "aiohttp>=3.9.0", "websockets>=13.0", - "stellar-sdk>=11.0.0,<16.0.0", + "stellar-sdk>=15.0.0,<16.0.0", ] [project.optional-dependencies] diff --git a/packages/sdk-python/src/nirium/client.py b/packages/sdk-python/src/nirium/client.py index d1159d73..1c6c54f7 100644 --- a/packages/sdk-python/src/nirium/client.py +++ b/packages/sdk-python/src/nirium/client.py @@ -19,7 +19,7 @@ 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, build_authorization_preimage, authorization_payload_hash # type: ignore +from stellar_sdk.auth import authorize_entry # type: ignore import stellar_sdk.xdr as stellar_xdr # type: ignore import base64 as _b64 import math as _math @@ -1078,6 +1078,8 @@ async def _x402_authorize_entry_with_policy( self._x402_report_decision("SIGNER_CHANGED", err="base signer address changed before gate evaluation") raise X402PolicyError("SIGNER_CHANGED", "base signer address changed before gate evaluation") + from stellar_sdk.auth import build_authorization_preimage, authorization_payload_hash # type: ignore + preimage = build_authorization_preimage(entry, max_ledger, network_passphrase) payload_hash = authorization_payload_hash(preimage).hex() @@ -1131,7 +1133,7 @@ async def _x402_authorize_entry_with_policy( } context_hash = _sha256_hex( - json.dumps({"v": 1, "url": url, "method": method, "payloadHash": payload_hash}, sort_keys=True) + json.dumps({"v": 1, "url": url, "method": method, "payloadHash": payload_hash}, separators=(",", ":"), ensure_ascii=False) ) context = X402PolicyContext( diff --git a/packages/sdk-python/tests/test_x402_policy.py b/packages/sdk-python/tests/test_x402_policy.py index c3de14b9..e821a08b 100644 --- a/packages/sdk-python/tests/test_x402_policy.py +++ b/packages/sdk-python/tests/test_x402_policy.py @@ -534,3 +534,22 @@ def deny_policy(ctx): outcomes = [r["outcome"] for r in records] assert outcomes == ["DENY"] + + +def test_context_hash_conformance_with_typescript_sdk(): + """Verify that Python SDK contextHash wire format and sha256hex match the TypeScript SDK exactly.""" + # Test vector produced by TypeScript SDK: + # sha256hex(JSON.stringify({ v: 1, url: 'https://api.example.com/pay', method: 'POST', payloadHash: 'abcd1234ef5678' })) + url = "https://api.example.com/pay" + method = "POST" + payload_hash = "abcd1234ef5678" + expected_hash = "9619ef78d875fe02387e6d06b0d79c42d7fb9b3499ac5737e4e257f6d1bafc9d" + + wire = json.dumps( + {"v": 1, "url": url, "method": method, "payloadHash": payload_hash}, + separators=(",", ":"), + ensure_ascii=False, + ) + assert wire == '{"v":1,"url":"https://api.example.com/pay","method":"POST","payloadHash":"abcd1234ef5678"}' + assert client_mod._sha256_hex(wire) == expected_hash + From c4c331154a91a05b0f049e84fa1207065868cda1 Mon Sep 17 00:00:00 2001 From: comandanto <89469777+comandanto@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:23:45 +0300 Subject: [PATCH 4/6] fix(sdk-python): support sync single-arg callables for _x402_build_transaction --- packages/sdk-python/src/nirium/client.py | 35 ++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/packages/sdk-python/src/nirium/client.py b/packages/sdk-python/src/nirium/client.py index 1c6c54f7..89d735a5 100644 --- a/packages/sdk-python/src/nirium/client.py +++ b/packages/sdk-python/src/nirium/client.py @@ -1308,8 +1308,8 @@ def _x402_prepare_transaction(self, accepted: Dict[str, Any]) -> tuple[Any, int, async def _x402_build_transaction( self, accepted: Dict[str, Any], - url: str = "", - method: str = "GET", + url: Optional[str] = None, + method: Optional[str] = None, ) -> str: """ Build the signed payment transaction for one payment requirement. @@ -1318,6 +1318,11 @@ async def _x402_build_transaction( the actual authorization entry (if configured), signs the entry, and re-simulates for fee estimation. """ + if url is None: + url = getattr(self, "_current_x402_url", "") + if method is None: + method = getattr(self, "_current_x402_method", "GET") + prepared, max_ledger, soroban = self._x402_prepare_transaction(accepted) op = prepared.transaction.operations[0] @@ -1428,7 +1433,31 @@ async def x402_fetch( accepted = await self._x402_select_requirement(url, accepts) - tx_xdr = await self._x402_build_transaction(accepted, url=url, method=method) + self._current_x402_url = url + self._current_x402_method = method + + build_fn = self._x402_build_transaction + try: + sig = inspect.signature(build_fn) + params = sig.parameters + accepts_url = "url" in params or any( + p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values() + ) + except (ValueError, TypeError): + accepts_url = True + + if accepts_url: + try: + res = build_fn(accepted, url=url, method=method) + except TypeError: + res = build_fn(accepted) + else: + res = build_fn(accepted) + + if inspect.isawaitable(res): + tx_xdr = await res + else: + tx_xdr = res payment = { "x402Version": challenge.get("x402Version", 2), From ba08a24186e99fc4d305572da8a50ad483ffacda Mon Sep 17 00:00:00 2001 From: comandanto <89469777+comandanto@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:27:26 +0300 Subject: [PATCH 5/6] test(sdk-python): update fake_build in test_x402_safety to async signature --- packages/sdk-python/tests/test_x402_safety.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sdk-python/tests/test_x402_safety.py b/packages/sdk-python/tests/test_x402_safety.py index ee15835d..f50e2253 100755 --- a/packages/sdk-python/tests/test_x402_safety.py +++ b/packages/sdk-python/tests/test_x402_safety.py @@ -89,7 +89,7 @@ def _make(accepts, **init_kwargs): agent.init_x402(SECRET, network=init_kwargs.pop("network", "stellar:testnet"), **init_kwargs) signed: List[Dict[str, Any]] = [] - def fake_build(accepted): + async def fake_build(accepted, **_): signed.append(accepted) return "SIGNED_XDR" From f845f5fa6ce6ee13eac2eaaa3679d0c925943964 Mon Sep 17 00:00:00 2001 From: comandanto <89469777+comandanto@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:22:48 +0300 Subject: [PATCH 6/6] fix(sdk-python): remove build_transaction shim and call directly --- packages/sdk-python/src/nirium/client.py | 35 ++---------------------- 1 file changed, 3 insertions(+), 32 deletions(-) diff --git a/packages/sdk-python/src/nirium/client.py b/packages/sdk-python/src/nirium/client.py index 89d735a5..1c6c54f7 100644 --- a/packages/sdk-python/src/nirium/client.py +++ b/packages/sdk-python/src/nirium/client.py @@ -1308,8 +1308,8 @@ def _x402_prepare_transaction(self, accepted: Dict[str, Any]) -> tuple[Any, int, async def _x402_build_transaction( self, accepted: Dict[str, Any], - url: Optional[str] = None, - method: Optional[str] = None, + url: str = "", + method: str = "GET", ) -> str: """ Build the signed payment transaction for one payment requirement. @@ -1318,11 +1318,6 @@ async def _x402_build_transaction( the actual authorization entry (if configured), signs the entry, and re-simulates for fee estimation. """ - if url is None: - url = getattr(self, "_current_x402_url", "") - if method is None: - method = getattr(self, "_current_x402_method", "GET") - prepared, max_ledger, soroban = self._x402_prepare_transaction(accepted) op = prepared.transaction.operations[0] @@ -1433,31 +1428,7 @@ async def x402_fetch( accepted = await self._x402_select_requirement(url, accepts) - self._current_x402_url = url - self._current_x402_method = method - - build_fn = self._x402_build_transaction - try: - sig = inspect.signature(build_fn) - params = sig.parameters - accepts_url = "url" in params or any( - p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values() - ) - except (ValueError, TypeError): - accepts_url = True - - if accepts_url: - try: - res = build_fn(accepted, url=url, method=method) - except TypeError: - res = build_fn(accepted) - else: - res = build_fn(accepted) - - if inspect.isawaitable(res): - tx_xdr = await res - else: - tx_xdr = res + tx_xdr = await self._x402_build_transaction(accepted, url=url, method=method) payment = { "x402Version": challenge.get("x402Version", 2),