Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into remake-remodel
[akkoma] / lib / pleroma / object / containment.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.Object.Containment do
6 @moduledoc """
7 This module contains some useful functions for containing objects to specific
8 origins and determining those origins. They previously lived in the
9 ActivityPub `Transmogrifier` module.
10
11 Object containment is an important step in validating remote objects to prevent
12 spoofing, therefore removal of object containment functions is NOT recommended.
13 """
14 def get_actor(%{"actor" => actor}) when is_binary(actor) do
15 actor
16 end
17
18 def get_actor(%{"actor" => actor}) when is_list(actor) do
19 if is_binary(Enum.at(actor, 0)) do
20 Enum.at(actor, 0)
21 else
22 Enum.find(actor, fn %{"type" => type} -> type in ["Person", "Service", "Application"] end)
23 |> Map.get("id")
24 end
25 end
26
27 def get_actor(%{"actor" => %{"id" => id}}) when is_bitstring(id) do
28 id
29 end
30
31 def get_actor(%{"actor" => nil, "attributedTo" => actor}) when not is_nil(actor) do
32 get_actor(%{"actor" => actor})
33 end
34
35 def get_object(%{"object" => id}) when is_binary(id) do
36 id
37 end
38
39 def get_object(%{"object" => %{"id" => id}}) when is_binary(id) do
40 id
41 end
42
43 def get_object(_) do
44 nil
45 end
46
47 # TODO: We explicitly allow 'tag' URIs through, due to references to legacy OStatus
48 # objects being present in the test suite environment. Once these objects are
49 # removed, please also remove this.
50 if Mix.env() == :test do
51 defp compare_uris(_, %URI{scheme: "tag"}), do: :ok
52 end
53
54 defp compare_uris(%URI{} = id_uri, %URI{} = other_uri) do
55 if id_uri.host == other_uri.host do
56 :ok
57 else
58 :error
59 end
60 end
61
62 defp compare_uris(_, _), do: :error
63
64 @doc """
65 Checks that an imported AP object's actor matches the domain it came from.
66 """
67 def contain_origin(_id, %{"actor" => nil}), do: :error
68
69 def contain_origin(id, %{"actor" => _actor} = params) do
70 id_uri = URI.parse(id)
71 actor_uri = URI.parse(get_actor(params))
72
73 compare_uris(actor_uri, id_uri)
74 end
75
76 def contain_origin(id, %{"attributedTo" => actor} = params),
77 do: contain_origin(id, Map.put(params, "actor", actor))
78
79 def contain_origin(_id, _data), do: :error
80
81 def contain_origin_from_id(id, %{"id" => other_id} = _params) when is_binary(other_id) do
82 id_uri = URI.parse(id)
83 other_uri = URI.parse(other_id)
84
85 compare_uris(id_uri, other_uri)
86 end
87
88 def contain_origin_from_id(_id, _data), do: :error
89
90 def contain_child(%{"object" => %{"id" => id, "attributedTo" => _} = object}),
91 do: contain_origin(id, object)
92
93 def contain_child(_), do: :ok
94 end