'Parsing the firebase private key on AWS Elastic beanstalk

I am moving my firebase authenticated node.js application from Heroku to AWS Elastic Beanstalk. The private key is not parsing correctly. It is having trouble understanding the newline characters from the environment variables.

For reference I have already tried the solution found in this stackoverflow post: Node.js -Firebase Service Account Private Key won't parse

privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n')

Unfortunately, as this works on Heroku, the same is not true for AWS Elastic Beanstalk. After logging the private key in the terminal I notice it is replacing the \n with simply 'n' and making no newline character at all.

Newline characters are not allowed while setting environment variables in the EB software configuration. Any new lines are replaced with just a single space.

Not sure if there is another way short of keeping the key directly in the code which I would like to avoid.



Solution 1:[1]

I had this issue too. I needed to get it working ASAP. None of the solutions worked for me. A temporary hack I did was to push the key but hide some parts of it as env variables.

Something like:

admin.initializeApp({
  credential: admin.credential.cert({
    privateKey: `-----BEGIN PRIVATE KEY-----\nkjhgfdftyujklkjhgf${process.env.PRIVATE_KEY_CHUNK_1}VGHJKMJHGhgfhjkljhg----END PRIVATE KEY-----`,
     projectId:  process.env.PROJECT_ID,
    clientEmail:  process.env.CLIENT_EMAIL,
  }),
})

I figured if they don't have everything, it's sorta useless. Except there's some way to reverse engineer -ish a firebase private key.

Solution 2:[2]

The thing is Elastic Beanstalk removes an escape \ character from environment value.

So your private key, for example

-----BEGIN PRIVATE KEY-----\nXIaEvQIBKDAN...

becomes

-----BEGIN PRIVATE KEY-----nXIaEvQIBKDAN... and invalid

In case anyone needs some example, this is what I did.

As suggested in the comment above, I replaced all \n with @ and put the key on the EB env's Environment properties.

When my app runs, it will get the key like this

-----BEGIN PRIVATE KEY-----@XIaEvQIBKDAN...

So before using it, just replaced @ back to \n with

process.env.PRIVATE_KEY.replace(/\@/g, '\n')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jirachai Uraijaree