Skip to content

armgit / ente

Public Imported from GitHub
0

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

Move auth from core into the accounts crate

Manav Rathi61aeb7be2f1e
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 9ae6aca003..f4dda65bf7 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2291,15 +2291,20 @@ name = "ente-accounts"
version = "0.0.0"
dependencies = [
"base64 0.22.1",
+ "bip39",
"ente-core",
"ente-test-support",
+ "getrandom 0.2.17",
+ "hex",
"hmac 0.13.0",
"mockito",
+ "rand_core 0.6.4",
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.0",
"srp",
+ "subtle",
"thiserror 2.0.18",
"tokio",
"urlencoding",
@@ -2344,14 +2349,12 @@ version = "0.0.0"
dependencies = [
"argon2",
"base64 0.22.1",
- "bip39",
"blake2b_simd",
"bytes",
"crypto_secretstream",
"futures-core",
"getrandom 0.2.17",
"gloo-timers",
- "hex",
"log",
"md-5 0.11.0",
"mockito",
@@ -2360,8 +2363,6 @@ dependencies = [
"salsa20",
"serde",
"serde_json",
- "sha2 0.11.0",
- "srp",
"subtle",
"thiserror 2.0.18",
"tokio",
@@ -2560,6 +2561,7 @@ dependencies = [
name = "ente-wasm"
version = "0.0.0"
dependencies = [
+ "ente-accounts",
"ente-contacts",
"ente-core",
"js-sys",
@@ -2591,6 +2593,7 @@ dependencies = [
name = "ente_rust"
version = "0.0.0"
dependencies = [
+ "ente-accounts",
"ente-contacts",
"ente-core",
"flutter_rust_bridge",
diff --git a/rust/apps/cli/Cargo.toml b/rust/apps/cli/Cargo.toml
index 802f6cbdab..64ae11bf21 100644
--- a/rust/apps/cli/Cargo.toml
+++ b/rust/apps/cli/Cargo.toml
@@ -14,7 +14,7 @@ museum = []
# CLI
clap = { version = "4.5", features = ["derive", "env"] }
ente-accounts.workspace = true
-ente-core = { workspace = true, features = ["srp"] }
+ente-core.workspace = true
ente-paste.workspace = true
serde.workspace = true
serde_json.workspace = true
diff --git a/rust/apps/cli/src/api/models.rs b/rust/apps/cli/src/api/models.rs
index 54d9fce47f..0980c1aca7 100644
--- a/rust/apps/cli/src/api/models.rs
+++ b/rust/apps/cli/src/api/models.rs
@@ -16,9 +16,9 @@ pub struct SrpAttributes {
#[serde(rename = "srpSalt")]
pub srp_salt: String,
#[serde(rename = "memLimit")]
- pub mem_limit: i32,
+ pub mem_limit: u32,
#[serde(rename = "opsLimit")]
- pub ops_limit: i32,
+ pub ops_limit: u32,
#[serde(rename = "kekSalt")]
pub kek_salt: String,
#[serde(rename = "isEmailMFAEnabled", default = "default_email_mfa_enabled")]
@@ -67,8 +67,8 @@ pub struct KeyAttributes {
pub public_key: String,
pub encrypted_secret_key: String,
pub secret_key_decryption_nonce: String,
- pub mem_limit: i32,
- pub ops_limit: i32,
+ pub mem_limit: u32,
+ pub ops_limit: u32,
pub master_key_encrypted_with_recovery_key: Option<String>,
pub master_key_decryption_nonce: Option<String>,
pub recovery_key_encrypted_with_master_key: Option<String>,
diff --git a/rust/apps/cli/src/models/error.rs b/rust/apps/cli/src/models/error.rs
index 33a5860960..8664f316b2 100644
--- a/rust/apps/cli/src/models/error.rs
+++ b/rust/apps/cli/src/models/error.rs
@@ -1,5 +1,6 @@
use ente_accounts::Error as AccountsError;
-use ente_core::{auth::AuthError, crypto};
+use ente_accounts::auth::AuthError;
+use ente_core::crypto;
use thiserror::Error;
#[derive(Error, Debug)]
diff --git a/rust/apps/ensu/src-tauri/src/commands/crypto.rs b/rust/apps/ensu/src-tauri/src/commands/crypto.rs
index 0c992bb18b..83810b836b 100644
--- a/rust/apps/ensu/src-tauri/src/commands/crypto.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/crypto.rs
@@ -9,7 +9,6 @@ impl From<crypto::Error> for ApiError {
let code = match &e {
E::Base64Decode(_) => "base64_decode",
- E::HexDecode(_) => "hex_decode",
E::InvalidKeyLength { .. } => "invalid_key_length",
E::InvalidNonceLength { .. } => "invalid_nonce_length",
E::InvalidSaltLength { .. } => "invalid_salt_length",
diff --git a/rust/bindings/frb/ente-rust/Cargo.toml b/rust/bindings/frb/ente-rust/Cargo.toml
index f7026a08dd..dfec2e64dd 100644
--- a/rust/bindings/frb/ente-rust/Cargo.toml
+++ b/rust/bindings/frb/ente-rust/Cargo.toml
@@ -7,6 +7,7 @@ crate-type = ["cdylib", "staticlib"]
[dependencies]
flutter_rust_bridge = "=2.12.0"
+ente-accounts.workspace = true
ente-contacts.workspace = true
ente-core.workspace = true
diff --git a/rust/bindings/frb/ente-rust/src/api/contacts.rs b/rust/bindings/frb/ente-rust/src/api/contacts.rs
index e9a91b8110..9a53cfbf04 100644
--- a/rust/bindings/frb/ente-rust/src/api/contacts.rs
+++ b/rust/bindings/frb/ente-rust/src/api/contacts.rs
@@ -2,6 +2,7 @@
use std::sync::Arc;
+use ente_accounts::auth::KeyAttributes as CoreKeyAttributes;
use ente_contacts::{
AttachmentType as CoreAttachmentType, ContactData as CoreContactData,
ContactRecord as CoreContactRecord, ContactsCtx as CoreContactsCtx,
@@ -13,7 +14,6 @@ use ente_contacts::{
LegacyKitVariant as CoreLegacyKitVariant, OpenContactsCtxInput as CoreOpenContactsCtxInput,
RootKeySource as CoreRootKeySource, WrappedRootContactKey as CoreWrappedRootContactKey,
};
-use ente_core::auth::KeyAttributes as CoreKeyAttributes;
use flutter_rust_bridge::frb;
#[frb]
@@ -97,9 +97,9 @@ pub struct AccountKeyAttributes {
/// Nonce for secret key decryption (base64).
pub secret_key_decryption_nonce: String,
/// Argon2 memory limit.
- pub mem_limit: Option<u32>,
+ pub mem_limit: u32,
/// Argon2 ops limit.
- pub ops_limit: Option<u32>,
+ pub ops_limit: u32,
/// Master key encrypted with recovery key (base64).
pub master_key_encrypted_with_recovery_key: Option<String>,
/// Nonce for master key decryption with recovery key (base64).
@@ -114,6 +114,7 @@ impl From<AccountKeyAttributes> for CoreKeyAttributes {
fn from(value: AccountKeyAttributes) -> Self {
Self {
kek_salt: value.kek_salt,
+ kek_hash: None,
encrypted_key: value.encrypted_key,
key_decryption_nonce: value.key_decryption_nonce,
public_key: value.public_key,
diff --git a/rust/bindings/wasm/ente-wasm/Cargo.toml b/rust/bindings/wasm/ente-wasm/Cargo.toml
index f578b94376..188faa9c6c 100644
--- a/rust/bindings/wasm/ente-wasm/Cargo.toml
+++ b/rust/bindings/wasm/ente-wasm/Cargo.toml
@@ -6,8 +6,9 @@ edition = "2024"
crate-type = ["cdylib"]
[dependencies]
+ente-accounts.workspace = true
ente-contacts.workspace = true
-ente-core = { workspace = true, features = ["srp"] }
+ente-core.workspace = true
md-5 = "0.11"
js-sys = "0.3"
serde.workspace = true
diff --git a/rust/bindings/wasm/ente-wasm/src/auth.rs b/rust/bindings/wasm/ente-wasm/src/auth.rs
index d482d80666..f6d77e8c03 100644
--- a/rust/bindings/wasm/ente-wasm/src/auth.rs
+++ b/rust/bindings/wasm/ente-wasm/src/auth.rs
@@ -1,6 +1,7 @@
//! WASM bindings for authentication and account crypto.
-use ente_core::{auth as core_auth, crypto as core_crypto};
+use ente_accounts::auth as core_auth;
+use ente_core::crypto as core_crypto;
use serde_wasm_bindgen as swb;
use wasm_bindgen::prelude::*;
diff --git a/rust/bindings/wasm/ente-wasm/src/contacts.rs b/rust/bindings/wasm/ente-wasm/src/contacts.rs
index 00c01911e1..bce9f1639f 100644
--- a/rust/bindings/wasm/ente-wasm/src/contacts.rs
+++ b/rust/bindings/wasm/ente-wasm/src/contacts.rs
@@ -1,10 +1,11 @@
//! WASM bindings for contacts sync and attachment reads.
+use ente_accounts::auth::KeyAttributes;
use ente_contacts::{
ContactsCtx, ContactsError as CoreContactsError, LegacyContactState, OpenContactsCtxInput,
RootKeySource, WrappedRootContactKey,
};
-use ente_core::{auth::KeyAttributes, crypto};
+use ente_core::crypto;
use js_sys::{Object, Reflect};
use serde::{Deserialize, Serialize};
use serde_wasm_bindgen as swb;
diff --git a/rust/bindings/wasm/ente-wasm/src/crypto.rs b/rust/bindings/wasm/ente-wasm/src/crypto.rs
index 46e36d88d5..3e1ef71072 100644
--- a/rust/bindings/wasm/ente-wasm/src/crypto.rs
+++ b/rust/bindings/wasm/ente-wasm/src/crypto.rs
@@ -32,7 +32,6 @@ impl From<core_crypto::Error> for CryptoError {
let code = match &e {
E::Base64Decode(_) => "base64_decode",
- E::HexDecode(_) => "hex_decode",
E::InvalidKeyLength { .. } => "invalid_key_length",
E::InvalidNonceLength { .. } => "invalid_nonce_length",
E::InvalidSaltLength { .. } => "invalid_salt_length",
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rs
index 9d5faf80ca..ea3995d5ce 100644
--- a/rust/bindings/wasm/space/src/space.rs
+++ b/rust/bindings/wasm/space/src/space.rs
@@ -52,7 +52,6 @@ impl From<CoreSpaceError> for WasmSpaceError {
CoreSpaceError::Http(HttpError::Network(_)) => ("network", None),
CoreSpaceError::Http(HttpError::Parse(_)) => ("parse", None),
CoreSpaceError::Crypto(_) => ("crypto", None),
- CoreSpaceError::Auth(_) => ("auth", None),
CoreSpaceError::InvalidInput(_) => ("invalid_input", None),
CoreSpaceError::MissingSecretKey => ("missing_secret_key", None),
CoreSpaceError::MissingFriendSealedSpaceKey => {
diff --git a/rust/crates/accounts/Cargo.toml b/rust/crates/accounts/Cargo.toml
index 906afa03d9..2ae143939e 100644
--- a/rust/crates/accounts/Cargo.toml
+++ b/rust/crates/accounts/Cargo.toml
@@ -6,11 +6,17 @@ edition = "2024"
museum = []
[dependencies]
-ente-core = { workspace = true, features = ["srp"] }
+ente-core.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
base64 = "0.22"
+bip39 = { version = "2", default-features = false, features = ["std"] }
+getrandom = { version = "0.2", features = ["js"] }
+hex = "0.4"
+sha2 = "0.11"
+srp = { version = "0.7.0-rc.3", default-features = false }
+subtle = "2"
uuid = { version = "1.11", features = ["js", "serde", "v4"] }
zeroize = { version = "1.8", features = ["derive"] }
urlencoding = "2.1"
@@ -19,7 +25,6 @@ urlencoding = "2.1"
ente-test-support.workspace = true
hmac = "0.13"
mockito = "1.6"
-sha2 = "0.11"
+rand_core = { version = "0.6", features = ["getrandom"] }
sha1 = "0.11"
-srp = { version = "0.7.0-rc.3", default-features = false }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
diff --git a/rust/crates/core/src/auth/api.rs b/rust/crates/accounts/src/auth/api.rs
similarity index 83%
rename from rust/crates/core/src/auth/api.rs
rename to rust/crates/accounts/src/auth/api.rs
index 6d7b7d7521..b40736867d 100644
--- a/rust/crates/core/src/auth/api.rs
+++ b/rust/crates/accounts/src/auth/api.rs
@@ -5,19 +5,12 @@
use std::fmt;
-#[cfg(feature = "srp")]
-use crate::crypto::Salt;
-use crate::crypto::{self, SecretVec, argon, kdf, sealed, secretbox};
-
-use super::{AuthError, KeyAttributes, Result, SrpAttributes};
-
-#[cfg(feature = "srp")]
-use super::srp::SrpSession;
-#[cfg(feature = "srp")]
+use ente_core::crypto::{self, Salt, SecretVec, argon, kdf, sealed, secretbox};
use sha2::Sha256;
-#[cfg(feature = "srp")]
use srp::ClientG4096;
+use super::{AuthError, KeyAttributes, Result, SrpAttributes};
+
/// Credentials derived from password for SRP authentication.
pub struct SrpCredentials {
/// Key encryption key (32 bytes) - used to decrypt master key after auth.
@@ -79,7 +72,6 @@ impl fmt::Debug for GeneratedKek {
}
/// Attributes needed to register or update SRP for a user.
-#[cfg(feature = "srp")]
pub struct GeneratedSrpSetup {
/// SRP salt bytes.
pub srp_salt: Vec<u8>,
@@ -89,7 +81,6 @@ pub struct GeneratedSrpSetup {
pub login_sub_key: SecretVec,
}
-#[cfg(feature = "srp")]
impl fmt::Debug for GeneratedSrpSetup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GeneratedSrpSetup")
@@ -191,14 +182,12 @@ fn generated_kek(derived: argon::DerivedKey) -> GeneratedKek {
}
/// Generate the SRP setup payload for a given KEK and SRP user ID.
-#[cfg(feature = "srp")]
pub fn generate_srp_setup(kek: &[u8], srp_user_id: &str) -> Result<GeneratedSrpSetup> {
let login_sub_key = kdf::derive_login_key(&crypto::Key::try_from_slice(kek)?);
generate_srp_setup_with_login_key(&login_sub_key, srp_user_id)
}
/// Generate the SRP setup payload from an already-derived login key.
-#[cfg(feature = "srp")]
pub fn generate_srp_setup_with_login_key(
login_key: &[u8],
srp_user_id: &str,
@@ -296,34 +285,6 @@ pub fn decrypt_secrets(
})
}
-/// Start an SRP session for password authentication.
-///
-/// This is a convenience function that:
-/// 1. Derives credentials from password
-/// 2. Creates an SRP session ready for the protocol
-///
-/// # Arguments
-/// * `password` - User's password
-/// * `srp_attrs` - SRP attributes from the server
-///
-/// # Returns
-/// * Tuple of (SrpSession, kek) - use session for SRP, keep kek for later decryption
-#[cfg(feature = "srp")]
-#[cfg_attr(not(test), allow(dead_code))]
-pub(crate) fn start_srp_session(
- password: &str,
- srp_attrs: &SrpAttributes,
-) -> Result<(SrpSession, SecretVec)> {
- let creds = derive_srp_credentials(password, srp_attrs)?;
-
- let srp_salt = crypto::decode_b64(&srp_attrs.srp_salt)
- .map_err(|e| AuthError::Decode(format!("srp_salt: {}", e)))?;
-
- let session = SrpSession::new(&srp_attrs.srp_user_id, &srp_salt, &creds.login_key)?;
-
- Ok((session, creds.kek))
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -336,10 +297,10 @@ mod tests {
generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap();
let srp_attrs = SrpAttributes {
- srp_user_id: "test-user".to_string(),
+ srp_user_id: uuid::Uuid::nil(),
srp_salt: crypto::encode_b64(&[0u8; 16]),
- mem_limit: gen_result.key_attributes.mem_limit.unwrap(),
- ops_limit: gen_result.key_attributes.ops_limit.unwrap(),
+ mem_limit: gen_result.key_attributes.mem_limit,
+ ops_limit: gen_result.key_attributes.ops_limit,
kek_salt: gen_result.key_attributes.kek_salt.clone(),
is_email_mfa_enabled: false,
};
@@ -371,8 +332,8 @@ mod tests {
let kek = derive_kek(
password,
&gen_result.key_attributes.kek_salt,
- gen_result.key_attributes.mem_limit.unwrap(),
- gen_result.key_attributes.ops_limit.unwrap(),
+ gen_result.key_attributes.mem_limit,
+ gen_result.key_attributes.ops_limit,
)
.unwrap();
@@ -409,8 +370,8 @@ mod tests {
let kek = derive_kek(
"wrong_password",
&gen_result.key_attributes.kek_salt,
- gen_result.key_attributes.mem_limit.unwrap(),
- gen_result.key_attributes.ops_limit.unwrap(),
+ gen_result.key_attributes.mem_limit,
+ gen_result.key_attributes.ops_limit,
)
.unwrap();
@@ -440,17 +401,10 @@ mod tests {
assert_eq!(generated.key.len(), 32);
assert_eq!(generated.salt.len(), 16);
- assert_eq!(
- generated.mem_limit,
- crate::crypto::argon::Params::INTERACTIVE.mem_limit
- );
- assert_eq!(
- generated.ops_limit,
- crate::crypto::argon::Params::INTERACTIVE.ops_limit
- );
+ assert_eq!(generated.mem_limit, argon::Params::INTERACTIVE.mem_limit);
+ assert_eq!(generated.ops_limit, argon::Params::INTERACTIVE.ops_limit);
}
- #[cfg(feature = "srp")]
#[test]
fn test_generate_srp_setup() {
let srp_setup = generate_srp_setup(&[1; 32], "test-user-id").unwrap();
@@ -460,7 +414,6 @@ mod tests {
assert!(!srp_setup.srp_verifier.is_empty());
}
- #[cfg(feature = "srp")]
#[test]
fn test_generate_srp_setup_with_login_key() {
let login_key = [1u8; 16];
@@ -470,26 +423,4 @@ mod tests {
assert_eq!(srp_setup.login_sub_key.as_ref(), login_key);
assert!(!srp_setup.srp_verifier.is_empty());
}
-
- #[cfg(feature = "srp")]
- #[test]
- fn test_start_srp_session() {
- let password = "test_password";
- let gen_result =
- generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap();
-
- let srp_attrs = SrpAttributes {
- srp_user_id: "test-user".to_string(),
- srp_salt: crypto::encode_b64(&[0u8; 16]),
- mem_limit: gen_result.key_attributes.mem_limit.unwrap(),
- ops_limit: gen_result.key_attributes.ops_limit.unwrap(),
- kek_salt: gen_result.key_attributes.kek_salt,
- is_email_mfa_enabled: false,
- };
-
- let (session, kek) = start_srp_session(password, &srp_attrs).unwrap();
-
- assert_eq!(kek.len(), 32);
- assert!(!session.public_a().is_empty());
- }
}
diff --git a/rust/crates/core/src/auth/key_gen.rs b/rust/crates/accounts/src/auth/key_gen.rs
similarity index 91%
rename from rust/crates/core/src/auth/key_gen.rs
rename to rust/crates/accounts/src/auth/key_gen.rs
index f2b00b55c5..fcbf60a877 100644
--- a/rust/crates/core/src/auth/key_gen.rs
+++ b/rust/crates/accounts/src/auth/key_gen.rs
@@ -1,6 +1,6 @@
//! Key generation for new account sign-up.
-use crate::crypto::{self, Key, SecretString, SecretVec, argon, kdf, secretbox};
+use ente_core::crypto::{self, Key, SecretString, SecretVec, argon, kdf, secretbox};
use super::{KeyAttributes, KeyGenResult, PrivateKeyAttributes, Result};
@@ -24,15 +24,8 @@ fn encrypt_to_b64(plaintext: &[u8], key: &Key) -> Result<(String, String)> {
))
}
-/// Generate all keys needed for a new account.
-///
-/// Uses sensitive (slow, secure) key derivation by default.
-/// For tests, use `generate_keys_with_strength` with `Interactive`.
-pub fn generate_keys(password: &str) -> Result<KeyGenResult> {
- generate_keys_with_strength(password, KeyDerivationStrength::Sensitive)
-}
-
-/// Generate all keys with specified derivation strength.
+/// Generate all keys needed for a new account, with the specified derivation
+/// strength.
pub fn generate_keys_with_strength(
password: &str,
strength: KeyDerivationStrength,
@@ -67,13 +60,14 @@ pub fn generate_keys_with_strength(
// Build key attributes for server
let key_attributes = KeyAttributes {
kek_salt: crypto::encode_b64(derived.salt.as_bytes()),
+ kek_hash: None,
encrypted_key: enc_key,
key_decryption_nonce: key_nonce,
public_key: crypto::encode_b64(public_key.as_bytes()),
encrypted_secret_key: enc_secret_key,
secret_key_decryption_nonce: secret_key_nonce,
- mem_limit: Some(derived.params.mem_limit),
- ops_limit: Some(derived.params.ops_limit),
+ mem_limit: derived.params.mem_limit,
+ ops_limit: derived.params.ops_limit,
master_key_encrypted_with_recovery_key: Some(enc_master_with_recovery),
master_key_decryption_nonce: Some(nonce_master_recovery),
recovery_key_encrypted_with_master_key: Some(enc_recovery_with_master),
@@ -83,7 +77,7 @@ pub fn generate_keys_with_strength(
// Build private key attributes for local storage
let private_key_attributes = PrivateKeyAttributes {
key: SecretString::new(crypto::encode_b64(master_key.as_bytes())),
- recovery_key: SecretString::new(crypto::encode_hex(recovery_key.as_bytes())),
+ recovery_key: SecretString::new(hex::encode(recovery_key.as_bytes())),
secret_key: SecretString::new(crypto::encode_b64(secret_key.as_bytes())),
};
@@ -132,10 +126,11 @@ pub fn generate_key_attributes_for_new_password_with_strength(
let key_attributes = KeyAttributes {
kek_salt: crypto::encode_b64(derived.salt.as_bytes()),
+ kek_hash: None,
encrypted_key: enc_key,
key_decryption_nonce: key_nonce,
- mem_limit: Some(derived.params.mem_limit),
- ops_limit: Some(derived.params.ops_limit),
+ mem_limit: derived.params.mem_limit,
+ ops_limit: derived.params.ops_limit,
public_key: existing_attributes.public_key.clone(),
encrypted_secret_key: existing_attributes.encrypted_secret_key.clone(),
secret_key_decryption_nonce: existing_attributes.secret_key_decryption_nonce.clone(),
@@ -164,7 +159,7 @@ pub fn create_new_recovery_key(
encrypt_to_b64(recovery_key.as_bytes(), &master_key_typed)?;
Ok((
- crypto::encode_hex(recovery_key.as_bytes()),
+ hex::encode(recovery_key.as_bytes()),
enc_master,
nonce_master,
enc_recovery,
@@ -175,7 +170,7 @@ pub fn create_new_recovery_key(
#[cfg(test)]
mod tests {
use super::*;
- use crate::crypto::Nonce;
+ use ente_core::crypto::Nonce;
// Typed-decrypt helper for byte-slice test material.
fn decrypt_raw(data: &[u8], nonce: &[u8], key: &[u8]) -> Vec<u8> {
@@ -236,7 +231,7 @@ mod tests {
#[test]
fn test_generate_keys_recovery_key_can_decrypt_master() {
let result = generate_test_keys("password").unwrap();
- let recovery_key = crypto::decode_hex(&result.private_key_attributes.recovery_key).unwrap();
+ let recovery_key = hex::decode(&*result.private_key_attributes.recovery_key).unwrap();
let encrypted = crypto::decode_b64(
result
@@ -283,7 +278,7 @@ mod tests {
.unwrap();
let decrypted = decrypt_raw(&encrypted, &nonce, &master_key);
- let original = crypto::decode_hex(&result.private_key_attributes.recovery_key).unwrap();
+ let original = hex::decode(&*result.private_key_attributes.recovery_key).unwrap();
assert_eq!(decrypted, original);
}
@@ -310,8 +305,8 @@ mod tests {
"new_password",
&salt,
argon::Params {
- mem_limit: new_attrs.mem_limit.unwrap(),
- ops_limit: new_attrs.ops_limit.unwrap(),
+ mem_limit: new_attrs.mem_limit,
+ ops_limit: new_attrs.ops_limit,
},
)
.unwrap();
@@ -329,7 +324,7 @@ mod tests {
assert_eq!(recovery_hex.len(), 64);
- let recovery_key = crypto::decode_hex(&recovery_hex).unwrap();
+ let recovery_key = hex::decode(&recovery_hex).unwrap();
let decrypted = decrypt_raw(
&crypto::decode_b64(&enc_master).unwrap(),
&crypto::decode_b64(&nonce_master).unwrap(),
diff --git a/rust/crates/accounts/src/auth/mod.rs b/rust/crates/accounts/src/auth/mod.rs
new file mode 100644
index 0000000000..c2531afcaf
--- /dev/null
+++ b/rust/crates/accounts/src/auth/mod.rs
@@ -0,0 +1,34 @@
+//! The account key hierarchy and login protocol.
+//!
+//! Key generation at sign-up, secret decryption at login, recovery keys, and
+//! the SRP handshake ([`SrpSession`]).
+
+mod api;
+mod key_gen;
+mod recovery;
+mod srp;
+mod types;
+
+pub use srp::SrpSession;
+
+// High-level API (recommended for applications)
+pub use api::{DecryptedSecrets, GeneratedKek, GeneratedSrpSetup, SrpCredentials};
+pub use api::{
+ decrypt_keys_only, decrypt_secrets, derive_kek, derive_srp_credentials,
+ generate_interactive_kek, generate_sensitive_kek, generate_srp_setup,
+ generate_srp_setup_with_login_key,
+};
+
+// Key generation (for signup)
+pub use key_gen::{
+ KeyDerivationStrength, create_new_recovery_key, generate_key_attributes_for_new_password,
+ generate_key_attributes_for_new_password_with_strength, generate_keys_with_strength,
+};
+
+// Recovery
+pub use recovery::{get_recovery_key, recovery_key_from_mnemonic_or_hex, recovery_key_to_mnemonic};
+
+// Types
+pub use types::{
+ AuthError, KeyAttributes, KeyGenResult, PrivateKeyAttributes, Result, SrpAttributes,
+};
diff --git a/rust/crates/accounts/src/auth/recovery.rs b/rust/crates/accounts/src/auth/recovery.rs
new file mode 100644
index 0000000000..7b2bf622f4
--- /dev/null
+++ b/rust/crates/accounts/src/auth/recovery.rs
@@ -0,0 +1,138 @@
+//! Account recovery using recovery key.
+
+use bip39::{Language, Mnemonic};
+
+use ente_core::crypto::{self, SecretVec, secretbox};
+
+use super::{AuthError, KeyAttributes, Result};
+
+/// Get the recovery key from stored encrypted form.
+pub fn get_recovery_key(master_key: &[u8], attributes: &KeyAttributes) -> Result<String> {
+ let encrypted_recovery_key = attributes
+ .recovery_key_encrypted_with_master_key
+ .as_ref()
+ .ok_or(AuthError::MissingField(
+ "recovery_key_encrypted_with_master_key",
+ ))?;
+
+ let nonce = attributes
+ .recovery_key_decryption_nonce
+ .as_ref()
+ .ok_or(AuthError::MissingField("recovery_key_decryption_nonce"))?;
+
+ let encrypted_bytes = crypto::decode_b64(encrypted_recovery_key)
+ .map_err(|e| AuthError::Decode(format!("recovery_key_encrypted_with_master_key: {}", e)))?;
+ let nonce_bytes = crypto::decode_b64(nonce)
+ .map_err(|e| AuthError::Decode(format!("recovery_key_decryption_nonce: {}", e)))?;
+
+ let recovery_key = SecretVec::new(
+ secretbox::decrypt(
+ &encrypted_bytes,
+ &crypto::Nonce::try_from_slice(&nonce_bytes)?,
+ &crypto::Key::try_from_slice(master_key)?,
+ )
+ .map_err(|_| AuthError::InvalidKeyAttributes)?,
+ );
+
+ Ok(hex::encode(&recovery_key))
+}
+
+/// Convert a user-provided recovery key mnemonic or hex string into raw bytes.
+///
+/// The mnemonic form must be a 24-word English BIP-39 phrase. The legacy hex
+/// form is still accepted for compatibility.
+pub fn recovery_key_from_mnemonic_or_hex(recovery_key_mnemonic_or_hex: &str) -> Result<SecretVec> {
+ let trimmed_input = recovery_key_mnemonic_or_hex
+ .split_whitespace()
+ .map(str::trim)
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join(" ");
+
+ let recovery_key = SecretVec::new(if trimmed_input.contains(' ') {
+ if trimmed_input.split(' ').count() != 24 {
+ return Err(AuthError::IncorrectRecoveryKey);
+ }
+
+ let mnemonic = Mnemonic::parse_in_normalized(Language::English, &trimmed_input)
+ .map_err(|_| AuthError::IncorrectRecoveryKey)?;
+ mnemonic.to_entropy()
+ } else {
+ hex::decode(&trimmed_input).map_err(|_| AuthError::IncorrectRecoveryKey)?
+ });
+
+ if recovery_key.len() != 32 {
+ return Err(AuthError::IncorrectRecoveryKey);
+ }
+
+ Ok(recovery_key)
+}
+
+/// Convert a base64-encoded recovery key into its 24-word English mnemonic.
+pub fn recovery_key_to_mnemonic(recovery_key_b64: &str) -> Result<String> {
+ let recovery_key = SecretVec::new(
+ crypto::decode_b64(recovery_key_b64)
+ .map_err(|e| AuthError::Decode(format!("recovery_key: {}", e)))?,
+ );
+
+ if recovery_key.len() != 32 {
+ return Err(AuthError::IncorrectRecoveryKey);
+ }
+
+ Mnemonic::from_entropy_in(Language::English, &recovery_key)
+ .map(|mnemonic| mnemonic.to_string())
+ .map_err(|e| AuthError::InvalidKey(format!("recovery_key: {}", e)))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::auth::{KeyDerivationStrength, generate_keys_with_strength};
+
+ fn generate_test_keys(password: &str) -> super::super::KeyGenResult {
+ generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap()
+ }
+
+ #[test]
+ fn test_get_recovery_key() {
+ let gen_result = generate_test_keys("password");
+ let master_key = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();
+
+ let recovered = get_recovery_key(&master_key, &gen_result.key_attributes).unwrap();
+ assert_eq!(
+ recovered,
+ gen_result.private_key_attributes.recovery_key.as_ref()
+ );
+ }
+
+ #[test]
+ fn test_recovery_key_mnemonic_roundtrip() {
+ let gen_result = generate_test_keys("password");
+ let master_key = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();
+ let recovery_key_hex = get_recovery_key(&master_key, &gen_result.key_attributes).unwrap();
+ let recovery_key_b64 = crypto::encode_b64(&hex::decode(&recovery_key_hex).unwrap());
+
+ let mnemonic = recovery_key_to_mnemonic(&recovery_key_b64).unwrap();
+ let decoded = recovery_key_from_mnemonic_or_hex(&mnemonic).unwrap();
+
+ assert_eq!(
+ decoded.as_ref(),
+ hex::decode(&recovery_key_hex).unwrap().as_slice()
+ );
+ }
+
+ #[test]
+ fn test_recovery_key_from_hex_accepts_legacy_format() {
+ let gen_result = generate_test_keys("password");
+ let decoded =
+ recovery_key_from_mnemonic_or_hex(&gen_result.private_key_attributes.recovery_key)
+ .unwrap();
+
+ assert_eq!(
+ decoded.as_ref(),
+ hex::decode(&*gen_result.private_key_attributes.recovery_key)
+ .unwrap()
+ .as_slice()
+ );
+ }
+}
diff --git a/rust/crates/core/src/auth/srp.rs b/rust/crates/accounts/src/auth/srp.rs
similarity index 99%
rename from rust/crates/core/src/auth/srp.rs
rename to rust/crates/accounts/src/auth/srp.rs
index 9e29064f87..624232e02e 100644
--- a/rust/crates/core/src/auth/srp.rs
+++ b/rust/crates/accounts/src/auth/srp.rs
@@ -4,7 +4,7 @@
//! step ordering (e.g. calling set_b before compute_m1). Callers only need to
//! exchange the public value and proofs with the server.
-use crate::crypto::SecretVec;
+use ente_core::crypto::SecretVec;
use sha2::{Digest, Sha256};
use srp::ClientG4096;
use subtle::ConstantTimeEq;
diff --git a/rust/crates/core/src/auth/types.rs b/rust/crates/accounts/src/auth/types.rs
similarity index 83%
rename from rust/crates/core/src/auth/types.rs
rename to rust/crates/accounts/src/auth/types.rs
index 35dddb3b30..1fc2903365 100644
--- a/rust/crates/core/src/auth/types.rs
+++ b/rust/crates/accounts/src/auth/types.rs
@@ -3,8 +3,9 @@
use std::fmt;
use serde::{Deserialize, Serialize};
+use uuid::Uuid;
-use crate::crypto::{SecretString, SecretVec};
+use ente_core::crypto::{SecretString, SecretVec};
/// Attributes stored on server for key derivation and encrypted keys.
#[derive(Clone, Serialize, Deserialize)]
@@ -12,6 +13,9 @@ use crate::crypto::{SecretString, SecretVec};
pub struct KeyAttributes {
/// Salt for deriving key-encryption-key from password (base64)
pub kek_salt: String,
+ /// Legacy KEK hash, present only on old accounts (base64)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub kek_hash: Option<String>,
/// Master key encrypted with KEK (base64)
pub encrypted_key: String,
/// Nonce for master key decryption (base64)
@@ -23,11 +27,9 @@ pub struct KeyAttributes {
/// Nonce for secret key decryption (base64)
pub secret_key_decryption_nonce: String,
/// Argon2 memory limit
- #[serde(skip_serializing_if = "Option::is_none")]
- pub mem_limit: Option<u32>,
+ pub mem_limit: u32,
/// Argon2 ops limit
- #[serde(skip_serializing_if = "Option::is_none")]
- pub ops_limit: Option<u32>,
+ pub ops_limit: u32,
/// Master key encrypted with recovery key (base64)
#[serde(skip_serializing_if = "Option::is_none")]
pub master_key_encrypted_with_recovery_key: Option<String>,
@@ -46,6 +48,7 @@ impl fmt::Debug for KeyAttributes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeyAttributes")
.field("kek_salt", &"[REDACTED]")
+ .field("kek_hash", &self.kek_hash.as_ref().map(|_| "[REDACTED]"))
.field("encrypted_key", &"[REDACTED]")
.field("key_decryption_nonce", &"[REDACTED]")
.field("public_key", &"[REDACTED]")
@@ -128,40 +131,17 @@ impl fmt::Debug for KeyGenResult {
}
}
-/// Result of successful login/decryption.
-pub struct LoginResult {
- /// Decrypted master key
- pub master_key: SecretVec,
- /// Decrypted X25519 secret key
- pub secret_key: SecretVec,
- /// Decrypted auth token
- pub token: SecretVec,
- /// Key-encryption-key (for SRP setup if needed)
- pub key_encryption_key: SecretVec,
-}
-
-impl fmt::Debug for LoginResult {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("LoginResult")
- .field("master_key", &"[REDACTED]")
- .field("secret_key", &"[REDACTED]")
- .field("token", &"[REDACTED]")
- .field("key_encryption_key", &"[REDACTED]")
- .finish()
- }
-}
-
fn default_email_mfa_enabled() -> bool {
true
}
-/// SRP attributes received from server.
+/// SRP attributes received from server (`/users/srp/attributes`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SrpAttributes {
- /// SRP user ID (UUID)
+ /// SRP user ID
#[serde(rename = "srpUserID")]
- pub srp_user_id: String,
+ pub srp_user_id: Uuid,
/// SRP salt (base64)
pub srp_salt: String,
/// Argon2 memory limit
@@ -200,7 +180,7 @@ pub enum AuthError {
/// Underlying cryptographic operation failed.
#[error("Crypto error: {0}")]
- Crypto(#[from] crate::crypto::Error),
+ Crypto(#[from] ente_core::crypto::Error),
/// Failed to decode base64 or hex data.
#[error("Decode error: {0}")]
@@ -225,13 +205,14 @@ mod tests {
fn sample_key_attributes() -> KeyAttributes {
KeyAttributes {
kek_salt: "server-kek-salt".to_string(),
+ kek_hash: Some("server-kek-hash".to_string()),
encrypted_key: "server-encrypted-key".to_string(),
key_decryption_nonce: "server-key-nonce".to_string(),
public_key: "server-public-key".to_string(),
encrypted_secret_key: "server-encrypted-secret-key".to_string(),
secret_key_decryption_nonce: "server-secret-key-nonce".to_string(),
- mem_limit: Some(1),
- ops_limit: Some(2),
+ mem_limit: 1,
+ ops_limit: 2,
master_key_encrypted_with_recovery_key: None,
master_key_decryption_nonce: None,
recovery_key_encrypted_with_master_key: None,
@@ -246,13 +227,14 @@ mod tests {
let debug = format!("{attrs:?}");
assert!(debug.contains("[REDACTED]"));
assert!(!debug.contains("server-kek-salt"));
+ assert!(!debug.contains("server-kek-hash"));
assert!(!debug.contains("server-encrypted-key"));
assert!(!debug.contains("server-key-nonce"));
assert!(!debug.contains("server-public-key"));
assert!(!debug.contains("server-encrypted-secret-key"));
assert!(!debug.contains("server-secret-key-nonce"));
- assert!(debug.contains("Some(1)"));
- assert!(debug.contains("Some(2)"));
+ assert!(debug.contains("mem_limit: 1"));
+ assert!(debug.contains("ops_limit: 2"));
}
#[test]
@@ -283,21 +265,4 @@ mod tests {
assert!(!debug.contains("server-secret-key-nonce"));
assert!(debug.contains("key_attributes"));
}
-
- #[test]
- fn test_login_result_debug_redacts_secret_material() {
- let result = LoginResult {
- master_key: SecretVec::new(vec![1, 2, 3]),
- secret_key: SecretVec::new(vec![4, 5, 6]),
- token: SecretVec::new(vec![7, 8, 9]),
- key_encryption_key: SecretVec::new(vec![10, 11, 12]),
- };
-
- let debug = format!("{result:?}");
- assert!(debug.contains("[REDACTED]"));
- assert!(!debug.contains("[1, 2, 3]"));
- assert!(!debug.contains("[4, 5, 6]"));
- assert!(!debug.contains("[7, 8, 9]"));
- assert!(!debug.contains("[10, 11, 12]"));
- }
}
diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rs
index 58a322e695..c8459a207f 100644
--- a/rust/crates/accounts/src/client.rs
+++ b/rust/crates/accounts/src/client.rs
@@ -2,12 +2,12 @@
use base64::{Engine, engine::general_purpose::STANDARD};
use ente_core::{
- auth::{SrpAttributes as CoreSrpAttributes, SrpSession},
crypto::SecretVec,
http::{self, Api, ApiConfig, Auth, Http},
};
use crate::{
+ auth::{self, SrpSession},
error::{Error, Result},
models::{
AccountsTokenResponse, AuthResponse, CompleteSrpSetupRequest, CompleteSrpSetupResponse,
@@ -102,19 +102,13 @@ impl AccountsClient {
password: &str,
) -> Result<(AuthResponse, SecretVec)> {
let srp_attrs = self.get_srp_attributes(email).await?;
- let core_attrs = CoreSrpAttributes {
- srp_user_id: srp_attrs.srp_user_id.to_string(),
- srp_salt: srp_attrs.srp_salt.clone(),
- mem_limit: srp_attrs.mem_limit as u32,
- ops_limit: srp_attrs.ops_limit as u32,
- kek_salt: srp_attrs.kek_salt.clone(),
- is_email_mfa_enabled: srp_attrs.is_email_mfa_enabled,
- };
-
- let creds = ente_core::auth::derive_srp_credentials(password, &core_attrs)?;
+ let creds = auth::derive_srp_credentials(password, &srp_attrs)?;
let srp_salt = STANDARD.decode(&srp_attrs.srp_salt)?;
- let mut srp_session =
- SrpSession::new(&core_attrs.srp_user_id, &srp_salt, &creds.login_key)?;
+ let mut srp_session = SrpSession::new(
+ &srp_attrs.srp_user_id.to_string(),
+ &srp_salt,
+ &creds.login_key,
+ )?;
let a_pub = pad_left(&srp_session.public_a(), SRP_A_LEN);
let session = self
diff --git a/rust/crates/accounts/src/error.rs b/rust/crates/accounts/src/error.rs
index f78de187ca..8ba1f03f75 100644
--- a/rust/crates/accounts/src/error.rs
+++ b/rust/crates/accounts/src/error.rs
@@ -1,9 +1,11 @@
//! Shared error types for account flows.
use base64::DecodeError;
-use ente_core::{auth::AuthError, crypto, http};
+use ente_core::{crypto, http};
use thiserror::Error;
+use crate::auth::AuthError;
+
/// Result alias for the shared account crate.
pub type Result<T> = std::result::Result<T, Error>;
diff --git a/rust/crates/accounts/src/flow.rs b/rust/crates/accounts/src/flow.rs
index fea6134046..be0a7b6a57 100644
--- a/rust/crates/accounts/src/flow.rs
+++ b/rust/crates/accounts/src/flow.rs
@@ -7,19 +7,16 @@ use base64::{
Engine,
engine::general_purpose::{STANDARD, URL_SAFE},
};
-use ente_core::{
- auth::{
- self, DecryptedSecrets, GeneratedSrpSetup, KeyAttributes as CoreKeyAttributes,
- KeyDerivationStrength, derive_kek, generate_keys_with_strength,
- generate_srp_setup_with_login_key, get_recovery_key,
- },
- crypto::{self, SecretVec, secretbox},
-};
+use ente_core::crypto::{self, SecretVec, secretbox};
use std::fmt;
use uuid::Uuid;
use zeroize::Zeroizing;
use crate::{
+ auth::{
+ self, DecryptedSecrets, GeneratedSrpSetup, KeyDerivationStrength, derive_kek,
+ generate_keys_with_strength, generate_srp_setup_with_login_key, get_recovery_key,
+ },
client::AccountsClient,
error::{Error, Result},
models::{
@@ -342,8 +339,8 @@ where
let kek = derive_kek(
&params.password,
&srp_attrs.kek_salt,
- srp_attrs.mem_limit as u32,
- srp_attrs.ops_limit as u32,
+ srp_attrs.mem_limit,
+ srp_attrs.ops_limit,
)?;
(response, kek)
} else {
@@ -378,8 +375,7 @@ where
};
let recovery_key =
- get_recovery_key(&params.master_key, &to_core_key_attributes(&key_attributes))
- .map_err(Error::from)?;
+ get_recovery_key(&params.master_key, &key_attributes).map_err(Error::from)?;
let secret = self.client.setup_two_factor().await?;
self.ui
@@ -420,15 +416,14 @@ where
params: ChangePasswordParams,
key_derivation_strength: KeyDerivationStrength,
) -> Result<ChangePasswordResult> {
- let (updated_key_attributes_core, login_key) =
+ let (updated_key_attributes, login_key) =
auth::generate_key_attributes_for_new_password_with_strength(
&params.master_key,
- &to_core_key_attributes(&params.key_attributes),
+ &params.key_attributes,
&params.password,
key_derivation_strength,
)?;
- let updated_key_attributes = to_api_key_attributes(&updated_key_attributes_core);
let updated_key_attr = UpdatedKeyAttr::from(&updated_key_attributes);
let srp_user_id = Uuid::new_v4();
@@ -632,10 +627,9 @@ where
.key_attributes
.clone()
.ok_or_else(|| Error::AuthenticationFailed("No key attributes".into()))?;
- let core_key_attributes = to_core_key_attributes(&key_attributes);
- let secrets = decrypt_auth_response(&auth_response, &core_key_attributes, kek)?;
+ let secrets = decrypt_auth_response(&auth_response, &key_attributes, kek)?;
let public_key = crypto::decode_b64(&key_attributes.public_key)?;
- let recovery_key = get_recovery_key(&secrets.master_key, &core_key_attributes).ok();
+ let recovery_key = get_recovery_key(&secrets.master_key, &key_attributes).ok();
Ok(AuthenticatedAccount {
user_id: auth_response.id,
@@ -699,7 +693,7 @@ where
let srp_user_id = Uuid::new_v4();
let srp_setup =
generate_srp_setup_with_login_key(&key_gen_result.login_key, &srp_user_id.to_string())?;
- let key_attributes = to_api_key_attributes(&key_gen_result.key_attributes);
+ let key_attributes = key_gen_result.key_attributes.clone();
self.client
.set_user_key_attributes(key_attributes.clone())
@@ -963,49 +957,6 @@ fn pad_left(data: &[u8], len: usize) -> Vec<u8> {
padded
}
-fn to_core_key_attributes(attributes: &KeyAttributes) -> CoreKeyAttributes {
- CoreKeyAttributes {
- kek_salt: attributes.kek_salt.clone(),
- encrypted_key: attributes.encrypted_key.clone(),
- key_decryption_nonce: attributes.key_decryption_nonce.clone(),
- public_key: attributes.public_key.clone(),
- encrypted_secret_key: attributes.encrypted_secret_key.clone(),
- secret_key_decryption_nonce: attributes.secret_key_decryption_nonce.clone(),
- mem_limit: Some(attributes.mem_limit as u32),
- ops_limit: Some(attributes.ops_limit as u32),
- master_key_encrypted_with_recovery_key: attributes
- .master_key_encrypted_with_recovery_key
- .clone(),
- master_key_decryption_nonce: attributes.master_key_decryption_nonce.clone(),
- recovery_key_encrypted_with_master_key: attributes
- .recovery_key_encrypted_with_master_key
- .clone(),
- recovery_key_decryption_nonce: attributes.recovery_key_decryption_nonce.clone(),
- }
-}
-
-fn to_api_key_attributes(attributes: &CoreKeyAttributes) -> KeyAttributes {
- KeyAttributes {
- kek_salt: attributes.kek_salt.clone(),
- kek_hash: None,
- encrypted_key: attributes.encrypted_key.clone(),
- key_decryption_nonce: attributes.key_decryption_nonce.clone(),
- public_key: attributes.public_key.clone(),
- encrypted_secret_key: attributes.encrypted_secret_key.clone(),
- secret_key_decryption_nonce: attributes.secret_key_decryption_nonce.clone(),
- mem_limit: attributes.mem_limit.unwrap_or_default() as i32,
- ops_limit: attributes.ops_limit.unwrap_or_default() as i32,
- master_key_encrypted_with_recovery_key: attributes
- .master_key_encrypted_with_recovery_key
- .clone(),
- master_key_decryption_nonce: attributes.master_key_decryption_nonce.clone(),
- recovery_key_encrypted_with_master_key: attributes
- .recovery_key_encrypted_with_master_key
- .clone(),
- recovery_key_decryption_nonce: attributes.recovery_key_decryption_nonce.clone(),
- }
-}
-
fn decode_plain_token(token: &str) -> Result<SecretVec> {
let bytes = URL_SAFE
.decode(token)
@@ -1016,7 +967,7 @@ fn decode_plain_token(token: &str) -> Result<SecretVec> {
fn decrypt_auth_response(
auth_response: &AuthResponse,
- key_attributes: &CoreKeyAttributes,
+ key_attributes: &KeyAttributes,
kek: &[u8],
) -> Result<DecryptedSecrets> {
if let Some(encrypted_token) = auth_response.encrypted_token.as_deref() {
@@ -1073,7 +1024,8 @@ fn encrypt_two_factor_secret(
recovery_key_hex: &str,
code: &str,
) -> Result<EnableTwoFactorRequest> {
- let recovery_key = crypto::decode_hex(recovery_key_hex)?;
+ let recovery_key =
+ hex::decode(recovery_key_hex).map_err(|e| Error::Crypto(format!("recovery_key: {e}")))?;
let encrypted = secretbox::encrypt(
secret_code.as_bytes(),
&crypto::Key::try_from_slice(&recovery_key)?,
@@ -1256,7 +1208,7 @@ mod tests {
let key_gen =
auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
.unwrap();
- let key_attributes = to_api_key_attributes(&key_gen.key_attributes);
+ let key_attributes = key_gen.key_attributes.clone();
let encrypted_token = {
let public_key = crypto::decode_b64(&key_attributes.public_key).unwrap();
let sealed = crypto::sealed::seal(
@@ -1370,7 +1322,7 @@ mod tests {
let key_gen =
auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
.unwrap();
- let key_attributes = to_api_key_attributes(&key_gen.key_attributes);
+ let key_attributes = key_gen.key_attributes.clone();
let mut server = Server::new_async().await;
let mut ui = ScriptedUi::new();
@@ -1445,7 +1397,7 @@ mod tests {
let key_gen =
auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
.unwrap();
- let key_attributes = to_api_key_attributes(&key_gen.key_attributes);
+ let key_attributes = key_gen.key_attributes.clone();
let mut server = Server::new_async().await;
let mut ui = ScriptedUi::new();
@@ -1531,7 +1483,7 @@ mod tests {
let key_gen =
auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
.unwrap();
- let key_attributes = to_api_key_attributes(&key_gen.key_attributes);
+ let key_attributes = key_gen.key_attributes.clone();
let mut server = Server::new_async().await;
let mut ui = ScriptedUi::new();
@@ -1623,7 +1575,7 @@ mod tests {
.unwrap();
let recovery_key = key_gen.private_key_attributes.recovery_key.into_string();
let master_key = crypto::decode_b64(&key_gen.private_key_attributes.key).unwrap();
- let key_attributes = to_api_key_attributes(&key_gen.key_attributes);
+ let key_attributes = key_gen.key_attributes.clone();
let mut server = Server::new_async().await;
let mut ui = ScriptedUi::new();
@@ -1679,7 +1631,7 @@ mod tests {
auth::generate_keys_with_strength("pw", auth::KeyDerivationStrength::Interactive)
.unwrap();
let recovery_key_hex = key_gen.private_key_attributes.recovery_key.into_string();
- let expected_recovery_key = crypto::decode_hex(&recovery_key_hex).unwrap();
+ let expected_recovery_key = hex::decode(&recovery_key_hex).unwrap();
let mut server = Server::new_async().await;
let configure = server
@@ -1722,7 +1674,7 @@ mod tests {
let key_gen =
auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
.unwrap();
- let key_attributes = to_api_key_attributes(&key_gen.key_attributes);
+ let key_attributes = key_gen.key_attributes.clone();
let mut server = Server::new_async().await;
let mut ui = ScriptedUi::new();
@@ -1870,8 +1822,8 @@ mod tests {
.with_body_from_request(move |request| {
let payload: SetUserAttributesPayload = parse_request_body(request);
let key_attributes = payload.key_attributes;
- let mem_limit = u64::try_from(key_attributes.mem_limit).unwrap();
- let ops_limit = u64::try_from(key_attributes.ops_limit).unwrap();
+ let mem_limit = u64::from(key_attributes.mem_limit);
+ let ops_limit = u64::from(key_attributes.ops_limit);
assert_eq!(mem_limit * ops_limit, 4_294_967_296);
assert!(
@@ -2036,7 +1988,7 @@ mod tests {
auth::KeyDerivationStrength::Interactive,
)
.unwrap();
- let key_attributes = to_api_key_attributes(&original.key_attributes);
+ let key_attributes = original.key_attributes.clone();
let master_key = crypto::decode_b64(&original.private_key_attributes.key).unwrap();
let state = Arc::new(Mutex::new(MockSignupState::default()));
diff --git a/rust/crates/accounts/src/lib.rs b/rust/crates/accounts/src/lib.rs
index e5ad1fffca..3d6614d412 100644
--- a/rust/crates/accounts/src/lib.rs
+++ b/rust/crates/accounts/src/lib.rs
@@ -1,17 +1,22 @@
-//! Shared Rust account transport and flow orchestration for Ente clients.
+//! Shared Rust account identity, transport, and flow orchestration for Ente
+//! clients.
//!
//! Preferred usage:
+//! - Use [`auth`] for the account key hierarchy: key generation, secret
+//! decryption, recovery keys, and the SRP login protocol.
//! - Use [`AccountsClient`] when a caller needs raw server failures, including
//! the HTTP status and API error code.
//! - Use [`AuthFlow`] for CLI/e2e-style interactive orchestration where the
//! library drives OTP/TOTP/passkey steps via a UI adapter.
+pub mod auth;
pub mod client;
pub mod error;
pub mod flow;
pub mod models;
pub mod types;
+pub use auth::KeyAttributes;
pub use client::AccountsClient;
pub use error::{Error, Result};
pub use flow::{
@@ -19,5 +24,4 @@ pub use flow::{
CheckSessionValidityParams, CreateAccountParams, LoginParams, OtpPurpose, RecoveryKeyResult,
SecondFactorMethod, SessionValidity, SetupTwoFactorParams, SetupTwoFactorResult, TotpPurpose,
};
-pub use models::KeyAttributes;
pub use types::{AccountSecrets, AccountsClientConfig};
diff --git a/rust/crates/accounts/src/models.rs b/rust/crates/accounts/src/models.rs
index 3d306db8c4..bdd407cafa 100644
--- a/rust/crates/accounts/src/models.rs
+++ b/rust/crates/accounts/src/models.rs
@@ -5,32 +5,7 @@ use std::fmt;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-fn default_email_mfa_enabled() -> bool {
- true
-}
-
-/// `/users/srp/attributes` response payload.
-#[derive(Debug, Deserialize, Serialize, Clone)]
-pub struct SrpAttributes {
- /// SRP user ID.
- #[serde(rename = "srpUserID")]
- pub srp_user_id: Uuid,
- /// Base64 SRP salt.
- #[serde(rename = "srpSalt")]
- pub srp_salt: String,
- /// Argon memory limit.
- #[serde(rename = "memLimit")]
- pub mem_limit: i32,
- /// Argon ops limit.
- #[serde(rename = "opsLimit")]
- pub ops_limit: i32,
- /// Base64 KEK salt.
- #[serde(rename = "kekSalt")]
- pub kek_salt: String,
- /// Whether email MFA is enabled.
- #[serde(rename = "isEmailMFAEnabled", default = "default_email_mfa_enabled")]
- pub is_email_mfa_enabled: bool,
-}
+pub use crate::auth::{KeyAttributes, SrpAttributes};
/// Outer wrapper for SRP attributes.
#[derive(Debug, Deserialize, Serialize)]
@@ -40,38 +15,6 @@ pub struct GetSrpAttributesResponse {
pub attributes: SrpAttributes,
}
-/// Shared remote key attributes.
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct KeyAttributes {
- /// Base64 KEK salt.
- pub kek_salt: String,
- /// Optional legacy field.
- pub kek_hash: Option<String>,
- /// Base64 encrypted master key.
- pub encrypted_key: String,
- /// Base64 nonce for encrypted key.
- pub key_decryption_nonce: String,
- /// Base64 public key.
- pub public_key: String,
- /// Base64 encrypted secret key.
- pub encrypted_secret_key: String,
- /// Base64 secret-key nonce.
- pub secret_key_decryption_nonce: String,
- /// Argon memory limit.
- pub mem_limit: i32,
- /// Argon ops limit.
- pub ops_limit: i32,
- /// Base64 encrypted master key with recovery key.
- pub master_key_encrypted_with_recovery_key: Option<String>,
- /// Base64 nonce for recovery-key-encrypted master key.
- pub master_key_decryption_nonce: Option<String>,
- /// Base64 encrypted recovery key with master key.
- pub recovery_key_encrypted_with_master_key: Option<String>,
- /// Base64 nonce for recovery key.
- pub recovery_key_decryption_nonce: Option<String>,
-}
-
/// Auth response emitted by login and verification endpoints.
#[derive(Deserialize, Serialize, Clone)]
#[serde(try_from = "AuthResponseWire")]
@@ -351,9 +294,9 @@ pub struct UpdatedKeyAttr {
/// Base64 nonce.
pub key_decryption_nonce: String,
/// Argon ops limit.
- pub ops_limit: i32,
+ pub ops_limit: u32,
/// Argon memory limit.
- pub mem_limit: i32,
+ pub mem_limit: u32,
}
impl From<&KeyAttributes> for UpdatedKeyAttr {
diff --git a/rust/crates/contacts/Cargo.toml b/rust/crates/contacts/Cargo.toml
index 768079d16a..d665640100 100644
--- a/rust/crates/contacts/Cargo.toml
+++ b/rust/crates/contacts/Cargo.toml
@@ -6,7 +6,8 @@ edition = "2024"
museum = []
[dependencies]
-ente-core = { workspace = true, features = ["srp"] }
+ente-accounts.workspace = true
+ente-core.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
@@ -16,7 +17,6 @@ uuid = { version = "1", features = ["v4", "js"] }
[dev-dependencies]
base64 = "0.22"
-ente-accounts.workspace = true
ente-test-support.workspace = true
hmac = "0.13"
mockito = "1.6"
diff --git a/rust/crates/contacts/src/client.rs b/rust/crates/contacts/src/client.rs
index 55b009458a..206c7d5b81 100644
--- a/rust/crates/contacts/src/client.rs
+++ b/rust/crates/contacts/src/client.rs
@@ -1,6 +1,6 @@
use std::sync::{Arc, RwLock};
-use ente_core::auth::{self, KeyAttributes, SrpSession};
+use ente_accounts::auth::{self, KeyAttributes, SrpSession};
use ente_core::crypto::{self, SecretVec, sealed, secretbox};
use ente_core::http::{self, Api, ApiConfig, Auth, Http};
use sha2::{Digest, Sha256};
@@ -669,12 +669,8 @@ impl ContactsCtx {
kek_salt: updated_key_attrs.kek_salt.clone(),
encrypted_key: updated_key_attrs.encrypted_key.clone(),
key_decryption_nonce: updated_key_attrs.key_decryption_nonce.clone(),
- mem_limit: updated_key_attrs.mem_limit.ok_or_else(|| {
- ContactsError::InvalidInput("updated key attributes missing memLimit".into())
- })?,
- ops_limit: updated_key_attrs.ops_limit.ok_or_else(|| {
- ContactsError::InvalidInput("updated key attributes missing opsLimit".into())
- })?,
+ mem_limit: updated_key_attrs.mem_limit,
+ ops_limit: updated_key_attrs.ops_limit,
};
let change_response = self
@@ -957,7 +953,7 @@ impl ContactsCtx {
fn current_recovery_key(&self, current_user_key_attrs: &KeyAttributes) -> Result<SecretVec> {
let master_key = self.master_key.read().expect("master key lock poisoned");
let recovery_key_hex = auth::get_recovery_key(&master_key, current_user_key_attrs)?;
- Ok(SecretVec::new(crypto::decode_hex(&recovery_key_hex)?))
+ Ok(auth::recovery_key_from_mnemonic_or_hex(&recovery_key_hex)?)
}
fn decrypt_legacy_recovery_key(
diff --git a/rust/crates/contacts/src/error.rs b/rust/crates/contacts/src/error.rs
index f77180f73e..694ce05834 100644
--- a/rust/crates/contacts/src/error.rs
+++ b/rust/crates/contacts/src/error.rs
@@ -1,4 +1,5 @@
-use ente_core::{auth::AuthError, crypto, http};
+use ente_accounts::auth::AuthError;
+use ente_core::{crypto, http};
use thiserror::Error;
#[derive(Debug, Error)]
diff --git a/rust/crates/contacts/src/legacy_kit/mod.rs b/rust/crates/contacts/src/legacy_kit/mod.rs
index 5f034ae8a3..d568fd0924 100644
--- a/rust/crates/contacts/src/legacy_kit/mod.rs
+++ b/rust/crates/contacts/src/legacy_kit/mod.rs
@@ -3,8 +3,8 @@ mod shares;
use std::sync::Arc;
+use ente_accounts::auth::{self, KeyAttributes, SrpSession};
use ente_core::{
- auth::{self, KeyAttributes, SrpSession},
crypto::{self, SecretString, SecretVec, kdf, sealed, secretbox},
http::{Api, ApiConfig, Http},
};
@@ -290,12 +290,8 @@ impl LegacyKitRecoveryHandle {
kek_salt: updated_key_attrs.kek_salt.clone(),
encrypted_key: updated_key_attrs.encrypted_key.clone(),
key_decryption_nonce: updated_key_attrs.key_decryption_nonce.clone(),
- mem_limit: updated_key_attrs.mem_limit.ok_or_else(|| {
- ContactsError::InvalidInput("updated key attributes missing memLimit".into())
- })?,
- ops_limit: updated_key_attrs.ops_limit.ok_or_else(|| {
- ContactsError::InvalidInput("updated key attributes missing opsLimit".into())
- })?,
+ mem_limit: updated_key_attrs.mem_limit,
+ ops_limit: updated_key_attrs.ops_limit,
};
let change_response = self
.api
diff --git a/rust/crates/contacts/src/legacy_kit_models.rs b/rust/crates/contacts/src/legacy_kit_models.rs
index f53746a9d6..7f7fc69688 100644
--- a/rust/crates/contacts/src/legacy_kit_models.rs
+++ b/rust/crates/contacts/src/legacy_kit_models.rs
@@ -1,4 +1,5 @@
-use ente_core::{auth::KeyAttributes, crypto::SecretVec};
+use ente_accounts::auth::KeyAttributes;
+use ente_core::crypto::SecretVec;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
pub const LEGACY_KIT_PAYLOAD_VERSION: u8 = 1;
diff --git a/rust/crates/contacts/src/legacy_kit_transport.rs b/rust/crates/contacts/src/legacy_kit_transport.rs
index e5432406cb..c79ada31da 100644
--- a/rust/crates/contacts/src/legacy_kit_transport.rs
+++ b/rust/crates/contacts/src/legacy_kit_transport.rs
@@ -1,4 +1,4 @@
-use ente_core::auth::KeyAttributes;
+use ente_accounts::auth::KeyAttributes;
use serde::{Deserialize, Serialize};
use crate::legacy_kit_models::{
diff --git a/rust/crates/contacts/src/legacy_models.rs b/rust/crates/contacts/src/legacy_models.rs
index 289a0dac5c..7661a0dc17 100644
--- a/rust/crates/contacts/src/legacy_models.rs
+++ b/rust/crates/contacts/src/legacy_models.rs
@@ -1,4 +1,5 @@
-use ente_core::{auth::KeyAttributes, crypto::SecretVec};
+use ente_accounts::auth::KeyAttributes;
+use ente_core::crypto::SecretVec;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
diff --git a/rust/crates/contacts/src/legacy_transport.rs b/rust/crates/contacts/src/legacy_transport.rs
index e873d4198e..c160b4b074 100644
--- a/rust/crates/contacts/src/legacy_transport.rs
+++ b/rust/crates/contacts/src/legacy_transport.rs
@@ -1,4 +1,4 @@
-use ente_core::auth::KeyAttributes;
+use ente_accounts::auth::KeyAttributes;
use serde::{Deserialize, Serialize};
use crate::legacy_models::{LegacyContactState, LegacyInfo};
diff --git a/rust/crates/contacts/tests/contacts.rs b/rust/crates/contacts/tests/contacts.rs
index 86c04466a6..5f3a8f16d4 100644
--- a/rust/crates/contacts/tests/contacts.rs
+++ b/rust/crates/contacts/tests/contacts.rs
@@ -215,11 +215,7 @@ async fn run_legacy_reinvite_stage(pair: &legacy::LegacyPair) {
);
pair.owner_ctx
- .legacy_add_contact(
- &pair.trusted.email,
- &contacts::to_core_key_attributes(&pair.owner.key_attributes),
- Some(14),
- )
+ .legacy_add_contact(&pair.trusted.email, &pair.owner.key_attributes, Some(14))
.await
.unwrap();
pair.trusted_ctx
@@ -275,11 +271,7 @@ async fn run_legacy_reset_stage(endpoint: &str, pair: &mut legacy::LegacyPair) {
let previous_password = pair.owner.password.clone();
let new_password = support::unique_password("LegacyRecovered");
pair.trusted_ctx
- .legacy_change_password(
- &recovery.id,
- &contacts::to_core_key_attributes(&pair.trusted.key_attributes),
- &new_password,
- )
+ .legacy_change_password(&recovery.id, &pair.trusted.key_attributes, &new_password)
.await
.unwrap();
@@ -371,7 +363,7 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
let waiting_kit = owner
.owner_ctx
.legacy_kit_create(
- &contacts::to_core_key_attributes(&owner.owner.key_attributes),
+ &owner.owner.key_attributes,
["North".into(), "East".into(), "West".into()],
24,
)
@@ -614,7 +606,7 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
let immediate_kit = owner
.owner_ctx
.legacy_kit_create(
- &contacts::to_core_key_attributes(&owner.owner.key_attributes),
+ &owner.owner.key_attributes,
["Alpha".into(), "Bravo".into(), "Charlie".into()],
0,
)
diff --git a/rust/crates/contacts/tests/support/auth.rs b/rust/crates/contacts/tests/support/auth.rs
index 093c679bee..d6f8f95fc4 100644
--- a/rust/crates/contacts/tests/support/auth.rs
+++ b/rust/crates/contacts/tests/support/auth.rs
@@ -4,16 +4,14 @@ use base64::{
Engine,
engine::general_purpose::{STANDARD, URL_SAFE},
};
+use ente_accounts::auth::{SrpSession, generate_srp_setup_with_login_key};
use ente_accounts::{
AccountsClient, AccountsClientConfig, AuthFlow, AuthFlowUi, AuthenticatedAccount,
CreateAccountParams, Error as CliError, KeyAttributes, LoginParams, OtpPurpose,
Result as CliResult, SecondFactorMethod, SetupTwoFactorParams, TotpPurpose,
models::SetupSrpRequest,
};
-use ente_core::{
- auth::{SrpSession, generate_srp_setup_with_login_key},
- crypto::{Key, SecretKey, SecretVec, decode_b64, encode_b64, kdf, secretbox},
-};
+use ente_core::crypto::{Key, SecretKey, SecretVec, decode_b64, encode_b64, kdf, secretbox};
use ente_test_support::{HARDCODED_OTT, account_fixture};
use hmac::{Hmac, KeyInit, Mac};
use sha1::Sha1;
diff --git a/rust/crates/contacts/tests/support/contacts.rs b/rust/crates/contacts/tests/support/contacts.rs
index fdce24596b..3c675c952c 100644
--- a/rust/crates/contacts/tests/support/contacts.rs
+++ b/rust/crates/contacts/tests/support/contacts.rs
@@ -1,9 +1,7 @@
-use ente_accounts::KeyAttributes as ApiKeyAttributes;
use ente_contacts::{
client::{ContactsCtx, OpenContactsCtxInput},
legacy_models::{LegacyContactRecord, LegacyInfo, LegacyRecoverySession},
};
-use ente_core::auth::KeyAttributes as CoreKeyAttributes;
use crate::CLIENT_PACKAGE;
use crate::support::auth::TestAccount;
@@ -34,7 +32,7 @@ pub async fn establish_legacy_contact(
owner_ctx
.legacy_add_contact(
&trusted.email,
- &to_core_key_attributes(&owner.key_attributes),
+ &owner.key_attributes,
Some(recovery_notice_in_days),
)
.await
@@ -49,27 +47,6 @@ pub async fn establish_legacy_contact(
.unwrap();
}
-pub fn to_core_key_attributes(attributes: &ApiKeyAttributes) -> CoreKeyAttributes {
- CoreKeyAttributes {
- kek_salt: attributes.kek_salt.clone(),
- encrypted_key: attributes.encrypted_key.clone(),
- key_decryption_nonce: attributes.key_decryption_nonce.clone(),
- public_key: attributes.public_key.clone(),
- encrypted_secret_key: attributes.encrypted_secret_key.clone(),
- secret_key_decryption_nonce: attributes.secret_key_decryption_nonce.clone(),
- mem_limit: Some(attributes.mem_limit as u32),
- ops_limit: Some(attributes.ops_limit as u32),
- master_key_encrypted_with_recovery_key: attributes
- .master_key_encrypted_with_recovery_key
- .clone(),
- master_key_decryption_nonce: attributes.master_key_decryption_nonce.clone(),
- recovery_key_encrypted_with_master_key: attributes
- .recovery_key_encrypted_with_master_key
- .clone(),
- recovery_key_decryption_nonce: attributes.recovery_key_decryption_nonce.clone(),
- }
-}
-
pub fn owner_contact(
info: &LegacyInfo,
owner_user_id: i64,
diff --git a/rust/crates/core/Cargo.toml b/rust/crates/core/Cargo.toml
index 255e32b3f1..c63412728e 100644
--- a/rust/crates/core/Cargo.toml
+++ b/rust/crates/core/Cargo.toml
@@ -21,10 +21,6 @@ rand_core = { version = "0.6", features = ["getrandom"] }
subtle = "2"
md-5 = "0.11"
-# SRP authentication (optional; enable via the `srp` feature)
-srp = { version = "0.7.0-rc.3", default-features = false, optional = true }
-sha2 = { version = "0.11", optional = true }
-
# Randomness
#
# We enable `getrandom`'s `js` feature so that the crate works on
@@ -34,9 +30,7 @@ getrandom = { version = "0.2", features = ["js"] }
# Common dependencies
base64 = "0.22"
-hex = "0.4"
log = "0.4"
-bip39 = { version = "2", default-features = false, features = ["std"] }
zeroize = { version = "1.8.2", features = ["derive"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
@@ -52,15 +46,5 @@ gloo-timers = { version = "0.3.0", features = ["futures"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
mockito = "1.6"
-[features]
-default = []
-
-# Enable SRP (Secure Remote Password) client for password-based authentication.
-#
-# Without this feature, you can still derive KEK/login keys and decrypt secrets,
-# but cannot perform the SRP handshake (i.e. create/use `auth::SrpSession`).
-#
-srp = ["dep:srp", "dep:sha2"]
-
[lints.rust]
missing_docs = "warn"
diff --git a/rust/crates/core/src/auth/login.rs b/rust/crates/core/src/auth/login.rs
deleted file mode 100644
index d0989b425c..0000000000
--- a/rust/crates/core/src/auth/login.rs
+++ /dev/null
@@ -1,219 +0,0 @@
-//! Login and password verification.
-
-use crate::crypto::{self, SecretVec, argon, kdf, sealed, secretbox};
-
-use super::{AuthError, KeyAttributes, LoginResult, Result, SrpAttributes};
-
-/// Decrypt secrets and get the key-encryption-key for login.
-///
-/// This is the main login flow that:
-/// 1. Derives KEK from password
-/// 2. Decrypts master key with KEK
-/// 3. Decrypts secret key with master key
-/// 4. Opens the sealed token with secret key
-pub fn decrypt_secrets(
- password: &str,
- attributes: &KeyAttributes,
- encrypted_token: &str,
-) -> Result<LoginResult> {
- let mem_limit = attributes
- .mem_limit
- .ok_or(AuthError::MissingField("mem_limit"))?;
- let ops_limit = attributes
- .ops_limit
- .ok_or(AuthError::MissingField("ops_limit"))?;
-
- let kek_salt = crypto::decode_b64(&attributes.kek_salt)
- .map_err(|e| AuthError::Decode(format!("kek_salt: {}", e)))?;
- let salt = crypto::Salt::try_from_slice(&kek_salt)?;
-
- let key_encryption_key = argon::derive_key(
- password,
- &salt,
- argon::Params {
- mem_limit,
- ops_limit,
- },
- )?;
-
- decrypt_secrets_with_kek(key_encryption_key.as_bytes(), attributes, encrypted_token)
-}
-
-/// Decrypt secrets using a pre-derived key-encryption-key.
-pub fn decrypt_secrets_with_kek(
- key_encryption_key: &[u8],
- attributes: &KeyAttributes,
- encrypted_token: &str,
-) -> Result<LoginResult> {
- let encrypted_key = crypto::decode_b64(&attributes.encrypted_key)
- .map_err(|e| AuthError::Decode(format!("encrypted_key: {}", e)))?;
- let key_nonce = crypto::decode_b64(&attributes.key_decryption_nonce)
- .map_err(|e| AuthError::Decode(format!("key_decryption_nonce: {}", e)))?;
-
- let master_key = SecretVec::new(
- secretbox::decrypt(
- &encrypted_key,
- &crypto::Nonce::try_from_slice(&key_nonce)?,
- &crypto::Key::try_from_slice(key_encryption_key)?,
- )
- .map_err(|_| AuthError::IncorrectPassword)?,
- );
-
- let encrypted_secret_key = crypto::decode_b64(&attributes.encrypted_secret_key)
- .map_err(|e| AuthError::Decode(format!("encrypted_secret_key: {}", e)))?;
- let secret_key_nonce = crypto::decode_b64(&attributes.secret_key_decryption_nonce)
- .map_err(|e| AuthError::Decode(format!("secret_key_decryption_nonce: {}", e)))?;
-
- let secret_key = SecretVec::new(
- secretbox::decrypt(
- &encrypted_secret_key,
- &crypto::Nonce::try_from_slice(&secret_key_nonce)?,
- &crypto::Key::try_from_slice(&master_key)?,
- )
- .map_err(|_| AuthError::InvalidKeyAttributes)?,
- );
-
- let public_key = crypto::decode_b64(&attributes.public_key)
- .map_err(|e| AuthError::Decode(format!("public_key: {}", e)))?;
- let sealed_token = crypto::decode_b64(encrypted_token)
- .map_err(|e| AuthError::Decode(format!("encrypted_token: {}", e)))?;
-
- let token = SecretVec::new(
- sealed::open(
- &sealed_token,
- &crypto::PublicKey::try_from_slice(&public_key)?,
- &crypto::SecretKey::try_from_slice(&secret_key)?,
- )
- .map_err(|_| AuthError::InvalidKeyAttributes)?,
- );
-
- Ok(LoginResult {
- master_key,
- secret_key,
- token,
- key_encryption_key: SecretVec::new(key_encryption_key.to_vec()),
- })
-}
-
-/// Derive the login key from password for SRP authentication.
-pub fn derive_login_key_for_srp(
- password: &str,
- srp_attributes: &SrpAttributes,
-) -> Result<SecretVec> {
- let kek_salt = crypto::decode_b64(&srp_attributes.kek_salt)
- .map_err(|e| AuthError::Decode(format!("kek_salt: {}", e)))?;
-
- let salt = crypto::Salt::try_from_slice(&kek_salt)?;
- let kek = argon::derive_key(
- password,
- &salt,
- argon::Params {
- mem_limit: srp_attributes.mem_limit,
- ops_limit: srp_attributes.ops_limit,
- },
- )?;
- let login_key = kdf::derive_login_key(&kek);
-
- Ok(login_key)
-}
-
-/// Derive KEK and login key together.
-pub fn derive_keys_for_login(
- password: &str,
- srp_attributes: &SrpAttributes,
-) -> Result<(SecretVec, SecretVec)> {
- let kek_salt = crypto::decode_b64(&srp_attributes.kek_salt)
- .map_err(|e| AuthError::Decode(format!("kek_salt: {}", e)))?;
-
- let salt = crypto::Salt::try_from_slice(&kek_salt)?;
- let kek = argon::derive_key(
- password,
- &salt,
- argon::Params {
- mem_limit: srp_attributes.mem_limit,
- ops_limit: srp_attributes.ops_limit,
- },
- )?;
- let login_key = kdf::derive_login_key(&kek);
-
- Ok((SecretVec::new(kek.as_bytes().to_vec()), login_key))
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::auth::{KeyDerivationStrength, generate_keys_with_strength};
- use crate::crypto::random_bytes;
-
- fn generate_test_keys(password: &str) -> super::super::KeyGenResult {
- generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap()
- }
-
- fn create_sealed_token(token: &[u8], public_key: &[u8]) -> String {
- let pk = crypto::PublicKey::try_from_slice(public_key).unwrap();
- let sealed = sealed::seal(token, &pk).unwrap();
- crypto::encode_b64(&sealed)
- }
-
- #[test]
- fn test_decrypt_secrets_roundtrip() {
- let password = "test_password_123";
- let gen_result = generate_test_keys(password);
-
- let token = b"auth_token_12345";
- let public_key = crypto::decode_b64(&gen_result.key_attributes.public_key).unwrap();
- let encrypted_token = create_sealed_token(token, &public_key);
-
- let login_result =
- decrypt_secrets(password, &gen_result.key_attributes, &encrypted_token).unwrap();
-
- let original_master_key =
- crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();
- assert_eq!(
- login_result.master_key.as_ref(),
- original_master_key.as_slice()
- );
-
- let original_secret_key =
- crypto::decode_b64(&gen_result.private_key_attributes.secret_key).unwrap();
- assert_eq!(
- login_result.secret_key.as_ref(),
- original_secret_key.as_slice()
- );
-
- assert_eq!(login_result.token.as_ref(), token);
- }
-
- #[test]
- fn test_wrong_password() {
- let gen_result = generate_test_keys("correct_password");
- let public_key = crypto::decode_b64(&gen_result.key_attributes.public_key).unwrap();
- let encrypted_token = create_sealed_token(b"token", &public_key);
-
- let result = decrypt_secrets(
- "wrong_password",
- &gen_result.key_attributes,
- &encrypted_token,
- );
- assert!(matches!(result, Err(AuthError::IncorrectPassword)));
- }
-
- #[test]
- fn test_derive_login_key_for_srp() {
- let password = "test_password";
- let gen_result = generate_test_keys(password);
-
- let srp_attrs = SrpAttributes {
- srp_user_id: "test_user".to_string(),
- srp_salt: crypto::encode_b64(&random_bytes(16)),
- mem_limit: gen_result.key_attributes.mem_limit.unwrap(),
- ops_limit: gen_result.key_attributes.ops_limit.unwrap(),
- kek_salt: gen_result.key_attributes.kek_salt.clone(),
- is_email_mfa_enabled: false,
- };
-
- let login_key = derive_login_key_for_srp(password, &srp_attrs).unwrap();
- assert_eq!(login_key.len(), 16);
- assert_eq!(login_key.as_ref(), gen_result.login_key.as_ref());
- }
-}
diff --git a/rust/crates/core/src/auth/mod.rs b/rust/crates/core/src/auth/mod.rs
deleted file mode 100644
index 39f13d2849..0000000000
--- a/rust/crates/core/src/auth/mod.rs
+++ /dev/null
@@ -1,97 +0,0 @@
-//! Authentication helpers (key derivation, login decryption, recovery).
-//!
-//! Enable the `srp` feature to use [`SrpSession`] for SRP handshakes.
-
-mod api;
-mod key_gen;
-mod login;
-mod recovery;
-#[cfg(feature = "srp")]
-mod srp;
-mod types;
-
-// SRP session type (behind the `srp` feature)
-#[cfg(feature = "srp")]
-pub use srp::SrpSession;
-
-/// Stub type when the `srp` feature is disabled.
-///
-/// This allows downstream crates to reference [`SrpSession`] in signatures and
-/// get a runtime error if they accidentally call it without enabling the
-/// feature.
-#[cfg(not(feature = "srp"))]
-pub struct SrpSession {
- _private: (),
-}
-
-#[cfg(not(feature = "srp"))]
-impl SrpSession {
- fn feature_disabled() -> types::AuthError {
- types::AuthError::Srp(
- "SRP support is disabled. Enable the `srp` feature on ente-core".to_string(),
- )
- }
-
- /// Create a new SRP session.
- ///
- /// Always errors when the `srp` feature is disabled.
- pub fn new(_srp_user_id: &str, _srp_salt: &[u8], _login_key: &[u8]) -> types::Result<Self> {
- Err(Self::feature_disabled())
- }
-
- /// Get the client's public ephemeral value A.
- ///
- /// When the `srp` feature is disabled, this returns an empty vector.
- pub fn public_a(&self) -> Vec<u8> {
- Vec::new()
- }
-
- /// Compute the client proof M1.
- ///
- /// Always errors when the `srp` feature is disabled.
- pub fn compute_m1(&mut self, _server_b: &[u8]) -> types::Result<Vec<u8>> {
- Err(Self::feature_disabled())
- }
-
- /// Verify the server's proof M2.
- ///
- /// Always errors when the `srp` feature is disabled.
- pub fn verify_m2(&self, _server_m2: &[u8]) -> types::Result<()> {
- Err(Self::feature_disabled())
- }
-}
-
-// High-level API (recommended for applications)
-#[cfg(feature = "srp")]
-pub use api::GeneratedSrpSetup;
-pub use api::{DecryptedSecrets, GeneratedKek, SrpCredentials};
-pub use api::{
- decrypt_keys_only, decrypt_secrets, derive_kek, derive_srp_credentials,
- generate_interactive_kek, generate_sensitive_kek,
-};
-#[cfg(feature = "srp")]
-pub use api::{generate_srp_setup, generate_srp_setup_with_login_key};
-
-// Key generation (for signup)
-pub use key_gen::{
- KeyDerivationStrength, create_new_recovery_key, generate_key_attributes_for_new_password,
- generate_key_attributes_for_new_password_with_strength, generate_keys,
- generate_keys_with_strength,
-};
-
-// Lower-level login utilities (prefer api module for new code)
-pub use login::{
- decrypt_secrets as decrypt_secrets_legacy, decrypt_secrets_with_kek, derive_keys_for_login,
- derive_login_key_for_srp,
-};
-
-// Recovery
-pub use recovery::{
- get_recovery_key, recover_with_key, recovery_key_from_mnemonic_or_hex, recovery_key_to_mnemonic,
-};
-
-// Types
-pub use types::{
- AuthError, KeyAttributes, KeyGenResult, LoginResult, PrivateKeyAttributes, Result,
- SrpAttributes,
-};
diff --git a/rust/crates/core/src/auth/recovery.rs b/rust/crates/core/src/auth/recovery.rs
deleted file mode 100644
index 3ebdcc6f60..0000000000
--- a/rust/crates/core/src/auth/recovery.rs
+++ /dev/null
@@ -1,256 +0,0 @@
-//! Account recovery using recovery key.
-
-use bip39::{Language, Mnemonic};
-
-use crate::crypto::{self, SecretVec, sealed, secretbox};
-
-use super::{AuthError, KeyAttributes, LoginResult, Result};
-
-/// Recover account using recovery key.
-///
-/// The recovery key should be provided as a hex string (64 characters).
-pub fn recover_with_key(
- recovery_key_hex: &str,
- attributes: &KeyAttributes,
- encrypted_token: &str,
-) -> Result<LoginResult> {
- let recovery_key = SecretVec::new(
- crypto::decode_hex(recovery_key_hex)
- .map_err(|e| AuthError::Decode(format!("recovery_key: {}", e)))?,
- );
-
- if recovery_key.len() != 32 {
- return Err(AuthError::IncorrectRecoveryKey);
- }
-
- let encrypted_master_key = attributes
- .master_key_encrypted_with_recovery_key
- .as_ref()
- .ok_or(AuthError::MissingField(
- "master_key_encrypted_with_recovery_key",
- ))?;
-
- let master_key_nonce = attributes
- .master_key_decryption_nonce
- .as_ref()
- .ok_or(AuthError::MissingField("master_key_decryption_nonce"))?;
-
- let encrypted_master_key_bytes = crypto::decode_b64(encrypted_master_key)
- .map_err(|e| AuthError::Decode(format!("master_key_encrypted_with_recovery_key: {}", e)))?;
- let master_key_nonce_bytes = crypto::decode_b64(master_key_nonce)
- .map_err(|e| AuthError::Decode(format!("master_key_decryption_nonce: {}", e)))?;
-
- let master_key = SecretVec::new(
- secretbox::decrypt(
- &encrypted_master_key_bytes,
- &crypto::Nonce::try_from_slice(&master_key_nonce_bytes)?,
- &crypto::Key::try_from_slice(&recovery_key)?,
- )
- .map_err(|_| AuthError::IncorrectRecoveryKey)?,
- );
-
- let encrypted_secret_key = crypto::decode_b64(&attributes.encrypted_secret_key)
- .map_err(|e| AuthError::Decode(format!("encrypted_secret_key: {}", e)))?;
- let secret_key_nonce = crypto::decode_b64(&attributes.secret_key_decryption_nonce)
- .map_err(|e| AuthError::Decode(format!("secret_key_decryption_nonce: {}", e)))?;
-
- let secret_key = SecretVec::new(
- secretbox::decrypt(
- &encrypted_secret_key,
- &crypto::Nonce::try_from_slice(&secret_key_nonce)?,
- &crypto::Key::try_from_slice(&master_key)?,
- )
- .map_err(|_| AuthError::InvalidKeyAttributes)?,
- );
-
- let public_key = crypto::decode_b64(&attributes.public_key)
- .map_err(|e| AuthError::Decode(format!("public_key: {}", e)))?;
- let sealed_token = crypto::decode_b64(encrypted_token)
- .map_err(|e| AuthError::Decode(format!("encrypted_token: {}", e)))?;
-
- let token = SecretVec::new(
- sealed::open(
- &sealed_token,
- &crypto::PublicKey::try_from_slice(&public_key)?,
- &crypto::SecretKey::try_from_slice(&secret_key)?,
- )
- .map_err(|_| AuthError::InvalidKeyAttributes)?,
- );
-
- Ok(LoginResult {
- master_key,
- secret_key,
- token,
- key_encryption_key: SecretVec::new(Vec::new()),
- })
-}
-
-/// Get the recovery key from stored encrypted form.
-pub fn get_recovery_key(master_key: &[u8], attributes: &KeyAttributes) -> Result<String> {
- let encrypted_recovery_key = attributes
- .recovery_key_encrypted_with_master_key
- .as_ref()
- .ok_or(AuthError::MissingField(
- "recovery_key_encrypted_with_master_key",
- ))?;
-
- let nonce = attributes
- .recovery_key_decryption_nonce
- .as_ref()
- .ok_or(AuthError::MissingField("recovery_key_decryption_nonce"))?;
-
- let encrypted_bytes = crypto::decode_b64(encrypted_recovery_key)
- .map_err(|e| AuthError::Decode(format!("recovery_key_encrypted_with_master_key: {}", e)))?;
- let nonce_bytes = crypto::decode_b64(nonce)
- .map_err(|e| AuthError::Decode(format!("recovery_key_decryption_nonce: {}", e)))?;
-
- let recovery_key = SecretVec::new(
- secretbox::decrypt(
- &encrypted_bytes,
- &crypto::Nonce::try_from_slice(&nonce_bytes)?,
- &crypto::Key::try_from_slice(master_key)?,
- )
- .map_err(|_| AuthError::InvalidKeyAttributes)?,
- );
-
- Ok(crypto::encode_hex(&recovery_key))
-}
-
-/// Convert a user-provided recovery key mnemonic or hex string into raw bytes.
-///
-/// The mnemonic form must be a 24-word English BIP-39 phrase. The legacy hex
-/// form is still accepted for compatibility.
-pub fn recovery_key_from_mnemonic_or_hex(recovery_key_mnemonic_or_hex: &str) -> Result<SecretVec> {
- let trimmed_input = recovery_key_mnemonic_or_hex
- .split_whitespace()
- .map(str::trim)
- .filter(|part| !part.is_empty())
- .collect::<Vec<_>>()
- .join(" ");
-
- let recovery_key = SecretVec::new(if trimmed_input.contains(' ') {
- if trimmed_input.split(' ').count() != 24 {
- return Err(AuthError::IncorrectRecoveryKey);
- }
-
- let mnemonic = Mnemonic::parse_in_normalized(Language::English, &trimmed_input)
- .map_err(|_| AuthError::IncorrectRecoveryKey)?;
- mnemonic.to_entropy()
- } else {
- crypto::decode_hex(&trimmed_input).map_err(|_| AuthError::IncorrectRecoveryKey)?
- });
-
- if recovery_key.len() != 32 {
- return Err(AuthError::IncorrectRecoveryKey);
- }
-
- Ok(recovery_key)
-}
-
-/// Convert a base64-encoded recovery key into its 24-word English mnemonic.
-pub fn recovery_key_to_mnemonic(recovery_key_b64: &str) -> Result<String> {
- let recovery_key = SecretVec::new(
- crypto::decode_b64(recovery_key_b64)
- .map_err(|e| AuthError::Decode(format!("recovery_key: {}", e)))?,
- );
-
- if recovery_key.len() != 32 {
- return Err(AuthError::IncorrectRecoveryKey);
- }
-
- Mnemonic::from_entropy_in(Language::English, &recovery_key)
- .map(|mnemonic| mnemonic.to_string())
- .map_err(|e| AuthError::InvalidKey(format!("recovery_key: {}", e)))
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::auth::{KeyDerivationStrength, generate_keys_with_strength};
- use crate::crypto::Key;
-
- fn generate_test_keys(password: &str) -> super::super::KeyGenResult {
- generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap()
- }
-
- fn create_sealed_token(token: &[u8], public_key: &[u8]) -> String {
- let pk = crypto::PublicKey::try_from_slice(public_key).unwrap();
- let sealed = sealed::seal(token, &pk).unwrap();
- crypto::encode_b64(&sealed)
- }
-
- #[test]
- fn test_recovery_roundtrip() {
- let gen_result = generate_test_keys("original_password");
- let public_key = crypto::decode_b64(&gen_result.key_attributes.public_key).unwrap();
- let encrypted_token = create_sealed_token(b"my_token", &public_key);
-
- let recovery_result = recover_with_key(
- &gen_result.private_key_attributes.recovery_key,
- &gen_result.key_attributes,
- &encrypted_token,
- )
- .unwrap();
-
- let expected_master = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();
- assert_eq!(
- recovery_result.master_key.as_ref(),
- expected_master.as_slice()
- );
- assert_eq!(recovery_result.token.as_ref(), b"my_token");
- }
-
- #[test]
- fn test_wrong_recovery_key() {
- let gen_result = generate_test_keys("password");
- let public_key = crypto::decode_b64(&gen_result.key_attributes.public_key).unwrap();
- let encrypted_token = create_sealed_token(b"token", &public_key);
-
- let wrong_key = crypto::encode_hex(Key::generate().as_bytes());
- let result = recover_with_key(&wrong_key, &gen_result.key_attributes, &encrypted_token);
- assert!(matches!(result, Err(AuthError::IncorrectRecoveryKey)));
- }
-
- #[test]
- fn test_get_recovery_key() {
- let gen_result = generate_test_keys("password");
- let master_key = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();
-
- let recovered = get_recovery_key(&master_key, &gen_result.key_attributes).unwrap();
- assert_eq!(
- recovered,
- gen_result.private_key_attributes.recovery_key.as_ref()
- );
- }
-
- #[test]
- fn test_recovery_key_mnemonic_roundtrip() {
- let gen_result = generate_test_keys("password");
- let master_key = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();
- let recovery_key_hex = get_recovery_key(&master_key, &gen_result.key_attributes).unwrap();
- let recovery_key_b64 = crypto::encode_b64(&crypto::decode_hex(&recovery_key_hex).unwrap());
-
- let mnemonic = recovery_key_to_mnemonic(&recovery_key_b64).unwrap();
- let decoded = recovery_key_from_mnemonic_or_hex(&mnemonic).unwrap();
-
- assert_eq!(
- decoded.as_ref(),
- crypto::decode_hex(&recovery_key_hex).unwrap().as_slice()
- );
- }
-
- #[test]
- fn test_recovery_key_from_hex_accepts_legacy_format() {
- let gen_result = generate_test_keys("password");
- let decoded =
- recovery_key_from_mnemonic_or_hex(&gen_result.private_key_attributes.recovery_key)
- .unwrap();
-
- assert_eq!(
- decoded.as_ref(),
- crypto::decode_hex(&gen_result.private_key_attributes.recovery_key)
- .unwrap()
- .as_slice()
- );
- }
-}
diff --git a/rust/crates/core/src/crypto/encoding.rs b/rust/crates/core/src/crypto/encoding.rs
index 7756d5a212..b9102c4706 100644
--- a/rust/crates/core/src/crypto/encoding.rs
+++ b/rust/crates/core/src/crypto/encoding.rs
@@ -1,9 +1,8 @@
-//! Base64 and hex encoding and decoding.
+//! Base64 encoding and decoding.
//!
//! Conversions between bytes and their textual forms: standard and URL-safe
-//! base64, hexadecimal, and base64 to hex. These move key material and
-//! ciphertext across text boundaries such as JSON and URLs; they are plumbing,
-//! not themselves cryptographic.
+//! base64. These move key material and ciphertext across text boundaries such
+//! as JSON and URLs; they are plumbing, not themselves cryptographic.
use base64::{
Engine,
@@ -32,13 +31,6 @@ pub fn encode_b64(input: &[u8]) -> String {
BASE64.encode(input)
}
-/// Decode a base64 string to bytes.
-///
-/// Alias for [`decode_b64`], matching libsodium's `base642bin()` naming.
-pub fn base642bin(input: &str) -> Result<Vec<u8>> {
- decode_b64(input)
-}
-
/// Encode bytes to a URL-safe base64 string.
///
/// This uses the URL-safe alphabet (RFC 4648 Β§5) with padding, matching
@@ -66,49 +58,6 @@ pub fn decode_b64_url_safe_no_padding(input: &str) -> Result<Vec<u8>> {
Ok(BASE64_URL_SAFE_NO_PAD.decode(input)?)
}
-/// Return the UTF-8 bytes of `input`.
-pub fn str_to_bin(input: &str) -> Vec<u8> {
- input.as_bytes().to_vec()
-}
-
-/// Decode a hex string to bytes, the inverse of [`encode_hex`].
-///
-/// # Errors
-///
-/// Returns [`HexDecode`](crate::crypto::Error::HexDecode) if `input` is
-/// not valid hexadecimal.
-pub fn decode_hex(input: &str) -> Result<Vec<u8>> {
- Ok(hex::decode(input)?)
-}
-
-/// Encode bytes to a lowercase hex string, the inverse of [`decode_hex`].
-pub fn encode_hex(input: &[u8]) -> String {
- hex::encode(input)
-}
-
-/// Re-encode a standard base64 string as lowercase hex, the inverse of
-/// [`hex_to_b64`].
-///
-/// # Errors
-///
-/// Returns [`Base64Decode`](crate::crypto::Error::Base64Decode) if `b64`
-/// is not valid standard base64.
-pub fn b64_to_hex(b64: &str) -> Result<String> {
- let bytes = decode_b64(b64)?;
- Ok(encode_hex(&bytes))
-}
-
-/// Re-encode a hex string as standard base64, the inverse of [`b64_to_hex`].
-///
-/// # Errors
-///
-/// Returns [`HexDecode`](crate::crypto::Error::HexDecode) if `hex_str` is
-/// not valid hexadecimal.
-pub fn hex_to_b64(hex_str: &str) -> Result<String> {
- let bytes = decode_hex(hex_str)?;
- Ok(encode_b64(&bytes))
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -121,42 +70,6 @@ mod tests {
assert_eq!(decoded, original);
}
- #[test]
- fn test_hex_roundtrip() {
- let original = b"Hello, World!";
- let encoded = encode_hex(original);
- let decoded = decode_hex(&encoded).unwrap();
- assert_eq!(decoded, original);
- }
-
- #[test]
- fn test_b64_to_hex() {
- let original = b"Test";
- let b64 = encode_b64(original);
- let hex = b64_to_hex(&b64).unwrap();
- assert_eq!(hex, "54657374"); // "Test" in hex
- }
-
- #[test]
- fn test_hex_to_b64() {
- let hex = "54657374"; // "Test" in hex
- let b64 = hex_to_b64(hex).unwrap();
- let decoded = decode_b64(&b64).unwrap();
- assert_eq!(decoded, b"Test");
- }
-
- #[test]
- fn test_str_to_bin_ascii() {
- let bytes = str_to_bin("Hello");
- assert_eq!(bytes, b"Hello");
- }
-
- #[test]
- fn test_str_to_bin_unicode() {
- let bytes = str_to_bin("βœ“");
- assert_eq!(bytes, vec![0xE2, 0x9C, 0x93]);
- }
-
#[test]
fn test_invalid_base64() {
let result = decode_b64("not valid base64!!!");
@@ -171,10 +84,4 @@ mod tests {
assert_eq!(encode_b64_url_safe_no_padding(&bytes), "--8");
assert_eq!(decode_b64_url_safe_no_padding("--8").unwrap(), bytes);
}
-
- #[test]
- fn test_invalid_hex() {
- let result = decode_hex("not valid hex!!!");
- assert!(result.is_err());
- }
}
diff --git a/rust/crates/core/src/crypto/error.rs b/rust/crates/core/src/crypto/error.rs
index a021736cd4..a520064049 100644
--- a/rust/crates/core/src/crypto/error.rs
+++ b/rust/crates/core/src/crypto/error.rs
@@ -13,10 +13,6 @@ pub enum Error {
#[error("Base64 decode error: {0}")]
Base64Decode(#[from] base64::DecodeError),
- /// Hex decoding failed.
- #[error("Hex decode error: {0}")]
- HexDecode(#[from] hex::FromHexError),
-
/// Invalid key length.
#[error("Invalid key length: expected {expected}, got {actual}")]
InvalidKeyLength {
@@ -133,7 +129,6 @@ impl Error {
pub fn code(&self) -> &'static str {
match self {
Error::Base64Decode(_) => "base64_decode",
- Error::HexDecode(_) => "hex_decode",
Error::InvalidKeyLength { .. } => "invalid_key_length",
Error::InvalidNonceLength { .. } => "invalid_nonce_length",
Error::InvalidSaltLength { .. } => "invalid_salt_length",
diff --git a/rust/crates/core/src/crypto/mod.rs b/rust/crates/core/src/crypto/mod.rs
index 313c2f7eef..7f3a5902b4 100644
--- a/rust/crates/core/src/crypto/mod.rs
+++ b/rust/crates/core/src/crypto/mod.rs
@@ -25,8 +25,8 @@
//! - [`kdf`] - derive subkeys from a high-entropy key (BLAKE2b)
//! - [`hash`] - BLAKE2b hashing
//!
-//! Base64 and hex helpers ([`encode_b64`], [`encode_hex`], and friends) are
-//! available directly on this module. Key material is typed ([`Key`],
+//! Base64 helpers ([`encode_b64`] and friends) are available directly on this
+//! module. Key material is typed ([`Key`],
//! [`Nonce`], [`Salt`], [`Header`], [`PublicKey`], [`SecretKey`]), with lengths
//! validated at construction, and secrets are held in zeroizing [`SecretVec`] /
//! [`SecretString`].
@@ -57,8 +57,8 @@ pub mod secretbox;
pub mod stream;
pub use encoding::{
- b64_to_hex, base642bin, decode_b64, decode_b64_url_safe_no_padding, decode_hex, encode_b64,
- encode_b64_url_safe, encode_b64_url_safe_no_padding, encode_hex, hex_to_b64, str_to_bin,
+ decode_b64, decode_b64_url_safe_no_padding, encode_b64, encode_b64_url_safe,
+ encode_b64_url_safe_no_padding,
};
pub use error::{Error, Result};
pub use secret::{SecretString, SecretVec};
diff --git a/rust/crates/core/src/lib.rs b/rust/crates/core/src/lib.rs
index f036e59678..9840a1fc7b 100644
--- a/rust/crates/core/src/lib.rs
+++ b/rust/crates/core/src/lib.rs
@@ -3,7 +3,6 @@
//! This crate provides shared functionality for all Ente client implementations,
//! including cryptography, HTTP utilities, and common data structures.
-pub mod auth;
pub mod crypto;
pub mod error;
pub mod http;
diff --git a/rust/crates/test-support/src/lib.rs b/rust/crates/test-support/src/lib.rs
index a0e01f2b92..19428e8651 100644
--- a/rust/crates/test-support/src/lib.rs
+++ b/rust/crates/test-support/src/lib.rs
@@ -28,6 +28,6 @@ pub mod account_fixture {
// Argon2id(PASSWORD, 16 Γ— 0x4d, 256 MiB, 16 ops).
pub const KEK: &str = "EwUWye3Qiu3bep2oujaO8oJvUgIdn0DSOk2g0oZ+AWs=";
pub const KEK_SALT: &str = "TU1NTU1NTU1NTU1NTU1NTQ==";
- pub const MEM_LIMIT: i32 = 268_435_456;
- pub const OPS_LIMIT: i32 = 16;
+ pub const MEM_LIMIT: u32 = 268_435_456;
+ pub const OPS_LIMIT: u32 = 16;
}
diff --git a/rust/space/Cargo.toml b/rust/space/Cargo.toml
index 5c8cde81f9..ccd4db9c07 100644
--- a/rust/space/Cargo.toml
+++ b/rust/space/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.0.1"
edition = "2024"
[features]
-museum = ["ente-core/srp"]
+museum = []
[dependencies]
ente-core.workspace = true
diff --git a/rust/space/src/error.rs b/rust/space/src/error.rs
index a96bef401f..742534cfc4 100644
--- a/rust/space/src/error.rs
+++ b/rust/space/src/error.rs
@@ -1,4 +1,4 @@
-use ente_core::{auth::AuthError, crypto::Error as CryptoError, http::Error as HttpError};
+use ente_core::{crypto::Error as CryptoError, http::Error as HttpError};
use thiserror::Error;
#[derive(Debug, Error)]
@@ -9,9 +9,6 @@ pub enum SpaceError {
#[error(transparent)]
Crypto(#[from] CryptoError),
- #[error(transparent)]
- Auth(#[from] AuthError),
-
#[error("invalid input: {0}")]
InvalidInput(String),
diff --git a/rust/space/tests/support/auth.rs b/rust/space/tests/support/auth.rs
index bf19c2e97f..dac3be6992 100644
--- a/rust/space/tests/support/auth.rs
+++ b/rust/space/tests/support/auth.rs
@@ -1,9 +1,10 @@
use base64::{Engine, engine::general_purpose::STANDARD};
-use ente_accounts::{AccountsClient, AccountsClientConfig, KeyAttributes, models::SetupSrpRequest};
-use ente_core::{
+use ente_accounts::{
+ AccountsClient, AccountsClientConfig, KeyAttributes,
auth::{SrpSession, generate_srp_setup_with_login_key},
- crypto::{Key, SecretKey, decode_b64, encode_b64, kdf, secretbox},
+ models::SetupSrpRequest,
};
+use ente_core::crypto::{Key, SecretKey, decode_b64, encode_b64, kdf, secretbox};
use ente_test_support::{HARDCODED_OTT, HARDCODED_OTT_EMAIL_SUFFIX, account_fixture};
use uuid::Uuid;