GithubHelp home page GithubHelp logo

Comments (2)

potatosalad avatar potatosalad commented on August 22, 2024

@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/[email protected]', []}, [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

from erlang-jose.

noizu avatar noizu commented on August 22, 2024

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/[email protected]"


  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

from erlang-jose.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.