0
votes
  • I've got a Firestore collection.

  • The IDs of the documents are secrets. You should be able to read only the document whose ID you know. For the sake of simplicity. I'd like to stick to this approach.

  • However, by default, one can read an entire collection from Firestore, for example

await firestore.collection("secret_documents").get()

Is it possible to allow reading only one document at once, only when it's referred by its ID?

1

1 Answers

2
votes

Yes, that is actually quite easy. To control what documents can be accessed, use Firebase security rules for Firestore.

By default your security rules will be read and write, but those can actually be broken down into more granular operations of get, list, create and update. And what you're trying to do is to allow get, but not a list operation. From the documentation:

service cloud.firestore {
  match /databases/{database}/documents {
    // A read rule can be divided into get and list rules
    match /cities/{city} {
      // Applies to single document read requests
      allow get: if <condition>;

     // Applies to queries and collection read requests
      allow list: if <condition>;
    }
    ...

So to allow get for everyone and disallow list calls:

allow get: if true;
allow list: if false;

You'll probably want to elaborate on the allow get rule a bit, because it's more common to restrict it, for example to users that are signed in to your project with Firebase Authentication:

allow get: if request.auth.uid != null;

https://firebase.google.com/docs/firestore/security/rules-query