Cloud Storage for Firebase Security Rules - File Size Criteria

In our previous post we locked down reads and writes on the path for our Cloud Storage for Firebase. Its time to think about the data we’re writing and further lock down our rules based on the metadata.

Cloud Storage for Firebase Security Rules provides rules for securing your data based on metadata of the file.

This post assumes that we will write a file containing a photo to Cloud Storage for Firebase at the following path:

    /Photos/<userUID>/filename

There are a couple of pieces of metadata that we know about files that represent photos:

  • Size

  • Contains image content

So let’s build some rules around what we know!

First of all, let’s break up the .read and .write rules into separate rules. Read operations do not carry any payload so there is no meta data to compare.

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /Photos/{userUID}/{allPaths=**} {
      allow read: if request.auth.uid == userUID;
      allow write: if request.auth.uid == userUID;
    }
  }
}

Yes, this is just a small step to break up the .read and .write rules. I personally like to go slow with my rules, change one thing at a time, and confirm things are working on each step. Feel free to run the Simulator and see all your Simulation types (get, create, update, delete) are working successfully.

We’re now going to add criteria to our rules that require photo files to be 2MB or less in order to be written successfully:

allow write: if request.auth.uid == userUID && request.resource.size <= 2 * 1024 * 1024;

A similar example can be found in the Google documentation for Cloud Storage for Firebase Security Rules.

In the Simulator we can simulate the metadata of the file we are writing. In this case we want to test files that are 2MB or larger.

In the Simulator click the Build Metadata button to bring up fields to set and pass to the Simulator such as Size.

2MB = 2097152 bytes so we’ll plug that value into the Size:

Screen Shot 2019-07-21 at 2.30.37 PM.png


Run the Simulator and you’ll see that its successful! For fun and for practice add one more byte to the size and run the Simulator to see that it fails.

Here are our rules:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /Photos/{userUID}/{allPaths=**} {
      allow read: if request.auth.uid == userUID;
      allow write: if request.auth.uid == userUID && request.resource.size <= 2 * 1024 * 1024;
    }
  }
}

Publish the rules to save them and then let’s keep going!