π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[rust] Stop CLI authenticator setup retries after server rejection (#14302)
Manav Rathi3611fee25755
diff --git a/rust/apps/cli/tests/cli/account.rs b/rust/apps/cli/tests/cli/account.rsindex e77f9059f1..b9dce3d14e 100644--- a/rust/apps/cli/tests/cli/account.rs+++ b/rust/apps/cli/tests/cli/account.rs@@ -633,21 +633,32 @@ fn creation_enrollment_and_login_across_processes() -> ente_test_support::TestRe#[cfg(all(unix, feature = "museum"))]#[test]fn interactive_creation_password_retry_and_enrollment() -> ente_test_support::TestResult {- ente_test_support::Museum::run_async(|origin| async move {+ use std::io::{BufRead, BufReader};++ ente_test_support::Museum::run(|museum| {let home = TestHome::new();let email = format!("cli-interactive-{}@example.org", uuid::Uuid::new_v4());- success(- Command::new("python3")+ success({+ let mut child = Command::new("python3").arg(concat!(env!("CARGO_MANIFEST_DIR"),"/tests/cli/account_prompt.py")).arg(cli_binary())- .args([&origin, &email])+ .args([museum.endpoint(), &email]).env("ENTE_CLI_HOME", home.dir.path()).env("ENTE_CLI_VAULT_KEY", b64::encode(home.key.as_bytes()))- .output()?,- );+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()?;+ let mut ready = String::new();+ BufReader::new(child.stdout.take().unwrap()).read_line(&mut ready)?;+ assert_eq!(ready.trim(), "expire");+ museum.execute_sql("UPDATE temp_two_factor SET expiration_time = 1")?;+ writeln!(child.stdin.take().unwrap(), "expired")?;+ child.wait_with_output()?+ });assert_eq!(home.json(&["account", "view"])["name"], email);assert_eq!(home.json(&["account", "totp", "status"]),diff --git a/rust/apps/cli/tests/cli/account_prompt.py b/rust/apps/cli/tests/cli/account_prompt.pyindex 91500ae655..2f7a78bdd8 100644--- a/rust/apps/cli/tests/cli/account_prompt.py+++ b/rust/apps/cli/tests/cli/account_prompt.py@@ -15,7 +15,7 @@ import timebinary, origin, email = sys.argv[1:4]-def run(args, replies):+def run(args, replies, expected_exit=0):pid, fd = pty.fork()if pid == 0:os.execv(binary, args)@@ -42,7 +42,7 @@ def run(args, replies):while time.monotonic() < deadline:done, status = os.waitpid(pid, os.WNOHANG)if done:- assert os.waitstatus_to_exitcode(status) == 0, output.decode(errors="replace")+ assert os.waitstatus_to_exitcode(status) == expected_exit, output.decode(errors="replace")returnif select.select([fd], [], [], 0.1)[0]:try:@@ -72,17 +72,22 @@ def create(expect, send):expect(b"Created ")-def enable(expect, send):+def enable(expect, send, expire=False):text = expect(b"Authenticator code:")secret = re.search(rb"authenticator: ([A-Z2-7]+)", text)[1]send(b"invalid", True)expect(b"Code not accepted. Check the code and your computer's date and time, then try again.")expect(b"Authenticator code:")+ if expire:+ print("expire", flush=True)+ assert sys.stdin.readline().strip() == "expired"key = base64.b32decode(secret + b"=" * (-len(secret) % 8))digest = hmac.new(key, (int(time.time()) // 30).to_bytes(8, "big"), hashlib.sha1).digest()offset = digest[-1] & 15code = (int.from_bytes(digest[offset:offset + 4], "big") & 0x7fffffff) % 1000000send(f"{code:06d}".encode(), True)+ if expire:+ expect(b"401")def login(expect, send, email_mfa):@@ -127,4 +132,6 @@ for email_mfa in [True, False]:)run([binary, "account", "login", "--app", "photos", "--email", email],lambda expect, send: login(expect, send, email_mfa))+run([binary, "account", "totp", "enable"],+ lambda expect, send: enable(expect, send, expire=True), expected_exit=1)run([binary, "account", "totp", "enable"], enable)diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rsindex 1de64cc55c..1910fc9a59 100644--- a/rust/crates/accounts/src/client.rs+++ b/rust/crates/accounts/src/client.rs@@ -420,19 +420,14 @@ impl AccountsClient {}pub async fn enable_two_factor(&self, request: &EnableTwoFactorRequest) -> Result<()> {- match self- .api+ self.api.post("/users/two-factor/enable").json(request).send().await?.error_for_code()- .await- {- Ok(_) => Ok(()),- Err(error) if error.status_code() == Some(401) => Err(Error::IncorrectTotp),- Err(error) => Err(error.into()),- }+ .await?;+ Ok(())}pub async fn disable_two_factor(&self) -> Result<()> {diff --git a/rust/crates/accounts/src/lifecycle.rs b/rust/crates/accounts/src/lifecycle.rsindex 0e414a9a4b..2e4c978960 100644--- a/rust/crates/accounts/src/lifecycle.rs+++ b/rust/crates/accounts/src/lifecycle.rs@@ -120,7 +120,8 @@ impl TwoFactorSetup {.map_err(|_| Error::InvalidInput("system clock is before the Unix epoch".into()))?.as_secs();verify_totp(&self.secret_code, code, time)?;- enable_two_factor(client, &self.secret_code, &self.recovery_key, code).await+ let request = encrypt_two_factor_secret(&self.secret_code, &self.recovery_key, code)?;+ client.enable_two_factor(&request).await}}@@ -282,7 +283,10 @@ pub async fn enable_two_factor(code: &str,) -> Result<()> {let request = encrypt_two_factor_secret(secret, recovery_key, code)?;- client.enable_two_factor(&request).await+ match client.enable_two_factor(&request).await {+ Err(Error::Http(error)) if error.status_code() == Some(401) => Err(Error::IncorrectTotp),+ result => result,+ }}pub async fn passkey_management_url(client: &AccountsClient, recovery_key: &str) -> Result<String> {diff --git a/rust/crates/accounts/src/lifecycle/tests.rs b/rust/crates/accounts/src/lifecycle/tests.rsindex d2b1a93a8c..45ffb56de6 100644--- a/rust/crates/accounts/src/lifecycle/tests.rs+++ b/rust/crates/accounts/src/lifecycle/tests.rs@@ -87,19 +87,31 @@ async fn setup_two_factor_encrypts_secret_with_recovery_key() {result.enable(&client, "invalid").await,Err(Error::IncorrectTotp)));- result- .enable(- &client,- &ente_test_support::account_fixture::current_totp(&result.secret_code).unwrap(),- )- .await- .unwrap();+ let code = ente_test_support::account_fixture::current_totp(&result.secret_code).unwrap();+ result.enable(&client, &code).await.unwrap();assert_eq!(result.secret_code, secret_code);assert_eq!(result.recovery_key, recovery_key);setup.assert_async().await;enable.assert_async().await;+ enable.remove_async().await;++ let rejected = server+ .mock("POST", "/users/two-factor/enable")+ .with_status(401)+ .expect(2)+ .create_async()+ .await;+ assert!(matches!(+ result.enable(&client, &code).await,+ Err(Error::Http(error)) if error.status_code() == Some(401)+ ));+ assert!(matches!(+ enable_two_factor(&client, secret_code, &recovery_key, &code).await,+ Err(Error::IncorrectTotp)+ ));+ rejected.assert_async().await;}#[test]