diff --git a/apps/desktop/src/ipc.test.ts b/apps/desktop/src/ipc.test.ts index 5b69168f75..78d46c830d 100644 --- a/apps/desktop/src/ipc.test.ts +++ b/apps/desktop/src/ipc.test.ts @@ -5,32 +5,122 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com Please see LICENSE files in the repository root for full details. */ -import { expect, describe, it, vi } from "vitest"; -import { ipcMain, type IpcMainInvokeEvent } from "electron"; +import { expect, describe, it, beforeEach, vi } from "vitest"; import { getConfig } from "./config.js"; -vi.mock("electron", () => ({ - ipcMain: { - on: vi.fn(), - once: vi.fn(), - handle: vi.fn(), +const { ipcHandlers, mockStore, send, randomArray } = vi.hoisted(() => ({ + ipcHandlers: {} as Record unknown>, + mockStore: { + isSecretUndecryptable: vi.fn<(key: string) => Promise>(), + setSecret: vi.fn<(key: string, secret: string) => Promise>(), + getSecret: vi.fn<(key: string) => Promise>(), + deleteSecret: vi.fn<(key: string) => Promise>(), + set: vi.fn<(key: string, value: unknown) => void>(), + get: vi.fn<(key: string) => unknown>(), }, + send: vi.fn(), + randomArray: vi.fn<(len: number) => Promise>(), })); +vi.mock("electron", () => ({ + app: { getVersion: vi.fn(() => "1.0.0") }, + autoUpdater: { getFeedURL: vi.fn() }, + desktopCapturer: { getSources: vi.fn() }, + ipcMain: { + on: vi.fn((channel: string, cb: (...a: unknown[]) => unknown) => { + ipcHandlers[channel] = cb; + }), + once: vi.fn((channel: string, cb: (...a: unknown[]) => unknown) => { + ipcHandlers[channel] = cb; + }), + handle: vi.fn((channel: string, cb: (...a: unknown[]) => unknown) => { + ipcHandlers[channel] = cb; + }), + }, + powerSaveBlocker: { isStarted: vi.fn(), start: vi.fn(), stop: vi.fn() }, + TouchBar: class {}, + nativeImage: { createFromBuffer: vi.fn() }, +})); + +vi.mock("./store.js", () => ({ + default: { instance: mockStore }, + clearDataAndRelaunch: vi.fn(), + SafeStorageDecryptionError: class SafeStorageDecryptionError extends Error {}, +})); +vi.mock("./utils.js", () => ({ randomArray })); +vi.mock("./displayMediaCallback.js", () => ({ + getDisplayMediaCallback: vi.fn(), + setDisplayMediaCallback: vi.fn(), +})); vi.mock("./config.js"); +await import("./ipc.js"); + +const ARGS = ["@alice:example.org", "DEVICEID"]; + +async function callIpc(name: string, id = 1): Promise { + await ipcHandlers["ipcCall"]({}, { id, name, args: ARGS }); +} + +describe("ipc pickle key handling", () => { + beforeEach(() => { + vi.clearAllMocks(); + randomArray.mockResolvedValue("GENERATEDKEY"); + (global as unknown as { mainWindow: unknown }).mainWindow = { webContents: { send } }; + }); + + describe("createPickleKey", () => { + it("refuses to overwrite an existing but undecryptable pickle key", async () => { + mockStore.isSecretUndecryptable.mockResolvedValue(true); + + await callIpc("createPickleKey", 7); + + expect(mockStore.setSecret).not.toHaveBeenCalled(); + expect(send).toHaveBeenCalledWith("ipcReply", { id: 7, reply: null }); + }); + + it("creates and stores a new pickle key when none is present", async () => { + mockStore.isSecretUndecryptable.mockResolvedValue(false); + + await callIpc("createPickleKey", 8); + + expect(mockStore.setSecret).toHaveBeenCalledWith("@alice:example.org|DEVICEID", "GENERATEDKEY"); + expect(send).toHaveBeenCalledWith("ipcReply", { id: 8, reply: "GENERATEDKEY" }); + }); + }); + + describe("getPickleKey", () => { + it("returns null when getSecret throws", async () => { + mockStore.getSecret.mockRejectedValue(new Error("safeStorage unavailable")); + + await callIpc("getPickleKey", 9); + + expect(send).toHaveBeenCalledWith("ipcReply", { id: 9, reply: null }); + }); + + it("returns null when the secret is present but cannot be decrypted", async () => { + const { SafeStorageDecryptionError } = await import("./store.js"); + mockStore.getSecret.mockRejectedValue( + new SafeStorageDecryptionError("Failed to decrypt safeStorage secret"), + ); + + await callIpc("getPickleKey", 10); + + expect(send).toHaveBeenCalledWith("ipcReply", { id: 10, reply: null }); + }); + }); +}); + describe("getConfig", () => { it("should call config.getConfig and return the value", async () => { const config = { brand: "BRAND", help_url: "HELP_URL", web_base_url: "WEB_BASE_URL" }; vi.mocked(getConfig).mockReturnValue(config); - await import("./ipc.js"); - - const handler = vi.mocked(ipcMain.handle).mock.calls.find(([channel]) => channel === "getConfig")?.[1]; + const handler = ipcHandlers["getConfig"]; expect(handler).toBeDefined(); - expect(handler!(new Event("test") as unknown as IpcMainInvokeEvent)).toStrictEqual(config); + expect(handler({})).toStrictEqual(config); expect(getConfig).toHaveBeenCalled(); }); }); diff --git a/apps/desktop/src/ipc.ts b/apps/desktop/src/ipc.ts index 229a525662..82183ad1f9 100644 --- a/apps/desktop/src/ipc.ts +++ b/apps/desktop/src/ipc.ts @@ -112,17 +112,29 @@ ipcMain.on("ipcCall", async function (_ev: IpcMainEvent, payload) { try { ret = await store.getSecret(`${args[0]}|${args[1]}`); } catch { - // if an error is thrown (e.g. we can't initialise safeStorage), - // then return null, which means the default pickle key will be used + // An error is thrown if we can't initialise safeStorage, or if a stored secret exists + // but can't be decrypted this launch (SafeStorageDecryptionError, e.g. the OS keychain + // is temporarily unavailable). In both cases return null so the default pickle key is + // used; we must NOT destroy the existing secret (see createPickleKey below) so the + // session can recover on a later launch. See element-web#32521 / #32715. ret = null; } break; case "createPickleKey": try { - const pickleKey = await randomArray(32); - await store.setSecret(`${args[0]}|${args[1]}`, pickleKey); - ret = pickleKey; + // Never overwrite a pickle key that already exists but is currently undecryptable. + // Overwriting it with a freshly-generated key would turn a transient keychain failure + // into permanent session and encryption-key loss. Preserve it so the existing session + // can be restored on a later launch once the keychain is readable again. + if (await store.isSecretUndecryptable(`${args[0]}|${args[1]}`)) { + console.warn("Refusing to overwrite an existing undecryptable pickle key; preserving it"); + ret = null; + } else { + const pickleKey = await randomArray(32); + await store.setSecret(`${args[0]}|${args[1]}`, pickleKey); + ret = pickleKey; + } } catch (e) { console.error("Failed to create pickle key", e); ret = null; diff --git a/apps/desktop/src/store.test.ts b/apps/desktop/src/store.test.ts new file mode 100644 index 0000000000..8bda03574d --- /dev/null +++ b/apps/desktop/src/store.test.ts @@ -0,0 +1,196 @@ +/* +Copyright 2026 New Vector Ltd. +Copyright 2026 hayaksi1 + +SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial +Please see LICENSE files in the repository root for full details. +*/ + +import { expect, describe, it, beforeAll, beforeEach, vi } from "vitest"; +import { app, safeStorage } from "electron"; + +import Store, { SafeStorageDecryptionError } from "./store.js"; + +// In-memory ElectronStore replacement so the tests don't touch the filesystem or real config. +const backing = new Map(); +vi.mock("electron-store", () => { + // No constructor: the options ElectronStore is handed are irrelevant to this fake, so an empty + // one would exist only to swallow them — which oxlint's no-useless-constructor rejects. + class MockElectronStore { + public get(key: string, defaultValue?: unknown): unknown { + return backing.has(key) ? backing.get(key) : defaultValue; + } + public set(key: string, value: unknown): void { + backing.set(key, value); + } + public has(key: string): boolean { + return backing.has(key); + } + public delete(key: string): void { + backing.delete(key); + } + public clear(): void { + backing.clear(); + } + } + return { default: MockElectronStore }; +}); + +vi.mock("./language-helper.js", () => ({ + _t: (key: string): string => key, +})); + +// store.ts reads getConfig().brand for the degraded-mode dialogs. The real config module only +// populates itself in loadConfig(), which these tests never run, so stub it out. +vi.mock("./config.js", () => ({ + getConfig: (): { brand: string } => ({ brand: "Element" }), +})); + +// A reversible "encryption" so we control exactly when decryption fails. +const PREFIX = "enc:"; +vi.mock("electron", () => ({ + app: { + whenReady: vi.fn(() => Promise.resolve()), + getPath: vi.fn(() => "/tmp/element-test"), + relaunch: vi.fn(), + exit: vi.fn(), + commandLine: { appendSwitch: vi.fn() }, + }, + dialog: { + showMessageBox: vi.fn(() => Promise.resolve({ response: 1 })), + }, + safeStorage: { + isEncryptionAvailable: vi.fn(() => true), + getSelectedStorageBackend: vi.fn(() => "basic_text"), + setUsePlainTextEncryption: vi.fn(), + encryptString: vi.fn((plaintext: string) => Buffer.from(PREFIX + plaintext, "utf8")), + decryptString: vi.fn((buf: Buffer) => { + const s = buf.toString("utf8"); + if (!s.startsWith(PREFIX)) throw new Error("Failed to decrypt"); + return s.slice(PREFIX.length); + }), + }, +})); + +const KEY = "@alice:example.org|DEVICEID"; + +describe("Store secret encryption (safeStorage)", () => { + let store: Store; + + beforeAll(async () => { + store = Store.initialize(undefined); + // getSelectedStorageBackend is mocked to "basic_text", so this walks the degraded-mode + // path and takes the mocked dialog's "use basic_text" answer. + await store.prepareSafeStorage({} as unknown as Electron.Session); + }); + + beforeEach(() => { + backing.clear(); + vi.mocked(safeStorage.decryptString).mockClear(); + // Restore the default reversible decrypt implementation between tests. + vi.mocked(safeStorage.decryptString).mockImplementation((buf: Buffer) => { + const s = buf.toString("utf8"); + if (!s.startsWith(PREFIX)) throw new Error("Failed to decrypt"); + return s.slice(PREFIX.length); + }); + }); + + it("round-trips a stored secret", async () => { + await store.setSecret(KEY, "s3cr3t"); + await expect(store.getSecret(KEY)).resolves.toBe("s3cr3t"); + }); + + it("returns undefined when no secret is stored", async () => { + await expect(store.getSecret(KEY)).resolves.toBeUndefined(); + }); + + it("throws SafeStorageDecryptionError when the stored secret cannot be decrypted", async () => { + await store.setSecret(KEY, "s3cr3t"); + // Simulate a transient keychain failure (e.g. keychain locked / ACL invalidated by re-sign). + vi.mocked(safeStorage.decryptString).mockImplementationOnce(() => { + throw new Error("keychain unavailable"); + }); + + await expect(store.getSecret(KEY)).rejects.toBeInstanceOf(SafeStorageDecryptionError); + }); + + describe("isSecretUndecryptable", () => { + it("is false when no secret is stored", async () => { + await expect(store.isSecretUndecryptable(KEY)).resolves.toBe(false); + }); + + it("is false when the stored secret decrypts correctly", async () => { + await store.setSecret(KEY, "s3cr3t"); + await expect(store.isSecretUndecryptable(KEY)).resolves.toBe(false); + }); + + it("is true when a stored secret exists but cannot be decrypted", async () => { + await store.setSecret(KEY, "s3cr3t"); + vi.mocked(safeStorage.decryptString).mockImplementationOnce(() => { + throw new Error("keychain unavailable"); + }); + await expect(store.isSecretUndecryptable(KEY)).resolves.toBe(true); + }); + + it("fails closed: is true when reading an existing secret fails with an unexpected error", async () => { + await store.setSecret(KEY, "s3cr3t"); + // An error from the storage layer itself, not a decryption failure: the guard must not + // report the secret as safe to overwrite when it cannot prove it is. + const getSpy = vi.spyOn(store, "get").mockImplementationOnce(() => { + throw new Error("storage layer exploded"); + }); + try { + await expect(store.isSecretUndecryptable(KEY)).resolves.toBe(true); + } finally { + getSpy.mockRestore(); + } + }); + }); + + describe("basic_text -> plaintext migration", () => { + // The private migration step normally runs via prepareSafeStorage on a relaunch with + // safeStorageBackendMigrate set; drive it directly to keep the singleton harness simple. + const migrate = (): void => + (store as unknown as { migrateBasicTextToPlaintext(): void }).migrateBasicTextToPlaintext(); + + const GOOD_CIPHERTEXT = Buffer.from(`${PREFIX}goodsecret`, "utf8").toString("base64"); + const BAD_CIPHERTEXT = Buffer.from("not-decryptable", "utf8").toString("base64"); + + beforeEach(() => { + backing.set("safeStorageBackend", "basic_text"); + backing.set("safeStorageBackendMigrate", true); + }); + + it("migrates all secrets to plaintext and records the plaintext backend", () => { + backing.set("safeStorage", { good: GOOD_CIPHERTEXT }); + backing.set("safeStorage.good", GOOD_CIPHERTEXT); + + migrate(); + + expect(backing.get("safeStorage.good")).toBe("goodsecret"); + expect(backing.get("safeStorageBackend")).toBe("plaintext"); + expect(backing.get("safeStorageBackendOverride")).toBeUndefined(); + expect(backing.has("safeStorageBackendMigrate")).toBe(false); + expect(app.relaunch).toHaveBeenCalled(); + }); + + it("defers the whole migration when any secret cannot be decrypted", () => { + backing.set("safeStorage", { good: GOOD_CIPHERTEXT, bad: BAD_CIPHERTEXT }); + backing.set("safeStorage.good", GOOD_CIPHERTEXT); + backing.set("safeStorage.bad", BAD_CIPHERTEXT); + + migrate(); + + // Nothing may be rewritten: recording "plaintext" while `bad` is still ciphertext would + // make the next launch re-encrypt the ciphertext as though it were the secret itself, + // silently corrupting it and defeating the do-not-overwrite protection. + expect(backing.get("safeStorage.good")).toBe(GOOD_CIPHERTEXT); + expect(backing.get("safeStorage.bad")).toBe(BAD_CIPHERTEXT); + expect(backing.get("safeStorageBackend")).toBe("basic_text"); + // Sticks with the working basic_text backend instead of retrying the migration forever. + expect(backing.get("safeStorageBackendOverride")).toBe(true); + expect(backing.has("safeStorageBackendMigrate")).toBe(false); + expect(app.relaunch).toHaveBeenCalled(); + }); + }); +}); diff --git a/apps/desktop/src/store.ts b/apps/desktop/src/store.ts index 12ff4d9472..154173c47a 100644 --- a/apps/desktop/src/store.ts +++ b/apps/desktop/src/store.ts @@ -47,6 +47,17 @@ const safeStorageBackendMap: Omit, "syste kwallet6: "kwallet6", }; +/** + * Error thrown when a secret is present in storage but cannot be decrypted with the current + * safeStorage backend (e.g. the OS keychain is temporarily unavailable or locked, or the app's + * keychain ACL was invalidated by a re-sign/update). + * + * This is deliberately distinct from a secret being absent so that callers can avoid destroying a + * still-valid-but-temporarily-unreadable secret (which would turn a transient failure into permanent + * session/encryption-key loss). See element-web#32521 and element-web#32715. + */ +export class SafeStorageDecryptionError extends Error {} + function relaunchApp(): void { console.info("Relaunching app..."); app.relaunch(); @@ -100,6 +111,10 @@ class StorageWriter { return this.store.get(this.getKey(key)); } + public has(key: string): boolean { + return this.store.has(this.getKey(key)); + } + public delete(key: string): void { this.store.delete(this.getKey(key)); } @@ -115,15 +130,21 @@ class SafeStorageWriter extends StorageWriter { public get(key: string): string | undefined { const ciphertext = this.store.get(this.getKey(key)); - if (ciphertext) { - try { - return safeStorage.decryptString(Buffer.from(ciphertext, "base64")); - } catch (e) { - console.error("Failed to decrypt secret", e); - console.error("...ciphertext:", JSON.stringify(ciphertext)); - } + if (!ciphertext) { + // No secret stored. + return undefined; + } + try { + return safeStorage.decryptString(Buffer.from(ciphertext, "base64")); + } catch (e) { + // The secret exists but cannot be decrypted in this session. Returning undefined here (as + // we used to) is indistinguishable from "no secret stored", which makes callers create or + // overwrite a fresh secret and permanently destroy the still-valid ciphertext. Throw a + // typed error instead so callers can preserve the data and recover on a later launch once + // the keychain is readable again. See element-web#32521 / #32715. + console.error("Failed to decrypt secret", e); + throw new SafeStorageDecryptionError("Failed to decrypt safeStorage secret", { cause: e }); } - return undefined; } } @@ -426,8 +447,27 @@ class Store extends ElectronStore { console.info("Performing safeStorage migration"); const data = this.get("safeStorage"); if (data) { - for (const key in data) { - this.set(secrets.getKey(key), secrets.get(key)); + // Decrypt everything up front: if any secret cannot be decrypted we must not migrate. + // Recording "plaintext" while a secret is still ciphertext would make the next launch + // re-encrypt that ciphertext as though it were the secret itself, silently corrupting it + // and defeating the do-not-overwrite protection in isSecretUndecryptable. + const decrypted = new Map(); + try { + for (const key in data) { + decrypted.set(secrets.getKey(key), secrets.get(key)); + } + } catch (e) { + // Abort the migration with the data untouched and stick with the basic_text backend + // (the same escape hatch as a failed backend change) so the app keeps working and no + // secret is destroyed or corrupted. + console.error("Aborting safeStorage migration: a secret cannot be decrypted", e); + this.set("safeStorageBackendOverride", true); + this.delete("safeStorageBackendMigrate"); + relaunchApp(); + return; + } + for (const [key, value] of decrypted) { + if (value !== undefined) this.set(key, value); } this.recordSafeStorageBackend("plaintext"); } @@ -459,6 +499,30 @@ class Store extends ElectronStore { return this.secrets!.get(key); } + /** + * Returns true if a secret is stored for the key but cannot currently be read and decrypted. + * + * Used to avoid destroying a recoverable secret by overwriting it with a freshly-generated one + * when the keychain is only temporarily unavailable. Fails closed: any error while reading an + * existing secret counts as undecryptable, so callers never overwrite a secret this method + * cannot prove is safe to replace. See element-web#32521 / #32715. + * + * @param key The string key name. + */ + public async isSecretUndecryptable(key: string): Promise { + await this.safeStorageReady(); + if (!this.secrets!.has(key)) return false; + try { + this.secrets!.get(key); + return false; + } catch (e) { + if (!(e instanceof SafeStorageDecryptionError)) { + console.error("Unexpected error reading existing secret; treating it as undecryptable", e); + } + return true; + } + } + /** * Add the secret for the key to the keychain. *