Search code examples
google-cloud-firestoregoogle-cloud-functionsfirebase-security

Safest approach: onChange vs https cloud functions


I am wondering, I have to allow a user to change only certain parts of a document and I came up with two different solutions:

  • A: Locking the document with firestore rules and modify parts I am interested in using a https function (checking that the request is coming from document owner)
  • B: allowing only the owner of the document to make changes (with firestore rules) and trigger a onChange cloud function to check if he/she changed only the things that they are allowed. If not reject the changes

I would like if there is any safer approach or both are valid in the same way. How easy is to trick a https function?


Solution

  • In many cases both approaches are valid and will depend on preference.

    People coming from a more traditional client/server environment will generally prefer a Cloud Function. This also allows you to do certain things which are not possible in a rule, for example you can perform any action with full server credentials.

    Rules are perhaps more idiomatic for Firebase, and may be cheaper and faster. That said, it is very important to craft any rules very carefully. You may refer to the documentation, which might be relevant in this case.

    The suggestion here is to use rules to prevent unwanted changes, rather than allow the owner to make any changes and then undo them in the trigger. If you want to implement logic which can't be done in rules, you might consider allowing the owner to write the changes to some kind of staging area, either separate fields in the same document, or a new pending document, then performing the checks and moving the data to its proper location in their trigger.