Skip to content

armgit / ente

Public Imported from GitHub
0

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

[rust] Separate login and signup from interactive prompts (#13197)

neeraj-pilotd399a76f9217
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index c40c0561bc..175bede711 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2878,8 +2878,6 @@ dependencies = [
"rusqlite",
"serde",
"serde_json",
- "sha2 0.11.0",
- "srp",
"thiserror 2.0.18",
"tokio",
"url",
diff --git a/rust/apps/cli-next/src/login.rs b/rust/apps/cli-next/src/login.rs
index 77bd1a4618..823201004a 100644
--- a/rust/apps/cli-next/src/login.rs
+++ b/rust/apps/cli-next/src/login.rs
@@ -7,8 +7,8 @@ use std::{
use anyhow::{Context, Result, ensure};
use dialoguer::{Input, Password, Select, console::Term};
use ente_accounts::{
- AuthFlow, AuthFlowUi, DEFAULT_API_ORIGIN, LoginParams, OtpPurpose, SecondFactorMethod,
- TotpPurpose, auth,
+ AccountsClient, AuthenticatedAccount, DEFAULT_API_ORIGIN, auth,
+ login::{LoginFlow, LoginStep},
};
use ente_core::http::{Api, ApiConfig, Http};
use serde::Deserialize;
@@ -58,12 +58,13 @@ pub async fn login(
.ping()
.await
.context("cannot reach the selected Ente server")?;
- let (params, mut ui) = match credentials {
- Some(credentials) => credentials.into_login(),
- None => LoginUi::prompt()?,
+ let interactive = credentials.is_none();
+ let mut credentials = match credentials {
+ Some(credentials) => credentials,
+ None => Credentials::prompt()?,
};
let client = api::accounts_client(&origin, product)?;
- let mut authenticated = AuthFlow::new(&client, &mut ui).login(params).await?;
+ let mut authenticated = authenticate(&client, &mut credentials, interactive).await?;
client.set_auth_token(Some(ente_core::b64::encode_url_safe(
&authenticated.secrets.token,
)));
@@ -86,7 +87,7 @@ pub async fn login(
let mut new_name = requested_name.unwrap_or_else(|| email.clone());
if snapshot_existing.is_none() {
while let Err(error) = snapshot.check_name(&new_name) {
- if !ui.interactive {
+ if !interactive {
return Err(error);
}
eprintln!("{error}");
@@ -226,150 +227,121 @@ impl Credentials {
.context("login input must contain email and password, with optional otp and totp")
}
- fn into_login(mut self) -> (LoginParams, LoginUi) {
- let params = LoginParams {
- email: std::mem::take(&mut self.email),
- password: Zeroizing::new(std::mem::take(&mut self.password)),
- };
- (
- params,
- LoginUi {
- interactive: false,
- credentials: Some(self),
- },
- )
- }
-}
-
-struct LoginUi {
- interactive: bool,
- credentials: Option<Credentials>,
-}
-
-impl LoginUi {
- fn prompt() -> Result<(LoginParams, Self)> {
+ fn prompt() -> Result<Self> {
ensure!(
io::stdin().is_terminal() && io::stderr().is_terminal(),
"noninteractive login requires --input <file> or --input -"
);
- let email = Input::new()
- .with_prompt("Email")
- .interact_on(&Term::stderr())?;
- let password = Password::new()
- .with_prompt("Password")
- .interact_on(&Term::stderr())?;
- Ok((
- LoginParams {
- email,
- password: Zeroizing::new(password),
- },
- Self {
- interactive: true,
- credentials: None,
- },
- ))
- }
-
- fn secret_prompt(&self, label: &str) -> ente_accounts::Result<String> {
- Password::new()
- .with_prompt(label)
- .interact_on(&Term::stderr())
- .map_err(|error| ente_accounts::Error::Ui(Box::new(error)))
+ Ok(Self {
+ email: Input::new()
+ .with_prompt("Email")
+ .interact_on(&Term::stderr())?,
+ password: Password::new()
+ .with_prompt("Password")
+ .interact_on(&Term::stderr())?,
+ otp: None,
+ totp: None,
+ })
}
}
-impl AuthFlowUi for LoginUi {
- fn read_email_otp(
- &mut self,
- _email: &str,
- _purpose: OtpPurpose,
- _resent: bool,
- ) -> ente_accounts::Result<String> {
- if self.interactive {
- return self.secret_prompt("Email verification code");
- }
- self.credentials
- .as_mut()
- .and_then(|c| c.otp.take())
- .ok_or_else(|| {
- ente_accounts::Error::InvalidInput(
- "login requires an email verification code; supply otp in --input".into(),
- )
- })
- }
-
- fn read_totp_code(&mut self, _purpose: TotpPurpose) -> ente_accounts::Result<String> {
- if self.interactive {
- return self.secret_prompt("Authenticator code");
- }
- self.credentials
- .as_mut()
- .and_then(|c| c.totp.take())
- .ok_or_else(|| {
- ente_accounts::Error::InvalidInput(
- "login requires an authenticator code; supply totp in --input".into(),
- )
- })
- }
-
- fn report_retryable_error(&mut self, message: &str) -> ente_accounts::Result<()> {
- if !self.interactive {
- return Err(ente_accounts::Error::InvalidInput(message.into()));
- }
- eprintln!("{message}");
- Ok(())
- }
-
- fn choose_second_factor(
- &mut self,
- methods: &[SecondFactorMethod],
- ) -> ente_accounts::Result<SecondFactorMethod> {
- if !self.interactive {
- return Ok(SecondFactorMethod::Totp);
- }
- let labels: Vec<_> = methods
- .iter()
- .map(|method| match method {
- SecondFactorMethod::Totp => "Authenticator code",
- SecondFactorMethod::Passkey => "Passkey in browser",
- })
- .collect();
- let index = Select::new()
- .with_prompt("Verify with")
- .items(&labels)
- .interact_on(&Term::stderr())
- .map_err(|error| ente_accounts::Error::Ui(Box::new(error)))?;
- Ok(methods[index])
- }
-
- fn present_passkey_verification(&mut self, url: &str) -> ente_accounts::Result<()> {
- if !self.interactive {
- return Err(ente_accounts::Error::InvalidInput(
- "passkey login requires an interactive terminal".into(),
- ));
- }
- eprintln!("Open this URL to verify your passkey:\n{url}");
- Ok(())
- }
-
- fn wait_for_passkey_verification(&mut self) -> ente_accounts::Result<()> {
- Input::<String>::new()
- .with_prompt("Press Enter after completing verification")
- .allow_empty(true)
- .interact_on(&Term::stderr())
- .map_err(|error| ente_accounts::Error::Ui(Box::new(error)))?;
- Ok(())
+async fn authenticate(
+ client: &AccountsClient,
+ credentials: &mut Credentials,
+ interactive: bool,
+) -> Result<AuthenticatedAccount> {
+ let (mut flow, mut step) = LoginFlow::start(client, credentials.email.clone()).await?;
+ loop {
+ step = match step {
+ LoginStep::EmailCode => loop {
+ let code = verification_code(
+ &mut credentials.otp,
+ interactive,
+ "Email verification code",
+ "otp",
+ )?;
+ match flow.submit_code(client, &code).await {
+ Ok(next) => break next,
+ Err(ente_accounts::Error::IncorrectEmailVerificationCode) if interactive => {
+ eprintln!("Incorrect email verification code. Try again.");
+ }
+ Err(ente_accounts::Error::EmailVerificationCodeExpired) if interactive => {
+ flow.resend_code(client).await?;
+ }
+ Err(error) => return Err(error.into()),
+ }
+ },
+ LoginStep::Password => flow.submit_password(client, &credentials.password).await?,
+ LoginStep::SecondFactor { totp, passkey } => {
+ let use_passkey = match (totp, passkey) {
+ (true, true) if interactive => {
+ Select::new()
+ .with_prompt("Verify with")
+ .items(&["Authenticator code", "Passkey in browser"])
+ .interact_on(&Term::stderr())?
+ == 1
+ }
+ (true, _) => false,
+ (false, true) => true,
+ (false, false) => {
+ return Err(
+ ente_accounts::Error::Protocol("Missing second factor".into()).into(),
+ );
+ }
+ };
+ if use_passkey {
+ ensure!(
+ interactive,
+ "passkey login requires an interactive terminal"
+ );
+ let url = flow.passkey_url(client, "ente-cli://passkey")?;
+ eprintln!("Open this URL to verify your passkey:\n{url}");
+ loop {
+ Input::<String>::new()
+ .with_prompt("Press Enter after completing verification")
+ .allow_empty(true)
+ .interact_on(&Term::stderr())?;
+ if let Some(next) = flow.poll_passkey(client).await? {
+ break next;
+ }
+ }
+ } else {
+ loop {
+ let code = verification_code(
+ &mut credentials.totp,
+ interactive,
+ "Authenticator code",
+ "totp",
+ )?;
+ match flow.submit_code(client, &code).await {
+ Ok(next) => break next,
+ Err(ente_accounts::Error::IncorrectTotp) if interactive => {
+ eprintln!("Incorrect TOTP code. Try again.");
+ }
+ Err(error) => return Err(error.into()),
+ }
+ }
+ }
+ }
+ LoginStep::Complete(account) => return Ok(*account),
+ };
}
+}
- fn present_totp_secret(
- &mut self,
- _secret_code: &str,
- _qr_code: &str,
- ) -> ente_accounts::Result<()> {
- Err(ente_accounts::Error::InvalidInput(
- "login cannot enroll a new authenticator".into(),
- ))
+fn verification_code(
+ supplied: &mut Option<String>,
+ interactive: bool,
+ label: &str,
+ field: &str,
+) -> Result<String> {
+ if interactive {
+ return Ok(Password::new()
+ .with_prompt(label)
+ .interact_on(&Term::stderr())?);
}
+ supplied
+ .take()
+ .with_context(|| format!("login requires {label}; supply {field} in --input"))
}
#[cfg(test)]
@@ -378,22 +350,26 @@ mod tests {
#[test]
fn noninteractive_codes_come_from_their_login_input_fields() {
- let credentials: Credentials = parse_json(
+ let mut credentials: Credentials = parse_json(
br#"{"email":"[email protected]","password":"secret","otp":"123456","totp":"654321"}"#,
)
.unwrap();
- let mut ui = LoginUi {
- interactive: false,
- credentials: Some(credentials),
- };
assert_eq!(
- ui.read_email_otp("[email protected]", OtpPurpose::Login, false)
- .unwrap(),
+ verification_code(
+ &mut credentials.otp,
+ false,
+ "Email verification code",
+ "otp"
+ )
+ .unwrap(),
"123456"
);
- assert_eq!(ui.read_totp_code(TotpPurpose::Login).unwrap(), "654321");
+ assert_eq!(
+ verification_code(&mut credentials.totp, false, "Authenticator code", "totp").unwrap(),
+ "654321"
+ );
assert!(
- ui.read_totp_code(TotpPurpose::Login)
+ verification_code(&mut credentials.totp, false, "Authenticator code", "totp")
.unwrap_err()
.to_string()
.contains("supply totp in --input")
diff --git a/rust/apps/cli-next/tests/support/museum.rs b/rust/apps/cli-next/tests/support/museum.rs
index bd16aa7d92..5d13ac9e12 100644
--- a/rust/apps/cli-next/tests/support/museum.rs
+++ b/rust/apps/cli-next/tests/support/museum.rs
@@ -1,14 +1,10 @@
-use ente_accounts::{
- AccountsClient, AccountsClientConfig, AuthFlow, AuthFlowUi, AuthenticatedAccount,
- CreateAccountParams, OtpPurpose, SecondFactorMethod, TotpPurpose,
-};
+use ente_accounts::{AccountsClient, AccountsClientConfig, AuthenticatedAccount, signup::Signup};
use ente_core::{
crypto::{PublicKey, blob, sealed, secretbox, stream},
io::Md5Writer,
};
use ente_test_support::{HARDCODED_OTT, Museum, TestResult};
use uuid::Uuid;
-use zeroize::Zeroizing;
use super::*;
@@ -600,15 +596,16 @@ async fn create_account(origin: &str, email: &str) -> AuthenticatedAccount {
AccountsClient::new(AccountsClientConfig::new("io.ente.photos").with_origin(origin))
.unwrap();
client.send_otp(email, "signup").await.unwrap();
- AuthFlow::new(&client, &mut NoPrompts)
- .create_account_with_otp(
- CreateAccountParams {
- email: email.into(),
- password: Zeroizing::new(PASSWORD.into()),
- source: Some("testAccount".into()),
- },
- HARDCODED_OTT,
- )
+ let response = client
+ .verify_email(email, HARDCODED_OTT, Some("testAccount"))
+ .await
+ .unwrap();
+ Signup::verified(email.into(), response)
+ .unwrap()
+ .prepare(&client, PASSWORD)
+ .await
+ .unwrap()
+ .finish(&client)
.await
.unwrap()
}
@@ -785,34 +782,5 @@ async fn set_album_metadata(
.unwrap();
}
-struct NoPrompts;
-
-impl AuthFlowUi for NoPrompts {
- fn read_email_otp(&mut self, _: &str, _: OtpPurpose, _: bool) -> ente_accounts::Result<String> {
- unreachable!()
- }
- fn read_totp_code(&mut self, _: TotpPurpose) -> ente_accounts::Result<String> {
- unreachable!()
- }
- fn report_retryable_error(&mut self, _: &str) -> ente_accounts::Result<()> {
- unreachable!()
- }
- fn choose_second_factor(
- &mut self,
- _: &[SecondFactorMethod],
- ) -> ente_accounts::Result<SecondFactorMethod> {
- unreachable!()
- }
- fn present_passkey_verification(&mut self, _: &str) -> ente_accounts::Result<()> {
- unreachable!()
- }
- fn wait_for_passkey_verification(&mut self) -> ente_accounts::Result<()> {
- unreachable!()
- }
- fn present_totp_secret(&mut self, _: &str, _: &str) -> ente_accounts::Result<()> {
- unreachable!()
- }
-}
-
#[path = "export.rs"]
mod export;
diff --git a/rust/apps/cli/Cargo.toml b/rust/apps/cli/Cargo.toml
index 042dfb93b7..621f3f1df0 100644
--- a/rust/apps/cli/Cargo.toml
+++ b/rust/apps/cli/Cargo.toml
@@ -36,8 +36,6 @@ zip.workspace = true
[dev-dependencies]
ente-test-support.workspace = true
mockito.workspace = true
-sha2.workspace = true
-srp.workspace = true
url.workspace = true
[lints]
diff --git a/rust/apps/cli/src/auth_flow.rs b/rust/apps/cli/src/auth_flow.rs
deleted file mode 100644
index 13ea76c589..0000000000
--- a/rust/apps/cli/src/auth_flow.rs
+++ /dev/null
@@ -1,674 +0,0 @@
-use crate::{
- api::{AppClient, client::USER_AGENT, models::KeyAttributes},
- models::{
- account::AccountSecrets,
- error::{Error, Result},
- },
-};
-
-use ente_core::b64;
-use ente_core::crypto::SecretVec;
-use serde::{Serialize, de::DeserializeOwned};
-use std::fmt;
-use zeroize::Zeroizing;
-
-fn convert<T, U>(value: T) -> Result<U>
-where
- T: Serialize,
- U: DeserializeOwned,
-{
- serde_json::from_value(serde_json::to_value(value)?).map_err(Error::from)
-}
-
-fn shared_client(
- app_client: &AppClient,
- authenticated: bool,
-) -> Result<ente_accounts::AccountsClient> {
- let mut config = ente_accounts::AccountsClientConfig::new(app_client.app().client_package())
- .with_origin(app_client.origin().to_string())
- .with_user_agent(USER_AGENT);
- if let Some(token) = authenticated.then(|| app_client.token()).flatten() {
- config = config.with_auth_token(token);
- }
- ente_accounts::AccountsClient::new(config).map_err(Error::from)
-}
-
-fn to_shared_error(error: Error) -> ente_accounts::Error {
- match error {
- Error::Http(source) => ente_accounts::Error::Http(source),
- Error::Accounts(source) => source,
- other => ente_accounts::Error::Ui(Box::new(other)),
- }
-}
-
-pub use ente_accounts::{OtpPurpose, SecondFactorMethod, TotpPurpose};
-
-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<()>;
-}
-
-struct UiAdapter<'a, U> {
- inner: &'a mut U,
-}
-
-impl<U: AuthFlowUi> ente_accounts::AuthFlowUi for UiAdapter<'_, U> {
- fn read_email_otp(
- &mut self,
- email: &str,
- purpose: OtpPurpose,
- resent: bool,
- ) -> ente_accounts::Result<String> {
- self.inner
- .read_email_otp(email, purpose, resent)
- .map_err(to_shared_error)
- }
-
- fn read_totp_code(&mut self, purpose: TotpPurpose) -> ente_accounts::Result<String> {
- self.inner.read_totp_code(purpose).map_err(to_shared_error)
- }
-
- fn report_retryable_error(&mut self, message: &str) -> ente_accounts::Result<()> {
- self.inner
- .report_retryable_error(message)
- .map_err(to_shared_error)
- }
-
- fn choose_second_factor(
- &mut self,
- methods: &[SecondFactorMethod],
- ) -> ente_accounts::Result<SecondFactorMethod> {
- self.inner
- .choose_second_factor(methods)
- .map_err(to_shared_error)
- }
-
- fn present_passkey_verification(&mut self, url: &str) -> ente_accounts::Result<()> {
- self.inner
- .present_passkey_verification(url)
- .map_err(to_shared_error)
- }
-
- fn wait_for_passkey_verification(&mut self) -> ente_accounts::Result<()> {
- self.inner
- .wait_for_passkey_verification()
- .map_err(to_shared_error)
- }
-
- fn present_totp_secret(
- &mut self,
- secret_code: &str,
- qr_code: &str,
- ) -> ente_accounts::Result<()> {
- self.inner
- .present_totp_secret(secret_code, qr_code)
- .map_err(to_shared_error)
- }
-}
-
-pub struct CreateAccountParams {
- pub email: String,
- pub password: Zeroizing<String>,
- pub source: Option<String>,
-}
-
-impl fmt::Debug for CreateAccountParams {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("CreateAccountParams")
- .field("email", &self.email)
- .field("password", &"[REDACTED]")
- .field("source", &self.source)
- .finish()
- }
-}
-
-pub struct LoginParams {
- pub email: String,
- pub password: Zeroizing<String>,
-}
-
-impl fmt::Debug for LoginParams {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("LoginParams")
- .field("email", &self.email)
- .field("password", &"[REDACTED]")
- .finish()
- }
-}
-
-pub struct SetupTwoFactorParams {
- pub account_id: String,
- pub master_key: SecretVec,
- pub key_attributes: Option<KeyAttributes>,
-}
-
-impl fmt::Debug for SetupTwoFactorParams {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("SetupTwoFactorParams")
- .field("account_id", &self.account_id)
- .field("master_key", &"[REDACTED]")
- .field("key_attributes", &self.key_attributes)
- .finish()
- }
-}
-
-pub struct AuthenticatedAccount {
- pub user_id: i64,
- pub key_attributes: KeyAttributes,
- pub secrets: AccountSecrets,
- pub recovery_key: Option<String>,
-}
-
-impl fmt::Debug for AuthenticatedAccount {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("AuthenticatedAccount")
- .field("user_id", &self.user_id)
- .field("key_attributes", &self.key_attributes)
- .field("secrets", &self.secrets)
- .field("recovery_key", &"[REDACTED]")
- .finish()
- }
-}
-
-pub struct SetupTwoFactorResult {
- pub secret_code: String,
- pub qr_code: String,
- pub recovery_key: String,
-}
-
-impl fmt::Debug for SetupTwoFactorResult {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("SetupTwoFactorResult")
- .field("secret_code", &"[REDACTED]")
- .field("qr_code", &"[REDACTED]")
- .field("recovery_key", &"[REDACTED]")
- .finish()
- }
-}
-
-fn from_shared_account(
- account: ente_accounts::AuthenticatedAccount,
-) -> Result<AuthenticatedAccount> {
- Ok(AuthenticatedAccount {
- user_id: account.user_id,
- key_attributes: convert(account.key_attributes)?,
- secrets: AccountSecrets {
- token: account.secrets.token.clone(),
- master_key: account.secrets.master_key.clone(),
- secret_key: account.secrets.secret_key.clone(),
- public_key: account.secrets.public_key.clone(),
- },
- recovery_key: account.recovery_key,
- })
-}
-
-pub struct AuthFlow<'a, U> {
- app_client: &'a AppClient,
- ui: &'a mut U,
-}
-
-impl<'a, U> AuthFlow<'a, U>
-where
- U: AuthFlowUi,
-{
- pub fn new(app_client: &'a AppClient, ui: &'a mut U) -> Self {
- Self { app_client, ui }
- }
-
- pub async fn create_account(
- &mut self,
- params: CreateAccountParams,
- ) -> Result<AuthenticatedAccount> {
- let client = shared_client(self.app_client, false)?;
- let mut ui = UiAdapter { inner: self.ui };
- let mut flow = ente_accounts::AuthFlow::new(&client, &mut ui);
- let account = from_shared_account(
- flow.create_account(ente_accounts::CreateAccountParams {
- email: params.email,
- password: params.password,
- source: params.source,
- })
- .await
- .map_err(Error::from)?,
- )?;
- self.app_client
- .set_token(&b64::encode_url_safe(&account.secrets.token));
- Ok(account)
- }
-
- pub async fn login(&mut self, params: LoginParams) -> Result<AuthenticatedAccount> {
- let client = shared_client(self.app_client, false)?;
- let mut ui = UiAdapter { inner: self.ui };
- let mut flow = ente_accounts::AuthFlow::new(&client, &mut ui);
- from_shared_account(
- flow.login(ente_accounts::LoginParams {
- email: params.email,
- password: params.password,
- })
- .await
- .map_err(Error::from)?,
- )
- }
-
- pub async fn setup_two_factor(
- &mut self,
- params: SetupTwoFactorParams,
- ) -> Result<SetupTwoFactorResult> {
- let client = shared_client(self.app_client, true)?;
- let mut ui = UiAdapter { inner: self.ui };
- let mut flow = ente_accounts::AuthFlow::new(&client, &mut ui);
- let result = flow
- .setup_two_factor(ente_accounts::SetupTwoFactorParams {
- master_key: params.master_key,
- key_attributes: params.key_attributes.map(convert).transpose()?,
- })
- .await
- .map_err(Error::from)?;
- Ok(SetupTwoFactorResult {
- secret_code: result.secret_code,
- qr_code: result.qr_code,
- recovery_key: result.recovery_key,
- })
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::models::account::App;
- use mockito::{Matcher, Server};
- use serde::{Deserialize, de::DeserializeOwned};
- use sha2::{Digest, Sha256};
- use srp::ServerG4096;
- use std::{
- collections::VecDeque,
- sync::{Arc, Mutex},
- };
- use uuid::Uuid;
-
- const SRP_A_LEN: usize = 512;
-
- #[derive(Default)]
- struct MockSignupState {
- uploaded_key_attributes: Option<KeyAttributes>,
- remote_srp_attributes: Option<ente_accounts::models::SrpAttributes>,
- 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,
- }
-
- struct ScriptedUi {
- email_otps: VecDeque<String>,
- setup_totps: VecDeque<String>,
- last_totp_secret: Option<String>,
- }
-
- impl ScriptedUi {
- fn new() -> Self {
- Self {
- email_otps: VecDeque::new(),
- setup_totps: VecDeque::new(),
- last_totp_secret: None,
- }
- }
- }
-
- 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> {
- self.setup_totps
- .pop_front()
- .ok_or_else(|| Error::InvalidInput("No scripted TOTP code available".into()))
- }
-
- fn report_retryable_error(&mut self, _message: &str) -> Result<()> {
- Ok(())
- }
-
- fn choose_second_factor(
- &mut self,
- _methods: &[SecondFactorMethod],
- ) -> Result<SecondFactorMethod> {
- Ok(SecondFactorMethod::Totp)
- }
-
- fn present_passkey_verification(&mut self, _url: &str) -> Result<()> {
- 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 parse_request_body<T>(request: &mockito::Request) -> T
- where
- T: DeserializeOwned,
- {
- serde_json::from_str(&request.utf8_lossy_body().unwrap()).unwrap()
- }
-
- 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
- }
-
- #[tokio::test]
- async fn create_account_persists_token_for_setup_two_factor() {
- let email = "[email protected]";
- let encoded_email = urlencoding::encode(email).into_owned();
- let signup_token_bytes = b"signup-session-token";
- let signup_token = b64::encode_url_safe(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());
- ui.setup_totps.push_back("123123".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);
- state.lock().unwrap().uploaded_key_attributes = Some(payload.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_salt = b64::decode(&payload.srp_salt).unwrap();
- let srp_verifier = b64::decode(&payload.srp_verifier).unwrap();
- let srp_a = b64::decode(&payload.srp_a).unwrap();
- let server = ServerG4096::<Sha256>::new();
- 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(
- payload.srp_user_id.as_bytes(),
- &srp_salt,
- &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(ente_accounts::models::SrpAttributes {
- 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": b64::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 = b64::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": b64::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 setup_two_factor = server
- .mock("POST", "/users/two-factor/setup")
- .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!({
- "secretCode": "JBSWY3DPEHPK3PXP",
- "qrCode": "qr-png-b64",
- })
- .to_string(),
- )
- .create_async()
- .await;
-
- let enable_two_factor = server
- .mock("POST", "/users/two-factor/enable")
- .match_header("x-auth-token", signup_token.as_str())
- .match_header("x-client-package", "io.ente.photos")
- .match_body(Matcher::Regex("\"encryptedTwoFactorSecret\"".into()))
- .with_status(200)
- .create_async()
- .await;
-
- let app_client = AppClient::new(Some(server.url()), App::Photos).unwrap();
- let mut flow = AuthFlow::new(&app_client, &mut ui);
-
- let created = flow
- .create_account(CreateAccountParams {
- email: email.into(),
- password: Zeroizing::new("correct horse battery staple".into()),
- source: Some("testAccount".into()),
- })
- .await
- .unwrap();
-
- assert_eq!(app_client.token().as_deref(), Some(signup_token.as_str()));
-
- let (uploaded_key_attributes, remote_srp_attributes) = {
- let state = signup_state.lock().unwrap();
- (
- state.uploaded_key_attributes.clone().unwrap(),
- state.remote_srp_attributes.clone().unwrap(),
- )
- };
-
- assert_eq!(created.user_id, 99);
- assert_eq!(created.secrets.token, signup_token_bytes);
- assert_eq!(
- remote_srp_attributes.kek_salt,
- uploaded_key_attributes.kek_salt
- );
- assert_eq!(
- remote_srp_attributes.mem_limit,
- uploaded_key_attributes.mem_limit
- );
- assert_eq!(
- remote_srp_attributes.ops_limit,
- uploaded_key_attributes.ops_limit
- );
-
- let setup = flow
- .setup_two_factor(SetupTwoFactorParams {
- account_id: email.into(),
- master_key: SecretVec::new(created.secrets.master_key.clone()),
- key_attributes: Some(created.key_attributes),
- })
- .await
- .unwrap();
-
- assert_eq!(setup.secret_code, "JBSWY3DPEHPK3PXP");
- assert_eq!(ui.last_totp_secret.as_deref(), Some("JBSWY3DPEHPK3PXP"));
-
- 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;
- setup_two_factor.assert_async().await;
- enable_two_factor.assert_async().await;
- }
-}
diff --git a/rust/apps/cli/src/commands/account.rs b/rust/apps/cli/src/commands/account.rs
index 3ea8fa97c6..68e23b295a 100644
--- a/rust/apps/cli/src/commands/account.rs
+++ b/rust/apps/cli/src/commands/account.rs
@@ -2,19 +2,18 @@ use crate::{
api::client::USER_AGENT,
cli::account::{AccountCommand, AccountSubcommands, AddArgs, CreateArgs},
models::{
- account::{Account, AccountSecrets as StoredAccountSecrets, App},
+ account::{Account, App},
error::{Error, Result},
},
storage::Storage,
};
use dialoguer::{Input, Password, Select};
use ente_accounts::{
- AccountsClient, AccountsClientConfig, AuthFlow, AuthFlowUi, AuthenticatedAccount,
- CreateAccountParams, LoginParams, OtpPurpose, SecondFactorMethod, SetupTwoFactorParams,
- TotpPurpose,
+ AccountsClient, AccountsClientConfig, AuthenticatedAccount, TwoFactorSetup,
+ login::{LoginFlow, LoginStep},
+ signup::Signup,
};
use ente_core::b64;
-use ente_core::crypto::SecretVec;
use ente_core::urls::PRODUCTION_API_ORIGIN;
use std::{path::PathBuf, str::FromStr};
use zeroize::Zeroizing;
@@ -37,135 +36,183 @@ pub async fn handle_account_command(cmd: AccountCommand, storage: &Storage) -> R
}
}
-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,
- }
- }
+#[derive(Clone, Copy)]
+enum SecondFactorMethod {
+ Totp,
+ Passkey,
}
-impl AuthFlowUi for DialoguerAuthFlowUi {
- fn read_email_otp(
- &mut self,
- email: &str,
- purpose: OtpPurpose,
- resent: bool,
- ) -> ente_accounts::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}")
+async fn login(
+ client: &AccountsClient,
+ email: &str,
+ password: Option<String>,
+ mut otp: Option<String>,
+ mut totp_code: Option<String>,
+ second_factor: Option<SecondFactorMethod>,
+) -> Result<AuthenticatedAccount> {
+ let interactive_password = password.is_none();
+ let mut password = Zeroizing::new(prompt_password(password, "Enter your password")?);
+ let (mut flow, mut step) = LoginFlow::start(client, email.into()).await?;
+ loop {
+ step = match step {
+ LoginStep::EmailCode => {
+ let mut resent = false;
+ loop {
+ let prompt = if resent {
+ format!("Enter the new email-MFA code sent to {email}")
+ } else {
+ format!("Enter the email-MFA code sent to {email}")
+ };
+ let code = take_code(&mut otp, &prompt)?;
+ match flow.submit_code(client, &code).await {
+ Ok(next) => break next,
+ Err(ente_accounts::Error::IncorrectEmailVerificationCode) => {
+ println!("\nIncorrect email verification code. Try again.");
+ resent = false;
+ }
+ Err(ente_accounts::Error::EmailVerificationCodeExpired) => {
+ flow.resend_code(client).await?;
+ resent = true;
+ }
+ Err(error) => return Err(error.into()),
+ }
+ }
}
- (OtpPurpose::Login, true) => {
- format!("Enter the new email-MFA code sent to {email}")
+ LoginStep::Password => loop {
+ match flow.submit_password(client, &password).await {
+ Ok(next) => break next,
+ Err(ente_accounts::Error::IncorrectPassword) if interactive_password => {
+ println!("\nIncorrect password. Try again.");
+ password = Zeroizing::new(prompt_password(None, "Re-enter your password")?);
+ }
+ Err(error) => return Err(error.into()),
+ }
+ },
+ LoginStep::SecondFactor { totp, passkey } => {
+ let method = match (totp, passkey) {
+ (true, true) => match second_factor {
+ Some(method) => method,
+ None => match Select::new()
+ .with_prompt("Choose verification method")
+ .items(&["TOTP (Authenticator app)", "Passkey"])
+ .default(0)
+ .interact()
+ .map_err(|error| Error::InvalidInput(error.to_string()))?
+ {
+ 0 => SecondFactorMethod::Totp,
+ _ => SecondFactorMethod::Passkey,
+ },
+ },
+ (true, false) => SecondFactorMethod::Totp,
+ (false, true) => SecondFactorMethod::Passkey,
+ (false, false) => {
+ return Err(
+ ente_accounts::Error::Protocol("Missing second factor".into()).into(),
+ );
+ }
+ };
+ match method {
+ SecondFactorMethod::Totp => loop {
+ let code = take_code(&mut totp_code, "Enter TOTP code")?;
+ match flow.submit_code(client, &code).await {
+ Ok(next) => break next,
+ Err(ente_accounts::Error::IncorrectTotp) => {
+ println!("\nIncorrect TOTP code. Try again.")
+ }
+ Err(error) => return Err(error.into()),
+ }
+ },
+ SecondFactorMethod::Passkey => {
+ let url = flow.passkey_url(client, "ente-cli://passkey")?;
+ println!("\nPasskey verification required");
+ println!("Open this URL in your browser to verify your passkey:\n{url}");
+ if can_open_automatically(&url) && open::that(&url).is_err() {
+ log::error!("failed to open browser");
+ }
+ loop {
+ Input::<String>::new()
+ .with_prompt(
+ "Press Enter once you have completed passkey verification",
+ )
+ .allow_empty(true)
+ .interact_text()
+ .map_err(|error| Error::InvalidInput(error.to_string()))?;
+ if let Some(next) = flow.poll_passkey(client).await? {
+ break next;
+ }
+ }
+ }
+ }
}
+ LoginStep::Complete(account) => return Ok(*account),
};
-
- read_six_digit_code_for_accounts(&prompt)
}
+}
- fn read_totp_code(&mut self, purpose: TotpPurpose) -> ente_accounts::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",
+async fn signup(
+ client: &AccountsClient,
+ email: &str,
+ password: &str,
+ mut otp: Option<String>,
+ source: Option<&str>,
+) -> Result<AuthenticatedAccount> {
+ client.send_otp(email, "signup").await?;
+ let mut resent = false;
+ let verification = loop {
+ let prompt = if resent {
+ format!("Enter the new signup verification code sent to {email}")
+ } else {
+ format!("Enter the signup verification code sent to {email}")
};
-
- read_six_digit_code_for_accounts(prompt)
- }
-
- fn report_retryable_error(&mut self, message: &str) -> ente_accounts::Result<()> {
- println!("\n{message}");
- Ok(())
- }
-
- fn choose_second_factor(
- &mut self,
- methods: &[SecondFactorMethod],
- ) -> ente_accounts::Result<SecondFactorMethod> {
- if let Some(choice) = self.second_factor {
- return Ok(choice);
+ let code = take_code(&mut otp, &prompt)?;
+ match client.verify_email(email, &code, source).await {
+ Ok(response) => break response,
+ Err(ente_accounts::Error::IncorrectEmailVerificationCode) => {
+ println!("\nIncorrect email verification code. Try again.");
+ resent = false;
+ }
+ Err(ente_accounts::Error::EmailVerificationCodeExpired) => {
+ client.send_otp(email, "signup").await?;
+ resent = true;
+ }
+ Err(error) => return Err(error.into()),
}
+ };
+ Ok(Signup::verified(email.into(), verification)?
+ .prepare(client, password)
+ .await?
+ .finish(client)
+ .await?)
+}
- 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| ente_accounts::Error::InvalidInput(e.to_string()))?;
-
- methods.get(index).copied().ok_or_else(|| {
- ente_accounts::Error::InvalidInput("Invalid second-factor selection".into())
- })
- }
-
- fn present_passkey_verification(&mut self, url: &str) -> ente_accounts::Result<()> {
- println!("\nPasskey verification required");
- println!("Open this URL in your browser to verify your passkey:\n{url}");
-
- if !self.passkey_presented
- && can_open_automatically(url)
- && let Err(error) = open::that(url)
- {
- log::error!("failed to open browser: {error}");
+async fn setup_two_factor(
+ client: &AccountsClient,
+ master_key: &[u8],
+ key_attributes: &ente_accounts::KeyAttributes,
+ mut code: Option<String>,
+) -> Result<TwoFactorSetup> {
+ let setup = TwoFactorSetup::start(client, master_key, key_attributes).await?;
+ println!("\nTOTP setup secret: {}", setup.secret_code);
+ println!("Add this secret to your authenticator app, then enter the current code.");
+ loop {
+ let code = take_code(
+ &mut code,
+ "Enter the current TOTP from your authenticator app",
+ )?;
+ match setup.enable(client, &code).await {
+ Ok(()) => return Ok(setup),
+ Err(ente_accounts::Error::IncorrectTotp) => println!(
+ "Incorrect TOTP code. Enter the current code from your authenticator app and try again."
+ ),
+ Err(error) => return Err(error.into()),
}
- self.passkey_presented = true;
-
- Ok(())
- }
-
- fn wait_for_passkey_verification(&mut self) -> ente_accounts::Result<()> {
- let _: String = Input::new()
- .with_prompt("Press Enter once you have completed passkey verification")
- .allow_empty(true)
- .interact_text()
- .map_err(|e| ente_accounts::Error::InvalidInput(e.to_string()))?;
- Ok(())
}
+}
- fn present_totp_secret(
- &mut self,
- secret_code: &str,
- _qr_code: &str,
- ) -> ente_accounts::Result<()> {
- println!("\nTOTP setup secret: {secret_code}");
- println!("Add this secret to your authenticator app, then enter the current code.");
- Ok(())
+fn take_code(code: &mut Option<String>, prompt: &str) -> Result<String> {
+ match code.take() {
+ Some(code) => Ok(code),
+ None => read_six_digit_code(prompt),
}
}
@@ -223,8 +270,6 @@ async fn add_account(storage: &Storage, args: AddArgs) -> Result<()> {
} = args;
let email = prompt_email(email)?;
- let interactive_password = password.is_none();
- let mut password = Zeroizing::new(prompt_password(password, "Enter your password")?);
let app = resolve_app(&app)?;
let second_factor = parse_second_factor(second_factor.as_deref())?;
@@ -237,26 +282,9 @@ async fn add_account(storage: &Storage, args: AddArgs) -> Result<()> {
ensure_export_dir(&export_dir)?;
let client = new_accounts_client(&endpoint, app)?;
- let mut ui = DialoguerAuthFlowUi::new(otp, totp_code, second_factor);
- let mut flow = AuthFlow::new(&client, &mut ui);
- let authenticated = loop {
- match flow
- .login(LoginParams {
- email: email.clone(),
- password: password.clone(),
- })
- .await
- {
- Ok(authenticated) => break authenticated,
- Err(ente_accounts::Error::IncorrectPassword) if interactive_password => {
- println!("\nIncorrect password. Try again.");
- password = Zeroizing::new(prompt_password(None, "Re-enter your password")?);
- }
- Err(error) => return Err(error.into()),
- }
- };
+ let authenticated = login(&client, &email, password, otp, totp_code, second_factor).await?;
- persist_account(storage, &email, app, &endpoint, &export_dir, authenticated)?;
+ persist_account(storage, &email, app, &endpoint, &export_dir, &authenticated)?;
println!("\nAccount added successfully!");
println!(" Email: {email}");
@@ -296,39 +324,9 @@ async fn create_account(storage: &Storage, args: CreateArgs) -> Result<()> {
ensure_export_dir(&export_dir)?;
let client = new_accounts_client(&endpoint, app)?;
- let mut ui = DialoguerAuthFlowUi::new(otp, totp_code, Some(SecondFactorMethod::Totp));
- let mut flow = AuthFlow::new(&client, &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 created = signup(&client, &email, &password, otp, source.as_deref()).await?;
- let two_factor_master_key = secrets.master_key.clone();
- let two_factor_key_attributes = key_attributes.clone();
-
- persist_account(
- storage,
- &email,
- app,
- &endpoint,
- &export_dir,
- AuthenticatedAccount {
- user_id,
- key_attributes,
- secrets,
- recovery_key: recovery_key.clone(),
- },
- )?;
+ persist_account(storage, &email, app, &endpoint, &export_dir, &created)?;
println!("\nAccount created successfully!");
println!(" Email: {email}");
@@ -337,7 +335,7 @@ async fn create_account(storage: &Storage, args: CreateArgs) -> Result<()> {
println!(" Export directory: {export_dir}");
if show_recovery_key {
- if let Some(recovery_key) = recovery_key.as_deref() {
+ if let Some(recovery_key) = created.recovery_key.as_deref() {
println!("\nRecovery key: {recovery_key}");
} else {
println!("\nRecovery key is not available for this account.");
@@ -345,12 +343,13 @@ async fn create_account(storage: &Storage, args: CreateArgs) -> Result<()> {
}
if setup_2fa {
- let result = flow
- .setup_two_factor(SetupTwoFactorParams {
- master_key: SecretVec::new(two_factor_master_key),
- key_attributes: Some(two_factor_key_attributes),
- })
- .await?;
+ let result = setup_two_factor(
+ &client,
+ &created.secrets.master_key,
+ &created.key_attributes,
+ totp_code,
+ )
+ .await?;
println!("\nTwo-factor authentication enabled.");
if show_recovery_key {
@@ -382,14 +381,12 @@ async fn enable_two_factor(
let token = b64::encode_url_safe(&secrets.token);
client.set_auth_token(Some(token));
- let mut ui = DialoguerAuthFlowUi::new(None, totp_code, Some(SecondFactorMethod::Totp));
- let mut flow = AuthFlow::new(&client, &mut ui);
- let result = flow
- .setup_two_factor(SetupTwoFactorParams {
- master_key: SecretVec::new(secrets.master_key.clone()),
- key_attributes: None,
- })
- .await?;
+ let key_attributes = client
+ .get_session_validity()
+ .await?
+ .key_attributes
+ .ok_or(ente_accounts::Error::MissingKeyAttributes)?;
+ let result = setup_two_factor(&client, &secrets.master_key, &key_attributes, totp_code).await?;
println!("\nTwo-factor authentication enabled for {email}.");
if show_recovery_key {
@@ -444,7 +441,7 @@ fn persist_account(
app: App,
endpoint: &str,
export_dir: &str,
- authenticated: AuthenticatedAccount,
+ authenticated: &AuthenticatedAccount,
) -> Result<()> {
let account = Account {
user_id: authenticated.user_id,
@@ -455,15 +452,9 @@ fn persist_account(
};
storage.accounts().add(&account)?;
- let stored_secrets = StoredAccountSecrets {
- token: authenticated.secrets.token.clone(),
- master_key: authenticated.secrets.master_key.clone(),
- secret_key: authenticated.secrets.secret_key.clone(),
- public_key: authenticated.secrets.public_key.clone(),
- };
storage
.accounts()
- .store_secrets(account.user_id, account.app, &stored_secrets)?;
+ .store_secrets(account.user_id, account.app, &authenticated.secrets)?;
Ok(())
}
@@ -556,11 +547,6 @@ fn read_six_digit_code(prompt: &str) -> Result<String> {
.map_err(|e| Error::InvalidInput(e.to_string()))
}
-fn read_six_digit_code_for_accounts(prompt: &str) -> ente_accounts::Result<String> {
- read_six_digit_code(prompt)
- .map_err(|error| ente_accounts::Error::InvalidInput(error.to_string()))
-}
-
#[cfg(test)]
mod tests {
use super::can_open_automatically;
diff --git a/rust/apps/cli/src/lib.rs b/rust/apps/cli/src/lib.rs
index 161733f46d..5688297689 100644
--- a/rust/apps/cli/src/lib.rs
+++ b/rust/apps/cli/src/lib.rs
@@ -1,5 +1,4 @@
pub mod api;
-pub mod auth_flow;
pub mod cli;
pub mod commands;
mod live_photo;
diff --git a/rust/apps/cli/src/models/account.rs b/rust/apps/cli/src/models/account.rs
index 8c705b46b3..e16d8cf0bc 100644
--- a/rust/apps/cli/src/models/account.rs
+++ b/rust/apps/cli/src/models/account.rs
@@ -1,6 +1,6 @@
+pub use ente_accounts::AccountSecrets;
use serde::{Deserialize, Serialize};
use std::{fmt, str::FromStr};
-use zeroize::ZeroizeOnDrop;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Account {
@@ -60,44 +60,3 @@ impl Account {
format!("{}:{}", self.email, self.app.client_package())
}
}
-
-#[derive(Serialize, Deserialize, ZeroizeOnDrop)]
-pub struct AccountSecrets {
- pub token: Vec<u8>,
- pub master_key: Vec<u8>,
- pub secret_key: Vec<u8>,
- pub public_key: Vec<u8>,
-}
-
-impl fmt::Debug for AccountSecrets {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("AccountSecrets")
- .field("token", &"[REDACTED]")
- .field("master_key", &"[REDACTED]")
- .field("secret_key", &"[REDACTED]")
- .field("public_key_len", &self.public_key.len())
- .finish()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_account_secrets_debug_redacts_secret_material() {
- let secrets = AccountSecrets {
- token: vec![1, 2, 3],
- master_key: vec![4, 5, 6],
- secret_key: vec![7, 8, 9],
- public_key: vec![10, 11, 12],
- };
-
- let debug = format!("{secrets:?}");
- assert!(debug.contains("[REDACTED]"));
- assert!(!debug.contains("[1, 2, 3]"));
- assert!(!debug.contains("[4, 5, 6]"));
- assert!(!debug.contains("[7, 8, 9]"));
- assert!(debug.contains("public_key_len"));
- }
-}
diff --git a/rust/apps/cli/tests/sync.rs b/rust/apps/cli/tests/sync.rs
index 06189c3112..ee643dd515 100644
--- a/rust/apps/cli/tests/sync.rs
+++ b/rust/apps/cli/tests/sync.rs
@@ -12,30 +12,32 @@ use support::{Museum, TestResult};
#[test]
fn sync() -> TestResult {
Museum::run(|museum| {
- let cli = support::cli_session(museum, "sync")?;
let export_dir = museum.temp_dir().join("export");
std::fs::create_dir_all(&export_dir)?;
- cli.run_ok(&[
- "account",
- "create",
- "--email",
- "--password",
- "sync-test-password",
- "--endpoint",
- museum.endpoint(),
- "--export-dir",
- export_dir.to_str().unwrap(),
- "--otp",
- HARDCODED_OTT,
- ])?;
+ for command in ["create", "add"] {
+ let cli = support::cli_session(museum, command)?;
+ cli.run_ok(&[
+ "account",
+ command,
+ "--email",
+ "--password",
+ "sync-test-password",
+ "--endpoint",
+ museum.endpoint(),
+ "--export-dir",
+ export_dir.to_str().unwrap(),
+ "--otp",
+ HARDCODED_OTT,
+ ])?;
- let output = cli.run_ok(&["export"])?;
- assert!(
- output.contains("Sync completed"),
- "export did not sync: {output}"
- );
+ let output = cli.run_ok(&["export"])?;
+ assert!(
+ output.contains("Sync completed"),
+ "export did not sync: {output}"
+ );
+ }
Ok(())
})
diff --git a/rust/checks/lint-exceptions/suppressions.json b/rust/checks/lint-exceptions/suppressions.json
index 3e7f8425cb..fd3b617f69 100644
--- a/rust/checks/lint-exceptions/suppressions.json
+++ b/rust/checks/lint-exceptions/suppressions.json
@@ -22,10 +22,7 @@
],
"rust/bindings/uniffi/ensu/src/assets.rs": ["clippy::expect_used"],
"rust/bindings/wasm/lib/src/logging.rs": ["clippy::expect_used"],
- "rust/crates/accounts/src/flow.rs": [
- "clippy::expect_used",
- "clippy::large_enum_variant"
- ],
+ "rust/crates/accounts/src/lifecycle.rs": ["clippy::large_enum_variant"],
"rust/crates/assets/src/download.rs": ["clippy::expect_used"],
"rust/crates/assets/src/store.rs": ["clippy::expect_used"],
"rust/crates/core/examples/ping.rs": ["clippy::expect_used"],
diff --git a/rust/crates/accounts/src/auth/types.rs b/rust/crates/accounts/src/auth/types.rs
index 029b7b608f..dc62bae29f 100644
--- a/rust/crates/accounts/src/auth/types.rs
+++ b/rust/crates/accounts/src/auth/types.rs
@@ -3,9 +3,14 @@ use std::fmt;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-use ente_core::crypto::{SecretString, SecretVec};
+use ente_core::{
+ b64,
+ crypto::{SecretString, SecretVec},
+};
-#[derive(Clone, Serialize, Deserialize)]
+use crate::{Error, Result};
+
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyAttributes {
pub kek_salt: String,
@@ -120,6 +125,40 @@ pub struct SrpAttributes {
pub is_email_mfa_enabled: bool,
}
+impl SrpAttributes {
+ pub(crate) fn validate_setup(
+ &self,
+ srp_user_id: Uuid,
+ srp_salt: &[u8],
+ keys: &KeyAttributes,
+ operation: &str,
+ ) -> Result<()> {
+ let mut mismatches = Vec::new();
+ if self.srp_user_id != srp_user_id {
+ mismatches.push("srpUserID");
+ }
+ if self.srp_salt != b64::encode(srp_salt) {
+ mismatches.push("srpSalt");
+ }
+ if self.kek_salt != keys.kek_salt {
+ mismatches.push("kekSalt");
+ }
+ if self.mem_limit != keys.mem_limit {
+ mismatches.push("memLimit");
+ }
+ if self.ops_limit != keys.ops_limit {
+ mismatches.push("opsLimit");
+ }
+ if !mismatches.is_empty() {
+ return Err(Error::Protocol(format!(
+ "Remote SRP attributes mismatched after {operation}: {}",
+ mismatches.join(", ")
+ )));
+ }
+ Ok(())
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rs
index 2b31f37571..653d5202b5 100644
--- a/rust/crates/accounts/src/client.rs
+++ b/rust/crates/accounts/src/client.rs
@@ -20,18 +20,6 @@ use crate::{
types::AccountsClientConfig,
};
-const SRP_A_LEN: usize = 512;
-
-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 require_srp_m2(auth_response: &AuthResponse) -> Result<&str> {
auth_response
.srp_m2
@@ -119,7 +107,7 @@ impl AccountsClient {
&srp_salt,
&creds.login_key,
)?;
- let a_pub = pad_left(&srp_session.public_a(), SRP_A_LEN);
+ let a_pub = srp_session.public_a();
let session = self
.create_srp_session(&srp_attrs.srp_user_id, &a_pub)
diff --git a/rust/crates/accounts/src/error.rs b/rust/crates/accounts/src/error.rs
index 3186b8f277..2515cd7931 100644
--- a/rust/crates/accounts/src/error.rs
+++ b/rust/crates/accounts/src/error.rs
@@ -72,9 +72,6 @@ pub enum Error {
#[error("{0}")]
Protocol(String),
-
- #[error(transparent)]
- Ui(Box<dyn std::error::Error + Send + Sync>),
}
impl From<b64::DecodeError> for Error {
diff --git a/rust/crates/accounts/src/flow.rs b/rust/crates/accounts/src/flow.rs
deleted file mode 100644
index 4e75fc0ad2..0000000000
--- a/rust/crates/accounts/src/flow.rs
+++ /dev/null
@@ -1,2026 +0,0 @@
-use ente_core::b64;
-use ente_core::crypto::{self, SecretVec, secretbox};
-use std::fmt;
-use uuid::Uuid;
-use zeroize::Zeroizing;
-
-use crate::{
- auth::{
- self, DecryptedSecrets, GeneratedSrpSetup, KeyDerivationStrength, derive_kek,
- generate_keys_with_strength, generate_srp_setup_with_login_key, get_recovery_key,
- },
- client::AccountsClient,
- error::{Error, Result},
- models::{
- AuthResponse, ConfigurePasskeyRecoveryRequest, EnableTwoFactorRequest, KeyAttributes,
- RemoveTwoFactorRequest, SetRecoveryKeyRequest, SetupSrpRequest, SrpAttributes,
- TwoFactorAuthorizationResponse, TwoFactorRecoveryResponse, TwoFactorType,
- UpdateSrpAndKeysRequest, UpdatedKeyAttr,
- },
- types::AccountSecrets,
-};
-
-const SRP_A_LEN: usize = 512;
-
-#[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<()>;
-}
-
-pub struct CreateAccountParams {
- pub email: String,
- pub password: Zeroizing<String>,
- pub source: Option<String>,
-}
-
-impl fmt::Debug for CreateAccountParams {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("CreateAccountParams")
- .field("email", &self.email)
- .field("password", &"[REDACTED]")
- .field("source", &self.source)
- .finish()
- }
-}
-
-pub struct LoginParams {
- pub email: String,
- pub password: Zeroizing<String>,
-}
-
-impl fmt::Debug for LoginParams {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("LoginParams")
- .field("email", &self.email)
- .field("password", &"[REDACTED]")
- .finish()
- }
-}
-
-pub struct SetupTwoFactorParams {
- pub master_key: SecretVec,
- pub key_attributes: Option<KeyAttributes>,
-}
-
-impl fmt::Debug for SetupTwoFactorParams {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("SetupTwoFactorParams")
- .field("master_key", &"[REDACTED]")
- .field("key_attributes", &self.key_attributes)
- .finish()
- }
-}
-
-pub struct ChangePasswordParams {
- pub email: String,
- pub password: Zeroizing<String>,
- pub master_key: SecretVec,
- pub key_attributes: KeyAttributes,
- pub log_out_other_devices: bool,
-}
-
-impl fmt::Debug for ChangePasswordParams {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("ChangePasswordParams")
- .field("email", &self.email)
- .field("password", &"[REDACTED]")
- .field("master_key", &"[REDACTED]")
- .field("key_attributes", &self.key_attributes)
- .field("log_out_other_devices", &self.log_out_other_devices)
- .finish()
- }
-}
-
-pub struct ChangePasswordResult {
- pub key_attributes: KeyAttributes,
- pub srp_attributes: SrpAttributes,
-}
-
-impl fmt::Debug for ChangePasswordResult {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("ChangePasswordResult")
- .field("key_attributes", &self.key_attributes)
- .field("srp_attributes", &self.srp_attributes)
- .finish()
- }
-}
-
-pub struct CheckSessionValidityParams {
- pub email: String,
- pub local_srp_attributes: SrpAttributes,
-}
-
-impl fmt::Debug for CheckSessionValidityParams {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("CheckSessionValidityParams")
- .field("email", &self.email)
- .field("local_srp_attributes", &self.local_srp_attributes)
- .finish()
- }
-}
-
-#[derive(Debug)]
-#[cfg_attr(
- target_pointer_width = "64",
- expect(
- clippy::large_enum_variant,
- reason = "A single session-check result does not need a separate allocation"
- )
-)]
-pub enum SessionValidity {
- Invalid,
- Valid,
- ValidButPasswordChanged {
- updated_key_attributes: KeyAttributes,
- updated_srp_attributes: SrpAttributes,
- },
-}
-
-pub struct AuthenticatedAccount {
- pub user_id: i64,
- pub key_attributes: KeyAttributes,
- pub secrets: AccountSecrets,
- pub recovery_key: Option<String>,
-}
-
-impl fmt::Debug for AuthenticatedAccount {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("AuthenticatedAccount")
- .field("user_id", &self.user_id)
- .field("key_attributes", &self.key_attributes)
- .field("secrets", &self.secrets)
- .field("recovery_key", &"[REDACTED]")
- .finish()
- }
-}
-
-pub struct SetupTwoFactorResult {
- pub secret_code: String,
- pub qr_code: String,
- pub recovery_key: String,
-}
-
-impl fmt::Debug for SetupTwoFactorResult {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("SetupTwoFactorResult")
- .field("secret_code", &"[REDACTED]")
- .field("qr_code", &"[REDACTED]")
- .field("recovery_key", &"[REDACTED]")
- .finish()
- }
-}
-
-pub struct RecoveryKeyResult {
- pub recovery_key: String,
- pub key_attributes: KeyAttributes,
-}
-
-impl fmt::Debug for RecoveryKeyResult {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("RecoveryKeyResult")
- .field("recovery_key", &"[REDACTED]")
- .field("key_attributes", &self.key_attributes)
- .finish()
- }
-}
-
-pub struct AuthFlow<'a, U> {
- client: &'a AccountsClient,
- ui: &'a mut U,
-}
-
-impl<'a, U> AuthFlow<'a, U>
-where
- U: AuthFlowUi,
-{
- pub fn new(client: &'a AccountsClient, ui: &'a mut U) -> Self {
- Self { client, ui }
- }
-
- pub async fn create_account(
- &mut self,
- params: CreateAccountParams,
- ) -> Result<AuthenticatedAccount> {
- self.create_account_with_strength(params, KeyDerivationStrength::Sensitive)
- .await
- }
-
- pub async fn create_account_with_otp(
- &mut self,
- params: CreateAccountParams,
- otp: &str,
- ) -> Result<AuthenticatedAccount> {
- let email = params.email;
- let password = params.password;
- let verification = self
- .client
- .verify_email(&email, otp, params.source.as_deref())
- .await?;
-
- self.finish_verified_signup(
- email,
- password,
- verification,
- KeyDerivationStrength::Sensitive,
- )
- .await
- }
-
- pub async fn login(&mut self, params: LoginParams) -> Result<AuthenticatedAccount> {
- let srp_attrs = self.client.get_srp_attributes(&params.email).await?;
-
- let (auth_response, kek) = if srp_attrs.is_email_mfa_enabled {
- self.client
- .send_otp(&params.email, OtpPurpose::Login.as_api_purpose())
- .await?;
- let response = self
- .verify_email_otp(&params.email, OtpPurpose::Login, None)
- .await?;
- let response = self.resolve_second_factor(response).await?;
- let kek = derive_kek(
- &params.password,
- &srp_attrs.kek_salt,
- srp_attrs.mem_limit,
- srp_attrs.ops_limit,
- )?;
- (response, kek)
- } else {
- let (response, kek) = self
- .client
- .login_with_srp(&params.password, &srp_attrs)
- .await?;
- let response = self.resolve_second_factor(response).await?;
- (response, kek)
- };
-
- self.build_authenticated_account(auth_response, &kek)
- }
-
- pub async fn setup_two_factor(
- &mut self,
- params: SetupTwoFactorParams,
- ) -> Result<SetupTwoFactorResult> {
- let key_attributes = if let Some(key_attributes) = params.key_attributes {
- key_attributes
- } else {
- self.client
- .get_session_validity()
- .await?
- .key_attributes
- .ok_or(Error::MissingKeyAttributes)?
- };
-
- let master_key = crypto::Key::try_from_slice(&params.master_key)?;
- let recovery_key = get_recovery_key(&master_key, &key_attributes)?;
-
- let secret = self.client.setup_two_factor().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 self.client.enable_two_factor(&request).await {
- Ok(()) => {
- return Ok(SetupTwoFactorResult {
- secret_code: secret.secret_code,
- qr_code: secret.qr_code,
- recovery_key,
- });
- }
- Err(Error::IncorrectTotp) => {
- self.ui.report_retryable_error(
- "Incorrect TOTP code. Enter the current code from your authenticator app and try again.",
- )?;
- }
- Err(error) => return Err(error),
- }
- }
- }
-
- pub async fn change_password(
- &self,
- params: ChangePasswordParams,
- ) -> Result<ChangePasswordResult> {
- self.change_password_with_strength(params, KeyDerivationStrength::Sensitive)
- .await
- }
-
- async fn change_password_with_strength(
- &self,
- params: ChangePasswordParams,
- key_derivation_strength: KeyDerivationStrength,
- ) -> Result<ChangePasswordResult> {
- let (updated_key_attributes, login_key) =
- auth::generate_key_attributes_for_new_password_with_strength(
- &params.master_key,
- &params.key_attributes,
- &params.password,
- key_derivation_strength,
- )?;
-
- let updated_key_attr = UpdatedKeyAttr::from(&updated_key_attributes);
-
- let srp_user_id = Uuid::new_v4();
- let srp_setup = generate_srp_setup_with_login_key(&login_key, &srp_user_id.to_string())?;
- self.complete_srp_update(
- &srp_user_id,
- &srp_setup,
- &updated_key_attr,
- params.log_out_other_devices,
- )
- .await?;
-
- let srp_attributes = self.client.get_srp_attributes(&params.email).await?;
-
- let expected_salt = b64::encode(&srp_setup.srp_salt);
- let mut mismatches = Vec::new();
- if srp_attributes.srp_user_id != srp_user_id {
- mismatches.push("srpUserID");
- }
- if srp_attributes.srp_salt != expected_salt {
- mismatches.push("srpSalt");
- }
- if srp_attributes.kek_salt != updated_key_attributes.kek_salt {
- mismatches.push("kekSalt");
- }
- if srp_attributes.mem_limit != updated_key_attributes.mem_limit {
- mismatches.push("memLimit");
- }
- if srp_attributes.ops_limit != updated_key_attributes.ops_limit {
- mismatches.push("opsLimit");
- }
- if !mismatches.is_empty() {
- return Err(Error::Protocol(format!(
- "Remote SRP attributes mismatched after password change: {}",
- mismatches.join(", ")
- )));
- }
-
- Ok(ChangePasswordResult {
- key_attributes: updated_key_attributes,
- srp_attributes,
- })
- }
-
- pub async fn check_session_validity(
- &self,
- params: CheckSessionValidityParams,
- ) -> Result<SessionValidity> {
- let remote = match self.client.get_session_validity().await {
- Ok(remote) => remote,
- Err(Error::SessionInvalid) => return Ok(SessionValidity::Invalid),
- Err(error) => return Err(error),
- };
-
- if let Some(remote_key_attributes) = remote.key_attributes {
- let remote_srp_attributes = self.client.get_srp_attributes(&params.email).await?;
- if remote_srp_attributes.kek_salt != params.local_srp_attributes.kek_salt {
- return Ok(SessionValidity::ValidButPasswordChanged {
- updated_key_attributes: remote_key_attributes,
- updated_srp_attributes: remote_srp_attributes,
- });
- }
- }
-
- Ok(SessionValidity::Valid)
- }
-
- pub async fn change_email(&self, email: &str, ott: &str) -> Result<()> {
- self.client.change_email(email, ott).await
- }
-
- pub async fn create_recovery_key(
- &self,
- master_key: &[u8],
- existing_attributes: &KeyAttributes,
- ) -> Result<RecoveryKeyResult> {
- let (
- recovery_key,
- master_key_encrypted_with_recovery_key,
- master_key_decryption_nonce,
- recovery_key_encrypted_with_master_key,
- recovery_key_decryption_nonce,
- ) = auth::create_new_recovery_key(master_key)?;
-
- let request = SetRecoveryKeyRequest {
- master_key_encrypted_with_recovery_key: master_key_encrypted_with_recovery_key.clone(),
- master_key_decryption_nonce: master_key_decryption_nonce.clone(),
- recovery_key_encrypted_with_master_key: recovery_key_encrypted_with_master_key.clone(),
- recovery_key_decryption_nonce: recovery_key_decryption_nonce.clone(),
- };
- self.client.set_recovery_key_attributes(request).await?;
-
- let key_attributes = KeyAttributes {
- master_key_encrypted_with_recovery_key: Some(master_key_encrypted_with_recovery_key),
- master_key_decryption_nonce: Some(master_key_decryption_nonce),
- recovery_key_encrypted_with_master_key: Some(recovery_key_encrypted_with_master_key),
- recovery_key_decryption_nonce: Some(recovery_key_decryption_nonce),
- ..existing_attributes.clone()
- };
-
- Ok(RecoveryKeyResult {
- recovery_key,
- key_attributes,
- })
- }
-
- pub async fn get_two_factor_recovery(
- &self,
- session_id: &str,
- two_factor_type: TwoFactorType,
- ) -> Result<TwoFactorRecoveryResponse> {
- self.client
- .get_two_factor_recovery(session_id, two_factor_type)
- .await
- }
-
- pub async fn recover_two_factor(
- &self,
- two_factor_type: TwoFactorType,
- session_id: &str,
- recovery_response: &TwoFactorRecoveryResponse,
- recovery_key_mnemonic_or_hex: &str,
- ) -> Result<TwoFactorAuthorizationResponse> {
- let recovery_key = auth::recovery_key_from_mnemonic_or_hex(recovery_key_mnemonic_or_hex)?;
- let encrypted_secret = b64::decode(&recovery_response.encrypted_secret)?;
- let nonce = b64::decode(&recovery_response.secret_decryption_nonce)?;
- let secret = secretbox::decrypt(
- &encrypted_secret,
- &crypto::Nonce::try_from_slice(&nonce)?,
- &crypto::Key::try_from_slice(&recovery_key)?,
- )
- .map_err(|_| Error::IncorrectRecoveryKey)?;
- let request = RemoveTwoFactorRequest {
- session_id: session_id.to_string(),
- secret: String::from_utf8(secret)
- .map_err(|e| Error::Protocol(format!("invalid recovery secret: {e}")))?,
- two_factor_type,
- };
- self.client.remove_two_factor(&request).await
- }
-
- pub async fn get_two_factor_status(&self) -> Result<bool> {
- self.client.get_two_factor_status().await
- }
-
- pub async fn disable_two_factor(&self) -> Result<()> {
- self.client.disable_two_factor().await
- }
-
- pub async fn get_passkey_recovery_status(&self) -> Result<bool> {
- Ok(self
- .client
- .get_two_factor_recovery_status()
- .await?
- .is_passkey_recovery_enabled)
- }
-
- pub async fn configure_passkey_recovery(
- &self,
- secret: &str,
- recovery_key_mnemonic_or_hex: &str,
- ) -> Result<()> {
- let recovery_key = auth::recovery_key_from_mnemonic_or_hex(recovery_key_mnemonic_or_hex)?;
- let encrypted = secretbox::encrypt(
- secret.as_bytes(),
- &crypto::Key::try_from_slice(&recovery_key)?,
- );
- let request = ConfigurePasskeyRecoveryRequest {
- secret: secret.to_string(),
- user_secret_cipher: b64::encode(&encrypted.encrypted_data),
- user_secret_nonce: b64::encode(encrypted.nonce.as_bytes()),
- };
- self.client.configure_passkey_recovery(&request).await
- }
-
- pub async fn get_accounts_token(&self) -> Result<crate::models::AccountsTokenResponse> {
- self.client.get_accounts_token().await
- }
-
- pub async fn check_passkey_status(&self, session_id: &str) -> Result<Option<AuthResponse>> {
- self.client.check_passkey_status(session_id).await
- }
-
- fn build_authenticated_account(
- &self,
- auth_response: AuthResponse,
- kek: &[u8],
- ) -> Result<AuthenticatedAccount> {
- let key_attributes = auth_response
- .key_attributes
- .clone()
- .ok_or(Error::MissingKeyAttributes)?;
- let secrets = decrypt_auth_response(&auth_response, &key_attributes, kek)?;
- let public_key = b64::decode(&key_attributes.public_key)?;
- let recovery_key = get_recovery_key(&secrets.master_key, &key_attributes).ok();
-
- Ok(AuthenticatedAccount {
- user_id: auth_response.id,
- key_attributes,
- secrets: AccountSecrets {
- token: secrets.token.into_vec(),
- master_key: secrets.master_key.as_bytes().to_vec(),
- secret_key: secrets.secret_key.as_bytes().to_vec(),
- public_key,
- },
- recovery_key,
- })
- }
-
- async fn create_account_with_strength(
- &mut self,
- params: CreateAccountParams,
- key_derivation_strength: KeyDerivationStrength,
- ) -> Result<AuthenticatedAccount> {
- let email = params.email;
- let password = params.password;
-
- self.client
- .send_otp(&email, OtpPurpose::Signup.as_api_purpose())
- .await?;
-
- let verification = self
- .verify_email_otp(&email, OtpPurpose::Signup, params.source.as_deref())
- .await?;
-
- self.finish_verified_signup(email, password, verification, key_derivation_strength)
- .await
- }
-
- async fn finish_verified_signup(
- &self,
- email: String,
- password: Zeroizing<String>,
- verification: AuthResponse,
- key_derivation_strength: KeyDerivationStrength,
- ) -> Result<AuthenticatedAccount> {
- let token = verification.token.clone().ok_or_else(|| {
- Error::Protocol("Signup verification did not return a session token".into())
- })?;
-
- self.client.set_auth_token(Some(token.clone()));
- let session_validity = self.client.get_session_validity().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::AccountAlreadyExists);
- }
-
- 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_with_login_key(&key_gen_result.login_key, &srp_user_id.to_string())?;
- let key_attributes = key_gen_result.key_attributes.clone();
-
- self.client
- .set_user_key_attributes(key_attributes.clone())
- .await?;
- self.complete_signup_srp(&srp_user_id, &srp_setup).await?;
-
- let remote_srp_attributes = self.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)?.into_vec(),
- master_key: b64::decode(&key_gen_result.private_key_attributes.key)?,
- secret_key: b64::decode(&key_gen_result.private_key_attributes.secret_key)?,
- public_key: b64::decode(&key_attributes.public_key)?,
- };
-
- Ok(AuthenticatedAccount {
- user_id: verification.id,
- key_attributes,
- secrets,
- recovery_key: Some(
- key_gen_result
- .private_key_attributes
- .recovery_key
- .into_string(),
- ),
- })
- }
-
- async fn verify_email_otp(
- &mut self,
- 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 self.client.verify_email(email, &otp, source).await {
- Ok(response) => return Ok(response),
- Err(Error::IncorrectEmailVerificationCode) => {
- self.ui
- .report_retryable_error("Incorrect email verification code. Try again.")?;
- resent = false;
- }
- Err(Error::EmailVerificationCodeExpired) => {
- self.client
- .send_otp(email, purpose.as_api_purpose())
- .await?;
- resent = true;
- }
- Err(error) => return Err(error),
- }
- }
- }
-
- async fn resolve_second_factor(&mut self, 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_response).await,
- SecondFactorMethod::Passkey => self.verify_passkey(&auth_response).await,
- }
- }
-
- async fn verify_totp(&mut self, auth_response: &AuthResponse) -> Result<AuthResponse> {
- let session_id = auth_response
- .get_two_factor_session_id()
- .ok_or_else(|| Error::Protocol("No 2FA session ID".into()))?;
-
- loop {
- let code = self.ui.read_totp_code(TotpPurpose::Login)?;
- match self.client.verify_totp(session_id, &code).await {
- Ok(response) => return Ok(response),
- Err(Error::IncorrectTotp) => {
- self.ui
- .report_retryable_error("Incorrect TOTP code. Try again.")?;
- }
- Err(error) => return Err(error),
- }
- }
- }
-
- async fn verify_passkey(&mut self, 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::Protocol("No passkey session ID".into()))?;
-
- #[expect(
- clippy::expect_used,
- reason = "AuthResponse validation requires accountsUrl for passkey sessions"
- )]
- let accounts_url = auth_response
- .accounts_url
- .as_deref()
- .expect("accountsUrl is required when passkeySessionID is present");
-
- let verification_url = build_passkey_verification_url(
- accounts_url,
- passkey_session_id,
- self.client.client_package(),
- "ente-cli://passkey",
- None,
- );
-
- self.ui.present_passkey_verification(&verification_url)?;
-
- loop {
- self.ui.wait_for_passkey_verification()?;
- if let Some(response) = self.client.check_passkey_status(passkey_session_id).await? {
- return Ok(response);
- }
- }
- }
-
- async fn complete_signup_srp(
- &self,
- 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 = b64::encode(&pad_left(&srp_session.public_a(), SRP_A_LEN));
-
- let response = self
- .client
- .setup_srp(&SetupSrpRequest {
- srp_user_id: srp_user_id.to_string(),
- srp_salt: b64::encode(&srp_setup.srp_salt),
- srp_verifier: b64::encode(&srp_setup.srp_verifier),
- srp_a,
- })
- .await?;
-
- let srp_b = b64::decode(&response.srp_b)?;
- let srp_m1 = b64::encode(&srp_session.compute_m1(&srp_b)?);
- let complete = self
- .client
- .complete_srp_setup(&response.setup_id, &srp_m1)
- .await?;
- let srp_m2 = b64::decode(&complete.srp_m2)?;
- srp_session.verify_m2(&srp_m2)?;
- Ok(())
- }
-
- async fn complete_srp_update(
- &self,
- srp_user_id: &Uuid,
- srp_setup: &GeneratedSrpSetup,
- updated_key_attr: &UpdatedKeyAttr,
- log_out_other_devices: bool,
- ) -> Result<crate::models::UpdateSrpAndKeysResponse> {
- let mut srp_session = auth::SrpSession::new(
- &srp_user_id.to_string(),
- &srp_setup.srp_salt,
- &srp_setup.login_sub_key,
- )?;
- let srp_a = b64::encode(&pad_left(&srp_session.public_a(), SRP_A_LEN));
-
- let setup = self
- .client
- .setup_srp(&SetupSrpRequest {
- srp_user_id: srp_user_id.to_string(),
- srp_salt: b64::encode(&srp_setup.srp_salt),
- srp_verifier: b64::encode(&srp_setup.srp_verifier),
- srp_a,
- })
- .await?;
-
- let srp_b = b64::decode(&setup.srp_b)?;
- let srp_m1 = b64::encode(&srp_session.compute_m1(&srp_b)?);
-
- let response = self
- .client
- .update_srp_and_key_attributes(&UpdateSrpAndKeysRequest {
- setup_id: setup.setup_id.to_string(),
- srp_m1,
- updated_key_attr: updated_key_attr.clone(),
- log_out_other_devices,
- })
- .await?;
-
- let srp_m2 = b64::decode(&response.srp_m2)?;
- srp_session.verify_m2(&srp_m2)?;
- Ok(response)
- }
-}
-
-pub fn build_passkey_verification_url(
- accounts_url: &str,
- passkey_session_id: &str,
- client_package: &str,
- redirect: &str,
- recover: Option<&str>,
-) -> String {
- let mut params = vec![
- ("clientPackage", client_package),
- ("passkeySessionID", passkey_session_id),
- ("redirect", redirect),
- ];
- if let Some(recover) = recover {
- params.push(("recover", recover));
- }
-
- let query = params
- .into_iter()
- .map(|(key, value)| format!("{key}={}", urlencoding::encode(value)))
- .collect::<Vec<_>>()
- .join("&");
-
- format!("{accounts_url}/passkeys/verify?{query}")
-}
-
-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 decode_plain_token(token: &str) -> Result<SecretVec> {
- let bytes = b64::decode_url_safe(token)
- .or_else(|_| b64::decode(token))
- .map_err(|e| Error::Decode(format!("token: {e}")))?;
- Ok(SecretVec::new(bytes))
-}
-
-fn decrypt_auth_response(
- auth_response: &AuthResponse,
- key_attributes: &KeyAttributes,
- kek: &[u8],
-) -> Result<DecryptedSecrets> {
- if let Some(encrypted_token) = auth_response.encrypted_token.as_deref() {
- auth::decrypt_secrets(kek, key_attributes, encrypted_token)
- } 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::Protocol("No token in response".into()))
- }
-}
-
-fn validate_remote_srp_attributes(
- remote: &SrpAttributes,
- srp_user_id: &Uuid,
- srp_setup: &GeneratedSrpSetup,
- key_attributes: &KeyAttributes,
-) -> Result<()> {
- let expected_salt = b64::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::Protocol(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 =
- hex::decode(recovery_key_hex).map_err(|e| Error::Decode(format!("recovery_key: {e}")))?;
- let encrypted = secretbox::encrypt(
- secret_code.as_bytes(),
- &crypto::Key::try_from_slice(&recovery_key)?,
- );
-
- Ok(EnableTwoFactorRequest {
- code: code.to_string(),
- encrypted_two_factor_secret: b64::encode(&encrypted.encrypted_data),
- two_factor_secret_decryption_nonce: b64::encode(encrypted.nonce.as_bytes()),
- })
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use mockito::{Matcher, Server};
- use serde::{Deserialize, de::DeserializeOwned};
- use sha2::{Digest, Sha256};
- use srp::ServerG4096;
- use std::{
- collections::VecDeque,
- sync::{Arc, Mutex},
- };
-
- use crate::types::AccountsClientConfig;
-
- #[derive(Default)]
- struct MockSignupState {
- uploaded_key_attributes: Option<KeyAttributes>,
- remote_srp_attributes: Option<SrpAttributes>,
- 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,
- }
-
- #[derive(Debug, Deserialize)]
- #[serde(rename_all = "camelCase")]
- struct UpdateSrpPayload {
- setup_id: String,
- srp_m1: String,
- updated_key_attr: UpdatedKeyAttr,
- log_out_other_devices: bool,
- }
-
- #[derive(Debug, Deserialize)]
- #[serde(rename_all = "camelCase")]
- struct ConfigurePasskeyRecoveryPayload {
- secret: String,
- user_secret_cipher: String,
- user_secret_nonce: 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 make_client(origin: String) -> AccountsClient {
- AccountsClient::new(
- AccountsClientConfig::new("io.ente.photos")
- .with_origin(origin)
- .with_user_agent("ente-accounts-test"),
- )
- .unwrap()
- }
-
- 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 = key_gen.key_attributes.clone();
- let encrypted_token = {
- let public_key = b64::decode(&key_attributes.public_key).unwrap();
- let sealed = crypto::sealed::seal(
- token.as_bytes(),
- &crypto::PublicKey::try_from_slice(&public_key).unwrap(),
- )
- .unwrap();
- b64::encode(&sealed)
- };
-
- (
- key_attributes,
- encrypted_token,
- key_gen.private_key_attributes.recovery_key.into_string(),
- key_gen.private_key_attributes.key.into_string(),
- key_gen.private_key_attributes.secret_key.into_string(),
- )
- }
-
- #[tokio::test]
- async fn login_with_email_mfa_and_totp_decrypts_account() {
- 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)
- .match_request(|request| {
- request.path() == "/users/srp/attributes"
- && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"
- })
- .with_status(200)
- .with_body(
- serde_json::json!({
- "attributes": {
- "srpUserID": Uuid::new_v4(),
- "srpSalt": b64::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 client = make_client(server.url());
- let mut flow = AuthFlow::new(&client, &mut ui);
-
- let result = flow
- .login(LoginParams {
- email: "[email protected]".into(),
- password: Zeroizing::new(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_email_mfa_treats_429_as_terminal_error() {
- let password = "hunter2";
- let key_gen =
- auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
- .unwrap();
- let key_attributes = key_gen.key_attributes.clone();
-
- let mut server = Server::new_async().await;
- let mut ui = ScriptedUi::new();
- ui.email_otps.push_back("123456".into());
-
- let srp_attrs = server
- .mock("GET", Matcher::Any)
- .match_request(|request| {
- request.path() == "/users/srp/attributes"
- && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"
- })
- .with_status(200)
- .with_body(
- serde_json::json!({
- "attributes": {
- "srpUserID": Uuid::new_v4(),
- "srpSalt": b64::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(429)
- .with_body("too many attempts")
- .create_async()
- .await;
-
- let client = make_client(server.url());
- let mut flow = AuthFlow::new(&client, &mut ui);
-
- let error = flow
- .login(LoginParams {
- email: "[email protected]".into(),
- password: Zeroizing::new(password.into()),
- })
- .await
- .unwrap_err();
-
- match error {
- Error::EmailVerificationRateLimited => {}
- other => panic!("unexpected error: {other:?}"),
- }
- assert!(ui.retryable_errors.is_empty());
-
- srp_attrs.assert_async().await;
- ott.assert_async().await;
- verify_email.assert_async().await;
- }
-
- #[tokio::test]
- async fn login_with_totp_treats_404_as_expired_session() {
- let password = "hunter2";
- let key_gen =
- auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
- .unwrap();
- let key_attributes = key_gen.key_attributes.clone();
-
- 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)
- .match_request(|request| {
- request.path() == "/users/srp/attributes"
- && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"
- })
- .with_status(200)
- .with_body(
- serde_json::json!({
- "attributes": {
- "srpUserID": Uuid::new_v4(),
- "srpSalt": b64::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(404)
- .with_body("missing session")
- .create_async()
- .await;
-
- let client = make_client(server.url());
- let mut flow = AuthFlow::new(&client, &mut ui);
-
- let error = flow
- .login(LoginParams {
- email: "[email protected]".into(),
- password: Zeroizing::new(password.into()),
- })
- .await
- .unwrap_err();
-
- match error {
- Error::SecondFactorSessionExpired => {}
- other => panic!("unexpected error: {other:?}"),
- }
-
- 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_treats_429_as_terminal_error() {
- let password = "hunter2";
- let key_gen =
- auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
- .unwrap();
- let key_attributes = key_gen.key_attributes.clone();
-
- 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)
- .match_request(|request| {
- request.path() == "/users/srp/attributes"
- && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"
- })
- .with_status(200)
- .with_body(
- serde_json::json!({
- "attributes": {
- "srpUserID": Uuid::new_v4(),
- "srpSalt": b64::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(429)
- .with_body("too many attempts")
- .create_async()
- .await;
-
- let client = make_client(server.url());
- let mut flow = AuthFlow::new(&client, &mut ui);
-
- let error = flow
- .login(LoginParams {
- email: "[email protected]".into(),
- password: Zeroizing::new(password.into()),
- })
- .await
- .unwrap_err();
-
- match error {
- Error::TotpRateLimited => {}
- other => panic!("unexpected error: {other:?}"),
- }
- assert!(ui.retryable_errors.is_empty());
-
- srp_attrs.assert_async().await;
- ott.assert_async().await;
- verify_email.assert_async().await;
- verify_totp.assert_async().await;
- }
-
- #[tokio::test]
- async fn setup_two_factor_encrypts_secret_with_recovery_key() {
- 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.into_string();
- let master_key = b64::decode(&key_gen.private_key_attributes.key).unwrap();
- let key_attributes = key_gen.key_attributes.clone();
-
- 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 client = make_client(server.url());
- client.set_auth_token(Some("session-token".into()));
- let mut flow = AuthFlow::new(&client, &mut ui);
-
- let result = flow
- .setup_two_factor(SetupTwoFactorParams {
- master_key: SecretVec::new(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 configure_passkey_recovery_accepts_hex_recovery_key() {
- let key_gen =
- auth::generate_keys_with_strength("pw", auth::KeyDerivationStrength::Interactive)
- .unwrap();
- let recovery_key_hex = key_gen.private_key_attributes.recovery_key.into_string();
- let expected_recovery_key = hex::decode(&recovery_key_hex).unwrap();
-
- let mut server = Server::new_async().await;
- let configure = server
- .mock("POST", "/users/two-factor/passkeys/configure-recovery")
- .match_header("x-auth-token", "session-token")
- .match_header("x-client-package", "io.ente.photos")
- .with_status(200)
- .with_body_from_request(move |request| {
- let payload: ConfigurePasskeyRecoveryPayload = parse_request_body(request);
- let cipher = b64::decode(&payload.user_secret_cipher).unwrap();
- let nonce = b64::decode(&payload.user_secret_nonce).unwrap();
- let decrypted = secretbox::decrypt(
- &cipher,
- &crypto::Nonce::try_from_slice(&nonce).unwrap(),
- &crypto::Key::try_from_slice(&expected_recovery_key).unwrap(),
- )
- .unwrap();
- assert_eq!(payload.secret, "reset-secret");
- assert_eq!(String::from_utf8(decrypted).unwrap(), "reset-secret");
- Vec::new()
- })
- .create_async()
- .await;
-
- let client = make_client(server.url());
- client.set_auth_token(Some("session-token".into()));
- let mut ui = ScriptedUi::new();
- let flow = AuthFlow::new(&client, &mut ui);
-
- flow.configure_passkey_recovery("reset-secret", &recovery_key_hex)
- .await
- .unwrap();
-
- configure.assert_async().await;
- }
-
- #[tokio::test]
- async fn login_with_passkey_treats_404_as_expired_session() {
- let password = "hunter2";
- let key_gen =
- auth::generate_keys_with_strength(password, auth::KeyDerivationStrength::Interactive)
- .unwrap();
- let key_attributes = key_gen.key_attributes.clone();
-
- let mut server = Server::new_async().await;
- let mut ui = ScriptedUi::new();
- ui.email_otps.push_back("123456".into());
-
- let srp_attrs = server
- .mock("GET", Matcher::Any)
- .match_request(|request| {
- request.path() == "/users/srp/attributes"
- && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"
- })
- .with_status(200)
- .with_body(
- serde_json::json!({
- "attributes": {
- "srpUserID": Uuid::new_v4(),
- "srpSalt": b64::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,
- "passkeySessionID": "passkey-session",
- "accountsUrl": "https://accounts.example.org"
- })
- .to_string(),
- )
- .create_async()
- .await;
-
- let passkey_status = server
- .mock("GET", "/users/two-factor/passkeys/get-token")
- .match_query(Matcher::UrlEncoded(
- "sessionID".into(),
- "passkey-session".into(),
- ))
- .with_status(404)
- .with_body("expired")
- .create_async()
- .await;
-
- let client = make_client(server.url());
- let mut flow = AuthFlow::new(&client, &mut ui);
-
- let error = flow
- .login(LoginParams {
- email: "[email protected]".into(),
- password: Zeroizing::new(password.into()),
- })
- .await
- .unwrap_err();
-
- match error {
- Error::SecondFactorSessionExpired => {}
- other => panic!("unexpected error: {other:?}"),
- }
- assert!(ui.passkey_presented);
-
- srp_attrs.assert_async().await;
- ott.assert_async().await;
- verify_email.assert_async().await;
- passkey_status.assert_async().await;
- }
-
- #[tokio::test]
- async fn create_account_uploads_keys_and_completes_srp_setup() {
- let email = "[email protected]";
- let encoded_email = urlencoding::encode(email).into_owned();
- let signup_token_bytes = b"signup-session-token";
- let signup_token = b64::encode_url_safe(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::from(key_attributes.mem_limit);
- let ops_limit = u64::from(key_attributes.ops_limit);
-
- assert_eq!(mem_limit * ops_limit, 4_294_967_296);
- assert!(
- 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_salt = b64::decode(&payload.srp_salt).unwrap();
- let srp_verifier = b64::decode(&payload.srp_verifier).unwrap();
- let srp_a = b64::decode(&payload.srp_a).unwrap();
- let server = ServerG4096::<Sha256>::new();
- 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(
- payload.srp_user_id.as_bytes(),
- &srp_salt,
- &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.pending_setup_id = Some(setup_id);
- state.remote_srp_attributes = Some(SrpAttributes {
- 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_client_proof = Some(client_proof);
- state.pending_server_proof = Some(server_proof);
-
- serde_json::json!({
- "setupID": setup_id,
- "srpB": b64::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 = b64::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": b64::encode(&state.pending_server_proof.take().unwrap()),
- })
- .to_string()
- .into_bytes()
- })
- .create_async()
- .await;
-
- let state = Arc::clone(&signup_state);
- let get_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::json!({
- "attributes": state.remote_srp_attributes.as_ref().unwrap()
- })
- .to_string()
- .into_bytes()
- })
- .create_async()
- .await;
-
- let client = make_client(server.url());
- let mut flow = AuthFlow::new(&client, &mut ui);
-
- let created = flow
- .create_account(CreateAccountParams {
- email: email.into(),
- password: Zeroizing::new("CorrectHorseBatteryStaple!".into()),
- source: Some("testAccount".into()),
- })
- .await
- .unwrap();
-
- assert_eq!(created.user_id, 99);
- assert_eq!(created.secrets.token, signup_token_bytes);
- assert!(created.recovery_key.is_some());
-
- 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;
- get_srp_attributes.assert_async().await;
- }
-
- #[tokio::test]
- async fn change_password_updates_srp_and_keys() {
- let original = auth::generate_keys_with_strength(
- "old-password",
- auth::KeyDerivationStrength::Interactive,
- )
- .unwrap();
- let key_attributes = original.key_attributes.clone();
- let master_key = b64::decode(&original.private_key_attributes.key).unwrap();
- let state = Arc::new(Mutex::new(MockSignupState::default()));
-
- let mut server = Server::new_async().await;
-
- let state_for_setup = Arc::clone(&state);
- let setup_srp = server
- .mock("POST", "/users/srp/setup")
- .match_header("x-auth-token", "session-token")
- .with_status(200)
- .with_body_from_request(move |request| {
- let payload: SetupSrpPayload = parse_request_body(request);
- let srp_salt = b64::decode(&payload.srp_salt).unwrap();
- let srp_verifier = b64::decode(&payload.srp_verifier).unwrap();
- let srp_a = b64::decode(&payload.srp_a).unwrap();
- let server = ServerG4096::<Sha256>::new();
- let b_private = [0x44u8; 64];
- let srp_b = pad_left(
- &server.compute_public_ephemeral(&b_private, &srp_verifier),
- SRP_A_LEN,
- );
- let setup_id = Uuid::new_v4();
- let verifier = server
- .process_reply(
- payload.srp_user_id.as_bytes(),
- &srp_salt,
- &b_private,
- &srp_verifier,
- &srp_a,
- )
- .unwrap();
- 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 state = &mut *state_for_setup.lock().unwrap();
- state.pending_setup_id = Some(setup_id);
- state.pending_client_proof = Some(client_proof);
- state.pending_server_proof = Some(server_proof);
- state.remote_srp_attributes = Some(SrpAttributes {
- srp_user_id: Uuid::parse_str(&payload.srp_user_id).unwrap(),
- srp_salt: payload.srp_salt.clone(),
- mem_limit: 0,
- ops_limit: 0,
- kek_salt: String::new(),
- is_email_mfa_enabled: false,
- });
-
- serde_json::json!({
- "setupID": setup_id,
- "srpB": b64::encode(&srp_b),
- })
- .to_string()
- .into_bytes()
- })
- .create_async()
- .await;
-
- let state_for_update = Arc::clone(&state);
- let update_srp = server
- .mock("POST", "/users/srp/update")
- .match_header("x-auth-token", "session-token")
- .with_status(200)
- .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!(
- b64::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
- });
- serde_json::json!({
- "setupID": payload.setup_id,
- "srpM2": b64::encode(state.pending_server_proof.as_ref().unwrap()),
- })
- .to_string()
- .into_bytes()
- })
- .create_async()
- .await;
-
- 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(),
- ))
- .with_status(200)
- .with_body_from_request(move |_| {
- let state = state_for_attrs.lock().unwrap();
- serde_json::json!({
- "attributes": state.remote_srp_attributes
- })
- .to_string()
- .into_bytes()
- })
- .create_async()
- .await;
-
- let client = make_client(server.url());
- client.set_auth_token(Some("session-token".into()));
- let mut ui = ScriptedUi::new();
- let flow = AuthFlow::new(&client, &mut ui);
-
- let result = flow
- .change_password_with_strength(
- ChangePasswordParams {
- email: "[email protected]".into(),
- password: Zeroizing::new("new-password".into()),
- master_key: SecretVec::new(master_key),
- key_attributes,
- log_out_other_devices: true,
- },
- KeyDerivationStrength::Interactive,
- )
- .await
- .unwrap();
-
- assert_eq!(
- result.srp_attributes.kek_salt,
- result.key_attributes.kek_salt
- );
-
- setup_srp.assert_async().await;
- update_srp.assert_async().await;
- get_srp_attributes.assert_async().await;
- }
-}
diff --git a/rust/crates/accounts/src/lib.rs b/rust/crates/accounts/src/lib.rs
index 1ff9a3cb30..347686321e 100644
--- a/rust/crates/accounts/src/lib.rs
+++ b/rust/crates/accounts/src/lib.rs
@@ -1,16 +1,20 @@
pub mod auth;
pub mod client;
pub mod error;
-pub mod flow;
+pub mod lifecycle;
+pub mod login;
pub mod models;
+pub mod signup;
pub mod types;
+#[cfg(test)]
+mod test_support;
+
pub use auth::KeyAttributes;
pub use client::AccountsClient;
pub use error::{Error, Result};
-pub use flow::{
- AuthFlow, AuthFlowUi, AuthenticatedAccount, ChangePasswordParams, ChangePasswordResult,
- CheckSessionValidityParams, CreateAccountParams, LoginParams, OtpPurpose, RecoveryKeyResult,
- SecondFactorMethod, SessionValidity, SetupTwoFactorParams, SetupTwoFactorResult, TotpPurpose,
+pub use lifecycle::{
+ ChangePasswordParams, ChangePasswordResult, CheckSessionValidityParams, RecoveryKeyResult,
+ SessionValidity, TwoFactorSetup,
};
-pub use types::{AccountSecrets, AccountsClientConfig, DEFAULT_API_ORIGIN};
+pub use types::{AccountSecrets, AccountsClientConfig, AuthenticatedAccount, DEFAULT_API_ORIGIN};
diff --git a/rust/crates/accounts/src/lifecycle.rs b/rust/crates/accounts/src/lifecycle.rs
new file mode 100644
index 0000000000..2320f99de6
--- /dev/null
+++ b/rust/crates/accounts/src/lifecycle.rs
@@ -0,0 +1,322 @@
+use ente_core::b64;
+use ente_core::crypto::{self, SecretVec, secretbox};
+use std::fmt;
+use uuid::Uuid;
+use zeroize::{ZeroizeOnDrop, Zeroizing};
+
+use crate::{
+ AccountsClient, Error, Result,
+ auth::{
+ self, GeneratedSrpSetup, KeyDerivationStrength, generate_srp_setup_with_login_key,
+ get_recovery_key,
+ },
+ models::{
+ ConfigurePasskeyRecoveryRequest, EnableTwoFactorRequest, KeyAttributes,
+ RemoveTwoFactorRequest, SetRecoveryKeyRequest, SetupSrpRequest, SrpAttributes,
+ TwoFactorAuthorizationResponse, TwoFactorRecoveryResponse, TwoFactorType,
+ UpdateSrpAndKeysRequest, UpdatedKeyAttr,
+ },
+};
+
+pub struct ChangePasswordParams {
+ pub email: String,
+ pub password: Zeroizing<String>,
+ pub master_key: SecretVec,
+ pub key_attributes: KeyAttributes,
+ pub log_out_other_devices: bool,
+}
+
+impl fmt::Debug for ChangePasswordParams {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("ChangePasswordParams")
+ .field("email", &self.email)
+ .field("password", &"[REDACTED]")
+ .field("master_key", &"[REDACTED]")
+ .field("key_attributes", &self.key_attributes)
+ .field("log_out_other_devices", &self.log_out_other_devices)
+ .finish()
+ }
+}
+
+#[derive(Debug)]
+pub struct ChangePasswordResult {
+ pub key_attributes: KeyAttributes,
+ pub srp_attributes: SrpAttributes,
+}
+
+#[derive(Debug)]
+pub struct CheckSessionValidityParams {
+ pub email: String,
+ pub local_srp_attributes: SrpAttributes,
+}
+
+#[derive(Debug)]
+#[cfg_attr(
+ target_pointer_width = "64",
+ expect(
+ clippy::large_enum_variant,
+ reason = "A single session-check result does not need a separate allocation"
+ )
+)]
+pub enum SessionValidity {
+ Invalid,
+ Valid,
+ ValidButPasswordChanged {
+ updated_key_attributes: KeyAttributes,
+ updated_srp_attributes: SrpAttributes,
+ },
+}
+
+pub struct RecoveryKeyResult {
+ pub recovery_key: String,
+ pub key_attributes: KeyAttributes,
+}
+
+impl fmt::Debug for RecoveryKeyResult {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("RecoveryKeyResult")
+ .field("recovery_key", &"[REDACTED]")
+ .field("key_attributes", &self.key_attributes)
+ .finish()
+ }
+}
+
+#[derive(ZeroizeOnDrop)]
+pub struct TwoFactorSetup {
+ pub secret_code: String,
+ pub qr_code: String,
+ pub recovery_key: String,
+}
+
+impl TwoFactorSetup {
+ pub async fn start(
+ client: &AccountsClient,
+ master_key: &[u8],
+ key_attributes: &KeyAttributes,
+ ) -> Result<Self> {
+ let master_key = crypto::Key::try_from_slice(master_key)?;
+ let recovery_key = get_recovery_key(&master_key, key_attributes)?;
+ let secret = client.setup_two_factor().await?;
+ Ok(Self {
+ secret_code: secret.secret_code,
+ qr_code: secret.qr_code,
+ recovery_key,
+ })
+ }
+
+ pub async fn enable(&self, client: &AccountsClient, code: &str) -> Result<()> {
+ let request = encrypt_two_factor_secret(&self.secret_code, &self.recovery_key, code)?;
+ client.enable_two_factor(&request).await
+ }
+}
+
+pub async fn change_password(
+ client: &AccountsClient,
+ params: ChangePasswordParams,
+) -> Result<ChangePasswordResult> {
+ change_password_with_strength(client, params, KeyDerivationStrength::Sensitive).await
+}
+
+async fn change_password_with_strength(
+ client: &AccountsClient,
+ params: ChangePasswordParams,
+ key_derivation_strength: KeyDerivationStrength,
+) -> Result<ChangePasswordResult> {
+ let (updated_key_attributes, login_key) =
+ auth::generate_key_attributes_for_new_password_with_strength(
+ &params.master_key,
+ &params.key_attributes,
+ &params.password,
+ key_derivation_strength,
+ )?;
+
+ let updated_key_attr = UpdatedKeyAttr::from(&updated_key_attributes);
+
+ let srp_user_id = Uuid::new_v4();
+ let srp_setup = generate_srp_setup_with_login_key(&login_key, &srp_user_id.to_string())?;
+ complete_srp_update(
+ client,
+ &srp_user_id,
+ &srp_setup,
+ &updated_key_attr,
+ params.log_out_other_devices,
+ )
+ .await?;
+
+ let srp_attributes = client.get_srp_attributes(&params.email).await?;
+
+ srp_attributes.validate_setup(
+ srp_user_id,
+ &srp_setup.srp_salt,
+ &updated_key_attributes,
+ "password change",
+ )?;
+
+ Ok(ChangePasswordResult {
+ key_attributes: updated_key_attributes,
+ srp_attributes,
+ })
+}
+
+pub async fn check_session_validity(
+ client: &AccountsClient,
+ params: CheckSessionValidityParams,
+) -> Result<SessionValidity> {
+ let remote = match client.get_session_validity().await {
+ Ok(remote) => remote,
+ Err(Error::SessionInvalid) => return Ok(SessionValidity::Invalid),
+ Err(error) => return Err(error),
+ };
+
+ if let Some(remote_key_attributes) = remote.key_attributes {
+ let remote_srp_attributes = client.get_srp_attributes(&params.email).await?;
+ if remote_srp_attributes.kek_salt != params.local_srp_attributes.kek_salt {
+ return Ok(SessionValidity::ValidButPasswordChanged {
+ updated_key_attributes: remote_key_attributes,
+ updated_srp_attributes: remote_srp_attributes,
+ });
+ }
+ }
+
+ Ok(SessionValidity::Valid)
+}
+
+pub async fn create_recovery_key(
+ client: &AccountsClient,
+ master_key: &[u8],
+ existing_attributes: &KeyAttributes,
+) -> Result<RecoveryKeyResult> {
+ let (
+ recovery_key,
+ master_key_encrypted_with_recovery_key,
+ master_key_decryption_nonce,
+ recovery_key_encrypted_with_master_key,
+ recovery_key_decryption_nonce,
+ ) = auth::create_new_recovery_key(master_key)?;
+
+ let request = SetRecoveryKeyRequest {
+ master_key_encrypted_with_recovery_key: master_key_encrypted_with_recovery_key.clone(),
+ master_key_decryption_nonce: master_key_decryption_nonce.clone(),
+ recovery_key_encrypted_with_master_key: recovery_key_encrypted_with_master_key.clone(),
+ recovery_key_decryption_nonce: recovery_key_decryption_nonce.clone(),
+ };
+ client.set_recovery_key_attributes(request).await?;
+
+ let key_attributes = KeyAttributes {
+ master_key_encrypted_with_recovery_key: Some(master_key_encrypted_with_recovery_key),
+ master_key_decryption_nonce: Some(master_key_decryption_nonce),
+ recovery_key_encrypted_with_master_key: Some(recovery_key_encrypted_with_master_key),
+ recovery_key_decryption_nonce: Some(recovery_key_decryption_nonce),
+ ..existing_attributes.clone()
+ };
+
+ Ok(RecoveryKeyResult {
+ recovery_key,
+ key_attributes,
+ })
+}
+
+pub async fn recover_two_factor(
+ client: &AccountsClient,
+ two_factor_type: TwoFactorType,
+ session_id: &str,
+ recovery_response: &TwoFactorRecoveryResponse,
+ recovery_key_mnemonic_or_hex: &str,
+) -> Result<TwoFactorAuthorizationResponse> {
+ let recovery_key = auth::recovery_key_from_mnemonic_or_hex(recovery_key_mnemonic_or_hex)?;
+ let encrypted_secret = b64::decode(&recovery_response.encrypted_secret)?;
+ let nonce = b64::decode(&recovery_response.secret_decryption_nonce)?;
+ let secret = secretbox::decrypt(
+ &encrypted_secret,
+ &crypto::Nonce::try_from_slice(&nonce)?,
+ &crypto::Key::try_from_slice(&recovery_key)?,
+ )
+ .map_err(|_| Error::IncorrectRecoveryKey)?;
+ let request = RemoveTwoFactorRequest {
+ session_id: session_id.to_string(),
+ secret: String::from_utf8(secret)
+ .map_err(|e| Error::Protocol(format!("invalid recovery secret: {e}")))?,
+ two_factor_type,
+ };
+ client.remove_two_factor(&request).await
+}
+
+pub async fn configure_passkey_recovery(
+ client: &AccountsClient,
+ secret: &str,
+ recovery_key_mnemonic_or_hex: &str,
+) -> Result<()> {
+ let recovery_key = auth::recovery_key_from_mnemonic_or_hex(recovery_key_mnemonic_or_hex)?;
+ let encrypted = secretbox::encrypt(
+ secret.as_bytes(),
+ &crypto::Key::try_from_slice(&recovery_key)?,
+ );
+ let request = ConfigurePasskeyRecoveryRequest {
+ secret: secret.to_string(),
+ user_secret_cipher: b64::encode(&encrypted.encrypted_data),
+ user_secret_nonce: b64::encode(encrypted.nonce.as_bytes()),
+ };
+ client.configure_passkey_recovery(&request).await
+}
+
+async fn complete_srp_update(
+ client: &AccountsClient,
+ srp_user_id: &Uuid,
+ srp_setup: &GeneratedSrpSetup,
+ updated_key_attr: &UpdatedKeyAttr,
+ log_out_other_devices: bool,
+) -> Result<crate::models::UpdateSrpAndKeysResponse> {
+ let mut srp_session = auth::SrpSession::new(
+ &srp_user_id.to_string(),
+ &srp_setup.srp_salt,
+ &srp_setup.login_sub_key,
+ )?;
+ let srp_a = b64::encode(&srp_session.public_a());
+
+ let setup = client
+ .setup_srp(&SetupSrpRequest {
+ srp_user_id: srp_user_id.to_string(),
+ srp_salt: b64::encode(&srp_setup.srp_salt),
+ srp_verifier: b64::encode(&srp_setup.srp_verifier),
+ srp_a,
+ })
+ .await?;
+
+ let srp_b = b64::decode(&setup.srp_b)?;
+ let srp_m1 = b64::encode(&srp_session.compute_m1(&srp_b)?);
+
+ let response = client
+ .update_srp_and_key_attributes(&UpdateSrpAndKeysRequest {
+ setup_id: setup.setup_id.to_string(),
+ srp_m1,
+ updated_key_attr: updated_key_attr.clone(),
+ log_out_other_devices,
+ })
+ .await?;
+
+ let srp_m2 = b64::decode(&response.srp_m2)?;
+ srp_session.verify_m2(&srp_m2)?;
+ Ok(response)
+}
+
+fn encrypt_two_factor_secret(
+ secret_code: &str,
+ recovery_key_hex: &str,
+ code: &str,
+) -> Result<EnableTwoFactorRequest> {
+ let recovery_key =
+ hex::decode(recovery_key_hex).map_err(|e| Error::Decode(format!("recovery_key: {e}")))?;
+ let encrypted = secretbox::encrypt(
+ secret_code.as_bytes(),
+ &crypto::Key::try_from_slice(&recovery_key)?,
+ );
+
+ Ok(EnableTwoFactorRequest {
+ code: code.to_string(),
+ encrypted_two_factor_secret: b64::encode(&encrypted.encrypted_data),
+ two_factor_secret_decryption_nonce: b64::encode(encrypted.nonce.as_bytes()),
+ })
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/rust/crates/accounts/src/lifecycle/tests.rs b/rust/crates/accounts/src/lifecycle/tests.rs
new file mode 100644
index 0000000000..f753668f68
--- /dev/null
+++ b/rust/crates/accounts/src/lifecycle/tests.rs
@@ -0,0 +1,237 @@
+use super::*;
+use mockito::{Matcher, Server};
+use serde::Deserialize;
+use std::sync::{Arc, Mutex};
+
+use crate::test_support::{SetupSrpPayload, SrpState, make_client, parse_request_body, srp_proofs};
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UpdateSrpPayload {
+ setup_id: String,
+ srp_m1: String,
+ updated_key_attr: UpdatedKeyAttr,
+ log_out_other_devices: bool,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ConfigurePasskeyRecoveryPayload {
+ secret: String,
+ user_secret_cipher: String,
+ user_secret_nonce: String,
+}
+
+#[tokio::test]
+async fn setup_two_factor_encrypts_secret_with_recovery_key() {
+ 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.into_string();
+ let master_key = b64::decode(&key_gen.private_key_attributes.key).unwrap();
+ let key_attributes = key_gen.key_attributes.clone();
+
+ let mut server = Server::new_async().await;
+
+ 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 client = make_client(server.url());
+ client.set_auth_token(Some("session-token".into()));
+
+ let result = TwoFactorSetup::start(&client, &master_key, &key_attributes)
+ .await
+ .unwrap();
+ result.enable(&client, "123123").await.unwrap();
+
+ assert_eq!(result.secret_code, "JBSWY3DPEHPK3PXP");
+ assert_eq!(result.recovery_key, recovery_key);
+
+ setup.assert_async().await;
+ enable.assert_async().await;
+}
+
+#[tokio::test]
+async fn configure_passkey_recovery_accepts_hex_recovery_key() {
+ let key_gen =
+ auth::generate_keys_with_strength("pw", auth::KeyDerivationStrength::Interactive).unwrap();
+ let recovery_key_hex = key_gen.private_key_attributes.recovery_key.into_string();
+ let expected_recovery_key = hex::decode(&recovery_key_hex).unwrap();
+
+ let mut server = Server::new_async().await;
+ let configure = server
+ .mock("POST", "/users/two-factor/passkeys/configure-recovery")
+ .match_header("x-auth-token", "session-token")
+ .match_header("x-client-package", "io.ente.photos")
+ .with_status(200)
+ .with_body_from_request(move |request| {
+ let payload: ConfigurePasskeyRecoveryPayload = parse_request_body(request);
+ let cipher = b64::decode(&payload.user_secret_cipher).unwrap();
+ let nonce = b64::decode(&payload.user_secret_nonce).unwrap();
+ let decrypted = secretbox::decrypt(
+ &cipher,
+ &crypto::Nonce::try_from_slice(&nonce).unwrap(),
+ &crypto::Key::try_from_slice(&expected_recovery_key).unwrap(),
+ )
+ .unwrap();
+ assert_eq!(payload.secret, "reset-secret");
+ assert_eq!(String::from_utf8(decrypted).unwrap(), "reset-secret");
+ Vec::new()
+ })
+ .create_async()
+ .await;
+
+ let client = make_client(server.url());
+ client.set_auth_token(Some("session-token".into()));
+
+ configure_passkey_recovery(&client, "reset-secret", &recovery_key_hex)
+ .await
+ .unwrap();
+
+ configure.assert_async().await;
+}
+
+#[tokio::test]
+async fn change_password_updates_srp_and_keys() {
+ let original =
+ auth::generate_keys_with_strength("old-password", auth::KeyDerivationStrength::Interactive)
+ .unwrap();
+ let key_attributes = original.key_attributes.clone();
+ let master_key = b64::decode(&original.private_key_attributes.key).unwrap();
+ let state = Arc::new(Mutex::new(SrpState::default()));
+
+ let mut server = Server::new_async().await;
+
+ let state_for_setup = Arc::clone(&state);
+ let setup_srp = server
+ .mock("POST", "/users/srp/setup")
+ .match_header("x-auth-token", "session-token")
+ .with_status(200)
+ .with_body_from_request(move |request| {
+ let payload: SetupSrpPayload = parse_request_body(request);
+ let (srp_b, client_proof, server_proof) = srp_proofs(&payload);
+ let setup_id = Uuid::new_v4();
+
+ let state = &mut *state_for_setup.lock().unwrap();
+ state.pending_setup_id = Some(setup_id);
+ state.pending_client_proof = Some(client_proof);
+ state.pending_server_proof = Some(server_proof);
+ state.remote_srp_attributes = Some(SrpAttributes {
+ srp_user_id: Uuid::parse_str(&payload.srp_user_id).unwrap(),
+ srp_salt: payload.srp_salt.clone(),
+ mem_limit: 0,
+ ops_limit: 0,
+ kek_salt: String::new(),
+ is_email_mfa_enabled: false,
+ });
+
+ serde_json::json!({
+ "setupID": setup_id,
+ "srpB": b64::encode(&srp_b),
+ })
+ .to_string()
+ .into_bytes()
+ })
+ .create_async()
+ .await;
+
+ let state_for_update = Arc::clone(&state);
+ let update_srp = server
+ .mock("POST", "/users/srp/update")
+ .match_header("x-auth-token", "session-token")
+ .with_status(200)
+ .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!(
+ b64::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
+ });
+ serde_json::json!({
+ "setupID": payload.setup_id,
+ "srpM2": b64::encode(state.pending_server_proof.as_ref().unwrap()),
+ })
+ .to_string()
+ .into_bytes()
+ })
+ .create_async()
+ .await;
+
+ 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(),
+ ))
+ .with_status(200)
+ .with_body_from_request(move |_| {
+ let state = state_for_attrs.lock().unwrap();
+ serde_json::json!({
+ "attributes": state.remote_srp_attributes
+ })
+ .to_string()
+ .into_bytes()
+ })
+ .create_async()
+ .await;
+
+ let client = make_client(server.url());
+ client.set_auth_token(Some("session-token".into()));
+
+ let result = change_password_with_strength(
+ &client,
+ ChangePasswordParams {
+ email: "[email protected]".into(),
+ password: Zeroizing::new("new-password".into()),
+ master_key: SecretVec::new(master_key),
+ key_attributes,
+ log_out_other_devices: true,
+ },
+ KeyDerivationStrength::Interactive,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ result.srp_attributes.kek_salt,
+ result.key_attributes.kek_salt
+ );
+
+ setup_srp.assert_async().await;
+ update_srp.assert_async().await;
+ get_srp_attributes.assert_async().await;
+}
diff --git a/rust/crates/accounts/src/login.rs b/rust/crates/accounts/src/login.rs
new file mode 100644
index 0000000000..5fd064010f
--- /dev/null
+++ b/rust/crates/accounts/src/login.rs
@@ -0,0 +1,238 @@
+use ente_core::{b64, crypto::SecretVec};
+
+use crate::{
+ AccountSecrets, AccountsClient, AuthenticatedAccount, Error, Result,
+ auth::{self, DecryptedSecrets, KeyAttributes, SrpAttributes, derive_kek, get_recovery_key},
+ models::AuthResponse,
+};
+
+pub enum LoginStep {
+ EmailCode,
+ Password,
+ SecondFactor { totp: bool, passkey: bool },
+ Complete(Box<AuthenticatedAccount>),
+}
+
+enum State {
+ EmailCode,
+ Password(Option<AuthResponse>),
+ SecondFactor {
+ response: AuthResponse,
+ kek: Option<SecretVec>,
+ },
+ Complete,
+}
+
+pub struct LoginFlow {
+ email: String,
+ attributes: SrpAttributes,
+ state: State,
+}
+
+impl LoginFlow {
+ pub async fn start(client: &AccountsClient, email: String) -> Result<(Self, LoginStep)> {
+ let attributes = client.get_srp_attributes(&email).await?;
+ let (state, step) = if attributes.is_email_mfa_enabled {
+ client.send_otp(&email, "login").await?;
+ (State::EmailCode, LoginStep::EmailCode)
+ } else {
+ (State::Password(None), LoginStep::Password)
+ };
+ Ok((
+ Self {
+ email,
+ attributes,
+ state,
+ },
+ step,
+ ))
+ }
+
+ pub async fn submit_password(
+ &mut self,
+ client: &AccountsClient,
+ password: &str,
+ ) -> Result<LoginStep> {
+ let State::Password(response) = &self.state else {
+ return Err(Error::InvalidInput("Password is not expected".into()));
+ };
+ if let Some(response) = response {
+ let kek = derive_kek(
+ password,
+ &self.attributes.kek_salt,
+ self.attributes.mem_limit,
+ self.attributes.ops_limit,
+ )?;
+ let account = build_authenticated_account(response, &kek)?;
+ self.state = State::Complete;
+ Ok(LoginStep::Complete(Box::new(account)))
+ } else {
+ let (response, kek) = client.login_with_srp(password, &self.attributes).await?;
+ self.advance(response, Some(kek))
+ }
+ }
+
+ pub async fn submit_code(&mut self, client: &AccountsClient, code: &str) -> Result<LoginStep> {
+ let (response, kek) = match &self.state {
+ State::EmailCode => (client.verify_email(&self.email, code, None).await?, None),
+ State::SecondFactor { response, kek } => {
+ let id = response.get_two_factor_session_id().ok_or_else(|| {
+ Error::InvalidInput("Authenticator code is not expected".into())
+ })?;
+ let verified = client.verify_totp(id, code).await?;
+ (
+ verified,
+ kek.as_ref().map(|key| SecretVec::new(key.to_vec())),
+ )
+ }
+ _ => {
+ return Err(Error::InvalidInput(
+ "Verification code is not expected".into(),
+ ));
+ }
+ };
+ self.advance(response, kek)
+ }
+
+ pub async fn resend_code(&self, client: &AccountsClient) -> Result<()> {
+ if !matches!(self.state, State::EmailCode) {
+ return Err(Error::InvalidInput("Email code is not expected".into()));
+ }
+ client.send_otp(&self.email, "login").await
+ }
+
+ pub fn passkey_url(&self, client: &AccountsClient, redirect: &str) -> Result<String> {
+ let response = self.passkey_response()?;
+ Ok(build_passkey_verification_url(
+ response
+ .accounts_url
+ .as_deref()
+ .ok_or(Error::MissingField("accountsUrl"))?,
+ response
+ .passkey_session_id
+ .as_deref()
+ .ok_or(Error::MissingField("passkeySessionID"))?,
+ client.client_package(),
+ redirect,
+ None,
+ ))
+ }
+
+ pub async fn poll_passkey(&mut self, client: &AccountsClient) -> Result<Option<LoginStep>> {
+ let response = self.passkey_response()?;
+ let id = response
+ .passkey_session_id
+ .as_deref()
+ .ok_or(Error::MissingField("passkeySessionID"))?;
+ let Some(verified) = client.check_passkey_status(id).await? else {
+ return Ok(None);
+ };
+ let kek = match &self.state {
+ State::SecondFactor { kek, .. } => kek.as_ref().map(|key| SecretVec::new(key.to_vec())),
+ _ => None,
+ };
+ self.advance(verified, kek).map(Some)
+ }
+
+ fn passkey_response(&self) -> Result<&AuthResponse> {
+ match &self.state {
+ State::SecondFactor { response, .. } if response.is_passkey_required() => Ok(response),
+ _ => Err(Error::InvalidInput("Passkey is not expected".into())),
+ }
+ }
+
+ fn advance(&mut self, response: AuthResponse, kek: Option<SecretVec>) -> Result<LoginStep> {
+ let totp = response.is_mfa_required();
+ let passkey = response.is_passkey_required();
+ if totp || passkey {
+ self.state = State::SecondFactor { response, kek };
+ return Ok(LoginStep::SecondFactor { totp, passkey });
+ }
+ if let Some(kek) = kek {
+ let account = build_authenticated_account(&response, &kek)?;
+ self.state = State::Complete;
+ Ok(LoginStep::Complete(Box::new(account)))
+ } else {
+ self.state = State::Password(Some(response));
+ Ok(LoginStep::Password)
+ }
+ }
+}
+
+pub fn build_passkey_verification_url(
+ accounts_url: &str,
+ passkey_session_id: &str,
+ client_package: &str,
+ redirect: &str,
+ recover: Option<&str>,
+) -> String {
+ let mut params = vec![
+ ("clientPackage", client_package),
+ ("passkeySessionID", passkey_session_id),
+ ("redirect", redirect),
+ ];
+ if let Some(recover) = recover {
+ params.push(("recover", recover));
+ }
+
+ let query = params
+ .into_iter()
+ .map(|(key, value)| format!("{key}={}", urlencoding::encode(value)))
+ .collect::<Vec<_>>()
+ .join("&");
+
+ format!("{accounts_url}/passkeys/verify?{query}")
+}
+
+fn build_authenticated_account(
+ auth_response: &AuthResponse,
+ kek: &[u8],
+) -> Result<AuthenticatedAccount> {
+ let key_attributes = auth_response
+ .key_attributes
+ .clone()
+ .ok_or(Error::MissingKeyAttributes)?;
+ let secrets = decrypt_auth_response(auth_response, &key_attributes, kek)?;
+ let public_key = b64::decode(&key_attributes.public_key)?;
+ let recovery_key = get_recovery_key(&secrets.master_key, &key_attributes).ok();
+ Ok(AuthenticatedAccount {
+ user_id: auth_response.id,
+ key_attributes,
+ secrets: AccountSecrets {
+ token: secrets.token.into_vec(),
+ master_key: secrets.master_key.as_bytes().to_vec(),
+ secret_key: secrets.secret_key.as_bytes().to_vec(),
+ public_key,
+ },
+ recovery_key,
+ })
+}
+
+fn decode_plain_token(token: &str) -> Result<SecretVec> {
+ let bytes = b64::decode_url_safe(token)
+ .or_else(|_| b64::decode(token))
+ .map_err(|e| Error::Decode(format!("token: {e}")))?;
+ Ok(SecretVec::new(bytes))
+}
+
+fn decrypt_auth_response(
+ auth_response: &AuthResponse,
+ key_attributes: &KeyAttributes,
+ kek: &[u8],
+) -> Result<DecryptedSecrets> {
+ if let Some(encrypted_token) = auth_response.encrypted_token.as_deref() {
+ auth::decrypt_secrets(kek, key_attributes, encrypted_token)
+ } 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::Protocol("No token in response".into()))
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/rust/crates/accounts/src/login/tests.rs b/rust/crates/accounts/src/login/tests.rs
new file mode 100644
index 0000000000..de98f0ad2c
--- /dev/null
+++ b/rust/crates/accounts/src/login/tests.rs
@@ -0,0 +1,358 @@
+use super::*;
+use mockito::{Matcher, Server};
+use serde_json::json;
+use uuid::Uuid;
+
+use crate::{AccountsClientConfig, auth::KeyDerivationStrength, test_support::make_client};
+use ente_core::crypto;
+
+async fn start_email_login(
+ server: &mut Server,
+ attributes: &KeyAttributes,
+ response: serde_json::Value,
+) -> (AccountsClient, LoginFlow) {
+ let srp = server
+ .mock("GET", "/users/srp/attributes")
+ .match_query(Matcher::UrlEncoded(
+ "email".into(),
+ "[email protected]".into(),
+ ))
+ .with_body(
+ json!({"attributes": {
+ "srpUserID": Uuid::new_v4(),
+ "srpSalt": b64::encode(&[1; 16]),
+ "memLimit": attributes.mem_limit,
+ "opsLimit": attributes.ops_limit,
+ "kekSalt": attributes.kek_salt,
+ "isEmailMFAEnabled": true
+ }})
+ .to_string(),
+ )
+ .create_async()
+ .await;
+ let ott = server.mock("POST", "/users/ott").create_async().await;
+ server
+ .mock("POST", "/users/verify-email")
+ .with_body(response.to_string())
+ .create_async()
+ .await;
+ let client =
+ AccountsClient::new(AccountsClientConfig::new("io.ente.photos").with_origin(server.url()))
+ .unwrap();
+ let (flow, step) = LoginFlow::start(&client, "[email protected]".into())
+ .await
+ .unwrap();
+ assert!(matches!(step, LoginStep::EmailCode));
+ srp.assert_async().await;
+ ott.assert_async().await;
+ (client, flow)
+}
+
+#[tokio::test]
+async fn email_login_retries_password_and_accepts_plain_token_without_recovery_key() {
+ let generated =
+ auth::generate_keys_with_strength("password", KeyDerivationStrength::Interactive).unwrap();
+ let mut attributes = generated.key_attributes;
+ attributes.recovery_key_encrypted_with_master_key = None;
+ attributes.recovery_key_decryption_nonce = None;
+ let token = [255; 32];
+ let mut server = Server::new_async().await;
+ let (client, mut flow) = start_email_login(
+ &mut server,
+ &attributes,
+ json!({"id": 77, "keyAttributes": attributes, "token": b64::encode_url_safe(&token)}),
+ )
+ .await;
+
+ assert!(matches!(
+ flow.submit_password(&client, "password").await,
+ Err(Error::InvalidInput(_))
+ ));
+ assert!(matches!(
+ flow.submit_code(&client, "123456").await.unwrap(),
+ LoginStep::Password
+ ));
+ assert!(matches!(
+ flow.submit_password(&client, "wrong").await,
+ Err(Error::IncorrectPassword)
+ ));
+ let LoginStep::Complete(account) = flow.submit_password(&client, "password").await.unwrap()
+ else {
+ panic!("login did not complete");
+ };
+ assert_eq!(account.user_id, 77);
+ assert_eq!(account.secrets.token, token);
+ assert_eq!(
+ account.secrets.master_key,
+ b64::decode(&generated.private_key_attributes.key).unwrap()
+ );
+ assert!(account.recovery_key.is_none());
+ assert!(matches!(
+ flow.submit_password(&client, "password").await,
+ Err(Error::InvalidInput(_))
+ ));
+}
+
+#[tokio::test]
+async fn passkey_login_waits_for_verification_before_requesting_password() {
+ let generated =
+ auth::generate_keys_with_strength("password", KeyDerivationStrength::Interactive).unwrap();
+ let attributes = generated.key_attributes;
+ let mut server = Server::new_async().await;
+ let (client, mut flow) = start_email_login(
+ &mut server,
+ &attributes,
+ json!({"id": 77, "passkeySessionID": "passkey-1", "accountsUrl": "https://accounts.ente.io"}),
+ )
+ .await;
+ assert!(matches!(
+ flow.submit_code(&client, "123456").await.unwrap(),
+ LoginStep::SecondFactor {
+ totp: false,
+ passkey: true
+ }
+ ));
+ assert_eq!(
+ flow.passkey_url(&client, "ente-cli://passkey").unwrap(),
+ "https://accounts.ente.io/passkeys/verify?clientPackage=io.ente.photos&passkeySessionID=passkey-1&redirect=ente-cli%3A%2F%2Fpasskey"
+ );
+ let pending = server
+ .mock("GET", "/users/two-factor/passkeys/get-token")
+ .match_query(Matcher::UrlEncoded("sessionID".into(), "passkey-1".into()))
+ .with_status(400)
+ .create_async()
+ .await;
+ assert!(flow.poll_passkey(&client).await.unwrap().is_none());
+ pending.assert_async().await;
+ pending.remove_async().await;
+
+ let verified = server
+ .mock("GET", "/users/two-factor/passkeys/get-token")
+ .match_query(Matcher::UrlEncoded("sessionID".into(), "passkey-1".into()))
+ .with_body(
+ json!({"id": 77, "keyAttributes": attributes, "token": b64::encode(&[255; 32])})
+ .to_string(),
+ )
+ .create_async()
+ .await;
+ assert!(matches!(
+ flow.poll_passkey(&client).await.unwrap(),
+ Some(LoginStep::Password)
+ ));
+ let LoginStep::Complete(account) = flow.submit_password(&client, "password").await.unwrap()
+ else {
+ panic!("login did not complete");
+ };
+ assert_eq!(account.secrets.token, [255; 32]);
+ assert_eq!(
+ account.recovery_key.as_deref(),
+ Some(&*generated.private_key_attributes.recovery_key)
+ );
+ verified.assert_async().await;
+}
+
+#[tokio::test]
+async fn login_retries_email_and_totp() {
+ let password = "hunter2";
+ let generated =
+ auth::generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap();
+ let key_attributes = generated.key_attributes;
+ let public_key = b64::decode(&key_attributes.public_key).unwrap();
+ let encrypted_token = b64::encode(
+ &crypto::sealed::seal(
+ b"plain-auth-token",
+ &crypto::PublicKey::try_from_slice(&public_key).unwrap(),
+ )
+ .unwrap(),
+ );
+ let recovery_key = generated.private_key_attributes.recovery_key.into_string();
+
+ let mut server = Server::new_async().await;
+
+ let srp_attrs = server
+ .mock("GET", Matcher::Any)
+ .match_request(|request| {
+ request.path() == "/users/srp/attributes"
+ && request.path_and_query() == "/users/srp/attributes?email=user%40example.org"
+ })
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "attributes": {
+ "srpUserID": Uuid::new_v4(),
+ "srpSalt": b64::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)
+ .expect(2)
+ .create_async()
+ .await;
+
+ let expired_email = server
+ .mock("POST", "/users/verify-email")
+ .match_body(Matcher::PartialJson(serde_json::json!({"ott": "expired"})))
+ .with_status(410)
+ .create_async()
+ .await;
+ let incorrect_email = server
+ .mock("POST", "/users/verify-email")
+ .match_body(Matcher::PartialJson(serde_json::json!({"ott": "wrong"})))
+ .with_status(400)
+ .create_async()
+ .await;
+ let verify_email = server
+ .mock("POST", "/users/verify-email")
+ .match_body(Matcher::PartialJson(serde_json::json!({"ott": "123456"})))
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "id": 77,
+ "twoFactorSessionID": "session-1",
+ "passkeySessionID": "passkey-1",
+ "accountsUrl": "https://accounts.ente.io",
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let incorrect_totp = server
+ .mock("POST", "/users/two-factor/verify")
+ .match_body(Matcher::PartialJson(serde_json::json!({"code": "wrong"})))
+ .with_status(400)
+ .create_async()
+ .await;
+ let verify_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 client = make_client(server.url());
+
+ let (mut flow, step) = LoginFlow::start(&client, "[email protected]".into())
+ .await
+ .unwrap();
+ assert!(matches!(step, LoginStep::EmailCode));
+ assert!(matches!(
+ flow.submit_code(&client, "expired").await,
+ Err(Error::EmailVerificationCodeExpired)
+ ));
+ flow.resend_code(&client).await.unwrap();
+ assert!(matches!(
+ flow.submit_code(&client, "wrong").await,
+ Err(Error::IncorrectEmailVerificationCode)
+ ));
+ assert!(matches!(
+ flow.submit_code(&client, "123456").await.unwrap(),
+ LoginStep::SecondFactor {
+ totp: true,
+ passkey: true
+ }
+ ));
+ assert!(matches!(
+ flow.submit_code(&client, "wrong").await,
+ Err(Error::IncorrectTotp)
+ ));
+ assert!(matches!(
+ flow.submit_code(&client, "654321").await.unwrap(),
+ LoginStep::Password
+ ));
+ let LoginStep::Complete(result) = flow.submit_password(&client, password).await.unwrap() else {
+ panic!("login did not complete");
+ };
+
+ 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;
+ expired_email.assert_async().await;
+ incorrect_email.assert_async().await;
+ incorrect_totp.assert_async().await;
+ verify_email.assert_async().await;
+ verify_totp.assert_async().await;
+}
+
+#[tokio::test]
+async fn totp_errors_are_preserved() {
+ let attributes =
+ auth::generate_keys_with_strength("password", KeyDerivationStrength::Interactive)
+ .unwrap()
+ .key_attributes;
+ for status in [404, 429] {
+ let mut server = Server::new_async().await;
+ let (client, mut flow) = start_email_login(
+ &mut server,
+ &attributes,
+ json!({"id": 77, "twoFactorSessionID": "session-1"}),
+ )
+ .await;
+ assert!(matches!(
+ flow.submit_code(&client, "123456").await.unwrap(),
+ LoginStep::SecondFactor { totp: true, .. }
+ ));
+ let verify = server
+ .mock("POST", "/users/two-factor/verify")
+ .with_status(status)
+ .create_async()
+ .await;
+ let error = flow.submit_code(&client, "654321").await.err().unwrap();
+ assert!(matches!(
+ (status, error),
+ (404, Error::SecondFactorSessionExpired) | (429, Error::TotpRateLimited)
+ ));
+ verify.assert_async().await;
+ }
+}
+
+#[tokio::test]
+async fn passkey_expiry_is_preserved() {
+ let attributes =
+ auth::generate_keys_with_strength("password", KeyDerivationStrength::Interactive)
+ .unwrap()
+ .key_attributes;
+ let mut server = Server::new_async().await;
+ let (client, mut flow) = start_email_login(
+ &mut server,
+ &attributes,
+ json!({"id": 77, "passkeySessionID": "passkey-1", "accountsUrl": "https://accounts.ente.io"}),
+ )
+ .await;
+ assert!(matches!(
+ flow.submit_code(&client, "123456").await.unwrap(),
+ LoginStep::SecondFactor { passkey: true, .. }
+ ));
+ let status = server
+ .mock("GET", "/users/two-factor/passkeys/get-token")
+ .match_query(Matcher::UrlEncoded("sessionID".into(), "passkey-1".into()))
+ .with_status(404)
+ .create_async()
+ .await;
+ assert!(matches!(
+ flow.poll_passkey(&client).await,
+ Err(Error::SecondFactorSessionExpired)
+ ));
+ status.assert_async().await;
+}
diff --git a/rust/crates/accounts/src/signup.rs b/rust/crates/accounts/src/signup.rs
new file mode 100644
index 0000000000..ad0f64139b
--- /dev/null
+++ b/rust/crates/accounts/src/signup.rs
@@ -0,0 +1,169 @@
+use ente_core::{b64, crypto::Key};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+use zeroize::ZeroizeOnDrop;
+
+use crate::{
+ AccountSecrets, AccountsClient, AuthenticatedAccount, Error, KeyAttributes, Result,
+ auth::{
+ KeyDerivationStrength, SrpSession, generate_keys_with_strength,
+ generate_srp_setup_with_login_key, get_recovery_key,
+ },
+ models::{AuthResponse, SetupSrpRequest},
+};
+
+#[derive(Clone, Serialize, Deserialize, ZeroizeOnDrop)]
+pub struct Signup {
+ pub user_id: i64,
+ pub email: String,
+ token: Vec<u8>,
+ #[zeroize(skip)]
+ keys: Option<PreparedKeys>,
+}
+
+#[derive(Clone, Serialize, Deserialize, ZeroizeOnDrop)]
+struct PreparedKeys {
+ #[zeroize(skip)]
+ attributes: KeyAttributes,
+ master_key: Vec<u8>,
+ secret_key: Vec<u8>,
+ login_key: Vec<u8>,
+ #[zeroize(skip)]
+ srp_user_id: Uuid,
+ srp_salt: Vec<u8>,
+ srp_verifier: Vec<u8>,
+}
+
+impl Signup {
+ pub fn verified(email: String, response: AuthResponse) -> Result<Self> {
+ if response.key_attributes.is_some()
+ || response.encrypted_token.is_some()
+ || response.is_mfa_required()
+ || response.is_passkey_required()
+ {
+ return Err(Error::AccountAlreadyExists);
+ }
+ let token = response.token.ok_or(Error::MissingField("token"))?;
+ Ok(Self {
+ user_id: response.id,
+ email,
+ token: b64::decode_url_safe(&token).or_else(|_| b64::decode(&token))?,
+ keys: None,
+ })
+ }
+
+ fn authorize(&self, client: &AccountsClient) {
+ client.set_auth_token(Some(b64::encode_url_safe(&self.token)));
+ }
+
+ pub async fn prepare(&self, client: &AccountsClient, password: &str) -> Result<Self> {
+ self.prepare_with_strength(client, password, KeyDerivationStrength::Sensitive)
+ .await
+ }
+
+ pub(crate) async fn prepare_with_strength(
+ &self,
+ client: &AccountsClient,
+ password: &str,
+ strength: KeyDerivationStrength,
+ ) -> Result<Self> {
+ if self.keys.is_some() {
+ return Ok(self.clone());
+ }
+ self.authorize(client);
+ let remote = client.get_session_validity().await?;
+ if remote.has_set_keys || remote.key_attributes.is_some() {
+ return Err(Error::AccountAlreadyExists);
+ }
+ let generated = generate_keys_with_strength(password, strength)?;
+ let srp_user_id = Uuid::new_v4();
+ let srp =
+ generate_srp_setup_with_login_key(&generated.login_key, &srp_user_id.to_string())?;
+ let mut prepared = self.clone();
+ prepared.keys = Some(PreparedKeys {
+ master_key: b64::decode(&generated.private_key_attributes.key)?,
+ secret_key: b64::decode(&generated.private_key_attributes.secret_key)?,
+ attributes: generated.key_attributes,
+ login_key: generated.login_key.into_vec(),
+ srp_user_id,
+ srp_salt: srp.srp_salt,
+ srp_verifier: srp.srp_verifier,
+ });
+ Ok(prepared)
+ }
+
+ pub fn recovery_key(&self) -> Result<Option<String>> {
+ self.keys
+ .as_ref()
+ .map(|keys| get_recovery_key(&Key::try_from_slice(&keys.master_key)?, &keys.attributes))
+ .transpose()
+ }
+
+ pub async fn finish(&self, client: &AccountsClient) -> Result<AuthenticatedAccount> {
+ let keys = self
+ .keys
+ .as_ref()
+ .ok_or_else(|| Error::InvalidInput("Prepare signup keys first".into()))?;
+ self.authorize(client);
+ let remote = client.get_session_validity().await?;
+ match (remote.has_set_keys, remote.key_attributes) {
+ (false, None) => {
+ client
+ .set_user_key_attributes(keys.attributes.clone())
+ .await?
+ }
+ (true, Some(attributes)) => {
+ if attributes != keys.attributes {
+ return Err(Error::AccountAlreadyExists);
+ }
+ }
+ _ => return Err(Error::AccountAlreadyExists),
+ }
+ // The server may have committed a previous attempt whose response was lost.
+ if let Err(error) = complete_signup_srp(client, keys).await
+ && !matches!(&error, Error::Http(error) if error.status_code() == Some(400))
+ {
+ return Err(error);
+ }
+ let remote = client.get_srp_attributes(&self.email).await?;
+ remote.validate_setup(keys.srp_user_id, &keys.srp_salt, &keys.attributes, "signup")?;
+ Ok(AuthenticatedAccount {
+ user_id: self.user_id,
+ key_attributes: keys.attributes.clone(),
+ secrets: AccountSecrets {
+ token: self.token.clone(),
+ master_key: keys.master_key.clone(),
+ secret_key: keys.secret_key.clone(),
+ public_key: b64::decode(&keys.attributes.public_key)?,
+ },
+ recovery_key: self.recovery_key()?,
+ })
+ }
+}
+
+async fn complete_signup_srp(client: &AccountsClient, keys: &PreparedKeys) -> Result<()> {
+ let mut srp_session = SrpSession::new(
+ &keys.srp_user_id.to_string(),
+ &keys.srp_salt,
+ &keys.login_key,
+ )?;
+ let srp_a = b64::encode(&srp_session.public_a());
+ let response = client
+ .setup_srp(&SetupSrpRequest {
+ srp_user_id: keys.srp_user_id.to_string(),
+ srp_salt: b64::encode(&keys.srp_salt),
+ srp_verifier: b64::encode(&keys.srp_verifier),
+ srp_a,
+ })
+ .await?;
+ let srp_b = b64::decode(&response.srp_b)?;
+ let srp_m1 = b64::encode(&srp_session.compute_m1(&srp_b)?);
+ let complete = client
+ .complete_srp_setup(&response.setup_id, &srp_m1)
+ .await?;
+ srp_session.verify_m2(&b64::decode(&complete.srp_m2)?)?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/rust/crates/accounts/src/signup/tests.rs b/rust/crates/accounts/src/signup/tests.rs
new file mode 100644
index 0000000000..331181dcbb
--- /dev/null
+++ b/rust/crates/accounts/src/signup/tests.rs
@@ -0,0 +1,367 @@
+use super::*;
+use crate::{
+ AccountsClientConfig,
+ auth::SrpAttributes,
+ test_support::{SetupSrpPayload, SrpState, make_client, parse_request_body, srp_proofs},
+};
+use mockito::{Matcher, Server};
+use serde::Deserialize;
+use serde_json::json;
+use std::sync::{Arc, Mutex};
+
+fn verified() -> Signup {
+ Signup::verified(
+ "[email protected]".into(),
+ serde_json::from_value(json!({"id": 7, "token": b64::encode_url_safe(b"session-token")}))
+ .unwrap(),
+ )
+ .unwrap()
+}
+
+fn restore(signup: &Signup) -> Signup {
+ let bytes = serde_json::to_vec(signup).unwrap();
+ assert!(!String::from_utf8_lossy(&bytes).contains("signup-password"));
+ serde_json::from_slice(&bytes).unwrap()
+}
+
+#[tokio::test]
+async fn checkpoints_preserve_keys_and_reconcile_an_accepted_upload() {
+ let mut server = Server::new_async().await;
+ let client =
+ AccountsClient::new(AccountsClientConfig::new("io.ente.locker").with_origin(server.url()))
+ .unwrap();
+ let empty = server
+ .mock("GET", "/users/session-validity/v2")
+ .match_header(
+ "x-auth-token",
+ b64::encode_url_safe(b"session-token").as_str(),
+ )
+ .with_body(json!({"hasSetKeys": false}).to_string())
+ .create_async()
+ .await;
+ let verified = restore(&verified());
+ assert!(verified.recovery_key().unwrap().is_none());
+ assert!(matches!(
+ verified.finish(&client).await,
+ Err(Error::InvalidInput(_))
+ ));
+ let prepared = verified
+ .prepare_with_strength(
+ &client,
+ "signup-password",
+ KeyDerivationStrength::Interactive,
+ )
+ .await
+ .unwrap();
+ let recovered = restore(&prepared);
+ assert_eq!(
+ prepared.recovery_key().unwrap(),
+ recovered.recovery_key().unwrap()
+ );
+ let retried = recovered
+ .prepare(&client, "different-password")
+ .await
+ .unwrap();
+ assert!(serde_json::to_vec(&retried).unwrap() == serde_json::to_vec(&recovered).unwrap());
+ let keys = recovered.keys.as_ref().unwrap();
+ empty.assert_async().await;
+ empty.remove_async().await;
+ let accepted = server
+ .mock("GET", "/users/session-validity/v2")
+ .with_body(json!({"hasSetKeys": true, "keyAttributes": keys.attributes}).to_string())
+ .create_async()
+ .await;
+ let setup = server
+ .mock("POST", "/users/srp/setup")
+ .with_status(400)
+ .create_async()
+ .await;
+ let remote = server
+ .mock("GET", "/users/srp/attributes?email=new%40example.org")
+ .with_body(
+ json!({"attributes": {
+ "srpUserID": keys.srp_user_id, "srpSalt": b64::encode(&keys.srp_salt),
+ "kekSalt": keys.attributes.kek_salt, "memLimit": keys.attributes.mem_limit,
+ "opsLimit": keys.attributes.ops_limit,
+ }})
+ .to_string(),
+ )
+ .create_async()
+ .await;
+ let account = restore(&recovered).finish(&client).await.unwrap();
+ assert_eq!(account.secrets.master_key, keys.master_key);
+ assert_eq!(account.secrets.secret_key, keys.secret_key);
+ assert_eq!(account.recovery_key, recovered.recovery_key().unwrap());
+ accepted.assert_async().await;
+ accepted.remove_async().await;
+ let mut different = keys.attributes.clone();
+ different.public_key = b64::encode(&[9; 32]);
+ let conflict = server
+ .mock("GET", "/users/session-validity/v2")
+ .with_body(json!({"hasSetKeys": true, "keyAttributes": different}).to_string())
+ .expect(2)
+ .create_async()
+ .await;
+ assert!(matches!(
+ recovered.finish(&client).await,
+ Err(Error::AccountAlreadyExists)
+ ));
+ assert!(matches!(
+ verified.prepare(&client, "signup-password").await,
+ Err(Error::AccountAlreadyExists)
+ ));
+ setup.assert_async().await;
+ remote.assert_async().await;
+ conflict.assert_async().await;
+}
+
+#[cfg(feature = "museum")]
+#[test]
+fn checkpoints_resume_signup_against_museum() -> ente_test_support::TestResult {
+ use ente_test_support::{HARDCODED_OTT, HARDCODED_OTT_EMAIL_SUFFIX, Museum};
+
+ Museum::run_async(|endpoint| async move {
+ let client =
+ AccountsClient::new(AccountsClientConfig::new("io.ente.photos").with_origin(endpoint))?;
+ let email = format!(
+ "signup-resume-{}{HARDCODED_OTT_EMAIL_SUFFIX}",
+ Uuid::new_v4()
+ );
+ client.send_otp(&email, "signup").await?;
+ let response = client
+ .verify_email(&email, HARDCODED_OTT, Some("testAccount"))
+ .await?;
+ let verified = Signup::verified(email.clone(), response)?;
+ let prepared = restore(
+ &restore(&verified)
+ .prepare(&client, "signup-password")
+ .await?,
+ );
+ let keys = prepared.keys.as_ref().unwrap();
+ client
+ .set_user_key_attributes(keys.attributes.clone())
+ .await?;
+ let account = restore(&prepared).finish(&client).await?;
+ let resumed = restore(&prepared).finish(&client).await?;
+ assert_eq!(account.secrets.master_key, keys.master_key);
+ assert_eq!(resumed.secrets.master_key, account.secrets.master_key);
+ assert_eq!(resumed.recovery_key, account.recovery_key);
+ assert!(matches!(
+ verified.prepare(&client, "different-password").await,
+ Err(Error::AccountAlreadyExists)
+ ));
+ let attributes = client.get_srp_attributes(&email).await?;
+ let (response, _) = client
+ .login_with_srp("signup-password", &attributes)
+ .await?;
+ assert_eq!(response.id, resumed.user_id);
+ Ok(())
+ })
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct SetUserAttributesPayload {
+ key_attributes: KeyAttributes,
+}
+
+#[derive(Debug, Deserialize)]
+struct CompleteSrpSetupPayload {
+ #[serde(rename = "setupID")]
+ setup_id: String,
+ #[serde(rename = "srpM1")]
+ srp_m1: String,
+}
+
+#[tokio::test]
+async fn create_account_uploads_keys_and_completes_srp_setup() {
+ let email = "[email protected]";
+ let encoded_email = urlencoding::encode(email).into_owned();
+ let signup_token_bytes = b"signup-session-token";
+ let signup_token = b64::encode_url_safe(signup_token_bytes);
+ let signup_state = Arc::new(Mutex::new(SrpState::default()));
+
+ let mut server = Server::new_async().await;
+
+ 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(),
+ )
+ .expect(2)
+ .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::from(key_attributes.mem_limit);
+ let ops_limit = u64::from(key_attributes.ops_limit);
+
+ assert_eq!(mem_limit * ops_limit, 4_294_967_296);
+ assert!(
+ 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_b, client_proof, server_proof) = srp_proofs(&payload);
+ let setup_id = Uuid::new_v4();
+
+ let mut state = state.lock().unwrap();
+ let uploaded_key_attributes = state.uploaded_key_attributes.clone().unwrap();
+ state.pending_setup_id = Some(setup_id);
+ state.remote_srp_attributes = Some(SrpAttributes {
+ 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_client_proof = Some(client_proof);
+ state.pending_server_proof = Some(server_proof);
+
+ serde_json::json!({
+ "setupID": setup_id,
+ "srpB": b64::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 = b64::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": b64::encode(&state.pending_server_proof.take().unwrap()),
+ })
+ .to_string()
+ .into_bytes()
+ })
+ .create_async()
+ .await;
+
+ let state = Arc::clone(&signup_state);
+ let get_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::json!({
+ "attributes": state.remote_srp_attributes.as_ref().unwrap()
+ })
+ .to_string()
+ .into_bytes()
+ })
+ .create_async()
+ .await;
+
+ let client = make_client(server.url());
+
+ client.send_otp(email, "signup").await.unwrap();
+ let verification = client
+ .verify_email(email, "123456", Some("testAccount"))
+ .await
+ .unwrap();
+ let created = Signup::verified(email.into(), verification)
+ .unwrap()
+ .prepare(&client, "CorrectHorseBatteryStaple!")
+ .await
+ .unwrap()
+ .finish(&client)
+ .await
+ .unwrap();
+
+ assert_eq!(created.user_id, 99);
+ assert_eq!(created.secrets.token, signup_token_bytes);
+ assert!(created.recovery_key.is_some());
+
+ 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;
+ get_srp_attributes.assert_async().await;
+}
diff --git a/rust/crates/accounts/src/test_support.rs b/rust/crates/accounts/src/test_support.rs
new file mode 100644
index 0000000000..c2cdc8a9ba
--- /dev/null
+++ b/rust/crates/accounts/src/test_support.rs
@@ -0,0 +1,87 @@
+use ente_core::b64;
+use serde::{Deserialize, de::DeserializeOwned};
+use sha2::{Digest, Sha256};
+use srp::ServerG4096;
+use uuid::Uuid;
+
+use crate::{AccountsClient, AccountsClientConfig, KeyAttributes, auth::SrpAttributes};
+
+#[derive(Default)]
+pub(crate) struct SrpState {
+ pub(crate) uploaded_key_attributes: Option<KeyAttributes>,
+ pub(crate) remote_srp_attributes: Option<SrpAttributes>,
+ pub(crate) pending_setup_id: Option<Uuid>,
+ pub(crate) pending_client_proof: Option<Vec<u8>>,
+ pub(crate) pending_server_proof: Option<Vec<u8>>,
+}
+
+#[derive(Debug, Deserialize)]
+pub(crate) struct SetupSrpPayload {
+ #[serde(rename = "srpUserID")]
+ pub(crate) srp_user_id: String,
+ #[serde(rename = "srpSalt")]
+ pub(crate) srp_salt: String,
+ #[serde(rename = "srpVerifier")]
+ pub(crate) srp_verifier: String,
+ #[serde(rename = "srpA")]
+ pub(crate) srp_a: String,
+}
+
+pub(crate) fn parse_request_body<T>(request: &mockito::Request) -> T
+where
+ T: DeserializeOwned,
+{
+ serde_json::from_str(&request.utf8_lossy_body().unwrap()).unwrap()
+}
+
+pub(crate) fn make_client(origin: String) -> AccountsClient {
+ AccountsClient::new(
+ AccountsClientConfig::new("io.ente.photos")
+ .with_origin(origin)
+ .with_user_agent("ente-accounts-test"),
+ )
+ .unwrap()
+}
+
+pub(crate) fn srp_proofs(payload: &SetupSrpPayload) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
+ let srp_salt = b64::decode(&payload.srp_salt).unwrap();
+ let srp_verifier = b64::decode(&payload.srp_verifier).unwrap();
+ let srp_a = b64::decode(&payload.srp_a).unwrap();
+ let server = ServerG4096::<Sha256>::new();
+ let b_private = [0x33u8; 64];
+ let srp_b = pad(&server.compute_public_ephemeral(&b_private, &srp_verifier));
+ let verifier = server
+ .process_reply(
+ payload.srp_user_id.as_bytes(),
+ &srp_salt,
+ &b_private,
+ &srp_verifier,
+ &srp_a,
+ )
+ .unwrap();
+ let srp_a = pad(&srp_a);
+ let shared_secret = pad(verifier.key());
+
+ 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();
+ (srp_b, client_proof, server_proof)
+}
+
+fn pad(data: &[u8]) -> Vec<u8> {
+ if data.len() >= 512 {
+ return data.to_vec();
+ }
+ let mut padded = vec![0u8; 512 - data.len()];
+ padded.extend_from_slice(data);
+ padded
+}
diff --git a/rust/crates/accounts/src/types.rs b/rust/crates/accounts/src/types.rs
index 114f7fb070..18ab6b4292 100644
--- a/rust/crates/accounts/src/types.rs
+++ b/rust/crates/accounts/src/types.rs
@@ -2,6 +2,8 @@ use ente_core::urls::PRODUCTION_API_ORIGIN;
use serde::{Deserialize, Serialize};
use zeroize::ZeroizeOnDrop;
+use crate::auth::KeyAttributes;
+
pub const DEFAULT_API_ORIGIN: &str = PRODUCTION_API_ORIGIN;
#[derive(Clone)]
@@ -79,6 +81,24 @@ impl std::fmt::Debug for AccountSecrets {
}
}
+pub struct AuthenticatedAccount {
+ pub user_id: i64,
+ pub key_attributes: KeyAttributes,
+ pub secrets: AccountSecrets,
+ pub recovery_key: Option<String>,
+}
+
+impl std::fmt::Debug for AuthenticatedAccount {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("AuthenticatedAccount")
+ .field("user_id", &self.user_id)
+ .field("key_attributes", &self.key_attributes)
+ .field("secrets", &self.secrets)
+ .field("recovery_key", &"[REDACTED]")
+ .finish()
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/crates/accounts/tests/accounts.rs b/rust/crates/accounts/tests/accounts.rs
index 8ed8099a79..6449b05a39 100644
--- a/rust/crates/accounts/tests/accounts.rs
+++ b/rust/crates/accounts/tests/accounts.rs
@@ -4,72 +4,17 @@
use std::time::{SystemTime, UNIX_EPOCH};
use ente_accounts::{
- AccountsClient, AccountsClientConfig, AuthFlow, AuthFlowUi, CreateAccountParams, LoginParams,
- OtpPurpose, SecondFactorMethod, SetupTwoFactorParams, TotpPurpose,
+ AccountsClient, AccountsClientConfig, TwoFactorSetup,
+ login::{LoginFlow, LoginStep},
+ signup::Signup,
};
-use ente_core::crypto::SecretVec;
use ente_test_support::{HARDCODED_OTT, HARDCODED_OTT_EMAIL_SUFFIX, Museum, TestResult};
use hmac::{Hmac, KeyInit, Mac};
use sha1::Sha1;
use uuid::Uuid;
-use zeroize::Zeroizing;
type HmacSha1 = Hmac<Sha1>;
-struct TestUi {
- totp_secret: Option<String>,
-}
-
-impl AuthFlowUi for TestUi {
- fn read_email_otp(
- &mut self,
- _email: &str,
- _purpose: OtpPurpose,
- _resent: bool,
- ) -> ente_accounts::Result<String> {
- Ok(HARDCODED_OTT.into())
- }
-
- fn read_totp_code(&mut self, _purpose: TotpPurpose) -> ente_accounts::Result<String> {
- self.totp_secret
- .as_deref()
- .map(current_totp)
- .ok_or_else(|| ente_accounts::Error::InvalidInput("TOTP secret missing".into()))
- }
-
- fn report_retryable_error(&mut self, _message: &str) -> ente_accounts::Result<()> {
- Ok(())
- }
-
- fn choose_second_factor(
- &mut self,
- _methods: &[SecondFactorMethod],
- ) -> ente_accounts::Result<SecondFactorMethod> {
- Ok(SecondFactorMethod::Totp)
- }
-
- fn present_passkey_verification(&mut self, _url: &str) -> ente_accounts::Result<()> {
- Err(ente_accounts::Error::InvalidInput(
- "Passkey flow not expected".into(),
- ))
- }
-
- fn wait_for_passkey_verification(&mut self) -> ente_accounts::Result<()> {
- Err(ente_accounts::Error::InvalidInput(
- "Passkey flow not expected".into(),
- ))
- }
-
- fn present_totp_secret(
- &mut self,
- secret_code: &str,
- _qr_code: &str,
- ) -> ente_accounts::Result<()> {
- self.totp_secret = Some(secret_code.to_string());
- Ok(())
- }
-}
-
#[test]
fn accounts() -> TestResult {
Museum::run_async(run)
@@ -83,36 +28,39 @@ async fn run(endpoint: String) -> TestResult {
);
let password = format!("Accounts-{}!", Uuid::new_v4().simple());
let client = accounts_client(endpoint);
- let mut ui = TestUi { totp_secret: None };
- let mut flow = AuthFlow::new(&client, &mut ui);
- let created = flow
- .create_account(CreateAccountParams {
- email: email.clone(),
- password: Zeroizing::new(password.clone()),
- source: Some("testAccount".into()),
- })
- .await
- .unwrap();
-
- let mut ui = TestUi { totp_secret: None };
- let setup = AuthFlow::new(&client, &mut ui)
- .setup_two_factor(SetupTwoFactorParams {
- master_key: SecretVec::new(created.secrets.master_key.clone()),
- key_attributes: Some(created.key_attributes.clone()),
- })
- .await
- .unwrap();
-
- let mut ui = TestUi {
- totp_secret: Some(setup.secret_code),
+ client.send_otp(&email, "signup").await?;
+ let response = client
+ .verify_email(&email, HARDCODED_OTT, Some("testAccount"))
+ .await?;
+ let created = Signup::verified(email.clone(), response)?
+ .prepare(&client, &password)
+ .await?
+ .finish(&client)
+ .await?;
+ let setup = TwoFactorSetup::start(
+ &client,
+ &created.secrets.master_key,
+ &created.key_attributes,
+ )
+ .await?;
+ setup
+ .enable(&client, &current_totp(&setup.secret_code))
+ .await?;
+
+ let login_client = accounts_client(endpoint);
+ let (mut flow, mut step) = LoginFlow::start(&login_client, email.clone()).await?;
+ let login = loop {
+ step = match step {
+ LoginStep::EmailCode => flow.submit_code(&login_client, HARDCODED_OTT).await?,
+ LoginStep::Password => flow.submit_password(&login_client, &password).await?,
+ LoginStep::SecondFactor { totp: true, .. } => {
+ flow.submit_code(&login_client, &current_totp(&setup.secret_code))
+ .await?
+ }
+ LoginStep::SecondFactor { .. } => panic!("expected authenticator verification"),
+ LoginStep::Complete(account) => break account,
+ };
};
- let login = AuthFlow::new(&accounts_client(endpoint), &mut ui)
- .login(LoginParams {
- email: email.clone(),
- password: Zeroizing::new(password),
- })
- .await
- .unwrap();
assert_eq!(login.user_id, created.user_id);
assert_eq!(login.secrets.master_key, created.secrets.master_key);
assert_eq!(client.email().await.unwrap(), email);
diff --git a/rust/crates/legacy/tests/support/auth.rs b/rust/crates/legacy/tests/support/auth.rs
index cdc9b030e9..e267f00a2a 100644
--- a/rust/crates/legacy/tests/support/auth.rs
+++ b/rust/crates/legacy/tests/support/auth.rs
@@ -2,116 +2,35 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use ente_accounts::auth::recovery_key_from_mnemonic_or_hex;
use ente_accounts::{
- AccountsClient, AccountsClientConfig, AuthFlow, AuthFlowUi, AuthenticatedAccount,
- CreateAccountParams, LoginParams, OtpPurpose, SecondFactorMethod, SetupTwoFactorParams,
- TotpPurpose,
+ AccountsClient, AccountsClientConfig, AuthenticatedAccount, TwoFactorSetup,
+ login::{LoginFlow, LoginStep},
+ signup::Signup,
};
use ente_core::b64;
-use ente_core::crypto::SecretVec;
use ente_test_support::HARDCODED_OTT;
pub use ente_test_support::account_fixture::{
TestAccount, create_account as create_fixture_account,
};
use hmac::{Hmac, KeyInit, Mac};
use sha1::Sha1;
-use zeroize::Zeroizing;
use crate::CLIENT_PACKAGE;
type HmacSha1 = Hmac<Sha1>;
-struct TestUi {
- otp: String,
- totp_secret: Option<String>,
- allow_totp: bool,
-}
-
-impl TestUi {
- fn otp_only() -> Self {
- Self {
- otp: HARDCODED_OTT.into(),
- totp_secret: None,
- allow_totp: false,
- }
- }
-
- fn with_totp(secret: Option<String>) -> Self {
- Self {
- otp: HARDCODED_OTT.into(),
- totp_secret: secret,
- allow_totp: true,
- }
- }
-}
-
-impl AuthFlowUi for TestUi {
- fn read_email_otp(
- &mut self,
- _email: &str,
- _purpose: OtpPurpose,
- _resent: bool,
- ) -> ente_accounts::Result<String> {
- Ok(self.otp.clone())
- }
-
- fn read_totp_code(&mut self, _purpose: TotpPurpose) -> ente_accounts::Result<String> {
- if !self.allow_totp {
- return Err(ente_accounts::Error::InvalidInput(
- "TOTP was requested unexpectedly in this e2e flow".into(),
- ));
- }
-
- let secret = self.totp_secret.as_deref().ok_or_else(|| {
- ente_accounts::Error::InvalidInput("No TOTP secret captured for rust e2e flow".into())
- })?;
- Ok(current_totp(secret))
- }
-
- fn report_retryable_error(&mut self, _message: &str) -> ente_accounts::Result<()> {
- Ok(())
- }
-
- fn choose_second_factor(
- &mut self,
- _methods: &[SecondFactorMethod],
- ) -> ente_accounts::Result<SecondFactorMethod> {
- Ok(SecondFactorMethod::Totp)
- }
-
- fn present_passkey_verification(&mut self, _url: &str) -> ente_accounts::Result<()> {
- Err(ente_accounts::Error::InvalidInput(
- "Passkey flow not expected in rust e2e tests".into(),
- ))
- }
-
- fn wait_for_passkey_verification(&mut self) -> ente_accounts::Result<()> {
- Err(ente_accounts::Error::InvalidInput(
- "Passkey flow not expected in rust e2e tests".into(),
- ))
- }
-
- fn present_totp_secret(
- &mut self,
- secret_code: &str,
- _qr_code: &str,
- ) -> ente_accounts::Result<()> {
- self.totp_secret = Some(secret_code.to_string());
- Ok(())
- }
-}
-
pub async fn create_account(endpoint: &str, email: String, password: String) -> TestAccount {
let client = accounts_client(endpoint).unwrap();
- let mut ui = TestUi::otp_only();
let authenticated = tokio::time::timeout(Duration::from_secs(180), async {
- let mut flow = AuthFlow::new(&client, &mut ui);
- flow.create_account(CreateAccountParams {
- email: email.clone(),
- password: Zeroizing::new(password.clone()),
- source: Some("testAccount".into()),
- })
- .await
+ client.send_otp(&email, "signup").await?;
+ let response = client
+ .verify_email(&email, HARDCODED_OTT, Some("testAccount"))
+ .await?;
+ Signup::verified(email.clone(), response)?
+ .prepare(&client, &password)
+ .await?
+ .finish(&client)
+ .await
})
.await
.expect("signup timed out")
@@ -137,26 +56,23 @@ pub async fn login_without_totp(
endpoint: &str,
email: &str,
password: &str,
-) -> ente_accounts::Result<AuthenticatedAccount> {
- let mut ui = TestUi::otp_only();
- login_with_ui(endpoint, email, password, &mut ui).await
-}
-
-async fn login_with_ui<U: AuthFlowUi>(
- endpoint: &str,
- email: &str,
- password: &str,
- ui: &mut U,
) -> ente_accounts::Result<AuthenticatedAccount> {
let client = accounts_client(endpoint)?;
tokio::time::timeout(Duration::from_secs(90), async {
- let mut flow = AuthFlow::new(&client, ui);
- flow.login(LoginParams {
- email: email.to_string(),
- password: Zeroizing::new(password.to_string()),
- })
- .await
+ let (mut flow, mut step) = LoginFlow::start(&client, email.into()).await?;
+ loop {
+ step = match step {
+ LoginStep::EmailCode => flow.submit_code(&client, HARDCODED_OTT).await?,
+ LoginStep::Password => flow.submit_password(&client, password).await?,
+ LoginStep::SecondFactor { .. } => {
+ return Err(ente_accounts::Error::InvalidInput(
+ "Second factor was requested unexpectedly in this e2e flow".into(),
+ ));
+ }
+ LoginStep::Complete(account) => return Ok(*account),
+ };
+ }
})
.await
.expect("login timed out")
@@ -165,21 +81,20 @@ async fn login_with_ui<U: AuthFlowUi>(
pub async fn enable_totp(endpoint: &str, account: &TestAccount) -> String {
let client = accounts_client(endpoint).unwrap();
client.set_auth_token(Some(account.auth_token.clone()));
- let mut ui = TestUi::with_totp(None);
let result = tokio::time::timeout(Duration::from_secs(60), async {
- let mut flow = AuthFlow::new(&client, &mut ui);
- flow.setup_two_factor(SetupTwoFactorParams {
- master_key: SecretVec::new(account.master_key.clone()),
- key_attributes: Some(account.key_attributes.clone()),
- })
- .await
+ let setup =
+ TwoFactorSetup::start(&client, &account.master_key, &account.key_attributes).await?;
+ setup
+ .enable(&client, &current_totp(&setup.secret_code))
+ .await?;
+ Ok::<_, ente_accounts::Error>(setup)
})
.await
.expect("two-factor setup timed out")
.expect("two-factor setup failed");
- result.secret_code
+ result.secret_code.clone()
}
pub async fn fetch_two_factor_status(