emqx_authn_pgsql_SUITE.erl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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].
  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_common_test_helpers: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. %%------------------------------------------------------------------------------
  206. %% Helpers
  207. %%------------------------------------------------------------------------------
  208. raw_pgsql_auth_config() ->
  209. #{
  210. mechanism => <<"password-based">>,
  211. password_hash_algorithm => #{name => <<"plain">>,
  212. salt_position => <<"suffix">>},
  213. enable => <<"true">>,
  214. backend => <<"postgresql">>,
  215. database => <<"mqtt">>,
  216. username => <<"root">>,
  217. password => <<"public">>,
  218. query => <<"SELECT password_hash, salt, is_superuser_str as is_superuser
  219. FROM users where username = ${username} LIMIT 1">>,
  220. server => pgsql_server()
  221. }.
  222. user_seeds() ->
  223. [#{data => #{
  224. username => "plain",
  225. password_hash => "plainsalt",
  226. salt => "salt",
  227. is_superuser_str => "1"
  228. },
  229. credentials => #{
  230. username => <<"plain">>,
  231. password => <<"plain">>},
  232. config_params => #{},
  233. result => {ok,#{is_superuser => true}}
  234. },
  235. #{data => #{
  236. username => "md5",
  237. password_hash => "9b4d0c43d206d48279e69b9ad7132e22",
  238. salt => "salt",
  239. is_superuser_str => "0"
  240. },
  241. credentials => #{
  242. username => <<"md5">>,
  243. password => <<"md5">>
  244. },
  245. config_params => #{
  246. password_hash_algorithm => #{name => <<"md5">>,
  247. salt_position => <<"suffix">>}
  248. },
  249. result => {ok,#{is_superuser => false}}
  250. },
  251. #{data => #{
  252. username => "sha256",
  253. password_hash => "ac63a624e7074776d677dd61a003b8c803eb11db004d0ec6ae032a5d7c9c5caf",
  254. salt => "salt",
  255. is_superuser_int => 1
  256. },
  257. credentials => #{
  258. clientid => <<"sha256">>,
  259. password => <<"sha256">>
  260. },
  261. config_params => #{
  262. query => <<"SELECT password_hash, salt, is_superuser_int as is_superuser
  263. FROM users where username = ${clientid} LIMIT 1">>,
  264. password_hash_algorithm => #{name => <<"sha256">>,
  265. salt_position => <<"prefix">>}
  266. },
  267. result => {ok,#{is_superuser => true}}
  268. },
  269. #{data => #{
  270. username => <<"bcrypt">>,
  271. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  272. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  273. is_superuser_int => 0
  274. },
  275. credentials => #{
  276. username => <<"bcrypt">>,
  277. password => <<"bcrypt">>
  278. },
  279. config_params => #{
  280. query => <<"SELECT password_hash, salt, is_superuser_int as is_superuser
  281. FROM users where username = ${username} LIMIT 1">>,
  282. password_hash_algorithm => #{name => <<"bcrypt">>}
  283. },
  284. result => {ok,#{is_superuser => false}}
  285. },
  286. #{data => #{
  287. username => <<"bcrypt0">>,
  288. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  289. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  290. is_superuser_str => "0"
  291. },
  292. credentials => #{
  293. username => <<"bcrypt0">>,
  294. password => <<"bcrypt">>
  295. },
  296. config_params => #{
  297. % clientid variable & username credentials
  298. query => <<"SELECT password_hash, salt, is_superuser_int as is_superuser
  299. FROM users where username = ${clientid} LIMIT 1">>,
  300. password_hash_algorithm => #{name => <<"bcrypt">>}
  301. },
  302. result => {error,not_authorized}
  303. },
  304. #{data => #{
  305. username => <<"bcrypt1">>,
  306. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  307. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  308. is_superuser_str => "0"
  309. },
  310. credentials => #{
  311. username => <<"bcrypt1">>,
  312. password => <<"bcrypt">>
  313. },
  314. config_params => #{
  315. % Bad keys in query
  316. query => <<"SELECT 1 AS unknown_field
  317. FROM users where username = ${username} LIMIT 1">>,
  318. password_hash_algorithm => #{name => <<"bcrypt">>}
  319. },
  320. result => {error,not_authorized}
  321. },
  322. #{data => #{
  323. username => <<"bcrypt2">>,
  324. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  325. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  326. is_superuser => "0"
  327. },
  328. credentials => #{
  329. username => <<"bcrypt2">>,
  330. % Wrong password
  331. password => <<"wrongpass">>
  332. },
  333. config_params => #{
  334. password_hash_algorithm => #{name => <<"bcrypt">>}
  335. },
  336. result => {error,bad_username_or_password}
  337. }
  338. ].
  339. init_seeds() ->
  340. ok = drop_seeds(),
  341. {ok, _, _} = q("CREATE TABLE users(
  342. username varchar(255),
  343. password_hash varchar(255),
  344. salt varchar(255),
  345. is_superuser_str varchar(255),
  346. is_superuser_int smallint,
  347. is_superuser_bool boolean)"),
  348. lists:foreach(
  349. fun(#{data := Values}) ->
  350. ok = create_user(Values)
  351. end,
  352. user_seeds()).
  353. create_user(Values) ->
  354. Fields = [username, password_hash, salt, is_superuser_str, is_superuser_int, is_superuser_bool],
  355. InsertQuery = "INSERT INTO users(username, password_hash, salt,"
  356. "is_superuser_str, is_superuser_int, is_superuser_bool) "
  357. "VALUES($1, $2, $3, $4, $5, $6)",
  358. Params = [maps:get(F, Values, null) || F <- Fields],
  359. {ok, 1} = q(InsertQuery, Params),
  360. ok.
  361. q(Sql) ->
  362. emqx_resource:query(
  363. ?PGSQL_RESOURCE,
  364. {query, Sql}).
  365. q(Sql, Params) ->
  366. emqx_resource:query(
  367. ?PGSQL_RESOURCE,
  368. {query, Sql, Params}).
  369. drop_seeds() ->
  370. {ok, _, _} = q("DROP TABLE IF EXISTS users"),
  371. ok.
  372. pgsql_server() ->
  373. iolist_to_binary(
  374. io_lib:format(
  375. "~s:~b",
  376. [?PGSQL_HOST, ?PGSQL_PORT])).
  377. pgsql_config() ->
  378. #{auto_reconnect => true,
  379. database => <<"mqtt">>,
  380. username => <<"root">>,
  381. password => <<"public">>,
  382. pool_size => 8,
  383. server => {?PGSQL_HOST, ?PGSQL_PORT},
  384. ssl => #{enable => false}
  385. }.
  386. start_apps(Apps) ->
  387. lists:foreach(fun application:ensure_all_started/1, Apps).
  388. stop_apps(Apps) ->
  389. lists:foreach(fun application:stop/1, Apps).