Is there a way to read environment variables inside override.ts with AWS Amplify Auth - aws-amplify

I used to AWS Amplify Auth for a social login, recently.
and, for social provider setting, I'm trying to use amplify auth override.
docs is here: https://docs.amplify.aws/cli/auth/override/
for security reason, I don't want write the secrets inside override.ts like client id, client secrets, etc.
Is it possible to read environment variables in override.ts?
or any idea?

Amplify CLI retained the information in amplify/backend/amplify-meta.json such as project environment information and others resources information.
I used amplify-meta.json as a module.
There is a StackName with the value of amplify-[PROJECT_NAME]-[ENVIRONMENT_NAME]-[PROECT_NUMBER]. So we can get the environment name by deconstructing the string.
override.ts
export function override(resources: AmplifyAuthCognitoStackTemplate) {
const amplifyMetaJson = require('../../../amplify-meta.json');
const envName = amplifyMetaJson.providers.awscloudformation.StackName.split("-").slice(-2, -1).pop();
console.log("Environment for cloudformation => ", envName);
}
Note: This is the temporary solution of an evil way. It is better to fix the issue.
https://github.com/aws-amplify/amplify-cli/issues/9063

Related

error using require.js to load aws-sdk databse script

I'm trying to require aws sdk database for use in a web application, but I'm getting the following errors
const AWS = require(["aws-sdk"]);
AWS.config.update({ region: "ap-southeast-2" });
AWS.config.update({
region: "{Region[enter image description here][1]}",
// For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
accessKeyId: "{Key}",
// secretAccessKey default can be used while using the downloadable version of DynamoDB.
// For security reasons, do not store AWS Credentials in your files. Use Amazon Cognito instead.
secretAccessKey: "{Key}"
});
You're using the wrong syntax, passing an array to require is part of the callback syntax and expects a function as a second argument.
Try this instead:
const AWS = require("aws-sdk");
Also, I'm not sure why you're calling config.update twice, you probably should just do it once to avoid any issues, or at a minimum to avoid confusion.

Firebase Admin SDK Not Reading, Writing, or Throwing Errors (Node.js)

This question was previously closed, telling me to "update the question so it focuses on one problem only;" I don't know what the problem is, and if I did, I wouldn't be posting this question. Regardless, I'll make some clarifications here:
I was previously using just the normal Firebase module (the one imported using "npm i firebase"); everything worked perfectly before. The issue has to do with the authentication (as far as I am aware) with the Firebase Admin SDK. I don't understand how I'm supposed to send this to the Heroku build without revealing the service account key JSON file on my GitHub.
As for the GOOGLE_APPLICATION_CREDENTIALS path, is there a way where I don't have to set it every session? The Heroku app restarts once a day, and I would need to somehow automate this entry process (or skip it entirely). That's the way I currently understand it. Here's a quote from a previous answer:
When I set the GOOGLE_APPLICATION_CREDENTIALS path, doesn't this only set it on my local machine?
Environment variables only work on the individual machine and process where they have been set. If you want it set on another machine and process, you will have to arrange for that separately. According to the documentation:
Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.
My main question here is as follows: "I implemented the Firebase Admin SDK incorrectly. How do I do it the right way?"
Even just posting a link to guides that would help would be appreciated (although I understand this is typically discouraged as links sometimes break).
Original:
Note: this is my first time using the Firebase Admin SDK, so I'm really not sure what I'm doing (although I have used Firebase quite a bit).
Recently, I decided I would go back to one of my older Discord bots and actually authenticate its requests to Firebase properly (I hadn't done this previously as I've never authenticated from a server before and didn't think it was possible). I discovered the Firebase Admin SDK, which sounded perfect for my needs (the bot is being hosted on Heroku, for the record).
I found this guide: https://firebase.google.com/docs/admin/setup, but there's a few things I can't wrap my head around (note that these are purely rhetorical, you don't need to answer them in your answer; I'm just providing them so you can understand my thought process):
When I set the GOOGLE_APPLICATION_CREDENTIALS path, doesn't this only set it on my local machine? I could also try running the export command on the server (using "heroku run" in the CLI), but then the path would be pointing to a file that doesn't exist on the server (since the service account key JSON file is on my local machine). Do I need to set an environment variable in Heroku or something?
How does "admin.credential.applicationDefault()" know how to get the credentials?
I can't find any other guides that make sense.
The way I currently have it setup must be wrong, since reads and writes fail silently.
Firebase setup code:
// Setup Firebase:
const admin = require('firebase-admin');
// Initialize Firebase:
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "https://<APP>.firebaseio.com" // I removed the actual <APP> name to ask this question
});
let database = admin.database();
Things like database.ref("test").set("Hello World!"); don't change the data in the database, and no errors are thrown (I've also tried attaching a .then and a .catch to the end of this; still nothing). This was working before I switched over to the Firebase Admin SDK (I was just using the "firebase" module previously, rather than the "firebase-admin" module that I'm now using). The same goes for reading data.
Any help would be appreciated.
Here was my problem:
I was sending res.status(200) outside of the async firebase call, killing the request before firebase had a chance to finish. Somehow localhost allows this to work properly but when its hosted things go sideways.
so I had this
fireabse.database().ref('parent/foo').set('bar');
res.status(200)
I needed this:
firebase.database().ref('parent/foo').set('bar').then(() => {
res.status(200);
});

Who can read config values set by functions:config:set command?

I'm working on the implementation of some Cloud Functions for Firebase and one of these require some configuration to call external providers.
I was able to successfully configure these values using firebase functions:config:set key="value" but I was wondering what are the actors able to read this value.
Is the function the only capable of read it? Should I encrypt "value"? At the end will have to have the key in order to decrypt it.
Thanks
Environment configuration is created exactly for keeping some settings or 3rd-party services keys.
Only your google functions will be able to extract the value on remote environment.
Also you can check those values locally using firebase functions:config:get key command.
To get those variables from the code of your function use this:
const functions = require('firebase-functions');
const someEnvVar = functions.config().key
// where key is name of key you setted before
See more in official docs

Can Firebase RemoteConfig be accessed from cloud functions

I'm using Firebase as a simple game-server and have some settings that are relevant for both client and backend and would like to keep them in RemoteConfig for consistency, but not sure if I can access it from my cloud functions in a simple way (I don't consider going through the REST interface a "simple" way)
As far as I can tell there is no mention of it in the docs, so I guess it's not possible, but does anyone know for sure?
firebaser here
There is a public REST API that allows you to read and set Firebase Remote Config conditions. This API requires that you have full administrative access to the Firebase project, so must only be used on a trusted environment (such as your development machine, a server you control or Cloud Functions).
There is no public API to get Firebase Remote Config settings from a client environment at the moment. Sorry I don't have better news.
This is probably only included in newer versions of firebase (8th or 9th and above if I'm not mistaken).
// We first need to import remoteConfig function.
import { remoteConfig } from firebase-admin
// Then in your cloud function we use it to fetch our remote config values.
const remoteConfigTemplate = await remoteConfig().getTemplate().catch(e => {
// Your error handling if fetching fails...
}
// Next it is just matter of extracting the values, which is kinda convoluted,
// let's say you want to extract `game_version` field from remote config:
const gameVersion = remoteConfigTemplate.parameters.game_version.defaultValue.value
So parameters are always followed by the name of the field that you defined in Firebase console's remote config, in this example game_version.
It's a mouthful (or typeful) but that's how you get it.
Also note that if value is stored as JSON string, you will need to parse it before usage, commonly: JSON.parse(gameVersion).
Similar process is outlined in Firebase docs.

Setting NODE_ENV for firebase function

I am moving some of my firebase-queue workers to Firebase Functions. I have used process.env.NODE_ENV to set some of the configuration for the workers depending on the environment in which I am running them. Is there a way to set the NODE_ENV for the functions while deploying them. I understand that the recommended way to provide such config options is via firebase.config.set which I have verified works as expected but just wanted to check if there is a way to set the NODE_ENV also. When I try to print out the NODE_ENV inside of a function, it is always set to production.
Following Google's Best practices and reserved environment variables in their documentation
Environment variables that are provided by the environment might change in future runtime versions. As a best practice, we recommend that you do not depend on or modify any environment variables that you have not set explicitly.
Basically don't use NODE_ENV. Use your own environment variables and set them accordingly.
NOTE: This documentations is from Google Cloud Functions. Firebase functions are like a wrapper around google cloud functions. Check this question
There is currently no way to set custom environment variables such as process.env.NODE_ENV. What you want to do can only be done for Google Cloud functions and you need to use the gcloud command-line tool.
https://cloud.google.com/functions/docs/env-var#accessing_environment_variables_at_runtime
Other options
If you are developing specifically for Firebase and need a similar solution, then there are options.
Conditions based on project ID
You can access the project id if you are having test, staging and production projects and want to have different behavior or logging depending on the environment.
process.env.GCLOUD_PROJECT is set to your GCP project ID so you can build logic based on that.
if (process.env.GCLOUD_PROJECT === 'my-production-project') {
// Only in production
} else {
// Do something for the test environments
}
Cloud Function Environment Variables
As you already mentioned there's the cloud functions environment variables also. You can effectively create build pipelines that are configuring your environment configuration upon build/deploy and later access them in your cloud function.
- firebase functions:config:set runtime.env="production" --token $FIREBASE_DEPLOY_KEY
Accessing the configuration is effectively the same as your process.env but can not be accessed outside of the scope of a cloud function (i.e. you can't use it in a global variable declaration).
if (functions.config().runtime.env === 'production') {
// Only in production
} else {
// Do something for the test environments
}
At the time I'm answering this question the Firebase SDK for Cloud Functions offers built-in environment configuration out of the box.
Set environment configuration for your project
$ firebase functions:config:set [values...]
Example
$ firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"
Get environment configuration for your project
$ firebase functions:config:get [path]
Example
const functions = require('firebase-functions')
console.log(functions.config().someservice.id)
NOTE: You must redeploy functions to make the new configuration available.

Resources