Search code examples
firebasegoogle-cloud-firestorefirebase-security

How to debug firestore.rules variables and functions?


I am having difficulty trying to diagnose a particular rule in my firestore.rules file. See that question here for context.

Is there a way to debug the firestore.rules file and/or functions? I'm using unit testing and the emulators to test my rules, but I would really love to see exactly what values are being evaluated by the rules engine.

For instance, here is my firestore.rules file:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /organizations/{orgId} {
      allow read: if isAdmin();
      allow create, update: if isAdmin();

      match /classes/{classId} {
        allow read: if request.auth.uid != null;
        allow create, update: if isAdmin();

        match /students/{studentId} {
          allow read: if isAdmin() || belongsToCurrentClass();
          allow create, update: if isAdmin();
        }
      }
    }
  }
}

function isAdmin() {
  // removed for security
}

function belongsToCurrentClass() {
  // retuns true if the authenticated user is the teacher of the requested class
  return get(/databases/$(database)/documents/organizations/$(orgId)/classes/$(classId)).data.teacherUid == request.auth.uid;
}

What I'd love to do is set breakpoints or step through the code. When attempting CRUD operations on a organizations/{orgId}/classes/{classId}/students/{studentId} path I'd love to inspect exactly what values the orgId, classId, and studentId variables are holding, as well as the resource and request parameters. I'd love to inspect exactly which document (if any) is returned by the get request in belongsToCurrentClass and what the return value is.

Does anyone know of any way to do this? I think I'd answer my question referred to above in 10 seconds if I could just see the data being evaluated.


Solution

  • There is a local emulator for Cloud Firestore security rules. This is your best (and really only) tool for digging into security rule execution. There is no step-through debugging, but you can see a lot of debug output in the console.

    https://firebase.google.com/docs/rules/emulator-setup