Ruby on Rails is a popular web application framework designed for developer productivity and code readability. While it is a delight to work with, it is important to understand how to maintain the security of your Rails applications. We will cover the essentials in that regard in this article. We will discuss Rails secrets, best practices for user password security, and securing your environments.
Rails 5.2 introduced a new feature known as Encrypted Credentials to replace the older secrets.yml file. With this feature, Rails' master.key and credentials.yml.enc are used to store sensitive data. The master.key file is used to decrypt the credentials file for use in the application.
# To edit the credentials, run:
EDITOR="nano" rails credentials:edit
For security purposes, the master.key file should not be checked into your version control system (like git). Instead, it should be shared securely with your team and backup service.
In Rails, the gem 'bcrypt' is a popular choice for securing user passwords. This gem is capable of hashing passwords and comparing hashed values to prevent storing raw password strings in your database. This is important because it means if your database is compromised, your users' passwords would still not be accessible in plain text.
# In the Gemfile
gem 'bcrypt', '~> 3.1.7'
# In your User model
has_secure_password
In combination with bcrypt, it’s also recommended to follow these best practices:
Environment variables are a secure way to store sensitive data like API keys, passwords, and database URIs. With the figaro gem in Rails, we can easily manage environment variables.
# In the Gemfile
gem 'figaro'
# Create the application.yml file
bundle exec figaro install
This generates config/application.yml, where you can store your environment-specific information. The file is added to .gitignore by default, increasing the security of your sensitive data.
Securing your Ruby on Rails applications is a key aspect of development. This guide has provided insight into securing secrets files, user passwords and environments in Rails. Additionally, remember that maintaining software and dependencies up to date, and educating your team about security best practices, also play significant roles in application security. Happy secure coding!