π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
rust/accounts: inject async sleep for timers
Neeraj Gupta1247afdcfcd0
diff --git a/rust/accounts/Cargo.lock b/rust/accounts/Cargo.lockindex e0affaa733..e2afb1723e 100644--- a/rust/accounts/Cargo.lock+++ b/rust/accounts/Cargo.lock@@ -343,6 +343,7 @@ version = "0.0.1"dependencies = ["base64","ente-core",+ "futures-timer","log","mockito","serde",@@ -448,6 +449,12 @@ version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"+[[package]]+name = "futures-timer"+version = "3.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24"+[[package]]name = "futures-util"version = "0.3.32"diff --git a/rust/accounts/Cargo.toml b/rust/accounts/Cargo.tomlindex 4f65f1eb54..28689aa6aa 100644--- a/rust/accounts/Cargo.toml+++ b/rust/accounts/Cargo.toml@@ -9,16 +9,17 @@ serde = { version = "1", features = ["derive"] }serde_json = "1"thiserror = "2"base64 = "0.22"+futures-timer = "3"uuid = { version = "1.11", features = ["js", "serde", "v4"] }zeroize = { version = "1.8", features = ["derive"] }log = "0.4"urlencoding = "2.1"-tokio = { version = "1", features = ["macros", "rt", "time"] }[dev-dependencies]mockito = "1.6"sha2 = "0.10"srp = "0.6"+tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }[lints.rust]missing_docs = "warn"diff --git a/rust/accounts/src/client.rs b/rust/accounts/src/client.rsindex 50e29b61bd..b418a42187 100644--- a/rust/accounts/src/client.rs+++ b/rust/accounts/src/client.rs@@ -7,7 +7,6 @@ use ente_core::{http::{Error as HttpError, HttpClient},};use std::time::Duration;-use tokio::time::sleep;use crate::{error::{Error, Result},@@ -21,7 +20,7 @@ use crate::{TwoFactorStatusResponse, TwoFactorType, UpdateSrpAndKeysRequest, UpdateSrpAndKeysResponse,VerifyEmailRequest, VerifySrpSessionRequest, VerifyTotpRequest,},- types::AccountsClientConfig,+ types::{AccountsClientConfig, SleepFn},};const SRP_A_LEN: usize = 512;@@ -57,16 +56,19 @@ fn require_srp_m2(auth_response: &AuthResponse) -> Result<&str> {pub struct AccountsClient {http: HttpClient,client_package: String,+ sleep_fn: SleepFn,}impl AccountsClient {/// Construct a client from a config.pub fn new(config: AccountsClientConfig) -> Result<Self> {let client_package = config.client_package.clone();+ let sleep_fn = config.sleep_fn();let http = HttpClient::new_with_config(config.into())?;Ok(Self {http,client_package,+ sleep_fn,})}@@ -80,6 +82,10 @@ impl AccountsClient {&self.client_package}+ async fn sleep(&self, duration: Duration) {+ (self.sleep_fn)(duration).await;+ }+fn should_retry(error: &HttpError, policy: RetryPolicy) -> bool {match policy {RetryPolicy::NoRetry => false,@@ -114,7 +120,7 @@ impl AccountsClient {attempt,MAX_RETRIES);- sleep(delay).await;+ self.sleep(delay).await;delay = delay.saturating_mul(2).min(Duration::from_millis(MAX_RETRY_DELAY_MS));@@ -161,7 +167,7 @@ impl AccountsClient {.create_srp_session(&srp_attrs.srp_user_id, &a_pub).await?;- tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;+ self.sleep(Duration::from_millis(100)).await;let server_b = STANDARD.decode(&session.srp_b)?;let proof = srp_session.compute_m1(&server_b)?;@@ -218,8 +224,10 @@ impl AccountsClient {email: email.to_string(),purpose: purpose.to_string(),};- self.execute(RetryPolicy::Default, || self.http.post_empty("/users/ott", &request))- .await+ self.execute(RetryPolicy::Default, || {+ self.http.post_empty("/users/ott", &request)+ })+ .await}/// Verify email ownership with an OTT.@@ -312,8 +320,10 @@ impl AccountsClient {/// Logout the current authenticated session.pub async fn logout(&self) -> Result<()> {let body = serde_json::json!({});- self.execute(RetryPolicy::Default, || self.http.post_empty("/users/logout", &body))- .await+ self.execute(RetryPolicy::Default, || {+ self.http.post_empty("/users/logout", &body)+ })+ .await}/// Return whether two-factor is enabled.@@ -398,9 +408,7 @@ impl AccountsClient {}/// Get passkey recovery status.- pub async fn get_two_factor_recovery_status(- &self,- ) -> Result<TwoFactorRecoveryStatusResponse> {+ pub async fn get_two_factor_recovery_status(&self) -> Result<TwoFactorRecoveryStatusResponse> {self.execute(RetryPolicy::Default, || {self.http.get_json("/users/two-factor/recovery-status", &[])})@@ -443,6 +451,10 @@ mod tests {use super::*;use crate::types::AccountsClientConfig;use mockito::Server;+ use std::sync::{+ Arc,+ atomic::{AtomicUsize, Ordering},+ };fn make_client(base_url: String) -> AccountsClient {AccountsClient::new(@@ -477,6 +489,47 @@ mod tests {second.assert_async().await;}+ #[tokio::test]+ async fn send_otp_uses_configured_sleep_fn_for_retry() {+ let mut server = Server::new_async().await;+ let first = server+ .mock("POST", "/users/ott")+ .with_status(500)+ .with_body("temporary failure")+ .expect(1)+ .create_async()+ .await;+ let second = server+ .mock("POST", "/users/ott")+ .with_status(200)+ .expect(1)+ .create_async()+ .await;++ let sleep_calls = Arc::new(AtomicUsize::new(0));+ let client = AccountsClient::new(+ AccountsClientConfig::new("io.ente.photos")+ .with_base_url(server.url())+ .with_user_agent("ente-accounts-test")+ .with_sleep_fn({+ let sleep_calls = Arc::clone(&sleep_calls);+ move |_| {+ let sleep_calls = Arc::clone(&sleep_calls);+ async move {+ sleep_calls.fetch_add(1, Ordering::SeqCst);+ }+ }+ }),+ )+ .unwrap();++ client.send_otp("[email protected]", "login").await.unwrap();++ assert_eq!(sleep_calls.load(Ordering::SeqCst), 1);+ first.assert_async().await;+ second.assert_async().await;+ }+#[tokio::test]async fn verify_srp_session_does_not_retry_on_server_error() {let mut server = Server::new_async().await;diff --git a/rust/accounts/src/error.rs b/rust/accounts/src/error.rsindex 6890fedd5c..058357c375 100644--- a/rust/accounts/src/error.rs+++ b/rust/accounts/src/error.rs@@ -1,11 +1,7 @@//! Shared error types for account flows.use base64::DecodeError;-use ente_core::{- auth::AuthError,- crypto::CryptoError,- http::Error as HttpError,-};+use ente_core::{auth::AuthError, crypto::CryptoError, http::Error as HttpError};use thiserror::Error;/// Result alias for the shared account crate.diff --git a/rust/accounts/src/flow.rs b/rust/accounts/src/flow.rsindex 7d79175d7e..82e5f33584 100644--- a/rust/accounts/src/flow.rs+++ b/rust/accounts/src/flow.rs@@ -26,7 +26,7 @@ use crate::{AuthResponse, ConfigurePasskeyRecoveryRequest, EnableTwoFactorRequest, KeyAttributes,RemoveTwoFactorRequest, SetRecoveryKeyRequest, SetupSrpRequest, SrpAttributes,TwoFactorAuthorizationResponse, TwoFactorRecoveryResponse, TwoFactorType,- UpdatedKeyAttr, UpdateSrpAndKeysRequest,+ UpdateSrpAndKeysRequest, UpdatedKeyAttr,},types::{AccountSecrets, DEFAULT_ACCOUNTS_URL},};@@ -843,7 +843,10 @@ wherelet srp_b = STANDARD.decode(&response.srp_b)?;let srp_m1 = STANDARD.encode(srp_session.compute_m1(&srp_b)?);- let complete = self.client.complete_srp_setup(&response.setup_id, &srp_m1).await?;+ let complete = self+ .client+ .complete_srp_setup(&response.setup_id, &srp_m1)+ .await?;let srp_m2 = STANDARD.decode(&complete.srp_m2)?;srp_session.verify_m2(&srp_m2).map_err(Error::from)?;Ok(())@@ -1251,8 +1254,7 @@ mod tests {.mock("GET", Matcher::Any).match_request(|request| {request.path() == "/users/srp/attributes"- && request.path_and_query()- == "/users/srp/attributes?email=user%40example.org"+ && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"}).with_status(200).with_body(@@ -1343,8 +1345,7 @@ mod tests {.mock("GET", Matcher::Any).match_request(|request| {request.path() == "/users/srp/attributes"- && request.path_and_query()- == "/users/srp/attributes?email=user%40example.org"+ && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"}).with_status(200).with_body(@@ -1422,8 +1423,7 @@ mod tests {.mock("GET", Matcher::Any).match_request(|request| {request.path() == "/users/srp/attributes"- && request.path_and_query()- == "/users/srp/attributes?email=user%40example.org"+ && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"}).with_status(200).with_body(@@ -1511,8 +1511,7 @@ mod tests {.mock("GET", Matcher::Any).match_request(|request| {request.path() == "/users/srp/attributes"- && request.path_and_query()- == "/users/srp/attributes?email=user%40example.org"+ && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"}).with_status(200).with_body(@@ -1570,7 +1569,10 @@ mod tests {match error {Error::AuthenticationFailed(message) => {- assert_eq!(message, "Too many incorrect TOTP attempts. Please restart login.");+ assert_eq!(+ message,+ "Too many incorrect TOTP attempts. Please restart login."+ );}other => panic!("unexpected error: {other:?}"),}@@ -1662,7 +1664,8 @@ mod tests {let payload: ConfigurePasskeyRecoveryPayload = parse_request_body(request);let cipher = crypto::decode_b64(&payload.user_secret_cipher).unwrap();let nonce = crypto::decode_b64(&payload.user_secret_nonce).unwrap();- let decrypted = secretbox::decrypt(&cipher, &nonce, &expected_recovery_key).unwrap();+ let decrypted =+ secretbox::decrypt(&cipher, &nonce, &expected_recovery_key).unwrap();assert_eq!(payload.secret, "reset-secret");assert_eq!(String::from_utf8(decrypted).unwrap(), "reset-secret");Vec::new()@@ -1700,8 +1703,7 @@ mod tests {.mock("GET", Matcher::Any).match_request(|request| {request.path() == "/users/srp/attributes"- && request.path_and_query()- == "/users/srp/attributes?email=user%40example.org"+ && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"}).with_status(200).with_body(@@ -2074,15 +2076,22 @@ mod tests {.with_body_from_request(move |request| {let payload: UpdateSrpPayload = parse_request_body(request);let state = &mut *state_for_update.lock().unwrap();- assert_eq!(payload.setup_id, state.pending_setup_id.unwrap().to_string());- assert_eq!(STANDARD.decode(&payload.srp_m1).unwrap(), state.pending_client_proof.as_ref().unwrap().clone());+ assert_eq!(+ payload.setup_id,+ state.pending_setup_id.unwrap().to_string()+ );+ assert_eq!(+ STANDARD.decode(&payload.srp_m1).unwrap(),+ state.pending_client_proof.as_ref().unwrap().clone()+ );assert!(payload.log_out_other_devices);- state.remote_srp_attributes = state.remote_srp_attributes.clone().map(|mut attrs| {- attrs.mem_limit = payload.updated_key_attr.mem_limit;- attrs.ops_limit = payload.updated_key_attr.ops_limit;- attrs.kek_salt = payload.updated_key_attr.kek_salt.clone();- attrs- });+ state.remote_srp_attributes =+ state.remote_srp_attributes.clone().map(|mut attrs| {+ attrs.mem_limit = payload.updated_key_attr.mem_limit;+ attrs.ops_limit = payload.updated_key_attr.ops_limit;+ attrs.kek_salt = payload.updated_key_attr.kek_salt.clone();+ attrs+ });serde_json::json!({"setupID": payload.setup_id,"srpM2": STANDARD.encode(state.pending_server_proof.as_ref().unwrap()),@@ -2096,7 +2105,10 @@ mod tests {let state_for_attrs = Arc::clone(&state);let get_srp_attributes = server.mock("GET", "/users/srp/attributes")- .match_query(Matcher::UrlEncoded("email".into(), "[email protected]".into()))+ .match_query(Matcher::UrlEncoded(+ "email".into(),+ "[email protected]".into(),+ )).with_status(200).with_body_from_request(move |_| {let state = state_for_attrs.lock().unwrap();diff --git a/rust/accounts/src/types.rs b/rust/accounts/src/types.rsindex eded713075..71437fc06f 100644--- a/rust/accounts/src/types.rs+++ b/rust/accounts/src/types.rs@@ -1,7 +1,9 @@//! Shared reusable types for account clients.use ente_core::http::HttpConfig;+use futures_timer::Delay;use serde::{Deserialize, Serialize};+use std::{future::Future, pin::Pin, sync::Arc, time::Duration};use zeroize::Zeroize;/// Default base URL for Ente's public API.@@ -10,8 +12,22 @@ pub const DEFAULT_API_BASE_URL: &str = "https://api.ente.io";/// Default base URL for Ente's accounts broker.pub const DEFAULT_ACCOUNTS_URL: &str = "https://accounts.ente.io";+/// Boxed future returned by a configured sleep hook.+pub type SleepFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;++/// Async sleep hook used by high-level account flows for retry/backoff waits.+pub type SleepFn = Arc<dyn Fn(Duration) -> SleepFuture + 'static>;++fn default_sleep_fn() -> SleepFn {+ Arc::new(|duration| {+ Box::pin(async move {+ Delay::new(duration).await;+ })+ })+}+/// Configuration for constructing an [`crate::client::AccountsClient`].-#[derive(Debug, Clone)]+#[derive(Clone)]pub struct AccountsClientConfig {/// Base Ente API URL.pub base_url: String,@@ -25,6 +41,24 @@ pub struct AccountsClientConfig {pub user_agent: Option<String>,/// Optional request timeout.pub timeout_secs: Option<u64>,+ sleep_fn: SleepFn,+}++impl std::fmt::Debug for AccountsClientConfig {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("AccountsClientConfig")+ .field("base_url", &self.base_url)+ .field(+ "auth_token",+ &self.auth_token.as_ref().map(|_| "<redacted>"),+ )+ .field("client_package", &self.client_package)+ .field("client_version", &self.client_version)+ .field("user_agent", &self.user_agent)+ .field("timeout_secs", &self.timeout_secs)+ .field("sleep_fn", &"<configured>")+ .finish()+ }}impl AccountsClientConfig {@@ -37,6 +71,7 @@ impl AccountsClientConfig {client_version: None,user_agent: None,timeout_secs: None,+ sleep_fn: default_sleep_fn(),}}@@ -69,6 +104,20 @@ impl AccountsClientConfig {self.timeout_secs = Some(timeout_secs);self}++ /// Override the async sleep implementation used for retry/backoff waits.+ pub fn with_sleep_fn<F, Fut>(mut self, sleep_fn: F) -> Self+ where+ F: Fn(Duration) -> Fut + 'static,+ Fut: Future<Output = ()> + 'static,+ {+ self.sleep_fn = Arc::new(move |duration| Box::pin(sleep_fn(duration)));+ self+ }++ pub(crate) fn sleep_fn(&self) -> SleepFn {+ Arc::clone(&self.sleep_fn)+ }}impl From<AccountsClientConfig> for HttpConfig {diff --git a/rust/cli/Cargo.lock b/rust/cli/Cargo.lockindex 32a8925cf9..73b6d01c18 100644--- a/rust/cli/Cargo.lock+++ b/rust/cli/Cargo.lock@@ -728,11 +728,11 @@ version = "0.0.1"dependencies = ["base64","ente-core",+ "futures-timer","log","serde","serde_json","thiserror 2.0.16",- "tokio","urlencoding","uuid","zeroize",@@ -1029,6 +1029,12 @@ version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"+[[package]]+name = "futures-timer"+version = "3.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24"+[[package]]name = "futures-util"version = "0.3.31"