strip \r and \r from content-disposition filenames
[akkoma] / lib / pleroma / web / plugs / uploaded_media.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.UploadedMedia do
6 @moduledoc """
7 """
8
9 import Plug.Conn
10 import Pleroma.Web.Gettext
11 require Logger
12
13 alias Pleroma.Web.MediaProxy
14
15 @behaviour Plug
16 # no slashes
17 @path "media"
18
19 @default_cache_control_header "public, max-age=1209600"
20
21 def init(_opts) do
22 static_plug_opts =
23 [
24 headers: %{"cache-control" => @default_cache_control_header},
25 cache_control_for_etags: @default_cache_control_header
26 ]
27 |> Keyword.put(:from, "__unconfigured_media_plug")
28 |> Keyword.put(:at, "/__unconfigured_media_plug")
29 |> Plug.Static.init()
30
31 %{static_plug_opts: static_plug_opts}
32 end
33
34 def call(%{request_path: <<"/", @path, "/", file::binary>>} = conn, opts) do
35 conn =
36 case fetch_query_params(conn) do
37 %{query_params: %{"name" => name}} = conn ->
38 name = escape_header_value(name)
39
40 put_resp_header(conn, "content-disposition", "filename=\"#{name}\"")
41
42 conn ->
43 conn
44 end
45 |> merge_resp_headers([{"content-security-policy", "sandbox"}])
46
47 config = Pleroma.Config.get(Pleroma.Upload)
48
49 with uploader <- Keyword.fetch!(config, :uploader),
50 {:ok, get_method} <- uploader.get_file(file),
51 false <- media_is_banned(conn, get_method) do
52 get_media(conn, get_method, opts)
53 else
54 _ ->
55 conn
56 |> send_resp(:internal_server_error, dgettext("errors", "Failed"))
57 |> halt()
58 end
59 end
60
61 def call(conn, _opts), do: conn
62
63 defp media_is_banned(%{request_path: path} = _conn, {:static_dir, _}) do
64 MediaProxy.in_banned_urls(Pleroma.Upload.base_url() <> path)
65 end
66
67 defp media_is_banned(_, {:url, url}), do: MediaProxy.in_banned_urls(url)
68
69 defp media_is_banned(_, _), do: false
70
71 defp get_media(conn, {:static_dir, directory}, opts) do
72 static_opts =
73 Map.get(opts, :static_plug_opts)
74 |> Map.put(:at, [@path])
75 |> Map.put(:from, directory)
76
77 conn = Plug.Static.call(conn, static_opts)
78
79 if conn.halted do
80 conn
81 else
82 conn
83 |> send_resp(:not_found, dgettext("errors", "Not found"))
84 |> halt()
85 end
86 end
87
88 defp get_media(conn, {:url, url}, _) do
89 conn
90 |> Phoenix.Controller.redirect(external: url)
91 |> halt()
92 end
93
94 defp get_media(conn, unknown, _) do
95 Logger.error("#{__MODULE__}: Unknown get startegy: #{inspect(unknown)}")
96
97 conn
98 |> send_resp(:internal_server_error, dgettext("errors", "Internal Error"))
99 |> halt()
100 end
101
102 defp escape_header_value(value) do
103 value
104 |> String.replace("\"", "\\\"")
105 |> String.replace("\\r", "")
106 |> String.replace("\\n", "")
107 end
108 end