SkillByAIOpen interactive version →

Lesson 13 / 25

Rules Language Basics

match, allow, request and resource.

How a rule is evaluated

A rules file declares a service and nested match blocks that select document paths, with {wildcards} capturing path segments. Inside, allow statements grant operations (read, which splits into get and list, and write, which splits into create, update and delete) when a condition is true. Access is denied by default; if any matching allow is true, the request is allowed. Key variables: request.auth (null when signed out; uid and token with claims otherwise), resource.data (the document as stored), and request.resource.data (the document as it would be after the write). Rules are not filters: a list query is rejected unless the rules can prove every possible result is allowed, so queries must include matching constraints.

The real backend boundary

Security Rules decide, for every client request, whether a read or write on Firestore or Storage is allowed.

Figure 5.1 — match, allow, conditions and tests.

A first rules file

Firestore Security Rules.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    // public read, signed-in users may create posts as themselves
    match /posts/{postId} {
      allow read: if true;
      allow create: if request.auth != null
                    && request.resource.data.authorId == request.auth.uid;
      allow update, delete: if request.auth != null
                            && resource.data.authorId == request.auth.uid;
    }

    // everything else is denied because nothing matches
  }
}

resource versus request.resource

Use resource.data to check who owns what exists now, and request.resource.data to validate what the client is trying to store.

Quick check: A query for all posts is rejected even though rules allow reading posts where authorId == request.auth.uid. Why?

  • Queries never pass rules
  • Rules are not filters; the query must itself constrain authorId to the user's uid
  • list operations are always denied
  • The rules need rules_version 3
Answer

Rules are not filters; the query must itself constrain authorId to the user's uid — Rules check whether every possible result is allowed.