1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Plugs.HTTPSignaturePlug do
7 import Phoenix.Controller, only: [get_format: 1, text: 2]
14 def call(%{assigns: %{valid_signature: true}} = conn, _opts) do
18 def call(conn, _opts) do
19 if get_format(conn) == "activity+json" do
21 |> maybe_assign_valid_signature()
22 |> maybe_require_signature()
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}"
36 |> put_req_header("(request-target)", request_target)
38 %{assigns: %{digest: digest}} = conn -> put_req_header(conn, "digest", digest)
42 assign(conn, :valid_signature, HTTPSignatures.validate_conn(conn))
44 Logger.debug("No signature header!")
49 defp has_signature_header?(conn) do
50 conn |> get_req_header("signature") |> Enum.at(0, false)
53 defp maybe_require_signature(%{assigns: %{valid_signature: true}} = conn), do: conn
55 defp maybe_require_signature(conn) do
56 if Pleroma.Config.get([:activitypub, :authorized_fetch_mode], false) do
58 |> put_status(:unauthorized)
59 |> text("Request not signed")