Ruby on Rails

Lock away your Rails credentials key, enter it only when needed


For years I had config/master.key sitting in every checkout of my apps. Gitignored, so it felt safe enough. But with agents running around in my worktrees these days, some of them in the cloud, a key to my production secrets on disk (or in an ENV var) is a risk I don’t want to take anymore.

I’d rather keep the key in my password manager and paste it in when I need to change a credential. Rails doesn’t really let you do that though, so I built a little wrapper for it.

The problem

Run bin/rails credentials:edit without a key present and Rails doesn’t ask for the key. It happily generates a new key, which of course can’t decrypt the existing file:

$ bin/rails credentials:edit
Adding config/master.key to store the encryption key: 3f1a...

Save this in a password manager your team can access.

If you lose the key, no one, including you, can access anything encrypted with it.

      create  config/master.key

Editing config/credentials.yml.enc...
Couldn't decrypt config/credentials.yml.enc. Perhaps you passed the wrong key?

Now you have a useless key file to clean up as well.

The workarounds aren’t great either. You can prefix the command with RAILS_MASTER_KEY=..., which puts the key in your shell history. Or you write the key to disk, edit, and try to remember to delete it again afterwards.

A rake task that prompts for the key

My wrapper is a rake task around credentials:edit. When the credentials file exists but its key is missing, it asks for the key instead:

$ bin/rails credentials:prompt_edit
Missing 'config/master.key' to decrypt 'config/credentials.yml.enc'.
Enter the encryption key:
Sorry, try again.
Enter the encryption key:
Editing config/credentials.yml.enc...
File encrypted and saved.

A few things it does:

  • The key is read without echoing it to the terminal.
  • After three wrong attempts it gives up.
  • The key is only kept in memory for the duration of the edit and never written to disk.
  • Without a terminal (CI, piped input) it refuses to prompt and tells you what’s missing.
  • If the key is there, it just runs the normal command.

Getting it into Rails

I’d rather have this in Rails itself, so I opened a PR to make credentials:edit prompt for the key out of the box.

It’s still open. Reading secrets from a terminal is the kind of thing where it’s easy to miss a gotcha, so if you know your way around this, I’d love an extra pair of eyes on it. Until it lands (fingers crossed 🤞), the rake task does the job.

The code

Drop this in lib/tasks/encryption_key_prompt.rake:

# frozen_string_literal: true

# Wraps `credentials:edit` and `encrypted:edit`. When the encrypted file exists
# but its key is missing, the stock commands generate a new key that can't
# decrypt the file. These tasks prompt for the key instead and only keep it in
# memory for the duration of the edit.
#
#   bin/rails credentials:prompt_edit
#   bin/rails "credentials:prompt_edit[production]"
#   bin/rails "encrypted:prompt_edit[config/tokens.yml.enc]"
#   bin/rails "encrypted:prompt_edit[config/tokens.yml.enc,config/tokens.key]"

require "rails/command"

module EncryptionKeyPrompt
  ATTEMPTS = 3

  extend self

  def edit(command, args, content_path:, key_path:)
    if Rails.root.join(content_path).exist? && !Rails.application.encrypted(content_path, key_path: key_path).key?
      abort "Missing '#{key_path}' to decrypt '#{content_path}'. Run this in a terminal to enter the key." unless $stdin.tty?

      key = prompt_for_key(content_path, key_path)
      with_master_key(key) { Rails::Command.invoke(command, args) }
    else
      Rails::Command.invoke(command, args)
    end
  end

  # Expands "prod" to "production" like `credentials:edit --environment` does,
  # so the prompt checks the same file the command will edit.
  def expand_environment(name)
    return name if Rails.root.join("config/environments/#{name}.rb").exist?

    %w[production development test].find { |full_name| full_name.start_with?(name) } || name
  end

  private

  def prompt_for_key(content_path, key_path)
    puts "Missing '#{key_path}' to decrypt '#{content_path}'."

    ATTEMPTS.times do |attempt|
      puts "Sorry, try again." if attempt.positive?
      key = ask_without_echo("Enter the encryption key: ")
      return key if valid_key?(key, content_path, key_path)
    end

    warn "#{ATTEMPTS} incorrect encryption key attempts."
    exit 1
  rescue Interrupt
    puts "Aborted."
    exit 1
  end

  def ask_without_echo(prompt)
    require "io/console"

    $stdin.noecho do
      print prompt
      ($stdin.gets or raise Interrupt).strip
    end
  ensure
    puts
  end

  # Decrypting never checks the key length, and a key one character short can
  # still decrypt, so check the length here before saving fails on it.
  def valid_key?(key, content_path, key_path)
    return false unless key.length == ActiveSupport::EncryptedFile.expected_key_length

    with_master_key(key) { Rails.application.encrypted(content_path, key_path: key_path).read }
    true
  rescue ActiveSupport::MessageEncryptor::InvalidMessage
    false
  end

  def with_master_key(key)
    previous_key = ENV.fetch("RAILS_MASTER_KEY", nil)
    ENV["RAILS_MASTER_KEY"] = key
    yield
  ensure
    ENV["RAILS_MASTER_KEY"] = previous_key
  end
end

namespace :credentials do
  desc "Like credentials:edit, but prompts for the key when it's missing"
  task :prompt_edit, [:environment] do |_task, args| # rubocop:disable Rails/RakeEnvironment -- booting the app may need the missing key
    if args[:environment]
      environment = EncryptionKeyPrompt.expand_environment(args[:environment])
      content_path = "config/credentials/#{environment}.yml.enc"
      key_path = "config/credentials/#{environment}.key"
      command_args = ["--environment", environment]
    else
      content_path = Rails.application.config.credentials.content_path.relative_path_from(Rails.root).to_s
      key_path = Rails.application.config.credentials.key_path.relative_path_from(Rails.root).to_s
      command_args = []
    end

    EncryptionKeyPrompt.edit("credentials:edit", command_args, content_path: content_path, key_path: key_path)
  end
end

namespace :encrypted do
  desc "Like encrypted:edit, but prompts for the key when it's missing"
  task :prompt_edit, [:file, :key] do |_task, args| # rubocop:disable Rails/RakeEnvironment -- booting the app may need the missing key
    abort "Usage: bin/rails \"encrypted:prompt_edit[config/file.yml.enc,config/master.key]\"" unless args[:file]
    key_path = args[:key] || "config/master.key"

    EncryptionKeyPrompt.edit("encrypted:edit", [args[:file], "--key", key_path], content_path: args[:file], key_path: key_path)
  end
end

I've got some availability for new clients! Want to move faster on your Rails app, migrate that old legacy system, or agent-proof your development setup? With 15 years of Rails experience and building with AI agents every day, I could be a great fit.

Get in touch