-
Notifications
You must be signed in to change notification settings - Fork 22
Introduce conditional throttle #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
michalmuskala
wants to merge
2
commits into
main
Choose a base branch
from
conditional-throttle
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -74,7 +74,7 @@ defmodule PlugAttack.Rule do | |
| now = System.system_time(:milliseconds) | ||
|
|
||
| expires_at = expires_at(now, period) | ||
| count = do_throttle(storage, key, now, period, expires_at) | ||
| count = increment_throttle(storage, key, now, period, expires_at) | ||
| rem = limit - count | ||
| data = [period: period, expires_at: expires_at, | ||
| limit: limit, remaining: max(rem, 0)] | ||
|
|
@@ -83,11 +83,106 @@ defmodule PlugAttack.Rule do | |
|
|
||
| defp expires_at(now, period), do: (div(now, period) + 1) * period | ||
|
|
||
| defp do_throttle({mod, opts}, key, now, period, expires_at) do | ||
| defp increment_throttle({mod, opts}, key, now, period, expires_at) do | ||
| full_key = {:throttle, key, div(now, period)} | ||
| mod.increment(opts, full_key, 1, expires_at) | ||
| end | ||
|
|
||
| @doc """ | ||
| Implements a conditional request throttling algorithm. | ||
|
|
||
| With a request that does not use conditional headers (`If-Modified-Since` | ||
| or `If-None-Match` behaves exactly like `throttle/2`). For conditional | ||
| requests defers counting the request towards the limit to after the response | ||
| is computed using `Plug.Conn.register_before_send/2`. The throttle counter | ||
| is not incremented in case of a `304 Not Modified` response. | ||
|
|
||
| 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. When lazy throttling is performed the `allow_action` | ||
| callback is called from within the callback registered with | ||
| `Plug.Conn.register_before_send/2`. | ||
|
|
||
| ## Race conditions | ||
|
|
||
| Because the counter is imcremented lazily, there's a possible race condition, | ||
| where more requests are let-through than intended. This can happen during | ||
| long requests, when the counter is not incremented (yet) when new requests | ||
| are coming in. | ||
|
|
||
| ## 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. | ||
|
|
||
| """ | ||
| @spec conditional_throttle(Plug.Conn.t, term, Keyword.t) :: PlugAttack.rule | ||
| def conditional_throttle(conn, key, opts) do | ||
|
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @ericmj What do you think about this? Would this work for hexpm? |
||
| cond do | ||
| key && conditional_request?(conn) -> | ||
| do_conditional_throttle(conn, key, opts) | ||
| key -> | ||
| do_throttle(key, opts) | ||
| true -> | ||
| nil | ||
| end | ||
| end | ||
|
|
||
| defp conditional_request?(conn) do | ||
| Plug.Conn.get_req_header(conn, "if-none-match") != [] | ||
| or Plug.Conn.get_req_header(conn, "if-modified-since") != [] | ||
| end | ||
|
|
||
| defp do_conditional_throttle(conn, key, opts) do | ||
| storage = Keyword.fetch!(opts, :storage) | ||
| limit = Keyword.fetch!(opts, :limit) | ||
| period = Keyword.fetch!(opts, :period) | ||
| now = System.system_time(:milliseconds) | ||
|
|
||
| expires_at = expires_at(now, period) | ||
| count = check_throttle(storage, key, now, period, expires_at) | ||
| rem = limit - count | ||
| if rem >= 0 do | ||
| Plug.Conn.register_before_send(conn, fn conn -> | ||
| before_send_throttle(conn, storage, key, now, period, expires_at, limit, rem) | ||
| end) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If this returns a conn it should be added to the |
||
| else | ||
| data = [period: period, expires_at: expires_at, | ||
| limit: limit, remaining: max(rem, 0)] | ||
| {:block, {:throttle, data}} | ||
| end | ||
| end | ||
|
|
||
| defp before_send_throttle(conn, storage, key, now, period, expires_at, limit, rem) do | ||
| rem = | ||
| if conn.status != 304 do | ||
| limit - increment_throttle(storage, key, now, period, expires_at) | ||
| else | ||
| rem | ||
| end | ||
| data = [period: period, expires_at: expires_at, | ||
| limit: limit, remaining: max(rem, 0)] | ||
| {attack_module, opts} = conn.private.plug_attack | ||
| attack_module.allow_action(conn, {:allow, {:throttle, data}}, opts) | ||
| end | ||
|
|
||
| defp check_throttle({mod, opts}, key, now, period, expires_at) do | ||
| full_key = {:throttle, key, div(now, period)} | ||
| mod.increment(opts, full_key, 0, expires_at) | ||
| end | ||
|
|
||
| @doc """ | ||
| Implements an algorithm inspired by fail2ban. | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| %{"earmark": {:hex, :earmark, "1.1.1", "433136b7f2e99cde88b745b3a0cfc3fbc81fe58b918a09b40fce7f00db4d8187", [:mix], []}, | ||
| "ex_doc": {:hex, :ex_doc, "0.15.0", "e73333785eef3488cf9144a6e847d3d647e67d02bd6fdac500687854dd5c599f", [:mix], [{:earmark, "~> 1.1", [hex: :earmark, optional: false]}]}, | ||
| "mime": {:hex, :mime, "1.1.0", "01c1d6f4083d8aa5c7b8c246ade95139620ef8effb009edde934e0ec3b28090a", [:mix], []}, | ||
| "plug": {:hex, :plug, "1.3.1", "aaf54675428a393370ec1f4c865e3fcf42608686960764beac93c5abeba9e655", [:mix], [{:cowboy, "~> 1.0.1 or ~> 1.1", [hex: :cowboy, optional: true]}, {:mime, "~> 1.0", [hex: :mime, optional: false]}]}} | ||
| %{"earmark": {:hex, :earmark, "1.2.2", "f718159d6b65068e8daeef709ccddae5f7fdc770707d82e7d126f584cd925b74", [:mix], [], "hexpm"}, | ||
| "ex_doc": {:hex, :ex_doc, "0.16.1", "b4b8a23602b4ce0e9a5a960a81260d1f7b29635b9652c67e95b0c2f7ccee5e81", [:mix], [{:earmark, "~> 1.1", [hex: :earmark, repo: "hexpm", optional: false]}], "hexpm"}, | ||
| "mime": {:hex, :mime, "1.1.0", "01c1d6f4083d8aa5c7b8c246ade95139620ef8effb009edde934e0ec3b28090a", [:mix], [], "hexpm"}, | ||
| "plug": {:hex, :plug, "1.3.5", "7503bfcd7091df2a9761ef8cecea666d1f2cc454cbbaf0afa0b6e259203b7031", [:mix], [{:cowboy, "~> 1.0.1 or ~> 1.1", [hex: :cowboy, repo: "hexpm", optional: true]}, {:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}], "hexpm"}} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
incremented*