emqx_authn_pgsql_SUITE.erl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020-2021 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("epgsql/include/epgsql.hrl").
  23. -include_lib("emqx/include/emqx_placeholder.hrl").
  24. -define(PGSQL_HOST, "pgsql").
  25. -define(PGSQL_PORT, 5432).
  26. -define(PGSQL_RESOURCE, <<"emqx_authn_pgsql_SUITE">>).
  27. -define(PATH, [authentication]).
  28. all() ->
  29. [{group, require_seeds}, t_create, t_create_invalid, t_parse_query].
  30. groups() ->
  31. [{require_seeds, [], [t_authenticate, t_update, t_destroy, t_is_superuser]}].
  32. init_per_testcase(_, Config) ->
  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. case emqx_authn_test_lib:is_tcp_server_available(?PGSQL_HOST, ?PGSQL_PORT) of
  46. true ->
  47. ok = emqx_common_test_helpers:start_apps([emqx_authn]),
  48. ok = start_apps([emqx_resource, emqx_connector]),
  49. {ok, _} = emqx_resource:create_local(
  50. ?PGSQL_RESOURCE,
  51. emqx_connector_pgsql,
  52. pgsql_config()),
  53. Config;
  54. false ->
  55. {skip, no_pgsql}
  56. end.
  57. end_per_suite(_Config) ->
  58. emqx_authn_test_lib:delete_authenticators(
  59. [authentication],
  60. ?GLOBAL),
  61. ok = emqx_resource:remove_local(?PGSQL_RESOURCE),
  62. ok = stop_apps([emqx_resource, emqx_connector]),
  63. ok = emqx_common_test_helpers:stop_apps([emqx_authn]).
  64. %%------------------------------------------------------------------------------
  65. %% Tests
  66. %%------------------------------------------------------------------------------
  67. t_create(_Config) ->
  68. AuthConfig = raw_pgsql_auth_config(),
  69. {ok, _} = emqx:update_config(
  70. ?PATH,
  71. {create_authenticator, ?GLOBAL, AuthConfig}),
  72. {ok, [#{provider := emqx_authn_pgsql}]} = emqx_authentication:list_authenticators(?GLOBAL).
  73. t_create_invalid(_Config) ->
  74. AuthConfig = raw_pgsql_auth_config(),
  75. InvalidConfigs =
  76. [
  77. maps:without([server], AuthConfig),
  78. AuthConfig#{server => <<"unknownhost:3333">>},
  79. AuthConfig#{password => <<"wrongpass">>},
  80. AuthConfig#{database => <<"wrongdatabase">>}
  81. ],
  82. lists:foreach(
  83. fun(Config) ->
  84. {error, _} = emqx:update_config(
  85. ?PATH,
  86. {create_authenticator, ?GLOBAL, Config}),
  87. {ok, []} = emqx_authentication:list_authenticators(?GLOBAL)
  88. end,
  89. InvalidConfigs).
  90. t_authenticate(_Config) ->
  91. ok = lists:foreach(
  92. fun(Sample) ->
  93. ct:pal("test_user_auth sample: ~p", [Sample]),
  94. test_user_auth(Sample)
  95. end,
  96. user_seeds()).
  97. test_user_auth(#{credentials := Credentials0,
  98. config_params := SpecificConfgParams,
  99. result := Result}) ->
  100. AuthConfig = maps:merge(raw_pgsql_auth_config(), SpecificConfgParams),
  101. {ok, _} = emqx:update_config(
  102. ?PATH,
  103. {create_authenticator, ?GLOBAL, AuthConfig}),
  104. Credentials = Credentials0#{
  105. listener => 'tcp:default',
  106. protocol => mqtt
  107. },
  108. ?assertEqual(Result, emqx_access_control:authenticate(Credentials)),
  109. emqx_authn_test_lib:delete_authenticators(
  110. [authentication],
  111. ?GLOBAL).
  112. t_destroy(_Config) ->
  113. AuthConfig = raw_pgsql_auth_config(),
  114. {ok, _} = emqx:update_config(
  115. ?PATH,
  116. {create_authenticator, ?GLOBAL, AuthConfig}),
  117. {ok, [#{provider := emqx_authn_pgsql, state := State}]}
  118. = emqx_authentication:list_authenticators(?GLOBAL),
  119. {ok, _} = emqx_authn_pgsql:authenticate(
  120. #{username => <<"plain">>,
  121. password => <<"plain">>
  122. },
  123. State),
  124. emqx_authn_test_lib:delete_authenticators(
  125. [authentication],
  126. ?GLOBAL),
  127. % Authenticator should not be usable anymore
  128. ?assertException(
  129. error,
  130. _,
  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 wrong_table where username = ${username} LIMIT 1">>},
  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 => <<"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 => <<"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 => <<"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 => <<"bcrypt">>,
  291. salt_position => <<"suffix">> % should be ignored
  292. },
  293. result => {ok,#{is_superuser => false}}
  294. },
  295. #{data => #{
  296. username => <<"bcrypt0">>,
  297. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  298. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  299. is_superuser_str => "0"
  300. },
  301. credentials => #{
  302. username => <<"bcrypt0">>,
  303. password => <<"bcrypt">>
  304. },
  305. config_params => #{
  306. % clientid variable & username credentials
  307. query => <<"SELECT password_hash, salt, is_superuser_int as is_superuser
  308. FROM users where username = ${clientid} LIMIT 1">>,
  309. password_hash_algorithm => <<"bcrypt">>,
  310. salt_position => <<"suffix">>
  311. },
  312. result => {error,not_authorized}
  313. },
  314. #{data => #{
  315. username => <<"bcrypt1">>,
  316. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  317. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  318. is_superuser_str => "0"
  319. },
  320. credentials => #{
  321. username => <<"bcrypt1">>,
  322. password => <<"bcrypt">>
  323. },
  324. config_params => #{
  325. % Bad keys in query
  326. query => <<"SELECT 1 AS unknown_field
  327. FROM users where username = ${username} LIMIT 1">>,
  328. password_hash_algorithm => <<"bcrypt">>,
  329. salt_position => <<"suffix">>
  330. },
  331. result => {error,not_authorized}
  332. },
  333. #{data => #{
  334. username => <<"bcrypt2">>,
  335. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  336. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  337. is_superuser => "0"
  338. },
  339. credentials => #{
  340. username => <<"bcrypt2">>,
  341. % Wrong password
  342. password => <<"wrongpass">>
  343. },
  344. config_params => #{
  345. password_hash_algorithm => <<"bcrypt">>,
  346. salt_position => <<"suffix">>
  347. },
  348. result => {error,bad_username_or_password}
  349. }
  350. ].
  351. init_seeds() ->
  352. ok = drop_seeds(),
  353. {ok, _, _} = q("CREATE TABLE users(
  354. username varchar(255),
  355. password_hash varchar(255),
  356. salt varchar(255),
  357. is_superuser_str varchar(255),
  358. is_superuser_int smallint,
  359. is_superuser_bool boolean)"),
  360. lists:foreach(
  361. fun(#{data := Values}) ->
  362. ok = create_user(Values)
  363. end,
  364. user_seeds()).
  365. create_user(Values) ->
  366. Fields = [username, password_hash, salt, is_superuser_str, is_superuser_int, is_superuser_bool],
  367. InsertQuery = "INSERT INTO users(username, password_hash, salt,"
  368. "is_superuser_str, is_superuser_int, is_superuser_bool) "
  369. "VALUES($1, $2, $3, $4, $5, $6)",
  370. Params = [maps:get(F, Values, null) || F <- Fields],
  371. {ok, 1} = q(InsertQuery, Params),
  372. ok.
  373. q(Sql) ->
  374. emqx_resource:query(
  375. ?PGSQL_RESOURCE,
  376. {sql, Sql}).
  377. q(Sql, Params) ->
  378. emqx_resource:query(
  379. ?PGSQL_RESOURCE,
  380. {sql, Sql, Params}).
  381. drop_seeds() ->
  382. {ok, _, _} = q("DROP TABLE IF EXISTS users"),
  383. ok.
  384. pgsql_server() ->
  385. iolist_to_binary(
  386. io_lib:format(
  387. "~s:~b",
  388. [?PGSQL_HOST, ?PGSQL_PORT])).
  389. pgsql_config() ->
  390. #{auto_reconnect => true,
  391. database => <<"mqtt">>,
  392. username => <<"root">>,
  393. password => <<"public">>,
  394. pool_size => 8,
  395. server => {?PGSQL_HOST, ?PGSQL_PORT},
  396. ssl => #{enable => false}
  397. }.
  398. start_apps(Apps) ->
  399. lists:foreach(fun application:ensure_all_started/1, Apps).
  400. stop_apps(Apps) ->
  401. lists:foreach(fun application:stop/1, Apps).