Search code examples
firebasegoogle-cloud-firestorefirebase-security

Firestore Security Rules: get path as string


With Firestore Security Rules (version 2), how can I turn a Path object into a String? The entire path as one String, not the individual segments.

I'm trying to write a generic function to use in various Match statements. Something like this:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    // "pathobj" is a rules.firestore.Path object
    function getPathAsString(pathobj) {
      // Does not work:
      return pathobj.toString();
    }

    // I would expect the following to evaluate to True:
    match /foo/{fooid} {
      allow read: if getPathAsString(path('one')) == 'one'
                  && getPathAsString(path('one/!two')) == 'one/!two';
    }
  }
}

Does anyone know if this is possible? I read the documentation on Path and have tried various things in the Firestore Rules Simulator, all with no success.


Solution

  • firebaser here

    We recently added support for casting paths to strings as a result of this question.

    You can now perform comparisons by casting paths using the string() cast method which already exists for other types (null, float, int, bool), ie:

    rules_version = '2';
    
    service cloud.firestore {
      match /databases/{database}/documents {
    
        // Evaluates to true for the foo/fooid document:
        match /foo/{fooid} {
          allow read: if string(path('one')) == '/one'
                      && string(request.path) == '/databases/(default)/documents/foo/fooid';
        }
      }
    }
    

    Note that valid paths will always start with a /. Leave a comment if you encounter any issues with this feature.