Firestore Rules not working as expected throwing errors when it shouldn’t

I’m implementing Firebase (firestore) into my nextjs adhd inventory app.
I wanted to secure my database with security rules but I’m having a tough time getting them to work.

It is working in the rule simulation on the firebase dashboard, also working when I try to get a specific document by id, but it’s giving me a general firebase error when trying to fetch with a filter. (VM21513 useFetchThing.ts:29 FirebaseError: Missing or insufficient permissions.)

Note that I have two main collections :

  1. things (contains the things people added)
  2. collections (contains the collections that each user has)
    — it has a sub collection ‘collaborators’ that holds document of allowed collaborators

In my React code, I am fetching the last thing a user created (pending = true, creator_uid=user uid), and I limit it to one document. I implemented security rules to prevent a user to access a thing if he is not the owner or a collaborator of in the associated collection. Thus I have to fetch the said collection for every element.

const thingQuery = query(
    collection(db, 'things').withConverter(thingConverter),
    where('creator_uid', '==', user?.uid),
    where('pending', '==', true),
    orderBy('creation_date', 'desc'),
    limit(1)
  );

  const [things, loading, error] = useCollectionData(thingQuery);

Here are the rules I’m using:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    
    function isSignedIn() {
      return request.auth != null;
    }
    
    // return true if the request.auth.uid is in /collections/{collectionID}/collaborators/{collaboratorID}
    function isCollaborator(collectionID) {
      return exists(/databases/$(database)/documents/collections/$(collectionID)/collaborators/$(request.auth.uid));
    }

    function isEditor(collectionID) {
      return get(/databases/$(database)/documents/collections/$(collectionID)/collaborators/$(request.auth.uid)).data.role == 'editor';
    }
      
    function isOwner(collectionID) {
      return get(/databases/$(database)/documents/collections/$(collectionID)).data.owner_uid == request.auth.uid;
    }

    // Rules for Thing documents
    match /things/{thingID} {
        allow read: if isSignedIn()
                            && (isOwner(resource.data.collection_id) || isCollaborator(resource.data.collection_id));
      allow create: if isSignedIn() 
                                && (isOwner(resource.data.collection_id) || isEditor(resource.data.collection_id))
                                && validateThingData(request.resource.data);
      allow update: if isSignedIn() 
                                && (isOwner(resource.data.collection_id) || isEditor(resource.data.collection_id))
                                && validateThingEdits(request.resource.data);
      allow delete: if isSignedIn() && (isOwner(resource.data.collection_id) || isEditor(resource.data.collection_id));

      function validateThingData(data) {
        return data.keys().hasAll(['creator_uid', 'creation_date', 'collection_uid', 'pending'])
          && (data.creator_uid is string && data.creator_uid == request.auth.uid)
          && data.creation_date is timestamp
          && data.collection_id is string
          && data.pending is bool
          && (data.pending == true || data.pending == false)
          && (data.name is string && data.name.size() <= 32 || !('name' in data))
          // && (data.pictures is list || !('pictures' in data))
          && (data.quantity is int || !('quantity' in data))
          && (data.origin is string && data.origin.size() <= 32 || !('origin' in data))
          && (data.date is timestamp || !('date' in data))
          && (data.price is float || !('price' in data))
          && (data.notes is string && data.notes.size() <= 140 || !('notes' in data))
          && (data.filtering_tag is string && data.filtering_tag.size() <= 10 || !('filtering_tag' in data));
      }
      
      function validateThingEdits(data) {
        return (!data.keys().hasAny(['creator_uid', 'creation_date']))
                        && data.collection_id is string
                && data.pending is bool
                && data.name is string && data.name.size() <= 32
                // && (data.pictures is list || !('pictures' in data))
                && data.quantity is int
                && data.origin is string && data.origin.size() <= 32
                && data.date is timestamp
                && data.price is float
                && data.notes is string && data.notes.size() <= 140
                && data.filtering_tag is string && data.filtering_tag.size() <= 10;
      }
    }

    // Rules for Collection documents
    match /collections/{collectionID} {
        allow read: if isSignedIn() 
                            && (isCollectionOwner(resource.data) || isCollaborator(collectionID));
      allow create: if isSignedIn() && validateCollectionData(request.resource.data);
      allow update: if isSignedIn() 
                                && isCollectionOwner(resource.data)
                                && validateCollectionEdits(request.resource.data);
      allow delete: if isSignedIn() 
                                && isCollectionOwner(resource.data);

      function validateCollectionData(data) {
        return data.keys().hasAll(['name', 'creation_date', 'owner_uid'])
                && data.name is string && data.name.size() <= 32
                && data.creation_date is timestamp
                && (data.owner_uid is string && data.owner_uid == request.auth.uid);
      }
      
        function validateCollectionEdits(data) {
        return (!data.keys().hasAny(['owner_uid', 'creation_date']))
                && data.name is string && data.name.size() <= 32;
      }
      
      function isCollectionOwner(data) {
        return data.owner_uid == request.auth.uid;
      }
      
      match /collaborators/{collaboratorID} {
        allow read: if isSignedIn()
                    && (isOwner(collectionID) || isCollaborator(collectionID));
        allow create: if isSignedIn() 
                      && isOwner(collectionID)
                      && validateCollaboratorData(request.resource.data);
        allow update: if isSignedIn()
                      && isOwner(collectionID)
                      && validateCollaboratorData(request.resource.data);
        allow delete: if isSignedIn()
                      && isOwner(collectionID);

        function validateCollaboratorData(data) {
          return data.keys().hasAll(['uid', 'role'])
            && data.uid is string
            && data.role is string && (data.role == 'editor' || data.role == 'viewer');
        }
      }
    }
  }
}

Those are two separate collections at the same level because I want to be able to rapidly switch the collection_id in a thing to move it to another collection.

I tried many approaches for solving this problem, still getting the same VM21513 useFetchThing.ts:29 FirebaseError: Missing or insufficient permissions. error.

  1. Tried to access a specific file in the simulator in firebase panel, it works there
  2. Tried to fetch a specific document with the id in my next project, it also works

I know that there are limits concerning the number of external document fetching I can do in the rules. firebase docs firestore limits

I also know that security rules are not handled in the same way if I query one specific document, or a query of one or more based on filters. bouncer reference as seen in this video from firebase

I asked some help from the embedded Google Gemini LLM and from Mistral AI chat, with no success.

That is why I’m coming to you, asking some help from kind experts who know more than me.
Thanks for your help.

William

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật