feat: Refactor kvstore and vault to use features and logging

- Remove hardcoded dependencies in kvstore Cargo.toml; use features
  instead. This allows for more flexible compilation for different
  targets (native vs. WASM).
- Improve logging in vault crate using the `log` crate. This makes
  debugging easier and provides more informative output during
  execution.  Native tests use `env_logger`, WASM tests use
  `console_log`.
- Update README to reflect new logging best practices.
- Add cfg attributes to native and wasm modules to improve clarity.
- Update traits.rs to specify Send + Sync behavior expectations.
This commit is contained in:
2025-05-15 16:42:19 +03:00
parent 7d7f94f114
commit cea2d7e655
17 changed files with 843 additions and 295 deletions

View File

@@ -3,20 +3,12 @@
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();
}
use log::{debug, info, error};
#[tokio::test]
async fn test_keypair_management_and_crypto() {
debug_log("[DEBUG][TEST] test_keypair_management_and_crypto started");
let _ = env_logger::builder().is_test(true).try_init();
debug!("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");
@@ -27,39 +19,39 @@ async fn test_keypair_management_and_crypto() {
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");
debug!("keyspace: {} password: {}", keyspace, hex::encode(password));
debug!("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");
debug!("after create_keyspace: keyspace={} password={}", keyspace, hex::encode(password));
debug!("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)),
Ok(_) => debug!("after add Ed25519 keypair (Ok)"),
Err(e) => debug!("after add Ed25519 keypair (Err): {:?}", e),
}
let key_id = key_id.unwrap();
debug_log("[DEBUG][TEST] before add secp256k1 keypair");
debug!("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");
debug!("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");
debug!("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");
debug!("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");
debug!("before verify Ed25519");
let ok = vault.verify(keyspace, password, &key_id, msg, &sig).await.unwrap();
assert!(ok);
debug_log("[DEBUG][TEST] before sign secp256k1");
debug!("before sign secp256k1");
let sig2 = vault.sign(keyspace, password, &secp_id, msg).await.unwrap();
debug_log("[DEBUG][TEST] before verify secp256k1");
debug!("before verify secp256k1");
let ok2 = vault.verify(keyspace, password, &secp_id, msg, &sig2).await.unwrap();
assert!(ok2);

View File

@@ -10,107 +10,108 @@ 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();
console_log::init_with_level(log::Level::Debug).expect("error initializing logger");
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");
log::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; }
Ok(_) => log::debug!("Created keyspace"),
Err(e) => { log::debug!("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; }
Ok(id) => { log::debug!("Added Ed25519 keypair: {}", id); id },
Err(e) => { log::debug!("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; }
Ok(id) => { log::debug!("Added Secp256k1 keypair: {}", id); id },
Err(e) => { log::debug!("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; }
Ok(keys) => { log::debug!("Listed keypairs: {:?}", keys); keys },
Err(e) => { log::debug!("Failed to list keypairs: {:?}", e); return; }
};
if keys.len() != 2 {
println!("[ERROR] Expected 2 keypairs, got {}", keys.len());
log::debug!("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());
log::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; }
Err(e) => { log::debug!("Failed to export Ed25519 keypair: {:?}", e); return; }
};
if priv_bytes.is_empty() || pub_bytes.is_empty() {
println!("[ERROR] Exported Ed25519 keypair bytes are empty");
log::debug!("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; }
Ok(sig) => { log::debug!("Signed message with Ed25519"); sig },
Err(e) => { log::debug!("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; }
Ok(ok) => { log::debug!("Verified Ed25519 signature: {}", ok); ok },
Err(e) => { log::debug!("Failed to verify Ed25519 signature: {:?}", e); return; }
};
if !ok {
println!("[ERROR] Ed25519 signature verification failed");
log::debug!("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; }
Ok(sig) => { log::debug!("Signed message with Secp256k1"); sig },
Err(e) => { log::debug!("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; }
Ok(ok) => { log::debug!("Verified Secp256k1 signature: {}", ok); ok },
Err(e) => { log::debug!("Failed to verify Secp256k1 signature: {:?}", e); return; }
};
if !ok2 {
println!("[ERROR] Secp256k1 signature verification failed");
log::debug!("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; }
Ok(ct) => { log::debug!("Encrypted message"); ct },
Err(e) => { log::debug!("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; }
Ok(pt) => { log::debug!("Decrypted message"); pt },
Err(e) => { log::debug!("Failed to decrypt message: {:?}", e); return; }
};
if plaintext != msg {
println!("[ERROR] Decrypted message does not match original");
log::debug!("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; }
Ok(_) => log::debug!("Removed Ed25519 keypair"),
Err(e) => { log::debug!("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; }
Ok(keys) => { log::debug!("Listed keypairs after removal: {:?}", keys); keys },
Err(e) => { log::debug!("Failed to list keypairs after removal: {:?}", e); return; }
};
if keys.len() != 1 {
println!("[ERROR] Expected 1 keypair after removal, got {}", keys.len());
log::debug!("Expected 1 keypair after removal, got {}", keys.len());
return;
}
}