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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/accounts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,24 @@ description = "Smart Account Contracts and Utilities."
[package.metadata.stellar]
cargo_inherit = true

[package.metadata.docs.rs]
features = ["testutils"]

[lib]
crate-type = ["lib", "cdylib"]
doctest = false

[features]
testutils = ["soroban-sdk/testutils", "dep:ed25519-dalek"]

[dependencies]
soroban-sdk = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde-json-core = { workspace = true }

[target.'cfg(not(target_family = "wasm"))'.dependencies]
ed25519-dalek = { workspace = true, optional = true }

[dev-dependencies]
soroban-sdk = { workspace = true, features = ["testutils"] }
soroban-test-helpers = { workspace = true }
Expand Down
12 changes: 8 additions & 4 deletions packages/accounts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,11 @@ pub trait Policy {

Policies follow a well-defined lifecycle that integrates with context rule management and authorization.

**Installation** occurs when a new context rule is created with attached policies. The smart account calls `install()` on each policy contract, passing account-specific and context-specific parameters. This initialization step allows policies to configure their logic (for example, a threshold policy might define the required number of signatures for that particular account and context rule, while a spending limit policy might set daily or per-transaction caps). Installation ensures that each policy has the necessary state and configuration ready before authorization checks begin.
**Installation** occurs when a policy is attached to a new or existing context rule. The smart account calls `install()` with the rule and installation parameters so the policy can validate its configuration and initialize its state.

**Enforcement** is triggered when a context rule is validated. The smart account calls `enforce()` on each policy in the matched rule. This hook validates authorization requirements (for example, that enough signers are present or that a spending limit is not exceeded) and applies any necessary state changes (for example, updating counters or emitting events). If a policy rejects the authorization attempt, the transaction is reverted.

**Uninstallation** occurs when a context rule is removed from the smart account. The account calls `uninstall()` on each attached policy, allowing them to clean up any stored data associated with that specific account and context rule pairing. This ensures that policies do not leave orphaned state in storage.
**Uninstallation** occurs when a policy is detached or its context rule is removed. The account attempts to call `uninstall()` so the policy can clean up state for that account and rule. Removal can succeed after a recoverable error from the hook, leaving policy state behind.

#### Policy Examples

Expand Down Expand Up @@ -188,7 +188,11 @@ Once no valid rule covers calls to the account, nothing can authorize a manageme

**`enforce()` Responsibilities**

The `enforce()` function handles both validation and state mutation in a single step. It must reject invalid authorization by panicking (which reverts the transaction), and apply any necessary state changes (for example, decrementing a spending allowance or incrementing a counter). Because it runs after signature authentication and context type matching are already confirmed, the focus inside `enforce()` is on business-logic constraints.
The `enforce()` function receives the current authorization context, the context rule, the smart account address, and the subset of rule signers whose authorization was verified. When a rule has policies, those policies decide which signers are required. If all attached policies accept an empty signer set and their other conditions are met, the call can proceed without signatures. Reject invalid authorization by panicking before applying state changes such as decrementing a spending allowance.

The spending limit policy requires at least one authenticated rule signer. If the rule lists multiple signers, pair it with `simple_threshold` to require the intended quorum.

To test a custom policy, enable the crate's `testutils` feature in your dev-dependencies and use `testutils::PolicyTestHarness` to exercise the smart account's authorization hook with selected Ed25519 signers.

### 6. Execution Entry Point

Expand Down Expand Up @@ -264,7 +268,7 @@ Each rule must:

#### Example

Consider a call in the `CallContract(dex_address)` context. The client presents an ed25519 key and a passkey signature. The smart account has a `CallContract(dex_address)` rule requiring both signers and a daily spending limit policy. The client sets `context_rule_ids = [rule_id]`. The account authenticates both keys, validates the rule, and then calls the spending limit policy’s `enforce()`, which checks the limit and updates counters. Authorization succeeds.
Consider a token `transfer` under a `CallContract(token_address)` rule with two signers, a `simple_threshold` policy configured for two signatures, and a daily spending limit policy. The client sets `context_rule_ids = [rule_id]` and supplies both signatures. The account validates the rule and authenticates the signers. Authorization succeeds if the threshold is met and the transfer fits the spending limit.

### Authorizing from a Client

Expand Down
2 changes: 2 additions & 0 deletions packages/accounts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@

pub mod policies;
pub mod smart_account;
#[cfg(all(not(target_family = "wasm"), any(test, feature = "testutils")))]
pub mod testutils;
pub mod verifiers;
13 changes: 12 additions & 1 deletion packages/accounts/src/policies/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ pub trait Policy {
///
/// * `e` - Access to the Soroban environment.
/// * `context` - The authorization context being enforced.
/// * `authenticated_signers` - List of signers that have been verified.
/// * `authenticated_signers` - The subset of the rule's signers whose
/// authorization was verified by the smart account for this attempt.
/// * `context_rule` - The context rule this policy is attached to.
/// * `smart_account` - The address of the smart account being authorized.
///
Expand All @@ -82,6 +83,16 @@ pub trait Policy {
/// time restrictions). See [`simple_threshold`],
/// [`weighted_threshold`], and [`spending_limit`] for reference
/// implementations.
///
/// # Security Warning
///
/// A context rule without policies requires every listed signer. Once
/// a rule has policies, those policies alone determine which signers
/// are required, and all attached policies must succeed. Check
/// `authenticated_signers` against the intended signer requirements, or
/// attach a policy that enforces them. If every policy accepts an empty
/// signer set and its other conditions are met, the rule authorizes the
/// call without signatures.
fn enforce(
e: &Env,
context: Context,
Expand Down
10 changes: 10 additions & 0 deletions packages/accounts/src/policies/spending_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@
//! the specified amount are blocked. It intersects transfer operations and
//! enforces spending limits over a configurable rolling time window.
//!
//! ## Signer requirements
//!
//! This policy requires at least one authenticated signer from the context
//! rule. Any single rule signer satisfies this requirement, even if the rule
//! lists multiple signers. An empty signer set is rejected with
//! [`SpendingLimitError::NotAllowed`]. For a rule with multiple signers,
//! pair this policy with
//! [`simple_threshold`](crate::policies::simple_threshold) to enforce the
//! intended quorum.
//!
//! ## Rolling window semantics
//!
//! The rolling window keeps only the last `period_ledgers` worth of ledger
Expand Down
25 changes: 2 additions & 23 deletions packages/accounts/src/smart_account/test/auth_entries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::{
add_context_rule, do_check_auth, AuthDigestPreimage, AuthPayload, ContextRule,
ContextRuleType, Signer, SmartAccount, SmartAccountError,
},
verifiers::{ed25519, Verifier},
testutils::TestEd25519Verifier,
};

const ACCOUNT_NONCE: i64 = 1;
Expand Down Expand Up @@ -81,27 +81,6 @@ impl CustomAccountInterface for ApprovingAccount {
}
}

#[contract]
struct Ed25519VerifierContract;

#[contractimpl]
impl Verifier for Ed25519VerifierContract {
type KeyData = BytesN<32>;
type SigData = BytesN<64>;

fn verify(e: &Env, hash: Bytes, key_data: BytesN<32>, sig_data: BytesN<64>) -> bool {
ed25519::verify(e, &hash, &key_data, &sig_data)
}

fn canonicalize_key(e: &Env, key_data: BytesN<32>) -> Bytes {
ed25519::canonicalize_key(e, &key_data)
}

fn batch_canonicalize_key(e: &Env, key_data: Vec<BytesN<32>>) -> Vec<Bytes> {
ed25519::batch_canonicalize_key(e, &key_data)
}
}

fn to_scval<T: IntoVal<Env, Val>>(e: &Env, value: T) -> ScVal {
ScVal::try_from_val(e, &value.into_val(e)).unwrap()
}
Expand Down Expand Up @@ -212,7 +191,7 @@ fn delegate_entry(delegate: &Address, account: &Address, arg: ScVal) -> SorobanA
}

fn external_signer(e: &Env) -> (Signer, SigningKey) {
let verifier = e.register(Ed25519VerifierContract, ());
let verifier = e.register(TestEd25519Verifier, ());
let signing_key = SigningKey::from_bytes(&SECRET_KEY);
let public_key = Bytes::from_array(e, signing_key.verifying_key().as_bytes());
(Signer::External(verifier, public_key), signing_key)
Expand Down
175 changes: 175 additions & 0 deletions packages/accounts/src/testutils/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
//! Native test helpers for custom policies. Enable the `testutils` feature
//! on `stellar-accounts` as a dev-dependency.
//!
//! [`PolicyTestHarness`] installs policies on a test account and exercises
//! its real authorization hook with a selected subset of Ed25519 signers.

extern crate alloc;

use ed25519_dalek::{Signer as _, SigningKey};
use soroban_sdk::{
auth::{Context, CustomAccountInterface},
contract, contractimpl,
crypto::Hash,
vec, Address, Bytes, BytesN, Env, Error, IntoVal, Map, String, Val, Vec,
};

use crate::{
smart_account::{
add_context_rule, do_check_auth, AuthDigestPreimage, AuthPayload, ContextRuleType, Signer,
SmartAccountError,
},
verifiers::{ed25519, Verifier},
};

#[cfg(test)]
mod test;

#[contract]
struct PolicyTestAccount;

#[contractimpl]
impl CustomAccountInterface for PolicyTestAccount {
type Error = SmartAccountError;
type Signature = AuthPayload;

fn __check_auth(
e: Env,
signature_payload: Hash<32>,
signatures: AuthPayload,
auth_contexts: Vec<Context>,
) -> Result<(), Self::Error> {
do_check_auth(&e, &signature_payload, &signatures, &auth_contexts)
}
}

#[contract]
pub(crate) struct TestEd25519Verifier;

#[contractimpl]
impl Verifier for TestEd25519Verifier {
type KeyData = BytesN<32>;
type SigData = BytesN<64>;

fn verify(e: &Env, hash: Bytes, key_data: BytesN<32>, sig_data: BytesN<64>) -> bool {
ed25519::verify(e, &hash, &key_data, &sig_data)
}

fn canonicalize_key(e: &Env, key_data: BytesN<32>) -> Bytes {
ed25519::canonicalize_key(e, &key_data)
}

fn batch_canonicalize_key(e: &Env, key_data: Vec<BytesN<32>>) -> Vec<Bytes> {
ed25519::batch_canonicalize_key(e, &key_data)
}
}

/// A native Soroban test account with one context rule and Ed25519 signers.
///
/// Each check calls the account's real `__check_auth` directly, with a
/// synthetic host payload and a single supplied authorization context. Policy
/// state persists across successful checks. Use a fresh [`Env`] without
/// mocked authorization.
pub struct PolicyTestHarness {
env: Env,
account: Address,
context_rule_id: u32,
signers: alloc::vec::Vec<(Signer, SigningKey)>,
}

impl PolicyTestHarness {
/// Registers a test account and installs the policies on one context rule.
///
/// # Arguments
/// * `env` - The environment in which the policies are already registered.
/// * `context_type` - The context type the rule accepts.
/// * `signer_seeds` - Distinct Ed25519 seeds in signer index order. Use
/// dedicated test seeds.
/// * `policies` - Builds the map of policy addresses to installation
/// parameters from the rule signers in seed order. Use this to configure
/// policies whose installation parameters refer to specific signers.
///
/// # Panics
/// Panics if the smart account rejects the rule or a policy rejects
/// installation.
pub fn new(
env: &Env,
context_type: &ContextRuleType,
signer_seeds: &[[u8; 32]],
policies: impl FnOnce(&Vec<Signer>) -> Map<Address, Val>,
) -> Self {
let account = env.register(PolicyTestAccount, ());
let verifier = env.register(TestEd25519Verifier, ());
let signers: alloc::vec::Vec<_> = signer_seeds
.iter()
.map(|seed| {
let key = SigningKey::from_bytes(seed);
let public_key = Bytes::from_array(env, key.verifying_key().as_bytes());
(Signer::External(verifier.clone(), public_key), key)
})
.collect();
let rule_signers = Vec::from_iter(env, signers.iter().map(|(signer, _)| signer.clone()));
let policies = policies(&rule_signers);
let context_rule_id = env.as_contract(&account, || {
add_context_rule(
env,
context_type,
&String::from_str(env, "policy test"),
None,
&rule_signers,
&policies,
)
.id
});
Self { env: env.clone(), account, context_rule_id, signers }
}

/// Returns the address of the registered smart account.
pub fn account(&self) -> &Address {
&self.account
}

/// Returns the ID of the installed context rule.
pub fn context_rule_id(&self) -> u32 {
self.context_rule_id
}

/// Signs with the selected zero-based signer indices and invokes
/// `__check_auth`. Pass an empty slice to test unsigned authorization.
///
/// # Arguments
/// * `context` - The authorization context to pass to the account.
/// * `signer_indices` - The indices of the test signers to authenticate. A
/// repeated index contributes only one signature.
///
/// # Errors
/// Returns the Soroban error if the authorization check fails.
///
/// # Panics
/// Panics if a signer index is out of range.
pub fn try_check_auth(&self, context: Context, signer_indices: &[usize]) -> Result<(), Error> {
let e = &self.env;
let signature_payload = BytesN::from_array(e, &[0; 32]);
let context_rule_ids = vec![e, self.context_rule_id];
let digest = AuthDigestPreimage {
account: self.account.clone(),
signature_payload: signature_payload.clone(),
context_rule_ids: context_rule_ids.clone(),
}
.digest(e)
.to_array();
let mut signers = Map::new(e);
for &index in signer_indices {
let (signer, key) = &self.signers[index];
let signature = Bytes::from_array(e, &key.sign(&digest).to_bytes());
signers.set(signer.clone(), signature);
}
e.try_invoke_contract_check_auth::<Error>(
&self.account,
&signature_payload,
AuthPayload { signers, context_rule_ids }.into_val(e),
&vec![e, context],
)
.map_err(|error| error.expect("conversion from a Soroban error to itself is infallible"))
}
}
Loading