I'm implementing Firebase (firestore) into my nextjs adhd inventory app. I wanted to secure my database with security rules but I'm having a tough time getting them to work.
It is working in the rule simulation on the firebase dashboard, also working when I try to get a specific document by id, but it's giving me a general firebase error when trying to fetch with a filter. (VM21513 useFetchThing.ts:29 FirebaseError: Missing or insufficient permissions.
)
Note that I have two main collections :
In my React code, I am fetching the last thing a user created (pending = true, creator_uid=user uid), and I limit it to one document. I implemented security rules to prevent a user from accessing a thing if he is not the owner or a collaborator in the associated collection. Thus I have to fetch the said collection for every element.
const thingQuery = query(
collection(db, 'things').withConverter(thingConverter),
where('creator_uid', '==', user?.uid),
where('pending', '==', true),
orderBy('creation_date', 'desc'),
limit(1)
);
const [things, loading, error] = useCollectionData(thingQuery);
Here are the rules I'm using:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isSignedIn() {
return request.auth != null;
}
// return true if the request.auth.uid is in /collections/{collectionID}/collaborators/{collaboratorID}
function isCollaborator(collectionID) {
return exists(/databases/$(database)/documents/collections/$(collectionID)/collaborators/$(request.auth.uid));
}
function isEditor(collectionID) {
return get(/databases/$(database)/documents/collections/$(collectionID)/collaborators/$(request.auth.uid)).data.role == 'editor';
}
function isOwner(collectionID) {
return get(/databases/$(database)/documents/collections/$(collectionID)).data.owner_uid == request.auth.uid;
}
// Rules for Thing documents
match /things/{thingID} {
allow read: if isSignedIn()
&& (isOwner(resource.data.collection_id) || isCollaborator(resource.data.collection_id));
allow create: if isSignedIn()
&& (isOwner(resource.data.collection_id) || isEditor(resource.data.collection_id))
&& validateThingData(request.resource.data);
allow update: if isSignedIn()
&& (isOwner(resource.data.collection_id) || isEditor(resource.data.collection_id))
&& validateThingEdits(request.resource.data);
allow delete: if isSignedIn() && (isOwner(resource.data.collection_id) || isEditor(resource.data.collection_id));
function validateThingData(data) {
return data.keys().hasAll(['creator_uid', 'creation_date', 'collection_uid', 'pending'])
&& (data.creator_uid is string && data.creator_uid == request.auth.uid)
&& data.creation_date is timestamp
&& data.collection_id is string
&& data.pending is bool
&& (data.pending == true || data.pending == false)
&& (data.name is string && data.name.size() <= 32 || !('name' in data))
// && (data.pictures is list || !('pictures' in data))
&& (data.quantity is int || !('quantity' in data))
&& (data.origin is string && data.origin.size() <= 32 || !('origin' in data))
&& (data.date is timestamp || !('date' in data))
&& (data.price is float || !('price' in data))
&& (data.notes is string && data.notes.size() <= 140 || !('notes' in data))
&& (data.filtering_tag is string && data.filtering_tag.size() <= 10 || !('filtering_tag' in data));
}
function validateThingEdits(data) {
return (!data.keys().hasAny(['creator_uid', 'creation_date']))
&& data.collection_id is string
&& data.pending is bool
&& data.name is string && data.name.size() <= 32
// && (data.pictures is list || !('pictures' in data))
&& data.quantity is int
&& data.origin is string && data.origin.size() <= 32
&& data.date is timestamp
&& data.price is float
&& data.notes is string && data.notes.size() <= 140
&& data.filtering_tag is string && data.filtering_tag.size() <= 10;
}
}
// Rules for Collection documents
match /collections/{collectionID} {
allow read: if isSignedIn()
&& (isCollectionOwner(resource.data) || isCollaborator(collectionID));
allow create: if isSignedIn() && validateCollectionData(request.resource.data);
allow update: if isSignedIn()
&& isCollectionOwner(resource.data)
&& validateCollectionEdits(request.resource.data);
allow delete: if isSignedIn()
&& isCollectionOwner(resource.data);
function validateCollectionData(data) {
return data.keys().hasAll(['name', 'creation_date', 'owner_uid'])
&& data.name is string && data.name.size() <= 32
&& data.creation_date is timestamp
&& (data.owner_uid is string && data.owner_uid == request.auth.uid);
}
function validateCollectionEdits(data) {
return (!data.keys().hasAny(['owner_uid', 'creation_date']))
&& data.name is string && data.name.size() <= 32;
}
function isCollectionOwner(data) {
return data.owner_uid == request.auth.uid;
}
match /collaborators/{collaboratorID} {
allow read: if isSignedIn()
&& (isOwner(collectionID) || isCollaborator(collectionID));
allow create: if isSignedIn()
&& isOwner(collectionID)
&& validateCollaboratorData(request.resource.data);
allow update: if isSignedIn()
&& isOwner(collectionID)
&& validateCollaboratorData(request.resource.data);
allow delete: if isSignedIn()
&& isOwner(collectionID);
function validateCollaboratorData(data) {
return data.keys().hasAll(['uid', 'role'])
&& data.uid is string
&& data.role is string && (data.role == 'editor' || data.role == 'viewer');
}
}
}
}
}
Those are two separate collections at the same level because I want to be able to rapidly switch the collection_id in a thing to move it to another collection.
I tried many approaches for solving this problem, still getting the same VM21513 useFetchThing.ts:29 FirebaseError: Missing or insufficient permissions.
error.
I know that there are limits concerning the number of external document fetching I can do in the rules. firebase docs firestore limits
I also know that security rules are not handled in the same way if I query one specific document, or a query of one or more based on filters. bouncer reference as seen in this video from firebase
Firebase security rules don't actively filter data. Instead they check any operation you perform to ensure it only can every be accessing data that your rules allow.
In your case, your isCollaborator
, isEditor
and isOwner
functions all need to read a document from another collection to check whether the condition is met. For list
operations that'd mean they have to inspect every document, which is not scalable - so is not allowed.
So your read
rule may work for get
operations, but it won't work for list
calls.
In addition, you have a mistake in your isOwner
as that seems to try and read the entire collectionID
, which is not possible. And since this is a failure, it means your entire read
check also fails (rather than short circuiting the ||
operations).
To make this type of check work, all data that you want to secure and filter on (these always go hand in hand) has to be inside the documents that you're reading. Just as the server can't join data from other documents into the result, neither can security rules inspect such data for (potentially very large) list calls.