11

I need some help making my security rules for firestore work.

These are my firestore rules:

service cloud.firestore {
  match /databases/{database}/documents {
     match /orders/{orderID} {
       allow read, update: if  request.auth.uid == resource.data.buyerId  || request.auth.uid == resource.data.sellerId;
    }
  }
}

my orders collection:

orders: {
sellerId: 'some-id',
createdAt: timestamp,
buyerId: 'some-id'
}

It should return all documents from orders collection which has either buyerId or sellerId equal to authorised user (request.auth.uid).

but the above rule is not working as expected.

firestore collections screenshot

firebase simulator output

Mohd Imran
  • 113
  • 1
  • 6

2 Answers2

13

That error message is suggesting that the requested document was not actually present in the database. You entered "orders/{orderId}", which looks like you put a wildcard in the Location field in the simulator. That's not going to work. You need to enter the path to an actual document that exists if you want to test your rule that uses its field values.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • orders collection already exists with the fields sellerId and buyerId – Mohd Imran May 03 '19 at 00:06
  • 1
    Sure, but there is no document with id {orderId}. You need to put an actual document ID there if you want to test against its contents. You can't use a wildcard in the simulator panel. – Doug Stevenson May 03 '19 at 00:07
  • I have edited post with attached firestore collections screenshot, there are some documents already present in the orders collection. – Mohd Imran May 03 '19 at 00:11
  • 1
    you were right, when putting orders/DePzMaZAMkJUcH66fIxA in location field of simulator it worked fine. – Mohd Imran May 03 '19 at 00:17
  • 1
    What to do for matching any document in the collection, could you please suggest? – Mohd Imran May 03 '19 at 00:30
  • You can't simulate a match against any document, in the same way that you can't make a query that fetches an unknown document. You need to know the document you're trying to access. – Doug Stevenson May 03 '19 at 00:33
  • Looks like I have the same issue. I've created git repo with tests. Could you please look at this https://github.com/OleksiiBrylin/firestore-rules – Oleksii.B Apr 01 '20 at 18:06
9

resource.data: Null - this error happens when you try to create a new entity.

Split write rule, on create and update.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /user/{userId} {
      allow read: if request.auth.uid == userId;

      function authed() {
        return request.auth.uid == userId;
      }
      allow create: if authed() && request.resource.data.keys().hasOnly(['name']);
      allow update: if authed() && request.resource.data.diff(resource.data).changedKeys().hasOnly(['name']);
      allow delete: if authed();
    }
  }
}
Oleksii.B
  • 618
  • 8
  • 16