All of the firestore security documents seem to have an assumption that users are malicious enough to hack their own apps and start using that exploited app to take advantage of weak database rules.
Therefore, if my app allows a user to edit certain fields of their profile document, how can I use the rules to lockdown the other fields that only the application should be able to edit?
Or have I misunderstood why firestore rules are necessary, if so, could you please explain? Thank you
CodePudding user response:
How can I use the rules to lockdown the other fields that only the application should be able to edit?
You question can actually apply to any Firestore document for which you want an end-user to be able to modify only a subset of the document's fields.
There is a specific section in the documentation, which is titled "Preventing some fields from being changed" and which indicates that:
By using the
hasAny()
method on the set generated byaffectedKeys()
and then negating the result, you can reject any client request that attempts to change fields that you don't want changed.
and which shows the following example:
service cloud.firestore {
match /databases/{database}/documents {
match /restaurant/{restId} {
// Allow the client to update a document only if that document doesn't
// change the average_score or rating_count fields
allow update: if (!request.resource.data.diff(resource.data).affectedKeys()
.hasAny(['average_score', 'rating_count']));
}
}
}
which allows users "to update information about a restaurant but not change their average score or number of reviews."
CodePudding user response:
[Editing following the comment below] If you look at the documentation: https://firebase.google.com/docs/firestore/security/rules-fields#preventing_some_fields_from_being_changed
they specify the following:
By using the hasAny() method on the set generated by affectedKeys() > and then negating the result, you can reject any client request that attempts to change fields that you don't want changed.
For instance, you might want to allow clients to update information about a restaurant but not change their average score or number of reviews.
service cloud.firestore {
match /databases/{database}/documents {
match /restaurant/{restId} {
// Allow the client to update a document only if that document doesn't
// change the average_score or rating_count fields
allow update: if (!request.resource.data.diff(resource.data).affectedKeys()
.hasAny(['average_score', 'rating_count']));
}
}
}
reverse logic is in: https://firebase.google.com/docs/firestore/security/rules-fields#allowing_only_certain_fields_to_be_changed