Feat: add vault module
This commit is contained in:
75
vault/tests/keypair_management.rs
Normal file
75
vault/tests/keypair_management.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
//! Tests for vault keypair management and crypto operations
|
||||
use vault::{Vault, KeyType, KeyMetadata};
|
||||
use kvstore::native::NativeStore;
|
||||
|
||||
fn debug_log(msg: &str) {
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
let mut f = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open("vault_crypto_debug.log")
|
||||
.unwrap();
|
||||
writeln!(f, "{}", msg).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_keypair_management_and_crypto() {
|
||||
debug_log("[DEBUG][TEST] test_keypair_management_and_crypto started");
|
||||
// Use NativeStore for native tests
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let store = NativeStore::open("vault_native_test").expect("Failed to open native store");
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let mut vault = Vault::new(store);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
compile_error!("This test is not intended for wasm32 targets");
|
||||
let keyspace = &format!("testspace_{}", chrono::Utc::now().timestamp_nanos());
|
||||
let password = b"supersecret";
|
||||
|
||||
debug_log(&format!("[DEBUG][TEST] keyspace: {} password: {}", keyspace, hex::encode(password)));
|
||||
debug_log("[DEBUG][TEST] before create_keyspace");
|
||||
vault.create_keyspace(keyspace, password, "pbkdf2", "chacha20poly1305", None).await.unwrap();
|
||||
|
||||
debug_log(&format!("[DEBUG][TEST] after create_keyspace: keyspace={} password={}", keyspace, hex::encode(password)));
|
||||
debug_log("[DEBUG][TEST] before add Ed25519 keypair");
|
||||
let key_id = vault.add_keypair(keyspace, password, KeyType::Ed25519, Some(KeyMetadata { name: Some("edkey".into()), created_at: None, tags: None })).await;
|
||||
match &key_id {
|
||||
Ok(_) => debug_log("[DEBUG][TEST] after add Ed25519 keypair (Ok)"),
|
||||
Err(e) => debug_log(&format!("[DEBUG][TEST] after add Ed25519 keypair (Err): {:?}", e)),
|
||||
}
|
||||
let key_id = key_id.unwrap();
|
||||
debug_log("[DEBUG][TEST] before add secp256k1 keypair");
|
||||
let secp_id = vault.add_keypair(keyspace, password, KeyType::Secp256k1, Some(KeyMetadata { name: Some("secpkey".into()), created_at: None, tags: None })).await.unwrap();
|
||||
|
||||
debug_log("[DEBUG][TEST] before list_keypairs");
|
||||
let keys = vault.list_keypairs(keyspace, password).await.unwrap();
|
||||
assert_eq!(keys.len(), 2);
|
||||
|
||||
debug_log("[DEBUG][TEST] before export Ed25519 keypair");
|
||||
let (priv_bytes, pub_bytes) = vault.export_keypair(keyspace, password, &key_id).await.unwrap();
|
||||
assert!(!priv_bytes.is_empty() && !pub_bytes.is_empty());
|
||||
|
||||
debug_log("[DEBUG][TEST] before sign Ed25519");
|
||||
let msg = b"hello world";
|
||||
let sig = vault.sign(keyspace, password, &key_id, msg).await.unwrap();
|
||||
debug_log("[DEBUG][TEST] before verify Ed25519");
|
||||
let ok = vault.verify(keyspace, password, &key_id, msg, &sig).await.unwrap();
|
||||
assert!(ok);
|
||||
|
||||
debug_log("[DEBUG][TEST] before sign secp256k1");
|
||||
let sig2 = vault.sign(keyspace, password, &secp_id, msg).await.unwrap();
|
||||
debug_log("[DEBUG][TEST] before verify secp256k1");
|
||||
let ok2 = vault.verify(keyspace, password, &secp_id, msg, &sig2).await.unwrap();
|
||||
assert!(ok2);
|
||||
|
||||
// Encrypt and decrypt
|
||||
let ciphertext = vault.encrypt(keyspace, password, msg).await.unwrap();
|
||||
let plaintext = vault.decrypt(keyspace, password, &ciphertext).await.unwrap();
|
||||
assert_eq!(plaintext, msg);
|
||||
|
||||
// Remove a keypair
|
||||
vault.remove_keypair(keyspace, password, &key_id).await.unwrap();
|
||||
let keys = vault.list_keypairs(keyspace, password).await.unwrap();
|
||||
assert_eq!(keys.len(), 1);
|
||||
}
|
35
vault/tests/mock_store.rs
Normal file
35
vault/tests/mock_store.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! In-memory mock key-value store for testing vault logic (native only)
|
||||
use kvstore::KVStore;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct MockStore {
|
||||
inner: Arc<Mutex<HashMap<String, Vec<u8>>>>,
|
||||
}
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
|
||||
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
|
||||
impl KVStore for MockStore {
|
||||
async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, kvstore::KVError> {
|
||||
Ok(self.inner.lock().unwrap().get(key).cloned())
|
||||
}
|
||||
async fn set(&self, key: &str, value: &[u8]) -> Result<(), kvstore::KVError> {
|
||||
self.inner.lock().unwrap().insert(key.to_string(), value.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
async fn remove(&self, key: &str) -> Result<(), kvstore::KVError> {
|
||||
self.inner.lock().unwrap().remove(key);
|
||||
Ok(())
|
||||
}
|
||||
async fn contains_key(&self, key: &str) -> Result<bool, kvstore::KVError> {
|
||||
Ok(self.inner.lock().unwrap().contains_key(key))
|
||||
}
|
||||
async fn keys(&self) -> Result<Vec<String>, kvstore::KVError> {
|
||||
Ok(self.inner.lock().unwrap().keys().cloned().collect())
|
||||
}
|
||||
async fn clear(&self) -> Result<(), kvstore::KVError> {
|
||||
self.inner.lock().unwrap().clear();
|
||||
Ok(())
|
||||
}
|
||||
}
|
128
vault/tests/wasm_keypair_management.rs
Normal file
128
vault/tests/wasm_keypair_management.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
#![cfg(target_arch = "wasm32")]
|
||||
//! WASM/browser tests for vault keypair management and crypto operations
|
||||
use wasm_bindgen_test::*;
|
||||
use vault::{Vault, KeyType, KeyMetadata};
|
||||
use kvstore::wasm::WasmStore;
|
||||
use console_error_panic_hook;
|
||||
|
||||
wasm_bindgen_test_configure!(run_in_browser);
|
||||
|
||||
#[wasm_bindgen_test(async)]
|
||||
async fn wasm_test_keypair_management_and_crypto() {
|
||||
console_error_panic_hook::set_once();
|
||||
let store = WasmStore::open("vault_idb_test").await.expect("Failed to open IndexedDB store");
|
||||
let mut vault = Vault::new(store);
|
||||
let keyspace = "wasmspace";
|
||||
let password = b"supersecret";
|
||||
println!("[DEBUG] Initialized vault and IndexedDB store");
|
||||
|
||||
// Step 1: Create keyspace
|
||||
match vault.create_keyspace(keyspace, password, "pbkdf2", "chacha20poly1305", None).await {
|
||||
Ok(_) => println!("[DEBUG] Created keyspace"),
|
||||
Err(e) => { println!("[ERROR] Failed to create keyspace: {:?}", e); return; }
|
||||
}
|
||||
|
||||
// Step 2: Add Ed25519 keypair
|
||||
let key_id = match vault.add_keypair(keyspace, password, KeyType::Ed25519, Some(KeyMetadata { name: Some("edkey".into()), created_at: None, tags: None })).await {
|
||||
Ok(id) => { println!("[DEBUG] Added Ed25519 keypair: {}", id); id },
|
||||
Err(e) => { println!("[ERROR] Failed to add Ed25519 keypair: {:?}", e); return; }
|
||||
};
|
||||
|
||||
// Step 3: Add Secp256k1 keypair
|
||||
let secp_id = match vault.add_keypair(keyspace, password, KeyType::Secp256k1, Some(KeyMetadata { name: Some("secpkey".into()), created_at: None, tags: None })).await {
|
||||
Ok(id) => { println!("[DEBUG] Added Secp256k1 keypair: {}", id); id },
|
||||
Err(e) => { println!("[ERROR] Failed to add Secp256k1 keypair: {:?}", e); return; }
|
||||
};
|
||||
|
||||
// Step 4: List keypairs
|
||||
let keys = match vault.list_keypairs(keyspace, password).await {
|
||||
Ok(keys) => { println!("[DEBUG] Listed keypairs: {:?}", keys); keys },
|
||||
Err(e) => { println!("[ERROR] Failed to list keypairs: {:?}", e); return; }
|
||||
};
|
||||
if keys.len() != 2 {
|
||||
println!("[ERROR] Expected 2 keypairs, got {}", keys.len());
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 5: Export Ed25519 keypair
|
||||
let (priv_bytes, pub_bytes) = match vault.export_keypair(keyspace, password, &key_id).await {
|
||||
Ok((priv_bytes, pub_bytes)) => {
|
||||
println!("[DEBUG] Exported Ed25519 keypair, priv: {} bytes, pub: {} bytes", priv_bytes.len(), pub_bytes.len());
|
||||
(priv_bytes, pub_bytes)
|
||||
},
|
||||
Err(e) => { println!("[ERROR] Failed to export Ed25519 keypair: {:?}", e); return; }
|
||||
};
|
||||
if priv_bytes.is_empty() || pub_bytes.is_empty() {
|
||||
println!("[ERROR] Exported Ed25519 keypair bytes are empty");
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 6: Sign and verify with Ed25519
|
||||
let msg = b"hello wasm";
|
||||
let sig = match vault.sign(keyspace, password, &key_id, msg).await {
|
||||
Ok(sig) => { println!("[DEBUG] Signed message with Ed25519"); sig },
|
||||
Err(e) => { println!("[ERROR] Failed to sign with Ed25519: {:?}", e); return; }
|
||||
};
|
||||
let ok = match vault.verify(keyspace, password, &key_id, msg, &sig).await {
|
||||
Ok(ok) => { println!("[DEBUG] Verified Ed25519 signature: {}", ok); ok },
|
||||
Err(e) => { println!("[ERROR] Failed to verify Ed25519 signature: {:?}", e); return; }
|
||||
};
|
||||
if !ok {
|
||||
println!("[ERROR] Ed25519 signature verification failed");
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 7: Sign and verify with Secp256k1
|
||||
let sig2 = match vault.sign(keyspace, password, &secp_id, msg).await {
|
||||
Ok(sig) => { println!("[DEBUG] Signed message with Secp256k1"); sig },
|
||||
Err(e) => { println!("[ERROR] Failed to sign with Secp256k1: {:?}", e); return; }
|
||||
};
|
||||
let ok2 = match vault.verify(keyspace, password, &secp_id, msg, &sig2).await {
|
||||
Ok(ok) => { println!("[DEBUG] Verified Secp256k1 signature: {}", ok); ok },
|
||||
Err(e) => { println!("[ERROR] Failed to verify Secp256k1 signature: {:?}", e); return; }
|
||||
};
|
||||
if !ok2 {
|
||||
println!("[ERROR] Secp256k1 signature verification failed");
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 8: Encrypt and decrypt
|
||||
let ciphertext = match vault.encrypt(keyspace, password, msg).await {
|
||||
Ok(ct) => { println!("[DEBUG] Encrypted message"); ct },
|
||||
Err(e) => { println!("[ERROR] Failed to encrypt message: {:?}", e); return; }
|
||||
};
|
||||
let plaintext = match vault.decrypt(keyspace, password, &ciphertext).await {
|
||||
Ok(pt) => { println!("[DEBUG] Decrypted message"); pt },
|
||||
Err(e) => { println!("[ERROR] Failed to decrypt message: {:?}", e); return; }
|
||||
};
|
||||
if plaintext != msg {
|
||||
println!("[ERROR] Decrypted message does not match original");
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 9: Remove Ed25519 keypair
|
||||
match vault.remove_keypair(keyspace, password, &key_id).await {
|
||||
Ok(_) => println!("[DEBUG] Removed Ed25519 keypair"),
|
||||
Err(e) => { println!("[ERROR] Failed to remove Ed25519 keypair: {:?}", e); return; }
|
||||
}
|
||||
let keys = match vault.list_keypairs(keyspace, password).await {
|
||||
Ok(keys) => { println!("[DEBUG] Listed keypairs after removal: {:?}", keys); keys },
|
||||
Err(e) => { println!("[ERROR] Failed to list keypairs after removal: {:?}", e); return; }
|
||||
};
|
||||
if keys.len() != 1 {
|
||||
println!("[ERROR] Expected 1 keypair after removal, got {}", keys.len());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
wasm_bindgen_test_configure!(run_in_browser);
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn sanity_check() {
|
||||
assert_eq!(2 + 2, 4);
|
||||
}
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user