Search code examples
androidfirebase-realtime-databasefirebase-security

firebase how can i restrict a write permission using validate to go though only a particular value only that is defined in the rules


i have a folder in the database user/user1 i want to write a name and phone to it i am testing this with in rules playground

location = /user/user1

Data (JSON)

{
  "name": "value",
  "phone": "value"
}

rules

"user":{      
  "$uid":{  
    ".read": true,
    ".write": true,
    ".validate" : "newData.child('name').exists() && newData.child('phone').exists() "         
  }  
}

This is working as i expected. If i put only the name, it will get denied. So that's good, and now i want also get denied if there is a 3rd value:

{
  "name": "value",
  "phone": "value",
  "data": "value"
}

Here is a security problem. If anyone adds a random value to this location, then i will get a large bill from firebase. I am afraid of this, or i am just getting paranoid?


Solution

  • It sounds like you want to disallow, which you can do by naming the allowed properties and then rejecting anything else with a so-called wildcard catch-all variable:

    "user":{      
      "$uid":{  
        ".read": true,
        ".write": true,
        ".validate": "newData.hasChildren(['name', 'phone'])", // 👈 you must always have these
        "name": {
          ".validate": true // 👈 you probably should validate the format here
        },
        "phone": {
          ".validate": true // 👈 and you should validate the format here too
        },
        "$others": {
          ".validate": false // 👈 other values are rejected
        }
      }  
    }
    

    Also see my answer to Firebase realtime database rules to edit only existing fields, which covers a similar care