Skip to content

Build your personal knowledge base with Trilium Notes

client/backup: update the container password in keyring after import

Adorian Doranc3860396c305
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 93223a3130..f9d39b53fa 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -35,6 +35,7 @@ import { setupDialogHandlers } from "./services/dialog";
import { setupExportHandlers } from "./services/export";
import { setupImportHandlers } from "./services/import";
import {
+ adoptBackupPassphrase,
getBackupPassphrase,
registerBackupPassphraseIpcHandlers
} from "./services/backup_passphrase";
@@ -275,7 +276,11 @@ export async function main() {
// Only the desktop lets the user pick where backups go; the server uses TRILIUM_BACKUP_DIR.
backup: new ServerBackupService(
options,
- { allowCustomDirectory: true, getPassphrase: getBackupPassphrase }
+ {
+ allowCustomDirectory: true,
+ getPassphrase: getBackupPassphrase,
+ setPassphrase: adoptBackupPassphrase
+ }
),
image: (await import("@triliumnext/server/src/services/image_provider.js")).serverImageProvider,
config,
diff --git a/apps/desktop/src/services/backup_passphrase.spec.ts b/apps/desktop/src/services/backup_passphrase.spec.ts
index 4ad6919672..0839a93b79 100644
--- a/apps/desktop/src/services/backup_passphrase.spec.ts
+++ b/apps/desktop/src/services/backup_passphrase.spec.ts
@@ -142,6 +142,19 @@ describe("backup passphrase storage", () => {
expect(h.errors.join()).toContain("keyring is locked");
expect(h.errors.join()).not.toContain("hunter2");
});
+
+ it("takes on a restored backup's password, and drops the old one when it brings none", async () => {
+ // The passphrase is not in the database, so a restore replaces every option saying how this
+ // instance backs up and leaves the password those options are carried out with. Kept, the
+ // instance encrypts with a password belonging to a database that is no longer here.
+ await passphrase.storeBackupPassphrase("the previous database's");
+
+ await passphrase.adoptBackupPassphrase("the restored database's");
+ expect(await passphrase.getBackupPassphrase()).toBe("the restored database's");
+
+ await passphrase.adoptBackupPassphrase(null);
+ expect(await passphrase.getBackupPassphrase()).toBeNull();
+ });
});
describe("keyring availability", () => {
diff --git a/apps/desktop/src/services/backup_passphrase.ts b/apps/desktop/src/services/backup_passphrase.ts
index 5fa7e2b223..e3eb8efba5 100644
--- a/apps/desktop/src/services/backup_passphrase.ts
+++ b/apps/desktop/src/services/backup_passphrase.ts
@@ -60,6 +60,27 @@ export function clearBackupPassphrase(): void {
fs.rmSync(PASSPHRASE_PATH, { force: true });
}
+/**
+ * Takes on the passphrase a restored backup was locked with, or lets the stored one go when the
+ * backup brought none.
+ *
+ * Unlike the renderer's way in, this asks nothing first. What the user typed to open the backup is
+ * a password for this database, given moments ago and for this purpose; the confirmation on the
+ * options screen guards against a password being changed behind someone's back, and here there is
+ * nobody's back to go behind.
+ *
+ * Clearing is the honest answer to a backup with no passphrase to take: the stored one belongs to a
+ * database that is no longer here, and going on encrypting with it produces backups the user cannot
+ * open. Encrypted backups then fall back to unencrypted and local, which says so out loud.
+ */
+export async function adoptBackupPassphrase(passphrase: string | null): Promise<void> {
+ if (passphrase) {
+ await storeBackupPassphrase(passphrase);
+ } else {
+ clearBackupPassphrase();
+ }
+}
+
/**
* Reads the passphrase back, for the main process alone. Never reachable from the renderer.
*
diff --git a/apps/server/src/backup_provider.spec.ts b/apps/server/src/backup_provider.spec.ts
index e08eca5128..72900209a4 100644
--- a/apps/server/src/backup_provider.spec.ts
+++ b/apps/server/src/backup_provider.spec.ts
@@ -679,3 +679,21 @@ describe("ServerBackupService: sending a backup for download", () => {
expect(desktopService(CUSTOM_DIR).sendBackup?.("/etc/passwd", res as any)).toBe(false);
});
});
+
+describe("ServerBackupService.adoptPassphrase", () => {
+ it("hands the password to wherever this platform keeps one, and clears it on null", async () => {
+ const stored: (string | null)[] = [];
+ const service = desktopService("", {}, { setPassphrase: async (p) => void stored.push(p) });
+
+ await service.adoptPassphrase("the restored database's password");
+ await service.adoptPassphrase(null);
+
+ expect(stored).toEqual([ "the restored database's password", null ]);
+ });
+
+ it("does nothing where there is nowhere to keep one, rather than failing the restore", async () => {
+ // The server has no keyring, so it has no stored passphrase for a restore to bring up to
+ // date; the restore calls this the same way regardless of the platform it is running on.
+ await expect(serverService(null).adoptPassphrase("a password")).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.ts
index d733b32831..b3de0029f6 100644
--- a/apps/server/src/backup_provider.ts
+++ b/apps/server/src/backup_provider.ts
@@ -35,6 +35,13 @@ export interface ServerBackupConfig {
* desktop application, which is the only one with an OS keyring to keep a passphrase in.
*/
getPassphrase?: () => Promise<string | null>;
+ /**
+ * Stores the backup passphrase, or lets go of the stored one when given `null`. Set alongside
+ * {@link getPassphrase}, and used by the restore rather than by any screen: unset, an instance
+ * simply has nowhere to keep a passphrase, and there is nothing for a restore to bring up to
+ * date.
+ */
+ setPassphrase?: (passphrase: string | null) => Promise<void>;
}
/** How a backup is to be written, once the options and the passphrase have both had their say. */
@@ -182,6 +189,19 @@ export default class ServerBackupService extends BackupService {
return !!(await this.config.getPassphrase?.());
}
+ /**
+ * Takes on the passphrase a restored backup was locked with, or lets go of the stored one when
+ * the backup brought none.
+ *
+ * The passphrase is not kept in the database, so a restore replaces every option that says how
+ * this instance backs up while leaving the password those options are carried out with. What is
+ * left is an instance encrypting its backups with the password of a database that is no longer
+ * here, saying nothing about it, and producing backups the user cannot open.
+ */
+ async adoptPassphrase(passphrase: string | null): Promise<void> {
+ await this.config.setPassphrase?.(passphrase);
+ }
+
/**
* Settles what the backup is written as, from what the user asked for where they were asked at
* all, and from the instance's own options where they were not.
diff --git a/apps/server/src/services/database_restore.spec.ts b/apps/server/src/services/database_restore.spec.ts
index 7a6aee39ba..3a3f3771d4 100644
--- a/apps/server/src/services/database_restore.spec.ts
+++ b/apps/server/src/services/database_restore.spec.ts
@@ -1,13 +1,15 @@
import { writeBackupContainer } from "@triliumnext/backup-container";
-import { app_info as appInfo, getLog, getSql } from "@triliumnext/core";
+import { app_info as appInfo, getBackup, getLog, getSql } from "@triliumnext/core";
import Database from "better-sqlite3";
import fs from "fs";
import os from "os";
import path from "path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type ServerBackupService from "../backup_provider.js";
import dataDir from "./data_dir.js";
import {
+ adoptBackupPassphrase,
exchangeDatabaseFiles,
getRestoreProgress,
logRestore,
@@ -18,6 +20,7 @@ import {
reportRestoreFailure,
restoreDatabase,
RestoreFailure,
+ type RestoreRequest,
stageBackup
} from "./database_restore.js";
@@ -479,3 +482,47 @@ describe("restoring a database", () => {
expect(getRestoreProgress()).toMatchObject({ stage: "failed", reason: "database-too-new" });
});
});
+
+describe("the backup password after a restore", () => {
+ /** What the restore reaches for: the desktop's keyring, by way of the backup service. */
+ const backupService = () => getBackup() as ServerBackupService;
+
+ function request(passphrase?: string): RestoreRequest {
+ const fileName = "backup.tnbackup";
+
+ return { path: fileName, fileName, consumable: false, passphrase };
+ }
+
+ it("takes on the password that opened the backup, which is this database's now", async () => {
+ const adopted = vi.spyOn(backupService(), "adoptPassphrase").mockResolvedValue();
+
+ await adoptBackupPassphrase(request("the newer database's password"), true);
+
+ expect(adopted).toHaveBeenCalledWith("the newer database's password");
+ });
+
+ it.each([
+ [ "an unlocked backup", undefined ],
+ [ "a password typed for a backup that turned out not to need one", "typed anyway" ]
+ ])("lets go of the stored password after %s", async (_label, passphrase) => {
+ // The stored one belongs to the database that was here before. Kept, this instance goes on
+ // encrypting with it and writes backups the password the user expects will not open.
+ const adopted = vi.spyOn(backupService(), "adoptPassphrase").mockResolvedValue();
+
+ await adoptBackupPassphrase(request(passphrase), false);
+
+ expect(adopted).toHaveBeenCalledWith(null);
+ });
+
+ it("does not fail a restore that already happened over a keyring that will not answer", async () => {
+ const said: string[] = [];
+ vi.spyOn(getLog(), "error").mockImplementation((message) => said.push(String(message)));
+ vi.spyOn(backupService(), "adoptPassphrase")
+ .mockRejectedValue(new Error("the keyring is locked"));
+
+ // The database is in place and open by this point; there is nothing left to undo and no
+ // honest way to call the restore failed.
+ await expect(adoptBackupPassphrase(request("a password"), true)).resolves.toBeUndefined();
+ expect(said.join("\n")).toContain("the keyring is locked");
+ });
+});
diff --git a/apps/server/src/services/database_restore.ts b/apps/server/src/services/database_restore.ts
index c5f7a52fc2..28054c9fe6 100644
--- a/apps/server/src/services/database_restore.ts
+++ b/apps/server/src/services/database_restore.ts
@@ -10,6 +10,7 @@ import {
cls,
type DatabaseRejection,
events as eventService,
+ getBackup,
getLog,
getSql,
leaveSetupMode,
@@ -19,6 +20,7 @@ import {
import fs from "fs";
import path from "path";
+import type ServerBackupService from "../backup_provider.js";
import config from "./config.js";
import dataDir from "./data_dir.js";
import { validateDatabaseFile } from "./database_validation.js";
@@ -256,6 +258,10 @@ export async function restoreDatabase(request: RestoreRequest): Promise<void> {
// is stated below in terms that are not.
logRestore(`starting, from ${request.consumable ? "a backup this instance was given" : "a backup already on this device"}`);
+ // Read here rather than taken from the staging that follows, which consumes a backup this
+ // instance was given: by the time the restore has finished there may be no file left to ask.
+ const wasEncrypted = readBackupFormat(request.path)?.encrypted ?? false;
+
// Announced through `report` like every other step, so that a log can be read by looking for the
// steps alone and the first one is not the exception that is missing.
progress = { stage: "staging", fileName: request.fileName };
@@ -283,6 +289,8 @@ export async function restoreDatabase(request: RestoreRequest): Promise<void> {
await openRestoredDatabase(validation.needsMigration);
});
+ await adoptBackupPassphrase(request, wasEncrypted);
+
report("done");
logRestore(`finished in ${describeElapsed(startedAt)}`);
} catch (e) {
@@ -310,6 +318,39 @@ export async function restoreDatabase(request: RestoreRequest): Promise<void> {
}
}
+/**
+ * Brings the stored backup passphrase into line with the database that has just been restored.
+ *
+ * The passphrase lives outside the database — an OS keyring on the desktop, nowhere at all
+ * elsewhere — so it is the one thing about how this instance backs up that a restore does not
+ * replace. Left alone, an instance restored from someone else's backup goes on encrypting with the
+ * password of the database it used to hold: the backups look fine, and the password the user
+ * expects does not open them.
+ *
+ * Never allowed to fail the restore. The database is already in place and open by this point, and a
+ * keyring that would not answer is not a reason to tell the user their restore did not work.
+ *
+ * @param wasEncrypted whether the backup was locked, which is what decides there is a password here
+ * worth taking on at all.
+ */
+export async function adoptBackupPassphrase(
+ request: RestoreRequest,
+ wasEncrypted: boolean
+): Promise<void> {
+ // A backup with no lock on it brings no password to take on, and the stored one is not an
+ // answer: it was the previous database's.
+ const passphrase = wasEncrypted ? request.passphrase ?? null : null;
+
+ try {
+ await (getBackup() as ServerBackupService).adoptPassphrase(passphrase);
+ logRestore(passphrase
+ ? "the backup password is now the one that opened this backup"
+ : "let go of the backup password, which belonged to the previous database");
+ } catch (e) {
+ logRestoreError(`the backup password could not be brought up to date: ${messageOf(e)}`);
+ }
+}
+
/**
* Records a failure that happened *instead of* a restore rather than during one, e.g. one that was
* refused before it could start.