Firebase Security Rules how to wildcard all path except the ones specified

Viewed 1024

Let's imagine a set of rules having the following fields:

service cloud.firestore {
   match /databases/{database}/documents {
     match /stories/{story} {}
     match /comments/{comment} {}
     match /posts/{post} {}
  }
} 

And we want to add a new match condition for all the remaining collections using a wildcard of come sort.

How can I achieve this?

3 Answers

I believe this is not possible. If you use a wildcard in a match on a collection like this:

match /{collection}/{doc} { ... }

Then it will match all documents in all collections, including stories, comments, and posts. This is certainly not what you want. There's no way to do substring or regex matching with a wildcard. It always applies to an entire collection or document ID in the path.

I've came across this recently and I've come up with a solution. Wildcards (non-recursive) can be not only at document level, but also at collection name level.

A solution to your example could be:

service cloud.firestore {
   match /databases/{database}/documents {
     match /{collection}/{docName}/{document=**} {
         allow read: if collection == 'comments';
         allow write: if collection != 'posts';
    }
  }
} 

Just as an example, I hope I've been clear

You can do this by using recursive wildcards that was introduced in Firestore Rules version 2 recently. But you need to specify rules version like this:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Matches any document in collection and subcollections
    match /{path=**} {
      allow read, write: if <condition>;
    }
  }
}

More details you can find here: https://firebase.google.com/docs/firestore/security/rules-structure#recursive_wildcards

Related