fix: harden migration command execution
Two problems in the migration commands: no timeouts, and SQL split on literal bytes. `migrations:plan` and `migrations:apply` constructed their connection with neither a connection deadline nor an operation deadline — a real server reported `statement_timeout = 0` on the migration connection. Both now default to 10 seconds for the connection deadline, the client query timeout, and PostgreSQL's own statement_timeout, applied at the one shared construction boundary so a future call site cannot silently omit them. History reads, advisory-lock queries, transaction control, migration SQL, and history writes are all covered. The existing lock-wait deadline, the Pass 2 TLS policy, and Doctor's and the bootstrap CLI's own timeouts are untouched, and no environment variable or flag was added. Explicit client fields do not win under the pinned driver. [email protected].0 builds parameters as `Object.assign({}, config, parse(config.connectionString))`, so the URL overrides passed options — verified directly, where an explicit statement_timeout of 10000 alongside `?statement_timeout=0` produced a server-reported 0, while a clean URL produced 10s. A DATABASE_URL carrying connect_timeout, query_timeout, statement_timeout, or an `options` value setting statement_timeout is therefore refused with the existing fixed configuration error, before any client is constructed and without echoing the URL, parameter, or value. Unrelated parameters are left alone. The runner split each migration on the literal `--> statement-breakpoint` bytes. Those bytes inside a string literal, a dollar-quoted function body, a quoted identifier, or a comment tore the migration into fragments that were no longer valid SQL — each case verified to produce two fragments where one was required. Each migration's exact SQL is now passed to the client once, with no values and no prepared-statement name, inside the existing transaction, and its history row inserted only after that batch succeeds. One transaction still spans all pending migrations; advisory locking, checksum validation, approval preflight, ordering, rollback, cleanup, and sanitized error identity are unchanged. The port method is renamed executeStatement to executeMigrationSql so the contract says what it receives. PostgreSQL parses the batch because it owns the only correct parser. A homegrown splitter would have to track single quotes, dollar quoting with arbitrary tags, quoted identifiers, line comments, nested block comments, and escape syntax to answer a question the server already answers, and a parser dependency would add supply-chain surface for the same reason. Drizzle's marker lines are ordinary `--` comments when the batch is sent whole. No custom SQL parser exists here. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
490b85b07c
commit
2983789779
@@ -1,4 +1,5 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import net from "node:net";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Client, type QueryResult, type QueryResultRow } from "pg";
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
MigrationRunnerError,
|
||||
type MigrationRunnerErrorCode,
|
||||
planModuleMigrations,
|
||||
PostgresMigrationDatabaseError,
|
||||
} from "../src/migrations/index.js";
|
||||
import type {
|
||||
DiscoveredModuleMigration,
|
||||
@@ -1457,3 +1459,179 @@ describe.sequential("live PostgreSQL Core identity migration execution", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Pass 4: the migration commands' finite timeout defaults, and whole-batch SQL execution, proven
|
||||
* against real PostgreSQL and a real TCP endpoint rather than a fake.
|
||||
*
|
||||
* Every listener, client, and disposable database here is closed in `finally`/`afterAll`, including
|
||||
* after a failed assertion.
|
||||
*/
|
||||
describe.sequential("live PostgreSQL migration command hardening", () => {
|
||||
it("bounds a connection to an endpoint that accepts TCP but never completes PostgreSQL startup", async () => {
|
||||
// A real blackhole listener bound only to loopback: it accepts the socket and then says
|
||||
// nothing, which is exactly the case `connectionTimeoutMillis` exists for.
|
||||
const sockets: net.Socket[] = [];
|
||||
const listener = net.createServer((socket) => {
|
||||
sockets.push(socket);
|
||||
});
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
listener.once("error", reject);
|
||||
listener.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
const address = listener.address();
|
||||
if (!address || typeof address !== "object") {
|
||||
throw harnessError("The blackhole listener has no bound address.");
|
||||
}
|
||||
|
||||
// A short, test-only override; production keeps MIGRATION_CONNECTION_TIMEOUT_MS unchanged.
|
||||
const blackholeDatabase = createPostgresMigrationDatabase(
|
||||
`postgresql://ekklesia:[email protected]:${address.port}/ekklesia`,
|
||||
{ connectionTimeoutMs: 300, operationTimeoutMs: 300 },
|
||||
);
|
||||
|
||||
const startedAt = Date.now();
|
||||
let captured: unknown;
|
||||
try {
|
||||
await blackholeDatabase.openSession();
|
||||
} catch (error) {
|
||||
captured = error;
|
||||
}
|
||||
|
||||
expect(captured).toBeInstanceOf(PostgresMigrationDatabaseError);
|
||||
expect(captured).toMatchObject({ code: "POSTGRES_MIGRATION_CONNECTION_FAILED" });
|
||||
// Finite, and nowhere near an unbounded wait.
|
||||
expect(Date.now() - startedAt).toBeLessThan(10_000);
|
||||
const publicText = `${String(captured)}\n${(captured as Error).stack ?? ""}`;
|
||||
expect(publicText).not.toContain("127.0.0.1");
|
||||
expect(publicText).not.toContain("ekklesia:ekklesia");
|
||||
expect(publicText).not.toContain(String(address.port));
|
||||
} finally {
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
await new Promise<void>((resolve) => {
|
||||
listener.close(() => resolve());
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("aborts a migration that exceeds the operation deadline and commits no history row", async () => {
|
||||
await withIsolatedDatabase("operation_timeout", async (database) => {
|
||||
const slow = migration("people", 0, {
|
||||
sql: "SELECT pg_sleep(5);",
|
||||
tag: "0000_slow",
|
||||
});
|
||||
// The operation deadline is the behavior under test, so a bounded server-side delay is the
|
||||
// only way to exercise it.
|
||||
const migrationDatabase = createPostgresMigrationDatabase(database.url, {
|
||||
connectionTimeoutMs: 5_000,
|
||||
operationTimeoutMs: 250,
|
||||
});
|
||||
|
||||
const error = await captureRunnerError(
|
||||
applyModuleMigrations({
|
||||
aggregate: aggregate({ id: "people", migrations: [slow] }),
|
||||
database: migrationDatabase,
|
||||
}),
|
||||
"MIGRATION_EXECUTION_FAILED",
|
||||
);
|
||||
|
||||
expect(error.migrationIdentity).toBe(slow.identity);
|
||||
const publicText = `${String(error)}\n${error.stack ?? ""}`;
|
||||
expect(publicText).not.toContain("pg_sleep");
|
||||
expect(publicText).not.toContain(database.name);
|
||||
|
||||
// Nothing was committed: the transaction rolled back with its history insert.
|
||||
const history = await safeQuery<{ identity: string }>(
|
||||
database.client,
|
||||
`select identity from public.ekklesia_core_migrations`,
|
||||
).catch(() => undefined);
|
||||
expect(history?.rows ?? []).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
it("executes marker bytes inside literals, dollar-quoted bodies, and comments intact", async () => {
|
||||
await withIsolatedDatabase("intact_sql", async (database) => {
|
||||
const marker = "--> statement-breakpoint";
|
||||
const sql = [
|
||||
`CREATE TABLE "people_notes" ("id" integer primary key, "body" text not null);`,
|
||||
marker,
|
||||
`INSERT INTO "people_notes" ("id", "body") VALUES (1, 'keep this: ${marker} intact');`,
|
||||
marker,
|
||||
`CREATE FUNCTION people_touch() RETURNS integer AS $$`,
|
||||
`BEGIN`,
|
||||
` -- ${marker}`,
|
||||
` PERFORM 1;`,
|
||||
` RETURN 42;`,
|
||||
`END;`,
|
||||
`$$ LANGUAGE plpgsql;`,
|
||||
marker,
|
||||
`/* block comment with ${marker} */`,
|
||||
`CREATE TABLE "odd${marker}name" ("id" integer);`,
|
||||
].join("\n");
|
||||
const intact = migration("people", 0, { sql, tag: "0000_intact" });
|
||||
|
||||
const result = await applyModuleMigrations({
|
||||
aggregate: aggregate({ id: "people", migrations: [intact] }),
|
||||
database: createPostgresMigrationDatabase(database.url),
|
||||
});
|
||||
expect(result.appliedCount).toBe(1);
|
||||
|
||||
// The literal survived byte-for-byte, so the marker was never treated as a split point.
|
||||
const stored = await safeQuery<{ body: string }>(
|
||||
database.client,
|
||||
`select body from "people_notes" where id = 1`,
|
||||
);
|
||||
expect(stored.rows[0]?.body).toBe(`keep this: ${marker} intact`);
|
||||
|
||||
// The dollar-quoted body executed as one function, not as fragments.
|
||||
const called = await safeQuery<{ result: number }>(
|
||||
database.client,
|
||||
`select people_touch() as result`,
|
||||
);
|
||||
expect(Number(called.rows[0]?.result)).toBe(42);
|
||||
|
||||
// The quoted identifier kept the marker in its name.
|
||||
const relations = await safeQuery<{ table_name: string }>(
|
||||
database.client,
|
||||
`select table_name from information_schema.tables
|
||||
where table_schema = 'public' and table_name like 'odd%'`,
|
||||
);
|
||||
expect(relations.rows.map((row) => row.table_name)).toEqual([`odd${marker}name`]);
|
||||
});
|
||||
});
|
||||
|
||||
it("rolls back the whole multi-statement migration when a later statement fails", async () => {
|
||||
await withIsolatedDatabase("intact_rollback", async (database) => {
|
||||
const failing = migration("people", 0, {
|
||||
sql: [
|
||||
`CREATE TABLE "people_partial" ("id" integer primary key);`,
|
||||
`--> statement-breakpoint`,
|
||||
`INSERT INTO "people_partial" ("id") VALUES (1);`,
|
||||
`--> statement-breakpoint`,
|
||||
`INSERT INTO "people_partial" ("id") VALUES (1);`,
|
||||
].join("\n"),
|
||||
tag: "0000_rollback",
|
||||
});
|
||||
|
||||
const error = await captureRunnerError(
|
||||
applyModuleMigrations({
|
||||
aggregate: aggregate({ id: "people", migrations: [failing] }),
|
||||
database: createPostgresMigrationDatabase(database.url),
|
||||
}),
|
||||
"MIGRATION_EXECUTION_FAILED",
|
||||
);
|
||||
expect(error.migrationIdentity).toBe(failing.identity);
|
||||
|
||||
// The earlier statements in the same batch rolled back with it.
|
||||
const relations = await safeQuery(
|
||||
database.client,
|
||||
`select table_name from information_schema.tables
|
||||
where table_schema = 'public' and table_name = 'people_partial'`,
|
||||
);
|
||||
expect(relations.rows).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user