Search code examples
google-cloud-firestorefirebase-security

Implementing an increment(+1) filed security using security rules


I want to be able to protect my increment logic from being abused from the front end my current frond end code

 // Initial Payload
const surfacePayload: SurfacePayload = {
        gender: selected.gender,
        unit: unit.current,
         // will increment the count in db by +1
        count: increment(+1),
        src: currentUser?.uid!,
     };
await setDoc(doc(db, docRef, surfacePayload);

my security rules logic is like the following :

// requestData.count types 
request.resource.data.count is number && // if the incoming count is a number
request.resource.data.count <= 12 && // this field cannot exceed 12 

my big concern however is the this counter is set as a protector for creating docs in a related sub-collection, and it is really ease to keep sending 0 or 1 there is no real check whether the incoming data are only (increment +1)added to the current state of the count in doc... is there any other check that I can implement to make it rock solid, I tried to check again the current state using only (resource.data) but since this check is a part of a bigger check and it is chained so it has failed..


Solution

  • For the case where your document might not exists at first place, you can write separate rules for create and update as shown below:

    allow create: if request.resource.data.count == 1; // default value 1
    allow update: if request.resource.data.count == resource.data.count + 1;