Rails credentials: Always use the bang version

Posted . Visible to the public. Repeats.

Rails credentials are a way to store secrets in an encrypted YAML file. Usage is simple: each key in the credentials file becomes a method on Rails.application.credentials, returning the corresponding secret.

# Credentials file
file_storage_secret: superstrongsecret
# Somewhere in the application
FileStorage.secret = Rails.application.credentials.file_storage_secret

Since credentials usually are different between environments, you can easily forget to define them for another environment. If it is an API token, you'll quickly notice. However, if it is some kind of hashing salt, it might be missing without you noticing.

Suggestion

To be sure, always access credentials with a trailing exclamation mark:

FileStorage.secret = Rails.application.credentials.file_storage_secret! # <- Here

This way, Rails will raise in case it is missing.

The same applies to the older "Rails secrets" stored in config/secrets.yml.

Dominik Schöler
Last edit
Daniel Straßner
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2024-09-23 08:37)