firebasegoogle-cloud-firestorefirebase-security

Firestore database rule always returns "missing or insufficient permissions" when accessing document fields


Rephrased entire question on your suggestion.

I have this setup in my firestore database:

enter image description here

I'd like to query the "incidents" collection and get back all documents that have my ID in the "members" array which is part of each document in the "incidents" collection.

I checked in the "Authentication" that this is in fact my ID.

I've set my rules like so:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /incidents/{document=**} {
            allow read, write: if
          request.auth.uid in resource.data.members
    }
  }
}

This is my client-side:

    import { collection } from 'firebase/firestore';
    const incidentsCollection = collection(db, 'incidents');

    onSnapshot(incidentsCollection, (querySnapshot) => {
      const fetchedIncidents = [];
      querySnapshot.forEach((doc) => {
        fetchedIncidents.push({
          id: doc.id,
          ...doc.data(),
        });
      });

With all of the above I get "permission_denied". What am I doing wrong?


Solution

  • Your query is demanding all of the documents in the "incidents" collection, however your rule requires that the client may only request documents where the "members" array field contains a specific string. So the rule is rejecting the query because it's requesting data disallowed by the rule.

    Firestore security rules are not filters (you should read and understand this documentation). Your query on the client should contain a filter that requests only the documents allowed by the rule, which means you should have an "array-contains" filter on the "members" field.