23
votes

I am using Firebase Cloud Firestore, and I want to modify my rules to restrict users from querying a collection.

This should not be allowed:

firestore().collection("users").get()

But this should be allowed:

firestore().collection("users").doc("someUserId").get()

Currently, my rules look like this:

match /users/{userId} {
    allow read;
}

but this rule allows the "users" collection to be queried.

How can I allow single document gets, but not collection queries?

2
I don't think you can write rules that only apply to collections. If you look at the Firestore Security Rules Docs, you'll notice that all the security rules are being applied to documents and their subcollections. There's no rule specifying a condition to access a collection. - Rosário Pereira Fernandes
Yeah, that's what I thought while reading the documentation, but I wanted to see if someone knows a way... - dshukertjr

2 Answers

33
votes

You can break read rules into get and list. Rules for get apply to requests for single documents, and rules for list apply to queries and requests for collections (docs).

match /users/{userId} {

  //signed in users can get individual documents
  allow get: if request.auth.uid != null;

  //no one can query the collection
  allow list: if false;
}
-5
votes

Give the following a try. I haven't been able to test it, so apologies if I've mistyped something.

match /users/{userId} {
    allow read: if $(request.auth.uid) == $(userId);
}