was working well but FirebaseException ([cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.) - flutter

I have been working on the Flutter app with firebase and the app was working well but today when I trying to retrieve the data from using snapshot I got this exception.
FirebaseException ([cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.)
is there any update on firebase i have to do or what ?

When you create a project and set Firestore access it test mode, it sets the database up to allow public access for only a month. If this suddenly happened without a change on your side, it could be that your security rules expired.
Now would be a good moment to implement proper security rules for your data, as leaving all data publicly accessible is a recipe for future problems.
So learn how to secure the data, have a look at the documentation on security rules, this more technical documentation, and also see:
Firestore Permission Denied in Android
Email: [Firebase] Client access to your Cloud Firestore database expiring in X day(s)

Related

Flutter App: Firebase Credentials viewable in Source Code (apk / web) = unsecure database? [duplicate]

The Firebase Web-App guide states I should put the given apiKey in my Html to initialize Firebase:
// TODO: Replace with your project's customized code snippet
<script src="https://www.gstatic.com/firebasejs/3.0.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket>'
};
firebase.initializeApp(config);
</script>
By doing so, the apiKey is exposed to every visitor.
What is the purpose of that key and is it really meant to be public?
The apiKey in this configuration snippet just identifies your Firebase project on the Google servers. It is not a security risk for someone to know it. In fact, it is necessary for them to know it, in order for them to interact with your Firebase project. This same configuration data is also included in every iOS and Android app that uses Firebase as its backend.
In that sense it is very similar to the database URL that identifies the back-end database associated with your project in the same snippet: https://<app-id>.firebaseio.com. See this question on why this is not a security risk: How to restrict Firebase data modification?, including the use of Firebase's server side security rules to ensure only authorized users can access the backend services.
If you want to learn how to secure all data access to your Firebase backend services is authorized, read up on the documentation on Firebase security rules. These rules control access to file storage and database access, and are enforced on the Firebase servers. So no matter if it's your code, or somebody else's code that uses you configuration data, it can only do what the security rules allow it to do.
For another explanation of what Firebase uses these values for, and for which of them you can set quotas, see the Firebase documentation on using and managing API keys.
If you'd like to reduce the risk of committing this configuration data to version control, consider using the SDK auto-configuration of Firebase Hosting. While the keys will still end up in the browser in the same format, they won't be hard-coded into your code anymore with that.
Update (May 2021): Thanks to the new feature called Firebase App Check, it is now actually possible to limit access to the backend services in your Firebase project to only those coming from iOS, Android and Web apps that are registered in that specific project.
You'll typically want to combine this with the user authentication based security described above, so that you have another shield against abusive users that do use your app.
By combining App Check with security rules you have both broad protection against abuse, and fine gained control over what data each user can access, while still allowing direct access to the database from your client-side application code.
Building on the answers of prufrofro and Frank van Puffelen here, I put together this setup that doesn't prevent scraping, but can make it slightly harder to use your API key.
Warning: To get your data, even with this method, one can for example simply open the JS console in Chrome and type:
firebase.database().ref("/get/all/the/data").once("value", function (data) {
console.log(data.val());
});
Only the database security rules can protect your data.
Nevertheless, I restricted my production API key use to my domain name like this:
https://console.developers.google.com/apis
Select your Firebase project
Credentials
Under API keys, pick your Browser key. It should look like this: "Browser key (auto created by Google Service)"
In "Accept requests from these
HTTP referrers (web sites)", add the URL of your app (exemple: projectname.firebaseapp.com/* )
Now the app will only work on this specific domain name. So I created another API Key that will be private for localhost developement.
Click Create credentials > API Key
By default, as mentioned by Emmanuel Campos, Firebase only whitelists localhost and your Firebase hosting domain.
In order to make sure I don't publish the wrong API key by mistake, I use one of the following methods to automatically use the more restricted one in production.
Setup for Create-React-App
In /env.development:
REACT_APP_API_KEY=###dev-key###
In /env.production:
REACT_APP_API_KEY=###public-key###
In /src/index.js
const firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,
// ...
};
I am not convinced to expose security/config keys to client. I would not call it secure, not because some one can steal all private information from first day, because someone can make excessive request, and drain your quota and make you owe to Google a lot of money.
You need to think about many concepts from restricting people not to access where they are not supposed to be, DOS attacks etc.
I would more prefer the client first will hit to your web server, there you put what ever first hand firewall, captcha , cloudflare, custom security in between the client and server, or between server and firebase and you are good to go. At least you can first stop suspect activity before it reaches to firebase. You will have much more flexibility.
I only see one good usage scenario for using client based config for internal usages. For example, you have internal domain, and you are pretty sure outsiders cannot access there, so you can setup environment like browser -> firebase type.
The API key exposure creates a vulnerability when user/password sign up is enabled. There is an open API endpoint that takes the API key and allows anyone to create a new user account. They then can use this new account to log in to your Firebase Auth protected app or use the SDK to auth with user/pass and run queries.
I've reported this to Google but they say it's working as intended.
If you can't disable user/password accounts you should do the following:
Create a cloud function to auto disable new users onCreate and create a new DB entry to manage their access.
Ex: MyUsers/{userId}/Access: 0
exports.addUser = functions.auth.user().onCreate(onAddUser);
exports.deleteUser = functions.auth.user().onDelete(onDeleteUser);
Update your rules to only allow reads for users with access > 1.
On the off chance the listener function doesn't disable the account fast enough then the read rules will prevent them from reading any data.
I believe once database rules are written accurately, it will be enough to protect your data. Moreover, there are guidelines that one can follow to structure your database accordingly. For example, making a UID node under users, and putting all under information under it. After that, you will need to implement a simple database rule as below
"rules": {
"users": {
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid"
}
}
}
}
No other user will be able to read other users' data, moreover, domain policy will restrict requests coming from other domains.
One can read more about it on
Firebase Security rules
While the original question was answered (that the api key can be exposed - the protection of the data must be set from the DB rulles), I was also looking for a solution to restrict the access to specific parts of the DB.
So after reading this and some personal research about the possibilities, I came up with a slightly different approach to restrict data usage for unauthorised users:
I save my users in my DB too, under the same uid (and save the profile data in there). So i just set the db rules like this:
".read": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()",
".write": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()"
This way only a previous saved user can add new users in the DB so there is no way anyone without an account can do operations on DB.
Also adding new users is posible only if the user has a special role and edit only by admin or by that user itself (something like this):
"userdata": {
"$userId": {
".write": "$userId === auth.uid || root.child('/userdata/'+auth.uid+'/userRole').val() === 'superadmin'",
...
EXPOSURE OF API KEYS ISN'T A SECURITY RISK BUT ANYONE CAN PUT YOUR CREDENTIALS ON THEIR SITE.
Open api keys leads to attacks that can use a lot resources at firebase that will definitely cost your hard money.
You can always restrict you firebase project keys to domains / IP's.
https://console.cloud.google.com/apis/credentials/key
select your project Id and key and restrict it to Your Android/iOs/web App.
It is oky to include them, and special care is required only for Firebase ML or when using Firebase Authentication
API keys for Firebase are different from typical API keys:
Unlike how API keys are typically used, API keys for Firebase services are not used to control access to backend resources; that can only be done with Firebase Security Rules. Usually, you need to fastidiously guard API keys (for example, by using a vault service or setting the keys as environment variables); however, API keys for Firebase services are ok to include in code or checked-in config files.
Although API keys for Firebase services are safe to include in code, there are a few specific cases when you should enforce limits for your API key; for example, if you're using Firebase ML or using Firebase Authentication with the email/password sign-in method. Learn more about these cases later on this page.
For more informations, check the offical docs
I am making a blog website on github pages. I got an idea to embbed comments in the end of every blog page. I understand how firebase get and gives you data.
I have tested many times with project and even using console. I am totally disagree the saying vlit is vulnerable.
Believe me there is no issue of showing your api key publically if you have followed privacy steps recommend by firebase.
Go to https://console.developers.google.com/apis
and perfrom a security steup.
You should not expose this info. in public, specially api keys.
It may lead to a privacy leak.
Before making the website public you should hide it. You can do it in 2 or more ways
Complex coding/hiding
Simply put firebase SDK codes at bottom of your website or app thus firebase automatically does all works. you don't need to put API keys anywhere

How to prevent a user from changing the app code in order to write data to Firestore?

In my app users can read and write data on Firestore.
In the Firestore Database there Is also a "Credit" document for each user where the balance of coins Is stored.
How can I be sure that no One could modify an APK of the app in order to change the balance?
In the app there are some functions that remove some coins from the balance, my fear Is that someone could change the code and add coins instead.
assuming that your app implements firebase authentication to authenticate operations on firestore it's safe to say that your app is compiled with a key and it has an hash.. it's not possible to someone to decompile the app, change the code and recompile it with your key.. so the new "hacked" app will have a different key and hash and firebase authentication will not work and your db will be safe
I think you need to secure the data itself. In your scenario I don't think you can have code in the app that simply writes a value to the balance. You need to create a separate API or firebase function to secure what you are trying to do.
If you want to ensure that only your application code can call Firestore, consider enabling Firebase App Check.
Just keep in mind that:
Using App Check does not guarantee the elimination of all abuse
So you'll want to combine it with other security measures, for example through the server-side security rules that Firebase also offers for Firestore.
Also see:
Locking down Firebase DB access to specific apps
How to allow only my app to access firebase without a login?

Custom Rest API And Firestore Database

I have been following a tutorial showing how to build a custom Rest API in Javascript which is then deployed to Firebase Functions which can then be used to communicate with a Firestore Database.
Everything appears to be working fine but one thing is bothering me.
One of my end points is url-to-api/read which fetches all the records in the database.
How can I prevent anyone from simply adding that url into a browser and reading all the data.
I have tried various Firestore rules but none seem to make any difference, adding /read on to the end of the API URL still shows all the data in the browser.
Cloud Functions access Firebase using the Admin SDK, which means they bypass the security rules and have unrestricted access to the database.
It is up to you to protect what users can do in this case. For example, you can require that they pass their ID token along, and use that to determine their authorization as shown in these examples of implementing an authorized HTTP endpoint and implementing an authorized JSON API.

How to have your app work offline from the start

I am looking for examples/tutorials or an explanation of how I can use my app that has both Firebase Authentication and the Firestore cloud database. I think I understand how to setup offline persistence with the Firestore db, and I think that means that data will be persisted while my app is running and should connection be lost.
What if a user jumps on a a plane with zero connection and wants to run my app and is first presented with the login screen for Authentication. Can you point to an example or tutorial on the best way to setup this so that the app can still run from the beginning with no connectivity and then be able to authenticate and put the data in the Firestore cloud database when connectivity is gained?
Thank you.
According to the official Firebase documentation:
If your app uses Firebase Authentication, the Firebase Realtime
Database client persists the user's authentication token across app
restarts. If the auth token expires while your app is offline, the
client pauses write operations until your app re-authenticates the
user, otherwise the write operations might fail due to security rules.
EDIT:
You can achieve that with Cloud Firestore by enabling offline persistence:
Cloud Firestore supports offline data persistence. This feature caches
a copy of the Cloud Firestore data that your app is actively using, so
your app can access the data when the device is offline. You can
write, read, listen to, and query the cached data. When the device
comes back online, Cloud Firestore synchronizes any local changes made
by your app to the Cloud Firestore backend.
Note that you won't need to make any changes to the code that you use to access Cloud Firestore data.
Here you can see some examples for configuring the offline persistence.

Is it possible to access Firebase data before creating a new user? (Swift)

Before creating my new user, I would like to check Firebase to see if the username already exists in the database. I would like to do this right after the user has finished editing the username textfield (the rest of my form will not be complete). I've attempted to access the Firebase DB, but I get the warning "Listener at /Users failed: permission_denied". From what I understand, in order to read/write to/from the Firebase DB the user must be authenticated, and obviously a user signing up isn't authenticated before they've signed up. Is there any way to access the database before running the createUserWithEmail:password:completion: method?
To be clear, let me say up front that I do NOT recommend you do this for your use case. But in general, you can allow unauthenticated users to access parts of the database by setting your security rules for that path to true:
{
"rules": {
".read": true,
".write": true
}
}
You would not want to do something like this because you don't want to give the public access to everyone's usernames.
Instead, I'd recommend using Cloud Functions for Firebase. You can create a Cloud Function that is triggered when a user chooses a username, perhaps by creating a temporary path in the database and using a database trigger. Now if you're not familiar with Cloud Functions or Node.js, there will be a lot of new information to learn up front, but you will discover that there are many use cases for Functions, so it's worth learning.
Here are some resources to check out:
Get Started
Cloud Functions Database Triggers
Cloud Functions Documentation