Data fails to load due to permissions but only initially - firebase

What's happening is that usually the first time I authenticate a user after enough time has passed that the session has expired my requests for data that the user should have access to are denied. The requests will start working eventually with no actual rules or code changing. It can take from 2 to 10 minutes but will eventually right itself.
I don't have hard data on this; it's just something I've observed.
I have no idea what I can do about this. Is anyone else seeing this? Is this a known bug? I've search but haven't found any other accounts of this happening.
Thanks.
here are the rules:
{
"rules": {
"users": {
"$user": {
".read" :"$user == auth.id || data.child('email').val() == auth.email",
".write":"$user == auth.id"
}
},
"todos":{
"$list":{
".read":"data.child('members').hasChild(auth.id)",
".write":"newData.child('members').hasChild(auth.id)"
}
}
}
}

By default, your auth tokens live for 24 hours, so if you're seeing security errors before then, it's probably not related to your session. To verify this, you can attach a callback to tell you when your session has expired. See:
https://www.firebase.com/docs/javascript/firebase/auth.html
I suspect what's going on here is simply that the data your rules are depending on is changing and causing writes to succeed some times, and fail others. This is the intended behavior of Security Rules in Firebase. For example, if someone was added / removed from /todos/blah/members/ it would affect your ability to read at /todos/blah
One odd thing about your rules is that you appear to be allowing anyone to write to /todos/$list as long as the data they are writing contains a member list that contains the writer's user id. I suspect this is not your intended behavior. Perhaps you meant to make the write rules depend on the data that was already in Firebase rather than new data?

Related

Why is this Cloud Firestore security rule suddenly failing?

For some time I was using the following rule for Cloud Firestore in my Flutter project:
"You can see chats if you're logged in, a member and the chat was not flagged".
match /chats/{chatId} {
allow read: if signedIn() && request.auth.uid in resource.data.members && resource.data.flagged == false;
}
It used to work and to me, it seems correct. But recently, it started to fail. When I use only
allow read: if signedIn();
It works just fine. Any idea what might be the problem? In the Firebase emulator, I can see it also fails, but there is no explanation. Obviously, members and flagged fields exist (when a chat document is available).
Could this have happened after updating a particular package, like cloud_firestore?
Any ideas?
I found out, finally, what was wrong. According to this page, "the result set should satisfy the rule's condition". However, I thought my query was exactly the same as my rule and I didn't know what was wrong.
It turns out, this is taken quite literally.
In my query I had:
where('flagged', isNotEqualTo: true) and my rule was flagged == false. I needed to change that to flagged != true. This is very confusing. It seems like a bug to me, and otherwise, I would be very curious to know the reason behind this.

Unable to base security rule condition on resource data in Firebase

I am attempting very simple thing and that is matching request.auth.uid to a field value in my transaction documents (like this resource.data.useruid) in Firebase security rule in order to get transactions of a particular logged in user. However, I don't get any documents while querying for them and get an error instead.
This is how the collection looks like - just one document there with useruid field.
The field's value is mapped to the users uid (screenshot taken in the Authentication -> Users tab.
And the rule looks like this
I should get the one document back but every time I query the documents with that user logged in (I am using angularfire2 for those purposes) I get Error: Missing or insufficient permissions.
If I modify the rule condition to return always true or if I only check for truthiness of request.auth.uid I get the query result alright. The funny thing though is that with resource.data involved - eg. checking for value of the amount field in the firebase rule - the condition is never met. I tried to write it like
allow read, write: if resource.data.amount == 3
and got the error again. Seems like I don't get the resource.data Map at all.
I feel like I am missing something obvious, although after reading the guides, it seems alright to me and I am already out of ideas. The debugging capabilities (or lack of) make the whole process very slow.
Could you please explain to me, why I don't get the resource.data Map in the firebase security rule or point me to a place where the problem might be?
You have most probably missed one specific point in the doc: your query fails "because it does not include the same constraints as your security rules". See https://firebase.google.com/docs/firestore/security/rules-query#secure_and_query_documents_based_on_authuid
The following, with your security rules works perfectly:
firebase.auth().signInWithEmailAndPassword("xxxx#xxxx.com", "xxxxx")
.then(function (info) {
db.collection("transactions").where("userid", "==", info.uid).get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
});
});
If you remove the where clause, you get the exact error you are getting

Firebase database rules – `data.exists()` always seems to be true, possible bug?

I am trying to secure my firebase database to allow the creation of new records, but not allow the deletion of existing records. Ultimately, I plan to utilise Firebase authentication in my app as well, and allow users to update existing records if they are the author, but I am trying to get the simple case working first.
However! No matter what I try in the database rules simulator, despite what the documentation seems to suggest, the value of data.exists() seems to always be true. From what I what I can understand from the documentation, the variable data represents a record in the database as it did before an operation took-place. That is to say, for creates, data would not exist, and for updates/deletes, data would refer to a real record that exists in the database. This does not seem to be the case, to the point where I am actually suspecting a bug in Firebase, as when setting the following rules on my database, all write operations are disallowed:
{
"rules": {
".read": true,
".write": "!data.exists()"
}
}
No matter what values I put into the simulator, be it Location or Data. I have even written a small EmberJS app to verify if the Simulator is telling the truth and it too, is denied permission for all write operations.
I really have no idea where to go from here as I am pretty much out of things to try. I tried deleting all records from my database, which lets the simulator think it can perform write operations, but my test app still gets PERMISSION_DENIED, so I don't know what's causing inconsistencies there.
Is my understanding of the predefined data variable correct? If so, why can't I write the rules I want? I have seen snippets literally trying to achieve my "create only, no-delete" rule that seem to line up with my understanding.
Last note: I am trying this in a totally new Firebase project with JUST the rules above, and only ~a few records of junk data laying around my database.
Because you have placed the !data.exists() at the root location of your database, data refers to the entire database. You will only be able to write to the database when it is completely empty.
You indicate that you run your tests with only a few records of junk data laying around my database. Those records will cause data.exists() to be true.
You can achieve your goal by placing the !data.exists() rule in your tree at the specific location where you want to require that no data already exists. This is typically done at a location with a wildcard key, as in the example you linked:
{
"rules": {
// default rules are false if not specified
"posts": {
".read": true, // everyone can read all posts
"$postId": {
// a new post can be created if it does not exist
// existing posts can only be edited by their original "author"
".write": "!data.exists() && newData.exists() || data.child('author').val() == auth.uid",
".validate": "newData.hasChildren(['title', 'author', 'timestamp'])",
}
}
}
}

How to create time-expiring data with Firebase Rules?

This talk mentions time-expiring data using Firebase rules at 22:55
https://www.youtube.com/watch?v=PUBnlbjZFAI
How can one do this ?
I didn't find any information regarding this.
I recommend two solutions.
1) Use cloud functions to record a message path and the date it was posted. Then every hour sort that list by date, pick all the expired ones, and create a deep update object to null out every expired message. Nowadays you can use Cron Scheduler to handle the periodic flush.
2) Make a rule that says anyone can delete expired messages and make it so that clients automatically delete expired messages when they are in a chat room.
Written here: https://firebase.google.com/docs/database/security/securing-data
You can't have it auto delete your data but you can make them unreadable (which is the same thing from the user standpoint). Just send a timestamp child field with you data and check against it.
{
"rules": {
"messages": {
"$message": {
// only messages from the last ten minutes can be read
".read": "data.child('timestamp').val() > (now - 600000)",
// new messages must have a string content and a number timestamp
".validate": "newData.hasChildren(['content', 'timestamp']) && newData.child('content').isString() && newData.child('timestamp').isNumber()"
}
}
}
}
Same question here.
You can't do it using firebase rules. You should either have a NodeJS backend removing your old data or clients doing it for you. For example, before a client retrieves data, he could remove old data.

firebase rules not working

I'm following the Firebase security tutorial.
I have this simple structure:
- requests
- request_id: {...}
- request_id: {...}
...
And my security rules:
{
"rules": {
"requests": {
".indexOn": ["id_company_owner", "id_app_user"],
"$request_id": {
// only request from the last ten minutes can be read
".read": "data.child('timestamp').val() > (now - 600000)",
}
}
}
}
All I want right now with my rule is to make my request readable. But I've to this inside (not outside) of $request_id, but no request is being readable; even if the request have the timestamp with less than 10 minutes ago. Can someone explain why?
It's hard to tell without looking at the actual data, but Firebase security rules are all-or-nothing. Firebase security rules do not filter data.
That is, if you attempted to attach a listener to /requests, and even a single item is not allowed to be read due to a security rule, none of them can be read. You'll need to listen for individual items, or restructure your data, to accomplish this "filtering" behavior.

Resources