Skip to Content
Course content

239: Secrets Management with Rails Credentials

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a pull request for a junior developer who had just integrated a payment gateway. Everything looked great until I scrolled down to the bottom of the file changes and saw a new file: .env. It contained the production Stripe secret key in plain text. He'd forgotten to add it to .gitignore.

Within ten minutes of that code hitting the public repository, we got an alert from Stripe. Bots had already scraped the key and were attempting to create test subscriptions. We spent the next three hours rotating keys and auditing logs. It was a stressful Friday afternoon that could have been avoided entirely if we weren't relying on plain-text files that are so easy to accidentally commit.

This is why Rails Credentials exist. Instead of keeping your secrets in a fragile .env file or haphazardly in environment variables that differ across every developer's machine, Rails provides a way to store encrypted secrets directly in your version control. You commit the encrypted file, but you keep the decryption key strictly private.

The Master Key and the Encrypted Vault

When you use credentials, Rails creates two files: config/credentials.yml.enc and config/master.key. The .enc file is an encrypted blob of YAML; if you open it in your editor, it looks like gibberish. The master.key is the "skeleton key" that allows Rails to decrypt that blob at runtime.

Here is the golden rule: Never commit your master.key to Git. It is already in your .gitignore by default, and for good reason. If someone gets your master key, your encrypted credentials are as good as plain text. In production, you don't upload the file; instead, you set an environment variable called RAILS_MASTER_KEY containing the contents of that file.

Managing Your Secrets Without a Text Editor

You don't edit the encrypted file directly. Instead, you use a built-in Rails command that decrypts the file into a temporary buffer, lets you make changes, and then re-encrypts it when you save and close the editor.

bin/rails credentials:edit

If you're using a service like SendGrid for emails, your credentials file might look like this while you're editing it:

sendgrid:
  api_key: sg_1234567890abcdefghijklmnopqrstuvwxyz
  sender_email: notifications@myapp.com
aws:
  access_key_id: AKIAIOSFODNN7EXAMPLE
  secret_access_key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

Once you save and exit, Rails encrypts this data back into credentials.yml.enc. Now, your API keys are safe in the repo, but unusable to anyone without the master key.

Retrieving Values in Your Application

Accessing these values in your Ruby code is straightforward. Rails provides a global Rails.application.credentials object. I highly recommend using the .dig method. Since credentials are nested hashes, using .dig prevents your app from crashing with a NoMethodError if a specific key is missing in a certain environment.

# The safe way to fetch a nested secret
api_key = Rails.application.credentials.dig(:sendgrid, :api_key)

if api_key.nil?
  Rails.logger.error "SendGrid API key is missing from credentials!"
end

I've seen developers try to use Rails.application.credentials[:sendgrid][:api_key], but if :sendgrid is missing, the app throws an error and crashes. Use .dig. Your future self will thank you when you're debugging a deployment at 2 AM.




📋 Practical Task

Exercise: Securing the SendGrid API Key for Transactional Emails

You are working on a notification system that needs to send welcome emails via SendGrid. Currently, the API key is hardcoded in the service class, which is a major security risk. Your task is to migrate this secret into Rails Credentials.

Requirements:

  • Run the Rails credentials editor and add a sendgrid section containing an api_key (use a fake string like "sg_test_key_123") and a sender_email ("no-reply@example.com").
  • Modify the EmailNotificationService class below to remove the hardcoded strings and instead fetch the values using Rails.application.credentials.dig.
  • Ensure the service handles the case where the credentials might be missing by logging a warning instead of crashing.
# app/services/email_notification_service.rb
class EmailNotificationService
  def initialize
    # TODO: Replace these hardcoded values with Rails Credentials
    @api_key = "sg_test_key_123" 
    @from_email = "no-reply@example.com"
  end

  def send_welcome_email(user_email)
    if @api_key.present?
      puts "Connecting to SendGrid with key #{@api_key}..."
      puts "Sending email from #{@from_email} to #{user_email}..."
      # Integration logic would go here
    else
      puts "Error: SendGrid configuration is missing!"
    end
  end
end
Rating
0 0

There are no comments for now.

to be the first to leave a comment.