Skip to content

feat(sdk-python): add pre-sign policy hook matching TypeScript SDK guarantees - #394

Merged
M0nsxx merged 7 commits into
nirium-protocol:mainfrom
comandanto:feat/python-sdk-presign-policy-hook
Nov 21, 2026
Merged

M0nsxx merged 7 commits into
nirium-protocol:mainfrom
comandanto:feat/python-sdk-presign-policy-hook

Conversation

@comandanto

Copy link
Copy Markdown
Contributor

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

  1. 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).
    • Context passed to the policy includes amount, asset, payee, payTo, resource, url, method, network, signer, contextHash, requirements, and authorization dictionary.
    • Supports verdicts ALLOW, DENY, and WAIT (as strings, dictionaries, or decision objects).
  2. Strict Fail-Closed Guarantees:

    • DENY and WAIT immediately raise X402PolicyError and never invoke the signer.
    • Policy exceptions fail closed with outcome="ENGINE_ERROR" without signing.
    • Unbound ALLOW (mismatched contextHash), expired ALLOW (expiresAt), or malformed verdicts raise X402PolicyError without signing.
    • Evaluator timeouts enforce policy_timeout_ms (bounded by half of maxTimeoutSeconds).
  3. Stale ALLOW Invalidation:

    • When current_version is configured, it is queried after ALLOW and before signing.
    • If policyVersion does not match the current version, the payment is refused with outcome="STALE".
  4. Tests & Coverage:

    • Added 17 unit tests in packages/sdk-python/tests/test_x402_policy.py covering ALLOW, DENY, WAIT, stale ALLOW, fail-closed exceptions, object hooks, and on_decision lifecycle observers.
    • Tests assert that DENY and WAIT never call the signer using a mock that fails the test if invoked. Zero network dependencies.
    • All 40 x402 safety and policy tests pass locally.
  5. Documentation:

    • Added "Pre-sign policy hook" section in packages/sdk-python/README.md matching the TypeScript documentation, including explicit discussion of scope boundaries (in-process limits and pending-capacity reservation).
    • Updated CHANGELOG.md under ## Unreleased.

Testnet Run

  • Settled Payment (ALLOW):
    • Endpoint: https://nirium-agent.fly.dev/api/v1/premium/signals
    • Network: stellar:testnet
    • Asset: CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA (USDC)
    • Amount: 200000 (0.02 USDC)
    • Verdict: ALLOW -> signed Soroban auth entry -> HTTP 200 settled.
  • Denied Payment (DENY - Zero Signatures Released):
    • Endpoint: https://nirium-agent.fly.dev/api/v1/premium/signals
    • Verdict: DENY (reason="daily budget exceeded")
    • Result: Raised X402PolicyError (outcome="DENY"), signer_called: false. Nothing signed, no transaction submitted.

@drips-wave

drips-wave Bot commented Nov 19, 2026

Copy link
Copy Markdown

@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! 🚀

Learn more about application limits

@Eras256 Eras256 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  1. An ALLOW without contextHash is accepted. if decision.contextHash and decision.contextHash != context_hash lets a bare "ALLOW" (string or dict) through. In the TS SDK the ALLOW must echo the context hash, otherwise it's UNBOUND. Please make a missing contextHash an UNBOUND refusal too.

  2. The hash isn't computed over what gets signed. context_hash comes from the payment requirements (asset, payTo, amount, network, url) before _x402_build_transaction runs, and auth_view is built by hand. prepare_transaction can 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.

  3. There's no check that the signer is still the same account between the decision and signing (SIGNER_CHANGED in 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.

@comandanto

Copy link
Copy Markdown
Contributor Author

Hey @Eras256, thanks for the review! All items have been addressed:

  1. A bare ALLOW without \contextHash\ or with mismatched \contextHash\ is now strictly refused as \UNBOUND.
  2. The transaction is prepared first, and the actual Soroban authorization entry preimage is hashed via \�uild_authorization_preimage\ and \�uthorization_payload_hash. The policy evaluation and contextHash are bound directly to this payload hash, and only that entry is signed.
  3. Added the \SIGNER_CHANGED\ check to ensure the signer address hasn't changed between policy evaluation and signing, covered by a dedicated test.
  4. Removed the public \signer=\ parameter from \init_x402\ and reverted the unnecessary awaitable in _x402_read_payload.
  5. All 19 unit tests in \ est_x402_policy.py\ pass cleanly.

@Eras256 Eras256 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. client.py imports build_authorization_preimage and authorization_payload_hash at the top. Those don't exist in stellar-sdk 11, 12 or 13 (they arrived in 14.0.0), and ENVELOPE_TYPE_SOROBAN_AUTHORIZATION_WITH_ADDRESS arrived in 15.0.0. pyproject.toml still allows stellar-sdk>=11.0.0, so on 11 to 13 import nirium fails 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.

  2. 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 like json.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.

@comandanto

Copy link
Copy Markdown
Contributor Author

Hey @Eras256, thanks for the review! Both items have been addressed:

  1. Raised the stellar-sdk dependency floor in pyproject.toml to >=15.0.0, noted it in CHANGELOG.md, and moved the preimage/auth helper imports directly into the policy path.
  2. Aligned contextHash serialization with the TypeScript SDK using json.dumps({"v": 1, "url": url, "method": method, "payloadHash": payload_hash}, separators=(",", ":"), ensure_ascii=False). Added a test confirming exact conformance with the TS SDK hash vector.

All 20 unit tests in test_x402_policy.py pass cleanly.

@Eras256 Eras256 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@comandanto

Copy link
Copy Markdown
Contributor Author

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 Eras256 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 without url/method whenever any TypeError happens inside the real build, which hides real bugs.
  • self._current_x402_url / _current_x402_method live on the agent, so two concurrent x402_fetch calls 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.

@comandanto

Copy link
Copy Markdown
Contributor Author

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>
@Eras256
Eras256 dismissed stale reviews from themself November 21, 2026 19:27

Addressed: contextHash aligned, stellar-sdk floor raised, tests fixed, client.py shim reverted.

@Eras256

Eras256 commented Nov 21, 2026

Copy link
Copy Markdown
Member

AI-assisted comment (Claude)

Thanks for reverting client.py, the PR now touches only what the issue asks for.

The 0.12.8 release (#431) landed in the same two files, so I pushed a9c8bd4 to your branch merging main in: __init__.py keeps both your X402Policy* exports and receipt_cid, and your Unreleased notes sit above the 0.12.8 entry in the CHANGELOG. 94 tests pass locally. Nothing else to do on your side; once CI runs green this goes to merge.

@M0nsxx M0nsxx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@M0nsxx
M0nsxx merged commit ad5465a into nirium-protocol:main Nov 21, 2026
4 checks passed
M0nsxx pushed a commit that referenced this pull request Nov 21, 2026
)

comandanto's Python pre-sign policy hook merged 21 Nov. Wave count
13 -> 14, outside total 37 -> 38, counted with the pulls API across
nirium-protocol repos.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
M0nsxx pushed a commit that referenced this pull request Nov 22, 2026
…, 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Python SDK: pre-sign policy hook, same guarantees as the TypeScript SDK

3 participants