Firebase Security Rules for Cloud Storage Reference

Firebase Security Rules forCloud Storage are used to determine who has read and write accessto files stored inCloud Storage, as well as how files are structuredand what metadata they contain.Cloud Storage Security Rules are composed of rules thatconsider therequest andresource to allow or deny a desired action, suchas uploading a file or retrieving file metadata. These reference docs coverthe types of rules, the properties of arequest and aresource, the datatypes used byCloud Storage Security Rules, and how errors occur.

Rule

Arule is an expression that is evaluated to determine if arequest isallowed to perform a desired action.

Types

Allow

allow rules consist of a method, such asread orwrite, as well asan optional condition. When a rule is executed, the condition is evaluated, andif the condition evaluates totrue, the desired method is allowed; otherwise,the method is denied. Anallow rule with no condition always allows thedesired method.

// Always allow methodallow<method>;// Allow method if condition is trueallow<method>:if<condition>;

Currently,allow is the only supported type of rule.

Request Methods

Read

Theread method covers all requests where file data or metadata is read,including file downloads and file metadata reads.

// Always allow readsallowread;// Allow reads if condition evaluates to trueallowread:if<condition>;

Write

Thewrite method covers all requests where file data or metadata is written,including file uploads, file deletes, and file metadata updates.

// Always allow writesallowwrite;// Allow writes if condition evaluates to trueallowwrite:if<condition>;

Match

Rules are executed when a userrequest (such as a file upload or download)matches a file path covered by a rule. Amatch consists of a path and a body,which must contain at least oneallow rule. If no path is matched, the requestis rejected.

You canmatch a fully named path, or you can insert wildcards to match allpaths that fit a certain pattern.

Path Segments

single_segment

You can use single path segments to create a rule that matches a file storedinCloud Storage.

// Allow read at "path" if condition evaluates to truematch/path{allowread:if<condition>;}

Multiple path segments and nested paths are also allowed:

// Allow read at "path/to/object" if condition evaluates to truematch/path{match/to{match/object{allowread:if<condition>;}}}

{single_segment_wildcard}

If you want to apply a rule to multiple files at the same path, you can use awildcard path segment to match all files at a certain path. A wildcard variableis declared in a path by wrapping a variable in curly braces:{variable}.This variable is accessible within the match statement as astring.

// Allow read at any path "/*", if condition evaluates to truematch/{single_path}{// Matches "path", "to", or "object" but not "path/to/object"allowread:if<condition>;}

Multiple path segments and nested paths may also have wildcards:

// Allow read at any path "/path/*/newPath/*", if condition evaluates to truematch/path/{first_wildcard}{match/newPath/{second_wildcard}{// Matches "path/to/newPath/newObject" or "path/from/newPath/oldObject"allowread:if<condition>;}}

{multi_segment_wildcard=**}

If you want to match any number of path segments at or below a path, you can usea multi segment wildcard, which will match all requests to and below thelocation. This can be useful for providing a user their own free formstorage space, or creating rules that match many different path segments (suchas creating a publicly readable set of files, or requiring authentication forall writes).

A multi segment wildcard path is declared similarly to a single segmentwildcard, with the addition of the=** at the end of the variable:{variable=**}. A multi-segment wildcard variable is available within the matchstatement as apath object.

// Allow read at any path "/**", if condition evaluates to truematch/{multi_path=**}{// Matches anything at or below this, from "path", "path/to", "path/to/object", ...allowread:if<condition>;}

Request

Therequest variable is provided within a condition to represent therequest being made at that path. Therequest variable has a number ofproperties which can be used to decide whether to allow the incoming request.

Properties

auth

When an authenticated user performs a request againstCloud Storage,theauth variable is populated with the user'suid (request.auth.uid) aswell as the claims of theFirebase Authentication JWT (request.auth.token).

request.auth.token contains some or all of the following keys:

FieldDescription
emailThe email address associated with the account, if present.
email_verifiedtrue if the user has verified they have access to theemail address. Some providers automatically verify email addresses they own.
phone_numberThe phone number associated with the account, if present.
nameThe user's display name, if set.
subThe user's Firebase UID. This is unique within a project.
firebase.identitiesDictionary of all the identities that are associated with this user's account. The keys of the dictionary can be any of the following:email,phone,google.com,facebook.com,github.com,twitter.com. The values of the dictionary are arrays of unique identifiers for each identity provider associated with the account. For example,auth.token.firebase.identities["google.com"][0] contains the first Google user ID associated with the account.
firebase.sign_in_providerThe sign-in provider used to obtain this token. Can be one of the following strings:custom,password,phone,anonymous,google.com,facebook.com,github.com,twitter.com.
firebase.tenantThe tenantId associated with the account, if present. e.g.tenant2-m6tyz

If using custom authentication,request.auth.token also contains any customclaims specified by the developer.

When an unauthenticated user performs a request,request.auth isnull.

// Allow requests from authenticated usersallowread,write:ifrequest.auth!=null;

path

Thepath variable contains the path that arequest is being performedagainst.

// Allow a request if the first path segment equals "images"allowread,write:ifrequest.path[0]=='images';

resource

Theresource variable contains the metadata of a file being uploaded or theupdated metadata for an existing file. This is related to theresource variable, which contains the current file metadata atthe requested path, as opposed to the new metadata.

// Allow a request if the new value is smaller than 5MBallowread,write:ifrequest.resource.size <5*1024*1024;

request.resource contains the following properties fromresource:

Property
name
bucket
metadata
size
contentType

time

Thetime variable contains a timestamp representing the current server timea request is being evaluated at. You can use this to provide time-based accessto files, such as: only allowing files to be uploaded until a certain date,or only allowing files to be read up to an hour after they were uploaded.

// Allow a read if the file was created less than one hour agoallowread:ifrequest.time <resource.timeCreated+duration.value(1,'h');

Many functions are provided to write rules usingtimestamps anddurations.

Resource

Theresource variable contains file metadata for files inCloud Storage, such as the file name, size, creation time, andcustom metadata.

Properties

name

A string containing the full name of the file, including the path to the file.

// Allow reads if the resource name is "path/to/object"allowread:ifresource.name=='path/to/object'

bucket

A string containing theGoogle Cloud Storagebucket this file is stored in.

// Allow reads of all resources in your bucketallowread:ifresource.bucket=='<your-cloud-storage-bucket>'

generation

A int containing the Google Cloud Storageobject generation ofthe file. Used for object versioning.

// Allow reads if the resource matches a known object versionallowread:ifresource.generation==<known-generation>

metageneration

A int containing the Google Cloud Storageobject metagenerationof the file. Used for object versioning.

// Allow reads if the resource matches a known object metadata versionallowread:ifresource.metageneration==<known-generation>

size

An int containing the file size in bytes.

// Allow reads if the resource is less than 10 MBallowread:ifresource.size <10*1024*1024;

timeCreated

A timestamp representing when the file was created.

// Allow reads if the resource was created less than an hour agoallowread:ifresource.timeCreated <request.time+duration.value(60,"m")

updated

A timestamp representing when the file was last updated.

// Allow reads if the resource was updated less than an hour agoallowread:ifresource.updated <request.time+duration.value(60,"m")

md5Hash

A string containing theMD5 hash of thefile.

//Allowwritesifthehashoftheuploadedfileisthesameastheexistingfileallowwrite:ifrequest.resource.md5Hash==resource.md5Hash;
Note: MD5 hash collisions are possible and could allow someone to overwrite afile, even if a rule like the above exists. Consider additional file validationor other rules to enforce immutability (e.g.allow write: if resource ==null;)

crc32c

A string containing thecrc32c hash of thefile.

//Allowwritesifthehashoftheuploadedfileisthesameastheexistingfileallowwrite:ifrequest.resource.crc32c==resource.crc32c;
Note: crc32c hash collisions are possible and could allow for someone tooverwrite a file, even if a rule like the above exists. Consider additional filevalidation or other rules to enforce immutability (e.g.allow write: ifresource == null;).

etag

A string containing theetag of thefile.

// Allow writes if the etag matches a known object etagallowwrite:ifresource.etag==<known-generation>

contentDisposition

A string containing the content disposition of the file.

// Allow reads if the content disposition matches a certain valueallowread:ifresource.contentDisposition=='inlined';

contentEncoding

A string containing the content encoding of the file.

// Allow reads if the content is encoded with gzipallowread:ifresource.contentEncoding=='gzip';

contentLanguage

A string containing the content language of the file.

// Allow reads if the content language is Japaneseallowread:ifresource.contentLanguage=='ja';

contentType

A string containing the content type of the file.

// Allow reads if the content type is PNG.allowread:ifresource.contentType=='image/png';

metadata

AMap<String, String> containing additional developer provided metadatafields.

// Allow reads if a certain metadata field matches a desired valueallowread:ifresource.metadata.customProperty=='customValue';

firestore.get and firestore.exists

Thefirestore.get() andfirestore.exists() functions allow you to accessdocuments inCloud Firestore to evaluate complex authorization criteria.

Thefirestore.get() andfirestore.exists() functions both expectfully-specified document paths. When using variables to construct paths forfirestore.get() andfirestore.exists(), you need to explicitly escapevariables using the$(variable) syntax.

firestore.get

Get the contents of aCloud Firestore document.

service firebase.storage {  match /b/{bucket}/o {    match /users/{club}/files/{fileId} {      allow read: if club in        firestore.get(/databases/(default)/documents/users/$(request.auth.uid)).data.memberships    }  }}

firestore.exists

Check if aCloud Firestore document exists.

service firebase.storage {  match /b/{bucket}/o {    match /users/{userId}/photos/{fileId} {      allow read: if        firestore.exists(/databases/(default)/documents/users/$(userId)/friends/$(request.auth.uid))    }  }}

Service

Theservice is the first declaration in aCloud Storage Security Rules file, andspecifies which service these rules will apply to.

Name

name

The name of the service rules will be apply to. The only current value isfirebase.storage.

// Specify the service nameservicefirebase.storage{match/b/{bucket}/o{...}}

Data Types

TheSecurity Rules language allows you to check type using theis operator.

// For exampleaisnullaisstring

null

Thenull data type represents a value not existing.

allowread:ifrequest.auth!=null;

bool

Thebool type represents a booleantrue orfalse value.

allowread:iftrue;//alwayssucceedsallowwrite:iffalse;//alwaysfails

Comparison

Boolean values can be compared using the== operators!=.

Boolean Operations

OperationExpression
ANDx && y
ORx || y
NOT!x

Operations short circuit, and can return eithertrue,false, or anError.

allowread:iftrue||false;//alwayssucceeds,shortcircuitsattrueallowwrite:iffalse &&true;//alwaysfails,shortcircuitsatfalse

int andfloat

Theint andfloat types represent numbers. Ints are:0,1,-2, etc., while floats are:1.0,-2.0,3.33, etc.

Ints are signed 64-bit values, and floats are 64-bit IEEE 754 compliant values.Values of typeint will be coerced tofloat when used in comparisons andarithmetic operations with afloat value.

Comparison

Ints and floats can be compared and ordered using the==,!=,>,<,>=, and<= operators.

Arithmetic

Ints and floats can be added, subtracted, multiplied, divided, moduloed, andnegated:

OperationExpression
Additionx + y
Subtractionx - y
Multiplicationx * y
Divisionx / y
Modulox % y
Negation-x

Mathematical functions

Firebase Security Rules forCloud Storage also provides a number of mathematics helperfunctions to simplify expressions:

FunctionDescription
math.ceil(x)Ceiling of the numeric value
math.floor(x)Floor of the numeric value
math.round(x)Round the input value to the nearest int
math.abs(x)Absolute value of the input
math.isInfinite(x)Test whether the value is±∞, returns abool
math.isNaN(x)Test whether the value is not a numberNaN, returns abool

string

Comparison

Strings can be lexographically compared and ordered using the==,!=,>,<,>=, and<= operators.

Concatenation

Strings can be concatenated using the+ operator.

// Concatenate a file name and extension'file'+'.txt'

Index and Range

Theindex operator,string[], returns a string that contains the characterat the provided index in the string.

// Allow reads of files that begin with 'a'match/{fileName}{allowread:iffileName[0]=='a';}

Therange operator,string[i:j], returns a string that contains thecharacters between the specified indices, fromi (inclusive) untilj(exclusive). Ifi orj are not specified, they default to 0 and the size ofthe string, respectively, but at leasti orj must be specifiedfor the range to be valid.

// Allow reads of files that begin with 'abcdef'match/{fileName}{allowread:iffileName[0:6]=='abcdef';}

Theindex andrange operators will yield an error if the indices providedexceed the string bounds.

size

Returns the number of characters in the string.

// Allow files with names less than 10 charactersmatch/{fileName}{allowwrite:iffileName.size() <10;}

matches

Performs a regular expression match, returnstrue if the string matches thegiven regular expression. UsesGoogle RE2 syntax.

// Allow writes to files which end in ".txt"match/{fileName}{allowwrite:iffileName.matches('.*\\.txt')}

split

Splits a string according to a provided regular expression and returns alistof strings. UsesGoogle RE2 syntax.

//Allowfilesnamed"file.*"tobeuploadedmatch/{fileName}{allowwrite:iffileName.split('.*\\..*')[0]=='file'}

path

Paths are directory-like names with optional pattern matching. Thepresence of a forward slash/ denotes the start of a path segment.

path

Converts astring argument to apath.

// Allow reads on a specific file pathmatch/{allFiles=**}{allowread:ifallFiles==path('/path/to/file');}

timestamp

Timestamps are in UTC, with possible values beginning at 0001-01-01T00.00.00Zand ending at 9999-12-31T23.59.59Z.

Comparison

Timestamps can be compared and ordered using the==,!=,>,<,>=, and<= operators.

Arithmetic

Timestamps support addition and subtraction between timestamps and durations asfollows:

ExpressionResult
timestamp + durationtimestamp
duration + timestamptimestamp
timestamp - durationtimestamp
timestamp - timestampduration
duration + durationduration
duration - durationduration

date

Atimestamp value containing theyear,month, andday only.

// Allow reads on the same day that the resource was created.allowread:ifrequest.time.date()==resource.timeCreated.date()

year

The year value as an int, from 1 to 9999.

// Allow reads on all requests made before 2017allowread:ifrequest.time.year() <2017

month

The month value as an int, from 1 to 12.

// Allow reads on all requests made during the month of Januaryallowread:ifrequest.time.month()==1;

day

The current day of the month as an int, from 1 to 31.

// Allow reads on all requests made during the first day of each monthallowread:ifrequest.time.day()==1;

time

Aduration value containing the current time.

// Allow reads on all requests made before 12PMallowread:ifrequest.time.time() <duration.time(12,0,0,0);

hours

The hours value as an int, from 0 to 23.

// Allow reads on all requests made before 12PMallowread:ifrequest.time.hours() <12;

minutes

The minutes value as an int, from 0 to 59.

// Allow reads during even minutes of every hourallowread:ifrequest.time.minutes()%2==0;

seconds

The seconds value as an int, from 0 to 59.

// Allow reads during the second half of each minuteallowread:ifrequest.time.seconds() >29;

nanos

The fractional seconds in nanos as an int.

// Allow reads during the first 0.1 seconds of each secondallowread:ifrequest.time.nanos() <100000000;

dayOfWeek

The day of the week, from 1 (Monday) to 7 (Sunday).

// Allow reads on weekdays (Monday to Friday)allowread:ifrequest.time.dayOfWeek() <6;

dayOfYear

The day of the current year, from 1 to 366.

// Allow reads every fourth dayallowread:ifrequest.time.dayOfYear()%4==0;

toMillis

Returns the current number of milliseconds since the Unix epoch.

// Allow reads if the request is made before a specified timeallowread:ifrequest.time.toMillis() <<milliseconds>;

duration

Duration values are represented as seconds plus fractional seconds innanoseconds.

Comparison

Durations can be compared and ordered using the==,!=,>,<,>=, and<= operators.

Arithmetic

Durations support addition and subtraction between timestamps and durations asfollows:

ExpressionResult
timestamp + durationtimestamp
duration + timestamptimestamp
timestamp - durationtimestamp
timestamp - timestampduration
duration + durationduration
duration - durationduration

seconds

The number of seconds in the current duration. Must be between -315,576,000,000and +315,576,000,000 inclusive.

nanos

The number of fractional seconds (in nanoseconds) of the current duration. Mustbe beween -999,999,999 and +999,999,999 inclusive. For non-zero seconds andnon-zero nanonseconds, the signs of both must be in agreement.

duration.value

Durations can be created using theduration.value(int magnitude, string units)function, which creates a time duration from the given magnitude and unit.

// All of these durations represent one hour:duration.value(1,"h")duration.value(60,"m")duration.value(3600,"s")

Possibleunits are:

Durationunit
Weeksw
Daysd
Hoursh
Minutesm
Secondss
Millisecondsms
Nanosecondsns

duration.time

Durations can be created using theduration.time(int hours, int minutes, int seconds, int nanoseconds) function,which creates a time duration of the given hours, minutes, seconds, andnanoseconds.

// Create a four hour, three minute, two second, one nanosecond durationduration.time(4,3,2,1)

list

A list contains an ordered array of values, which can of type:null,bool,int,float,string,path,list,map,timestamp, orduration.

Givenx andy of typelist andi andj of typeint

Creation

To create a list, add values between brackets:

// Create a list of strings['apples','grapes','bananas','cheese','goats']

Comparison

Lists can be compared using the== operators!=. Equality of two listsrequires all values to be equal.

Index and Range

Theindex operator,list[], returns the item at the provided index in thelist.

// Allow reads of all files that begin with 'a'match/{fileName}{allowread:iffileName[0]=='a';}

Therange operator,list[i:j], returns all items in a list between thespecified indices, fromi (inclusive) untilj (exclusive). Ifi orj arenot specified, they default to 0 and the size of the list, respectively, butat leasti orj must be specified for the range to be valid.

// Allow reads of all files that begin with 'abcdef'match/{fileName}{allowread:iffileName[0:6]=='abcdef';}

in

Returnstrue if the desired value is present in the list orfalse if notpresent.

// Allow read if a filename has the string 'txt' in itmatch/{fileName}{allowread:if'txt'infileName.split('\\.');}

join

Combines a list of strings into a single string, separated by the given string.

// Allow reads if the joined array is 'file.txt'allowread:if['file','txt'].join('.')=='file.txt';

size

The number of items in the list.

// Allow read if there are three items in our listallowread:if['foo','bar','baz'].size()==3;

hasAll

Returnstrue if all values are present in the list.

// Allow read if one list has all items in the other listallowread:if['file','txt'].hasAll(['file','txt']);

map

A map contains key/value pairs, where keys are strings and values can be anyof:null,bool,int,float,string,path,list,map,timestamp, orduration.

Creation

To create a map, add key/value pairs between braces:

// Create a map of strings to strings{'mercury':'mars','rain':'cloud','cats':'dogs',}

Comparison

Maps can be compared using the== operators!=. Equality of two mapsrequires all keys are present in both maps and all values are equal.

Index

Values in a map are accessed by using either bracket or dot notation:

// Access custom metadata propertiesallowread:ifresource.metadata.property=='property'allowwrite:ifresource.metadata['otherProperty']=='otherProperty'

If a key is not present, anerror will be returned.

in

Returnstrue if the desired key is present in the map orfalse if notpresent.

// Allow reads if a property is present in the custom metadataallowread:ifpropertyinresource.metadata;

size

The number of keys in the map.

// Allow reads if there's exactly one custom metadata keyallowread:ifresource.metadata.size()==1;

keys

A list of all keys in the map.

// Allow reads if the first metadata key is 'myKey'allowread:ifresource.metadata.keys()[0]=='myKey';

values

A list of all values in the map, in key order.

// Allow reads if the first metadata value is 'myValue'allowread:ifresource.metadata.values()[0]=='myValue';

Errors

Error Evaluation

Firebase Security Rules forCloud Storage continue evaluation when errors are encountered.This is useful because conditional&& and|| expressions may absorb an errorif the conditional would otherwise short-circuit tofalse ortruerespectively. For instance:

ExpressionResult
error && trueerror
error && falsefalse
error || truetrue
error || falseerror

Common places where errors are raised are: division by zero, accessing valuesin a list or map that don't exist, and passing values of the incorrect typeto a function.

// Error if resource.size is zeroallowread:if1000000/resource.size;// Error, key doesn't existallowread:ifresource.metadata.nonExistentKey=='value';// Error, no unit 'y' existsallowread:ifrequest.time <resource.timeCreated+duration.value(1,'y');

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-01-21 UTC.