Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a migration to encrypt database password using scram-sha-256 #757

Merged
merged 1 commit into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions db/migrate/20241017013023_reencrypt_password_scramsha.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class ReencryptPasswordScramsha < ActiveRecord::Migration[6.1]
def up
say_with_time('Reencrypting database user password with scram-sha-256') do
db_config = ActiveRecord::Base.connection_db_config.configuration_hash
username = db_config[:username]
password = connection.raw_connection.encrypt_password(db_config[:password], username, "scram-sha-256")

connection.execute <<-SQL
ALTER ROLE #{username} WITH PASSWORD '#{password}';
Fryguy marked this conversation as resolved.
Show resolved Hide resolved
SQL
end
end
end
22 changes: 22 additions & 0 deletions spec/migrations/20241017013023_reencrypt_password_scramsha_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
require_migration

# This is mostly necessary for data migrations, so feel free to delete this
# file if you do no need it.
describe ReencryptPasswordScramsha do
migration_context :up do
it "Ensures that the user password is stored as scram-sha-256" do
migrate

username = ActiveRecord::Base.connection_db_config.configuration_hash[:username]

users_and_passwords = ActiveRecord::Base.connection.execute <<-SQL
SELECT rolname, rolpassword FROM pg_authid WHERE rolcanlogin;
SQL

record = users_and_passwords.to_a.detect { |i| i["rolname"] == username }

expect(record["rolname"]).to eq(username)
expect(record["rolpassword"]).to match(/^SCRAM-SHA-256.*/)
end
end
end