Skip to content
Merged
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
12 changes: 12 additions & 0 deletions crates/openhuman-core/src/web3/wallet/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,18 @@ fn validate_setup(params: &WalletSetupParams) -> Result<Vec<WalletAccount>, Stri
account.chain.as_str()
));
}
if account.index == 0
&& SECONDARY_ACCOUNTS.iter().any(|secondary| {
secondary.chain == account.chain && secondary.derivation_path == derivation_path
})
{
// A primary at a secondary path resolves to that secondary account's
// key, so the secondary's program policy would sign for the primary.
return Err(format!(
"wallet setup account '{}' index 0 uses a secondary account path; a primary account must not alias one",
account.chain.as_str()
));
}
if account.index > 0 {
// A secondary account must be one the host knows, at its canonical
// path, so the key it later signs with is the one its policy names.
Expand Down
49 changes: 49 additions & 0 deletions crates/openhuman-core/src/web3/wallet/ops_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,3 +453,52 @@ async fn secret_material_resolves_the_secondary_path_for_a_wallet_that_predates_
crate::web3::wallet::test_support::sample_solana_address()
);
}

#[test]
fn validate_setup_rejects_a_primary_at_a_secondary_path() {
// An index-0 account at the giveaway path would resolve to the same key
// as index 1, so the secondary program policy would sign for the primary.
let mut params = sample_params();
let mut alias = sample_account(WalletChain::Solana);
alias.derivation_path = giveaway_account().derivation_path;
params
.accounts
.retain(|account| account.chain != WalletChain::Solana);
params.accounts.push(alias);
assert!(validate_setup(&params)
.expect_err("primary aliasing the secondary path")
.contains("secondary account path"));
}

#[tokio::test]
async fn a_stored_primary_at_the_secondary_path_is_quarantined_before_signing() {
// A wallet state written with its Solana primary on the giveaway path (by a
// build that did not refuse it) must not sign for index 1: load validation
// quarantines it, so no secondary key is ever resolved from it.
let temp = tempfile::tempdir().expect("temp dir");
let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock().await;
let ctx = DispatchCtx::process_default();
let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp).await;
let config = ctx.load_config().await.expect("config");
{
let mut state = stored_state();
state.accounts = WalletChain::ALL
.into_iter()
.map(crate::web3::wallet::test_support::sample_account)
.collect();
for account in state.accounts.iter_mut() {
if account.chain == WalletChain::Solana {
account.derivation_path = giveaway_account().derivation_path;
}
}
let _guard = WALLET_STATE_FILE_LOCK.lock();
save_stored_wallet_state_unlocked(&config, &state).expect("save state");
}
let error = secret_material(&ctx, WalletChain::Solana, 1)
.await
.expect_err("an aliased primary must not sign as the secondary");
assert_eq!(error, WALLET_NOT_CONFIGURED_MESSAGE);
assert!(load_stored_wallet_state_unlocked(&config)
.expect("load")
.is_none());
}
2 changes: 2 additions & 0 deletions crates/openhuman-core/src/web3/wallet/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ pub enum RefusalKind {
/// The declared token debits disagree with what the transaction moves
/// (its visible transfers, or its simulation), or the simulation failed.
SimulationMismatch,
/// The prepared quote reached its expiry before it could be signed.
QuoteExpired,
}

/// A refused execute.
Expand Down
101 changes: 84 additions & 17 deletions crates/openhuman-core/src/web3/wallet/program/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::sync::Mutex;
use base64::Engine as _;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tinywallet_bus::wire::{RpcEndpointKey, RpcSource, Scheme, SecretMaterial, Signature};
use zeroize::Zeroizing;

Expand Down Expand Up @@ -82,11 +83,25 @@ pub struct ExecuteProgramParams {
pub quote_id: String,
}

/// What a quote is bound to. The quote map is process-wide, so a quote can be
/// taken only by the context it was prepared in: the same workspace (whose
/// spend ledger it draws on), the same wallet (a hash of the encrypted phrase,
/// which changes when the wallet is replaced), the same account and the same
/// Solana endpoint.
#[derive(Debug, Clone, PartialEq, Eq)]
struct QuoteBinding {
workspace: std::path::PathBuf,
wallet: String,
account_index: u32,
endpoint: String,
}

#[derive(Clone)]
struct StoredQuote {
prepared: PreparedProgram,
transaction: Vec<u8>,
decoded: DecodedTransaction,
binding: QuoteBinding,
}

static QUOTES: Lazy<Mutex<HashMap<String, StoredQuote>>> = Lazy::new(|| Mutex::new(HashMap::new()));
Expand All @@ -98,8 +113,48 @@ fn store_quote(quote: StoredQuote, now_ms: u64) {
}
}

fn take_quote(quote_id: &str) -> Option<StoredQuote> {
QUOTES.lock().ok()?.remove(quote_id)
/// Remove the quote only when `binding` matches the one it was prepared under.
/// A mismatched request leaves the quote where it is, for its own context.
fn take_quote(quote_id: &str, binding: &QuoteBinding) -> Option<StoredQuote> {
let mut quotes = QUOTES.lock().ok()?;
if quotes.get(quote_id)?.binding != *binding {
return None;
}
quotes.remove(quote_id)
}

/// Whether a quote with this id is held, in any context.
fn quote_held(quote_id: &str) -> bool {
QUOTES
.lock()
.is_ok_and(|quotes| quotes.contains_key(quote_id))
}

/// The context a quote for `account_index` is bound to, read now.
async fn quote_binding(
ctx: &DispatchCtx,
config: &crate::config::Config,
account_index: u32,
) -> Result<QuoteBinding, String> {
let material =
super::super::ops::secret_material(ctx, WalletChain::Solana, account_index).await?;
Ok(QuoteBinding {
workspace: config.workspace_dir.clone(),
wallet: hex::encode(Sha256::digest(material.encrypted_mnemonic.as_bytes())),
account_index,
endpoint: solana_rpc_url(ctx).await?,
})
}

/// A quote is usable strictly before its expiry instant.
fn ensure_unexpired(expires_at_ms: u64, now_ms: u64) -> Result<(), PolicyRefusal> {
if expires_at_ms > now_ms {
return Ok(());
}
Err(refusal(
RefusalKind::QuoteExpired,
format!("the quote expired at {expires_at_ms} (now {now_ms}); prepare it again"),
))
}

/// Prepare quotes currently held (test support).
Expand Down Expand Up @@ -155,6 +210,7 @@ pub async fn prepare_program(
.map_err(|error| format!("transaction is not valid base64: {error}"))?;
let decoded = decode_transaction(&transaction)?;
let account = super::super::ops::ensure_account(ctx, chain, params.account_index).await?;
let binding = quote_binding(ctx, &config, params.account_index).await?;
let summary = summarize(&decoded, &account.address).map_err(|refused| refused.to_string())?;
let now = super::super::policy::wall_clock_ms();
let (_, records) = ledger_records(&config)?;
Expand Down Expand Up @@ -197,6 +253,7 @@ pub async fn prepare_program(
prepared: prepared.clone(),
transaction,
decoded,
binding,
},
now,
);
Expand Down Expand Up @@ -262,23 +319,24 @@ pub async fn execute_prepared_program(
) -> Result<Outcome<ExecutedProgram>, String> {
let config = ctx.load_config().await?;
let now = super::super::policy::wall_clock_ms();
let stored = take_quote(&params.quote_id)
.filter(|stored| stored.prepared.expires_at_ms > now)
.ok_or_else(|| "prepared program quote is unavailable or expired".to_string())?;
if stored.prepared.account_index != params.account_index {
let message = format!(
"quote {} was prepared for account index {}, not {}",
params.quote_id, stored.prepared.account_index, params.account_index
);
store_quote(stored, now);
return Err(message);
let unavailable = || "prepared program quote is unavailable or expired".to_string();
if !quote_held(&params.quote_id) {
return Err(unavailable());
}
// A quote from another workspace, wallet, account or endpoint is reported
// as unavailable and stays in the map for its own context.
let binding = quote_binding(ctx, &config, params.account_index).await?;
let stored = take_quote(&params.quote_id, &binding)
.filter(|stored| stored.prepared.expires_at_ms > now)
.ok_or_else(unavailable)?;
let origin = ExecutionOrigin::rpc();
let prepared = stored.prepared.clone();
let chain = chain_name(prepared.chain);
let (ledger, _) = ledger_records(&config)?;
// Simulate again against the chain as it is now: the caps and the
// declaration must still hold when the key is used.
// Simulate against the chain as it is now. The caps and the declaration
// are checked against this snapshot only: an opaque program can debit a
// different amount when the transaction is included, so the caps are
// not a bound on the chain's final state.
let simulated = match simulate_quote(ctx, &stored.transaction, &stored.decoded).await {
Ok(report) => check_simulation(&prepared.declared_debits, &report),
Err(error) => {
Expand All @@ -288,9 +346,14 @@ pub async fn execute_prepared_program(
};
let reserved = ledger
.reserve(|records| {
// Read the clock at the point of no return. The simulation above
// can take many seconds, so a quote that expired while it ran must
// be refused here, before anything is signed.
let reserved_at = super::super::policy::wall_clock_ms();
if let Some(refused) = origin_refusal(&origin) {
return Err(refused);
}
ensure_unexpired(prepared.expires_at_ms, reserved_at)?;
simulated.clone()?;
if let Some(earlier) = records.iter().rev().find(|record| {
record.quote_id == prepared.quote_id && record.status.counts_against_caps()
Expand All @@ -310,13 +373,13 @@ pub async fn execute_prepared_program(
&prepared.summary,
&prepared.declared_debits,
records,
now,
reserved_at,
)?;
Ok(program_record(
&prepared,
&origin,
LedgerStatus::Pending,
now,
reserved_at,
))
})
.map_err(|error| format!("wallet spend ledger is unavailable: {error:#}"))?;
Expand Down Expand Up @@ -469,7 +532,11 @@ async fn simulate_quote(
.first()
.ok_or_else(|| "the transaction lists no accounts".to_string())?;
let url = solana_rpc_url(ctx).await?;
simulate(&url, transaction, owner)
simulate(&url, transaction, owner, &decoded.account_keys)
.await
.map_err(|error| format!("could not simulate the transaction: {error}"))
}

#[cfg(test)]
#[path = "ops_tests.rs"]
mod tests;
88 changes: 88 additions & 0 deletions crates/openhuman-core/src/web3/wallet/program/ops_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use super::*;

fn binding(workspace: &str, wallet: &str, account_index: u32, endpoint: &str) -> QuoteBinding {
QuoteBinding {
workspace: std::path::PathBuf::from(workspace),
wallet: wallet.to_string(),
account_index,
endpoint: endpoint.to_string(),
}
}

fn stored(quote_id: &str, binding: QuoteBinding) -> StoredQuote {
StoredQuote {
prepared: PreparedProgram {
quote_id: quote_id.to_string(),
chain: WalletChain::Solana,
account_index: binding.account_index,
address: String::new(),
summary: ProgramTransactionSummary {
fee_payer: String::new(),
signers: Vec::new(),
recent_blockhash: String::new(),
programs: Vec::new(),
instructions: Vec::new(),
movements: Vec::new(),
totals: Vec::new(),
},
declared_debits: Vec::new(),
simulation: SimulationReport::default(),
created_at_ms: 0,
expires_at_ms: u64::MAX,
},
transaction: Vec::new(),
decoded: DecodedTransaction {
signature_count: 0,
signatures_offset: 0,
signatures: Vec::new(),
message: Vec::new(),
versioned: false,
num_required_signatures: 0,
account_keys: Vec::new(),
recent_blockhash: [0; 32],
instructions: Vec::new(),
lookup_table_count: 0,
},
binding,
}
}

#[test]
fn a_quote_is_taken_only_in_the_context_it_was_prepared_in() {
// The quote map is process-wide: another workspace, wallet, account or
// endpoint must not be able to spend this quote, and a refused take must
// leave it in place for its own context.
let id = format!("test-quote-{}", uuid::Uuid::new_v4());
let prepared_in = binding("/ws/a", "wallet-1", 1, "https://rpc.a");
store_quote(stored(&id, prepared_in.clone()), 0);

let other_contexts = [
binding("/ws/b", "wallet-1", 1, "https://rpc.a"),
binding("/ws/a", "wallet-2", 1, "https://rpc.a"),
binding("/ws/a", "wallet-1", 0, "https://rpc.a"),
binding("/ws/a", "wallet-1", 1, "https://rpc.b"),
];
for other in &other_contexts {
assert!(take_quote(&id, other).is_none(), "taken under {other:?}");
}
assert!(
has_quote_for_test(&id),
"a refused take must keep the quote"
);

let taken = take_quote(&id, &prepared_in).expect("the preparing context takes it");
assert_eq!(taken.binding, prepared_in);
assert!(!has_quote_for_test(&id), "a taken quote is removed");
}

#[test]
fn a_quote_is_refused_from_its_expiry_instant_onward() {
assert!(ensure_unexpired(1_000, 999).is_ok());
assert_eq!(
ensure_unexpired(1_000, 1_000)
.expect_err("the expiry instant is already too late")
.kind,
RefusalKind::QuoteExpired
);
assert!(ensure_unexpired(1_000, 1_001).is_err());
}
Loading
Loading