diff --git a/src/oidcc_client_context.erl b/src/oidcc_client_context.erl index 50bf83fe..2ca48eee 100644 --- a/src/oidcc_client_context.erl +++ b/src/oidcc_client_context.erl @@ -139,7 +139,24 @@ Create Client Context from a `m:oidcc_provider_configuration_worker`. ClientId :: binary(), ClientSecret :: unauthenticated, Opts :: unauthenticated_opts(). -from_configuration_worker(ProviderName, ClientId, ClientSecret, Opts) when is_pid(ProviderName) -> +from_configuration_worker(ProviderName, ClientId, ClientSecret, Opts) when is_atom(ProviderName) -> + case erlang:whereis(ProviderName) of + undefined -> + {error, provider_not_ready}; + _Pid -> + load_from_configuration_worker(ProviderName, ClientId, ClientSecret, Opts) + end; +from_configuration_worker(ProviderName, ClientId, ClientSecret, Opts) -> + load_from_configuration_worker(ProviderName, ClientId, ClientSecret, Opts). + +-spec load_from_configuration_worker(ProviderName, ClientId, ClientSecret, Opts) -> + {ok, t()} | {error, error()} +when + ProviderName :: gen_server:server_ref(), + ClientId :: binary(), + ClientSecret :: binary() | unauthenticated, + Opts :: opts(). +load_from_configuration_worker(ProviderName, ClientId, ClientSecret, Opts) -> maybe #oidcc_provider_configuration{} = ProviderConfiguration ?= @@ -155,13 +172,6 @@ from_configuration_worker(ProviderName, ClientId, ClientSecret, Opts) when is_pi )} else undefined -> {error, provider_not_ready} - end; -from_configuration_worker(ProviderName, ClientId, ClientSecret, Opts) -> - case erlang:whereis(ProviderName) of - undefined -> - {error, provider_not_ready}; - Pid -> - from_configuration_worker(Pid, ClientId, ClientSecret, Opts) end. -doc """ diff --git a/src/oidcc_jwt_util.erl b/src/oidcc_jwt_util.erl index 458fc007..d9972aef 100644 --- a/src/oidcc_jwt_util.erl +++ b/src/oidcc_jwt_util.erl @@ -86,23 +86,7 @@ when Jws :: #jose_jws{}, Jwk :: jose_jwk:key(). verify_signature(Token, AllowAlgorithms, #jose_jwk{keys = {jose_jwk_set, Keys}}) -> - lists:foldl( - fun - (_Key, {ok, _Res} = Acc) -> - Acc; - (Key, Acc) -> - case {verify_signature(Token, AllowAlgorithms, Key), Acc} of - {{ok, Res}, _Acc} -> - {ok, Res}; - {_Res, {error, {no_matching_key_with_kid, Kid}}} -> - {error, {no_matching_key_with_kid, Kid}}; - {Res, _Acc} -> - Res - end - end, - {error, no_matching_key}, - Keys - ); + try_key_set(fun(Key) -> verify_signature(Token, AllowAlgorithms, Key) end, Keys); verify_signature(Token, AllowAlgorithms, #jose_jwk{} = Jwks) -> try Kid = @@ -344,22 +328,8 @@ decrypt(_Jwt, _Jwk, undefined, _SupportedEncValues) -> decrypt(_Jwt, _Jwk, _SupportedAlgorithms, undefined) -> {error, no_supported_alg_or_key}; decrypt(Jwt, #jose_jwk{keys = {jose_jwk_set, Keys}}, SupportedAlgorithms, SupportedEncValues) -> - lists:foldl( - fun - (_Key, {ok, _Res} = Acc) -> - Acc; - (Key, Acc) -> - case {decrypt(Jwt, Key, SupportedAlgorithms, SupportedEncValues), Acc} of - {{ok, Res}, _Acc} -> - {ok, Res}; - {_Res, {error, {no_matching_key_with_kid, Kid}}} -> - {error, {no_matching_key_with_kid, Kid}}; - {Res, _Acc} -> - Res - end - end, - {error, no_matching_key}, - Keys + try_key_set( + fun(Key) -> decrypt(Jwt, Key, SupportedAlgorithms, SupportedEncValues) end, Keys ); decrypt(Jwt, #jose_jwk{} = Jwk, SupportedAlgorithms, SupportedEncValues) -> maybe @@ -384,10 +354,8 @@ decrypt(Jwt, #jose_jwk{} = Jwk, SupportedAlgorithms, SupportedEncValues) -> {Token, _Jwe} = jose_jwe:block_decrypt(Jwk, Jwt), {ok, Token} catch - error:_ when Kid =:= none -> - {error, no_matching_key}; error:_ -> - {error, {no_matching_key_with_kid, Kid}} + {error, no_matching_key} end end end. @@ -400,6 +368,38 @@ verify_in_list(Value, List) -> {error, no_matching_key} end. +-spec try_key_set(Fun, Keys) -> {ok, Result} | {error, error()} when + Fun :: fun((jose_jwk:key()) -> {ok, Result} | {error, error()}), + Keys :: [jose_jwk:key()], + Result :: term(). +try_key_set(Fun, Keys) -> + {_Rank, Result} = + lists:foldl( + fun + (_Key, {_AccRank, {ok, _Res}} = Acc) -> + Acc; + (Key, {AccRank, _AccResult} = Acc) -> + Result = Fun(Key), + case key_result_rank(Key, Result) of + Rank when Rank >= AccRank -> {Rank, Result}; + _Rank -> Acc + end + end, + {0, {error, no_matching_key}}, + Keys + ), + Result. + +%% The error of a key that the token kid selects must win over the kid error +%% of other keys. The kid error must win over a key without kid, because only +%% the kid error makes the caller refresh the key set. +-spec key_result_rank(Key :: jose_jwk:key(), Result :: {ok, term()} | {error, error()}) -> + 0..3. +key_result_rank(_Key, {ok, _Res}) -> 3; +key_result_rank(_Key, {error, {no_matching_key_with_kid, _Kid}}) -> 1; +key_result_rank(#jose_jwk{fields = #{<<"kid">> := _}}, {error, _Reason}) -> 2; +key_result_rank(#jose_jwk{}, {error, _Reason}) -> 0. + verify_decrypted_token(Jwt, SigningAlgs, Jwe, Jwks) -> case verify_signature(Jwt, SigningAlgs, Jwks) of {ok, Result} -> diff --git a/src/oidcc_provider_configuration_worker.erl b/src/oidcc_provider_configuration_worker.erl index 10d4b1fd..5b087f6f 100644 --- a/src/oidcc_provider_configuration_worker.erl +++ b/src/oidcc_provider_configuration_worker.erl @@ -220,9 +220,11 @@ handle_continue( maybe_cancel_timer(OldTimer), + LoadResult = oidcc_provider_configuration:load_jwks(JwksUri, ProviderConfigurationOpts), + ok = drop_queued_unknown_kid_refreshes(), + maybe - {ok, {Jwks, Expiry}} ?= - oidcc_provider_configuration:load_jwks(JwksUri, ProviderConfigurationOpts), + {ok, {Jwks, Expiry}} ?= LoadResult, NewTimer = erlang:send_after(Expiry, self(), jwks_expired), ok = store_in_ets(EtsTable, jwks, Jwks), {noreply, State#state{ @@ -362,14 +364,31 @@ has_kid(#jose_jwk{fields = #{<<"kid">> := _}}, _Kid) -> has_kid(#jose_jwk{keys = {jose_jwk_set, Keys}}, Kid) -> lists:foldl( fun - (_Key, Acc) when is_boolean(Acc) -> - Acc; - (Key, unknown) -> - has_kid(Key, Kid) + (_Key, true) -> + true; + (Key, Acc) -> + case has_kid(Key, Kid) of + unknown -> Acc; + Result -> Result + end end, unknown, Keys - ). + ); +has_kid(#jose_jwk{}, _Kid) -> + unknown. + +%% A queued request was sent before the fetch finished. Another fetch for it +%% would only repeat the one that just ran. The pattern relies on the +%% `gen_server:cast/2' message format. +-spec drop_queued_unknown_kid_refreshes() -> ok. +drop_queued_unknown_kid_refreshes() -> + receive + {'$gen_cast', {refresh_jwks_for_unknown_kid, _Kid}} -> + drop_queued_unknown_kid_refreshes() + after 0 -> + ok + end. -spec maybe_cancel_timer(Timer :: undefined | reference()) -> ok. maybe_cancel_timer(undefined) -> diff --git a/test/oidcc_client_context_test.erl b/test/oidcc_client_context_test.erl index a87f81ad..b616f374 100644 --- a/test/oidcc_client_context_test.erl +++ b/test/oidcc_client_context_test.erl @@ -21,6 +21,91 @@ provider_not_running_test() -> ), ok. +from_configuration_worker_reads_from_ets_test() -> + Name = from_configuration_worker_reads_from_ets_test, + with_provider_mock(fun() -> + {ok, Pid} = oidcc_provider_configuration_worker:start_link(#{ + issuer => <<"https://example.com">>, + name => {local, Name} + }), + try + #jose_jwk{} = oidcc_provider_configuration_worker:get_jwks(Pid), + with_suspended_worker(Pid, fun() -> + ?assertMatch( + {ok, #oidcc_client_context{}}, + oidcc_client_context:from_configuration_worker( + Name, <<"client_id">>, <<"client_secret">> + ) + ) + end) + after + ok = gen_server:stop(Pid) + end + end). + +from_configuration_worker_global_name_test() -> + Name = {global, from_configuration_worker_global_name_test}, + with_provider_mock(fun() -> + {ok, Pid} = oidcc_provider_configuration_worker:start_link(#{ + issuer => <<"https://example.com">>, + name => Name + }), + try + ?assertMatch( + {ok, #oidcc_client_context{}}, + oidcc_client_context:from_configuration_worker( + Name, <<"client_id">>, <<"client_secret">> + ) + ) + after + ok = gen_server:stop(Pid) + end + end). + +with_suspended_worker(Pid, TestFun) -> + ok = sys:suspend(Pid), + try + TestFun() + after + ok = sys:resume(Pid) + end. + +with_provider_mock(TestFun) -> + DiscoveryBody = iolist_to_binary( + json:encode(#{ + issuer => <<"https://example.com">>, + jwks_uri => <<"https://example.com/keys">>, + authorization_endpoint => <<"https://example.com/authorize">>, + scopes_supported => [<<"openid">>], + response_types_supported => [<<"code">>], + subject_types_supported => [<<"public">>], + id_token_signing_alg_values_supported => [<<"RS256">>] + }) + ), + JwksBody = iolist_to_binary(json:encode(#{keys => []})), + HttpFun = + fun + ( + get, + {"https://example.com/.well-known/openid-configuration", []}, + _HttpOpts, + _Opts, + _Profile + ) -> + {ok, { + {"HTTP/1.1", 200, "OK"}, [{"content-type", "application/json"}], DiscoveryBody + }}; + (get, {<<"https://example.com/keys">>, []}, _HttpOpts, _Opts, _Profile) -> + {ok, {{"HTTP/1.1", 200, "OK"}, [{"content-type", "application/json"}], JwksBody}} + end, + ok = meck:new(httpc, [no_link]), + try + ok = meck:expect(httpc, request, HttpFun), + TestFun() + after + meck:unload(httpc) + end. + apply_profiles_fapi2_security_profile_test() -> ClientContext0 = client_context_fixture(), Opts0 = #{ diff --git a/test/oidcc_jwt_util_test.erl b/test/oidcc_jwt_util_test.erl index 4a14678c..aac88fdf 100644 --- a/test/oidcc_jwt_util_test.erl +++ b/test/oidcc_jwt_util_test.erl @@ -4,6 +4,7 @@ -module(oidcc_jwt_util_test). -include_lib("eunit/include/eunit.hrl"). +-include_lib("jose/include/jose_jwk.hrl"). verify_claims_test() -> % Test exact match claims @@ -95,3 +96,76 @@ verify_claims_test() -> ), ok. + +verify_signature_key_set_kid_test() -> + Key1 = key_with_kid(<<"kid-1">>), + Key2 = key_with_kid(<<"kid-2">>), + OtherKey = jose_jwk:generate_key({ec, <<"P-256">>}), + KeySet = #jose_jwk{keys = {jose_jwk_set, [Key1, Key2]}}, + Algs = [<<"ES256">>], + + ?assertMatch( + {ok, _}, + oidcc_jwt_util:verify_signature(sign_with_kid(Key2, <<"kid-2">>), Algs, KeySet) + ), + ?assertEqual( + {error, no_matching_key}, + oidcc_jwt_util:verify_signature(sign_with_kid(OtherKey, <<"kid-1">>), Algs, KeySet) + ), + ?assertEqual( + {error, no_matching_key}, + oidcc_jwt_util:verify_signature(sign_with_kid(OtherKey, <<"kid-2">>), Algs, KeySet) + ), + ?assertEqual( + {error, {no_matching_key_with_kid, <<"kid-3">>}}, + oidcc_jwt_util:verify_signature(sign_with_kid(OtherKey, <<"kid-3">>), Algs, KeySet) + ), + + MixedKeySet = #jose_jwk{ + keys = {jose_jwk_set, [jose_jwk:generate_key({ec, <<"P-256">>}), Key1]} + }, + ?assertEqual( + {error, {no_matching_key_with_kid, <<"kid-3">>}}, + oidcc_jwt_util:verify_signature(sign_with_kid(OtherKey, <<"kid-3">>), Algs, MixedKeySet) + ). + +key_with_kid(Kid) -> + key_with_kid({ec, <<"P-256">>}, Kid). + +key_with_kid(KeyType, Kid) -> + jose_jwk:merge(jose_jwk:generate_key(KeyType), #{<<"kid">> => Kid}). + +sign_with_kid(Key, Kid) -> + Jws = #{<<"alg">> => <<"ES256">>, <<"kid">> => Kid}, + {_Jws, Token} = jose_jws:compact(jose_jwt:sign(Key, Jws, jose_jwt:from(#{}))), + Token. + +decrypt_and_verify_key_set_kid_test() -> + Key1 = key_with_kid({rsa, 2048}, <<"kid-1">>), + Key2 = key_with_kid({rsa, 2048}, <<"kid-2">>), + OtherKey = jose_jwk:generate_key({rsa, 2048}), + KeySet = #jose_jwk{keys = {jose_jwk_set, [Key1, Key2]}}, + DecryptAndVerify = fun(Token) -> + oidcc_jwt_util:decrypt_and_verify( + Token, KeySet, [<<"RS256">>], [<<"RSA-OAEP">>], [<<"A256GCM">>] + ) + end, + + ?assertMatch({ok, _}, DecryptAndVerify(encrypt_with_kid(Key2, <<"kid-2">>))), + ?assertEqual( + {error, no_matching_key}, + DecryptAndVerify(encrypt_with_kid(OtherKey, <<"kid-1">>)) + ), + ?assertEqual( + {error, no_matching_key}, + DecryptAndVerify(encrypt_with_kid(OtherKey, <<"kid-2">>)) + ), + ?assertEqual( + {error, {no_matching_key_with_kid, <<"kid-3">>}}, + DecryptAndVerify(encrypt_with_kid(OtherKey, <<"kid-3">>)) + ). + +encrypt_with_kid(Key, Kid) -> + Jwe = #{<<"alg">> => <<"RSA-OAEP">>, <<"enc">> => <<"A256GCM">>, <<"kid">> => Kid}, + {_Jwe, Token} = jose_jwe:compact(jose_jwk:block_encrypt(<<"{}">>, Jwe, Key)), + Token. diff --git a/test/oidcc_provider_configuration_worker_test.erl b/test/oidcc_provider_configuration_worker_test.erl index 8e8fcadc..ac61c66f 100644 --- a/test/oidcc_provider_configuration_worker_test.erl +++ b/test/oidcc_provider_configuration_worker_test.erl @@ -366,6 +366,137 @@ refreshes_jwks_for_unknown_kid_without_jwks_test() -> ) end). +refreshes_jwks_for_unknown_kid_only_test() -> + JwksRequests = atomics:new(1, []), + HttpFun = jwks_http_fun(JwksRequests, [<<"kid-1">>, <<"kid-2">>]), + + with_httpc_mock(HttpFun, fun() -> + with_live_provider_worker( + #{issuer => <<"https://example.com">>}, + fun(Pid) -> + ?assertMatch( + #jose_jwk{keys = {jose_jwk_set, [_, _]}}, + wait_until(fun() -> + oidcc_provider_configuration_worker:get_jwks(Pid) + end) + ), + ?assertEqual(1, atomics:get(JwksRequests, 1)), + + ok = oidcc_provider_configuration_worker:refresh_jwks_for_unknown_kid( + Pid, <<"kid-1">> + ), + ok = oidcc_provider_configuration_worker:refresh_jwks_for_unknown_kid( + Pid, <<"kid-2">> + ), + ?assertEqual(1, atomics:get(JwksRequests, 1)), + + ok = oidcc_provider_configuration_worker:refresh_jwks_for_unknown_kid( + Pid, <<"kid-3">> + ), + ?assertEqual(2, atomics:get(JwksRequests, 1)) + end + ) + end). + +refreshes_jwks_for_unknown_kid_with_key_without_kid_test() -> + JwksRequests = atomics:new(1, []), + HttpFun = jwks_http_fun(JwksRequests, [undefined, <<"kid-1">>]), + + with_httpc_mock(HttpFun, fun() -> + with_live_provider_worker( + #{issuer => <<"https://example.com">>}, + fun(Pid) -> + ?assertMatch( + #jose_jwk{keys = {jose_jwk_set, [_, _]}}, + wait_until(fun() -> + oidcc_provider_configuration_worker:get_jwks(Pid) + end) + ), + ?assertEqual(1, atomics:get(JwksRequests, 1)), + + ok = oidcc_provider_configuration_worker:refresh_jwks_for_unknown_kid( + Pid, <<"kid-1">> + ), + ?assertEqual(1, atomics:get(JwksRequests, 1)), + + ok = oidcc_provider_configuration_worker:refresh_jwks_for_unknown_kid( + Pid, <<"kid-2">> + ), + ?assertEqual(2, atomics:get(JwksRequests, 1)) + end + ) + end). + +refreshes_jwks_once_for_concurrent_unknown_kids_test() -> + JwksRequests = atomics:new(1, []), + JwksFun = jwks_http_fun(JwksRequests, [<<"kid-1">>]), + HttpFun = + fun + (get, {<<"https://example.com/keys">>, []} = Request, HttpOpts, Opts, Profile) -> + timer:sleep(200), + JwksFun(get, Request, HttpOpts, Opts, Profile); + (Method, Request, HttpOpts, Opts, Profile) -> + JwksFun(Method, Request, HttpOpts, Opts, Profile) + end, + + with_httpc_mock(HttpFun, fun() -> + with_live_provider_worker( + #{issuer => <<"https://example.com">>}, + fun(Pid) -> + ?assertMatch( + #jose_jwk{}, + wait_until(fun() -> + oidcc_provider_configuration_worker:get_jwks(Pid) + end) + ), + ?assertEqual(1, atomics:get(JwksRequests, 1)), + + TestPid = self(), + Refs = [ + spawn_unknown_kid_refresh(TestPid, Pid, integer_to_binary(N)) + || N <- lists:seq(1, 20) + ], + [ + receive + {refreshed, Ref} -> ok + after 5_000 -> + ct:fail(timeout_concurrent_refresh) + end + || Ref <- Refs + ], + + ?assertEqual(2, atomics:get(JwksRequests, 1)) + end + ) + end). + +spawn_unknown_kid_refresh(TestPid, Pid, Kid) -> + Ref = make_ref(), + spawn_link(fun() -> + ok = oidcc_provider_configuration_worker:refresh_jwks_for_unknown_kid(Pid, Kid), + TestPid ! {refreshed, Ref} + end), + Ref. + +jwks_http_fun(JwksRequests, Kids) -> + Keys = [public_key_map(Kid) || Kid <- Kids], + JwksBody = iolist_to_binary(json:encode(#{keys => Keys})), + DiscoveryFun = jwks_failing_http_fun(fun() -> true end), + fun + (get, {<<"https://example.com/keys">>, []}, _HttpOpts, _Opts, _Profile) -> + atomics:add(JwksRequests, 1, 1), + {ok, {{"HTTP/1.1", 200, "OK"}, [{"content-type", "application/json"}], JwksBody}}; + (Method, Request, HttpOpts, Opts, Profile) -> + DiscoveryFun(Method, Request, HttpOpts, Opts, Profile) + end. + +public_key_map(Kid) -> + {_Kty, KeyMap} = jose_jwk:to_public_map(jose_jwk:generate_key({ec, <<"P-256">>})), + case Kid of + undefined -> KeyMap; + _ -> KeyMap#{<<"kid">> => Kid} + end. + jwks_failing_http_fun(JwksAvailable) -> fun (