:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(nodejs): refuse destructive test helpers on non-test databases (#62818)
Phil Haack5439c93757c6
diff --git a/nodejs/README.md b/nodejs/README.mdnew file mode 100644index 000000000000..c05d3a721400--- /dev/null+++ b/nodejs/README.md@@ -0,0 +1,32 @@+# PostHog Node.js services++Node.js services for PostHog: ingestion pipeline, CDP, session recording, and more.++## Running tests++Tests run against **dedicated test databases**, never the dev stack's databases:++| Store | Test database | Dev database (never used by tests) |+| ----------------------------- | --------------------------------------- | ---------------------------------- |+| Postgres (common) | `test_posthog` | `posthog` |+| Postgres (persons) | `test_persons` | `posthog_persons` |+| Postgres (behavioral cohorts) | `test_behavioral_cohorts` | `behavioral_cohorts` |+| Postgres (cyclotron) | `test_cyclotron`, `test_cyclotron_node` | `cyclotron` |+| ClickHouse | `posthog_test` | `default` |++These are the defaults whenever `NODE_ENV=test`, which `jest.setup-env.ts` forces for every jest run. The schema is owned by Django and rust migrations, so the test databases must be created before the first run:++```bash+# From the repo root, with the dev stack's Postgres/ClickHouse/Kafka/Redis running:+pnpm --filter=@posthog/nodejs setup:test+```++This runs Django's `setup_test_environment` (creates `test_posthog` and the ClickHouse `posthog_test` schema) plus the rust migrations for the persons, behavioral cohorts, and cyclotron test databases. Then:++```bash+cd nodejs+pnpm test # full suite (sharded in CI)+pnpm jest tests/path/to.test.ts # single file+```++Destructive test helpers refuse to run against a database without `test` in its name — see `tests/helpers/database-guard.ts`. The guard's error message explains how to fix a misconfigured environment.diff --git a/nodejs/jest.config.js b/nodejs/jest.config.jsindex da995fe11588..16b96f74a3e7 100644--- a/nodejs/jest.config.js+++ b/nodejs/jest.config.js@@ -10,6 +10,7 @@ module.exports = {testEnvironment: 'node',clearMocks: true,coverageProvider: 'v8',+ setupFiles: ['./jest.setup-env.ts'],setupFilesAfterEnv: ['./jest.setup.ts'],testMatch: ['<rootDir>/tests/**/*.test.ts', '<rootDir>/src/**/*.test.ts'],testTimeout: 60000,diff --git a/nodejs/jest.setup-env.ts b/nodejs/jest.setup-env.tsnew file mode 100644index 000000000000..75fc574076cb--- /dev/null+++ b/nodejs/jest.setup-env.ts@@ -0,0 +1,10 @@+// Jest's CLI only sets NODE_ENV=test when it is unset. When tests are launched+// from an environment where NODE_ENV or DEBUG is already set (IDE test runners,+// debuggers, flox exports DEBUG=1), `determineNodeEnv()` resolves to dev and+// every config default (DATABASE_URL, PERSONS_DATABASE_URL, CLICKHOUSE_DATABASE,+// CYCLOTRON_DATABASE_URL, ...) points at the real dev databases — which+// destructive test helpers would then wipe. Force the test environment so the+// defaults always resolve to their test_* counterparts. Explicitly exported+// *_DATABASE_URL variables still win; tests/helpers/database-guard.ts catches+// those when they point at a non-test database.+process.env.NODE_ENV = 'test'diff --git a/nodejs/tests/helpers/clickhouse.ts b/nodejs/tests/helpers/clickhouse.tsindex ee0fa8d6813c..edd82514b879 100644--- a/nodejs/tests/helpers/clickhouse.ts+++ b/nodejs/tests/helpers/clickhouse.ts@@ -21,6 +21,7 @@ import { fetch } from '~/utils/request'import { logger } from '../../src/utils/logger'import { delay, escapeClickHouseString } from '../../src/utils/utils'+import { assertTestDatabaseName } from './database-guard'// Extracts the topic(s) a ClickHouse Kafka engine table consumes from its `engine_full` string.// Handles both the keyword form (`kafka_topic_list = 'a,b'`) and the positional form@@ -75,12 +76,34 @@ export class Clickhouse {this.client.close()}+ // Memoized so repeated truncates don't re-query the database name. The+ // onRejected handler resets the cache when the `query` itself fails (a+ // transient connection error), so it isn't cached as a permanently rejected+ // promise. An assertTestDatabaseName failure throws from onFulfilled and+ // stays cached on purpose: it's a deterministic verdict on a fixed database+ // name, so re-querying would only reach the same conclusion.+ private databaseGuard?: Promise<void>+ private ensureTestDatabase(): Promise<void> {+ this.databaseGuard ??= this.query<{ name: string }>('SELECT currentDatabase() AS name').then(+ (rows) => assertTestDatabaseName(rows[0].name, 'ClickHouse'),+ (error) => {+ this.databaseGuard = undefined+ throw error+ }+ )+ return this.databaseGuard+ }+async truncate(table: string) {+ await this.ensureTestDatabase()await this.exec(`TRUNCATE ${table}`)}async resetTestDatabase(): Promise<void> {await this.waitForHealthy()+ // Guard before the truncates: Promise.allSettled below would swallow+ // the guard error if it only surfaced inside truncate().+ await this.ensureTestDatabase()// NOTE: Don't do more than 5 at once otherwise we get socket timeout errorsawait Promise.allSettled([this.truncate('sharded_events'),diff --git a/nodejs/tests/helpers/database-guard.test.ts b/nodejs/tests/helpers/database-guard.test.tsnew file mode 100644index 000000000000..35e80d658a00--- /dev/null+++ b/nodejs/tests/helpers/database-guard.test.ts@@ -0,0 +1,59 @@+import { PostgresRouter, PostgresUse } from '../../src/utils/db/postgres'+import { assertRouterTargetsTestDatabase, assertTestDatabaseName } from './database-guard'++describe('database-guard', () => {+ describe('assertTestDatabaseName', () => {+ it.each(['test_posthog', 'test_persons', 'test_persons_parity', 'test_behavioral_cohorts', 'posthog_test'])(+ 'allows test database %s',+ (name) => {+ expect(() => assertTestDatabaseName(name, 'unit test')).not.toThrow()+ }+ )++ it.each([+ 'posthog',+ 'posthog_persons',+ 'behavioral_cohorts',+ 'cyclotron',+ 'default',+ // "test" embedded in another word must not pass the guard.+ 'latest',+ 'posthog_latest',+ ])('refuses non-test database %s', (name) => {+ expect(() => assertTestDatabaseName(name, 'unit test')).toThrow(/Refusing to run a destructive test helper/)+ })++ it('includes the database name and source in the error', () => {+ expect(() => assertTestDatabaseName('posthog', 'Postgres COMMON_WRITE')).toThrow(+ expect.objectContaining({+ message: expect.stringMatching(/"posthog" \(Postgres COMMON_WRITE\)/),+ })+ )+ })+ })++ describe('assertRouterTargetsTestDatabase', () => {+ const routerReturning = (name: string): PostgresRouter =>+ ({+ query: jest.fn().mockResolvedValue({ rows: [{ name }] }),+ }) as unknown as PostgresRouter++ it('passes when the pool connects to a test database', async () => {+ await expect(+ assertRouterTargetsTestDatabase(routerReturning('test_posthog'), PostgresUse.COMMON_WRITE)+ ).resolves.toBeUndefined()+ })++ it('throws when the pool connects to a non-test database', async () => {+ await expect(+ assertRouterTargetsTestDatabase(routerReturning('posthog'), PostgresUse.COMMON_WRITE)+ ).rejects.toThrow(/Refusing to run a destructive test helper/)+ })++ it('names the postgres use in the error', async () => {+ await expect(+ assertRouterTargetsTestDatabase(routerReturning('posthog_persons'), PostgresUse.PERSONS_WRITE)+ ).rejects.toThrow(/Postgres PERSONS_WRITE/)+ })+ })+})diff --git a/nodejs/tests/helpers/database-guard.ts b/nodejs/tests/helpers/database-guard.tsnew file mode 100644index 000000000000..c6bf278eb381--- /dev/null+++ b/nodejs/tests/helpers/database-guard.ts@@ -0,0 +1,49 @@+import { PostgresRouter, PostgresUse } from '../../src/utils/db/postgres'++// Matches "test" only as an underscore- or boundary-delimited token, so real+// test databases (test_posthog, posthog_test) pass while names that merely+// embed the substring (latest, posthog_latest) are still refused.+const TEST_DATABASE_NAME_PATTERN = /(^|_)test(_|$)/i++/**+ * Throws unless `databaseName` looks like a test database — i.e. it contains+ * "test" as an underscore- or boundary-delimited token (test_posthog,+ * posthog_test). Names that merely embed the substring (latest, mytest) are+ * refused.+ *+ * Destructive test helpers (mass DELETE/TRUNCATE) call this before touching a+ * database, so a misconfigured environment (e.g. NODE_ENV/DEBUG or a+ * DATABASE_URL pointing at the dev `posthog` database leaking in from a shell+ * or IDE) produces a loud error instead of silently wiping real dev data.+ */+export function assertTestDatabaseName(databaseName: string, source: string): void {+ if (TEST_DATABASE_NAME_PATTERN.test(databaseName)) {+ return+ }+ throw new Error(+ `🛑 Refusing to run a destructive test helper against database "${databaseName}" (${source}).\n\n` ++ `The database name does not contain "test" as a standalone segment, so it looks\n` ++ `like a real development or production database. Continuing would have deleted\n` ++ `data from it.\n\n` ++ `The nodejs tests expect dedicated test databases (test_posthog, test_persons,\n` ++ `test_behavioral_cohorts on Postgres; posthog_test on ClickHouse). This error\n` ++ `usually means DATABASE_URL, PERSONS_DATABASE_URL, CLICKHOUSE_DATABASE or similar\n` ++ `leaked in from your shell or IDE. Unset them, or create the test databases with\n` ++ `\`pnpm --filter=@posthog/nodejs setup:test\`.`+ )+}++/**+ * Asserts that the database a router's pool actually connects to for the given+ * use is a test database. Queries `current_database()` so the check reflects+ * ground truth regardless of how the connection URL was assembled.+ */+export async function assertRouterTargetsTestDatabase(router: PostgresRouter, use: PostgresUse): Promise<void> {+ const result = await router.query<{ name: string }>(+ use,+ 'SELECT current_database() AS name',+ undefined,+ 'database-guard'+ )+ assertTestDatabaseName(result.rows[0].name, `Postgres ${PostgresUse[use]}`)+}diff --git a/nodejs/tests/helpers/sql.ts b/nodejs/tests/helpers/sql.tsindex 9c431a0cab37..5fa393155d3a 100644--- a/nodejs/tests/helpers/sql.ts+++ b/nodejs/tests/helpers/sql.ts@@ -4,6 +4,7 @@ import { defaultConfig } from '../../src/config/config'import { CookielessServerHashMode, InternalPerson, ProjectId, RawOrganization, RawPerson, Team } from '../../src/types'import { PostgresRouter, PostgresUse } from '../../src/utils/db/postgres'import { UUIDT } from '../../src/utils/utils'+import { assertRouterTargetsTestDatabase } from './database-guard'export const commonUserId = 1001export const commonOrganizationMembershipId = '0177364a-fc7b-0000-511c-137090b9e4e1'@@ -101,6 +102,11 @@ END $$;`export async function clearDatabase(db: PostgresRouter) {+ await Promise.all([+ assertRouterTargetsTestDatabase(db, PostgresUse.COMMON_WRITE),+ assertRouterTargetsTestDatabase(db, PostgresUse.PERSONS_WRITE),+ ])+await db.query(PostgresUse.COMMON_WRITE, POSTGRES_DELETE_COMMON_TABLES_QUERY, undefined, 'delete-common-tables').catch((e) => {@@ -122,21 +128,7 @@ export async function resetTestDatabase(): Promise<void> {const config = { ...defaultConfig, POSTGRES_CONNECTION_POOL_SIZE: 1 }const pg = new PostgresRouter(config)- // Delete common tables using COMMON_WRITE- await pg- .query(PostgresUse.COMMON_WRITE, POSTGRES_DELETE_COMMON_TABLES_QUERY, undefined, 'delete-common-tables')- .catch((e) => {- console.error('Error deleting common tables', e)- throw e- })-- // Delete persons tables using PERSONS_WRITE- await pg- .query(PostgresUse.PERSONS_WRITE, POSTGRES_DELETE_PERSONS_TABLES_QUERY, undefined, 'delete-persons-tables')- .catch((e) => {- console.error('Error deleting persons tables', e)- throw e- })+ await clearDatabase(pg)const teamIdToCreate = 2 // TODO: This might be wrongawait createUserTeamAndOrganization(pg, teamIdToCreate)@@ -505,6 +497,7 @@ export async function fetchPostgresDistinctIdsForPerson(postgres: PostgresRouter}export async function resetBehavioralCohortsDatabase(postgres: PostgresRouter): Promise<void> {+ await assertRouterTargetsTestDatabase(postgres, PostgresUse.BEHAVIORAL_COHORTS_RW)await postgres.query(PostgresUse.BEHAVIORAL_COHORTS_RW,'TRUNCATE TABLE cohort_membership',