DevMike
DevMike

Reputation: 1821

How do i write a Firebase Storage security rule that only allows write file permissions for auth users to a nested directory and none its parents?

I have the following security rule set for a Firebase Storage bucket:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /avatars/{userId}/{profileId}/{allPaths=**} {
        allow write: if request.auth != null && request.auth.uid == userId
    }
  }
}

This works assuming the dynamic subdirectory userId matches the request.auth.uid.

However, this rule also allows that same user to write a file to the subdirectory {userId} and to write additional directories into profileId.

Id like to allow the authenticated user to generate both of the wildcard subdirectories as i have specified, but ONLY allow FILES to be uploaded into the last directory: profileId.

So...

attempting to upload a file into /avatars/${userId}/{profileId}/file.jpg should succeed.

attempting to write a file into /avatars/${userId}/file.jpg should fail.

attempting to create a directory in /avatars/${userId}/{profileId}/directoryName should fail.

attempting to upload a file into /avatars/${userId}/{profileId}/directoryName/file.jpg should fail.

Is this not possible?

Upvotes: 0

Views: 518

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317958

Firstly, it's important to understand that Cloud Storage does not have "directories". There is no operation to create a "directory". There are only objects with paths that can have / separators to make it easier for you to organize content.

The reason why users can write to nested paths under profileId is because you are using a trailing recursive wildcard match {allPaths=**}, which allows writes under any possible path under profileId. I suggest reviewing the documentation on wildcards to better understand the behavior. It sounds like you don't want a recursive wildcard match at all, and instead just a single path segment match, e.g. {imageId}.

Upvotes: 1

Related Questions