π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Harden rust core auth and HTTP handling
Manav Rathi5fac64d888ce
diff --git a/mobile/packages/rust/rust/src/api/http.rs b/mobile/packages/rust/rust/src/api/http.rsindex d4eab61484..de961e4401 100644--- a/mobile/packages/rust/rust/src/api/http.rs+++ b/mobile/packages/rust/rust/src/api/http.rs@@ -6,6 +6,11 @@ use flutter_rust_bridge::frb;/// HTTP client errors.#[frb]pub enum HttpError {+ /// Invalid base URL or request path.+ InvalidUrl {+ /// Error message.+ message: String,+ },/// Network error - connection failed, timeout, etc.Network {/// Error message.@@ -28,6 +33,7 @@ pub enum HttpError {impl From<CoreError> for HttpError {fn from(e: CoreError) -> Self {match e {+ CoreError::InvalidUrl(message) => HttpError::InvalidUrl { message },CoreError::Network(message) => HttpError::Network { message },CoreError::Http { status, message } => HttpError::Http { status, message },CoreError::Parse(message) => HttpError::Parse { message },diff --git a/rust/core/src/auth/api.rs b/rust/core/src/auth/api.rsindex e33f96aeb3..8d5b81ef21 100644--- a/rust/core/src/auth/api.rs+++ b/rust/core/src/auth/api.rs@@ -3,6 +3,8 @@//! This module provides the main entry points that CLI/GUI applications should use//! for authentication flows. It wraps the lower-level crypto operations.+use std::fmt;+#[cfg(feature = "srp")]use crate::crypto::keys;use crate::crypto::{self, argon, kdf, sealed, secretbox};@@ -17,7 +19,6 @@ use sha2::Sha256;use srp::{client::SrpClient as SrpClientInner, groups::G_4096};/// Credentials derived from password for SRP authentication.-#[derive(Debug)]pub struct SrpCredentials {/// Key encryption key (32 bytes) - used to decrypt master key after auth.pub kek: Vec<u8>,@@ -25,8 +26,16 @@ pub struct SrpCredentials {pub login_key: Vec<u8>,}+impl fmt::Debug for SrpCredentials {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("SrpCredentials")+ .field("kek", &"[REDACTED]")+ .field("login_key", &"[REDACTED]")+ .finish()+ }+}+/// Decrypted secrets after successful authentication.-#[derive(Debug)]pub struct DecryptedSecrets {/// Master key for encrypting/decrypting data.pub master_key: Vec<u8>,@@ -36,8 +45,17 @@ pub struct DecryptedSecrets {pub token: Vec<u8>,}+impl fmt::Debug for DecryptedSecrets {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("DecryptedSecrets")+ .field("master_key", &"[REDACTED]")+ .field("secret_key", &"[REDACTED]")+ .field("token", &"[REDACTED]")+ .finish()+ }+}+/// A derived key-encryption-key and the parameters used to derive it.-#[derive(Debug)]pub struct GeneratedKek {/// Derived KEK bytes.pub key: Vec<u8>,@@ -49,9 +67,19 @@ pub struct GeneratedKek {pub ops_limit: u32,}+impl fmt::Debug for GeneratedKek {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("GeneratedKek")+ .field("key", &"[REDACTED]")+ .field("salt_len", &self.salt.len())+ .field("mem_limit", &self.mem_limit)+ .field("ops_limit", &self.ops_limit)+ .finish()+ }+}+/// Attributes needed to register or update SRP for a user.#[cfg(feature = "srp")]-#[derive(Debug)]pub struct GeneratedSrpSetup {/// SRP salt bytes.pub srp_salt: Vec<u8>,@@ -61,6 +89,17 @@ pub struct GeneratedSrpSetup {pub login_sub_key: Vec<u8>,}+#[cfg(feature = "srp")]+impl fmt::Debug for GeneratedSrpSetup {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("GeneratedSrpSetup")+ .field("srp_salt_len", &self.srp_salt.len())+ .field("srp_verifier", &"[REDACTED]")+ .field("login_sub_key", &"[REDACTED]")+ .finish()+ }+}+/// Derive SRP credentials from password.////// This is the first step in the SRP login flow. Call this after password entry@@ -110,16 +149,18 @@ pub fn derive_kek(argon::derive_key(password, &salt, mem_limit, ops_limit).map_err(AuthError::from)}-/// Generate a KEK using the current sensitive web policy.+/// Generate a KEK using the current adaptive sensitive client policy.pub fn generate_sensitive_kek(password: &str) -> Result<GeneratedKek> {- let derived = argon::derive_sensitive_key(password).map_err(|e| match e {+ let mut derived = argon::derive_sensitive_key(password).map_err(|e| match e {crypto::CryptoError::InvalidKeyDerivationParams(_) => AuthError::Crypto(e),_ => AuthError::InsufficientMemory,})?;+ let key = std::mem::take(&mut derived.key);+ let salt = std::mem::take(&mut derived.salt);Ok(GeneratedKek {- key: derived.key,- salt: derived.salt,+ key,+ salt,mem_limit: derived.mem_limit,ops_limit: derived.ops_limit,})@@ -127,10 +168,13 @@ pub fn generate_sensitive_kek(password: &str) -> Result<GeneratedKek> {/// Generate a KEK using the current interactive web policy.pub fn generate_interactive_kek(password: &str) -> Result<GeneratedKek> {- let derived = argon::derive_interactive_key(password)?;+ let mut derived = argon::derive_interactive_key(password)?;+ let key = std::mem::take(&mut derived.key);+ let salt = std::mem::take(&mut derived.salt);+Ok(GeneratedKek {- key: derived.key,- salt: derived.salt,+ key,+ salt,mem_limit: derived.mem_limit,ops_limit: derived.ops_limit,})@@ -230,14 +274,14 @@ pub(crate) fn start_srp_session(password: &str,srp_attrs: &SrpAttributes,) -> Result<(SrpSession, Vec<u8>)> {- let creds = derive_srp_credentials(password, srp_attrs)?;+ let mut 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))+ Ok((session, std::mem::take(&mut creds.kek)))}#[cfg(test)]@@ -345,6 +389,21 @@ mod tests {assert!(generated.ops_limit > 0);}+ #[test]+ fn test_generated_kek_debug_redacts_secret_material() {+ let generated = GeneratedKek {+ key: vec![1, 2, 3],+ salt: vec![4, 5, 6],+ mem_limit: 123,+ ops_limit: 456,+ };++ let debug = format!("{generated:?}");+ assert!(debug.contains("[REDACTED]"));+ assert!(!debug.contains("[1, 2, 3]"));+ assert!(debug.contains("salt_len"));+ }+#[test]fn test_generate_interactive_kek() {crate::crypto::init().unwrap();diff --git a/rust/core/src/auth/key_gen.rs b/rust/core/src/auth/key_gen.rsindex 2c9cba01db..b15117fa35 100644--- a/rust/core/src/auth/key_gen.rs+++ b/rust/core/src/auth/key_gen.rs@@ -46,7 +46,7 @@ pub fn generate_keys_with_strength(encrypt_to_b64(&recovery_key, &master_key)?;// Derive key-encryption-key from password- let derived = match strength {+ let mut derived = match strength {KeyDerivationStrength::Interactive => argon::derive_interactive_key(password)?,KeyDerivationStrength::Sensitive => argon::derive_sensitive_key(password)?,};@@ -87,7 +87,7 @@ pub fn generate_keys_with_strength(Ok(KeyGenResult {key_attributes,private_key_attributes,- key_encryption_key: derived.key,+ key_encryption_key: std::mem::take(&mut derived.key),login_key,})}diff --git a/rust/core/src/auth/types.rs b/rust/core/src/auth/types.rsindex bec0831450..52a594f777 100644--- a/rust/core/src/auth/types.rs+++ b/rust/core/src/auth/types.rs@@ -1,5 +1,7 @@//! Data types for authentication operations.+use std::fmt;+use serde::{Deserialize, Serialize};/// Attributes stored on server for key derivation and encrypted keys.@@ -39,7 +41,6 @@ pub struct KeyAttributes {}/// Private key material (never sent to server).-#[derive(Debug, Clone)]pub struct PrivateKeyAttributes {/// Master key (base64)pub key: String,@@ -49,8 +50,17 @@ pub struct PrivateKeyAttributes {pub secret_key: String,}+impl fmt::Debug for PrivateKeyAttributes {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("PrivateKeyAttributes")+ .field("key", &"[REDACTED]")+ .field("recovery_key", &"[REDACTED]")+ .field("secret_key", &"[REDACTED]")+ .finish()+ }+}+/// Result of key generation during sign-up.-#[derive(Debug, Clone)]pub struct KeyGenResult {/// Attributes to send to serverpub key_attributes: KeyAttributes,@@ -62,8 +72,18 @@ pub struct KeyGenResult {pub login_key: Vec<u8>,}+impl fmt::Debug for KeyGenResult {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("KeyGenResult")+ .field("key_attributes", &self.key_attributes)+ .field("private_key_attributes", &self.private_key_attributes)+ .field("key_encryption_key", &"[REDACTED]")+ .field("login_key", &"[REDACTED]")+ .finish()+ }+}+/// Result of successful login/decryption.-#[derive(Debug, Clone)]pub struct LoginResult {/// Decrypted master keypub master_key: Vec<u8>,@@ -75,6 +95,17 @@ pub struct LoginResult {pub key_encryption_key: Vec<u8>,}+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}@@ -141,3 +172,65 @@ pub enum AuthError {/// Result type for auth operations.pub type Result<T> = std::result::Result<T, AuthError>;++#[cfg(test)]+mod tests {+ use super::*;++ fn sample_key_attributes() -> KeyAttributes {+ KeyAttributes {+ kek_salt: "server-kek-salt".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),+ master_key_encrypted_with_recovery_key: None,+ master_key_decryption_nonce: None,+ recovery_key_encrypted_with_master_key: None,+ recovery_key_decryption_nonce: None,+ }+ }++ #[test]+ fn test_key_gen_result_debug_redacts_secret_material() {+ let result = KeyGenResult {+ key_attributes: sample_key_attributes(),+ private_key_attributes: PrivateKeyAttributes {+ key: "private-master-key".to_string(),+ recovery_key: "private-recovery-key".to_string(),+ secret_key: "private-secret-key".to_string(),+ },+ key_encryption_key: vec![1, 2, 3],+ login_key: vec![4, 5, 6],+ };++ let debug = format!("{result:?}");+ assert!(debug.contains("[REDACTED]"));+ assert!(!debug.contains("private-master-key"));+ assert!(!debug.contains("private-recovery-key"));+ assert!(!debug.contains("private-secret-key"));+ assert!(!debug.contains("[1, 2, 3]"));+ assert!(!debug.contains("[4, 5, 6]"));+ assert!(debug.contains("key_attributes"));+ }++ #[test]+ fn test_login_result_debug_redacts_secret_material() {+ let result = LoginResult {+ master_key: vec![1, 2, 3],+ secret_key: vec![4, 5, 6],+ token: vec![7, 8, 9],+ key_encryption_key: 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/core/src/crypto/impl_pure/argon.rs b/rust/core/src/crypto/impl_pure/argon.rsindex 30e6a72171..a0f9634405 100644--- a/rust/core/src/crypto/impl_pure/argon.rs+++ b/rust/core/src/crypto/impl_pure/argon.rs@@ -2,13 +2,14 @@//!//! This module provides password-based key derivation using Argon2id.+use std::fmt;+use argon2::{Algorithm, Argon2, Params, Version};use crate::crypto::{CryptoError, Result, SecretVec};use zeroize::Zeroizing;/// Result of key derivation with password.-#[derive(Debug, Clone)]pub struct DerivedKeyResult {/// The derived key.pub key: Vec<u8>,@@ -20,6 +21,17 @@ pub struct DerivedKeyResult {pub ops_limit: u32,}+impl fmt::Debug for DerivedKeyResult {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("DerivedKeyResult")+ .field("key", &"[REDACTED]")+ .field("salt_len", &self.salt.len())+ .field("mem_limit", &self.mem_limit)+ .field("ops_limit", &self.ops_limit)+ .finish()+ }+}+/// Memory limit for interactive operations (64 MiB).pub const MEMLIMIT_INTERACTIVE: u32 = 67_108_864;@@ -186,6 +198,10 @@ pub fn derive_moderate_key(password: &str, salt: &[u8]) -> Result<Vec<u8>> {/// MEMLIMIT_SENSITIVE * OPSLIMIT_SENSITIVE strength. If derivation fails,/// it halves mem_limit and doubles ops_limit until limits are reached.///+/// This mirrors the established adaptive "sensitive" policy used by the+/// existing web and Flutter clients so that newly generated key attributes+/// remain consistent across platforms.+////// # Arguments/// * `password` - Password bytes./// * `salt` - 16-byte salt.@@ -225,7 +241,7 @@ pub fn derive_sensitive_key_with_salt_adaptive(}let mut last_error = None;- while mem_limit >= MEMLIMIT_MIN {+ while mem_limit > MEMLIMIT_MIN {match derive_key_bytes(password, salt, mem_limit, ops_limit) {Ok(key) => {return Ok(DerivedKeyResult {@@ -250,7 +266,7 @@ pub fn derive_sensitive_key_with_salt_adaptive(Err(last_error.unwrap_or(CryptoError::KeyDerivationFailed))}-/// Derive a key with sensitive parameters (maximum security).+/// Derive a key with the current adaptive sensitive client policy.////// Uses adaptive mem/ops fallback while preserving sensitive strength.///@@ -415,6 +431,48 @@ mod tests {);assert!(result.mem_limit <= MEMLIMIT_MODERATE);assert!(result.ops_limit >= OPSLIMIT_SENSITIVE);+ assert!(result.mem_limit > MEMLIMIT_MIN);+ }++ #[test]+ fn test_sensitive_policy_matches_existing_client_bounds() {+ let desired_strength = u64::from(MEMLIMIT_SENSITIVE) * u64::from(OPSLIMIT_SENSITIVE);+ let factor = MEMLIMIT_SENSITIVE / MEMLIMIT_MODERATE;+ let mut mem_limit = MEMLIMIT_MODERATE;+ let mut ops_limit = OPSLIMIT_SENSITIVE * factor;+ let mut attempts = Vec::new();++ while mem_limit > MEMLIMIT_MIN {+ attempts.push((mem_limit, ops_limit));+ mem_limit /= 2;+ ops_limit *= 2;+ }++ assert_eq!(+ attempts.first(),+ Some(&(MEMLIMIT_MODERATE, OPSLIMIT_SENSITIVE * factor))+ );+ assert!(attempts.last().unwrap().0 > MEMLIMIT_MIN);+ assert!(+ attempts+ .iter()+ .all(|(mem, ops)| u64::from(*mem) * u64::from(*ops) == desired_strength)+ );+ }++ #[test]+ fn test_derived_key_result_debug_redacts_secret_material() {+ let result = DerivedKeyResult {+ key: vec![1, 2, 3],+ salt: vec![4, 5, 6],+ mem_limit: 123,+ ops_limit: 456,+ };++ let debug = format!("{result:?}");+ assert!(debug.contains("[REDACTED]"));+ assert!(!debug.contains("[1, 2, 3]"));+ assert!(debug.contains("salt_len"));}#[test]diff --git a/rust/core/src/http.rs b/rust/core/src/http.rsindex eaaf8b849e..d91aeca6e3 100644--- a/rust/core/src/http.rs+++ b/rust/core/src/http.rs@@ -1,5 +1,6 @@//! HTTP client for communicating with the Ente API.+use reqwest::Url;use serde::Deserialize;use thiserror::Error;@@ -22,6 +23,10 @@ pub enum Error {/// Failed to parse JSON response.#[error("JSON parse error: {0}")]Parse(String),++ /// Invalid base URL or request path.+ #[error("Invalid URL: {0}")]+ InvalidUrl(String),}impl From<reqwest::Error> for Error {@@ -77,13 +82,46 @@ impl HttpClient {/// GET request, returns response body as text.pub async fn get(&self, path: &str) -> Result<String, Error> {- let url = format!("{}{}", self.base_url, path);- let response = self.client.get(&url).send().await?;+ let url = self.resolve_url(path)?;+ let response = self.client.get(url).send().await?;let response = response.error_for_status()?;let text = response.text().await?;Ok(text)}+ fn resolve_url(&self, path: &str) -> Result<Url, Error> {+ if !path.starts_with('/') || path.starts_with("//") {+ return Err(Error::InvalidUrl(+ "request paths must start with a single '/'".to_string(),+ ));+ }++ let path_only = path+ .split_once(['?', '#'])+ .map_or(path, |(path_only, _)| path_only);+ if path_only+ .split('/')+ .any(|segment| matches!(segment, "." | ".."))+ {+ return Err(Error::InvalidUrl(+ "request paths must not contain dot segments".to_string(),+ ));+ }++ let mut base = Url::parse(&self.base_url)+ .map_err(|e| Error::InvalidUrl(format!("invalid base URL: {e}")))?;++ let base_path = base.path().trim_end_matches('/');+ let resolved_path = if base_path.is_empty() || base_path == "/" {+ path.to_string()+ } else {+ format!("{base_path}{path}")+ };++ base.set_path(&resolved_path);+ Ok(base)+ }+/// Ping the API, returns [PingResponse].pub async fn ping(&self) -> Result<PingResponse, Error> {let text = self.get("/ping").await?;@@ -96,9 +134,16 @@ impl HttpClient {mod tests {use super::*;+ fn test_client(base_url: &str) -> HttpClient {+ HttpClient {+ client: reqwest::Client::builder().no_proxy().build().unwrap(),+ base_url: base_url.to_string(),+ }+ }+#[test]fn test_client_creation() {- let client = HttpClient::new("https://api.ente.io");+ let client = test_client("https://api.ente.io");assert_eq!(client.base_url, "https://api.ente.io");}@@ -109,4 +154,39 @@ mod tests {println!("{:?}", err);assert!(matches!(err, Err(Error::Parse(_))))}++ #[test]+ fn test_resolve_url_uses_origin_path_join() {+ let client = test_client("https://api.ente.io/v1");+ let url = client.resolve_url("/ping").unwrap();+ assert_eq!(url.as_str(), "https://api.ente.io/v1/ping");+ }++ #[test]+ fn test_resolve_url_rejects_host_confusion_payload() {+ let client = test_client("https://api.ente.io");+ let err = client.resolve_url("@attacker.com").unwrap_err();+ assert!(matches!(err, Error::InvalidUrl(_)));+ }++ #[test]+ fn test_resolve_url_rejects_protocol_relative_path() {+ let client = test_client("https://api.ente.io");+ let err = client.resolve_url("//attacker.com").unwrap_err();+ assert!(matches!(err, Error::InvalidUrl(_)));+ }++ #[test]+ fn test_resolve_url_rejects_dot_segments() {+ let client = test_client("https://api.ente.io/v1");+ let err = client.resolve_url("/../admin").unwrap_err();+ assert!(matches!(err, Error::InvalidUrl(_)));+ }++ #[test]+ fn test_resolve_url_rejects_invalid_base_url() {+ let client = test_client("not a url");+ let err = client.resolve_url("/ping").unwrap_err();+ assert!(matches!(err, Error::InvalidUrl(_)));+ }}diff --git a/web/packages/wasm/src/http.rs b/web/packages/wasm/src/http.rsindex 3903da1c1a..8faf0c5341 100644--- a/web/packages/wasm/src/http.rs+++ b/web/packages/wasm/src/http.rs@@ -35,6 +35,11 @@ impl HttpError {impl From<CoreError> for HttpError {fn from(e: CoreError) -> Self {match e {+ CoreError::InvalidUrl(message) => HttpError {+ code: "invalid_url".to_string(),+ message,+ status: None,+ },CoreError::Network(message) => HttpError {code: "network".to_string(),message,