Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(database): version-gate the pgcrypto extension in the UUID-defaults migration (#599)

Yudhi Armyndharisf26d27fc272e
diff --git a/src/database/add-uuid-defaults-migration.spec.ts b/src/database/add-uuid-defaults-migration.spec.ts
index ee16b6334..bb67c65d9 100644
--- a/src/database/add-uuid-defaults-migration.spec.ts
+++ b/src/database/add-uuid-defaults-migration.spec.ts
@@ -6,14 +6,33 @@ import { AddUuidDefaultsForPostgres1779235200000 } from './migrations/1779235200
const ALL_TABLES = ['sessions', 'webhooks', 'messages', 'message_batches'];
-function makeQueryRunner(type: string, existingTables: Set<string>) {
+interface RunnerOpts {
+ versionNum?: number; // server_version_num, e.g. 150000 (PG 15) or 120000 (PG 12)
+ extInstalled?: boolean; // is pgcrypto already present in pg_extension?
+ createExtensionThrows?: boolean; // does CREATE EXTENSION fail (unprivileged role)?
+}
+
+function makeQueryRunner(type: string, existingTables: Set<string>, opts: RunnerOpts = {}) {
+ const { versionNum = 150000, extInstalled = false, createExtensionThrows = false } = opts;
+ const query = jest.fn((sql: string) => {
+ const s = String(sql);
+ if (/server_version_num/i.test(s)) return Promise.resolve([{ num: versionNum }]);
+ if (/pg_extension/i.test(s)) return Promise.resolve(extInstalled ? [{ ok: 1 }] : []);
+ if (/CREATE EXTENSION/i.test(s) && createExtensionThrows) {
+ return Promise.reject(new Error('permission denied to create extension "pgcrypto"'));
+ }
+ return Promise.resolve(undefined);
+ });
return {
connection: { options: { type } },
hasTable: jest.fn((t: string) => Promise.resolve(existingTables.has(t))),
- query: jest.fn().mockResolvedValue(undefined),
+ query,
};
}
+const sqlOf = (qr: ReturnType<typeof makeQueryRunner>): string[] =>
+ qr.query.mock.calls.map(call => String((call as unknown[])[0]));
+
describe('AddUuidDefaultsForPostgres migration', () => {
const migration = new AddUuidDefaultsForPostgres1779235200000();
@@ -25,28 +44,56 @@ describe('AddUuidDefaultsForPostgres migration', () => {
expect(qr.hasTable).not.toHaveBeenCalled();
});
- it('on Postgres up() creates pgcrypto, then sets a uuid DEFAULT on every existing table', async () => {
- const qr = makeQueryRunner('postgres', new Set(ALL_TABLES));
+ it('on PG 13+ does NOT touch pgcrypto (core gen_random_uuid), only sets the DEFAULTs', async () => {
+ const qr = makeQueryRunner('postgres', new Set(ALL_TABLES), { versionNum: 150000 });
await migration.up(qr as unknown as QueryRunner);
- // 1 CREATE EXTENSION + one ALTER per table.
- expect(qr.query).toHaveBeenCalledTimes(ALL_TABLES.length + 1);
- const calls = qr.query.mock.calls.map(call => String((call as unknown[])[0]));
- // pgcrypto must be ensured before any gen_random_uuid() default that depends on it (PG <= 12).
- const extIdx = calls.findIndex(q => /CREATE EXTENSION IF NOT EXISTS pgcrypto/i.test(q));
- const firstAlterIdx = calls.findIndex(q => /gen_random_uuid\(\)/i.test(q));
- expect(extIdx).toBe(0);
- expect(extIdx).toBeLessThan(firstAlterIdx);
+ const calls = sqlOf(qr);
+ expect(calls.some(q => /CREATE EXTENSION/i.test(q))).toBe(false);
+ expect(calls.some(q => /pg_extension/i.test(q))).toBe(false); // no need to probe the catalog on 13+
+ // version probe + one ALTER per existing table.
+ expect(qr.query).toHaveBeenCalledTimes(1 + ALL_TABLES.length);
expect(qr.query).toHaveBeenCalledWith(
'ALTER TABLE "sessions" ALTER COLUMN "id" SET DEFAULT gen_random_uuid()::varchar',
);
});
- it('skips tables that do not exist (still creates pgcrypto)', async () => {
- const qr = makeQueryRunner('postgres', new Set(['sessions', 'messages']));
+ it('on PG <= 12 with pgcrypto missing, creates it BEFORE any gen_random_uuid() default', async () => {
+ const qr = makeQueryRunner('postgres', new Set(ALL_TABLES), { versionNum: 120000, extInstalled: false });
+ await migration.up(qr as unknown as QueryRunner);
+
+ const calls = sqlOf(qr);
+ const extIdx = calls.findIndex(q => /CREATE EXTENSION IF NOT EXISTS pgcrypto/i.test(q));
+ const firstAlterIdx = calls.findIndex(q => /gen_random_uuid\(\)/i.test(q));
+ expect(extIdx).toBeGreaterThanOrEqual(0);
+ expect(extIdx).toBeLessThan(firstAlterIdx);
+ });
+
+ it('on PG <= 12 with pgcrypto already installed, does NOT attempt CREATE EXTENSION', async () => {
+ const qr = makeQueryRunner('postgres', new Set(ALL_TABLES), { versionNum: 120000, extInstalled: true });
+ await migration.up(qr as unknown as QueryRunner);
+
+ const calls = sqlOf(qr);
+ expect(calls.some(q => /CREATE EXTENSION/i.test(q))).toBe(false);
+ expect(calls.some(q => /gen_random_uuid/i.test(q))).toBe(true); // DEFAULTs still applied
+ });
+
+ it('on PG <= 12 where the role cannot create pgcrypto, throws a clear error and sets no DEFAULT', async () => {
+ const qr = makeQueryRunner('postgres', new Set(ALL_TABLES), {
+ versionNum: 120000,
+ extInstalled: false,
+ createExtensionThrows: true,
+ });
+ await expect(migration.up(qr as unknown as QueryRunner)).rejects.toThrow(/pgcrypto/i);
+ // Aborted before any ALTER — no half-applied default.
+ expect(sqlOf(qr).some(q => /gen_random_uuid/i.test(q))).toBe(false);
+ });
+
+ it('skips tables that do not exist', async () => {
+ const qr = makeQueryRunner('postgres', new Set(['sessions', 'messages']), { versionNum: 150000 });
await migration.up(qr as unknown as QueryRunner);
- // 1 CREATE EXTENSION + 2 ALTERs (only the two existing tables).
- expect(qr.query).toHaveBeenCalledTimes(3);
+ // version probe + 2 ALTERs (only the two existing tables).
+ expect(qr.query).toHaveBeenCalledTimes(1 + 2);
});
it('on Postgres down() drops the DEFAULT on every existing table', async () => {
diff --git a/src/database/migrations/1779235200000-AddUuidDefaultsForPostgres.ts b/src/database/migrations/1779235200000-AddUuidDefaultsForPostgres.ts
index aca2743bc..6d9c7c4d5 100644
--- a/src/database/migrations/1779235200000-AddUuidDefaultsForPostgres.ts
+++ b/src/database/migrations/1779235200000-AddUuidDefaultsForPostgres.ts
@@ -14,10 +14,14 @@ import { MigrationInterface, QueryRunner } from 'typeorm';
* This migration is a no-op on SQLite (TypeORM generates the UUID in the
* driver layer there, so no DB default is needed).
*
- * `gen_random_uuid()` is a core built-in only from PostgreSQL 13; on PG <= 12
- * it lives in the pgcrypto extension. We `CREATE EXTENSION IF NOT EXISTS
- * pgcrypto` first so the default (and every insert that relies on it) works on
- * older servers too. On PG 13+ the extension is harmless/redundant.
+ * `gen_random_uuid()` is a core built-in from PostgreSQL 13; on PG <= 12 it lives
+ * in the pgcrypto extension. We therefore version-gate: on PG 13+ no extension is
+ * touched at all (the common case, and CREATE EXTENSION needs a privilege managed
+ * Postgres often withholds), and only on PG <= 12 do we ensure pgcrypto — with a
+ * clear, actionable error if the role cannot create it, instead of a boot crash-loop.
+ *
+ * NOTE: editing an already-recorded migration body only benefits new / currently
+ * crash-looping deployments; healthy ones that already ran it are unaffected.
*/
export class AddUuidDefaultsForPostgres1779235200000 implements MigrationInterface {
name = 'AddUuidDefaultsForPostgres1779235200000';
@@ -28,9 +32,37 @@ export class AddUuidDefaultsForPostgres1779235200000 implements MigrationInterfa
public async up(queryRunner: QueryRunner): Promise<void> {
if (queryRunner.connection.options.type !== 'postgres') return;
- // gen_random_uuid() is core only on PG 13+; ensure pgcrypto is present so PG <= 12 resolves it too.
- await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS pgcrypto`);
+ // gen_random_uuid() is a core built-in from PostgreSQL 13+, so on any modern server we need NO
+ // extension — and CREATE EXTENSION requires a privilege that managed Postgres (RDS/Cloud SQL/…)
+ // often withholds, so running it unconditionally crash-loops boot there. Probe the version with a
+ // non-erroring catalog query (never a caught SQL exception, which would poison the migration tx)
+ // and only touch pgcrypto on PG <= 12.
+ const versionRows = (await queryRunner.query(`SELECT current_setting('server_version_num')::int AS num`)) as
+ { num: number | string }[] | undefined;
+ const versionNum = Number(versionRows?.[0]?.num ?? 0);
+
+ if (versionNum > 0 && versionNum < 130000) {
+ // PG <= 12: gen_random_uuid() lives in pgcrypto. Check the catalog first (readable by any role);
+ // only attempt CREATE EXTENSION when it is genuinely missing, and if the role can't create it,
+ // fail with a clear, actionable error rather than a raw permission-denied crash-loop.
+ const installed = (await queryRunner.query(`SELECT 1 FROM pg_extension WHERE extname = 'pgcrypto'`)) as
+ unknown[] | undefined;
+ if (!installed?.length) {
+ try {
+ await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS pgcrypto`);
+ } catch (err) {
+ throw new Error(
+ `PostgreSQL ${versionNum} (< 13) needs the pgcrypto extension for gen_random_uuid(), but it is ` +
+ `not installed and this database role cannot create it. Have a superuser run ` +
+ `"CREATE EXTENSION pgcrypto;" once, then restart.`,
+ { cause: err },
+ );
+ }
+ }
+ }
+ // By this point gen_random_uuid() resolves (core on 13+, pgcrypto ensured on <= 12), so the DEFAULT
+ // expression — which Postgres validates at ALTER time — is safe to set.
for (const table of this.tables) {
const exists = await queryRunner.hasTable(table);
if (!exists) continue;