summaryrefslogtreecommitdiff
path: root/test/plugs/rate_limiter_test.exs
blob: 8023271e468cc4d3854acd02f2baf66d27b402ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Plugs.RateLimiterTest do
  use ExUnit.Case, async: true
  use Plug.Test

  alias Pleroma.Config
  alias Pleroma.Plugs.RateLimiter

  import Pleroma.Factory
  import Pleroma.Tests.Helpers, only: [clear_config: 1, clear_config: 2]

  # Note: each example must work with separate buckets in order to prevent concurrency issues

  clear_config([Pleroma.Web.Endpoint, :http, :ip])
  clear_config(:rate_limit)

  describe "config" do
    @limiter_name :test_init

    clear_config([Pleroma.Plugs.RemoteIp, :enabled])

    test "config is required for plug to work" do
      Config.put([:rate_limit, @limiter_name], {1, 1})
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})

      assert %{limits: {1, 1}, name: :test_init, opts: [name: :test_init]} ==
               [name: @limiter_name]
               |> RateLimiter.init()
               |> RateLimiter.action_settings()

      assert nil ==
               [name: :nonexisting_limiter]
               |> RateLimiter.init()
               |> RateLimiter.action_settings()
    end

    test "it is disabled for localhost" do
      Config.put([:rate_limit, @limiter_name], {1, 1})
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {127, 0, 0, 1})
      Config.put([Pleroma.Plugs.RemoteIp, :enabled], false)

      assert RateLimiter.disabled?() == true
    end

    test "it is disabled for socket" do
      Config.put([:rate_limit, @limiter_name], {1, 1})
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {:local, "/path/to/pleroma.sock"})
      Config.put([Pleroma.Plugs.RemoteIp, :enabled], false)

      assert RateLimiter.disabled?() == true
    end

    test "it is enabled for socket when remote ip is enabled" do
      Config.put([:rate_limit, @limiter_name], {1, 1})
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {:local, "/path/to/pleroma.sock"})
      Config.put([Pleroma.Plugs.RemoteIp, :enabled], true)

      assert RateLimiter.disabled?() == false
    end

    test "it restricts based on config values" do
      limiter_name = :test_plug_opts
      scale = 80
      limit = 5

      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})
      Config.put([:rate_limit, limiter_name], {scale, limit})

      plug_opts = RateLimiter.init(name: limiter_name)
      conn = conn(:get, "/")

      for i <- 1..5 do
        conn = RateLimiter.call(conn, plug_opts)
        assert {^i, _} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts)
        Process.sleep(10)
      end

      conn = RateLimiter.call(conn, plug_opts)
      assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests)
      assert conn.halted

      Process.sleep(50)

      conn = conn(:get, "/")

      conn = RateLimiter.call(conn, plug_opts)
      assert {1, 4} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts)

      refute conn.status == Plug.Conn.Status.code(:too_many_requests)
      refute conn.resp_body
      refute conn.halted
    end
  end

  describe "options" do
    test "`bucket_name` option overrides default bucket name" do
      limiter_name = :test_bucket_name

      Config.put([:rate_limit, limiter_name], {1000, 5})
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})

      base_bucket_name = "#{limiter_name}:group1"
      plug_opts = RateLimiter.init(name: limiter_name, bucket_name: base_bucket_name)

      conn = conn(:get, "/")

      RateLimiter.call(conn, plug_opts)
      assert {1, 4} = RateLimiter.inspect_bucket(conn, base_bucket_name, plug_opts)
      assert {:error, :not_found} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts)
    end

    test "`params` option allows different queries to be tracked independently" do
      limiter_name = :test_params
      Config.put([:rate_limit, limiter_name], {1000, 5})
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})

      plug_opts = RateLimiter.init(name: limiter_name, params: ["id"])

      conn = conn(:get, "/?id=1")
      conn = Plug.Conn.fetch_query_params(conn)
      conn_2 = conn(:get, "/?id=2")

      RateLimiter.call(conn, plug_opts)
      assert {1, 4} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts)
      assert {0, 5} = RateLimiter.inspect_bucket(conn_2, limiter_name, plug_opts)
    end

    test "it supports combination of options modifying bucket name" do
      limiter_name = :test_options_combo
      Config.put([:rate_limit, limiter_name], {1000, 5})
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})

      base_bucket_name = "#{limiter_name}:group1"

      plug_opts =
        RateLimiter.init(name: limiter_name, bucket_name: base_bucket_name, params: ["id"])

      id = "100"

      conn = conn(:get, "/?id=#{id}")
      conn = Plug.Conn.fetch_query_params(conn)
      conn_2 = conn(:get, "/?id=#{101}")

      RateLimiter.call(conn, plug_opts)
      assert {1, 4} = RateLimiter.inspect_bucket(conn, base_bucket_name, plug_opts)
      assert {0, 5} = RateLimiter.inspect_bucket(conn_2, base_bucket_name, plug_opts)
    end
  end

  describe "unauthenticated users" do
    test "are restricted based on remote IP" do
      limiter_name = :test_unauthenticated
      Config.put([:rate_limit, limiter_name], [{1000, 5}, {1, 10}])
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})

      plug_opts = RateLimiter.init(name: limiter_name)

      conn = %{conn(:get, "/") | remote_ip: {127, 0, 0, 2}}
      conn_2 = %{conn(:get, "/") | remote_ip: {127, 0, 0, 3}}

      for i <- 1..5 do
        conn = RateLimiter.call(conn, plug_opts)
        assert {^i, _} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts)
        refute conn.halted
      end

      conn = RateLimiter.call(conn, plug_opts)

      assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests)
      assert conn.halted

      conn_2 = RateLimiter.call(conn_2, plug_opts)
      assert {1, 4} = RateLimiter.inspect_bucket(conn_2, limiter_name, plug_opts)

      refute conn_2.status == Plug.Conn.Status.code(:too_many_requests)
      refute conn_2.resp_body
      refute conn_2.halted
    end
  end

  describe "authenticated users" do
    setup do
      Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo)

      :ok
    end

    test "can have limits separate from unauthenticated connections" do
      limiter_name = :test_authenticated1

      scale = 50
      limit = 5
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})
      Config.put([:rate_limit, limiter_name], [{1000, 1}, {scale, limit}])

      plug_opts = RateLimiter.init(name: limiter_name)

      user = insert(:user)
      conn = conn(:get, "/") |> assign(:user, user)

      for i <- 1..5 do
        conn = RateLimiter.call(conn, plug_opts)
        assert {^i, _} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts)
        refute conn.halted
      end

      conn = RateLimiter.call(conn, plug_opts)

      assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests)
      assert conn.halted
    end

    test "different users are counted independently" do
      limiter_name = :test_authenticated2
      Config.put([:rate_limit, limiter_name], [{1, 10}, {1000, 5}])
      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})

      plug_opts = RateLimiter.init(name: limiter_name)

      user = insert(:user)
      conn = conn(:get, "/") |> assign(:user, user)

      user_2 = insert(:user)
      conn_2 = conn(:get, "/") |> assign(:user, user_2)

      for i <- 1..5 do
        conn = RateLimiter.call(conn, plug_opts)
        assert {^i, _} = RateLimiter.inspect_bucket(conn, limiter_name, plug_opts)
      end

      conn = RateLimiter.call(conn, plug_opts)
      assert %{"error" => "Throttled"} = Phoenix.ConnTest.json_response(conn, :too_many_requests)
      assert conn.halted

      conn_2 = RateLimiter.call(conn_2, plug_opts)
      assert {1, 4} = RateLimiter.inspect_bucket(conn_2, limiter_name, plug_opts)
      refute conn_2.status == Plug.Conn.Status.code(:too_many_requests)
      refute conn_2.resp_body
      refute conn_2.halted
    end
  end

  test "doesn't crash due to a race condition when multiple requests are made at the same time and the bucket is not yet initialized" do
    limiter_name = :test_race_condition
    Pleroma.Config.put([:rate_limit, limiter_name], {1000, 5})
    Pleroma.Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})

    opts = RateLimiter.init(name: limiter_name)

    conn = conn(:get, "/")
    conn_2 = conn(:get, "/")

    %Task{pid: pid1} =
      task1 =
      Task.async(fn ->
        receive do
          :process2_up ->
            RateLimiter.call(conn, opts)
        end
      end)

    task2 =
      Task.async(fn ->
        send(pid1, :process2_up)
        RateLimiter.call(conn_2, opts)
      end)

    Task.await(task1)
    Task.await(task2)

    refute {:err, :not_found} == RateLimiter.inspect_bucket(conn, limiter_name, opts)
  end
end