refactor(vault): remove irpc actor dispatch — direct method calls on VaultServiceHandle (task: vault/irpc-removal)
ADR-025 / drift item #4: remove the irpc-based actor dispatch from the vault crate. VaultServiceHandle (Arc<std::sync::RwLock<>>) is now the sole synchronous API. Removed: VaultProtocol enum, VaultServiceActor, VaultService wrapper, Client<VaultProtocol> usage, irpc/irpc-derive/tokio deps, postcard dev-dep, Serialize/Deserialize on VaultServiceError. lib.rs re-exports match the vault README Public API. The vault is now local-only by construction with zero async runtime dependency. Refs: docs/architecture/crates/vault/README.md drift #4 Implements: ADR-025 # Conflicts: # Cargo.lock
This commit is contained in:
780
Cargo.lock
generated
780
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -25,11 +25,7 @@ zeroize = { version = "1", features = ["derive"] }
|
||||
hmac = "0.12"
|
||||
rand = "0.8"
|
||||
base64 = "0.22"
|
||||
irpc = { workspace = true }
|
||||
irpc-derive = { workspace = true }
|
||||
tokio = { version = "1", features = ["sync", "rt", "macros"] }
|
||||
secp256k1 = { version = "0.29", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
hex = "0.4"
|
||||
postcard = { version = "1", features = ["alloc"] }
|
||||
@@ -309,8 +309,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_cache_expired_entry_evicted_on_access() {
|
||||
let mut config = CacheConfig::default();
|
||||
config.ttl = Duration::from_millis(1);
|
||||
let config = CacheConfig {
|
||||
ttl: Duration::from_millis(1),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut cache = KeyCache::new(config);
|
||||
cache.insert("m/74'/0'/0'/0'", make_cached_key(KeyType::Ed25519));
|
||||
@@ -323,8 +325,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_cache_lru_eviction() {
|
||||
let mut config = CacheConfig::default();
|
||||
config.max_entries = 3;
|
||||
let config = CacheConfig {
|
||||
max_entries: 3,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut cache = KeyCache::new(config);
|
||||
|
||||
@@ -345,8 +349,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_cache_lru_access_reorders() {
|
||||
let mut config = CacheConfig::default();
|
||||
config.max_entries = 3;
|
||||
let config = CacheConfig {
|
||||
max_entries: 3,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut cache = KeyCache::new(config);
|
||||
|
||||
@@ -381,8 +387,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_evict_expired_removes_only_expired() {
|
||||
let mut config = CacheConfig::default();
|
||||
config.ttl = Duration::from_millis(10);
|
||||
let config = CacheConfig {
|
||||
ttl: Duration::from_millis(10),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut cache = KeyCache::new(config);
|
||||
cache.insert("path1", make_cached_key(KeyType::Ed25519));
|
||||
|
||||
@@ -25,8 +25,8 @@
|
||||
//! - [`mnemonic`] — BIP39 mnemonic generation, validation, and seed derivation
|
||||
//! - [`derivation`] — SLIP-0010 Ed25519 HD key derivation and path constants
|
||||
//! - [`encryption`] — AES-256-GCM encrypt/decrypt and `EncryptedData` type
|
||||
//! - [`protocol`] — `VaultProtocol` irpc message enum, `DerivedKey`, `KeyType`
|
||||
//! - [`service`] — `VaultService` implementation with Unlock/Lock lifecycle
|
||||
//! - [`protocol`] — `DerivedKey` and `KeyType` (return types from vault methods)
|
||||
//! - [`service`] — `VaultServiceHandle` runtime API with Unlock/Lock lifecycle
|
||||
//! - [`ethereum`] — BIP-0032 secp256k1 HD key derivation (behind `secp256k1` feature)
|
||||
|
||||
pub mod cache;
|
||||
@@ -42,7 +42,8 @@ pub mod ethereum;
|
||||
// Re-export primary public API
|
||||
pub use cache::CacheConfig;
|
||||
pub use derivation::{DerivationError, ExtendedPrivKey, PATHS};
|
||||
pub use encryption::{EncryptedData, EncryptionError};
|
||||
pub use encryption::CURRENT_KEY_VERSION;
|
||||
pub use encryption::{EncryptedData, EncryptionError, EncryptionKey};
|
||||
pub use mnemonic::{Language, Mnemonic, Seed};
|
||||
pub use protocol::{DerivedKey, KeyType, VaultMessage, VaultProtocol};
|
||||
pub use service::{VaultService, VaultServiceActor, VaultServiceError, VaultServiceHandle};
|
||||
pub use protocol::{DerivedKey, KeyType};
|
||||
pub use service::{VaultServiceError, VaultServiceHandle};
|
||||
|
||||
@@ -1,32 +1,19 @@
|
||||
//! VaultProtocol irpc message definition and associated types.
|
||||
//! Vault key types: `DerivedKey` and `KeyType`.
|
||||
//!
|
||||
//! This module defines the `VaultProtocol` enum for irpc-based message dispatch.
|
||||
//! The protocol supports unlock/lock lifecycle, key derivation,
|
||||
//! and encryption/decryption operations.
|
||||
//! The vault's dispatch is direct method calls on `VaultServiceHandle`
|
||||
//! (ADR-025). The types defined here — `DerivedKey`, `KeyType` — are the
|
||||
//! return types from those methods. There is no `VaultProtocol` enum, no
|
||||
//! `VaultMessage`, no `VaultServiceActor`, and no remote dispatch capability.
|
||||
//!
|
||||
//! # Protocol Operation
|
||||
//!
|
||||
//! The VaultProtocol follows a lifecycle: the vault starts in a **locked**
|
||||
//! state where no derivation or encryption operations are possible. The `Unlock`
|
||||
//! call loads the seed into memory (derived from the mnemonic passphrase). After
|
||||
//! that, derive and encrypt/decrypt operations are available. The `Lock` call
|
||||
//! purges the seed and all cached keys.
|
||||
//!
|
||||
//! # Wire Format
|
||||
//!
|
||||
//! For local (in-process) calls, the protocol uses tokio channels directly.
|
||||
//! For remote (in-cluster) calls, the protocol is serialized with postcard.
|
||||
//! For cross-node (call protocol) exposure, the vault is wrapped in an
|
||||
//! operation that serializes to JSON.
|
||||
//! The vault is **local-only by construction**. If remote vault access is
|
||||
//! ever needed, it requires a separate crate that wraps the vault and adds
|
||||
//! remote transport + auth (ADR-025, OQ-021).
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use irpc::rpc_requests;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::encryption::EncryptedData;
|
||||
|
||||
/// The type of a derived key.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum KeyType {
|
||||
@@ -46,10 +33,8 @@ pub enum KeyType {
|
||||
/// by `#[zeroize(drop)]`).
|
||||
///
|
||||
/// Serialization redacts the `private_key` field for human-readable formats
|
||||
/// (JSON) for safety, showing `"[REDACTED]"` instead of the key bytes. For
|
||||
/// binary formats (postcard, used by irpc), the actual bytes are serialized
|
||||
/// so that remote communication works correctly. Deserialization always reads
|
||||
/// the full bytes.
|
||||
/// (JSON) for safety, showing `"[REDACTED]"` instead of the key bytes.
|
||||
/// Deserialization always reads the full bytes.
|
||||
#[derive(Zeroize, Deserialize)]
|
||||
#[zeroize(drop)]
|
||||
pub struct DerivedKey {
|
||||
@@ -98,115 +83,6 @@ impl Serialize for DerivedKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// VaultProtocol message definition.
|
||||
///
|
||||
/// This is the irpc protocol enum that defines all vault operations.
|
||||
/// The `#[rpc_requests]` macro generates:
|
||||
/// - **`VaultMessage`**: message enum with `WithChannels` wrappers for each variant
|
||||
/// - **`Channels<VaultProtocol>`** impls for each wrapper type
|
||||
/// - **`From`** impls for protocol enum and message enum conversions
|
||||
/// - **`Service`** and **`RemoteService`** trait impls for remote dispatch
|
||||
///
|
||||
/// # State Requirements
|
||||
///
|
||||
/// All operations except `Unlock` require the vault to be in an **unlocked**
|
||||
/// state. Calling derive/encrypt/decrypt on a locked vault returns an error.
|
||||
#[rpc_requests(message = VaultMessage, no_spans)]
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum VaultProtocol {
|
||||
/// Derive an Ed25519 keypair at the given path.
|
||||
///
|
||||
/// Path format: `m/74'/0'/0'/0'` (SLIP-0010 hardened-only notation).
|
||||
/// Returns a `DerivedKey` with `KeyType::Ed25519`.
|
||||
#[rpc(tx = irpc::channel::oneshot::Sender<Result<DerivedKey, crate::service::VaultServiceError>>)]
|
||||
#[wrap(DeriveEd25519)]
|
||||
DeriveEd25519 {
|
||||
/// SLIP-0010 derivation path (e.g., "m/74'/0'/0'/0'").
|
||||
path: String,
|
||||
},
|
||||
|
||||
/// Derive an AES-256-GCM encryption key at the given path.
|
||||
///
|
||||
/// The default encryption path is `m/74'/2'/0'/0'`.
|
||||
/// Returns a `DerivedKey` with `KeyType::Aes256Gcm`.
|
||||
#[rpc(tx = irpc::channel::oneshot::Sender<Result<DerivedKey, crate::service::VaultServiceError>>)]
|
||||
#[wrap(DeriveEncryptionKey)]
|
||||
DeriveEncryptionKey {
|
||||
/// SLIP-0010 derivation path for the encryption key.
|
||||
path: String,
|
||||
},
|
||||
|
||||
/// Derive a secp256k1 (Ethereum) keypair at the given path.
|
||||
///
|
||||
/// The default Ethereum path is `m/44'/60'/0'/0/0`.
|
||||
/// Returns a `DerivedKey` with `KeyType::Secp256k1`.
|
||||
#[rpc(tx = irpc::channel::oneshot::Sender<Result<DerivedKey, crate::service::VaultServiceError>>)]
|
||||
#[wrap(DeriveEthereumKey)]
|
||||
DeriveEthereumKey {
|
||||
/// BIP-0032 derivation path (e.g., "m/44'/60'/0'/0/0").
|
||||
path: String,
|
||||
},
|
||||
|
||||
/// Derive a deterministic password at the given path.
|
||||
///
|
||||
/// Path format: `m/74'/1'/0'/{hash}'` (SLIP-0010 hardened notation).
|
||||
/// The `length` parameter controls the output length.
|
||||
#[rpc(tx = irpc::channel::oneshot::Sender<Result<Vec<u8>, crate::service::VaultServiceError>>)]
|
||||
#[wrap(DerivePassword)]
|
||||
DerivePassword {
|
||||
/// SLIP-0010 derivation path for the password.
|
||||
path: String,
|
||||
/// Desired password length in bytes.
|
||||
length: usize,
|
||||
},
|
||||
|
||||
/// Encrypt plaintext using a derived encryption key.
|
||||
///
|
||||
/// The key is derived at the path `m/74'/2'/0'/0'` with the given version.
|
||||
/// Returns an `EncryptedData` blob suitable for storage.
|
||||
#[rpc(tx = irpc::channel::oneshot::Sender<Result<EncryptedData, crate::service::VaultServiceError>>)]
|
||||
#[wrap(Encrypt)]
|
||||
Encrypt {
|
||||
/// The plaintext string to encrypt.
|
||||
plaintext: String,
|
||||
/// The key version for rotation tracking.
|
||||
key_version: u32,
|
||||
},
|
||||
|
||||
/// Decrypt an `EncryptedData` blob back to plaintext.
|
||||
///
|
||||
/// The key is derived from the seed at the path indicated by the key version.
|
||||
#[rpc(tx = irpc::channel::oneshot::Sender<Result<String, crate::service::VaultServiceError>>)]
|
||||
#[wrap(Decrypt)]
|
||||
Decrypt {
|
||||
/// The encrypted data blob to decrypt.
|
||||
encrypted: EncryptedData,
|
||||
},
|
||||
|
||||
/// Lock the service, purging the seed and all cached derived keys.
|
||||
///
|
||||
/// After locking, no derive/encrypt/decrypt operations are possible
|
||||
/// until `Unlock` is called again. Calls `zeroize()` on all sensitive
|
||||
/// material (ADR-038).
|
||||
#[rpc(tx = irpc::channel::oneshot::Sender<Result<(), crate::service::VaultServiceError>>)]
|
||||
#[wrap(Lock)]
|
||||
Lock,
|
||||
|
||||
/// Unlock the service with a BIP39 mnemonic and optional passphrase.
|
||||
///
|
||||
/// The mnemonic is the space-separated BIP39 word list. The passphrase is
|
||||
/// the optional BIP39 password extension (the "25th word"). After unlocking,
|
||||
/// derive and encrypt/decrypt operations are available.
|
||||
#[rpc(tx = irpc::channel::oneshot::Sender<Result<(), crate::service::VaultServiceError>>)]
|
||||
#[wrap(Unlock)]
|
||||
Unlock {
|
||||
/// The BIP39 mnemonic phrase (space-separated word list).
|
||||
mnemonic: String,
|
||||
/// Optional BIP39 passphrase (the "25th word" password extension).
|
||||
passphrase: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -249,35 +125,6 @@ mod tests {
|
||||
assert!(json.contains("Ed25519"), "JSON must contain key_type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derived_key_serialize_preserves_bytes_postcard() {
|
||||
let key = make_test_key();
|
||||
let bytes = postcard::to_allocvec(&key).unwrap();
|
||||
let restored: DerivedKey = postcard::from_bytes(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
restored.private_key,
|
||||
vec![0xABu8; 32],
|
||||
"postcard must preserve private_key bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
restored.public_key,
|
||||
vec![0xCDu8; 32],
|
||||
"postcard must preserve public_key bytes"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derived_key_deserialize_preserves_bytes() {
|
||||
let key = make_test_key();
|
||||
let bytes = postcard::to_allocvec(&key.private_key).unwrap();
|
||||
let restored: Vec<u8> = postcard::from_bytes(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
restored,
|
||||
vec![0xABu8; 32],
|
||||
"Deserialization must preserve private_key bytes"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derived_key_zeroize_on_drop() {
|
||||
let key = DerivedKey {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! VaultService implementation with Unlock/Lock lifecycle.
|
||||
//! VaultServiceHandle — the sole runtime API for the vault.
|
||||
//!
|
||||
//! The `VaultService` is the primary runtime interface for key management.
|
||||
//! It holds the master seed in `Zeroize`-protected memory and provides methods
|
||||
//! for the Unlock/Lock lifecycle, key derivation, and encryption/decryption.
|
||||
//! The `VaultServiceHandle` wraps the vault's state in an
|
||||
//! `Arc<std::sync::RwLock<>>` and provides direct, synchronous method calls
|
||||
//! for the unlock/lock lifecycle, key derivation, and encryption/decryption.
|
||||
//!
|
||||
//! # Lifecycle
|
||||
//!
|
||||
@@ -25,37 +25,30 @@
|
||||
//! → vault returns to locked state
|
||||
//! ```
|
||||
//!
|
||||
//! # Dispatch Paths
|
||||
//! # Dispatch
|
||||
//!
|
||||
//! There are two ways to interact with the vault:
|
||||
//!
|
||||
//! 1. **Local (in-process)**: `VaultServiceHandle` wraps `VaultServiceInner`
|
||||
//! behind `Arc<RwLock<>>` and provides direct method calls without serialization.
|
||||
//! 2. **Remote (in-cluster)**: `VaultServiceActor` processes `VaultMessage`
|
||||
//! variants from an mpsc channel and dispatches to the handle methods.
|
||||
//! The vault uses **direct method calls** on `VaultServiceHandle` — no actor,
|
||||
//! no message enum, no channels, no serialization (ADR-025). The handle is
|
||||
//! `Arc<std::sync::RwLock<VaultServiceInner>>` — clone it, share it, call
|
||||
//! methods directly. All methods are synchronous (no `async`, no `.await`).
|
||||
//! The vault does not depend on `tokio` (ADR-025).
|
||||
//!
|
||||
//! # Assembly
|
||||
//!
|
||||
//! The `VaultService` is assembled by the CLI binary. The CLI unlocks the vault
|
||||
//! at startup and injects derived/decrypted material into operation contexts.
|
||||
//! No handler crate accesses the vault directly — they receive keys through
|
||||
//! their operation context or via the call protocol.
|
||||
//! The `VaultServiceHandle` is assembled by the CLI binary. The CLI unlocks
|
||||
//! the vault at startup and injects derived/decrypted material into operation
|
||||
//! contexts. No handler crate accesses the vault directly — they receive keys
|
||||
//! through their operation context or via the call protocol.
|
||||
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine;
|
||||
use irpc::WithChannels;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::cache::{CacheConfig, CachedKey, KeyCache};
|
||||
use crate::derivation::{self, DerivationError, PATHS};
|
||||
use crate::encryption::{self, EncryptedData, EncryptionKey};
|
||||
use crate::mnemonic::{Language, Mnemonic, Seed};
|
||||
use crate::protocol::{
|
||||
Decrypt, DeriveEd25519, DeriveEncryptionKey, DeriveEthereumKey, DerivePassword, Encrypt,
|
||||
VaultMessage, VaultProtocol, Unlock,
|
||||
};
|
||||
use crate::protocol::{DerivedKey, KeyType};
|
||||
|
||||
/// Handle to a running VaultService for local (in-process) use.
|
||||
@@ -80,7 +73,7 @@ struct VaultServiceInner {
|
||||
}
|
||||
|
||||
/// Errors that can occur during vault operations.
|
||||
#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum VaultServiceError {
|
||||
#[error("vault is locked; call Unlock first")]
|
||||
VaultLocked,
|
||||
@@ -206,10 +199,7 @@ impl VaultServiceHandle {
|
||||
});
|
||||
}
|
||||
|
||||
let seed = inner
|
||||
.seed
|
||||
.as_ref()
|
||||
.ok_or(VaultServiceError::VaultLocked)?;
|
||||
let seed = inner.seed.as_ref().ok_or(VaultServiceError::VaultLocked)?;
|
||||
let key = derivation::derive_path_from_seed(seed.as_bytes(), path)?;
|
||||
let private_key = key.private_key().to_vec();
|
||||
let public_key = key.public_key().to_vec();
|
||||
@@ -237,10 +227,7 @@ impl VaultServiceHandle {
|
||||
});
|
||||
}
|
||||
|
||||
let seed = inner
|
||||
.seed
|
||||
.as_ref()
|
||||
.ok_or(VaultServiceError::VaultLocked)?;
|
||||
let seed = inner.seed.as_ref().ok_or(VaultServiceError::VaultLocked)?;
|
||||
let key = derivation::derive_path_from_seed(seed.as_bytes(), path)?;
|
||||
let private_key = key.private_key().to_vec();
|
||||
let public_key = key.public_key().to_vec();
|
||||
@@ -274,10 +261,7 @@ impl VaultServiceHandle {
|
||||
});
|
||||
}
|
||||
|
||||
let seed = inner
|
||||
.seed
|
||||
.as_ref()
|
||||
.ok_or(VaultServiceError::VaultLocked)?;
|
||||
let seed = inner.seed.as_ref().ok_or(VaultServiceError::VaultLocked)?;
|
||||
|
||||
let key = crate::ethereum::derive_secp256k1_path(seed.as_bytes(), path)?;
|
||||
let private_key = key.private_key().to_vec();
|
||||
@@ -299,19 +283,12 @@ impl VaultServiceHandle {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn derive_password(
|
||||
&self,
|
||||
path: &str,
|
||||
length: usize,
|
||||
) -> Result<Vec<u8>, VaultServiceError> {
|
||||
pub fn derive_password(&self, path: &str, length: usize) -> Result<Vec<u8>, VaultServiceError> {
|
||||
let inner = self.inner.read().unwrap();
|
||||
if !inner.unlocked {
|
||||
return Err(VaultServiceError::VaultLocked);
|
||||
}
|
||||
let seed = inner
|
||||
.seed
|
||||
.as_ref()
|
||||
.ok_or(VaultServiceError::VaultLocked)?;
|
||||
let seed = inner.seed.as_ref().ok_or(VaultServiceError::VaultLocked)?;
|
||||
|
||||
let key = derivation::derive_path_from_seed(seed.as_bytes(), path)?;
|
||||
let private_key = key.private_key();
|
||||
@@ -345,10 +322,7 @@ impl VaultServiceHandle {
|
||||
let private_key = if let Some(cached) = inner.cache.get(PATHS::ENCRYPTION) {
|
||||
cached.private_key.clone()
|
||||
} else {
|
||||
let seed = inner
|
||||
.seed
|
||||
.as_ref()
|
||||
.ok_or(VaultServiceError::VaultLocked)?;
|
||||
let seed = inner.seed.as_ref().ok_or(VaultServiceError::VaultLocked)?;
|
||||
let derived = derivation::derive_path_from_seed(seed.as_bytes(), PATHS::ENCRYPTION)?;
|
||||
let pk = derived.private_key().to_vec();
|
||||
let pubk = derived.public_key().to_vec();
|
||||
@@ -372,10 +346,7 @@ impl VaultServiceHandle {
|
||||
let private_key = if let Some(cached) = inner.cache.get(PATHS::ENCRYPTION) {
|
||||
cached.private_key.clone()
|
||||
} else {
|
||||
let seed = inner
|
||||
.seed
|
||||
.as_ref()
|
||||
.ok_or(VaultServiceError::VaultLocked)?;
|
||||
let seed = inner.seed.as_ref().ok_or(VaultServiceError::VaultLocked)?;
|
||||
let derived = derivation::derive_path_from_seed(seed.as_bytes(), PATHS::ENCRYPTION)?;
|
||||
let pk = derived.private_key().to_vec();
|
||||
let pubk = derived.public_key().to_vec();
|
||||
@@ -396,166 +367,9 @@ impl Default for VaultServiceHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// The VaultService manages the lifecycle of the master seed and provides
|
||||
/// secret operations. This is the type used by the irpc service handler.
|
||||
///
|
||||
/// For local (in-process) use, prefer `VaultServiceHandle` which wraps
|
||||
/// this in thread-safe locks.
|
||||
pub struct VaultService {
|
||||
handle: VaultServiceHandle,
|
||||
}
|
||||
|
||||
impl VaultService {
|
||||
/// Create a new VaultService in the locked state.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
handle: VaultServiceHandle::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a handle for local (in-process) use.
|
||||
pub fn handle(&self) -> &VaultServiceHandle {
|
||||
&self.handle
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for VaultService {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Actor that processes `VaultMessage` variants and dispatches to `VaultServiceHandle`.
|
||||
///
|
||||
/// The actor runs as a `tokio::task`, receives messages from an mpsc channel,
|
||||
/// dispatches to the handle methods, and sends responses through oneshot channels.
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// ```ignore
|
||||
/// let handle = VaultServiceHandle::new();
|
||||
/// let (client, actor) = VaultServiceActor::spawn(handle);
|
||||
/// tokio::task::spawn(actor.run(rx));
|
||||
/// // Use client to send messages
|
||||
/// ```
|
||||
pub struct VaultServiceActor {
|
||||
handle: VaultServiceHandle,
|
||||
}
|
||||
|
||||
impl VaultServiceActor {
|
||||
/// Create a new actor wrapping the given handle.
|
||||
pub fn new(handle: VaultServiceHandle) -> Self {
|
||||
Self { handle }
|
||||
}
|
||||
|
||||
/// Run the actor message loop, processing `VaultMessage` variants.
|
||||
///
|
||||
/// This method runs until the receiver channel is closed. Each message
|
||||
/// variant is dispatched to the corresponding `VaultServiceHandle` method
|
||||
/// and the response is sent through the oneshot channel embedded in the message.
|
||||
pub async fn run(mut self, mut rx: tokio::sync::mpsc::Receiver<VaultMessage>) {
|
||||
while let Some(msg) = rx.recv().await {
|
||||
self.handle_message(msg);
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn the actor as a `tokio::task` and return a `Client<VaultProtocol>` for sending messages.
|
||||
///
|
||||
/// The actor runs on a tokio task and processes messages from the mpsc channel.
|
||||
/// The returned `Client<VaultProtocol>` can be used to send `VaultMessage` variants
|
||||
/// to the actor.
|
||||
pub fn spawn(
|
||||
handle: VaultServiceHandle,
|
||||
) -> (irpc::Client<VaultProtocol>, VaultServiceActor) {
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(64);
|
||||
let client = irpc::Client::local(tx);
|
||||
let actor = Self::new(handle.clone());
|
||||
tokio::task::spawn(actor.run(rx));
|
||||
(client, Self::new(handle))
|
||||
}
|
||||
|
||||
/// Handle a single `VaultMessage` by dispatching to the appropriate handle method.
|
||||
fn handle_message(&mut self, msg: VaultMessage) {
|
||||
match msg {
|
||||
VaultMessage::DeriveEd25519(msg) => {
|
||||
let WithChannels { inner, tx, .. } = msg;
|
||||
let DeriveEd25519 { path } = inner;
|
||||
let result = self.handle.derive_ed25519(&path);
|
||||
tokio::spawn(async move {
|
||||
let _ = tx.send(result).await;
|
||||
});
|
||||
}
|
||||
VaultMessage::DeriveEncryptionKey(msg) => {
|
||||
let WithChannels { inner, tx, .. } = msg;
|
||||
let DeriveEncryptionKey { path } = inner;
|
||||
let result = self.handle.derive_encryption_key(&path);
|
||||
tokio::spawn(async move {
|
||||
let _ = tx.send(result).await;
|
||||
});
|
||||
}
|
||||
VaultMessage::DeriveEthereumKey(msg) => {
|
||||
let WithChannels { inner, tx, .. } = msg;
|
||||
let DeriveEthereumKey { path } = inner;
|
||||
let result = self.handle.derive_ethereum_key(&path);
|
||||
tokio::spawn(async move {
|
||||
let _ = tx.send(result).await;
|
||||
});
|
||||
}
|
||||
VaultMessage::DerivePassword(msg) => {
|
||||
let WithChannels { inner, tx, .. } = msg;
|
||||
let DerivePassword { path, length } = inner;
|
||||
let result = self.handle.derive_password(&path, length);
|
||||
tokio::spawn(async move {
|
||||
let _ = tx.send(result).await;
|
||||
});
|
||||
}
|
||||
VaultMessage::Encrypt(msg) => {
|
||||
let WithChannels { inner, tx, .. } = msg;
|
||||
let Encrypt {
|
||||
plaintext,
|
||||
key_version,
|
||||
} = inner;
|
||||
let result = self.handle.encrypt(&plaintext, key_version);
|
||||
tokio::spawn(async move {
|
||||
let _ = tx.send(result).await;
|
||||
});
|
||||
}
|
||||
VaultMessage::Decrypt(msg) => {
|
||||
let WithChannels { inner, tx, .. } = msg;
|
||||
let Decrypt { encrypted } = inner;
|
||||
let result = self.handle.decrypt(&encrypted);
|
||||
tokio::spawn(async move {
|
||||
let _ = tx.send(result).await;
|
||||
});
|
||||
}
|
||||
VaultMessage::Lock(msg) => {
|
||||
let WithChannels { inner: _, tx, .. } = msg;
|
||||
self.handle.lock();
|
||||
tokio::spawn(async move {
|
||||
let _ = tx.send(Ok(())).await;
|
||||
});
|
||||
}
|
||||
VaultMessage::Unlock(msg) => {
|
||||
let WithChannels { inner, tx, .. } = msg;
|
||||
let Unlock {
|
||||
mnemonic,
|
||||
passphrase,
|
||||
} = inner;
|
||||
let result = self.handle.unlock(&mnemonic, passphrase.as_deref());
|
||||
tokio::spawn(async move {
|
||||
let _ = tx.send(result).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::protocol::Lock;
|
||||
use irpc::channel::oneshot;
|
||||
use irpc::WithChannels;
|
||||
|
||||
#[test]
|
||||
fn test_service_starts_locked() {
|
||||
@@ -750,10 +564,7 @@ mod tests {
|
||||
service.unlock_new(24).unwrap();
|
||||
|
||||
let result = service.derive_ethereum_key(PATHS::ETHEREUM);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(VaultServiceError::UnsupportedKeyType)
|
||||
));
|
||||
assert!(matches!(result, Err(VaultServiceError::UnsupportedKeyType)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -847,72 +658,6 @@ mod tests {
|
||||
assert_eq!(service.inner.read().unwrap().cache.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_actor_unlock_responds_successfully() {
|
||||
let handle = VaultServiceHandle::new();
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(64);
|
||||
let actor = VaultServiceActor::new(handle);
|
||||
tokio::task::spawn(actor.run(rx));
|
||||
|
||||
let (resp_tx, resp_rx) = oneshot::channel();
|
||||
let msg = VaultMessage::Unlock(WithChannels::from((
|
||||
Unlock {
|
||||
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".to_string(),
|
||||
passphrase: None,
|
||||
},
|
||||
resp_tx,
|
||||
)));
|
||||
tx.send(msg).await.unwrap();
|
||||
|
||||
let result = resp_rx.await.unwrap();
|
||||
assert!(result.is_ok(), "Unlock via actor must succeed");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_actor_derive_ed25519_returns_key() {
|
||||
let handle = VaultServiceHandle::new();
|
||||
handle.unlock_new(24).unwrap();
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(64);
|
||||
let actor = VaultServiceActor::new(handle);
|
||||
tokio::task::spawn(actor.run(rx));
|
||||
|
||||
let (resp_tx, resp_rx) = oneshot::channel();
|
||||
let msg = VaultMessage::DeriveEd25519(WithChannels::from((
|
||||
DeriveEd25519 {
|
||||
path: PATHS::IDENTITY.to_string(),
|
||||
},
|
||||
resp_tx,
|
||||
)));
|
||||
tx.send(msg).await.unwrap();
|
||||
|
||||
let result = resp_rx.await.unwrap();
|
||||
assert!(result.is_ok(), "DeriveEd25519 via actor must succeed");
|
||||
let key = result.unwrap();
|
||||
assert!(
|
||||
!key.private_key.is_empty(),
|
||||
"DerivedKey must have private_key"
|
||||
);
|
||||
assert_eq!(key.key_type, KeyType::Ed25519);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_actor_lock_clears_state() {
|
||||
let handle = VaultServiceHandle::new();
|
||||
handle.unlock_new(24).unwrap();
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(64);
|
||||
let actor = VaultServiceActor::new(handle.clone());
|
||||
tokio::task::spawn(actor.run(rx));
|
||||
|
||||
let (resp_tx, resp_rx): (oneshot::Sender<Result<(), VaultServiceError>>, _) =
|
||||
oneshot::channel();
|
||||
let msg = VaultMessage::Lock(WithChannels::from((Lock, resp_tx)));
|
||||
tx.send(msg).await.unwrap();
|
||||
|
||||
let result = resp_rx.await.unwrap();
|
||||
assert!(result.is_ok(), "Lock via actor must succeed");
|
||||
assert!(!handle.is_unlocked(), "Handle must be locked after Lock");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unlock_with_passphrase_produces_different_seed() {
|
||||
let service_a = VaultServiceHandle::new();
|
||||
@@ -943,30 +688,4 @@ mod tests {
|
||||
"Unlock with None passphrase must produce same seed as another None passphrase unlock"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_actor_unlock_with_passphrase() {
|
||||
let handle = VaultServiceHandle::new();
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(64);
|
||||
let actor = VaultServiceActor::new(handle);
|
||||
tokio::task::spawn(actor.run(rx));
|
||||
|
||||
let mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
|
||||
|
||||
let (resp_tx, resp_rx) = oneshot::channel();
|
||||
let msg = VaultMessage::Unlock(WithChannels::from((
|
||||
Unlock {
|
||||
mnemonic: mnemonic.to_string(),
|
||||
passphrase: Some("TREZOR".to_string()),
|
||||
},
|
||||
resp_tx,
|
||||
)));
|
||||
tx.send(msg).await.unwrap();
|
||||
|
||||
let result = resp_rx.await.unwrap();
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"Unlock with passphrase via actor must succeed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user