I recently started a firebase project, and I need some help with the security rules. When A user signs up, I create a new document in a collection called "Users". The document name is encrypted by a server, and can only be decrypted by that same server. The problem I am having now is that if a malicious entity wanted to, they could get all of the documents in the collection by changing client-side code, and that would defeat the whole purpose of encrypting the data. So my question is: Is there a way to enforce that somebody can only read the data of their document in the collection, and block attempts to read the whole collection? (I am using Firestore by the way.)
Thanks so much!
FireBase Rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
match /users/{userId} {
//signed in users can get individual documents
allow get: if request.auth.uid != null;
//no one can query the collection
allow list: if false;
allow read, write;
}
}
}
}
You're duplicating rules:
//signed in users can get individual documents
allow get: if request.auth.uid != null;
//no one can query the collection
allow list: if false;
allow read, write;
Since allow read is a combination of allow list and allow get, that last line make the two lines above it useless.
The minimum change is to remove read from the allows:
//signed in users can get individual documents
allow get: if request.auth.uid != null;
//no one can query the collection
allow list: if false;
allow write;
I suspect you'll want to tighten the allow write to only allow users to write their own document, but that's a separate problem.
Related
I am having an issue where I am trying to query a subquery by a field, and I have tried the emulator as well as firebase support (still on going, but not solutions yet).
When running the following query:
const queryByNumber = query(
collectionGroup(this.firestore, 'residents'),
where('cellNumber', '==', number)
);
return from(getDocs(queryByNumber));
This query has the error of:
Property cellNumber is undefined on object. for 'list' # L6
This is what the rules look like at the moment
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{path=**}/residents/{residentDoc} {
allow write: if resource.data.cellNumber == request.auth.token.phone_number;
allow read: if request.auth.token.phone_number == resource.data.cellNumber;
//allow read; //temp permission till support fix
}
match /Units/{unitNumber} {
allow read: if request.auth != null;
function residentDoc(residentId) {
return get(/databases/$(database)/documents/Units/$(unitNumber)/residents/$(residentId))
}
match /pets/{petId} {
allow write: if residentDoc(request.resource.data.residentId).data.cellNumber == request.auth.token.phone_number;
allow read: if request.auth != null;
}
}
}
}
And this is the firestore data structure at the moment:
I have tried to change my query to have the array-contains in the where clause, but that doesn't change much.
Note: the allow read without the if check allows the data to be retrieved, so the query does work, just the rules to secure it are not`
The problem is in this condition in your rules:
request.auth.token.phone_number in resource.data.cellNumber
The in operation in Firestore security rules is only defined for maps and lists/arrays, but your cellNumber field is a simple string value, which does not define an in operation as you can see here.
If you want to check whether the phone number in the token is the same as the value of the field, use == instead of in. If you want to test whether it is in the field, consider using the matches method on the string.
Also see:
Firebase firestore security rules allow if document ID contains string
Using contains() with firebase rules
The issue was another query trying to get all resident data after the initial one was fired, which caused it to fail the rule because the second one wasn't querying by cellNumber anymore. I have changed the rules to validate by UID since that will always be provided
I am using Firebase Firestore to store a list of transactions in a collection called transactions .
I use react to get the transaction from the collection, using a URL with the id of the transaction document: http://myurl.com/h1kj54h2jk35h
const id = match.params.id;
firebase.firestore().collection('transactions').doc(id).get()
The same way I create a new doc. I have not firebase authentication.
How can I secure my Firestore rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /transactions/{id} {
allow read, write;
}
}
}
If I don't allow write, I can't create new transactions.
If I don't allow read, I can't read the transaction, but I don't want to allow the read of all transactions. Only the once when the id from the URL is valid.
Thus, I am looking for a way to protect my database agains unwanted document creations and unwanted document reads.
I think you're looking for what are called granular operations. From that link:
In some situations, it's useful to break down read and write into more granular operations. For example, your app may want to enforce different conditions on document creation than on document deletion. Or you may want to allow single document reads but deny large queries.
A read rule can be broken into get and list, while a write rule can be broken into create, update, and delete.
So if you want to only allow creation of new documents, and getting of document for which a user must know the ID, that'd be:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /transactions/{id} {
allow create, get;
}
}
}
I have an app that is designed so authenticated users via Google only have access to their own data with no "social" features. I want to know the security rules for the below criteria.
Let's say I have 5 collections and one of them is called "todos" and the data mirrors the other collections in that it has a field for the authenticated users uid. The typical document looks something like this:
Todos
todo:{
title:"some titled",
body:"we are the world , we are the children",
uid:"2378y4c2378rdt2387btyc23r7y"
}
Some other collection
thing:{
name:"some name",
content:"Some content",
whatever:"whu-eva",
uid:"2378y4c2378rdt2387btyc23r7y"
}
I want the authenticated Google user to be able to CRUD any data that has said users uid in the uid field. I want all other data to be inaccessible to the logged in user.
I want to know how to create rules for this scenario.
I'm mulling through the documentation now but I figure I might be able to save some time by asking.
I do not have specific roles for the app.
https://firebase.google.com/docs/firestore/solutions/role-based-access
As a side note, is their a feature in Firebase to automatically bind an authenticated Google users uid to documents created while they are logged in? (I am assuming the answer is no and I was planning on manually grabbing the uid in my app and setting it on the client prior to document creation).
Thank you.
Update
I tried using the code that Klugjo posted below.
When I try to test it in the simulator I get an error.
Here is my collection and a screenshot of the error.
Here is something else I tried:
Based on everything I've read it seems like the following code should work - but it doesn't. I've supplemented the key "userId" in place of " uid" that is written in the object data at the top of this post. I changed the key to distinguish it from the uid.
service cloud.firestore {
match /databases/{database}/documents {
match /todos/{id} {
allow read: if request.auth.uid == request.resource.data.userId;
allow create, update, delete:
if request.resource.data.userId == request.auth.uid;
}
}
}
I've created a video where I try to GET and CREATE a document.
I don't think I am using the testing feature correctly.
Video
https://www.youtube.com/watch?v=W7GZNxmBCBo&feature=youtu.be
EDIT
I have it working when I test with a hard-coded request.auth.uid.
In the image below I hardcoded "test" as the request.auth.uid.
My problem now is that I would really like to know how to test it in the rules editor without hard-coding this information.
Edit
Here is a video demo of the problem using a real app.
https://www.youtube.com/watch?v=J8qctcpKd4Y&feature=youtu.be
Here is a sample secure rule set for your requirements.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{id}/{u=**} {
allow read, write: if (isSignedIn() && isUser(id));
}
match /todos/{id}/{t=**} {
allow read, write: if (isSignedIn() && isUserOwner());
}
match /{document=**} {
allow read, write: if false;
}
function isSignedIn() {
return request.auth != null;
}
function isUser(uid) {
return uid == request.auth.uid;
}
function isUserOwner() {
return getResourceData().uid == request.auth.uid;
}
function getResourceData() {
return resource == null ? request.resource.data : resource.data
}
}
}
All documents are publicly inaccessible.
The rests will be decided based on the data already saved in DB and / or the data being sent by the user. The key point is resource only exists when reading from DB and request.resource only exists when writing to DB (reading from the user).
Documents under todos can be read and written only if they have a saved uid which is the same as the sent request's uid.
Documents under users can be read and written only if their document id is the same as the sent request's uid.
isSignedIn() function checks if request is authorised.
isUser(id) function checks if id matches the authorised request's uid.
isUserOwner() function checks if document's uid matches the authorised request's uid.
I think what you are looking for is the "resource" parameter in the security rules: https://firebase.google.com/docs/firestore/security/rules-conditions#data_validation
Try something like:
service cloud.firestore {
match /databases/{database}/documents {
match /todos/{id} {
allow read, write: if request.auth.uid == resource.data.userId;
}
}
}
EDIT:
Subcollection strategy
If you change your DB to look like the following:
/users/{userId}/todos/**
then you could allow users to read/write anything under their own document with the following rule:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{uid}/{doc=**} {
allow read, write: if request.auth != null && request.auth.uid == uid;
}
}
}
This would have the advantage of not needing to introspect the contents of the data which I believe might count against your read quota.
You are looking for something like this
service.cloud.firestore {
match /databases/{database}/documents {
match /todos/{userId} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
}
}
}
match /todos/{userId} makes the userId variable available in the rule condition
request.auth.uid matches the auth'd user uid
I volunteered to make a class blog for my English class where everyone can make an account and post stuff. I used Google firebase for this, the Authentication and Firestore. Anyone can sign up and post their thing. Everything works fine except for the database security rules, right now, it's on test mode so anyone can do anything to the data.
The structure of it is:
/users/{Authentication UID}:
- joined
- name
- uid (this is a token generated from javascript used for the profile page and others)
/posts/{PID}:
- date
- pid
- post
- title
- uid
/comments/{PID}:
- comment
- date
- pid
- uid
To clear up some things: there are two uids, one as the document name which is from the Authentication and another which is a token generated from JavaScript used for the posts, comments and profile page.
All I ask for is one simple thing. What rules should I use to secure the data? I had a look at the firebase docs but ended up with no luck.
EDIT 1: Changed the accepted answer's rules a bit and got it working (I think):
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
}
match /users/{userId} {
allow write: if request.auth.uid == userId;
}
match /posts/{postId} {
allow create: if request.auth.uid != null;
allow update, delete: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.uid == resource.data.uid;
}
match /comments/{commentId} {
allow create: if request.auth.uid != null;
allow update, delete: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.uid == resource.data.uid;
}
}
}
Check out the following rules you can use for your firestore database
service cloud.firestore {
match /databases/{database}/documents {
//create document id with users UID assigned by firestore, while creating a users document, this rules allows users to read and write only their data
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
//post id is random id generated by firebase
match /posts/{postId} {
//allows authenticated users to create or read posts
allow read, create: if request.auth.uid != null;
//allows users to update or delete only their posts.
allow update, delete: if get(/databases/$(database)/documents/posts/$(request.auth.uid)).data.uid == request.auth.uid;
}
//comment id is random id generated by firebase
match /comments/{commentId} {
//allows authenticated users to create or read comments
allow read, create: if request.auth.uid != null;
//allows users to update or delete only their comments.
allow update, delete: if get(/databases/$(database)/documents/posts/$(request.auth.uid)).data.uid == request.auth.uid;
}
}
}
I am using Firebase Cloud Firestore, and I want to modify my rules to restrict users from querying a collection.
This should not be allowed:
firestore().collection("users").get()
But this should be allowed:
firestore().collection("users").doc("someUserId").get()
Currently, my rules look like this:
match /users/{userId} {
allow read;
}
but this rule allows the "users" collection to be queried.
How can I allow single document gets, but not collection queries?
You can break read rules into get and list. Rules for get apply to requests for single documents, and rules for list apply to queries and requests for collections (docs).
match /users/{userId} {
//signed in users can get individual documents
allow get: if request.auth.uid != null;
//no one can query the collection
allow list: if false;
}
Just allow get and you'll be good:
match /users/{userId} {
allow get;
}
Reference: https://firebase.google.com/docs/rules/rules-language#:~:text=Convenience%20methods-,read,-Any%20type%20of