π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Map auth HTTP statuses to typed errors in the accounts client
Manav Rathi690a36d27958
diff --git a/rust/apps/cli/src/commands/account.rs b/rust/apps/cli/src/commands/account.rsindex be3b135b69..7e5d6b9734 100644--- a/rust/apps/cli/src/commands/account.rs+++ b/rust/apps/cli/src/commands/account.rs@@ -248,7 +248,7 @@ async fn add_account(storage: &Storage, args: AddArgs) -> Result<()> {.await{Ok(authenticated) => break authenticated,- Err(error) if interactive_password && is_retryable_password_error(&error) => {+ Err(ente_accounts::Error::IncorrectPassword) if interactive_password => {println!("\nIncorrect password. Try again.");password = Zeroizing::new(prompt_password(None, "Re-enter your password")?);}@@ -537,10 +537,6 @@ fn new_accounts_client(endpoint: &str, app: App) -> Result<AccountsClient> {.map_err(Error::from)}-fn is_retryable_password_error(error: &ente_accounts::Error) -> bool {- matches!(error, ente_accounts::Error::IncorrectPassword) || error.is_http_status(&[401])-}-fn can_open_automatically(url: &str) -> bool {url.split_once("://").is_some_and(|(scheme, _)| {scheme.eq_ignore_ascii_case("https") || scheme.eq_ignore_ascii_case("http")diff --git a/rust/bindings/frb/ente-rust/src/api/contacts.rs b/rust/bindings/frb/ente-rust/src/api/contacts.rsindex 9949ec5eee..cba55d7556 100644--- a/rust/bindings/frb/ente-rust/src/api/contacts.rs+++ b/rust/bindings/frb/ente-rust/src/api/contacts.rs@@ -6,7 +6,7 @@ use flutter_rust_bridge::frb;#[frb]pub enum ContactsError {Network { message: String },- Http { status: u16, message: String },+ Http { message: String },Parse { message: String },Crypto { message: String },Auth { message: String },@@ -23,10 +23,7 @@ impl From<ente_contacts::Error> for ContactsError {let message = ente_core::error::chain(&e);match e.kind() {K::Network => Self::Network { message },- K::Http => Self::Http {- status: e.status().unwrap_or_default(),- message,- },+ K::Http => Self::Http { message },K::Parse => Self::Parse { message },K::Crypto => Self::Crypto { message },K::Auth => Self::Auth { message },diff --git a/rust/bindings/wasm/ente-wasm/src/auth.rs b/rust/bindings/wasm/ente-wasm/src/auth.rsindex bf39bc9df4..79f16721c2 100644--- a/rust/bindings/wasm/ente-wasm/src/auth.rs+++ b/rust/bindings/wasm/ente-wasm/src/auth.rs@@ -39,9 +39,14 @@ impl From<ente_accounts::Error> for AccountsError {E::InvalidKey(_) => "invalid_key",E::Srp(_) => "srp",E::InvalidInput(_) => "invalid_input",+ E::IncorrectEmailVerificationCode => "incorrect_email_verification_code",+ E::EmailVerificationCodeExpired => "email_verification_code_expired",E::EmailVerificationRateLimited => "email_verification_rate_limited",+ E::IncorrectTotp => "incorrect_totp",E::TotpRateLimited => "totp_rate_limited",E::SecondFactorSessionExpired => "second_factor_session_expired",+ E::PasskeyVerificationPending => "passkey_verification_pending",+ E::SessionInvalid => "session_invalid",E::MissingKeyAttributes => "missing_key_attributes",E::AccountAlreadyExists => "account_already_exists",E::Protocol(_) => "protocol",diff --git a/rust/bindings/wasm/ente-wasm/src/contacts.rs b/rust/bindings/wasm/ente-wasm/src/contacts.rsindex 060255b400..0c67247157 100644--- a/rust/bindings/wasm/ente-wasm/src/contacts.rs+++ b/rust/bindings/wasm/ente-wasm/src/contacts.rs@@ -12,7 +12,7 @@ use wasm_bindgen::prelude::*;#[serde(tag = "kind", rename_all = "snake_case")]pub enum ContactsError {Network { message: String },- Http { status: u16, message: String },+ Http { message: String },Parse { message: String },Crypto { message: String },Auth { message: String },@@ -47,10 +47,7 @@ impl From<ente_contacts::Error> for ContactsError {let message = ente_core::error::chain(&e);match e.kind() {K::Network => Self::Network { message },- K::Http => Self::Http {- status: e.status().unwrap_or_default(),- message,- },+ K::Http => Self::Http { message },K::Parse => Self::Parse { message },K::Crypto => Self::Crypto { message },K::Auth => Self::Auth { message },diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rsindex 23a8033613..f925f0b635 100644--- a/rust/crates/accounts/src/client.rs+++ b/rust/crates/accounts/src/client.rs@@ -163,7 +163,11 @@ impl AccountsClient {.send().await?.error_for_code()- .await?+ .await+ .map_err(|error| match error.status_code() {+ Some(401) => Error::IncorrectPassword,+ _ => error.into(),+ })?.json().await?)}@@ -204,7 +208,13 @@ impl AccountsClient {.send().await?.error_for_code()- .await?+ .await+ .map_err(|error| match error.status_code() {+ Some(400 | 401) => Error::IncorrectEmailVerificationCode,+ Some(410) => Error::EmailVerificationCodeExpired,+ Some(429) => Error::EmailVerificationRateLimited,+ _ => error.into(),+ })?.json().await?)}@@ -291,7 +301,7 @@ impl AccountsClient {}pub async fn get_session_validity(&self) -> Result<SessionValidityResponse> {- Ok(http::retry(|| async {+ http::retry(|| async {self.api.get("/users/session-validity/v2").send()@@ -301,7 +311,11 @@ impl AccountsClient {.json().await})- .await?)+ .await+ .map_err(|error| match error.status_code() {+ Some(401) => Error::SessionInvalid,+ _ => error.into(),+ })}pub async fn change_email(&self, email: &str, ott: &str) -> Result<()> {@@ -367,7 +381,11 @@ impl AccountsClient {.send().await?.error_for_code()- .await?;+ .await+ .map_err(|error| match error.status_code() {+ Some(400 | 401) => Error::IncorrectTotp,+ _ => error.into(),+ })?;Ok(())}@@ -398,7 +416,13 @@ impl AccountsClient {.send().await?.error_for_code()- .await?+ .await+ .map_err(|error| match error.status_code() {+ Some(400 | 401) => Error::IncorrectTotp,+ Some(404 | 410) => Error::SecondFactorSessionExpired,+ Some(429) => Error::TotpRateLimited,+ _ => error.into(),+ })?.json().await?)}@@ -481,7 +505,7 @@ impl AccountsClient {pub async fn check_passkey_status(&self, session_id: &str) -> Result<AuthResponse> {let query = [("sessionID", session_id.to_string())];- Ok(http::retry(|| async {+ http::retry(|| async {self.api.get("/users/two-factor/passkeys/get-token").query(&query)@@ -492,7 +516,12 @@ impl AccountsClient {.json().await})- .await?)+ .await+ .map_err(|error| match error.status_code() {+ Some(400) => Error::PasskeyVerificationPending,+ Some(404 | 410) => Error::SecondFactorSessionExpired,+ _ => error.into(),+ })}pub async fn get_accounts_token(&self) -> Result<AccountsTokenResponse> {@@ -566,7 +595,7 @@ mod tests {.await.unwrap_err();- assert_eq!(error.status_code(), Some(500));+ assert!(matches!(&error, Error::Http(e) if e.status_code() == Some(500)));verify.assert_async().await;}@@ -609,7 +638,7 @@ mod tests {.await.unwrap_err();- assert_eq!(error.status_code(), Some(429));+ assert!(matches!(error, Error::EmailVerificationRateLimited));verify.assert_async().await;}}diff --git a/rust/crates/accounts/src/error.rs b/rust/crates/accounts/src/error.rsindex 4c48a52063..edd50dd09b 100644--- a/rust/crates/accounts/src/error.rs+++ b/rust/crates/accounts/src/error.rs@@ -41,15 +41,30 @@ pub enum Error {#[error("Invalid input: {0}")]InvalidInput(String),+ #[error("Incorrect email verification code")]+ IncorrectEmailVerificationCode,++ #[error("Email verification code has expired")]+ EmailVerificationCodeExpired,+#[error("Too many incorrect email verification attempts. Please wait and request a new code.")]EmailVerificationRateLimited,+ #[error("Incorrect TOTP code")]+ IncorrectTotp,+#[error("Too many incorrect TOTP attempts. Please restart login.")]TotpRateLimited,#[error("Second factor session expired. Please restart login.")]SecondFactorSessionExpired,+ #[error("Passkey verification is pending")]+ PasskeyVerificationPending,++ #[error("Session is invalid")]+ SessionInvalid,+#[error("Account key attributes are not available")]MissingKeyAttributes,@@ -65,20 +80,6 @@ pub enum Error {Ui(Box<dyn std::error::Error + Send + Sync>),}-impl Error {- pub fn status_code(&self) -> Option<u16> {- match self {- Error::Http(error) => error.status_code(),- _ => None,- }- }-- pub fn is_http_status(&self, statuses: &[u16]) -> bool {- self.status_code()- .is_some_and(|status| statuses.contains(&status))- }-}-impl From<b64::DecodeError> for Error {fn from(err: b64::DecodeError) -> Self {Error::Decode(err.to_string())diff --git a/rust/crates/accounts/src/flow.rs b/rust/crates/accounts/src/flow.rsindex 810af7075f..5b4f4d8ab5 100644--- a/rust/crates/accounts/src/flow.rs+++ b/rust/crates/accounts/src/flow.rs@@ -316,7 +316,7 @@ whererecovery_key,});}- Err(error) if error.is_http_status(&[400, 401]) => {+ Err(Error::IncorrectTotp) => {self.ui.report_retryable_error("Incorrect TOTP code. Enter the current code from your authenticator app and try again.",)?;@@ -397,7 +397,7 @@ where) -> Result<SessionValidity> {let remote = match self.client.get_session_validity().await {Ok(remote) => remote,- Err(error) if error.is_http_status(&[401]) => return Ok(SessionValidity::Invalid),+ Err(Error::SessionInvalid) => return Ok(SessionValidity::Invalid),Err(error) => return Err(error),};@@ -650,15 +650,12 @@ wherelet 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) if error.is_http_status(&[400, 401]) => {+ Err(Error::IncorrectEmailVerificationCode) => {self.ui.report_retryable_error("Incorrect email verification code. Try again.")?;resent = false;}- Err(error) if error.is_http_status(&[429]) => {- return Err(Error::EmailVerificationRateLimited);- }- Err(error) if error.is_http_status(&[410]) => {+ Err(Error::EmailVerificationCodeExpired) => {self.client.send_otp(email, purpose.as_api_purpose()).await?;@@ -697,16 +694,10 @@ wherelet code = self.ui.read_totp_code(TotpPurpose::Login)?;match self.client.verify_totp(session_id, &code).await {Ok(response) => return Ok(response),- Err(error) if error.is_http_status(&[400, 401]) => {+ Err(Error::IncorrectTotp) => {self.ui.report_retryable_error("Incorrect TOTP code. Try again.")?;}- Err(error) if error.is_http_status(&[429]) => {- return Err(Error::TotpRateLimited);- }- Err(error) if error.is_http_status(&[404, 410]) => {- return Err(Error::SecondFactorSessionExpired);- }Err(error) => return Err(error),}}@@ -738,10 +729,7 @@ whereself.ui.wait_for_passkey_verification()?;match self.client.check_passkey_status(passkey_session_id).await {Ok(result) => return Ok(result),- Err(error) if error.is_http_status(&[400]) => {}- Err(error) if error.is_http_status(&[404, 410]) => {- return Err(Error::SecondFactorSessionExpired);- }+ Err(Error::PasskeyVerificationPending) => {}Err(error) => return Err(error),}}diff --git a/rust/crates/contacts/src/error.rs b/rust/crates/contacts/src/error.rsindex 9ea5346598..af31b20240 100644--- a/rust/crates/contacts/src/error.rs+++ b/rust/crates/contacts/src/error.rs@@ -61,13 +61,6 @@ impl Error {Error::ActiveRecoverySession => ErrorKind::ActiveRecoverySession,}}-- pub fn status(&self) -> Option<u16> {- match self {- Error::Http(error) => error.status_code(),- _ => None,- }- }}pub type Result<T> = std::result::Result<T, Error>;diff --git a/rust/crates/contacts/tests/contacts.rs b/rust/crates/contacts/tests/contacts.rsindex a9733bf979..e0dbfdb81a 100644--- a/rust/crates/contacts/tests/contacts.rs+++ b/rust/crates/contacts/tests/contacts.rs@@ -276,7 +276,6 @@ async fn run_legacy_reset_stage(endpoint: &str, pair: &mut legacy::LegacyPair) {match auth::login_without_totp(endpoint, &pair.owner.email, &previous_password).await {Err(ente_accounts::Error::IncorrectPassword) => {}- Err(error) if error.is_http_status(&[401]) => {}other => panic!("expected old password login to fail, got {other:?}"),}@@ -636,7 +635,6 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitOmatch auth::login_without_totp(endpoint, &owner.owner.email, &previous_password).await {Err(ente_accounts::Error::IncorrectPassword) => {}- Err(error) if error.is_http_status(&[401]) => {}other => panic!("expected old legacy kit password login to fail, got {other:?}"),}