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]
13 @spec in_banned_urls(String.t()) :: boolean()
14 def in_banned_urls(url), do: elem(Cachex.exists?(:banned_urls_cache, url(url)), 1)
16 def remove_from_banned_urls(urls) when is_list(urls) do
17 Cachex.execute!(:banned_urls_cache, fn cache ->
18 Enum.each(Invalidation.prepare_urls(urls), &Cachex.del(cache, &1))
22 def remove_from_banned_urls(url) when is_binary(url) do
23 Cachex.del(:banned_urls_cache, url(url))
26 def put_in_banned_urls(urls) when is_list(urls) do
27 Cachex.execute!(:banned_urls_cache, fn cache ->
28 Enum.each(Invalidation.prepare_urls(urls), &Cachex.put(cache, &1, true))
32 def put_in_banned_urls(url) when is_binary(url) do
33 Cachex.put(:banned_urls_cache, url(url), true)
36 def url(url) when is_nil(url) or url == "", do: nil
37 def url("/" <> _ = url), do: url
40 if disabled?() or not url_proxiable?(url) do
47 @spec url_proxiable?(String.t()) :: boolean()
48 def url_proxiable?(url) do
49 if local?(url) or whitelisted?(url) do
56 defp disabled?, do: !Config.get([:media_proxy, :enabled], false)
58 defp local?(url), do: String.starts_with?(url, Pleroma.Web.base_url())
60 defp whitelisted?(url) do
61 %{host: domain} = URI.parse(url)
63 mediaproxy_whitelist_domains =
64 [:media_proxy, :whitelist]
66 |> Enum.map(&maybe_get_domain_from_url/1)
69 if base_url = Config.get([Upload, :base_url]) do
70 %{host: base_domain} = URI.parse(base_url)
71 [base_domain | mediaproxy_whitelist_domains]
73 mediaproxy_whitelist_domains
76 domain in whitelist_domains
79 defp maybe_get_domain_from_url("http" <> _ = url) do
83 defp maybe_get_domain_from_url(domain), do: domain
85 def encode_url(url) do
86 base64 = Base.url_encode64(url, @base64_opts)
91 |> Base.url_encode64(@base64_opts)
93 build_url(sig64, base64, filename(url))
96 def decode_url(sig, url) do
97 with {:ok, sig} <- Base.url_decode64(sig, @base64_opts),
98 signature when signature == sig <- signed_url(url) do
99 {:ok, Base.url_decode64!(url, @base64_opts)}
101 _ -> {:error, :invalid_signature}
105 defp signed_url(url) do
106 :crypto.hmac(:sha, Config.get([Web.Endpoint, :secret_key_base]), url)
109 def filename(url_or_path) do
110 if path = URI.parse(url_or_path).path, do: Path.basename(path)
113 def build_url(sig_base64, url_base64, filename \\ nil) do
115 Config.get([:media_proxy, :base_url], Web.base_url()),