Dynamic auth.token based on resource.data - firebase

I'm trying to write a rule allowing an user to access only the documents he has access to:
match /websites/{website} {
function isSignedIn() {
return request.auth.uid != null;
}
function isAuthorized(rsc) {
return request.auth.token[rsc.data.role] == true
}
function isAdmin() {
return request.auth.token.admin == true
}
allow read, write: if isSignedIn() && (isAuthorized(resource) || isAdmin());
}
Seems like there is a issue with request.auth.token[rsc.data.role] but I can't figure out what's the problem. rsc.data.role is set as a string in the database, and my user as a token as a boolean.
Example: website.role: 'editor' and request.auth.token.editor: true.
Here's a screenshot of the document I'm trying to access:
Any idea?

Related

How do I access the document ID in firestore rules

I am seemingly unable to access the resource.id value when trying queries using these rules. when I manually enter the schools id (the commented out line) the data returns fine. I only have 1 school and the doc ID definitely matches the string. but when I ask to match to the resource.id value, my rules return an 'insufficient permissions' error.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
//functions
function signedIn() {
return request.auth.uid != null;
}
function returnUID(){
return request.auth.uid;
}
function getUserData() {
return get(/databases/$(database)/documents/All%20Users/$(request.auth.uid)).data;
}
match /All%20Users/{userID} {
allow read,write: if
signedIn() && returnUID() == userID;
}
match /All%20Schools/{schoolID}{
allow read, write: if
// signedIn() && getUserData().school == "f7asMxUvTs3uFhE08AJr"
signedIn() && getUserData().school == resource.id
}
}
}
my structure is like this
All Schools / school (document) / Classrooms (subcollection)
All Users / User (document) (each user doc has a classroomID associated to it)
as a point of reference this is a query that is successful
var docRef = db.collection("All Users").doc(uid).get()
and the one that is failing
db.collection("All Schools/" + properties.schoolid + "/Classrooms").onSnapshot()
[update]
the working set of rules!
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
//functions
function signedIn() {
return request.auth.uid != null;
}
function returnUID(){
return request.auth.uid;
}
function getUserData() {
return get(/databases/$(database)/documents/All%20Users/$(request.auth.uid)).data;
}
match /All%20Users/{userID} {
allow read,write: if
signedIn() && returnUID() == userID;
}
match /All%20Schools/{schoolID}{
allow read, write: if schoolID == 'f7asMxUvTs3uFhE08AJr'
}
match /All%20Schools/{schoolID}/Classrooms/{classId} {
allow read, write: if getUserData().school == schoolID;
}
match /All%20Schools/{schoolID}/Student%20List/{student} {
allow read, write: if getUserData().school == schoolID;
}
match /All%20Schools/{schoolID}/Staff/{staff} {
allow read, write: if getUserData().school == schoolID;
}
}
}
The following rules will be effective on documents of 'All Schools' collection only and not documents of 'Classrooms' sub-collection:
match /All%20Schools/{schoolID} {
// ...
}
That's why db.collection("All Users").doc(uid).get() works and fetching 'Classrooms' collection fail since you do not have any rules specified for it. Although you had a recursive wildcard earlier (before editing the question), resource object contains data of those documents being matched in 'Classrooms' sub-collection and hence getUserData().school == resource.id failed too.
That being said, try specifying rules for 'Classrooms' sub-collection as well:
match /All%20Schools/{schoolID}/Classrooms/{classId} {
allow read, write: if getUserData().school == schoolID;
}
match /All%20Schools/{schoolID}/Classrooms/{classID} {
// schoolID is the documentId
allow read, write: if signedIn() && getUserData().school == schoolID
}
If this was my code, I would not use spaces in my collection or field names. Rather I will use snake_case or camelCase.
So instead of All Schools, I will use either all_schools or allSchools.

Firestore: Prevent write/overwrite/update field once it is added

I have a collection in which I am storing user requests in documents having documents ID as user's email. In the document, I am creating fields the key for which is being generated at client side.
Now, the problem that I am facing is that user can overwrite the existing field/request in the document if the key matches which I don't want to happen.
What I tried was to use this rule which unfortunately does not work
resource.data.keys().hasAny(request.resource.data.key();
So how can I achieve this?
Below are the screen shot of the firestore data and the current security rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /roles/{userId}{
allow read: if isSignedIn() && hasId(userId);
}
match /requests/{email} {
allow read, update: if isSignedIn() && hasMail(email)
}
//functions//
function hasMail (email) {
return request.auth.token.email == email;
}
function hasId (userId) {
return request.auth.uid == userId;
}
function isSignedIn () {
return request.auth != null;
}
function getUserRole () {
return get(/databases/$(database)/documents/roles/$(request.auth.uid)).data.role
}
}
}
You can check if a resource already exists. Here an example:
allow write: if resource == null // Can create, not update
Use that to restrict any edit or update of the data. If you have additional rules you can granulate them to update, delete and create.

Firestore security rule: Null value error when using Set.hasAny()

I have a user collection with two fields memberOf and managerOf (that is, of an organisation; both are arrays of doc id).
I would like to restrict a manager to list only users that are members of an organisation they managed.
In JS, it would be something like this:
const memberOf = [1, 2, 3, 4, 5]
const managerOf = [6, 7, 1, 9, 0]
console.log(memberOf.some(el => managerOf.includes(el))) // 👈 returns true
This is what I have so far:
function isSignedIn() {
return request.auth.uid != null
}
function isAdmin() {
return isSignedIn() && 'admin' in request.auth.token && request.auth.token.admin
}
match /users/{userId} {
allow get: if isSignedIn() && (request.auth.uid == userId || isAdmin());
allow list: if isAdmin() || ???; // 👈 how can I express the above condition?
allow write: if isAdmin();
}
And that's the query:
const unsubscribe = db.collection('users')
.where('memberOf', 'array-contains', organisationId)
.orderBy('email', 'asc')
.onSnapshot(snap => {
console.log(`Received query snapshot of size ${snap.size}`)
var docs = []
snap.forEach(doc => docs.push({ ...doc.data(), id: doc.id }))
actions.setMembers(docs)
}, error => console.error(error))
First, I wanted to use the organisationId from the request in the security rule, but it's not available as it's not a write operation (https://firebase.google.com/docs/reference/rules/rules.firestore.Request#resource)
I thought about:
function hasMemberManagerRelationship(userId) {
return isSignedIn() && get(/databases/$(database)/documents/users/$(userId)).data.memberOf in get(/databases/$(database)/documents/users/$(request.auth.uid)).data.managerOf
}
match /users/{userId} {
allow get: if isSignedIn() && (request.auth.uid == userId || isAdmin());
allow list: if isAdmin() || hasMemberManagerRelationship(userId);
allow write: if isAdmin();
}
or
function hasMemberManagerRelationship(userId) {
return isSignedIn() && get(/databases/$(database)/documents/users/$(userId)).data.memberOf.toSet().hasAny(get(/databases/$(database)/documents/users/$(request.auth.uid)).data.managerOf.toSet())
}
(https://firebase.google.com/docs/reference/rules/rules.Set#hasAny)
But it's not working and I have the error FirebaseError: Null value error. for 'list' # L27. AND on top of that, that could generate a lot of extra read operations (not billing-wise optimised).
I could do something like the following:
allow list: if isAdmin() || (isManagerOf('jJXLKq7p9wWSNLsHcVIn') && 'jJXLKq7p9wWSNLsHcVIn' in resource.data.memberOf);
where jJXLKq7p9wWSNLsHcVIn is the id of an organisation (and used in the query), but I don't know how I can retrieve the id from the request "context"..
Any help would be appreciated!
Ok. First, thank you #Doug Stevenson for mentioning debug() in another post! I didn't know it exists, and it rocks!
The result of debug(resource.data.memberOf) in the debug log was:
constraint_value {
simple_constraints {
comparator: LIST_CONTAINS
value {
string_value: "jJXLKq7p9wWSNLsHcVIn"
}
}
}
LIST_CONTAINS forced me to have a look at List: https://firebase.google.com/docs/reference/rules/rules.List#hasAny
toSet() does not apply to a list, but a list has already the hasAny() function.
(in fact, it does exist but it didn't work in my case 🤔)
In the end, this rule works:
function hasMemberManagerRelationship() {
return isSignedIn() && resource.data.memberOf.hasAny(getUser(request.auth.uid).data.managerOf)
}
Now I'm just wondering if getUser(request.auth.uid).data.managerOf is somehow cached (1 read for multiple user entries) or re-run every time (100 users, 100 extra reads).
Any thoughts on that?
I sincerely hope this is the first case ^^
I tested rules which are pretty similar to your attempt using the firestore "Rules Playground" and it seems to be working.
You do not need to get() the current userId because you already have it in the resource object.
I am not sure it would generate a lot more read operations because we are only using get() for request.auth.uid.
function getUser(userId) {
return get(/databases/$(database)/documents/users/$(userId));
}
function isSignedIn() {
return request.auth.uid != null;
}
function isAdmin() {
return isSignedIn() && 'admin' in request.auth.token && request.auth.token.admin;
}
function hasMemberManagerRelationship() {
return isSignedIn() && resource.data.memberOf.toSet().hasAny(getUser(request.auth.uid).data.managerOf.toSet());
}
match /users/{userId} {
allow read: if isAdmin() || hasMemberManagerRelationship();
}
Where exactly are you getting the FirebaseError: Null value error?

Firebase Security Rules - using get in a function

I am trying to setup security rules for my firestore instance, I have three basic requirements:
User must be authenticated to read
Owners of documents are the only
ones who can write to them (use a field called owner on document to
verify)
Any admin user can also write to any document
The code below achieves all of this (excluded the check for ownership) but the get function to determine the users role only works when specified on the same row as the if condition. In the code below the update and delete works for the admin but not the create.
Can anyone please tell why the isAdmin() function does not evaluate to the same result?
service cloud.firestore {
match /databases/{database}/documents {
// Only 'owners' of data can make changes to data
match /posts/{post} {
allow read: if isAuthenticated();
allow create: if isAuthenticated() && isAdmin();
allow update, delete: if isAuthenticated() && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 1;
}
}
/// FUNCTIONS ///
function isAuthenticated() {
return request.auth.uid != null;
}
// function requestIsOwner() {
// return request.resource.data.owner == request.auth.uid;
// }
// function resourceIsOwner() {
// return resource.data.owner == request.auth.uid;
// }
function isAdmin() {
return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 1
}
}
You need to pass the database variable as argument in your function like this:
service cloud.firestore {
match /databases/{database}/documents {
// Only 'owners' of data can make changes to data
match /posts/{post} {
allow read: if isAuthenticated();
allow create: if isAuthenticated() && isAdmin(database);
allow update, delete: if isAuthenticated() && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 1;
}
}
/// FUNCTIONS ///
function isAuthenticated() {
return request.auth.uid != null;
}
// function requestIsOwner() {
// return request.resource.data.owner == request.auth.uid;
// }
// function resourceIsOwner() {
// return resource.data.owner == request.auth.uid;
// }
function isAdmin(database) {
return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 1
}
}

Firestore rules objects

I am trying to setup some basic Firestore security rules in my database. I am having some trouble finding the relevant documentation to learn how to do this.
Currently my document is structured like this:
project(document): {
createdBy(string): chris#emailaddress.com,
users(object): {
{ graham#emailaddress.com(object): access: write },
{ paul#emailaddress.com(object): access: read }
}
}
I'd like to setup my rules so that:
Users must be signed in to read, write or delete anything
If a user is added to a project with 'read' access they can only read the document.
If a user is setup with write access they can update and read the document but not update the createdBy field.
If a user has created the document they can read, update and delete the document.
My security rules are setup like this:
service cloud.firestore {
match /databases/{database}/documents {
match /projects/{projectId} {
allow read: if existingData().users[getUser()token.email].access != null && isSignedInAndVerified()
allow read, update: if existingData().users[getUser()token.email].access != "write" && isSignedInAndVerified()
allow update, delete: if sameAsEmail(existingData().createdBy) && isSignedInAndVerified()
}
//my functions
function getUser(){
return request.auth
}
function existingData(){
return resource.data
}
function sameAsEmail(resource){
return resource == request.auth.token.email
}
function isSignedInAndVerified() {
return request.auth != null && request.auth.token.email_verified;
}
}
}
Incorrect use of syntax use: getUser().token.email instead.

Resources