In my firestore rules, this allows me to query a list of all of a user's "organizations":
match /organizations/{orgId}{
allow read: if request.auth.uid in resource.data.members;
}
Where members is an array of user id's.
But, if I change this to work with claims:
match /organizations/{orgId}{
allow read: if orgId in request.auth.token.organizations;
}
Where organizations is a list of organization id's.
It seems to work with:
match /organizations/{orgId}{
allow read: if request.auth.token.organizations[orgId] == true;
}
It will let me access the document, but not a list of documents. Is there any way around this?
This doesn't work because security rules are not filters. (Be sure to read the docs in that link.) Also read more here.
When you perform a query on a collection (not a single document get), the filters on the query must absolutely match the requirements of the rules, before the contents of any documents are known. The security rules will not remove individual documents from the results. In this respect, Firestore queries are "all or nothing" - either all of the requested documents are known to match ahead of time, or the entire query fails.
What you have now suggests that each document ID should be read and individually compared to the list of organizations to determine which ones should be returned. Since rules won't do this filtering, it simply simply rejects the query altogether.
What you should probably do instead is simply make one get() for each org ID in the user's claims. It's definitely possible to read custom claims in the client app.
Related
I have a collection on which I want to provide list access, but only in a limited manner for most users.
All users should be able to do this: (the string valuex can be anything)
collection("XYZ").where("fieldx", "==", "valuex").get()
Only admins can get all the documents:
collection("XYZ").get()
Note that as valuex can be anything, at the end of the day all users can see all documents. The difference is that non-admins need to know what to query, admins don't, they get it all directly.
The only solution I have found is to force non-admins to write to a document the value they are querying, prior to calling get. The rules then are:
allow list: if isadmin() || resource.data.fieldx == getvaluex();
function isadmin() { return request.auth.token.get("admin", false); }
function getvaluex() { return get(/databases/$(database)/documents/users/$(request.auth.uid).data.valuex; }
That way all returned documents must have the same value for fieldx. But this solution 1) needs 1 additional write 2) adds a read in the rules and 3) in my case valuex is sensitive and I dont want the user to have to store it in Firestore.
So is there any better solution?
Is it possible for instance to limit the usage of an index to only some users? (both queries above actually have more where statements and require each a specific composite index).
Is it possible to compare the returned documents between each others to ensure they all have the same value for fieldx?
The way I would do it is this:
Don't allow non-admins to make those direct requests to the database at all.
Instead, have them send a request to a Firebase Http function.
The Http function has admin access to the db, it can accept any valuex non-null value.
It queries the db using that valuex, on behalf of the non-admin users, and returns the results.
This way, you can keep the documents in collection XYZ locked to non-admins in your Firestore Rules.
You can even keep sensitive data in those documents, since you have control on what you share with users. You can control that by choosing which fields your HTTP function will return to clients.
Mind you, Firebase function invocations are way cheaper than making additional writes/reads.
Firestore works well for easy/normalized access from clients to collections and documents.
What you are trying to do is pretty specific to your implementation of the these "lists".
You may create another collection (list_auth) that tracks the accesses to the list.
In the security access you can create a security rule for the collection that looks up the permissions of user into the list by accessing the list_auth collection.
https://firebase.google.com/docs/firestore/security/rules-conditions#access_other_documents
Several questions address whether knowing a Firestore uid allows hackers to edit that person's data, like this question and this question. My question is about security rules to filter when users can read another's data.
Specifically, I have a social media app that allows people to post data anonymously. My data model is /users/{user}/posts/{post}. I use db.collectionGroup("posts") to build a timeline of posts, (some anonymous, others with users' names).
Posts that are not anonymous have a valid uid, so it wouldn't be tough for a hacker to figure out someone's uid, which I'm not concerned about. My concern is whether a hacker could then query usersRef.document(uid).posts.getDocuments(); to get all the posts of that user, including the anonymous ones?
Because my app builds timelines from users "posts" collection, I can't write a rule that they can't read another user's posts. Can I write a rule that they can only read posts with collectionGroup?
That's not going to be possible with the way things are structured now. Here's the way you write a rule to allow collection group queries, as described in the documentation
match /{path=**}/posts/{post} {
allow read: if ...condition...;
}
The path wildcard in the rule explicitly allows all reads for all collections named "posts". The rule does not limit the reads to only collection group queries - any normal collection query on any "posts" will be allowed.
Bear in mind also that a collection group query would not hide any data from the caller compared to a normal collection query. The query results will still contain a reference to the full path of each document, which includes the document uid in the path.
So I have a query (that fails). It reads like this: "As I user I can list all the businesses, which I'm a part of, for an organization".
fs
.collection('businesses')
.where('organizationUid', isEqualTo: 'some-organization-id')
.get();
And a security rule to protect it (the gist of it):
match /businesses/{businessId} {
function isStaffOrHigher() {
return get(/databases/$(database)/documents/businesses/$(businessId)/users/$(request.auth.uid)).data.role >= 50;
}
allow read: if isStaffOrHigher();
match /orders/{orderId} {
allow read, write: if isStaffOrHigher();
}
match /users/{userId} {
allow read: if request.auth.uid == userId || isStaffOrHigher();
}
}
Basically it looks up the user's role in his user document (that is owned by that business). This type of rule (that uses the get() operator) works for sub-collections (there's no problem querying orders, for example) of {businessId}, but not for queries that attempts to list the businesses.
Now I KNOW that the organizationUid is a valid constraint, but having read Rules are not filters, I can understand why Firestore can't validate this claim without reading a ton of data.
The question is just, then how do I solve this? And how does Firestore validate the constraint for sub-collections correctly?
Security rules won't do what you want because it would involve reading another document for every document matched by the query. The rules can't know ahead of time what those documents are going to be, as there are variables (businessId) in the path. If this query would yield a millions of documents the businesses collection, you can see how it would be problematic (and expensive for you) to read each of the matching documents from /businesses/$(businessId)/users/$(request.auth.uid) to find out if the entire query should be allowed rejected.
Rules must operate extremely quickly in order to scale in the way that Firestore needs to scale. The limitation that rules can't be filters is part of that requirement for scalability. It's also why there is an overall limit of 10 documents read with get() per rule evaluation.
There is no workaround here from a rules perspective, other than to perform multiple queries, each within bounds of your rules for each collection, and merge the results in your client app.
I have a field on my "feed" documents that represents the userId. I want to secure my data such that only the user can read/write feed entries with their own userId. Everything else - allow the user to read/write as long as they are authenticated.
I'm a little new to firestore, but so far I have something like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /feed/{feedItem} {
allow read, write: if request.auth.uid == resource.data.userId
}
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
Unfortunately, this is still allowing read/write access to everything, including feed items.
Those rules are not going to work the way you expect.
Your rule to limit reads and writes on document in the feed collection looks OK, assuming that the field name seen here matches the name of field in the documents.
However, your rule for "everything else" with match /{document=**} is not OK. This rule always matches every document in your entire database, no matter what your other rules are. So, as you have it written right now, every user can still read and write every document, including those in "feed" because that rule always allows it.
It's good to keep in mind the following statements about the way security rules work:
If any rule would allow access to some document, then access will be allowed.
Once access to a document has been allowed by a rule, that access cannot be revoked by another rule.
In fact, security rules don't have a way to specify "everything else" in relation to some other rule. What you'll need to be do instead is call out each collection by name in its own rule, and assigning access to it. Yes, this is cumbersome if you have a lot of collections, but it's your only option.
I am new to the Firestore security rules and I wanted to make sure that the rules I wrote are secure for my case.
My database structure is like the following:
users / userId / employees / employeeId / files / fileId
The reason I don't denormalize it and create a separate collection for users, employees and files is because this application does not require any sort of cross collection query, there is no place in the application where all employees or their files need to be listed. Which brings me to the rules.
Only the owner of the employee or file collections should be able to access it. Everything inside employees or files can be changed. For the users collection, only creation should be allowed since new users should be able to be created when signing in but no user should be able to edit or delete any other existing user.
Apart from all of the above, there isn't anything else, there are no roles for this app.
My rules are the following:
service cloud.firestore {
match /databases/{database}/documents {
//can read and create if matching userId
//CREATE: NO USER CAN DELETE ACCOUNTS
match /users/{userId} {
allow read, create: if request.auth.uid == userId;
//can read and write if matching userId
match /employees/{employeeId} {
allow read, write, update: if request.auth.uid == userId;
//can read and write if matching userId
match /files/{fileId} {
allow read, write: if request.auth.uid == userId;
}
}
}
}
}
My question would be if my rules are secure? This seems awfully simplistic and I am just not sure if it is enough for my case.
Thanks in advance!
Your rules look fine to me.
But instead of taking my word for it, I strongly suggest using the Firestore local rules emulator and write some tests against your rules in order to verify that very specific queries (that you define) will be allowed or denied. Run these tests against your rules every time your rules have to change, for whatever reason, so you have confidence that the rules are still going to work as expected. I guarantee you this procedure will yield better and faster results than posting to Stack Overflow every time you're wondering if a set of rules will do what you expect. :-)