1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MediaProxy do
9 alias Pleroma.Web.MediaProxy.Invalidation
11 @base64_opts [padding: false]
12 @cache_table :banned_urls_cache
14 def cache_table, do: @cache_table
16 @spec in_banned_urls(String.t()) :: boolean()
17 def in_banned_urls(url), do: elem(Cachex.exists?(@cache_table, url(url)), 1)
19 def remove_from_banned_urls(urls) when is_list(urls) do
20 Cachex.execute!(@cache_table, fn cache ->
21 Enum.each(Invalidation.prepare_urls(urls), &Cachex.del(cache, &1))
25 def remove_from_banned_urls(url) when is_binary(url) do
26 Cachex.del(@cache_table, url(url))
29 def put_in_banned_urls(urls) when is_list(urls) do
30 Cachex.execute!(@cache_table, fn cache ->
31 Enum.each(Invalidation.prepare_urls(urls), &Cachex.put(cache, &1, true))
35 def put_in_banned_urls(url) when is_binary(url) do
36 Cachex.put(@cache_table, url(url), true)
39 def url(url) when is_nil(url) or url == "", do: nil
40 def url("/" <> _ = url), do: url
43 if disabled?() or not url_proxiable?(url) do
50 @spec url_proxiable?(String.t()) :: boolean()
51 def url_proxiable?(url) do
52 if local?(url) or whitelisted?(url) do
59 defp disabled?, do: !Config.get([:media_proxy, :enabled], false)
61 defp local?(url), do: String.starts_with?(url, Pleroma.Web.base_url())
63 defp whitelisted?(url) do
64 %{host: domain} = URI.parse(url)
66 mediaproxy_whitelist_domains =
67 [:media_proxy, :whitelist]
69 |> Enum.map(&maybe_get_domain_from_url/1)
72 if base_url = Config.get([Upload, :base_url]) do
73 %{host: base_domain} = URI.parse(base_url)
74 [base_domain | mediaproxy_whitelist_domains]
76 mediaproxy_whitelist_domains
79 domain in whitelist_domains
82 defp maybe_get_domain_from_url("http" <> _ = url) do
86 defp maybe_get_domain_from_url(domain), do: domain
88 def encode_url(url) do
89 base64 = Base.url_encode64(url, @base64_opts)
94 |> Base.url_encode64(@base64_opts)
96 build_url(sig64, base64, filename(url))
99 def decode_url(sig, url) do
100 with {:ok, sig} <- Base.url_decode64(sig, @base64_opts),
101 signature when signature == sig <- signed_url(url) do
102 {:ok, Base.url_decode64!(url, @base64_opts)}
104 _ -> {:error, :invalid_signature}
108 defp signed_url(url) do
109 :crypto.hmac(:sha, Config.get([Web.Endpoint, :secret_key_base]), url)
112 def filename(url_or_path) do
113 if path = URI.parse(url_or_path).path, do: Path.basename(path)
116 def build_url(sig_base64, url_base64, filename \\ nil) do
118 Config.get([:media_proxy, :base_url], Web.base_url()),