logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

signature.ex (2245B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Signature do
  5. @behaviour HTTPSignatures.Adapter
  6. alias Pleroma.EctoType.ActivityPub.ObjectValidators
  7. alias Pleroma.Keys
  8. alias Pleroma.User
  9. alias Pleroma.Web.ActivityPub.ActivityPub
  10. @known_suffixes ["/publickey", "/main-key"]
  11. def key_id_to_actor_id(key_id) do
  12. uri =
  13. key_id
  14. |> URI.parse()
  15. |> Map.put(:fragment, nil)
  16. |> remove_suffix(@known_suffixes)
  17. maybe_ap_id = URI.to_string(uri)
  18. case ObjectValidators.ObjectID.cast(maybe_ap_id) do
  19. {:ok, ap_id} ->
  20. {:ok, ap_id}
  21. _ ->
  22. case Pleroma.Web.WebFinger.finger(maybe_ap_id) do
  23. {:ok, %{"ap_id" => ap_id}} -> {:ok, ap_id}
  24. _ -> {:error, maybe_ap_id}
  25. end
  26. end
  27. end
  28. defp remove_suffix(uri, [test | rest]) do
  29. if not is_nil(uri.path) and String.ends_with?(uri.path, test) do
  30. Map.put(uri, :path, String.replace(uri.path, test, ""))
  31. else
  32. remove_suffix(uri, rest)
  33. end
  34. end
  35. defp remove_suffix(uri, []), do: uri
  36. def fetch_public_key(conn) do
  37. with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
  38. {:ok, actor_id} <- key_id_to_actor_id(kid),
  39. {:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
  40. {:ok, public_key}
  41. else
  42. e ->
  43. {:error, e}
  44. end
  45. end
  46. def refetch_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, _user} <- ActivityPub.make_user_from_ap_id(actor_id),
  50. {:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
  51. {:ok, public_key}
  52. else
  53. e ->
  54. {:error, e}
  55. end
  56. end
  57. def sign(%User{keys: keys} = user, headers) do
  58. with {:ok, private_key, _} <- Keys.keys_from_pem(keys) do
  59. HTTPSignatures.sign(private_key, user.ap_id <> "#main-key", headers)
  60. end
  61. end
  62. def signed_date, do: signed_date(NaiveDateTime.utc_now())
  63. def signed_date(%NaiveDateTime{} = date) do
  64. Timex.format!(date, "{WDshort}, {0D} {Mshort} {YYYY} {h24}:{m}:{s} GMT")
  65. end
  66. end