2

I want to write game events and audit logs from my app to Cloud Firestore. Once written, I don't want the user to be able to modify or delete these events/logs.

How can I do this?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Dan McGrath
  • 41,220
  • 11
  • 99
  • 130

1 Answers1

4

Rules in Cloud Firestore makes it quite simply to make a collection, or even the entire database, into an append-only system from the mobile & web clients.

Example

Below is a set of rules that will turn the root collection audit_logs into an append-only collection.

service cloud.firestore {
   match /databases/{database}/documents/ {
      function permission_granted() {
         return request.auth != null; // Change this to your logic.
      }

      match /audit_logs/{log} {
         allow update,delete: if false;
         allow read, create, list: if permission_granted();
      }
   }
}

Let's break down the most important pieces.

Function: permission_granted()

function permission_granted() {
   return request.auth != null; // Change this to your logic.
}

This one is just a placeholder for however you want to restrict insert new documents or reading existing documents in the collection. In this case it's letting anyone who has signed in using Firebase Auth -> You might want it more restrictive.

It just returns true or false, which we'll use later to actually enforce.

Match: Root collection audit_log

match /audit_logs/{log} { ... }

This one's simple, we're just matching against any requests regarding for the root collect called audit_logs. The document Id in questions is made available via $(log) due to the {log} piece.

Blocking any modification that is append-only

allow update,delete: if false;

The 2 write methods that are not append-only are update and delete, so here we just universally disallow any mobile & web SDK from performing them.

Allow the rest

allow read, create, list: if permission_granted();

Lastly, using the permission_granted function we set up earlier, we allow reading, listing, and creating new documents in the collection.

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130