0

Bad idea: I am going to allow anonymous website users to log a visit to a Firestore collection, but I don't want them stomping around and using my site to serve bad things™️, how do I constrain the writes?

(admittedly poor practice, this is just a prototype, the right way to do this would be to hit up a middle layer, have the middle layer validate the write request, only allow the firestore DB to be written to from the middle layer, etc.)

I'd like to constrain the documents that the visitor can add to the collection to a simple "add a doc with a number and timestamp."

Something like

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if
          request.time < timestamp.date(2021, 5, 22);
    }
    match /{pageId}/visit/} {
      allow write: if
          request.time < timestamp.date(2021, 5, 22)
          && request.num EXISTS AS A NUMBER
          && request.timestamp EXISTS AS A TIMESTAMP
          && NO OTHER FUNNY STUFF ALLOWED;
    }
  }
}
Benjamin H
  • 5,164
  • 6
  • 34
  • 42
  • I did make some progress, but not quite solved. There is a function that takes key names and make sure those are the ONLY key names. Very promising. – Benjamin H Mar 09 '21 at 16:33

1 Answers1

0

Have a look at my answer here to learn how to implement both a global and a user-specific write rate limit: How do I implement a write rate limit in Cloud Firestore security rules?

In addition I would recommend to anonymously authenticate the users, so that users are signed in automatically without enter credentials. That would then allow you to limit the write rate limit per user, as my answer to the above question also shows.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807