de79cad739b86c841d61b77c6439d3e866b96d5a
[akkoma] / lib / pleroma / web / media_proxy / controller.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.Web.MediaProxy.MediaProxyController do
6 use Pleroma.Web, :controller
7 alias Pleroma.{Web.MediaProxy, ReverseProxy}
8
9 @default_proxy_opts [max_body_length: 25 * 1_048_576, http: [follow_redirect: true]]
10
11 def remote(conn, params = %{"sig" => sig64, "url" => url64}) do
12 with config <- Pleroma.Config.get([:media_proxy], []),
13 true <- Keyword.get(config, :enabled, false),
14 {:ok, url} <- MediaProxy.decode_url(sig64, url64),
15 :ok <- filename_matches(Map.has_key?(params, "filename"), conn.request_path, url) do
16 ReverseProxy.call(conn, url, Keyword.get(config, :proxy_opts, @default_proxy_opts))
17 else
18 false ->
19 send_resp(conn, 404, Plug.Conn.Status.reason_phrase(404))
20
21 {:error, :invalid_signature} ->
22 send_resp(conn, 403, Plug.Conn.Status.reason_phrase(403))
23
24 {:wrong_filename, filename} ->
25 redirect(conn, external: MediaProxy.build_url(sig64, url64, filename))
26 end
27 end
28
29 def filename_matches(has_filename, path, url) do
30 filename =
31 url
32 |> MediaProxy.filename()
33 |> URI.decode()
34
35 path = URI.decode(path)
36
37 if has_filename && filename && Path.basename(path) != filename do
38 {:wrong_filename, filename}
39 else
40 :ok
41 end
42 end
43 end