Best Practice to Store Ownership of a Document in Firestore

Viewed 46

Let's say I have a collection todos that contains documents that represent todo lists of users.

To secure these documents, often, you can find the following snippets of security rules:

...
match /todos/{todo} {
    allow create: if request.auth.uid != null && request.resource.data.ownedBy == request.auth.uid;
    allow read, update, delete: if resource.data.ownedBy == request.auth.uid;
}
...

These rules allow CRUD operations on the documents as long as the ownedBy field is the same as the uid of the person performing the requests.

My concern here is that the ownedBy field is also part of that document, meaning that a user can easily modify ownedBy to a different userId. I doubt anyone will do it for any reasons, but from a developer point of view, would that mean it is dangerous to have the field you rely on to be part of the document that can be edited?

Another way to look at it is, this behavior is the same as storing the permissions/authorizations in the same documents. It'd be wrong to store { canEdit: true, canDelete: false} inside that same document, so why is it ok to store the ownedBy field in that document?

What are some good practices to deal with this problem?

1 Answers

"a user can easily modify ownedBy to a different userId"

Given your rules, they actually can't. You're explicitly checking that resource.data.ownedBy == request.auth.uid and request.resource.data.ownedBy == request.auth.uid. Given that request.auth is auto-populated by Firebase and can't be spoofed, the only value they can ever set for ownedBy is their own UID.

I also recommend checking out the Firebase documentation on controlling access per field.

Related