5e5361082755d11f3036d678d0f6881564b15433
[akkoma] / lib / pleroma / web / activity_pub / mrf.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.MRF do
6 @callback filter(Map.t()) :: {:ok | :reject, Map.t()}
7
8 def filter(policies, %{} = message) do
9 policies
10 |> Enum.reduce({:ok, message}, fn
11 policy, {:ok, message} -> policy.filter(message)
12 _, error -> error
13 end)
14 end
15
16 def filter(%{} = object), do: get_policies() |> filter(object)
17
18 def pipeline_filter(%{} = message, meta) do
19 object = meta[:object_data]
20 ap_id = message["object"]
21
22 if object && ap_id do
23 with {:ok, message} <- filter(Map.put(message, "object", object)) do
24 meta = Keyword.put(meta, :object_data, message["object"])
25 {:ok, Map.put(message, "object", ap_id), meta}
26 else
27 {err, message} -> {err, message, meta}
28 end
29 else
30 {err, message} = filter(message)
31
32 {err, message, meta}
33 end
34 end
35
36 def get_policies do
37 Pleroma.Config.get([:mrf, :policies], []) |> get_policies()
38 end
39
40 defp get_policies(policy) when is_atom(policy), do: [policy]
41 defp get_policies(policies) when is_list(policies), do: policies
42 defp get_policies(_), do: []
43
44 @spec subdomains_regex([String.t()]) :: [Regex.t()]
45 def subdomains_regex(domains) when is_list(domains) do
46 for domain <- domains, do: ~r(^#{String.replace(domain, "*.", "(.*\\.)*")}$)i
47 end
48
49 @spec subdomain_match?([Regex.t()], String.t()) :: boolean()
50 def subdomain_match?(domains, host) do
51 Enum.any?(domains, fn domain -> Regex.match?(domain, host) end)
52 end
53
54 @callback describe() :: {:ok | :error, Map.t()}
55
56 def describe(policies) do
57 {:ok, policy_configs} =
58 policies
59 |> Enum.reduce({:ok, %{}}, fn
60 policy, {:ok, data} ->
61 {:ok, policy_data} = policy.describe()
62 {:ok, Map.merge(data, policy_data)}
63
64 _, error ->
65 error
66 end)
67
68 mrf_policies =
69 get_policies()
70 |> Enum.map(fn policy -> to_string(policy) |> String.split(".") |> List.last() end)
71
72 exclusions = Pleroma.Config.get([:mrf, :transparency_exclusions])
73
74 base =
75 %{
76 mrf_policies: mrf_policies,
77 exclusions: length(exclusions) > 0
78 }
79 |> Map.merge(policy_configs)
80
81 {:ok, base}
82 end
83
84 def describe, do: get_policies() |> describe()
85 end