Closed noizu closed 7 years ago
@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
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
Google serves firebase keys in a somewhat nonstandard form.
#{kid := key}
https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.comIt 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