Using Encrypted Credentials In Rails 6 Production Mode To Store AWS S3 and Stripe Keys
Recently I’ve been building a complex applications that handles active storage file uploads to AWS S3 and interacts with the Stripe API for subscription services. I’m pretty big on security and I wanted to make sure that all my API keys were super safe and stored properly, so I started following the official Securing Rails Applications guide.
To set rails credentials we only need to run this command:
EDITOR=vim rails credentials:edit
This will open up the encrypted credentials files in the vim editor, using vim as an editor is of course optional.
If you’ve used vim before you can skip this section. Once we have the file open press i to enter insertion mode. Now you can begin entering your credentials. Once your done, pressing esc to escape from insertion mode. In order to save our file we need to enter command mode by pressing : . Once in command mode type x followed by the enter to save your file.
We Once the YAML file is open we can set a credential as a key/value pair like so:
my_api_key: "NotAR3alK3y"
All of our credentials are available in a hash. Inside of our application we can decrypt & access a specific credential like so:
Rails.application.credentials.my_api_key
Using Rails 6 Credentials In Production Mode
When I pushed my app to production my credentials were not appearing, this was obviously very annoying. What I didn’t understand was how credentials work.
Rails automatically decrypts credentials from the private key found in the config/master.key file. Obviously this key shouldn’t be shared with anyone and is automatically included in the .gitnore file, which means it will not be pushed to a remote repository.
If no master.key file is not available Rails will fall back onto the value set to the RAILS_MASTER_KEY environmental variable to decrypt your files. To use your credentials in production you need to set the RAILS_MASTER_KEY variable to the value in your master.key file.
NEVER EVER REMOVE THE MASTER.KEY FILE FROM GITNORE EVEN WHEN USING A PRIVATE REPO.
For more Ruby on Rails and Flutter content checkout Coreys Code Camp and my Youtube Channel !
Corey’s Corner Podcast: https://anchor.fm/coreys-corner
Gardner App Development: https://gardnerappdev.com
Get Yoked 🍳 https://thoughtsandfitness.com
Corey’s Corner Tech Blog: https://coreyscorner.medium.com/
C The Latin of Programming Languages: https://medium.com/codex/the-latin-of-programming-languages-c-bad21e2976b5
Learn To Code: https://www.youtube.com/channel/UCfd8A1xfzqk7veapUhe8hLQ