Merge branch 'bugfix/unauthed-liked-by' into 'develop'
[akkoma] / lib / pleroma / signature.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.Signature do
6 @behaviour HTTPSignatures.Adapter
7
8 alias Pleroma.Keys
9 alias Pleroma.User
10 alias Pleroma.Web.ActivityPub.ActivityPub
11
12 def key_id_to_actor_id(key_id) do
13 uri =
14 URI.parse(key_id)
15 |> Map.put(:fragment, nil)
16
17 uri =
18 if String.ends_with?(uri.path, "/publickey") do
19 Map.put(uri, :path, String.replace(uri.path, "/publickey", ""))
20 else
21 uri
22 end
23
24 URI.to_string(uri)
25 end
26
27 def fetch_public_key(conn) do
28 with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
29 actor_id <- key_id_to_actor_id(kid),
30 {:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
31 {:ok, public_key}
32 else
33 e ->
34 {:error, e}
35 end
36 end
37
38 def refetch_public_key(conn) do
39 with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
40 actor_id <- key_id_to_actor_id(kid),
41 {:ok, _user} <- ActivityPub.make_user_from_ap_id(actor_id),
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 sign(%User{} = user, headers) do
51 with {:ok, %{info: %{keys: keys}}} <- User.ensure_keys_present(user),
52 {:ok, private_key, _} <- Keys.keys_from_pem(keys) do
53 HTTPSignatures.sign(private_key, user.ap_id <> "#main-key", headers)
54 end
55 end
56 end