π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Reconcile password metadata during session checks
Neeraj Gupta0b27952fa9c4
diff --git a/web/apps/photos/tests/password-change.test.ts b/web/apps/photos/tests/password-change.test.tsindex fe439ea900..41abd9d72b 100644--- a/web/apps/photos/tests/password-change.test.ts+++ b/web/apps/photos/tests/password-change.test.ts@@ -1,25 +1,28 @@+import {+ replaceSavedLocalUser,+ savedKeyAttributes,+ savedOriginalKeyAttributes,+ savedSRPAttributes,+ saveKeyAttributes,+ saveOriginalKeyAttributes,+ saveSRPAttributes,+} from "ente-accounts/services/accounts-db";import { changePassword } from "ente-accounts/services/password";import { PasswordWorker } from "ente-accounts/services/password.worker";+import { checkSessionValidity } from "ente-accounts/services/session";import { afterEach, beforeEach, expect, test, vi } from "vitest";const {generateInteractiveKeyAttributes,- getAndSaveSRPAttributes,- keyAttributes,rustChangePassword,- saveKeyAttributes,- warn,+ rustCheckSessionValidity,} = vi.hoisted(() => ({generateInteractiveKeyAttributes: vi.fn(),- getAndSaveSRPAttributes: vi.fn(),- keyAttributes: { kekSalt: "old-salt" },rustChangePassword: vi.fn(),- saveKeyAttributes: vi.fn(),- warn: vi.fn(),+ rustCheckSessionValidity: vi.fn(),}));vi.mock("comlink", () => ({ expose: vi.fn() }));-vi.mock("ente-base/log", () => ({ default: { warn } }));vi.mock("ente-base/log-web", () => ({logUnhandledErrorsAndRejectionsInWorker: vi.fn(),}));@@ -39,18 +42,38 @@ 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,+ checkSessionValidity: rustCheckSessionValidity,}));-vi.mock("ente-prelogin-wasm", () => ({ changePassword: rustChangePassword }));-const updated = { kekSalt: "new-local-salt" };+const original = {+ kekSalt: "old-salt",+ encryptedKey: "encrypted-key",+ keyDecryptionNonce: "key-nonce",+ publicKey: "public-key",+ encryptedSecretKey: "encrypted-secret-key",+ secretKeyDecryptionNonce: "secret-key-nonce",+ memLimit: 65536,+ opsLimit: 2,+};+const updated = { ...original, kekSalt: "new-local-salt" };+const remote = { ...original, kekSalt: "new-remote-salt" };+const updatedSRPAttributes = {+ kekSalt: remote.kekSalt,+ memLimit: remote.memLimit,+ opsLimit: remote.opsLimit,+ srpUserID: "srp-user-id",+ srpSalt: "srp-salt",+ isEmailMFAEnabled: true,+};+const originalSRPAttributes = {+ ...updatedSRPAttributes,+ kekSalt: original.kekSalt,+};const change = () => changePassword("new-password", vi.fn());afterEach(() => vi.unstubAllGlobals());@@ -58,23 +81,52 @@ afterEach(() => vi.unstubAllGlobals());beforeEach(() => {vi.resetAllMocks();vi.stubGlobal("Worker", vi.fn());+ const storage = new Map<string, string>();+ vi.stubGlobal("localStorage", {+ getItem: (key: string) => storage.get(key) ?? null,+ setItem: (key: string, value: string) => storage.set(key, value),+ });+ replaceSavedLocalUser({ id: 1, email: "[email protected]", token: "token" });+ saveKeyAttributes(original);+ saveOriginalKeyAttributes(original);+ saveSRPAttributes(originalSRPAttributes);generateInteractiveKeyAttributes.mockResolvedValue(updated);- rustChangePassword.mockResolvedValue({ kekSalt: "new-remote-salt" });- getAndSaveSRPAttributes.mockResolvedValue(undefined);+ rustChangePassword.mockResolvedValue(remote);+ rustCheckSessionValidity.mockResolvedValue({+ status: "validButPasswordChanged",+ updatedKeyAttributes: remote,+ updatedSRPAttributes,+ });});-test("SRP refresh failure preserves a successful password change", async () => {- const refreshError = new Error("offline");- getAndSaveSRPAttributes.mockRejectedValue(refreshError);-+test("password change saves keys and the next session check reconciles SRP", async () => {await expect(change()).resolves.toBeUndefined();expect(generateInteractiveKeyAttributes).toHaveBeenCalledBefore(rustChangePassword,);- expect(saveKeyAttributes).toHaveBeenCalledWith(updated);- expect(saveKeyAttributes).toHaveBeenCalledBefore(getAndSaveSRPAttributes);- expect(warn).toHaveBeenCalledWith(expect.any(String), refreshError);+ expect(savedKeyAttributes()).toEqual(updated);+ expect(savedOriginalKeyAttributes()).toEqual(remote);+ expect(savedSRPAttributes()).toEqual(originalSRPAttributes);++ await expect(checkSessionValidity()).resolves.toEqual({ status: "valid" });+ expect(savedSRPAttributes()).toEqual(updatedSRPAttributes);+});++test("a subsequent password change elsewhere is still detected", async () => {+ await change();+ const result = {+ status: "validButPasswordChanged",+ updatedKeyAttributes: { ...remote, kekSalt: "another-salt" },+ updatedSRPAttributes: {+ ...updatedSRPAttributes,+ kekSalt: "another-salt",+ },+ };+ rustCheckSessionValidity.mockResolvedValue(result);++ await expect(checkSessionValidity()).resolves.toEqual(result);+ expect(savedSRPAttributes()).toEqual(originalSRPAttributes);});test("local key preparation failure does not change the password", async () => {@@ -84,7 +136,8 @@ test("local key preparation failure does not change the password", async () => {await expect(change()).rejects.toBe(error);expect(rustChangePassword).not.toHaveBeenCalled();- expect(saveKeyAttributes).not.toHaveBeenCalled();+ expect(savedKeyAttributes()).toEqual(original);+ expect(savedOriginalKeyAttributes()).toEqual(original);});test("failed password update preserves the existing local keys", async () => {@@ -93,6 +146,7 @@ test("failed password update preserves the existing local keys", async () => {await expect(change()).rejects.toBe(error);- expect(saveKeyAttributes).not.toHaveBeenCalled();- expect(getAndSaveSRPAttributes).not.toHaveBeenCalled();+ expect(savedKeyAttributes()).toEqual(original);+ expect(savedOriginalKeyAttributes()).toEqual(original);+ expect(savedSRPAttributes()).toEqual(originalSRPAttributes);});diff --git a/web/packages/accounts/services/password.ts b/web/packages/accounts/services/password.tsindex 804bc98a6b..516cd3f890 100644--- a/web/packages/accounts/services/password.ts+++ b/web/packages/accounts/services/password.ts@@ -1,19 +1,16 @@-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 } from "./accounts-db";+import { saveKeyAttributes, saveOriginalKeyAttributes } from "./accounts-db";import type { PasswordWorker } from "./password.worker";-import { getAndSaveSRPAttributes } from "./srp";-import { ensureLocalUser, ensureSavedKeyAttributes } from "./user";+import { ensureSavedKeyAttributes } from "./user";export const changePassword = async (password: string,decryptBox: SessionStorageCrypto["decryptBox"],) => {- const { email } = ensureLocalUser();const keyAttributes = ensureSavedKeyAttributes();const masterKey = await readMasterKeyFromSession(decryptBox);if (!masterKey) throw new Error("Master key not found in session");@@ -23,16 +20,11 @@ export const changePassword = async (new Worker(new URL("password.worker.ts", import.meta.url)),);try {- const updated = await (+ const { interactiveKeyAttributes, remoteKeyAttributes } = await (await worker.remote).changePassword(password, masterKey, keyAttributes);- saveKeyAttributes(updated);- void getAndSaveSRPAttributes(email).catch((error: unknown) =>- log.warn(- "Failed to refresh SRP attributes after password change",- error,- ),- );+ saveKeyAttributes(interactiveKeyAttributes);+ saveOriginalKeyAttributes(remoteKeyAttributes);} finally {worker.terminate();}diff --git a/web/packages/accounts/services/password.worker.ts b/web/packages/accounts/services/password.worker.tsindex 34a95ea207..f84dc9a93b 100644--- a/web/packages/accounts/services/password.worker.ts+++ b/web/packages/accounts/services/password.worker.ts@@ -4,7 +4,7 @@ import { ensureAuthToken } from "ente-base/token";import { changePassword } from "ente-prelogin-wasm";import { withAccountsClient } from "./accounts-client";import { generateInteractiveKeyAttributes } from "./key-attributes";-import type { KeyAttributes } from "./user";+import { RemoteKeyAttributes, type KeyAttributes } from "./user";export class PasswordWorker {async changePassword(@@ -18,10 +18,13 @@ export class PasswordWorker {masterKey,);const token = await ensureAuthToken();- await withAccountsClient((client) =>+ const response = await withAccountsClient((client) =>changePassword(client, token, password, masterKey, keyAttributes),);- return interactiveKeyAttributes;+ return {+ interactiveKeyAttributes,+ remoteKeyAttributes: RemoteKeyAttributes.parse(response),+ };}}diff --git a/web/packages/accounts/services/session.ts b/web/packages/accounts/services/session.tsindex f53c383606..7b046410bc 100644--- a/web/packages/accounts/services/session.ts+++ b/web/packages/accounts/services/session.ts@@ -1,6 +1,7 @@import {savedOriginalKeyAttributes,savedSRPAttributes,+ saveSRPAttributes,} from "ente-accounts/services/accounts-db";import { isNamedError } from "ente-base/error";import log from "ente-base/log";@@ -36,7 +37,7 @@ const SessionValidityResponse = z.object({export const checkSessionValidity = async () => {const token = await ensureAuthToken();- return SessionValidity.parse(+ const result = SessionValidity.parse(await withAccountsClient((client) =>rustCheckSessionValidity(client,@@ -46,6 +47,15 @@ export const checkSessionValidity = async () => {),),);+ if (+ result.status === "validButPasswordChanged" &&+ result.updatedSRPAttributes.kekSalt ===+ savedOriginalKeyAttributes()?.kekSalt+ ) {+ saveSRPAttributes(result.updatedSRPAttributes);+ return { status: "valid" as const };+ }+ return result;};export const isSessionInvalid = async (): Promise<boolean> => {