Fear, Loathing and Regret with Rails 7 Credentials Edit
If you’ve been around computing for any length of time, you’ve likely learned this lesson:
Tread carefully when the word encryption comes up, here there be dragons!
I didn’t honestly expect this for Rails 7 and encrypted credentials and boy was I surprised!
Insanity the First - It isn’t RAILS_ENV=production
This was the first thing that struck me – when you edit credentials for different environments, you use:
rails credentials:edit --environment production
and for development, you use:
rails credentials:edit --environment development
that last one? Oh yeah, we’re coming back to that.
Sigh. I may just be dating myself with the use of RAILS_ENV=production because:
bundle exec rails c --environment production
Loading production environment (Rails 7.0.3)
3.1.2 :001 > Rails.env
=> "production"
3.1.2 :002 >
Given that just works, maybe the core Rails community has deprecated the older style RAILS_ENV=production. I’ve clearly never payed enough attention to the Rails change logs.
Insanity the Second – You Apparently HAVE to Specify Development
I had this situation earlier this morning:
- Run rails credentials:edit
- Edit the file in TextMate, add a credential.
- Go into rails console and look for the credential and it isn’t there.
What experimentation has shown me is that you have to create a credentials set with:
rails credentials:edit --environment development
and add the credential there. Then you can use it inside rails console in development mode.
I believe the explanation for this behavior is covered below. This is a comment from Chris Oliver of GoRails on his discord forum:
environment credentials are picked up before the generic credentials, so if you have production.key/.enc, it will be used instead of master.key I wish that there was a config to disallow the non-environment credentials because it’s easy to forget the –environment flag
Paulo Abreu also chimed in with:
I’m not sure if I understand your question, but if you run bin/rails credentials:help you can see:
bin/rails credentials:edit --environment development
will create config/credentials/development.yml.enc with the corresponding encryption key
in config/credentials/development.key if the credentials file doesn't exist.
The encryption key can also be put in ENV["RAILS_MASTER_KEY"], which takes precedence over the file encryption key.
Mainly, if you don’t have anything in config/credentials/ RAILS_MASTER_KEY must be assigned to the master.key content, else it must be assigned to the environment.key content.
My thanks go out to both Chris and Paulo