How to run ElasticSearch on user's devices AND keep ElasticSearch server safe? - firebase

Writing a mobile app with Firebase being my backend, also using ES to power my search. I'm completely new to ES.
Suppose each user can publish articles, each of which contains some number of tags, which denotes what this article is about, kind of like questions asked here. Users can search for articles, with tags, and articles containing that tag will be displayed. I manage to do that with Cloud Function, so, the Cloud Function basically looks like this:
exports.articleSearch = functions.https.onRequest((req, res) => {
const { tag } = req.query;
const ElasticSearchConfig = {
uri: '..<my elastic cloud url>/articles/article/_search...',
method: 'GET',
body: ...,
json: true,
auth: {
username: '...<my elastic cloud username>...',
password: '...<my elastic cloud password>...'
}
};
// If succeeds, send results back to user, if not, send error back
request(ElasticSearchConfig).then((results) => ...)
.catch((error) => ...);
});
This works, however, it's a bit slow, because I'm not running ElasticSearch on user's devices, instead, through a cloud function. But if I do run the above code on user's devices, you noticed auth property of ElasticSearchConfig object, I'm basically giving everybody permissions to access and manipulate my ES server. How can I run the above code on user's devices and at the same time, prevent them from reading or writing anything without proper permission?

There's no secure way to do what your asking. Even if it was possible, you don't want that kind of processing client side draining the battery, especially on mobile. Your slow response from cloud functions may be caused from the function entering a timeout state, meaning it hasn't been called in a while.

Related

Firebase emulator: see outgoing HTTP traffic

I have a Cloud Function that calls to Chargebee. In index.ts:
const chargeBee = new ChargeBee();
...
chargeBee.configure({
site,
api_key: apiKey
});
...
export const finalizeSignup = https.onCall(
async (info: SignupInfo, ctx: CallableContext) => {
const cbCmd = chargeBee.hosted_page.retrieve(info.cbHostedPage);
const callbackResolver = new Promise<any>((resolve, reject) => {
// cbCmd.request returns a Promise that seems to do nothing.
// The callback works, however.
// Resolve/reject the Promise with the callback.
void cbCmd.request((err: any, res: any) => {
if (err) {
reject(err);
}
resolve(res);
});
});
// Calling Promise.resolve subscribes to the Promise.
return Promise.resolve(callbackResolver);
}
);
I am testing this function using the Firebase emulators, started via firebase emulators:start --only functions. Chargebee is responding strangely. They require the domain of their incoming requests to be whitelisted: my first guess is that the domain being used by my locally emulated Cloud Function is not whitelisted on the Chargebee side.
How do I see outgoing HTTP information sent by my locally emulated Cloud Function?
The connection is actually HTTPS, not HTTP.
The emulators provide no functionality to intercept network traffic of any form.
For HTTP: you have to apply your own tooling to monitor the HTTP traffic (ie Wireshark).
For HTTPS: possible to monitor using Wireshark, but impossible to analyze without knowing the SSL key. And in the setup above, where a third-party library is handling the request, there is currently no way to obtain the SSL key. I entered a feature request with Firebase to gauge the interest of developing a way to define an SSL key log when starting the Functions emulator, similar to Chrome. A user only identifying themselves as 'Oscar' told me in a private email that "I've already filed a feature regarding this topic to our engineering team regarding this matter, which will be discussed internally." So that tells us that (1) Firebase is aware that the feature is currently lacking, and (2) there is no progress to report on the feature.

eHow to transition away from inline editor on actions on google

In a previous Stack Overflow question, I shied away from using an external webhook on Actions on Google
so I needed to go back to the inline editor. I got that worked out, but now I'm feeling brave again.
I've outgrown the inline editor and want the ability to develop my code on my laptop, testing it in Firebase, and publishing to a site for my webhook, presumably where the inline code editor publishes to. In fact, I have already written the require functions and deployed them from Firebase. So the full functionality is ready to go, I just need to hook it up properly to Actions on Google.
What I have now in Actions on Google, inline editor, is more of a stub. I want to merge that stub into my more fullblown logic that I have in Firebase. Here is what is in the inline editor:
const { conversation } = require('#assistant/conversation');
const functions = require('firebase-functions');
const app = conversation();
app.handle('intent_a_handler', conv => {
// Implement your code here
conv.add("Here I am in intent A");
});
app.handle('intent_b_handler', conv => {
// Implement your code here
conv.add("Here I am in intent B");
});
exports.ActionsOnGoogleFulfillment = functions.https.onRequest(app);
When I search on the Internet, I see discussion from the point of view of Dialogflow, but like I say, I'm in "Actions on Google". I want to transition away from the inline editor, taking what I already have, as a basis.Can someone explain how I set that up? I'm happy to do this within the context of the Google ecosystem.
To test your own webhook locally on your own system I would recommend incorporating a web app framework such as express. With express you can host code on your local machine and make it respond to request from Actions on Google. In your case you would replace this will all the code related to the Firebase functions package. Here is an example of what a simple webhook for Actions on Google looks like:
const express = require('express');
const bodyParser = require('body-parser')
const { conversation } = require('#assistant/conversation');
const exprs = express();
exprs.use(bodyParser.json()) // allows Express to work with JSON requests
const app = conversation();
app.handle('example intent', () => {
// Do something
})
// More app.handle() setups
exprs.post('/', app);
exprs.listen(3000);
With this setup you should be able to run your own application locally. The only thing you need to do is install the required dependencies and add your own intent handlers for your action. At this point you have a webhook running on your own machine, but that isn't enough to use it as a webhook in Actions on Google because it runs locally and isn't publicly available via the internet.
For this reason we will be using a tool called ngrok. With ngrok you can create a public https address that runs all messages to your local machine. This way you can use ngrok address as your webhook URL. Now you can just make as many code changes as you want and Actions on Google will automatically use the latest changes when you develop. No need to upload and wait for Firebase to do this.
Just to be clear: Ngrok should only be used for development. When you are done with developing your action you should upload all your code to a cloud service or host it on your own server if you have any. A (free plan) ngrok URL usually expires every 6 hours. So its not a suitable solution for anything other than development.

Firebase Cloud Function location setting

I would like to request an API which only allow IP from Hong Kong, therefore I perform a check using https://ifconfig.co/country-iso. Even I set functions.region('asia-east2') as stated in the document page (https://firebase.google.com/docs/functions/locations), the console logged the location detected is US
exports.locationFunction = functions.region('asia-east2').pubsub.schedule('every 1 minutes').onRun((context) => {
request('https://ifconfig.co/country-iso', function (error, response, body) {
console.log("RESULTbody:" + body)
});
return admin.database().ref("mylocation").set("detection finished");
});
If you are using scheduled functions, as you are, then you have an App Engine machine that is required for Cloud Scheduler to work. I think that the default project region might be set to something else than 'asia-east2' that you want.
If the function is set correctly to asia-east2 the only other regional config that can affect is the default project region where the App Engine machine spins up, I think that might be your issue.
Here you have more information on scheduled functions and the information I mentioned about the App Engine machine.
And here you can see more information about default project location.
Let me know.

Firebase session persistence in Express

I just started learning node, express, and Firebase and after digging around, I've decided to ditch express's express-session API and go with Firebase's authentication system.
I'm trying to build a simple app that can handle multiple user sign-ins with express but I'm lost on where and when to use Firebase functions. I know I need some sort of session on the client side, but I'm unsure how to implement it.
Below is what I want my app to do:
Log in with user credentials
Store user information in a session object
Redirect to the dashboard
Retrieve user details from session object
Here is what I have so far:
app.post('/login', (req, res, next) => {
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(function() {
firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then((user) => {
res.redirect('/dashboard');
})
.catch((err) => {
res.send(err);
});
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
});
});
I've read up on Admin SDKs, authChange, tokens and client SDKs. I'm a total newbie at this and I'm blown away by all the information. I feel like I'm missing an onAuthChange statement, but I'm unsure where to put it. This is also a testing nightmare because my local server returns an error when I use persistence.
How can I use session-like objects in Express? What do I need to implement to make sure multiple users can use my app at the same time?
I found my answer. There's no need to initiate sessions in the back end because Firebase functions create a session object in LocalStorage. Powerful stuff.

Inner auth() seems to adhere to outer auth() rules

In our application we use Firebase's custom login functionality to store some metadata in user's auth token.
Later we send this token to one of our web applications to perform a task on behalf of the user using a new admin token to disable security rules. The idea is that a particular location is not writable by authenticated users directly, but data could be written in that location after some server side calculations and validations are done.
Here's a sample code of what I'm trying to do:
var testRef = new Firebase(firebaseApp + 'test');
testRef.auth(userFirebaseAuthToken, function(error, result) {
if (!error) {
var userId = result.auth.userId;
// perform validations and calculations
var tokenGenerator = new FirebaseTokenGenerator(firebaseSecret);
var token = tokenGenerator.createToken({admin: true});
var protectedRef = new Firebase(firebaseApp + '/protected/');
protectedRef.auth(token, function(error) {
if (!error) {
protectedRef.child('foo').push({id: userId});
}
});
}
});
But I get this error:
FIREBASE WARNING: set at /protected/foo/-Ityb1F6_G9ZrGCvMtX- failed: permission_denied
When desired behavior is to be able to write in that location using an admin token.
I understand that this might not be a Firebase issue, but some JavaScript good/bad parts, but what I need to do is to write in some protected location on behalf of a user which even though is not authorized to write in that location, but needs to be authenticated.
Based on what I've seen from my test units and from experience, I don't think that new Firebase actually gives you an independent connection to the data. That is to say, these are both connected to the same Firebase instance internally (I think):
var refA = new Firebase('...');
var refB = new Firebase('...');
So if you want to re-auth, I'm pretty sure you need to call unauth first, which will probably affect your testRef instance as well.
If you truly need to have multiple instances opened to the database with different auth at the same time, then you'll have to look at node-fibers or some other worker pool model, which will allow separate connections.
However, give some thought to this; you are probably overthinking your approach. If you are writing on behalf of a user who doesn't have permissions, then you probably don't actually need to be authenticated as that user.
I've written an entire app with secure Firebase components that are consumed by a third-party app, and then written back to privileged paths and then read by users, and haven't yet run into a condition where the server would need to demote its permissions to do this.
That's not meant to presume I know your use case, just to give you some encouragement to keep things simple, because trying to juggle authentication will not be simple.
My approach is to treat the Firebase security rules as a last defense--like my firewall--rather than part of the programming algorithm used by privileged processes.

Resources