Rack::Attack – secure you rails app for the real world


Bookmark and Share

Are you worried about the security issues in your Rails app? The rack-attack gem, can help you. Rack::Attack is a rack middleware which provides security to our rails application. It allows us to safelist, blacklist, throttle and to track requests.

  • If the request matches any safelist, it is allowed.
  • If the request matches any blocklist, it is blocked.
  • If the request matches any throttle, a counter is incremented in the Rack::Attack.cache. If any throttle’s limit is exceeded, the request is blocked.
  • Otherwise, all tracks are checked, and the request is allowed.

Implementation

Install the rack-attack gem, or add it to you Gemfile as:

Then tell your app to use the Rack::Attack middleware. For Rails 3+ apps:

Or you can use it in Rackup file as

By default, Rack Attack uses Rails cache. You can override that by setting the Rack::Attack.cache.store value. It is used for throttling. If you want to create use a custom adapter, for example, memory store,  create a file called rack_attack.rb in config/initializers to configure Rack Attack and put the following code in the file:

Throttle

Here we are limiting the request per seconds from the same IP address. Here we are limiting only 3 requests in 10 sec.

Safelist

Above example always …

Read More

How to write your own Rack middleware


Bookmark and Share

How to write your own Rack middleware

Rack is a Ruby package which provides an interface for a web server to communicate with the application. It is very easy to add middleware components between the web server and the app to customize the way your request/response behaves. The middleware component sits between the client and the server, processing inbound requests and outbound responses. Rack Middleware is an implementation of the pipeline design pattern for web servers using Rack.

For example with Rack, we can have separate stages of the pipeline:

  • Authentication: Checks whether the login details are correct or not when the request arrives.
  • Authorization:  It performs role-based security. i.e. checks whether the user is authorized to perform the particular task.
  • Caching: Return a cached result if the request is already processed.
  • Decoration: Enhance the request to make downstream processing better.
  • Performance & Usage Monitoring: Status get from the request and response.
  • Execution: actually handle the request and provide a response.

Next, we will see how to build our own rack middleware.

Building your own …

Read More