From 89da19e5354d0e552e6e594783ec7951f7c810fb Mon Sep 17 00:00:00 2001 From: Maurice Date: Mon, 23 Nov 2026 14:57:15 +0100 Subject: [PATCH] fix(backup): refuse a Postgres restore the role or tools cannot run before anything is copied The admin restore now answers a privileged role, old client tools or an unreachable server with a 400 naming the reason, before it keeps a pre-restore dump. RESTORE_FROM_BACKUP checks the same before it unpacks the archive, and removes the unpacked copy when the load fails. --- server/src/db/engine/postgres/pg-tools.ts | 20 ++++++++-- server/src/nest/backup/boot-restore.ts | 30 ++++++++++++-- .../nest/backup/postgres-database-backup.ts | 16 ++++++-- server/tests/unit/nest/boot-restore.test.ts | 39 +++++++++++++++++-- .../nest/postgres-database-backup.test.ts | 20 ++++++++++ 5 files changed, 112 insertions(+), 13 deletions(-) diff --git a/server/src/db/engine/postgres/pg-tools.ts b/server/src/db/engine/postgres/pg-tools.ts index 5f72662ea..4dffedc33 100644 --- a/server/src/db/engine/postgres/pg-tools.ts +++ b/server/src/db/engine/postgres/pg-tools.ts @@ -172,6 +172,21 @@ async function writeRestoreScript( } } +/** + * The server a restore into the database at `url` loads into, once the + * checks that need no dump have passed: client tools with the CVE-2025-8714 + * fix and not older than the server, and a role that could not reach the + * database host (`PRIVILEGED_ROLE_SQL`). Both restore paths ask it before + * they unpack or copy anything, and `pgRestore` asks it again. + */ +export async function pgRestoreTarget(url: string, binDir: string | undefined): Promise { + await refuseToolsWithoutRestrict(binDir); + const server = await pgServer(url, binDir); + if (server.privileged) throw new Error(PRIVILEGED_RESTORE_REFUSAL); + await refuseClientOlderThanServer(['pg_restore', 'psql'], binDir, server.major); + return server; +} + /** * Replaces the current schema of the database at `url` with the dump at * `source`, and the plugin data schemas with the dump's: pg_restore turns the @@ -197,10 +212,7 @@ export async function pgRestore( binDir: string | undefined, maxScriptBytes: number, ): Promise { - await refuseToolsWithoutRestrict(binDir); - const { schema, major, privileged } = await pgServer(url, binDir); - if (privileged) throw new Error(PRIVILEGED_RESTORE_REFUSAL); - await refuseClientOlderThanServer(['pg_restore', 'psql'], binDir, major); + const { schema, major } = await pgRestoreTarget(url, binDir); const workDir = fs.mkdtempSync(path.join(path.dirname(source), '.pg-restore-')); try { const clear = path.join(workDir, 'clear-schema.sql'); diff --git a/server/src/nest/backup/boot-restore.ts b/server/src/nest/backup/boot-restore.ts index 388deb593..e3a66e9bc 100644 --- a/server/src/nest/backup/boot-restore.ts +++ b/server/src/nest/backup/boot-restore.ts @@ -1,4 +1,5 @@ -import { pgRestore, pgTablesInUse } from '../../db/engine/postgres/pg-tools'; +import { pgRestore, pgRestoreTarget, pgTablesInUse } from '../../db/engine/postgres/pg-tools'; +import { describeError } from '../common/describe-error'; import { stageExtractedPluginTrees } from '../plugins/plugin-backup'; import { checkBackupDatabase, @@ -85,6 +86,18 @@ async function checkArchiveDatabase(plan: BootRestorePlan, staging: string): Pro return checkBackupDatabase(staging)?.error ?? null; } +/** + * Refuses a Postgres restore the tools, the server or the role would refuse + * anyway (`pgRestoreTarget`), before the archive is unpacked. + */ +async function refuseRestoreTarget(target: { url: string; binDir: string | undefined }): Promise { + try { + await pgRestoreTarget(target.url, target.binDir); + } catch (err) { + throw new BootRestoreError(`RESTORE_FROM_BACKUP: ${describeError(err)}`, { cause: err }); + } +} + /** Puts the archive's database in place: renamed in beside the file, or loaded into Postgres in one transaction. */ async function putDatabaseInPlace(plan: BootRestorePlan, staging: string): Promise { if (plan.postgres) { @@ -112,6 +125,8 @@ export async function restoreOnFirstBoot(plan: BootRestorePlan): Promise { - const refusal = await checkPostgresDump(extractDir, this.connection.binDir); + const { url, binDir } = this.connection; + const refusal = await checkPostgresDump(extractDir, binDir); if (refusal) throw new DomainError(400, refusal); + try { + await pgRestoreTarget(url, binDir); + } catch (err) { + throw new DomainError(400, describeError(err)); + } } /** A kept copy must be a dump this build can restore: a SQLite file a switch of engine left behind is refused. */ diff --git a/server/tests/unit/nest/boot-restore.test.ts b/server/tests/unit/nest/boot-restore.test.ts index 484a4f001..dec15b820 100644 --- a/server/tests/unit/nest/boot-restore.test.ts +++ b/server/tests/unit/nest/boot-restore.test.ts @@ -12,6 +12,7 @@ import { answersSchema, answersHistoryRows, answersTables, + failsWith, installFakeTool, listsMigrations, touches, @@ -142,15 +143,21 @@ describe('restoreOnFirstBoot', () => { * known migration as the dump's history, or writes a restricted script. * Their arguments are pinned in pg-tools.test.ts. */ - const postgresPlan = (archivePath: string, tables: string[] = [], historyRows = 0) => { + const postgresPlan = ( + archivePath: string, + tables: string[] = [], + historyRows = 0, + server: Parameters[2] = {}, + load = touches(path.join(root, 'loaded')), + ) => { const bin = path.join(root, 'bin'); fs.mkdirSync(bin, { recursive: true }); installFakeTool(bin, 'psql', { snippets: [ - answersSchema(), + answersSchema('public', 'public', server), answersTables(tables), answersHistoryRows(historyRows), - touches(path.join(root, 'loaded')), + load, ], }); const migration = [...knownMigrationNames()][0]; @@ -200,6 +207,32 @@ describe('restoreOnFirstBoot', () => { expect(loaded()).toBe(false); }); + const scratch = () => fs.readdirSync(dataDir).filter((f) => f.startsWith('restore-boot-')); + + it('BOOT-RESTORE-004g: a restore the database refuses leaves neither the unpacked archive nor the reclaim marker', async () => { + const plan = postgresPlan( + await archive({ 'travel.pgdump': 'dump', 'uploads/a.jpg': 'jpeg' }), + [], + 0, + {}, + failsWith('psql: error: permission denied for schema public'), + ); + await expect(restoreOnFirstBoot(plan)).rejects.toThrow('psql failed: psql: error: permission denied'); + expect(scratch()).toEqual([]); + expect(fs.existsSync(reclaimResetFile)).toBe(false); + }); + + it('BOOT-RESTORE-004h: a role that could reach the database host is refused before the archive is unpacked', async () => { + const plan = postgresPlan(await archive({ 'travel.pgdump': 'dump' }), [], 0, { privileged: true }); + await expect(restoreOnFirstBoot(plan)).rejects.toThrow( + /^RESTORE_FROM_BACKUP: TREK_DB_URL connects as a superuser/, + ); + await expect(restoreOnFirstBoot(plan)).rejects.toBeInstanceOf(BootRestoreError); + expect(loaded()).toBe(false); + expect(scratch()).toEqual([]); + expect(fs.existsSync(reclaimResetFile)).toBe(false); + }); + it('BOOT-RESTORE-004d: a SQLite backup is refused before anything is loaded, leaving no scratch', async () => { const plan = postgresPlan(await goodArchive()); await expect(restoreOnFirstBoot(plan)).rejects.toThrow( diff --git a/server/tests/unit/nest/postgres-database-backup.test.ts b/server/tests/unit/nest/postgres-database-backup.test.ts index 4baa4070e..ba8fbcb7a 100644 --- a/server/tests/unit/nest/postgres-database-backup.test.ts +++ b/server/tests/unit/nest/postgres-database-backup.test.ts @@ -136,6 +136,26 @@ describe('PostgresDatabaseBackup', () => { else expect(refused.message).toMatch(message); }); + it.each([ + { + id: 'PGBACKUP-002f', + server: { privileged: true }, + message: /^TREK_DB_URL connects as a superuser or a member of a superuser role/, + }, + { + id: 'PGBACKUP-002g', + server: { versionNum: '180001' }, + message: /^pg_restore is version 17, older than the PostgreSQL 18 server/, + }, + ])('$id: verify refuses what the restore itself would refuse, before a copy is kept', async ({ server, message }) => { + writeFileSync(path.join(extract, 'travel.pgdump'), 'dump'); + installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3))] }); + installFakeTool(bin, 'psql', { snippets: [answersSchema('public', 'public', server)] }); + const refused = await refusal(backup.verify(extract)); + expect(refused.status).toBe(400); + expect(refused.message).toMatch(message); + }); + it('PGBACKUP-003: keeps a dump of the database a restore replaces, or says it could not', async () => { vi.spyOn(console, 'log').mockImplementation(() => undefined); vi.spyOn(console, 'warn').mockImplementation(() => undefined);