skip to content

Security Rules

Security Rules authorize every client read and write to Firestore and Cloud Storage against request.auth and the stored resource. A weak rule is a public database, so interviewers ask.

on this pageshow

explore

questions

6

In Firebase Security Rules for Firestore, how do you let each student in a classroom app read only their own grades?

level: juniorimportance: must knowfreq 72%

answer

  1. path patterns bind variables
  2. compare the signed-in user to the path
  3. denied unless something allows
  4. subcollections are not inherited
  5. any matching allow wins

basics

~10 s

Match the grades path with a wildcard for the student ID and allow reads only when request.auth.uid equals that wildcard. Firestore denies anything no rule allows, and each subcollection needs its own match block.

solid answer

~40 s

A `match` block binds path segments to wildcards, so `match /students/{studentId}/grades/{gradeId}` makes `studentId` available to the condition. `allow read: if request.auth != null && request.auth.uid == studentId;` lets a signed-in student read only the documents under their own ID. Everything else is denied by default, because access exists only where some `allow` grants it. Two traps catch people: rules on `/students/{studentId}` do not cascade into its `grades` subcollection, which needs its own nested `match`; and when several `allow` statements match a request, any one that passes grants it, so a broad recursive rule elsewhere silently undoes the careful one. Teachers get write access through a separate condition, such as a `teacher` custom claim read from `request.auth.token`.

go deeper

for a junior

Recall the shape: service, the databases match, a wildcard path, and an allow with request.auth.uid compared to the wildcard. Know that request.auth is null when signed out.

for a middle

Explain deny by default, how nested match paths are relative, why subcollections need their own match, and how read splits into get and list.

for a senior

Show you audit a ruleset as a whole: OR across matching blocks, a leftover recursive wildcard that opens everything, and why the Admin SDK bypassing rules changes nothing for phones.

for a principal

Frame rules as the only gate between untrusted clients and data, so a team needs ruleset review, tests and a closed default as standing policy rather than one careful author.

## How a request meets the ruleset **Firebase Security Rules** for Firestore are a small declarative language deployed with your project. Every read or write that arrives from a client SDK (the Android, iOS or web library talking to Firestore directly) is checked against them before Firestore touches the data. A ruleset has three layers: - a **service declaration**, `service cloud.firestore`, which scopes the file to Firestore rather than Cloud Storage; - a fixed outer **match**, `match /databases/{database}/documents`, which reaches the documents of the database the rules are deployed to; - your own nested **match blocks**, each holding **allow statements** with a condition. The model is **deny by default**. A request succeeds only if at least one `allow` statement whose `match` covers the document's full path evaluates to `true`. Nothing in the language says "deny"; you deny by not allowing. One boundary matters before anything else: the **server client libraries**, including the Admin SDK running on your backend, bypass these rules entirely and authorize through Google Cloud IAM. Rules guard what phones and browsers do, not what your own trusted server does. ## Wildcards and request.auth A match path is written against **documents**, not collections. A segment in braces is a **wildcard**: `match /students/{studentId}/grades/{gradeId}` matches any grade document of any student, and inside the block `studentId` holds the actual segment, for example `alice`. The second ingredient is `request.auth`. When the client is signed in with Firebase Authentication, `request.auth.uid` is that user's UID and `request.auth.token` is a map of the ID token's claims, including any **custom claims** your backend set. When nobody is signed in, `request.auth` is `null`. Anonymous accounts count as signed in: they have a UID, and `request.auth.token.firebase.sign_in_provider` is `anonymous`. Combining the two gives the classic ownership rule: ```plaintext rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /students/{studentId} { allow read: if request.auth != null && request.auth.uid == studentId; match /grades/{gradeId} { allow read: if request.auth != null && request.auth.uid == studentId; allow write: if request.auth != null && request.auth.token.teacher == true; } } } } ``` The student document is keyed by the student's UID, so the path itself records ownership. Nested `match` paths are relative to their parent, so the inner block covers `/students/{studentId}/grades/{gradeId}`, and the outer `studentId` stays visible inside it. ## Read and write, split finer `read` and `write` are convenience methods. Underneath them: | Method | Covers | |---|---| | `get` | reading one document by its path | | `list` | queries and reads of a whole collection | | `create` | writing a document that does not exist yet | | `update` | writing to an existing document | | `delete` | deleting a document | Splitting matters later: you might let a student `get` one grade but forbid broad `list` queries, or let teachers `create` and `update` grades while nobody may `delete` them. In the ruleset above the student's `read` covers both: a query on `students/alice/grades` passes for Alice, because every document it could return lives under her own ID. ## The two traps that open the data 1. **Rules do not cascade into subcollections.** Rules apply only at the path they match. An `allow read` on `/students/{studentId}` says nothing about `/students/{studentId}/grades/{gradeId}`; unless some other block matches it, the subcollection is simply denied. People then "fix" the denial with a recursive wildcard, `match /students/{document=**}`, and the next trap fires. 2. **Matching allows are combined with OR.** If two `match` blocks cover the same document, the request succeeds when either grants it. A more specific block cannot narrow a broader one. An old `match /{document=**} { allow read, write: if request.auth != null; }` left over from prototyping lets every signed-in student read every grade, whatever the careful rule says. The recursive wildcard `{name=**}` also depends on the **rules version**. With `rules_version = '2';` it matches zero or more path segments and may appear anywhere in the path; in version 1, the default when the line is missing, it matches one or more segments and must come last. Collection group queries need version 2. ## What the client sees On Android, a denied read or write fails its `Task` with a `FirebaseFirestoreException` whose `code` is `PERMISSION_DENIED`. Nothing is partially returned and no field is silently dropped. That is useful in tests: a missing rule shows up as a hard failure rather than as quietly missing data. A few habits keep this rule honest: - start every ruleset closed and add one `match` per collection you actually expose; - grep the deployed ruleset for recursive wildcards with permissive conditions before every release; - keep teacher powers in their own condition, a claim or a lookup, instead of widening the student rule; - remember that hiding a collection name in the app protects nothing, because any client with the project's configuration can call Firestore directly.

  • Why does the student's rule use read rather than only get?
    `read` covers both `get` and `list`. A grades screen usually runs a query on `students/{uid}/grades`, which is a `list` request. With only `allow get`, the student could open one grade by ID but the query would be denied. Splitting the two is useful when you want single reads but no broad queries, or when you want to cap queries with `request.query.limit`.
  • How do teachers get write access without loosening the student rule?
    Give writes their own condition. A common one checks a custom claim, `request.auth.token.teacher == true`, which the backend sets through Firebase Authentication. Another reads a document with `get()` or `exists()`, such as a teachers list for the class. The student's `read` stays tied to `request.auth.uid == studentId`, and because rules combine with OR, the two conditions never weaken each other.

  • Rules on a parent document automatically protect its subcollections.
  • A more specific match block can override and restrict a broader allow.
  • When nobody is signed in, request.auth is an object with an empty uid.
  • An anonymous Firebase user makes request.auth null in Security Rules.
  • Not exposing the collection name in the app keeps the data private.
open as a page

In Firestore, why does a student's query over the grades collection fail with PERMISSION_DENIED when Security Rules let them read their own grades?

level: middleimportance: must knowfreq 68%

basics

~20 s

Security Rules are not filters. Firestore checks a query against every document it could possibly return, so an unconstrained query fails outright; the query must carry the same constraint as the rule, such as whereEqualTo on studentId.

open as a page

In Firebase Security Rules for Cloud Storage, how do you limit a student's assignment upload to their own folder, PDF files and a maximum size?

level: juniorimportance: should knowfreq 34%

basics

~10 s

In a service firebase.storage ruleset, match /submissions/{studentId}/{fileName} and allow create only when request.auth.uid equals studentId, request.resource.size is under the cap and request.resource.contentType is application/pdf.

open as a page

How do you unit-test Firestore Security Rules against the Firebase Local Emulator Suite before deploying them?

level: middleimportance: should knowfreq 30%

basics

~10 s

Run 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.

open as a page

In Firestore Security Rules, how do resource.data and request.resource.data differ, and how do you stop a grade update from changing protected fields?

level: middleimportance: should knowfreq 52%

basics

~10 s

resource.data is the document as stored before the write; request.resource.data is the whole document as it would be after it. Protect fields on update with request.resource.data.diff(resource.data).affectedKeys().hasOnly([...]) plus type and range checks.

open as a page

In Firestore Security Rules for a classroom app, when should a teacher check read a custom claim from request.auth.token rather than call get() on a roles document?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Use a custom claim for a coarse, slow-changing role such as teacher: it costs no read but stays stale until a new ID token. Use get() or exists() for live per-class membership, paying a billed read and a capped lookup count.

open as a page