PlugAttack.Rule (plug_attack v0.4.3)

Defines various rules that can be used inside the PlugAttack.rule/2 macro.

Link to this section Summary

Functions

The simplest rule that always allows the request to pass.

The simplest rule that always blocks the request.

Implements an algorithm inspired by fail2ban.

Implements a request throttling algorithm.

Link to this section Functions

Specs

allow(term()) :: PlugAttack.rule()

The simplest rule that always allows the request to pass.

If value is truthy the request is allowed, otherwise next rules are evaluated.

Specs

block(term()) :: PlugAttack.rule()

The simplest rule that always blocks the request.

If value is truthy the request is blocked, otherwise next rules are evaluated.

Link to this function

fail2ban(key, opts)

Specs

fail2ban(term(), Keyword.t()) :: PlugAttack.rule()

Implements an algorithm inspired by fail2ban.

This intends to catch misbehaving clients early and for longer amounts of time. The key differentiates different clients, you can use, for example, conn.remote_ip for per IP tracking. If the key is falsey the action is skipped and next rules are evaluated.

Be careful not to use the same key for different rules that use the same storage.

Passes {:fail2ban, key}, as the data to block_action calls when an abusive request is detected. Each misbehaving client is blocked after each call and tracked for :period time. If more than :limit abusive requests are detected within the :period, the client is banned for :ban_for.

Options

  • :storage - required, a tuple of PlugAttack.Storage implementation and storage options.
  • :period - required, how long to store abusive requests for counting towards :limit exhaustion.
  • :limit - required, max abusive requests allowed before the ban.
  • :ban_for - required, length of the ban in milliseconds.
Link to this function

throttle(key, opts)

Specs

throttle(term(), Keyword.t()) :: PlugAttack.rule()

Implements a request throttling algorithm.

The key differentiates different throttles, you can use, for example, conn.remote_ip for per IP throttling, or an email address for login attempts limitation. If the key is falsey the throttling is not performed and next rules are evaluated.

Be careful not to use the same key for different rules that use the same storage.

Passes {:throttle, data}, as the data to both allow and block tuples, where data is a keyword containing: :period, :limit, :expires_at - when the current limit will expire as unix time in milliseconds, and :remaining - the remaining limit. This can be useful for adding "X-RateLimit-*" headers.

Options

  • :storage - required, a tuple of PlugAttack.Storage implementation and storage options.
  • :limit - required, how many requests in a period are allowed.
  • :period - required, how long, in ms, is the period.