Home > Enterprise >  How to read a document in Firebase security rules?
How to read a document in Firebase security rules?

Time:12-30

I'm trying to run a test on the simulator for some firebase security rules, but when running it, the resource is always shown as null and the test is never run for the allow write on the bottom level. Here's my code for the security rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
  
    match /{document=**} {
      allow read, write: if isSignedIn(); // only if user is signed in are they allow to do any operation
      
      match /{spaceId} { // Any space: not reading or writing allowed to those docs
            allow read, write: if false;
        }
        match /{spaceId}/posts/{postId} { // any post
            allow read; 
        allow write: if resource.user.uid == request.auth.uid;
        }
    }

In this picture the innermost match isn't being checked against.

enter image description here

CodePudding user response:

The match /{document=**} says that you're defining rules for this collection and all documents under it. So the top-level allow rule that checks isSignedIn, is also applied to all subcollections. And since rules are ORed together, that means any signed in user can also read/write the spaceid documents.

To make the match only apply to its own collection, remove the =** from it.

CodePudding user response:

Frank have right you have vulnerability in rules. Rules are work like in css code i'm pretty sure. First restrict access to all data then allow to do any thing any one.

In example below users are only allowed to do some thing in users and app collection.

match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
    match /users/{userId} {
        allow create: if (isLoggedIn() && !userExist()) || isAdmin());
        allow read, update: if isOwner(userId) || isAdmin());
    }
    match /app/{data} {
        allow write: if isEditor();
        allow read: if true;
    }
}

And solution for your question is resource.data.user.uid you miss data after resource. And remember there will be no resource if you create a document write operation is create and update. Update will work but no create.

  • Related