π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Separate password updates from SRP metadata refresh
Neeraj Gupta19cb761d859f
diff --git a/mobile/apps/photos/lib/services/account/user_service.dart b/mobile/apps/photos/lib/services/account/user_service.dartindex f408bae440..f679c56cae 100644--- a/mobile/apps/photos/lib/services/account/user_service.dart+++ b/mobile/apps/photos/lib/services/account/user_service.dart@@ -691,7 +691,6 @@ class UserService {final attributes = await _withAccountsClient((client) => client.changePassword(token: _config.getToken()!,- email: _config.getEmail()!,password: password,masterKey: _config.getKey()!,keyAttributes: accountsKeyAttributes(diff --git a/mobile/packages/accounts/lib/services/user_service.dart b/mobile/packages/accounts/lib/services/user_service.dartindex e5d2d3c25c..faec884cab 100644--- a/mobile/packages/accounts/lib/services/user_service.dart+++ b/mobile/packages/accounts/lib/services/user_service.dart@@ -668,7 +668,6 @@ class UserService {final attributes = await _withAccountsClient((client) => client.changePassword(token: _config.getToken()!,- email: _config.getEmail()!,password: password,masterKey: _config.getKey()!,keyAttributes: accountsKeyAttributes(diff --git a/rust/bindings/frb/lib/src/accounts/types.rs b/rust/bindings/frb/lib/src/accounts/types.rsindex 7655dc5115..632133a349 100644--- a/rust/bindings/frb/lib/src/accounts/types.rs+++ b/rust/bindings/frb/lib/src/accounts/types.rs@@ -244,24 +244,22 @@ impl AccountsClient {pub async fn change_password(&self,token: String,- email: String,password: String,master_key: Vec<u8>,key_attributes: KeyAttributes,log_out_other_devices: bool,) -> Result<KeyAttributes, AccountsError> {- let result = lifecycle::change_password(+ lifecycle::change_password(&self.0.with_auth_token(token),lifecycle::ChangePasswordParams {- email,password: password.into(),master_key: SecretVec::new(master_key),key_attributes,log_out_other_devices,},)- .await?;- Ok(result.key_attributes)+ .await+ .map_err(Into::into)}pub async fn setup_two_factor(&self, token: String) -> Result<TwoFactorSecret, AccountsError> {diff --git a/rust/bindings/wasm/lib/src/accounts/client.rs b/rust/bindings/wasm/lib/src/accounts/client.rsindex 56d55a7960..96b5e4c9e9 100644--- a/rust/bindings/wasm/lib/src/accounts/client.rs+++ b/rust/bindings/wasm/lib/src/accounts/client.rs@@ -265,7 +265,6 @@ pub fn recover_account(pub async fn change_password(client: &AccountsClient,token: String,- email: String,password: String,master_key: &str,#[wasm_bindgen(unchecked_param_type = "unknown")] key_attributes: JsValue,@@ -273,7 +272,6 @@ pub async fn change_password(let result = lifecycle::change_password(&client.0.with_auth_token(token),lifecycle::ChangePasswordParams {- email,password: password.into(),master_key: SecretVec::new(decode(master_key)?),key_attributes: swb::from_value(key_attributes)?,diff --git a/rust/crates/accounts/src/lib.rs b/rust/crates/accounts/src/lib.rsindex c6be7ef649..0c6c65cc0e 100644--- a/rust/crates/accounts/src/lib.rs+++ b/rust/crates/accounts/src/lib.rs@@ -17,7 +17,7 @@ pub use auth::KeyAttributes;pub use client::AccountsClient;pub use error::{Error, Result};pub use lifecycle::{- ChangePasswordParams, ChangePasswordResult, CheckSessionValidityParams, RecoveryKeyResult,- SessionValidity, TwoFactorSetup,+ ChangePasswordParams, CheckSessionValidityParams, RecoveryKeyResult, SessionValidity,+ TwoFactorSetup,};pub use types::{AccountSecrets, AccountsClientConfig, AuthenticatedAccount, DEFAULT_API_ORIGIN};diff --git a/rust/crates/accounts/src/lifecycle.rs b/rust/crates/accounts/src/lifecycle.rsindex 8392342e40..9474c5fe29 100644--- a/rust/crates/accounts/src/lifecycle.rs+++ b/rust/crates/accounts/src/lifecycle.rs@@ -23,7 +23,6 @@ use crate::{};pub struct ChangePasswordParams {- pub email: String,pub password: Zeroizing<String>,pub master_key: SecretVec,pub key_attributes: KeyAttributes,@@ -33,7 +32,6 @@ pub struct ChangePasswordParams {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)@@ -42,13 +40,6 @@ impl fmt::Debug for ChangePasswordParams {}}-#[derive(Debug, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ChangePasswordResult {- pub key_attributes: KeyAttributes,- pub srp_attributes: SrpAttributes,-}-#[derive(Debug)]pub struct CheckSessionValidityParams {pub email: String,@@ -147,7 +138,7 @@ fn verify_totp(secret: &str, code: &str, time: u64) -> Result<()> {pub async fn change_password(client: &AccountsClient,params: ChangePasswordParams,-) -> Result<ChangePasswordResult> {+) -> Result<KeyAttributes> {change_password_with_strength(client, params, KeyDerivationStrength::Sensitive).await}@@ -155,7 +146,7 @@ async fn change_password_with_strength(client: &AccountsClient,params: ChangePasswordParams,key_derivation_strength: KeyDerivationStrength,-) -> Result<ChangePasswordResult> {+) -> Result<KeyAttributes> {let (updated_key_attributes, login_key) =auth::generate_key_attributes_for_new_password_with_strength(¶ms.master_key,@@ -177,19 +168,7 @@ async fn change_password_with_strength().await?;- let srp_attributes = client.get_srp_attributes(¶ms.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,- })+ Ok(updated_key_attributes)}pub async fn check_session_validity(diff --git a/rust/crates/accounts/src/lifecycle/tests.rs b/rust/crates/accounts/src/lifecycle/tests.rsindex 5d861ba602..10c74dcc20 100644--- a/rust/crates/accounts/src/lifecycle/tests.rs+++ b/rust/crates/accounts/src/lifecycle/tests.rs@@ -297,22 +297,14 @@ async fn change_password_updates_srp_and_keys() {.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()- })+ .with_status(503)+ .expect(0).create_async().await;@@ -322,7 +314,6 @@ async fn change_password_updates_srp_and_keys() {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,@@ -334,8 +325,14 @@ async fn change_password_updates_srp_and_keys() {.unwrap();assert_eq!(- result.srp_attributes.kek_salt,- result.key_attributes.kek_salt+ result.kek_salt,+ state+ .lock()+ .unwrap()+ .remote_srp_attributes+ .as_ref()+ .unwrap()+ .kek_salt);setup_srp.assert_async().await;diff --git a/rust/crates/accounts/tests/accounts.rs b/rust/crates/accounts/tests/accounts.rsindex f950b04b99..5eaf552374 100644--- a/rust/crates/accounts/tests/accounts.rs+++ b/rust/crates/accounts/tests/accounts.rs@@ -102,7 +102,6 @@ async fn run(endpoint: String) -> TestResult {let changed = change_password(&recovery_client,ChangePasswordParams {- email: email.clone(),password: Zeroizing::new(new_password.clone()),master_key: SecretVec::new(recovered.secrets.master_key.clone()),key_attributes: recovered.key_attributes.clone(),@@ -125,24 +124,17 @@ async fn run(endpoint: String) -> TestResult {else {panic!("existing session did not detect the password change");};- assert_eq!(- updated_key_attributes.kek_salt,- changed.key_attributes.kek_salt- );- assert_eq!(- updated_srp_attributes.srp_user_id,- changed.srp_attributes.srp_user_id- );+ assert_eq!(updated_key_attributes.kek_salt, changed.kek_salt);let login_client = accounts_client(endpoint);assert!(matches!(login_client- .login_with_srp(&password, &changed.srp_attributes)+ .login_with_srp(&password, &updated_srp_attributes).await,Err(Error::IncorrectPassword)));let (response, kek) = login_client- .login_with_srp(&new_password, &changed.srp_attributes)+ .login_with_srp(&new_password, &updated_srp_attributes).await?;let changed_login = unlock(&response, &kek)?;assert_eq!(changed_login.secrets.master_key, created.secrets.master_key);@@ -157,10 +149,9 @@ async fn run(endpoint: String) -> TestResult {assert_eq!(recovered_client.email().await?, email);let reset_password = format!("Reset-{}!", Uuid::new_v4().simple());- let reset = change_password(+ change_password(&recovered_client,ChangePasswordParams {- email: email.clone(),password: Zeroizing::new(reset_password.clone()),master_key: SecretVec::new(recovered.secrets.master_key.clone()),key_attributes: recovered.key_attributes.clone(),@@ -173,15 +164,16 @@ async fn run(endpoint: String) -> TestResult {&client,CheckSessionValidityParams {email: email.clone(),- local_srp_attributes: changed.srp_attributes,+ local_srp_attributes: updated_srp_attributes,},).await?,SessionValidity::Invalid));assert_eq!(recovered_client.email().await?, email);+ let reset_srp_attributes = login_client.get_srp_attributes(&email).await?;let (response, kek) = login_client- .login_with_srp(&reset_password, &reset.srp_attributes)+ .login_with_srp(&reset_password, &reset_srp_attributes).await?;assert_eq!(unlock(&response, &kek)?.secrets.master_key,diff --git a/web/apps/photos/tests/password-change.test.ts b/web/apps/photos/tests/password-change.test.tsnew file mode 100644index 0000000000..fe439ea900--- /dev/null+++ b/web/apps/photos/tests/password-change.test.ts@@ -0,0 +1,98 @@+import { changePassword } from "ente-accounts/services/password";+import { PasswordWorker } from "ente-accounts/services/password.worker";+import { afterEach, beforeEach, expect, test, vi } from "vitest";++const {+ generateInteractiveKeyAttributes,+ getAndSaveSRPAttributes,+ keyAttributes,+ rustChangePassword,+ saveKeyAttributes,+ warn,+} = vi.hoisted(() => ({+ generateInteractiveKeyAttributes: vi.fn(),+ getAndSaveSRPAttributes: vi.fn(),+ keyAttributes: { kekSalt: "old-salt" },+ rustChangePassword: vi.fn(),+ saveKeyAttributes: vi.fn(),+ warn: vi.fn(),+}));++vi.mock("comlink", () => ({ expose: vi.fn() }));+vi.mock("ente-base/log", () => ({ default: { warn } }));+vi.mock("ente-base/log-web", () => ({+ logUnhandledErrorsAndRejectionsInWorker: vi.fn(),+}));+vi.mock("ente-base/token", () => ({+ ensureAuthToken: () => Promise.resolve("token"),+}));+vi.mock("ente-base/session-storage", () => ({+ readMasterKeyFromSession: () => Promise.resolve("master-key"),+}));+vi.mock("ente-base/worker/comlink-worker", () => ({+ ComlinkWorker: class {+ remote = Promise.resolve(new PasswordWorker());+ terminate = vi.fn();+ },+}));+vi.mock("ente-accounts/services/accounts-client", () => ({+ withAccountsClient: (operation: (client: unknown) => Promise<unknown>) =>+ operation({}),+}));+vi.mock("ente-accounts/services/accounts-db", () => ({ saveKeyAttributes }));+vi.mock("ente-accounts/services/key-attributes", () => ({+ generateInteractiveKeyAttributes,+}));+vi.mock("ente-accounts/services/srp", () => ({ getAndSaveSRPAttributes }));+vi.mock("ente-accounts/services/user", () => ({+ ensureLocalUser: () => ({ email: "[email protected]" }),+ ensureSavedKeyAttributes: () => keyAttributes,+}));+vi.mock("ente-prelogin-wasm", () => ({ changePassword: rustChangePassword }));++const updated = { kekSalt: "new-local-salt" };+const change = () => changePassword("new-password", vi.fn());++afterEach(() => vi.unstubAllGlobals());++beforeEach(() => {+ vi.resetAllMocks();+ vi.stubGlobal("Worker", vi.fn());+ generateInteractiveKeyAttributes.mockResolvedValue(updated);+ rustChangePassword.mockResolvedValue({ kekSalt: "new-remote-salt" });+ getAndSaveSRPAttributes.mockResolvedValue(undefined);+});++test("SRP refresh failure preserves a successful password change", async () => {+ const refreshError = new Error("offline");+ getAndSaveSRPAttributes.mockRejectedValue(refreshError);++ await expect(change()).resolves.toBeUndefined();++ expect(generateInteractiveKeyAttributes).toHaveBeenCalledBefore(+ rustChangePassword,+ );+ expect(saveKeyAttributes).toHaveBeenCalledWith(updated);+ expect(saveKeyAttributes).toHaveBeenCalledBefore(getAndSaveSRPAttributes);+ expect(warn).toHaveBeenCalledWith(expect.any(String), refreshError);+});++test("local key preparation failure does not change the password", async () => {+ const error = new Error("key preparation failed");+ generateInteractiveKeyAttributes.mockRejectedValue(error);++ await expect(change()).rejects.toBe(error);++ expect(rustChangePassword).not.toHaveBeenCalled();+ expect(saveKeyAttributes).not.toHaveBeenCalled();+});++test("failed password update preserves the existing local keys", async () => {+ const error = new Error("update rejected");+ rustChangePassword.mockRejectedValue(error);++ await expect(change()).rejects.toBe(error);++ expect(saveKeyAttributes).not.toHaveBeenCalled();+ expect(getAndSaveSRPAttributes).not.toHaveBeenCalled();+});diff --git a/web/packages/accounts/services/password.ts b/web/packages/accounts/services/password.tsindex 56eaa6680f..804bc98a6b 100644--- a/web/packages/accounts/services/password.ts+++ b/web/packages/accounts/services/password.ts@@ -1,10 +1,12 @@+import log from "ente-base/log";import {readMasterKeyFromSession,type SessionStorageCrypto,} from "ente-base/session-storage";import { ComlinkWorker } from "ente-base/worker/comlink-worker";-import { saveKeyAttributes, saveSRPAttributes } from "./accounts-db";+import { saveKeyAttributes } from "./accounts-db";import type { PasswordWorker } from "./password.worker";+import { getAndSaveSRPAttributes } from "./srp";import { ensureLocalUser, ensureSavedKeyAttributes } from "./user";export const changePassword = async (@@ -23,9 +25,14 @@ export const changePassword = async (try {const updated = await (await worker.remote- ).changePassword(password, masterKey, keyAttributes, email);- saveSRPAttributes(updated.srpAttributes);- saveKeyAttributes(updated.keyAttributes);+ ).changePassword(password, masterKey, keyAttributes);+ saveKeyAttributes(updated);+ void getAndSaveSRPAttributes(email).catch((error: unknown) =>+ log.warn(+ "Failed to refresh SRP attributes after password change",+ error,+ ),+ );} finally {worker.terminate();}diff --git a/web/packages/accounts/services/password.worker.ts b/web/packages/accounts/services/password.worker.tsindex 71aa7fddfd..34a95ea207 100644--- a/web/packages/accounts/services/password.worker.ts+++ b/web/packages/accounts/services/password.worker.ts@@ -2,45 +2,26 @@ import { expose } from "comlink";import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";import { ensureAuthToken } from "ente-base/token";import { changePassword } from "ente-prelogin-wasm";-import { z } from "zod";import { withAccountsClient } from "./accounts-client";import { generateInteractiveKeyAttributes } from "./key-attributes";-import { RemoteSRPAttributes } from "./srp";-import { RemoteKeyAttributes, type KeyAttributes } from "./user";--const ChangedPassword = z.object({- keyAttributes: RemoteKeyAttributes,- srpAttributes: RemoteSRPAttributes,-});+import type { KeyAttributes } from "./user";export class PasswordWorker {async changePassword(password: string,masterKey: string,keyAttributes: KeyAttributes,- email: string,) {+ const interactiveKeyAttributes = await generateInteractiveKeyAttributes(+ password,+ keyAttributes,+ masterKey,+ );const token = await ensureAuthToken();- const updated = ChangedPassword.parse(- await withAccountsClient((client) =>- changePassword(- client,- token,- email,- password,- masterKey,- keyAttributes,- ),- ),+ await withAccountsClient((client) =>+ changePassword(client, token, password, masterKey, keyAttributes),);- return {- srpAttributes: updated.srpAttributes,- keyAttributes: await generateInteractiveKeyAttributes(- password,- updated.keyAttributes,- masterKey,- ),- };+ return interactiveKeyAttributes;}}diff --git a/web/packages/wasm/prelogin/index.ts b/web/packages/wasm/prelogin/index.tsindex e5f2345845..e57c1f90b3 100644--- a/web/packages/wasm/prelogin/index.ts+++ b/web/packages/wasm/prelogin/index.ts@@ -174,7 +174,6 @@ export const recoverAccount = async (export const changePassword = async (client: AccountsClient,token: string,- email: string,password: string,masterKey: string,keyAttributes: unknown,@@ -182,7 +181,6 @@ export const changePassword = async ((await wasm()).changePassword(client,token,- email,password,masterKey,keyAttributes,