During a code audit of a Flutter app backed by Firestore, we found a collection that any unauthenticated client could read in full. Nobody had made a mistake in the rules file they remembered writing. The leak came from a rule they didn't remember at all. That is the case for Firebase security rules testing: rules are executable code that gates every byte of your data, and most teams ship them with less test coverage than a date-formatting helper.

This post walks through the finding, why it slipped through, and the allow/deny matrix approach we now use to keep it from recurring.

The finding: a wildcard that outlived its purpose

The rules file looked reasonable at a glance. Per-user documents under /users/{uid} had an owner-only check. But further down, left over from an early prototype, sat something like this:

match /{path=**}/profiles/{doc} {
  allow read: if true;
}

The intent was a public profile card for a leaderboard. The effect, thanks to the recursive wildcard, was that any collection or subcollection named profiles, at any depth, became world-readable. Later, a feature nested a profiles subcollection under /users/{uid} holding contact details and settings. The owner-only rule on the parent did nothing, because Firestore rules are additive: if any matching rule allows the operation, the request succeeds. There is no deny override.

That additive behavior is the root of most rules bugs. You cannot reason about a rule in isolation, and you cannot grep for the dangerous one, because the dangerous one is the one that matches paths you forgot it could match. Reading the file top to bottom feels like review. It isn't.

Firebase security rules testing with the emulator

The fix for "I can't reason about the union of all rules" is to stop reasoning and start asserting. The Firebase Emulator Suite runs the real rules engine locally, and @firebase/rules-unit-testing gives you authenticated and unauthenticated contexts to fire requests at it. Setup is small:

import { initializeTestEnvironment, assertFails, assertSucceeds }
  from '@firebase/rules-unit-testing';
import { readFileSync } from 'fs';

let env;
beforeAll(async () => {
  env = await initializeTestEnvironment({
    projectId: 'rules-test',
    firestore: { rules: readFileSync('firestore.rules', 'utf8') },
  });
});
afterEach(() => env.clearFirestore());
afterAll(() => env.cleanup());

Run it with firebase emulators:exec --only firestore "npm test" so the emulator starts and stops with the test process. That one command is also what you drop into CI.

Think in matrices, not happy paths

The common mistake is testing only what should work: "owner can read own doc." That passes against a file containing allow read: if true everywhere. The valuable assertions are the denials. For each collection, enumerate the actors and operations, and assert every cell:

  • Actors: unauthenticated, authenticated stranger, owner, admin (custom claim), and a user with a valid token but an unverified email if your rules care.
  • Operations: get, list, create, update, delete, kept separate because rules often treat them differently.
  • Paths: the collection, every subcollection, and a deliberately made-up collection name to prove the default is deny.

Table-driven tests keep this readable:

const actors = {
  anon:  () => env.unauthenticatedContext(),
  alice: () => env.authenticatedContext('alice'),
  bob:   () => env.authenticatedContext('bob'),
  admin: () => env.authenticatedContext('root', { admin: true }),
};

const matrix = [
  // path,                    actor,   op,      expected
  ['users/alice',             'alice', 'get',   true ],
  ['users/alice',             'bob',   'get',   false],
  ['users/alice',             'anon',  'get',   false],
  ['users/alice/profiles/p1', 'anon',  'get',   false],
  ['users/alice/profiles/p1', 'bob',   'get',   false],
  ['users/alice/profiles/p1', 'alice', 'get',   true ],
  ['nonexistent/x',           'admin', 'get',   false],
];

test.each(matrix)('%s as %s %s -> %s', async (path, who, op, ok) => {
  await env.withSecurityRulesDisabled(c =>
    c.firestore().doc(path).set({ seeded: true }));
  const ref = actors[who]().firestore().doc(path);
  await (ok ? assertSucceeds(ref.get()) : assertFails(ref.get()));
});

Seed with withSecurityRulesDisabled, then test with the real context. Forgetting to seed is a classic false positive: a read of a nonexistent document can fail or succeed for reasons unrelated to your rule's intent.

What the suite caught in the audit

We wrote the matrix before touching the rules, which matters: a test that never failed against the broken file proves nothing. Two rows went red immediately. users/alice/profiles/p1 read by anon and by bob both succeeded. A third surprise came from the "made-up collection" row: a second leftover wildcard allowed authenticated reads on an unrelated path. We would not have found that by reading, because it only matched a name we hadn't thought to look for.

The fix was to delete the recursive wildcard and replace it with an explicit match on the one top-level public collection the leaderboard actually needed, exposing only a stripped-down document containing display name and score. We then moved contact details out of anything adjacent to public data. The matrix went green, and it stayed in the repo.

Failure modes worth encoding as tests

  • Recursive wildcards ({path=**}): add a row for every nested collection you have, plus one you invent.
  • Update rules that don't pin fields: test that a user cannot write role: 'admin' or reassign ownerId on their own document.
  • Create vs. update asymmetry: an owner check using resource.data doesn't apply on create, where you need request.resource.data.
  • List vs. get: a rule that allows get by ID but not list is a deliberate privacy property. Assert it.
  • Cross-service rules: Storage rules calling firestore.get() need both emulators running, or the test silently exercises less than you think.

Making it stick

Three habits turned this from a one-off audit artifact into a safeguard. First, the suite runs in CI on every change to firestore.rules, so a loosened rule fails a pull request, not production. Second, adding a collection means adding its matrix rows in the same PR, which makes the data model and its access policy reviewed together. Third, the emulator's rules coverage report (available from the emulator's coverage endpoint) shows which rule branches your tests never exercised. An unexercised allow is exactly where a forgotten wildcard hides.

None of this replaces thinking about your data model, and tests only encode the threats you imagined. But they convert "we reviewed the rules" from an opinion into a checkable claim.

At orithLabs, this is the kind of finding we look for when we audit an existing codebase, and the kind of test suite we build into the Flutter and backend projects we ship ourselves. If you suspect your own rules have drifted from your intentions, we're happy to talk it through engineer to engineer.