Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestoregoogle-cloud-functionsfirebase-security

Firestore Rules Not Working At All with Functions


service cloud.firestore {
  match /databases/{database}/documents {
    match /pool/{poolId} {
      allow read: if request.auth != null;
      allow write: if request.auth != null && get(/databases/$(database)/documents/user/$(request.auth.uid)).data.admin == true;
    }
  }
}

I wrote the previous rules by following https://firebase.google.com/docs/firestore/security/rules-conditions#access_other_documents. I expected that, for a user to add a new document into the collection pool, a document of the ID request.auth.uid should exist in the collection user and have an entry admin: true .

But every request from Functions

    pool.post('/add', async (req, res) => {
        const added = await db.collection('pool').add({
            ...
        }); 
    });

is allowed to add a new document to the collection pool.

Even the following rules

service cloud.firestore {
  match /databases/{database}/documents {
    match /pool/{poolId} {
      allow read, write: if false;
    }
  }
}

do not disallow any requests from Functions...

What's the problem of the rules? Or, is there something in Functions which makes the rules not working? Or, in my project configuration...?


Solution

  • Cloud Functions for Firebase use the Node.js Admin SDK which totally bypasses the security rules since it is considered as a "privileged environment".

    You'll find a note on this aspect in the Firestore doc:

    Note: The server client libraries bypass all Cloud Firestore Security Rules


    If you want to restrict your HTTPS Cloud Function to only the Firebase users of your app (and identify which user is calling it through the decoded ID token) you can follow the following Firebase official Cloud Function sample: Authorized HTTPS Endpoint.