π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
rust/cli: update auth API client
Prateek Sunalf52de45199df
diff --git a/rust/cli/src/api/auth.rs b/rust/cli/src/api/auth.rsindex 1cea4bc81f..cde0924d47 100644--- a/rust/cli/src/api/auth.rs+++ b/rust/cli/src/api/auth.rs@@ -1,16 +1,106 @@+//! Authentication API client.+//!+//! Handles HTTP API calls for authentication. Crypto operations are delegated+//! to ente-core's auth module.+use crate::api::client::ApiClient;use crate::api::models::{AuthResponse, CreateSrpSessionRequest, CreateSrpSessionResponse, GetSrpAttributesResponse,SendOtpRequest, SrpAttributes, VerifyEmailRequest, VerifySrpSessionRequest, VerifyTotpRequest,};-use crate::crypto::{derive_argon_key, derive_login_key};-use crate::models::error::Result;+use crate::models::error::{Error, Result};use base64::{Engine, engine::general_purpose::STANDARD};+use rand::RngCore;use sha2::Sha256;-use srp::client::SrpClient;+use srp::client::{SrpClient as SrpClientInner, SrpClientVerifier};use srp::groups::G_4096;use uuid::Uuid;+// Use ente-core for crypto operations+use ente_core::auth::SrpAttributes as CoreSrpAttributes;++struct SrpSession {+ inner: SrpClientInner<'static, Sha256>,+ identity: Vec<u8>,+ login_key: Vec<u8>,+ salt: Vec<u8>,+ a_private: Vec<u8>,+ a_public: Vec<u8>,+ verifier: Option<SrpClientVerifier<Sha256>>,+}++impl SrpSession {+ fn new(srp_user_id: &str, srp_salt: &[u8], login_key: &[u8]) -> Result<Self> {+ if login_key.len() != 16 {+ return Err(Error::Srp(format!(+ "login key must be 16 bytes, got {}",+ login_key.len()+ )));+ }++ let client = SrpClientInner::<Sha256>::new(&G_4096);++ let mut a_private = vec![0u8; 64];+ rand::rngs::OsRng.fill_bytes(&mut a_private);++ let a_public = client.compute_public_ephemeral(&a_private);+ let identity = srp_user_id.as_bytes().to_vec();++ Ok(Self {+ inner: client,+ identity,+ login_key: login_key.to_vec(),+ salt: srp_salt.to_vec(),+ a_private,+ a_public,+ verifier: None,+ })+ }++ fn public_a(&self) -> Vec<u8> {+ self.a_public.clone()+ }++ fn compute_m1(&mut self, server_b: &[u8]) -> Result<Vec<u8>> {+ let verifier = self+ .inner+ .process_reply(+ &self.a_private,+ &self.identity,+ &self.login_key,+ &self.salt,+ server_b,+ )+ .map_err(|e| Error::Srp(format!("Failed to process server response: {:?}", e)))?;++ let proof = verifier.proof().to_vec();+ self.verifier = Some(verifier);++ Ok(proof)+ }++ #[allow(dead_code)]+ fn verify_m2(&self, server_m2: &[u8]) -> Result<()> {+ let verifier = self+ .verifier+ .as_ref()+ .ok_or_else(|| Error::Srp("Client proof not computed".to_string()))?;++ verifier+ .verify_server(server_m2)+ .map_err(|_| Error::Srp("Server proof verification failed".to_string()))+ }+}++fn pad_bytes(data: &[u8], len: usize) -> Vec<u8> {+ if data.len() >= len {+ return data.to_vec();+ }+ let mut padded = vec![0u8; len - data.len()];+ padded.extend_from_slice(data);+ padded+}+/// SRP authentication implementation for Ente APIpub struct AuthClient<'a> {api: &'a ApiClient,@@ -25,6 +115,10 @@ impl<'a> AuthClient<'a> {pub async fn get_srp_attributes(&self, email: &str) -> Result<SrpAttributes> {let url = format!("/users/srp/attributes?email={}", urlencoding::encode(email));let response: GetSrpAttributesResponse = self.api.get(&url, None).await?;+ log::debug!(+ "SRP attributes response: is_email_mfa_enabled={}",+ response.attributes.is_email_mfa_enabled+ );Ok(response.attributes)}@@ -67,44 +161,41 @@ impl<'a> AuthClient<'a> {.await}- /// Complete SRP authentication flow+ /// Complete SRP authentication flow using ente-core credential derivationpub async fn login_with_srp(&self,email: &str,password: &str,) -> Result<(AuthResponse, Vec<u8>)> {- use rand::RngCore;-// Step 1: Get SRP attributeslet srp_attrs = self.get_srp_attributes(email).await?;- // Step 2: Derive key encryption key from password- let key_enc_key = derive_argon_key(- password,- &srp_attrs.kek_salt,- srp_attrs.mem_limit as u32,- srp_attrs.ops_limit as u32,- )?;-- // Step 3: Derive login key- let login_key = derive_login_key(&key_enc_key)?;-- // Step 4: Initialize SRP client- let srp_salt = STANDARD.decode(&srp_attrs.srp_salt)?;- // Use the UUID string directly as bytes (matching TypeScript's Buffer.from(srpUserID))- let identity = srp_attrs.srp_user_id.to_string().into_bytes();+ // Step 2: Derive SRP credentials and build SRP client state+ println!("Deriving encryption key (this may take a few seconds)...");+ 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,+ };- // Create SRP client with 4096-bit group (matching Go's srp.GetParams(4096))- let client = SrpClient::<Sha256>::new(&G_4096);+ let creds = ente_core::auth::derive_srp_credentials(password, &core_attrs)+ .map_err(|e| Error::Crypto(e.to_string()))?;+ let srp_salt = STANDARD+ .decode(&srp_attrs.srp_salt)+ .map_err(|e| Error::Crypto(format!("Invalid srp_salt: {}", e)))?;- // Generate random ephemeral private key- let mut a = vec![0u8; 64];- rand::thread_rng().fill_bytes(&mut a);+ let mut srp_session = SrpSession::new(+ &srp_attrs.srp_user_id.to_string(),+ &srp_salt,+ &creds.login_key,+ )?;- // Compute public ephemeral- let a_pub = client.compute_public_ephemeral(&a);+ // Step 3: Get client's public value and create session+ let a_pub = pad_bytes(&srp_session.public_a(), 512);- // Step 5: Create SRP sessionlog::debug!("Creating SRP session...");let session = self.create_srp_session(&srp_attrs.srp_user_id, &a_pub)@@ -114,38 +205,26 @@ impl<'a> AuthClient<'a> {// Add a small delay to avoid potential rate limitingtokio::time::sleep(tokio::time::Duration::from_millis(100)).await;- // Step 6: Process server's public key and generate proof- let server_public = STANDARD.decode(&session.srp_b)?;+ // Step 4: Decode server's public key+ let server_b = STANDARD+ .decode(&session.srp_b)+ .map_err(|e| Error::Crypto(format!("Invalid server B: {}", e)))?;- // Process the server's response and generate client proof- // The srp crate expects: a, username, password, salt, b_pub- // But Ente uses the login_key (derived from password) as the password for SRP- let verifier = client- .process_reply(&a, &identity, &login_key, &srp_salt, &server_public)- .map_err(|e| {- crate::models::error::Error::AuthenticationFailed(format!(- "SRP client process failed: {e:?}"- ))- })?;-- // Step 7: Verify session with proof- let proof = verifier.proof();+ // Step 5: Compute proof using server's public value+ let proof = srp_session.compute_m1(&server_b)?;+ let proof = pad_bytes(&proof, 32);let auth_response = self- .verify_srp_session(&srp_attrs.srp_user_id, &session.session_id, proof)+ .verify_srp_session(&srp_attrs.srp_user_id, &session.session_id, &proof).await?;// TODO: Verify server proof if provided// if let Some(srp_m2) = &auth_response.srp_m2 {// let server_proof = STANDARD.decode(srp_m2)?;- // verifier.verify_server(&server_proof).map_err(|_| {- // crate::models::error::Error::AuthenticationFailed(- // "Server proof verification failed".to_string()- // )- // })?;+ // srp_session.verify_m2(&server_proof)?;// }- Ok((auth_response, key_enc_key))+ Ok((auth_response, creds.kek))}/// Send OTP for email verification@@ -155,8 +234,7 @@ impl<'a> AuthClient<'a> {purpose: "login".to_string(),};- let _: serde_json::Value = self.api.post("/users/ott", &request, None).await?;- Ok(())+ self.api.post_empty("/users/ott", &request, None).await}/// Verify email with OTP@@ -191,18 +269,30 @@ impl<'a> AuthClient<'a> {#[cfg(test)]mod tests {use super::*;- use crate::crypto::{derive_argon_key, derive_login_key};+ use base64::engine::general_purpose::STANDARD;#[test]fn test_login_key_derivation() {- // Test that login key derivation matches expected output+ ente_core::crypto::init().unwrap();++ // Test that ente-core's key derivation works correctlylet password = "test_password";- let salt = b"test_salt_16bytes";+ let salt = b"test_salt_16byte"; // Exactly 16 bytes++ let srp_attrs = CoreSrpAttributes {+ srp_user_id: "test-user".to_string(),+ srp_salt: STANDARD.encode([0u8; 16]),+ mem_limit: 67108864, // Interactive+ ops_limit: 2,+ kek_salt: STANDARD.encode(salt),+ is_email_mfa_enabled: false,+ };- let key = derive_argon_key(password, &STANDARD.encode(salt), 4, 3).unwrap();- assert_eq!(key.len(), 32);+ let creds = ente_core::auth::derive_srp_credentials(password, &srp_attrs).unwrap();+ let srp_salt = STANDARD.decode(&srp_attrs.srp_salt).unwrap();+ let session = SrpSession::new(&srp_attrs.srp_user_id, &srp_salt, &creds.login_key).unwrap();- let login_key = derive_login_key(&key).unwrap();- assert_eq!(login_key.len(), 32);+ assert_eq!(creds.kek.len(), 32);+ assert!(!session.public_a().is_empty());}}diff --git a/rust/cli/src/api/client.rs b/rust/cli/src/api/client.rsindex 66742bdd81..f9001e92b4 100644--- a/rust/cli/src/api/client.rs+++ b/rust/cli/src/api/client.rs@@ -172,24 +172,26 @@ impl ApiClient {// Try to parse as JSON to get error detailsif let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {- log::error!(+ log::debug!("API error: status={}, body={}",status,serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone()));} else {- log::error!("API error: status={status}, body={error_text}");+ log::debug!("API error: status={status}, body={error_text}");}- return Err(Error::Generic(format!(- "API error ({status}): {error_text}"- )));+ return Err(Error::api_error(+ status.as_u16(),+ format!("API error ({status}): {error_text}"),+ ));}let text = response.text().await?;+ log::trace!("Raw API response: {}", &text[..500.min(text.len())]);serde_json::from_str(&text).map_err(|e| {- log::error!("Failed to deserialize response: {e}");- log::error!(+ log::debug!("Failed to deserialize response: {e}");+ log::debug!("Response text (first 1000 chars): {}",&text[..1000.min(text.len())]);@@ -205,15 +207,6 @@ impl ApiClient {{let url = format!("{}{}", self.base_url, path);- // Debug log the JSON being sent- if path.contains("verify-session") {- log::debug!(- "POST {} with JSON: {}",- url,- serde_json::to_string_pretty(body)?- );- }-let request = self.client.post(&url).json(body);let request = self.build_request(request, account_id);@@ -228,24 +221,26 @@ impl ApiClient {// Try to parse as JSON to get error detailsif let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {- log::error!(+ log::debug!("API error: status={}, body={}",status,serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone()));} else {- log::error!("API error: status={status}, body={error_text}");+ log::debug!("API error: status={status}, body={error_text}");}- return Err(Error::Generic(format!(- "API error ({status}): {error_text}"- )));+ return Err(Error::api_error(+ status.as_u16(),+ format!("API error ({status}): {error_text}"),+ ));}let text = response.text().await?;+serde_json::from_str(&text).map_err(|e| {- log::error!("Failed to deserialize response: {e}");- log::error!(+ log::debug!("Failed to deserialize response: {e}");+ log::debug!("Response text (first 1000 chars): {}",&text[..1000.min(text.len())]);@@ -253,6 +248,43 @@ impl ApiClient {})}+ /// Make a POST request that expects no response body+ pub async fn post_empty<B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<()>+ where+ B: Serialize,+ {+ let url = format!("{}{}", self.base_url, path);+ let request = self.client.post(&url).json(body);+ let request = self.build_request(request, account_id);++ let response = self.execute_with_retry(request).await?;++ if !response.status().is_success() {+ let status = response.status();+ let error_text = response+ .text()+ .await+ .unwrap_or_else(|_| "Unknown error".to_string());++ if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {+ log::debug!(+ "API error: status={}, body={}",+ status,+ serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone())+ );+ } else {+ log::debug!("API error: status={status}, body={error_text}");+ }++ return Err(Error::api_error(+ status.as_u16(),+ format!("API error ({status}): {error_text}"),+ ));+ }++ Ok(())+ }+/// Make a PUT requestpub async fn put<T, B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<T>where@@ -274,24 +306,25 @@ impl ApiClient {// Try to parse as JSON to get error detailsif let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {- log::error!(+ log::debug!("API error: status={}, body={}",status,serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone()));} else {- log::error!("API error: status={status}, body={error_text}");+ log::debug!("API error: status={status}, body={error_text}");}- return Err(Error::Generic(format!(- "API error ({status}): {error_text}"- )));+ return Err(Error::api_error(+ status.as_u16(),+ format!("API error ({status}): {error_text}"),+ ));}let text = response.text().await?;serde_json::from_str(&text).map_err(|e| {- log::error!("Failed to deserialize response: {e}");- log::error!(+ log::debug!("Failed to deserialize response: {e}");+ log::debug!("Response text (first 1000 chars): {}",&text[..1000.min(text.len())]);@@ -316,18 +349,19 @@ impl ApiClient {// Try to parse as JSON to get error detailsif let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&error_text) {- log::error!(+ log::debug!("API error: status={}, body={}",status,serde_json::to_string_pretty(&error_json).unwrap_or(error_text.clone()));} else {- log::error!("API error: status={status}, body={error_text}");+ log::debug!("API error: status={status}, body={error_text}");}- return Err(Error::Generic(format!(- "API error ({status}): {error_text}"- )));+ return Err(Error::api_error(+ status.as_u16(),+ format!("API error ({status}): {error_text}"),+ ));}Ok(())@@ -341,11 +375,15 @@ impl ApiClient {let response = self.execute_with_retry(request).await?;if !response.status().is_success() {+ let status = response.status();let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());- return Err(Error::Generic(format!("Download error: {error_text}")));+ return Err(Error::api_error(+ status.as_u16(),+ format!("Download error: {error_text}"),+ ));}Ok(response.bytes().await?.to_vec())diff --git a/rust/cli/src/api/models.rs b/rust/cli/src/api/models.rsindex 3f96debc0d..006d64ac12 100644--- a/rust/cli/src/api/models.rs+++ b/rust/cli/src/api/models.rs@@ -3,6 +3,13 @@ use uuid::Uuid;// ========== Authentication Models ==========+/// Default to true for security - if field is missing, use email OTP flow.+///+/// Matches mobile/web behavior: absence falls back to email verification.+fn default_email_mfa_enabled() -> bool {+ true+}+#[derive(Debug, Deserialize, Serialize)]pub struct SrpAttributes {#[serde(rename = "srpUserID")]@@ -15,7 +22,7 @@ pub struct SrpAttributes {pub ops_limit: i32,#[serde(rename = "kekSalt")]pub kek_salt: String,- #[serde(rename = "isEmailMFAEnabled")]+ #[serde(rename = "isEmailMFAEnabled", default = "default_email_mfa_enabled")]pub is_email_mfa_enabled: bool,}@@ -72,15 +79,32 @@ pub struct AuthResponse {pub key_attributes: Option<KeyAttributes>,pub encrypted_token: Option<String>,pub token: Option<String>,+ #[serde(default, rename = "twoFactorSessionID")]pub two_factor_session_id: Option<String>,+ /// V2 TOTP session ID (used during migration period)+ #[serde(default, rename = "twoFactorSessionIDV2")]+ pub two_factor_session_id_v2: Option<String>,+ #[serde(default, rename = "passkeySessionID")]pub passkey_session_id: Option<String>,pub srp_m2: Option<String>,pub accounts_url: Option<String>,}impl AuthResponse {+ /// Get the TOTP session ID (checks both V1 and V2 fields, filters empty strings)+ pub fn get_two_factor_session_id(&self) -> Option<&String> {+ self.two_factor_session_id+ .as_ref()+ .filter(|s| !s.is_empty())+ .or_else(|| {+ self.two_factor_session_id_v2+ .as_ref()+ .filter(|s| !s.is_empty())+ })+ }+pub fn is_mfa_required(&self) -> bool {- self.two_factor_session_id.is_some()+ self.get_two_factor_session_id().is_some()}pub fn is_passkey_required(&self) -> bool {