Merge remote-tracking branch 'pleroma/develop' into feature/addressable-lists
[akkoma] / lib / pleroma / object / containment.ex
1 defmodule Pleroma.Object.Containment do
2 @moduledoc """
3 This module contains some useful functions for containing objects to specific
4 origins and determining those origins. They previously lived in the
5 ActivityPub `Transmogrifier` module.
6
7 Object containment is an important step in validating remote objects to prevent
8 spoofing, therefore removal of object containment functions is NOT recommended.
9 """
10 def get_actor(%{"actor" => actor}) when is_binary(actor) do
11 actor
12 end
13
14 def get_actor(%{"actor" => actor}) when is_list(actor) do
15 if is_binary(Enum.at(actor, 0)) do
16 Enum.at(actor, 0)
17 else
18 Enum.find(actor, fn %{"type" => type} -> type in ["Person", "Service", "Application"] end)
19 |> Map.get("id")
20 end
21 end
22
23 def get_actor(%{"actor" => %{"id" => id}}) when is_bitstring(id) do
24 id
25 end
26
27 def get_actor(%{"actor" => nil, "attributedTo" => actor}) when not is_nil(actor) do
28 get_actor(%{"actor" => actor})
29 end
30
31 @doc """
32 Checks that an imported AP object's actor matches the domain it came from.
33 """
34 def contain_origin(_id, %{"actor" => nil}), do: :error
35
36 def contain_origin(id, %{"actor" => _actor} = params) do
37 id_uri = URI.parse(id)
38 actor_uri = URI.parse(get_actor(params))
39
40 if id_uri.host == actor_uri.host do
41 :ok
42 else
43 :error
44 end
45 end
46
47 def contain_origin_from_id(_id, %{"id" => nil}), do: :error
48
49 def contain_origin_from_id(id, %{"id" => other_id} = _params) do
50 id_uri = URI.parse(id)
51 other_uri = URI.parse(other_id)
52
53 if id_uri.host == other_uri.host do
54 :ok
55 else
56 :error
57 end
58 end
59 end