reverse_proxy.ex 11.5 KB
Newer Older
1
# Pleroma: A lightweight social networking server
kaniini's avatar
kaniini committed
2
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3
4
# SPDX-License-Identifier: AGPL-3.0-only

href's avatar
href committed
5
defmodule Pleroma.ReverseProxy do
6
7
  @keep_req_headers ~w(accept user-agent accept-encoding cache-control if-modified-since) ++
                      ~w(if-unmodified-since if-none-match if-range range)
href's avatar
href committed
8
9
  @resp_cache_headers ~w(etag date last-modified cache-control)
  @keep_resp_headers @resp_cache_headers ++
10
11
                       ~w(content-type content-disposition content-encoding content-range) ++
                       ~w(accept-ranges vary)
href's avatar
href committed
12
13
  @default_cache_control_header "public, max-age=1209600"
  @valid_resp_codes [200, 206, 304]
14
  @max_read_duration :timer.seconds(30)
href's avatar
href committed
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
  @max_body_length :infinity
  @methods ~w(GET HEAD)

  @moduledoc """
  A reverse proxy.

      Pleroma.ReverseProxy.call(conn, url, options)

  It is not meant to be added into a plug pipeline, but to be called from another plug or controller.

  Supports `#{inspect(@methods)}` HTTP methods, and only allows `#{inspect(@valid_resp_codes)}` status codes.

  Responses are chunked to the client while downloading from the upstream.

  Some request / responses headers are preserved:

  * request: `#{inspect(@keep_req_headers)}`
  * response: `#{inspect(@keep_resp_headers)}`

  If no caching headers (`#{inspect(@resp_cache_headers)}`) are returned by upstream, `cache-control` will be
  set to `#{inspect(@default_cache_control_header)}`.

  Options:

  * `redirect_on_failure` (default `false`). Redirects the client to the real remote URL if there's any HTTP
  errors. Any error during body processing will not be redirected as the response is chunked. This may expose
  remote URL, clients IPs, ….

  * `max_body_length` (default `#{inspect(@max_body_length)}`): limits the content length to be approximately the
  specified length. It is validated with the `content-length` header and also verified when proxying.

  * `max_read_duration` (default `#{inspect(@max_read_duration)}` ms): the total time the connection is allowed to
  read from the remote upstream.

  * `inline_content_types`:
    * `true` will not alter `content-disposition` (up to the upstream),
    * `false` will add `content-disposition: attachment` to any request,
    * a list of whitelisted content types

    * `keep_user_agent` will forward the client's user-agent to the upstream. This may be useful if the upstream is
    doing content transformation (encoding, …) depending on the request.

  * `req_headers`, `resp_headers` additional headers.

  * `http`: options for [hackney](https://github.com/benoitc/hackney).

  """
  @hackney Application.get_env(:pleroma, :hackney, :hackney)
  @httpoison Application.get_env(:pleroma, :httpoison, HTTPoison)

Hakaba Hitoyo's avatar
Hakaba Hitoyo committed
65
  @default_hackney_options []
href's avatar
href committed
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

  @inline_content_types [
    "image/gif",
    "image/jpeg",
    "image/jpg",
    "image/png",
    "image/svg+xml",
    "audio/mpeg",
    "audio/mp3",
    "video/webm",
    "video/mp4",
    "video/quicktime"
  ]

  require Logger
  import Plug.Conn

  @type option() ::
          {:keep_user_agent, boolean}
          | {:max_read_duration, :timer.time() | :infinity}
          | {:max_body_length, non_neg_integer() | :infinity}
          | {:http, []}
          | {:req_headers, [{String.t(), String.t()}]}
          | {:resp_headers, [{String.t(), String.t()}]}
          | {:inline_content_types, boolean() | [String.t()]}
          | {:redirect_on_failure, boolean()}

  @spec call(Plug.Conn.t(), url :: String.t(), [option()]) :: Plug.Conn.t()
Maksim's avatar
Maksim committed
94
95
96
  def call(_conn, _url, _opts \\ [])

  def call(conn = %{method: method}, url, opts) when method in @methods do
href's avatar
href committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    hackney_opts =
      @default_hackney_options
      |> Keyword.merge(Keyword.get(opts, :http, []))
      |> @httpoison.process_request_options()

    req_headers = build_req_headers(conn.req_headers, opts)

    opts =
      if filename = Pleroma.Web.MediaProxy.filename(url) do
        Keyword.put_new(opts, :attachment_name, filename)
      else
        opts
      end

    with {:ok, code, headers, client} <- request(method, url, req_headers, hackney_opts),
href's avatar
href committed
112
         :ok <- header_length_constraint(headers, Keyword.get(opts, :max_body_length)) do
href's avatar
href committed
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
      response(conn, client, url, code, headers, opts)
    else
      {:ok, code, headers} ->
        head_response(conn, url, code, headers, opts)
        |> halt()

      {:error, {:invalid_http_response, code}} ->
        Logger.error("#{__MODULE__}: request to #{inspect(url)} failed with HTTP status #{code}")

        conn
        |> error_or_redirect(
          url,
          code,
          "Request failed: " <> Plug.Conn.Status.reason_phrase(code),
          opts
        )
        |> halt()

      {:error, error} ->
        Logger.error("#{__MODULE__}: request to #{inspect(url)} failed: #{inspect(error)}")

        conn
        |> error_or_redirect(url, 500, "Request failed", opts)
        |> halt()
    end
  end

  def call(conn, _, _) do
    conn
    |> send_resp(400, Plug.Conn.Status.reason_phrase(400))
    |> halt()
  end

  defp request(method, url, headers, hackney_opts) do
    Logger.debug("#{__MODULE__} #{method} #{url} #{inspect(headers)}")
    method = method |> String.downcase() |> String.to_existing_atom()

    case @hackney.request(method, url, headers, "", hackney_opts) do
      {:ok, code, headers, client} when code in @valid_resp_codes ->
        {:ok, code, downcase_headers(headers), client}

      {:ok, code, headers} when code in @valid_resp_codes ->
        {:ok, code, downcase_headers(headers)}

      {:ok, code, _, _} ->
        {:error, {:invalid_http_response, code}}

      {:error, error} ->
        {:error, error}
    end
  end

  defp response(conn, client, url, status, headers, opts) do
    result =
      conn
      |> put_resp_headers(build_resp_headers(headers, opts))
      |> send_chunked(status)
      |> chunk_reply(client, opts)

    case result do
      {:ok, conn} ->
        halt(conn)

      {:error, :closed, conn} ->
        :hackney.close(client)
        halt(conn)

      {:error, error, conn} ->
        Logger.warn(
          "#{__MODULE__} request to #{url} failed while reading/chunking: #{inspect(error)}"
        )

        :hackney.close(client)
        halt(conn)
    end
  end

  defp chunk_reply(conn, client, opts) do
    chunk_reply(conn, client, opts, 0, 0)
  end

  defp chunk_reply(conn, client, opts, sent_so_far, duration) do
    with {:ok, duration} <-
           check_read_duration(
             duration,
             Keyword.get(opts, :max_read_duration, @max_read_duration)
           ),
         {:ok, data} <- @hackney.stream_body(client),
         {:ok, duration} <- increase_read_duration(duration),
         sent_so_far = sent_so_far + byte_size(data),
         :ok <- body_size_constraint(sent_so_far, Keyword.get(opts, :max_body_size)),
         {:ok, conn} <- chunk(conn, data) do
      chunk_reply(conn, client, opts, sent_so_far, duration)
    else
      :done -> {:ok, conn}
      {:error, error} -> {:error, error, conn}
    end
  end

  defp head_response(conn, _url, code, headers, opts) do
    conn
    |> put_resp_headers(build_resp_headers(headers, opts))
    |> send_resp(code, "")
  end

  defp error_or_redirect(conn, url, code, body, opts) do
    if Keyword.get(opts, :redirect_on_failure, false) do
      conn
      |> Phoenix.Controller.redirect(external: url)
      |> halt()
    else
      conn
      |> send_resp(code, body)
      |> halt
    end
  end

  defp downcase_headers(headers) do
    Enum.map(headers, fn {k, v} ->
      {String.downcase(k), v}
    end)
  end

236
  defp get_content_type(headers) do
href's avatar
href committed
237
238
239
240
    {_, content_type} =
      List.keyfind(headers, "content-type", 0, {"content-type", "application/octet-stream"})

    [content_type | _] = String.split(content_type, ";")
241
242
243
    content_type
  end

href's avatar
href committed
244
245
246
247
248
249
250
  defp put_resp_headers(conn, headers) do
    Enum.reduce(headers, conn, fn {k, v}, conn ->
      put_resp_header(conn, k, v)
    end)
  end

  defp build_req_headers(headers, opts) do
Maksim's avatar
Maksim committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    headers
    |> downcase_headers()
    |> Enum.filter(fn {k, _} -> k in @keep_req_headers end)
    |> (fn headers ->
          headers = headers ++ Keyword.get(opts, :req_headers, [])

          if Keyword.get(opts, :keep_user_agent, false) do
            List.keystore(
              headers,
              "user-agent",
              0,
              {"user-agent", Pleroma.Application.user_agent()}
            )
          else
            headers
          end
        end).()
href's avatar
href committed
268
269
270
  end

  defp build_resp_headers(headers, opts) do
href's avatar
href committed
271
272
273
274
275
    headers
    |> Enum.filter(fn {k, _} -> k in @keep_resp_headers end)
    |> build_resp_cache_headers(opts)
    |> build_resp_content_disposition_header(opts)
    |> (fn headers -> headers ++ Keyword.get(opts, :resp_headers, []) end).()
href's avatar
href committed
276
277
  end

Maksim's avatar
Maksim committed
278
  defp build_resp_cache_headers(headers, _opts) do
href's avatar
href committed
279
    has_cache? = Enum.any?(headers, fn {k, _} -> k in @resp_cache_headers end)
280
281
282
283
284
285
286
    has_cache_control? = List.keymember?(headers, "cache-control", 0)

    cond do
      has_cache? && has_cache_control? ->
        headers

      has_cache? ->
287
288
        # There's caching header present but no cache-control -- we need to explicitely override it
        # to public as Plug defaults to "max-age=0, private, must-revalidate"
289
290
291
292
293
294
295
296
297
        List.keystore(headers, "cache-control", 0, {"cache-control", "public"})

      true ->
        List.keystore(
          headers,
          "cache-control",
          0,
          {"cache-control", @default_cache_control_header}
        )
href's avatar
href committed
298
299
300
301
302
303
    end
  end

  defp build_resp_content_disposition_header(headers, opts) do
    opt = Keyword.get(opts, :inline_content_types, @inline_content_types)

304
    content_type = get_content_type(headers)
href's avatar
href committed
305
306
307
308
309
310
311
312
313

    attachment? =
      cond do
        is_list(opt) && !Enum.member?(opt, content_type) -> true
        opt == false -> true
        true -> false
      end

    if attachment? do
314
315
316
317
318
      name =
        try do
          {{"content-disposition", content_disposition_string}, _} =
            List.keytake(headers, "content-disposition", 0)

319
          [name | _] =
320
            Regex.run(
321
              ~r/filename="((?:[^"\\]|\\.)*)"/u,
322
323
324
325
326
327
328
329
330
              content_disposition_string || "",
              capture: :all_but_first
            )

          name
        rescue
          MatchError -> Keyword.get(opts, :attachment_name, "attachment")
        end

331
      disposition = "attachment; filename=\"#{name}\""
332

href's avatar
href committed
333
334
335
336
337
338
      List.keystore(headers, "content-disposition", 0, {"content-disposition", disposition})
    else
      headers
    end
  end

href's avatar
href committed
339
  defp header_length_constraint(headers, limit) when is_integer(limit) and limit > 0 do
href's avatar
href committed
340
341
342
343
344
345
346
347
348
349
350
351
352
    with {_, size} <- List.keyfind(headers, "content-length", 0),
         {size, _} <- Integer.parse(size),
         true <- size <= limit do
      :ok
    else
      false ->
        {:error, :body_too_large}

      _ ->
        :ok
    end
  end

href's avatar
href committed
353
  defp header_length_constraint(_, _), do: :ok
href's avatar
href committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381

  defp body_size_constraint(size, limit) when is_integer(limit) and limit > 0 and size >= limit do
    {:error, :body_too_large}
  end

  defp body_size_constraint(_, _), do: :ok

  defp check_read_duration(duration, max)
       when is_integer(duration) and is_integer(max) and max > 0 do
    if duration > max do
      {:error, :read_duration_exceeded}
    else
      {:ok, {duration, :erlang.system_time(:millisecond)}}
    end
  end

  defp check_read_duration(_, _), do: {:ok, :no_duration_limit, :no_duration_limit}

  defp increase_read_duration({previous_duration, started})
       when is_integer(previous_duration) and is_integer(started) do
    duration = :erlang.system_time(:millisecond) - started
    {:ok, previous_duration + duration}
  end

  defp increase_read_duration(_) do
    {:ok, :no_duration_limit, :no_duration_limit}
  end
end