I'm working on a project using firebase where each user will have one book. Each book has inside many chapters. I want each user to be able to share any chapter with any amount of other users. My current hierarchy is /books/{id}/chapter/{id}
My question is if I give access to another user to /books/{id}/chapter/{id} will he also have access to books/{id}?
So I need to write a firebase rule that gives access to the child but prevents access to the parent. Is this the behaviour by default or do I need to do anything else?
CodePudding user response:
No. You must set your security rules to allow users to read sub-collections only as shown below:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /books/{bookId} {
allow read: if false; // Rules for who can read books
match /chapters/{chapterId} {
allow read: if true; // Rules for who can read chapters
}
}
}
}
The allow read: if true; is applied only for the chapters sub-collection here.
CodePudding user response:
TL;DR: No.
Access permission is only inherited by subcollections when you use a recursive wildcard rule and can't be "inherited" upwards. Of you want to grant a user access to the parent book, you will have to grant them permission on that collection.
CodePudding user response:
My question is if I give access to another user to /books/{id}/chapter/{id} will he also have access to books/{id}?
No, that will not happen.
If there is no rule that explicitly allows access to any document, then no one will have access it. Rules that match nested documents do not match parent documents.
If you want to test if your rules work the way you expect, you should write code to see if that actually happens in practice. That is the best way you can ensure that your rules work the way you expect (and you will not have to take the advice of strangers on the internet). There is a test library and emulator for that. Please read the documentation to learn about how that works.
https://firebase.google.com/docs/firestore/security/test-rules-emulator
You can also use the Firestore console to test if your rules work as you expect.
