The Firebase Rules docs suggest building conditions comparing the authenticated user's token (i.e., request.auth) with the target Firestore document(s). Something like:
match /posts/{postId} {
allow read, write: if (request.auth.uid != null) &&
(resource.data.tenantId == request.auth.token.tenantId);
}
However, tenantId doesn't appear to be available in Firebase Rules like other related auth fields (e.g., uid, email, email_verified, etc.).
One option appears to be to add tenantId separately as a custom claim using the firebase-admin SDK. But that would create duplicate info on the user object:
{
uid: 'nzjNp3QIfSR6uWy',
emailVerified: true,
displayName: 'pickleR'
...
tenantId: 'wubalubadubdub',
customClaims: { tenantId: 'wubalubadubdub' },
}
An alternative option appears to be to create a tenants collection in Firestore. However, that approach seems to introduce needless complexity and inflate the # of required Firestore queries.
Are there alternatives for accessing the tenantId in Firestore Rules and/or alternative best practices for using Firestore with multi-tenancy?
Having gone down the custom claim route, I've then found the tenant Id is already stored in a nested object as 'request.auth.token.firebase.tenant'
In your example the rule would be:
match /posts/{postId} {
allow read, write: if (request.auth.uid != null) &&
(resource.data.tenantId == request.auth.token.firebase.tenant);
}
The two options you describe are the idiomatic ones:
Pass the information into the rules as part of the ID token as a custom claim.
Look up the information in the database from the rules by the request.auth.uid.
Neither of these is always better than the other: custom claims are more convenient and readable, while using the database is usually faster. It's common to use the database lookup for more volatile information, and claims for information that is "once".
Since this is for a tenant ID, which is unlikely to change quickly, I'd probably go for a custom claim.
Related
Is there any way to prevent user send custom id for newly created document?
For example
This operation create's new document with id "8pqLuAc6BXCVRF7SB6xT"
db.collection("users").add({foo : 1})
And in my application i always want to have id generate by firebase sdk not by user
because as we know user can hack app and trigger operation like this
db.collection("users").doc('CUSTOM_ID').set({foo : 1})
After this operation id will be "CUSTOM_ID" instead generated by SDK like '8pqLuAc6BXCVRF7SB6xT'
So question is how to write rule to ensure me that id is generated from sdk
Update following your clarification:
It is not possible with Security Rules to avoid a user specifying the ID of a document when it is created.
Even if the code in your front end only uses the add() method, one can write his own code and use the doc() method to write to your DB (as soon as he gets the Firebase configuration object, which is easy).
One possibility would be to write to Firestore via a Cloud Function, but this has some drawbacks see this article.
Original answer:
It is not crystal clear what you mean by a "custom id" but I understand that you probably want a given user to be able to create a document in the users collection only if this document ID is corresponding to his user uid (from the Auth service)
The following Security Rule should the trick:
service cloud.firestore {
match /databases/{database}/documents {
// Make sure the uid of the requesting user matches name of the user
// document. The wildcard expression {userId} makes the userId variable
// available in rules.
match /users/{userId} {
allow create: if request.auth != null && request.auth.uid == userId;
// ...
}
}
}
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?
"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.
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
On my app I am trying to make it so that users have to have a unique username.
My current method is to have a Social Collection with one document called Usernames. That document will store the users userID as the key for the field and then their username for the value.
I am struggling to write the correct security rules for this. I would like it so that:
All signed-in users can get this document
Users can only update their own data in the document, formatted as [theirUserId: theirUsername]
There can be no duplicate usernames, e.g.
userIdA: "foo"
userIdB: "foo"
At the moment the only point that I can't get to work is checking to see whether a username is already taken.
Another solution I have thought of is to reverse the fields (username: userID). But I can't figure out a way how to write the security rules for this method either.
Current Rules
// Usernames
match /Social/Usernames {
allow get: if request.auth.uid != null;
allow update: if isUserNameAvailable();
}
// Functions
function isUserNameAvailable() {
// This line works
return (request.writeFields.hasOnly([request.auth.uid]))
// This one doesn't
&& !(resource.data.values().hasAny([request.writeFields[request.auth.uid]]));
}
Firestore Data Structure
Any help is greatly appreciated, many thanks!
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.