Ben Edgar
Ben Edgar

Reputation: 3

Is it possible to restrict firebase firestore access to only service accounts and API keys using cloud firestore rules?

I am using firebase's cloud firestore database and I would like to restrict access to this database to two mobile apps that authenticate via API keys and one service account.

I have reviewed the firebase documentation on implementing custom rules but I do not see any API key or service account examples so I am unsure how to utilize rules for this use case.

From this stackoverflow question and answer it looks like service accounts using the firebase admin API bypass any firestore security rules, is that correct? If so is it reasonable to turn off write access entirely to any firestore collections that I only expect this service account to update?

So far I have tried something like this to allow access from the service account but it was not working as expected. I am not sure if cloud firestore rules support restricting access to only certain API keys.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /sales_reps/{document=**} {
      allow read: if true;
      allow write: if request.auth.token.email == '<first-service-account-email>';
    }
    match /gps_tracking/{document=**} {
      allow read: if true;
      allow write: if request.auth.token.email == '<second-service-account-email>';
    }
    match /{document=\*\*} {
      allow read: if true;
      allow write: if false;
    }
  }
}

Upvotes: 0

Views: 951

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

From this stackoverflow question and answer it looks like service accounts using the firebase admin API bypass any firestore security rules, is that correct?

Yes this is correct

If so is it reasonable to turn off write access entirely to any firestore collections that I only expect this service account to update?

Yes, since no user using a Client SDK (or the REST API) is going to update your collection(s) it is the correct aproach.


So concretely no need to use rules like

allow write: if request.auth.token.email == '<first-service-account-email>';

just do

allow write: if false;

for all the collections for which you only want the service account to have the write access right.

Upvotes: 2

Related Questions