Skip to content

Commit

Permalink
Merge pull request #23259 from jrafanie/properly-reset-cached-secrets
Browse files Browse the repository at this point in the history
Reset cached secrets on Rails 7.0
  • Loading branch information
bdunne authored Nov 7, 2024
2 parents 1b2f4e7 + 8f8ac7e commit bd4b369
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
5 changes: 5 additions & 0 deletions app/models/mixins/miq_web_server_worker_mixin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ def configure_secret_token(token = MiqDatabase.first.session_secret_token)
return if Rails.application.config.secret_key_base

Rails.application.config.secret_key_base = token

# To set a secret token after the Rails.application is initialized,
# we need to reset the secrets since they are cached:
# https://github.com/rails/rails/blob/7-0-stable/railties/lib/rails/application.rb#L392-L404
Rails.application.secrets = nil if Rails.version < "7.1"
end

def rails_server
Expand Down
11 changes: 6 additions & 5 deletions spec/models/mixins/miq_web_server_worker_mixin_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,20 @@
end

before do
@token = Rails.application.config.secret_key_base
@credentials = Rails.application.credentials
@token = Rails.application.secret_key_base
MiqDatabase.seed
end

after do
Rails.application.config.secret_key_base = @token
Rails.application.credentials = @credentials
Rails.application.secrets = nil if Rails.version < "7.1"
end

it ".configure_secret_token defaults to MiqDatabase session_secret_token" do
Rails.application.config.secret_key_base = nil

test_class.configure_secret_token
expect(Rails.application.secret_key_base).to eq(MiqDatabase.first.session_secret_token)
expect(Rails.application.config.secret_key_base).to eq(MiqDatabase.first.session_secret_token)
end

Expand All @@ -37,16 +37,17 @@

token = SecureRandom.hex(64)
test_class.configure_secret_token(token)
expect(Rails.application.secret_key_base).to eq(token)
expect(Rails.application.config.secret_key_base).to eq(token)
end

it ".configure_secret_token does not reset secrets when token already configured" do
existing_value = SecureRandom.hex(64)
Rails.application.config.secret_key_base = existing_value
Rails.application.credentials = nil
Rails.application.credentials
Rails.application.secrets = nil if Rails.version < "7.1"

test_class.configure_secret_token
expect(Rails.application.secret_key_base).to eq(existing_value)
expect(Rails.application.config.secret_key_base).to eq(existing_value)
end

Expand Down

0 comments on commit bd4b369

Please sign in to comment.