Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
core/backup import: fix handling wrong password for encrypted backup containers
Adorian Dorana921afc32ae5
diff --git a/apps/server/src/routes/api/setup_restore.ts b/apps/server/src/routes/api/setup_restore.tsindex 19ab600aeb..aa2c587bae 100644--- a/apps/server/src/routes/api/setup_restore.ts+++ b/apps/server/src/routes/api/setup_restore.ts@@ -9,6 +9,7 @@ import dataDir from "../../services/data_dir.js";import {getRestoreProgress,readBackupFormat,+ removeQuietly,reportRestoreFailure,restoreDatabase,RestoreFailure,@@ -204,10 +205,16 @@ function existingBackup(filePath: string | undefined) {return { path: resolvedPath, fileName: path.basename(resolvedPath), consumable: false };}-/** Frees setup and the disk once an upload is restored, abandoned, or found to be unusable. */+/**+ * Frees setup and the disk once an upload is restored, abandoned, or found to be unusable.+ *+ * Runs while a failure is on its way to the user, so the file not going quietly must not become the+ * failure they are told about. Setup is freed either way: a file left behind costs disk, a lock left+ * behind costs them every other way out of the setup screen.+ */function discardPendingUpload() {pendingUpload = null;- fs.rmSync(PENDING_UPLOAD_PATH, { force: true });+ removeQuietly(PENDING_UPLOAD_PATH);releaseSetupHold?.();releaseSetupHold = null;diff --git a/apps/server/src/services/database_restore.spec.ts b/apps/server/src/services/database_restore.spec.tsindex defd7008c1..af43d23274 100644--- a/apps/server/src/services/database_restore.spec.ts+++ b/apps/server/src/services/database_restore.spec.ts@@ -143,6 +143,24 @@ describe("staging a backup", () => {expect(fs.existsSync(backup)).toBe(true);});+ it("closes both files when the unwrap fails, so what is left can be deleted and replaced", async () => {+ // Windows refuses to delete or overwrite an open file, so a leaked handle turns one wrong+ // password into a staging directory that cannot be cleared (ENOTEMPTY) and an uploaded+ // backup the next attempt cannot replace (EPERM).+ const backup = await containerOf(validDatabase(), "hunter2");+ const opened = vi.spyOn(fs, "createReadStream");+ const written = vi.spyOn(fs, "createWriteStream");++ await expect(stageBackup({ path: backup, fileName: "b.tnbackup", consumable: false, passphrase: "wrong" }))+ .rejects.toMatchObject({ reason: "wrong-passphrase-or-damaged-header" });++ expect(opened.mock.results[0].value.closed).toBe(true);+ expect(written.mock.results[0].value.closed).toBe(true);+ // Which is what the caller then relies on, on both counts.+ expect(() => fs.rmSync(path.dirname(String(written.mock.calls[0][0])), { recursive: true })).not.toThrow();+ expect(() => fs.rmSync(backup)).not.toThrow();+ });+it("refuses a file it cannot even open", async () => {await expect(stageBackup({ path: path.join(tempRoot, "gone.db"), fileName: "gone.db", consumable: false })).rejects.toMatchObject({ reason: "not-a-database" });@@ -246,6 +264,22 @@ describe("restoring a database", () => {});});+ it("reports why it failed even when the tidying up afterwards fails too", async () => {+ // A throw from the `finally` would replace the failure on its way out, and the client would+ // be told the temporary directory would not delete rather than that the password was wrong.+ vi.spyOn(fs, "rmSync").mockImplementation(() => {+ throw new Error("ENOTEMPTY, Directory not empty");+ });++ await expect(restoreDatabase({+ path: fileWith("a photograph, renamed"),+ fileName: "holiday.db",+ consumable: false+ })).rejects.toMatchObject({ reason: "not-a-database" });++ expect(getRestoreProgress()).toMatchObject({ stage: "failed", reason: "not-a-database" });+ });+it("records a failure that happened instead of a restore, so nothing waits on a run that never began", () => {reportRestoreFailure("backup.db", new Error("setup is already busy with 'new-document'"));diff --git a/apps/server/src/services/database_restore.ts b/apps/server/src/services/database_restore.tsindex 487843b280..634c5343b6 100644--- a/apps/server/src/services/database_restore.ts+++ b/apps/server/src/services/database_restore.ts@@ -140,8 +140,11 @@ export async function restoreDatabase(request: RestoreRequest): Promise<void> {throw failure;} finally {- // Whatever happened, the temporary files are of no further use.- fs.rmSync(stagingDirectory(), { recursive: true, force: true });+ // Whatever happened, the temporary files are of no further use. Tidying up is never allowed+ // to throw from here: an exception raised in a `finally` replaces the one on its way out, so+ // a directory that would not delete used to bury the reason the restore actually failed —+ // and with it the client's only way of telling a wrong passphrase from a broken backup.+ removeQuietly(stagingDirectory(), { recursive: true });}}@@ -285,11 +288,20 @@ export async function stageBackup(request: RestoreRequest): Promise<string> {}const candidate = freshCandidatePath();- await readBackupContainer(- fs.createReadStream(request.path),- fs.createWriteStream(candidate),- { passphrase: request.passphrase }- );+ const source = fs.createReadStream(request.path);+ const destination = fs.createWriteStream(candidate);++ try {+ await readBackupContainer(source, destination, { passphrase: request.passphrase });+ } finally {+ // Both streams are closed here rather than left to the reader, which only ends them once it+ // gets as far as its pipeline: a wrong passphrase is refused before that, from the header, so+ // on a failure the two handles are still open. Windows will not let an open file be deleted+ // or replaced, which turns one wrong password into a staging directory that cannot be+ // cleared and an uploaded backup that cannot be overwritten by the next attempt.+ await closeStream(source);+ await closeStream(destination);+ }if (request.consumable) {await fs.promises.rm(request.path, { force: true });@@ -367,6 +379,39 @@ function report(stage: RestoreStage): void {}}+/**+ * Deletes something that is no longer wanted, and carries on if it will not go.+ *+ * Every use of this is cleaning up after something else, on a path that is already reporting its own+ * outcome. A leftover temporary file is worth a line in the log; it is not worth replacing the answer+ * the caller was about to give, and on Windows a file another process has briefly opened — a virus+ * scanner, an indexer — is a failure that says nothing about the operation at hand.+ */+export function removeQuietly(target: string, options: { recursive?: boolean } = {}): void {+ try {+ fs.rmSync(target, { force: true, recursive: options.recursive });+ } catch (e) {+ getLog().error(`Could not remove a temporary file after a restore: ${messageOf(e)}`);+ }+}++/**+ * Releases a stream's file handle and waits for the operating system to agree that it is released.+ *+ * Waiting is the point: `destroy()` only asks, and the handle is still open until `close` fires.+ * Anything that then tries to delete or replace the file on Windows fails until it does.+ */+function closeStream(stream: NodeJS.EventEmitter & { closed: boolean; destroy(): void }): Promise<void> {+ if (stream.closed) {+ return Promise.resolve();+ }++ return new Promise((resolve) => {+ stream.once("close", () => resolve());+ stream.destroy();+ });+}+function stagingDirectory(): string {return path.join(dataDir.TMP_DIR, "restore");}