Rack-attack gem setup to protect Rails and Rack apps from bad clients
Tags: ruby, rails, middleware, security
Published: 2022-08-09 00:45:43

Rack middleware for blocking & throttling abusive requests. Protect your Rails and Rack apps from bad clients. Rack::Attack lets you quickly decide when to allow, block, and throttle based on the properties of the request.

Using this gem you can save your web application from attacks, we can whitelist IPs, Block requests according to requirements, and many more…

**Install Rack-attack gem:**

    # In your Gemfile
    gem 'rack-attack'

### Plugging into the application

Then tell your ruby web application to use rack-attack as a middleware.

    # config/application.rb
    # rack attack middleware
    config.middleware.use Rack::Attack

Once you’ve done that, you’ll need to configure it. You can do this by creating the file, config/initializers/rack-attack.rband adding the rules to fit your needs.

You can disable it permanently (like for a specific environment) or temporarily (can be helpful for specific test cases) by writing:
{% gist https://gist.github.com/kananinirav/73a740704a5e9721b7e1f73baae33b6d.js %}
## Usage
>  Safe listing

Safelists have the most precedence, so any request matching a safelist would be allowed despite matching any number of blocklists or throttles.

* safelist_ip(ip_address_string)

```
Rack::Attack.safelist_ip(“5.6.7.8”)
```
* safelist_ip(ip_subnet_string)

```
Rack::Attack.safelist_ip(“5.6.7.0/24”)
```

* safelist(name, &block)

Name your custom safelist and make your ruby-block argument return a truthy value if you want the request to be allowed, and false otherwise.
{% gist https://gist.github.com/kananinirav/ef9881de794f554d58c07c6b0f0204ae %}
>  Blocking

* blocklist_ip(ip_address_string)

```
 Rack::Attack.blocklist_ip(“1.2.3.4”)
```
* blocklist_ip(ip_subnet_string)

```
 Rack::Attack.blocklist_ip(“1.2.0.0/16”)
```
* blocklist(name, &block)

Name your custom blocklist and make your ruby-block argument return a truthy value if you want the request to be blocked, and false otherwise.
{% gist https://gist.github.com/kananinirav/6740f5d0b1fcd049a26efb1ed7e7acdb %}

>  Throttling

**throttle(name, options, &block) **( provide limit and period as options)

Throttle state is stored in a [configurable cache](https://github.com/rack/rack-attack/blob/6-stable/README.md#cache-store-configuration) (which defaults to Rails.cache if present).

Name your custom throttle, provide limit and period as options, and make your ruby-block argument return the discriminator. This discriminator is how you tell rack-attack whether you’re limiting per IP address, per user email, or any other.

- For example, if we want to restrict requests other than defined routes and display a custom error page.
{% gist https://gist.github.com/kananinirav/d7c601bb465f32ed6cd2159d59b613f4 %}
Error page:


![Error page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ueio4pgp4f0ondd81xxt.png)

- If we want to restrict requests/IP and if the request limit increases then send a reminder mail.

For Example, we want to allow only 300 requests per 30 seconds after that will restrict requests from this IP till the next 30 seconds interval starting.
{% gist https://gist.github.com/kananinirav/11ad6882c12b6571e94733cf1c7b5745 %}
Get error mail if the limit is extended.

![Error mail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ilhxjo9onjc95t6z3kqq.png)
**Performance**

The overhead of running Rack::Attack is typically negligible (a few milliseconds per request), but it depends on how many checks you’ve configured, and how long they take. Throttles usually require a network roundtrip to your cache server(s), so try to keep the number of throttle checks per request low.

If a request is blocklisted or throttled, the response is a very simple Rack response. A single typical ruby web server thread can block several hundred requests per second.
>  Sample rack-attack.rb file

{% gist https://gist.github.com/kananinirav/1a374e266f45ece21ab007945b3fa0d1 %}

For more information: [https://github.com/rack/rack-attack](https://github.com/rack/rack-attack)


If You are using [Medium](https://medium.com/) Please support and follow me for interesting articles. **[Medium Profile](https://medium.com/@kanani-nirav)**

If this guide has been helpful to you and your team please share it with others!