Firestore Security Rules - How can I check that a

2019-01-15 01:14发布

For the life of me, I cannot understand why the following is resulting in a false for allowing writes. Assume my users collection is empty to start, and I am writing a document of the following form from my Angular frontend:

{
  displayName: 'FooBar',
  email: 'foo.bar@example.com'
}

My current security rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      function isAdmin() {
        return resource.data.role == 'ADMIN';
      }

      function isEditingRole() {
        return request.resource.data.role != null;
      }

      function isEditingOwnRole() {
        return isOwnDocument() && isEditingRole();
      }

      function isOwnDocument() {
        return request.auth.uid == userId;
      }

      allow read: if isOwnDocument() || isAdmin();
      allow write: if !isEditingOwnRole() && (isOwnDocument() || isAdmin());
    }
  }
}

In general, I want no users to be able to edit their own role. Regular users can edit their own document otherwise, and admins can edit anyone's.

Stubbing isEditingRole() for false gives the expected result, so I've narrowed it down to that expression.

The write keeps coming back false, and I cannot determine why. Any ideas or fixes would be helpful!

Edit 1

Things I've tried:

function isEditingRole() {
  return request.resource.data.keys().hasAny(['role']);
}

and

function isEditingRole() {
  return 'role' in request.resource.data;
}

and

function isEditingRole() {
  return 'role' in request.resource.data.keys();
}

Edit 2

Note that eventually, admins will set a role for users, so a role could eventually exist on a document. This means that, according to the Firestore docs below, the request will have a role key, even if wasn't in the original request.

Fields not provided in the request which exist in the resource are added to request.resource.data. Rules can test whether a field is modified by comparing request.resource.data.foo to resource.data.foo knowing that every field in the resource will also be present in request.resource even if it was not submitted in the write request.

According to that, I think the three options from "Edit 1" are ruled out. I did try the suggestion of request.resource.data.role != resource.data.role and that's not working either... I'm at a loss and am beginning to wonder if there's actually a bug in Firestore.

6条回答
太酷不给撩
2楼-- · 2019-01-15 01:51

request.resource.keys.hasAny() is probably your best bet here. It allows you to check if a particular request.resource has any of the keys specified. By the negating the logic you can ensure that write requests do not have your blacklisted keys. For example:

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      //read rules here...
      allow write: if !request.resource.keys().hasAny(["role", "adminOnlyAttribute"]);
    }
  }
}
查看更多
\"骚年 ilove
3楼-- · 2019-01-15 01:54

So in the end, it seems I was assuming that resource.data.nonExistentField == null would return false, when it actually returns an Error (according to this and my tests). So my original solution may have been running into that. This is puzzling because the opposite should work according to the docs, but maybe the docs are referring to a value being "non-existent", rather than the key -- a subtle distinction.

I still don't have 100% clarity, but this is what I ended up with that worked:

function isAddingRole() {
  return !('role' in resource.data) && 'role' in request.resource.data;
}

function isChangingRole() {
  return 'role' in resource.data && 'role' in request.resource.data && resource.data.role != request.resource.data.role;
}

function isEditingRole() {
  return isAddingRole() || isChangingRole();
}

Another thing that still puzzles me is that, according to the docs, I shouldn't need the && 'role' in request.resource.data part in isChangingRole(), because it should be inserted automatically by Firestore. Though this didn't seem to be the case, as removing it causes my write to fail for permissions issues.

It could likely be clarified/improved by breaking the write out into the create, update, and delete parts, instead of just allow write: if !isEditingOwnRole() && (isOwnDocument() || isAdmin());.

查看更多
Deceive 欺骗
4楼-- · 2019-01-15 01:56

I solved it by using writeFields. Please try this rule.

allow write: if !('role' in request.writeFields);

In my case, I use list to restrict updating fields. It works, too.

allow update: if !(['leader', '_created'] in request.writeFields);
查看更多
太酷不给撩
5楼-- · 2019-01-15 02:00

Since reference to writeFields in documentation has disappeared, I had to come up new way to do what we could do with writeFields.

function isSameProperty(request, resource, key) {
    return request.resource.data[key] == resource.data[key]
}

match /myCollection/{id} {
    // before version !request.writeFields.hasAny(['property1','property2','property3', 'property4']);
  allow update: isSameProperty(request, resource, 'property1')
    && isSameProperty(request, resource, 'property2')
    && isSameProperty(request, resource, 'property3')
    && isSameProperty(request, resource, 'property4')
  }
查看更多
成全新的幸福
6楼-- · 2019-01-15 02:03

In order to enforce fields that are readonly in the client, use writeFields (https://firebase.google.com/docs/reference/rules/rules.firestore.Request#writeFields). gekijin suggested this, but got the syntax slightly wrong.

match /myCollection/{id}
  // Readonly fields
  allow update: if !(request.writeFields.hasAny(['field1', 'field2']));
}

Firestore will populate the writeFields for you, so the above check is always safe to do in your update & create rules.

EDIT 9 Oct 2018

@dls101 Was kind enough to inform that Google seem to have removed any mention of writeFields from the docs. So be careful using this solution.

查看更多
劫难
7楼-- · 2019-01-15 02:04

With this single function you can check if a fields are/aren't being created/modified.

function incomingDataHasFields(fields) {
    return (( 
        request.writeFields == null
        && request.resource.data.keys().hasAll(fields)
    ) || (
        request.writeFields != null
        && request.writeFields.hasAll(fields)
    ));
}

Usage:

match /xxx/{xxx} {    
    allow create:
        if incomingDataHasFields(['foo'])              // allow creating a document that contains 'foo' field
           && !incomingDataHasFields(['bar', 'baz']);  // but don't allow 'bar' and 'baz' fields to be created
查看更多
登录 后发表回答