Firestore orderBy security rule

Viewed 502

I've just started using Firestore and am trying to create a security rule to support this kind of query from my app (Android/kotlin)

firestoreDb.collection("messages").whereEqualTo("room_id", "c_1")
    .orderBy("timestamp", Query.Direction.ASCENDING)

Structure of my database is:

room
   -{roomId}
      -members [] //this is an array of strings
messages
   -{messageId}
      -timestamp
      -room_id
      -message_text

The security rule looks as follows:

service cloud.firestore {
  match /databases/{database}/documents {
    match /messages/{messageId} {
        allow read: if request.auth.uid in get(/databases/$(database)/documents/rooms/$(resource.data.room_id)).data.members && 
        request.query.orderBy == "timestamp"
    }
  }
}

If I don't use the orderBy part everything works fine and I get a successful response. However after applying orderBy in code, I need to add the orderBy rule to the firestore security rules. Unfortunately I wasn't able to find any example of the syntax, how that should be defined.

This is the official documentation I'm using as a reference, but there's only an example for request.query.limit, from which it isn't clear how the request.query.orderBy should work.

Any help much appreciated Cheers

1 Answers

Sorry for the late answer.

We should treat request.query.orderBy has Map.

request.query.orderBy.timestamp == 'ASC'
Related