Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

chore(rust): drop core tests from cli branch

Prateek Sunal8cb81663d131
diff --git a/rust/core/tests/.gitignore b/rust/core/tests/.gitignore
deleted file mode 100644
index 6f6e4b49dd..0000000000
--- a/rust/core/tests/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# Node dependencies should not be committed
-node_modules/
diff --git a/rust/core/tests/auth_integration.rs b/rust/core/tests/auth_integration.rs
deleted file mode 100644
index 527c89b5a6..0000000000
--- a/rust/core/tests/auth_integration.rs
+++ /dev/null
@@ -1,319 +0,0 @@
-//! Integration tests for authentication module.
-
-use ente_core::auth::{
- KeyAttributes, KeyDerivationStrength, SrpAttributes, create_new_recovery_key,
- decrypt_secrets_legacy, decrypt_secrets_with_kek, derive_keys_for_login,
- generate_key_attributes_for_new_password_with_strength, generate_keys_with_strength,
- get_recovery_key, recover_with_key,
-};
-use ente_core::crypto::{self, argon, keys, sealed, secretbox};
-
-// Use Interactive for fast tests
-fn generate_test_keys(password: &str) -> ente_core::auth::KeyGenResult {
- generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap()
-}
-
-fn create_sealed_token(token: &[u8], public_key: &[u8]) -> String {
- let sealed = sealed::seal(token, public_key).unwrap();
- crypto::encode_b64(&sealed)
-}
-
-mod signup {
- use super::*;
-
- #[test]
- fn test_complete_signup_flow() {
- crypto::init().unwrap();
- let result = generate_test_keys("secure_password_123!");
-
- assert!(!result.key_attributes.kek_salt.is_empty());
- assert!(!result.key_attributes.encrypted_key.is_empty());
- assert!(result.key_attributes.mem_limit.is_some());
- assert!(
- result
- .key_attributes
- .master_key_encrypted_with_recovery_key
- .is_some()
- );
- assert_eq!(result.login_key.len(), 16);
- }
-
- #[test]
- fn test_signup_produces_valid_keypair() {
- crypto::init().unwrap();
- let result = generate_test_keys("password");
-
- let public_key = crypto::decode_b64(&result.key_attributes.public_key).unwrap();
- let master_key = crypto::decode_b64(&result.private_key_attributes.key).unwrap();
-
- let enc_secret = crypto::decode_b64(&result.key_attributes.encrypted_secret_key).unwrap();
- let nonce = crypto::decode_b64(&result.key_attributes.secret_key_decryption_nonce).unwrap();
- let secret_key = secretbox::decrypt(&enc_secret, &nonce, &master_key).unwrap();
-
- let test_data = b"test message";
- let sealed = sealed::seal(test_data, &public_key).unwrap();
- let opened = sealed::open(&sealed, &public_key, &secret_key).unwrap();
- assert_eq!(opened, test_data);
- }
-}
-
-mod login {
- use super::*;
-
- #[test]
- fn test_complete_login_flow() {
- crypto::init().unwrap();
- let password = "my_password";
- let signup = generate_test_keys(password);
- let public_key = crypto::decode_b64(&signup.key_attributes.public_key).unwrap();
-
- let token = b"auth_token_xyz";
- let encrypted_token = create_sealed_token(token, &public_key);
-
- let login_result =
- decrypt_secrets_legacy(password, &signup.key_attributes, &encrypted_token).unwrap();
-
- let expected_master = crypto::decode_b64(&signup.private_key_attributes.key).unwrap();
- assert_eq!(login_result.master_key, expected_master);
- assert_eq!(login_result.token, token);
- }
-
- #[test]
- fn test_wrong_password_fails() {
- crypto::init().unwrap();
- let signup = generate_test_keys("correct_password");
- let public_key = crypto::decode_b64(&signup.key_attributes.public_key).unwrap();
- let encrypted_token = create_sealed_token(b"token", &public_key);
-
- let result =
- decrypt_secrets_legacy("wrong_password", &signup.key_attributes, &encrypted_token);
- assert!(result.is_err());
- }
-
- #[test]
- fn test_login_with_precomputed_kek() {
- crypto::init().unwrap();
- let password = "password";
- let signup = generate_test_keys(password);
- let public_key = crypto::decode_b64(&signup.key_attributes.public_key).unwrap();
- let encrypted_token = create_sealed_token(b"token", &public_key);
-
- let kek_salt = crypto::decode_b64(&signup.key_attributes.kek_salt).unwrap();
- let kek = argon::derive_key(
- password,
- &kek_salt,
- signup.key_attributes.mem_limit.unwrap(),
- signup.key_attributes.ops_limit.unwrap(),
- )
- .unwrap();
-
- let result =
- decrypt_secrets_with_kek(&kek, &signup.key_attributes, &encrypted_token).unwrap();
- assert_eq!(result.token, b"token");
- }
-
- #[test]
- fn test_derive_keys_for_login() {
- crypto::init().unwrap();
- let password = "password";
- let signup = generate_test_keys(password);
-
- let srp_attrs = SrpAttributes {
- srp_user_id: "user123".to_string(),
- srp_salt: crypto::encode_b64(&keys::random_bytes(16)),
- mem_limit: signup.key_attributes.mem_limit.unwrap(),
- ops_limit: signup.key_attributes.ops_limit.unwrap(),
- kek_salt: signup.key_attributes.kek_salt.clone(),
- is_email_mfa_enabled: false,
- };
-
- let (kek, login_key) = derive_keys_for_login(password, &srp_attrs).unwrap();
- assert_eq!(kek.len(), 32);
- assert_eq!(login_key, signup.login_key);
- }
-}
-
-mod recovery {
- use super::*;
-
- #[test]
- fn test_complete_recovery_flow() {
- crypto::init().unwrap();
- let signup = generate_test_keys("original_password");
- let public_key = crypto::decode_b64(&signup.key_attributes.public_key).unwrap();
- let encrypted_token = create_sealed_token(b"my_token", &public_key);
-
- let recovery_result = recover_with_key(
- &signup.private_key_attributes.recovery_key,
- &signup.key_attributes,
- &encrypted_token,
- )
- .unwrap();
-
- let expected_master = crypto::decode_b64(&signup.private_key_attributes.key).unwrap();
- assert_eq!(recovery_result.master_key, expected_master);
- }
-
- #[test]
- fn test_wrong_recovery_key_fails() {
- crypto::init().unwrap();
- let signup = generate_test_keys("password");
- let public_key = crypto::decode_b64(&signup.key_attributes.public_key).unwrap();
- let encrypted_token = create_sealed_token(b"token", &public_key);
-
- let wrong_key = crypto::encode_hex(&keys::generate_key());
- let result = recover_with_key(&wrong_key, &signup.key_attributes, &encrypted_token);
- assert!(result.is_err());
- }
-
- #[test]
- fn test_get_recovery_key() {
- crypto::init().unwrap();
- let signup = generate_test_keys("password");
- let master_key = crypto::decode_b64(&signup.private_key_attributes.key).unwrap();
-
- let recovered = get_recovery_key(&master_key, &signup.key_attributes).unwrap();
- assert_eq!(recovered, signup.private_key_attributes.recovery_key);
- }
-
- #[test]
- fn test_create_new_recovery_key() {
- crypto::init().unwrap();
- let signup = generate_test_keys("password");
- let master_key = crypto::decode_b64(&signup.private_key_attributes.key).unwrap();
- let public_key = crypto::decode_b64(&signup.key_attributes.public_key).unwrap();
-
- let (new_recovery_hex, enc_master, nonce_master, enc_recovery, nonce_recovery) =
- create_new_recovery_key(&master_key).unwrap();
-
- assert_ne!(new_recovery_hex, signup.private_key_attributes.recovery_key);
-
- let mut updated_attrs = signup.key_attributes.clone();
- updated_attrs.master_key_encrypted_with_recovery_key = Some(enc_master);
- updated_attrs.master_key_decryption_nonce = Some(nonce_master);
- updated_attrs.recovery_key_encrypted_with_master_key = Some(enc_recovery);
- updated_attrs.recovery_key_decryption_nonce = Some(nonce_recovery);
-
- let encrypted_token = create_sealed_token(b"token", &public_key);
- let result = recover_with_key(&new_recovery_hex, &updated_attrs, &encrypted_token).unwrap();
- assert_eq!(result.master_key, master_key);
- }
-}
-
-mod password_change {
- use super::*;
-
- #[test]
- fn test_password_change_flow() {
- crypto::init().unwrap();
- let old_password = "old_password";
- let new_password = "new_password";
-
- let signup = generate_test_keys(old_password);
- let master_key = crypto::decode_b64(&signup.private_key_attributes.key).unwrap();
- let public_key = crypto::decode_b64(&signup.key_attributes.public_key).unwrap();
-
- let (new_attrs, _) = generate_key_attributes_for_new_password_with_strength(
- &master_key,
- new_password,
- KeyDerivationStrength::Interactive,
- )
- .unwrap();
-
- let mut updated = signup.key_attributes.clone();
- updated.kek_salt = new_attrs.kek_salt;
- updated.encrypted_key = new_attrs.encrypted_key;
- updated.key_decryption_nonce = new_attrs.key_decryption_nonce;
- updated.mem_limit = new_attrs.mem_limit;
- updated.ops_limit = new_attrs.ops_limit;
-
- let encrypted_token = create_sealed_token(b"token", &public_key);
-
- // Old password should fail
- let result = decrypt_secrets_legacy(old_password, &updated, &encrypted_token);
- assert!(result.is_err());
-
- // New password should work
- let result = decrypt_secrets_legacy(new_password, &updated, &encrypted_token).unwrap();
- assert_eq!(result.master_key, master_key);
- }
-}
-
-mod edge_cases {
- use super::*;
-
- #[test]
- fn test_unicode_passwords() {
- crypto::init().unwrap();
-
- let passwords = ["ΠΏΠ°Ρ€ΠΎΠ»ΡŒ", "密码", "πŸ”πŸ”‘πŸ”’"];
-
- for password in &passwords {
- let signup = generate_test_keys(password);
- let public_key = crypto::decode_b64(&signup.key_attributes.public_key).unwrap();
- let encrypted_token = create_sealed_token(b"token", &public_key);
-
- let result =
- decrypt_secrets_legacy(password, &signup.key_attributes, &encrypted_token).unwrap();
- assert_eq!(result.token, b"token");
- }
- }
-
- #[test]
- fn test_empty_password() {
- crypto::init().unwrap();
- let result = generate_test_keys("");
- assert!(!result.key_attributes.encrypted_key.is_empty());
- }
-}
-
-mod serialization {
- use super::*;
-
- #[test]
- fn test_key_attributes_json_roundtrip() {
- crypto::init().unwrap();
- let signup = generate_test_keys("password");
-
- let json = serde_json::to_string(&signup.key_attributes).unwrap();
- let parsed: KeyAttributes = serde_json::from_str(&json).unwrap();
-
- assert_eq!(parsed.kek_salt, signup.key_attributes.kek_salt);
- assert_eq!(parsed.encrypted_key, signup.key_attributes.encrypted_key);
- }
-
- #[test]
- fn test_key_attributes_camel_case() {
- crypto::init().unwrap();
- let signup = generate_test_keys("password");
- let json = serde_json::to_string(&signup.key_attributes).unwrap();
-
- assert!(json.contains("kekSalt"));
- assert!(json.contains("encryptedKey"));
- assert!(json.contains("memLimit"));
- }
-
- #[test]
- fn test_srp_attributes_json() {
- let attrs = SrpAttributes {
- srp_user_id: "user123".to_string(),
- srp_salt: "c2FsdA==".to_string(),
- mem_limit: 67108864,
- ops_limit: 2,
- kek_salt: "a2VrU2FsdA==".to_string(),
- is_email_mfa_enabled: false,
- };
-
- let json = serde_json::to_string(&attrs).unwrap();
- assert!(json.contains("\"srpUserID\""));
- assert!(json.contains("\"isEmailMFAEnabled\""));
-
- let parsed: SrpAttributes = serde_json::from_str(&json).unwrap();
- assert_eq!(parsed.srp_user_id, attrs.srp_user_id);
- assert_eq!(parsed.mem_limit, attrs.mem_limit);
-
- let json_missing_flag = r#"{"srpUserID":"user123","srpSalt":"c2FsdA==","memLimit":67108864,"opsLimit":2,"kekSalt":"a2VrU2FsdA=="}"#;
- let parsed_missing: SrpAttributes = serde_json::from_str(json_missing_flag).unwrap();
- assert!(parsed_missing.is_email_mfa_enabled);
- }
-}
diff --git a/rust/core/tests/comprehensive_crypto_tests.rs b/rust/core/tests/comprehensive_crypto_tests.rs
deleted file mode 100644
index 11061f63fb..0000000000
--- a/rust/core/tests/comprehensive_crypto_tests.rs
+++ /dev/null
@@ -1,651 +0,0 @@
-//! Comprehensive cryptographic tests for ente-core.
-//!
-//! These tests verify the pure Rust crypto implementation with:
-//! - Edge cases (empty, small, large data)
-//! - All crypto primitives
-//! - Format compatibility
-
-use ente_core::crypto;
-
-// ============================================================================
-// Stream Encryption Tests
-// ============================================================================
-
-#[test]
-fn test_stream_encrypt_decrypt_empty() {
- crypto::init().unwrap();
- let key = vec![0x42u8; 32];
- let plaintext = b"";
-
- let encrypted = crypto::stream::encrypt(plaintext, &key).unwrap();
- let decrypted = crypto::stream::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
-
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_stream_encrypt_decrypt_small() {
- crypto::init().unwrap();
- let key = vec![0x42u8; 32];
- let plaintext = b"Hello, World!";
-
- let encrypted = crypto::stream::encrypt(plaintext, &key).unwrap();
- let decrypted = crypto::stream::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
-
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_stream_encrypt_decrypt_large() {
- crypto::init().unwrap();
- let key = vec![0x42u8; 32];
- let plaintext = vec![0xAB; 1024 * 1024]; // 1 MB
-
- let encrypted = crypto::stream::encrypt(&plaintext, &key).unwrap();
- let decrypted = crypto::stream::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
-
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_stream_multi_chunk() {
- crypto::init().unwrap();
- let key = vec![0x42u8; 32];
- let chunks = [
- b"First chunk".to_vec(),
- b"Second chunk".to_vec(),
- b"Third chunk".to_vec(),
- ];
-
- let mut encryptor = crypto::stream::StreamEncryptor::new(&key).unwrap();
- let mut encrypted_chunks = Vec::new();
- for (i, chunk) in chunks.iter().enumerate() {
- let is_final = i == chunks.len() - 1;
- encrypted_chunks.push(encryptor.push(chunk, is_final).unwrap());
- }
-
- let mut decryptor = crypto::stream::StreamDecryptor::new(&encryptor.header, &key).unwrap();
- for (i, (ct, original)) in encrypted_chunks.iter().zip(chunks.iter()).enumerate() {
- let (pt, tag) = decryptor.pull(ct).unwrap();
- assert_eq!(pt, *original);
- let expected_tag = if i == chunks.len() - 1 {
- crypto::stream::TAG_FINAL
- } else {
- crypto::stream::TAG_MESSAGE
- };
- assert_eq!(tag, expected_tag);
- }
-}
-
-// ============================================================================
-// SecretBox Tests
-// ============================================================================
-
-#[test]
-fn test_secretbox_roundtrip() {
- crypto::init().unwrap();
- let key = vec![0x42u8; 32];
- let nonce = vec![0x00u8; 24];
- let plaintext = b"Secret message";
-
- let ciphertext = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();
- let decrypted = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
-
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_secretbox_empty() {
- crypto::init().unwrap();
- let key = vec![0x42u8; 32];
- let nonce = vec![0x00u8; 24];
- let plaintext = b"";
-
- let ciphertext = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();
- assert_eq!(ciphertext.len(), 16); // Just MAC
-
- let decrypted = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_secretbox_large() {
- crypto::init().unwrap();
- let key = vec![0x42u8; 32];
- let nonce = vec![0x00u8; 24];
- let plaintext = vec![0xAB; 1024 * 1024];
-
- let ciphertext = crypto::secretbox::encrypt_with_nonce(&plaintext, &nonce, &key).unwrap();
- let decrypted = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
-
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_secretbox_tamper_detection() {
- crypto::init().unwrap();
- let key = vec![0x42u8; 32];
- let nonce = vec![0x00u8; 24];
- let plaintext = b"Secret message";
-
- let mut ciphertext = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();
- ciphertext[10] ^= 0xFF; // Tamper
-
- let result = crypto::secretbox::decrypt(&ciphertext, &nonce, &key);
- assert!(result.is_err());
-}
-
-#[test]
-fn test_secretbox_with_generated_nonce() {
- crypto::init().unwrap();
- let key = vec![0x42u8; 32];
- let plaintext = b"Secret message";
-
- // Use the encrypt function that generates nonce
- let encrypted = crypto::secretbox::encrypt(plaintext, &key).unwrap();
-
- // Decrypt using decrypt_box which handles EncryptedData
- let decrypted = crypto::secretbox::decrypt_box(&encrypted, &key).unwrap();
- assert_eq!(decrypted, plaintext);
-}
-
-// ============================================================================
-// SealedBox Tests
-// ============================================================================
-
-#[test]
-fn test_sealedbox_roundtrip() {
- crypto::init().unwrap();
- let (pk, sk) = crypto::keys::generate_keypair().unwrap();
- let plaintext = b"Sealed message";
-
- let ciphertext = crypto::sealed::seal(plaintext, &pk).unwrap();
- let decrypted = crypto::sealed::open(&ciphertext, &pk, &sk).unwrap();
-
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_sealedbox_empty() {
- crypto::init().unwrap();
- let (pk, sk) = crypto::keys::generate_keypair().unwrap();
- let plaintext = b"";
-
- let ciphertext = crypto::sealed::seal(plaintext, &pk).unwrap();
- let decrypted = crypto::sealed::open(&ciphertext, &pk, &sk).unwrap();
-
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_sealedbox_wrong_key() {
- crypto::init().unwrap();
- let (pk1, _sk1) = crypto::keys::generate_keypair().unwrap();
- let (_pk2, sk2) = crypto::keys::generate_keypair().unwrap();
- let plaintext = b"Sealed message";
-
- let ciphertext = crypto::sealed::seal(plaintext, &pk1).unwrap();
- let result = crypto::sealed::open(&ciphertext, &pk1, &sk2);
- assert!(result.is_err());
-}
-
-// ============================================================================
-// Argon2 Tests
-// ============================================================================
-
-#[test]
-fn test_argon2_deterministic() {
- crypto::init().unwrap();
- let password = "test_password";
- let salt = [0u8; 16];
-
- let key1 = crypto::argon::derive_key(password, &salt, 64 * 1024, 2).unwrap();
- let key2 = crypto::argon::derive_key(password, &salt, 64 * 1024, 2).unwrap();
-
- assert_eq!(key1, key2);
-}
-
-#[test]
-fn test_argon2_different_salts() {
- crypto::init().unwrap();
- let password = "test_password";
- let salt1 = [0u8; 16];
- let salt2 = [1u8; 16];
-
- let key1 = crypto::argon::derive_key(password, &salt1, 64 * 1024, 2).unwrap();
- let key2 = crypto::argon::derive_key(password, &salt2, 64 * 1024, 2).unwrap();
-
- assert_ne!(key1, key2);
-}
-
-#[test]
-fn test_argon2_interactive() {
- crypto::init().unwrap();
- let password = "test_password";
- let salt = [0x42u8; 16];
-
- let key = crypto::argon::derive_interactive_key_with_salt(password, &salt).unwrap();
- assert_eq!(key.len(), 32);
-}
-
-// ============================================================================
-// KDF Tests
-// ============================================================================
-
-#[test]
-fn test_kdf_deterministic() {
- crypto::init().unwrap();
- let master_key = [0x42u8; 32];
-
- let subkey1 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"loginctx").unwrap();
- let subkey2 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"loginctx").unwrap();
-
- assert_eq!(subkey1, subkey2);
-}
-
-#[test]
-fn test_kdf_different_ids() {
- crypto::init().unwrap();
- let master_key = [0x42u8; 32];
-
- let subkey1 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"loginctx").unwrap();
- let subkey2 = crypto::kdf::derive_subkey(&master_key, 32, 2, b"loginctx").unwrap();
-
- assert_ne!(subkey1, subkey2);
-}
-
-#[test]
-fn test_kdf_different_contexts() {
- crypto::init().unwrap();
- let master_key = [0x42u8; 32];
-
- let subkey1 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"loginctx").unwrap();
- let subkey2 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"otherctx").unwrap();
-
- assert_ne!(subkey1, subkey2);
-}
-
-#[test]
-fn test_kdf_login_key() {
- crypto::init().unwrap();
- let master_key = [0x42u8; 32];
-
- let login_key = crypto::kdf::derive_login_key(&master_key).unwrap();
- assert_eq!(login_key.len(), 16);
-
- // Should be deterministic
- let login_key2 = crypto::kdf::derive_login_key(&master_key).unwrap();
- assert_eq!(login_key, login_key2);
-}
-
-// ============================================================================
-// Hash Tests
-// ============================================================================
-
-#[test]
-fn test_hash_deterministic() {
- crypto::init().unwrap();
- let data = b"Data to hash";
-
- let hash1 = crypto::hash::hash(data, Some(64), None).unwrap();
- let hash2 = crypto::hash::hash(data, Some(64), None).unwrap();
-
- assert_eq!(hash1, hash2);
-}
-
-#[test]
-fn test_hash_different_lengths() {
- crypto::init().unwrap();
- let data = b"Data to hash";
-
- let hash32 = crypto::hash::hash(data, Some(32), None).unwrap();
- let hash64 = crypto::hash::hash(data, Some(64), None).unwrap();
-
- assert_eq!(hash32.len(), 32);
- assert_eq!(hash64.len(), 64);
-}
-
-#[test]
-fn test_hash_keyed() {
- crypto::init().unwrap();
- let data = b"Data to hash";
- let key1 = [0x42u8; 32];
- let key2 = [0x43u8; 32];
-
- let hash1 = crypto::hash::hash(data, Some(64), Some(&key1)).unwrap();
- let hash2 = crypto::hash::hash(data, Some(64), Some(&key2)).unwrap();
- let hash_unkeyed = crypto::hash::hash(data, Some(64), None).unwrap();
-
- assert_ne!(hash1, hash2);
- assert_ne!(hash1, hash_unkeyed);
-}
-
-#[test]
-fn test_hash_default() {
- crypto::init().unwrap();
- let data = b"Data to hash";
-
- let hash = crypto::hash::hash_default(data).unwrap();
- assert_eq!(hash.len(), 64); // Default is 64 bytes (BLAKE2b-512)
-}
-
-// ============================================================================
-// Integration: Ente Auth Flow
-// ============================================================================
-
-#[test]
-fn test_ente_key_derivation_flow() {
- crypto::init().unwrap();
-
- // 1. Derive KEK from password
- let password = "user_password";
- let salt = [0x42u8; 16];
- let kek = crypto::argon::derive_interactive_key_with_salt(password, &salt).unwrap();
-
- // 2. Generate master key
- let master_key = crypto::keys::generate_key();
- assert_eq!(master_key.len(), 32);
-
- // 3. Encrypt master key with KEK
- let encrypted = crypto::secretbox::encrypt(&master_key, &kek).unwrap();
-
- // 4. Decrypt master key
- let decrypted_master_key = crypto::secretbox::decrypt_box(&encrypted, &kek).unwrap();
- assert_eq!(decrypted_master_key, master_key);
-
- // 5. Derive login key from master key
- let login_key = crypto::kdf::derive_login_key(&decrypted_master_key).unwrap();
- assert_eq!(login_key.len(), 16);
-}
-
-#[test]
-fn test_ente_file_encryption_flow() {
- crypto::init().unwrap();
-
- // 1. Generate file key
- let file_key = crypto::keys::generate_stream_key();
-
- // 2. Encrypt file content
- let file_content = b"Photo data here...";
- let encrypted_file = crypto::stream::encrypt(file_content, &file_key).unwrap();
-
- // 3. Encrypt metadata
- let metadata = br#"{"title": "photo.jpg"}"#;
- let encrypted_meta = crypto::stream::encrypt(metadata, &file_key).unwrap();
-
- // 4. Decrypt file
- let decrypted_file = crypto::stream::decrypt(
- &encrypted_file.encrypted_data,
- &encrypted_file.decryption_header,
- &file_key,
- )
- .unwrap();
- assert_eq!(decrypted_file, file_content);
-
- // 5. Decrypt metadata
- let decrypted_meta = crypto::stream::decrypt(
- &encrypted_meta.encrypted_data,
- &encrypted_meta.decryption_header,
- &file_key,
- )
- .unwrap();
- assert_eq!(decrypted_meta, metadata);
-}
-
-// ============================================================================
-// Known Test Vectors (from libsodium validation)
-// ============================================================================
-
-#[test]
-fn test_argon2_known_vector() {
- crypto::init().unwrap();
-
- // This vector was validated against libsodium
- let password = "test_password";
- let salt = [
- 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd,
- 0xef,
- ];
-
- let key = crypto::argon::derive_key(password, &salt, 64 * 1024, 2).unwrap();
-
- // The key should be deterministic - same params = same output
- let key2 = crypto::argon::derive_key(password, &salt, 64 * 1024, 2).unwrap();
- assert_eq!(key, key2);
- assert_eq!(key.len(), 32);
-}
-
-#[test]
-fn test_kdf_known_vector() {
- crypto::init().unwrap();
-
- // This vector was validated against libsodium
- let master_key = [
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
- 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
- 0x1e, 0x1f,
- ];
-
- let login_key = crypto::kdf::derive_login_key(&master_key).unwrap();
-
- // Known expected value (validated against libsodium)
- let expected = hex::decode("6970b5d34442fd11788a83b4b57e1e72").unwrap();
- assert_eq!(login_key, expected);
-}
-
-#[test]
-fn test_secretbox_known_vector() {
- crypto::init().unwrap();
-
- let key = [0x42u8; 32];
- let nonce = [0x00u8; 24];
- let plaintext = b"test";
-
- let ciphertext = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();
-
- // Ciphertext should be plaintext + 16 bytes MAC
- assert_eq!(ciphertext.len(), plaintext.len() + 16);
-
- // Should decrypt correctly
- let decrypted = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_hash_known_vector() {
- crypto::init().unwrap();
-
- // BLAKE2b test vector
- let data = b"";
- let hash = crypto::hash::hash(data, Some(64), None).unwrap();
-
- // Empty string BLAKE2b-512 hash (known value)
- let expected = hex::decode(
- "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419\
- d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce",
- )
- .unwrap();
- assert_eq!(hash, expected);
-}
-
-// ============================================================================
-// More Known Test Vectors (validated against libsodium)
-// These ensure we don't need to run validation suite for basic checks
-// ============================================================================
-
-#[test]
-fn test_secretbox_known_vector_full() {
- crypto::init().unwrap();
-
- // Test vector with known inputs and expected output
- let key =
- hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap();
- let nonce = hex::decode("000102030405060708090a0b0c0d0e0f1011121314151617").unwrap();
- let plaintext = b"Hello, World!";
-
- let ciphertext = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();
-
- // Verify we can decrypt
- let decrypted = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
- assert_eq!(decrypted, plaintext);
-
- // Verify format: ciphertext = encrypted_data || MAC (16 bytes)
- assert_eq!(ciphertext.len(), plaintext.len() + 16);
-}
-
-#[test]
-fn test_sealedbox_format() {
- crypto::init().unwrap();
-
- let (pk, sk) = crypto::keys::generate_keypair().unwrap();
- let plaintext = b"Sealed test";
-
- let ciphertext = crypto::sealed::seal(plaintext, &pk).unwrap();
-
- // Format: ephemeral_pk (32) || ciphertext || MAC
- // Total overhead: 32 + 16 = 48 bytes
- assert_eq!(ciphertext.len(), plaintext.len() + 48);
-
- let decrypted = crypto::sealed::open(&ciphertext, &pk, &sk).unwrap();
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_stream_format() {
- crypto::init().unwrap();
-
- let key = [0x42u8; 32];
- let plaintext = b"Stream test";
-
- let encrypted = crypto::stream::encrypt(plaintext, &key).unwrap();
-
- // Header is 24 bytes
- assert_eq!(encrypted.decryption_header.len(), 24);
-
- // Ciphertext = encrypted_tag (1) || ciphertext || MAC (16) = 17 + plaintext.len()
- assert_eq!(encrypted.encrypted_data.len(), plaintext.len() + 17);
-
- let decrypted = crypto::stream::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
- assert_eq!(decrypted, plaintext);
-}
-
-#[test]
-fn test_argon2_moderate_params() {
- crypto::init().unwrap();
-
- let password = "test_password";
- let salt = [0x42u8; 16];
-
- // Moderate: 256 MB, 3 ops
- let key = crypto::argon::derive_moderate_key(password, &salt).unwrap();
- assert_eq!(key.len(), 32);
-
- // Should be deterministic
- let key2 = crypto::argon::derive_moderate_key(password, &salt).unwrap();
- assert_eq!(key, key2);
-}
-
-#[test]
-fn test_kdf_subkey_lengths() {
- crypto::init().unwrap();
-
- let master_key = [0x42u8; 32];
-
- // Test various output lengths
- let key16 = crypto::kdf::derive_subkey(&master_key, 16, 1, b"testctx0").unwrap();
- let key32 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"testctx0").unwrap();
- let key64 = crypto::kdf::derive_subkey(&master_key, 64, 1, b"testctx0").unwrap();
-
- assert_eq!(key16.len(), 16);
- assert_eq!(key32.len(), 32);
- assert_eq!(key64.len(), 64);
-
- // Longer key should be prefix of shorter? No - they're different derivations
- // Just verify they're all deterministic
- let key32_2 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"testctx0").unwrap();
- assert_eq!(key32, key32_2);
-}
-
-#[test]
-fn test_hash_empty_input() {
- crypto::init().unwrap();
-
- // BLAKE2b-512 of empty string - known value
- let hash = crypto::hash::hash(b"", Some(64), None).unwrap();
- let expected = hex::decode(
- "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419\
- d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce",
- )
- .unwrap();
- assert_eq!(hash, expected);
-}
-
-#[test]
-fn test_ente_full_auth_simulation() {
- crypto::init().unwrap();
-
- // Simulate full ente auth flow with known values
- let password = "my_secure_password";
- let salt = [0x01u8; 16];
-
- // 1. Derive KEK
- let kek = crypto::argon::derive_interactive_key_with_salt(password, &salt).unwrap();
- assert_eq!(kek.len(), 32);
-
- // 2. Generate and encrypt master key
- let master_key = crypto::keys::generate_key();
- let encrypted_mk = crypto::secretbox::encrypt(&master_key, &kek).unwrap();
-
- // 3. Decrypt master key
- let decrypted_mk = crypto::secretbox::decrypt_box(&encrypted_mk, &kek).unwrap();
- assert_eq!(decrypted_mk, master_key);
-
- // 4. Derive login key
- let login_key = crypto::kdf::derive_login_key(&decrypted_mk).unwrap();
- assert_eq!(login_key.len(), 16);
-
- // 5. Generate keypair for sealed box
- let (pk, sk) = crypto::keys::generate_keypair().unwrap();
-
- // 6. Seal a token
- let token = b"auth_token_12345";
- let sealed_token = crypto::sealed::seal(token, &pk).unwrap();
-
- // 7. Open the token
- let opened_token = crypto::sealed::open(&sealed_token, &pk, &sk).unwrap();
- assert_eq!(opened_token, token);
-
- // 8. Encrypt a file
- let file_key = crypto::keys::generate_stream_key();
- let file_data = b"Photo metadata and content";
- let encrypted_file = crypto::stream::encrypt(file_data, &file_key).unwrap();
-
- // 9. Decrypt the file
- let decrypted_file = crypto::stream::decrypt(
- &encrypted_file.encrypted_data,
- &encrypted_file.decryption_header,
- &file_key,
- )
- .unwrap();
- assert_eq!(decrypted_file, file_data);
-}
diff --git a/rust/core/tests/crypto_interop.rs b/rust/core/tests/crypto_interop.rs
deleted file mode 100644
index ec81cab8e8..0000000000
--- a/rust/core/tests/crypto_interop.rs
+++ /dev/null
@@ -1,1411 +0,0 @@
-//! Integration tests for crypto interoperability with JS library.
-//!
-//! These tests verify that:
-//! 1. Rust encryption can be decrypted by JS (using fixed test vectors)
-//! 2. JS encryption can be decrypted by Rust (using pre-generated JS vectors)
-//!
-//! To regenerate JS test vectors, run: `node tests/js_interop_test.mjs --generate`
-
-use ente_core::crypto;
-
-/// Initialize crypto before all tests
-fn setup() {
- crypto::init().unwrap();
-}
-
-// =============================================================================
-// RUST β†’ JS: Encrypt in Rust, these vectors should decrypt correctly in JS
-// =============================================================================
-
-mod rust_to_js {
- use super::*;
-
- /// Fixed test data used across all tests
- const TEST_PLAINTEXT: &[u8] =
- b"Hello from Rust! This is test data for cross-platform verification.";
- const TEST_KEY_HEX: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
- const TEST_NONCE_HEX: &str = "000102030405060708090a0b0c0d0e0f1011121314151617";
-
- #[test]
- fn test_secretbox_encrypt_for_js() {
- setup();
-
- let key = crypto::decode_hex(TEST_KEY_HEX).unwrap();
- let nonce = crypto::decode_hex(TEST_NONCE_HEX).unwrap();
-
- let ciphertext =
- crypto::secretbox::encrypt_with_nonce(TEST_PLAINTEXT, &nonce, &key).unwrap();
- let ciphertext_b64 = crypto::encode_b64(&ciphertext);
-
- // This ciphertext should be decryptable in JS with the same key/nonce
- // JS: sodium.crypto_secretbox_open_easy(fromB64(ciphertext_b64), fromHex(nonce), fromHex(key))
- println!("=== RUST→JS SecretBox Test Vector ===");
- println!("Key (hex): {}", TEST_KEY_HEX);
- println!("Nonce (hex): {}", TEST_NONCE_HEX);
- println!("Plaintext: {:?}", String::from_utf8_lossy(TEST_PLAINTEXT));
- println!("Ciphertext (b64): {}", ciphertext_b64);
-
- // Verify we can decrypt our own ciphertext
- let decrypted = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
- assert_eq!(decrypted, TEST_PLAINTEXT);
-
- // Verify ciphertext has correct overhead (16 bytes MAC)
- assert_eq!(
- ciphertext.len(),
- TEST_PLAINTEXT.len() + crypto::secretbox::MAC_BYTES
- );
- }
-
- #[test]
- fn test_blob_encrypt_for_js() {
- setup();
-
- let key = crypto::decode_hex(TEST_KEY_HEX).unwrap();
- let plaintext = b"Metadata from Rust";
-
- let encrypted = crypto::blob::encrypt(plaintext, &key).unwrap();
- let ciphertext_b64 = crypto::encode_b64(&encrypted.encrypted_data);
- let header_b64 = crypto::encode_b64(&encrypted.decryption_header);
-
- println!("\n=== RUST→JS Blob Test Vector ===");
- println!("Key (hex): {}", TEST_KEY_HEX);
- println!("Plaintext: {:?}", String::from_utf8_lossy(plaintext));
- println!("Header (b64): {}", header_b64);
- println!("Ciphertext (b64): {}", ciphertext_b64);
-
- // Verify roundtrip
- let decrypted = crypto::blob::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
- assert_eq!(decrypted, plaintext);
- }
-
- #[test]
- fn test_hash_for_js() {
- setup();
-
- let data = b"Data to hash for cross-platform verification";
- let hash = crypto::hash::hash_default(data).unwrap();
- let hash_b64 = crypto::encode_b64(&hash);
-
- println!("\n=== RUST→JS Hash Test Vector ===");
- println!("Data: {:?}", String::from_utf8_lossy(data));
- println!("Hash (b64): {}", hash_b64);
-
- // Verify hash is correct length (64 bytes for BLAKE2b-512)
- assert_eq!(hash.len(), 64);
-
- // Verify hash is deterministic
- let hash2 = crypto::hash::hash_default(data).unwrap();
- assert_eq!(hash, hash2);
- }
-
- #[test]
- fn test_argon_derive_for_js() {
- setup();
-
- let password = "test_password_for_interop";
- let salt = crypto::decode_hex("fedcba9876543210fedcba9876543210").unwrap();
-
- let key = crypto::argon::derive_key(
- password,
- &salt,
- crypto::argon::MEMLIMIT_INTERACTIVE,
- crypto::argon::OPSLIMIT_INTERACTIVE,
- )
- .unwrap();
-
- let key_b64 = crypto::encode_b64(&key);
-
- println!("\n=== RUST→JS Argon2 Test Vector ===");
- println!("Password: {}", password);
- println!("Salt (hex): fedcba9876543210fedcba9876543210");
- println!("MemLimit: {}", crypto::argon::MEMLIMIT_INTERACTIVE);
- println!("OpsLimit: {}", crypto::argon::OPSLIMIT_INTERACTIVE);
- println!("Derived Key (b64): {}", key_b64);
-
- // JS should produce the same key with same parameters
- assert_eq!(key.len(), 32);
- }
-
- #[test]
- fn test_kdf_derive_for_js() {
- setup();
-
- let master_key = crypto::decode_hex(TEST_KEY_HEX).unwrap();
- let login_key = crypto::kdf::derive_login_key(&master_key).unwrap();
- let login_key_b64 = crypto::encode_b64(&login_key);
-
- println!("\n=== RUST→JS KDF Login Key Test Vector ===");
- println!("Master Key (hex): {}", TEST_KEY_HEX);
- println!("Login Key (b64): {}", login_key_b64);
-
- // JS: sodium.crypto_kdf_derive_from_key(32, 1, "loginctx", masterKey).slice(0, 16)
- assert_eq!(login_key.len(), 16);
- }
-
- #[test]
- fn test_sealed_box_for_js() {
- setup();
-
- // Use fixed keypair for reproducibility
- // In real usage, keys are random
- let (public_key, secret_key) = crypto::keys::generate_keypair().unwrap();
- let plaintext = b"Secret for sealed box";
-
- let ciphertext = crypto::sealed::seal(plaintext, &public_key).unwrap();
-
- println!("\n=== RUST→JS Sealed Box Test Vector ===");
- println!("Public Key (b64): {}", crypto::encode_b64(&public_key));
- println!("Secret Key (b64): {}", crypto::encode_b64(&secret_key));
- println!("Plaintext: {:?}", String::from_utf8_lossy(plaintext));
- println!("Ciphertext (b64): {}", crypto::encode_b64(&ciphertext));
-
- // Verify roundtrip
- let decrypted = crypto::sealed::open(&ciphertext, &public_key, &secret_key).unwrap();
- assert_eq!(decrypted, plaintext);
- }
-}
-
-// =============================================================================
-// JS β†’ RUST: These are test vectors generated by JS, verified to decrypt in Rust
-// =============================================================================
-
-mod js_to_rust {
- use super::*;
-
- /// These test vectors were generated using the JS library:
- /// ```javascript
- /// const sodium = require('libsodium-wrappers-sumo');
- /// await sodium.ready;
- /// // ... generate vectors
- /// ```
-
- #[test]
- fn test_secretbox_decrypt_from_js() {
- setup();
-
- // This test verifies that Rust can decrypt what it encrypts
- // (simulating JS-generated ciphertext with same algorithm)
- //
- // To test with actual JS ciphertext:
- // 1. Run: node tests/js_interop_test.mjs
- // 2. Copy the generated ciphertext here
-
- let key =
- crypto::decode_hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
- .unwrap();
- let nonce = crypto::decode_hex("000102030405060708090a0b0c0d0e0f1011121314151617").unwrap();
- let plaintext = b"Hello from JavaScript!";
-
- // Encrypt (simulating what JS would do)
- let ciphertext = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();
-
- // Verify Rust can decrypt
- let decrypted = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
- assert_eq!(decrypted, plaintext);
- }
-
- #[test]
- fn test_blob_decrypt_from_js() {
- setup();
-
- // Vector generated in JS:
- // const key = sodium.from_hex('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
- // const { state, header } = sodium.crypto_secretstream_xchacha20poly1305_init_push(key);
- // const ciphertext = sodium.crypto_secretstream_xchacha20poly1305_push(state, plaintext, null, TAG_FINAL);
-
- let key =
- crypto::decode_hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
- .unwrap();
-
- // These values would be generated by JS - using Rust values for now as placeholder
- // In a real scenario, you'd run the JS script and paste the output here
- let plaintext = b"Test blob from JS";
- let encrypted = crypto::blob::encrypt(plaintext, &key).unwrap();
-
- // Verify Rust can decrypt
- let decrypted = crypto::blob::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
- assert_eq!(decrypted, plaintext);
- }
-
- #[test]
- fn test_hash_matches_js() {
- setup();
-
- // This test verifies BLAKE2b hashing works correctly
- // Hash is deterministic - same input always produces same output
- let data = b"Hello from JavaScript!";
- let hash1 = crypto::hash::hash_default(data).unwrap();
- let hash2 = crypto::hash::hash_default(data).unwrap();
-
- // Verify deterministic
- assert_eq!(hash1, hash2);
-
- // Verify correct length
- assert_eq!(hash1.len(), 64);
-
- // Different data = different hash
- let hash3 = crypto::hash::hash_default(b"Different data").unwrap();
- assert_ne!(hash1, hash3);
- }
-
- #[test]
- fn test_argon_matches_js() {
- setup();
-
- // JS:
- // const password = sodium.from_string('interop_password');
- // const salt = sodium.from_hex('abcdef0123456789abcdef0123456789');
- // const key = sodium.crypto_pwhash(32, password, salt, 2, 67108864, sodium.crypto_pwhash_ALG_ARGON2ID13);
-
- let password = "interop_password";
- let salt = crypto::decode_hex("abcdef0123456789abcdef0123456789").unwrap();
-
- let key = crypto::argon::derive_key(
- password,
- &salt,
- crypto::argon::MEMLIMIT_INTERACTIVE,
- crypto::argon::OPSLIMIT_INTERACTIVE,
- )
- .unwrap();
-
- // The key should be deterministic - same inputs = same output
- let key2 = crypto::argon::derive_key(
- password,
- &salt,
- crypto::argon::MEMLIMIT_INTERACTIVE,
- crypto::argon::OPSLIMIT_INTERACTIVE,
- )
- .unwrap();
-
- assert_eq!(key, key2);
- assert_eq!(key.len(), 32);
- }
-
- #[test]
- fn test_sealed_box_decrypt_from_js() {
- setup();
-
- // For sealed box, we need to use a fixed keypair
- // JS would seal with the public key, Rust opens with the keypair
-
- let (public_key, secret_key) = crypto::keys::generate_keypair().unwrap();
- let plaintext = b"Sealed by hypothetical JS";
-
- // Simulate JS sealing (in reality, this would come from JS)
- let ciphertext = crypto::sealed::seal(plaintext, &public_key).unwrap();
-
- // Rust can open it
- let decrypted = crypto::sealed::open(&ciphertext, &public_key, &secret_key).unwrap();
- assert_eq!(decrypted, plaintext);
- }
-}
-
-// =============================================================================
-// BIDIRECTIONAL: Tests that verify encrypt/decrypt works in both directions
-// =============================================================================
-
-mod bidirectional {
- use super::*;
- use std::io::Cursor;
-
- /// This test generates vectors that can be used to verify JS implementation
- #[test]
- fn test_secretbox_bidirectional_vectors() {
- setup();
-
- let key =
- crypto::decode_hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
- .unwrap();
- let nonce = crypto::decode_hex("000102030405060708090a0b0c0d0e0f1011121314151617").unwrap();
-
- // Test 1: Encrypt in Rust
- let plaintext1 = b"Rust plaintext for JS to decrypt";
- let ciphertext1 = crypto::secretbox::encrypt_with_nonce(plaintext1, &nonce, &key).unwrap();
-
- // Verify Rust can decrypt its own ciphertext
- let decrypted1 = crypto::secretbox::decrypt(&ciphertext1, &nonce, &key).unwrap();
- assert_eq!(decrypted1, plaintext1);
-
- // Test 2: Decrypt ciphertext that would come from JS
- // (Using Rust-generated for now, but the point is the format is compatible)
- let plaintext2 = b"JS plaintext for Rust to decrypt";
- let ciphertext2 = crypto::secretbox::encrypt_with_nonce(plaintext2, &nonce, &key).unwrap();
- let decrypted2 = crypto::secretbox::decrypt(&ciphertext2, &nonce, &key).unwrap();
- assert_eq!(decrypted2, plaintext2);
-
- println!("\n=== Bidirectional SecretBox Vectors ===");
- println!("Key (hex): 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
- println!("Nonce (hex): 000102030405060708090a0b0c0d0e0f1011121314151617");
- println!("Plaintext 1: {:?}", String::from_utf8_lossy(plaintext1));
- println!("Ciphertext 1 (b64): {}", crypto::encode_b64(&ciphertext1));
- println!("Plaintext 2: {:?}", String::from_utf8_lossy(plaintext2));
- println!("Ciphertext 2 (b64): {}", crypto::encode_b64(&ciphertext2));
- }
-
- #[test]
- fn test_stream_bidirectional() {
- setup();
-
- let key = crypto::keys::generate_stream_key();
-
- // Test single-chunk encryption (simple encrypt function)
- let plaintext = vec![0x42u8; 1000];
- let encrypted = crypto::stream::encrypt(&plaintext, &key).unwrap();
- let decrypted = crypto::stream::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
- assert_eq!(decrypted, plaintext);
-
- // Simple encrypt is single-chunk: size = plaintext + ABYTES
- assert_eq!(
- encrypted.encrypted_data.len(),
- plaintext.len() + crypto::stream::ABYTES
- );
- }
-
- #[test]
- fn test_stream_multi_chunk_bidirectional() {
- setup();
-
- // Test multi-chunk encryption using encrypt_file (the chunking API)
- let plaintext = vec![0x42u8; crypto::stream::ENCRYPTION_CHUNK_SIZE + 500];
- let mut source = Cursor::new(plaintext.clone());
- let mut encrypted = Vec::new();
-
- let (key, header) =
- crypto::stream::encrypt_file(&mut source, &mut encrypted, None).unwrap();
-
- // Decrypt and verify roundtrip
- let mut enc_cursor = Cursor::new(encrypted.clone());
- let mut decrypted = Vec::new();
- crypto::stream::decrypt_file(&mut enc_cursor, &mut decrypted, &header, &key).unwrap();
- assert_eq!(decrypted, plaintext);
-
- // Verify size: encrypt_file writes ciphertext only (header returned separately)
- // estimate_encrypted_size returns ciphertext size (excludes header)
- let expected_size = crypto::stream::estimate_encrypted_size(plaintext.len());
- assert_eq!(encrypted.len(), expected_size);
- }
-
- #[test]
- fn test_full_ente_workflow_bidirectional() {
- setup();
-
- // Simulate the full Ente encryption workflow
-
- // 1. User creates account with password
- let password = "user_secure_password";
- let derived = crypto::argon::derive_interactive_key(password).unwrap();
- let kek = &derived.key;
-
- // 2. Generate master key
- let master_key = crypto::keys::generate_key();
-
- // 3. Encrypt master key with KEK
- let encrypted_master_key = crypto::secretbox::encrypt(&master_key, kek).unwrap();
-
- // 4. Generate collection key
- let collection_key = crypto::keys::generate_key();
-
- // 5. Encrypt collection key with master key
- let encrypted_collection_key =
- crypto::secretbox::encrypt(&collection_key, &master_key).unwrap();
-
- // 6. Generate file key
- let file_key = crypto::keys::generate_stream_key();
-
- // 7. Encrypt file key with collection key
- let encrypted_file_key = crypto::secretbox::encrypt(&file_key, &collection_key).unwrap();
-
- // 8. Encrypt file content
- let file_content = b"This is the actual file content that would be a photo or video";
- let encrypted_file = crypto::stream::encrypt(file_content, &file_key).unwrap();
-
- // 9. Encrypt file metadata
- #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
- struct FileMetadata {
- title: String,
- creation_time: i64,
- }
- let metadata = FileMetadata {
- title: "photo.jpg".to_string(),
- creation_time: 1703318400,
- };
- let encrypted_metadata = crypto::blob::encrypt_json(&metadata, &file_key).unwrap();
-
- // === Now verify the reverse (decryption) ===
-
- // 10. Re-derive KEK from password
- let kek_again = crypto::argon::derive_key(
- password,
- &derived.salt,
- derived.mem_limit,
- derived.ops_limit,
- )
- .unwrap();
- assert_eq!(kek_again, *kek);
-
- // 11. Decrypt master key
- let decrypted_master_key =
- crypto::secretbox::decrypt_box(&encrypted_master_key, &kek_again).unwrap();
- assert_eq!(decrypted_master_key, master_key);
-
- // 12. Decrypt collection key
- let decrypted_collection_key =
- crypto::secretbox::decrypt_box(&encrypted_collection_key, &decrypted_master_key)
- .unwrap();
- assert_eq!(decrypted_collection_key, collection_key);
-
- // 13. Decrypt file key
- let decrypted_file_key =
- crypto::secretbox::decrypt_box(&encrypted_file_key, &decrypted_collection_key).unwrap();
- assert_eq!(decrypted_file_key, file_key);
-
- // 14. Decrypt file content
- let decrypted_file = crypto::stream::decrypt(
- &encrypted_file.encrypted_data,
- &encrypted_file.decryption_header,
- &decrypted_file_key,
- )
- .unwrap();
- assert_eq!(decrypted_file, file_content);
-
- // 15. Decrypt metadata
- let decrypted_metadata: FileMetadata =
- crypto::blob::decrypt_json(&encrypted_metadata, &decrypted_file_key).unwrap();
- assert_eq!(decrypted_metadata, metadata);
- }
-}
-
-// =============================================================================
-// CONSTANT VERIFICATION: Verify constants match across platforms
-// =============================================================================
-
-mod constants_verification {
- use super::*;
-
- #[test]
- fn test_secretbox_constants() {
- assert_eq!(crypto::secretbox::KEY_BYTES, 32);
- assert_eq!(crypto::secretbox::NONCE_BYTES, 24);
- assert_eq!(crypto::secretbox::MAC_BYTES, 16);
- }
-
- #[test]
- fn test_blob_constants() {
- assert_eq!(crypto::blob::KEY_BYTES, 32);
- assert_eq!(crypto::blob::HEADER_BYTES, 24);
- assert_eq!(crypto::blob::ABYTES, 17);
- assert_eq!(crypto::blob::TAG_FINAL, 3);
- assert_eq!(crypto::blob::TAG_MESSAGE, 0);
- }
-
- #[test]
- fn test_stream_constants() {
- assert_eq!(crypto::stream::KEY_BYTES, 32);
- assert_eq!(crypto::stream::HEADER_BYTES, 24);
- assert_eq!(crypto::stream::ABYTES, 17);
- assert_eq!(crypto::stream::ENCRYPTION_CHUNK_SIZE, 4 * 1024 * 1024);
- assert_eq!(crypto::stream::DECRYPTION_CHUNK_SIZE, 4 * 1024 * 1024 + 17);
- assert_eq!(crypto::stream::TAG_FINAL, 3);
- assert_eq!(crypto::stream::TAG_MESSAGE, 0);
- }
-
- #[test]
- fn test_argon_constants() {
- assert_eq!(crypto::argon::MEMLIMIT_INTERACTIVE, 67108864); // 64 MB
- assert_eq!(crypto::argon::MEMLIMIT_MODERATE, 268435456); // 256 MB
- assert_eq!(crypto::argon::MEMLIMIT_SENSITIVE, 1073741824); // 1 GB
- assert_eq!(crypto::argon::OPSLIMIT_INTERACTIVE, 2);
- assert_eq!(crypto::argon::OPSLIMIT_MODERATE, 3);
- assert_eq!(crypto::argon::OPSLIMIT_SENSITIVE, 4);
- assert_eq!(crypto::argon::SALT_BYTES, 16);
- }
-
- #[test]
- fn test_kdf_constants() {
- assert_eq!(crypto::kdf::KEY_BYTES, 32);
- assert_eq!(crypto::kdf::CONTEXT_BYTES, 8);
- assert_eq!(crypto::kdf::SUBKEY_BYTES_MIN, 16);
- assert_eq!(crypto::kdf::SUBKEY_BYTES_MAX, 64);
- }
-
- #[test]
- fn test_sealed_constants() {
- assert_eq!(crypto::sealed::PUBLIC_KEY_BYTES, 32);
- assert_eq!(crypto::sealed::SECRET_KEY_BYTES, 32);
- assert_eq!(crypto::sealed::SEAL_BYTES, 48);
- }
-
- #[test]
- fn test_hash_constants() {
- assert_eq!(crypto::hash::HASH_BYTES, 32);
- assert_eq!(crypto::hash::HASH_BYTES_MIN, 16);
- assert_eq!(crypto::hash::HASH_BYTES_MAX, 64);
- }
-}
-
-// =============================================================================
-// PUBLIC FUNCTION COVERAGE: Ensure every public function has at least one test
-// =============================================================================
-
-mod public_api_coverage {
- use super::*;
- use std::io::Cursor;
-
- // --- crypto module functions ---
-
- #[test]
- fn test_init() {
- crypto::init().unwrap();
- crypto::init().unwrap(); // Safe to call multiple times
- }
-
- #[test]
- fn test_decode_b64() {
- setup();
- let decoded = crypto::decode_b64("SGVsbG8=").unwrap();
- assert_eq!(decoded, b"Hello");
- }
-
- #[test]
- fn test_encode_b64() {
- setup();
- let encoded = crypto::encode_b64(b"Hello");
- assert_eq!(encoded, "SGVsbG8=");
- }
-
- #[test]
- fn test_base642bin() {
- setup();
- let decoded = crypto::base642bin("SGVsbG8=").unwrap();
- assert_eq!(decoded, b"Hello");
- }
-
- #[test]
- fn test_bin2base64() {
- setup();
- let standard = crypto::bin2base64(b"\xfb\xef", false);
- assert_eq!(standard, "++8=");
-
- let url_safe = crypto::bin2base64(b"\xfb\xef", true);
- assert_eq!(url_safe, "--8=");
- }
-
- #[test]
- fn test_decode_hex() {
- setup();
- let decoded = crypto::decode_hex("48656c6c6f").unwrap();
- assert_eq!(decoded, b"Hello");
- }
-
- #[test]
- fn test_encode_hex() {
- setup();
- let encoded = crypto::encode_hex(b"Hello");
- assert_eq!(encoded, "48656c6c6f");
- }
-
- #[test]
- fn test_b64_to_hex() {
- setup();
- let hex = crypto::b64_to_hex("SGVsbG8=").unwrap();
- assert_eq!(hex, "48656c6c6f");
- }
-
- #[test]
- fn test_hex_to_b64() {
- setup();
- let b64 = crypto::hex_to_b64("48656c6c6f").unwrap();
- assert_eq!(b64, "SGVsbG8=");
- }
-
- // --- keys module functions ---
-
- #[test]
- fn test_keys_generate_key() {
- setup();
- let key = crypto::keys::generate_key();
- assert_eq!(key.len(), 32);
- }
-
- #[test]
- fn test_keys_generate_stream_key() {
- setup();
- let key = crypto::keys::generate_stream_key();
- assert_eq!(key.len(), 32);
- }
-
- #[test]
- fn test_keys_generate_salt() {
- setup();
- let salt = crypto::keys::generate_salt();
- assert_eq!(salt.len(), 16);
- }
-
- #[test]
- fn test_keys_generate_secretbox_nonce() {
- setup();
- let nonce = crypto::keys::generate_secretbox_nonce();
- assert_eq!(nonce.len(), 24);
- }
-
- #[test]
- fn test_keys_generate_keypair() {
- setup();
- let (pk, sk) = crypto::keys::generate_keypair().unwrap();
- assert_eq!(pk.len(), 32);
- assert_eq!(sk.len(), 32);
- }
-
- #[test]
- fn test_keys_random_bytes() {
- setup();
- let bytes = crypto::keys::random_bytes(64);
- assert_eq!(bytes.len(), 64);
- }
-
- // --- secretbox module functions ---
-
- #[test]
- fn test_secretbox_encrypt() {
- setup();
- let key = crypto::keys::generate_key();
- let encrypted = crypto::secretbox::encrypt(b"test", &key).unwrap();
- assert_eq!(encrypted.nonce.len(), 24);
- }
-
- #[test]
- fn test_secretbox_encrypt_with_nonce() {
- setup();
- let key = crypto::keys::generate_key();
- let nonce = crypto::keys::generate_secretbox_nonce();
- let ciphertext = crypto::secretbox::encrypt_with_nonce(b"test", &nonce, &key).unwrap();
- assert_eq!(ciphertext.len(), 4 + 16); // data + MAC
- }
-
- #[test]
- fn test_secretbox_decrypt() {
- setup();
- let key = crypto::keys::generate_key();
- let nonce = crypto::keys::generate_secretbox_nonce();
- let ciphertext = crypto::secretbox::encrypt_with_nonce(b"test", &nonce, &key).unwrap();
- let plaintext = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
- assert_eq!(plaintext, b"test");
- }
-
- #[test]
- fn test_secretbox_decrypt_box() {
- setup();
- let key = crypto::keys::generate_key();
- let encrypted = crypto::secretbox::encrypt(b"test", &key).unwrap();
- let plaintext = crypto::secretbox::decrypt_box(&encrypted, &key).unwrap();
- assert_eq!(plaintext, b"test");
- }
-
- // --- blob module functions ---
-
- #[test]
- fn test_blob_encrypt() {
- setup();
- let key = crypto::keys::generate_stream_key();
- let encrypted = crypto::blob::encrypt(b"test", &key).unwrap();
- assert_eq!(encrypted.decryption_header.len(), 24);
- }
-
- #[test]
- fn test_blob_decrypt() {
- setup();
- let key = crypto::keys::generate_stream_key();
- let encrypted = crypto::blob::encrypt(b"test", &key).unwrap();
- let plaintext = crypto::blob::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
- assert_eq!(plaintext, b"test");
- }
-
- #[test]
- fn test_blob_encrypt_json() {
- setup();
- let key = crypto::keys::generate_stream_key();
- let data = serde_json::json!({"key": "value"});
- let encrypted = crypto::blob::encrypt_json(&data, &key).unwrap();
- assert!(!encrypted.encrypted_data.is_empty());
- }
-
- #[test]
- fn test_blob_decrypt_json() {
- setup();
- let key = crypto::keys::generate_stream_key();
- let data = serde_json::json!({"key": "value"});
- let encrypted = crypto::blob::encrypt_json(&data, &key).unwrap();
- let decrypted: serde_json::Value = crypto::blob::decrypt_json(&encrypted, &key).unwrap();
- assert_eq!(decrypted, data);
- }
-
- // --- stream module functions ---
-
- #[test]
- fn test_stream_encrypt() {
- setup();
- let key = crypto::keys::generate_stream_key();
- let encrypted = crypto::stream::encrypt(b"test data", &key).unwrap();
- assert!(!encrypted.encrypted_data.is_empty());
- }
-
- #[test]
- fn test_stream_decrypt() {
- setup();
- let key = crypto::keys::generate_stream_key();
- let encrypted = crypto::stream::encrypt(b"test data", &key).unwrap();
- let plaintext = crypto::stream::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
- assert_eq!(plaintext, b"test data");
- }
-
- #[test]
- fn test_stream_encrypt_file() {
- setup();
- let mut source = Cursor::new(b"file content".to_vec());
- let mut dest = Vec::new();
- let (key, header) = crypto::stream::encrypt_file(&mut source, &mut dest, None).unwrap();
- assert_eq!(key.len(), 32);
- assert_eq!(header.len(), 24);
- }
-
- #[test]
- fn test_stream_decrypt_file() {
- setup();
- let mut source = Cursor::new(b"file content".to_vec());
- let mut encrypted = Vec::new();
- let (key, header) =
- crypto::stream::encrypt_file(&mut source, &mut encrypted, None).unwrap();
-
- let mut enc_source = Cursor::new(encrypted);
- let mut decrypted = Vec::new();
- crypto::stream::decrypt_file(&mut enc_source, &mut decrypted, &header, &key).unwrap();
- assert_eq!(decrypted, b"file content");
- }
-
- #[test]
- fn test_stream_estimate_encrypted_size() {
- let abytes = crypto::stream::ABYTES;
- let chunk_size = crypto::stream::ENCRYPTION_CHUNK_SIZE;
- let dec_chunk_size = crypto::stream::DECRYPTION_CHUNK_SIZE;
-
- // Empty: still produces a FINAL chunk with ABYTES overhead
- assert_eq!(crypto::stream::estimate_encrypted_size(0), abytes);
-
- // Small data: single FINAL chunk
- assert_eq!(crypto::stream::estimate_encrypted_size(100), 100 + abytes);
-
- // Exact chunk size: one FINAL chunk
- assert_eq!(
- crypto::stream::estimate_encrypted_size(chunk_size),
- dec_chunk_size
- );
-
- // Chunk size + extra: one MESSAGE chunk + non-empty FINAL chunk
- assert_eq!(
- crypto::stream::estimate_encrypted_size(chunk_size + 500),
- dec_chunk_size + 500 + abytes
- );
-
- // Two full chunks + partial: two MESSAGE chunks + non-empty FINAL chunk
- assert_eq!(
- crypto::stream::estimate_encrypted_size(2 * chunk_size + 100),
- 2 * dec_chunk_size + 100 + abytes
- );
- }
-
- #[test]
- fn test_stream_validate_sizes() {
- let abytes = crypto::stream::ABYTES;
- let chunk_size = crypto::stream::ENCRYPTION_CHUNK_SIZE;
- let dec_chunk_size = crypto::stream::DECRYPTION_CHUNK_SIZE;
-
- // Valid cases
- assert!(crypto::stream::validate_sizes(0, abytes)); // empty plaintext
- assert!(crypto::stream::validate_sizes(100, 117)); // small data
- assert!(crypto::stream::validate_sizes(chunk_size, dec_chunk_size)); // exact chunk
-
- // Invalid cases
- assert!(!crypto::stream::validate_sizes(100, 100)); // missing ABYTES
- assert!(!crypto::stream::validate_sizes(0, 0)); // ciphertext can't be 0
- assert!(!crypto::stream::validate_sizes(
- chunk_size,
- dec_chunk_size + abytes
- )); // extra empty chunk
- }
-
- #[test]
- fn test_stream_encryptor_new_and_push() {
- setup();
- let key = crypto::keys::generate_stream_key();
- let mut encryptor = crypto::stream::StreamEncryptor::new(&key).unwrap();
- let chunk = encryptor.push(b"test", true).unwrap();
- assert!(!chunk.is_empty());
- }
-
- #[test]
- fn test_stream_decryptor_new_and_pull() {
- setup();
- let key = crypto::keys::generate_stream_key();
- let mut encryptor = crypto::stream::StreamEncryptor::new(&key).unwrap();
- let header = encryptor.header.clone();
- let chunk = encryptor.push(b"test", true).unwrap();
-
- let mut decryptor = crypto::stream::StreamDecryptor::new(&header, &key).unwrap();
- let (plaintext, tag) = decryptor.pull(&chunk).unwrap();
- assert_eq!(plaintext, b"test");
- assert_eq!(tag, crypto::stream::TAG_FINAL);
- }
-
- // --- argon module functions ---
-
- #[test]
- fn test_argon_derive_key() {
- setup();
- let salt = crypto::keys::generate_salt();
- let key = crypto::argon::derive_key(
- "password",
- &salt,
- crypto::argon::MEMLIMIT_INTERACTIVE,
- crypto::argon::OPSLIMIT_INTERACTIVE,
- )
- .unwrap();
- assert_eq!(key.len(), 32);
- }
-
- #[test]
- fn test_argon_derive_key_from_b64_salt() {
- setup();
- let salt = crypto::keys::generate_salt();
- let salt_b64 = crypto::encode_b64(&salt);
- let key = crypto::argon::derive_key_from_b64_salt(
- "password",
- &salt_b64,
- crypto::argon::MEMLIMIT_INTERACTIVE,
- crypto::argon::OPSLIMIT_INTERACTIVE,
- )
- .unwrap();
- assert_eq!(key.len(), 32);
- }
-
- #[test]
- fn test_argon_derive_interactive_key() {
- setup();
- let derived = crypto::argon::derive_interactive_key("password").unwrap();
- assert_eq!(derived.key.len(), 32);
- assert_eq!(derived.salt.len(), 16);
- }
-
- // Note: derive_sensitive_key is slow, tested in unit tests
-
- // --- kdf module functions ---
-
- #[test]
- fn test_kdf_derive_subkey() {
- setup();
- let key = crypto::keys::generate_key();
- let subkey = crypto::kdf::derive_subkey(&key, 32, 1, b"testctx1").unwrap();
- assert_eq!(subkey.len(), 32);
- }
-
- #[test]
- fn test_kdf_derive_login_key() {
- setup();
- let key = crypto::keys::generate_key();
- let login_key = crypto::kdf::derive_login_key(&key).unwrap();
- assert_eq!(login_key.len(), 16);
- }
-
- // --- sealed module functions ---
-
- #[test]
- fn test_sealed_seal() {
- setup();
- let (pk, _) = crypto::keys::generate_keypair().unwrap();
- let ciphertext = crypto::sealed::seal(b"test", &pk).unwrap();
- assert_eq!(ciphertext.len(), 4 + 48); // data + overhead
- }
-
- #[test]
- fn test_sealed_open() {
- setup();
- let (pk, sk) = crypto::keys::generate_keypair().unwrap();
- let ciphertext = crypto::sealed::seal(b"test", &pk).unwrap();
- let plaintext = crypto::sealed::open(&ciphertext, &pk, &sk).unwrap();
- assert_eq!(plaintext, b"test");
- }
-
- // --- hash module functions ---
-
- #[test]
- fn test_hash_hash() {
- setup();
- let hash = crypto::hash::hash(b"test", Some(32), None).unwrap();
- assert_eq!(hash.len(), 32);
- }
-
- #[test]
- fn test_hash_hash_default() {
- setup();
- let hash = crypto::hash::hash_default(b"test").unwrap();
- assert_eq!(hash.len(), 64);
- }
-
- #[test]
- fn test_hash_hash_reader() {
- setup();
- let mut reader = Cursor::new(b"test data".to_vec());
- let hash = crypto::hash::hash_reader(&mut reader, None).unwrap();
- assert_eq!(hash.len(), 64);
- }
-
- #[test]
- fn test_hash_state_new_update_finalize() {
- setup();
- let mut state = crypto::hash::HashState::new(Some(32), None).unwrap();
- state.update(b"test").unwrap();
- let hash = state.finalize().unwrap();
- assert_eq!(hash.len(), 32);
- }
-}
-
-// =============================================================================
-// ERROR HANDLING: Tests matching ente_crypto_dart error cases
-// =============================================================================
-
-mod error_handling {
- use super::*;
- use std::fs::File;
-
- #[test]
- fn test_invalid_key_length_secretbox() {
- setup();
- let invalid_key = vec![0u8; 10]; // Wrong length (should be 32)
- let source = b"data";
-
- let result = crypto::secretbox::encrypt(source, &invalid_key);
- assert!(result.is_err(), "Should error on invalid key length");
- }
-
- #[test]
- fn test_invalid_key_length_blob() {
- setup();
- let invalid_key = vec![0u8; 10];
- let source = b"data";
-
- let result = crypto::blob::encrypt(source, &invalid_key);
- assert!(
- result.is_err(),
- "Should error on invalid key length for blob"
- );
- }
-
- #[test]
- fn test_invalid_key_length_stream() {
- setup();
- let invalid_key = vec![0u8; 10];
- let source = b"data";
-
- let result = crypto::stream::encrypt(source, &invalid_key);
- assert!(
- result.is_err(),
- "Should error on invalid key length for stream"
- );
- }
-
- #[test]
- fn test_invalid_secret_key_sealed_box() {
- setup();
- let (pk, _sk) = crypto::keys::generate_keypair().unwrap();
- let message = b"Hello, world!";
- let ciphertext = crypto::sealed::seal(message, &pk).unwrap();
-
- // Invalid secret key (all zeros)
- let invalid_sk = vec![0u8; 32];
- let result = crypto::sealed::open(&ciphertext, &pk, &invalid_sk);
- assert!(result.is_err(), "Should error with invalid secret key");
- }
-
- #[test]
- fn test_empty_salt_key_derivation() {
- setup();
- let password = "password123";
- let empty_salt: &[u8] = &[];
-
- let result = crypto::argon::derive_key(
- password,
- empty_salt,
- crypto::argon::MEMLIMIT_INTERACTIVE,
- crypto::argon::OPSLIMIT_INTERACTIVE,
- );
- assert!(result.is_err(), "Should error with empty salt");
- }
-
- #[test]
- fn test_short_salt_key_derivation() {
- setup();
- let password = "password123";
- let short_salt = vec![0u8; 8]; // Should be 16 bytes
-
- let result = crypto::argon::derive_key(
- password,
- &short_salt,
- crypto::argon::MEMLIMIT_INTERACTIVE,
- crypto::argon::OPSLIMIT_INTERACTIVE,
- );
- assert!(result.is_err(), "Should error with short salt");
- }
-
- #[test]
- fn test_invalid_key_login_derivation() {
- setup();
- let invalid_key: &[u8] = &[]; // Empty key
-
- let result = crypto::kdf::derive_login_key(invalid_key);
- assert!(
- result.is_err(),
- "Should error with empty key for login derivation"
- );
- }
-
- #[test]
- fn test_short_key_login_derivation() {
- setup();
- let short_key = vec![0u8; 16]; // Should be 32 bytes
-
- let result = crypto::kdf::derive_login_key(&short_key);
- assert!(
- result.is_err(),
- "Should error with short key for login derivation"
- );
- }
-
- #[test]
- fn test_hash_nonexistent_file() {
- setup();
- let result = File::open("/nonexistent/path/to/file.txt");
- assert!(result.is_err(), "Should error when file doesn't exist");
- }
-
- #[test]
- fn test_wrong_key_decryption_fails() {
- setup();
- let correct_key = crypto::keys::generate_key();
- let wrong_key = crypto::keys::generate_key();
- let plaintext = b"secret data";
-
- let encrypted = crypto::secretbox::encrypt(plaintext, &correct_key).unwrap();
- let result = crypto::secretbox::decrypt_box(&encrypted, &wrong_key);
- assert!(
- result.is_err(),
- "Should error when decrypting with wrong key"
- );
- }
-
- #[test]
- fn test_wrong_key_blob_decryption_fails() {
- setup();
- let correct_key = crypto::keys::generate_stream_key();
- let wrong_key = crypto::keys::generate_stream_key();
- let plaintext = b"secret data";
-
- let encrypted = crypto::blob::encrypt(plaintext, &correct_key).unwrap();
- let result = crypto::blob::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &wrong_key,
- );
- assert!(
- result.is_err(),
- "Should error when decrypting blob with wrong key"
- );
- }
-
- #[test]
- fn test_wrong_key_stream_decryption_fails() {
- setup();
- let correct_key = crypto::keys::generate_stream_key();
- let wrong_key = crypto::keys::generate_stream_key();
- let plaintext = b"secret data";
-
- let encrypted = crypto::stream::encrypt(plaintext, &correct_key).unwrap();
- let result = crypto::stream::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &wrong_key,
- );
- assert!(
- result.is_err(),
- "Should error when decrypting stream with wrong key"
- );
- }
-
- #[test]
- fn test_corrupted_ciphertext_fails() {
- setup();
- let key = crypto::keys::generate_key();
- let plaintext = b"secret data";
-
- let mut encrypted = crypto::secretbox::encrypt(plaintext, &key).unwrap();
- // Corrupt the ciphertext
- if !encrypted.encrypted_data.is_empty() {
- encrypted.encrypted_data[0] ^= 0xFF;
- }
- let result = crypto::secretbox::decrypt_box(&encrypted, &key);
- assert!(result.is_err(), "Should error with corrupted ciphertext");
- }
-
- #[test]
- fn test_truncated_ciphertext_fails() {
- setup();
- let key = crypto::keys::generate_key();
- let nonce = crypto::keys::generate_secretbox_nonce();
- let plaintext = b"secret data that is longer";
-
- let ciphertext = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();
- // Truncate the ciphertext
- let truncated = &ciphertext[..ciphertext.len() / 2];
-
- let result = crypto::secretbox::decrypt(truncated, &nonce, &key);
- assert!(result.is_err(), "Should error with truncated ciphertext");
- }
-}
-
-// =============================================================================
-// DART COMPATIBILITY: Tests matching ente_crypto_dart behavior
-// =============================================================================
-
-mod dart_compatibility {
- use super::*;
- use std::io::Cursor;
-
- #[test]
- fn test_derive_sensitive_key_parameters() {
- setup();
- // Matches: test('Succeeds with default memLimit and opsLimit on high-spec device')
- let password = "password";
- let salt = b"thisisof16length"; // 16 bytes
-
- let result = crypto::argon::derive_key(
- password,
- salt,
- crypto::argon::MEMLIMIT_SENSITIVE,
- crypto::argon::OPSLIMIT_SENSITIVE,
- );
-
- // This might fail on low-memory systems, which is expected
- if let Ok(key) = result {
- assert_eq!(key.len(), 32);
- }
- }
-
- #[test]
- fn test_derive_interactive_key_parameters() {
- setup();
- // Matches: test('Derives a key with the correct parameters')
- let password = "password";
- let salt = b"thisisof16length";
-
- let key = crypto::argon::derive_key(
- password,
- salt,
- crypto::argon::MEMLIMIT_INTERACTIVE,
- crypto::argon::OPSLIMIT_INTERACTIVE,
- )
- .unwrap();
-
- assert_eq!(key.len(), 32);
-
- // Verify deterministic
- let key2 = crypto::argon::derive_key(
- password,
- salt,
- crypto::argon::MEMLIMIT_INTERACTIVE,
- crypto::argon::OPSLIMIT_INTERACTIVE,
- )
- .unwrap();
-
- assert_eq!(key, key2);
- }
-
- #[test]
- fn test_derive_login_key_length() {
- setup();
- // Matches: test('Derives a login key with the correct parameters')
- let key = crypto::keys::generate_key();
- let login_key = crypto::kdf::derive_login_key(&key).unwrap();
-
- assert_eq!(login_key.len(), 16, "Login key should be 16 bytes");
- }
-
- #[test]
- fn test_keypair_sizes() {
- setup();
- // Matches: test('Check generated keypair')
- let (pk, sk) = crypto::keys::generate_keypair().unwrap();
-
- assert_eq!(pk.len(), 32, "Public key should be 32 bytes");
- assert_eq!(sk.len(), 32, "Secret key should be 32 bytes");
- }
-
- #[test]
- fn test_salt_size() {
- setup();
- // Matches: test('Test salt to derive key')
- let salt = crypto::keys::generate_salt();
- assert_eq!(salt.len(), 16, "Salt should be 16 bytes");
- }
-
- #[test]
- fn test_hash_size() {
- setup();
- // Matches: test('Calculates the hash of a file correctly')
- let data = b"test content";
- let mut reader = Cursor::new(data.to_vec());
-
- let hash = crypto::hash::hash_reader(&mut reader, None).unwrap();
-
- assert_eq!(
- hash.len(),
- 64,
- "Default hash should be 64 bytes (BLAKE2b-512)"
- );
- }
-
- #[test]
- fn test_secretbox_cross_encrypt_decrypt() {
- setup();
- // Matches: test('Encrypt sodium_libs, decrypt flutter_sodium')
- let source = b"Hello, world!";
- let key = crypto::keys::generate_key();
-
- let encrypted = crypto::secretbox::encrypt(source, &key).unwrap();
- let decrypted = crypto::secretbox::decrypt_box(&encrypted, &key).unwrap();
-
- assert_eq!(decrypted, source);
- }
-
- #[test]
- fn test_blob_cross_encrypt_decrypt() {
- setup();
- // Matches: test('Encrypt data sodium_libs, decrypt on flutter_sodium')
- let source = b"hello world";
- let key = crypto::keys::generate_stream_key();
-
- let encrypted = crypto::blob::encrypt(source, &key).unwrap();
- let decrypted = crypto::blob::decrypt(
- &encrypted.encrypted_data,
- &encrypted.decryption_header,
- &key,
- )
- .unwrap();
-
- assert_eq!(decrypted, source);
- }
-
- #[test]
- fn test_sealed_box_cross_encrypt_decrypt() {
- setup();
- // Matches: test('openSealSync decrypts ciphertext from sodium_libs correctly')
- let (pk, sk) = crypto::keys::generate_keypair().unwrap();
- let message = b"Hello, world!";
-
- let ciphertext = crypto::sealed::seal(message, &pk).unwrap();
- let decrypted = crypto::sealed::open(&ciphertext, &pk, &sk).unwrap();
-
- assert_eq!(decrypted, message);
- }
-
- #[test]
- fn test_file_encrypt_decrypt() {
- setup();
- // Matches: test('Encrypts a file successfully sodium_libs')
- let source_data = vec![0x42u8; 5 * 1024 * 1024]; // 5MB of data
- let mut source = Cursor::new(source_data.clone());
- let mut encrypted = Vec::new();
-
- let (key, header) =
- crypto::stream::encrypt_file(&mut source, &mut encrypted, None).unwrap();
-
- // Decrypt
- let mut enc_cursor = Cursor::new(encrypted);
- let mut decrypted = Vec::new();
- crypto::stream::decrypt_file(&mut enc_cursor, &mut decrypted, &header, &key).unwrap();
-
- assert_eq!(decrypted, source_data);
- }
-
- #[test]
- fn test_base64_roundtrip() {
- setup();
- // Matches: test('Decode base64 string to Uint8List') and test('Encode Uint8List to base64 string')
- let original = b"hello world";
- let encoded = crypto::encode_b64(original);
- let decoded = crypto::decode_b64(&encoded).unwrap();
-
- assert_eq!(decoded, original);
- assert_eq!(encoded, "aGVsbG8gd29ybGQ=");
- }
-
- #[test]
- fn test_hex_roundtrip() {
- setup();
- // Matches: test('Convert Uint8List to hex string')
- let original = b"hello world";
- let hex = crypto::encode_hex(original);
- let back = crypto::decode_hex(&hex).unwrap();
-
- assert_eq!(back, original);
- }
-
- #[test]
- fn test_chunk_size_constants() {
- setup();
- // Verify chunk sizes match Dart's encryptionChunkSize and decryptionChunkSize
- assert_eq!(crypto::stream::ENCRYPTION_CHUNK_SIZE, 4 * 1024 * 1024);
- assert_eq!(
- crypto::stream::DECRYPTION_CHUNK_SIZE,
- 4 * 1024 * 1024 + crypto::stream::ABYTES
- );
- }
-
- #[test]
- fn test_login_key_context_and_id() {
- setup();
- // Verify login key derivation uses correct context
- // Dart: loginSubKeyContext = "loginctx", loginSubKeyId = 1, loginSubKeyLen = 32 (then truncated to 16)
- let master_key = crypto::keys::generate_key();
-
- // Derive using our function
- let login_key = crypto::kdf::derive_login_key(&master_key).unwrap();
- assert_eq!(login_key.len(), 16);
-
- // Verify deterministic
- let login_key2 = crypto::kdf::derive_login_key(&master_key).unwrap();
- assert_eq!(login_key, login_key2);
- }
-}
diff --git a/rust/core/tests/js_interop_test.mjs b/rust/core/tests/js_interop_test.mjs
deleted file mode 100644
index 1cdac4c395..0000000000
--- a/rust/core/tests/js_interop_test.mjs
+++ /dev/null
@@ -1,320 +0,0 @@
-/**
- * JavaScript crypto tests for ente-core compatibility.
- *
- * Since JS libsodium-wrappers IS libsodium, and we've validated Rust matches
- * libsodium, these tests verify:
- * 1. JS crypto works correctly (roundtrips)
- * 2. Constants match Rust expectations
- * 3. Format/sizes match what Rust expects
- * 4. Ente workflow works end-to-end
- *
- * Run with: node tests/js_interop_test.mjs
- */
-
-import _sodium from 'libsodium-wrappers-sumo';
-
-async function runTests() {
- await _sodium.ready;
- const sodium = _sodium;
-
- console.log('╔════════════════════════════════════════════════════════════════╗');
- console.log('β•‘ JavaScript Crypto Validation Tests β•‘');
- console.log('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•\n');
-
- let passed = 0;
- let failed = 0;
-
- function test(name, fn) {
- try {
- fn();
- console.log(` βœ“ ${name}`);
- passed++;
- } catch (e) {
- console.log(` βœ— ${name}`);
- console.log(` Error: ${e.message}`);
- failed++;
- }
- }
-
- function assertEqual(actual, expected, msg = '') {
- const actualStr = typeof actual === 'string' ? actual :
- actual instanceof Uint8Array ? sodium.to_hex(actual) :
- JSON.stringify(actual);
- const expectedStr = typeof expected === 'string' ? expected :
- expected instanceof Uint8Array ? sodium.to_hex(expected) :
- JSON.stringify(expected);
- if (actualStr !== expectedStr) {
- throw new Error(`${msg}\n Expected: ${expectedStr}\n Actual: ${actualStr}`);
- }
- }
-
- // =========================================================================
- // CONSTANTS: Verify values match Rust
- // =========================================================================
-
- console.log('── Constants Verification ──\n');
-
- test('SecretBox constants', () => {
- assertEqual(sodium.crypto_secretbox_KEYBYTES, 32);
- assertEqual(sodium.crypto_secretbox_NONCEBYTES, 24);
- assertEqual(sodium.crypto_secretbox_MACBYTES, 16);
- });
-
- test('SecretStream constants', () => {
- assertEqual(sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES, 32);
- assertEqual(sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES, 24);
- assertEqual(sodium.crypto_secretstream_xchacha20poly1305_ABYTES, 17);
- assertEqual(sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL, 3);
- assertEqual(sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE, 0);
- });
-
- test('Argon2 constants', () => {
- assertEqual(sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE, 67108864); // 64 MB
- assertEqual(sodium.crypto_pwhash_MEMLIMIT_MODERATE, 268435456); // 256 MB
- assertEqual(sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE, 2);
- assertEqual(sodium.crypto_pwhash_OPSLIMIT_MODERATE, 3);
- assertEqual(sodium.crypto_pwhash_SALTBYTES, 16);
- });
-
- test('KDF constants', () => {
- assertEqual(sodium.crypto_kdf_KEYBYTES, 32);
- assertEqual(sodium.crypto_kdf_CONTEXTBYTES, 8);
- assertEqual(sodium.crypto_kdf_BYTES_MIN, 16);
- assertEqual(sodium.crypto_kdf_BYTES_MAX, 64);
- });
-
- test('Sealed box constants', () => {
- assertEqual(sodium.crypto_box_PUBLICKEYBYTES, 32);
- assertEqual(sodium.crypto_box_SECRETKEYBYTES, 32);
- assertEqual(sodium.crypto_box_SEALBYTES, 48);
- });
-
- test('Hash constants', () => {
- assertEqual(sodium.crypto_generichash_BYTES, 32);
- assertEqual(sodium.crypto_generichash_BYTES_MIN, 16);
- assertEqual(sodium.crypto_generichash_BYTES_MAX, 64);
- });
-
- // =========================================================================
- // ROUNDTRIP: Verify each primitive works
- // =========================================================================
-
- console.log('\n── Roundtrip Tests ──\n');
-
- test('SecretBox roundtrip', () => {
- const key = sodium.crypto_secretbox_keygen();
- const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
- const plaintext = sodium.from_string('Test message for SecretBox');
-
- const ciphertext = sodium.crypto_secretbox_easy(plaintext, nonce, key);
- assertEqual(ciphertext.length, plaintext.length + 16, 'Ciphertext size');
-
- const decrypted = sodium.crypto_secretbox_open_easy(ciphertext, nonce, key);
- assertEqual(sodium.to_string(decrypted), 'Test message for SecretBox');
- });
-
- test('SecretStream roundtrip', () => {
- const key = sodium.crypto_secretstream_xchacha20poly1305_keygen();
- const plaintext = sodium.from_string('Test message for SecretStream');
-
- const { state: encState, header } = sodium.crypto_secretstream_xchacha20poly1305_init_push(key);
- assertEqual(header.length, 24, 'Header size');
-
- const ciphertext = sodium.crypto_secretstream_xchacha20poly1305_push(
- encState, plaintext, null, sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
- );
- assertEqual(ciphertext.length, plaintext.length + 17, 'Ciphertext size');
-
- const decState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(header, key);
- const { message, tag } = sodium.crypto_secretstream_xchacha20poly1305_pull(decState, ciphertext);
- assertEqual(sodium.to_string(message), 'Test message for SecretStream');
- assertEqual(tag, sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL);
- });
-
- test('SecretStream multi-chunk roundtrip', () => {
- const key = sodium.crypto_secretstream_xchacha20poly1305_keygen();
- const chunks = ['First chunk', 'Second chunk', 'Third chunk'];
-
- const { state: encState, header } = sodium.crypto_secretstream_xchacha20poly1305_init_push(key);
- const encrypted = chunks.map((chunk, i) => {
- const tag = i === chunks.length - 1
- ? sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
- : sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
- return sodium.crypto_secretstream_xchacha20poly1305_push(
- encState, sodium.from_string(chunk), null, tag
- );
- });
-
- const decState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(header, key);
- encrypted.forEach((ct, i) => {
- const { message, tag } = sodium.crypto_secretstream_xchacha20poly1305_pull(decState, ct);
- assertEqual(sodium.to_string(message), chunks[i]);
- const expectedTag = i === chunks.length - 1
- ? sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
- : sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
- assertEqual(tag, expectedTag);
- });
- });
-
- test('Sealed box roundtrip', () => {
- const { publicKey, privateKey } = sodium.crypto_box_keypair();
- const plaintext = sodium.from_string('Sealed box message');
-
- assertEqual(publicKey.length, 32, 'Public key size');
- assertEqual(privateKey.length, 32, 'Private key size');
-
- const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
- assertEqual(ciphertext.length, plaintext.length + 48, 'Ciphertext size');
-
- const decrypted = sodium.crypto_box_seal_open(ciphertext, publicKey, privateKey);
- assertEqual(sodium.to_string(decrypted), 'Sealed box message');
- });
-
- test('Argon2 deterministic derivation', () => {
- const password = sodium.from_string('test_password');
- const salt = sodium.randombytes_buf(sodium.crypto_pwhash_SALTBYTES);
-
- const key1 = sodium.crypto_pwhash(
- 32, password, salt,
- sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
- sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE,
- sodium.crypto_pwhash_ALG_ARGON2ID13
- );
-
- const key2 = sodium.crypto_pwhash(
- 32, password, salt,
- sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
- sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE,
- sodium.crypto_pwhash_ALG_ARGON2ID13
- );
-
- assertEqual(key1, key2, 'Same inputs produce same key');
- assertEqual(key1.length, 32, 'Key size');
- });
-
- test('KDF deterministic subkey derivation', () => {
- const masterKey = sodium.crypto_kdf_keygen();
-
- const subKey1 = sodium.crypto_kdf_derive_from_key(32, 1, 'loginctx', masterKey);
- const subKey2 = sodium.crypto_kdf_derive_from_key(32, 1, 'loginctx', masterKey);
- const subKey3 = sodium.crypto_kdf_derive_from_key(32, 2, 'loginctx', masterKey);
-
- assertEqual(subKey1, subKey2, 'Same inputs produce same subkey');
- assertEqual(subKey1.length, 32, 'Subkey size');
-
- // Different ID should produce different key
- if (sodium.to_hex(subKey1) === sodium.to_hex(subKey3)) {
- throw new Error('Different IDs should produce different subkeys');
- }
- });
-
- test('BLAKE2b hash', () => {
- const data = sodium.from_string('Data to hash');
-
- const hash32 = sodium.crypto_generichash(32, data);
- const hash64 = sodium.crypto_generichash(64, data);
-
- assertEqual(hash32.length, 32, 'Hash32 size');
- assertEqual(hash64.length, 64, 'Hash64 size');
-
- // Same input produces same hash
- const hash32_2 = sodium.crypto_generichash(32, data);
- assertEqual(hash32, hash32_2, 'Deterministic hash');
- });
-
- // =========================================================================
- // ENTE WORKFLOW: Full encryption flow
- // =========================================================================
-
- console.log('\n── Ente Workflow Simulation ──\n');
-
- test('Full key hierarchy encryption', () => {
- // 1. Derive KEK from password
- const password = sodium.from_string('user_password');
- const salt = sodium.randombytes_buf(sodium.crypto_pwhash_SALTBYTES);
- const kek = sodium.crypto_pwhash(
- 32, password, salt,
- sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
- sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE,
- sodium.crypto_pwhash_ALG_ARGON2ID13
- );
-
- // 2. Generate and encrypt master key
- const masterKey = sodium.crypto_secretbox_keygen();
- const masterKeyNonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
- const encryptedMasterKey = sodium.crypto_secretbox_easy(masterKey, masterKeyNonce, kek);
-
- // 3. Decrypt and verify
- const decryptedMasterKey = sodium.crypto_secretbox_open_easy(encryptedMasterKey, masterKeyNonce, kek);
- assertEqual(decryptedMasterKey, masterKey);
- });
-
- test('Login key derivation', () => {
- const masterKey = sodium.crypto_kdf_keygen();
-
- // Derive login key using same method as Rust
- const subKey = sodium.crypto_kdf_derive_from_key(32, 1, 'loginctx', masterKey);
- const loginKey = subKey.slice(0, 16);
-
- assertEqual(loginKey.length, 16, 'Login key is 16 bytes');
- });
-
- test('File encryption workflow', () => {
- // Generate file key
- const fileKey = sodium.crypto_secretstream_xchacha20poly1305_keygen();
-
- // Encrypt file content
- const fileContent = sodium.from_string('Photo EXIF data and pixels...');
- const { state: encState, header } = sodium.crypto_secretstream_xchacha20poly1305_init_push(fileKey);
- const encryptedFile = sodium.crypto_secretstream_xchacha20poly1305_push(
- encState, fileContent, null, sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
- );
-
- // Encrypt metadata
- const metadata = JSON.stringify({ title: 'photo.jpg', size: 1234 });
- const { state: metaState, header: metaHeader } = sodium.crypto_secretstream_xchacha20poly1305_init_push(fileKey);
- const encryptedMeta = sodium.crypto_secretstream_xchacha20poly1305_push(
- metaState, sodium.from_string(metadata), null, sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
- );
-
- // Decrypt and verify
- const decState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(header, fileKey);
- const { message: decFile } = sodium.crypto_secretstream_xchacha20poly1305_pull(decState, encryptedFile);
- assertEqual(sodium.to_string(decFile), 'Photo EXIF data and pixels...');
-
- const metaDecState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(metaHeader, fileKey);
- const { message: decMeta } = sodium.crypto_secretstream_xchacha20poly1305_pull(metaDecState, encryptedMeta);
- const parsedMeta = JSON.parse(sodium.to_string(decMeta));
- assertEqual(parsedMeta.title, 'photo.jpg');
- });
-
- test('Recovery key encryption', () => {
- const masterKey = sodium.crypto_secretbox_keygen();
- const recoveryKey = sodium.crypto_secretbox_keygen();
-
- // Encrypt master key with recovery key
- const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
- const encryptedMasterKey = sodium.crypto_secretbox_easy(masterKey, nonce, recoveryKey);
-
- // Decrypt with recovery key
- const decryptedMasterKey = sodium.crypto_secretbox_open_easy(encryptedMasterKey, nonce, recoveryKey);
- assertEqual(decryptedMasterKey, masterKey);
- });
-
- // =========================================================================
- // SUMMARY
- // =========================================================================
-
- console.log('\n╔════════════════════════════════════════════════════════════════╗');
- console.log(`β•‘ Results: ${passed} passed, ${failed} failed${' '.repeat(Math.max(0, 35 - String(passed).length - String(failed).length))}β•‘`);
- console.log('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•');
-
- if (failed > 0) {
- process.exit(1);
- }
-}
-
-runTests().catch(e => {
- console.error('Test runner failed:', e);
- process.exit(1);
-});
diff --git a/rust/core/tests/libsodium_vectors.rs b/rust/core/tests/libsodium_vectors.rs
deleted file mode 100644
index cc1d8b6c0d..0000000000
--- a/rust/core/tests/libsodium_vectors.rs
+++ /dev/null
@@ -1,368 +0,0 @@
-//! Libsodium compatibility test vectors.
-//!
-//! These vectors were generated using libsodium-sys and verify that
-//! ente-core's pure Rust implementation produces byte-identical output.
-//!
-//! If these tests pass, the implementation is libsodium-compatible.
-//! No need to run the validation suite for routine checks.
-
-use ente_core::crypto;
-
-// =============================================================================
-// LIBSODIUM TEST VECTORS - Generated from libsodium-sys
-// =============================================================================
-
-// --- SecretBox (XSalsa20-Poly1305) ---
-const SECRETBOX_KEY: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
-const SECRETBOX_NONCE: &str = "000102030405060708090a0b0c0d0e0f1011121314151617";
-const SECRETBOX_PLAINTEXT: &[u8] = b"Hello, World!";
-const SECRETBOX_CIPHERTEXT: &str = "7e15aaa64ac1e7b68335aa1854c3dfd9169a5423a8e68247d44ee35a49";
-
-// --- KDF (BLAKE2b) ---
-const KDF_MASTER_KEY: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
-const KDF_SUBKEY_32: &str = "6970b5d34442fd11788a83b4b57e1e7224d625c38e2b0374cb2217aa6f8d91e1";
-const KDF_LOGIN_KEY: &str = "6970b5d34442fd11788a83b4b57e1e72";
-
-// --- Argon2id ---
-const ARGON2_PASSWORD: &str = "test_password";
-const ARGON2_SALT: &str = "0123456789abcdef0123456789abcdef";
-const ARGON2_KEY: &str = "ae14cd677df2d021b6aa7545a2670925b718b4f1ff8faec933a88578da4c64b1";
-
-// --- BLAKE2b Hash ---
-const HASH_INPUT: &[u8] = b"Data to hash";
-const HASH_OUTPUT_64: &str = "45b50ebce21bae657a3b4ed0cd321c784c5473799b461cc81923cbfa65a2849bc60366a08114152a90435ec5a3182ef013c8a203e8a0514649f14b8696ccb1ca";
-const HASH_OUTPUT_32: &str = "55e744dfea583d7a2896335a4f70d67833c929c3f66a83820869f31db06fcd55";
-const HASH_EMPTY_64: &str = "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce";
-
-// --- Stream (XChaCha20-Poly1305 secretstream) ---
-const STREAM_KEY: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
-const STREAM_PLAINTEXT: &[u8] = b"Stream test";
-const STREAM_HEADER: &str = "1ad40de26aa2c803d55c1c7fe1cff7cec88069df6eb627ac";
-const STREAM_CIPHERTEXT: &str = "9079bad016c27d7886551b95e3f80b2f6e3f6ee77921df7e62e59b38";
-
-// --- HChaCha20 (internal) ---
-const HCHACHA_KEY: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
-const HCHACHA_INPUT: &str = "000102030405060708090a0b0c0d0e0f";
-const HCHACHA_OUTPUT: &str = "51e3ff45a895675c4b33b46c64f4a9ace110d34df6a2ceab486372bacbd3eff6";
-
-// =============================================================================
-// TESTS
-// =============================================================================
-
-#[test]
-fn test_secretbox_encrypt_matches_libsodium() {
- crypto::init().unwrap();
-
- let key = hex::decode(SECRETBOX_KEY).unwrap();
- let nonce = hex::decode(SECRETBOX_NONCE).unwrap();
- let expected_ct = hex::decode(SECRETBOX_CIPHERTEXT).unwrap();
-
- let ciphertext =
- crypto::secretbox::encrypt_with_nonce(SECRETBOX_PLAINTEXT, &nonce, &key).unwrap();
-
- assert_eq!(
- hex::encode(&ciphertext),
- hex::encode(&expected_ct),
- "SecretBox ciphertext must match libsodium output exactly"
- );
-}
-
-#[test]
-fn test_secretbox_decrypt_libsodium_ciphertext() {
- crypto::init().unwrap();
-
- let key = hex::decode(SECRETBOX_KEY).unwrap();
- let nonce = hex::decode(SECRETBOX_NONCE).unwrap();
- let ciphertext = hex::decode(SECRETBOX_CIPHERTEXT).unwrap();
-
- let plaintext = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
-
- assert_eq!(
- plaintext, SECRETBOX_PLAINTEXT,
- "Must decrypt libsodium ciphertext correctly"
- );
-}
-
-#[test]
-fn test_kdf_subkey_matches_libsodium() {
- crypto::init().unwrap();
-
- let master_key = hex::decode(KDF_MASTER_KEY).unwrap();
- let expected_subkey = hex::decode(KDF_SUBKEY_32).unwrap();
-
- let subkey = crypto::kdf::derive_subkey(&master_key, 32, 1, b"loginctx").unwrap();
-
- assert_eq!(
- hex::encode(&subkey),
- hex::encode(&expected_subkey),
- "KDF subkey must match libsodium output exactly"
- );
-}
-
-#[test]
-fn test_kdf_login_key_matches_libsodium() {
- crypto::init().unwrap();
-
- let master_key = hex::decode(KDF_MASTER_KEY).unwrap();
- let expected_login_key = hex::decode(KDF_LOGIN_KEY).unwrap();
-
- let login_key = crypto::kdf::derive_login_key(&master_key).unwrap();
-
- assert_eq!(
- hex::encode(&login_key),
- hex::encode(&expected_login_key),
- "Login key must match libsodium output exactly"
- );
-}
-
-#[test]
-fn test_argon2_matches_libsodium() {
- crypto::init().unwrap();
-
- let salt = hex::decode(ARGON2_SALT).unwrap();
- let expected_key = hex::decode(ARGON2_KEY).unwrap();
-
- // 64MB in bytes = 67108864
- let key = crypto::argon::derive_key(ARGON2_PASSWORD, &salt, 67108864, 2).unwrap();
-
- assert_eq!(
- hex::encode(&key),
- hex::encode(&expected_key),
- "Argon2id key must match libsodium output exactly"
- );
-}
-
-#[test]
-fn test_hash_64_matches_libsodium() {
- crypto::init().unwrap();
-
- let expected_hash = hex::decode(HASH_OUTPUT_64).unwrap();
-
- let hash = crypto::hash::hash(HASH_INPUT, Some(64), None).unwrap();
-
- assert_eq!(
- hex::encode(&hash),
- hex::encode(&expected_hash),
- "BLAKE2b-512 hash must match libsodium output exactly"
- );
-}
-
-#[test]
-fn test_hash_32_matches_libsodium() {
- crypto::init().unwrap();
-
- let expected_hash = hex::decode(HASH_OUTPUT_32).unwrap();
-
- let hash = crypto::hash::hash(HASH_INPUT, Some(32), None).unwrap();
-
- assert_eq!(
- hex::encode(&hash),
- hex::encode(&expected_hash),
- "BLAKE2b-256 hash must match libsodium output exactly"
- );
-}
-
-#[test]
-fn test_hash_empty_matches_libsodium() {
- crypto::init().unwrap();
-
- let expected_hash = hex::decode(HASH_EMPTY_64).unwrap();
-
- let hash = crypto::hash::hash(b"", Some(64), None).unwrap();
-
- assert_eq!(
- hex::encode(&hash),
- hex::encode(&expected_hash),
- "BLAKE2b-512 of empty input must match libsodium output exactly"
- );
-}
-
-#[test]
-fn test_stream_decrypt_libsodium_ciphertext() {
- crypto::init().unwrap();
-
- let key = hex::decode(STREAM_KEY).unwrap();
- let header = hex::decode(STREAM_HEADER).unwrap();
- let ciphertext = hex::decode(STREAM_CIPHERTEXT).unwrap();
-
- let mut decryptor = crypto::stream::StreamDecryptor::new(&header, &key).unwrap();
- let (plaintext, tag) = decryptor.pull(&ciphertext).unwrap();
-
- assert_eq!(
- plaintext, STREAM_PLAINTEXT,
- "Must decrypt libsodium stream ciphertext correctly"
- );
- assert_eq!(tag, crypto::stream::TAG_FINAL, "Tag must be FINAL");
-}
-
-#[test]
-fn test_stream_roundtrip_format() {
- crypto::init().unwrap();
-
- let key = hex::decode(STREAM_KEY).unwrap();
-
- // Encrypt with our implementation
- let mut encryptor = crypto::stream::StreamEncryptor::new(&key).unwrap();
- let ciphertext = encryptor.push(STREAM_PLAINTEXT, true).unwrap();
-
- // Verify format
- assert_eq!(encryptor.header.len(), 24, "Header must be 24 bytes");
- assert_eq!(
- ciphertext.len(),
- STREAM_PLAINTEXT.len() + 17,
- "Ciphertext must be plaintext + 17 bytes overhead"
- );
-
- // Decrypt and verify
- let mut decryptor = crypto::stream::StreamDecryptor::new(&encryptor.header, &key).unwrap();
- let (plaintext, tag) = decryptor.pull(&ciphertext).unwrap();
-
- assert_eq!(plaintext, STREAM_PLAINTEXT);
- assert_eq!(tag, crypto::stream::TAG_FINAL);
-}
-
-#[test]
-fn test_hchacha20_matches_libsodium() {
- // HChaCha20 is internal, but we can verify it through stream encryption
- // by checking that we can decrypt libsodium-encrypted data
- crypto::init().unwrap();
-
- // The fact that test_stream_decrypt_libsodium_ciphertext passes
- // proves HChaCha20 is correct (it's used to derive the subkey from header)
-
- // We can also verify the constant directly if exposed
- let key = hex::decode(HCHACHA_KEY).unwrap();
- let input = hex::decode(HCHACHA_INPUT).unwrap();
- let expected = hex::decode(HCHACHA_OUTPUT).unwrap();
-
- // Use chacha20 crate directly to verify
- use chacha20::cipher::consts::U10;
- use chacha20::hchacha;
-
- let key_arr: [u8; 32] = key.try_into().unwrap();
- let input_arr: [u8; 16] = input.try_into().unwrap();
-
- let output = hchacha::<U10>((&key_arr).into(), (&input_arr).into());
-
- assert_eq!(
- hex::encode(output.as_slice()),
- hex::encode(&expected),
- "HChaCha20 must match libsodium output exactly"
- );
-}
-
-// =============================================================================
-// SEALED BOX - Can't use fixed vectors (ephemeral key), but verify format
-// =============================================================================
-
-#[test]
-fn test_sealedbox_format_matches_libsodium() {
- crypto::init().unwrap();
-
- let (pk, sk) = crypto::keys::generate_keypair().unwrap();
- let plaintext = b"Sealed message";
-
- let ciphertext = crypto::sealed::seal(plaintext, &pk).unwrap();
-
- // libsodium sealed box format: ephemeral_pk (32) || box (plaintext + 16)
- // Total overhead: 32 + 16 = 48 bytes
- assert_eq!(
- ciphertext.len(),
- plaintext.len() + 48,
- "Sealed box must have 48 bytes overhead (32 ephemeral pk + 16 MAC)"
- );
-
- // Must decrypt correctly
- let decrypted = crypto::sealed::open(&ciphertext, &pk, &sk).unwrap();
- assert_eq!(decrypted, plaintext);
-}
-
-// =============================================================================
-// ADDITIONAL EDGE CASES
-// =============================================================================
-
-#[test]
-fn test_secretbox_empty_plaintext() {
- crypto::init().unwrap();
-
- let key = hex::decode(SECRETBOX_KEY).unwrap();
- let nonce = hex::decode(SECRETBOX_NONCE).unwrap();
-
- let ciphertext = crypto::secretbox::encrypt_with_nonce(b"", &nonce, &key).unwrap();
-
- // Empty plaintext should produce 16-byte ciphertext (just MAC)
- assert_eq!(ciphertext.len(), 16);
-
- let plaintext = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();
- assert_eq!(plaintext, b"");
-}
-
-#[test]
-fn test_kdf_different_contexts() {
- crypto::init().unwrap();
-
- let master_key = hex::decode(KDF_MASTER_KEY).unwrap();
-
- let key1 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"loginctx").unwrap();
- let key2 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"otherctx").unwrap();
-
- assert_ne!(key1, key2, "Different contexts must produce different keys");
-}
-
-#[test]
-fn test_kdf_different_ids() {
- crypto::init().unwrap();
-
- let master_key = hex::decode(KDF_MASTER_KEY).unwrap();
-
- let key1 = crypto::kdf::derive_subkey(&master_key, 32, 1, b"loginctx").unwrap();
- let key2 = crypto::kdf::derive_subkey(&master_key, 32, 2, b"loginctx").unwrap();
-
- assert_ne!(key1, key2, "Different IDs must produce different keys");
-}
-
-#[test]
-fn test_stream_multi_chunk() {
- crypto::init().unwrap();
-
- let key = hex::decode(STREAM_KEY).unwrap();
- let chunks = [b"First".to_vec(), b"Second".to_vec(), b"Third".to_vec()];
-
- let mut encryptor = crypto::stream::StreamEncryptor::new(&key).unwrap();
- let mut encrypted: Vec<Vec<u8>> = Vec::new();
-
- for (i, chunk) in chunks.iter().enumerate() {
- let is_final = i == chunks.len() - 1;
- encrypted.push(encryptor.push(chunk, is_final).unwrap());
- }
-
- let mut decryptor = crypto::stream::StreamDecryptor::new(&encryptor.header, &key).unwrap();
-
- for (i, (ct, original)) in encrypted.iter().zip(chunks.iter()).enumerate() {
- let (pt, tag) = decryptor.pull(ct).unwrap();
- assert_eq!(pt, *original);
-
- let expected_tag = if i == chunks.len() - 1 {
- crypto::stream::TAG_FINAL
- } else {
- crypto::stream::TAG_MESSAGE
- };
- assert_eq!(tag, expected_tag);
- }
-}
-
-// =============================================================================
-// SUMMARY
-// =============================================================================
-//
-// These tests verify byte-for-byte compatibility with libsodium:
-// - SecretBox: encrypt/decrypt with known vectors βœ“
-// - KDF: subkey derivation with known vectors βœ“
-// - Argon2id: key derivation with known vectors βœ“
-// - BLAKE2b: hash with known vectors βœ“
-// - Stream: decrypt known vectors + format verification βœ“
-// - SealedBox: format verification (can't use fixed vectors) βœ“
-// - HChaCha20: internal primitive verification βœ“
-//
-// If all tests pass, the implementation is libsodium-compatible.
-// =============================================================================
diff --git a/rust/core/tests/package-lock.json b/rust/core/tests/package-lock.json
deleted file mode 100644
index 4443924faa..0000000000
--- a/rust/core/tests/package-lock.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "name": "tests",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "dependencies": {
- "libsodium-wrappers-sumo": "^0.7.15"
- }
- },
- "node_modules/libsodium-sumo": {
- "version": "0.7.15",
- "resolved": "https://registry.npmjs.org/libsodium-sumo/-/libsodium-sumo-0.7.15.tgz",
- "integrity": "sha512-5tPmqPmq8T8Nikpm1Nqj0hBHvsLFCXvdhBFV7SGOitQPZAA6jso8XoL0r4L7vmfKXr486fiQInvErHtEvizFMw==",
- "license": "ISC"
- },
- "node_modules/libsodium-wrappers-sumo": {
- "version": "0.7.15",
- "resolved": "https://registry.npmjs.org/libsodium-wrappers-sumo/-/libsodium-wrappers-sumo-0.7.15.tgz",
- "integrity": "sha512-aSWY8wKDZh5TC7rMvEdTHoyppVq/1dTSAeAR7H6pzd6QRT3vQWcT5pGwCotLcpPEOLXX6VvqihSPkpEhYAjANA==",
- "license": "ISC",
- "dependencies": {
- "libsodium-sumo": "^0.7.15"
- }
- }
- }
-}
diff --git a/rust/core/tests/package.json b/rust/core/tests/package.json
deleted file mode 100644
index f4344b9f79..0000000000
--- a/rust/core/tests/package.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "dependencies": {
- "libsodium-wrappers-sumo": "^0.7.15"
- }
-}