5
votes

The Database have a collection "Collection" and each document inside the collection have an object "members" which contains the "uid" of users who will have access to the document.

Collection--->document-->members = {"BZntnJO2PVS8OZ9wctwHiyxBytc2": true} 

I have tried many different types of rules but none of these rules seems to work

service cloud.firestore {
  match /databases/{database}/documents {
  match /collection/{documentId} {
         allow read: ****
 }
}

1)

allow read: if get(/databases/$(database)/documents/collection/$(documentId)).members[request.auth.uid] != null

2)

allow read: if resource.data.members[request.auth.uid] != null

3)

allow read: resource.members[request.auth.uid] != null

4)

allow read: if request.resource.data.members[request.auth.uid] != null

5)

allow read: request.resource.members[request.auth.uid] != null

Can it be a Firestore bug?

1

1 Answers

6
votes

You need to access the data property to get at any user-created properties, so rules 1, 3, and 5 won't work.

request.resource generally refers to the data that you're sending down to the database, typically in the case of a write operation, so rule #4 won't work, because request.resource.data will probably be empty in the case of a read.

Rule #2 does look right, but keep in mind this will only work in the case of fetching a single document. Queries are a little trickier.

Specifically, if you're running a general "Get every document in my collection" kind of query, Cloud Firestore doesn't have the time to search through every record in your database to ensure that your user has access, so it will reject this query. Instead, you'd need to run a query where Cloud Firestore can "prove" that all documents you'd retrieve will be valid. In your case, for example, you would want to make sure your query is something like "Get every document in my collection where members.(userID) != null". Cloud Firestore rules can then compare your query with its rules and feel satisfied that you'll only get documents you have access to.