development_secret.txtってなんだ?

こんにちは!kossyです!



さて、今回はRails 6 でアプリケーションを開発している時に見つけたテキストファイルである、
「./tmp/development_secret.txt」についてブログに残してみたいと思います。



dev環境およびテスト環境の場合にsecret_key_baseを生成するために使う

Railsの公式ドキュメントを見てみました。

Rails::Application

The secret_key_base is used as the input secret to the application's key generator, which in turn is used to create all MessageVerifiers/MessageEncryptors, including the ones that sign and encrypt cookies.

In development and test, this is randomly generated and stored in a temporary file in tmp/development_secret.txt.

In all other environments, we look for it first in ENV, then credentials.secret_key_base, and finally secrets.secret_key_base. For most applications, the correct place to store it is in the encrypted credentials file.

secret_key_baseは、アプリケーションのキージェネレーターへの入力シークレットとして使用され、Cookieの署名および暗号化を含むすべてのMessageVerifiers / MessageEncryptorsの作成に使用されます。
開発環境およびテスト環境では、これはランダムに生成され、tmp / development_secret.txtの一時ファイルに保存されます。
他のすべての環境では、まずENVで検索し、次にcredentials.secret_key_base、最後にsecrets.secret_key_baseで検索します。ほとんどのアプリケーションでは、暗号化された資格情報ファイルに正しい場所が保存されています。

ソースコードはこの辺りかと。

def secrets
  @secrets ||= begin
    secrets = ActiveSupport::OrderedOptions.new
    files = config.paths["config/secrets"].existent
    files = files.reject { |path| path.end_with?(".enc") } unless config.read_encrypted_secrets
    secrets.merge! Rails::Secrets.parse(files, env: Rails.env)

    # Fallback to config.secret_key_base if secrets.secret_key_base isn't set
    secrets.secret_key_base ||= config.secret_key_base

    secrets
  end
end

def secret_key_base
  if Rails.env.development? || Rails.env.test?
    secrets.secret_key_base ||= generate_development_secret
  else
    validate_secret_key_base(
      ENV["SECRET_KEY_BASE"] || credentials.secret_key_base || secrets.secret_key_base
    )
  end
end

def generate_development_secret
  if secrets.secret_key_base.nil?
    key_file = Rails.root.join("tmp/development_secret.txt")

    if !File.exist?(key_file)
      random_key = SecureRandom.hex(64)
      FileUtils.mkdir_p(key_file.dirname)
      File.binwrite(key_file, random_key)
    end

    secrets.secret_key_base = File.binread(key_file)
  end

  secrets.secret_key_base
end

developement環境またはtest環境の時はtmp下のtxtファイルを用いてsecret_key_baseを決める実装になってます。


勉強になりました。

  @valiable ||= begin
  end

の書き方は実務でも使えそうです。