gitmyhub

rack-attack

Ruby ★ 5.8k updated 17d ago

Rack middleware for blocking & throttling

Rack::Attack is a Ruby middleware library that protects Rails and Rack web apps from abuse by letting you define rules to block bad IPs, throttle login forms and APIs, and permanently ban repeat offenders.

RubyRailsRackRedissetup: moderatecomplexity 2/5

Rack::Attack is a Ruby library that lets you protect a web application from unwanted or abusive traffic. It works as middleware, meaning it sits in front of your application and inspects incoming requests before they reach your code. You define rules describing which requests to allow, which to block, and which to slow down, and the library enforces those rules automatically.

The three core tools are safelists, blocklists, and throttles. A safelist marks certain requests as always allowed, such as requests from your own office IP address or from authenticated internal users. A blocklist identifies requests that should always be rejected, such as traffic from a known bad IP or requests hitting a path that should never be publicly accessible. A throttle limits how many requests a client can make within a time window, which is useful for protecting login forms or APIs from being hammered.

The library also includes two more advanced patterns called Fail2Ban and Allow2Ban. Fail2Ban tracks suspicious requests and permanently blocks a client after they trip a threshold a certain number of times, similar in concept to the Unix tool of the same name. Allow2Ban does the reverse: it lets requests through until a threshold is reached, then cuts off the client.

Rack::Attack is designed for Rails applications but works with any Ruby web framework built on the Rack standard. Rules are written in Ruby and live in an initializer file. Blocked and throttled requests can return customized HTTP responses. The library also emits events that you can hook into for logging or monitoring. State for throttles and ban tracking is stored in a cache, which defaults to Rails.cache but can be configured to use Redis or another store.

Installation is through a Gemfile entry. The project includes documentation for common configuration patterns and a test helper for verifying your rules work as expected.

Where it fits