Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore Security Rules - How can I check if the FieldValue.increment is valid?

I have a firebase collection of documents "posts", each post document contains four fields: "likes", "dislikes", "super", and "total". I perform batch updates on the each document with following three data objects:

 var data_like_obj =    {
likes: firebase.firestore.FieldValue.increment(1),
total: firebase.firestore.FieldValue.increment(1)
    }


 var data_dislike_obj =   {
dislikes: firebase.firestore.FieldValue.increment(1),
total: firebase.firestore.FieldValue.increment(-1)
    }


 var data_super_obj =   {
super: firebase.firestore.FieldValue.increment(1),
total: firebase.firestore.FieldValue.increment(4)
    }

I couldn't find a security rule that allows me to check if the increment is valid, that is only (+1, -1, or +4) and nothing else. I made the following security function:

function validVote() {
    return ( ( isUpdatingField("super") || isUpdatingField("liked") || isUpdatingField("disliked") ) && isUpdatingField("total") ) &&
  (( isUpdatingField("disliked") && (0 <= (int(incomingData().disliked) - int(existingData().disliked)) && (int(incomingData().disliked) - int(existingData().disliked)) <= 1) ) ||
  ( isUpdatingField("super") && (0 <= (int(incomingData().super) - int(existingData().super)) && (int(incomingData().super) - int(existingData().super)) <= 1) ) ||
  ( isUpdatingField("liked") && (0 <= (int(incomingData().liked) - int(existingData().liked)) && (int(incomingData().liked) - int(existingData().liked)) <= 1) )) &&
  ( incomingData().total == incomingData().super * 4 + incomingData().liked - incomingData().disliked )
  ;
}
// Utility Funcs
function existingData() {
    return resource.data;
}
function incomingData() {
    return request.resource.data;
} 

The function works just fine when I tested it on the simulator, but simulator had no way to submit FieldValue.increment object. How can I go about validating if the increment is legal?

like image 420
Parth Raghav Avatar asked Nov 06 '22 13:11

Parth Raghav


1 Answers

The console simulator is very limited. It's basically just a playground where you can get accustomed to basic rules. For serious development, you should use the rules emulator that's part of the Firebase CLI to validate your rules against actual queries:

https://firebase.google.com/docs/firestore/security/test-rules-emulator

You will be able to issues queries with actual FieldValue.increment tokens and test that the changes are valid.

like image 123
Doug Stevenson Avatar answered Nov 12 '22 12:11

Doug Stevenson