fix(backup): refuse a Postgres dump from a newer server major before restoring it

The restore reads the server version the dump was taken from in its table of contents and refuses, naming both majors, before anything is cleared, from the admin restore (400) and from RESTORE_FROM_BACKUP alike.
This commit is contained in:
Maurice
2026-11-23 17:18:05 +01:00
parent b03597957c
commit c4326ec545
4 changed files with 73 additions and 10 deletions
+25 -7
View File
@@ -219,6 +219,8 @@ export interface PreparedPgRestore {
* beside it, refusing (and removing them) on:
*
* - client tools without the CVE-2025-8714 fix, or older than the server;
* - a dump taken from a newer server major than this one, whose DDL an older
* server may not know;
* - a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL`),
* since the script comes from an archive and runs as that role;
* - a script past `maxScriptBytes` (BACKUP_MAX_DECOMPRESSED_MB): the dump is
@@ -237,7 +239,14 @@ export async function pgPrepareRestore(
try {
const clear = path.join(workDir, 'clear-schema.sql');
const script = path.join(workDir, 'restore.sql');
const pluginSchemas = await dumpPluginSchemas(source, path.join(workDir, 'toc.txt'), binDir);
const { pluginSchemas, dumpedFromMajor } = await readDumpToc(source, path.join(workDir, 'toc.txt'), binDir);
if (dumpedFromMajor !== null && dumpedFromMajor > major) {
throw new Error(
`The backup was dumped from PostgreSQL ${dumpedFromMajor}, newer than the PostgreSQL ${major} server ` +
`it would be restored into; nothing was replaced. Restore it into a PostgreSQL ${dumpedFromMajor} ` +
'server or newer.',
);
}
fs.writeFileSync(clear, CLEAR_SCHEMA_SQL + pluginSchemasSql(pluginSchemas), { mode: 0o600 });
createPrivateFile(script);
await writeRestoreScript(source, script, [schema.name, ...pluginSchemas], binDir, {
@@ -281,20 +290,29 @@ export async function pgRunRestore(
}
/**
* The plugin data schemas the dump at `source` holds, read from its table of
* contents (`pg_restore --list`, written to `toc`), which has a line
* `<id>; <oid> <oid> SCHEMA - <name> <owner>` per schema. Only a name TREK
* gives a plugin schema counts.
* What a restore reads from the table of contents of the dump at `source`
* (`pg_restore --list`, written to `toc`): the plugin data schemas it holds,
* from its `<id>; <oid> <oid> SCHEMA - <name> <owner>` lines (only a name TREK
* gives a plugin schema counts), and the major version of the server it was
* dumped from, from its `Dumped from database version` header (null when the
* header is missing).
*/
async function dumpPluginSchemas(source: string, toc: string, binDir: string | undefined): Promise<string[]> {
async function readDumpToc(
source: string,
toc: string,
binDir: string | undefined,
): Promise<{ pluginSchemas: string[]; dumpedFromMajor: number | null }> {
createPrivateFile(toc);
await run('pg_restore', binDir, ['--list', `--file=${toc}`, '--', source], {});
const names = new Set<string>();
let dumpedFromMajor: number | null = null;
for (const line of fs.readFileSync(toc, 'utf8').split('\n')) {
const name = /^\d+; \d+ \d+ SCHEMA - (\S+) /.exec(line)?.[1];
if (name !== undefined && isPluginSchemaName(name)) names.add(name);
const version = /^;\s+Dumped from database version: (\d+)/.exec(line)?.[1];
if (version !== undefined) dumpedFromMajor = Number(version);
}
return [...names].sort((a, b) => a.localeCompare(b));
return { pluginSchemas: [...names].sort((a, b) => a.localeCompare(b)), dumpedFromMajor };
}
/** The tables in the current schema of the database at `url`, read before TREK opens it. */
+6 -3
View File
@@ -86,10 +86,13 @@ export function writesRestrictedScript(table = 'public.mikro_orm_migrations'): s
/**
* Answers a `--list` call with a table of contents holding a SCHEMA line for
* each of `schemas`, written to its `--file=`, as `pg_restore --list` does.
* each of `schemas`, written to its `--file=`, as `pg_restore --list` does,
* under a header naming the server version the dump was taken from, if given.
*/
export function listsSchemas(schemas: readonly string[]): string {
const toc = schemas.map((name, i) => `${i + 4}; 2615 ${16000 + i} SCHEMA - ${name} trek\n`).join('');
export function listsSchemas(schemas: readonly string[], dumpedFrom?: string): string {
const header = dumpedFrom === undefined ? '' : `;\n; Dumped from database version: ${dumpedFrom}\n;\n`;
const lines = schemas.map((name, i) => `${i + 4}; 2615 ${16000 + i} SCHEMA - ${name} trek\n`).join('');
const toc = header + lines;
return `case "$*" in *--list*) printf '%s' ${shellWord(toc)} | fake_write "$@"; exit 0;; esac`;
}
@@ -417,4 +417,31 @@ describe('pg-tools', () => {
installFakeTool(bin, 'pg_restore', { snippets: [printsWhen('--data-only', forged)] });
await expect(pgDumpMigrations('/data/in.pgdump', bin)).resolves.toEqual([]);
});
it('PGTOOLS-022: a dump from a newer server major is refused before anything is cleared, naming both majors', async () => {
const psqlLog = installFakeTool(bin, 'psql', { version: '18.1', snippets: [answersSchema()] });
installFakeTool(bin, 'pg_restore', {
version: '18.1',
snippets: [listsSchemas([], '18.1 (Debian 18.1-1.pgdg13+2)'), writesRestrictedScript()],
});
await expect(pgRestore(URL_WITH_SECRET, path.join(out, 'in.pgdump'), bin, LIMIT)).rejects.toThrow(
'The backup was dumped from PostgreSQL 18, newer than the PostgreSQL 17 server it would be restored into; ' +
'nothing was replaced.',
);
expect(readToolCall(psqlLog).args.join(' ')).not.toContain('--single-transaction');
expect(readdirSync(out)).toEqual([]);
});
it.each(['17.6', '14.19'])(
'PGTOOLS-022b: a dump from %s restores into a PostgreSQL 17 server',
async (dumpedFrom) => {
const psqlLog = installFakeTool(bin, 'psql', { version: '18.1', snippets: [answersSchema()] });
installFakeTool(bin, 'pg_restore', {
version: '18.1',
snippets: [listsSchemas([], dumpedFrom), writesRestrictedScript()],
});
await pgRestore(URL_WITH_SECRET, path.join(out, 'in.pgdump'), bin, LIMIT);
expect(readToolCall(psqlLog).args).toContain('--single-transaction');
},
);
});
@@ -15,6 +15,7 @@ import {
failsWith,
installFakeTool,
listsMigrations,
listsSchemas,
touches,
writesRestrictedScript,
} from '../../helpers/fake-pg-tools';
@@ -233,6 +234,20 @@ describe('restoreOnFirstBoot', () => {
expect(fs.existsSync(reclaimResetFile)).toBe(false);
});
it('BOOT-RESTORE-004i: a dump from a newer server major is refused before anything is loaded, naming both', async () => {
const plan = postgresPlan(await archive({ 'travel.pgdump': 'dump' }));
const migration = [...knownMigrationNames()][0];
installFakeTool(plan.postgres.binDir, 'pg_restore', {
snippets: [listsSchemas([], '18.1'), listsMigrations([migration]), writesRestrictedScript()],
});
await expect(restoreOnFirstBoot(plan)).rejects.toThrow(
'The backup was dumped from PostgreSQL 18, newer than the PostgreSQL 17 server',
);
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(