Merge branch 'docs/storing-remote-media' into 'develop'
[akkoma] / lib / pleroma / signature.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.Signature do
6 @behaviour HTTPSignatures.Adapter
7
8 alias Pleroma.Keys
9 alias Pleroma.User
10 alias Pleroma.Web.ActivityPub.ActivityPub
11 alias Pleroma.Web.ActivityPub.ObjectValidators.Types
12
13 def key_id_to_actor_id(key_id) do
14 uri =
15 URI.parse(key_id)
16 |> Map.put(:fragment, nil)
17
18 uri =
19 if not is_nil(uri.path) and String.ends_with?(uri.path, "/publickey") do
20 Map.put(uri, :path, String.replace(uri.path, "/publickey", ""))
21 else
22 uri
23 end
24
25 maybe_ap_id = URI.to_string(uri)
26
27 case Types.ObjectID.cast(maybe_ap_id) do
28 {:ok, ap_id} ->
29 {:ok, ap_id}
30
31 _ ->
32 case Pleroma.Web.WebFinger.finger(maybe_ap_id) do
33 %{"ap_id" => ap_id} -> {:ok, ap_id}
34 _ -> {:error, maybe_ap_id}
35 end
36 end
37 end
38
39 def fetch_public_key(conn) do
40 with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
41 {:ok, actor_id} <- key_id_to_actor_id(kid),
42 {:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
43 {:ok, public_key}
44 else
45 e ->
46 {:error, e}
47 end
48 end
49
50 def refetch_public_key(conn) do
51 with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
52 {:ok, actor_id} <- key_id_to_actor_id(kid),
53 {:ok, _user} <- ActivityPub.make_user_from_ap_id(actor_id),
54 {:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
55 {:ok, public_key}
56 else
57 e ->
58 {:error, e}
59 end
60 end
61
62 def sign(%User{} = user, headers) do
63 with {:ok, %{keys: keys}} <- User.ensure_keys_present(user),
64 {:ok, private_key, _} <- Keys.keys_from_pem(keys) do
65 HTTPSignatures.sign(private_key, user.ap_id <> "#main-key", headers)
66 end
67 end
68
69 def signed_date, do: signed_date(NaiveDateTime.utc_now())
70
71 def signed_date(%NaiveDateTime{} = date) do
72 Timex.format!(date, "{WDshort}, {0D} {Mshort} {YYYY} {h24}:{m}:{s} GMT")
73 end
74 end