Get collection with exists() security rule - google-cloud-firestore

I have a collection called "classrooms" with the following security rule:
match /classrooms/{classroom} {
allow read, write: if request.auth != null && exists(/$(request.path)/users/$(request.auth.uid));
}
I only want users to be able to access the documents where they have a document with their user ID in "classrooms/{classroom}/users".
The above rules work for getting an individual document, but I get a permissions error when calling the collection (obviously because it's also trying to get documents I can't access, and security rules aren't filters).
How would I write a query to get the classrooms collection with the JS library and the above security rule without getting the "Missing or Insufficient permissions" error? Thanks

Related

Does a wildcard have to be used for the document segment in a matching path of a Firestore collection group security rule?

db.collectionGroup('private')
.where('members', 'array-contains', userId)
.get()
.then(...)
This query fetches documents successfully if the relevant security rule is set like:
match /{path=**}/private/{document} {
allow read: if request.auth.uid in resource.data.members;
}
However, the similar rule below prevents the same query unexpectedly.
match /{path=**}/private/allowed {
allow read: if request.auth.uid in resource.data.members;
}
In this database,
private subcollections exist only under documents in the rooms collection.
Every private has only a single document with the ID "allowed".
This means /rooms/xxxxxxxx/private/allowed is the only possible path existing, where xxxxxxxx is an auto-assigned document ID.
Therefore specifying the path as /{path=**}/private/allowed looks correct to me.
In fact, "get" queries work in simulations in the playground, so is it a restriction only for collection group queries, or am I doing anything wrong?
FYI, more detailed database structure is described in another question of mine here.
Yes, it is required.
When you perform a collection group query, it's not possible to call out a specific document id in the query (e.g. "allowed"). The query is explicitly asking to consider all of the documents in all of the subcollections of the given name ("private"). Therefore, the rules must allow for those documents to be considered by adding the trailing wildcard.
You can certainly add a filter to the query if you want to get only certain documents with certain field values, but that filter can't be enforced in the rules.

Firestore Security Get with a Where Query using Array Contains produces a permission denied

I've got a Document structure where I have a collection of accounts (_accounts), and each account document in the collection has a subcollection called allowedusers. The documents within allowedusers has a document of each user that has access to the account. Each account document also has field of an array of string of the userids which I'm using to query using Array Contains.
My Firestore rules to ensure that each read is checked against the allowed users is :
match /_accounts/{accountid}{
allow read: if request.auth != null && get(/databases/$(database)/documents/_accounts/$(accountid)/allowedusers/$(request.auth.uid)).data.allowed == true
}
Dart Code from Flutter:
QuerySnapshot querySnapshot = await firestore.collection('_accounts').getAccounts()
.where('userids', arrayContains: _user.id)
.getDocuments();
The above query is producing a Permission Denied :
PlatformException (PlatformException(Error performing getDocuments,
PERMISSION_DENIED: Missing or insufficient permissions., null))
Alternate methods that I've attempted:
Security Rule :
match /_accounts/{accountid}{
allow read: if request.auth != null && resource.data.userids == request.auth.uid
}
Dart Code:
QuerySnapshot querySnapshot = await firestore.collection('_accounts')
.where('userids', arrayContains: _user.id)
.limit(5)
.getDocuments();
For testing purposes I've only got two documents in the _accounts collection, so I'm assuming that the permission denied is coming from hitting the limits when using get within the security rules.
Is there a way of applying security rule and query the collection like this ?
The first security rule is rejecting the query because security rules are not filters. Read more about what that means. It's important to understand this concept, so be sure to read and understand the documentation.
Security rules will only allow a query if it can determine that the query will only find documents that are allowed. It will not check each individual document in the collection for permission and filter out the ones that don't pass the rules. That would not scale at all.
The second rule is rejecting access because it's not correctly checking the array field. If userids is an array field, you can't use an equality expression to compare it with a string as you are with resource.data.userids == request.auth.uid.
If you want to make sure that the user's UID is contained within a document, you will need to treat the field like a list object, and use list operations on it. Use hasAny for that.
allow read: if request.auth != null && resource.data.userids.hasAny([request.auth.uid]);

Securely querying data with firestore - Permission denied

I'm facing a permission denied error when querying firestore, when I have introduced a rule. I have narrowed down my complex rule and filter to the below 2 examples of which one query works, and one doesn't. I do not understand what is wrong with my failing query.
From https://cloud.google.com/firestore/docs/security/rules-query I understand that a rule is not a filter. According to this document: "If a query could potentially return documents that the client does not have permission to read, the entire request fails.".
Baring that in mind, I have been iterating over my rule, filter and data, and come with the below:
The data:
I have NO data in my collection called "MyCollection". As a matter of fact, the collection "MyCollection" has never existed.
The rule:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /MyCollection/{id} {
allow read: if (
(resource.data.readAccess == 0)
)
allow write: if (true)
}
}
}
My failing query (where I have the permission denied error):
Firestore.instance.collection('MyCollection')
.where("readAccess", isLessThanOrEqualTo: 0)
.getDocuments()
.then((_) => print("Success!"));
When I run this query, I get the following error:
W/Firestore(12491): (21.3.0) [Firestore]: Listen for Query(MyCollection where readAccess <= 0) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}
My successfull query:
(The only difference in this query is that I replaced "isLessThanOrEqualTo" with isEqualTo)
Firestore.instance.collection('MyCollection')
.where("readAccess", isEqualTo: 0)
.getDocuments()
.then((_) => print("Success!"));
Comments:
I have the same results when I do populate MyCollection with data.
It looks like the query is validated against the rule, not the "potential return documents" as the document https://cloud.google.com/firestore/docs/security/rules-query states. If this is the case I wonder how I will be able to translate the following rule into a filter:
(resource.data.readAccess == 0) ||
((request.auth != null) &&
(resource.data.readAccess <= get(/databases/$(database)/documents/App/$(resource.data.appId)).data.group[request.auth.uid])
)
This rule is fairly similar, except that it validates the readAccess level of a document against the group access level in the "App" document for that data's app, for the logged on user. If I can't match the query for a simple rule, I can't imagine what I need to do for this complex rule.
Please advise. Many thanks.
With security rules, the query must exactly match the rules. The behavior you're observe is exactly what I would expect.
With a rule like this:
allow read: if resource.data.readAccess == 0;
That means the query must be filtered exactly like this;
where("readAccess", isEqualTo: 0)
Nothing else will satisfy this rule. It's absolutely demands that the query filter for exactly the value of 0 on the readAccess field. It's not clear to me why you're expecting a different outcome.
Your query suggests that the client provide its own "access" to the collection. Note that this is not secure. You can't depend on client apps self-reporting their own level of access in a database query. Something else on the backend needs to determine if the app is allowed to make the query.
Typically, Firebase Authentication is used to determine who the user is, then allow access based on what that user is allowed to do. You could store the user's permissions somewhere in another document, and use the contents of that document to determine what they can do. Or perhaps use custom claims. But you can't trust the the user pass their own permissions.

firestore security rules get subcollection document

I'm facing insufficient permissions for this firestore security check.
service cloud.firestore
{
match /databases/{database}/documents
{
match /events/{eventID}
{
allow read:
if get(/databases/$(database)/documents/events/$(eventID)/authorizations/$(request.auth.uid)).data.EVENT_READ == true;
}
}
}
the get document is hardcoded in the firestore database and the simulator returns true but for the actual query returns insufficient privileges.
I tested and moved the authorizations subcollection to the same level as users collection and it works. Am i missing out anything?
Additional testing: Reading the document directly does not result in insufficient privileges. I'm testing to see if it's an issue with listing but to my knowledge read should cover both get and list in firestore security rules.
Update: Listing seems to be the issue here. I tried to list the entire collection with only one document and it results in the insufficient privileges.
Works:
this.angularFirestore.collection('events').doc(eventID).valueChanges();
Doesn't work (updated):
this.angularFirestore.collection('events', query => query.where('admins', 'array-contains', auth.uid)).valueChanges()
My firestore database:
/events/event1_id
- field 1: some string
- field 2: some string
- admins: array of uid strings
/authorizations/<uid> #uid for $(request.auth.uid)
- EVENT_READ: true
Update 2: Updated the doesn't work query string which I tried out. It is intriguing that if i move the /authorizations sub collection out to be the same level as /events collections, the query will not fail.
Your first query works because it's accessing the events collection with a specific document. That specific document meets the rules criteria, because you've arranged for the get() to allow it.
Your second query doesn't work because it's attempting to get all of the documents in events collection. Your rule does not specifically allow that. It looks like you expect your rule to filter out the events that aren't allowed access based on the contents an unknown number of other documents. You need to be aware that security rules are not filters. Please click through to the documentation and read that section. The client must only request documents that are known to be readable according to rules. It can't depend on rules to filter documents that are not allowed.
If you want to be able to query for all events that the current user has access to, your current database structure will not work. You will need to put all the relevant information in the events collection itself. This means you should consider something like putting the UID of each user that's allowed to read the event in the document itself, then filter on that field. Or have some other collection that you can query in this way.

Is there any function for rules in reading all documents in a collection?

I have some trouble with setting up my rules for a firestore project. I try to learn the database setup but can't find any solution for this. So there's no problems when i try to get a document from my collection "lists". But when i try to get all of the documents in the collection "lists" xcode tells me "Missing or insufficient permissions".
My goal is to have users that are able to create documents in collection "lists" but they can only read the documents in "lists" where they appear in the document array "members".
Right now I can add documents in collection("lists") without any problem but I can't read them. I can only read them one by one from xcode with a specific target.
Any tips or ideas?
service cloud.firestore {
match /databases/{database}/documents {
match /{documentId} {
allow read: if request.auth.uid != null;
}
match /lists/{docId} {
allow write: if request.auth.uid != null;
allow read: if request.auth.uid in resource.data.members
}
}
}
Xcode.
//working
let docRef = db.collection("lists").document("j0hHA5TLPETf6JRMbC1s")
docRef.getDocument { ...
//not working due to permission failed
db.collection("lists").getDocuments() { ...
Your rule doesn't work because it assuming that the rule will filter out all the documents that don't match the rule. This is not how security rules work. Security rules are not filters. From the linked documentation:
When writing queries to retrieve documents, keep in mind that security
rules are not filters—queries are all or nothing. To save you time and
resources, Cloud Firestore evaluates a query against its potential
result set instead of the actual field values for all of your
documents. If a query could potentially return documents that the
client does not have permission to read, the entire request fails.
The client must only request documents that would satisfy the rules. Right now, the query is asking for ALL documents in the lists collection, regardless of whether or not the client has access to them. This is going to fail the security rule, because it's attempting to read documents that it doesn't have access to.
What you need to do instead is make your query only request documents that are readable by the user. This means that you should probably be using an array-contains filter on the client to match only documents that the rule would allow it to read.
Actually, you are on the right path, I think if you change your code like this, it will work.
Instead of this:
match /{documentId} {
allow read: if request.auth.uid != null;
}
Use this:
match /lists {
allow read: if request.auth.uid != null;
}
So when you try to access lists without documentId, it will check the auth.uid.
But when you try to access a document ex. lists/1, it will check whether that user exists in the array.