Add RateLimiter
[akkoma] / lib / pleroma / plugs / 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 ### Example
18
19 config :pleroma, :rate_limit,
20 one: {1000, 10},
21 two: [{10_000, 10}, {10_000, 50}]
22
23 Here we have two limiters: `one` which is not over 10req/1s and `two` which has two limits 10req/10s for unauthenticated users and 50req/10s for authenticated users.
24
25 ## Usage
26
27 Inside a controller:
28
29 plug(Pleroma.Plugs.RateLimiter, :one when action == :one)
30 plug(Pleroma.Plugs.RateLimiter, :two when action in [:two, :three])
31
32 or inside a router pipiline:
33
34 pipeline :api do
35 ...
36 plug(Pleroma.Plugs.RateLimiter, :one)
37 ...
38 end
39 """
40
41 import Phoenix.Controller, only: [json: 2]
42 import Plug.Conn
43
44 alias Pleroma.User
45
46 def init(limiter_name) do
47 case Pleroma.Config.get([:rate_limit, limiter_name]) do
48 nil -> nil
49 config -> {limiter_name, config}
50 end
51 end
52
53 # do not limit if there is no limiter configuration
54 def call(conn, nil), do: conn
55
56 def call(conn, opts) do
57 case check_rate(conn, opts) do
58 {:ok, _count} -> conn
59 {:error, _count} -> render_error(conn)
60 end
61 end
62
63 defp check_rate(%{assigns: %{user: %User{id: user_id}}}, {limiter_name, [_, {scale, limit}]}) do
64 ExRated.check_rate("#{limiter_name}:#{user_id}", scale, limit)
65 end
66
67 defp check_rate(conn, {limiter_name, [{scale, limit} | _]}) do
68 ExRated.check_rate("#{limiter_name}:#{ip(conn)}", scale, limit)
69 end
70
71 defp check_rate(conn, {limiter_name, {scale, limit}}) do
72 check_rate(conn, {limiter_name, [{scale, limit}]})
73 end
74
75 def ip(%{remote_ip: remote_ip}) do
76 remote_ip
77 |> Tuple.to_list()
78 |> Enum.join(".")
79 end
80
81 defp render_error(conn) do
82 conn
83 |> put_status(:too_many_requests)
84 |> json(%{error: "Throttled"})
85 |> halt()
86 end
87 end