emqx_authn_pgsql_SUITE.erl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020-2022 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_authn_pgsql_SUITE).
  17. -compile(nowarn_export_all).
  18. -compile(export_all).
  19. -include("emqx_authn.hrl").
  20. -include_lib("eunit/include/eunit.hrl").
  21. -include_lib("common_test/include/ct.hrl").
  22. -include_lib("emqx/include/emqx_placeholder.hrl").
  23. -define(PGSQL_HOST, "pgsql").
  24. -define(PGSQL_PORT, 5432).
  25. -define(PGSQL_RESOURCE, <<"emqx_authn_pgsql_SUITE">>).
  26. -define(PATH, [authentication]).
  27. all() ->
  28. [{group, require_seeds}, t_create_invalid, t_parse_query].
  29. groups() ->
  30. [{require_seeds, [], [t_create, t_authenticate, t_update, t_destroy, t_is_superuser]}].
  31. init_per_testcase(_, Config) ->
  32. {ok, _} = emqx_cluster_rpc:start_link(node(), emqx_cluster_rpc, 1000),
  33. emqx_authentication:initialize_authentication(?GLOBAL, []),
  34. emqx_authn_test_lib:delete_authenticators(
  35. [authentication],
  36. ?GLOBAL),
  37. Config.
  38. init_per_group(require_seeds, Config) ->
  39. ok = init_seeds(),
  40. Config.
  41. end_per_group(require_seeds, Config) ->
  42. ok = drop_seeds(),
  43. Config.
  44. init_per_suite(Config) ->
  45. _ = application:load(emqx_conf),
  46. case emqx_authn_test_lib:is_tcp_server_available(?PGSQL_HOST, ?PGSQL_PORT) of
  47. true ->
  48. ok = emqx_common_test_helpers:start_apps([emqx_authn]),
  49. ok = start_apps([emqx_resource, emqx_connector]),
  50. {ok, _} = emqx_resource:create_local(
  51. ?PGSQL_RESOURCE,
  52. emqx_connector_pgsql,
  53. pgsql_config()),
  54. Config;
  55. false ->
  56. {skip, no_pgsql}
  57. end.
  58. end_per_suite(_Config) ->
  59. emqx_authn_test_lib:delete_authenticators(
  60. [authentication],
  61. ?GLOBAL),
  62. ok = emqx_resource:remove_local(?PGSQL_RESOURCE),
  63. ok = stop_apps([emqx_resource, emqx_connector]),
  64. ok = emqx_common_test_helpers:stop_apps([emqx_authn]).
  65. %%------------------------------------------------------------------------------
  66. %% Tests
  67. %%------------------------------------------------------------------------------
  68. t_create(_Config) ->
  69. AuthConfig = raw_pgsql_auth_config(),
  70. {ok, _} = emqx:update_config(
  71. ?PATH,
  72. {create_authenticator, ?GLOBAL, AuthConfig}),
  73. {ok, [#{provider := emqx_authn_pgsql}]} = emqx_authentication:list_authenticators(?GLOBAL).
  74. t_create_invalid(_Config) ->
  75. AuthConfig = raw_pgsql_auth_config(),
  76. InvalidConfigs =
  77. [
  78. maps:without([server], AuthConfig),
  79. AuthConfig#{server => <<"unknownhost:3333">>},
  80. AuthConfig#{password => <<"wrongpass">>},
  81. AuthConfig#{database => <<"wrongdatabase">>}
  82. ],
  83. lists:foreach(
  84. fun(Config) ->
  85. {error, _} = emqx:update_config(
  86. ?PATH,
  87. {create_authenticator, ?GLOBAL, Config}),
  88. {ok, []} = emqx_authentication:list_authenticators(?GLOBAL)
  89. end,
  90. InvalidConfigs).
  91. t_authenticate(_Config) ->
  92. ok = lists:foreach(
  93. fun(Sample) ->
  94. ct:pal("test_user_auth sample: ~p", [Sample]),
  95. test_user_auth(Sample)
  96. end,
  97. user_seeds()).
  98. test_user_auth(#{credentials := Credentials0,
  99. config_params := SpecificConfigParams,
  100. result := Result}) ->
  101. AuthConfig = maps:merge(raw_pgsql_auth_config(), SpecificConfigParams),
  102. {ok, _} = emqx:update_config(
  103. ?PATH,
  104. {create_authenticator, ?GLOBAL, AuthConfig}),
  105. Credentials = Credentials0#{
  106. listener => 'tcp:default',
  107. protocol => mqtt
  108. },
  109. ?assertEqual(Result, emqx_access_control:authenticate(Credentials)),
  110. emqx_authn_test_lib:delete_authenticators(
  111. [authentication],
  112. ?GLOBAL).
  113. t_destroy(_Config) ->
  114. AuthConfig = raw_pgsql_auth_config(),
  115. {ok, _} = emqx:update_config(
  116. ?PATH,
  117. {create_authenticator, ?GLOBAL, AuthConfig}),
  118. {ok, [#{provider := emqx_authn_pgsql, state := State}]}
  119. = emqx_authentication:list_authenticators(?GLOBAL),
  120. {ok, _} = emqx_authn_pgsql:authenticate(
  121. #{username => <<"plain">>,
  122. password => <<"plain">>
  123. },
  124. State),
  125. emqx_authn_test_lib:delete_authenticators(
  126. [authentication],
  127. ?GLOBAL),
  128. % Authenticator should not be usable anymore
  129. ?assertMatch(
  130. ignore,
  131. emqx_authn_pgsql:authenticate(
  132. #{username => <<"plain">>,
  133. password => <<"plain">>
  134. },
  135. State)).
  136. t_update(_Config) ->
  137. CorrectConfig = raw_pgsql_auth_config(),
  138. IncorrectConfig =
  139. CorrectConfig#{
  140. query => <<"SELECT password_hash, salt, is_superuser_str as is_superuser
  141. FROM users where username = ${username} LIMIT 0">>},
  142. {ok, _} = emqx:update_config(
  143. ?PATH,
  144. {create_authenticator, ?GLOBAL, IncorrectConfig}),
  145. {error, not_authorized} = emqx_access_control:authenticate(
  146. #{username => <<"plain">>,
  147. password => <<"plain">>,
  148. listener => 'tcp:default',
  149. protocol => mqtt
  150. }),
  151. % We update with config with correct query, provider should update and work properly
  152. {ok, _} = emqx:update_config(
  153. ?PATH,
  154. {update_authenticator, ?GLOBAL, <<"password-based:postgresql">>, CorrectConfig}),
  155. {ok,_} = emqx_access_control:authenticate(
  156. #{username => <<"plain">>,
  157. password => <<"plain">>,
  158. listener => 'tcp:default',
  159. protocol => mqtt
  160. }).
  161. t_is_superuser(_Config) ->
  162. Config = raw_pgsql_auth_config(),
  163. {ok, _} = emqx:update_config(
  164. ?PATH,
  165. {create_authenticator, ?GLOBAL, Config}),
  166. Checks = [
  167. {is_superuser_str, "0", false},
  168. {is_superuser_str, "", false},
  169. {is_superuser_str, null, false},
  170. {is_superuser_str, "1", true},
  171. {is_superuser_str, "val", true},
  172. {is_superuser_int, 0, false},
  173. {is_superuser_int, null, false},
  174. {is_superuser_int, 1, true},
  175. {is_superuser_int, 123, true},
  176. {is_superuser_bool, false, false},
  177. {is_superuser_bool, null, false},
  178. {is_superuser_bool, true, true}
  179. ],
  180. lists:foreach(fun test_is_superuser/1, Checks).
  181. test_is_superuser({Field, Value, ExpectedValue}) ->
  182. {ok, _} = q("DELETE FROM users"),
  183. UserData = #{
  184. username => "user",
  185. password_hash => "plainsalt",
  186. salt => "salt",
  187. Field => Value
  188. },
  189. ok = create_user(UserData),
  190. Query = "SELECT password_hash, salt, " ++ atom_to_list(Field) ++ " as is_superuser "
  191. "FROM users where username = ${username} LIMIT 1",
  192. Config = maps:put(query, Query, raw_pgsql_auth_config()),
  193. {ok, _} = emqx:update_config(
  194. ?PATH,
  195. {update_authenticator, ?GLOBAL, <<"password-based:postgresql">>, Config}),
  196. Credentials = #{
  197. listener => 'tcp:default',
  198. protocol => mqtt,
  199. username => <<"user">>,
  200. password => <<"plain">>
  201. },
  202. ?assertEqual(
  203. {ok, #{is_superuser => ExpectedValue}},
  204. emqx_access_control:authenticate(Credentials)).
  205. t_parse_query(_) ->
  206. Query1 = ?PH_USERNAME,
  207. ?assertEqual({<<"$1">>, [?PH_USERNAME]}, emqx_authn_pgsql:parse_query(Query1)),
  208. Query2 = <<?PH_USERNAME/binary, ", ", ?PH_CLIENTID/binary>>,
  209. ?assertEqual({<<"$1, $2">>, [?PH_USERNAME, ?PH_CLIENTID]},
  210. emqx_authn_pgsql:parse_query(Query2)),
  211. Query3 = <<"nomatch">>,
  212. ?assertEqual({<<"nomatch">>, []}, emqx_authn_pgsql:parse_query(Query3)).
  213. %%------------------------------------------------------------------------------
  214. %% Helpers
  215. %%------------------------------------------------------------------------------
  216. raw_pgsql_auth_config() ->
  217. #{
  218. mechanism => <<"password-based">>,
  219. password_hash_algorithm => #{name => <<"plain">>,
  220. salt_position => <<"suffix">>},
  221. enable => <<"true">>,
  222. backend => <<"postgresql">>,
  223. database => <<"mqtt">>,
  224. username => <<"root">>,
  225. password => <<"public">>,
  226. query => <<"SELECT password_hash, salt, is_superuser_str as is_superuser
  227. FROM users where username = ${username} LIMIT 1">>,
  228. server => pgsql_server()
  229. }.
  230. user_seeds() ->
  231. [#{data => #{
  232. username => "plain",
  233. password_hash => "plainsalt",
  234. salt => "salt",
  235. is_superuser_str => "1"
  236. },
  237. credentials => #{
  238. username => <<"plain">>,
  239. password => <<"plain">>},
  240. config_params => #{},
  241. result => {ok,#{is_superuser => true}}
  242. },
  243. #{data => #{
  244. username => "md5",
  245. password_hash => "9b4d0c43d206d48279e69b9ad7132e22",
  246. salt => "salt",
  247. is_superuser_str => "0"
  248. },
  249. credentials => #{
  250. username => <<"md5">>,
  251. password => <<"md5">>
  252. },
  253. config_params => #{
  254. password_hash_algorithm => #{name => <<"md5">>,
  255. salt_position => <<"suffix">>}
  256. },
  257. result => {ok,#{is_superuser => false}}
  258. },
  259. #{data => #{
  260. username => "sha256",
  261. password_hash => "ac63a624e7074776d677dd61a003b8c803eb11db004d0ec6ae032a5d7c9c5caf",
  262. salt => "salt",
  263. is_superuser_int => 1
  264. },
  265. credentials => #{
  266. clientid => <<"sha256">>,
  267. password => <<"sha256">>
  268. },
  269. config_params => #{
  270. query => <<"SELECT password_hash, salt, is_superuser_int as is_superuser
  271. FROM users where username = ${clientid} LIMIT 1">>,
  272. password_hash_algorithm => #{name => <<"sha256">>,
  273. salt_position => <<"prefix">>}
  274. },
  275. result => {ok,#{is_superuser => true}}
  276. },
  277. #{data => #{
  278. username => <<"bcrypt">>,
  279. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  280. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  281. is_superuser_int => 0
  282. },
  283. credentials => #{
  284. username => <<"bcrypt">>,
  285. password => <<"bcrypt">>
  286. },
  287. config_params => #{
  288. query => <<"SELECT password_hash, salt, is_superuser_int as is_superuser
  289. FROM users where username = ${username} LIMIT 1">>,
  290. password_hash_algorithm => #{name => <<"bcrypt">>}
  291. },
  292. result => {ok,#{is_superuser => false}}
  293. },
  294. #{data => #{
  295. username => <<"bcrypt0">>,
  296. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  297. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  298. is_superuser_str => "0"
  299. },
  300. credentials => #{
  301. username => <<"bcrypt0">>,
  302. password => <<"bcrypt">>
  303. },
  304. config_params => #{
  305. % clientid variable & username credentials
  306. query => <<"SELECT password_hash, salt, is_superuser_int as is_superuser
  307. FROM users where username = ${clientid} LIMIT 1">>,
  308. password_hash_algorithm => #{name => <<"bcrypt">>}
  309. },
  310. result => {error,not_authorized}
  311. },
  312. #{data => #{
  313. username => <<"bcrypt1">>,
  314. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  315. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  316. is_superuser_str => "0"
  317. },
  318. credentials => #{
  319. username => <<"bcrypt1">>,
  320. password => <<"bcrypt">>
  321. },
  322. config_params => #{
  323. % Bad keys in query
  324. query => <<"SELECT 1 AS unknown_field
  325. FROM users where username = ${username} LIMIT 1">>,
  326. password_hash_algorithm => #{name => <<"bcrypt">>}
  327. },
  328. result => {error,not_authorized}
  329. },
  330. #{data => #{
  331. username => <<"bcrypt2">>,
  332. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  333. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  334. is_superuser => "0"
  335. },
  336. credentials => #{
  337. username => <<"bcrypt2">>,
  338. % Wrong password
  339. password => <<"wrongpass">>
  340. },
  341. config_params => #{
  342. password_hash_algorithm => #{name => <<"bcrypt">>}
  343. },
  344. result => {error,bad_username_or_password}
  345. }
  346. ].
  347. init_seeds() ->
  348. ok = drop_seeds(),
  349. {ok, _, _} = q("CREATE TABLE users(
  350. username varchar(255),
  351. password_hash varchar(255),
  352. salt varchar(255),
  353. is_superuser_str varchar(255),
  354. is_superuser_int smallint,
  355. is_superuser_bool boolean)"),
  356. lists:foreach(
  357. fun(#{data := Values}) ->
  358. ok = create_user(Values)
  359. end,
  360. user_seeds()).
  361. create_user(Values) ->
  362. Fields = [username, password_hash, salt, is_superuser_str, is_superuser_int, is_superuser_bool],
  363. InsertQuery = "INSERT INTO users(username, password_hash, salt,"
  364. "is_superuser_str, is_superuser_int, is_superuser_bool) "
  365. "VALUES($1, $2, $3, $4, $5, $6)",
  366. Params = [maps:get(F, Values, null) || F <- Fields],
  367. {ok, 1} = q(InsertQuery, Params),
  368. ok.
  369. q(Sql) ->
  370. emqx_resource:query(
  371. ?PGSQL_RESOURCE,
  372. {query, Sql}).
  373. q(Sql, Params) ->
  374. emqx_resource:query(
  375. ?PGSQL_RESOURCE,
  376. {query, Sql, Params}).
  377. drop_seeds() ->
  378. {ok, _, _} = q("DROP TABLE IF EXISTS users"),
  379. ok.
  380. pgsql_server() ->
  381. iolist_to_binary(
  382. io_lib:format(
  383. "~s:~b",
  384. [?PGSQL_HOST, ?PGSQL_PORT])).
  385. pgsql_config() ->
  386. #{auto_reconnect => true,
  387. database => <<"mqtt">>,
  388. username => <<"root">>,
  389. password => <<"public">>,
  390. pool_size => 8,
  391. server => {?PGSQL_HOST, ?PGSQL_PORT},
  392. ssl => #{enable => false}
  393. }.
  394. start_apps(Apps) ->
  395. lists:foreach(fun application:ensure_all_started/1, Apps).
  396. stop_apps(Apps) ->
  397. lists:foreach(fun application:stop/1, Apps).