How do you unit-test Firestore Security Rules against the Firebase Local Emulator Suite before deploying them?
answer
- a local emulator plus a test library
- fake identities, real rules
- seed with rules switched off
- assert the denials too
- clear data between tests
basics
~10 sRun the Firestore emulator and test with @firebase/rules-unit-testing: initializeTestEnvironment loads the rules, authenticatedContext and unauthenticatedContext fake users and claims, withSecurityRulesDisabled seeds data, and assertSucceeds or assertFails check each request.
solid answer
~40 sStart the Firestore emulator, for example with `firebase emulators:exec --only firestore "npm test"`, and write Node tests against the `@firebase/rules-unit-testing` library. In its current v9-style API, `initializeTestEnvironment` takes a project ID and the rules text; `authenticatedContext('alice', { teacher: true })` returns a client that sends a mock ID token with those claims, and `unauthenticatedContext()` one with none. Seed fixtures inside `withSecurityRulesDisabled`, then wrap each client call in `assertSucceeds` or `assertFails`. Call `clearFirestore()` between tests because the emulator keeps data for its whole run, and `cleanup()` at the end. Test the denials as carefully as the grants: an unfiltered query, another student's grade, a forbidden field change. Without rules loaded the emulator treats the project as open, so a suite that only asserts successes proves nothing.
code
typescript · 31 linesimport { readFileSync } from "node:fs";
import { after, before, test } from "node:test";
import {
assertFails,
assertSucceeds,
initializeTestEnvironment,
RulesTestEnvironment,
} from "@firebase/rules-unit-testing";
let testEnv: RulesTestEnvironment;
before(async () => {
testEnv = await initializeTestEnvironment({
projectId: "demo-classroom",
firestore: { rules: readFileSync("firestore.rules", "utf8") },
});
await testEnv.withSecurityRulesDisabled(async (context) => {
await context.firestore().doc("students/alice/grades/g1").set({ score: 91 });
});
});
after(async () => {
await testEnv.cleanup();
});
test("only the owner reads a grade", async () => {
const alice = testEnv.authenticatedContext("alice");
const bob = testEnv.authenticatedContext("bob");
await assertSucceeds(alice.firestore().doc("students/alice/grades/g1").get());
await assertFails(bob.firestore().doc("students/alice/grades/g1").get());
});go deeper
Recall the tools: the Firestore emulator from the Firebase CLI and the rules-unit-testing library with assertSucceeds and assertFails.
Walk through a suite: initializeTestEnvironment with the rules text, contexts for each identity and claim, seeding with rules disabled, and clearing data between tests.
Show coverage judgment: denials for every grant, queries that must fail, frozen-field updates, and the open-rules trap when no rules file is loaded.
Make the rules suite a CI gate on the rules file, so no ruleset deploys without tests that prove what it denies.
## Why rules need their own tests Security Rules are the only thing between an untrusted phone and the database, and they fail open in quiet ways: a recursive wildcard added for one feature, an update rule that forgot a field check, a query that the rules accidentally permit. None of that shows up in the Android app's own tests, because the app never tries to read another student's grades. Rules tests do exactly that, locally and repeatably, before `firebase deploy --only firestore:rules` publishes anything. The pieces are: - the **Firebase Local Emulator Suite**, started by the Firebase CLI, which runs Firestore (and Storage, and Realtime Database) on your machine and evaluates real rules; - the **`@firebase/rules-unit-testing`** library for Node, the only Firebase SDK that can **mock `request.auth`**, so a test can act as any user, with any claims, without signing anyone in; - any Node test runner. ## Starting the emulator Either keep it running in a terminal with `firebase emulators:start --only firestore`, or let the CLI wrap the test command, start the emulator, run the script and shut down: `firebase emulators:exec --only firestore "npm test"`. The second form suits CI. At startup the emulator loads the file named by the `firestore.rules` key in `firebase.json`. If there is no such file and the tests do not load rules themselves, the emulator **treats the project as having open rules**, so a suite that only checks successes will pass against no protection at all. If tests report timeouts or `ECONNREFUSED`, the emulator is not running or not where the library expects it. ## The test API The current library (the v9-style modular API) is built around a `RulesTestEnvironment`: | Call | Purpose | |---|---| | `initializeTestEnvironment({ projectId, firestore: { rules } })` | connect to the emulator and load the rules text | | `authenticatedContext(uid, tokenOptions?)` | a client signed in as `uid`, optionally with custom claims | | `unauthenticatedContext()` | a client with no ID token, so `request.auth` is null | | `withSecurityRulesDisabled(callback)` | seed fixtures as if rules were off | | `assertSucceeds(promise)` / `assertFails(promise)` | assert a request was allowed or denied by rules | | `clearFirestore()` | delete the emulator's data for this project | | `cleanup()` | tear down every context so the process can exit | The library is always aware of the emulators and never touches production resources, which is one reason Firebase recommends it over the older v8 testing library, whose API was `initializeTestApp`, `initializeAdminApp` and `loadFirestoreRules`. ## A suite for the grades rules The rules under test let a student read `students/{studentId}/grades/{gradeId}` only when `request.auth.uid == studentId`, and let a user with the `teacher` claim write. ```typescript import { readFileSync } from "node:fs"; import { after, before, beforeEach, test } from "node:test"; import { assertFails, assertSucceeds, initializeTestEnvironment, RulesTestEnvironment, } from "@firebase/rules-unit-testing"; let testEnv: RulesTestEnvironment; before(async () => { testEnv = await initializeTestEnvironment({ projectId: "demo-classroom", firestore: { rules: readFileSync("firestore.rules", "utf8") }, }); }); beforeEach(async () => { await testEnv.clearFirestore(); await testEnv.withSecurityRulesDisabled(async (context) => { await context.firestore().doc("students/alice/grades/g1").set({ score: 91 }); }); }); after(async () => { await testEnv.cleanup(); }); test("a student reads her own grade", async () => { const alice = testEnv.authenticatedContext("alice"); await assertSucceeds(alice.firestore().doc("students/alice/grades/g1").get()); }); test("another student cannot read it", async () => { const bob = testEnv.authenticatedContext("bob"); await assertFails(bob.firestore().doc("students/alice/grades/g1").get()); }); test("a signed-out client cannot read it", async () => { const anon = testEnv.unauthenticatedContext(); await assertFails(anon.firestore().doc("students/alice/grades/g1").get()); }); test("a teacher claim can write a grade", async () => { const teacher = testEnv.authenticatedContext("t1", { teacher: true }); await assertSucceeds( teacher.firestore().doc("students/alice/grades/g2").set({ score: 78 }), ); }); ``` Points worth saying aloud in an interview: 1. Fixtures are written through `withSecurityRulesDisabled`, so seeding never depends on the rules being tested. 2. Custom claims are passed as `tokenOptions`; no Authentication backend is involved. 3. Every grant has a matching denial. The denials are the actual security property. 4. `clearFirestore()` runs before each test because the emulator keeps data for its whole run, so one test's writes would otherwise leak into the next. ## What to cover - each `allow` method separately: `get`, `list`, `create`, `update`, `delete`; - queries, including an unconstrained one that must fail, since rules are not filters; - field-level update rules, with a write that touches a frozen field; - signed-out, other-user and wrong-claim callers for every path; - the test project ID kept separate from production, and the rules file the tests read being the one that ships. Running the suite in CI on every change to the rules file turns a review opinion into a gate.
- Why must a rules suite include assertFails cases, not just assertSucceeds?A rule that allows everything passes every success test. The security property is what gets denied: another student's grade, an unfiltered query, a write without the teacher claim. Also, with no rules file configured the emulator treats the project as open, so a success-only suite can pass against no protection at all.
- How do you test a rule that depends on a teacher custom claim without real Firebase Authentication?Pass the claims as the second argument of `authenticatedContext`, for example `authenticatedContext('t1', { teacher: true })`. The library attaches a mock ID token with those claims, which the emulator evaluates as `request.auth.token.teacher`. No real user account or sign-in is needed, which keeps the test fast and deterministic.
- The emulator denies everything by default when no rules file is configured.
- The rules-unit-testing library may run tests against the production project.
- Testing only the allowed paths is enough to trust the rules.
- Rules tests need a real Firebase Authentication sign-in for each user.
- Emulator data resets automatically after every test case.
Assumes the v9-style @firebase/rules-unit-testing API (initializeTestEnvironment, RulesTestEnvironment); the older v8 library used initializeTestApp, initializeAdminApp and loadFirestoreRules.