mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 21:33:19 +00:00
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.
This commit is contained in:
@@ -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<PgServer> {
|
||||
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<void> {
|
||||
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');
|
||||
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
if (plan.postgres) {
|
||||
@@ -112,6 +125,8 @@ export async function restoreOnFirstBoot(plan: BootRestorePlan): Promise<BootRes
|
||||
throw new BootRestoreError(`RESTORE_FROM_BACKUP: no backup archive at ${plan.archive}`);
|
||||
}
|
||||
|
||||
if (plan.postgres) await refuseRestoreTarget(plan.postgres);
|
||||
|
||||
console.log(`[restore] Restoring ${plan.archive} before the first start`);
|
||||
const staging = path.join(plan.dataDir, `restore-boot-${Date.now()}`);
|
||||
const refused = await extractBackupArchive(plan.archive, staging);
|
||||
@@ -125,8 +140,17 @@ export async function restoreOnFirstBoot(plan: BootRestorePlan): Promise<BootRes
|
||||
|
||||
// Storage reclaim drops what the restored database knew about its storage on
|
||||
// the start that follows, even when the backup is this installation's own.
|
||||
markReclaimResetPending(plan.reclaimResetFile);
|
||||
await putDatabaseInPlace(plan, staging);
|
||||
let marked = false;
|
||||
try {
|
||||
markReclaimResetPending(plan.reclaimResetFile);
|
||||
marked = true;
|
||||
await putDatabaseInPlace(plan, staging);
|
||||
} catch (err) {
|
||||
// The next start extracts the archive again, so this one's copy must not stay behind.
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
if (marked) fs.rmSync(plan.reclaimResetFile, { force: true });
|
||||
throw err;
|
||||
}
|
||||
|
||||
// The key the archive's secrets were encrypted with. An ENCRYPTION_KEY in the
|
||||
// environment still wins over the file, exactly as on any other start.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { DbSettings } from '../../app-config';
|
||||
import { postgresTarget, type DatabaseEngine } from '../../db/engine';
|
||||
import { pgDump, pgDumpMigrations, pgRestore } from '../../db/engine/postgres/pg-tools';
|
||||
import { pgDump, pgDumpMigrations, pgRestore, pgRestoreTarget } 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';
|
||||
@@ -106,10 +106,20 @@ export class PostgresDatabaseBackup implements DatabaseBackupStrategy {
|
||||
await pgDump(url, target, binDir);
|
||||
}
|
||||
|
||||
/** Throws a DomainError (400) with the refusal when the archive cannot be restored here, before anything is replaced. */
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
async verify(extractDir: string): Promise<void> {
|
||||
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. */
|
||||
|
||||
@@ -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<typeof answersSchema>[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(
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user