wfgilman

wfgilman

How to: Plug which verifies header signature signed using request body

I’m writing up this quick “How to” because what I thought was going to be an easy implementation of a Plug to validate a webhook request turned out to be more complicated than I expected. Hopefully this can save others some time. This is for a JSON API.

Prior discussions here, and here. Recommended approach here by Jose from these discussions.

Goal: Validate a request signature which is a SHA256 HMAC of the request body signed by your secret key.

Challenge: The request body can only be read once from the conn, and it is done by Plug.Parsers before the request even reaches the router.

Solution: Normally, I add a webhook endpoint to my router, and add a controller which does something with the webhook, like store it in a queue for later processing. I can put the webhook route inside a pipeline, or add a Plug to my controller which verifies the header before processing the request.

However, I need the request body (as a string) to sign and compare to the signature in the header. It can only be accessed in this way using Plug.Conn.read_body/2. Unfortunately, that function is called by Plug.Parsers before the request hits the router.

Therefore, I need to create a Plug which is added to the endpoint of my app, before Plug.Parsers, here in endpoint.ex:

...
plug Plug.RequestId
plug Plug.Logger

# --> Add my Plug here <--
plug Plug.Parsers,
  parsers: [:urlencoded, :multipart, :json],
  pass: ["*/*"],
  json_decoder: Poison

plug Plug.MethodOverride
plug Plug.Head
...

Also, the Plug has to actually handle the request and then halt the conn. Once the request body is read, the subsequent plug, Plug.Parsers will fail. This means I can’t use a controller. It also means every request to the endpoint will go through my Plug; so I need a way of only taking action on request to the endpoint I care about.

I used a module plug for this. I copied the format from the recommended approach linked above (credit to hamiltop (Peter Hamilton) · GitHub).

init/1 and call/2 are simple. init/1 just passed along the options with no modifications. I actually need to do modifications here, but I punt to a private function after I know whether the request is to the endpoint I care about. Otherwise every request will go through those modification - unnecessary overhead.

def init(opts), do: opts

call/2 checks the request path. It just returns the connection to continue one if it doesn’t match, otherwise it performs the verification and ultimately halts it.

def call(conn, opts) do
  mount = Keyword.get(opts, :mount)
  case conn.request_path do
    ^mount ->
      verify_signature(conn, opts)
    _ ->
      conn
  end
end

verify_signature/2 does the work of verifying the header signature. If correct, it will handle the request. If not, it will return a 401 error. handle_request/2 here is the equivalent of create/2 if I were using a Phoenix.Controller. (All my webhooks come in as POST requests.)

defp verify_signature(conn, opts) do
  opts = prepare_options(opts) # Normally my init/1 function.
  with [request_signature|_] <- get_req_header(conn, opts[:header]),
       secret when not is_nil(secret) <- opts[:secret],
       {:ok, body, _} <- Plug.Conn.read_body(conn),
       signature = Plug.Crypto.MessageVerifier.sign(body, secret, :sha256),
       true <- Plug.Crypto.secure_compare(signature, request_signature) do
    handle_webhook(conn, Poison.decode!(body))
  else
    nil ->
      Logger.error(fn -> "Webhook secret is not set" end)
      halt send_resp(conn, 401, "")
    false ->
      Logger.error(fn -> "Received webhook with invalid signature" end)
      halt send_resp(conn, 401, "")
    _ ->
      halt send_resp(conn, 401, "")
  end
end

Important: Note how each response includes halt/1. This ensures the conn won’t proceed to the next plug and foul things up (since the request body has already been read). Whatever you implement for handle_webhook/2, it needs to also included halt/1 with its response.

defp handle_webhook(conn, webhook) do
  event_params = get_params(webhook)
  with {:error, changeset} <- Event.store(event_params),
       true <- is_nil(changeset.errors[:resource_topic]) do
    Logger.warn(fn -> "Failed to store event: #{inspect changeset}" end)
  end
  halt send_resp(conn, 200, "")
end

Finally, my Plug is placed in endpoint.ex at the location noted above.

MyApp.Plug.Webhook, mount: "/v1/webhooks", header: "X-Request-Signature-Sha-256", secret: "s3cret"

Where Next?

Popular in Guides/Tuts Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
wfgilman
I’m writing up this quick “How to” because what I thought was going to be an easy implementation of a Plug to validate a webhook request ...
New
anuragg
Hi everyone! I’m the founder of Render, a new cloud provider with native support for Elixir. When we launched Elixir support the most po...
New
cheerfulstoic
I spent quite a bit of time trying to find a good configuration to build / test my Elixir app in CircleCI and then push an image to Docke...
New
f0rest8
Hi, TLDR: form attribute set on the input fields and button submit. I just wanted to share a solution I discovered when making live inl...
New
magnetic
Hey :waving_hand:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and ...
New
jshprentz
Geoffrey Lessel’s 2019 book, Phoenix in Action, was written for Phoenix 1.4. I found that the book’s code examples did not match the cur...
New
zazaian
I recently generated the boilerplate for a new mix app using the Phoenix 1.3.1 phx.new generator and realized that the structure of the w...
New
pinksynth
Whenever tests have to interact with an Ecto.Repo, sometimes it’s necessary to test a few different branches or paths that data can take....
New
smpallen99
Some advice for Elixir programmers. I was reviewing someone’s Elixir Code yesterday and found a deadlock condition bug in a GenServer im...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41989 114
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement