Rails Credentials と Secrets 2026年版:環境変数の安全な管理方法

Ruby on Rails 8 における credentials、secrets、環境変数の安全な管理方法を解説。暗号化された認証情報の設定から本番環境でのベストプラクティスまで、実践的なチュートリアル。

Rails Credentials と Secrets 2026年版:環境変数の安全な管理方法

Ruby on Rails アプリケーションにおいて、API キー、データベースパスワード、サードパーティサービスの認証情報といった機密情報の管理は、セキュリティの根幹を成す重要な課題です。2026年現在、Rails 8 では credentials システムが成熟し、より安全で使いやすい機密情報管理が可能になっています。

本記事では、Rails の credentials システムを活用した環境変数と機密情報の安全な管理方法について、基礎から本番環境でのベストプラクティスまで詳しく解説します。

Rails 8 では、credentials ファイルがデフォルトで環境ごとに分離され、より細かい権限管理が可能になっています。新規プロジェクトでは、従来の .env ファイルよりも Rails 標準の credentials を使用することが推奨されます。

Rails Credentials の基本概念

Rails credentials は、機密情報を暗号化してリポジトリに安全にコミットできる仕組みです。config/credentials.yml.enc に暗号化された認証情報が保存され、config/master.key で復号化されます。

このアプローチには以下の利点があります:

  • 機密情報をバージョン管理できる
  • 環境変数の設定漏れを防げる
  • チーム間での共有が容易
  • 本番環境へのデプロイが簡単
bash
# credentials ファイルを編集する
RAILS_MASTER_KEY=your-master-key rails credentials:edit

# または、エディタを指定して編集
EDITOR="code --wait" rails credentials:edit

環境別の Credentials 設定

Rails 8 では、環境ごとに異なる credentials ファイルを使用できます。これにより、開発環境と本番環境で異なる API キーやサービスエンドポイントを安全に管理できます。

bash
# 本番環境用の credentials を作成・編集
rails credentials:edit --environment production

# ステージング環境用の credentials を作成・編集
rails credentials:edit --environment staging

# 開発環境用の credentials を作成・編集
rails credentials:edit --environment development

これらのコマンドを実行すると、以下のファイルが生成されます:

  • config/credentials/production.yml.enc
  • config/credentials/production.key
  • config/credentials/staging.yml.enc
  • config/credentials/staging.key
yaml
# config/credentials/production.yml.enc の内容例(復号化後)
aws:
  access_key_id: AKIAIOSFODNN7EXAMPLE
  secret_access_key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
  region: ap-northeast-1
  bucket: myapp-production-assets

database:
  host: production-db.example.com
  username: myapp_prod
  password: super_secure_password_here

stripe:
  publishable_key: pk_live_xxxxx
  secret_key: sk_live_xxxxx
  webhook_secret: whsec_xxxxx

redis:
  url: redis://production-redis.example.com:6379/0

secret_key_base: a1b2c3d4e5f6...

Credentials へのアクセス方法

Rails アプリケーション内から credentials にアクセスする方法は複数あります。

ruby
# config/initializers/aws.rb
Aws.config.update(
  region: Rails.application.credentials.dig(:aws, :region),
  credentials: Aws::Credentials.new(
    Rails.application.credentials.dig(:aws, :access_key_id),
    Rails.application.credentials.dig(:aws, :secret_access_key)
  )
)

# Stripe の設定
Stripe.api_key = Rails.application.credentials.dig(:stripe, :secret_key)

環境別の credentials を使用している場合、Rails は自動的に現在の環境に対応するファイルを読み込みます。

ruby
# app/services/payment_service.rb
class PaymentService
  def initialize
    @api_key = Rails.application.credentials.stripe[:secret_key]
    @webhook_secret = Rails.application.credentials.stripe[:webhook_secret]
  end

  def process_payment(amount:, customer_id:)
    Stripe::PaymentIntent.create(
      amount: amount,
      currency: 'jpy',
      customer: customer_id
    )
  end
end

データベース設定での Credentials 活用

database.yml で credentials を参照することで、データベース接続情報を安全に管理できます。

yaml
# config/database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: myapp_development

production:
  <<: *default
  host: <%= Rails.application.credentials.dig(:database, :host) %>
  database: <%= Rails.application.credentials.dig(:database, :name) %>
  username: <%= Rails.application.credentials.dig(:database, :username) %>
  password: <%= Rails.application.credentials.dig(:database, :password) %>
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 10 } %>

マスターキーの安全な管理

マスターキーは credentials を復号化するための鍵であり、最も厳重に管理する必要があります。

bash
# .gitignore に必ずマスターキーを追加
echo "config/master.key" >> .gitignore
echo "config/credentials/*.key" >> .gitignore

本番環境では、マスターキーを環境変数として設定します。

bash
# Heroku の場合
heroku config:set RAILS_MASTER_KEY=$(cat config/credentials/production.key)

# AWS ECS の場合(Secrets Manager を使用)
aws secretsmanager create-secret \
  --name myapp/production/rails-master-key \
  --secret-string "$(cat config/credentials/production.key)"

# Docker の場合
docker run -e RAILS_MASTER_KEY=your-key-here myapp:latest

カスタム Credentials クラスの実装

大規模なアプリケーションでは、credentials へのアクセスをラップするカスタムクラスを作成すると便利です。

ruby
# app/lib/app_credentials.rb
class AppCredentials
  class MissingCredentialError < StandardError; end

  class << self
    def aws
      @aws ||= OpenStruct.new(credentials.aws || {})
    end

    def stripe
      @stripe ||= OpenStruct.new(credentials.stripe || {})
    end

    def database
      @database ||= OpenStruct.new(credentials.database || {})
    end

    def fetch(*keys)
      value = credentials.dig(*keys)
      raise MissingCredentialError, "Credential not found: #{keys.join('.')}" if value.nil?
      value
    end

    private

    def credentials
      Rails.application.credentials
    end
  end
end

このクラスを使用すると、credentials へのアクセスがより明確になります。

ruby
# 使用例
AppCredentials.aws.access_key_id
AppCredentials.stripe.secret_key
AppCredentials.fetch(:stripe, :webhook_secret)

環境変数との併用パターン

場合によっては、credentials と環境変数を併用する必要があります。以下のパターンが有効です。

ruby
# config/initializers/configuration.rb
module MyApp
  class Configuration
    def self.stripe_api_key
      ENV['STRIPE_API_KEY'] || Rails.application.credentials.dig(:stripe, :secret_key)
    end

    def self.database_url
      ENV['DATABASE_URL'] || build_database_url
    end

    private

    def self.build_database_url
      creds = Rails.application.credentials.database
      return nil unless creds

      "postgresql://#{creds[:username]}:#{creds[:password]}@#{creds[:host]}/#{creds[:name]}"
    end
  end
end

CI/CD パイプラインでの Credentials 管理

CI/CD 環境では、マスターキーを安全に渡す必要があります。

yaml
# .github/workflows/test.yml
name: Test

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    env:
      RAILS_ENV: test
      RAILS_MASTER_KEY: ${{ secrets.RAILS_MASTER_KEY }}

    steps:
      - uses: actions/checkout@v4

      - name: Set up Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: '3.4'
          bundler-cache: true

      - name: Run tests
        run: |
          bundle exec rails db:prepare
          bundle exec rspec

Credentials の検証とテスト

アプリケーション起動時に必要な credentials が設定されているかを検証することで、設定ミスを早期に発見できます。

ruby
# config/initializers/verify_credentials.rb
if Rails.env.production?
  required_credentials = [
    [:stripe, :secret_key],
    [:stripe, :webhook_secret],
    [:aws, :access_key_id],
    [:aws, :secret_access_key],
    [:database, :password]
  ]

  missing = required_credentials.reject do |keys|
    Rails.application.credentials.dig(*keys).present?
  end

  if missing.any?
    raise "Missing required credentials: #{missing.map { |k| k.join('.') }.join(', ')}"
  end
end

テスト環境では、credentials をモックすることも可能です。

ruby
# spec/rails_helper.rb
RSpec.configure do |config|
  config.before(:each) do
    allow(Rails.application.credentials).to receive(:dig)
      .with(:stripe, :secret_key)
      .and_return('sk_test_xxx')
  end
end

Ruby on Railsの面接対策はできていますか?

インタラクティブなシミュレーター、flashcards、技術テストで練習しましょう。

セキュリティのベストプラクティス

Rails credentials を安全に運用するためのベストプラクティスをまとめます。

ruby
# config/initializers/security.rb

# 1. 本番環境では必ず secret_key_base を設定
if Rails.env.production? && Rails.application.credentials.secret_key_base.blank?
  raise 'secret_key_base is not set in production credentials!'
end

# 2. 機密情報のログ出力を防ぐ
Rails.application.config.filter_parameters += [
  :password, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn,
  :api_key, :access_key, :secret_key
]

# 3. 暗号化されていない機密情報の検出
if Rails.env.development?
  Dir.glob('config/**/*.yml').each do |file|
    content = File.read(file)
    if content.match?(/password:\s*['"]?[^<]/) && !file.end_with?('.enc')
      Rails.logger.warn "Potential unencrypted secret in #{file}"
    end
  end
end

キーのローテーション

定期的なキーのローテーションは、セキュリティ維持に不可欠です。

bash
#!/bin/bash
# scripts/rotate_credentials.sh

# 現在の credentials をバックアップ
cp config/credentials/production.yml.enc config/credentials/production.yml.enc.backup
cp config/credentials/production.key config/credentials/production.key.backup

# 新しいキーで credentials を再暗号化
RAILS_ENV=production rails credentials:edit --environment production

# 新しいマスターキーを安全な場所に保存
echo "New master key: $(cat config/credentials/production.key)"
echo "Update this key in your deployment secrets!"

まとめ

Rails credentials システムは、アプリケーションの機密情報を安全に管理するための強力なツールです。環境別の credentials ファイル、マスターキーの適切な管理、CI/CD パイプラインとの統合により、セキュアで保守性の高いアプリケーションを構築できます。

主なポイントを振り返ると、環境ごとに credentials を分離し、マスターキーを絶対にリポジトリにコミットせず、本番環境では環境変数経由でマスターキーを提供し、起動時に必要な credentials の存在を検証することが重要です。

これらのベストプラクティスを実践することで、Rails アプリケーションのセキュリティを大幅に向上させることができます。

共有

関連記事