giant massive dep upgrade and dialyxir-found error emporium (#371)
[akkoma] / lib / pleroma / web / plugs / remote_ip.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Plugs.RemoteIp do
6 @moduledoc """
7 This is a shim to call [`RemoteIp`](https://git.pleroma.social/pleroma/remote_ip) but with runtime configuration.
8 """
9
10 alias Pleroma.Config
11
12 @behaviour Plug
13
14 def init(_), do: nil
15
16 def call(%{remote_ip: original_remote_ip} = conn, _) do
17 if Config.get([__MODULE__, :enabled]) do
18 {headers, proxies} = remote_ip_opts()
19 new_remote_ip = RemoteIp.from(conn.req_headers, headers: headers, proxies: proxies)
20
21 if new_remote_ip != original_remote_ip do
22 Map.put(conn, :remote_ip, new_remote_ip)
23 else
24 conn
25 end
26 else
27 conn
28 end
29 end
30
31 defp remote_ip_opts do
32 headers = Config.get([__MODULE__, :headers], [])
33 reserved = Config.get([__MODULE__, :reserved], [])
34
35 proxies =
36 Config.get([__MODULE__, :proxies], [])
37 |> Enum.concat(reserved)
38 |> Enum.map(&maybe_add_cidr/1)
39
40 {headers, proxies}
41 end
42
43 defp maybe_add_cidr(proxy) when is_binary(proxy) do
44 cond do
45 "/" in String.codepoints(proxy) -> proxy
46 InetCidr.v4?(InetCidr.parse_address!(proxy)) -> proxy <> "/32"
47 InetCidr.v6?(InetCidr.parse_address!(proxy)) -> proxy <> "/128"
48 end
49 end
50 end