Firebase Realtime Database Security Rules - Tips for Sounding Out Rules

Here are some tips for success when using Firebase Realtime Database Security Rules:

  1. Write your rules as you go when writing your app. It will be much, much easier than needing to write many rules for code that is already written and may not map well to your rules.

  2. Even while you write and test your rules you can always save a copy of your rules offline and go back to locking down your database to allow only yourself while you continue work.

  3. Always, always, ALWAYS copy the database path from the LogCat error and paste it in the Location field when testing using the Simulator. It’s so easy to make a slight typo if you type it in.

  4. When testing the JSON Data that represents your model objects it’s easy to just type “blah” or “123” for data.  Since you’re going fast it’s also easy to forget the junk data you used and later get confused as to why your rules aren’t working in the Simulator. Try always to use representative data that you expect in your app when testing your rules to avoid confusion.

  5. After testing model object data in the Data (JSON) field you should save a copy offline. For less trivial object models the fields and data can take time to put together validly. So saving a copy speeds things up later and facilitates consistency to testing your rules.

  6. If your path contains the user UID then when testing be sure to change the Location path in the Simulator AND the Authenticated Google UID value and be sure they match in order to satisfy rule requirements. It’s easy to forget to change both when testing!

  7. The Simulator will run against the existing data in your database. So if you are testing a set operation on a path with an existing model at that path and your rule does yet provide for update then your rule may fail. You may stare at the rule and think it looks perfect and not understand why its not working. Check your database to see if data already exists at that location!

  8. If your app allows users to enter user-specified data then rules become pretty important. Consider which data is determined by your app and which data is user-specified. You’ll want to extra constrain user-specified data to keep out unwanted content.

  9. When you are ready to write a rule then just sound out and starting writing the rule as you

    1. Who should be able to write the data?

    2. Who should be able to read the data?

    3. Is this data dependent on other data existing in the tree? If yes, create a rule with that dependency.

    4. Is the data going to be specified by a user or predetermined by the app?

    5. For each field ask: what kind of data is a field storing and how should that data be constrained?