1

I'm trying to follow the examples laid out in the Firebase Security Rules for Cloud Storage Reference:

https://firebase.google.com/docs/reference/security/storage/

I copy & paste the example for split() into my Storage Rules and it won't compile/let me save:

Splits a string according to a provided regular expression and returns a list of strings. Uses Google RE2 syntax.

// Allow files named "file.*" to be uploaded
match /{fileName} {
  allow write: if fileName.split('.*\..*')[0] == 'file'
}

The error I get: Unexpected '.'.

For the life of me, I can't get the example code provided to run, nor can I make changes and get Regex to work as expected.

Anyone have any suggestions for Allow files named "file.*" to be uploaded?

briannyc
  • 35
  • 2
  • 4

2 Answers2

4

There seems to be a \ missing in the rules. Try this:

// Allow files named "file.*" to be uploaded
match /{fileName} {
  allow write: if fileName.split('.*\\..*')[0] == 'file'
}

In general when working with regular expressions, the backslashes are the first thing to check. Different systems use backslashes for escaping and sometimes (such as here) you'll need to double escape them.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 2
    Frank, thank you for the quick response. Your regex `split('.*\\..*')[0]` example still didn't work for me, but your comment on double escaping got me on the right path. Seems you'd do `split('\\.')[0]` to get the actual file name, which worked for me. Am I missing something, or is the example in the documentation off a bit? I also got false negatives when testing right after a change, seems there is a propagation delay for the rules to reach nodes or remove some cache? – briannyc Jul 03 '17 at 03:26
  • 1
    @briannyc: Your observation regarding the delay is correct. It's noted in the [Security Rules Guide](https://firebase.google.com/docs/storage/security/start#edit_rules): _Rules are immediately uploaded to Cloud Storage servers, but may take up to five minutes to become live_. – Bob Snyder Jul 03 '17 at 04:27
  • @YosefBro That question is about the Realtime Database, which doesn't allow the use of `.` and `/` in its keys. This question is about Cloud Storage, where using `.` in names is actually quite common, to separate the base file name and its extension. – Frank van Puffelen Aug 25 '20 at 13:17
2

The documentation is wrong. Use this instead ('\.'):

// Allow files named "file.*" to be uploaded
match /{fileName} {
  allow write: if fileName.split('\\.')[0] == 'file'
}