Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[akkoma] / lib / pleroma / web / plugs / http_signature_plug.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.Web.Plugs.HTTPSignaturePlug do
6 import Plug.Conn
7 import Phoenix.Controller, only: [get_format: 1, text: 2]
8 require Logger
9
10 def init(options) do
11 options
12 end
13
14 def call(%{assigns: %{valid_signature: true}} = conn, _opts) do
15 conn
16 end
17
18 def call(conn, _opts) do
19 if get_format(conn) == "activity+json" do
20 conn
21 |> maybe_assign_valid_signature()
22 |> maybe_require_signature()
23 else
24 conn
25 end
26 end
27
28 defp maybe_assign_valid_signature(conn) do
29 if has_signature_header?(conn) do
30 # set (request-target) header to the appropriate value
31 # we also replace the digest header with the one we computed
32 request_target = String.downcase("#{conn.method}") <> " #{conn.request_path}"
33
34 conn =
35 conn
36 |> put_req_header("(request-target)", request_target)
37 |> case do
38 %{assigns: %{digest: digest}} = conn -> put_req_header(conn, "digest", digest)
39 conn -> conn
40 end
41
42 assign(conn, :valid_signature, HTTPSignatures.validate_conn(conn))
43 else
44 Logger.debug("No signature header!")
45 conn
46 end
47 end
48
49 defp has_signature_header?(conn) do
50 conn |> get_req_header("signature") |> Enum.at(0, false)
51 end
52
53 defp maybe_require_signature(%{assigns: %{valid_signature: true}} = conn), do: conn
54
55 defp maybe_require_signature(conn) do
56 if Pleroma.Config.get([:activitypub, :authorized_fetch_mode], false) do
57 conn
58 |> put_status(:unauthorized)
59 |> text("Request not signed")
60 |> halt()
61 else
62 conn
63 end
64 end
65 end