add test for metrics controller
[akkoma] / lib / pleroma / signature.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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.EctoType.ActivityPub.ObjectValidators
9 alias Pleroma.Keys
10 alias Pleroma.User
11 alias Pleroma.Web.ActivityPub.ActivityPub
12
13 @known_suffixes ["/publickey", "/main-key"]
14
15 def key_id_to_actor_id(key_id) do
16 uri =
17 key_id
18 |> URI.parse()
19 |> Map.put(:fragment, nil)
20 |> remove_suffix(@known_suffixes)
21
22 maybe_ap_id = URI.to_string(uri)
23
24 case ObjectValidators.ObjectID.cast(maybe_ap_id) do
25 {:ok, ap_id} ->
26 {:ok, ap_id}
27
28 _ ->
29 case Pleroma.Web.WebFinger.finger(maybe_ap_id) do
30 {:ok, %{"ap_id" => ap_id}} -> {:ok, ap_id}
31 _ -> {:error, maybe_ap_id}
32 end
33 end
34 end
35
36 defp remove_suffix(uri, [test | rest]) do
37 if not is_nil(uri.path) and String.ends_with?(uri.path, test) do
38 Map.put(uri, :path, String.replace(uri.path, test, ""))
39 else
40 remove_suffix(uri, rest)
41 end
42 end
43
44 defp remove_suffix(uri, []), do: uri
45
46 def fetch_public_key(conn) do
47 with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
48 {:ok, actor_id} <- key_id_to_actor_id(kid),
49 {:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
50 {:ok, public_key}
51 else
52 e ->
53 {:error, e}
54 end
55 end
56
57 def refetch_public_key(conn) do
58 with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
59 {:ok, actor_id} <- key_id_to_actor_id(kid),
60 {:ok, _user} <- ActivityPub.make_user_from_ap_id(actor_id),
61 {:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
62 {:ok, public_key}
63 else
64 e ->
65 {:error, e}
66 end
67 end
68
69 def sign(%User{keys: keys} = user, headers) do
70 with {:ok, private_key, _} <- Keys.keys_from_pem(keys) do
71 HTTPSignatures.sign(private_key, user.ap_id <> "#main-key", headers)
72 end
73 end
74
75 def signed_date, do: signed_date(NaiveDateTime.utc_now())
76
77 def signed_date(%NaiveDateTime{} = date) do
78 Timex.format!(date, "{WDshort}, {0D} {Mshort} {YYYY} {h24}:{m}:{s} GMT")
79 end
80 end