skip to content

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%

answer

  1. rules judge the query, not the rows
  2. potential result set
  3. all or nothing
  4. repeat the rule's constraint in the query

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.

solid answer

~40 s

Firestore does not run the rule over each stored document and drop the ones you may not see. It evaluates the query itself: if any document the query could return might fail the `list` rule, the whole request is rejected with `PERMISSION_DENIED`, even when every document actually stored would pass. So with `allow read: if resource.data.studentId == request.auth.uid`, `collection("grades").get()` fails, while `collection("grades").whereEqualTo("studentId", uid)` succeeds because the filter proves every result satisfies the rule. The same holds for aggregation queries, `in` and OR queries are checked value by value, and a collection group query additionally needs `rules_version = '2'` and a `match /{path=**}/grades/{id}` rule. A `get()` of one document by ID is different: it is checked against that document's real fields.

code

kotlin · 21 lines
kotlin
import com.google.firebase.Firebase
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.firestore

fun loadMyGrades(
    uid: String,
    render: (List<DocumentSnapshot>) -> Unit,
    onDenied: () -> Unit,
) {
    Firebase.firestore.collection("grades")
        .whereEqualTo("studentId", uid)
        .limit(20)
        .get()
        .addOnSuccessListener { snapshot -> render(snapshot.documents) }
        .addOnFailureListener { e ->
            val denied = e is FirebaseFirestoreException &&
                e.code == FirebaseFirestoreException.Code.PERMISSION_DENIED
            if (denied) onDenied()
        }
}

go deeper

for a junior

Remember the phrase: rules are not filters. A query must include the same condition the rule checks, or it fails completely.

for a middle

Explain potential result set versus actual data, why get by ID behaves differently from list, and how request.query.limit lets a list rule cap queries.

for a senior

Diagnose a PERMISSION_DENIED list screen from the rule and query alone, and handle OR and in queries, aggregations and collection group queries with rules_version 2.

for a principal

Treat data shape and rules as one design: ownership fields duplicated for queryability, and a review step that pairs every list rule with the queries the apps run.

## The symptom A classroom app stores grades in a flat collection, `grades/{gradeId}`, and each document carries a `studentId` field. The ruleset says: ```plaintext rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /grades/{gradeId} { allow read: if request.auth != null && resource.data.studentId == request.auth.uid; } } } ``` Opening a single grade by its ID works. But the grades screen runs `Firebase.firestore.collection("grades").get()` and the task fails with a `FirebaseFirestoreException` whose code is `PERMISSION_DENIED`, even in a test project where every stored grade belongs to the signed-in student. ## Rules are not filters The cause is the most-asked fact about Firestore rules: **rules are not filters, and queries are all or nothing**. - For a **query**, Firestore does not read every candidate document, run the rule on it, and hand back the survivors. To save time and cost it evaluates the query against its **potential result set**: could this query, as written, return a document the rule would reject? - If the answer is yes, the **entire request** fails. No partial result comes back. - The actual data does not rescue the query. An unconstrained query on `grades` *could* return another student's grade, so it fails even when no such grade exists yet. - For a **single-document read** by ID, Firestore does read the document and evaluates the rule against its real fields. This is why the detail view worked while the list failed. The fix is to make the query prove what the rule demands: ```kotlin import com.google.firebase.Firebase import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.firestore fun loadMyGrades( uid: String, render: (List<DocumentSnapshot>) -> Unit, onDenied: () -> Unit, ) { Firebase.firestore.collection("grades") .whereEqualTo("studentId", uid) .limit(20) .get() .addOnSuccessListener { snapshot -> render(snapshot.documents) } .addOnFailureListener { e -> val denied = e is FirebaseFirestoreException && e.code == FirebaseFirestoreException.Code.PERMISSION_DENIED if (denied) onDenied() } } ``` The `whereEqualTo("studentId", uid)` filter guarantees `resource.data.studentId == request.auth.uid` for every possible result, so the rule engine can approve the query without looking at a single row. ## How common query shapes are judged | Query | Rule `resource.data.studentId == request.auth.uid` | |---|---| | `collection("grades")` with no filter | denied: could include anyone's grades | | `whereEqualTo("studentId", uid)` | allowed: every result satisfies the rule | | `whereEqualTo("studentId", otherUid)` | denied: the filter proves the rule fails | | `whereIn("studentId", listOf(uid, otherUid))` | denied: each value is checked separately | | `count()` on the filtered query | allowed: aggregations follow the same rule | For **OR-style queries** (`or`, `in`, `array-contains-any`) the rules engine checks each comparison value on its own; one value that cannot pass sinks the query. **Aggregation queries** such as `count()` obey exactly the same rules as queries that return documents: rules control which conditions are allowed, not how data is returned. ## Constraining queries from the rules side Because `read` splits into `get` and `list`, you can treat queries differently from single reads. The `request.query` variable exposes the query's `limit`, `offset` and `orderBy`, so a rule can refuse unbounded listing: ```plaintext match /grades/{gradeId} { allow get: if request.auth != null && resource.data.studentId == request.auth.uid; allow list: if request.auth != null && resource.data.studentId == request.auth.uid && request.query.limit <= 50; } ``` A query without `.limit()`, or with a larger one, is now denied, which caps how much one client can pull per request. ## Collection group queries If grades instead live under each class, `classes/{classId}/grades/{gradeId}`, a student's "all my grades" screen needs a **collection group query**: `Firebase.firestore.collectionGroup("grades").whereEqualTo("studentId", uid)`. Two rules facts apply: 1. The ruleset must start with `rules_version = '2';`, because collection group rules depend on version 2's recursive wildcard. 2. You must allow the group explicitly with `match /{path=**}/grades/{gradeId}`. A rule on `classes/{classId}/grades/{gradeId}` alone does not authorize a collection group query. That recursive rule applies to **every** collection named `grades` anywhere in the database, so its condition must hold on its own, here by requiring the `studentId` filter. The query also needs a single-field index with collection group scope, which is a Firestore indexing matter rather than a rules one. ## Habits that prevent the surprise - Write the rule and the query together: every field a `list` rule tests on `resource.data` must be pinned by a filter in the query. - Duplicate ownership into a field when ownership lives in the path and you need collection group queries, then validate that field on write. - Treat `PERMISSION_DENIED` on a list screen as "the query does not prove the rule" before suspecting the user's identity. - Unit-test the unconstrained query with an expectation that it fails, so a later rule change that turns rules into an accidental filter is caught.

  • Why does opening one grade by its ID work when the list query fails?
    A single-document `get` is evaluated against the stored document's real fields, so Firestore reads that grade and checks `resource.data.studentId`. A query is evaluated against its potential result set without reading the rows. The detail screen passes on data; the list screen must pass on the query's own constraints.
  • How can a rule refuse queries that pull too many grades at once?
    Split `read` into `get` and `list`, and in the `list` rule check `request.query.limit`, for example `request.query.limit <= 50`. A query without a limit, or with a bigger one, is then denied. `request.query` also exposes `offset` and `orderBy` for similar checks.
  • What extra does a collection group query over every class's grades need from the rules?
    The ruleset needs `rules_version = '2'` and an explicit `match /{path=**}/grades/{gradeId}` block; a rule on the full `classes/{classId}/grades/{gradeId}` path does not authorize the group. That recursive block covers every collection named `grades`, so its condition, such as the `studentId` check, must stand on its own.

A records office that will not search the archive for you: it reads your request slip, and only if the slip itself says 'grades for student Alice only' does it fetch anything. A vague slip is refused even if every file happens to be Alice's.

  • Firestore filters out the documents the rules deny and returns the rest.
  • The query should succeed because all stored grades belong to this student.
  • An in query passes if at least one listed value satisfies the rule.
  • count() aggregations bypass Security Rules because they return no documents.
  • A rule on the full nested path also authorizes collection group queries.