skip to content

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%

answer

  1. before versus after the write
  2. the whole pending document
  3. diff, then affectedKeys
  4. allowlist with hasOnly
  5. a missing field is an error

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.

solid answer

~40 s

In a Firestore rule, `resource.data` is the stored document and `request.resource.data` is the complete pending document after the write, including unchanged fields merged in on an update. That is why `request.resource.data.keys()` cannot tell you what an update touched; `request.resource.data.diff(resource.data).affectedKeys()` can, and `.hasOnly(['score', 'comment'])` lets a teacher change only those two fields while `teacherId` and `studentId` stay frozen. On `create`, `keys().hasAll([...])` requires fields and `keys().hasOnly([...])` forbids extras, `is number` and comparisons check types and ranges, and `request.resource.data.teacherId == request.auth.uid` stops spoofed ownership. Reading a field that does not exist raises an error and denies the request, so optional fields go through `get('comment', '')`. A write is accepted or rejected whole; rules never keep some fields and drop others.

code

plaintext · 8 lines
plaintext
match /students/{studentId}/grades/{gradeId} {
  allow update: if request.auth != null
      && request.auth.token.teacher == true
      && request.resource.data.diff(resource.data).affectedKeys().hasOnly(['score', 'comment'])
      && request.resource.data.score is number
      && request.resource.data.score >= 0
      && request.resource.data.score <= 100;
}

go deeper

for a junior

Recall that resource.data is the stored document and request.resource.data is the document after the write, and that rules can check field types with is.

for a middle

Explain why keys() fails for updates and diff().affectedKeys().hasOnly() works, how hasAll and hasOnly shape creates, and why optional fields need get with a default.

for a senior

Spot the unsafe patterns in review: validation only on create, denylists instead of allowlists, client-sent owner fields, and private fields that rules cannot hide.

for a principal

Decide which invariants rules can carry and which need server code, because rules accept or reject whole writes and cannot transform or partially hide data.

## Two views of one document Every write rule in Firestore can see the document twice: - **`resource`** is the document as it is stored now. `resource.data` is a map of its fields. On a `create`, nothing is stored yet, so there is no existing data to compare against. - **`request.resource`** is the document as it **would be** if the write were allowed. On an `update` that sends only a couple of fields, `request.resource.data` still holds the **whole** future document: the sent fields merged over the stored ones. That second point is the one interviews probe. Because `request.resource.data` is complete, `request.resource.data.keys()` lists every field of the future document, including ones the client never touched. It answers "what will the document contain?", not "what did this write change?". ## Locking fields on update To learn what an update changed, compare the two views: - `request.resource.data.diff(resource.data)` returns a **map diff** between the future and stored maps; - `.affectedKeys()` on that diff is the set of fields added, removed or changed; - `.hasOnly([...])` is true when every affected key is in your allowlist, and `.hasAny([...])` is true when at least one is. An allowlist is the safer habit. With `affectedKeys().hasOnly(['score', 'comment'])`, a field added to the schema next year is frozen until someone deliberately allows it. A denylist with `!affectedKeys().hasAny(['teacherId'])` leaves every new field writable by default. ## A grade ruleset ```plaintext rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /students/{studentId}/grades/{gradeId} { function isTeacher() { return request.auth != null && request.auth.token.teacher == true; } function validGrade(data) { return data.score is number && data.score >= 0 && data.score <= 100 && data.get('comment', '') is string; } allow read: if request.auth != null && request.auth.uid == studentId; allow create: if isTeacher() && request.resource.data.keys().hasAll(['score', 'subject', 'teacherId']) && request.resource.data.keys().hasOnly(['score', 'subject', 'teacherId', 'comment']) && request.resource.data.teacherId == request.auth.uid && validGrade(request.resource.data); allow update: if isTeacher() && request.resource.data.diff(resource.data).affectedKeys().hasOnly(['score', 'comment']) && validGrade(request.resource.data); } } } ``` What each piece buys: 1. `keys().hasAll` makes `score`, `subject` and `teacherId` mandatory on creation. 2. `keys().hasOnly` rejects any field outside the allowed set, so a client cannot smuggle in `approved: true`. 3. `teacherId == request.auth.uid` stops one teacher filing a grade in another's name. 4. The `diff` check on update freezes `subject` and `teacherId` after creation. 5. `validGrade` runs on both create and update; Firestore is schemaless, so types are only enforced where you check them. 6. There is no `delete` rule, so deletes are denied. ## Type checks and missing fields The `is` operator tests a value's type: `bool`, `bytes`, `float`, `int`, `list`, `latlng`, `number`, `path`, `map`, `string` and `timestamp`. The ruleset above uses `number` rather than `int` so the check does not hinge on how the client encoded the score. Lists and maps have no element types, so you can check that `tags is list` and that `tags[0] is string`, but not "a list of strings" in one step. Reading a field that is absent, such as `request.resource.data.comment` when no comment was sent, is an **error**, and an error denies the request. Optional fields therefore go through the map's `get` with a default: `data.get('comment', '') is string` passes when the field is missing and checks the type when it is present. ## What rules cannot do here | Want | Rules answer | |---|---| | Accept the valid fields, drop the bad one | Impossible: a write is accepted or rejected whole | | Hide one field from students on read | Impossible: reads return whole documents; move the field to another document | | Check a field against another document | Possible with `get()` or `exists()`, each a billed read | | Require two documents to change together | Possible with `getAfter()` inside a batch or transaction | The read-side limit surprises people: a teacher's private note on a grade document is readable by anyone who may read that grade. Put it in a separate document, such as a `private` subcollection, with its own stricter rule. ## Common mistakes - Validating on `create` and forgetting `update`, so a valid grade can later be edited to `score: 1000`. - Using `request.resource.data.keys()` to restrict updates, which also counts untouched fields and makes the rule either useless or impossible to satisfy. - Comparing ownership against a field the client sends, with no check that the field equals `request.auth.uid`. - Expecting server code using the Admin SDK to be validated too; server client libraries bypass rules, so their writes must be validated in that code.

  • Why can't the update rule simply check request.resource.data.keys().hasOnly(['score', 'comment'])?
    Because `request.resource.data` is the whole future document, its `keys()` include every stored field such as `subject` and `teacherId`, even if the update did not touch them. That rule would deny every update of a normal grade. `diff(resource.data).affectedKeys()` lists only the fields the write adds, removes or changes, which is what an update allowlist needs.
  • A teacher's private remark sits on the grade document; can rules hide it from the student?
    No. Firestore reads return whole documents, and rules can only allow or deny the read, never strip a field. Move the remark to a separate document, for example `grades/{gradeId}/private/remark`, and give that path a rule that only teachers satisfy.

  • On an update, request.resource.data contains only the fields the client sent.
  • request.resource.data.keys() shows which fields an update changed.
  • Rules can accept the valid fields of a write and drop the invalid ones.
  • A rule can let students read a grade but hide its teacher remark field.
  • Reading a missing field in a rule just evaluates to null and continues.
  • Validating fields on create is enough because updates keep the same shape.