Security features in Rails 7 & 8
Ruby on Rails has long been recognized for its emphasis on security, offering developers a robust framework to build secure web applications.
With the releases of Rails 7 and the upcoming Rails 8, the framework introduces several enhancements aimed at fortifying applications against evolving threats. This article explores these security features in detail, providing insights and practical examples for implementation.
Rails 7 Security Enhancements
1. Encrypted Attributes
Rails 7 introduces native support for encrypting Active Record attributes, allowing developers to safeguard sensitive data such as emails, social security numbers, and API keys.
Implementation:
class User < ApplicationRecord
encrypts :email, :ssn
end
Key Points:
- Automatic Encryption/Decryption: Rails handles the encryption when saving to the database and decryption when retrieving, abstracting the complexity from developers.
- Deterministic vs. Non-Deterministic Encryption: By default, encryption is non-deterministic, enhancing security. However, if querying encrypted fields is necessary, deterministic encryption can be enabled:
encrypts :email, deterministic: true
- Security Implication: Even if the database is compromised, encrypted fields remain unintelligible without the encryption keys, adding a layer of protection against data breaches.
2. Cross-Site Request Forgery (CSRF) Protection
Rails 7 continues to provide built-in CSRF protection, preventing unauthorized commands from being transmitted from a user that the web application trusts.
Implementation:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
Enhancements:
- Custom CSRF Token Storage: Rails 7.1 introduces the ability to store CSRF tokens outside of sessions, reducing session bloat and improving performance.
class ApplicationController < ActionController::Base
protect_from_forgery store: CustomStore.new
end
Reference: AppSignal Blog
3. Strong Parameters
To mitigate mass assignment vulnerabilities, Rails enforces strong parameters, ensuring only permitted attributes are updated.
Example:
def user_params
params.require(:user).permit(:name, :email)
end
Best Practices:
- Always whitelist parameters explicitly.
- Avoid using
params.permit!
as it permits all parameters, potentially exposing the application to security risks.
4. Secure Password Storage
Rails leverages the bcrypt
gem to securely hash and store passwords.
Implementation:
class User < ApplicationRecord
has_secure_password
end
Enhancements in Rails 7.1:
- Password Challenge: Introduces
password_challenge
accessor and validation, enabling re-authentication flows without additional setup.
password_params = params.require(:password).permit(
:password_challenge,
:password,
:password_confirmation,
).with_defaults(password_challenge: "")
Reference: AppSignal Blog
5. Content Security Policy (CSP)
Implementing CSP helps mitigate XSS attacks by specifying allowed content sources.
Configuration:
# config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy do |policy|
policy.default_src :self, :https
policy.script_src :self, :https
end
Enhancements:
- Trusted Types Support: Rails 7 supports the experimental CSP policy with
trusted types, controlling data passed to DOM XSS sink functions
like
Element.innerHTML
.
Reference: Greg Molnar’s Blog
6. Open Redirect Protection
Rails 7 introduces a mechanism to prevent open redirects, which can be exploited for phishing attacks.
Implementation:
# config/application.rb
config.action_controller.raise_on_open_redirects = true
Behavior:
- Raises an exception if
redirect_to
is called with an untrusted URL, ensuring that redirects are only made to safe destinations.
Rails 8 Security Enhancements
1. Active Record Encryption
Building upon Rails 7’s encrypted attributes, Rails 8 enhances this feature by introducing “at-work” encryption, ensuring data remains encrypted even during processing.
Implementation:
class SensitiveDocument < ApplicationRecord
encrypts :body, at_work: true
end
Benefits:
- Enhanced Security: Protects sensitive data throughout its lifecycle, not just at rest.
- Compliance: Assists in meeting stringent data protection regulations by
minimizing data exposure.
Reference: Bounga’s Home
2. Built-in Authentication
Rails 8 introduces a native authentication system, reducing reliance on third-party gems like Devise.
Setup:
rails g authentication
rails db:migrate
Features:
- Password Encryption: Utilizes
bcrypt
for secure password storage. - Session Management: Provides controllers and views for handling user sessions.
- Customization: Offers flexibility to tailor authentication flows to specific application needs.
Reference: The Rails Drop
3. Rate Limiting with Rack::Attack
To mitigate brute-force attacks, Rails 8 integrates rate limiting capabilities using Rack::Attack.
Configuration:
# config/initializers/rack_attack.rb
class Rack::Attack
throttle('logins/ip', limit: 5, period: 20.seconds) do |req|
req.ip if req.path == '/login' && req.post?
end
end
Advantages:
- Security: Prevents abuse by limiting the number of requests from a single IP.
- Flexibility: Allows customization of throttling rules based on application requirements.
4. Solid Adapters
Rails 8 introduces Solid Adapters, reducing dependency on external services like Redis.
Components:
- Solid Cable: Replaces Redis for Action Cable, using fast polling through SQLite.
- Solid Cache: Provides disk-based caching, offering larger and more persistent caches.
- Solid Queue: Manages background jobs using database-backed queues.
Benefits:
- Simplified Architecture: Reduces the need for additional infrastructure.
- Cost-Effective: Lowers operational costs by minimizing external service
dependencies.
Reference: AppSignal Blog
5. Enhanced CSP Management
Rails 8 offers improved tools for managing Content Security Policies, allowing for more granular control over content sources.
Configuration:
Rails.application.config.content_security_policy do |policy|
policy.default_src :self, :https
policy.img_src :self, :https, :data
policy.object_src :none
end
Advantages:
- Security: Mitigates risks associated with loading untrusted content.
- Flexibility: Enables developers to define specific policies tailored to application needs.
Best Practices for Securing Rails Applications
Regardless of the Rails version, adhering to best practices is crucial for maintaining application security.
1. Regularly Update Dependencies
- Stay Current: Regularly update Rails and gems to incorporate the latest security patches.
- Monitor Vulnerabilities: Use tools like
bundler-audit
to identify known vulnerabilities in dependencies.
2. Enforce HTTPS
- Secure Communication: Ensure all data transmission is encrypted by enforcing HTTPS.
# config/environments/production.rb
config.force_ssl = true
3. Implement Proper Authentication and Authorization
- Authentication: Utilize built-in or third-party solutions to manage user authentication securely.
- Authorization: Implement role-based access controls to restrict access to sensitive resources.
4. Sanitize User Input
- Prevent Injection Attacks: Always sanitize and validate user input to prevent SQL injection and XSS attacks.
sanitize(params[:comment])
5. Monitor and Log Suspicious Activities
- Logging: Implement comprehensive logging to track user activities and detect anomalies.
- Monitoring: Use monitoring tools to alert on suspicious activities or potential breaches.
Conclusion
Rails 7 and 8 introduce significant security enhancements, reinforcing the framework’s commitment to safe web development. By leveraging these features and adhering to best practices, developers can build robust applications resilient to common threats.
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs — boost your Personal Brand & career! 🚀