Skip to content

Instantly share code, notes, and snippets.

@Bitcents
Created February 23, 2023 13:08
Show Gist options
  • Save Bitcents/71328c001fb368f70ccab4061c344ea1 to your computer and use it in GitHub Desktop.
Save Bitcents/71328c001fb368f70ccab4061c344ea1 to your computer and use it in GitHub Desktop.
Setting private keys in Heroku Dyno

Background

This is for those who have had trouble setting up private keys following the PEM format on Heroku Dyno. These keys have the following structure:

-----BEGIN {SOME KEY TYPE}-----
{string representation of key}
-----END {SOME KEY TYPE}-----

When you get this kind of key from some service, such as a key file from a GCP/AWS service account, you would usually get it as a string literal, like the following:

"-----BEGIN PRIVATE KEY-----\n{line of text}\n{more lines of text}\n-----END PRIVATE KEY-----\n"

In Heroku Dyno, you would set this as a config variable under Settings > Reveal Config Vars. Config Vars can be accessed by your Heroku application as environment variables. The problem here is that you cannot set the Config Var the same way you would set up an environment variable.

The problem

When setting the key as an environment variable, you can usually set it as a string literal. For example:

GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n{line of text}\n{more lines of text}\n-----END PRIVATE KEY-----\n"

The same cannot be done with Config Vars on Heroku Dyno. When I tried to read the private key into Gapi under Node 16, the program would encounter key formatting errors.

The solution

The only way I would get to work, was to remove the quotations, and replace the '\n' with actual carriages. In other words, I had to find each newline character, remove it and manually press enter in the Config Var input field. In the end you, would end up with something like this:

                      -----BEGIN PRIVATE KEY-----
GOOGLE_PRIVATE_KEY =  Aasdhjkzvhouqhnmeoijsdfsdfhjksf
                      ...
                      ...
                      ...
                      xZcvjlksdjfljlqjipaijfakakjls==
                      -----END PRIVATE KEY-----

You would basically have to convert a string literal into a formatted string. You can also think about it as the output you would get if you were to run the 'cat' command on a private key file:

cat path/to/private-key

Output:

-----BEGIN PRIVATE KEY-----
Aasdhjkzvhouqhnmeoijsdfsdfhjksf
...
...
...
xZcvjlksdjfljlqjipaijfakakjls==
-----END PRIVATE KEY-----

It makes sense that the input field of a Dyno Config Var would not accept string literals, nor perform string transformations, but I did not realize it at first. Hopefully this helps someone out.

If you note something wrong, please feel free to point it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment