1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Plugs.RateLimiter do
10 A keyword list of rate limiters where a key is a limiter name and value is the limiter configuration. The basic configuration is a tuple where:
12 * The first element: `scale` (Integer). The time scale in milliseconds.
13 * The second element: `limit` (Integer). How many requests to limit in the time scale provided.
15 It is also possible to have different limits for unauthenticated and authenticated users: the keyword value must be a list of two tuples where the first one is a config for unauthenticated users and the second one is for authenticated.
17 To disable a limiter set its value to `nil`.
21 config :pleroma, :rate_limit,
23 two: [{10_000, 10}, {10_000, 50}],
26 Here we have three limiters:
28 * `one` which is not over 10req/1s
29 * `two` which has two limits: 10req/10s for unauthenticated users and 50req/10s for authenticated users
30 * `foobar` which is disabled
36 plug(Pleroma.Plugs.RateLimiter, name: :limiter_name)
37 plug(Pleroma.Plugs.RateLimiter, options) # :name is a required option
41 * `name` required, always used to fetch the limit values from the config
42 * `bucket_name` overrides name for counting purposes (e.g. to have a separate limit for a set of actions)
43 * `params` appends values of specified request params (e.g. ["id"]) to bucket name
47 plug(Pleroma.Plugs.RateLimiter, [name: :one] when action == :one)
48 plug(Pleroma.Plugs.RateLimiter, [name: :two] when action in [:two, :three])
51 Pleroma.Plugs.RateLimiter,
52 [name: :status_id_action, bucket_name: "status_id_action:fav_unfav", params: ["id"]]
53 when action in ~w(fav_status unfav_status)a
56 or inside a router pipeline:
60 plug(Pleroma.Plugs.RateLimiter, name: :one)
64 import Pleroma.Web.TranslationHelpers
67 alias Pleroma.Plugs.RateLimiter.LimiterSupervisor
73 limiter_name = Keyword.get(opts, :name)
75 case Pleroma.Config.get([:rate_limit, limiter_name]) do
80 name_root = Keyword.get(opts, :bucket_name, limiter_name)
90 # Do not limit if there is no limiter configuration
91 def call(conn, nil), do: conn
93 def call(conn, settings) do
96 if Pleroma.Config.get(:env) == :prod,
97 do: Logger.warn("Rate limiter is disabled for localhost/socket")
103 |> incorporate_conn_info(conn)
110 render_throttled_error(conn)
116 localhost_or_socket =
117 Pleroma.Config.get([Pleroma.Web.Endpoint, :http, :ip])
120 |> String.match?(~r/^local|^127.0.0.1/)
122 remote_ip_disabled = not Pleroma.Config.get([Pleroma.Plugs.RemoteIp, :enabled])
124 localhost_or_socket and remote_ip_disabled
127 def inspect_bucket(conn, name_root, settings) do
130 |> incorporate_conn_info(conn)
132 bucket_name = make_bucket_name(%{settings | name: name_root})
133 key_name = make_key_name(settings)
134 limit = get_limits(settings)
136 case Cachex.get(bucket_name, key_name) do
137 {:error, :no_cache} ->
144 {value, limit - value}
148 defp check_rate(settings) do
149 bucket_name = make_bucket_name(settings)
150 key_name = make_key_name(settings)
151 limit = get_limits(settings)
153 case Cachex.get_and_update(bucket_name, key_name, &increment_value(&1, limit)) do
160 {:error, :no_cache} ->
161 initialize_buckets(settings)
166 defp increment_value(nil, _limit), do: {:commit, 1}
168 defp increment_value(val, limit) when val >= limit, do: {:ignore, val}
170 defp increment_value(val, _limit), do: {:commit, val + 1}
172 defp incorporate_conn_info(settings, %{assigns: %{user: %User{id: user_id}}, params: params}) do
173 Map.merge(settings, %{
176 conn_info: "#{user_id}"
180 defp incorporate_conn_info(settings, %{params: params} = conn) do
181 Map.merge(settings, %{
184 conn_info: "#{ip(conn)}"
188 defp ip(%{remote_ip: remote_ip}) do
194 defp render_throttled_error(conn) do
196 |> render_error(:too_many_requests, "Throttled")
200 defp make_key_name(settings) do
202 |> attach_params(settings)
203 |> attach_identity(settings)
206 defp get_scale(_, {scale, _}), do: scale
208 defp get_scale(:anon, [{scale, _}, {_, _}]), do: scale
210 defp get_scale(:user, [{_, _}, {scale, _}]), do: scale
212 defp get_limits(%{limits: {_scale, limit}}), do: limit
214 defp get_limits(%{mode: :user, limits: [_, {_, limit}]}), do: limit
216 defp get_limits(%{limits: [{_, limit}, _]}), do: limit
218 defp make_bucket_name(%{mode: :user, name: name_root}),
219 do: user_bucket_name(name_root)
221 defp make_bucket_name(%{mode: :anon, name: name_root}),
222 do: anon_bucket_name(name_root)
224 defp attach_params(input, %{conn_params: conn_params, opts: opts}) do
227 |> Keyword.get(:params, [])
229 |> Enum.map(&Map.get(conn_params, &1, ""))
232 "#{input}#{param_string}"
235 defp initialize_buckets(%{name: _name, limits: nil}), do: :ok
237 defp initialize_buckets(%{name: name, limits: limits}) do
238 LimiterSupervisor.add_limiter(anon_bucket_name(name), get_scale(:anon, limits))
239 LimiterSupervisor.add_limiter(user_bucket_name(name), get_scale(:user, limits))
242 defp attach_identity(base, %{mode: :user, conn_info: conn_info}),
243 do: "user:#{base}:#{conn_info}"
245 defp attach_identity(base, %{mode: :anon, conn_info: conn_info}),
246 do: "ip:#{base}:#{conn_info}"
248 defp user_bucket_name(name_root), do: "user:#{name_root}" |> String.to_atom()
249 defp anon_bucket_name(name_root), do: "anon:#{name_root}" |> String.to_atom()