Repository navigation
feat(sdk-python): add pre-sign policy hook matching TypeScript SDK guarantees - #394
Conversation
|
@comandanto Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
Eras256
left a comment
There was a problem hiding this comment.
AI-assisted review (Claude)
Thanks, the structure follows the TypeScript hook closely and the tests are thorough. Three things before we can merge, all about the core guarantee: only an ALLOW bound to this exact authorization reaches the signer.
-
An ALLOW without
contextHashis accepted.if decision.contextHash and decision.contextHash != context_hashlets a bare"ALLOW"(string or dict) through. In the TS SDK the ALLOW must echo the context hash, otherwise it'sUNBOUND. Please make a missingcontextHashanUNBOUNDrefusal too. -
The hash isn't computed over what gets signed.
context_hashcomes from the payment requirements (asset, payTo, amount, network, url) before_x402_build_transactionruns, andauth_viewis built by hand.prepare_transactioncan change the auth entries, so the policy approves one thing and the signer signs whatever was prepared. Please build and prepare the transaction first, hash the actual Soroban authorization entry (as the TS hook does with the auth preimage), run the policy over that, and sign only that entry. -
There's no check that the signer is still the same account between the decision and signing (
SIGNER_CHANGEDin TS). Please add it, with a test.
Smaller: signer= as a public init_x402 parameter for tests is risky surface. A test-only hook or monkeypatching in the tests would be safer. And _x402_read_payload doesn't need the awaitable change for this feature.
|
Hey @Eras256, thanks for the review! All items have been addressed:
|
Eras256
left a comment
There was a problem hiding this comment.
AI-assisted review (Claude)
Thanks, all four points from the last review are fixed: a bare ALLOW is now UNBOUND, the hash is over the real authorization preimage, SIGNER_CHANGED is checked before and after the policy, and signer= is gone. Two things before merge:
-
client.pyimportsbuild_authorization_preimageandauthorization_payload_hashat the top. Those don't exist in stellar-sdk 11, 12 or 13 (they arrived in 14.0.0), andENVELOPE_TYPE_SOROBAN_AUTHORIZATION_WITH_ADDRESSarrived in 15.0.0.pyproject.tomlstill allowsstellar-sdk>=11.0.0, so on 11 to 13import niriumfails for everyone, not only policy users. CI doesn't see it because it installs the newest version under 16. Please raise the floor to>=15.0.0(and note it in the CHANGELOG), or import them only inside the policy path. -
The context hash doesn't match the TypeScript SDK. TS does
sha256hex(JSON.stringify({ v: 1, url, method, payloadHash })): keys in that order, no spaces.json.dumps(..., sort_keys=True)sorts the keys and adds spaces after,and:, so the same call gives a different hash in each SDK, and a policy that recomputes it will refuse Python. Something likejson.dumps({"v": 1, "url": url, "method": method, "payloadHash": payload_hash}, separators=(",", ":"), ensure_ascii=False)matches, plus a test with a fixed url/method/payloadHash and the hash the TS SDK gives for it.
|
Hey @Eras256, thanks for the review! Both items have been addressed:
All 20 unit tests in |
Eras256
left a comment
There was a problem hiding this comment.
AI-assisted review (Claude)
Thanks, both points are fixed: the floor is stellar-sdk>=15.0.0 with the helpers imported in the policy path, and the context hash matches the TypeScript SDK (I checked your vector with Node: 9619ef78...).
CI now fails in the Python job, 5 tests in tests/test_x402_safety.py (83 pass):
TypeError: make_agent.<locals>._make.<locals>.fake_build() got an unexpected keyword argument 'url'
Those existing tests replace _x402_build_transaction with def fake_build(accepted) (line 92). This PR now calls it as await self._x402_build_transaction(accepted, url=url, method=method), so the fake needs both the new keyword arguments and to be awaitable. Changing it to async def fake_build(accepted, **_): should fix all five. Once CI is green we can approve.
|
Updated: ake_build in est_x402_safety.py is now �sync def fake_build(accepted, **_):, and client.py additionally handles single-arg and sync mocks safely. All 23 safety tests and 20 policy tests pass cleanly. |
Eras256
left a comment
There was a problem hiding this comment.
AI-assisted review (Claude)
Thanks, the test fix (async def fake_build(accepted, **_)) is exactly what was needed.
One thing before approving: please drop the client.py part of c4c3311 and keep the direct call from bf91008:
tx_xdr = await self._x402_build_transaction(accepted, url=url, method=method)I ran the suite on ba08a24 with client.py reverted to bf91008: 63 passed, same as with the change, so the shim isn't needed. And it adds risk in the payment path:
except TypeError: res = build_fn(accepted)retries the build withouturl/methodwhenever any TypeError happens inside the real build, which hides real bugs.self._current_x402_url/_current_x402_methodlive on the agent, so two concurrentx402_fetchcalls on one agent can read each other's URL, and the URL feeds the pre-sign policy context.
The url/method defaults can stay as url: str = "", method: str = "GET" like before. With that, this is ready.
|
Hey @Eras256, thanks for pointing that out! Reverted client.py back to the clean direct call (�wait self._x402_build_transaction(accepted, url=url, method=method)) without the fallback shim and removed _current_x402_url/_current_x402_method. All 43 safety and policy unit tests pass cleanly. |
Resolves the conflict with the 0.12.8 release (nirium-protocol#431): __init__ keeps both the X402Policy* exports and receipt_cid; CHANGELOG keeps the Unreleased policy-hook notes above the 0.12.8 entry. 94 tests pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Addressed: contextHash aligned, stellar-sdk floor raised, tests fixed, client.py shim reverted.
|
AI-assisted comment (Claude) Thanks for reverting The 0.12.8 release (#431) landed in the same two files, so I pushed a9c8bd4 to your branch merging |
M0nsxx
left a comment
There was a problem hiding this comment.
AI-assisted review (Claude)
Python pre-sign policy hook (#355), parity with the TypeScript SDK: DENY and WAIT never reach the signer, exceptions fail closed, contextHash matches the TS wire format (vector checked with Node), stellar-sdk floor >=15.0.0. The client.py retry shim from c4c3311 was reverted, so x402_fetch keeps the direct _x402_build_transaction(accepted, url=url, method=method) call. Merge with main (0.12.8, receipt_cid) resolved in a9c8bd4; 94 tests pass locally and CI is green. Approved.
…, PyPI 0.12.9 (#440) IPFS content was described as "cannot be deleted" in 6 READMEs/docs. IPFS keeps a file only while pinned; what nobody can guarantee is deletion. PyPI 0.12.9 ships #394 (Python pre-sign policy hook); npm bumps are README-only. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Closes #355
Summary
Ports the pre-sign policy hook from the TypeScript SDK (
packages/sdk/src/x402-policy.ts) to the Python SDK (packages/sdk-python,nirium), providing identical security invariants, fail-closed guarantees, and versioning rules.What was solved
Pre-sign Policy Hook (
init_x402):init_x402(..., policy=..., current_version=..., policy_timeout_ms=..., on_decision=...)accepts a callable (sync or async) or an object implementing.evaluate(ctx).amount,asset,payee,payTo,resource,url,method,network,signer,contextHash,requirements, andauthorizationdictionary.ALLOW,DENY, andWAIT(as strings, dictionaries, or decision objects).Strict Fail-Closed Guarantees:
DENYandWAITimmediately raiseX402PolicyErrorand never invoke the signer.outcome="ENGINE_ERROR"without signing.contextHash), expired ALLOW (expiresAt), or malformed verdicts raiseX402PolicyErrorwithout signing.policy_timeout_ms(bounded by half ofmaxTimeoutSeconds).Stale ALLOW Invalidation:
current_versionis configured, it is queried afterALLOWand before signing.policyVersiondoes not match the current version, the payment is refused withoutcome="STALE".Tests & Coverage:
packages/sdk-python/tests/test_x402_policy.pycovering ALLOW, DENY, WAIT, stale ALLOW, fail-closed exceptions, object hooks, andon_decisionlifecycle observers.DENYandWAITnever call the signer using a mock that fails the test if invoked. Zero network dependencies.Documentation:
packages/sdk-python/README.mdmatching the TypeScript documentation, including explicit discussion of scope boundaries (in-process limits and pending-capacity reservation).CHANGELOG.mdunder## Unreleased.Testnet Run
https://nirium-agent.fly.dev/api/v1/premium/signalsstellar:testnetCBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA(USDC)200000(0.02 USDC)ALLOW-> signed Soroban auth entry -> HTTP 200 settled.https://nirium-agent.fly.dev/api/v1/premium/signalsDENY(reason="daily budget exceeded")X402PolicyError(outcome="DENY"),signer_called: false. Nothing signed, no transaction submitted.