firebasegoogle-cloud-firestorefirebase-security

Cost of Firebase Firestore rules if many requests


What is the cost of the Firestore security rules below if there are many requests? I'm particularly concerned about unwanted requests due to a malicious attack. There is no rule that reads a document directly into Firestore.

firestore.rules:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    function isUserAuthenticated() {
      return request.auth != null;
    }

    function isUserDocumentOwner() {
      return (
        isUserAuthenticated() &&
        (
          request.auth.uid == resource.data.userId ||
          request.auth.uid == request.resource.data.userId ||
          request.auth.uid == resource.id ||
          request.auth.uid == request.resource.id
        )
      );
    }

    function isEnterpriseEmployee() {
      return (
        isUserAuthenticated() &&
        (
          resource.data.enterpriseId == request.auth.token.enterpriseId ||
          request.resource.data.enterpriseId == request.auth.token.enterpriseId ||
          resource.id == request.auth.token.enterpriseId ||
          request.resource.id == request.auth.token.enterpriseId
        )
      );
    }

    function isEnterpriseAdmin() {
      return (
        isUserAuthenticated() &&
        request.auth.token.teamIds is list &&
        string(request.auth.token.adminTeamId) in request.auth.token.teamIds
      );
    }

    function isAdminTeamDocument (teamId) {
      return teamId == request.auth.token.adminTeamId;
    }

    match /users/{userId} {
      allow get, update: if isUserDocumentOwner() || isEnterpriseAdmin();
      allow list, create: if isEnterpriseAdmin();
      allow delete: if false; // Firebase Admin SDK only
    }

    match /teams/{teamId} {
      allow get: if isEnterpriseEmployee();
      allow list, create, update: if isEnterpriseAdmin();
      allow delete: if isEnterpriseAdmin() && !isAdminTeamDocument(teamId); // Do not delete the admin team document
    }

    match /enterprises/{enterpriseId} {
      allow get: if isEnterpriseEmployee();
      allow update: if isEnterpriseAdmin();
      allow list, create, delete: if false; // Firebase Admin SDK only
    }

    // Firebase Admin SDK only
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

Solution

  • There are no costs to security rules that don't read or refer to data from Firestore. You can review the documented costs for security rules in the documentation.

    Your rules do refer to documents when using resource to access fields, so you will be charged for documents read when for queries that evaluate rules that use resource. For example, this will incur the cost of a document read:

    resource.data.enterpriseId == request.auth.token.enterpriseId
    

    See also: Firestore security rule: cost of using request.resource.data.__field__ != resource.data.__field__?