New rate limiter
[akkoma] / lib / pleroma / plugs / rate_limiter / rate_limiter.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Plugs.RateLimiter do
6 @moduledoc """
7
8 ## Configuration
9
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:
11
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.
14
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.
16
17 To disable a limiter set its value to `nil`.
18
19 ### Example
20
21 config :pleroma, :rate_limit,
22 one: {1000, 10},
23 two: [{10_000, 10}, {10_000, 50}],
24 foobar: nil
25
26 Here we have three limiters:
27
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
31
32 ## Usage
33
34 AllowedSyntax:
35
36 plug(Pleroma.Plugs.RateLimiter, name: :limiter_name)
37 plug(Pleroma.Plugs.RateLimiter, options) # :name is a required option
38
39 Allowed options:
40
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
44
45 Inside a controller:
46
47 plug(Pleroma.Plugs.RateLimiter, [name: :one] when action == :one)
48 plug(Pleroma.Plugs.RateLimiter, [name: :two] when action in [:two, :three])
49
50 plug(
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
54 )
55
56 or inside a router pipeline:
57
58 pipeline :api do
59 ...
60 plug(Pleroma.Plugs.RateLimiter, name: :one)
61 ...
62 end
63 """
64 import Pleroma.Web.TranslationHelpers
65 import Plug.Conn
66
67 alias Pleroma.Plugs.RateLimiter.LimiterSupervisor
68 alias Pleroma.User
69
70 def init(opts) do
71 limiter_name = Keyword.get(opts, :name)
72
73 case Pleroma.Config.get([:rate_limit, limiter_name]) do
74 nil ->
75 nil
76
77 config ->
78 name_root = Keyword.get(opts, :bucket_name, limiter_name)
79
80 %{
81 name: name_root,
82 limits: config,
83 opts: opts
84 }
85 end
86 end
87
88 # Do not limit if there is no limiter configuration
89 def call(conn, nil), do: conn
90
91 def call(conn, settings) do
92 settings
93 |> incorporate_conn_info(conn)
94 |> check_rate()
95 |> case do
96 {:ok, _count} ->
97 conn
98
99 {:error, _count} ->
100 render_throttled_error(conn)
101 end
102 end
103
104 def inspect_bucket(conn, name_root, settings) do
105 settings =
106 settings
107 |> incorporate_conn_info(conn)
108
109 bucket_name = make_bucket_name(%{settings | name: name_root})
110 key_name = make_key_name(settings)
111 limit = get_limits(settings)
112
113 case Cachex.get(bucket_name, key_name) do
114 {:error, :no_cache} ->
115 {:err, :not_found}
116
117 {:ok, nil} ->
118 {0, limit}
119
120 {:ok, value} ->
121 {value, limit - value}
122 end
123 end
124
125 defp check_rate(settings) do
126 bucket_name = make_bucket_name(settings)
127 key_name = make_key_name(settings)
128 limit = get_limits(settings)
129
130 case Cachex.get_and_update(bucket_name, key_name, &increment_value(&1, limit)) do
131 {:commit, value} ->
132 {:ok, value}
133
134 {:ignore, value} ->
135 {:error, value}
136
137 {:error, :no_cache} ->
138 initialize_buckets(settings)
139 check_rate(settings)
140 end
141 end
142
143 defp increment_value(nil, _limit), do: {:commit, 1}
144
145 defp increment_value(val, limit) when val >= limit, do: {:ignore, val}
146
147 defp increment_value(val, _limit), do: {:commit, val + 1}
148
149 defp incorporate_conn_info(settings, %{assigns: %{user: %User{id: user_id}}, params: params}) do
150 Map.merge(settings, %{
151 mode: :user,
152 conn_params: params,
153 conn_info: "#{user_id}"
154 })
155 end
156
157 defp incorporate_conn_info(settings, %{params: params} = conn) do
158 Map.merge(settings, %{
159 mode: :anon,
160 conn_params: params,
161 conn_info: "#{ip(conn)}"
162 })
163 end
164
165 defp ip(%{remote_ip: remote_ip}) do
166 remote_ip
167 |> Tuple.to_list()
168 |> Enum.join(".")
169 end
170
171 defp render_throttled_error(conn) do
172 conn
173 |> render_error(:too_many_requests, "Throttled")
174 |> halt()
175 end
176
177 defp make_key_name(settings) do
178 ""
179 |> attach_params(settings)
180 |> attach_identity(settings)
181 end
182
183 defp get_scale(_, {scale, _}), do: scale
184
185 defp get_scale(:anon, [{scale, _}, {_, _}]), do: scale
186
187 defp get_scale(:user, [{_, _}, {scale, _}]), do: scale
188
189 defp get_limits(%{limits: {_scale, limit}}), do: limit
190
191 defp get_limits(%{mode: :user, limits: [_, {_, limit}]}), do: limit
192
193 defp get_limits(%{limits: [{_, limit}, _]}), do: limit
194
195 defp make_bucket_name(%{mode: :user, name: name_root}),
196 do: user_bucket_name(name_root)
197
198 defp make_bucket_name(%{mode: :anon, name: name_root}),
199 do: anon_bucket_name(name_root)
200
201 defp attach_params(input, %{conn_params: conn_params, opts: opts}) do
202 param_string =
203 opts
204 |> Keyword.get(:params, [])
205 |> Enum.sort()
206 |> Enum.map(&Map.get(conn_params, &1, ""))
207 |> Enum.join(":")
208
209 "#{input}#{param_string}"
210 end
211
212 defp initialize_buckets(%{name: _name, limits: nil}), do: :ok
213
214 defp initialize_buckets(%{name: name, limits: limits}) do
215 LimiterSupervisor.add_limiter(anon_bucket_name(name), get_scale(:anon, limits))
216 LimiterSupervisor.add_limiter(user_bucket_name(name), get_scale(:user, limits))
217 end
218
219 defp attach_identity(base, %{mode: :user, conn_info: conn_info}),
220 do: "user:#{base}:#{conn_info}"
221
222 defp attach_identity(base, %{mode: :anon, conn_info: conn_info}),
223 do: "ip:#{base}:#{conn_info}"
224
225 defp user_bucket_name(name_root), do: "user:#{name_root}" |> String.to_atom()
226 defp anon_bucket_name(name_root), do: "anon:#{name_root}" |> String.to_atom()
227 end