Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 31 ยท Security Rules and Row Level Security

Firestore Security Rules

Write Firestore Security Rules that protect your data: match paths, request.auth, resource.data, write validation, why rules are not filters, and testing.

In a Firebase app the browser talks straight to Firestore. There is no server of yours in between to say "this user may not read that document". Something has to enforce that, and it is Firestore Security Rules. They are a small program that Google runs on every read and write request. If the rules say no, the request fails, no matter what your client code does.

This is the most important lesson for a Firebase app. Your app config and public key are visible to everyone who opens the page, so the rules are your only gate. Below you will learn the rules language (read-only, because it runs inside Firebase), then run a stand-in evaluator that behaves the same way on a tiny scale. The stand-in is ours and covers only a fraction of the real language.

Rules run on every request

Request Who is asking, and what do they want to do?
Rules Match the path, then check the conditions.
Allow At least one matching rule says yes.
Deny Otherwise the request is rejected.

The default answer is no.

1 / 2

The shape of a rules file

Rules live in firestore.rules and are deployed with the Firebase CLI. The file starts with a service block, then match blocks that describe document paths, and allow statements inside them.

Text
// firestore.rules (read-only)
rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {

    match /posts/{postId} {
      allow read: if true;
      allow create: if request.auth != null;
      allow update, delete: if request.auth != null
                            && request.auth.uid == resource.data.authorId;
    }

  }
}

Three ideas carry the whole language:

  • match selects documents by path. is a wildcard that captures one path segment into a variable. {path=**} captures any depth.
  • allow names the operations: read (which means get and list) and write (which means create, update and delete). You can list operations separated by commas.
  • if holds a condition. If no allow matches and passes, access is denied. If several match, one passing is enough.

Rules do not cascade down by themselves. A match /posts/{postId} does not cover /posts/p1/comments/c1. You write a nested match or use {document=**} when you really want everything below.

What the rules can look at

Every request gives the rules a few objects:

Name Meaning
request.auth null for signed-out users, else uid and token (claims, email_verified)
request.resource.data The document as it would look after a create or update
resource.data The document as it is now in the database
request.time The server time of the request
path variables postId and others captured by match

The pair resource and request.resource is what lets you write rules about changes: "the owner field may not change", "the balance may only go down by the price".

Text
// read-only
match /profiles/{userId} {
  allow read: if request.auth != null;
  allow create: if request.auth.uid == userId
                && request.resource.data.keys().hasOnly(["name", "bio"])
                && request.resource.data.name is string
                && request.resource.data.name.size() <= 40;
  allow update: if request.auth.uid == userId
                && request.resource.data.diff(resource.data).affectedKeys().hasOnly(["bio"]);
}

The create rule makes the document ID equal the user's own uid, accepts only the fields name and bio, and checks type and length. The update rule uses diff().affectedKeys() to allow changing bio only.

Helper functions and roles

Functions keep rules readable. Roles typically come from custom claims on the token, or from a document you look up.

Text
// read-only
function signedIn() {
  return request.auth != null;
}
function isAdmin() {
  return signedIn() && request.auth.token.admin == true;
}
function isMember(teamId) {
  return exists(/databases/$(database)/documents/teams/$(teamId)/members/$(request.auth.uid));
}

get() and exists() read other documents inside a rule. Each one is a billed read and the number of such calls per request is limited, so use them sparingly.

Rules are not filters

This is the mistake that surprises almost everyone. A query is allowed or denied as a whole, and Firestore decides by looking at the query, not at the data it would return. It will not quietly return only the documents you may see.

Suppose posts are readable only when resource.data.published == true. This query fails with a permission error:

JavaScript
// Firebase (read-only)
const snap = await getDocs(collection(db, "posts"));   // permission-denied

It fails because the query could match unpublished posts. The query must prove it only asks for allowed documents:

JavaScript
// Firebase (read-only)
const q = query(collection(db, "posts"), where("published", "==", true));
const snap = await getDocs(q);                          // allowed

Design your data and rules together: if a rule depends on a field, your queries must filter on that field. It also means a rule can never hide "some" of a collection from a broad query, so keep private and public data in separate collections or documents.

Validating writes

Because the client is untrusted, rules are also your last line of validation. Check required fields, types, sizes and allowed values, and stop clients from setting fields only the server should control.

Text
// read-only
match /orders/{orderId} {
  allow create: if signedIn()
    && request.resource.data.userId == request.auth.uid
    && request.resource.data.status == "new"
    && request.resource.data.total is number
    && request.resource.data.total > 0
    && request.resource.data.createdAt == request.time;
}

request.time compared with a field written using serverTimestamp() stops users from faking dates. For anything that rules cannot express (prices from a product catalog, stock checks, sending email), move the write into a Cloud Function and close the collection to clients.

Testing rules

Never test rules only by clicking around in your app. Use the Firebase Emulator Suite, which runs the same rules engine on your machine, and the @firebase/rules-unit-testing package.

JavaScript
// rules.test.js (read-only)
import { initializeTestEnvironment, assertFails, assertSucceeds } from "@firebase/rules-unit-testing";

const env = await initializeTestEnvironment({
  projectId: "demo-test",
  firestore: { rules: fs.readFileSync("firestore.rules", "utf8") },
});

const ana = env.authenticatedContext("ana").firestore();
const guest = env.unauthenticatedContext().firestore();

await assertSucceeds(setDoc(doc(ana, "profiles/ana"), { name: "Ana" }));
await assertFails(setDoc(doc(ana, "profiles/ben"), { name: "Ben" }));
await assertFails(getDoc(doc(guest, "profiles/ana")));

Write one test for every rule that grants access and several that must be denied. The failing tests protect you more than the passing ones. The console's Rules Playground is handy for a quick check, but it is not a test suite.

A stand-in rule evaluator

The evaluator below mirrors the main mechanics: rules have a path pattern with wildcards, one or more operations, and a condition. A request is allowed only if some matching rule allows that operation, and the default is deny. The conditions are JavaScript functions here, standing in for the rules expression language.

JS Stand-in rules evaluator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the third line: Ana cannot read her own draft because we never wrote a rule that allows it. Adding || resource.authorId == auth.uid to the read condition would fix that, and then queries would have to filter by authorId too. The last line shows the default: a path no rule matches is denied.

The second stand-in demonstrates "rules are not filters". It decides a query by checking its constraints against the rule, never by looking at the rows.

JS A query must prove it is allowed

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Even though the unfiltered query would have returned two allowed rows, it is rejected completely. That all-or-nothing behavior is exactly how Firestore treats queries.

Common mistakes

  • Test mode left on. Rules like allow read, write: if true; or a time-limited "test mode" open the whole database to the internet. Replace them before launch.
  • Checking only sign-in. request.auth != null means "anyone with an account", and anyone can register. Compare uid with the owner field or a membership.
  • Trusting fields the client sends. If a user can write role: "admin" into their own profile, they are an admin. Validate keys with hasOnly.
  • Forgetting nested paths. Subcollections need their own match blocks.
  • Expecting rules to filter results. They never do; shape your queries to match.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user queries a whole collection, but rules only allow reading documents where published == true. What happens?

    Firestore evaluates the query against the rules before running it. Rules are not filters, so the query itself must guarantee it only asks for allowed documents.
  2. 2. Which object holds the document as it would look after the write?

    resource.data is the stored version; request.resource.data is the proposed version. Compare them to protect fields.
  3. 3. What does a request get when no allow rule matches it?

    Security Rules deny by default. Access exists only where a matching allow condition passes.
  4. 4. Why is request.auth != null alone a weak rule for private data?

    Being signed in proves identity, not permission. Compare request.auth.uid with an owner field or membership.

Summary

  • Security Rules run on every Firestore request from the client and deny by default.
  • match selects paths, allow lists operations, and if holds the condition; one passing rule is enough.
  • Use resource.data for stored data and request.resource.data for incoming data to validate writes and protect fields.
  • Rules are not filters: queries must constrain the same fields the rules check.
  • Test rules with the emulator and @firebase/rules-unit-testing, with many cases that must fail.

Next: Row Level Security Policies