Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way of defining secret_key_base on Rails 6?

What's the correct way of defining secret_key_base on Rails 6 now that we have per-environment credentials?

My environment has the variable SECRET_KEY_BASE but Rails is not picking it up. I tried defining secret_key_base in config\credentials\production.yml.enc but it has no effect on Rails.application.credentials.secret_key_base

I know config/secrets.yml with

staging:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

works, but, is that the Rails 6 way?

like image 557
Marta Silva Avatar asked Mar 16 '20 08:03

Marta Silva


People also ask

What is Rails secret_key_base?

The secret_key_base is used as the input secret to the application's key generator, which in turn is used to create all MessageVerifiers/MessageEncryptors, including the ones that sign and encrypt cookies.

What is config credentials Yml ENC?

credentials. yml. enc file is used to manage configuration such as environment variable, ID or password. This file is encrypted by config/master.


1 Answers

The right way to access and check for secret_key_base in Rails 6 is no longer:~

Rails.application.credentials.secret_key_base

it now is:

Rails.application.secret_key_base

I'm not sure if this is Rails 6 or it's been like this forever. This becomes pretty clear when looking at this method, and its implementation:

https://github.com/rails/rails/blob/09a2979f75c51afb797dd60261a8930f84144af8/railties/lib/rails/application.rb#L410-L427

# The secret_key_base is used as the input secret to the application's key generator, which in turn
# is used to create all MessageVerifiers/MessageEncryptors, including the ones that sign and encrypt cookies.
#
# In development and test, this is randomly generated and stored in a
# temporary file in <tt>tmp/development_secret.txt</tt>.
#
# In all other environments, we look for it first in ENV["SECRET_KEY_BASE"],
# then credentials.secret_key_base, and finally secrets.secret_key_base. For most applications,
# the correct place to store it is in the encrypted credentials file.
def secret_key_base
  if Rails.env.development? || Rails.env.test?
    secrets.secret_key_base ||= generate_development_secret
  else
    validate_secret_key_base(
      ENV["SECRET_KEY_BASE"] || credentials.secret_key_base || secrets.secret_key_base
    )
  end
end

Both development and test mode have their own way of generating and storing the secret key base. For everything else, it pics it up from the environment, or credentials or secrets, in that order.

like image 175
Marta Silva Avatar answered Nov 15 '22 21:11

Marta Silva