How to reference Firebase Functions config variables from a Firebase-hosted application? - firebase

I am transitioning a Heroku-hosted ReactJS/NodeJS application to be hosted on Firebase. Because Firebase only handles static pages I need to reconfigure how my private environmental-specific variables for Development, Staging, Production environments are configured. For example before I defined these sorts of variables:
CLIENT_ID=secret_here
DOMAIN=secret_here
REDIRECT_URI=secret_here
upon the Heroku environment I was deploying to and now I must set them into firebase functions environments from the Firebase CLI for Dev, Staging and Production.
Firebase has documentation on adding environmental configurations to Firebase Functions such that I can add key/value pairs to be accessed at runtime from within a firebase function:
firebase functions:config:set mySecret.key="CLIENT_ID" mySecret.id="secret_here"
however I am unclear how added configuration variables can be accessed from Firebase-hosted static applications (rather than functions).
Is it as simple as simply referencing the firebase functions library from my application and retrieving the defined key from within my application (like so)?
const functions = require('firebase-functions');
...
functions.config().auth0.CLIENT_ID

The variables you define through the link you provided are only available via Cloud Functions. They're not made available directly to the static content served by Firebase Hosting.
If you want, you can make an HTTP function that does nothing but return the JSON from your env vars, and call that from your web content. Bear in mind that you're exposing your secret keys to the world.

The best practice way to handle what I am trying to do is to refactor all of the application logic requiring environment configuration into firebase functions. I can then invoke said functions to reference environment config and execute the code consuming them. This is the answer/solution I needed and didn't have the context to realize earlier. thanks for edging me towards that realization.

Related

Expose firebase functions config to create-react-app?

I'm using two firebase projects: one for development and staging, and another for production. The Firebase CLI allows me to switch projects with firebase use _____.
For the client I'm using create-react-app and implicitly configuring firebase by using the From Hosting URLs.
The trouble comes with configuring each project's connection to third party services. For most services I have separate accounts, so need different keys (and secrets on the server), for development and production.
For firebase functions, I can use functions config vars for each project. Pretty easy.
But what's the best way to do this on the client?
create-react-app has great support for various .env files, but can I link a .env file to a firebase project rather than using their prioritization?
Or is there a way to expose the firebase functions config vars to create-react-app's start, build, and test processes as environment variables? (preferably without building all variables into the public js :-P)
What's the best way to do this?
The best way to do this seems to be to use GCP secret manager :
Secret Manager stores API keys, passwords, certificates, and other
sensitive data. It provides convenience while improving security
https://cloud.google.com/secret-manager/docs/quickstart
Beware, it's a standalone service by GCP, therefore Google charges you to store your API keys. The pricing calculation example they detail, so i'm guessing it's a typical use case, gives a monthly cost of $15.15.
That's not cheap to store dumb API keys.
The other way is to use cloud functions as you did.
The benefits of using GCP SM are that the service can be combined with audit logs, that it has a version management feature, and that you can set permission levels.

Cloud Functions: Store Simple Shared Value Across Instances without Database/VPC?

Writing a firebase/google cloud function, and need to store an environment value for use across multiple function calls. That value expires and needs to be re-fetched on occasion and updated in production.
I'm looking for a lightweight option for that. Seems all the advice I can find is that you need to spin up a VPC and create a dedicated Redis instance... or you need to create a cloud database and store it there... I just need to save a simple string, and it seems like an awful lot of infrastructure to do that.
One would think environment variables would work, but you can only set on the command line and they are only refreshed on deploy...
To store environment data, you can use the firebase
functions:config:set command.
To get environment data, you can use the functions.config() function.
See https://firebase.google.com/docs/functions/config-env.
So, is there a way to update/set a value in my code? I cannot rely on the command line to update it as it expires, like a cron to update and redeploy.
In Google Apps Script, for example, I'd just use the 'cache' helper service and store the value for a few hours. Any equivalent cache available to cloud functions without resorting to storing on GCS or in a database (it's a single, simple token string...)? Thanks.
Cloud Functions does not offer any form of shared environment variables between functions. You will need to look to an external source such as Cloud Secrets Manager, Cloud Storage or one of the databases. I use both Cloud Storage and Datastore for this feature. I am now looking into Cloud Secrets Manager as my software usually has secrets as well.

How can I "admin.initializeApp();" no arguments in local

I am always grateful for your help.
I want to write code admin.initializeApp(); both locally and in production.
When I deploy functions to production with no auguments, it works.
But locally, it requires me to write it like below:
const serviceAccount = require("/home/yhirochick/development/ServiceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxx.firebaseio.com/"
});
In the official documentation it says that configuration is applied automatically when you initialize the Firebase Admin SDK with no arguments
But when I execute the command firebase serve --only functions locally and some calls some requests by postman produce the error below:
[2019-07-22T06:45:26.227Z] #firebase/database: FIREBASE WARNING: Provided
authentication credentials for the app named "[DEFAULT]" are invalid. This
usually indicates your app was not initialized correctly. Make sure the
"credential" property provided to initializeApp() is authorized to access the
specified "databaseURL" and is from the correct project.
I want to know How can I "admin.initializeApp();" no arguments locally.
I have grappled with this also and I don't think the local testing scenario currently is explained very well in the official documentation. But here is a solution:
For your local environment you need to download the firebase projects firebase service account json file (found in firebase console under project settings -> service account) and set an environment variable GOOGLE_APPLICATION_CREDENTIALS to point to the file:
# Linux/MACOS version
export GOOGLE_APPLICATION_CREDENTIALS="[PATH_TO_YOUR_SERVICE_ACCOUNT_FILE]"
Read more here, also on how to do this on Windows
Now you will be able to use admin.initializeApp() (with no arguments) locally.
A possible downside of this approach is that you have to set the environment variable each time you fire up a terminal before you start the firebase emulator, because the variable gets deleted when you end the session.
Automate it...
You could automate the export ... command by bundling it together with the command that fires up the emulator. You could do this by adding an entry to the scripts section of your package.json, e.g.:
"local": "export GOOGLE_APPLICATION_CREDENTIALS='[PATH_TO_YOUR_SERVICE_ACCOUNT_FILE]' && firebase emulators:start --only functions"
Then, in this example, you would only need to type npm run local.
Alternative: provide explicit credentials in local environment only
Look at this example: https://stackoverflow.com/a/47517466/1269280.
It basically use a runtime node environment variable to separate between local and production and then use the explicit way of providing credentials in the local environment only.
This is my preferred way of doing things, as I think it is more portable. It allows me to put the service account file inside my codebase and not deal with its absolute file path.
If you do something like this then remember to to exclude the service account file from your repo! (it contains sensitive info).
Background: difference between production and local service account discovery
The reason that admin.initializeApp() (with no arguments) works out-of-the-box in production is that when you deploy to production, i.e. Firebase Functions, the code ends up in a 'Google managed environment'. In Google managed environments like Cloud Functions, Cloud Run, App Engine.. etc, the admin SDK has access to your applications default service account (the one you downloaded above) and will use that when no credentials are specified.
This is part of Google Clouds Application Default Credentials (ADC) strategy which also applies to firebase functions.
Now, your local environment is not a 'google managed environment' so it doesn't have access to the default service account credentials. To google cloud, your local box is just an external server trying to access your private Firebase ressources. So you need to provide your service account credentials in one of the ways described above.
Before I knew this, I thought that because I was already logged in to firebase via my terminal i.e. firebase login and were able to deploy code to firebase, the firebase emulator would also have the necessary credentials for the firebase admin sdk, but this is not the case.

How to get the firebase functions URL in a firebase hosted webapp?

I am working on a project in which we have pre-existing cloud functions in use with Firebase. We are adding a small React SPA using firebase cloud hosting, and this SPA will interact with some of the existing public cloud functions.
The way we have been doing things so far, we have a dev project, and a production project in Firebase. For cloud functions, this works fine, we have environment specific config set up with firebase functions:config:set for differentiations between prod and dev servers.
The problem comes with the hosted SPA contacting the cloud functions. I've seen a lot of questions on how to access the environment config in the hosted code, eg this one: How to reference Firebase Functions config variables from a Firebase-hosted application? where the answer seems to be to have firebase functions that return the values of the environment variables, but for me this just moves the problem further back on step. I fully understand that having the environment variables accessible to this code would be a massive security problem as the SPA is run in the browser.
The only environment specific config I really need for the hosted SPA is the base address for the cloud functions.
eg if in my cloud functions I have
const functions = require('firebase-functions');
const express = require('express');
const test = express();
test.on('/hello/:target', (req, res) => {
res.send(`Hello ${req.params.target}`);
})
exports.test = functions.https.onRequest(test);
then having deployed, this cloud function is available both at https://us-central1-DEV-PROJECT-NAME.cloudfunctions.net/test/hello/world and https://us-central1-PROD-PROJECT-NAME.cloudfunctions.net/test/hello/world . How would I best get the appropriate root url (https://us-central1-DEV-PROJECT-NAME.cloudfunctions.net or https://us-central1-PROD-PROJECT-NAME.cloudfunctions.net) for the project that the SPA is deployed to?
eg. is there some global I can access in the frontend js code where I could do something like:
const url = `${__FIREBASE_GLOBALS__.cloudFunctions.baseUrl}/test/hello/${input}`;
And have the url be correctly defined based on which project the hosted app is deployed to?
I'm assuming here that you're not using Firebase in any other way in your SPA other than to call Cloud Functions (since you didn't say otherwise).
Read the Firebase web setup docs for Firebase Hosting, especially the section on SDK imports and implicit initialization. When you host a site with Firebase Hosting, there are some special URLs that give you the configurations for that project. There are some special script includes that give you access to Firebase products. In particular, note the relative path URI /__/firebase/init.js will yield JavaScript that initializes the Firebase JavaScript SDK with the default settings for your project. Go ahead and access that in a browser pointing to your web app. You're probably interested in the projectId property of the config.
If you want to get a hold of that value, you can use the Firebase SDK, which would be initialized by the script includes from the first link above. Minimally, you could add:
<script src="/__/firebase/5.8.2/firebase-app.js"></script>
<script src="/__/firebase/init.js"></script>
Then later on (see API docs):
firebase.app().options.projectId
to get the ID of the project where Firebase Hosting is serving the content. You can use that to build the URL to your functions.
It might also be convenient for you to port your HTTP functions to callable functions and invoke them from the web site with the Firebase SDK to invoke kthem. Or not.
I was able to get the region and appId from the environment variables.
eg:
console.log(process.env);
Check your firebase logs
{ ...
ENTRY_POINT: 'server',
X_GOOGLE_FUNCTION_TRIGGER_TYPE: 'HTTP_TRIGGER',
FIREBASE_CONFIG: '{"projectId":"pid","databaseURL":"https://pid.firebaseio.com","storageBucket":"pid.appspot.com","locationId":"europe-west"}',
X_GOOGLE_FUNCTION_NAME: 'server',
FUNCTION_TRIGGER_TYPE: 'HTTP_TRIGGER',
X_GOOGLE_GCLOUD_PROJECT: 'pid',
FUNCTION_NAME: 'server',
X_GOOGLE_GCP_PROJECT: 'pid',
X_GOOGLE_FUNCTION_REGION: 'us-central1',
FUNCTION_REGION: 'us-central1',
X_GOOGLE_ENTRY_POINT: 'server',
GCLOUD_PROJECT: 'pid',
GCP_PROJECT: 'pid',
... ommited
}
Out of these GCP_PROJECT, GCLOUD_PROJECT, FUNCTION_REGION, FUNCTION_NAME should work. So for eg. process.env.FUNCTION_REGION
Not sure how reliable this will be.

How to access environment-specific Firebase Function endpoints from Firebase Hosted application?

I have three Firebase projects representing Development, Staging and Production environments hosted on Firebase hosting. Each environment utilizes its own deployed Firebase functions like so:
Dev function endpoint: https://us-central1-my-app-dev.cloudfunctions.net/someFunction
Staging function endpoint: https://us-central1-my-app-staging.cloudfunctions.net/someFunction
Production function endpoint: https://us-central1-my-app.cloudfunctions.net/someFunction
I can't figure out how the static, Firebase-hosted client React application should invoke these functions because the URI endpoints of each changes depending on which environment the code is executing from.
Ideally I could set environment-specific configuration for each Firebase Hosting environment; unfortunately the only way to do this in Firebase Hosting is from within Firebase Functions themselves.
How can I retrieve the environment-specific endpoint for each Firebase Function?
You have a couple options here.
First, you could just configure your React app any way you like. It's necessarily not a bad thing for each system component (backend, frontend) to have its own configuration.
Second, since you're using Firebase Hosting to serve your static content, you can also use it to serve your functions API endpoints. This means that both your static content and API endpoints are all served through the same hostname, which means you no longer have to specify the host when making a request. All the requests can be relative to that host. You can achieve this via Hosting rewrite rules.

Resources