TLDR; I want restrict reading a firestore doc to the two users that are mentioned in that doc. Firestore security rules are allowing one to access but failing for other.
In my ecommerce app, when customer A places an order in Shop B, an order document is added in orders collection. I want to setup security rules so that this order can only be read by the customer A or the shop B.
This is what the rules look like :
match /orders/{orderId} {
allow read: if request.auth.uid == resource.data.cust.uid ||
request.auth.uid == resource.data.shop.ownerUid;
allow write: if < Some Condition >;
}
Now while fetching orders for a customer I am querying like this, and it works OK. Security Rules pass it through.
let query = dbFirestore.collection('orders')
.where("cust.uid", "==", firebase.auth().currentUser.uid)
.orderBy('statusHistory.New', 'desc')
.startAfter(lastVisible)
.limit(5);
query.get();
However, when i query for the shop (like below), I get permission denied error (by Security rules)
let query = dbFirestore.collection('orders')
.where("shop.ownerUid", "==", firebase.auth().currentUser.uid)
.orderBy('statusHistory.New', 'desc')
.startAfter(lastVisible)
.limit(5);
query.get();
Both queries are similar, yet one passes and the other fails !!!
Another fact that i want to mention is that a customer can own a shop too, so below is one possible case :
request.auth.uid = shop.ownerUid = cust.uid = firebase.auth().currentUser.uid
I am having a feeling that it may have something to do with the Rules error, but I am not on any conclusion.
I also tried with adding shopId in query and rules, but it still fails.
let query = dbFirestore.collection('orders')
.where("shop.ownerUid", "==", firebase.auth().currentUser.uid)
.where("shop.shopId", "==", shopId_of_this_shop) // <---- This
.orderBy('statusHistory.New', 'desc')
.startAfter(lastVisible)
.limit(5);
Rules :
match /orders/{orderId} {
allow read: if request.auth.uid == resource.data.cust.uid ||
(request.auth.uid == resource.data.shop.ownerUid &&
request.resource.data.shop.shopId == resource.data.shop.shopId);
}
For reference, below is the data from order document :
I appreciate any help on this.
It was due to index not existing.
I hadn't generated index for "shop.ownerUid", and since the query was failing with the "Permission Error" and not the "Index is Required". I kept focussing on Security Rules.
Query on "cust.uid" was passing because it had the index.
Once i realised and generated the index on "shop.ownerUid" and the status field of query, it worked.
Related
I have a firebase collection notes where each document has a user-id array that contains some user ids.
I've set a custom claim on my user access token that is in the format of nid=true (where nid is the note document id they should have access to) however when I try and query the collection for any relevant documents I receive a permission error.
My query is written as follows:
const notesRef = collection(db, "notes");
const allNotesQuery = query(
notesRef,
where("user_ids", "array-contains", user.uid)
);
const noteDocs = await getDocs(allNotesQuery);
my security rules are:
match /notes/{nid} {
allow read, write: if request.auth != null && request.auth.token[(nid)] == true
}
I've also tried nid without the brackets around it like so, but it still doesn't work
match /notes/{nid} {
allow read, write: if request.auth != null && request.auth.token[nid] == true
}
Can anyone see anything obviously wrong with this? If I inspect my token I see the custom claim set correctly with the correct nid value. Unfortunately I can't find a way to test custom claims in the developer console.
*** edit ***
As a follow up to my comments on the first posted answer. The following doesn't work.
allow read, write, list: if request.auth != null && request.auth.token[nid] in resource.data.user_ids
but this does:
allow read, write, list: if request.auth != null && request.auth.uid in resource.data.user_ids
Firestore security rules don't filter the data. Instead they merely ensure that your app is not requesting more data than it's permitted to. For more on this, see the Firebase documentation on rules are not filters.
Since your code is not in any way filtering on the nid token (as far as I can tell), the rules reject the operation. So modify the query to only request only note IDs that the user has access to, and then the rule you wrote can validate it.
So I have a followers collection and a users collection. Creating a doc in the followers collection with a certain ID requires a doc to exist with the same ID in the users collection.
So, in the security rules, I check for the existence of that document.
match /followers/{followers} {
function loggedInUserMatching() {
return (request.auth != null) && (request.auth.uid == followers);
}
function userExistsAndLoggedIn() {
return loggedInUserMatching() && exists(/databases/$(database)/documents/users/$(request.auth.uid));
}
allow create, delete: if userExistsAndLoggedIn();
}
In my tests, I try to create a doc in followers without the corresponding doc in the users collection. This should fail.
const database = testEnv.authenticatedContext('user1').firestore();
let testFollowersDoc = database.collection("followers").doc("user1");
expect(assertFails(testFollowersDoc.set({followers: []}))).resolves.toBeDefined();
Then, I create the doc in the users collection and then try to create the doc in followers again. This should succeed, but it always fails.
const testUserDoc = database.collection("users").doc("user1");
testUserDoc.set({about: "Wow", following: []});
expect(assertSucceeds(testFollowersDoc.set({followers: []}))).resolves.toBeUndefined();
The create rule for the users collection is correct and the document is actually created. I can access its data and verify it exists. But in my security rules, the exists() function always returns false, so the permission is denied and the document is not created.
What could be the cause of this? Am I using the exists() function incorrectly? Or am I not creating the document properly in my test?
I've been trying to solve this for a long time so any help would be appreciated!
These lines are asynchronous and should have await.
expect(assertFails(await testFollowersDoc.set({followers: []}))).resolves.toBeDefined();
expect(assertSucceeds(await testFollowersDoc.set({followers: []}))).resolves.toBeUndefined();
I have the following batch, where I delete three documents in a collection,
the data-set-c collection however has one nested collection for massages where each message is a doc each.
the problem is that the (data-set-c) collection never gets deleted, I don't know if it is due to the nesting taking place? will deleting this way affect also sub-collection? or is it the rules that are blocking it since my rules are specific to the deepest level endpoint, or should use the cloud function instead since this doc will be massive later on, and each day is massages collection but the main issue here is how to delete this one level nested structure.
could you please take a look and see what I am doing wrong.
// Batch
const batch = writeBatch(db);
// data-set-a/{Id}/sub-set-a/{subSetId} ---> the direct document
const colA = collection(db, data-set-a,_authContext.currentUser.uid, sub-set-a);
// data-set-b/{Id}/sub-set-b/{subSetId} ---> the direct document
const colB = collection(db, data-set-b, _authContext.currentUser.uid, sub-set-b);
// data-set-c/{Id}/sub-set-c/{subSetId}/masseges/{mgsId} /*nested collection*/
const colC = collection(db, 'data-set-c', _authContext.currentUser.uid, sub-set-c);
const docA = doc(colA, subSetId);
const docB = doc(colB, subSetId);
const docC = doc(colC, subSetId);
const docsArr = [docA, docB, docC];
docsArr.forEach((col: any) => {
batch.delete(col)
});
await batch.commit();
// sub-set-a + sub-set-b SECURITY RULES
match /data-set-a/Id}sub-set-a/{subId} {
allow delete: if request.auth != null
&& request.auth.token.email_verified
&& request.auth.uid == Id
}
// sub-set-c SECURITY RULES
match /data-set-c/{Id}/sub-set-c/{subSetId}/masseges/{mgsId} {
allow delete: if request.auth != null
&& request.auth.token.email_verified
&& request.auth.uid == Id
}
the problem is that the (data-set-c) collection never gets deleted.
That's the expected behavior. If you delete a document, doesn't mean that you delete all sub-collections that exist within that document. Besides that, that document ID will continue to exist and the Firebase Console will display it in italic.
will deleting this way affect also sub-collection?
No, it won't.
or is it the rules that are blocking it since my rules are specific to the deepest level endpoint.
If it was about the security rules, then you would have received an error indicating that.
or should use cloud function instead since this doc will be massive later on
Yes, you can indeed use a Cloud Function to delete all documents that exist in all sub-collection of the document that was deleted.
How to delete this one-level nested structure.
You can achieve this by iterating each sub-collection, and by deleting each document. But don't do it on the client!
I am having an issue where I am trying to query a subquery by a field, and I have tried the emulator as well as firebase support (still on going, but not solutions yet).
When running the following query:
const queryByNumber = query(
collectionGroup(this.firestore, 'residents'),
where('cellNumber', '==', number)
);
return from(getDocs(queryByNumber));
This query has the error of:
Property cellNumber is undefined on object. for 'list' # L6
This is what the rules look like at the moment
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{path=**}/residents/{residentDoc} {
allow write: if resource.data.cellNumber == request.auth.token.phone_number;
allow read: if request.auth.token.phone_number == resource.data.cellNumber;
//allow read; //temp permission till support fix
}
match /Units/{unitNumber} {
allow read: if request.auth != null;
function residentDoc(residentId) {
return get(/databases/$(database)/documents/Units/$(unitNumber)/residents/$(residentId))
}
match /pets/{petId} {
allow write: if residentDoc(request.resource.data.residentId).data.cellNumber == request.auth.token.phone_number;
allow read: if request.auth != null;
}
}
}
}
And this is the firestore data structure at the moment:
I have tried to change my query to have the array-contains in the where clause, but that doesn't change much.
Note: the allow read without the if check allows the data to be retrieved, so the query does work, just the rules to secure it are not`
The problem is in this condition in your rules:
request.auth.token.phone_number in resource.data.cellNumber
The in operation in Firestore security rules is only defined for maps and lists/arrays, but your cellNumber field is a simple string value, which does not define an in operation as you can see here.
If you want to check whether the phone number in the token is the same as the value of the field, use == instead of in. If you want to test whether it is in the field, consider using the matches method on the string.
Also see:
Firebase firestore security rules allow if document ID contains string
Using contains() with firebase rules
The issue was another query trying to get all resident data after the initial one was fired, which caused it to fail the rule because the second one wasn't querying by cellNumber anymore. I have changed the rules to validate by UID since that will always be provided
I have added some security rules to my project and tested them in rules playground everything seems to be working perfect but when I try to retrieve the same doc using same UID from my website it throws error: "FirebaseError: Missing or insufficient permissions".
Refrence to collection:
dbRef = db.collection("organization").doc(organization).collection(course).doc(courseId).collection("meetings");
This are the snapshot of my code:
Note: I have already tested the security rules in rules playground with different uids and paths. And it worked perfectly.
dbRef = db.collection("organization").doc(organization).collection(course).doc(courseId).collection("meetings");
This query attempts to fetch all documents under meeting collection.
There is a possibility that the above query will fetch documents where designation != 'Teacher' && courseId != course;
Therefore it will fail.
From firestore rules docs
if you have this rule:
match /stories/{storyid} {
// Only the authenticated user who authored the document can read or write
allow read, write: if request.auth != null && request.auth.uid == resource.data.author;
}
and this request db.collection("stories").get().
The query fails even if the current user actually is the author of every story document. The reason for this behavior is that when Cloud Firestore applies your security rules, it evaluates the query against its potential result set, not against the actual properties of documents in your database. If a query could potentially include documents that violate your security rules, the query will fail.
the following query succeeds, because it includes the same constraint on the author field as the security rules:
var user = firebase.auth().currentUser;
db.collection("stories").where("author", "==", user.uid).get()
NB: playground can only test for document gets (not list collection).
Possible solution.
You can write your query in such a way that it can never return the wrong document.
Something like this. When a student is enrolled to take a meeting (or course), add his uid to that meeting's document.
doc = {student_ids = [uidofstudent1, uidOfStudent2, ...]}.
Then you can query like this:
db
.collection("organization")
.doc(organization)
.collection(course)
.doc(courseId)
.collection("meetings")
.where('student_ids', arrayContains: studentUid);
Your firestore rules can be something like this:
match /organisation/{org}/{course}/{courseId}/meetings/{meet=**} {
allow read: if request.auth.uid in resource.data.student_ids ||
isTeacher(request.auth.uid);
}