I have a firestore with a collection called "children" and a subcollection called events. The children documents have an array called "caretakers" which contains the authids for users that should have access to this document. My question is, what is the right way to secure the subcollection. I am currently doing the following:
match /children/{childId} {
allow read, write, delete, list:
if request.auth.uid in resource.data.caretakers;
allow create:
if true;
}
match /children/{childId}/events/{eventId} {
allow read,write,delete,get:
if request.auth.uid in get(/databases/$(database)/documents/children/$(childId)).data.caretakers
}
Something about that get(...) doesn't feel right to me. Is that necessary? Do I really need to specify rules separately for each subcollection? or if the parent document has permissions.. those permissions should cascade down to subcollections?
With your current structure unfortunately you will indeed need to read the parent document to check against its caretakers role for each subdocument. What's even worse is that this makes queries impossible, as you can't read from the parent document when querying events.
The common workaround for this is to duplicate the caretakers into each events document, so that you can query for it there, and the rules can then secure that only that query is allowed.
Yes you need to explicitly define rules for sub-collections. You can nest the sub-collection's rule in that collection itself to structure it.
Security rules apply only at the matched path, so the access controls defined on the [children] collection do not apply to the [events] subcollection
service cloud.firestore {
match /databases/{database}/documents {
match /children/{childId} {
allow read, write, delete, list: if request.auth.uid in resource.data.caretakers;
allow create: if true;
// These rule will apply for docs in children collection only
// Explicitly define rules for the 'events' subcollection
match /events/{eventId} {
allow read,write,delete,get: if request.auth.uid in get(/databases/$(database)/documents/children/$(childId)).data.caretakers
// This rule will apply for docs in events sub-collections only
}
}
}
}
You can read more about this at: How security rules work?
I'm answering my own question to note what I ended up going with as a solution.
In my case, the number of Users that have access to each {childId} is very low. Therefore, I ended up storing custom claims in the Users Auth object. Basically stored an array of {childId} in the Users auth object instead of storing a bunch of userIds into the Child object.
This allows me to do a direct check to see if the {childId} exists in the users auth object and saves me extra reads of data.
Related
I can't figure out how to write a Firestore rule that reflects: "when the user requests a doc from the messages collection, check that the doc above that "messages" collection includes a field thats an array which includes their uid. I've gotten the rule to work on the top level but if I try to access a document inside a collection, which is inside the "chats" collection, the user is denied.
Here's my relevant rule:
match /chats/{chatId}/{allChildren=**} {
allow read, update: if request.auth.uid in resource.data.usersUids;
}
This works (the chatId doc has an array of uids):
await db.collection("chats").doc(chatId).get()
This does not work (none of the messages have an array of uids):
await db.collection("chats").doc(chatId).collection("messages").get()
It seems like the heart of the issue is that I'm trying to get the resource.data of the messages collection rather than the resource of the chatId doc, but I can't figure out to solve this.
resource only contains the data from the specific document that was matched by the entire path. It doesn't contain anything from any parent documents that appear in that path.
Any time you want to use fields from a document that wasn't matched by the full path, you have to get() the document using its own full path as described in the documentation. For example:
match /chats/{chatId}/{allChildren=**} {
allow read, update: if request.auth.uid in get(/databases/$(database)/documents/chats/$(chatId)).data.usersUids;
}
I know that Firebase has the FieldValue class, which can be used to generate e.g. a server-side timestamp when writing a document (link).
What's the preferred practice for inserting the current user's uid into a document?
Having the client provide that field seems to allow misuse - unless I provide a server rule that checks for (new/updated) documents to match the request.auth.uid, something like:
service cloud.firestore {
match /databases/{database}/documents {
match /broadcasts/{broadcast}/chatMessagesCollection/{message} {
allow write: if request.resource.data.uid == request.auth.uid;
allow read: if true;
}
}
}
I can't find anything on the web for the use-case of having a document be populated with the user writing it -- so what's the best take on this?
What you're doing now with security rules to enforce that the provided UID matches the current user is exactly the right thing to do. There is really nothing better (for this specific use case), and this is a common practice.
I've even written about it in this blog series: https://medium.com/firebase-developers/patterns-for-security-with-firebase-per-user-permissions-for-cloud-firestore-be67ee8edc4a
I've got a Firestore collection.
The IDs of the documents are secrets. You should be able to read only the document whose ID you know.
For the sake of simplicity. I'd like to stick to this approach.
However, by default, one can read an entire collection from Firestore, for example
await firestore.collection("secret_documents").get()
Is it possible to allow reading only one document at once, only when it's referred by its ID?
Yes, that is actually quite easy. To control what documents can be accessed, use Firebase security rules for Firestore.
By default your security rules will be read and write, but those can actually be broken down into more granular operations of get, list, create and update. And what you're trying to do is to allow get, but not a list operation. From the documentation:
service cloud.firestore {
match /databases/{database}/documents {
// A read rule can be divided into get and list rules
match /cities/{city} {
// Applies to single document read requests
allow get: if <condition>;
// Applies to queries and collection read requests
allow list: if <condition>;
}
...
So to allow get for everyone and disallow list calls:
allow get: if true;
allow list: if false;
You'll probably want to elaborate on the allow get rule a bit, because it's more common to restrict it, for example to users that are signed in to your project with Firebase Authentication:
allow get: if request.auth.uid != null;
https://firebase.google.com/docs/firestore/security/rules-query
I see that to get a field of a document in security rules one must use get. The example below shows getting the 'admin' field of some document in the users collection. If I wanted to get another field, would I have to do another get request or can I just do one get request and get all the fields I need in the document.
Here is the example I'm referring to in the documentation.
https://firebase.google.com/docs/firestore/security/rules-conditions
service cloud.firestore {
match /databases/{database}/documents {
match /cities/{city} {
// Make sure a 'users' document exists for the requesting user before
// allowing any writes to the 'cities' collection
allow create: if exists(/databases/$(database)/documents/users/$(request.auth.uid))
// Allow the user to delete cities if their user document has the
// 'admin' field set to 'true'
allow delete: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
}
}
}
Yes, you would have to write another get(). There are no variables in Firestore security rules, so you can't store the contents of a get() in order to use its data multiple times.
Multiple gets accessing the same document might not incur multiple read charges. The documentation states:
Some document access calls may be cached, and cached calls do not count towards the limits.
The Firestore documentation shows examples of how to secure data using Firestore security rules based on the request.auth.uid field. These typically look something like this:
service cloud.firestore {
match /databases/{database}/documents {
match /stories/{storyid} {
// Only the authenticated user who authored the document can read or write
allow read, write: if request.auth.uid == resource.data.author;
}
}
}
That makes perfect sense.
What I don't understand (and doesn't appear to be shown anywhere) is how to set the resource.data.author field securely.
Obviously that can't just be based from the client because then any authenticated user can tamper with the request to set their author to any value.
I thought maybe we are supposed to use CloudFunctions to set that field but at the moment this doesn't work.
The impact of this is pretty clear in the role based access example:
{
user: "alice",
content: "I think this is a great story!"
}
Surely there must be a tamper-proof way to set the user field there - otherwise any user can make their comments appear to be from anyone else. This seems bad.
In the Firestore example web app, it seems to set the userId field on the client side and I think it is doing the same in the Android version.
What am I missing?
Edit: as #imjared points out this rule implies that 'alice' in user: "alice" is actually a uid, so I think this is safe.
I knew I was missing something.
match /comments/{comment} {
allow read: if isOneOfRoles(get(/databases/$(database)/documents/stories/$(story)),
['owner', 'writer', 'commenter', 'reader']);
allow create: if isOneOfRoles(get(/databases/$(database)/documents/stories/$(story)),
['owner', 'writer', 'commenter'])
&& request.resource.data.user == request.auth.uid;
When the user writes a document to Firebase, they can indeed send any value for the author field they want. But there's no way for them to set request.auth.uid. This last bit in crucial to ensure all (read and write) access is authorized.
The first rules snippet you shared actually has two rules, and it might be easier to separate them out for a moment:
allow read: if request.auth.uid == resource.data.author;
allow write: if request.auth.uid == resource.data.author;
The write rule only allows the operation when the author specific in the request is the same as the request.auth.uid. Since request.auth.uid can't be spoofed, and the value of author will only be accepted if it is the same, the write operation is only allowed if the author field is that of the currently authenticated user.
In fact, that latter rule is more regularly written as:
allow write: if request.auth.uid == request.resource.data.author;
The difference when using request is that it explicitly refers to the document (resource) that is in the write request. The result is the same here whether we use resource or request.resource, but I find it easier to see how security works when thinking of the request here.