Search code examples
listfirebasegoogle-cloud-firestorefirebase-security

Check if request.resource.data is a list of strings in Firebase Firestore


How do I check if a field is of type string[] in firestore rules?

I have a tags field in a document, which should be a list of strings, and I want to enforce that. Normally, I can say request.resource.data is int if I want to see if the field is an int, but I can't find an equivalent for lists.

Thanks!


Solution

  • There is no explicit type check in the rules language (at least as far as I know). So the best I can come up with is trying to find a way to distinguish between a List (the type of an array), and other types.

    For example, a list has a join() method, which can be used to concatenate the values from the list into a single string. Since (as far as I can see) none of the other types have that operation, this check can detect an array:

    allow write: if request.resource.data.categories.join(",") != "";
    

    Any non-empty array will pass this test, while empty arrays and other types will fail. In the simulator this gives a pretty ugly error message, but that translates to a normal, generic "permission denied" when exposed to clients.

    For my own future reference: test code is here.