feat(db): back up, restore and copy a Postgres database before migrating it

On Postgres the backup port dumps with pg_dump and restores by turning the
dump into a script with pg_restore and having psql clear the current schema
and run it in one transaction. A dump only recreates what it holds, so a
plain pg_restore --clean would leave a later migration's tables behind and
break the migrations the reopen runs; a restore that fails leaves the
database as it was. A restore refuses a pg_restore or psql older than
17.6/16.10/15.14/14.19, whose script would lack the \restrict line that
keeps a psql meta-command smuggled into an uploaded dump from running
(CVE-2025-8714). A restore
refuses a SQLite archive, a dump without TREK's migration history or one a
newer TREK wrote before anything is replaced, and keeps a dump of the
database it replaces.

RESTORE_FROM_BACKUP loads the archive's dump the same way into a database
that holds no table yet, and is ignored with a warning once it holds one.

Before pending migrations the boot now takes a pg_dump copy to
data/pre-migrate-<last migration>-<time>.pgdump under the same
TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP) policy as the SQLite file, instead of
refusing; a copy that cannot be written refuses the boot.

The tools run by absolute path (TREK_DB_PG_BIN_DIR, or the usual
directories), never through PATH, with the password in PGPASSWORD; an
sslmode that asks for SSL verifies the certificate as the app pool does.
Dumps are written beside their target and renamed into place, readable by
their owner only, and a tool's stderr reaches errors without the lines that
quote SQL or rows. The image installs postgresql-client-17 from Debian 13.
This commit is contained in:
Isaias Tavares
2026-11-02 15:59:01 -03:00
parent 515caffa79
commit fc9e634d86
21 changed files with 1099 additions and 108 deletions
+6 -3
View File
@@ -108,11 +108,14 @@ describe('buildOrmConfig', () => {
expect(config.entities).toBe(buildOrmConfig(resolveEngine()).entities);
});
it('ENGINE-032: a Postgres engine opens and closes nothing of its own, and refuses a reopen (no restore yet)', async () => {
it('ENGINE-032: a Postgres engine opens and closes nothing of its own; a reopen (after pg_restore) rebinds and migrates', async () => {
const engine = resolveEngine(deriveDb({ TREK_DB_URL: PG_URL }));
expect(() => engine.open(() => undefined)).not.toThrow();
await expect(engine.reopen()).rejects.toThrow(/reopened before it was opened/);
const onReopened = vi.fn(async () => undefined);
expect(() => engine.open(onReopened)).not.toThrow();
expect(() => engine.close()).not.toThrow();
await expect(engine.reopen()).rejects.toThrow(/not available in this release/);
await engine.reopen();
expect(onReopened).toHaveBeenCalledTimes(1);
});
it('ENGINE-033: Postgres serializes write transactions with one advisory lock taken in the transaction, SQLite needs none', async () => {