๐Ÿ” Understanding TLS in Web: How HTTPS Works and Performance Considerations

Secure communication over HTTPS is powered by TLS (Transport Layer Security). In this post, we’ll explore:

  • The TLS handshake step by step
  • Performance impacts and optimizations
  • Real-world examples and a visual diagram

โ“ Why TLS Matters

The Problem with Plain HTTP

  • Data in plaintext: Every header, URL, form field (including passwords) is exposed.
  • Easy to intercept: Public Wiโ€‘Fi or malicious network nodes can read or tamper with requests.

With TLS, your browser and server create a secure, encrypted tunnel, protecting confidentiality and integrity.

The TLS Handshake ๐Ÿค๐Ÿป (Simplified)

Below is a diagram illustrating the core steps of a TLS 1.2 handshake. TLS 1.3 is similar but reduces round trips:

Handshake Breakdown

  1. ClientHello
    • Announces TLS version, cipher suites, and random nonce.
  2. ServerHello + Certificate
    • Server selects parameters and presents its X.509 certificate (with public key).
  3. Key Exchange
    • Client encrypts a “pre-master secret” with the server’s public key.
  4. ChangeCipherSpec & Finished
    • Both sides notify each other that future messages will be encrypted, then exchange integrity-checked “Finished” messages.

Once complete, all application data (HTTP requests/responses) flows through a symmetric cipher (e.g., AES), which is fast and secure.

โšก Performance: Overhead and Optimizations

๐Ÿ•’ Latency Costs

  • Full TLS 1.2 handshake: ~2 extra network roundโ€‘trips (100โ€“200โ€ฏms).
  • TLS 1.3 handshake: Only 1 RTT โ€” significantly faster.

Key Optimizations

๐Ÿ”ง Technique๐ŸŽ Benefit
Session ResumptionSkip full handshake using session tickets
HTTP/2 + Keepโ€‘AliveReuse one TCP/TLS connection for many requests
TLS 1.3Fewer round trips; optional 0โ€‘RTT data
ECDSA CertificatesFaster cryptography than RSA
TLS Offloading/CDNHardware or edge servers handle encryption

๐Ÿ’ป Real-World Example: Enabling TLS in Rails

  1. Obtain a Certificate (Let’s Encrypt, commercial CA)
  2. Configure Nginx (example snippet)
server {
  listen 443 ssl http2;
  server_name example.com;

  ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

  ssl_protocols       TLSv1.2 TLSv1.3;
  ssl_ciphers         HIGH:!aNULL:!MD5;

  location / {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto https;
  }
}

  1. Force HTTPS in Rails
# config/environments/production.rb file
config.force_ssl = true

With this setup, Rails responds only over encrypted channels, and browsers automatically redirect HTTP to HTTPS.

๐Ÿ“Š Measuring Impact

Run curl -w to compare:

# HTTP
โœ— curl -o /dev/null -s -w "HTTP time: %{time_total}s\n" "http://railsdrop.com"
HTTP time: 0.634649s

# HTTPS
โœ— curl -o /dev/null -s -w "HTTP time: %{time_total}s\n" "https://railsdrop.com"
HTTP time: 1.571834s

Typical difference is milliseconds once session resumption and keepโ€‘alive take effect.

โœ… Key Takeaways

  • TLS handshake uses asymmetric crypto to establish a symmetric key, then encrypts all traffic.
  • TLS 1.3 and optimizations (resumption, HTTP/2) minimize latency.
  • Modern hardware and CDNs make HTTPS nearly as fast as HTTP.
  • Always enable TLS for any site handling sensitive data.

๐Ÿ”— Secure your apps todayโ€”HTTPS is no longer optional!

๐Ÿ” SSL: The Security Foundation of the Modern Web

๐Ÿ‘‹ Introduction

In today’s digital landscape, SSL (Secure Sockets Layer) and its successor TLS (Transport Layer Security) form the backbone of internet security. Every time you see that reassuring padlock icon in your browser’s address bar, you’re witnessing SSL/TLS in action. But what exactly is SSL, how does it work, and why has it become so crucial for every website owner? Let’s dive deep into the world of SSL certificates and explore how they’ve transformed the web.

โš™๏ธ What is SSL and How Does It Work?

SSL (Secure Sockets Layer) is a cryptographic protocol designed to provide secure communication over a computer network. While SSL has been largely replaced by TLS (Transport Layer Security), the term “SSL” is still commonly used to refer to both protocols.

The SSL Handshake Process

When you visit a website with SSL enabled, a complex but lightning-fast process occurs:

  1. Client Hello: Your browser sends a “hello” message to the server, including supported encryption methods
  2. Server Hello: The server responds with its chosen encryption method and sends its SSL certificate
  3. Certificate Verification: Your browser verifies the certificate’s authenticity against trusted Certificate Authorities (CAs)
  4. Key Exchange: Both parties establish a shared secret key for encryption
  5. Secure Connection: All subsequent communication is encrypted using the established key

Encryption Types

SSL uses two types of encryption:

  • Symmetric Encryption: Fast encryption using the same key for both encryption and decryption
  • Asymmetric Encryption: Uses a pair of keys (public and private) for initial handshake and key exchange

๐ŸŒ How SSL Transformed the Web

Before SSL: The Wild West of the Internet

In the early days of the web, all data transmitted between browsers and servers was sent in plain text. This meant:

  • No Privacy: Anyone intercepting traffic could read sensitive information
  • No Integrity: Data could be modified without detection
  • No Authentication: No way to verify you were communicating with the intended server

The SSL Revolution

SSL implementation brought three fundamental security principles to the web:

  1. Confidentiality: Data encryption ensures only intended recipients can read the information
  2. Integrity: Cryptographic hashes detect any tampering with data during transmission
  3. Authentication: Digital certificates verify the identity of websites

Impact on E-commerce and Online Services

SSL made modern e-commerce possible by:

  • Enabling secure credit card transactions
  • Building user trust in online services
  • Protecting sensitive personal information
  • Facilitating the growth of online banking and financial services

๐Ÿ“œ SSL Certificates: Your Digital Identity Card

An SSL certificate is a digital document that:

  • Proves the identity of a website
  • Contains the website’s public key
  • Is digitally signed by a trusted Certificate Authority (CA)

Types of SSL Certificates

1. Domain Validated (DV) Certificates

  • Validation: Only verifies domain ownership
  • Trust Level: Basic
  • Use Case: Personal websites, blogs
  • Issuance Time: Minutes to hours

2. Organization Validated (OV) Certificates

  • Validation: Verifies domain ownership and organization details
  • Trust Level: Medium
  • Use Case: Business websites
  • Issuance Time: 1-3 days

3. Extended Validation (EV) Certificates

  • Validation: Rigorous verification of organization’s legal existence
  • Trust Level: Highest
  • Use Case: E-commerce, banking, high-security sites
  • Issuance Time: 1-2 weeks

Certificate Coverage Options

  • Single Domain: Protects one specific domain (e.g., http://www.example.com)
  • Multi-Domain (SAN): Protects multiple different domains
  • Wildcard: Protects a domain and all its subdomains (e.g., *.example.com)

๐Ÿ› ๏ธ How to Get and Implement SSL Certificates

Step 1: Choose Your SSL Provider

Select from various Certificate Authorities based on your needs:

  • Free Options: Let’s Encrypt, SSL.com Free
  • Commercial Providers: DigiCert, GlobalSign, Sectigo, GoDaddy

Step 2: Generate a Certificate Signing Request (CSR)

# Example using OpenSSL
openssl req -new -newkey rsa:2048 -nodes -keyout yourdomain.key -out yourdomain.csr

Step 3: Validate Domain Ownership

Certificate Authorities typically offer three validation methods:

  • Email Validation: Receive validation email at admin@yourdomain.com
  • DNS Validation: Add a specific TXT record to your DNS
  • HTTP File Upload: Upload a verification file to your website

Step 4: Install the Certificate

Installation varies by server type:

Apache

<VirtualHost *:443>
    ServerName www.yourdomain.com
    SSLEngine on
    SSLCertificateFile /path/to/yourdomain.crt
    SSLCertificateKeyFile /path/to/yourdomain.key
    SSLCertificateChainFile /path/to/intermediate.crt
</VirtualHost>

Nginx

server {
    listen 443 ssl;
    server_name www.yourdomain.com;

    ssl_certificate /path/to/yourdomain.crt;
    ssl_certificate_key /path/to/yourdomain.key;
    ssl_protocols TLSv1.2 TLSv1.3;
}

Step 5: Configure HTTP to HTTPS Redirect

# Apache .htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

โš ๏ธ The Cost of Not Having SSL

SEO Impact

  • Google Ranking Factor: HTTPS is a confirmed ranking signal
  • Browser Warnings: Modern browsers flag non-HTTPS sites as “Not Secure”
  • User Trust: Visitors are likely to leave unsecured sites

Security Risks

  • Data Interception: Sensitive information transmitted in plain text
  • Man-in-the-Middle Attacks: Attackers can intercept and modify communications
  • Session Hijacking: User sessions can be stolen on unsecured networks

Business Consequences

  • Lost Revenue: Users abandon transactions on insecure sites
  • Compliance Issues: Many regulations require encryption (GDPR, PCI DSS)
  • Reputation Damage: Security breaches can destroy customer trust

๐Ÿ’ฐ SSL Providers: Free vs. Paid Services

Free SSL Providers

Let’s Encrypt

  • Cost: Completely free
  • Validity: 90 days (auto-renewable)
  • Support: Domain and wildcard certificates
  • Automation: Excellent with tools like Certbot
  • Limitation: DV certificates only
# Install Let's Encrypt certificate with Certbot
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

SSL.com Free

  • Cost: Free for basic DV certificates
  • Validity: 90 days
  • Features: Basic domain validation

Cloudflare SSL

  • Cost: Free with Cloudflare service
  • Features: Universal SSL for all domains
  • Limitation: Requires using Cloudflare as CDN/proxy

Commercial SSL Providers

DigiCert

  • Reputation: Industry leader with highest trust
  • Features: EV, OV, DV certificates with extensive support
  • Price Range: $175-$595+ annually
  • Benefits: 24/7 support, warranty, advanced features

GlobalSign

  • Strengths: Enterprise-focused solutions
  • Features: Complete certificate lifecycle management
  • Price Range: $149-$649+ annually

Sectigo (formerly Comodo)

  • Position: Largest commercial CA by volume
  • Features: Wide range of certificate types
  • Price Range: $89-$299+ annually

GoDaddy

  • Advantage: Integration with hosting services
  • Features: Easy installation for beginners
  • Price Range: $69-$199+ annually

Cloud Provider SSL Solutions

AWS Certificate Manager (ACM)

  • Cost: Free for AWS services
  • Integration: Seamless with CloudFront, Load Balancers, API Gateway
  • Automation: Automatic renewal and deployment
  • Limitation: Only works within AWS ecosystem
# Request certificate via AWS CLI
aws acm request-certificate \
    --domain-name yourdomain.com \
    --subject-alternative-names www.yourdomain.com \
    --validation-method DNS

Google Trust Services

  • Integration: Works with Google Cloud Platform
  • Features: Managed certificates for Google Cloud Load Balancer
  • Cost: Free for Google Cloud services
  • Automation: Automatic provisioning and renewal

Azure SSL

  • Service: App Service Certificates
  • Integration: Native Azure integration
  • Features: Wildcard and standard certificates available

โœ… Best Practices for SSL Implementation

Security Configuration

  1. Use Strong Ciphers: Disable weak encryption algorithms
  2. Enable HSTS: Force HTTPS connections
  3. Configure Perfect Forward Secrecy: Protect past communications
  4. Regular Updates: Keep SSL/TLS libraries updated

Monitoring and Maintenance

  • Certificate Expiration Monitoring: Set up alerts before expiration
  • Security Scanning: Regular vulnerability assessments
  • Performance Monitoring: Track SSL handshake performance

Common Pitfalls to Avoid

  • Mixed Content: Ensure all resources load over HTTPS
  • Certificate Chain Issues: Include intermediate certificates
  • Weak Configurations: Avoid outdated protocols and ciphers

๐Ÿš€ The Future of SSL/TLS

TLS 1.3 Adoption

  • Faster handshakes
  • Improved security
  • Better performance

Certificate Transparency

  • Public logs of all certificates
  • Enhanced security monitoring
  • Improved detection of unauthorized certificates

Automated Certificate Management

  • ACME protocol standardization
  • Integration with CI/CD pipelines
  • Infrastructure as Code compatibility

๐ŸŽฏ Conclusion

SSL/TLS has evolved from a nice-to-have security feature to an absolute necessity for any serious web presence. Whether you choose a free solution like Let’s Encrypt for basic protection or invest in enterprise-grade certificates from providers like DigiCert, implementing SSL is no longer optionalโ€”it’s essential.

The transformation from an insecure web to today’s encrypted-by-default internet represents one of the most significant security improvements in computing history. As we move forward, SSL/TLS will continue to evolve, becoming faster, more secure, and easier to implement.

For website owners, the message is clear: implement SSL today, keep your certificates updated, and follow security best practices. Your users’ trust and your website’s success depend on it.


Remember: Security is not a destination but a journey. Stay informed about the latest SSL/TLS developments and regularly review your security configurations to ensure optimal protection for your users and your business.

Happy Web coding! ๐Ÿš€

A Complete Guide to Ruby on Rails Security Measures ๐Ÿ›ก๏ธ

Ruby on Rails is known for its developer-friendly conventions, but it’s also built with security in mind. While the framework provides many features to guard against common threats, it’s up to developers to understand and apply them correctly.

In this post, weโ€™ll walk through essential Rails security measures, tackle real-world threats, and share best practices – with examples for both API-only and full-stack Rails applications.

๐Ÿšจ Common Web Threats Rails Helps Mitigate

  1. SQL Injection
  2. Cross-Site Scripting (XSS)
  3. Cross-Site Request Forgery (CSRF)
  4. Mass Assignment
  5. Session Hijacking
  6. Insecure Deserialization
  7. Insecure File Uploads
  8. Authentication & Authorization flaws

Let’s explore how Rails addresses these and what you can do to reinforce your app.


1. ๐Ÿงฑ SQL Injection

๐Ÿ›ก๏ธ Rails Protection:

Threat: Attackers inject malicious SQL through user inputs to read, modify, or delete database records

Rails uses Active Record with prepared statements to prevent SQL injection by default.

Arel: Build complex queries without string interpolation.

# Safe - uses bound parameters
User.where(email: params[:email])

# โŒ Dangerous - interpolates input directly
User.where("email = '#{params[:email]}'")

# Safe: Parameterized query
User.where("role = ? AND created_at > ?", params[:role], 7.days.ago)

# Using Arel for dynamic conditions
users = User.arel_table
def recent_admins
  User.where(users[:role].eq('admin').and(users[:created_at].gt(7.days.ago)))
end

Tip: Never use string interpolation to build SQL queries. Use .where, .find_by, or Arel methods.

Additional Measures

  • Whitelist Columns: Pass only known column names to dynamic ordering or filtering.
  • Gem: activerecord-security to raise errors on unsafe query methods.

2. ๐Ÿงผ Cross-Site Scripting (XSS)

Threat: Injection of malicious JavaScript via user inputs, compromising other usersโ€™ sessions.

๐Ÿ›ก๏ธ Rails Protection

Content Security Policy (CSP): Limit sources of executable scripts.

# config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy do |policy|
  policy.default_src :self
  policy.script_src  :self, :https
  policy.style_src   :self, :https
end

Auto-Escaping: <%= %> escapes HTML; <%== %> and raw do not.

Rails auto-escapes output in views.

<!-- Safe: Escaped -->
<%= user.bio %>

<!-- Unsafe: Unescaped (only use if trusted) -->
<%= raw user.bio %>

In API-only apps: Always sanitize any input returned in JSON if used in web contexts later.

Use gems:

  • sanitize gem to strip malicious HTML
  • loofah for more control (Loofah for robust HTML5 handling and scrubbers.)
# In models or controllers
clean_bio = Loofah.fragment(params[:bio]).scrub!(:prune).to_s

3. ๐Ÿ” Cross-Site Request Forgery (CSRF)

๐Ÿ” How CSRF Works (Example)

1.Victim logs in to bank.example.com, receiving a session cookie.

2. Attacker crafts a hidden form on attacker.com:

<form action="https://bank.example.com/transfer" method="POST">
  <input type="hidden" name="amount" value="1000">
  <input type="hidden" name="to_account" value="attacker_account">
</form>
<script>document.forms[0].submit();</script>

3. Victim visits attacker.com while still logged into the bank.

4. Browser auto-sends the bank session cookie with the forged POSTโ€”and the transfer goes through, because the bank sees a โ€œlegitimateโ€ logged-in request.

๐Ÿ›ก๏ธ Rails’ CSRF Protection

Rails ships with built-in defenses against CSRF by embedding an unguessable token in forms and verifying it on each non-GET request.

1.protect_from_forgery

In ApplicationController, Rails by default includes:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

This causes Rails to raise an exception if the token is missing or invalid.

Refer: https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html

2. Authenticity Token in Forms

All Rails form-builders (form_with, form_for, form_tag) automatically insert:

<input type="hidden" name="authenticity_token" value="โ€ฆsecure randomโ€ฆ">

3.Meta Tag for AJAX

Rails also inserts in <head>:

<%= csrf_meta_tags %>

Which renders:

<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="โ€ฆsecure randomโ€ฆ" />

Rails UJS or Turbo JS will read these and include the token on XHR/fetch requests.

4.Server-Side Verification

On each POST/PUT/PATCH/DELETE, Rails:

  • Extracts the token (from form param, header X-CSRF-Token, or query string).
  • Compares it to the session-stored token.
  • Rejects the request if they donโ€™t match.

API-only apps:

CSRF is less relevant for stateless APIs using tokens, but if you use session-based authentication, enable CSRF protection:

# application_controller.rb
protect_from_forgery with: :exception

Thought for a couple of seconds

Cross-Site Request Forgery (CSRF) is an attack that tricks a userโ€™s browser into submitting a request (e.g. form submission, link click) to your application without the userโ€™s intention, leveraging the fact that the browser automatically includes credentials (cookies, basic auth headers, etc.) with each request.

๐Ÿ”ง Disabling or Customizing CSRF

โ™ฆ๏ธ Disable for APIs (stateless JSON endpoints):

class Api::BaseController < ActionController::API skip_before_action :verify_authenticity_token end

โ™ฆ๏ธ Use Null Session (allowing some API use without exception):

protect_from_forgery with: :null_session

โœ… Key Takeaways

  • CSRF exploits the browserโ€™s automatic credential sending.
  • Rails guards by inserting and validating an unguessable token.
  • Always keep protect_from_forgery with: :exception in your base controller for full-stack Rails apps.

4. ๐Ÿ›‘ Mass Assignment Vulnerability

Threat: Attackers pass unexpected parameters to update sensitive attributes (e.g., admin=true).

Before Rails 4, mass assignment was a common issue. Now, strong parameters protect against it.

โœ… Use Strong Parameters:

# โœ… Safe
def user_params
  params.require(:user).permit(:name, :email)
end

User.create(user_params)

# โŒ Unsafe
User.create(params[:user])

Pro tip: Don’t over-permit, especially with admin or role-based attributes.

Real-World Gotcha

  • Before permitting arrays or nested attributes, validate length and content.
params.require(:order).permit(:total, items: [:product_id, :quantity])

5. ๐Ÿ”’ Secure Authentication

Built-In: has_secure_password

Provides authenticate method.

Uses BCrypt with configurable cost.

# user.rb
class User < ApplicationRecord
  has_secure_password
  # optional: validates length, complexity
  validates :password, length: { minimum: 12 }, format: { with: /(?=.*\d)(?=.*[A-Z])/ }
end

Make sure you have a password_digest column. This uses bcrypt under the hood.

Using Devise

JWT: integrate with devise-jwt for stateless APIs.

Modules: Database Authenticatable, Confirmable, Lockable, Timeoutable, Trackable.

Devise gives you:

  • Password encryption
  • Lockable accounts
  • Timeoutable sessions
  • Token-based authentication for APIs (with devise-jwt)
# config/initializers/devise.rb
Devise.setup do |config|
  config.jwt do |jwt|
    jwt.secret = Rails.application.credentials.devise_jwt_secret
    jwt.dispatch_requests = [['POST', %r{^/login$}]]
    jwt.revocation_requests = [['DELETE', %r{^/logout$}]]
  end
end

6. ๐Ÿงพ Authorization

Threat: Users access or modify resources beyond their permissions.

Never trust the frontend. Always check permissions server-side.

# โŒ Dangerous
redirect_to dashboard_path if current_user.admin?

# โœ… Use Pundit or CanCanCan
authorize @order

Gems:

  • pundit โ€“ lean policy-based authorization
  • cancancan โ€“ rule-based authorization

Pundit Example

# app/policies/article_policy.rb
class ArticlePolicy
  attr_reader :user, :article

  def initialize(user, article)
    @user = user
    @article = article
  end

  def update?
    user.admin? || article.author_id == user.id
  end
end

# In controller
def update
  @article = Article.find(params[:id])
  authorize @article
  @article.update!(article_params)
end

Use Existing Auditing Libraries

To track user actions including access, use:

For Rails 8 check the post for Rails own Authentication: https://railsdrop.com/2025/05/07/rails-8-implement-users-authentication-orders-order-items/

7. ๐Ÿ—ƒ๏ธ Secure File Uploads

Threat: Attackers upload malicious files (e.g., scripts, executables).

Use Active Storage securely:

<%= image_tag url_for(user.avatar) %>

Active Storage Best Practices

Validation:

class Photo < ApplicationRecord
  has_one_attached :image
  validate :image_type, :image_size

  private
  def image_type
    return unless image.attached?
    acceptable = ['image/jpeg', 'image/png']
    errors.add(:image, 'must be JPEG or PNG') unless acceptable.include?(image.content_type)
  end

  def image_size
    return unless image.attached?
    errors.add(:image, 'is too big') if image.byte_size > 5.megabytes
  end
end
  • Validate content type:
validates :avatar, content_type: ['image/png', 'image/jpg', 'image/jpeg']

  • Restrict file size.
  • Store uploads in private S3 buckets for sensitive data.
  • Private URLs for sensitive documents (e.g., contracts).
  • Virus Scanning: hook into after_upload to scan with ClamAV (or VirusTotal API).

8. ๐Ÿงพ HTTP Headers & SSL

Rails helps with secure headers via secure_headers gem (https://github.com/github/secure_headers).

# config/initializers/secure_headers.rb
SecureHeaders::Configuration.default do |config|
  config.hsts = "max-age=31536000; includeSubDomains"
  config.x_frame_options = "DENY"
  config.x_content_type_options = "nosniff"
  config.x_xss_protection = "1; mode=block"
end

SSL/TLS Force HTTPS:

# config/environments/production.rb
config.force_ssl = true

Ensure HSTS is enabled:
# config/initializers/secure_headers.rb
Rails.application.config.middleware.insert_before 0, SecureHeaders::Middleware
SecureHeaders::Configuration.default do |config|
  config.hsts = "max-age=63072000; includeSubDomains; preload"
end

Key Headers

  • X-Frame-Options: DENY to prevent clickjacking.
  • X-Content-Type-Options: nosniff.
  • Referrer-Policy: strict-origin-when-cross-origin.

9. ๐Ÿงช Security Testing

  • Use brakeman to detect common vulnerabilities.
bundle exec brakeman

  • Add bundler-audit to scan for insecure gems.
bundle exec bundler-audit check --update

Check the post for more details: https://railsdrop.com/2025/05/05/rails-8-setup-simplecov-brakeman-for-test-coverage-security/

  • Fuzz & Pen Testing: Use tools like ZAP Proxy, OWASP ZAP.
  • Use RSpec tests for role restrictions, parameter whitelisting, and CSRF.
describe "Admin access" do
  it "forbids non-admins from deleting users" do
    delete admin_user_path(user)
    expect(response).to redirect_to(root_path)
  end
end

  • Continuous Integration – Integrate scans in CI pipeline (GitHub Actions example):
jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Brakeman
        run: bundle exec brakeman -o brakeman-report.html
      - name: Bundler Audit
        run: bundle exec bundler-audit check --update

Read the post: Setup ๐Ÿ›  Rails 8 App โ€“ Part 15: Set Up CI/CD โš™๏ธ with GitHub Actions for Rails 8

10. ๐Ÿ”‘ API Security (Extra Measures)

  • Use JWT or OAuth2 for stateless token authentication.
  • Set appropriate CORS headers.

Gem: `rack-cors` (https://github.com/cyu/rack-cors)

Add in your Gemfile:

gem 'rack-cors'
# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'your-frontend.com'
    resource '*',
      headers: :any,
      expose: ['Authorization'],
      methods: [:get, :post, :patch, :put, :delete, :options]
  end
end

  • Rate-limit endpoints with Rack::Attack

Include the Gem rack-attack (https://github.com/rack/rack-attack) to your Gemfile.

# In your Gemfile
gem 'rack-attack'
# config/initializers/rack_attack.rb

Rack::Attack.throttle('req/ip', limit: 60, period: 1.minute) do |req|
  req.ip
end

in Rails 8 we can use rate_limit for Controller actions like:

  rate_limit to: 10, within: 1.minutes, only: :create, with: -> { redirect_to new_session_url, alert: "Try again later." }

  • Pagination & Filtering: Prevent large payloads to avoid DoS.

๐Ÿ“ Summary: Best Practices Checklist

โœ… Use Strong Parameters
โœ… Escape output (no raw unless absolutely trusted)
โœ… Sanitize user content
โœ… Use Devise or Sorcery for auth
โœ… Authorize every resource with Pundit or CanCanCan
โœ… Store files safely and validate uploads
โœ… Enforce HTTPS in production
โœ… Regularly run Brakeman and bundler-audit
โœ… Rate-limit APIs with Rack::Attack
โœ… Keep dependencies up to date

๐Ÿ” Final Thought

Rails does a lot to keep you safe โ€” but security is your responsibility. Follow these practices and treat every external input as potentially dangerous. Security is not a one-time setup โ€” it’s an ongoing process.


Happy and secure coding! ๐Ÿš€

Setup Nginx, SSL , Firewall | Moving micro-services into AWS EC2 instance โ€“ Part 4

Install Nginx proxy server. Nginx also act like a load-balacer which is helpful for the balancing of network traffic.

sudo apt-get update
sudo apt-get install nginx

Commands to stop, start, restart, check status

sudo systemctl stop nginx
sudo systemctl start nginx
sudo systemctl restart nginx

# after making configuration changes
sudo systemctl reload nginx
sudo systemctl disable nginx
sudo systemctl enable nginx

Install SSL – Letsencrypt

Install packages needed for ssl

sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install python-certbot-nginx

Install the SSL Certificate:

certbot -d '*.domain.com' -d domain.com --manual --preferred-challenges dns certonly

Your certificate and chain have been saved at:
   /etc/letsencrypt/live/domain.com/fullchain.pem

Your key file has been saved at:
   /etc/letsencrypt/live/domain.com/privkey.pem
SSL certificate auto renewal

Let’s Encrypt’s certificates are valid for 90 days. To automatically renew the certificates before they expire, the certbot package creates a cronjob which will run twice a day and will automatically renew any certificate 30 days before its expiration.

Since we are using the certbot webroot plug-in once the certificate is renewed we also have to reload the nginx service. To do so append –renew-hook “systemctl reload nginx” to the /etc/cron.d/certbot file so as it looks like this:

/etc/cron.d/certbot
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew --renew-hook "systemctl reload nginx"

To test the renewal process, use the certbot –dry-run switch:

sudo certbot renew --dry-run

Renew your EXPIRED certificate this way:

sudo certbot --force-renewal -d '*.domain.com' -d domain.com --manual --preferred-challenges dns certonly

Are you OK with your IP being logged?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please deploy a DNS TXT record under the name
_acme-challenge.<domain>.com with the following value:

O3bpxxxxxxxxxxxxxxxxxxxxxxxxxxY4TnNo

Before continuing, verify the record is deployed.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Press Enter to Continue

You need to update the DNS txt record for _acme-challenge.<domain>.com

sudo systemctl restart nginx # restart nginx to take effect

Configure the Firewall

Next, weโ€™ll update our firewall to allow HTTPS traffic.

Check firewall status in the system. If it is inactive enable firewall.

sudo ufw status # check status

# enable firewall
sudo ufw enable
sudo ufw allow ssh
sudo ufw allow OpenSSH

Enable particular ports where your micro-services are running. Example:

sudo ufw allow 4031/tcp # Authentication service
sudo ufw allow 4131/tcp # File service
sudo ufw allow 4232/tcp # Search service

You can delete the ‘Authentication service’ firewall rule by:

sudo ufw delete allow 4031/tcp