Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Move all crypto related modules to src/crypto namespace (#2159)

Leendert de Borst7c3fb342934c
diff --git a/core/rust/src/argon2/mod.rs b/core/rust/src/argon2/mod.rs
deleted file mode 100644
index 14c0a3c98..000000000
--- a/core/rust/src/argon2/mod.rs
+++ /dev/null
@@ -1,263 +0,0 @@
-//! Argon2id key derivation.
-
-use serde::Deserialize;
-use thiserror::Error;
-
-/// Length of every derived key in bytes; the vault format assumes a 256-bit key throughout.
-pub const ARGON2_OUTPUT_LENGTH: usize = 32;
-
-/// Default memory cost in KiB, used when the settings do not state one.
-pub const ARGON2_DEFAULT_MEMORY_KIB: u32 = 19456;
-
-/// Default number of passes, used when the settings do not state one.
-pub const ARGON2_DEFAULT_ITERATIONS: u32 = 2;
-
-/// Default number of lanes, used when the settings do not state one.
-pub const ARGON2_DEFAULT_PARALLELISM: u32 = 1;
-
-/// Argon2-related errors.
-#[derive(Error, Debug, Clone)]
-#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
-#[cfg_attr(feature = "uniffi", uniffi(flat_error))]
-pub enum Argon2Error {
- /// The encryption settings JSON could not be read.
- #[error("Invalid encryption settings: {0}")]
- InvalidSettings(String),
-
- /// The cost parameters were rejected by the Argon2 implementation.
- #[error("Invalid parameter: {0}")]
- InvalidParameter(String),
-}
-
-/// Argon2id cost parameters, matching the `EncryptionSettings` the server stores per account.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct Argon2Params {
- /// Memory cost in KiB (`MemorySize` in the settings JSON).
- pub memory_kib: u32,
-
- /// Number of passes over memory (`Iterations` in the settings JSON).
- pub iterations: u32,
-
- /// Number of lanes (`DegreeOfParallelism` in the settings JSON).
- pub parallelism: u32,
-}
-
-impl Default for Argon2Params {
- fn default() -> Self {
- Self {
- memory_kib: ARGON2_DEFAULT_MEMORY_KIB,
- iterations: ARGON2_DEFAULT_ITERATIONS,
- parallelism: ARGON2_DEFAULT_PARALLELISM,
- }
- }
-}
-
-impl Argon2Params {
- /// Reads the `EncryptionSettings` JSON the server handed the client with its login challenge.
- ///
- /// A missing field falls back to the AliasVault default for that field. An empty string means
- /// the caller has no settings at all and wants the defaults.
- ///
- /// # Arguments
- /// * `settings_json` - Settings as `{"DegreeOfParallelism":1,"MemorySize":19456,"Iterations":2}`.
- ///
- /// # Returns
- /// The parsed cost parameters.
- pub fn from_settings_json(settings_json: &str) -> Result<Self, Argon2Error> {
- let defaults = Self::default();
- if settings_json.trim().is_empty() {
- return Ok(defaults);
- }
-
- let parsed: EncryptionSettingsJson = serde_json::from_str(settings_json).map_err(|e| Argon2Error::InvalidSettings(e.to_string()))?;
-
- Ok(Self {
- memory_kib: parsed.memory_size.unwrap_or(defaults.memory_kib),
- iterations: parsed.iterations.unwrap_or(defaults.iterations),
- parallelism: parsed.degree_of_parallelism.unwrap_or(defaults.parallelism),
- })
- }
-}
-
-/// The `EncryptionSettings` JSON as the server stores it.
-#[derive(Deserialize)]
-struct EncryptionSettingsJson {
- #[serde(rename = "MemorySize")]
- memory_size: Option<u32>,
-
- #[serde(rename = "Iterations")]
- iterations: Option<u32>,
-
- #[serde(rename = "DegreeOfParallelism")]
- degree_of_parallelism: Option<u32>,
-}
-
-/// Derives a 32-byte key from a password using Argon2id with explicit cost parameters.
-///
-/// # Arguments
-/// * `password` - The password bytes.
-/// * `salt` - The salt bytes, at least 8 bytes long.
-/// * `params` - The cost parameters.
-///
-/// # Returns
-/// The derived key, [`ARGON2_OUTPUT_LENGTH`] bytes long.
-pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) -> Result<Vec<u8>, Argon2Error> {
- use argon2::{Algorithm, Argon2, Params, Version};
-
- let argon2_params = Params::new(params.memory_kib, params.iterations, params.parallelism, Some(ARGON2_OUTPUT_LENGTH))
- .map_err(|e| Argon2Error::InvalidParameter(format!("Invalid Argon2 params: {}", e)))?;
-
- let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params);
-
- let mut output = vec![0u8; ARGON2_OUTPUT_LENGTH];
- argon2
- .hash_password_into(password, salt, &mut output)
- .map_err(|e| Argon2Error::InvalidParameter(format!("Argon2 hash failed: {}", e)))?;
-
- Ok(output)
-}
-
-/// Derives a 32-byte key from a password using the cost parameters stated as settings JSON.
-///
-/// # Arguments
-/// * `password` - The password; hashed as its UTF-8 bytes.
-/// * `salt` - The salt; hashed as its UTF-8 bytes, at least 8 bytes long.
-/// * `settings_json` - The `EncryptionSettings` JSON, or an empty string for the defaults.
-///
-/// # Returns
-/// The derived key, [`ARGON2_OUTPUT_LENGTH`] bytes long.
-pub fn argon2_derive_key_from_settings(password: &str, salt: &str, settings_json: &str) -> Result<Vec<u8>, Argon2Error> {
- let params = Argon2Params::from_settings_json(settings_json)?;
- argon2_derive_key(password.as_bytes(), salt.as_bytes(), params)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- use crate::hex::bytes_to_hex;
-
- const PASSWORD: &str = "correct horse battery staple";
- const SALT: &str = "somesalt12345678";
-
- /// The parameters the E2E suite overrides accounts to, cheap enough to run in a debug build.
- const CHEAP: Argon2Params = Argon2Params { memory_kib: 1024, iterations: 1, parallelism: 1 };
-
- /// Known-answer vector at the E2E override parameters.
- ///
- /// Produced by the C reference implementation (`argon2-browser`, which the browser extension
- /// ships) and independently by C# Konscious (which the Blazor client ships). If this ever
- /// fails, the Rust implementation has drifted away from the other clients and no vault
- /// written by one will open in the other.
- #[test]
- fn test_known_answer_cheap_params() {
- let key = argon2_derive_key(PASSWORD.as_bytes(), SALT.as_bytes(), CHEAP).unwrap();
- assert_eq!(bytes_to_hex(&key), "64596CFF33144564EEF5652EBB00DB5AA9B98E8FE45E87DC4718147381EEA2E4");
- }
-
- /// Known-answer vector at the multi-lane parameters, guarding the parallelism plumbing.
- #[test]
- fn test_known_answer_multiple_lanes() {
- let params = Argon2Params { memory_kib: 2048, iterations: 2, parallelism: 4 };
- let key = argon2_derive_key(PASSWORD.as_bytes(), SALT.as_bytes(), params).unwrap();
- assert_eq!(bytes_to_hex(&key), "21C9EB8CEFAAEA52FA9D5D0E07F33810AFFA86AAD928A107D83554DB8DA78696");
- }
-
- /// Known-answer vector at the production defaults, reached through the settings JSON.
- #[test]
- fn test_known_answer_default_params() {
- let key = argon2_derive_key_from_settings(PASSWORD, SALT, "").unwrap();
- assert_eq!(bytes_to_hex(&key), "8AA6C7860B6A24C5967F6DE421AB515A7898351CA115689FFE5E88FA6FF6131C");
- }
-
- /// Known-answer vector at the PIN unlock parameters.
- #[test]
- fn test_known_answer_pin_params() {
- let params = Argon2Params { memory_kib: 65536, iterations: 3, parallelism: 1 };
- let key = argon2_derive_key(b"123456", b"AAAAAAAAAAAAAAAAAAAAAA==", params).unwrap();
- assert_eq!(bytes_to_hex(&key), "94E3C74246F03BA82A02BCD0665DADB3F6569CC2565F4C2F6DEB9046EB139166");
- }
-
- /// The settings JSON the server actually sends must map onto the right parameters.
- #[test]
- fn test_settings_json_is_parsed() {
- let params = Argon2Params::from_settings_json("{\"DegreeOfParallelism\":4,\"MemorySize\":2048,\"Iterations\":3}").unwrap();
- assert_eq!(params, Argon2Params { memory_kib: 2048, iterations: 3, parallelism: 4 });
- }
-
- /// An empty settings string means "use the defaults", as does a settings object that omits a field.
- #[test]
- fn test_settings_fall_back_per_field() {
- assert_eq!(Argon2Params::from_settings_json("").unwrap(), Argon2Params::default());
- assert_eq!(Argon2Params::from_settings_json("{}").unwrap(), Argon2Params::default());
-
- let partial = Argon2Params::from_settings_json("{\"Iterations\":5}").unwrap();
- assert_eq!(partial.iterations, 5);
- assert_eq!(partial.memory_kib, ARGON2_DEFAULT_MEMORY_KIB);
- assert_eq!(partial.parallelism, ARGON2_DEFAULT_PARALLELISM);
- }
-
- /// Malformed settings are an error rather than a silent fall back to the defaults, so a
- /// corrupted value can never quietly derive a different key than the account was created with.
- #[test]
- fn test_malformed_settings_are_rejected() {
- assert!(matches!(Argon2Params::from_settings_json("not json"), Err(Argon2Error::InvalidSettings(_))));
- assert!(matches!(Argon2Params::from_settings_json("{\"MemorySize\":\"lots\"}"), Err(Argon2Error::InvalidSettings(_))));
- }
-
- /// Known-answer vectors for the byte-salt path the mobile PIN unlock takes.
- #[test]
- fn test_known_answer_byte_salt() {
- const SALT: &[u8] = &[0x00, 0xFF, 0x80, 0x01, 0xC0, 0xAF, 0x7F, 0xFE, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80];
-
- let cheap = argon2_derive_key(b"123456", SALT, CHEAP).unwrap();
- assert_eq!(bytes_to_hex(&cheap), "27BA8FB75AA770D41358073B80AE7F411B1C1EC5AA25F342473BC479B721485D");
-
- let pin_params = Argon2Params { memory_kib: 65536, iterations: 3, parallelism: 1 };
- let pin = argon2_derive_key(b"123456", SALT, pin_params).unwrap();
- assert_eq!(bytes_to_hex(&pin), "98130FBB995A7BCE6937911146E95D92752716BF3CB0445A221C5439CB587679");
- }
-
- /// The salt is hashed as the characters of the string, never as decoded bytes.
- #[test]
- fn test_salt_is_hashed_as_utf8_bytes() {
- let cheap_settings = "{\"MemorySize\":1024,\"Iterations\":1,\"DegreeOfParallelism\":1}";
- let from_str = argon2_derive_key_from_settings("pw", "0A0B0C0D0E0F1011", cheap_settings).unwrap();
- let from_bytes = argon2_derive_key(b"pw", b"0A0B0C0D0E0F1011", CHEAP).unwrap();
- assert_eq!(from_str, from_bytes);
-
- let decoded = argon2_derive_key(b"pw", &[0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11], CHEAP).unwrap();
- assert_ne!(from_bytes, decoded);
- }
-
- /// Argon2 requires a salt of at least 8 bytes.
- #[test]
- fn test_short_salt_fails() {
- let result = argon2_derive_key(PASSWORD.as_bytes(), b"short", CHEAP);
- assert!(matches!(result, Err(Argon2Error::InvalidParameter(_))));
- }
-
- /// Cost parameters outside what Argon2 accepts are reported rather than silently corrected.
- #[test]
- fn test_invalid_params_fail() {
- let no_iterations = Argon2Params { memory_kib: 1024, iterations: 0, parallelism: 1 };
- assert!(matches!(argon2_derive_key(PASSWORD.as_bytes(), SALT.as_bytes(), no_iterations), Err(Argon2Error::InvalidParameter(_))));
-
- let too_little_memory = Argon2Params { memory_kib: 1, iterations: 1, parallelism: 1 };
- assert!(matches!(argon2_derive_key(PASSWORD.as_bytes(), SALT.as_bytes(), too_little_memory), Err(Argon2Error::InvalidParameter(_))));
- }
-
- /// Different inputs must produce different keys, and identical inputs the same key.
- #[test]
- fn test_hash_varies_with_inputs() {
- let base = argon2_derive_key(PASSWORD.as_bytes(), SALT.as_bytes(), CHEAP).unwrap();
- assert_eq!(base, argon2_derive_key(PASSWORD.as_bytes(), SALT.as_bytes(), CHEAP).unwrap());
- assert_eq!(base.len(), ARGON2_OUTPUT_LENGTH);
-
- assert_ne!(base, argon2_derive_key(b"other password", SALT.as_bytes(), CHEAP).unwrap());
- assert_ne!(base, argon2_derive_key(PASSWORD.as_bytes(), b"othersalt1234567", CHEAP).unwrap());
-
- let other_params = Argon2Params { memory_kib: 1024, iterations: 2, parallelism: 1 };
- assert_ne!(base, argon2_derive_key(PASSWORD.as_bytes(), SALT.as_bytes(), other_params).unwrap());
- }
-}
diff --git a/core/rust/src/crypto/aes_gcm.rs b/core/rust/src/crypto/aes_gcm.rs
new file mode 100644
index 000000000..b8c4c071e
--- /dev/null
+++ b/core/rust/src/crypto/aes_gcm.rs
@@ -0,0 +1,118 @@
+//! AES-256-GCM.
+
+use aes_gcm::aead::{Aead, KeyInit, Payload};
+use aes_gcm::{Aes256Gcm, Nonce};
+use base64::engine::general_purpose::STANDARD as BASE64;
+use base64::Engine;
+use zeroize::{Zeroize, Zeroizing};
+
+use crate::error::{VaultError, VaultResult};
+
+const IV_LENGTH: usize = 12;
+const KEY_LENGTH: usize = 32;
+
+/// A fresh random 256-bit key as base64.
+pub fn generate_key_base64() -> String {
+ let mut key = Zeroizing::new([0u8; KEY_LENGTH]);
+ super::fill_random(&mut key[..]);
+ BASE64.encode(&key[..])
+}
+
+/// Encrypt bytes with a base64 key. Returns base64 of `IV | ciphertext | tag`.
+pub fn symmetric_encrypt_bytes(plaintext: &[u8], key_base64: &str) -> VaultResult<String> {
+ let cipher = cipher_for(key_base64)?;
+ let mut iv = [0u8; IV_LENGTH];
+ super::fill_random(&mut iv);
+
+ let ciphertext = cipher
+ .encrypt(Nonce::from_slice(&iv), Payload { msg: plaintext, aad: &[] })
+ .map_err(|_| VaultError::General("AES-GCM encryption failed".to_string()))?;
+
+ let mut combined = Vec::with_capacity(IV_LENGTH + ciphertext.len());
+ combined.extend_from_slice(&iv);
+ combined.extend_from_slice(&ciphertext);
+ Ok(BASE64.encode(combined))
+}
+
+/// Decrypt `IV | ciphertext | tag` bytes with a base64 key.
+pub fn symmetric_decrypt_bytes(iv_and_ciphertext: &[u8], key_base64: &str) -> VaultResult<Vec<u8>> {
+ if iv_and_ciphertext.len() < IV_LENGTH {
+ return Err(VaultError::General("AES-GCM ciphertext is too short".to_string()));
+ }
+ let cipher = cipher_for(key_base64)?;
+ let (iv, ciphertext) = iv_and_ciphertext.split_at(IV_LENGTH);
+ cipher
+ .decrypt(Nonce::from_slice(iv), Payload { msg: ciphertext, aad: &[] })
+ .map_err(|_| VaultError::General("AES-GCM decryption failed (wrong key or corrupt data)".to_string()))
+}
+
+/// Encrypt a UTF-8 string.
+pub fn symmetric_encrypt(plaintext: &str, key_base64: &str) -> VaultResult<String> {
+ if plaintext.is_empty() {
+ return Ok(String::new());
+ }
+ symmetric_encrypt_bytes(plaintext.as_bytes(), key_base64)
+}
+
+/// Decrypt a base64 `IV | ciphertext | tag` string into UTF-8.
+pub fn symmetric_decrypt(base64_ciphertext: &str, key_base64: &str) -> VaultResult<String> {
+ if base64_ciphertext.is_empty() {
+ return Ok(String::new());
+ }
+ let bytes = decode_base64(base64_ciphertext)?;
+ let plaintext = symmetric_decrypt_bytes(&bytes, key_base64)?;
+ match String::from_utf8(plaintext) {
+ Ok(text) => Ok(text),
+ Err(error) => {
+ error.into_bytes().zeroize();
+ Err(VaultError::General("AES-GCM plaintext is not valid UTF-8".to_string()))
+ }
+ }
+}
+
+/// Decode a base64 string, with the error the callers report.
+pub(crate) fn decode_base64(value: &str) -> VaultResult<Vec<u8>> {
+ BASE64.decode(value).map_err(|_| VaultError::General("Invalid base64".to_string()))
+}
+
+fn cipher_for(key_base64: &str) -> VaultResult<Aes256Gcm> {
+ let key = Zeroizing::new(decode_base64(key_base64)?);
+ if key.len() != KEY_LENGTH {
+ return Err(VaultError::General(format!("AES-GCM key must be {} bytes, got {}", KEY_LENGTH, key.len())));
+ }
+ Ok(Aes256Gcm::new_from_slice(&key[..]).expect("key length checked above"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn round_trips_bytes_and_strings() {
+ let key = generate_key_base64();
+ let bytes: Vec<u8> = (0..=255u8).collect();
+ let encrypted = symmetric_encrypt_bytes(&bytes, &key).unwrap();
+ assert_eq!(symmetric_decrypt_bytes(&decode_base64(&encrypted).unwrap(), &key).unwrap(), bytes);
+
+ let encrypted = symmetric_encrypt("héllo ✓", &key).unwrap();
+ assert_eq!(symmetric_decrypt(&encrypted, &key).unwrap(), "héllo ✓");
+ assert_eq!(symmetric_encrypt("", &key).unwrap(), "");
+ assert_eq!(symmetric_decrypt("", &key).unwrap(), "");
+ }
+
+ #[test]
+ fn rejects_wrong_key_and_short_input() {
+ let key = generate_key_base64();
+ let encrypted = symmetric_encrypt("secret", &key).unwrap();
+ assert!(symmetric_decrypt(&encrypted, &generate_key_base64()).is_err());
+ assert!(symmetric_decrypt_bytes(&[1, 2, 3], &key).is_err());
+ assert!(symmetric_encrypt("x", "dG9vc2hvcnQ=").is_err());
+ }
+
+ #[test]
+ fn layout_is_iv_then_ciphertext_then_tag() {
+ let key = generate_key_base64();
+ let encrypted = decode_base64(&symmetric_encrypt_bytes(b"abc", &key).unwrap()).unwrap();
+ assert_eq!(encrypted.len(), IV_LENGTH + 3 + 16);
+ }
+}
diff --git a/core/rust/src/crypto/argon2.rs b/core/rust/src/crypto/argon2.rs
new file mode 100644
index 000000000..a42eb0ebb
--- /dev/null
+++ b/core/rust/src/crypto/argon2.rs
@@ -0,0 +1,132 @@
+//! Argon2id key derivation.
+
+use serde::Deserialize;
+use thiserror::Error;
+
+/// Length of every derived key in bytes; the vault format assumes a 256-bit key throughout.
+pub const ARGON2_OUTPUT_LENGTH: usize = 32;
+
+/// Default memory cost in KiB, used when the settings do not state one.
+pub const ARGON2_DEFAULT_MEMORY_KIB: u32 = 19456;
+
+/// Default number of passes, used when the settings do not state one.
+pub const ARGON2_DEFAULT_ITERATIONS: u32 = 2;
+
+/// Default number of lanes, used when the settings do not state one.
+pub const ARGON2_DEFAULT_PARALLELISM: u32 = 1;
+
+/// Argon2-related errors.
+#[derive(Error, Debug, Clone)]
+#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
+#[cfg_attr(feature = "uniffi", uniffi(flat_error))]
+pub enum Argon2Error {
+ /// The encryption settings JSON could not be read.
+ #[error("Invalid encryption settings: {0}")]
+ InvalidSettings(String),
+
+ /// The cost parameters were rejected by the Argon2 implementation.
+ #[error("Invalid parameter: {0}")]
+ InvalidParameter(String),
+}
+
+/// Argon2id cost parameters, matching the `EncryptionSettings` the server stores per account.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Argon2Params {
+ /// Memory cost in KiB (`MemorySize` in the settings JSON).
+ pub memory_kib: u32,
+
+ /// Number of passes over memory (`Iterations` in the settings JSON).
+ pub iterations: u32,
+
+ /// Number of lanes (`DegreeOfParallelism` in the settings JSON).
+ pub parallelism: u32,
+}
+
+impl Default for Argon2Params {
+ fn default() -> Self {
+ Self {
+ memory_kib: ARGON2_DEFAULT_MEMORY_KIB,
+ iterations: ARGON2_DEFAULT_ITERATIONS,
+ parallelism: ARGON2_DEFAULT_PARALLELISM,
+ }
+ }
+}
+
+impl Argon2Params {
+ /// Reads the `EncryptionSettings` JSON the server handed the client with its login challenge.
+ ///
+ /// A missing field falls back to the AliasVault default for that field. An empty string means
+ /// the caller has no settings at all and wants the defaults.
+ ///
+ /// # Arguments
+ /// * `settings_json` - Settings as `{"DegreeOfParallelism":1,"MemorySize":19456,"Iterations":2}`.
+ ///
+ /// # Returns
+ /// The parsed cost parameters.
+ pub fn from_settings_json(settings_json: &str) -> Result<Self, Argon2Error> {
+ let defaults = Self::default();
+ if settings_json.trim().is_empty() {
+ return Ok(defaults);
+ }
+
+ let parsed: EncryptionSettingsJson = serde_json::from_str(settings_json).map_err(|e| Argon2Error::InvalidSettings(e.to_string()))?;
+
+ Ok(Self {
+ memory_kib: parsed.memory_size.unwrap_or(defaults.memory_kib),
+ iterations: parsed.iterations.unwrap_or(defaults.iterations),
+ parallelism: parsed.degree_of_parallelism.unwrap_or(defaults.parallelism),
+ })
+ }
+}
+
+/// The `EncryptionSettings` JSON as the server stores it.
+#[derive(Deserialize)]
+struct EncryptionSettingsJson {
+ #[serde(rename = "MemorySize")]
+ memory_size: Option<u32>,
+
+ #[serde(rename = "Iterations")]
+ iterations: Option<u32>,
+
+ #[serde(rename = "DegreeOfParallelism")]
+ degree_of_parallelism: Option<u32>,
+}
+
+/// Derives a 32-byte key from a password using Argon2id with explicit cost parameters.
+///
+/// # Arguments
+/// * `password` - The password bytes.
+/// * `salt` - The salt bytes, at least 8 bytes long.
+/// * `params` - The cost parameters.
+///
+/// # Returns
+/// The derived key, [`ARGON2_OUTPUT_LENGTH`] bytes long.
+pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) -> Result<Vec<u8>, Argon2Error> {
+ use argon2::{Algorithm, Argon2, Params, Version};
+
+ let argon2_params = Params::new(params.memory_kib, params.iterations, params.parallelism, Some(ARGON2_OUTPUT_LENGTH))
+ .map_err(|e| Argon2Error::InvalidParameter(format!("Invalid Argon2 params: {}", e)))?;
+
+ let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params);
+
+ let mut output = vec![0u8; ARGON2_OUTPUT_LENGTH];
+ argon2
+ .hash_password_into(password, salt, &mut output)
+ .map_err(|e| Argon2Error::InvalidParameter(format!("Argon2 hash failed: {}", e)))?;
+
+ Ok(output)
+}
+
+/// Derives a 32-byte key from a password using the cost parameters stated as settings JSON.
+///
+/// # Arguments
+/// * `password` - The password; hashed as its UTF-8 bytes.
+/// * `salt` - The salt; hashed as its UTF-8 bytes, at least 8 bytes long.
+/// * `settings_json` - The `EncryptionSettings` JSON, or an empty string for the defaults.
+///
+/// # Returns
+/// The derived key, [`ARGON2_OUTPUT_LENGTH`] bytes long.
+pub fn argon2_derive_key_from_settings(password: &str, salt: &str, settings_json: &str) -> Result<Vec<u8>, Argon2Error> {
+ let params = Argon2Params::from_settings_json(settings_json)?;
+ argon2_derive_key(password.as_bytes(), salt.as_bytes(), params)
+}
diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rs
new file mode 100644
index 000000000..d2da64cca
--- /dev/null
+++ b/core/rust/src/crypto/key_chain.rs
@@ -0,0 +1,111 @@
+//! The account key hierarchy: KEK (password-derived) wraps the Account Key, which wraps the Vault Encryption
+//! Key and the account's private key.
+
+use serde::{Deserialize, Serialize};
+use std::fmt;
+use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
+
+use super::aes_gcm::{decode_base64, generate_key_base64, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};
+use super::rsa_oaep::generate_rsa_key_pair;
+use crate::error::VaultResult;
+use base64::engine::general_purpose::STANDARD as BASE64;
+use base64::Engine;
+
+/// The wrapped halves of an account key hierarchy: what the server stores.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AccountKeyBlobs {
+ pub encrypted_account_key: String,
+ pub encrypted_vek: String,
+ pub account_public_key: String,
+ pub encrypted_account_private_key: String,
+}
+
+/// A newly created account key hierarchy: the wrapped blobs plus the plaintext halves the client keeps.
+#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
+#[serde(rename_all = "camelCase")]
+pub struct AccountKeyHierarchy {
+ pub vault_encryption_key: String,
+ pub account_private_key: String,
+
+ #[zeroize(skip)]
+ pub account_keys: AccountKeyBlobs,
+}
+
+impl fmt::Debug for AccountKeyHierarchy {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("AccountKeyHierarchy")
+ .field("vault_encryption_key", &"<redacted>")
+ .field("account_private_key", &"<redacted>")
+ .field("account_keys", &self.account_keys)
+ .finish()
+ }
+}
+
+/// Wrap a base64 key with another base64 key. Returns base64 of `IV | ciphertext | tag`.
+pub fn wrap_key(key_base64: &str, wrapping_key_base64: &str) -> VaultResult<String> {
+ symmetric_encrypt_bytes(&Zeroizing::new(decode_base64(key_base64)?), wrapping_key_base64)
+}
+
+/// Unwrap a wrapped key. Returns the key as base64.
+pub fn unwrap_key(wrapped_key_base64: &str, wrapping_key_base64: &str) -> VaultResult<Zeroizing<String>> {
+ let raw = Zeroizing::new(symmetric_decrypt_bytes(&decode_base64(wrapped_key_base64)?, wrapping_key_base64)?);
+ Ok(Zeroizing::new(BASE64.encode(&raw[..])))
+}
+
+/// Turn a password-derived key into the vault encryption key: KEK > Account Key > VEK. Returns the VEK and the
+/// Account Key (base64).
+pub fn resolve_vault_encryption_key(
+ encrypted_account_key: &str,
+ encrypted_vek: &str,
+ kek_base64: &str,
+) -> VaultResult<(Zeroizing<String>, Zeroizing<String>)> {
+ let account_key = unwrap_key(encrypted_account_key, kek_base64)?;
+ let vek = unwrap_key(encrypted_vek, &account_key)?;
+ Ok((vek, account_key))
+}
+
+/// Create a new account key hierarchy wrapped under the given KEK.
+pub fn create_account_key_hierarchy(kek_base64: &str) -> VaultResult<AccountKeyHierarchy> {
+ let vault_encryption_key = generate_key_base64();
+ let account_key = Zeroizing::new(generate_key_base64());
+ let key_pair = generate_rsa_key_pair()?;
+
+ let account_keys = AccountKeyBlobs {
+ encrypted_account_key: wrap_key(&account_key, kek_base64)?,
+ encrypted_vek: wrap_key(&vault_encryption_key, &account_key)?,
+ account_public_key: key_pair.public_key.clone(),
+ encrypted_account_private_key: symmetric_encrypt(&key_pair.private_key, &account_key)?,
+ };
+
+ Ok(AccountKeyHierarchy { vault_encryption_key, account_private_key: key_pair.private_key.clone(), account_keys })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::crypto::aes_gcm::symmetric_decrypt;
+
+ #[test]
+ fn hierarchy_unwraps_back_to_its_plaintext_halves() {
+ let kek = generate_key_base64();
+ let hierarchy = create_account_key_hierarchy(&kek).unwrap();
+
+ let (vek, account_key) = resolve_vault_encryption_key(&hierarchy.account_keys.encrypted_account_key, &hierarchy.account_keys.encrypted_vek, &kek).unwrap();
+ assert_eq!(*vek, hierarchy.vault_encryption_key);
+ assert_eq!(symmetric_decrypt(&hierarchy.account_keys.encrypted_account_private_key, &account_key).unwrap(), hierarchy.account_private_key);
+ }
+
+ #[test]
+ fn wrong_kek_does_not_unwrap() {
+ let hierarchy = create_account_key_hierarchy(&generate_key_base64()).unwrap();
+ assert!(resolve_vault_encryption_key(&hierarchy.account_keys.encrypted_account_key, &hierarchy.account_keys.encrypted_vek, &generate_key_base64()).is_err());
+ }
+
+ #[test]
+ fn wrap_and_unwrap_round_trip() {
+ let wrapping = generate_key_base64();
+ let key = generate_key_base64();
+ assert_eq!(*unwrap_key(&wrap_key(&key, &wrapping).unwrap(), &wrapping).unwrap(), key);
+ }
+}
diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rs
new file mode 100644
index 000000000..d44a09863
--- /dev/null
+++ b/core/rust/src/crypto/mod.rs
@@ -0,0 +1,23 @@
+//! Cryptographic modules used by the clients.
+
+pub mod aes_gcm;
+pub mod argon2;
+pub mod key_chain;
+pub mod rsa_oaep;
+pub mod srp;
+
+pub use aes_gcm::{generate_key_base64, symmetric_decrypt, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};
+pub use key_chain::{create_account_key_hierarchy, resolve_vault_encryption_key, unwrap_key, wrap_key, AccountKeyBlobs, AccountKeyHierarchy};
+pub use rsa_oaep::{decrypt_with_private_key, encrypt_with_public_key, generate_rsa_key_pair, RsaKeyPair};
+
+pub use self::argon2::{argon2_derive_key, argon2_derive_key_from_settings, Argon2Error, Argon2Params};
+pub use self::srp::{
+ srp_derive_private_key, srp_derive_session, srp_derive_session_server, srp_derive_verifier,
+ srp_generate_ephemeral, srp_generate_ephemeral_server, srp_generate_salt,
+ SrpEphemeral, SrpError, SrpSession,
+};
+
+/// Fill a buffer from the operating system's CSPRNG.
+pub(crate) fn fill_random(dest: &mut [u8]) {
+ getrandom::fill(dest).expect("the OS CSPRNG is unavailable");
+}
diff --git a/core/rust/src/crypto/rsa_oaep.rs b/core/rust/src/crypto/rsa_oaep.rs
new file mode 100644
index 000000000..720a9042c
--- /dev/null
+++ b/core/rust/src/crypto/rsa_oaep.rs
@@ -0,0 +1,178 @@
+//! RSA-OAEP (SHA-256) with keys carried as JWK JSON strings compatible with the WebCrypto API.
+
+use base64::engine::general_purpose::{STANDARD as BASE64, URL_SAFE_NO_PAD as BASE64_URL};
+use base64::Engine;
+use rsa::traits::{PrivateKeyParts, PublicKeyParts};
+use rsa::{BigUint, Oaep, RsaPrivateKey, RsaPublicKey};
+use serde::{Deserialize, Serialize};
+use sha2::Sha256;
+use std::fmt;
+use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
+
+use crate::error::{VaultError, VaultResult};
+
+const MODULUS_BITS: usize = 2048;
+
+/// A freshly generated key pair, both halves as JWK JSON strings.
+#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
+#[serde(rename_all = "camelCase")]
+pub struct RsaKeyPair {
+ pub public_key: String,
+ pub private_key: String,
+}
+
+impl fmt::Debug for RsaKeyPair {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("RsaKeyPair").field("public_key", &self.public_key).field("private_key", &"<redacted>").finish()
+ }
+}
+
+/// The JWK fields WebCrypto emits for an RSA-OAEP-256 key. Optional members are absent on a public key.
+#[derive(Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
+struct RsaJwk {
+ key_ops: Vec<String>,
+ ext: bool,
+ alg: String,
+ kty: String,
+ n: String,
+ e: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ d: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ p: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ q: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ dp: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ dq: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ qi: Option<String>,
+}
+
+/// Adapts the crate's CSPRNG to the `rand_core` version the `rsa` crate draws from.
+struct CoreRng;
+
+impl rand_core06::RngCore for CoreRng {
+ fn next_u32(&mut self) -> u32 {
+ let mut bytes = [0u8; 4];
+ super::fill_random(&mut bytes);
+ u32::from_le_bytes(bytes)
+ }
+
+ fn next_u64(&mut self) -> u64 {
+ let mut bytes = [0u8; 8];
+ super::fill_random(&mut bytes);
+ u64::from_le_bytes(bytes)
+ }
+
+ fn fill_bytes(&mut self, dest: &mut [u8]) {
+ super::fill_random(dest);
+ }
+
+ fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core06::Error> {
+ super::fill_random(dest);
+ Ok(())
+ }
+}
+
+impl rand_core06::CryptoRng for CoreRng {}
+
+/// Generate a 2048-bit RSA key pair for RSA-OAEP-256 grants.
+pub fn generate_rsa_key_pair() -> VaultResult<RsaKeyPair> {
+ let private = RsaPrivateKey::new(&mut CoreRng, MODULUS_BITS).map_err(|e| VaultError::General(format!("RSA key generation failed: {}", e)))?;
+ let public = private.to_public_key();
+ Ok(RsaKeyPair { public_key: public_to_jwk(&public)?, private_key: private_to_jwk(&private)? })
+}
+
+/// Encrypt bytes for the holder of a JWK public key. Returns base64 ciphertext.
+pub fn encrypt_with_public_key(plaintext: &[u8], public_key_jwk: &str) -> VaultResult<String> {
+ let public = public_from_jwk(public_key_jwk)?;
+ let ciphertext = public
+ .encrypt(&mut CoreRng, Oaep::new::<Sha256>(), plaintext)
+ .map_err(|e| VaultError::General(format!("RSA-OAEP encryption failed: {}", e)))?;
+ Ok(BASE64.encode(ciphertext))
+}
+
+/// Decrypt base64 ciphertext with a JWK private key.
+pub fn decrypt_with_private_key(base64_ciphertext: &str, private_key_jwk: &str) -> VaultResult<Vec<u8>> {
+ let private = private_from_jwk(private_key_jwk)?;
+ let ciphertext = super::aes_gcm::decode_base64(base64_ciphertext)?;
+ // Blinded: plain `decrypt` runs the exponentiation on the ciphertext as given, which leaks timing an
+ // attacker who can submit chosen ciphertexts turns into key recovery (RUSTSEC-2023-0071, Marvin attack).
+ private
+ .decrypt_blinded(&mut CoreRng, Oaep::new::<Sha256>(), &ciphertext)
+ .map_err(|_| VaultError::General("RSA-OAEP decryption failed (wrong key or corrupt data)".to_string()))
+}
+
+fn public_from_jwk(jwk: &str) -> VaultResult<RsaPublicKey> {
+ let parsed = parse_jwk(jwk)?;
+ RsaPublicKey::new(field(&parsed.n)?, field(&parsed.e)?).map_err(|e| VaultError::General(format!("Invalid RSA public key: {}", e)))
+}
+
+fn private_from_jwk(jwk: &str) -> VaultResult<RsaPrivateKey> {
+ let parsed = parse_jwk(jwk)?;
+ let d = parsed.d.as_deref().ok_or_else(|| VaultError::General("JWK is not a private key".to_string()))?;
+ let p = parsed.p.as_deref().ok_or_else(|| VaultError::General("JWK private key is missing p".to_string()))?;
+ let q = parsed.q.as_deref().ok_or_else(|| VaultError::General("JWK private key is missing q".to_string()))?;
+ RsaPrivateKey::from_components(field(&parsed.n)?, field(&parsed.e)?, field(d)?, vec![field(p)?, field(q)?])
+ .map_err(|e| VaultError::General(format!("Invalid RSA private key: {}", e)))
+}
+
+fn parse_jwk(jwk: &str) -> VaultResult<RsaJwk> {
+ let parsed: RsaJwk = serde_json::from_str(jwk).map_err(|e| VaultError::General(format!("Invalid RSA JWK: {}", e)))?;
+ if parsed.kty != "RSA" {
+ return Err(VaultError::General(format!("Unsupported JWK key type \"{}\"", parsed.kty)));
+ }
+ Ok(parsed)
+}
+
+fn field(value: &str) -> VaultResult<BigUint> {
+ let bytes = Zeroizing::new(BASE64_URL.decode(value).map_err(|_| VaultError::General("Invalid base64url in JWK".to_string()))?);
+ Ok(BigUint::from_bytes_be(&bytes))
+}
+
+fn encode(value: &BigUint) -> String {
+ BASE64_URL.encode(Zeroizing::new(value.to_bytes_be()))
+}
+
+fn public_to_jwk(public: &RsaPublicKey) -> VaultResult<String> {
+ let jwk = RsaJwk {
+ key_ops: vec!["encrypt".to_string()],
+ ext: true,
+ alg: "RSA-OAEP-256".to_string(),
+ kty: "RSA".to_string(),
+ n: encode(public.n()),
+ e: encode(public.e()),
+ d: None,
+ p: None,
+ q: None,
+ dp: None,
+ dq: None,
+ qi: None,
+ };
+ serde_json::to_string(&jwk).map_err(VaultError::from)
+}
+
+fn private_to_jwk(private: &RsaPrivateKey) -> VaultResult<String> {
+ let primes = private.primes();
+ if primes.len() != 2 {
+ return Err(VaultError::General("Only two-prime RSA keys can be exported as JWK".to_string()));
+ }
+ let qinv = private.qinv().ok_or_else(|| VaultError::General("RSA key is missing its CRT coefficient".to_string()))?;
+ let jwk = RsaJwk {
+ key_ops: vec!["decrypt".to_string()],
+ ext: true,
+ alg: "RSA-OAEP-256".to_string(),
+ kty: "RSA".to_string(),
+ n: encode(private.n()),
+ e: encode(private.e()),
+ d: Some(encode(private.d())),
+ p: Some(encode(&primes[0])),
+ q: Some(encode(&primes[1])),
+ dp: private.dp().map(encode),
+ dq: private.dq().map(encode),
+ qi: Some(encode(&qinv.to_biguint().ok_or_else(|| VaultError::General("RSA CRT coefficient is negative".to_string()))?)),
+ };
+ serde_json::to_string(&jwk).map_err(VaultError::from)
+}
diff --git a/core/rust/src/srp/mod.rs b/core/rust/src/crypto/srp.rs
similarity index 99%
rename from core/rust/src/srp/mod.rs
rename to core/rust/src/crypto/srp.rs
index 64e383fa9..54a49a27a 100644
--- a/core/rust/src/srp/mod.rs
+++ b/core/rust/src/crypto/srp.rs
@@ -6,7 +6,6 @@
use digest::Digest;
use num_bigint::BigUint;
-use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use srp::client::SrpClient;
@@ -96,7 +95,7 @@ fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, SrpError> {
/// Generate cryptographically secure random bytes.
fn generate_random_bytes(len: usize) -> Vec<u8> {
let mut bytes = vec![0u8; len];
- rand::rng().fill_bytes(&mut bytes);
+ super::fill_random(&mut bytes);
bytes
}
diff --git a/core/rust/src/ffi.rs b/core/rust/src/ffi.rs
index e1bc8fd45..3b244868d 100644
--- a/core/rust/src/ffi.rs
+++ b/core/rust/src/ffi.rs
@@ -7,51 +7,8 @@ use std::ffi::{c_char, CStr, CString};
use std::ptr;
use crate::credential_matcher::{filter_credentials, CredentialMatcherInput};
-use crate::vault_merge::{merge_vaults, MergeInput};
use crate::vault_pruner::{prune_vault, PruneInput};
-/// Merge two vaults using LWW strategy.
-///
-/// # Safety
-///
-/// - `input_json` must be a valid null-terminated C string
-/// - The returned pointer must be freed by calling `free_string`
-///
-/// # Returns
-///
-/// A null-terminated C string containing the JSON result (MergeOutput).
-/// Returns null on error.
-#[no_mangle]
-pub unsafe extern "C" fn merge_vaults_ffi(input_json: *const c_char) -> *mut c_char {
- if input_json.is_null() {
- return ptr::null_mut();
- }
-
- let c_str = match CStr::from_ptr(input_json).to_str() {
- Ok(s) => s,
- Err(_) => return ptr::null_mut(),
- };
-
- let input: MergeInput = match serde_json::from_str(c_str) {
- Ok(i) => i,
- Err(e) => {
- return create_error_response(&format!("Failed to parse input: {}", e));
- }
- };
-
- let output = match merge_vaults(input) {
- Ok(o) => o,
- Err(e) => {
- return create_error_response(&format!("Merge failed: {}", e));
- }
- };
-
- match serde_json::to_string(&output) {
- Ok(json) => string_to_c_char(json),
- Err(e) => create_error_response(&format!("Failed to serialize output: {}", e)),
- }
-}
-
/// Prune expired items from trash.
///
/// Items with DeletedAt older than retention_days are marked as permanently deleted.
@@ -144,7 +101,7 @@ pub unsafe extern "C" fn filter_credentials_ffi(input_json: *const c_char) -> *m
/// A null-terminated C string containing a JSON array of table names.
#[no_mangle]
pub extern "C" fn get_syncable_table_names_ffi() -> *mut c_char {
- let names = crate::vault_merge::merge_table_names();
+ let names = crate::vault_merge::syncable_table_names();
match serde_json::to_string(&names) {
Ok(json) => string_to_c_char(json),
Err(_) => ptr::null_mut(),
@@ -379,7 +336,7 @@ pub unsafe extern "C" fn vault_codec_unpack_payload_ffi(base64_plain_bytes: *con
/// A null-terminated C string containing the salt as uppercase hex.
#[no_mangle]
pub extern "C" fn srp_generate_salt_ffi() -> *mut c_char {
- string_to_c_char(crate::srp::srp_generate_salt())
+ string_to_c_char(crate::crypto::srp::srp_generate_salt())
}
/// Derive the SRP private key from credentials.
@@ -418,7 +375,7 @@ pub unsafe extern "C" fn srp_derive_private_key_ffi(
Err(_) => return create_error_response("Invalid UTF-8 in password_hash"),
};
- match crate::srp::srp_derive_private_key(salt_str, identity_str, password_hash_str) {
+ match crate::crypto::srp::srp_derive_private_key(salt_str, identity_str, password_hash_str) {
Ok(key) => string_to_c_char(key),
Err(e) => create_error_response(&format!("SRP error: {}", e)),
}
@@ -446,7 +403,7 @@ pub unsafe extern "C" fn srp_derive_verifier_ffi(private_key: *const c_char) ->
Err(_) => return create_error_response("Invalid UTF-8 in private_key"),
};
- match crate::srp::srp_derive_verifier(private_key_str) {
+ match crate::crypto::srp::srp_derive_verifier(private_key_str) {
Ok(verifier) => string_to_c_char(verifier),
Err(e) => create_error_response(&format!("SRP error: {}", e)),
}
@@ -463,7 +420,7 @@ pub unsafe extern "C" fn srp_derive_verifier_ffi(private_key: *const c_char) ->
/// A null-terminated C string containing JSON: {"public": "...", "secret": "..."}
#[no_mangle]
pub extern "C" fn srp_generate_ephemeral_ffi() -> *mut c_char {
- let ephemeral = crate::srp::srp_generate_ephemeral();
+ let ephemeral = crate::crypto::srp::srp_generate_ephemeral();
match serde_json::to_string(&ephemeral) {
Ok(json) => string_to_c_char(json),
Err(e) => create_error_response(&format!("Failed to serialize ephemeral: {}", e)),
@@ -520,7 +477,7 @@ pub unsafe extern "C" fn srp_derive_session_ffi(
Err(_) => return create_error_response("Invalid UTF-8 in private_key"),
};
- match crate::srp::srp_derive_session(
+ match crate::crypto::srp::srp_derive_session(
client_secret_str,
server_public_str,
salt_str,
@@ -557,7 +514,7 @@ pub unsafe extern "C" fn srp_generate_ephemeral_server_ffi(verifier: *const c_ch
Err(_) => return create_error_response("Invalid UTF-8 in verifier"),
};
- match crate::srp::srp_generate_ephemeral_server(verifier_str) {
+ match crate::crypto::srp::srp_generate_ephemeral_server(verifier_str) {
Ok(ephemeral) => match serde_json::to_string(&ephemeral) {
Ok(json) => string_to_c_char(json),
Err(e) => create_error_response(&format!("Failed to serialize ephemeral: {}", e)),
@@ -624,7 +581,7 @@ pub unsafe extern "C" fn srp_derive_session_server_ffi(
Err(_) => return create_error_response("Invalid UTF-8 in client_proof"),
};
- match crate::srp::srp_derive_session_server(
+ match crate::crypto::srp::srp_derive_session_server(
server_secret_str,
client_public_str,
salt_str,
@@ -664,9 +621,6 @@ mod tests {
#[test]
fn test_null_input() {
unsafe {
- let result = merge_vaults_ffi(ptr::null());
- assert!(result.is_null());
-
let result = prune_vault_ffi(ptr::null());
assert!(result.is_null());
@@ -679,7 +633,7 @@ mod tests {
fn test_invalid_json_input() {
let invalid_json = CString::new("not valid json").unwrap();
unsafe {
- let result = merge_vaults_ffi(invalid_json.as_ptr());
+ let result = prune_vault_ffi(invalid_json.as_ptr());
assert!(!result.is_null());
let c_str = CStr::from_ptr(result);
diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rs
index 74260595a..0d15da32c 100644
--- a/core/rust/src/lib.rs
+++ b/core/rust/src/lib.rs
@@ -8,8 +8,8 @@
//! - **favicon**: Favicon handling and source selection
//! - **password_generator**: Password and passphrase (Diceware) generation
//! - **identity_generator**: Random identity (alias persona) generation
-//! - **srp**: Secure Remote Password (SRP-6a) protocol for authentication
-//! - **argon2**: Argon2id key derivation
+//! - **crypto**: Argon2id derivation, AES-256-GCM, RSA-OAEP, the account key hierarchy and the SRP-6a handshake
+//! - **vault_sync**: the sans-IO vault sync engine every client drives
//!
//! This library accepts data as JSON and returns results as JSON.
//! Each platform (browser, iOS, Android, .NET) handles its own I/O
@@ -17,6 +17,7 @@
pub mod error;
mod hex;
+pub mod timestamp;
mod rng;
pub mod vault_model;
pub mod vault_merge;
@@ -28,14 +29,13 @@ pub mod email_parser;
pub mod favicon;
pub mod password_generator;
pub mod identity_generator;
-pub mod srp;
-pub mod argon2;
+pub mod crypto;
+pub mod vault_sync;
pub use error::VaultError;
pub use vault_merge::{
- merge_canonical, merge_canonical_json, merge_vaults, CanonicalManifestMerge, CanonicalMergeInput,
- CanonicalMergeOutput, MergeInput, MergeOutput, MergeStats, SqlStatement, TableData,
- SYNCABLE_TABLE_NAMES,
+ merge_canonical, merge_canonical_json, CanonicalManifestMerge, CanonicalMergeInput,
+ CanonicalMergeOutput, MergeStats, SqlStatement, SYNCABLE_TABLE_NAMES,
};
pub use vault_codec::{
compute_ciphertext_hash, compute_content_fingerprint, canonicalize_from_sqlite,
@@ -60,13 +60,13 @@ pub use email_parser::{ParsedEmail, ParsedEmailAttachment};
pub use favicon::{favicon_source_key, select_favicon_target, FaviconTarget};
pub use password_generator::{generate_password, PasswordSettings};
pub use identity_generator::{generate_identity, Identity, IdentityRequest};
-pub use srp::{
+pub use crypto::{
+ argon2_derive_key, argon2_derive_key_from_settings, Argon2Error, Argon2Params,
srp_generate_salt, srp_derive_private_key, srp_derive_verifier,
srp_generate_ephemeral, srp_derive_session,
srp_generate_ephemeral_server, srp_derive_session_server,
SrpEphemeral, SrpSession, SrpError,
};
-pub use crate::argon2::{argon2_derive_key, argon2_derive_key_from_settings, Argon2Error, Argon2Params};
// WASM bindings
#[cfg(feature = "wasm")]
diff --git a/core/rust/src/timestamp.rs b/core/rust/src/timestamp.rs
new file mode 100644
index 000000000..66427f6b9
--- /dev/null
+++ b/core/rust/src/timestamp.rs
@@ -0,0 +1,24 @@
+//! The timestamp formats the vault data model uses.
+
+use chrono::{DateTime, Utc};
+
+/// ISO-8601 UTC with milliseconds (`2026-01-01T00:00:00.000Z`): canonicalized payloads and prune input.
+pub const ISO_UTC_MILLIS: &str = "%Y-%m-%dT%H:%M:%S%.3fZ";
+
+/// The vault's row timestamp format (`2026-01-01 00:00:00.000`, UTC).
+pub const VAULT_DATETIME: &str = "%Y-%m-%d %H:%M:%S%.3f";
+
+/// Format an instant as ISO-8601 UTC with milliseconds.
+pub fn iso_utc(instant: &DateTime<Utc>) -> String {
+ instant.format(ISO_UTC_MILLIS).to_string()
+}
+
+/// The current instant as ISO-8601 UTC with milliseconds.
+pub fn now_iso_utc() -> String {
+ iso_utc(&Utc::now())
+}
+
+/// The current instant in the vault's row timestamp format.
+pub fn now_vault_datetime() -> String {
+ Utc::now().format(VAULT_DATETIME).to_string()
+}
diff --git a/core/rust/src/uniffi_api.rs b/core/rust/src/uniffi_api.rs
index f4afc3e85..61dba0a99 100644
--- a/core/rust/src/uniffi_api.rs
+++ b/core/rust/src/uniffi_api.rs
@@ -11,35 +11,17 @@ pub fn get_core_version() -> String {
crate::get_core_version().to_string()
}
-/// Get the list of syncable table names a platform must read into the merge input.
+/// Get the list of table names that take part in a vault sync.
#[uniffi::export]
pub fn get_syncable_table_names() -> Vec<String> {
- crate::vault_merge::merge_table_names().iter().map(|s| s.to_string()).collect()
+ crate::vault_merge::syncable_table_names().iter().map(|s| s.to_string()).collect()
}
-/// Merge local and server vaults using Last-Write-Wins strategy.
-///
-/// # Arguments
-/// * `input_json` - JSON string with format:
-/// ```json
-/// {
-/// "local_tables": [{"name": "Items", "records": [...]}],
-/// "server_tables": [{"name": "Items", "records": [...]}]
-/// }
-/// ```
-///
-/// # Returns
-/// JSON string with format:
-/// ```json
-/// {
-/// "success": true,
-/// "statements": [{"sql": "UPDATE ...", "params": [...]}],
-/// "stats": {"tablesProcessed": 11, "conflicts": 0, ...}
-/// }
-/// ```
+/// Merge the local canonical vault onto the server canonical vault (manifest-v1 format), one
+/// manifest at a time, rows out. Input: `CanonicalMergeInput` JSON. Output: `CanonicalMergeOutput` JSON.
#[uniffi::export]
-pub fn merge_vaults_json(input_json: String) -> Result<String, VaultError> {
- crate::vault_merge::merge_vaults_json(&input_json)
+pub fn merge_canonical_json(input_json: String) -> Result<String, VaultError> {
+ crate::vault_merge::merge_canonical_json(&input_json)
}
/// Prune expired items from trash (items with DeletedAt older than retention_days).
@@ -283,6 +265,12 @@ pub fn vault_codec_bucket_layout() -> Result<String, VaultError> {
crate::vault_codec::bucket_layout_json()
}
+/// The name of the client-local SQLite table that carries the codec overflow inside the vault DB.
+#[uniffi::export]
+pub fn vault_codec_overflow_table() -> String {
+ crate::vault_codec::OVERFLOW_TABLE.to_string()
+}
+
/// Generate a fresh 32-byte per-manifest blob-hashing salt (lowercase hex).
#[uniffi::export]
pub fn vault_codec_generate_manifest_salt() -> String {
@@ -358,7 +346,7 @@ pub fn vault_codec_extract_encryption_key_for_public_key(manifest_json: String,
// Argon2id Key Derivation Functions
// ═══════════════════════════════════════════════════════════════════════════════
-pub use crate::argon2::Argon2Error;
+pub use crate::crypto::argon2::Argon2Error;
/// Derive a key from a password using Argon2id.
///
@@ -371,7 +359,7 @@ pub use crate::argon2::Argon2Error;
/// The derived key as 32 bytes
#[uniffi::export]
pub fn argon2_derive_key(password: String, salt: String, encryption_settings: String) -> Result<Vec<u8>, Argon2Error> {
- crate::argon2::argon2_derive_key_from_settings(&password, &salt, &encryption_settings)
+ crate::crypto::argon2::argon2_derive_key_from_settings(&password, &salt, &encryption_settings)
}
/// Derive a key from a password using Argon2id, taking the password and salt as raw bytes.
@@ -388,21 +376,21 @@ pub fn argon2_derive_key(password: String, salt: String, encryption_settings: St
/// The derived key as 32 bytes
#[uniffi::export]
pub fn argon2_derive_key_bytes(password: Vec<u8>, salt: Vec<u8>, encryption_settings: String) -> Result<Vec<u8>, Argon2Error> {
- let params = crate::argon2::Argon2Params::from_settings_json(&encryption_settings)?;
- crate::argon2::argon2_derive_key(&password, &salt, params)
+ let params = crate::crypto::argon2::Argon2Params::from_settings_json(&encryption_settings)?;
+ crate::crypto::argon2::argon2_derive_key(&password, &salt, params)
}
// ═══════════════════════════════════════════════════════════════════════════════
// SRP (Secure Remote Password) Functions
// ═══════════════════════════════════════════════════════════════════════════════
-pub use crate::srp::{SrpEphemeral, SrpSession, SrpError};
+pub use crate::crypto::srp::{SrpEphemeral, SrpSession, SrpError};
/// Generate a cryptographic salt for SRP.
/// Returns a 32-byte random salt as an uppercase hex string.
#[uniffi::export]
pub fn srp_generate_salt() -> String {
- crate::srp::srp_generate_salt()
+ crate::crypto::srp::srp_generate_salt()
}
/// Derive the SRP private key (x) from credentials.
@@ -420,7 +408,7 @@ pub fn srp_derive_private_key(
identity: String,
password_hash: String,
) -> Result<String, SrpError> {
- crate::srp::srp_derive_private_key(&salt, &identity, &password_hash)
+ crate::crypto::srp::srp_derive_private_key(&salt, &identity, &password_hash)
}
/// Derive the SRP verifier (v) from a private key.
@@ -432,14 +420,14 @@ pub fn srp_derive_private_key(
/// Verifier as uppercase hex string (for registration)
#[uniffi::export]
pub fn srp_derive_verifier(private_key: String) -> Result<String, SrpError> {
- crate::srp::srp_derive_verifier(&private_key)
+ crate::crypto::srp::srp_derive_verifier(&private_key)
}
/// Generate a client ephemeral key pair.
/// Returns a pair of public (A) and secret (a) values as uppercase hex strings.
#[uniffi::export]
pub fn srp_generate_ephemeral() -> SrpEphemeral {
- crate::srp::srp_generate_ephemeral()
+ crate::crypto::srp::srp_generate_ephemeral()
}
/// Derive the client session from server response.
@@ -461,7 +449,7 @@ pub fn srp_derive_session(
identity: String,
private_key: String,
) -> Result<SrpSession, SrpError> {
- crate::srp::srp_derive_session(&client_secret, &server_public, &salt, &identity, &private_key)
+ crate::crypto::srp::srp_derive_session(&client_secret, &server_public, &salt, &identity, &private_key)
}
/// Generate a server ephemeral key pair.
@@ -473,7 +461,7 @@ pub fn srp_derive_session(
/// Ephemeral containing public (B) and secret (b) as uppercase hex strings
#[uniffi::export]
pub fn srp_generate_ephemeral_server(verifier: String) -> Result<SrpEphemeral, SrpError> {
- crate::srp::srp_generate_ephemeral_server(&verifier)
+ crate::crypto::srp::srp_generate_ephemeral_server(&verifier)
}
/// Derive and verify the server session from client response.
@@ -497,7 +485,7 @@ pub fn srp_derive_session_server(
verifier: String,
client_proof: String,
) -> Result<Option<SrpSession>, SrpError> {
- crate::srp::srp_derive_session_server(
+ crate::crypto::srp::srp_derive_session_server(
&server_secret,
&client_public,
&salt,
@@ -519,24 +507,10 @@ mod tests {
assert!(names.contains(&"Settings".to_string()));
assert!(names.contains(&"ItemStats".to_string()));
assert!(names.contains(&"EncryptionKeys".to_string()));
- assert!(!names.contains(&crate::vault_codec::OVERFLOW_TABLE.to_string()), "overflow carrier is not in the merge input; the server base owns it");
+ assert!(!names.contains(&crate::vault_codec::OVERFLOW_TABLE.to_string()), "the overflow carrier is not synced as a table of its own; it rides inside the manifest");
assert_eq!(names.len(), 14);
}
- #[test]
- fn test_merge_vaults_json() {
- let input = r#"{
- "local_tables": [{"name": "Items", "records": []}],
- "server_tables": [{"name": "Items", "records": []}]
- }"#;
-
- let result = merge_vaults_json(input.to_string());
- assert!(result.is_ok());
-
- let output: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
- assert_eq!(output["success"], true);
- }
-
#[test]
fn test_prune_vault_json() {
let input = r#"{
@@ -566,3 +540,87 @@ mod tests {
assert_eq!(extract_root_domain("github.com".to_string()), "github.com");
}
}
+
+// ═══════════════════════════════════════════════════════════════════════════════
+// Crypto
+// ═══════════════════════════════════════════════════════════════════════════════
+
+/// AES-256-GCM encrypt bytes with a base64 key. Returns base64 of `IV | ciphertext | tag`.
+#[uniffi::export]
+pub fn aes_gcm_encrypt(plaintext: Vec<u8>, key_base64: String) -> Result<String, VaultError> {
+ crate::crypto::symmetric_encrypt_bytes(&plaintext, &key_base64)
+}
+
+/// AES-256-GCM decrypt base64 `IV | ciphertext | tag` with a base64 key.
+#[uniffi::export]
+pub fn aes_gcm_decrypt(base64_ciphertext: String, key_base64: String) -> Result<Vec<u8>, VaultError> {
+ let bytes = crate::crypto::aes_gcm::decode_base64(&base64_ciphertext)?;
+ crate::crypto::symmetric_decrypt_bytes(&bytes, &key_base64)
+}
+
+/// Unwrap a wrapped key (base64 of `IV | ciphertext | tag`) with a base64 key. Returns the key as base64.
+#[uniffi::export]
+pub fn unwrap_key(wrapped_key_base64: String, wrapping_key_base64: String) -> Result<String, VaultError> {
+ // The caller owns the copy it gets across the FFI boundary; nothing here can wipe that one.
+ Ok(crate::crypto::unwrap_key(&wrapped_key_base64, &wrapping_key_base64)?.to_string())
+}
+
+/// Wrap a base64 key with another base64 key.
+#[uniffi::export]
+pub fn wrap_key(key_base64: String, wrapping_key_base64: String) -> Result<String, VaultError> {
+ crate::crypto::wrap_key(&key_base64, &wrapping_key_base64)
+}
+
+/// Generate an RSA-OAEP-256 key pair. Output: `RsaKeyPair` JSON (`publicKey`, `privateKey` as JWK strings).
+#[uniffi::export]
+pub fn rsa_generate_key_pair_json() -> Result<String, VaultError> {
+ Ok(serde_json::to_string(&crate::crypto::generate_rsa_key_pair()?)?)
+}
+
+/// RSA-OAEP-256 encrypt bytes for a JWK public key. Returns base64 ciphertext.
+#[uniffi::export]
+pub fn rsa_encrypt(plaintext: Vec<u8>, public_key_jwk: String) -> Result<String, VaultError> {
+ crate::crypto::encrypt_with_public_key(&plaintext, &public_key_jwk)
+}
+
+/// RSA-OAEP-256 decrypt base64 ciphertext with a JWK private key.
+#[uniffi::export]
+pub fn rsa_decrypt(base64_ciphertext: String, private_key_jwk: String) -> Result<Vec<u8>, VaultError> {
+ crate::crypto::decrypt_with_private_key(&base64_ciphertext, &private_key_jwk)
+}
+
+/// Create a new account key hierarchy under a base64 KEK. Output: `AccountKeyHierarchy` JSON.
+#[uniffi::export]
+pub fn create_account_key_hierarchy_json(kek_base64: String) -> Result<String, VaultError> {
+ Ok(serde_json::to_string(&crate::crypto::create_account_key_hierarchy(&kek_base64)?)?)
+}
+
+// ═══════════════════════════════════════════════════════════════════════════════
+// Vault sync engine
+// ═══════════════════════════════════════════════════════════════════════════════
+
+/// One engine operation. The host loops on `next_command` / `resume` until the command is `done`; see the
+/// `vault_sync` module docs for the command and response shapes.
+#[derive(uniffi::Object)]
+pub struct VaultSyncSession {
+ inner: crate::vault_sync::SyncSession,
+}
+
+#[uniffi::export]
+impl VaultSyncSession {
+ /// Start an operation from its `SyncRequest` JSON.
+ #[uniffi::constructor]
+ pub fn new(request_json: String) -> Result<std::sync::Arc<Self>, VaultError> {
+ Ok(std::sync::Arc::new(Self { inner: crate::vault_sync::SyncSession::new(&request_json)? }))
+ }
+
+ /// The next command for the host, as JSON.
+ pub fn next_command(&self) -> Result<String, VaultError> {
+ self.inner.next_command()
+ }
+
+ /// Hand the host's response to the last command back, as JSON.
+ pub fn resume(&self, response_json: String) -> Result<(), VaultError> {
+ self.inner.resume(&response_json)
+ }
+}