Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for firebase kid:key maps. #30

Closed
noizu opened this issue Feb 17, 2017 · 2 comments
Closed

Add support for firebase kid:key maps. #30

noizu opened this issue Feb 17, 2017 · 2 comments

Comments

@noizu
Copy link

noizu commented Feb 17, 2017

Google serves firebase keys in a somewhat nonstandard form. #{kid := key}
https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com

It seems that many jose implementations, have made allowances for this structure and when passed a map of keys correctly extract and verify a firebase token using this data structure.

e.g. http://stackoverflow.com/questions/40839874/how-to-decode-firebase-jwt-token-in-python
along with some php and node and I suspect others.

Although it's a little nonstandardized putting up some docs or possible code changes for handling firebase certs will probably save some people a bunch of time down the road.

Additionally I was unable to use from_pem calls to prepare keys from the the google RSA certificates. Although possibly this was due to user error. This forced me to manually extract the certificates using :public_keys and logic derived from from https://codegists.com/snippet/erlang/jwterl_ahmadster_erlang
before passing on to JWK (below code snippet).

From_pem failed due to a inability to match the decoded record to a from_key call in jose_jwk_kty.erl

    ["Bearer " <> token] = get_req_header(conn, "authorization");
    [header, _,_] = String.split(token, ".")
    encoding_key = :base64url.decode(header) |> Poison.decode!() |> Map.get("kid")
    # TODO track expiration time, and cache entry rather than continuously querying.
    # TODO fail to fetch handling.
    api_tokens_url = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"
    request = HTTPotion.get(api_tokens_url)
    keys = Poison.decode!(request.body)
    [cert] = :public_key.pem_decode(keys[encoding_key])
    {:Certificate, {:TBSCertificate, _, _, _, _, _, _, {:SubjectPublicKeyInfo,
          {:AlgorithmIdentifier, _, _}, rsa_pub_key_der}, _, _, _}, _, _} = :public_key.pem_entry_decode(cert)
    rsa_pub_key =  :public_key.der_decode(:RSAPublicKey, rsa_pub_key_der)
    jwk = JOSE.JWK.from_key(rsa_pub_key)
    verified = JOSE.JWT.verify_strict(jwk, ["RS256"], token)
potatosalad added a commit that referenced this issue Mar 15, 2017
* Enhancements
  * Add support for decoding firebase certificate public keys (thanks to @noizu, see #30)

* Fixes
  * Fix cross-platform issues with EC signatures (specifically S and R sizes, thanks to @alexandrejbr, see #32)
  * Typo in documentation for `JOSE.encode/1` (thanks to @DaveLampton, see #31)

* Tests
  * Tested against OTP 19.3, Elixir 1.4.x, and Poison 3.x
@potatosalad
Copy link
Owner

@noizu The API is still a little clunky (I couldn't find any reference anywhere for the "standard" that the firebase keys are in. The kid appears to be a SHA-1 hash of something, but I'm not sure what has been hashed), but here's how you might accomplish a key verification (I'm just using :httpc because it's already included in OTP, but HTTPotion would also work).

["Bearer " <> token] = get_req_header(conn, "authorization")
kid =
  try do
    token
    |> JOSE.JWS.peek_protected()
    |> JOSE.decode()
    |> Map.get("kid")
  catch
    _, _ ->
      nil
  end
{:ok, {{_, 200, _}, _, body}} = :httpc.request(:get, {'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com', []}, [autoredirect: true], [])
firebase_keys = JOSE.JWK.from_firebase(IO.iodata_to_binary(body))
case Map.get(firebase_keys, kid) do
  jwk=%JOSE.JWK{} ->
    verified = JOSE.JWT.verify_strict(jwk, ["RS256"], token)
  _ ->
    # handle invalid token or kid
end

@noizu
Copy link
Author

noizu commented Mar 15, 2017

Yes, google kind of decided to go it alone in their implementation instead of following best practices .etc. Which is kind of how google seems to operate these days. Too many PHDs not enough engineers.

The token is base64 encoded with the first part indicating the current kid being used, they provide an api with current keys which slowly rotate over some period of time. Aka they return ~4 or so keys and i assume eventually dequeue and queue off the old and new keys so that there's a hour or so window in which you'll be able to look up the key.

I use rather inelegant hack of the uberauth verify_headers behaviour to handle authorization. Although I'll need to clean this up to take advantage of your latest revision.

If anyone else finds themselves dealing with googles nonsense this is what I currently use (worts and all). (I keep keys cached to avoid the need to constantly ping google's endpoint per request with some cache busting logic and rate limiting threshold of 5 seconds to avoid a disfavored or misconfigured user from being able to cause my backend to endlessly request key updates.

I'll follow up when I get the chance to refactor this a bit more to help anyone else down the road that has to handle firebase auth from elixir.

defmodule Ingressor.Plug.VerifyFirebaseHeader do
  @moduledoc """

  """


  @googleCertificateUrl "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"


  defp fetch_firebase_keys do
    request = HTTPotion.get(@googleCertificateUrl)
    expire = Timex.parse!(request.headers["expires"], "{RFC1123}")
    %{expire: expire, retrieved: DateTime.utc_now(), keys: Poison.decode!(request.body)}
  end

  defp fetch_firebase_keys_cache(refresh \\ false) do
    case :ets.lookup(:firebase_keys, :cache) do
      [{:cache, entry}] ->
        if (refresh) do
          shift = case refresh do
            {unit, offset} -> [{unit, offset}]
            _ -> [{:minutes, 5}]
          end
          expires = entry.retrieved |> Timex.shift(shift)
          if (DateTime.compare(expires, DateTime.utc_now()) == :gt) do
            entry.keys
          else
            entry = fetch_firebase_keys()
            :ets.insert(:firebase_keys, {:cache, entry})
            entry.keys
          end
        else
          if (DateTime.compare(entry.expire, DateTime.utc_now()) == :gt) do
            entry.keys
          else
            entry = fetch_firebase_keys()
            :ets.insert(:firebase_keys, {:cache, entry})
            entry.keys
          end
        end
      [] ->
        entry = fetch_firebase_keys()
        :ets.insert(:firebase_keys, {:cache, entry})
        entry.keys
    end
  end

  defp fetch_firebase_key(encoding_key) do
    keys = fetch_firebase_keys_cache()
    case (keys[encoding_key] || (fetch_firebase_keys_cache(true))[encoding_key] || (fetch_firebase_keys_cache({:seconds, 5}))[encoding_key] || :unable_to_fetch_encoding_key) do
      {:error, _} = e ->  e
      k -> {:ok, k}
    end
  end

  defp firebase_jwk(encoding_key) do
    {:ok, google_cert} = fetch_firebase_key(encoding_key)
    [cert] = :public_key.pem_decode(google_cert)
    {:Certificate, {:TBSCertificate, _, _, _, _, _, _, {:SubjectPublicKeyInfo,
          {:AlgorithmIdentifier, _, _}, rsa_pub_key_der}, _, _, _}, _, _} = :public_key.pem_entry_decode(cert)
    rsa_pub_key =  :public_key.der_decode(:RSAPublicKey, rsa_pub_key_der)
    JOSE.JWK.from_key(rsa_pub_key)
  end

  defp firebase_secret(token) do
    [header|_t] = String.split(token, ".")
    jwk = :base64url.decode(header)
      |> Poison.decode!()
      |> Map.get("kid")
      |> firebase_jwk()
  end

  #-----------------------------------------------------------------------------
  # Below identicial to Guardian.Plug.VerifyHeader
  # with small tweak to pass firebase_secret to Guardian.decode_and_verify
  #-----------------------------------------------------------------------------
  def init(opts \\ %{}) do
    opts_map = Enum.into(opts, %{})
    realm = Map.get(opts_map, :realm)
    if realm do
      {:ok, reg} = Regex.compile("#{realm}\:?\s+(.*)$", "i")
      opts_map = Map.put(opts_map, :realm_reg, reg)
    end
    opts_map
  end

  def call(conn, opts) do
    key = Map.get(opts, :key, :default)

    case Guardian.Plug.claims(conn, key) do
      {:ok, _} -> conn
      {:error, :no_session} ->
        verify_token(conn, fetch_token(conn, opts), key)
      _ -> conn
    end
  end

  defp verify_token(conn, nil, _), do: conn
  defp verify_token(conn, "", _), do: conn

  defp verify_token(conn, token, key) do
    case Guardian.decode_and_verify(token, %{"secret" => firebase_secret(token)}) do
      {:ok, claims} ->
        conn
        |> Guardian.Plug.set_claims({:ok, claims}, key)
        |> Guardian.Plug.set_current_token(token, key)
      {:error, reason} ->
        Guardian.Plug.set_claims(conn,{:error, reason}, key)
    end
  end

  defp fetch_token(conn, opts) do
    fetch_token(conn, opts, Plug.Conn.get_req_header(conn, "authorization"))
  end

  defp fetch_token(_, _, nil), do: nil
  defp fetch_token(_, _, []), do: nil

  defp fetch_token(conn, opts = %{realm_reg: reg}, [token|tail]) do
    trimmed_token = String.strip(token)
    case Regex.run(reg, trimmed_token) do
      [_, match] -> String.strip(match)
      _ -> fetch_token(conn, opts, tail)
    end
  end

  defp fetch_token(_, _, [token|_tail]), do: String.strip(token)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants