From 0fa14777a2fd9b8c583fffdebfd88c06b75db652 Mon Sep 17 00:00:00 2001 From: Augusto Alonso Date: Thu, 21 Sep 2023 13:17:01 -0300 Subject: [PATCH] Make Lti_1p3.Utils.fetch_public_key/2 more robust --- lib/lti_1p3/utils.ex | 42 +++++++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/lib/lti_1p3/utils.ex b/lib/lti_1p3/utils.ex index 54c0b7a..192d8b9 100644 --- a/lib/lti_1p3/utils.ex +++ b/lib/lti_1p3/utils.ex @@ -138,24 +138,36 @@ defmodule Lti_1p3.Utils do error end - case Enum.find(public_key_set["keys"], fn key -> key["kid"] == kid end) do - nil -> - {:error, - %{ - reason: :key_not_found, - msg: "Key with kid #{kid} not found in the fetched list of public keys" - }} - - public_key_json -> - public_key = - public_key_json - |> convert_map_to_base64url() - |> JOSE.JWK.from() - - {:ok, public_key} + if is_container(public_key_set) do + case Enum.find(public_key_set["keys"], fn key -> is_container(key) && key["kid"] == kid end) do + nil -> + return_key_not_found(kid) + + public_key_json -> + public_key = + public_key_json + |> convert_map_to_base64url() + |> JOSE.JWK.from() + + {:ok, public_key} + end + else + return_key_not_found(kid) end end + defp is_container(container) do + Keyword.keyword?(container) || is_map(container) || is_struct(container) + end + + defp return_key_not_found(kid) do + {:error, + %{ + reason: :key_not_found, + msg: "Key with kid #{kid} not found in the fetched list of public keys" + }} + end + @doc """ Given a map representing a JWK, encodes all its values to Base64URL. """