http_signatures.ex 1.08 KB
Newer Older
lain's avatar
lain committed
1
2
3
# https://tools.ietf.org/html/draft-cavage-http-signatures-08
defmodule Pleroma.Web.HTTPSignatures do
  def split_signature(sig) do
4
    default = %{"headers" => "date"}
lain's avatar
lain committed
5

6
    sig = sig
lain's avatar
lain committed
7
8
9
10
11
12
13
    |> String.trim()
    |> String.split(",")
    |> Enum.reduce(default, fn(part, acc) ->
      [key | rest] = String.split(part, "=")
      value = Enum.join(rest, "=")
      Map.put(acc, key, String.trim(value, "\""))
    end)
14
15

    Map.put(sig, "headers", String.split(sig["headers"], ~r/\s/))
lain's avatar
lain committed
16
17
18
19
20
21
22
23
  end

  def validate(headers, signature, public_key) do
    sigstring = build_signing_string(headers, signature["headers"])
    {:ok, sig} = Base.decode64(signature["signature"])
    verify = :public_key.verify(sigstring, :sha256, sig, public_key)
  end

lain's avatar
lain committed
24
25
26
27
28
29
  def validate_conn(conn, public_key) do
    headers = Enum.into(conn.req_headers, %{})
    signature = split_signature(headers["signature"])
    validate(headers, signature, public_key)
  end

lain's avatar
lain committed
30
31
32
33
34
35
  def build_signing_string(headers, used_headers) do
    used_headers
    |> Enum.map(fn (header) -> "#{header}: #{headers[header]}" end)
    |> Enum.join("\n")
  end
end