Having problems with Firebase access rules - swift

This is mostly me playing with various cloud storage mechanisms, so I came with some test code. In this one, I wanted to have users and group them into households. The data structures I have in Firestore are:
Users/{user}/
name (string)
email (string)
admin (bool)
Households/{household}/
name (string)
users (array of string)
The identifier for {user} is the user ID from the User api (I'm using Swift for my code); the identifier for {household} is a UUID.
The rules I have for the database are:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /Users/{uid} {
allow create: if request.auth.uid != null;
allow read, write: if request.auth.uid != null && (request.auth.uid == uid || isAdmin());
allow delete: if isAdmin();
}
match /Households/{household} {
allow create: if request.auth.uid != null;
allow read, write: if hasAccess(household);
}
function hasAccess(household) {
let id = (request.auth != null) ? string(request.auth.uid) : "";
let users = id == "" ? [] : get(/databases/$(database)/documents/Households/$(household)).data.users;
return id != null && ((id in users) || isAdmin());
}
function isAdmin() {
let id = request.auth.uid;
return get(/databases/$(database)/documents/Users/$(id)).data.admin == true;
}
}
}
The Playground works with my UID; however, my code does not -- it gets an access denied error. (If I set my UID to have admin set to true, it works, so I know that part of the rules is working.)
A different problem on stackoverflow I found yesterday (63621376) showed the same problem, and it was fixed by converting a value to a string, which you can see I try there.
I have been unable to get the CLI emulator working, primarily because I use Macs, and I haven't been able to get the 1.8 version of Java installed in a way that it can work with.
ETA the client code:
let ref = self.dbHouseholds!
ref
.whereField("users", arrayContains: self.user?.id ?? "")
.getDocuments { snapshots, err in
print("snapshots = \(snapshots), err = \(err)")
}
It also fails if I don't have the .whereField query. The errors are
snapshots = nil, err = Optional(Error Domain=FIRFirestoreErrorDomain Code=7 "Missing or insufficient permissions." UserInfo={NSLocalizedDescription=Missing or insufficient permissions.})

The rule is denying your query because Firebase security rules are not filters. Please be sure to read and understand that documentation thoroughly.
The playground allows you to perform a request for a single document, but what you're showing here is a collection query, which you can't simulate in the console. When you perform a collection query, the rules will reject any query where there is any possible document that might not allow access. Rules will not scan every single document to pick out the ones that match - that does not scale at all.
Your function hasAccess depends on the value of a variable "household" containing an individual document ID being accessed. Since you are querying for many documents, you can't use that variable to check each document.
If you want to write a rule that requires that users can only query documents that have their UID in the users field, you'll have to write that condition like this instead:
request.auth.uid in resource.data.users
This will enforce the where clause in your query.

Related

In firestore rules, allow reading only users that belong to at least one of the workspaces to which the client belongs

According to the program architecture, the "member" object has a unique pair of workspaceId and userId. Thus, each workspace has one or more members (users), while each user has one or more members (workspaces).
To prevent the client from reading users that do not belong to any of the workspaces s/he belongs to, I came up with the following firestore rule:
match /users/{userId} {
allow read: if request.auth != null && belongsToAnyWorkspace(userId);
}
function belongsToAnyWorkspace(userId) {
let memberWithUser = get(/databases/$(database)/documents/members/{document=**}).data;
return memberWithUser.userId == userId && existAuth(memberWithUser)
}
function existAuth(memWithUser){
let member = get(/databases/$(database)/documents/members/{document=**}).data;
return member.workspaceId == memWithUser.workspaceId
&& member.userId == request.auth.uid;
}
The result is that firestore blocks reading for all users. My impression is that the logic of my formulas is correct, but the syntax is flawed. For example, I don't think it's correct to use there wildcard {document=**} as a way to get "any document from the collection members". Any help is appreciated!

How to make a user read a collection of all documents where documents.uid == user.uid in firebase flutter

Basically I have 2 collections 'Bookings' and 'Users'. The 'Bookings' collection contains all bookings created by every user, and the 'Users' collection displays information about the user.
User: {
name:
uid:
}
Bookings: {
location:
time:
uid:
etc:
}
I have a GetBookings() function that retrieves the 'Bookings' collection and display it for an admin account. However, I am currently stuck on how to approach displaying a user his bookings.
getBookings() {
var bookings = FirebaseFirestore.instance.collection('bookings');
return bookings.get();
}
I thought about creating another 'Bookings' collection under each user but am unsure on how to link this new 'Bookings' collection with the previous collection in order to preserve the same bookings id. I had a go with security rules as mentioned by #Renaud Tarnec, however I might be getting the syntax wrong, or during looping through the bookings collection and receiving a permission denied on our request it preemptively stops my fetchBookings() function, or a user might be able to access the entire 'Bookings' collection regardless of whether each booking has his uid or not.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Allows users to view their bookings
match /bookings/{booking} {
allow read: if request.auth != null && request.auth.uid == booking.uid;
allow write: if true;
}
}
}
Future<List<BookingModel>> fetchBookings() async {
var bookings = await _bookingRepository.fetchAllBookings();
return bookings.map((snapshot) {
var bookingMap = snapshot.data();
return BookingModel(bookingMap['email'], bookingMap['location'], bookingMap['phoneNumber'],
bookingMap['dateTime'], bookingMap['uid'], bookingMap['dateCreated']);
}).toList();
}
I'd like to know what would be professional/industrially accepted way in tackling this problem.
Like I said, in my opinion, the best solution for you is to set correct rules in database and create correct queries to get that data.
Rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
match /bookings/{docId} {
allow read: if resource.data.uid == request.auth.uid || isAdmin()
// bellow you can use second part after && but im not sure are it will be null or unassigned this is overenginered so you can just not use condition after &&.
allow update: if resource.data.uid == request.auth.uid && request.resource.data.uid == null || isAdmin()
allow create: if request.auth != null && request.resource.data.uid == request.auth.uid || isAdmin()
allow delete: if isAdmin()
}
}
}
function isAdmin() {
return request.auth.token.admin == true;
}
Queries you need to make for users:
getBookings() {
// Im not sure are it will work like that in flutter im not a flutter programmer.
// You need to specify using where() method that you want documents with your uid or rules will not allow you to get eny data.
var bookings = FirebaseFirestore.instance.collection('bookings').where('uid', '==', user.uid);
return bookings.get();
}
It would be better if: While you adding the booking data to the "Booking" collection, you also need to add it also to the user.booking collection.
Since the bookings collection can only be accessed by an admin account, a classical solution in your case (denormalization in a NoSQL Database) is to use a Cloud Function to create the Booking document in the users/{userID}/bookings subcollection when a new Booking is created in the bookings collection.
Something along the following lines:
exports.duplicateBooking = functions
.firestore
.document('bookings/{docId}')
.onCreate((snap, context) => {
const userId = ....; // Not clear from your question how you define that. You should probably add it to the booking doc.
const bookingData = snap.data();
return admin
.firestore()
.collection(`users/${userId}/bookings)
.add({
'location': bookingData.location,
'time': bookingData.time,
'email': bookingData.email,
'phoneNumber': bookingData.phoneNumber
});
});
Another possibilities would be to keep a unique bookings collection with a set of Security Rules that allows a user to read his own bookings. In this case, remember that rules are not filters when you write the corresponding query.

Firestore security rules and Swift

I'm struggling with the Firestore security rules. This is the struct for my users collection and I also have structures for other collections: machines, logs, and photos. I want to set up the rule such that data can be accessed only when the request.auth.uid == user.user_UUID
I presume my syntax must not be correct in my rule because with what I have below, I'm not able to read or write any data after I log in with me app. thinking that maybe the brackets around the user_UUID were the problemI tried changing 'match users/{user_UUID}' to 'match users/user_UUID' but that didn't work. I also tried removing the 'match /{document=**} '
each of my collections have a user_UUID field and I want security to protect such that only the respective authenticated user can access that data.
import Foundation
struct User: Codable {
var email: String?
var userUUID: String?
}
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
match /users/{user_UUID} {
allow read, update, delete: if request.auth != null && request.auth.uid == user_UUID;
allow create: if request.auth != null;
}
}
}
}
I think I am seeing my problem. When I create a new authenticated user, in my user collection the UUID is being captured as a field and the documentID of the user itself is getting it's own identifier which I'm capturing separately in the user as property userDocumentID.
let db = Firestore.firestore()
let usersRef = db.collection("users")
let newUser = usersRef.document()
let docID = newUser.documentID ///*** THIS MUST BE WHERE PROBLEM LIES
let userData = [
//"date": "",
"user_UUID": result!.user.uid,
"userDocumentID": docID,
"nameLast": lastName,
"nameFirst": firstName,
"email": email,
"unlimited": false,
"password": password] as [String : Any]
newUser.setData(userData)
self.user_UUID = result!.user.uid
}
I've been doing more reading and am wondering if my database structure is inherently wrong. I have 4 different collections none of which are nested within the other. I am using a key value from each to link them together.
So I have machine.user_UUID to link the document to the correct record.
But I'm seeing that perhaps I should have a path such as user/machines
Could that be the source of my problems?

Query firestore in flutter: permission denied, what to do

I am trying to query some data from private devices. My rules are set as following:
match /private_devices/{device} {
function userHasKey() {
return request.auth != null && exists(/databases/$(database)/documents/users/$(request.auth.uid)/keys/$(device));
}
allow read: if (userHasKey())
}
My flutter code:
Stream<QuerySnapshot> getPrivateDevices(List<String> keyList) {
return private.where('UDID', whereIn: keyList).snapshots();
}
I use a list to import the keys from:
Stream<QuerySnapshot> getUserKeys(User user) {
return users.document(user.uid).collection('keys').snapshots();
}
And my user rules:
match /users/{userId} {
allow read, write: if (request.auth != null && request.auth.uid == userId)
}
match /users/{userId}/keys/{key} {
allow read, write: if (request.auth != null && request.auth.uid == userId)
}
Edit: my collection references:
final CollectionReference devices = Firestore.instance.collection("devices");
final CollectionReference users = Firestore.instance.collection("users");
final CollectionReference private = Firestore.instance.collection("private_devices");
I get a following permission error in my console:
Listen for Query(private_devices where UDID in [F8MXi2JzwYvIAoVRYG5f] order by __name__) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}
I/System.out(27625): com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.
I also tested my rules in the rules playground, and everything worked fine. I know it has to do with querying, but have no clue how to progress forward.
I have also noticed that when i try to get a single document with private.document(keyList[0]).get(), I actually get back the data.
Any help is welcome, thank you in advance.
Your rules don't allow the query because security rules are not filters. Be sure to read that documentation carefully, as well as this blog.
Security rules are not going to cross-reference another document for each document in the query result. That just doesn't scale in the way that Firestore requires. You can do that for individual document gets, but not for queries.
What you will have to do instead is put all of the data necessary for the filter into documents in a single collection, and make sure the client is applying a filter that matches only the documents they are allowed to read by the rule.

Firestore: How to set security on object types with users as field names

As I understand it, Firestore does not allow queries within fields of type array, which is a shame. Therefore, if you want to be able to query the contents of an array you have to set up a field as an object type and then set the fields like a map, this is called a nested map. I want to have a map where the key is the ID of another user. Therefore, the database structure is:
database
users
{userId}
friends
userId1: true
userId2: true
The 'userId1' and 'userId2' field names will vary depending on the userId of the person listed as a friend.
The question is, how do I write my security rule so I can find my documents (via my {userId}) and the documents of other users where my {userId} is a field in the 'friends' object of the other user's document?
I guess it needs to be something like..
match /users/{userId} {
allow read, update, delete: if resource.data.userId == request.auth.uid;
allow read: if resource.data.friends.{userId} == true;
}
But of course this does not work because you cannot seem to use the variable {userId} to name the field that you want to perform a test on. So, if this cannot be done, what is a way to search for documents and have my {userId} stored somehow in someone else's document?
Edit
Well, I think I have the rules determined (see below). However, when trying to test these rules I can't seem to write a Swift call to retrieve data based on that friends object. My Swift call is:
db.collection("users").whereField(FieldPath(["friends.\(userId)"]), isEqualTo: true)
So, my questions are:
Are the rules below correct?
How do I make a Swift call to find the people with a certain userId in the field name of an object type?
service cloud.firestore {
match /databases/{database}/documents {
match /users/{documentId} {
allow read, write: if isOwner();
allow read: if getFriend(request.auth.uid) == true;
function isOwner() {
return request.auth.uid == resource.auth.uid;
}
function getFriend(userId) {
return getUserData().friends[userId]
}
function getUserData() {
return get(/databases/$(database)/documents/rooms/{documentId}).data
}
}
}
}
I still have not resolved the problem of accessing fields in an object, but it is noted that my Security Rules where generally invalid. You cannot have multiple lines with the same rule type in it, you cannot have multiple lines with 'allow: read' for example. You must use && and ||. For example, the correct definition for the basic rules if you want to check two things are:
// Database rules
service cloud.firestore {
// Any Cloud Firestore database in the project.
match /databases/{database}/documents {
// Handle users
match /users/{documentId} {
// The owner can do anything, you can access public data
allow read: if (isOwner() && isEmailVerified()) || isPublic();
allow write: if isOwner() && isEmailVerified();
// Functions //
function isSignedIn() {
return request.auth != null;
}
function isOwner() {
return request.auth.uid == resource.data.userId;
}
function isPublic() {
return resource.data.userId == "public";
}
function isEmailVerified() {
return request.auth.token.email_verified
}
}
}
}