Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(test): name-floor guard for every destructive-SQL test + repo-wide coverage gate (#3485)

Garry Tanc439fad23e34
diff --git a/test/db-guard-coverage.test.ts b/test/db-guard-coverage.test.ts
new file mode 100644
index 0000000000..2353c48e12
--- /dev/null
+++ b/test/db-guard-coverage.test.ts
@@ -0,0 +1,243 @@
+/**
+ * Coverage gate for the destructive-SQL guard.
+ *
+ * Any test file that connects a PostgresEngine to DATABASE_URL can TRUNCATE or
+ * DELETE from whatever brain that URL points at. setupDB() calls
+ * assertSafeE2eDatabaseUrl() before it does so; files that connect directly
+ * bypass that check unless they call the guard themselves.
+ *
+ * This test scans the suite and fails when a file connects to DATABASE_URL
+ * without either going through setupDB() or calling the guard. Static scan
+ * only: no database connection, no DATABASE_URL required.
+ *
+ * KNOWN BLIND SPOTS (documented, not silent): a test that only passes the
+ * ambient URL into a SPAWNED subprocess (gbrain CLI) has no in-file connect
+ * idiom and is invisible here — the preload guard and the spawned CLI's own
+ * config path are the layers that cover it. Destructive helpers living in
+ * non-test files (other than setupDB) are likewise unscanned.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { readdirSync, readFileSync } from 'fs';
+import { join, resolve, relative } from 'path';
+
+// Walk from the REPO root, not test/: a bare `bun test` at the repo root
+// discovers *.test.ts repo-wide (evals/, examples/, …), so a test/-only scan
+// would be a permanent blind spot for destructive tests outside test/.
+const REPO_ROOT = resolve(import.meta.dir, '..');
+
+function walk(dir: string, out: string[] = []): string[] {
+ // fixtures/ IS scanned: `bun test` discovers *.test.ts there too, so an
+ // exemption would be a blind spot. Only node_modules (never collected by
+ // bun) and .git are skipped.
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) walk(full, out);
+ // Match every pattern bun test collects (.test/.spec/.bench and _test/_spec,
+ // all JS/TS extensions) — a destructive foo.spec.ts must not evade the scan.
+ // Skip this file itself: the classifier positive-control fixtures below
+ // are string literals that would otherwise scan as real test code.
+ else if (
+ /(\.(test|spec|bench)|_(test|spec))\.(ts|tsx|js|jsx|mjs|cjs)$/.test(entry.name) &&
+ full !== import.meta.path
+ ) out.push(full);
+ }
+ return out;
+}
+
+/**
+ * Reads an ambient database URL AND constructs a connection path. Detection is
+ * at the ASSIGNMENT site (any binding name), not a connect-site identifier
+ * allowlist — `const url = process.env.DATABASE_URL!; connect({ database_url:
+ * url })` and GBRAIN_DATABASE_URL spellings must not evade the scan
+ * (fail-closed: prefer flagging a guarded file over missing an unguarded one).
+ */
+/**
+ * Yields only non-comment lines: skips `//` lines, tracks multi-line block
+ * comments statefully (a block comment written WITHOUT leading `*` per line
+ * must still be excluded — the fail-open direction), and JSDoc `*` lines.
+ */
+function* codeLines(src: string): Generator<string> {
+ let inBlock = false;
+ for (const line of src.split('\n')) {
+ if (inBlock) {
+ if (/\*\//.test(line)) inBlock = false;
+ continue;
+ }
+ if (/^\s*\/\*/.test(line)) {
+ if (!/\*\//.test(line)) inBlock = true;
+ continue;
+ }
+ if (/^\s*(\/\/|\*)/.test(line)) continue;
+ yield line;
+ }
+}
+
+function readsAmbientDatabaseUrl(src: string): boolean {
+ for (const line of codeLines(src)) {
+ // `delete process.env.DATABASE_URL` is a scrub, not a read — files that
+ // explicitly REMOVE the ambient URL before building fixture engines must
+ // not be classified as connecting to it.
+ if (/delete\s+process\.env/.test(line)) continue;
+ if (/process\.env\.(GBRAIN_)?DATABASE_URL\b/.test(line)) return true;
+ // bracket notation: process.env['DATABASE_URL'] / ["GBRAIN_DATABASE_URL"]
+ if (/process\.env\[\s*['"`](GBRAIN_)?DATABASE_URL['"`]\s*\]/.test(line)) return true;
+ }
+ return false;
+}
+
+function connectsToAmbientDatabaseUrl(src: string): boolean {
+ if (!readsAmbientDatabaseUrl(src)) return false;
+ return /new\s+PostgresEngine\s*\(/.test(src)
+ || /\bdb\.connect\s*\(/.test(src)
+ // engine-factory idiom (env-inferred postgres) and raw postgres.js clients
+ || /\bcreateEngine\s*\(/.test(src)
+ || /\bpostgres\s*\(\s*[A-Za-z_$'"`]/.test(src);
+}
+
+/** Runs SQL that destroys data or schema. initSchema() counts: it migrates. */
+function runsDestructiveSql(src: string): boolean {
+ return /\b(TRUNCATE|DELETE\s+FROM|DROP\s+(TABLE|SCHEMA|INDEX|TRIGGER|FUNCTION|DATABASE|EXTENSION|OWNED)|ALTER\s+TABLE\s+\w+\s+DROP)\b/i.test(src)
+ || /\.initSchema\s*\(/.test(src);
+}
+
+/**
+ * Guarded either by the shared helper, by setupDB() (which calls it), or by an
+ * inline db-name floor. schema-drift.test.ts uses the last form: its pattern is
+ * deliberately different from the shared one (it also accepts *_e2e), so it is
+ * recognized rather than rewritten.
+ *
+ * Comment-hardened: a guard token on a comment line (`// unlike setupDB() ...`)
+ * must NOT count — this classifier is the exempting (fail-open) direction, so
+ * it only accepts tokens on non-comment lines. Residual limitation: a trailing
+ * comment after real code on the same line still counts that line.
+ */
+function isGuarded(src: string): boolean {
+ for (const line of codeLines(src)) {
+ if (/\b(assertSafeE2eDatabaseUrl|setupDB)\s*\(/.test(line)) return true;
+ if (/looksLikeTestDb/.test(line)) return true;
+ }
+ return false;
+}
+
+function scan(): { unguarded: string[]; guarded: string[] } {
+ const unguarded: string[] = [];
+ const guarded: string[] = [];
+ for (const file of walk(REPO_ROOT)) {
+ const src = readFileSync(file, 'utf-8');
+ if (!connectsToAmbientDatabaseUrl(src)) continue;
+ if (!runsDestructiveSql(src)) continue;
+ (isGuarded(src) ? guarded : unguarded).push(relative(REPO_ROOT, file));
+ }
+ return { unguarded, guarded };
+}
+
+describe('destructive-SQL guard coverage', () => {
+ test('every test that runs destructive SQL on DATABASE_URL is guarded', () => {
+ expect(scan().unguarded).toEqual([]);
+ });
+
+ test('positive control: the scan actually detects known destructive files', () => {
+ // Guards against regex rot: if connectsToAmbientDatabaseUrl or
+ // runsDestructiveSql stopped matching anything, the gate above would pass
+ // vacuously forever. These two files connect to the ambient URL, run
+ // destructive SQL, and call the guard — the scan must classify them so.
+ const { guarded } = scan();
+ expect(guarded).toContain('test/e2e/multimodal-postgres.test.ts');
+ expect(guarded).toContain('test/phantom-redirect-engine-parity.test.ts');
+ });
+});
+
+describe('scan classifiers (the gate must be able to fire)', () => {
+ test('connectsToAmbientDatabaseUrl matches every ambient spelling in the suite', () => {
+ const spellings = [
+ `engine = new PostgresEngine();\nawait engine.connect({ database_url: process.env.DATABASE_URL });`,
+ `const DATABASE_URL = process.env.DATABASE_URL;\nconst engine = new PostgresEngine();\nawait engine.connect({ database_url: DATABASE_URL! });`,
+ `const dbUrl = process.env.DATABASE_URL;\npg = new PostgresEngine();\nawait pg.connect({ database_url: dbUrl } as never);`,
+ // arbitrary binding name — the exact idiom the old allowlist missed
+ `const url = process.env.DATABASE_URL!;\nengine = new PostgresEngine();\nawait engine.connect({ database_url: url });`,
+ // GBRAIN_DATABASE_URL is honored by the runtime and must not evade the scan
+ `const u = process.env.GBRAIN_DATABASE_URL;\nconst engine = new PostgresEngine();\nawait engine.connect({ database_url: u });`,
+ // db.connect() path (no engine construction in the test file itself)
+ `const url = process.env.DATABASE_URL;\nawait db.connect({ database_url: url });`,
+ ];
+ for (const src of spellings) expect(connectsToAmbientDatabaseUrl(src)).toBe(true);
+ });
+
+ test('connectsToAmbientDatabaseUrl ignores fixture-URL connections and non-connecting files', () => {
+ expect(
+ connectsToAmbientDatabaseUrl(
+ `const engine = new PostgresEngine();\nawait engine.connect({ database_url: fixtureUrl });`,
+ ),
+ ).toBe(false);
+ expect(
+ connectsToAmbientDatabaseUrl(`const url = process.env.DATABASE_URL; // read, no engine/connect`),
+ ).toBe(false);
+ });
+
+ test('runsDestructiveSql matches each destructive arm and not plain reads', () => {
+ for (const src of [
+ 'await engine.executeRaw(`TRUNCATE pages`);',
+ "await engine.executeRaw('DELETE FROM pages');",
+ 'await engine.executeRaw(`DROP TABLE takes`);',
+ 'await engine.executeRaw(`ALTER TABLE pages DROP COLUMN x`);',
+ 'await engine.initSchema();',
+ ]) {
+ expect(runsDestructiveSql(src)).toBe(true);
+ }
+ expect(runsDestructiveSql('await engine.executeRaw(`SELECT 1`);')).toBe(false);
+ });
+
+ test('isGuarded recognizes each accepted guard form and nothing else', () => {
+ expect(isGuarded('assertSafeE2eDatabaseUrl(url);')).toBe(true);
+ expect(isGuarded('await setupDB();')).toBe(true);
+ expect(isGuarded('if (!looksLikeTestDb(name)) return;')).toBe(true);
+ expect(isGuarded('// totally unguarded')).toBe(false);
+ });
+
+ test('isGuarded rejects comment-only guard mentions (fail-open hardening)', () => {
+ expect(isGuarded('// unlike setupDB() we connect directly')).toBe(false);
+ expect(isGuarded('/* assertSafeE2eDatabaseUrl( would go here */')).toBe(false);
+ expect(isGuarded(' * setupDB() runs SCHEMA_SQL — JSDoc mention')).toBe(false);
+ // multi-line block comment WITHOUT leading * per line — must not count
+ expect(isGuarded('/*\nsetupDB() would be wrong here\n*/\nconnect();')).toBe(false);
+ // real call on a code line still counts even with comments elsewhere
+ expect(isGuarded('// intro comment\nawait setupDB();')).toBe(true);
+ expect(isGuarded('/* block */\nawait setupDB();')).toBe(true);
+ });
+
+ test('readsAmbientDatabaseUrl catches bracket notation and skips scrubs', () => {
+ expect(
+ connectsToAmbientDatabaseUrl(
+ `const u = process.env['DATABASE_URL'];\nconst engine = new PostgresEngine();`,
+ ),
+ ).toBe(true);
+ expect(
+ connectsToAmbientDatabaseUrl(
+ `delete process.env.DATABASE_URL;\ndelete process.env.GBRAIN_DATABASE_URL;\nconst e = await createEngine(cfg);`,
+ ),
+ ).toBe(false);
+ });
+
+ test('runsDestructiveSql catches the non-TABLE DROP arms', () => {
+ for (const src of [
+ 'await sql.unsafe(`DROP TRIGGER IF EXISTS t ON oauth_tokens`);',
+ 'await sql.unsafe(`DROP FUNCTION IF EXISTS f()`);',
+ "psqlish('DROP DATABASE gbrain');",
+ ]) {
+ expect(runsDestructiveSql(src)).toBe(true);
+ }
+ });
+
+ test('an unguarded destructive source would be flagged end-to-end', () => {
+ const bad = [
+ `const engine = new PostgresEngine();`,
+ `await engine.connect({ database_url: process.env.DATABASE_URL });`,
+ `await engine.executeRaw('TRUNCATE pages');`,
+ ].join('\n');
+ expect(connectsToAmbientDatabaseUrl(bad)).toBe(true);
+ expect(runsDestructiveSql(bad)).toBe(true);
+ expect(isGuarded(bad)).toBe(false);
+ });
+});
diff --git a/test/e2e/bootstrap-keyed-postgres.serial.test.ts b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
index aa429b4f86..e87cb3550a 100644
--- a/test/e2e/bootstrap-keyed-postgres.serial.test.ts
+++ b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
@@ -25,6 +25,7 @@ import { loadCorpusPages } from '../helpers/bootstrap-corpus.ts';
import { runEmbedCore } from '../../src/commands/embed.ts';
import { hybridSearch } from '../../src/core/search/hybrid.ts';
import { runSchemaTransition } from '../../src/core/retrieval-upgrade-planner.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
import { extractTakesFromPages } from '../../src/core/extract-takes-from-pages.ts';
import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
import {
@@ -282,6 +283,7 @@ describe.skipIf(!DATABASE_URL)('Postgres bootstrap verify (real Postgres)', () =
process.env.GBRAIN_HOME = root;
engine = new PostgresEngine();
+ assertSafeE2eDatabaseUrl(DATABASE_URL!);
await engine.connect({ database_url: DATABASE_URL! });
await engine.initSchema();
await addSource(engine, { id: 'workspace', localPath: join(ws, 'brain'), force: true });
diff --git a/test/e2e/embedding-column-postgres.test.ts b/test/e2e/embedding-column-postgres.test.ts
index 849a2df179..eae21c5075 100644
--- a/test/e2e/embedding-column-postgres.test.ts
+++ b/test/e2e/embedding-column-postgres.test.ts
@@ -20,6 +20,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { quoteIdentifier } from '../../src/core/search/embedding-column.ts';
import type { ResolvedColumn } from '../../src/core/types.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const dbUrl = process.env.DATABASE_URL;
if (!dbUrl) {
@@ -33,6 +34,7 @@ if (!dbUrl) {
beforeAll(async () => {
engine = new PostgresEngine();
+ assertSafeE2eDatabaseUrl(dbUrl!);
await engine.connect({ database_url: dbUrl } as never);
await engine.initSchema();
diff --git a/test/e2e/eval-capture.test.ts b/test/e2e/eval-capture.test.ts
index da400924e0..85b471e2d6 100644
--- a/test/e2e/eval-capture.test.ts
+++ b/test/e2e/eval-capture.test.ts
@@ -15,6 +15,7 @@
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import type { EvalCandidateInput } from '../../src/core/types.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const DATABASE_URL = process.env.DATABASE_URL;
@@ -26,6 +27,7 @@ beforeAll(async () => {
return;
}
engine = new PostgresEngine();
+ assertSafeE2eDatabaseUrl(DATABASE_URL!);
await engine.connect({ database_url: DATABASE_URL });
await engine.initSchema();
});
diff --git a/test/e2e/eval-contradictions-postgres.test.ts b/test/e2e/eval-contradictions-postgres.test.ts
index a8c8c0163a..6da325fe99 100644
--- a/test/e2e/eval-contradictions-postgres.test.ts
+++ b/test/e2e/eval-contradictions-postgres.test.ts
@@ -24,6 +24,7 @@ import { writeRunRow, loadTrend } from '../../src/core/eval-contradictions/trend
import { JudgeCache, buildCacheKey } from '../../src/core/eval-contradictions/cache.ts';
import type { ProbeReport } from '../../src/core/eval-contradictions/types.ts';
import { operationsByName, type OperationContext } from '../../src/core/operations.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const DATABASE_URL = process.env.DATABASE_URL;
@@ -35,6 +36,7 @@ beforeAll(async () => {
return;
}
engine = new PostgresEngine();
+ assertSafeE2eDatabaseUrl(DATABASE_URL!);
await engine.connect({ database_url: DATABASE_URL });
await engine.initSchema();
});
diff --git a/test/e2e/facts-fence-reconcile-postgres.test.ts b/test/e2e/facts-fence-reconcile-postgres.test.ts
index d57e806202..16875df2f0 100644
--- a/test/e2e/facts-fence-reconcile-postgres.test.ts
+++ b/test/e2e/facts-fence-reconcile-postgres.test.ts
@@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';
import { parseFactsFence, renderFactsTable, type ParsedFact } from '../../src/core/facts-fence.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const databaseUrl = process.env.DATABASE_URL;
const skip = !databaseUrl;
@@ -14,6 +15,7 @@ describe.skipIf(skip)('facts-fence escaped-pipe reconciliation on Postgres', ()
beforeAll(async () => {
engine = new PostgresEngine();
+ assertSafeE2eDatabaseUrl(databaseUrl!);
await engine.connect({ database_url: databaseUrl! });
await engine.initSchema();
});
diff --git a/test/e2e/helpers.ts b/test/e2e/helpers.ts
index 0d0fe762b8..1203d2bbc4 100644
--- a/test/e2e/helpers.ts
+++ b/test/e2e/helpers.ts
@@ -13,6 +13,7 @@ import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import * as db from '../../src/core/db.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import { parseMarkdown } from '../../src/core/markdown.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
// Load .env.testing if present
const envPath = resolve(import.meta.dir, '../../.env.testing');
@@ -67,38 +68,11 @@ export function hasDatabase(): boolean {
}
/**
- * Production guard: setupDB() TRUNCATEs every data table on whatever
- * DATABASE_URL points at, and run-e2e.sh deliberately preserves an exported
- * DATABASE_URL — so a developer with a production URL in their environment
- * would wipe their real brain by running the suite. Refuse unless the
- * database name identifies itself as a test database ("test" as a word
- * segment, e.g. gbrain_test — the CI/.env.testing.example convention), or
- * the operator explicitly opts the exact name in via GBRAIN_E2E_ALLOW_DB.
- *
- * Exported for unit testing; pure — no connection is made.
+ * Production guard, moved to test/helpers/db-guard.ts so test files outside
+ * test/e2e/ can import it without loading this module. Re-exported here for
+ * existing call sites (setupDB below, test/e2e/db-guard.test.ts).
*/
-export function assertSafeE2eDatabaseUrl(
- url: string,
- env: Record<string, string | undefined> = process.env,
-): void {
- let dbName: string;
- try {
- dbName = decodeURIComponent(new URL(url).pathname.replace(/^\//, ''));
- } catch {
- throw new Error(`E2E guard: DATABASE_URL is not a parseable URL; refusing to run destructive setup.`);
- }
- if (!dbName) {
- throw new Error(`E2E guard: DATABASE_URL has no database name; refusing to run destructive setup.`);
- }
- if (/(^|[_-])test([_-]|$)/i.test(dbName)) return;
- if (env.GBRAIN_E2E_ALLOW_DB && env.GBRAIN_E2E_ALLOW_DB === dbName) return;
- throw new Error(
- `E2E guard: database "${dbName}" does not look like a test database ` +
- `(expected "test" as a name segment, e.g. gbrain_test). setupDB() would ` +
- `TRUNCATE every data table in it. If this is intentional, set ` +
- `GBRAIN_E2E_ALLOW_DB=${dbName} to opt in explicitly.`,
- );
-}
+export { assertSafeE2eDatabaseUrl };
/**
* Connect to DB, run schema init, truncate all tables.
diff --git a/test/e2e/mcp-budget-reservation-postgres.test.ts b/test/e2e/mcp-budget-reservation-postgres.test.ts
index fd8442ee8d..e246c9fc45 100644
--- a/test/e2e/mcp-budget-reservation-postgres.test.ts
+++ b/test/e2e/mcp-budget-reservation-postgres.test.ts
@@ -14,6 +14,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test
import { randomUUIDv7 } from 'bun';
import { PostgresEngine } from 'gbrain';
import { BudgetExceededError, reserve } from '../../src/core/minions/budget-meter.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const databaseUrl = process.env.DATABASE_URL;
const describePostgres = databaseUrl ? describe : describe.skip;
@@ -24,6 +25,7 @@ describePostgres('MCP spend reservation — Postgres concurrency', () => {
beforeAll(async () => {
engine = new PostgresEngine();
+ assertSafeE2eDatabaseUrl(databaseUrl!);
await engine.connect({ database_url: databaseUrl!, poolSize: 16 });
await engine.initSchema();
});
diff --git a/test/e2e/multimodal-postgres.test.ts b/test/e2e/multimodal-postgres.test.ts
index 64c3dc92ad..47c9a3754d 100644
--- a/test/e2e/multimodal-postgres.test.ts
+++ b/test/e2e/multimodal-postgres.test.ts
@@ -15,6 +15,7 @@
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const DATABASE_URL = process.env.DATABASE_URL;
const skip = !DATABASE_URL;
@@ -28,6 +29,7 @@ describe.skipIf(skip)('multimodal v0.27.1 against real Postgres', () => {
beforeAll(async () => {
pg = new PostgresEngine();
+ assertSafeE2eDatabaseUrl(DATABASE_URL!);
await pg.connect({ database_url: DATABASE_URL! });
await pg.initSchema();
}, 60_000);
diff --git a/test/e2e/postgres-bootstrap.test.ts b/test/e2e/postgres-bootstrap.test.ts
index 46829885a9..0d275a9ee0 100644
--- a/test/e2e/postgres-bootstrap.test.ts
+++ b/test/e2e/postgres-bootstrap.test.ts
@@ -25,6 +25,7 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { LATEST_VERSION } from '../../src/core/migrate.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const DATABASE_URL = process.env.DATABASE_URL;
const skip = !DATABASE_URL;
@@ -34,6 +35,7 @@ describe.skipIf(skip)('PostgresEngine forward-reference bootstrap (E2E)', () =>
beforeAll(async () => {
engine = new PostgresEngine();
+ assertSafeE2eDatabaseUrl(DATABASE_URL!);
await engine.connect({ database_url: DATABASE_URL! });
}, 30_000);
diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.ts
index f27be05aa6..636b9a6732 100644
--- a/test/e2e/serve-http-oauth.test.ts
+++ b/test/e2e/serve-http-oauth.test.ts
@@ -15,8 +15,15 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { createHash } from 'crypto';
import { hasDatabase } from './helpers.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const skip = !hasDatabase();
+// #3485 name floor: this suite opens raw postgres() clients on the ambient URL
+// and runs DROP TRIGGER/FUNCTION + DELETE cleanups — refuse non-test-shaped
+// database names before any connection is made.
+if (!skip) {
+ assertSafeE2eDatabaseUrl(process.env.GBRAIN_DATABASE_URL || process.env.DATABASE_URL || '');
+}
const describeE2E = skip ? describe.skip : describe;
if (skip) {
diff --git a/test/helpers/db-guard.ts b/test/helpers/db-guard.ts
new file mode 100644
index 0000000000..c06adecef6
--- /dev/null
+++ b/test/helpers/db-guard.ts
@@ -0,0 +1,41 @@
+/**
+ * Production guard for tests that run destructive SQL against DATABASE_URL.
+ *
+ * setupDB() TRUNCATEs every data table on whatever DATABASE_URL points at, and
+ * run-e2e.sh deliberately preserves an exported DATABASE_URL, so a developer
+ * with a production URL in their environment would wipe their real brain by
+ * running the suite. Test files that connect a PostgresEngine directly, without
+ * going through setupDB(), carry the same risk and must call this themselves.
+ *
+ * Refuse unless the database name identifies itself as a test database ("test"
+ * as a word segment, e.g. gbrain_test, the CI/.env.testing.example convention),
+ * or the operator explicitly opts the exact name in via GBRAIN_E2E_ALLOW_DB.
+ *
+ * Lives in its own leaf module so unit-directory tests can import it without
+ * pulling in test/e2e/helpers.ts, which loads .env.testing and the engines at
+ * import time. test/e2e/helpers.ts re-exports it for existing call sites.
+ *
+ * Pure: no connection is made.
+ */
+export function assertSafeE2eDatabaseUrl(
+ url: string,
+ env: Record<string, string | undefined> = process.env,
+): void {
+ let dbName: string;
+ try {
+ dbName = decodeURIComponent(new URL(url).pathname.replace(/^\//, ''));
+ } catch {
+ throw new Error(`E2E guard: DATABASE_URL is not a parseable URL; refusing to run destructive setup.`);
+ }
+ if (!dbName) {
+ throw new Error(`E2E guard: DATABASE_URL has no database name; refusing to run destructive setup.`);
+ }
+ if (/(^|[_-])test([_-]|$)/i.test(dbName)) return;
+ if (env.GBRAIN_E2E_ALLOW_DB && env.GBRAIN_E2E_ALLOW_DB === dbName) return;
+ throw new Error(
+ `E2E guard: database "${dbName}" does not look like a test database ` +
+ `(expected "test" as a name segment, e.g. gbrain_test). This test runs ` +
+ `destructive SQL against it. If this is intentional, set ` +
+ `GBRAIN_E2E_ALLOW_DB=${dbName} to opt in explicitly.`,
+ );
+}
diff --git a/test/phantom-redirect-engine-parity.test.ts b/test/phantom-redirect-engine-parity.test.ts
index d208c38f33..33b6299a48 100644
--- a/test/phantom-redirect-engine-parity.test.ts
+++ b/test/phantom-redirect-engine-parity.test.ts
@@ -14,6 +14,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { PostgresEngine } from '../src/core/postgres-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import type { BrainEngine } from '../src/core/engine.ts';
+import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';
let pglite: PGLiteEngine;
let pg: PostgresEngine | null = null;
@@ -25,6 +26,7 @@ beforeAll(async () => {
if (process.env.DATABASE_URL) {
pg = new PostgresEngine();
+ assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);
await pg.connect({ database_url: process.env.DATABASE_URL });
await pg.initSchema();
}