fix(db): keep Postgres backups and restores inside TREK's schema

pg_dump copied every schema of the database, so on a hosted Postgres such
as Supabase a backup carried its auth and storage schemas too, and a
restore failed on them. A dump now holds the current schema only, a
restore loads only that schema, and a dump without TREK's tables in it is
refused before anything is replaced.
This commit is contained in:
Isaias Tavares
2026-11-03 09:06:41 -03:00
parent fc9e634d86
commit c72b680fec
5 changed files with 132 additions and 23 deletions
+66 -9
View File
@@ -166,19 +166,59 @@ function createPrivateFile(file: string): void {
fs.writeFileSync(file, '', { mode: 0o600 });
}
/** The schema TREK's tables live in: its name, and the name as SQL quotes it (`quote_ident`). */
interface PgSchema {
name: string;
quoted: string;
}
/**
* Writes a custom-format dump of the database at `url` to `target`, readable
* by its owner only. It is written beside the target and renamed into place,
* so a dump that fails or is killed never leaves a file that passes for a copy.
* The current schema of the database at `url`, the one TREK creates its
* tables in. A backup and a restore stay inside it: a hosted database
* (Supabase) keeps the platform's own schemas, `auth` among them, beside it,
* and they are neither TREK's to copy nor to replace.
*/
async function pgCurrentSchema(url: string, binDir: string | undefined): Promise<PgSchema> {
const out = await run(
'psql',
binDir,
[
'--no-psqlrc',
'--no-align',
'--tuples-only',
"--command=select current_schema() || E'\\t' || quote_ident(current_schema())",
],
pgConnectionEnv(url),
);
const [name, quoted] = out.replace(/\n$/, '').split('\t');
if (!name || !quoted) {
throw new Error('The database has no current schema: set the search_path of the role in TREK_DB_URL.');
}
return { name, quoted };
}
/**
* Writes a custom-format dump of the current schema of the database at `url`
* to `target`, readable by its owner only. It is written beside the target and
* renamed into place, so a dump that fails or is killed never leaves a file
* that passes for a copy.
*/
export async function pgDump(url: string, target: string, binDir: string | undefined): Promise<void> {
const partial = `${target}.partial`;
try {
createPrivateFile(partial);
const schema = await pgCurrentSchema(url, binDir);
await run(
'pg_dump',
binDir,
['--format=custom', '--no-owner', '--no-privileges', `--file=${partial}`],
[
'--format=custom',
'--no-owner',
'--no-privileges',
`--file=${partial}`,
// A pattern in double quotes matches that one name, as written.
`--schema="${schema.name.replaceAll('"', '""')}"`,
],
pgConnectionEnv(url),
);
fs.renameSync(partial, target);
@@ -226,21 +266,38 @@ async function refuseToolsWithoutRestrict(binDir: string | undefined): Promise<v
}
}
/** Whether the restore script creates TREK's migration table in `schema`: a dump of TREK's own schema does. */
function scriptHoldsTrekSchema(script: string, schema: PgSchema): boolean {
const table = `${schema.quoted}.mikro_orm_migrations`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`^CREATE TABLE ${table} \\(`, 'm').test(fs.readFileSync(script, 'utf8'));
}
/**
* Replaces the database at `url` with the dump at `source`: pg_restore turns
* the dump into a script beside it, then psql clears the current schema and
* runs the script in one transaction, so a restore that fails leaves the
* database as it was.
* Replaces the current schema of the database at `url` with the dump at
* `source`: pg_restore turns the dump's objects in that schema into a script
* beside it (anything else the dump holds is left out), then psql clears the
* schema and runs the script in one transaction, so a restore that fails
* leaves the database as it was. A dump without TREK's tables in that schema
* is refused before anything is cleared.
*/
export async function pgRestore(url: string, source: string, binDir: string | undefined): Promise<void> {
await refuseToolsWithoutRestrict(binDir);
const schema = await pgCurrentSchema(url, binDir);
const workDir = fs.mkdtempSync(path.join(path.dirname(source), '.pg-restore-'));
try {
const clear = path.join(workDir, 'clear-schema.sql');
const script = path.join(workDir, 'restore.sql');
fs.writeFileSync(clear, CLEAR_SCHEMA_SQL, { mode: 0o600 });
createPrivateFile(script);
await run('pg_restore', binDir, ['--no-owner', '--no-privileges', `--file=${script}`, '--', source], {});
await run(
'pg_restore',
binDir,
['--no-owner', '--no-privileges', `--schema=${schema.name}`, `--file=${script}`, '--', source],
{},
);
if (!scriptHoldsTrekSchema(script, schema)) {
throw new Error(`The backup holds no TREK tables in the schema "${schema.name}"; nothing was replaced.`);
}
await run(
'psql',
binDir,
@@ -35,8 +35,11 @@ const URL_WITH_SECRET = 'postgresql://trek:s3cr%40t@db.example:6543/trek_db?sslm
let bin: string;
let out: string;
/** pg_restore writing its --file (the third argument) as 17.6+ does: opened with a \\restrict line. */
const WRITES_RESTRICTED_SCRIPT = "printf '%s\\n' '\\restrict k1' 'SELECT 1;' > \"${3#--file=}\"";
/** pg_restore writing its --file (the fourth argument) as 17.6+ does: opened with a \\restrict line. */
const WRITES_RESTRICTED_SCRIPT =
"printf '%s\\n' '\\restrict k1' 'CREATE TABLE public.mikro_orm_migrations (' ');' > \"${4#--file=}\"";
/** What psql answers to the current-schema query: the name, a tab, the name as quote_ident writes it. */
const PUBLIC_SCHEMA = 'public\tpublic';
interface FakeOptions {
stdout?: string;
@@ -125,14 +128,16 @@ describe('pg-tools', () => {
});
it('PGTOOLS-004: pg_dump writes a private custom-format dump beside the target and renames it into place', async () => {
fakeTool('psql', { stdout: PUBLIC_SCHEMA });
const log = fakeTool('pg_dump', { body: 'printf dump >> "${4#--file=}"' });
const target = path.join(out, 'x.pgdump');
await pgDump(URL_WITH_SECRET, target, bin);
expect(argsOf(log).slice(0, 4)).toEqual([
expect(argsOf(log).slice(0, 5)).toEqual([
'--format=custom',
'--no-owner',
'--no-privileges',
`--file=${target}.partial`,
'--schema="public"',
]);
expect(readFileSync(log, 'utf8')).toContain('PGPASSWORD=s3cr@t');
expect(argsOf(log).join(' ')).not.toContain('s3cr');
@@ -144,13 +149,16 @@ describe('pg-tools', () => {
it('PGTOOLS-005: a restore clears the schema and loads the script in one psql transaction, then removes its work files', async () => {
const source = path.join(out, 'in.pgdump');
const restoreLog = fakeTool('pg_restore', { body: WRITES_RESTRICTED_SCRIPT });
const psqlLog = fakeTool('psql', { body: `cp "\${6#--file=}" '${path.join(bin, 'clear.sql')}'` });
const psqlLog = fakeTool('psql', {
stdout: PUBLIC_SCHEMA,
body: `[ -n "$6" ] && cp "\${6#--file=}" '${path.join(bin, 'clear.sql')}'`,
});
await pgRestore(URL_WITH_SECRET, source, bin);
const restoreArgs = argsOf(restoreLog);
expect(restoreArgs.slice(0, 2)).toEqual(['--no-owner', '--no-privileges']);
expect(restoreArgs[2]).toMatch(/^--file=.*\.pg-restore-[^/]+\/restore\.sql$/);
expect(restoreArgs.slice(3, 5)).toEqual(['--', source]);
expect(restoreArgs.slice(0, 3)).toEqual(['--no-owner', '--no-privileges', '--schema=public']);
expect(restoreArgs[3]).toMatch(/^--file=.*\.pg-restore-[^/]+\/restore\.sql$/);
expect(restoreArgs.slice(4, 6)).toEqual(['--', source]);
expect(readFileSync(restoreLog, 'utf8')).not.toContain('PGPASSWORD');
const psqlArgs = argsOf(psqlLog);
@@ -162,7 +170,7 @@ describe('pg-tools', () => {
'--output=/dev/null',
]);
expect(psqlArgs[5]).toMatch(/clear-schema\.sql$/);
expect(psqlArgs[6]).toBe(restoreArgs[2]);
expect(psqlArgs[6]).toBe(restoreArgs[3]);
expect(readFileSync(psqlLog, 'utf8')).toContain('PGOPTIONS=-c lock_timeout=60s -c client_min_messages=warning');
expect(readFileSync(path.join(bin, 'clear.sql'), 'utf8')).toMatch(/DROP %s IF EXISTS %s CASCADE/);
expect(readdirSync(out)).toEqual([]);
@@ -194,6 +202,7 @@ describe('pg-tools', () => {
});
it('PGTOOLS-007: a failing tool reports its own message without the lines that quote SQL or rows, and leaves no file', async () => {
fakeTool('psql', { stdout: PUBLIC_SCHEMA });
fakeTool('pg_dump', {
exitCode: 1,
stderr: 'pg_dump: error: query failed\nCommand was: SELECT secret_row\nDETAIL: Key (email)=(a@b.c)\n',
@@ -237,4 +246,32 @@ describe('pg-tools', () => {
for (const v of unfixed) expect(hasRestrictFix(`pg_restore (PostgreSQL) ${v}`), v).toBe(false);
expect(hasRestrictFix('not a version')).toBe(false);
});
it('PGTOOLS-011: a dump holds the current schema only, matched by its exact name, which psql reads without the password in an argument', async () => {
const psqlLog = fakeTool('psql', { stdout: 'My"Trek\t"My""Trek"' });
const log = fakeTool('pg_dump', { body: 'printf dump >> "${4#--file=}"' });
await pgDump(URL_WITH_SECRET, path.join(out, 'x.pgdump'), bin);
expect(argsOf(log)[4]).toBe('--schema="My""Trek"');
expect(argsOf(psqlLog).join(' ')).toContain('current_schema()');
expect(argsOf(psqlLog).join(' ')).not.toContain('s3cr');
fakeTool('psql', { stdout: '\n' });
await expect(pgDump(URL_WITH_SECRET, path.join(out, 'y.pgdump'), bin)).rejects.toThrow(/no current schema/);
expect(readdirSync(out)).toEqual(['x.pgdump']);
});
it('PGTOOLS-012: a restore keeps to the current schema, and refuses a dump without TREK tables there before clearing anything', async () => {
const source = path.join(out, 'in.pgdump');
const restoreLog = fakeTool('pg_restore', {
body: "printf '%s\\n' '\\restrict k1' 'CREATE TABLE auth.users (' ');' > \"${4#--file=}\"",
});
const psqlLog = fakeTool('psql', { stdout: 'trek\ttrek' });
await expect(pgRestore(URL_WITH_SECRET, source, bin)).rejects.toThrow(
'The backup holds no TREK tables in the schema "trek"; nothing was replaced.',
);
expect(argsOf(restoreLog)[2]).toBe('--schema=trek');
// psql only read the schema: it never ran the clear or the load.
expect(argsOf(psqlLog).join(' ')).not.toContain('--single-transaction');
expect(readdirSync(out)).toEqual([]);
});
});
@@ -192,13 +192,18 @@ describe('postgresSafetyNet', () => {
rmSync(bin, { recursive: true, force: true });
});
/** A stand-in pg_dump that writes its --file, or fails like one that cannot connect. */
/**
* A stand-in pg_dump that writes its --file, or fails like one that cannot
* connect, beside the psql that names the schema the dump is limited to.
*/
const fakePgDump = (ok: boolean) => {
const body = ok
? 'for a in "$@"; do case "$a" in --file=*) printf dump > "${a#--file=}";; esac; done'
: 'echo "could not connect" >&2; exit 1';
writeFileSync(path.join(bin, 'pg_dump'), `#!/bin/sh\n${body}\n`);
writeFileSync(path.join(bin, 'psql'), "#!/bin/sh\nprintf 'public\\tpublic\\n'\n");
chmodSync(path.join(bin, 'pg_dump'), 0o755);
chmodSync(path.join(bin, 'psql'), 0o755);
};
const envWith =
(preMigrateSnapshot: boolean | undefined, isTest: boolean, keep = 3) =>
+8 -2
View File
@@ -143,7 +143,13 @@ describe('restoreOnFirstBoot', () => {
};
write(
'psql',
`case "$*" in *--command=*) [ -f '${root}/tables' ] && cat '${root}/tables'; exit 0;; *) touch '${root}/loaded';; esac`,
[
'case "$*" in',
" *quote_ident*) printf 'public\\tpublic\\n';;",
` *--command=*) [ -f '${root}/tables' ] && cat '${root}/tables'; exit 0;;`,
` *) touch '${root}/loaded';;`,
'esac',
].join('\n'),
);
const migration = [...knownMigrationNames()][0];
write(
@@ -151,7 +157,7 @@ describe('restoreOnFirstBoot', () => {
[
'case "$*" in',
` *--data-only*) printf 'COPY public.mikro_orm_migrations (id, name) FROM stdin;\\n1\\t${migration}\\n\\\\.\\n';;`,
` *) for a in "$@"; do case "$a" in --file=*) printf '%s\\n' '\\restrict k1' > "\${a#--file=}";; esac; done;;`,
` *) for a in "$@"; do case "$a" in --file=*) printf '%s\\n' '\\restrict k1' 'CREATE TABLE public.mikro_orm_migrations (' > "\${a#--file=}";; esac; done;;`,
'esac',
].join('\n'),
);
@@ -30,6 +30,8 @@ function tool(name: 'pg_dump' | 'pg_restore' | 'psql', body: string): void {
chmodSync(path.join(bin, name), 0o755);
}
const WRITES_ITS_FILE = 'for a in "$@"; do case "$a" in --file=*) printf dump > "${a#--file=}";; esac; done';
/** A psql that answers the current-schema query a dump and a restore start with, and otherwise succeeds. */
const ANSWERS_SCHEMA = 'case "$*" in *quote_ident*) printf \'public\\tpublic\\n\';; esac';
const FAILS = 'echo "connection refused" >&2; exit 1';
/** A pg_restore whose --data-only listing shows `names` as the dump's migrations. */
const LISTS = (names: string[]) =>
@@ -47,6 +49,7 @@ beforeEach(() => {
extract = path.join(root, 'extract');
mkdirSync(bin);
mkdirSync(extract);
tool('psql', ANSWERS_SCHEMA);
vi.stubEnv('TREK_DB_URL', 'postgresql://trek:pw@db/trek');
vi.stubEnv('TREK_DB_PG_BIN_DIR', bin);
reopen = vi.fn(async () => undefined);
@@ -115,8 +118,10 @@ describe('PostgresDatabaseBackup', () => {
});
it('PGBACKUP-004: replace restores, then reopens; a reopen failure is reported, not thrown', async () => {
tool('pg_restore', "printf '%s\\n' '\\restrict k1' > \"${3#--file=}\"");
tool('psql', 'exit 0');
tool(
'pg_restore',
"printf '%s\\n' '\\restrict k1' 'CREATE TABLE public.mikro_orm_migrations (' > \"${4#--file=}\"",
);
await expect(backup.replace(path.join(extract, 'travel.pgdump'))).resolves.toEqual({ reopenError: null });
expect(reopen).toHaveBeenCalledTimes(1);
const lost = new Error('reconnect failed');
@@ -126,7 +131,6 @@ describe('PostgresDatabaseBackup', () => {
it('PGBACKUP-005: a failed restore still reopens, and both failures surface when the reopen fails too', async () => {
tool('pg_restore', FAILS);
tool('psql', 'exit 0');
const source = path.join(extract, 'travel.pgdump');
await expect(backup.replace(source)).rejects.toThrow('pg_restore failed: connection refused');
expect(reopen).toHaveBeenCalledTimes(1);