Skip to content

Commit

Permalink
Patch Rails.application.secret_key_base to read from config/secrets…
Browse files Browse the repository at this point in the history
….yml

...and generate if missing
  • Loading branch information
fbacall committed Jan 16, 2025
1 parent bf37a6a commit 8410053
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
42 changes: 42 additions & 0 deletions config/initializers/0_secret_key_base_patch.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
require 'securerandom'

module Extensions
module SecretKeyBase
def secret_key_base
@secret_key_base ||
begin
self.secret_key_base =
if Rails.env.local? || ENV["SECRET_KEY_BASE_DUMMY"]
super
else
ENV["SECRET_KEY_BASE"] || Rails.application.credentials.secret_key_base || secret_from_file
end
end
end

# Read secret from config/secrets.yml, generate if missing.
def secret_from_file
file = Rails.root.join('config', 'secrets.yml')
if file.exist?
yaml = file.read
secret = YAML.load(yaml, aliases: true).dig(Rails.env, 'secret_key_base')
if secret.blank?
lines = yaml.split("\n")
index = lines.index { |line| line.match(/\A\s*secret_key_base:\s*# ! Set production secret here/) }
if index
puts 'Writing new production secret_key_base to config/secrets.yml'
lines[index].sub!(/: \s*# ! Set production secret here/, ": #{SecureRandom.hex(64)}")
File.write(file, lines.join("\n"))
return secret_from_file
end
elsif !secret.start_with?('<%')
return secret
end
end

raise 'No secret key base found! Either set the SECRET_KEY_BASE environment variable, edit config/secrets.yml, or use Rails encrypted credentials.'
end
end
end

Rails::Application::Configuration.prepend Extensions::SecretKeyBase
2 changes: 1 addition & 1 deletion config/secrets.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ test:
# instead read values from the environment.
production:
<<: *external_api_keys
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
secret_key_base: # ! Set production secret here
smtp:
:address: smtp.gmail.com
:user_name: <%= ENV["PRODUCTION_GMAIL_USERNAME"] %>
Expand Down
2 changes: 1 addition & 1 deletion docs/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ Edit config/secrets.yml to configure the database name, user and password define

Edit config/secrets.yml to configure the app's secret_key_base which you can generate with:

bundle exec rake secret
bundle exec rails secret

Create the databases:

Expand Down

0 comments on commit 8410053

Please sign in to comment.