Search code examples
node.jsgoogle-cloud-firestoregoogle-cloud-functionsfirebase-admin

Firebase Functions how to access Firestore without admin privileges


I want to implement a callable Firebase cloud function to modify an existing document on Firestore. When I search online, I found that I need to add admin privileges to my server then call it like:

const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

But in documentation(https://firebase.google.com/docs/admin/setup) it says admin SDK gives privileges to manipulate basically everything in Firebase platform. I do not want to give all privileges to a function call, or to a server. If I call a function related to User collection, I want that function to be able to manipulate User collection only.

My questions are: Is it safe to give all privileges to a function? Can reverse engineering be dangerous? If so, how do I block non-legit function calls? Is it possible to restrict access of a firebase function?


Solution

  • Cloud functions cannot be reverse engineered. They run in a secure environment. Admin SDK does bypass all security rules but its your responsibility to authorize incoming requests. If you use onCall functions, Firebase will add caller's auth information such as UID and custom claims in the context object.

    That being said, you just need to run so simple if-else logic to reject malicious requests. For example the caller is A but is requesting data of B, you can deny the request.

    Do note that, if you are using onRequest functions then you'll you'll to pass ID token, verify it on cloud functions yourself I.e. there won't be context.auth object by default.

    Additionally you can use Firebase App Check to make sure the request is triggered from your applications only.