2
votes

I am trying to implement a Firestore security rule that validates all the entries made on creation inside a map. However, I have the problem that I don't know the keys to the map. I have something like this:

{
    "name": "Tom",
    "answers": {
        "SomeUUID": {
            "answer": "Alps",
            "right": true
        },
        "AnotherUUID": {
            "answer": "Mount Everest",
            "right": false
        }
    }
}

To validate the entries with security rules I would do something like this

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

  match /answers/{answerID} {  
        allow read;
        allow create: request.resource.data.name is string && request.resource.data.answers is map
  } 

}

How can I further validate the content of the members map without knowing the size of the map or the keys? Is there a wildcard that I could use for the keys? The value for each created key should be the same. I would like to do something like this:

    allow create: request.resource.data.name is string && request.resource.data.answers && 
request.resource.data.member.$(wildcard).keys().size() == 2 && request.resource.data.member.$(wildcard).answer is string && request.resource.data.member.$(wildcard).right is bool

Is this possible or do I need to change the whole logic? Any chance there is a wildcard available?

1

1 Answers

2
votes

It's not possible to check the contents of a field if you don't know its name. There are no wildcards or iterators in security rules that let you discover random things.

If you must keep this document structure and validation logic, consider instead sending the document data to a backend you control, and use server-side logic to determine if the data is valid.