Restrict access in firebase - firebase

I am making a web app using firebase. I was looking into restricting access to certain pages unless there's a subscription. When I looked through the docs all I found was that I could do transactions with stripe and it only applied on signing in and up not restricting pages.
After searching on the internet, I didn't find a viable solution, but three ideas came up to me I could use (which are either with low working possibility or very lackluster to say the least. (all include using stripe.))
One: I would use a middleware to verify the token I get from stripe and then redirect from there. (but all that comes to my mind how I would identify the redirected page in the middleware. And even if that was probable how much time would that take to make it work(if that even is possible), I have no idea.)
Two: in hosting configurations I could call a function when a rewrite is performed. I thought I could call a make a function that verifies the token from the strip when a restricted page is called. (But then again not only is the function accessible after hosting and can be viewed, I don't know if I can call firebase configurations and functions inside the firebase.json.)
third: this is the most viable but has very bad downsides, is authenticating the strip token from in a regular javascript, and if it fails it would restrict the access to the page. Do the same in the rules so that the database section related to that page. (the downside is that the HTML, CSS, and javascript would all be accessible. Only the database functions relating to them are restricted.
So with all that being said, I couldn't find any viable option I could use. So I was wondering if anyone in here have met the same problem and got a solution or do you have any advice I could use.
Note: I am using firebase's realtime database by the way.

If you are trying to restrict access to your webpages/app, you should come up with a logic in your backend or frontend (depending on your app structure) where you could store values needed in Firestore or another solution.
In case you would like to restrict access to Firestore, you can achieve that with Rules.

Related

Cloud Functions, Cloud Firestore, Cloud Storage: How to protect against bots?

I already use ReCAPTCHA for Android apps client-side (I've also implemented, of course, its server-side verification).
However, this ReCAPTCHA is implemented only in one activity. But, of course, hackers can modify the app. For example:
they can simply remove ReCAPTCHA from all activities,
or start another activity that would not have ReCAPTCHA implemented; it's the case btw: I didn't implement ReCAPTCHA in each activity because it's useless according to the first problem I've just mentioned.
So I would want to detect bot and spam requests in Cloud Functions, then in Cloud Firestore, then in Cloud Storage, for the following accesses: read, write, function call. It'd allow me to prevent unwanted contents from being saved in Firestore for example (spamming messages, etc.), and to avoid overreaching my monthly billing quota (because of spam requests to Firestore for example).
Is it possible? How?
There is no "spam detection" for these products. Your security rules will determine who can access what data. If you don't have security rules in place, and allow public access, then anyone will be able to get that data, and you will be charged for it when that happens. This is the nature of publicly accessible cloud services.
If you want more control over the data in these products, you could stop all direct public access with security rules, and force clients to go through a backend you control. The backend could try to apply some logic to determine if it's "spam", by whatever criteria you determine. There is no simple algorithm for this - you will need to define what "spam" means, and reject the request if it meets you criteria.
Google does have some amount of abuse detection for its cloud products, but it will likely take a lot of abuse to trigger an alert. If you suspect abusive behavior, be sure to collect information and send that to Firebase support for assistance.
Just thought I'd add that there is another way to restrict access to Cloud Functions.
Doug already described Way 1, where you write the access logic within the cloud function. In that case, the function still gets invoked, but which code path is taken is up to your logic.
Way 2 is that you can set a function to be "private" so that it can't be invoked except by registered users (you decide on permissions). In this case, unauthenticated requests are denied and the function is not invoked at all.
Way 2 works because every Firebase project is also a Google Cloud Platform project, and GCP offers this functionality. Here are the relevant references to (a) Configuring functions as public/private, and then (b) authenticating end-users to your functions.

Firebase Cloud Functions Secure HTTPS Endpoints with API key

I've looked at a few places, Including this post and the firebase panel
Is there no way to use these api's to secure these endpoints using an api key you create per client who uses your cloud functions?
I'm able to block every one putting a restriction on the Browser key, but I would like to create a new api key, and use that as a way to authenticate my endpoint for various clients.
Creating a new api key, and using that as a parameter in my query doesn't work (don't now if I'm doing anything wrong)
Is there a way to do this?
Option 1: handle authentication within the function
https://github.com/firebase/functions-samples/tree/master/authorized-https-endpoint
Adapt above to use clients/keys stored in firestore
Option 2: Use an an API Gateway
Google Cloud Endpoints (no direct support for functions yet, need to implement a proxy)
Apigee (higher cost, perhaps more than you need)
Azure API Management (lower entry cost + easy to implement as a facade for services hosted outside Azure)
there are more..
The above gateways are probably best for your use case in that the first two would let you keep everything within Google, albeit with more complexity/cost -- hopefully Endpoints will get support for functions soon. Azure would mean having part of your architecture outside Google, but looks like an easy way to achieve what your after (api key per client for your google cloud / firebase functions)
Here's a good walkthrough of implementing Azure API Management:
https://koukia.ca/a-microservices-implementation-journey-part-4-9c19a16385e9
Not to achieve what you are after, as far as firebase and GCP is concerned your clients is your specific business problem.
One way you could tackle this (with the little information that is provided);
You need somewhere to store a list of clients + their API key (I would use firestore)
For the endpoints you want to secure with a client-specific API key you can include a check to confirm the header exists and also exists in your firestore client record.
Considerations:
Depending on your expected traffic loads and the the number of firestore reads you'll be adding, you might want to double check this kind of solution will work for your budget.
Is the API-key type solution the only option you must go for? You Could probably get pretty far using the https://github.com/firebase/firebaseui-web and doing user checks in your function with no extra DB read required. If you go down this path most of the user signup/ emails / account creation logic is ready to go.
https://firebase.google.com/docs/auth/web/password-auth#before_you_begin
Curious to see what some other firebase users suggest.

Understanding the Firebase and purpose of google cloud functions

Let's say I'm developing app like Instagram: for iOS, Android and Web. I decided to use Google Firebase as it really seems to simplify the work.
The features user needs in the app are:
Authorization/Registration
Uploading photos
Searching for other people, following them and see their photos
I come from traditional "own-backend" development where I do need to setup a server, create database and finally write the API to let the frontend retrieve the data from the server. That's the reason why it's unclear to me how it all works in Firebase.
So the question is how can I create such app:
Should I create my own API with cloud functions? Or it's ok to work with the database directly from the client-side?
If I work with the database directly why do I need cloud functions? Should I use them?
Sorry for such silly questions, but it is really hard to get from scratch.
The main difference between Firebase and the traditional setup you describe is that with Firebase, as far as the app developer is concerned, the client has direct access to the database, without the need for an intermediate custom API layer. Firebase provides SDKs in various languages that you would typically use to fetch the data you need / commit data updates.
You also have admin SDKs that you can use server-side, but these are meant for you to run some custom business logic - such as analytics, caching in an external service, for exemple - not for you to implement a data fetching API layer.
This has 2 important consequences:
You must define security rules to control who is allowed to read/write at what paths in your database. These security rules are defined at the project level, and rely on the authenticated user (using Firebase Authentication). Typically, if you store the user profile at the path users/$userId, you would define a rule saying that this node can be written to only if the authenticated user has an id of $userId.
You must structure your data in a way that makes it easily readable - without the need for complex database operations such as JOINs that are not supported by Firebase (you do have some limited querying options tough).
These 2 points allow you to skip the 2 main roles of traditional APIs: validating access and fetching/formatting the data.
Cloud functions allow you to react to data changes. Let's say everytime a new user is created, you want to send him a Welcome email: you could define a cloud function sending this email everytime a new node is appended to the users path. They allow you to run the code you would typically run server-side when writes happen, so they can have a very broad range of use-cases: side-effects (such as sending an email), caching data in an external service, caching data within Firebase for easier reads, analytics, etc..
You don't really need a server, you can access the database directly from the client, as long as your users are authenticated and you have defined reasonable security rules on Firebase.
In your use case you could, for example, use cloud functions to create a thumbnail when someone uploads a photo (Firebase Cloud Functions has ImageMagick included for that), or to denormalize your data so your application is faster, or to generate logs. So, basically you can use them whenever you need to do some server side processing when something changes on your database or storage. But I find cloud functions hard to develop and debug, and there are alternatives such as creating a Node application that subscribes to real time changes in your data and processes it. The downside is that you need to host it outside Firebase.
My answer is definitely NOT complete or professional, but here are the reasons why I choose Cloud Functions
Performance
You mentioned that you're writing an instagram-like mobile device app, then I assume that people can comment on others' pictures, as well as view those comments. How would you like to download comments from database and display them on users' devices? I mean, there could be hundreds, maybe thousands of comments on 1 post, you'll need to paginate your results. Why not let the server do all the hard work, free up users' devices and wait for the results? This doesn't seem like a lot better, but let's face it, if your app is incredibly successful, you'll have millions of users, millions of comments that you need to deal with, server will do those hard jobs way better than a mobile phone.
Security
If your project is small, then it's true that you won't worry about performance, but what about security? If you do everything on client side, you're basically allowing every device to connect to your database, meaning that every device can read from/write into your database. Once a malicious user have found out your database url, all he has to do is to
firebase.database().ref(...).remove();
With 1 line of code, you'll lose all your data. Okay, if you say, then I'll just come up with some good security rules like the one below:
This means that for each post, only the owner of that post can make any changes to it or read from it, other people are forbidden to do anything. It's good, but not realistic. People are supposed to be able to comment on the post, that's modifying the post, this rule will not apply to the situation. But again, if you let everybody read/write, it's not safe again. Then, why not just make .read and .write false, like this:
It's 100% safe, because nobody can do anything about anything in your database. Then, you write an API to do all the operations to your database. API limits the operations that can be done to your database. And you have experience in writing APIs, I'm sure you can do something to make your API strong in terms of security, for example, if a user wants to delete a post that he created, in your deletePost API, you're supposed to authenticate the user first. This way, 'nobody' can cause any damage to your database.

Secure writing of data to Firebase via Angular

I want to setup a public form to write to Firebase via the Angular Firebase plugin AngularFire but it feels like there needs to be some security added so that data is only posted from that form, I can't see any interface to Whitelist a Domain/URL. Is there a way to only accept writes from a specific Form/URL without getting the User to login first?
Nope.
But it wouldn't help in your scenario anyway: when you're using Angular, all code is running in the user's browser. It might be served from your domain into that browser first, but just as easily the user might have saved the HTML locally and started running it that way.
It sounds like you're trying to secure things so that only your code can modify them, probably because you think that your code is the only thing that can be trusted to follow some of your application-specific business rules. Instead of trying to limit access to just your code, I'd instead recommend capturing the business rules server-side. Firebase has a very powerful security and data validation model just for that purpose. See https://www.firebase.com/docs/security/guide/
Once you enforce these business rules on the server, it doesn't matter how someone access your data. They could be using your code - or somebody could have taken your code (or an API that you've documented) and written a third-party application. Either way: the (security and validation) rules will be enforced by Firebase, so your data will stay valid and secure.

REST APIs, HTTP verbs and ACCESS LOGs

I've been trying to follow good RESTful APIs practices when designing them. One of them which happens to be very simple and common keeps getting hard to follow:
Use GET http verb to retrieve resources
Why? Consider you have a URI to get account information like this:
http://www.example.com/account/AXY_883772
Where AXY_883772 is an account id in a bank system. Security auditing will raise a warning stating that:
Account ID will appear on HTTP ACCESS LOGS
Account ID might get cached on browser's history (even though is unlikely to use a browser regularly to access a RESTful API)
And they end up by "recommending" that POST verb should be used instead.
So, my question is:
What can we do about it? Just follow security recommendations and avoid using GET most of the times? Use some kind of special APACHE/IIS/NGINX access log configuration to avoid logging access to certain URLs?
If you have sensitive information in your urls, and you are logging urls you are logging sensitive information.
So there's two obvious solutions:
Don't log the url
Use a different url that doesn't contain the sensitive information
The last one could be implemented by using some (different) id that your server maps back to the normal id.
If neither of those solutions are an option for you, then you cannot use GET and therefore it's not good RESTful design.
I realize all these things are probably already obvious to you; But it's the most accurate answer I could give.
It's worth nothing that this doesn't just apply to GET, it would actually also be the case for PUT, DELETE and often POST.

Resources