Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add rust CLI account auth flow

Neeraj Gupta9ab83b1603c8
diff --git a/rust/cli/Cargo.lock b/rust/cli/Cargo.lock
index 884ebd1017..e5ca776ca0 100644
--- a/rust/cli/Cargo.lock
+++ b/rust/cli/Cargo.lock
@@ -760,6 +760,7 @@ dependencies = [
"ente-core",
"env_logger",
"futures",
+ "hmac",
"indicatif",
"log",
"mockito",
@@ -768,7 +769,10 @@ dependencies = [
"rusqlite",
"serde",
"serde_json",
+ "sha1",
+ "sha2",
"sqlx",
+ "srp",
"tempdir",
"thiserror 2.0.16",
"tokio",
diff --git a/rust/cli/Cargo.toml b/rust/cli/Cargo.toml
index c896b22462..261b90f078 100644
--- a/rust/cli/Cargo.toml
+++ b/rust/cli/Cargo.toml
@@ -43,5 +43,9 @@ open = "5.0"
zip = "2.2"
[dev-dependencies]
+hmac = "0.12"
mockito = "1.6"
+sha2 = "0.10"
+srp = "0.6"
+sha1 = "0.10"
tempdir = "0.3"
diff --git a/rust/cli/src/api/auth.rs b/rust/cli/src/api/auth.rs
index 43e8009656..b242e1cfbe 100644
--- a/rust/cli/src/api/auth.rs
+++ b/rust/cli/src/api/auth.rs
@@ -1,7 +1,9 @@
use crate::api::client::ApiClient;
use crate::api::models::{
- AuthResponse, CreateSrpSessionRequest, CreateSrpSessionResponse, GetSrpAttributesResponse,
- SendOtpRequest, SrpAttributes, VerifyEmailRequest, VerifySrpSessionRequest, VerifyTotpRequest,
+ AuthResponse, CompleteSrpSetupRequest, CompleteSrpSetupResponse, CreateSrpSessionRequest,
+ CreateSrpSessionResponse, EnableTwoFactorRequest, GetSrpAttributesResponse, SendOtpRequest,
+ SessionValidityResponse, SetUserAttributesRequest, SetupSrpRequest, SetupSrpResponse,
+ SrpAttributes, TwoFactorSecret, VerifyEmailRequest, VerifySrpSessionRequest, VerifyTotpRequest,
};
use crate::models::error::Result;
use base64::{Engine, engine::general_purpose::STANDARD};
@@ -135,25 +137,70 @@ impl<'a> AuthClient<'a> {
}
/// Send OTP for email verification
- pub async fn send_login_otp(&self, email: &str) -> Result<()> {
+ pub async fn send_otp(&self, email: &str, purpose: &str) -> Result<()> {
let request = SendOtpRequest {
email: email.to_string(),
- purpose: "login".to_string(),
+ purpose: purpose.to_string(),
};
self.api.post_empty("/users/ott", &request, None).await
}
/// Verify email with OTP
- pub async fn verify_email(&self, email: &str, otp: &str) -> Result<AuthResponse> {
+ pub async fn verify_email(
+ &self,
+ email: &str,
+ otp: &str,
+ source: Option<&str>,
+ ) -> Result<AuthResponse> {
let request = VerifyEmailRequest {
email: email.to_string(),
ott: otp.to_string(),
+ source: source.map(str::to_string),
};
self.api.post("/users/verify-email", &request, None).await
}
+ /// Upload key attributes for the authenticated user
+ pub async fn set_user_key_attributes(
+ &self,
+ account_id: &str,
+ key_attributes: crate::api::models::KeyAttributes,
+ ) -> Result<()> {
+ let request = SetUserAttributesRequest { key_attributes };
+ self.api
+ .put_empty("/users/attributes", &request, Some(account_id))
+ .await
+ }
+
+ /// Start SRP setup for the authenticated user
+ pub async fn setup_srp(
+ &self,
+ account_id: &str,
+ request: &SetupSrpRequest,
+ ) -> Result<SetupSrpResponse> {
+ self.api
+ .post("/users/srp/setup", request, Some(account_id))
+ .await
+ }
+
+ /// Complete SRP setup for the authenticated user
+ pub async fn complete_srp_setup(
+ &self,
+ account_id: &str,
+ setup_id: &Uuid,
+ srp_m1: &str,
+ ) -> Result<CompleteSrpSetupResponse> {
+ let request = CompleteSrpSetupRequest {
+ setup_id: setup_id.to_string(),
+ srp_m1: srp_m1.to_string(),
+ };
+ self.api
+ .post("/users/srp/complete", &request, Some(account_id))
+ .await
+ }
+
/// Verify TOTP for two-factor authentication
pub async fn verify_totp(&self, session_id: &str, code: &str) -> Result<AuthResponse> {
let request = VerifyTotpRequest {
@@ -171,6 +218,32 @@ impl<'a> AuthClient<'a> {
let url = format!("/users/two-factor/passkeys/get-token?sessionID={session_id}");
self.api.get(&url, None).await
}
+
+ /// Read the current user's key attributes if already configured
+ pub async fn get_session_validity(&self, account_id: &str) -> Result<SessionValidityResponse> {
+ self.api
+ .get("/users/session-validity/v2", Some(account_id))
+ .await
+ }
+
+ /// Start TOTP setup and receive the secret and QR code
+ pub async fn setup_two_factor(&self, account_id: &str) -> Result<TwoFactorSecret> {
+ let request = serde_json::json!({});
+ self.api
+ .post("/users/two-factor/setup", &request, Some(account_id))
+ .await
+ }
+
+ /// Enable TOTP with the encrypted recovery secret
+ pub async fn enable_two_factor(
+ &self,
+ account_id: &str,
+ request: &EnableTwoFactorRequest,
+ ) -> Result<()> {
+ self.api
+ .post_empty("/users/two-factor/enable", request, Some(account_id))
+ .await
+ }
}
#[cfg(test)]
diff --git a/rust/cli/src/api/client.rs b/rust/cli/src/api/client.rs
index 3fc2da1c5f..814e582110 100644
--- a/rust/cli/src/api/client.rs
+++ b/rust/cli/src/api/client.rs
@@ -12,7 +12,7 @@ use tokio::time::sleep;
const ENTE_API_ENDPOINT: &str = "https://api.ente.io";
const TOKEN_HEADER: &str = "X-Auth-Token";
const CLIENT_PKG_HEADER: &str = "X-Client-Package";
-const CLIENT_PACKAGE: &str = "io.ente.cli";
+const DEFAULT_CLIENT_PACKAGE: &str = "io.ente.photos";
/// Maximum number of retry attempts for failed requests
const MAX_RETRIES: u32 = 3;
@@ -62,6 +62,7 @@ pub struct ApiClient {
client: Client,
download_client: Client,
pub(crate) base_url: String,
+ client_package: String,
/// Token storage for multi-account support: account_id -> token
tokens: Arc<RwLock<HashMap<String, String>>>,
/// Retry configuration
@@ -70,6 +71,13 @@ pub struct ApiClient {
impl ApiClient {
pub fn new(base_url: Option<String>) -> Result<Self> {
+ Self::new_with_client_package(base_url, DEFAULT_CLIENT_PACKAGE)
+ }
+
+ pub fn new_with_client_package<S>(base_url: Option<String>, client_package: S) -> Result<Self>
+ where
+ S: Into<String>,
+ {
let client = Client::builder()
.timeout(Duration::from_secs(30))
.user_agent(format!("ente-cli-rust/{}", env!("CARGO_PKG_VERSION")))
@@ -86,6 +94,7 @@ impl ApiClient {
client,
download_client,
base_url: base_url.unwrap_or_else(|| ENTE_API_ENDPOINT.to_string()),
+ client_package: client_package.into(),
tokens: Arc::new(RwLock::new(HashMap::new())),
retry_config: RetryConfig::default(),
})
@@ -116,7 +125,7 @@ impl ApiClient {
/// Build a request with common headers
fn build_request(&self, builder: RequestBuilder, account_id: Option<&str>) -> RequestBuilder {
- let mut req = builder.header(CLIENT_PKG_HEADER, CLIENT_PACKAGE);
+ let mut req = builder.header(CLIENT_PKG_HEADER, &self.client_package);
if let Some(id) = account_id {
if let Some(token) = self.get_token(id) {
@@ -298,6 +307,29 @@ impl ApiClient {
})
}
+ /// Make a PUT request that expects no response body
+ pub async fn put_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.put(&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 body = response
+ .text()
+ .await
+ .unwrap_or_else(|_| "Unknown error".to_string());
+ return Err(make_api_error("PUT", path, status, body));
+ }
+
+ Ok(())
+ }
+
/// Make a DELETE request
pub async fn delete(&self, path: &str, account_id: Option<&str>) -> Result<()> {
let url = format!("{}{}", self.base_url, path);
diff --git a/rust/cli/src/api/models.rs b/rust/cli/src/api/models.rs
index 94fb9f471c..381a4351c8 100644
--- a/rust/cli/src/api/models.rs
+++ b/rust/cli/src/api/models.rs
@@ -55,7 +55,7 @@ pub struct VerifySrpSessionRequest {
pub srp_m1: String,
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyAttributes {
pub kek_salt: String,
@@ -67,6 +67,10 @@ pub struct KeyAttributes {
pub secret_key_decryption_nonce: String,
pub mem_limit: i32,
pub ops_limit: i32,
+ 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>,
+ pub recovery_key_decryption_nonce: Option<String>,
}
#[derive(Debug, Deserialize)]
@@ -119,6 +123,8 @@ pub struct SendOtpRequest {
pub struct VerifyEmailRequest {
pub email: String,
pub ott: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub source: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -128,6 +134,70 @@ pub struct VerifyTotpRequest {
pub code: String,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SetUserAttributesRequest {
+ pub key_attributes: KeyAttributes,
+}
+
+#[derive(Debug, Serialize)]
+pub struct SetupSrpRequest {
+ #[serde(rename = "srpUserID")]
+ pub srp_user_id: String,
+ #[serde(rename = "srpSalt")]
+ pub srp_salt: String,
+ #[serde(rename = "srpVerifier")]
+ pub srp_verifier: String,
+ #[serde(rename = "srpA")]
+ pub srp_a: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct SetupSrpResponse {
+ #[serde(rename = "setupID")]
+ pub setup_id: Uuid,
+ #[serde(rename = "srpB")]
+ pub srp_b: String,
+}
+
+#[derive(Debug, Serialize)]
+pub struct CompleteSrpSetupRequest {
+ #[serde(rename = "setupID")]
+ pub setup_id: String,
+ #[serde(rename = "srpM1")]
+ pub srp_m1: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct CompleteSrpSetupResponse {
+ #[serde(rename = "setupID")]
+ pub setup_id: Uuid,
+ #[serde(rename = "srpM2")]
+ pub srp_m2: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SessionValidityResponse {
+ pub has_set_keys: bool,
+ pub key_attributes: Option<KeyAttributes>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TwoFactorSecret {
+ pub secret_code: String,
+ pub qr_code: String,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct EnableTwoFactorRequest {
+ pub code: String,
+ pub encrypted_two_factor_secret: String,
+ pub two_factor_secret_decryption_nonce: String,
+}
+
// ========== User Models ==========
#[derive(Debug, Deserialize)]
diff --git a/rust/cli/src/auth_flow.rs b/rust/cli/src/auth_flow.rs
new file mode 100644
index 0000000000..74e7ce12b3
--- /dev/null
+++ b/rust/cli/src/auth_flow.rs
@@ -0,0 +1,1301 @@
+use crate::{
+ api::{
+ ApiClient, AuthClient,
+ models::{
+ AuthResponse, EnableTwoFactorRequest, KeyAttributes, SetupSrpRequest,
+ SrpAttributes as RemoteSrpAttributes,
+ },
+ },
+ models::{
+ account::{AccountSecrets, App},
+ error::{Error, Result},
+ },
+};
+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,
+ get_recovery_key,
+ },
+ crypto::{self, secretbox},
+};
+use uuid::Uuid;
+
+const SRP_A_LEN: usize = 512; // 4096-bit group
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum OtpPurpose {
+ Login,
+ Signup,
+}
+
+impl OtpPurpose {
+ fn as_api_purpose(self) -> &'static str {
+ match self {
+ OtpPurpose::Login => "login",
+ OtpPurpose::Signup => "signup",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TotpPurpose {
+ Login,
+ Setup,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SecondFactorMethod {
+ Totp,
+ Passkey,
+}
+
+pub trait AuthFlowUi {
+ fn read_email_otp(&mut self, email: &str, purpose: OtpPurpose, resent: bool) -> Result<String>;
+ fn read_totp_code(&mut self, purpose: TotpPurpose) -> Result<String>;
+ fn report_retryable_error(&mut self, message: &str) -> Result<()>;
+ fn choose_second_factor(
+ &mut self,
+ methods: &[SecondFactorMethod],
+ ) -> Result<SecondFactorMethod>;
+ fn present_passkey_verification(&mut self, url: &str) -> Result<()>;
+ fn wait_for_passkey_verification(&mut self) -> Result<()>;
+ fn present_totp_secret(&mut self, secret_code: &str, qr_code: &str) -> Result<()>;
+}
+
+#[derive(Debug)]
+pub struct CreateAccountParams {
+ pub email: String,
+ pub password: String,
+ pub source: Option<String>,
+}
+
+#[derive(Debug)]
+pub struct LoginParams {
+ pub email: String,
+ pub password: String,
+}
+
+#[derive(Debug)]
+pub struct SetupTwoFactorParams {
+ pub account_id: String,
+ pub master_key: Vec<u8>,
+ pub key_attributes: Option<KeyAttributes>,
+}
+
+#[derive(Debug)]
+pub struct AuthenticatedAccount {
+ pub user_id: i64,
+ pub key_attributes: KeyAttributes,
+ pub secrets: AccountSecrets,
+ pub recovery_key: Option<String>,
+}
+
+#[derive(Debug)]
+pub struct SetupTwoFactorResult {
+ pub secret_code: String,
+ pub qr_code: String,
+ pub recovery_key: String,
+}
+
+pub struct AuthFlow<'a, U> {
+ api_client: &'a ApiClient,
+ app: App,
+ ui: &'a mut U,
+}
+
+impl<'a, U> AuthFlow<'a, U>
+where
+ U: AuthFlowUi,
+{
+ pub fn new(api_client: &'a ApiClient, app: App, ui: &'a mut U) -> Self {
+ Self {
+ api_client,
+ app,
+ ui,
+ }
+ }
+
+ pub async fn create_account(
+ &mut self,
+ params: CreateAccountParams,
+ ) -> Result<AuthenticatedAccount> {
+ self.create_account_with_strength(params, KeyDerivationStrength::Sensitive)
+ .await
+ }
+
+ async fn create_account_with_strength(
+ &mut self,
+ params: CreateAccountParams,
+ key_derivation_strength: KeyDerivationStrength,
+ ) -> Result<AuthenticatedAccount> {
+ crypto::init()?;
+
+ let auth_client = AuthClient::new(self.api_client);
+ let email = params.email;
+ let password = params.password;
+
+ auth_client
+ .send_otp(&email, OtpPurpose::Signup.as_api_purpose())
+ .await?;
+
+ let verification = self
+ .verify_email_otp(
+ &auth_client,
+ &email,
+ OtpPurpose::Signup,
+ params.source.as_deref(),
+ )
+ .await?;
+
+ let token = verification.token.clone().ok_or_else(|| {
+ Error::AuthenticationFailed("Signup verification did not return a session token".into())
+ })?;
+
+ self.api_client.add_token(&email, &token);
+ let session_validity = auth_client.get_session_validity(&email).await?;
+ if verification.key_attributes.is_some()
+ || verification.encrypted_token.is_some()
+ || verification.is_mfa_required()
+ || verification.is_passkey_required()
+ || session_validity.has_set_keys
+ || session_validity.key_attributes.is_some()
+ {
+ return Err(Error::AuthenticationFailed(
+ "Email already has server-side key state; use 'ente account add' or recover the incomplete signup instead of creating a new account.".into(),
+ ));
+ }
+
+ let key_gen_result = generate_keys_with_strength(&password, key_derivation_strength)?;
+
+ let srp_user_id = Uuid::new_v4();
+ let srp_setup =
+ generate_srp_setup(&key_gen_result.key_encryption_key, &srp_user_id.to_string())?;
+ let key_attributes = to_api_key_attributes(&key_gen_result.key_attributes);
+
+ auth_client
+ .set_user_key_attributes(&email, key_attributes.clone())
+ .await?;
+ self.complete_signup_srp(&auth_client, &email, &srp_user_id, &srp_setup)
+ .await?;
+ let remote_srp_attributes = auth_client.get_srp_attributes(&email).await?;
+ validate_remote_srp_attributes(
+ &remote_srp_attributes,
+ &srp_user_id,
+ &srp_setup,
+ &key_attributes,
+ )?;
+
+ let secrets = AccountSecrets {
+ token: decode_plain_token(&token)?,
+ master_key: crypto::decode_b64(&key_gen_result.private_key_attributes.key)?,
+ secret_key: crypto::decode_b64(&key_gen_result.private_key_attributes.secret_key)?,
+ public_key: crypto::decode_b64(&key_attributes.public_key)?,
+ };
+
+ Ok(AuthenticatedAccount {
+ user_id: verification.id,
+ key_attributes,
+ secrets,
+ recovery_key: Some(key_gen_result.private_key_attributes.recovery_key),
+ })
+ }
+
+ pub async fn login(&mut self, params: LoginParams) -> Result<AuthenticatedAccount> {
+ crypto::init()?;
+
+ let auth_client = AuthClient::new(self.api_client);
+ let srp_attrs = auth_client.get_srp_attributes(&params.email).await?;
+
+ let (auth_response, kek) = if srp_attrs.is_email_mfa_enabled {
+ auth_client
+ .send_otp(&params.email, OtpPurpose::Login.as_api_purpose())
+ .await?;
+ let response = self
+ .verify_email_otp(&auth_client, &params.email, OtpPurpose::Login, None)
+ .await?;
+ let response = self.resolve_second_factor(&auth_client, response).await?;
+ let kek = derive_kek(
+ &params.password,
+ &srp_attrs.kek_salt,
+ srp_attrs.mem_limit as u32,
+ srp_attrs.ops_limit as u32,
+ )?;
+ (response, kek)
+ } else {
+ let (response, kek) = auth_client
+ .login_with_srp(&params.email, &params.password)
+ .await?;
+ let response = self.resolve_second_factor(&auth_client, response).await?;
+ (response, kek)
+ };
+
+ self.build_authenticated_account(auth_response, &kek)
+ }
+
+ pub async fn setup_two_factor(
+ &mut self,
+ params: SetupTwoFactorParams,
+ ) -> Result<SetupTwoFactorResult> {
+ crypto::init()?;
+
+ let auth_client = AuthClient::new(self.api_client);
+ let key_attributes = if let Some(key_attributes) = params.key_attributes {
+ key_attributes
+ } else {
+ auth_client
+ .get_session_validity(&params.account_id)
+ .await?
+ .key_attributes
+ .ok_or_else(|| {
+ Error::AuthenticationFailed(
+ "Account keys are not available for two-factor setup".into(),
+ )
+ })?
+ };
+
+ let recovery_key =
+ get_recovery_key(&params.master_key, &to_core_key_attributes(&key_attributes))
+ .map_err(Error::from)?;
+
+ let secret = auth_client.setup_two_factor(&params.account_id).await?;
+ self.ui
+ .present_totp_secret(&secret.secret_code, &secret.qr_code)?;
+
+ loop {
+ let code = self.ui.read_totp_code(TotpPurpose::Setup)?;
+ let request = encrypt_two_factor_secret(&secret.secret_code, &recovery_key, &code)?;
+
+ match auth_client
+ .enable_two_factor(&params.account_id, &request)
+ .await
+ {
+ Ok(()) => {
+ return Ok(SetupTwoFactorResult {
+ secret_code: secret.secret_code,
+ qr_code: secret.qr_code,
+ recovery_key,
+ });
+ }
+ Err(Error::ApiError {
+ status: 400 | 401, ..
+ }) => {
+ self.ui.report_retryable_error(
+ "Incorrect TOTP code. Enter the current code from your authenticator app and try again.",
+ )?;
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ }
+
+ fn build_authenticated_account(
+ &self,
+ auth_response: AuthResponse,
+ kek: &[u8],
+ ) -> Result<AuthenticatedAccount> {
+ let key_attributes = auth_response
+ .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 public_key = crypto::decode_b64(&key_attributes.public_key)?;
+ let recovery_key = get_recovery_key(&secrets.master_key, &core_key_attributes).ok();
+
+ Ok(AuthenticatedAccount {
+ user_id: auth_response.id,
+ key_attributes,
+ secrets: AccountSecrets {
+ token: secrets.token,
+ master_key: secrets.master_key,
+ secret_key: secrets.secret_key,
+ public_key,
+ },
+ recovery_key,
+ })
+ }
+
+ async fn verify_email_otp(
+ &mut self,
+ auth_client: &AuthClient<'_>,
+ email: &str,
+ purpose: OtpPurpose,
+ source: Option<&str>,
+ ) -> Result<AuthResponse> {
+ let mut resent = false;
+
+ loop {
+ let otp = self.ui.read_email_otp(email, purpose, resent)?;
+ match auth_client.verify_email(email, &otp, source).await {
+ Ok(response) => return Ok(response),
+ Err(Error::ApiError {
+ status: 400 | 401, ..
+ }) => {
+ self.ui
+ .report_retryable_error("Incorrect email verification code. Try again.")?;
+ resent = false;
+ }
+ Err(Error::ApiError { status: 410, .. }) => {
+ auth_client
+ .send_otp(email, purpose.as_api_purpose())
+ .await?;
+ resent = true;
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ }
+
+ async fn resolve_second_factor(
+ &mut self,
+ auth_client: &AuthClient<'_>,
+ auth_response: AuthResponse,
+ ) -> Result<AuthResponse> {
+ let has_totp = auth_response.get_two_factor_session_id().is_some();
+ let has_passkey = auth_response.is_passkey_required();
+
+ let method = match (has_totp, has_passkey) {
+ (false, false) => return Ok(auth_response),
+ (true, false) => SecondFactorMethod::Totp,
+ (false, true) => SecondFactorMethod::Passkey,
+ (true, true) => self
+ .ui
+ .choose_second_factor(&[SecondFactorMethod::Totp, SecondFactorMethod::Passkey])?,
+ };
+
+ match method {
+ SecondFactorMethod::Totp => self.verify_totp(auth_client, &auth_response).await,
+ SecondFactorMethod::Passkey => self.verify_passkey(auth_client, &auth_response).await,
+ }
+ }
+
+ async fn verify_totp(
+ &mut self,
+ auth_client: &AuthClient<'_>,
+ auth_response: &AuthResponse,
+ ) -> Result<AuthResponse> {
+ let session_id = auth_response
+ .get_two_factor_session_id()
+ .ok_or_else(|| Error::AuthenticationFailed("No 2FA session ID".into()))?;
+
+ loop {
+ let code = self.ui.read_totp_code(TotpPurpose::Login)?;
+ match auth_client.verify_totp(session_id, &code).await {
+ Ok(response) => return Ok(response),
+ Err(Error::ApiError {
+ status: 400 | 401, ..
+ }) => {
+ self.ui
+ .report_retryable_error("Incorrect TOTP code. Try again.")?;
+ }
+ Err(Error::ApiError { status: 410, .. }) => {
+ return Err(Error::AuthenticationFailed(
+ "TOTP session expired. Please restart login.".into(),
+ ));
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ }
+
+ async fn verify_passkey(
+ &mut self,
+ auth_client: &AuthClient<'_>,
+ auth_response: &AuthResponse,
+ ) -> Result<AuthResponse> {
+ let passkey_session_id = auth_response
+ .passkey_session_id
+ .as_ref()
+ .filter(|session_id| !session_id.is_empty())
+ .ok_or_else(|| Error::AuthenticationFailed("No passkey session ID".into()))?;
+
+ let accounts_url = auth_response
+ .accounts_url
+ .as_ref()
+ .filter(|url| !url.is_empty())
+ .map(String::as_str)
+ .unwrap_or("https://accounts.ente.io");
+
+ let verification_url = format!(
+ "{accounts_url}/passkeys/verify?passkeySessionID={passkey_session_id}&redirect=ente-cli://passkey&clientPackage={}",
+ self.app.client_package()
+ );
+
+ self.ui.present_passkey_verification(&verification_url)?;
+
+ loop {
+ self.ui.wait_for_passkey_verification()?;
+ match auth_client.check_passkey_status(passkey_session_id).await {
+ Ok(result) => return Ok(result),
+ Err(Error::ApiError {
+ status: 400 | 404, ..
+ }) => {}
+ Err(Error::ApiError { status: 410, .. }) => {
+ return Err(Error::AuthenticationFailed(
+ "Passkey session expired. Please restart login.".into(),
+ ));
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ }
+
+ async fn complete_signup_srp(
+ &self,
+ auth_client: &AuthClient<'_>,
+ account_id: &str,
+ srp_user_id: &Uuid,
+ srp_setup: &GeneratedSrpSetup,
+ ) -> Result<()> {
+ let mut srp_session = auth::SrpSession::new(
+ &srp_user_id.to_string(),
+ &srp_setup.srp_salt,
+ &srp_setup.login_sub_key,
+ )?;
+ let srp_a = STANDARD.encode(pad_left(&srp_session.public_a(), SRP_A_LEN));
+
+ let response = auth_client
+ .setup_srp(
+ account_id,
+ &SetupSrpRequest {
+ srp_user_id: srp_user_id.to_string(),
+ srp_salt: STANDARD.encode(&srp_setup.srp_salt),
+ srp_verifier: STANDARD.encode(&srp_setup.srp_verifier),
+ srp_a,
+ },
+ )
+ .await?;
+
+ let srp_b = STANDARD.decode(&response.srp_b)?;
+ let srp_m1 = STANDARD.encode(srp_session.compute_m1(&srp_b)?);
+
+ let complete = auth_client
+ .complete_srp_setup(account_id, &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(())
+ }
+}
+
+fn pad_left(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
+}
+
+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<Vec<u8>> {
+ URL_SAFE
+ .decode(token)
+ .or_else(|_| STANDARD.decode(token))
+ .map_err(|e| Error::Crypto(format!("token: {e}")))
+}
+
+fn decrypt_auth_response(
+ auth_response: &AuthResponse,
+ key_attributes: &CoreKeyAttributes,
+ kek: &[u8],
+) -> Result<DecryptedSecrets> {
+ if let Some(encrypted_token) = auth_response.encrypted_token.as_deref() {
+ auth::decrypt_secrets(kek, key_attributes, encrypted_token).map_err(Error::from)
+ } else if let Some(token) = auth_response.token.as_deref() {
+ let (master_key, secret_key) = auth::decrypt_keys_only(kek, key_attributes)?;
+ Ok(DecryptedSecrets {
+ master_key,
+ secret_key,
+ token: decode_plain_token(token)?,
+ })
+ } else {
+ Err(Error::AuthenticationFailed("No token in response".into()))
+ }
+}
+
+fn validate_remote_srp_attributes(
+ remote: &RemoteSrpAttributes,
+ srp_user_id: &Uuid,
+ srp_setup: &GeneratedSrpSetup,
+ key_attributes: &KeyAttributes,
+) -> Result<()> {
+ let expected_salt = STANDARD.encode(&srp_setup.srp_salt);
+
+ let mut mismatches = Vec::new();
+
+ if remote.srp_user_id != *srp_user_id {
+ mismatches.push("srpUserID");
+ }
+ if remote.srp_salt != expected_salt {
+ mismatches.push("srpSalt");
+ }
+ if remote.kek_salt != key_attributes.kek_salt {
+ mismatches.push("kekSalt");
+ }
+ if remote.mem_limit != key_attributes.mem_limit {
+ mismatches.push("memLimit");
+ }
+ if remote.ops_limit != key_attributes.ops_limit {
+ mismatches.push("opsLimit");
+ }
+
+ if !mismatches.is_empty() {
+ return Err(Error::AuthenticationFailed(format!(
+ "Remote SRP attributes mismatched after signup: {}",
+ mismatches.join(", ")
+ )));
+ }
+
+ Ok(())
+}
+
+fn encrypt_two_factor_secret(
+ secret_code: &str,
+ recovery_key_hex: &str,
+ code: &str,
+) -> Result<EnableTwoFactorRequest> {
+ let recovery_key = crypto::decode_hex(recovery_key_hex)?;
+ let encrypted = secretbox::encrypt_with_key(secret_code.as_bytes(), &recovery_key)?;
+
+ Ok(EnableTwoFactorRequest {
+ code: code.to_string(),
+ encrypted_two_factor_secret: crypto::encode_b64(&encrypted.ciphertext),
+ two_factor_secret_decryption_nonce: crypto::encode_b64(&encrypted.nonce),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use mockito::{Matcher, Server};
+ use serde::{Deserialize, de::DeserializeOwned};
+ use sha2::{Digest, Sha256};
+ use srp::{groups::G_4096, server::SrpServer};
+ use std::{
+ collections::VecDeque,
+ sync::{Arc, Mutex},
+ };
+
+ #[derive(Default)]
+ struct MockSignupState {
+ uploaded_key_attributes: Option<KeyAttributes>,
+ remote_srp_attributes: Option<RemoteSrpAttributes>,
+ pending_setup_id: Option<Uuid>,
+ pending_client_proof: Option<Vec<u8>>,
+ pending_server_proof: Option<Vec<u8>>,
+ }
+
+ #[derive(Debug, Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct SetUserAttributesPayload {
+ key_attributes: KeyAttributes,
+ }
+
+ #[derive(Debug, Deserialize)]
+ struct SetupSrpPayload {
+ #[serde(rename = "srpUserID")]
+ srp_user_id: String,
+ #[serde(rename = "srpSalt")]
+ srp_salt: String,
+ #[serde(rename = "srpVerifier")]
+ srp_verifier: String,
+ #[serde(rename = "srpA")]
+ srp_a: String,
+ }
+
+ #[derive(Debug, Deserialize)]
+ struct CompleteSrpSetupPayload {
+ #[serde(rename = "setupID")]
+ setup_id: String,
+ #[serde(rename = "srpM1")]
+ srp_m1: String,
+ }
+
+ fn parse_request_body<T>(request: &mockito::Request) -> T
+ where
+ T: DeserializeOwned,
+ {
+ serde_json::from_str(&request.utf8_lossy_body().unwrap()).unwrap()
+ }
+
+ struct ScriptedUi {
+ email_otps: VecDeque<String>,
+ login_totps: VecDeque<String>,
+ setup_totps: VecDeque<String>,
+ chosen_second_factor: Option<SecondFactorMethod>,
+ last_totp_secret: Option<String>,
+ passkey_presented: bool,
+ retryable_errors: Vec<String>,
+ }
+
+ impl ScriptedUi {
+ fn new() -> Self {
+ Self {
+ email_otps: VecDeque::new(),
+ login_totps: VecDeque::new(),
+ setup_totps: VecDeque::new(),
+ chosen_second_factor: None,
+ last_totp_secret: None,
+ passkey_presented: false,
+ retryable_errors: Vec::new(),
+ }
+ }
+ }
+
+ impl AuthFlowUi for ScriptedUi {
+ fn read_email_otp(
+ &mut self,
+ _email: &str,
+ _purpose: OtpPurpose,
+ _resent: bool,
+ ) -> Result<String> {
+ self.email_otps
+ .pop_front()
+ .ok_or_else(|| Error::InvalidInput("No scripted email OTP available".into()))
+ }
+
+ fn read_totp_code(&mut self, purpose: TotpPurpose) -> Result<String> {
+ let queue = match purpose {
+ TotpPurpose::Login => &mut self.login_totps,
+ TotpPurpose::Setup => &mut self.setup_totps,
+ };
+
+ queue
+ .pop_front()
+ .ok_or_else(|| Error::InvalidInput("No scripted TOTP code available".into()))
+ }
+
+ fn report_retryable_error(&mut self, message: &str) -> Result<()> {
+ self.retryable_errors.push(message.to_string());
+ Ok(())
+ }
+
+ fn choose_second_factor(
+ &mut self,
+ methods: &[SecondFactorMethod],
+ ) -> Result<SecondFactorMethod> {
+ if let Some(choice) = self.chosen_second_factor {
+ Ok(choice)
+ } else {
+ methods
+ .first()
+ .copied()
+ .ok_or_else(|| Error::InvalidInput("No second-factor method available".into()))
+ }
+ }
+
+ fn present_passkey_verification(&mut self, _url: &str) -> Result<()> {
+ self.passkey_presented = true;
+ Ok(())
+ }
+
+ fn wait_for_passkey_verification(&mut self) -> Result<()> {
+ Ok(())
+ }
+
+ fn present_totp_secret(&mut self, secret_code: &str, _qr_code: &str) -> Result<()> {
+ self.last_totp_secret = Some(secret_code.to_string());
+ Ok(())
+ }
+ }
+
+ fn build_login_response(
+ password: &str,
+ token: &str,
+ ) -> (KeyAttributes, String, String, String, String) {
+ 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 encrypted_token = {
+ let public_key = crypto::decode_b64(&key_attributes.public_key).unwrap();
+ let sealed = crypto::sealed::seal(token.as_bytes(), &public_key).unwrap();
+ crypto::encode_b64(&sealed)
+ };
+
+ (
+ key_attributes,
+ encrypted_token,
+ key_gen.private_key_attributes.recovery_key,
+ key_gen.private_key_attributes.key,
+ key_gen.private_key_attributes.secret_key,
+ )
+ }
+
+ #[tokio::test]
+ async fn login_with_email_mfa_and_totp_decrypts_account() {
+ crypto::init().unwrap();
+
+ let password = "hunter2";
+ let (key_attributes, encrypted_token, recovery_key, _, _) =
+ build_login_response(password, "plain-auth-token");
+
+ let mut server = Server::new_async().await;
+ let mut ui = ScriptedUi::new();
+ ui.email_otps.push_back("123456".into());
+ ui.login_totps.push_back("654321".into());
+
+ let srp_attrs = server
+ .mock("GET", Matcher::Any)
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "attributes": {
+ "srpUserID": Uuid::new_v4(),
+ "srpSalt": STANDARD.encode([1u8; 16]),
+ "memLimit": key_attributes.mem_limit,
+ "opsLimit": key_attributes.ops_limit,
+ "kekSalt": key_attributes.kek_salt,
+ "isEmailMFAEnabled": true
+ }
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let ott = server
+ .mock("POST", "/users/ott")
+ .with_status(200)
+ .create_async()
+ .await;
+
+ let verify_email = server
+ .mock("POST", "/users/verify-email")
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "id": 77,
+ "twoFactorSessionID": "session-1",
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let verify_totp = server
+ .mock("POST", "/users/two-factor/verify")
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "id": 77,
+ "keyAttributes": key_attributes,
+ "encryptedToken": encrypted_token,
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let api_client = ApiClient::new(Some(server.url())).unwrap();
+ let mut flow = AuthFlow::new(&api_client, App::Photos, &mut ui);
+
+ let result = flow
+ .login(LoginParams {
+ email: "[email protected]".into(),
+ password: password.into(),
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(result.user_id, 77);
+ assert_eq!(result.secrets.token, b"plain-auth-token");
+ assert_eq!(result.recovery_key.as_deref(), Some(recovery_key.as_str()));
+
+ srp_attrs.assert_async().await;
+ ott.assert_async().await;
+ verify_email.assert_async().await;
+ verify_totp.assert_async().await;
+ }
+
+ #[tokio::test]
+ async fn login_with_totp_reports_invalid_code_before_retrying() {
+ crypto::init().unwrap();
+
+ let password = "hunter2";
+ let (key_attributes, encrypted_token, _, _, _) =
+ build_login_response(password, "plain-auth-token");
+
+ let mut server = Server::new_async().await;
+ let mut ui = ScriptedUi::new();
+ ui.email_otps.push_back("123456".into());
+ ui.login_totps.push_back("000000".into());
+ ui.login_totps.push_back("654321".into());
+
+ let srp_attrs = server
+ .mock("GET", Matcher::Any)
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "attributes": {
+ "srpUserID": Uuid::new_v4(),
+ "srpSalt": STANDARD.encode([1u8; 16]),
+ "memLimit": key_attributes.mem_limit,
+ "opsLimit": key_attributes.ops_limit,
+ "kekSalt": key_attributes.kek_salt,
+ "isEmailMFAEnabled": true
+ }
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let ott = server
+ .mock("POST", "/users/ott")
+ .with_status(200)
+ .create_async()
+ .await;
+
+ let verify_email = server
+ .mock("POST", "/users/verify-email")
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "id": 77,
+ "twoFactorSessionID": "session-1",
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let rejected_totp = server
+ .mock("POST", "/users/two-factor/verify")
+ .match_body(Matcher::PartialJson(
+ serde_json::json!({ "code": "000000" }),
+ ))
+ .with_status(401)
+ .create_async()
+ .await;
+
+ let accepted_totp = server
+ .mock("POST", "/users/two-factor/verify")
+ .match_body(Matcher::PartialJson(
+ serde_json::json!({ "code": "654321" }),
+ ))
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "id": 77,
+ "keyAttributes": key_attributes,
+ "encryptedToken": encrypted_token,
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let api_client = ApiClient::new(Some(server.url())).unwrap();
+ let mut flow = AuthFlow::new(&api_client, App::Photos, &mut ui);
+
+ let result = flow
+ .login(LoginParams {
+ email: "[email protected]".into(),
+ password: password.into(),
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(result.user_id, 77);
+ assert_eq!(
+ ui.retryable_errors,
+ vec!["Incorrect TOTP code. Try again.".to_string()]
+ );
+
+ srp_attrs.assert_async().await;
+ ott.assert_async().await;
+ verify_email.assert_async().await;
+ rejected_totp.assert_async().await;
+ accepted_totp.assert_async().await;
+ }
+
+ #[tokio::test]
+ async fn setup_two_factor_encrypts_secret_with_recovery_key() {
+ crypto::init().unwrap();
+
+ let password = "pw";
+ let key_gen =
+ auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
+ .unwrap();
+ let recovery_key = key_gen.private_key_attributes.recovery_key.clone();
+ 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 mut server = Server::new_async().await;
+ let mut ui = ScriptedUi::new();
+ ui.setup_totps.push_back("123123".into());
+
+ let setup = server
+ .mock("POST", "/users/two-factor/setup")
+ .match_header("x-auth-token", "session-token")
+ .match_header("x-client-package", "io.ente.photos")
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "secretCode": "JBSWY3DPEHPK3PXP",
+ "qrCode": "qr-png-b64"
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let enable = server
+ .mock("POST", "/users/two-factor/enable")
+ .match_header("x-auth-token", "session-token")
+ .match_header("x-client-package", "io.ente.photos")
+ .match_body(Matcher::Regex("\"encryptedTwoFactorSecret\"".into()))
+ .with_status(200)
+ .create_async()
+ .await;
+
+ let api_client = ApiClient::new(Some(server.url())).unwrap();
+ api_client.add_token("[email protected]", "session-token");
+ let mut flow = AuthFlow::new(&api_client, App::Photos, &mut ui);
+
+ let result = flow
+ .setup_two_factor(SetupTwoFactorParams {
+ account_id: "[email protected]".into(),
+ master_key,
+ key_attributes: Some(key_attributes),
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(result.secret_code, "JBSWY3DPEHPK3PXP");
+ assert_eq!(result.recovery_key, recovery_key);
+ assert_eq!(ui.last_totp_secret.as_deref(), Some("JBSWY3DPEHPK3PXP"));
+
+ setup.assert_async().await;
+ enable.assert_async().await;
+ }
+
+ #[tokio::test]
+ async fn create_account_uploads_keys_and_completes_srp_setup() {
+ crypto::init().unwrap();
+
+ let email = "[email protected]";
+ let encoded_email = urlencoding::encode(email).into_owned();
+ let signup_token_bytes = b"signup-session-token";
+ let signup_token = URL_SAFE.encode(signup_token_bytes);
+ let signup_state = Arc::new(Mutex::new(MockSignupState::default()));
+
+ let mut server = Server::new_async().await;
+ let mut ui = ScriptedUi::new();
+ ui.email_otps.push_back("123456".into());
+
+ let send_otp = server
+ .mock("POST", "/users/ott")
+ .match_body(Matcher::PartialJson(serde_json::json!({
+ "email": email,
+ "purpose": "signup",
+ })))
+ .with_status(200)
+ .create_async()
+ .await;
+
+ let verify_email = server
+ .mock("POST", "/users/verify-email")
+ .match_body(Matcher::PartialJson(serde_json::json!({
+ "email": email,
+ "ott": "123456",
+ "source": "testAccount",
+ })))
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "id": 99,
+ "token": signup_token,
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let session_validity = server
+ .mock("GET", "/users/session-validity/v2")
+ .match_header("x-auth-token", signup_token.as_str())
+ .match_header("x-client-package", "io.ente.photos")
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "hasSetKeys": false,
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let state = Arc::clone(&signup_state);
+ let set_attributes = server
+ .mock("PUT", "/users/attributes")
+ .match_header("x-auth-token", signup_token.as_str())
+ .match_header("x-client-package", "io.ente.photos")
+ .with_status(200)
+ .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();
+
+ assert!(!key_attributes.kek_salt.is_empty());
+ assert_eq!(mem_limit * ops_limit, 4_294_967_296);
+ assert!(
+ key_attributes
+ .master_key_encrypted_with_recovery_key
+ .is_some()
+ );
+ assert!(
+ key_attributes
+ .recovery_key_encrypted_with_master_key
+ .is_some()
+ );
+
+ state.lock().unwrap().uploaded_key_attributes = Some(key_attributes);
+ Vec::new()
+ })
+ .create_async()
+ .await;
+
+ let state = Arc::clone(&signup_state);
+ let setup_srp = server
+ .mock("POST", "/users/srp/setup")
+ .match_header("x-auth-token", signup_token.as_str())
+ .match_header("x-client-package", "io.ente.photos")
+ .with_status(200)
+ .with_body_from_request(move |request| {
+ let payload: SetupSrpPayload = parse_request_body(request);
+ let srp_user_id = Uuid::parse_str(&payload.srp_user_id).unwrap();
+ let srp_verifier = STANDARD.decode(&payload.srp_verifier).unwrap();
+ let srp_a = STANDARD.decode(&payload.srp_a).unwrap();
+ let server = SrpServer::<Sha256>::new(&G_4096);
+ let b_private = [0x33u8; 64];
+ let srp_b = pad_left(
+ &server.compute_public_ephemeral(&b_private, &srp_verifier),
+ SRP_A_LEN,
+ );
+ let verifier = server
+ .process_reply(&b_private, &srp_verifier, &srp_a)
+ .unwrap();
+ let setup_id = Uuid::new_v4();
+ let srp_a = pad_left(&srp_a, SRP_A_LEN);
+ let shared_secret = pad_left(verifier.key(), SRP_A_LEN);
+
+ let mut client_proof_hasher = Sha256::new();
+ client_proof_hasher.update(&srp_a);
+ client_proof_hasher.update(&srp_b);
+ client_proof_hasher.update(&shared_secret);
+ let client_proof = client_proof_hasher.finalize().to_vec();
+
+ let server_key = Sha256::digest(&shared_secret);
+ let mut server_proof_hasher = Sha256::new();
+ server_proof_hasher.update(&srp_a);
+ server_proof_hasher.update(&client_proof);
+ server_proof_hasher.update(server_key);
+ let server_proof = server_proof_hasher.finalize().to_vec();
+
+ let mut state = state.lock().unwrap();
+ let uploaded_key_attributes = state.uploaded_key_attributes.clone().unwrap();
+ state.remote_srp_attributes = Some(RemoteSrpAttributes {
+ srp_user_id,
+ srp_salt: payload.srp_salt,
+ mem_limit: uploaded_key_attributes.mem_limit,
+ ops_limit: uploaded_key_attributes.ops_limit,
+ kek_salt: uploaded_key_attributes.kek_salt,
+ is_email_mfa_enabled: false,
+ });
+ state.pending_setup_id = Some(setup_id);
+ state.pending_client_proof = Some(client_proof);
+ state.pending_server_proof = Some(server_proof);
+
+ serde_json::json!({
+ "setupID": setup_id,
+ "srpB": STANDARD.encode(&srp_b),
+ })
+ .to_string()
+ .into_bytes()
+ })
+ .create_async()
+ .await;
+
+ let state = Arc::clone(&signup_state);
+ let complete_srp = server
+ .mock("POST", "/users/srp/complete")
+ .match_header("x-auth-token", signup_token.as_str())
+ .match_header("x-client-package", "io.ente.photos")
+ .with_status(200)
+ .with_body_from_request(move |request| {
+ let payload: CompleteSrpSetupPayload = parse_request_body(request);
+ let setup_id = Uuid::parse_str(&payload.setup_id).unwrap();
+ let srp_m1 = STANDARD.decode(&payload.srp_m1).unwrap();
+
+ let mut state = state.lock().unwrap();
+ assert_eq!(state.pending_setup_id, Some(setup_id));
+ assert_eq!(state.pending_client_proof.take().unwrap(), srp_m1);
+
+ serde_json::json!({
+ "setupID": setup_id,
+ "srpM2": STANDARD.encode(state.pending_server_proof.take().unwrap()),
+ })
+ .to_string()
+ .into_bytes()
+ })
+ .create_async()
+ .await;
+
+ let state = Arc::clone(&signup_state);
+ let srp_attributes = server
+ .mock("GET", Matcher::Any)
+ .match_request(move |request| {
+ request.path() == "/users/srp/attributes"
+ && request.path_and_query()
+ == format!("/users/srp/attributes?email={encoded_email}")
+ })
+ .with_status(200)
+ .with_body_from_request(move |_| {
+ let state = state.lock().unwrap();
+ serde_json::to_vec(&serde_json::json!({
+ "attributes": state.remote_srp_attributes.as_ref().unwrap()
+ }))
+ .unwrap()
+ })
+ .create_async()
+ .await;
+
+ let api_client = ApiClient::new(Some(server.url())).unwrap();
+ let mut flow = AuthFlow::new(&api_client, App::Photos, &mut ui);
+
+ let result = flow
+ .create_account(CreateAccountParams {
+ email: email.into(),
+ password: "correct horse battery staple".into(),
+ source: Some("testAccount".into()),
+ })
+ .await
+ .unwrap();
+
+ let uploaded_key_attributes = signup_state
+ .lock()
+ .unwrap()
+ .uploaded_key_attributes
+ .clone()
+ .unwrap();
+
+ assert_eq!(result.user_id, 99);
+ assert_eq!(result.secrets.token, signup_token_bytes);
+ assert_eq!(
+ result.key_attributes.public_key,
+ uploaded_key_attributes.public_key
+ );
+ assert_eq!(
+ result.key_attributes.kek_salt,
+ uploaded_key_attributes.kek_salt
+ );
+ assert_eq!(
+ result.key_attributes.mem_limit,
+ uploaded_key_attributes.mem_limit
+ );
+ assert_eq!(
+ result.key_attributes.ops_limit,
+ uploaded_key_attributes.ops_limit
+ );
+ assert!(result.recovery_key.is_some());
+ assert_eq!(result.secrets.master_key.len(), 32);
+ assert_eq!(result.secrets.secret_key.len(), 32);
+ assert_eq!(result.secrets.public_key.len(), 32);
+
+ send_otp.assert_async().await;
+ verify_email.assert_async().await;
+ session_validity.assert_async().await;
+ set_attributes.assert_async().await;
+ setup_srp.assert_async().await;
+ complete_srp.assert_async().await;
+ srp_attributes.assert_async().await;
+ }
+
+ #[test]
+ fn validate_remote_srp_attributes_reports_mismatched_fields() {
+ crypto::init().unwrap();
+
+ 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 srp_user_id = Uuid::new_v4();
+ let srp_setup =
+ generate_srp_setup(&key_gen.key_encryption_key, &srp_user_id.to_string()).unwrap();
+
+ let remote = RemoteSrpAttributes {
+ srp_user_id,
+ srp_salt: "wrong-salt".into(),
+ mem_limit: key_attributes.mem_limit + 1,
+ ops_limit: key_attributes.ops_limit + 1,
+ kek_salt: key_attributes.kek_salt.clone(),
+ is_email_mfa_enabled: false,
+ };
+
+ let error =
+ validate_remote_srp_attributes(&remote, &srp_user_id, &srp_setup, &key_attributes)
+ .unwrap_err();
+
+ match error {
+ Error::AuthenticationFailed(message) => {
+ assert!(message.contains("srpSalt"));
+ assert!(message.contains("memLimit"));
+ assert!(message.contains("opsLimit"));
+ }
+ other => panic!("unexpected error: {other}"),
+ }
+ }
+}
diff --git a/rust/cli/src/cli/account.rs b/rust/cli/src/cli/account.rs
index 3cb2dfba60..bd0ceac8f8 100644
--- a/rust/cli/src/cli/account.rs
+++ b/rust/cli/src/cli/account.rs
@@ -12,6 +12,7 @@ pub enum AccountSubcommands {
List,
/// Login into existing account
+ #[command(alias = "login")]
Add {
/// Email address (optional - will prompt if not provided)
#[arg(long)]
@@ -32,6 +33,62 @@ pub enum AccountSubcommands {
/// Export directory path
#[arg(long)]
export_dir: Option<String>,
+
+ /// Email verification code for email-MFA accounts
+ #[arg(long)]
+ otp: Option<String>,
+
+ /// TOTP code to use if login requires two-factor verification
+ #[arg(long)]
+ totp_code: Option<String>,
+
+ /// Preferred second-factor method when multiple are available (totp or passkey)
+ #[arg(long)]
+ second_factor: Option<String>,
+ },
+
+ /// Create a new account via email verification, key setup, and SRP registration
+ #[command(alias = "signup")]
+ Create {
+ /// Email address (optional - will prompt if not provided)
+ #[arg(long)]
+ email: Option<String>,
+
+ /// Password (optional - will prompt if not provided)
+ #[arg(long)]
+ password: Option<String>,
+
+ /// Specify the app (photos, locker, auth)
+ #[arg(long, default_value = "photos")]
+ app: String,
+
+ /// API endpoint (defaults to https://api.ente.io)
+ #[arg(long, default_value = "https://api.ente.io")]
+ endpoint: String,
+
+ /// Export directory path
+ #[arg(long)]
+ export_dir: Option<String>,
+
+ /// Signup email verification code
+ #[arg(long)]
+ otp: Option<String>,
+
+ /// Referral/source string to pass during verify-email
+ #[arg(long)]
+ source: Option<String>,
+
+ /// Enable TOTP two-factor immediately after signup
+ #[arg(long)]
+ setup_2fa: bool,
+
+ /// TOTP code to use when enabling two-factor
+ #[arg(long)]
+ totp_code: Option<String>,
+
+ /// Print the recovery key after signup
+ #[arg(long)]
+ show_recovery_key: bool,
},
/// Update an existing account's export directory
@@ -59,4 +116,24 @@ pub enum AccountSubcommands {
#[arg(long, default_value = "photos")]
app: String,
},
+
+ /// Enable TOTP two-factor for an existing account
+ #[command(name = "two-factor", alias = "2fa")]
+ TwoFactor {
+ /// Email address of the account
+ #[arg(long)]
+ email: String,
+
+ /// Specify the app (photos, locker, auth)
+ #[arg(long, default_value = "photos")]
+ app: String,
+
+ /// TOTP code to use for enabling two-factor
+ #[arg(long)]
+ totp_code: Option<String>,
+
+ /// Print the recovery key after enabling two-factor
+ #[arg(long)]
+ show_recovery_key: bool,
+ },
}
diff --git a/rust/cli/src/commands/account.rs b/rust/cli/src/commands/account.rs
index 55f327277f..14cadadc19 100644
--- a/rust/cli/src/commands/account.rs
+++ b/rust/cli/src/commands/account.rs
@@ -1,57 +1,19 @@
use crate::{
- api::{ApiClient, AuthClient},
+ api::ApiClient,
+ auth_flow::{
+ AuthFlow, AuthFlowUi, AuthenticatedAccount, CreateAccountParams, LoginParams, OtpPurpose,
+ SecondFactorMethod, SetupTwoFactorParams, TotpPurpose,
+ },
cli::account::{AccountCommand, AccountSubcommands},
models::{
- account::{Account, AccountSecrets, App},
+ account::{Account, App},
error::{Error, Result},
},
storage::Storage,
};
use base64::Engine;
use dialoguer::{Input, Password, Select};
-use std::path::PathBuf;
-
-use ente_core::auth::{self, DecryptedSecrets, KeyAttributes as CoreKeyAttributes, derive_kek};
-use ente_core::crypto;
-
-fn to_core_key_attributes(attrs: &crate::api::models::KeyAttributes) -> CoreKeyAttributes {
- CoreKeyAttributes {
- kek_salt: attrs.kek_salt.clone(),
- encrypted_key: attrs.encrypted_key.clone(),
- key_decryption_nonce: attrs.key_decryption_nonce.clone(),
- public_key: attrs.public_key.clone(),
- encrypted_secret_key: attrs.encrypted_secret_key.clone(),
- secret_key_decryption_nonce: attrs.secret_key_decryption_nonce.clone(),
- mem_limit: Some(attrs.mem_limit as u32),
- ops_limit: Some(attrs.ops_limit as u32),
- master_key_encrypted_with_recovery_key: None,
- master_key_decryption_nonce: None,
- recovery_key_encrypted_with_master_key: None,
- recovery_key_decryption_nonce: None,
- }
-}
-
-fn decrypt_secrets_with_plain_token(
- kek: &[u8],
- key_attrs: &CoreKeyAttributes,
- token: &str,
-) -> auth::Result<DecryptedSecrets> {
- let (master_key, secret_key) = auth::decrypt_keys_only(kek, key_attrs)?;
-
- // AuthResponse.token from server is a URL-safe base64 string even in the
- // "plain token" flow (JWTs are returned via dedicated endpoints). Decode
- // it before persisting so callers always get raw token bytes.
- let token = base64::engine::general_purpose::URL_SAFE
- .decode(token)
- .or_else(|_| base64::engine::general_purpose::STANDARD.decode(token))
- .map_err(|e| auth::AuthError::Decode(format!("token: {e}")))?;
-
- Ok(DecryptedSecrets {
- master_key,
- secret_key,
- token,
- })
-}
+use std::{path::PathBuf, str::FromStr};
pub async fn handle_account_command(cmd: AccountCommand, storage: &Storage) -> Result<()> {
match cmd.command {
@@ -62,11 +24,183 @@ pub async fn handle_account_command(cmd: AccountCommand, storage: &Storage) -> R
app,
endpoint,
export_dir,
- } => add_account(storage, email, password, app, endpoint, export_dir).await,
+ otp,
+ totp_code,
+ second_factor,
+ } => {
+ add_account(
+ storage,
+ email,
+ password,
+ &app,
+ endpoint,
+ export_dir,
+ otp,
+ totp_code,
+ second_factor,
+ )
+ .await
+ }
+ AccountSubcommands::Create {
+ email,
+ password,
+ app,
+ endpoint,
+ export_dir,
+ otp,
+ source,
+ setup_2fa,
+ totp_code,
+ show_recovery_key,
+ } => {
+ create_account(
+ storage,
+ email,
+ password,
+ &app,
+ endpoint,
+ export_dir,
+ otp,
+ source,
+ setup_2fa,
+ totp_code,
+ show_recovery_key,
+ )
+ .await
+ }
AccountSubcommands::Update { email, dir, app } => {
update_account(storage, &email, &dir, &app).await
}
AccountSubcommands::GetToken { email, app } => get_token(storage, &email, &app).await,
+ AccountSubcommands::TwoFactor {
+ email,
+ app,
+ totp_code,
+ show_recovery_key,
+ } => enable_two_factor(storage, &email, &app, totp_code, show_recovery_key).await,
+ }
+}
+
+struct DialoguerAuthFlowUi {
+ email_otp: Option<String>,
+ totp_code: Option<String>,
+ second_factor: Option<SecondFactorMethod>,
+ passkey_presented: bool,
+}
+
+impl DialoguerAuthFlowUi {
+ fn new(
+ email_otp: Option<String>,
+ totp_code: Option<String>,
+ second_factor: Option<SecondFactorMethod>,
+ ) -> Self {
+ Self {
+ email_otp,
+ totp_code,
+ second_factor,
+ passkey_presented: false,
+ }
+ }
+}
+
+impl AuthFlowUi for DialoguerAuthFlowUi {
+ fn read_email_otp(&mut self, email: &str, purpose: OtpPurpose, resent: bool) -> Result<String> {
+ if let Some(code) = self.email_otp.take() {
+ return Ok(code);
+ }
+
+ let prompt = match (purpose, resent) {
+ (OtpPurpose::Signup, false) => {
+ format!("Enter the signup verification code sent to {email}")
+ }
+ (OtpPurpose::Signup, true) => {
+ format!("Enter the new signup verification code sent to {email}")
+ }
+ (OtpPurpose::Login, false) => {
+ format!("Enter the email-MFA code sent to {email}")
+ }
+ (OtpPurpose::Login, true) => {
+ format!("Enter the new email-MFA code sent to {email}")
+ }
+ };
+
+ read_six_digit_code(&prompt)
+ }
+
+ fn read_totp_code(&mut self, purpose: TotpPurpose) -> Result<String> {
+ if let Some(code) = self.totp_code.take() {
+ return Ok(code);
+ }
+
+ let prompt = match purpose {
+ TotpPurpose::Login => "Enter TOTP code",
+ TotpPurpose::Setup => "Enter the current TOTP from your authenticator app",
+ };
+
+ read_six_digit_code(prompt)
+ }
+
+ fn report_retryable_error(&mut self, message: &str) -> Result<()> {
+ println!("\n{message}");
+ Ok(())
+ }
+
+ fn choose_second_factor(
+ &mut self,
+ methods: &[SecondFactorMethod],
+ ) -> Result<SecondFactorMethod> {
+ if let Some(choice) = self.second_factor {
+ return Ok(choice);
+ }
+
+ let options: Vec<&str> = methods
+ .iter()
+ .map(|method| match method {
+ SecondFactorMethod::Totp => "TOTP (Authenticator app)",
+ SecondFactorMethod::Passkey => "Passkey",
+ })
+ .collect();
+
+ let index = Select::new()
+ .with_prompt("Choose verification method")
+ .items(&options)
+ .default(0)
+ .interact()
+ .map_err(|e| Error::InvalidInput(e.to_string()))?;
+
+ methods
+ .get(index)
+ .copied()
+ .ok_or_else(|| Error::InvalidInput("Invalid second-factor selection".into()))
+ }
+
+ fn present_passkey_verification(&mut self, url: &str) -> Result<()> {
+ println!("\nPasskey verification required");
+ println!("Open this URL in your browser to verify your passkey:\n{url}");
+
+ if !self.passkey_presented {
+ if let Err(error) = open::that(url) {
+ log::error!("failed to open browser: {error}");
+ }
+ self.passkey_presented = true;
+ }
+
+ Ok(())
+ }
+
+ fn wait_for_passkey_verification(&mut self) -> Result<()> {
+ let _: String = Input::new()
+ .with_prompt("Press Enter once you have completed passkey verification")
+ .allow_empty(true)
+ .interact_text()
+ .map_err(|e| Error::InvalidInput(e.to_string()))?;
+ Ok(())
+ }
+
+ fn present_totp_secret(&mut self, secret_code: &str, _qr_code: &str) -> Result<()> {
+ println!("\nTOTP setup secret: {secret_code}");
+ println!("Add this secret to your authenticator app, then enter the current code.");
+ Ok(())
}
}
@@ -74,7 +208,7 @@ async fn list_accounts(storage: &Storage) -> Result<()> {
let accounts = storage.accounts().list()?;
if accounts.is_empty() {
- println!("No accounts configured. Use 'ente account add' to add an account.");
+ println!("No accounts configured. Use 'ente account create' or 'ente account add'.");
return Ok(());
}
@@ -86,7 +220,6 @@ async fn list_accounts(storage: &Storage) -> Result<()> {
println!("{}", "-".repeat(110));
for account in accounts {
- // Shorten endpoint display for better readability
let endpoint_display = if account.endpoint == "https://api.ente.io" {
"api.ente.io (prod)".to_string()
} else if account.endpoint.starts_with("http://localhost") {
@@ -101,7 +234,7 @@ async fn list_accounts(storage: &Storage) -> Result<()> {
println!(
"{:<30} {:<10} {:<30} {:<40}",
account.email,
- format!("{:?}", account.app).to_lowercase(),
+ account.app.to_string(),
endpoint_display,
account.export_dir.as_deref().unwrap_or("Not configured")
);
@@ -114,313 +247,217 @@ async fn add_account(
storage: &Storage,
email_arg: Option<String>,
password_arg: Option<String>,
- app_arg: String,
+ app_arg: &str,
endpoint: String,
export_dir_arg: Option<String>,
+ otp: Option<String>,
+ totp_code: Option<String>,
+ second_factor: Option<String>,
) -> Result<()> {
- println!("\n=== Add Ente Account ===\n");
-
- let email = if let Some(email) = email_arg {
- email
- } else {
- Input::new()
- .with_prompt("Enter your email address")
- .interact_text()
- .map_err(|e| Error::InvalidInput(e.to_string()))?
- };
+ println!("\n=== Add Existing Ente Account ===\n");
- let app = match app_arg.to_lowercase().as_str() {
- "photos" => App::Photos,
- "locker" => App::Locker,
- "auth" => App::Auth,
- _ => {
- if password_arg.is_some() {
- return Err(Error::InvalidInput(format!(
- "Invalid app: {app_arg}. Must be one of: photos, locker, auth"
- )));
- }
- let apps = vec!["photos", "locker", "auth"];
- let app_index = Select::new()
- .with_prompt("Select the Ente app")
- .items(&apps)
- .default(0)
- .interact()
- .map_err(|e| Error::InvalidInput(e.to_string()))?;
- match apps[app_index] {
- "photos" => App::Photos,
- "locker" => App::Locker,
- "auth" => App::Auth,
- _ => unreachable!(),
- }
- }
- };
+ let email = prompt_email(email_arg)?;
+ let interactive_password = password_arg.is_none();
+ let mut password = prompt_password(password_arg, "Enter your password")?;
+ let app = resolve_app(app_arg)?;
+ let second_factor = parse_second_factor(second_factor.as_deref())?;
- if let Ok(Some(_existing)) = storage.accounts().get(&email, app) {
- println!("\n❌ Account already exists for {email} with app {app:?}");
+ if let Ok(Some(_)) = storage.accounts().get(&email, app) {
+ println!("\nAccount already exists for {email} with app {app}");
return Ok(());
}
- let is_non_interactive = password_arg.is_some();
-
- let mut password = if let Some(password) = password_arg {
- password
- } else {
- Password::new()
- .with_prompt("Enter your password")
- .interact()
- .map_err(|e| Error::InvalidInput(e.to_string()))?
- };
-
- let export_dir = if let Some(dir) = export_dir_arg {
- dir
- } else if is_non_interactive {
- format!("./exports/{email}")
- } else {
- Input::new()
- .with_prompt("Enter export directory path")
- .default(format!("./exports/{email}"))
- .interact_text()
- .map_err(|e| Error::InvalidInput(e.to_string()))?
- };
-
- let export_path = PathBuf::from(&export_dir);
- if !export_path.exists() {
- println!("Creating export directory: {export_dir}");
- std::fs::create_dir_all(&export_path).map_err(Error::Io)?;
- }
-
- log::info!("Using API endpoint: {endpoint}");
- let api_client = ApiClient::new(Some(endpoint.clone()))?;
- let auth_client = AuthClient::new(&api_client);
-
- println!("\nAuthenticating with Ente servers...");
-
- let srp_attrs = auth_client.get_srp_attributes(&email).await?;
-
- let (auth_response, mut key_enc_key) = if srp_attrs.is_email_mfa_enabled {
- println!("\nπŸ“§ Email MFA is enabled. Sending verification code...");
- auth_client.send_login_otp(&email).await?;
-
- let auth_response = loop {
- let otp: String = Input::new()
- .with_prompt("Enter the 6-digit code from your email")
- .validate_with(|input: &String| {
- if input.len() == 6 && input.chars().all(char::is_numeric) {
- Ok(())
- } else {
- Err("Code must be 6 digits")
- }
- })
- .interact_text()
- .map_err(|e| Error::InvalidInput(e.to_string()))?;
-
- match auth_client.verify_email(&email, &otp).await {
- Ok(resp) => break resp,
- Err(Error::ApiError {
- status: 400 | 401, ..
- }) => {
- println!("❌ Invalid code, please try again.");
- }
- Err(Error::ApiError { status: 410, .. }) => {
- println!("❌ Code expired. Sending a new code...");
- auth_client.send_login_otp(&email).await?;
- }
- Err(e) => return Err(e),
- }
- };
-
- let auth_response = maybe_verify_2fa(&auth_client, auth_response, app).await?;
-
- println!("\nPlease wait authenticating...");
- let key_enc_key = derive_kek(
- &password,
- &srp_attrs.kek_salt,
- srp_attrs.mem_limit as u32,
- srp_attrs.ops_limit as u32,
- )?;
-
- (auth_response, key_enc_key)
- } else {
- let (auth_response, key_enc_key) = if is_non_interactive {
- auth_client.login_with_srp(&email, &password).await?
- } else {
- loop {
- match auth_client.login_with_srp(&email, &password).await {
- Ok(result) => break result,
- Err(Error::ApiError {
- status: 400 | 401, ..
- }) => {
- println!("❌ Incorrect password, please try again.");
- password = Password::new()
- .with_prompt("Enter your password")
- .interact()
- .map_err(|e| Error::InvalidInput(e.to_string()))?;
- }
- Err(e) => return Err(e),
- }
+ let export_dir = resolve_export_dir(export_dir_arg, &email)?;
+ ensure_export_dir(&export_dir)?;
+
+ let api_client = new_api_client(&endpoint, app)?;
+ let mut ui = DialoguerAuthFlowUi::new(otp, totp_code, second_factor);
+ let mut flow = AuthFlow::new(&api_client, app, &mut ui);
+ let authenticated = loop {
+ match flow
+ .login(LoginParams {
+ email: email.clone(),
+ password: password.clone(),
+ })
+ .await
+ {
+ Ok(authenticated) => break authenticated,
+ Err(error) if interactive_password && is_retryable_password_error(&error) => {
+ println!("\nIncorrect password. Try again.");
+ password = prompt_password(None, "Re-enter your password")?;
}
- };
-
- let auth_response = maybe_verify_2fa(&auth_client, auth_response, app).await?;
- (auth_response, key_enc_key)
+ Err(error) => return Err(error),
+ }
};
- let key_attributes = auth_response
- .key_attributes
- .as_ref()
- .ok_or_else(|| Error::AuthenticationFailed("No key attributes".to_string()))?;
+ persist_account(storage, &email, app, &endpoint, &export_dir, authenticated)?;
- println!("\nDecrypting account keys...");
+ println!("\nAccount added successfully!");
+ println!(" Email: {email}");
+ println!(" App: {app}");
+ println!(" Endpoint: {endpoint}");
+ println!(" Export directory: {export_dir}");
- let core_key_attrs = to_core_key_attributes(key_attributes);
+ Ok(())
+}
- let encrypted_token = auth_response.encrypted_token.as_deref();
- let response_token = auth_response.token.as_deref();
+#[allow(clippy::too_many_arguments)]
+async fn create_account(
+ storage: &Storage,
+ email_arg: Option<String>,
+ password_arg: Option<String>,
+ app_arg: &str,
+ endpoint: String,
+ export_dir_arg: Option<String>,
+ otp: Option<String>,
+ source: Option<String>,
+ setup_2fa: bool,
+ totp_code: Option<String>,
+ show_recovery_key: bool,
+) -> Result<()> {
+ println!("\n=== Create Ente Account ===\n");
- let secrets: DecryptedSecrets = loop {
- let result = if let Some(encrypted_token) = encrypted_token {
- auth::decrypt_secrets(&key_enc_key, &core_key_attrs, encrypted_token)
- } else if let Some(token) = response_token {
- decrypt_secrets_with_plain_token(&key_enc_key, &core_key_attrs, token)
- } else {
- return Err(Error::AuthenticationFailed(
- "No token in response".to_string(),
- ));
- };
+ let email = prompt_email(email_arg)?;
+ let password = prompt_password(password_arg, "Choose a password")?;
+ let app = resolve_app(app_arg)?;
- match result {
- Ok(secrets) => break secrets,
- Err(auth::AuthError::IncorrectPassword) if !is_non_interactive => {
- println!("❌ Incorrect password.");
- password = Password::new()
- .with_prompt("Enter your password")
- .interact()
- .map_err(|e| Error::InvalidInput(e.to_string()))?;
-
- println!("\nPlease wait authenticating...");
- key_enc_key = derive_kek(
- &password,
- &key_attributes.kek_salt,
- key_attributes.mem_limit as u32,
- key_attributes.ops_limit as u32,
- )?;
- }
- Err(e) => return Err(e.into()),
- }
- };
+ if let Ok(Some(_)) = storage.accounts().get(&email, app) {
+ println!("\nAccount already exists for {email} with app {app}");
+ return Ok(());
+ }
- let public_key = crypto::decode_b64(&key_attributes.public_key)?;
+ let export_dir = resolve_export_dir(export_dir_arg, &email)?;
+ ensure_export_dir(&export_dir)?;
- let account = Account {
- user_id: auth_response.id,
- email: email.clone(),
+ let api_client = new_api_client(&endpoint, app)?;
+ let mut ui = DialoguerAuthFlowUi::new(otp, totp_code, Some(SecondFactorMethod::Totp));
+ let mut flow = AuthFlow::new(&api_client, app, &mut ui);
+ let created = flow
+ .create_account(CreateAccountParams {
+ email: email.clone(),
+ password,
+ source,
+ })
+ .await?;
+
+ let AuthenticatedAccount {
+ user_id,
+ key_attributes,
+ secrets,
+ recovery_key,
+ } = created;
+
+ let two_factor_master_key = secrets.master_key.clone();
+ let two_factor_key_attributes = key_attributes.clone();
+
+ persist_account(
+ storage,
+ &email,
app,
- endpoint: endpoint.clone(),
- export_dir: Some(export_dir.clone()),
- };
-
- let secrets = AccountSecrets {
- token: secrets.token,
- master_key: secrets.master_key,
- secret_key: secrets.secret_key,
- public_key,
- };
+ &endpoint,
+ &export_dir,
+ AuthenticatedAccount {
+ user_id,
+ key_attributes,
+ secrets,
+ recovery_key: recovery_key.clone(),
+ },
+ )?;
+
+ println!("\nAccount created successfully!");
+ println!(" Email: {email}");
+ println!(" App: {app}");
+ println!(" Endpoint: {endpoint}");
+ println!(" Export directory: {export_dir}");
+
+ if show_recovery_key {
+ if let Some(recovery_key) = recovery_key.as_deref() {
+ println!("\nRecovery key: {recovery_key}");
+ } else {
+ println!("\nRecovery key is not available for this account.");
+ }
+ }
- storage.accounts().add(&account)?;
- storage
- .accounts()
- .store_secrets(account.user_id, account.app, &secrets)?;
+ if setup_2fa {
+ let result = flow
+ .setup_two_factor(SetupTwoFactorParams {
+ account_id: email.clone(),
+ master_key: two_factor_master_key,
+ key_attributes: Some(two_factor_key_attributes),
+ })
+ .await?;
- println!("\nβœ… Account added successfully!");
- println!(" Email: {email}");
- println!(" App: {app:?}");
- println!(" Endpoint: {endpoint}");
- println!(" Export directory: {export_dir}");
+ println!("\nTwo-factor authentication enabled.");
+ if show_recovery_key {
+ println!("Recovery key: {}", result.recovery_key);
+ }
+ }
Ok(())
}
-async fn maybe_verify_2fa(
- auth_client: &AuthClient<'_>,
- auth_resp: crate::api::models::AuthResponse,
- app: App,
-) -> Result<crate::api::models::AuthResponse> {
- let has_totp = auth_resp.get_two_factor_session_id().is_some();
- let has_passkey = auth_resp
- .passkey_session_id
- .as_ref()
- .is_some_and(|s| !s.is_empty());
-
- if has_totp && has_passkey {
- println!("\nπŸ” Two-factor authentication required");
- println!("Choose verification method:");
- let options = vec!["TOTP (Authenticator app)", "Passkey"];
- let choice = Select::new()
- .items(&options)
- .default(0)
- .interact()
- .map_err(|e| Error::InvalidInput(e.to_string()))?;
+async fn enable_two_factor(
+ storage: &Storage,
+ email: &str,
+ app_arg: &str,
+ totp_code: Option<String>,
+ show_recovery_key: bool,
+) -> Result<()> {
+ let app = resolve_app(app_arg)?;
+ let account = storage
+ .accounts()
+ .get(email, app)?
+ .ok_or_else(|| Error::NotFound(format!("Account not found: {email}")))?;
+ let secrets = storage
+ .accounts()
+ .get_secrets(account.user_id, account.app)?
+ .ok_or_else(|| Error::NotFound(format!("Secrets not found for account {email}")))?;
- if choice == 0 {
- verify_totp_2fa(auth_client, &auth_resp).await
- } else {
- verify_passkey_2fa(auth_client, &auth_resp, app).await
- }
- } else if has_totp {
- verify_totp_2fa(auth_client, &auth_resp).await
- } else if has_passkey {
- verify_passkey_2fa(auth_client, &auth_resp, app).await
- } else {
- Ok(auth_resp)
+ let api_client = new_api_client(&account.endpoint, app)?;
+ let token = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);
+ api_client.add_token(&account.email, &token);
+
+ let mut ui = DialoguerAuthFlowUi::new(None, totp_code, Some(SecondFactorMethod::Totp));
+ let mut flow = AuthFlow::new(&api_client, app, &mut ui);
+ let result = flow
+ .setup_two_factor(SetupTwoFactorParams {
+ account_id: account.email.clone(),
+ master_key: secrets.master_key.clone(),
+ key_attributes: None,
+ })
+ .await?;
+
+ println!("\nTwo-factor authentication enabled for {email}.");
+ if show_recovery_key {
+ println!("Recovery key: {}", result.recovery_key);
}
+
+ Ok(())
}
async fn update_account(storage: &Storage, email: &str, dir: &str, app_str: &str) -> Result<()> {
- let app = match app_str.to_lowercase().as_str() {
- "photos" => App::Photos,
- "locker" => App::Locker,
- "auth" => App::Auth,
- _ => {
- return Err(Error::InvalidInput(format!(
- "Invalid app: {app_str}. Must be one of: photos, locker, auth"
- )));
- }
- };
+ let app = resolve_app(app_str)?;
if storage.accounts().get(email, app)?.is_none() {
return Err(Error::NotFound(format!(
- "Account not found: {} (app: {:?})",
+ "Account not found: {} (app: {})",
email, app
)));
}
- let export_path = PathBuf::from(dir);
- if !export_path.exists() {
- println!("Creating export directory: {dir}");
- std::fs::create_dir_all(&export_path).map_err(Error::Io)?;
- }
-
+ ensure_export_dir(dir)?;
storage.accounts().update_export_dir(email, app, dir)?;
- println!("\nβœ… Account updated successfully!");
- println!(" Email: {email}");
- println!(" App: {app:?}");
- println!(" New export directory: {dir}");
+ println!("\nAccount updated successfully!");
+ println!(" Email: {email}");
+ println!(" App: {app}");
+ println!(" New export directory: {dir}");
Ok(())
}
async fn get_token(storage: &Storage, email: &str, app_str: &str) -> Result<()> {
- let app = match app_str.to_lowercase().as_str() {
- "photos" => App::Photos,
- "locker" => App::Locker,
- "auth" => App::Auth,
- _ => {
- return Err(Error::InvalidInput(format!(
- "Invalid app: {app_str}. Must be one of: photos, locker, auth"
- )));
- }
- };
+ let app = resolve_app(app_str)?;
let account = storage
.accounts()
@@ -432,115 +469,116 @@ async fn get_token(storage: &Storage, email: &str, app_str: &str) -> Result<()>
.get_secrets(account.user_id, account.app)?
.ok_or_else(|| Error::NotFound(format!("Secrets not found for account {email}")))?;
- let token_str = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);
+ let token = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);
+ println!("{token}");
- println!("{token_str}");
+ Ok(())
+}
+
+fn persist_account(
+ storage: &Storage,
+ email: &str,
+ app: App,
+ endpoint: &str,
+ export_dir: &str,
+ authenticated: AuthenticatedAccount,
+) -> Result<()> {
+ let account = Account {
+ user_id: authenticated.user_id,
+ email: email.to_string(),
+ app,
+ endpoint: endpoint.to_string(),
+ export_dir: Some(export_dir.to_string()),
+ };
+
+ storage.accounts().add(&account)?;
+ storage
+ .accounts()
+ .store_secrets(account.user_id, account.app, &authenticated.secrets)?;
Ok(())
}
-async fn verify_totp_2fa(
- auth_client: &AuthClient<'_>,
- auth_resp: &crate::api::models::AuthResponse,
-) -> Result<crate::api::models::AuthResponse> {
- println!("\nπŸ“± Two-factor authentication required");
-
- let session_id = auth_resp
- .get_two_factor_session_id()
- .ok_or_else(|| Error::AuthenticationFailed("No 2FA session ID".to_string()))?;
-
- loop {
- let totp_code: String = Input::new()
- .with_prompt("Enter TOTP code")
- .validate_with(|input: &String| {
- if input.len() == 6 && input.chars().all(char::is_numeric) {
- Ok(())
- } else {
- Err("TOTP code must be 6 digits")
- }
- })
+fn prompt_email(email_arg: Option<String>) -> Result<String> {
+ if let Some(email) = email_arg {
+ Ok(email)
+ } else {
+ Input::new()
+ .with_prompt("Enter your email address")
.interact_text()
- .map_err(|e| Error::InvalidInput(e.to_string()))?;
+ .map_err(|e| Error::InvalidInput(e.to_string()))
+ }
+}
- match auth_client.verify_totp(session_id, &totp_code).await {
- Ok(result) => {
- println!("βœ“ Two-factor authentication verified!");
- return Ok(result);
- }
- Err(Error::ApiError {
- status: 400 | 401, ..
- }) => {
- println!("❌ Invalid code, please try again.");
- }
- Err(Error::ApiError { status: 410, .. }) => {
- return Err(Error::AuthenticationFailed(
- "TOTP session expired. Please restart login.".to_string(),
- ));
- }
- Err(e) => return Err(e),
- }
+fn prompt_password(password_arg: Option<String>, prompt: &str) -> Result<String> {
+ if let Some(password) = password_arg {
+ Ok(password)
+ } else {
+ Password::new()
+ .with_prompt(prompt)
+ .interact()
+ .map_err(|e| Error::InvalidInput(e.to_string()))
}
}
-async fn verify_passkey_2fa(
- auth_client: &AuthClient<'_>,
- auth_resp: &crate::api::models::AuthResponse,
- app: App,
-) -> Result<crate::api::models::AuthResponse> {
- let passkey_session_id = auth_resp
- .passkey_session_id
- .as_ref()
- .filter(|s| !s.is_empty())
- .ok_or_else(|| Error::AuthenticationFailed("No passkey session ID".to_string()))?;
-
- let accounts_url = auth_resp
- .accounts_url
- .as_ref()
- .filter(|s| !s.is_empty())
- .map(|s| s.as_str())
- .unwrap_or("https://accounts.ente.io");
-
- let client_package = match app {
- App::Photos => "io.ente.photos",
- App::Auth => "io.ente.auth",
- App::Locker => "io.ente.locker",
- };
+fn resolve_export_dir(export_dir_arg: Option<String>, email: &str) -> Result<String> {
+ if let Some(dir) = export_dir_arg {
+ Ok(dir)
+ } else {
+ Input::new()
+ .with_prompt("Enter export directory path")
+ .default(format!("./exports/{email}"))
+ .interact_text()
+ .map_err(|e| Error::InvalidInput(e.to_string()))
+ }
+}
- let passkey_url = format!(
- "{}/passkeys/verify?passkeySessionID={}&redirect=ente-cli://passkey&clientPackage={}",
- accounts_url, passkey_session_id, client_package
- );
+fn ensure_export_dir(dir: &str) -> Result<()> {
+ let export_path = PathBuf::from(dir);
+ if !export_path.exists() {
+ println!("Creating export directory: {dir}");
+ std::fs::create_dir_all(&export_path).map_err(Error::Io)?;
+ }
+ Ok(())
+}
- println!("\nπŸ”‘ Passkey verification required");
- println!("Open this URL in your browser to verify your passkey:\n{passkey_url}");
+fn resolve_app(app_arg: &str) -> Result<App> {
+ App::from_str(app_arg).map_err(Error::InvalidInput)
+}
- if let Err(e) = open::that(&passkey_url) {
- log::error!("failed to open browser: {e}");
- }
+fn parse_second_factor(second_factor: Option<&str>) -> Result<Option<SecondFactorMethod>> {
+ second_factor
+ .map(|value| match value.trim().to_ascii_lowercase().as_str() {
+ "totp" => Ok(SecondFactorMethod::Totp),
+ "passkey" => Ok(SecondFactorMethod::Passkey),
+ other => Err(Error::InvalidInput(format!(
+ "Invalid second-factor method: {other}. Must be one of: totp, passkey"
+ ))),
+ })
+ .transpose()
+}
- loop {
- let _: String = Input::new()
- .with_prompt("Press Enter once you have completed passkey verification")
- .allow_empty(true)
- .interact_text()
- .map_err(|e| Error::InvalidInput(e.to_string()))?;
+fn new_api_client(endpoint: &str, app: App) -> Result<ApiClient> {
+ ApiClient::new_with_client_package(Some(endpoint.to_string()), app.client_package())
+}
- match auth_client.check_passkey_status(passkey_session_id).await {
- Ok(result) => {
- println!("βœ“ Passkey verification completed!");
- return Ok(result);
- }
- Err(Error::ApiError {
- status: 400 | 404, ..
- }) => {
- println!("⏳ Passkey verification not yet complete.");
- }
- Err(Error::ApiError { status: 410, .. }) => {
- return Err(Error::AuthenticationFailed(
- "Passkey session expired. Please restart login.".to_string(),
- ));
+fn is_retryable_password_error(error: &Error) -> bool {
+ matches!(
+ error,
+ Error::AuthenticationFailed(message) if message == "Incorrect password"
+ ) || matches!(error, Error::ApiError { status: 401, .. })
+}
+
+fn read_six_digit_code(prompt: &str) -> Result<String> {
+ Input::new()
+ .with_prompt(prompt)
+ .validate_with(|input: &String| {
+ if input.len() == 6 && input.chars().all(char::is_numeric) {
+ Ok(())
+ } else {
+ Err("Code must be 6 digits")
}
- Err(e) => return Err(e),
- }
- }
+ })
+ .interact_text()
+ .map_err(|e| Error::InvalidInput(e.to_string()))
}
diff --git a/rust/cli/src/commands/export.rs b/rust/cli/src/commands/export.rs
index 7d57a73826..1c80243501 100644
--- a/rust/cli/src/commands/export.rs
+++ b/rust/cli/src/commands/export.rs
@@ -191,7 +191,10 @@ async fn sync_account_before_export(storage: &Storage, account: &Account) -> Res
.ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;
// Create API client with account's endpoint
- let api_client = ApiClient::new(Some(account.endpoint.clone()))?;
+ let api_client = ApiClient::new_with_client_package(
+ Some(account.endpoint.clone()),
+ account.app.client_package(),
+ )?;
// Store token for this account
let token = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);
@@ -252,7 +255,10 @@ async fn export_account(storage: &Storage, account: &Account, filter: &ExportFil
.ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;
// Create API client with account's endpoint
- let api_client = ApiClient::new(Some(account.endpoint.clone()))?;
+ let api_client = ApiClient::new_with_client_package(
+ Some(account.endpoint.clone()),
+ account.app.client_package(),
+ )?;
// Store token for this account
// Token is stored as raw bytes from sealed_box_open
diff --git a/rust/cli/src/commands/sync.rs b/rust/cli/src/commands/sync.rs
index 4720f80a69..deede83c17 100644
--- a/rust/cli/src/commands/sync.rs
+++ b/rust/cli/src/commands/sync.rs
@@ -75,7 +75,8 @@ async fn sync_account(
.ok_or_else(|| crate::Error::NotFound("Account secrets not found".into()))?;
// Create API client with account's endpoint
- let api_client = ApiClient::new(Some(account.endpoint.clone()))?;
+ let api_client =
+ ApiClient::new_with_client_package(Some(account.endpoint.clone()), account.app.client_package())?;
// Store token for this account
let token = base64::engine::general_purpose::URL_SAFE.encode(&secrets.token);
@@ -93,7 +94,8 @@ async fn sync_account(
.ok_or_else(|| crate::Error::Generic("Database path not available".into()))?;
// Create API client for sync engine
- let sync_api_client = ApiClient::new(Some(account.endpoint.clone()))?;
+ let sync_api_client =
+ ApiClient::new_with_client_package(Some(account.endpoint.clone()), account.app.client_package())?;
sync_api_client.add_token(&account.email, &token);
let sync_storage = Storage::new(db_path)?;
@@ -128,7 +130,10 @@ async fn sync_account(
// Create download manager
// Create a new API client for the download manager
- let download_api_client = ApiClient::new(Some(account.endpoint.clone()))?;
+ let download_api_client = ApiClient::new_with_client_package(
+ Some(account.endpoint.clone()),
+ account.app.client_package(),
+ )?;
download_api_client.add_token(&account.email, &token);
let mut download_manager = DownloadManager::new(download_api_client)?;
diff --git a/rust/cli/src/lib.rs b/rust/cli/src/lib.rs
index d4c22ab88c..16669ca82c 100644
--- a/rust/cli/src/lib.rs
+++ b/rust/cli/src/lib.rs
@@ -1,4 +1,5 @@
pub mod api;
+pub mod auth_flow;
pub mod cli;
pub mod commands;
pub mod models;
diff --git a/rust/cli/src/models/account.rs b/rust/cli/src/models/account.rs
index 4e5031b7a4..b7b3e0293a 100644
--- a/rust/cli/src/models/account.rs
+++ b/rust/cli/src/models/account.rs
@@ -1,7 +1,7 @@
#![allow(dead_code)]
use serde::{Deserialize, Serialize};
-use uuid::Uuid;
+use std::{fmt, str::FromStr};
use zeroize::Zeroize;
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -31,6 +31,32 @@ impl App {
}
}
+impl fmt::Display for App {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let value = match self {
+ App::Photos => "photos",
+ App::Locker => "locker",
+ App::Auth => "auth",
+ };
+ write!(f, "{value}")
+ }
+}
+
+impl FromStr for App {
+ type Err = String;
+
+ fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "photos" => Ok(App::Photos),
+ "locker" => Ok(App::Locker),
+ "auth" => Ok(App::Auth),
+ other => Err(format!(
+ "Invalid app: {other}. Must be one of: photos, locker, auth"
+ )),
+ }
+ }
+}
+
impl Account {
pub fn account_key(&self) -> String {
format!("{}:{}", self.email, self.app.client_package())
@@ -45,49 +71,3 @@ pub struct AccountSecrets {
pub secret_key: Vec<u8>,
pub public_key: Vec<u8>,
}
-
-#[derive(Debug, Deserialize)]
-pub struct SrpAttributes {
- #[serde(rename = "srpUserID")]
- pub srp_user_id: Uuid,
- #[serde(rename = "srpSalt")]
- pub srp_salt: String,
- #[serde(rename = "memLimit")]
- pub mem_limit: u32,
- #[serde(rename = "opsLimit")]
- pub ops_limit: u32,
- #[serde(rename = "kekSalt")]
- pub kek_salt: String,
- #[serde(rename = "isEmailMFAEnabled")]
- pub is_email_mfa_enabled: bool,
-}
-
-#[derive(Debug, Deserialize)]
-pub struct KeyAttributes {
- #[serde(rename = "kekSalt")]
- pub kek_salt: String,
- #[serde(rename = "encryptedKey")]
- pub encrypted_key: String,
- #[serde(rename = "keyDecryptionNonce")]
- pub key_decryption_nonce: String,
- #[serde(rename = "publicKey")]
- pub public_key: String,
- #[serde(rename = "encryptedSecretKey")]
- pub encrypted_secret_key: String,
- #[serde(rename = "secretKeyDecryptionNonce")]
- pub secret_key_decryption_nonce: String,
- #[serde(rename = "memLimit")]
- pub mem_limit: u32,
- #[serde(rename = "opsLimit")]
- pub ops_limit: u32,
-}
-
-#[derive(Debug, Deserialize)]
-pub struct AuthResponse {
- pub id: i64,
- pub token: Option<String>,
- #[serde(rename = "encryptedToken")]
- pub encrypted_token: Option<String>,
- #[serde(rename = "keyAttributes")]
- pub key_attributes: Option<KeyAttributes>,
-}
diff --git a/rust/cli/tests/auth_live.rs b/rust/cli/tests/auth_live.rs
new file mode 100644
index 0000000000..92b6dbd0f9
--- /dev/null
+++ b/rust/cli/tests/auth_live.rs
@@ -0,0 +1,224 @@
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use ente_rs::{
+ api::ApiClient,
+ auth_flow::{
+ AuthFlow, AuthFlowUi, CreateAccountParams, LoginParams, OtpPurpose, SecondFactorMethod,
+ SetupTwoFactorParams, TotpPurpose,
+ },
+ models::{account::App, error::Error},
+};
+use hmac::{Hmac, Mac};
+use sha1::Sha1;
+use uuid::Uuid;
+
+type HmacSha1 = Hmac<Sha1>;
+
+struct LiveUi {
+ otp: String,
+ totp_secret: Option<String>,
+}
+
+impl LiveUi {
+ fn new() -> Self {
+ Self {
+ otp: "123456".into(),
+ totp_secret: None,
+ }
+ }
+}
+
+impl AuthFlowUi for LiveUi {
+ fn read_email_otp(
+ &mut self,
+ _email: &str,
+ _purpose: OtpPurpose,
+ _resent: bool,
+ ) -> ente_rs::Result<String> {
+ Ok(self.otp.clone())
+ }
+
+ fn read_totp_code(&mut self, _purpose: TotpPurpose) -> ente_rs::Result<String> {
+ let secret = self
+ .totp_secret
+ .as_deref()
+ .ok_or_else(|| Error::InvalidInput("No TOTP secret captured for live test".into()))?;
+
+ Ok(current_totp(secret))
+ }
+
+ fn report_retryable_error(&mut self, _message: &str) -> ente_rs::Result<()> {
+ Ok(())
+ }
+
+ fn choose_second_factor(
+ &mut self,
+ _methods: &[SecondFactorMethod],
+ ) -> ente_rs::Result<SecondFactorMethod> {
+ Ok(SecondFactorMethod::Totp)
+ }
+
+ fn present_passkey_verification(&mut self, _url: &str) -> ente_rs::Result<()> {
+ Ok(())
+ }
+
+ fn wait_for_passkey_verification(&mut self) -> ente_rs::Result<()> {
+ Ok(())
+ }
+
+ fn present_totp_secret(&mut self, secret_code: &str, _qr_code: &str) -> ente_rs::Result<()> {
+ self.totp_secret = Some(secret_code.to_string());
+ Ok(())
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires local Museum at http://localhost:8080 with hardcoded OTT config"]
+async fn live_create_login_and_enable_totp() {
+ let endpoint = "http://localhost:8080".to_string();
+ let ping_url = format!("{endpoint}/ping");
+ let ping = match reqwest::get(&ping_url).await {
+ Ok(response) if response.status().is_success() => response,
+ Ok(response) => {
+ eprintln!(
+ "skipping live auth test: {ping_url} returned {}",
+ response.status()
+ );
+ return;
+ }
+ Err(error) => {
+ eprintln!("skipping live auth test: could not reach {ping_url}: {error}");
+ return;
+ }
+ };
+ assert!(ping.status().is_success());
+
+ let email = format!("ente-rs-{}@ente-rust-test.org", Uuid::new_v4());
+ let password = format!("EnteLiveTest-{}!", Uuid::new_v4().simple());
+
+ let create_api =
+ ApiClient::new_with_client_package(Some(endpoint.clone()), App::Photos.client_package())
+ .unwrap();
+ let mut ui = LiveUi::new();
+
+ let created = tokio::time::timeout(Duration::from_secs(120), async {
+ let mut flow = AuthFlow::new(&create_api, App::Photos, &mut ui);
+ flow.create_account(CreateAccountParams {
+ email: email.clone(),
+ password: password.clone(),
+ source: Some("testAccount".into()),
+ })
+ .await
+ })
+ .await
+ .expect("signup timed out")
+ .expect("signup failed");
+
+ assert!(created.recovery_key.is_some());
+ let created_user_id = created.user_id;
+ let created_master_key = created.secrets.master_key.clone();
+ let created_key_attributes = created.key_attributes.clone();
+
+ let login_api =
+ ApiClient::new_with_client_package(Some(endpoint.clone()), App::Photos.client_package())
+ .unwrap();
+ let first_login = tokio::time::timeout(Duration::from_secs(90), async {
+ let mut flow = AuthFlow::new(&login_api, App::Photos, &mut ui);
+ flow.login(LoginParams {
+ email: email.clone(),
+ password: password.clone(),
+ })
+ .await
+ })
+ .await
+ .expect("initial login timed out")
+ .expect("initial login failed");
+
+ assert_eq!(first_login.user_id, created_user_id);
+ assert_eq!(first_login.secrets.master_key, created_master_key);
+
+ let setup_result = tokio::time::timeout(Duration::from_secs(60), async {
+ let mut flow = AuthFlow::new(&create_api, App::Photos, &mut ui);
+ flow.setup_two_factor(SetupTwoFactorParams {
+ account_id: email.clone(),
+ master_key: created_master_key.clone(),
+ key_attributes: Some(created_key_attributes),
+ })
+ .await
+ })
+ .await
+ .expect("two-factor setup timed out")
+ .expect("two-factor setup failed");
+
+ assert_eq!(
+ ui.totp_secret.as_deref(),
+ Some(setup_result.secret_code.as_str())
+ );
+
+ let login_after_2fa_api =
+ ApiClient::new_with_client_package(Some(endpoint.clone()), App::Photos.client_package())
+ .unwrap();
+ let second_login = tokio::time::timeout(Duration::from_secs(90), async {
+ let mut flow = AuthFlow::new(&login_after_2fa_api, App::Photos, &mut ui);
+ flow.login(LoginParams {
+ email: email.clone(),
+ password: password.clone(),
+ })
+ .await
+ })
+ .await
+ .expect("two-factor login timed out")
+ .expect("two-factor login failed");
+
+ assert_eq!(second_login.user_id, created_user_id);
+ assert_eq!(second_login.secrets.master_key, created_master_key);
+}
+
+fn current_totp(secret: &str) -> String {
+ let key = decode_base32(secret);
+ let counter = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("system time before UNIX_EPOCH")
+ .as_secs()
+ / 30;
+
+ let mut mac = HmacSha1::new_from_slice(&key).expect("invalid HMAC key");
+ mac.update(&counter.to_be_bytes());
+ let digest = mac.finalize().into_bytes();
+ let offset = (digest[19] & 0x0f) as usize;
+
+ let binary = ((digest[offset] as u32 & 0x7f) << 24)
+ | ((digest[offset + 1] as u32) << 16)
+ | ((digest[offset + 2] as u32) << 8)
+ | digest[offset + 3] as u32;
+
+ format!("{:06}", binary % 1_000_000)
+}
+
+fn decode_base32(secret: &str) -> Vec<u8> {
+ let mut output = Vec::new();
+ let mut buffer = 0u32;
+ let mut bits = 0u8;
+
+ for ch in secret
+ .chars()
+ .filter(|ch| !ch.is_whitespace() && *ch != '=')
+ {
+ let value = match ch {
+ 'A'..='Z' => ch as u8 - b'A',
+ 'a'..='z' => ch as u8 - b'a',
+ '2'..='7' => ch as u8 - b'2' + 26,
+ _ => panic!("invalid base32 character in TOTP secret: {ch}"),
+ } as u32;
+
+ buffer = (buffer << 5) | value;
+ bits += 5;
+
+ while bits >= 8 {
+ bits -= 8;
+ output.push(((buffer >> bits) & 0xff) as u8);
+ }
+ }
+
+ output
+}
diff --git a/rust/core/src/auth/key_gen.rs b/rust/core/src/auth/key_gen.rs
index ebe214530e..2c9cba01db 100644
--- a/rust/core/src/auth/key_gen.rs
+++ b/rust/core/src/auth/key_gen.rs
@@ -87,6 +87,7 @@ pub fn generate_keys_with_strength(
Ok(KeyGenResult {
key_attributes,
private_key_attributes,
+ key_encryption_key: derived.key,
login_key,
})
}
@@ -197,21 +198,12 @@ mod tests {
fn test_generate_keys_can_decrypt_master_key() {
crypto::init().unwrap();
- let password = "my_secure_password";
- let result = generate_test_keys(password).unwrap();
-
- let kek_salt = crypto::decode_b64(&result.key_attributes.kek_salt).unwrap();
- let kek = argon::derive_key(
- password,
- &kek_salt,
- result.key_attributes.mem_limit.unwrap(),
- result.key_attributes.ops_limit.unwrap(),
- )
- .unwrap();
+ let result = generate_test_keys("my_secure_password").unwrap();
let encrypted_key = crypto::decode_b64(&result.key_attributes.encrypted_key).unwrap();
let nonce = crypto::decode_b64(&result.key_attributes.key_decryption_nonce).unwrap();
- let decrypted_master = secretbox::decrypt(&encrypted_key, &nonce, &kek).unwrap();
+ let decrypted_master =
+ secretbox::decrypt(&encrypted_key, &nonce, &result.key_encryption_key).unwrap();
let original_master = crypto::decode_b64(&result.private_key_attributes.key).unwrap();
assert_eq!(decrypted_master, original_master);
diff --git a/rust/core/src/auth/types.rs b/rust/core/src/auth/types.rs
index 7fb4d655d1..bec0831450 100644
--- a/rust/core/src/auth/types.rs
+++ b/rust/core/src/auth/types.rs
@@ -56,6 +56,8 @@ pub struct KeyGenResult {
pub key_attributes: KeyAttributes,
/// Private keys to store locally
pub private_key_attributes: PrivateKeyAttributes,
+ /// Key-encryption-key used to encrypt the master key and seed SRP setup.
+ pub key_encryption_key: Vec<u8>,
/// Login key for SRP registration (16 bytes)
pub login_key: Vec<u8>,
}