Refactoring

- Use rabbit_oauth2 prefix for modules which do not have it
- Ensure most lines stick to 80 column
This commit is contained in:
Marcial Rosales 2024-10-04 12:56:21 +02:00
parent ea6f194eb3
commit d25e0f8e88
17 changed files with 639 additions and 454 deletions

View File

@ -13,11 +13,11 @@ def all_beam_files(name = "all_beam_files"):
"src/Elixir.RabbitMQ.CLI.Ctl.Commands.AddUaaKeyCommand.erl",
"src/rabbit_auth_backend_oauth2.erl",
"src/rabbit_auth_backend_oauth2_app.erl",
"src/oauth_provider.erl",
"src/resource_server.erl",
"src/rar.erl",
"src/keycloak.erl",
"src/oauth2_schema.erl",
"src/rabbit_oauth2_provider.erl",
"src/rabbit_oauth2_resource_server.erl",
"src/rabbit_oauth2_rar.erl",
"src/rabbit_oauth2_keycloak.erl",
"src/rabbit_oauth2_schema.erl",
"src/rabbit_oauth2_scope.erl",
"src/uaa_jwks.erl",
"src/uaa_jwt.erl",
@ -51,11 +51,11 @@ def all_test_beam_files(name = "all_test_beam_files"):
"src/Elixir.RabbitMQ.CLI.Ctl.Commands.AddUaaKeyCommand.erl",
"src/rabbit_auth_backend_oauth2.erl",
"src/rabbit_auth_backend_oauth2_app.erl",
"src/resource_server.erl",
"src/oauth_provider.erl",
"src/oauth2_schema.erl",
"src/rar.erl",
"src/keycloak.erl",
"src/rabbit_oauth2_resource_server.erl",
"src/rabbit_oauth2_provider.erl",
"src/rabbit_oauth2_schema.erl",
"src/rabbit_oauth2_rar.erl",
"src/rabbit_oauth2_keycloak.erl",
"src/rabbit_oauth2_scope.erl",
"src/uaa_jwks.erl",
"src/uaa_jwt.erl",
@ -101,11 +101,11 @@ def all_srcs(name = "all_srcs"):
"src/Elixir.RabbitMQ.CLI.Ctl.Commands.AddUaaKeyCommand.erl",
"src/rabbit_auth_backend_oauth2.erl",
"src/rabbit_auth_backend_oauth2_app.erl",
"src/oauth_provider.erl",
"src/resource_server.erl",
"src/oauth2_schema.erl",
"src/rar.erl",
"src/keycloak.erl",
"src/rabbit_oauth2_provider.erl",
"src/rabbit_oauth2_resource_server.erl",
"src/rabbit_oauth2_schema.erl",
"src/rabbit_oauth2_rar.erl",
"src/rabbit_oauth2_keycloak.erl",
"src/rabbit_oauth2_scope.erl",
"src/uaa_jwks.erl",
"src/uaa_jwt.erl",
@ -169,10 +169,10 @@ def test_suite_beam_files(name = "test_suite_beam_files"):
deps = ["//deps/rabbit_common:erlang_app"],
)
erlang_bytecode(
name = "oauth2_schema_SUITE_beam_files",
name = "rabbit_oauth2_schema_SUITE_beam_files",
testonly = True,
srcs = ["test/oauth2_schema_SUITE.erl"],
outs = ["test/oauth2_schema_SUITE.beam"],
srcs = ["test/rabbit_oauth2_schema_SUITE.erl"],
outs = ["test/rabbit_oauth2_schema_SUITE.beam"],
app_name = "rabbitmq_auth_backend_oauth2",
erlc_opts = "//:test_erlc_opts",
deps = ["//deps/rabbit_common:erlang_app"],
@ -248,20 +248,20 @@ def test_suite_beam_files(name = "test_suite_beam_files"):
erlc_opts = "//:test_erlc_opts",
)
erlang_bytecode(
name = "oauth_provider_SUITE_beam_files",
name = "rabbit_oauth2_provider_SUITE_beam_files",
testonly = True,
srcs = ["test/oauth_provider_SUITE.erl"],
outs = ["test/oauth_provider_SUITE.beam"],
srcs = ["test/rabbit_oauth2_provider_SUITE.erl"],
outs = ["test/rabbit_oauth2_provider_SUITE.beam"],
hdrs = ["include/oauth2.hrl"],
app_name = "rabbitmq_auth_backend_oauth2",
erlc_opts = "//:test_erlc_opts",
deps = ["//deps/oauth2_client:erlang_app"],
)
erlang_bytecode(
name = "resource_server_SUITE_beam_files",
name = "rabbit_oauth2_resource_server_SUITE_beam_files",
testonly = True,
srcs = ["test/resource_server_SUITE.erl"],
outs = ["test/resource_server_SUITE.beam"],
srcs = ["test/rabbit_oauth2_resource_server_SUITE.erl"],
outs = ["test/rabbit_oauth2_resource_server_SUITE.beam"],
hdrs = ["include/oauth2.hrl"],
app_name = "rabbitmq_auth_backend_oauth2",
erlc_opts = "//:test_erlc_opts",

View File

@ -130,7 +130,7 @@
{translation,
"rabbitmq_auth_backend_oauth2.key_config.signing_keys",
fun(Conf) ->
oauth2_schema:translate_signing_keys(Conf)
rabbit_oauth2_schema:translate_signing_keys(Conf)
end}.
{mapping,
@ -170,7 +170,7 @@
{translation, "rabbitmq_auth_backend_oauth2.discovery_endpoint_params",
fun(Conf) ->
oauth2_schema:translate_endpoint_params("discovery_endpoint_params", Conf)
rabbit_oauth2_schema:translate_endpoint_params("discovery_endpoint_params", Conf)
end}.
{mapping,
@ -190,7 +190,7 @@
{translation, "rabbitmq_auth_backend_oauth2.oauth_providers",
fun(Conf) ->
oauth2_schema:translate_oauth_providers(Conf)
rabbit_oauth2_schema:translate_oauth_providers(Conf)
end}.
{mapping,
@ -327,7 +327,7 @@
{translation, "rabbitmq_auth_backend_oauth2.oauth_providers",
fun(Conf) ->
oauth2_schema:translate_oauth_providers(Conf)
rabbit_oauth2_schema:translate_oauth_providers(Conf)
end}.
{mapping,
@ -369,5 +369,5 @@
{translation, "rabbitmq_auth_backend_oauth2.resource_servers",
fun(Conf) ->
oauth2_schema:translate_resource_servers(Conf)
rabbit_oauth2_schema:translate_resource_servers(Conf)
end}.

View File

@ -28,8 +28,8 @@
get_scope/1, set_scope/2,
resolve_resource_server/1]).
-import(keycloak, [has_keycloak_scopes/1, extract_scopes_from_keycloak_format/1]).
-import(rar, [extract_scopes_from_rich_auth_request/2, has_rich_auth_request_scopes/1]).
-import(rabbit_oauth2_keycloak, [has_keycloak_scopes/1, extract_scopes_from_keycloak_format/1]).
-import(rabbit_oauth2_rar, [extract_scopes_from_rich_auth_request/2, has_rich_auth_request_scopes/1]).
-import(rabbit_oauth2_scope, [filter_matching_scope_prefix_and_drop_it/2]).

View File

@ -5,7 +5,7 @@
%% Copyright (c) 2007-2024 Broadcom. All Rights Reserved. The term Broadcom refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
-module(keycloak).
-module(rabbit_oauth2_keycloak).
-include("oauth2.hrl").

View File

@ -5,7 +5,7 @@
%% Copyright (c) 2007-2024 Broadcom. All Rights Reserved. The term Broadcom refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
-module(oauth_provider).
-module(rabbit_oauth2_provider).
-include("oauth2.hrl").

View File

@ -6,7 +6,7 @@
%%
% Rich Authorization Request
-module(rar).
-module(rabbit_oauth2_rar).
-include("oauth2.hrl").
-import(uaa_jwt, [get_scope/1, set_scope/2]).

View File

@ -5,7 +5,7 @@
%% Copyright (c) 2007-2024 Broadcom. All Rights Reserved. The term Broadcom refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
-module(resource_server).
-module(rabbit_oauth2_resource_server).
-include("oauth2.hrl").

View File

@ -5,7 +5,7 @@
%% Copyright (c) 2007-2024 Broadcom. All Rights Reserved. The term Broadcom refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
-module(oauth2_schema).
-module(rabbit_oauth2_schema).
-export([
@ -20,7 +20,8 @@ extract_value({_Name,V}) -> V.
-spec translate_resource_servers([{list(), binary()}]) -> map().
translate_resource_servers(Conf) ->
Settings = cuttlefish_variable:filter_by_prefix("auth_oauth2.resource_servers", Conf),
Settings = cuttlefish_variable:filter_by_prefix("auth_oauth2.resource_servers",
Conf),
Map = merge_list_of_maps([
extract_resource_server_properties(Settings),
extract_resource_server_preferred_username_claims(Settings)
@ -31,16 +32,19 @@ translate_resource_servers(Conf) ->
_ -> V
end end, Map),
ResourceServers = maps:values(Map0),
lists:foldl(fun(Elem,AccMap)-> maps:put(proplists:get_value(id, Elem), Elem, AccMap) end, #{},
lists:foldl(fun(Elem,AccMap) ->
maps:put(proplists:get_value(id, Elem), Elem, AccMap) end, #{},
ResourceServers).
-spec translate_oauth_providers([{list(), binary()}]) -> map().
translate_oauth_providers(Conf) ->
Settings = cuttlefish_variable:filter_by_prefix("auth_oauth2.oauth_providers", Conf),
Settings = cuttlefish_variable:filter_by_prefix("auth_oauth2.oauth_providers",
Conf),
merge_list_of_maps([
extract_oauth_providers_properties(Settings),
extract_oauth_providers_endpoint_params(discovery_endpoint_params, Settings),
extract_oauth_providers_endpoint_params(discovery_endpoint_params,
Settings),
extract_oauth_providers_algorithm(Settings),
extract_oauth_providers_https(Settings),
extract_oauth_providers_signing_keys(Settings)
@ -48,8 +52,10 @@ translate_oauth_providers(Conf) ->
-spec translate_signing_keys([{list(), binary()}]) -> map().
translate_signing_keys(Conf) ->
Settings = cuttlefish_variable:filter_by_prefix("auth_oauth2.signing_keys", Conf),
ListOfKidPath = lists:map(fun({Id, Path}) -> {list_to_binary(lists:last(Id)), Path} end, Settings),
Settings = cuttlefish_variable:filter_by_prefix("auth_oauth2.signing_keys",
Conf),
ListOfKidPath = lists:map(fun({Id, Path}) -> {
list_to_binary(lists:last(Id)), Path} end, Settings),
translate_list_of_signing_keys(ListOfKidPath).
-spec translate_list_of_signing_keys([{list(), list()}]) -> map().
@ -61,15 +67,20 @@ translate_list_of_signing_keys(ListOfKidPath) ->
string:trim(Bin, trailing, "\n");
_Error ->
%% this throws and makes Cuttlefish treak the key as invalid
cuttlefish:invalid("file does not exist or cannot be read by the node")
cuttlefish:invalid("file does not exist or cannot be " ++
"read by the node")
end
end,
maps:map(fun(_K, Path) -> {pem, TryReadingFileFun(Path)} end, maps:from_list(ListOfKidPath)).
maps:map(fun(_K, Path) -> {pem, TryReadingFileFun(Path)} end,
maps:from_list(ListOfKidPath)).
-spec translate_endpoint_params(list(), [{list(), binary()}]) -> [{binary(), binary()}].
-spec translate_endpoint_params(list(), [{list(), binary()}]) ->
[{binary(), binary()}].
translate_endpoint_params(Variable, Conf) ->
Params0 = cuttlefish_variable:filter_by_prefix("auth_oauth2." ++ Variable, Conf),
[{list_to_binary(Param), list_to_binary(V)} || {["auth_oauth2", _, Param], V} <- Params0].
Params0 = cuttlefish_variable:filter_by_prefix("auth_oauth2." ++ Variable,
Conf),
[{list_to_binary(Param), list_to_binary(V)} || {["auth_oauth2", _, Param], V}
<- Params0].
validator_file_exists(Attr, Filename) ->
case file:read_file(Filename) of
@ -78,7 +89,8 @@ validator_file_exists(Attr, Filename) ->
_Error ->
%% this throws and makes Cuttlefish treak the key as invalid
cuttlefish:invalid(io_lib:format(
"Invalid attribute (~p) value: file ~p does not exist or cannot be read by the node", [Attr, Filename]))
"Invalid attribute (~p) value: file ~p does not exist or " ++
"cannot be read by the node", [Attr, Filename]))
end.
validator_uri(Attr, Uri) when is_binary(Uri) ->
@ -99,7 +111,8 @@ validator_https_uri(Attr, Uri) when is_list(Uri) ->
true -> Uri;
false ->
cuttlefish:invalid(io_lib:format(
"Invalid attribute (~p) value: uri ~p must be a valid https uri", [Attr, Uri]))
"Invalid attribute (~p) value: uri ~p must be a valid https uri",
[Attr, Uri]))
end.
merge_list_of_maps(ListOfMaps) ->
@ -110,7 +123,8 @@ extract_oauth_providers_properties(Settings) ->
KeyFun = fun extract_key_as_binary/1,
ValueFun = fun extract_value/1,
OAuthProviders = [{Name, mapOauthProviderProperty({list_to_atom(Key), list_to_binary(V)})}
OAuthProviders = [
{Name, mapOauthProviderProperty({list_to_atom(Key), list_to_binary(V)})}
|| {["auth_oauth2", "oauth_providers", Name, Key], V} <- Settings],
maps:groups_from_list(KeyFun, ValueFun, OAuthProviders).
@ -133,7 +147,8 @@ mapOauthProviderProperty({Key, Value}) ->
discovery_endpoint_path -> validator_uri(Key, Value);
discovery_endpoint_params ->
cuttlefish:invalid(io_lib:format(
"Invalid attribute (~p) value: should be a map of Key,Value pairs", [Key]));
"Invalid attribute (~p) value: should be a map of Key,Value pairs",
[Key]));
_ -> Value
end}.
@ -144,7 +159,8 @@ extract_oauth_providers_https(Settings) ->
{["auth_oauth2","oauth_providers", Name, "https", Key], V} <- Settings ],
maps:map(fun(_K,V)-> [{https, V}] end,
maps:groups_from_list(ExtractProviderNameFun, fun({_, V}) -> V end, AttributesPerProvider)).
maps:groups_from_list(ExtractProviderNameFun, fun({_, V}) -> V end,
AttributesPerProvider)).
mapHttpProperty({Key, Value}) ->
{Key, case Key of
@ -156,8 +172,10 @@ extract_oauth_providers_algorithm(Settings) ->
KeyFun = fun extract_key_as_binary/1,
IndexedAlgorithms = [{Name, {Index, list_to_binary(V)}} ||
{["auth_oauth2","oauth_providers", Name, "algorithms", Index], V} <- Settings ],
SortedAlgorithms = lists:sort(fun({_,{AI,_}},{_,{BI,_}}) -> AI < BI end, IndexedAlgorithms),
{["auth_oauth2","oauth_providers", Name, "algorithms", Index], V}
<- Settings ],
SortedAlgorithms = lists:sort(fun({_,{AI,_}},{_,{BI,_}}) -> AI < BI end,
IndexedAlgorithms),
Algorithms = [{Name, V} || {Name, {_I, V}} <- SortedAlgorithms],
maps:map(fun(_K,V)-> [{algorithms, V}] end,
maps:groups_from_list(KeyFun, fun({_, V}) -> V end, Algorithms)).
@ -166,8 +184,10 @@ extract_resource_server_preferred_username_claims(Settings) ->
KeyFun = fun extract_key_as_binary/1,
IndexedClaims = [{Name, {Index, list_to_binary(V)}} ||
{["auth_oauth2","resource_servers", Name, "preferred_username_claims", Index], V} <- Settings ],
SortedClaims = lists:sort(fun({_,{AI,_}},{_,{BI,_}}) -> AI < BI end, IndexedClaims),
{["auth_oauth2","resource_servers", Name, "preferred_username_claims",
Index], V} <- Settings ],
SortedClaims = lists:sort(fun({_,{AI,_}},{_,{BI,_}}) -> AI < BI end,
IndexedClaims),
Claims = [{Name, V} || {Name, {_I, V}} <- SortedClaims],
maps:map(fun(_K,V)-> [{preferred_username_claims, V}] end,
maps:groups_from_list(KeyFun, fun({_, V}) -> V end, Claims)).
@ -185,6 +205,7 @@ extract_oauth_providers_signing_keys(Settings) ->
KeyFun = fun extract_key_as_binary/1,
IndexedSigningKeys = [{Name, {list_to_binary(Kid), list_to_binary(V)}} ||
{["auth_oauth2","oauth_providers", Name, "signing_keys", Kid], V} <- Settings ],
{["auth_oauth2","oauth_providers", Name, "signing_keys", Kid], V}
<- Settings ],
maps:map(fun(_K,V)-> [{signing_keys, translate_list_of_signing_keys(V)}] end,
maps:groups_from_list(KeyFun, fun({_, V}) -> V end, IndexedSigningKeys)).

View File

@ -23,9 +23,9 @@
format_ssl_options/1,
format_oauth_provider_id/1,
get_oauth_provider/2]).
-import(resource_server, [
-import(rabbit_oauth2_resource_server, [
resolve_resource_server_from_audience/1]).
-import(oauth_provider, [
-import(rabbit_oauth2_provider, [
add_signing_key/2, get_signing_key/2,
get_internal_oauth_provider/1,
replace_signing_keys/2]).

View File

@ -13,9 +13,20 @@
-include_lib("amqp_client/include/amqp_client.hrl").
-include_lib("eunit/include/eunit.hrl").
-import(rabbit_ct_client_helpers, [close_connection/1, close_channel/1,
open_unmanaged_connection/4, open_unmanaged_connection/5,
close_connection_and_channel/2]).
-import(rabbit_ct_client_helpers, [
close_connection/1,
close_channel/1,
open_unmanaged_connection/4,
open_unmanaged_connection/5,
close_connection_and_channel/2
]).
-import(rabbit_ct_helpers, [
set_config/2,
get_config/2, get_config/3
]).
-import(rabbit_ct_broker_helpers, [
rpc/5
]).
-import(rabbit_mgmt_test_util, [amqp_port/1]).
all() ->
@ -159,21 +170,23 @@ end_per_suite(Config) ->
] ++ rabbit_ct_broker_helpers:teardown_steps()).
init_per_group(no_peer_verification, Config) ->
KeyConfig = rabbit_ct_helpers:set_config(?config(key_config, Config), [{jwks_url, ?config(non_strict_jwks_url, Config)}, {peer_verification, verify_none}]),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env, [rabbitmq_auth_backend_oauth2, key_config, KeyConfig]),
rabbit_ct_helpers:set_config(Config, {key_config, KeyConfig});
KeyConfig = set_config(?config(key_config, Config), [
{jwks_url, ?config(non_strict_jwks_url, Config)},
{peer_verification, verify_none}
]),
ok = rpc_set_env(Config,key_config, KeyConfig),
set_config(Config, {key_config, KeyConfig});
init_per_group(without_kid, Config) ->
rabbit_ct_helpers:set_config(Config, [{include_kid, false}]);
set_config(Config, [{include_kid, false}]);
init_per_group(with_resource_servers_rabbitmq1_with_oauth_provider_A, Config) ->
ResourceServersConfig0 = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, resource_servers, #{}]),
Resource0 = maps:get(<<"rabbitmq1">>, ResourceServersConfig0, [{id, <<"rabbitmq1">>}]),
ResourceServersConfig1 = maps:put(<<"rabbitmq1">>, [{oauth_provider_id, <<"A">>} | Resource0], ResourceServersConfig0),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, resource_servers, ResourceServersConfig1]);
ResourceServersConfig0 = rpc_get_env(Config, resource_servers, #{}),
Resource0 = maps:get(<<"rabbitmq1">>,
ResourceServersConfig0, [{id, <<"rabbitmq1">>}]),
ResourceServersConfig1 = maps:put(<<"rabbitmq1">>,
[{oauth_provider_id, <<"A">>} | Resource0], ResourceServersConfig0),
ok = rpc_set_env(Config, resource_servers, ResourceServersConfig1);
init_per_group(with_oauth_providers_A_B_and_C, Config) ->
OAuthProviders = #{
@ -190,58 +203,50 @@ init_per_group(with_oauth_providers_A_B_and_C, Config) ->
{https, [{verify, verify_none}]}
]
},
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, oauth_providers, OAuthProviders]),
ok = rpc_set_env(Config, oauth_providers, OAuthProviders),
Config;
init_per_group(with_default_oauth_provider_B, Config) ->
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, default_oauth_provider, <<"B">>]);
ok = rpc_set_env(Config, default_oauth_provider, <<"B">>);
init_per_group(with_oauth_providers_A_with_default_key, Config) ->
{ok, OAuthProviders0} = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, oauth_providers]),
{ok, OAuthProviders0} = rpc_get_env(Config, oauth_providers),
OAuthProvider = maps:get(<<"A">>, OAuthProviders0, []),
OAuthProviders1 = maps:put(<<"A">>, [
{default_key, ?UTIL_MOD:token_key(?config(fixture_jwksA, Config))} | OAuthProvider],
OAuthProviders0),
{default_key, ?UTIL_MOD:token_key(?config(fixture_jwksA, Config))}
| OAuthProvider], OAuthProviders0),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, oauth_providers, OAuthProviders1]),
ok = rpc_set_env(Config, oauth_providers, OAuthProviders1),
Config;
init_per_group(with_oauth_provider_A_with_jwks_with_one_signing_key, Config) ->
{ok, OAuthProviders0} = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, oauth_providers]),
{ok, OAuthProviders0} = rpc_get_env(Config, oauth_providers),
OAuthProvider = maps:get(<<"A">>, OAuthProviders0, []),
OAuthProviders1 = maps:put(<<"A">>, [{jwks_uri, strict_jwks_url(Config, "/jwksA")} | OAuthProvider],
OAuthProviders1 = maps:put(<<"A">>, [
{jwks_uri, strict_jwks_url(Config, "/jwksA")} | OAuthProvider],
OAuthProviders0),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, oauth_providers, OAuthProviders1]),
ok = rpc_set_env(Config, oauth_providers, OAuthProviders1),
Config;
init_per_group(with_resource_servers_rabbitmq2, Config) ->
ResourceServersConfig0 = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, resource_servers, #{}]),
Resource0 = maps:get(<<"rabbitmq2">>, ResourceServersConfig0, [{id, <<"rabbitmq2">>}]),
ResourceServersConfig1 = maps:put(<<"rabbitmq2">>, Resource0, ResourceServersConfig0),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, resource_servers, ResourceServersConfig1]);
ResourceServersConfig0 = rpc_get_env(Config, resource_servers, #{}),
Resource0 = maps:get(<<"rabbitmq2">>, ResourceServersConfig0,
[{id, <<"rabbitmq2">>}]),
ResourceServersConfig1 = maps:put(<<"rabbitmq2">>, Resource0,
ResourceServersConfig0),
ok = rpc_set_env(Config, resource_servers, ResourceServersConfig1);
init_per_group(with_oauth_providers_B_with_default_key_static_key, Config) ->
{ok, OAuthProviders0} = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, oauth_providers]),
{ok, OAuthProviders0} = rpc_get_env(Config, oauth_providers),
OAuthProvider = maps:get(<<"B">>, OAuthProviders0, []),
OAuthProviders1 = maps:put(<<"B">>, [
{default_key, ?UTIL_MOD:token_key(?config(fixture_staticB, Config))} |
proplists:delete(default_key, OAuthProvider)],
OAuthProviders0),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, oauth_providers, OAuthProviders1]),
ok = rpc_set_env(Config,oauth_providers, OAuthProviders1),
Config;
init_per_group(with_oauth_provider_C_with_two_static_keys, Config) ->
{ok, OAuthProviders0} = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, oauth_providers]),
{ok, OAuthProviders0} = rpc_get_env(Config, oauth_providers),
OAuthProvider = maps:get(<<"C">>, OAuthProviders0, []),
Jwks1 = ?config(fixture_staticC_1, Config),
Jwks2 = ?config(fixture_staticC_2, Config),
@ -249,16 +254,14 @@ init_per_group(with_oauth_provider_C_with_two_static_keys, Config) ->
?UTIL_MOD:token_key(Jwks1) => {json, Jwks1},
?UTIL_MOD:token_key(Jwks2) => {json, Jwks2}
},
OAuthProviders1 = maps:put(<<"C">>, [{signing_keys, SigningKeys} | OAuthProvider],
OAuthProviders0),
OAuthProviders1 = maps:put(<<"C">>, [
{signing_keys, SigningKeys} | OAuthProvider], OAuthProviders0),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, oauth_providers, OAuthProviders1]),
ok = rpc_set_env(Config, oauth_providers, OAuthProviders1),
Config;
init_per_group(with_root_oauth_provider_with_two_static_keys_and_one_jwks_key, Config) ->
KeyConfig = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, key_config, []]),
KeyConfig = rpc_get_env(Config, key_config, []),
Jwks1 = ?config(fixture_static_1, Config),
Jwks2 = ?config(fixture_static_2, Config),
SigningKeys = #{
@ -267,28 +270,25 @@ init_per_group(with_root_oauth_provider_with_two_static_keys_and_one_jwks_key, C
},
KeyConfig1 = [{signing_keys, SigningKeys},
{jwks_url, strict_jwks_url(Config, "/jwks")}| KeyConfig],
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, key_config, KeyConfig1]),
ok = rpc_set_env(Config, key_config, KeyConfig1),
Config;
init_per_group(with_root_oauth_provider_with_default_key_1, Config) ->
KeyConfig = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, key_config, []]),
KeyConfig1 = [{default_key, ?UTIL_MOD:token_key(?config(fixture_static_1, Config))} | KeyConfig],
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, key_config, KeyConfig1]),
KeyConfig = rpc_get_env(Config, key_config, []),
KeyConfig1 = [
{default_key, ?UTIL_MOD:token_key(?config(fixture_static_1, Config))}
| KeyConfig],
ok = rpc_set_env(Config, key_config, KeyConfig1),
Config;
init_per_group(with_root_oauth_provider_with_default_jwks_key, Config) ->
KeyConfig = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, key_config, []]),
KeyConfig1 = [{default_key, ?UTIL_MOD:token_key(?config(fixture_jwk, Config))} | KeyConfig],
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, key_config, KeyConfig1]),
KeyConfig = rpc_get_env(Config, key_config, []),
KeyConfig1 = [
{default_key, ?UTIL_MOD:token_key(?config(fixture_jwk, Config))}
| KeyConfig],
ok = rpc_set_env(Config, key_config, KeyConfig1),
Config;
init_per_group(with_oauth_provider_B_with_one_static_key_and_jwks_with_two_signing_keys, Config) ->
{ok, OAuthProviders0} = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, oauth_providers]),
{ok, OAuthProviders0} = rpc_get_env(Config, oauth_providers),
OAuthProvider = maps:get(<<"B">>, OAuthProviders0, []),
Jwks = ?config(fixture_staticB, Config),
SigningKeys = #{
@ -299,63 +299,55 @@ init_per_group(with_oauth_provider_B_with_one_static_key_and_jwks_with_two_signi
{jwks_uri, strict_jwks_url(Config, "/jwksB")} | OAuthProvider],
OAuthProviders0),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, oauth_providers, OAuthProviders1]),
ok = rpc_set_env(Config, oauth_providers, OAuthProviders1),
Config;
init_per_group(with_resource_servers_rabbitmq3_with_oauth_provider_C, Config) ->
ResourceServersConfig0 = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, resource_servers, #{}]),
ResourceServersConfig0 = rpc_get_env(Config, resource_servers, #{}),
Resource0 = maps:get(<<"rabbitmq3">>, ResourceServersConfig0, [
{id, <<"rabbitmq3">>},{oauth_provider_id, <<"C">>}]),
ResourceServersConfig1 = maps:put(<<"rabbitmq3">>, Resource0, ResourceServersConfig0),
ResourceServersConfig1 = maps:put(<<"rabbitmq3">>, Resource0,
ResourceServersConfig0),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, resource_servers, ResourceServersConfig1]);
ok = rpc_set_env(Config, resource_servers, ResourceServersConfig1);
init_per_group(with_oauth_providers_C_with_default_key_static_key_1, Config) ->
{ok, OAuthProviders0} = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, oauth_providers]),
{ok, OAuthProviders0} = rpc_get_env(Config, oauth_providers),
OAuthProvider = maps:get(<<"C">>, OAuthProviders0, []),
Jwks = ?config(fixture_staticC_1, Config),
OAuthProviders1 = maps:put(<<"C">>, [
{default_key, ?UTIL_MOD:token_key(Jwks)} | OAuthProvider],
OAuthProviders0),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, oauth_providers, OAuthProviders1]),
ok = rpc_set_env(Config, oauth_providers, OAuthProviders1),
Config;
init_per_group(_Group, Config) ->
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, resource_server_id, ?RESOURCE_SERVER_ID]),
ok = rpc_set_env(Config, resource_server_id, ?RESOURCE_SERVER_ID),
Config.
end_per_group(without_kid, Config) ->
rabbit_ct_helpers:delete_config(Config, include_kid);
end_per_group(no_peer_verification, Config) ->
KeyConfig = rabbit_ct_helpers:set_config(?config(key_config, Config), [{jwks_url, ?config(strict_jwks_url, Config)}, {peer_verification, verify_peer}]),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env, [rabbitmq_auth_backend_oauth2, key_config, KeyConfig]),
rabbit_ct_helpers:set_config(Config, {key_config, KeyConfig});
KeyConfig = set_config(?config(key_config, Config), [
{jwks_url, ?config(strict_jwks_url, Config)},
{peer_verification, verify_peer}]),
ok = rpc_set_env(Config, key_config, KeyConfig),
set_config(Config, {key_config, KeyConfig});
end_per_group(with_default_oauth_provider_B, Config) ->
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, unset_env,
[rabbitmq_auth_backend_oauth2, default_oauth_provider]);
ok = rpc_unset_env(Config, default_oauth_provider);
end_per_group(with_root_oauth_provider_with_default_key_1, Config) ->
KeyConfig = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, key_config, []]),
KeyConfig = rpc_get_env(Config, key_config, []),
KeyConfig1 = proplists:delete(default_key, KeyConfig),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, key_config, KeyConfig1]),
ok = rpc_set_env(Config, key_config, KeyConfig1),
Config;
end_per_group(with_root_oauth_provider_with_default_jwks_key, Config) ->
KeyConfig = rabbit_ct_broker_helpers:rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, key_config, []]),
KeyConfig = rpc_get_env(Config, key_config, []),
KeyConfig1 = proplists:delete(default_key, KeyConfig),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, key_config, KeyConfig1]),
ok = rpc_set_env(Config, key_config, KeyConfig1),
Config;
end_per_group(_Group, Config) ->
@ -363,44 +355,50 @@ end_per_group(_Group, Config) ->
add_vhosts(Config) ->
%% The broker is managed by {init,end}_per_testcase().
lists:foreach(fun(Value) -> rabbit_ct_broker_helpers:add_vhost(Config, Value) end,
[<<"vhost1">>, <<"vhost2">>, <<"vhost3">>, <<"vhost4">>]).
lists:foreach(fun(Value) ->
rabbit_ct_broker_helpers:add_vhost(Config, Value) end,
[<<"vhost1">>, <<"vhost2">>, <<"vhost3">>, <<"vhost4">>]).
%rabbit_ct_helpers:set_config(Config, []).
delete_vhosts(Config) ->
%% The broker is managed by {init,end}_per_testcase().
lists:foreach(fun(Value) -> rabbit_ct_broker_helpers:delete_vhost(Config, Value) end,
[<<"vhost1">>, <<"vhost2">>, <<"vhost3">>, <<"vhost4">>]).
lists:foreach(fun(Value) ->
rabbit_ct_broker_helpers:delete_vhost(Config, Value) end,
[<<"vhost1">>, <<"vhost2">>, <<"vhost3">>, <<"vhost4">>]).
init_per_testcase(Testcase, Config) when Testcase =:= test_successful_connection_with_a_full_permission_token_and_explicitly_configured_vhost orelse
Testcase =:= test_successful_token_refresh ->
init_per_testcase(Testcase, Config) when
Testcase =:= test_successful_connection_with_a_full_permission_token_and_explicitly_configured_vhost orelse
Testcase =:= test_successful_token_refresh ->
rabbit_ct_broker_helpers:add_vhost(Config, <<"vhost1">>),
rabbit_ct_helpers:testcase_started(Config, Testcase),
Config;
init_per_testcase(Testcase, Config) when Testcase =:= test_failed_token_refresh_case1 orelse
Testcase =:= test_failed_token_refresh_case2 ->
init_per_testcase(Testcase, Config) when
Testcase =:= test_failed_token_refresh_case1 orelse
Testcase =:= test_failed_token_refresh_case2 ->
rabbit_ct_broker_helpers:add_vhost(Config, <<"vhost4">>),
rabbit_ct_helpers:testcase_started(Config, Testcase),
Config;
init_per_testcase(Testcase, Config) when Testcase =:= test_successful_connection_with_complex_claim_as_a_map orelse
Testcase =:= test_successful_connection_with_complex_claim_as_a_list orelse
Testcase =:= test_successful_connection_with_complex_claim_as_a_binary ->
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, extra_scopes_source, ?EXTRA_SCOPES_SOURCE]),
init_per_testcase(Testcase, Config) when
Testcase =:= test_successful_connection_with_complex_claim_as_a_map orelse
Testcase =:= test_successful_connection_with_complex_claim_as_a_list orelse
Testcase =:= test_successful_connection_with_complex_claim_as_a_binary ->
ok = rpc_set_env(Config, extra_scopes_source, ?EXTRA_SCOPES_SOURCE),
rabbit_ct_helpers:testcase_started(Config, Testcase),
Config;
init_per_testcase(Testcase, Config) when Testcase =:= test_successful_connection_with_algorithm_restriction ->
init_per_testcase(Testcase, Config) when
Testcase =:= test_successful_connection_with_algorithm_restriction ->
KeyConfig = ?config(key_config, Config),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env, [rabbitmq_auth_backend_oauth2, key_config, [{algorithms, [<<"HS256">>]} | KeyConfig]]),
ok = rpc_set_env(Config, key_config, [{algorithms, [<<"HS256">>]} | KeyConfig]),
rabbit_ct_helpers:testcase_started(Config, Testcase),
Config;
init_per_testcase(Testcase, Config) when Testcase =:= test_failed_connection_with_algorithm_restriction ->
init_per_testcase(Testcase, Config) when
Testcase =:= test_failed_connection_with_algorithm_restriction ->
KeyConfig = ?config(key_config, Config),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env, [rabbitmq_auth_backend_oauth2, key_config, [{algorithms, [<<"RS256">>]} | KeyConfig]]),
ok = rpc_set_env(Config, key_config, [{algorithms, [<<"RS256">>]} | KeyConfig]),
rabbit_ct_helpers:testcase_started(Config, Testcase),
Config;
@ -408,25 +406,28 @@ init_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_started(Config, Testcase),
Config.
end_per_testcase(Testcase, Config) when Testcase =:= test_failed_token_refresh_case1 orelse
Testcase =:= test_failed_token_refresh_case2 ->
end_per_testcase(Testcase, Config) when
Testcase =:= test_failed_token_refresh_case1 orelse
Testcase =:= test_failed_token_refresh_case2 ->
rabbit_ct_broker_helpers:delete_vhost(Config, <<"vhost4">>),
rabbit_ct_helpers:testcase_started(Config, Testcase),
Config;
end_per_testcase(Testcase, Config) when Testcase =:= test_successful_connection_with_complex_claim_as_a_map orelse
Testcase =:= test_successful_connection_with_complex_claim_as_a_list orelse
Testcase =:= test_successful_connection_with_complex_claim_as_a_binary ->
end_per_testcase(Testcase, Config) when
Testcase =:= test_successful_connection_with_complex_claim_as_a_map orelse
Testcase =:= test_successful_connection_with_complex_claim_as_a_list orelse
Testcase =:= test_successful_connection_with_complex_claim_as_a_binary ->
rabbit_ct_broker_helpers:delete_vhost(Config, <<"vhost1">>),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, unset_env,
[rabbitmq_auth_backend_oauth2, extra_scopes_source]),
rabbit_ct_helpers:testcase_started(Config, Testcase),
Config;
end_per_testcase(Testcase, Config) when Testcase =:= test_successful_connection_with_algorithm_restriction orelse
Testcase =:= test_failed_connection_with_algorithm_restriction ->
end_per_testcase(Testcase, Config) when
Testcase =:= test_successful_connection_with_algorithm_restriction orelse
Testcase =:= test_failed_connection_with_algorithm_restriction ->
rabbit_ct_broker_helpers:delete_vhost(Config, <<"vhost1">>),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env, [rabbitmq_auth_backend_oauth2, key_config, ?config(key_config, Config)]),
ok = rpc_set_env(Config, key_config, ?config(key_config, Config)),
rabbit_ct_helpers:testcase_finished(Config, Testcase),
Config;
@ -436,10 +437,9 @@ end_per_testcase(Testcase, Config) ->
Config.
preconfigure_node(Config) ->
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbit, auth_backends, [rabbit_auth_backend_oauth2]]),
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, resource_server_id, ?RESOURCE_SERVER_ID]),
ok = rpc(Config, 0, application, set_env,
[rabbit, auth_backends, [rabbit_auth_backend_oauth2]]),
ok = rpc_set_env(Config, resource_server_id, ?RESOURCE_SERVER_ID),
add_vhosts(Config),
Config.
@ -477,25 +477,23 @@ start_jwks_server(Config0) ->
KeyConfig = [{jwks_url, StrictJwksUrl},
{peer_verification, verify_peer},
{cacertfile, filename:join([CertsDir, "testca", "cacert.pem"])}],
ok = rabbit_ct_broker_helpers:rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, key_config, KeyConfig]),
rabbit_ct_helpers:set_config(Config,
[
{non_strict_jwks_url, NonStrictJwksUrl},
{strict_jwks_url, StrictJwksUrl},
{key_config, KeyConfig},
{fixture_static_1, Jwk7},
{fixture_static_2, Jwk8},
{fixture_staticB, Jwk4},
{fixture_staticC_1, Jwk5},
{fixture_staticC_2, Jwk6},
{fixture_jwksB_1, Jwk1},
{fixture_jwksB_2, Jwk3},
{fixture_jwksA, Jwk},
{fixture_jwk, Jwk},
{fixture_jwks_1, [Jwk1, Jwk3]},
{fixture_jwks_2, [Jwk2]}
]).
ok = rpc_set_env(Config, key_config, KeyConfig),
set_config(Config, [
{non_strict_jwks_url, NonStrictJwksUrl},
{strict_jwks_url, StrictJwksUrl},
{key_config, KeyConfig},
{fixture_static_1, Jwk7},
{fixture_static_2, Jwk8},
{fixture_staticB, Jwk4},
{fixture_staticC_1, Jwk5},
{fixture_staticC_2, Jwk6},
{fixture_jwksB_1, Jwk1},
{fixture_jwksB_2, Jwk3},
{fixture_jwksA, Jwk},
{fixture_jwk, Jwk},
{fixture_jwks_1, [Jwk1, Jwk3]},
{fixture_jwks_2, [Jwk2]}
]).
strict_jwks_url(Config) ->
strict_jwks_url(Config, "/jwks").
strict_jwks_url(Config, Path) ->
@ -517,54 +515,63 @@ generate_valid_token(Config, Scopes) ->
generate_valid_token(Config, Scopes, undefined).
generate_valid_token(Config, Scopes, Audience) ->
Jwk = case rabbit_ct_helpers:get_config(Config, fixture_jwk) of
Jwk =
case get_config(Config, fixture_jwk) of
undefined -> ?UTIL_MOD:fixture_jwk();
Value -> Value
end,
generate_valid_token(Config, Jwk, Scopes, Audience).
generate_valid_token(Config, Jwk, Scopes, Audience) ->
Token = case Audience of
undefined -> ?UTIL_MOD:fixture_token_with_scopes(Scopes);
DefinedAudience -> maps:put(<<"aud">>, DefinedAudience, ?UTIL_MOD:fixture_token_with_scopes(Scopes))
Token =
case Audience of
undefined ->
?UTIL_MOD:fixture_token_with_scopes(Scopes);
DefinedAudience ->
maps:put(<<"aud">>, DefinedAudience,
?UTIL_MOD:fixture_token_with_scopes(Scopes))
end,
IncludeKid = rabbit_ct_helpers:get_config(Config, include_kid, true),
?UTIL_MOD:sign_token_hs(Token, Jwk, IncludeKid).
generate_valid_token_with_extra_fields(Config, ExtraFields) ->
Jwk = case rabbit_ct_helpers:get_config(Config, fixture_jwk) of
undefined -> ?UTIL_MOD:fixture_jwk();
Value -> Value
end,
Jwk =
case rabbit_ct_helpers:get_config(Config, fixture_jwk) of
undefined -> ?UTIL_MOD:fixture_jwk();
Value -> Value
end,
Token = maps:merge(?UTIL_MOD:fixture_token_with_scopes([]), ExtraFields),
?UTIL_MOD:sign_token_hs(Token, Jwk, rabbit_ct_helpers:get_config(Config, include_kid, true)).
?UTIL_MOD:sign_token_hs(Token, Jwk,
rabbit_ct_helpers:get_config(Config, include_kid, true)).
generate_expired_token(Config) ->
generate_expired_token(Config, ?UTIL_MOD:full_permission_scopes()).
generate_expired_token(Config, Scopes) ->
Jwk = case rabbit_ct_helpers:get_config(Config, fixture_jwk) of
undefined -> ?UTIL_MOD:fixture_jwk();
Value -> Value
end,
Jwk =
case get_config(Config, fixture_jwk) of
undefined -> ?UTIL_MOD:fixture_jwk();
Value -> Value
end,
?UTIL_MOD:sign_token_hs(?UTIL_MOD:expired_token_with_scopes(Scopes), Jwk,
rabbit_ct_helpers:get_config(Config, include_kid, true)).
get_config(Config, include_kid, true)).
generate_expirable_token(Config, Seconds) ->
generate_expirable_token(Config, ?UTIL_MOD:full_permission_scopes(), Seconds).
generate_expirable_token(Config, Scopes, Seconds) ->
Jwk = case rabbit_ct_helpers:get_config(Config, fixture_jwk) of
undefined -> ?UTIL_MOD:fixture_jwk();
Value -> Value
end,
Jwk =
case get_config(Config, fixture_jwk) of
undefined -> ?UTIL_MOD:fixture_jwk();
Value -> Value
end,
Expiration = os:system_time(seconds) + Seconds,
?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_scopes_and_expiration(Scopes, Expiration),
Jwk, rabbit_ct_helpers:get_config(Config, include_kid, true)).
?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_scopes_and_expiration(
Scopes, Expiration), Jwk, get_config(Config, include_kid, true)).
preconfigure_token(Config) ->
Token = generate_valid_token(Config),
rabbit_ct_helpers:set_config(Config, {fixture_jwt, Token}).
set_config(Config, {fixture_jwt, Token}).
%%
@ -682,7 +689,7 @@ test_unsuccessful_connection_for_rabbitmq_audience_signed_by_root_oauth_provider
?assertMatch({error, {auth_failure, _}},
open_unmanaged_connection(Config, 0, <<"vhost1">>, <<"username">>, Token)).
test_successful_connection_with_a_full_permission_token_and_all_defaults(Config) ->
{_Algo, Token} = rabbit_ct_helpers:get_config(Config, fixture_jwt),
{_Algo, Token} = get_config(Config, fixture_jwt),
verify_queue_declare_with_token(Config, Token).
verify_queue_declare_with_token(Config, Token) ->
@ -734,10 +741,12 @@ test_successful_queue_declaration_using_multiple_keys_and_audiences(Config) ->
test_successful_connection_with_a_full_permission_token_and_explicitly_configured_vhost(Config) ->
{_Algo, Token} = generate_valid_token(Config, [<<"rabbitmq.configure:vhost1/*">>,
<<"rabbitmq.write:vhost1/*">>,
<<"rabbitmq.read:vhost1/*">>]),
Conn = open_unmanaged_connection(Config, 0, <<"vhost1">>, <<"username">>, Token),
{_Algo, Token} = generate_valid_token(Config, [
<<"rabbitmq.configure:vhost1/*">>,
<<"rabbitmq.write:vhost1/*">>,
<<"rabbitmq.read:vhost1/*">>]),
Conn = open_unmanaged_connection(Config, 0, <<"vhost1">>, <<"username">>,
Token),
{ok, Ch} = amqp_connection:open_channel(Conn),
#'queue.declare_ok'{queue = _} =
amqp_channel:call(Ch, #'queue.declare'{exclusive = true}),
@ -758,7 +767,13 @@ test_successful_connection_with_simple_strings_for_aud_and_scope(Config) ->
test_successful_connection_with_complex_claim_as_a_map(Config) ->
{_Algo, Token} = generate_valid_token_with_extra_fields(
Config,
#{<<"additional_rabbitmq_scopes">> => #{<<"rabbitmq">> => [<<"configure:*/*">>, <<"read:*/*">>, <<"write:*/*">>]}}
#{<<"additional_rabbitmq_scopes">> => #{
<<"rabbitmq">> => [
<<"configure:*/*">>,
<<"read:*/*">>,
<<"write:*/*">>
]}
}
),
Conn = open_unmanaged_connection(Config, 0, <<"username">>, Token),
{ok, Ch} = amqp_connection:open_channel(Conn),
@ -769,7 +784,11 @@ test_successful_connection_with_complex_claim_as_a_map(Config) ->
test_successful_connection_with_complex_claim_as_a_list(Config) ->
{_Algo, Token} = generate_valid_token_with_extra_fields(
Config,
#{<<"additional_rabbitmq_scopes">> => [<<"rabbitmq.configure:*/*">>, <<"rabbitmq.read:*/*">>, <<"rabbitmq.write:*/*">>]}
#{<<"additional_rabbitmq_scopes">> => [
<<"rabbitmq.configure:*/*">>,
<<"rabbitmq.read:*/*">>,
<<"rabbitmq.write:*/*">>
]}
),
Conn = open_unmanaged_connection(Config, 0, <<"username">>, Token),
{ok, Ch} = amqp_connection:open_channel(Conn),
@ -780,7 +799,8 @@ test_successful_connection_with_complex_claim_as_a_list(Config) ->
test_successful_connection_with_complex_claim_as_a_binary(Config) ->
{_Algo, Token} = generate_valid_token_with_extra_fields(
Config,
#{<<"additional_rabbitmq_scopes">> => <<"rabbitmq.configure:*/* rabbitmq.read:*/* rabbitmq.write:*/*">>}
#{<<"additional_rabbitmq_scopes">> =>
<<"rabbitmq.configure:*/* rabbitmq.read:*/* rabbitmq.write:*/*">>}
),
Conn = open_unmanaged_connection(Config, 0, <<"username">>, Token),
{ok, Ch} = amqp_connection:open_channel(Conn),
@ -815,79 +835,94 @@ test_successful_connection_with_keycloak_token(Config) ->
test_successful_token_refresh(Config) ->
Duration = 5,
{_Algo, Token} = generate_expirable_token(Config, [<<"rabbitmq.configure:vhost1/*">>,
<<"rabbitmq.write:vhost1/*">>,
<<"rabbitmq.read:vhost1/*">>],
Duration),
Conn = open_unmanaged_connection(Config, 0, <<"vhost1">>, <<"username">>, Token),
{_Algo, Token} = generate_expirable_token(Config, [
<<"rabbitmq.configure:vhost1/*">>,
<<"rabbitmq.write:vhost1/*">>,
<<"rabbitmq.read:vhost1/*">>
], Duration),
Conn = open_unmanaged_connection(Config, 0, <<"vhost1">>,
<<"username">>, Token),
{ok, Ch} = amqp_connection:open_channel(Conn),
{_Algo2, Token2} = generate_valid_token(Config, [<<"rabbitmq.configure:vhost1/*">>,
<<"rabbitmq.write:vhost1/*">>,
<<"rabbitmq.read:vhost1/*">>]),
{_Algo2, Token2} = generate_valid_token(Config, [
<<"rabbitmq.configure:vhost1/*">>,
<<"rabbitmq.write:vhost1/*">>,
<<"rabbitmq.read:vhost1/*">>]),
?UTIL_MOD:wait_for_token_to_expire(timer:seconds(Duration)),
?assertEqual(ok, amqp_connection:update_secret(Conn, Token2, <<"token refresh">>)),
?assertEqual(ok, amqp_connection:update_secret(Conn, Token2,
<<"token refresh">>)),
{ok, Ch2} = amqp_connection:open_channel(Conn),
#'queue.declare_ok'{queue = _} =
amqp_channel:call(Ch, #'queue.declare'{exclusive = true}),
#'queue.declare_ok'{queue = _} =
amqp_channel:call(Ch2, #'queue.declare'{exclusive = true}),
#'queue.declare_ok'{queue = _} = amqp_channel:call(Ch,
#'queue.declare'{exclusive = true}),
#'queue.declare_ok'{queue = _} = amqp_channel:call(Ch2,
#'queue.declare'{exclusive = true}),
amqp_channel:close(Ch2),
close_connection_and_channel(Conn, Ch).
test_successful_connection_with_algorithm_restriction(Config) ->
{_Algo, Token} = rabbit_ct_helpers:get_config(Config, fixture_jwt),
{_Algo, Token} = get_config(Config, fixture_jwt),
Conn = open_unmanaged_connection(Config, 0, <<"username">>, Token),
{ok, Ch} = amqp_connection:open_channel(Conn),
#'queue.declare_ok'{queue = _} =
amqp_channel:call(Ch, #'queue.declare'{exclusive = true}),
#'queue.declare_ok'{queue = _} = amqp_channel:call(Ch,
#'queue.declare'{exclusive = true}),
close_connection_and_channel(Conn, Ch).
test_failed_connection_with_expired_token(Config) ->
{_Algo, Token} = generate_expired_token(Config, [<<"rabbitmq.configure:vhost1/*">>,
<<"rabbitmq.write:vhost1/*">>,
<<"rabbitmq.read:vhost1/*">>]),
{_Algo, Token} = generate_expired_token(Config, [
<<"rabbitmq.configure:vhost1/*">>,
<<"rabbitmq.write:vhost1/*">>,
<<"rabbitmq.read:vhost1/*">>]),
?assertMatch({error, {auth_failure, _}},
open_unmanaged_connection(Config, 0, <<"vhost1">>, <<"username">>, Token)).
open_unmanaged_connection(Config, 0, <<"vhost1">>,
<<"username">>, Token)).
test_failed_connection_with_a_non_token(Config) ->
?assertMatch({error, {auth_failure, _}},
open_unmanaged_connection(Config, 0, <<"vhost1">>, <<"username">>, <<"a-non-token-value">>)).
open_unmanaged_connection(Config, 0, <<"vhost1">>,
<<"username">>, <<"a-non-token-value">>)).
test_failed_connection_with_a_token_with_insufficient_vhost_permission(Config) ->
{_Algo, Token} = generate_valid_token(Config, [<<"rabbitmq.configure:alt-vhost/*">>,
<<"rabbitmq.write:alt-vhost/*">>,
<<"rabbitmq.read:alt-vhost/*">>]),
{_Algo, Token} = generate_valid_token(Config, [
<<"rabbitmq.configure:alt-vhost/*">>,
<<"rabbitmq.write:alt-vhost/*">>,
<<"rabbitmq.read:alt-vhost/*">>]),
?assertEqual({error, not_allowed},
open_unmanaged_connection(Config, 0, <<"off-limits-vhost">>, <<"username">>, Token)).
open_unmanaged_connection(Config, 0, <<"off-limits-vhost">>,
<<"username">>, Token)).
test_failed_connection_with_a_token_with_insufficient_resource_permission(Config) ->
{_Algo, Token} = generate_valid_token(Config, [<<"rabbitmq.configure:vhost2/jwt*">>,
<<"rabbitmq.write:vhost2/jwt*">>,
<<"rabbitmq.read:vhost2/jwt*">>]),
Conn = open_unmanaged_connection(Config, 0, <<"vhost2">>, <<"username">>, Token),
{_Algo, Token} = generate_valid_token(Config, [
<<"rabbitmq.configure:vhost2/jwt*">>,
<<"rabbitmq.write:vhost2/jwt*">>,
<<"rabbitmq.read:vhost2/jwt*">>]),
Conn = open_unmanaged_connection(Config, 0, <<"vhost2">>, <<"username">>,
Token),
{ok, Ch} = amqp_connection:open_channel(Conn),
?assertExit({{shutdown, {server_initiated_close, 403, _}}, _},
amqp_channel:call(Ch, #'queue.declare'{queue = <<"alt-prefix.eq.1">>, exclusive = true})),
amqp_channel:call(Ch, #'queue.declare'{queue = <<"alt-prefix.eq.1">>,
exclusive = true})),
close_connection(Conn).
test_failed_token_refresh_case1(Config) ->
{_Algo, Token} = generate_valid_token(Config, [<<"rabbitmq.configure:vhost4/*">>,
<<"rabbitmq.write:vhost4/*">>,
<<"rabbitmq.read:vhost4/*">>]),
Conn = open_unmanaged_connection(Config, 0, <<"vhost4">>, <<"username">>, Token),
{_Algo, Token} = generate_valid_token(Config, [
<<"rabbitmq.configure:vhost4/*">>,
<<"rabbitmq.write:vhost4/*">>,
<<"rabbitmq.read:vhost4/*">>]),
Conn = open_unmanaged_connection(Config, 0, <<"vhost4">>, <<"username">>,
Token),
{ok, Ch} = amqp_connection:open_channel(Conn),
#'queue.declare_ok'{queue = _} =
amqp_channel:call(Ch, #'queue.declare'{exclusive = true}),
{_Algo2, Token2} = generate_expired_token(Config, [<<"rabbitmq.configure:vhost4/*">>,
<<"rabbitmq.write:vhost4/*">>,
<<"rabbitmq.read:vhost4/*">>]),
{_Algo2, Token2} = generate_expired_token(Config, [
<<"rabbitmq.configure:vhost4/*">>,
<<"rabbitmq.write:vhost4/*">>,
<<"rabbitmq.read:vhost4/*">>]),
%% the error is communicated asynchronously via a connection-level error
?assertEqual(ok, amqp_connection:update_secret(Conn, Token2, <<"token refresh">>)),
?assertEqual(ok, amqp_connection:update_secret(Conn, Token2,
<<"token refresh">>)),
{ok, Ch2} = amqp_connection:open_channel(Conn),
?assertExit({{shutdown, {server_initiated_close, 403, _}}, _},
@ -896,16 +931,19 @@ test_failed_token_refresh_case1(Config) ->
close_connection(Conn).
test_failed_token_refresh_case2(Config) ->
{_Algo, Token} = generate_valid_token(Config, [<<"rabbitmq.configure:vhost4/*">>,
<<"rabbitmq.write:vhost4/*">>,
<<"rabbitmq.read:vhost4/*">>]),
Conn = open_unmanaged_connection(Config, 0, <<"vhost4">>, <<"username">>, Token),
{_Algo, Token} = generate_valid_token(Config, [
<<"rabbitmq.configure:vhost4/*">>,
<<"rabbitmq.write:vhost4/*">>,
<<"rabbitmq.read:vhost4/*">>]),
Conn = open_unmanaged_connection(Config, 0, <<"vhost4">>,
<<"username">>, Token),
{ok, Ch} = amqp_connection:open_channel(Conn),
#'queue.declare_ok'{queue = _} =
amqp_channel:call(Ch, #'queue.declare'{exclusive = true}),
%% the error is communicated asynchronously via a connection-level error
?assertEqual(ok, amqp_connection:update_secret(Conn, <<"not-a-token-^^^^5%">>, <<"token refresh">>)),
?assertEqual(ok, amqp_connection:update_secret(Conn, <<"not-a-token-^^^^5%">>,
<<"token refresh">>)),
?assertExit({{shutdown, {connection_closing, {server_initiated_close, 530, _}}}, _},
amqp_connection:open_channel(Conn)),
@ -913,6 +951,20 @@ test_failed_token_refresh_case2(Config) ->
close_connection(Conn).
test_failed_connection_with_algorithm_restriction(Config) ->
{_Algo, Token} = rabbit_ct_helpers:get_config(Config, fixture_jwt),
{_Algo, Token} = get_config(Config, fixture_jwt),
?assertMatch({error, {auth_failure, _}},
open_unmanaged_connection(Config, 0, <<"username">>, Token)).
%%% HELPERS
rpc_unset_env(Config, Par) ->
rpc(Config, 0, application, unset_env,
[rabbitmq_auth_backend_oauth2, Par]).
rpc_set_env(Config, Par, Val) ->
rpc(Config, 0, application, set_env,
[rabbitmq_auth_backend_oauth2, Par, Val]).
rpc_get_env(Config, Par) ->
rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, Par]).
rpc_get_env(Config, Par, Default) ->
rpc(Config, 0, application, get_env,
[rabbitmq_auth_backend_oauth2, Par, Default]).

View File

@ -5,7 +5,7 @@
%% Copyright (c) 2007-2024 Broadcom. All Rights Reserved. The term Broadcom refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
-module(oauth_provider_SUITE).
-module(rabbit_oauth2_provider_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
@ -17,7 +17,7 @@
-define(RABBITMQ_RESOURCE_TWO,<<"rabbitmq2">>).
-define(AUTH_PORT, 8000).
-import(oauth_provider, [
-import(rabbit_oauth2_provider, [
get_internal_oauth_provider/0,get_internal_oauth_provider/1,
add_signing_key/2, add_signing_key/3, replace_signing_keys/1,
replace_signing_keys/2,
@ -237,22 +237,27 @@ call_get_env(Config, Par, Def) ->
[rabbitmq_auth_backend_oauth2, Par, Def]).
call_add_signing_key(Config, Args) ->
rabbit_ct_broker_helpers:rpc(Config, 0, oauth_provider, add_signing_key, Args).
rabbit_ct_broker_helpers:rpc(Config, 0, rabbit_oauth2_provider,
add_signing_key, Args).
call_get_signing_keys(Config, Args) ->
rabbit_ct_broker_helpers:rpc(Config, 0, oauth_provider, get_signing_keys, Args).
rabbit_ct_broker_helpers:rpc(Config, 0, rabbit_oauth2_provider,
get_signing_keys, Args).
call_get_signing_keys(Config) ->
call_get_signing_keys(Config, []).
call_get_signing_key(Config, Args) ->
rabbit_ct_broker_helpers:rpc(Config, 0, oauth_provider, get_signing_key, Args).
rabbit_ct_broker_helpers:rpc(Config, 0, rabbit_oauth2_provider,
get_signing_key, Args).
call_add_signing_keys(Config, Args) ->
rabbit_ct_broker_helpers:rpc(Config, 0, oauth_provider, add_signing_keys, Args).
rabbit_ct_broker_helpers:rpc(Config, 0, rabbit_oauth2_provider,
add_signing_keys, Args).
call_replace_signing_keys(Config, Args) ->
rabbit_ct_broker_helpers:rpc(Config, 0, oauth_provider, replace_signing_keys, Args).
rabbit_ct_broker_helpers:rpc(Config, 0, rabbit_oauth2_provider,
replace_signing_keys, Args).
%% ----- Test cases
@ -474,15 +479,13 @@ start_https_oauth_server(Port, CertsDir, Expectations) when is_list(Expectations
{'_', [{Path, oauth2_http_mock, Expected} ||
#{request := #{path := Path}} = Expected <- Expectations ]}
]),
ct:log("start_https_oauth_server (port:~p) with expectation list : ~p -> dispatch: ~p", [Port, Expectations, Dispatch]),
{ok, Pid} = cowboy:start_tls(
mock_http_auth_listener,
[{port, Port},
{certfile, filename:join([CertsDir, "server", "cert.pem"])},
{keyfile, filename:join([CertsDir, "server", "key.pem"])}
],
#{env => #{dispatch => Dispatch}}),
ct:log("Started on Port ~p and pid ~p", [ranch:get_port(mock_http_auth_listener), Pid]).
#{env => #{dispatch => Dispatch}}).
build_url_to_oauth_provider(Path) ->
uri_string:recompose(#{scheme => "https",

View File

@ -5,7 +5,7 @@
%% Copyright (c) 2007-2024 Broadcom. All Rights Reserved. The term Broadcom refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
-module(resource_server_SUITE).
-module(rabbit_oauth2_resource_server_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
@ -19,7 +19,7 @@
-define(OAUTH_PROVIDER_B,<<"B">>).
-import(oauth2_client, [get_oauth_provider/2]).
-import(resource_server, [resolve_resource_server_from_audience/1]).
-import(rabbit_oauth2_resource_server, [resolve_resource_server_from_audience/1]).
all() -> [

View File

@ -4,7 +4,7 @@
%%
%% Copyright (c) 2007-2024 Broadcom. All Rights Reserved. The term Broadcom refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
-module(oauth2_schema_SUITE).
-module(rabbit_oauth2_schema_SUITE).
-compile(export_all).
@ -12,7 +12,11 @@
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-import(oauth2_schema, [translate_endpoint_params/2, translate_oauth_providers/1]).
-import(rabbit_oauth2_schema, [
translate_endpoint_params/2,
translate_oauth_providers/1,
translate_resource_servers/1
]).
all() ->
[
@ -39,10 +43,10 @@ all() ->
test_without_oauth_providers(_) ->
#{} = oauth2_schema:translate_oauth_providers([]).
#{} = translate_oauth_providers([]).
test_without_resource_servers(_) ->
#{} = oauth2_schema:translate_resource_servers([]).
#{} = translate_resource_servers([]).
test_without_endpoint_params(_) ->
[] = translate_endpoint_params("oauth_discovery_endpoint_params", []).
@ -64,7 +68,7 @@ test_with_endpoint_params(_) ->
translate_endpoint_params("discovery_endpoint_params", Conf).
test_invalid_oauth_providers_endpoint_params(_) ->
try oauth2_schema:translate_oauth_providers([
try translate_oauth_providers([
{["auth_oauth2","oauth_providers", "X", "discovery_endpoint_params"], ""}]) of
_ -> {throw, should_have_failed}
catch
@ -73,11 +77,13 @@ test_invalid_oauth_providers_endpoint_params(_) ->
test_without_oauth_providers_with_endpoint_params(_) ->
Conf = [
{["auth_oauth2","oauth_providers", "A", "discovery_endpoint_params","param1"], "some-value1"},
{["auth_oauth2","oauth_providers", "A", "discovery_endpoint_params","param2"], "some-value2"},
{["auth_oauth2","oauth_providers", "B", "discovery_endpoint_params","param3"], "some-value3"}
{["auth_oauth2","oauth_providers", "A", "discovery_endpoint_params","param1"],
"some-value1"},
{["auth_oauth2","oauth_providers", "A", "discovery_endpoint_params","param2"],
"some-value2"},
{["auth_oauth2","oauth_providers", "B", "discovery_endpoint_params","param3"],
"some-value3"}
],
#{
<<"A">> := [{discovery_endpoint_params, [
{<<"param1">>, <<"some-value1">>},
@ -90,107 +96,143 @@ test_without_oauth_providers_with_endpoint_params(_) ->
} = translate_oauth_providers(Conf).
test_with_one_oauth_provider(_) ->
Conf = [{["auth_oauth2","oauth_providers","keycloak","issuer"],"https://rabbit"}
],
Conf = [
{["auth_oauth2","oauth_providers","keycloak","issuer"],"https://rabbit"}
],
#{<<"keycloak">> := [{issuer, "https://rabbit"}]
} = oauth2_schema:translate_oauth_providers(Conf).
} = translate_oauth_providers(Conf).
test_with_one_resource_server(_) ->
Conf = [{["auth_oauth2","resource_servers","rabbitmq1","id"],"rabbitmq1"}
],
Conf = [
{["auth_oauth2","resource_servers","rabbitmq1","id"],"rabbitmq1"}
],
#{<<"rabbitmq1">> := [{id, <<"rabbitmq1">>}]
} = oauth2_schema:translate_resource_servers(Conf).
} = translate_resource_servers(Conf).
test_with_many_oauth_providers(_) ->
Conf = [{["auth_oauth2","oauth_providers","keycloak","issuer"],"https://keycloak"},
{["auth_oauth2","oauth_providers","uaa","issuer"],"https://uaa"},
{["auth_oauth2","oauth_providers","uaa","discovery_endpoint_path"],"/some-path"}
],
Conf = [
{["auth_oauth2","oauth_providers","keycloak","issuer"],
"https://keycloak"},
{["auth_oauth2","oauth_providers","uaa","issuer"],
"https://uaa"},
{["auth_oauth2","oauth_providers","uaa","discovery_endpoint_path"],
"/some-path"}
],
#{<<"keycloak">> := [{issuer, "https://keycloak"}
],
<<"uaa">> := [{issuer, "https://uaa"},
{discovery_endpoint_path, "/some-path"}
]
} = oauth2_schema:translate_oauth_providers(Conf).
} = translate_oauth_providers(Conf).
test_with_many_resource_servers(_) ->
Conf = [{["auth_oauth2","resource_servers","rabbitmq1","id"],"rabbitmq1"},
{["auth_oauth2","resource_servers","rabbitmq2","id"],"rabbitmq2"}
],
Conf = [
{["auth_oauth2","resource_servers","rabbitmq1","id"], "rabbitmq1"},
{["auth_oauth2","resource_servers","rabbitmq2","id"], "rabbitmq2"}
],
#{<<"rabbitmq1">> := [{id, <<"rabbitmq1">>}
],
<<"rabbitmq2">> := [{id, <<"rabbitmq2">>}
]
} = oauth2_schema:translate_resource_servers(Conf).
} = translate_resource_servers(Conf).
test_oauth_providers_attributes(_) ->
Conf = [{["auth_oauth2","oauth_providers","keycloak","issuer"],"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","default_key"],"token-key"}
],
Conf = [
{["auth_oauth2","oauth_providers","keycloak","issuer"],
"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","default_key"],
"token-key"}
],
#{<<"keycloak">> := [{default_key, <<"token-key">>},
{issuer, "https://keycloak"}
]
} = sort_settings(oauth2_schema:translate_oauth_providers(Conf)).
} = sort_settings(translate_oauth_providers(Conf)).
test_resource_servers_attributes(_) ->
Conf = [{["auth_oauth2","resource_servers","rabbitmq1","id"],"rabbitmq1xxx"},
{["auth_oauth2","resource_servers","rabbitmq1","scope_prefix"],"somescope."},
{["auth_oauth2","resource_servers","rabbitmq1","additional_scopes_key"],"roles"},
{["auth_oauth2","resource_servers","rabbitmq1","preferred_username_claims","1"],"userid"},
{["auth_oauth2","resource_servers","rabbitmq1","preferred_username_claims","2"],"groupid"}
],
Conf = [
{["auth_oauth2","resource_servers","rabbitmq1","id"],
"rabbitmq1xxx"},
{["auth_oauth2","resource_servers","rabbitmq1","scope_prefix"],
"somescope."},
{["auth_oauth2","resource_servers","rabbitmq1","additional_scopes_key"],
"roles"},
{["auth_oauth2","resource_servers","rabbitmq1","preferred_username_claims","1"],
"userid"},
{["auth_oauth2","resource_servers","rabbitmq1","preferred_username_claims","2"],
"groupid"}
],
#{<<"rabbitmq1xxx">> := [{additional_scopes_key, <<"roles">>},
{id, <<"rabbitmq1xxx">>},
{preferred_username_claims, [<<"userid">>, <<"groupid">>]},
{scope_prefix, <<"somescope.">>}
]
} = sort_settings(oauth2_schema:translate_resource_servers(Conf)),
} = sort_settings(translate_resource_servers(Conf)),
Conf2 = [
{["auth_oauth2","resource_servers","rabbitmq1","scope_prefix"],"somescope."},
{["auth_oauth2","resource_servers","rabbitmq1","additional_scopes_key"],"roles"},
{["auth_oauth2","resource_servers","rabbitmq1","preferred_username_claims","1"],"userid"},
{["auth_oauth2","resource_servers","rabbitmq1","preferred_username_claims","2"],"groupid"}
],
{["auth_oauth2","resource_servers","rabbitmq1","scope_prefix"],
"somescope."},
{["auth_oauth2","resource_servers","rabbitmq1","additional_scopes_key"],
"roles"},
{["auth_oauth2","resource_servers","rabbitmq1","preferred_username_claims","1"],
"userid"},
{["auth_oauth2","resource_servers","rabbitmq1","preferred_username_claims","2"],
"groupid"}
],
#{<<"rabbitmq1">> := [{additional_scopes_key, <<"roles">>},
{id, <<"rabbitmq1">>},
{preferred_username_claims, [<<"userid">>, <<"groupid">>]},
{scope_prefix, <<"somescope.">>}
]
} = sort_settings(oauth2_schema:translate_resource_servers(Conf2)).
} = sort_settings(translate_resource_servers(Conf2)).
test_oauth_providers_attributes_with_invalid_uri(_) ->
Conf = [{["auth_oauth2","oauth_providers","keycloak","issuer"],"http://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","default_key"],"token-key"}
],
try sort_settings(oauth2_schema:translate_oauth_providers(Conf)) of
Conf = [
{["auth_oauth2","oauth_providers","keycloak","issuer"],
"http://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","default_key"],
"token-key"}
],
try sort_settings(translate_oauth_providers(Conf)) of
_ -> {throw, should_have_failed}
catch
_ -> ok
end.
test_oauth_providers_algorithms(_) ->
Conf = [{["auth_oauth2","oauth_providers","keycloak","issuer"],"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","algorithms","2"],"HS256"},
{["auth_oauth2","oauth_providers","keycloak","algorithms","1"],"RS256"}
],
Conf = [
{["auth_oauth2","oauth_providers","keycloak","issuer"],
"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","algorithms","2"],
"HS256"},
{["auth_oauth2","oauth_providers","keycloak","algorithms","1"],
"RS256"}
],
#{<<"keycloak">> := [{algorithms, [<<"RS256">>, <<"HS256">>]},
{issuer, "https://keycloak"}
]
} = sort_settings(oauth2_schema:translate_oauth_providers(Conf)).
} = sort_settings(translate_oauth_providers(Conf)).
test_oauth_providers_https(Conf) ->
CuttlefishConf = [{["auth_oauth2","oauth_providers","keycloak","issuer"],"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","https","verify"],verify_none},
{["auth_oauth2","oauth_providers","keycloak","https","peer_verification"],verify_peer},
{["auth_oauth2","oauth_providers","keycloak","https","depth"],2},
{["auth_oauth2","oauth_providers","keycloak","https","hostname_verification"],wildcard},
{["auth_oauth2","oauth_providers","keycloak","https","crl_check"],false},
{["auth_oauth2","oauth_providers","keycloak","https","fail_if_no_peer_cert"],true},
{["auth_oauth2","oauth_providers","keycloak","https","cacertfile"],cert_filename(Conf)}
],
CuttlefishConf = [
{["auth_oauth2","oauth_providers","keycloak","issuer"],
"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","https","verify"],
verify_none},
{["auth_oauth2","oauth_providers","keycloak","https","peer_verification"],
verify_peer},
{["auth_oauth2","oauth_providers","keycloak","https","depth"],
2},
{["auth_oauth2","oauth_providers","keycloak","https","hostname_verification"],
wildcard},
{["auth_oauth2","oauth_providers","keycloak","https","crl_check"],
false},
{["auth_oauth2","oauth_providers","keycloak","https","fail_if_no_peer_cert"],
true},
{["auth_oauth2","oauth_providers","keycloak","https","cacertfile"],
cert_filename(Conf)}
],
#{<<"keycloak">> := [{https, [{verify, verify_none},
{peer_verification, verify_peer},
{depth, 2},
@ -201,36 +243,44 @@ test_oauth_providers_https(Conf) ->
]},
{issuer, "https://keycloak"}
]
} = sort_settings(oauth2_schema:translate_oauth_providers(CuttlefishConf)).
} = sort_settings(translate_oauth_providers(CuttlefishConf)).
test_oauth_providers_https_with_missing_cacertfile(_) ->
Conf = [{["auth_oauth2","oauth_providers","keycloak","issuer"],"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","https","cacertfile"],"/non-existent.pem"}
],
try sort_settings(oauth2_schema:translate_oauth_providers(Conf)) of
Conf = [
{["auth_oauth2","oauth_providers","keycloak","issuer"],
"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","https","cacertfile"],
"/non-existent.pem"}
],
try sort_settings(translate_oauth_providers(Conf)) of
_ -> {throw, should_have_failed}
catch
_ -> ok
end.
test_oauth_providers_signing_keys(Conf) ->
CuttlefishConf = [{["auth_oauth2","oauth_providers","keycloak","issuer"],"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","signing_keys","2"], cert_filename(Conf)},
{["auth_oauth2","oauth_providers","keycloak","signing_keys","1"], cert_filename(Conf)}
],
CuttlefishConf = [
{["auth_oauth2","oauth_providers","keycloak","issuer"],
"https://keycloak"},
{["auth_oauth2","oauth_providers","keycloak","signing_keys","2"],
cert_filename(Conf)},
{["auth_oauth2","oauth_providers","keycloak","signing_keys","1"],
cert_filename(Conf)}
],
#{<<"keycloak">> := [{issuer, "https://keycloak"},
{signing_keys, SigningKeys}
]
} = sort_settings(oauth2_schema:translate_oauth_providers(CuttlefishConf)),
} = sort_settings(translate_oauth_providers(CuttlefishConf)),
ct:log("SigningKey: ~p", [SigningKeys]),
#{<<"1">> := {pem, <<"I'm not a certificate">>},
<<"2">> := {pem, <<"I'm not a certificate">>}
} = SigningKeys.
} = SigningKeys.
cert_filename(Conf) ->
string:concat(?config(data_dir, Conf), "certs/cert.pem").
sort_settings(MapOfListOfSettings) ->
maps:map(fun(_K,List) ->
lists:sort(fun({K1,_}, {K2,_}) -> K1 < K2 end, List) end, MapOfListOfSettings).
lists:sort(fun({K1,_}, {K2,_}) -> K1 < K2 end, List) end,
MapOfListOfSettings).

View File

@ -18,6 +18,9 @@
user_login_authorization/2,
normalize_token_scope/2,
check_vhost_access/3]).
-import(rabbit_oauth2_resource_server, [
new_resource_server/1
]).
all() ->
[
@ -77,7 +80,7 @@ end_per_suite(Config) ->
Env = ?config(env, Config),
lists:foreach(
fun({K, V}) ->
application:set_env(rabbitmq_auth_backend_oauth2, K, V)
set_env(K, V)
end,
Env),
rabbit_ct_helpers:run_teardown_steps(Config).
@ -95,7 +98,7 @@ init_per_group(with_rabbitmq_node, Config) ->
rabbit_ct_helpers:run_steps(Config2, rabbit_ct_broker_helpers:setup_steps());
init_per_group(with_resource_server_id, Config) ->
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
set_env(resource_server_id, <<"rabbitmq">>),
Config;
init_per_group(_, Config) ->
@ -172,7 +175,7 @@ normalize_token_scope_with_keycloak_scopes(_) ->
],
lists:foreach(fun({Case, Authorization, ExpectedScope}) ->
ResourceServer = resource_server:new_resource_server(<<"rabbitmq-resource">>),
ResourceServer = new_resource_server(<<"rabbitmq-resource">>),
Token0 = #{<<"authorization">> => Authorization},
Token = normalize_token_scope(ResourceServer, Token0),
?assertEqual(ExpectedScope, uaa_jwt:get_scope(Token), Case)
@ -216,7 +219,7 @@ normalize_token_scope_with_rich_auth_request_using_regular_expression_with_clust
lists:foreach(
fun({Case, Permissions, ExpectedScope}) ->
ResourceServer0 = resource_server:new_resource_server(<<"rabbitmq-test">>),
ResourceServer0 = new_resource_server(<<"rabbitmq-test">>),
ResourceServer = ResourceServer0#resource_server{
resource_server_type = ?RESOURCE_SERVER_TYPE
},
@ -531,7 +534,7 @@ normalize_token_scope_with_rich_auth_request(_) ->
],
lists:foreach(fun({Case, Permissions, ExpectedScope0}) ->
ResourceServer0 = resource_server:new_resource_server(?RESOURCE_SERVER_ID),
ResourceServer0 = new_resource_server(?RESOURCE_SERVER_ID),
ResourceServer = ResourceServer0#resource_server{
resource_server_type = ?RESOURCE_SERVER_TYPE
},
@ -600,7 +603,7 @@ normalize_token_scope_with_additional_scopes_complex_claims(_) ->
"no extra claims provided", #{}, []
}],
lists:foreach(fun({Case, Authorization, ExpectedScope0}) ->
ResourceServer0 = resource_server:new_resource_server(?RESOURCE_SERVER_ID),
ResourceServer0 = new_resource_server(?RESOURCE_SERVER_ID),
ResourceServer = ResourceServer0#resource_server{
scope_prefix = <<"rabbitmq.rabbitmq-resource.">>,
additional_scopes_key = <<"custom-key">>
@ -627,7 +630,7 @@ test_successful_authentication_without_scopes(_) ->
test_successful_authorization_without_scopes(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
Username = <<"username">>,
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(
@ -641,11 +644,12 @@ test_successful_access_with_a_token(_) ->
%% Check user access granted by token
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
VHost = <<"vhost">>,
Username = <<"username">>,
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk),
Token = ?UTIL_MOD:sign_token_hs(
?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk),
{ok, #auth_user{username = Username} = User} =
user_login_authentication(Username, [{password, Token}]),
@ -656,7 +660,8 @@ test_successful_access_with_a_token(_) ->
assert_resource_access_granted(User, VHost, <<"bar">>, read),
assert_resource_access_granted(User, VHost, custom, <<"bar">>, read),
assert_topic_access_granted(User, VHost, <<"bar">>, read, #{routing_key => <<"#/foo">>}).
assert_topic_access_granted(User, VHost, <<"bar">>, read,
#{routing_key => <<"#/foo">>}).
successful_access_with_a_token_with_variables_in_scopes(_) ->
%% Generate a token with JOSE
@ -664,25 +669,28 @@ successful_access_with_a_token_with_variables_in_scopes(_) ->
%% Check user access granted by token
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
VHost = <<"my-vhost">>,
Username = <<"username">>,
Token = ?UTIL_MOD:sign_token_hs(
?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token([<<"rabbitmq.read:{vhost}/*/{sub}">>]), Username),
?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(
[<<"rabbitmq.read:{vhost}/*/{sub}">>]), Username),
Jwk),
{ok, #auth_user{username = Username} = User} =
user_login_authentication(Username, #{password => Token}),
assert_topic_access_granted(User, VHost, <<"bar">>, read, #{routing_key => Username}).
assert_topic_access_granted(User, VHost, <<"bar">>, read,
#{routing_key => Username}).
successful_access_with_a_parsed_token(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
Username = <<"username">>,
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk),
Token = ?UTIL_MOD:sign_token_hs(
?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk),
{ok, #auth_user{impl = Impl} } =
user_login_authentication(Username, [{password, Token}]),
@ -693,10 +701,12 @@ successful_access_with_a_parsed_token(_) ->
test_successful_access_with_a_token_that_has_tag_scopes(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
Username = <<"username">>,
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(
[<<"rabbitmq.tag:management">>, <<"rabbitmq.tag:policymaker">>]), Username), Jwk),
Token = ?UTIL_MOD:sign_token_hs(
?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(
[<<"rabbitmq.tag:management">>, <<"rabbitmq.tag:policymaker">>]),
Username), Jwk),
{ok, #auth_user{username = Username, tags = [management, policymaker]}} =
user_login_authentication(Username, [{password, Token}]).
@ -704,9 +714,9 @@ test_successful_access_with_a_token_that_has_tag_scopes(_) ->
test_successful_access_with_a_token_that_uses_single_scope_alias_in_scope_field(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
Alias = <<"client-alias-1">>,
application:set_env(rabbitmq_auth_backend_oauth2, scope_aliases, #{
set_env(scope_aliases, #{
Alias => [
<<"rabbitmq.configure:vhost/one">>,
<<"rabbitmq.write:vhost/two">>,
@ -744,10 +754,10 @@ test_successful_access_with_a_token_that_uses_single_scope_alias_in_scope_field(
test_successful_access_with_a_token_that_uses_single_scope_alias_in_scope_field_and_custom_scope_prefix(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
application:set_env(rabbitmq_auth_backend_oauth2, scope_prefix, <<>>),
set_env(key_config, UaaEnv),
set_env(scope_prefix, <<>>),
Alias = <<"client-alias-1">>,
application:set_env(rabbitmq_auth_backend_oauth2, scope_aliases, #{
set_env(scope_aliases, #{
Alias => [
<<"configure:vhost/one">>,
<<"write:vhost/two">>,
@ -785,11 +795,11 @@ test_successful_access_with_a_token_that_uses_single_scope_alias_in_scope_field_
test_successful_access_with_a_token_that_uses_multiple_scope_aliases_in_scope_field(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
Role1 = <<"client-aliases-1">>,
Role2 = <<"client-aliases-2">>,
Role3 = <<"client-aliases-3">>,
application:set_env(rabbitmq_auth_backend_oauth2, scope_aliases, #{
set_env(scope_aliases, #{
Role1 => [
<<"rabbitmq.configure:vhost/one">>,
<<"rabbitmq.tag:management">>
@ -808,7 +818,8 @@ test_successful_access_with_a_token_that_uses_multiple_scope_aliases_in_scope_fi
VHost = <<"vhost">>,
Username = <<"username">>,
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(
?UTIL_MOD:token_with_scope_alias_in_scope_field([Role1, Role2, Role3]), Username), Jwk),
?UTIL_MOD:token_with_scope_alias_in_scope_field([Role1, Role2, Role3]),
Username), Jwk),
{ok, #auth_user{username = Username} = AuthUser} =
user_login_authentication(Username, [{password, Token}]),
@ -830,10 +841,10 @@ test_successful_access_with_a_token_that_uses_multiple_scope_aliases_in_scope_fi
test_unsuccessful_access_with_a_token_that_uses_missing_scope_alias_in_scope_field(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
set_env(key_config, UaaEnv),
set_env(resource_server_id, <<"rabbitmq">>),
Alias = <<"client-alias-33">>,
application:set_env(rabbitmq_auth_backend_oauth2, scope_aliases, #{
set_env(scope_aliases, #{
<<"non-existent-alias-23948sdkfjsdof8">> => [
<<"rabbitmq.configure:vhost/one">>,
<<"rabbitmq.write:vhost/two">>,
@ -867,10 +878,10 @@ test_unsuccessful_access_with_a_token_that_uses_missing_scope_alias_in_scope_fie
test_successful_access_with_a_token_that_uses_single_scope_alias_in_extra_scope_source_field(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
application:set_env(rabbitmq_auth_backend_oauth2, extra_scopes_source, <<"claims">>),
set_env(key_config, UaaEnv),
set_env(extra_scopes_source, <<"claims">>),
Alias = <<"client-alias-1">>,
application:set_env(rabbitmq_auth_backend_oauth2, scope_aliases, #{
set_env(scope_aliases, #{
Alias => [
<<"rabbitmq.configure:vhost/one">>,
<<"rabbitmq.write:vhost/two">>,
@ -883,7 +894,8 @@ test_successful_access_with_a_token_that_uses_single_scope_alias_in_extra_scope_
VHost = <<"vhost">>,
Username = <<"username">>,
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(
?UTIL_MOD:token_with_scope_alias_in_claim_field(Alias, [<<"unrelated">>]), Username), Jwk),
?UTIL_MOD:token_with_scope_alias_in_claim_field(Alias, [<<"unrelated">>]),
Username), Jwk),
{ok, AuthUser} = user_login_authentication(Username, [{password, Token}]),
assert_vhost_access_granted(AuthUser, VHost),
@ -904,12 +916,12 @@ test_successful_access_with_a_token_that_uses_single_scope_alias_in_extra_scope_
test_successful_access_with_a_token_that_uses_multiple_scope_aliases_in_extra_scope_source_field(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
application:set_env(rabbitmq_auth_backend_oauth2, extra_scopes_source, <<"claims">>),
set_env(key_config, UaaEnv),
set_env(extra_scopes_source, <<"claims">>),
Role1 = <<"client-aliases-1">>,
Role2 = <<"client-aliases-2">>,
Role3 = <<"client-aliases-3">>,
application:set_env(rabbitmq_auth_backend_oauth2, scope_aliases, #{
set_env(scope_aliases, #{
Role1 => [
<<"rabbitmq.configure:vhost/one">>
],
@ -927,7 +939,8 @@ test_successful_access_with_a_token_that_uses_multiple_scope_aliases_in_extra_sc
Username = <<"username">>,
Claims = [Role1, Role2, Role3],
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(
?UTIL_MOD:token_with_scope_alias_in_claim_field(Claims, [<<"unrelated">>]), Username), Jwk),
?UTIL_MOD:token_with_scope_alias_in_claim_field(Claims, [<<"unrelated">>]),
Username), Jwk),
{ok, AuthUser} = user_login_authentication(Username, [{password, Token}]),
assert_vhost_access_granted(AuthUser, VHost),
@ -948,11 +961,11 @@ test_successful_access_with_a_token_that_uses_multiple_scope_aliases_in_extra_sc
test_unsuccessful_access_with_a_token_that_uses_missing_scope_alias_in_extra_scope_source_field(_) ->
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
application:set_env(rabbitmq_auth_backend_oauth2, extra_scopes_source, <<"claims">>),
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
set_env(key_config, UaaEnv),
set_env(extra_scopes_source, <<"claims">>),
set_env(resource_server_id, <<"rabbitmq">>),
Alias = <<"client-alias-11">>,
application:set_env(rabbitmq_auth_backend_oauth2, scope_aliases, #{
set_env(scope_aliases, #{
<<"non-existent-client-alias-9238923789">> => [
<<"rabbitmq.configure:vhost/one">>,
<<"rabbitmq.write:vhost/two">>,
@ -965,7 +978,8 @@ test_unsuccessful_access_with_a_token_that_uses_missing_scope_alias_in_extra_sco
VHost = <<"vhost">>,
Username = <<"username">>,
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(
?UTIL_MOD:token_with_scope_alias_in_claim_field(Alias, [<<"unrelated">>]), Username), Jwk),
?UTIL_MOD:token_with_scope_alias_in_claim_field(Alias, [<<"unrelated">>]),
Username), Jwk),
{ok, AuthUser} = user_login_authentication(Username, [{password, Token}]),
assert_vhost_access_denied(AuthUser, VHost),
@ -985,38 +999,40 @@ test_unsuccessful_access_with_a_token_that_uses_missing_scope_alias_in_extra_sco
test_unsuccessful_access_with_a_bogus_token(_) ->
Username = <<"username">>,
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
set_env(resource_server_id, <<"rabbitmq">>),
Jwk0 = ?UTIL_MOD:fixture_jwk(),
Jwk = Jwk0#{<<"k">> => <<"bm90b2tlbmtleQ">>},
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
?assertMatch({refused, _, _},
user_login_authentication(Username, [{password, <<"not a token">>}])).
?assertMatch({refused, _, _}, user_login_authentication(Username,
[{password, <<"not a token">>}])).
unsuccessful_access_without_scopes(_) ->
Username = <<"username">>,
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
set_env(resource_server_id, <<"rabbitmq">>),
Jwk = ?UTIL_MOD:fixture_jwk(),
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(?UTIL_MOD:token_without_scopes(), Username), Jwk),
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(
?UTIL_MOD:token_without_scopes(), Username), Jwk),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
{ok, #auth_user{username = Username, tags = [], impl = _CredentialsFun } = AuthUser} =
user_login_authentication(Username, [{password, Token}]),
{ok, #auth_user{username = Username, tags = [], impl = _CredentialsFun }
= AuthUser} = user_login_authentication(Username, [{password, Token}]),
assert_vhost_access_denied(AuthUser, <<"vhost">>).
test_restricted_vhost_access_with_a_valid_token(_) ->
Username = <<"username">>,
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
set_env(resource_server_id, <<"rabbitmq">>),
Jwk = ?UTIL_MOD:fixture_jwk(),
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk),
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(
?UTIL_MOD:fixture_token(), Username), Jwk),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
%% this user can authenticate successfully and access certain vhosts
{ok, #auth_user{username = Username, tags = []} = User} =
@ -1028,12 +1044,13 @@ test_restricted_vhost_access_with_a_valid_token(_) ->
test_insufficient_permissions_in_a_valid_token(_) ->
VHost = <<"vhost">>,
Username = <<"username">>,
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
set_env(resource_server_id, <<"rabbitmq">>),
Jwk = ?UTIL_MOD:fixture_jwk(),
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk),
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(
?UTIL_MOD:fixture_token(), Username), Jwk),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
set_env(key_config, UaaEnv),
{ok, #auth_user{username = Username} = User} =
user_login_authentication(Username, [{password, Token}]),
@ -1041,15 +1058,16 @@ test_insufficient_permissions_in_a_valid_token(_) ->
%% access to these resources is not granted
assert_resource_access_denied(User, VHost, <<"foo1">>, configure),
assert_resource_access_denied(User, VHost, <<"bar">>, write),
assert_topic_access_refused(User, VHost, <<"bar">>, read, #{routing_key => <<"foo/#">>}).
assert_topic_access_refused(User, VHost, <<"bar">>, read,
#{routing_key => <<"foo/#">>}).
test_invalid_signature(_) ->
Username = <<"username">>,
Jwk = ?UTIL_MOD:fixture_jwk(),
WrongJwk = ?UTIL_MOD:fixture_jwk("wrong", <<"GawgguFyGrWKav7AX4VKUg">>),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, WrongJwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
set_env(key_config, UaaEnv),
set_env(resource_server_id, <<"rabbitmq">>),
TokenData = ?UTIL_MOD:token_with_sub(?UTIL_MOD:expirable_token(), Username),
Token = ?UTIL_MOD:sign_token_hs(TokenData, Jwk),
?assertMatch({refused, _, [signature_invalid]},
@ -1060,8 +1078,8 @@ test_token_expiration(_) ->
Username = <<"username">>,
Jwk = ?UTIL_MOD:fixture_jwk(),
UaaEnv = [{signing_keys, #{<<"token-key">> => {map, Jwk}}}],
application:set_env(rabbitmq_auth_backend_oauth2, key_config, UaaEnv),
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
set_env(key_config, UaaEnv),
set_env(resource_server_id, <<"rabbitmq">>),
TokenData = ?UTIL_MOD:token_with_sub(?UTIL_MOD:expirable_token(), Username),
Token = ?UTIL_MOD:sign_token_hs(TokenData, Jwk),
{ok, #auth_user{username = Username} = User} =
@ -1076,7 +1094,8 @@ test_token_expiration(_) ->
?UTIL_MOD:wait_for_token_to_expire(),
#{<<"exp">> := Exp} = TokenData,
ExpectedError = "Provided JWT token has expired at timestamp " ++ integer_to_list(Exp) ++ " (validated at " ++ integer_to_list(Exp) ++ ")",
ExpectedError = "Provided JWT token has expired at timestamp " ++
integer_to_list(Exp) ++ " (validated at " ++ integer_to_list(Exp) ++ ")",
assert_resource_access_errors(ExpectedError, User, VHost, <<"foo">>, configure),
?assertMatch({refused, _, _},
@ -1086,9 +1105,14 @@ test_incorrect_kid(_) ->
AltKid = <<"other-token-key">>,
Username = <<"username">>,
Jwk = ?UTIL_MOD:fixture_jwk(),
application:set_env(rabbitmq_auth_backend_oauth2, resource_server_id, <<"rabbitmq">>),
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk, AltKid, true),
?assertMatch({refused, "Authentication using an OAuth 2/JWT token failed: ~tp", [{error,{missing_oauth_provider_attributes, [issuer]}}]},
set_env(resource_server_id,
<<"rabbitmq">>),
Token = ?UTIL_MOD:sign_token_hs(
?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk,
AltKid, true),
?assertMatch(
{refused, "Authentication using an OAuth 2/JWT token failed: ~tp",
[{error,{missing_oauth_provider_attributes, [issuer]}}]},
user_login_authentication(Username, #{password => Token})).
login_and_check_vhost_access(Username, Token, Vhost) ->
@ -1104,9 +1128,12 @@ test_command_json(Config) ->
'Elixir.RabbitMQ.CLI.Ctl.Commands.AddUaaKeyCommand':run(
[<<"token-key">>],
#{node => rabbit_ct_broker_helpers:get_node_config(Config, 0, nodename), json => Json}),
Token = ?UTIL_MOD:sign_token_hs(?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk),
rabbit_ct_broker_helpers:rpc(Config, 0, unit_SUITE, login_and_check_vhost_access, [Username, Token, none]).
#{node => rabbit_ct_broker_helpers:get_node_config(Config, 0, nodename),
json => Json}),
Token = ?UTIL_MOD:sign_token_hs(
?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk),
rabbit_ct_broker_helpers:rpc(Config, 0, unit_SUITE,
login_and_check_vhost_access, [Username, Token, none]).
test_username_from(_) ->
Pairs = [
@ -1143,7 +1170,8 @@ test_username_from(_) ->
lists:foreach(
fun(
{Comment, PreferredUsernameClaims, Token, ExpectedUsername}) ->
ActualUsername = rabbit_auth_backend_oauth2:username_from(PreferredUsernameClaims, Token),
ActualUsername = rabbit_auth_backend_oauth2:username_from(
PreferredUsernameClaims, Token),
?assertEqual(ExpectedUsername, ActualUsername, Comment)
end,
Pairs).
@ -1160,10 +1188,13 @@ test_command_pem_file(Config) ->
'Elixir.RabbitMQ.CLI.Ctl.Commands.AddUaaKeyCommand':run(
[<<"token-key">>],
#{node => rabbit_ct_broker_helpers:get_node_config(Config, 0, nodename), pem_file => PublicKeyFile}),
#{node => rabbit_ct_broker_helpers:get_node_config(
Config, 0, nodename), pem_file => PublicKeyFile}),
Token = ?UTIL_MOD:sign_token_rsa(?UTIL_MOD:fixture_token(), Jwk, <<"token-key">>),
rabbit_ct_broker_helpers:rpc(Config, 0, unit_SUITE, login_and_check_vhost_access, [Username, Token, none]).
Token = ?UTIL_MOD:sign_token_rsa(?UTIL_MOD:fixture_token(),
Jwk, <<"token-key">>),
rabbit_ct_broker_helpers:rpc(Config, 0, unit_SUITE,
login_and_check_vhost_access, [Username, Token, none]).
test_command_pem(Config) ->
@ -1176,10 +1207,13 @@ test_command_pem(Config) ->
'Elixir.RabbitMQ.CLI.Ctl.Commands.AddUaaKeyCommand':run(
[<<"token-key">>],
#{node => rabbit_ct_broker_helpers:get_node_config(Config, 0, nodename), pem => Pem}),
#{node => rabbit_ct_broker_helpers:get_node_config(
Config, 0, nodename), pem => Pem}),
Token = ?UTIL_MOD:sign_token_rsa(?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk, <<"token-key">>),
rabbit_ct_broker_helpers:rpc(Config, 0, unit_SUITE, login_and_check_vhost_access, [Username, Token, none]).
Token = ?UTIL_MOD:sign_token_rsa(?UTIL_MOD:token_with_sub(
?UTIL_MOD:fixture_token(), Username), Jwk, <<"token-key">>),
rabbit_ct_broker_helpers:rpc(Config, 0, unit_SUITE,
login_and_check_vhost_access, [Username, Token, none]).
test_command_pem_no_kid(Config) ->
Username = <<"username">>,
@ -1191,10 +1225,13 @@ test_command_pem_no_kid(Config) ->
'Elixir.RabbitMQ.CLI.Ctl.Commands.AddUaaKeyCommand':run(
[<<"token-key">>],
#{node => rabbit_ct_broker_helpers:get_node_config(Config, 0, nodename), pem => Pem}),
#{node => rabbit_ct_broker_helpers:get_node_config(Config, 0, nodename),
pem => Pem}),
Token = ?UTIL_MOD:sign_token_no_kid(?UTIL_MOD:token_with_sub(?UTIL_MOD:fixture_token(), Username), Jwk),
rabbit_ct_broker_helpers:rpc(Config, 0, unit_SUITE, login_and_check_vhost_access, [Username, Token, none]).
Token = ?UTIL_MOD:sign_token_no_kid(?UTIL_MOD:token_with_sub(
?UTIL_MOD:fixture_token(), Username), Jwk),
rabbit_ct_broker_helpers:rpc(Config, 0, unit_SUITE,
login_and_check_vhost_access, [Username, Token, none]).
filter_matching_scope_prefix_and_drop_it(_) ->
@ -1208,7 +1245,8 @@ filter_matching_scope_prefix_and_drop_it(_) ->
],
lists:map(
fun({ScopePrefix, Src, Dest}) ->
Dest = rabbit_oauth2_scope:filter_matching_scope_prefix_and_drop_it(Src, ScopePrefix)
Dest = rabbit_oauth2_scope:filter_matching_scope_prefix_and_drop_it(
Src, ScopePrefix)
end,
Examples).
@ -1233,7 +1271,7 @@ normalize_token_scopes_with_scope_prefix(_) ->
],
lists:map(fun({ ScopePrefix, Token0, ExpectedScopes}) ->
ResourceServer0 = resource_server:new_resource_server(?RESOURCE_SERVER_ID),
ResourceServer0 = new_resource_server(?RESOURCE_SERVER_ID),
ResourceServer = ResourceServer0#resource_server {
scope_prefix = ScopePrefix
},
@ -1242,7 +1280,7 @@ normalize_token_scopes_with_scope_prefix(_) ->
end, Scenarios).
normalize_token_scope_from_space_separated_list_in_scope_claim(_) ->
ResourceServer = resource_server:new_resource_server(?RESOURCE_SERVER_ID),
ResourceServer = new_resource_server(?RESOURCE_SERVER_ID),
Token0 = #{
?SCOPE_JWT_FIELD => <<"foo rabbitmq.bar bar.foo one.two foobar rabbitmq.other.third">>
},
@ -1250,7 +1288,7 @@ normalize_token_scope_from_space_separated_list_in_scope_claim(_) ->
?assertEqual([<<"bar">>, <<"other.third">>], uaa_jwt:get_scope(Token)).
normalize_token_scope_without_scope_claim(_) ->
ResourceServer = resource_server:new_resource_server(?RESOURCE_SERVER_ID),
ResourceServer = new_resource_server(?RESOURCE_SERVER_ID),
Token0 = #{ },
?assertEqual([], uaa_jwt:get_scope(normalize_token_scope(ResourceServer, Token0))).
@ -1258,6 +1296,9 @@ normalize_token_scope_without_scope_claim(_) ->
%% Helpers
%%
set_env(Par, Var) ->
application:set_env(rabbitmq_auth_backend_oauth2, Par, Var).
assert_vhost_access_granted(AuthUser, VHost) ->
assert_vhost_access_response(true, AuthUser, VHost).
@ -1269,45 +1310,63 @@ assert_vhost_access_response(ExpectedResult, AuthUser, VHost) ->
check_vhost_access(AuthUser, VHost, none)).
assert_resource_access_granted(AuthUser, VHost, ResourceName, PermissionKind) ->
assert_resource_access_response(true, AuthUser, VHost, ResourceName, PermissionKind).
assert_resource_access_response(true, AuthUser, VHost, ResourceName,
PermissionKind).
assert_resource_access_denied(AuthUser, VHost, ResourceName, PermissionKind) ->
assert_resource_access_response(false, AuthUser, VHost, ResourceName, PermissionKind).
assert_resource_access_response(false, AuthUser, VHost, ResourceName,
PermissionKind).
assert_resource_access_errors(ExpectedError, AuthUser, VHost, ResourceName, PermissionKind) ->
assert_resource_access_response({error, ExpectedError}, AuthUser, VHost, ResourceName, PermissionKind).
assert_resource_access_errors(ExpectedError, AuthUser, VHost, ResourceName,
PermissionKind) ->
assert_resource_access_response({error, ExpectedError}, AuthUser, VHost,
ResourceName, PermissionKind).
assert_resource_access_response(ExpectedResult, AuthUser, VHost, ResourceName, PermissionKind) ->
assert_resource_access_response(ExpectedResult, AuthUser, VHost, ResourceName,
PermissionKind) ->
?assertEqual(ExpectedResult,
rabbit_auth_backend_oauth2:check_resource_access(
AuthUser,
rabbit_misc:r(VHost, queue, ResourceName),
PermissionKind, #{})).
assert_resource_access_granted(AuthUser, VHost, ResourceKind, ResourceName, PermissionKind) ->
assert_resource_access_response(true, AuthUser, VHost, ResourceKind, ResourceName, PermissionKind).
assert_resource_access_granted(AuthUser, VHost, ResourceKind, ResourceName,
PermissionKind) ->
assert_resource_access_response(true, AuthUser, VHost, ResourceKind,
ResourceName, PermissionKind).
assert_resource_access_denied(AuthUser, VHost, ResourceKind, ResourceName, PermissionKind) ->
assert_resource_access_response(false, AuthUser, VHost, ResourceKind, ResourceName, PermissionKind).
assert_resource_access_denied(AuthUser, VHost, ResourceKind, ResourceName,
PermissionKind) ->
assert_resource_access_response(false, AuthUser, VHost, ResourceKind,
ResourceName, PermissionKind).
assert_resource_access_errors(ExpectedError, AuthUser, VHost, ResourceKind, ResourceName, PermissionKind) ->
assert_resource_access_response({error, ExpectedError}, AuthUser, VHost, ResourceKind, ResourceName, PermissionKind).
assert_resource_access_errors(ExpectedError, AuthUser, VHost, ResourceKind,
ResourceName, PermissionKind) ->
assert_resource_access_response({error, ExpectedError}, AuthUser, VHost,
ResourceKind, ResourceName, PermissionKind).
assert_resource_access_response(ExpectedResult, AuthUser, VHost, ResourceKind, ResourceName, PermissionKind) ->
assert_resource_access_response(ExpectedResult, AuthUser, VHost, ResourceKind,
ResourceName, PermissionKind) ->
?assertEqual(ExpectedResult,
rabbit_auth_backend_oauth2:check_resource_access(
AuthUser,
rabbit_misc:r(VHost, ResourceKind, ResourceName),
PermissionKind, #{})).
assert_topic_access_granted(AuthUser, VHost, ResourceName, PermissionKind, AuthContext) ->
assert_topic_access_response(true, AuthUser, VHost, ResourceName, PermissionKind, AuthContext).
assert_topic_access_granted(AuthUser, VHost, ResourceName, PermissionKind,
AuthContext) ->
assert_topic_access_response(true, AuthUser, VHost, ResourceName,
PermissionKind, AuthContext).
assert_topic_access_refused(AuthUser, VHost, ResourceName, PermissionKind, AuthContext) ->
assert_topic_access_response(false, AuthUser, VHost, ResourceName, PermissionKind, AuthContext).
assert_topic_access_refused(AuthUser, VHost, ResourceName, PermissionKind,
AuthContext) ->
assert_topic_access_response(false, AuthUser, VHost, ResourceName,
PermissionKind, AuthContext).
assert_topic_access_response(ExpectedResult, AuthUser, VHost, ResourceName, PermissionKind, AuthContext) ->
?assertEqual(ExpectedResult, rabbit_auth_backend_oauth2:check_topic_access(
assert_topic_access_response(ExpectedResult, AuthUser, VHost, ResourceName,
PermissionKind, AuthContext) ->
?assertEqual(ExpectedResult,
rabbit_auth_backend_oauth2:check_topic_access(
AuthUser,
#resource{virtual_host = VHost,
kind = topic,