Skip to main content

The test suite that wrote to production

8 min read
Testing
Prisma
PostgreSQL
Software Quality
Engineering Practice
SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus

If your tests can reach a production database, one check is not enough. Refuse to start unless DATABASE_URL names a local host and a throwaway database (a name ending in _test or _e2e), and then, after the client connects, run SELECT current_database() and refuse again if the answer is not a throwaway. The second check exists because the string you validated and the database the tool opened can differ, and with Prisma they did. And never allow-list the name postgres: on Supabase, that is what production is called.

What broke

EduScale's battle.test.ts creates two users and a topic, runs the battle repository against them, and deletes everything in afterAll. The repo has a checked-in Backend/.env, and its DATABASE_URL points at the live Supabase pooler. The schema reads url = env("DATABASE_URL"). The test never set the variable. So npm test on a laptop was creating and deleting rows in production.

Nothing was harmed. Jest runs afterAll even when a test fails, and a read-only sweep for leftover test-supabase-* users and Test Topic * rows found none. But look at why it was fine. The teardown was careful. Nothing was stopping the connection. A process killed between create and delete ends in production, silently. A deleteMany whose where clause gets widened in a refactor ends there too.

How it was found

Not by a tool, and later than it should have been. I had run the suite several times that day before I stopped and asked one question of the test: where does this code get its database from, and is that the thing it thinks it is? The answer was three hops long. The datasource is env("DATABASE_URL"). The test does not set it. The only file that does is .env, and .env is production.

The guard

The fix is src/tests/helpers/assertTestDatabase.ts, two functions. The first validates the string before anything connects:

const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);

function isThrowawayName(name: string): boolean {
  return name.endsWith('_test') || name.endsWith('_e2e');
}

export function assertTestDatabaseUrl(url: string | undefined): void {
  // ...parse, refuse unset or unparseable...
  if (!LOCAL_HOSTS.has(parsed.hostname)) {
    throw new Error(
      [
        'REFUSING TO RUN: these tests create and delete rows.',
        `DATABASE_URL host is "${parsed.hostname}", which is not local.`,
        'Backend/.env points at PRODUCTION Supabase — never run this against it.',
        'Start a local Postgres and export DATABASE_URL before running.',
      ].join('\n')
    );
  }

  const database = parsed.pathname.replace(/^\//, '');
  if (!isThrowawayName(database)) {
    throw new Error(
      `REFUSING TO RUN: database "${database}" is not an obvious throwaway ` +
        '(expected a *_test / *_e2e name, or the CI container default).'
    );
  }
}

It runs at import time in battle.test.ts, before Jest registers a single test, so a wrong URL fails the file rather than one case:

assertTestDatabaseUrl(process.env.DATABASE_URL);

The second function runs inside beforeAll, after prisma.$connect(), and asks the open connection what it actually opened:

export async function assertConnectedToTestDatabase(
  prisma: PrismaClient
): Promise<void> {
  const [row] = await prisma.$queryRaw<
    { db: string }[]
  >`SELECT current_database() AS db`;

  if (!isThrowawayName(row.db)) {
    throw new Error(
      [
        `REFUSING TO RUN: connected to database "${row.db}", which is not a throwaway.`,
        'The client resolved a different database than the URL that was validated.',
        'Production Supabase is named "postgres" — if that is what you see, stop.',
      ].join('\n')
    );
  }
}

There is no override flag on either. The seeder that fills a local database with battles (src/scripts/battle-seeder.ts) calls both as well, because a seeder pointed at production is the same bug with a friendlier name.

The hole I put in it

Writing the first version, I allow-listed the database name postgres. It is the default name for a Postgres service container in CI, and I wanted the job to pass without extra config.

Production Supabase's database is also named postgres.

So the name check would have waved production straight through, and the only thing left between the suite and the live database was the host check. That is the redundancy I had just argued was necessary, doing the whole job by itself. An allow-list whose most permissive entry matches the thing you are guarding against is not an allow-list.

The fix was to stop accepting a default at all. The CI container is configured with its own name, and the workflow says why:

# NOT the default `postgres`: production Supabase's database is also
# named that, so the test-database guard refuses it on purpose.
POSTGRES_DB: eduscale_test

And the hole has a test now, so it cannot quietly come back:

it('refuses the name `postgres`, even on localhost', () => {
  expect(() =>
    assertTestDatabaseUrl(
      'postgresql://postgres:postgres@localhost:5432/postgres'
    )
  ).toThrow(/not an obvious throwaway/);
});

The same file pins the exact production URL shape as a refusal, and a remote host with a throwaway name (10.0.0.5:5432/eduscale_test) as a refusal too. That last one is the near-miss a name-only check would accept.

Then the guard cried wolf

The first connection-level check also required inet_server_addr() to be a loopback address. It passed on my machine and failed in CI:

REFUSING TO RUN: connected to non-local host 172.18.0.2/32

A Docker service container is reached at localhost from the runner, but from inside it reports its own private address. Containers, pgbouncer, proxies and SSH tunnels all legitimately answer with a non-loopback address, so the server address is a bad signal at the connection layer. Failing closed is the right direction to be wrong in, but a guard that cries wolf gets deleted, and then you have nothing.

So the two layers now check different things. The URL check owns the host. The connection check owns the database name, which is the one fact a string cannot know. A name ending in _test cannot be production, because production is postgres.

Why the second check exists: the Prisma CLI

This is the part people search for, so here is exactly what happened in the sibling repo, KhataGO, on 2026-08-23.

I ran a migration against what I believed was a local database:

DATABASE_URL="postgresql://localhost:5432/khatago_ballast" npx prisma migrate deploy

The CLI printed Environment variables loaded from .env and connected to production Supabase. It applied nothing, because production was already at every migration and migrate deploy never resets or drops. Safe by luck, not by construction.

My note in the repo at the time said the repo's .env wins over the shell. I now think that wording is wrong, and the real cause is more useful. Prisma's docs say that when a variable is defined in two places, dotenv's rules decide, and by default dotenv keeps a variable the shell already set. So DATABASE_URL was probably mine. The variable I had not set was DIRECT_URL. KhataGO's schema declares both (EduScale's does too):

datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL")
  directUrl = env("DIRECT_URL")
}

When a schema declares a direct URL, migrations use it, and the only place DIRECT_URL was defined was .env. So the tool most likely read the one variable I had not overridden and went where that pointed, while printing a line that sounded like it had read my command.

The lesson is the same whichever explanation is right. A pre-flight check on a string is defeated by any tool that can substitute configuration underneath it. Validate the string, then ask the connection what it is. For the CLI specifically: run npx prisma migrate status first and read the datasource line it prints, export DIRECT_URL alongside DATABASE_URL, or run from a directory with no .env in it.

What to do in your own repo

Keep the checked-in .env away from production credentials if you can. I have not managed that yet in either repo, which is exactly why the guard exists; the honest state is that the guard is what stands between npm test and the live database.

Add a URL check that runs at import time and refuses anything that is not a local host with a throwaway suffix. No override flag.

Add a connection check that runs after $connect() and asserts current_database(), not the server address.

Give the CI database a real name. Never accept a default, because a default is what production will be called too.

Put a test on the refusal cases, including the one you nearly allowed. A guard with no test is a guard you will loosen the next time it is inconvenient.

And after you fix it, ask what else in the repo reads a connection string the same way. The seeder did. A guard around one test file and nothing else is a passing test that proves only that the test passes.

SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus