In Firebase Security Rules for Firestore, how do you let each student in a classroom app read only their own grades?
answer
- path patterns bind variables
- compare the signed-in user to the path
- denied unless something allows
- subcollections are not inherited
- any matching allow wins
basics
~10 sMatch 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 sA `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
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.
Explain deny by default, how nested match paths are relative, why subcollections need their own match, and how read splits into get and list.
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.
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.