Search code examples
firebasegoogle-cloud-firestorefirebase-security

If I set up my security rules like this, can a user modify a document that isn't part of their collection but shares their user ID?


My Firestore structure is going to look like this:

users
{userDocID}
friendsCollection                    notificationsCollection
{friendDocID = userDocID}            {notifDocID}

I'm going to use the rule below to only allow users to modify stuff where the parent {userDocID} is their own. But I just want to confirm something to quell my paranoia - if I also use each user's {userDocID} as the doc ID of the friend record, that won't allow those friends to modify their own document inside another friend's friendCollection, right?

match /users/{usersDocID=**} {
  allow read, write, delete: if true; 
}

Example:

users
{userA}
friendsCollection
{userB}

userB won't be able to modify the document inside of userA's friendCollection even though it has his own user ID as the doc ID, right?


Solution

  • As you are using recursive wildcards, the wildcard variable will contain the entire matching path segment, even if the document is located in a deeply nested subcollection. Hence it allows userB to modify the document inside of userA's friendCollection.

    Note, however, that the behavior of recursive wildcards depends on the rules version.

    To avoid this, just use the wildcard syntax as below:

    match /users/{Id} {
      allow read, write, delete: if true; 
    }
    

    or use Hierarchical rules (if you want to explicitly give access to subcollection).

    If you want to see if your rules function as expected, you should build code to see if that happens in practice. That is the greatest method you can ensure that your rules work the way you anticipate. For that, a test library and emulator are available. To discover more about how it functions, kindly see the rules emulator documentation.

    Also, you may verify whether your rules behave as you anticipate using the Firestore console.