http signatures: derive actor ID from key ID.
[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 defp key_id_to_actor_id(key_id) do
13 URI.parse(key_id)
14 |> Map.put(:fragment, nil)
15 |> URI.to_string()
16 end
17
18 def fetch_public_key(conn) do
19 with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
20 actor_id <- key_id_to_actor_id(kid),
21 {:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
22 {:ok, public_key}
23 else
24 e ->
25 {:error, e}
26 end
27 end
28
29 def refetch_public_key(conn) do
30 with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
31 actor_id <- key_id_to_actor_id(kid),
32 {:ok, _user} <- ActivityPub.make_user_from_ap_id(actor_id),
33 {:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
34 {:ok, public_key}
35 else
36 e ->
37 {:error, e}
38 end
39 end
40
41 def sign(%User{} = user, headers) do
42 with {:ok, %{info: %{keys: keys}}} <- User.ensure_keys_present(user),
43 {:ok, private_key, _} <- Keys.keys_from_pem(keys) do
44 HTTPSignatures.sign(private_key, user.ap_id <> "#main-key", headers)
45 end
46 end
47 end