Firestore security rules ship as whole-file releases
A Firestore rules deploy replaces everything at once, with no canary. The traps in the rules and the release path, and the pipeline that catches them.
Here is a rules file that looks like it protects the notes collection and closes everything else:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /notes/{noteId} {
allow read: if request.auth != null && request.auth.uid == resource.data.ownerId;
}
match /{document=**} {
allow read: if request.auth != null; // added "temporarily" for a debugging session
}
match /{document=**} {
allow read, write: if false;
}
}
}Every signed-in user can read every note. The deny-all block at the bottom changes nothing, and nobody reviewing the file top to bottom would be reassured by its presence. That is the first trap in this article, and it sets the tone: Firestore Security Rules decide who can read and write every document your browsers and apps touch, they are released as one text file with one command, and the failure modes are quiet. The traps below are the ones worth designing around. Each gives what you see, why it happens and the fix. The pipeline that contains most of them comes after.
Rules and IAM are two separate gates. The Firebase documentation states that the server client libraries bypass Security Rules and authenticate through IAM. Mobile and web SDK traffic is checked against rules; Admin SDK and Google Cloud client library traffic never evaluates them. Keep that in mind for the third trap.
A deny-all block is not a safety net#
What you see: a broad allow somewhere in the file, and a false rule below it that appears to cancel it.
Why: Security Rules are additive. When a request matches several match statements, access is allowed if any condition is true. A deny in one block cannot veto an allow in another, so the closing if false block only documents intent; it can never remove access that another block grants.
Fix: protection comes from never writing the broad allow, not from a rule placed after it. In review, search the diff for {document=**}, for {path=**} and for if true the way you would search code for eval. Prefer helper functions to new wildcards, and add a test for every path that must stay closed (the last test in the suite below does).
Rules and queries are not the same thing#
What you see: a query fails with a permission error even though every document it would return is readable.
Why: rules are not filters. A query has to prove from its own constraints that every document it could return is readable, otherwise the whole request is rejected. The Firebase documentation notes that if the rules deny access to any of the specified document paths, the entire request fails.
Fix: write the query's where clauses so they imply the rule. If a rule says a note is readable by its owner, the query filters on ownerId equal to the signed-in user. This is a data-modelling concern as much as a rules concern, which Firestore data modelling for a million users develops.
A broken rules file keeps your health checks green#
What you see: a deploy goes out, the backend dashboards stay calm, and users report that the app is broken, or nobody notices that it has become too permissive.
Why: your server code uses the Admin SDK and is checked against IAM, so it never evaluates the rules. Only browser and mobile clients feel a rules change, and server-side monitoring cannot see them.
Fix: treat the rules file as a client-facing API. Run its tests in the pipeline, and when a deploy matters, send a canary request from a real client SDK as the last pipeline step. A permissive mistake produces no error at all, which is why the tests below always come in pairs: one request that must succeed and one that must fail.
An update that touches a field you never meant to expose#
What you see: a user changes a field the app never lets them edit, or hands a document to someone else.
Why: a rule that only checks who is writing, and not what changes, lets a legitimate user rewrite any field. An owner who can change ownerId can transfer the document, and the new owner's rules then apply.
Fix: allow-list the fields an update may touch with diff(...).affectedKeys().hasOnly(...), and require ownership fields to be unchanged. Here is a file that does both, with helper functions so a diff reads as intent rather than as boolean soup:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function signedIn() {
return request.auth != null;
}
function isOwner(uid) {
return signedIn() && request.auth.uid == uid;
}
function onlyChanges(allowedFields) {
return request.resource.data.diff(resource.data).affectedKeys()
.hasOnly(allowedFields);
}
// profiles: any signed-in user can read, only the owner can write
match /profiles/{uid} {
allow read: if signedIn();
allow create: if isOwner(uid)
&& request.resource.data.keys().hasOnly(['displayName', 'bio', 'createdAt']);
allow update: if isOwner(uid)
&& onlyChanges(['displayName', 'bio']);
allow delete: if false;
}
// notes: private to the owner
match /notes/{noteId} {
allow read, delete: if isOwner(resource.data.ownerId);
allow create: if isOwner(request.resource.data.ownerId);
allow update: if isOwner(resource.data.ownerId)
&& request.resource.data.ownerId == resource.data.ownerId;
}
// everything else: closed, as documentation of intent only
match /{document=**} {
allow read, write: if false;
}
}
}The collection names and fields are examples. The final block is harmless because it can only ever add a false, but remember the first trap: it protects nothing by itself.
{document=**} does not mean the same in both rules versions#
What you see: a wildcard at a collection root matches the path you did not expect, or fails to match the one you did.
Why: in rules version 1 the recursive wildcard matches one or more path segments; in version 2 it matches zero or more. The two behave differently at the root of a collection.
Fix: declare rules_version = '2'; explicitly in the first line, as above, and check the declared version before you reason about a wildcard.
The console simulator tests the editor, not production#
What you see: "I tested it in the console and it passed", followed by an incident.
Why: the console rules simulator evaluates the ruleset currently in the editor, not the one deployed. The documentation recommends the Local Emulator Suite for real validation.
Fix: put the test suite on the emulator, and make it fail the pipeline. The library is @firebase/rules-unit-testing, with initializeTestEnvironment, assertSucceeds and assertFails, per the emulator testing documentation:
import { readFileSync } from "node:fs";
import { afterAll, beforeAll, beforeEach, describe, it } from "vitest";
import {
assertFails,
assertSucceeds,
initializeTestEnvironment,
type RulesTestEnvironment,
} from "@firebase/rules-unit-testing";
import { doc, getDoc, setDoc, updateDoc } from "firebase/firestore";
let env: RulesTestEnvironment;
beforeAll(async () => {
env = await initializeTestEnvironment({
projectId: "demo-rules-test",
firestore: { rules: readFileSync("firestore.rules", "utf8") },
});
});
beforeEach(async () => {
await env.clearFirestore();
});
afterAll(async () => {
await env.cleanup();
});
describe("notes", () => {
it("lets the owner read, refuses everyone else, refuses a hand-over", async () => {
await env.withSecurityRulesDisabled(async (ctx) => {
await setDoc(doc(ctx.firestore(), "notes/n1"), { ownerId: "alice", text: "x" });
});
const alice = env.authenticatedContext("alice").firestore();
const bob = env.authenticatedContext("bob").firestore();
const anon = env.unauthenticatedContext().firestore();
await assertSucceeds(getDoc(doc(alice, "notes/n1")));
await assertFails(getDoc(doc(bob, "notes/n1")));
await assertFails(getDoc(doc(anon, "notes/n1")));
await assertFails(updateDoc(doc(alice, "notes/n1"), { ownerId: "bob" }));
await assertSucceeds(updateDoc(doc(alice, "notes/n1"), { text: "y" }));
});
});
describe("profiles and unknown paths", () => {
it("allows only listed fields, and closes unknown collections", async () => {
await env.withSecurityRulesDisabled(async (ctx) => {
await setDoc(doc(ctx.firestore(), "profiles/alice"), { displayName: "A", bio: "", createdAt: 1 });
});
const alice = env.authenticatedContext("alice").firestore();
await assertSucceeds(updateDoc(doc(alice, "profiles/alice"), { bio: "hello" }));
await assertFails(updateDoc(doc(alice, "profiles/alice"), { createdAt: 2 }));
await assertFails(getDoc(doc(alice, "secrets/anything")));
});
});Seed data with withSecurityRulesDisabled so setup does not depend on the rules under test, and clear the emulator between tests. Run the suite through the emulator, which manages ports and lifecycle:
firebase emulators:exec --only firestore "pnpm vitest run firestore.rules.test.ts"While the emulator runs, the documented coverage report at http://localhost:8080/emulator/v1/projects/<project_id>:ruleCoverage.html shows which rules the tests exercised. An allow that no test touches is a missing test.
The CLI overwrites whatever someone changed in the console#
What you see: a fix made in the console disappears at the next deploy, or a console edit that nobody copied back is live for months.
Why: the documentation says the rules in your project directory overwrite any existing rules in the Firebase console. Rules can be published from the Firebase console, the Google Cloud console, the Firebase CLI and the Rules REST API, and nothing reconciles them.
Fix: make the repository the only source, publish only from CI, and detect drift. The deploy job runs the tests and then the release, on the main branch only:
firebase emulators:exec --only firestore "pnpm vitest run firestore.rules.test.ts"
firebase deploy --only firestore:rules --project YOUR_PROJECT_IDGive the job a keyless identity, as in Workload Identity Federation for GitHub Actions, with only the permissions a rules release needs. The documentation lists firebaserules.releases.create and firebaserules.releases.update for deploying; a failed deploy names any permission still missing, so build a custom role from that rather than granting a broad one. Keep rules deploys separate from index deploys so a failed index build cannot block an urgent rules fix, and a rules revert does not roll back indexes.
The drift check reads the deployed ruleset through the Rules REST API: projects.releases.get returns a release whose rulesetName points at a ruleset, and projects.rulesets.get returns that ruleset with its full source. For the default database the release is named projects/PROJECT/releases/cloud.firestore; a named database appends its ID, as in cloud.firestore/east_store. The identity running the check needs firebaserules.releases.get and firebaserules.rulesets.get.
import { readFileSync } from "node:fs";
import { GoogleAuth } from "google-auth-library";
const PROJECT_ID = "my-project";
const RELEASE = "cloud.firestore"; // or "cloud.firestore/east_store" for a named database
const BASE = "https://firebaserules.googleapis.com/v1";
const auth = new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"] });
async function get<T>(path: string): Promise<T> {
const client = await auth.getClient();
const res = await client.request<T>({ url: `${BASE}/${path}` });
return res.data;
}
const normalise = (s: string) => s.replace(/\r\n/g, "\n").trim();
const release = await get<{ rulesetName: string }>(`projects/${PROJECT_ID}/releases/${RELEASE}`);
const ruleset = await get<{ source: { files: { name: string; content: string }[] } }>(release.rulesetName);
const deployed = normalise(ruleset.source.files[0].content);
const committed = normalise(readFileSync("firestore.rules", "utf8"));
if (deployed !== committed) {
console.error(`Deployed rules (${release.rulesetName}) differ from firestore.rules in the repository.`);
process.exit(1);
}
console.log("No drift.");Run it weekly on a schedule, and route its failure to a channel someone reads; wire the notification the way Cloud Scheduler jobs that don't silently fail describes, or the check becomes a silent failure itself. A console edit then becomes visible in days instead of at the next incident.
One file, several databases#
What you see: the wrong database gets the rules, or a database keeps old ones.
Why: with multiple databases, firebase.json associates a rules file with each one, and firebase deploy --only firestore:rules deploys the rules of every database listed. The single-database form, with one firestore object, is not enough once a second database exists.
Fix: make firestore an array, with one entry per database, and target one database with firebase deploy --only firestore:<databaseId>:
{
"firestore": [
{
"database": "(default)",
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
{
"database": "ecommerce",
"rules": "firestore.ecommerce.rules",
"indexes": "firestore.ecommerce.indexes.json"
}
],
"emulators": {
"firestore": { "port": 8080 }
}
}The drift check above then runs once per database, with the release name for each. Note also that the Google Cloud console does not support deploying to the (default) database; use the Firebase console or the CLI for that one.
A bad release is not gone when the command exits#
What you see: the rollback command succeeded and the bad behaviour continues for several minutes.
Why: propagation is not instant. Updates can take up to a minute to affect new queries and listeners, and up to 10 minutes to fully propagate to active listeners. A rollback has the same delay. Rolling back is also just another release: the Google Cloud console keeps a timeline of prior rulesets that can be viewed, cloned or restored, and redeploying an earlier commit through CI does the same.
Fix: do not mark an incident resolved when the command returns, and rehearse the rollback once in a throwaway project. Two limits are worth knowing, neither close for a normal application: a ruleset must be smaller than 256 KiB of UTF-8 text, and a project can hold at most 2,500 deployed rulesets, so a pipeline that deploys on every branch will use them faster than one that deploys from main only.
Rules are not the place for every invariant#
Rules see the request and a few lookups. Cross-document business invariants, such as a balance that must never go negative, belong in server code or transactions, through the Admin SDK that bypasses rules. Lookups with get() and exists() cost document reads, so a rule that leans on them is slower, costlier and harder to test and review. If you are writing hundreds of lines of rules with multiple cross-document lookups, the logic probably belongs behind an API you can unit test like any other code.
And if your clients never talk to Firestore directly, because every request goes through your own backend, a deny-all file is all you need, allow read, write: if false;, deployed once, with IAM doing the real work. The pipeline above is for teams whose browsers and apps are the clients.
Related articles
All articles →Swap service account keys in GitHub secrets for short-lived OIDC tokens, lock the trust to your own repo, and deploy to Cloud Run with no JSON key.
11 min
Most small teams should not start with a service perimeter. The organization prerequisite, the friction it adds, and when it pays for itself.
9 min
An Eventarc trigger delivering to a private Cloud Run service passes four identity checks. A 401/403 reference table, and the setup that keeps each one correct.
9 min