From 950942f7b9d8950607b955f879eae3b53c93f8e0 Mon Sep 17 00:00:00 2001 From: Maurice Date: Mon, 23 Nov 2026 15:38:39 +0100 Subject: [PATCH] fix(backup): refuse a Postgres restore of another schema or past the size limit with a 400 The admin restore now writes and checks the restore script while it verifies the archive, so a dump without TREK's tables in the target schema or one expanding past BACKUP_MAX_DECOMPRESSED_MB is refused before a pre-restore copy is kept, and the restore runs the checked script. --- server/src/db/engine/postgres/pg-tools.ts | 52 +++++++++++++++---- .../nest/backup/postgres-database-backup.ts | 30 +++++++++-- .../nest/postgres-database-backup.test.ts | 25 ++++++++- 3 files changed, 92 insertions(+), 15 deletions(-) diff --git a/server/src/db/engine/postgres/pg-tools.ts b/server/src/db/engine/postgres/pg-tools.ts index 4dffedc33..e3ea50c42 100644 --- a/server/src/db/engine/postgres/pg-tools.ts +++ b/server/src/db/engine/postgres/pg-tools.ts @@ -177,7 +177,7 @@ async function writeRestoreScript( * 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. + * they unpack or copy anything, and `pgPrepareRestore` asks it again. */ export async function pgRestoreTarget(url: string, binDir: string | undefined): Promise { await refuseToolsWithoutRestrict(binDir); @@ -194,7 +194,29 @@ export async function pgRestoreTarget(url: string, binDir: string | undefined): * dump holds is left out), then psql clears the schema, drops the plugin * schemas TREK's role owns, creates the dump's and runs the script, all in * one transaction, so a restore that fails leaves the database as it was. No - * other schema of the database is touched. Refused before anything is cleared: + * other schema of the database is touched. Refused before anything is cleared, + * by {@link pgPrepareRestore}. The work files are removed whatever happens. + */ +export async function pgRestore( + url: string, + source: string, + binDir: string | undefined, + maxScriptBytes: number, +): Promise { + await pgRunRestore(url, await pgPrepareRestore(url, source, binDir, maxScriptBytes), binDir); +} + +/** A restore whose script pg_restore has written and checked, ready for psql to run. */ +export interface PreparedPgRestore { + readonly source: string; + readonly workDir: string; + readonly clear: string; + readonly script: string; +} + +/** + * Writes the work files of a restore of the dump at `source` into a folder + * beside it, refusing (and removing them) on: * * - client tools without the CVE-2025-8714 fix, or older than the server; * - a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL`), @@ -203,15 +225,13 @@ export async function pgRestoreTarget(url: string, binDir: string | undefined): * compressed once more inside the archive, so its script is held to the * limit while pg_restore writes it, not only the archive's entry; * - a dump without TREK's tables in that schema. - * - * The work files are removed whatever happens. */ -export async function pgRestore( +export async function pgPrepareRestore( url: string, source: string, binDir: string | undefined, maxScriptBytes: number, -): Promise { +): Promise { const { schema, major } = await pgRestoreTarget(url, binDir); const workDir = fs.mkdtempSync(path.join(path.dirname(source), '.pg-restore-')); try { @@ -227,6 +247,20 @@ export async function pgRestore( if (!(await scriptHoldsTrekSchema(script, schema))) { throw new Error(`The backup holds no TREK tables in the schema "${schema.name}"; nothing was replaced.`); } + return { source, workDir, clear, script }; + } catch (err) { + fs.rmSync(workDir, { recursive: true, force: true }); + throw err; + } +} + +/** Runs a prepared restore in one psql transaction, then removes its work files. */ +export async function pgRunRestore( + url: string, + prepared: PreparedPgRestore, + binDir: string | undefined, +): Promise { + try { await run( 'psql', binDir, @@ -236,13 +270,13 @@ export async function pgRestore( '--single-transaction', '--set=ON_ERROR_STOP=1', `--output=${os.devNull}`, - `--file=${clear}`, - `--file=${script}`, + `--file=${prepared.clear}`, + `--file=${prepared.script}`, ], { ...pgConnectionEnv(url), PGOPTIONS: RESTORE_SESSION_OPTIONS }, ); } finally { - fs.rmSync(workDir, { recursive: true, force: true }); + fs.rmSync(prepared.workDir, { recursive: true, force: true }); } } diff --git a/server/src/nest/backup/postgres-database-backup.ts b/server/src/nest/backup/postgres-database-backup.ts index 73c5a8fd1..1c269254d 100644 --- a/server/src/nest/backup/postgres-database-backup.ts +++ b/server/src/nest/backup/postgres-database-backup.ts @@ -1,7 +1,14 @@ import type { DbSettings } from '../../app-config'; import { postgresTarget, type DatabaseEngine } from '../../db/engine'; import { PgToolMissingError } from '../../db/engine/postgres/pg-process'; -import { pgDump, pgDumpMigrations, pgRestore, pgRestoreTarget } from '../../db/engine/postgres/pg-tools'; +import { + pgDump, + pgDumpMigrations, + pgPrepareRestore, + pgRestore, + pgRunRestore, + type PreparedPgRestore, +} from '../../db/engine/postgres/pg-tools'; import { unknownMigrations } from '../../db/known-migrations'; import { DataPathsService } from '../app-config/data-paths.service'; import { logWarn } from '../audit/audit-log.logger'; @@ -90,6 +97,8 @@ export class PostgresDatabaseBackup implements DatabaseBackupStrategy { readonly archiveEntry = PG_ARCHIVE_ENTRY; /** The URL and the tools' directory; null on SQLite, where this provider is built but never called. */ private readonly target: ReturnType; + /** The restore `verify` prepared for the archive it checked, run by the `replace` that follows. */ + private prepared: PreparedPgRestore | null = null; constructor( private readonly lifecycle: DatabaseLifecycle, @@ -127,14 +136,22 @@ export class PostgresDatabaseBackup implements DatabaseBackupStrategy { /** * Throws a DomainError (400) with the refusal when the archive cannot be * restored here, before anything is replaced or copied: the dump's own - * checks, then the tools, the server and the role `pgRestore` would refuse. + * checks, then everything `pgPrepareRestore` refuses (the tools, the server, + * the role, the script's size and schema). The prepared script waits beside + * the dump for `replace`. */ async verify(extractDir: string): Promise { const { url, binDir } = this.connection; const refusal = await checkPostgresDump(extractDir, binDir); if (refusal) throw new DomainError(400, refusal); + this.prepared = null; try { - await pgRestoreTarget(url, binDir); + this.prepared = await pgPrepareRestore( + url, + path.join(extractDir, PG_ARCHIVE_ENTRY), + binDir, + MAX_BACKUP_DECOMPRESSED_SIZE, + ); } catch (err) { throw new DomainError(400, describeError(err)); } @@ -155,8 +172,13 @@ export class PostgresDatabaseBackup implements DatabaseBackupStrategy { return replaceThenReopen( async () => { const { url, binDir } = this.connection; + const prepared = this.prepared?.source === source ? this.prepared : null; + this.prepared = null; + const restore = prepared + ? pgRunRestore(url, prepared, binDir) + : pgRestore(url, source, binDir, MAX_BACKUP_DECOMPRESSED_SIZE); // A rejection with no reason still has to fail the swap, so it is never swallowed. - await pgRestore(url, source, binDir, MAX_BACKUP_DECOMPRESSED_SIZE).catch((err: unknown) => { + await restore.catch((err: unknown) => { throw err ?? new Error('pg_restore failed'); }); }, diff --git a/server/tests/unit/nest/postgres-database-backup.test.ts b/server/tests/unit/nest/postgres-database-backup.test.ts index 41e44d380..6b2f7a7b9 100644 --- a/server/tests/unit/nest/postgres-database-backup.test.ts +++ b/server/tests/unit/nest/postgres-database-backup.test.ts @@ -21,7 +21,7 @@ import { writesRestrictedScript, } from '../../helpers/fake-pg-tools'; -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -85,10 +85,31 @@ describe('PostgresDatabaseBackup', () => { it('PGBACKUP-002: verify accepts a TREK dump this build knows', async () => { writeFileSync(path.join(extract, 'travel.pgdump'), 'dump'); - installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3))] }); + installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3)), writesRestrictedScript()] }); await expect(backup.verify(extract)).resolves.toBeUndefined(); }); + it('PGBACKUP-002h: verify refuses a dump of another schema with a 400, leaving no work files, before a copy is kept', async () => { + writeFileSync(path.join(extract, 'travel.pgdump'), 'dump'); + installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3)), writesRestrictedScript()] }); + installFakeTool(bin, 'psql', { snippets: [answersSchema('trek')] }); + expect(await refusal(backup.verify(extract))).toEqual({ + status: 400, + message: 'The backup holds no TREK tables in the schema "trek"; nothing was replaced.', + }); + expect(readdirSync(extract)).toEqual(['travel.pgdump']); + }); + + it('PGBACKUP-002i: replace runs the script verify prepared, without asking pg_restore again', async () => { + const source = path.join(extract, 'travel.pgdump'); + writeFileSync(source, 'dump'); + installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3)), writesRestrictedScript()] }); + await backup.verify(extract); + installFakeTool(bin, 'pg_restore', { snippets: [failsWith('pg_restore must not run again')] }); + await expect(backup.replace(source)).resolves.toEqual({ reopenError: null }); + expect(readdirSync(extract)).toEqual(['travel.pgdump']); + }); + it('PGBACKUP-002a: verify refuses an archive without a TREK dump in it', async () => { expect(await refusal(backup.verify(extract))).toEqual({ status: 400,