emqx_authn_postgresql_SUITE.erl 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020-2024 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_postgresql_SUITE).
  17. -compile(nowarn_export_all).
  18. -compile(export_all).
  19. -include_lib("../../emqx_postgresql/include/emqx_postgresql.hrl").
  20. -include_lib("emqx_auth/include/emqx_authn.hrl").
  21. -include_lib("eunit/include/eunit.hrl").
  22. -include_lib("common_test/include/ct.hrl").
  23. -define(PGSQL_HOST, "pgsql").
  24. -define(PGSQL_RESOURCE, <<"emqx_authn_postgresql_SUITE">>).
  25. -define(ResourceID, <<"password_based:postgresql">>).
  26. -define(PATH, [authentication]).
  27. -import(emqx_common_test_helpers, [on_exit/1]).
  28. all() ->
  29. AllTCs = emqx_common_test_helpers:all(?MODULE),
  30. TCs = AllTCs -- require_seeds_tests(),
  31. [
  32. {group, require_seeds}
  33. | TCs
  34. ].
  35. groups() ->
  36. [{require_seeds, [], require_seeds_tests()}].
  37. require_seeds_tests() ->
  38. [
  39. t_create,
  40. t_authenticate,
  41. t_authenticate_disabled_prepared_statements,
  42. t_update,
  43. t_destroy,
  44. t_is_superuser
  45. ].
  46. init_per_testcase(_, Config) ->
  47. emqx_authn_test_lib:delete_authenticators(
  48. [authentication],
  49. ?GLOBAL
  50. ),
  51. Config.
  52. end_per_testcase(_TestCase, _Config) ->
  53. emqx_common_test_helpers:call_janitor(),
  54. ok.
  55. init_per_group(require_seeds, Config) ->
  56. ok = init_seeds(),
  57. Config.
  58. end_per_group(require_seeds, Config) ->
  59. ok = drop_seeds(),
  60. Config.
  61. init_per_suite(Config) ->
  62. case emqx_common_test_helpers:is_tcp_server_available(?PGSQL_HOST, ?PGSQL_DEFAULT_PORT) of
  63. true ->
  64. Apps = emqx_cth_suite:start([emqx, emqx_conf, emqx_auth, emqx_auth_postgresql], #{
  65. work_dir => ?config(priv_dir, Config)
  66. }),
  67. {ok, _} = emqx_resource:create_local(
  68. postgresql,
  69. ?PGSQL_RESOURCE,
  70. ?AUTHN_RESOURCE_GROUP,
  71. emqx_postgresql,
  72. pgsql_config(),
  73. #{}
  74. ),
  75. [{apps, Apps} | Config];
  76. false ->
  77. case os:getenv("IS_CI") of
  78. "yes" ->
  79. throw(no_postgres);
  80. _ ->
  81. {skip, no_postgres}
  82. end
  83. end.
  84. end_per_suite(Config) ->
  85. emqx_authn_test_lib:delete_authenticators(
  86. [authentication],
  87. ?GLOBAL
  88. ),
  89. ok = emqx_resource:remove_local(?PGSQL_RESOURCE),
  90. ok = emqx_cth_suite:stop(?config(apps, Config)),
  91. ok.
  92. %%------------------------------------------------------------------------------
  93. %% Tests
  94. %%------------------------------------------------------------------------------
  95. t_create(_Config) ->
  96. AuthConfig = raw_pgsql_auth_config(),
  97. {ok, _} = emqx:update_config(
  98. ?PATH,
  99. {create_authenticator, ?GLOBAL, AuthConfig}
  100. ),
  101. {ok, [#{provider := emqx_authn_postgresql}]} = emqx_authn_chains:list_authenticators(?GLOBAL),
  102. emqx_authn_test_lib:delete_config(?ResourceID).
  103. %% invalid config which does not pass the schema check should result in an error
  104. t_update_with_invalid_config(_Config) ->
  105. AuthConfig = raw_pgsql_auth_config(),
  106. BadConfig = maps:without([<<"server">>], AuthConfig),
  107. ?assertMatch(
  108. {error, #{
  109. kind := validation_error,
  110. matched_type := "authn:postgresql",
  111. path := "authentication.1.server",
  112. reason := required_field
  113. }},
  114. emqx:update_config(
  115. ?PATH,
  116. {create_authenticator, ?GLOBAL, BadConfig}
  117. )
  118. ),
  119. ok.
  120. %% bad config values may cause connection failure, but should still be able to update
  121. t_update_with_bad_config_value(_Config) ->
  122. AuthConfig = raw_pgsql_auth_config(),
  123. InvalidConfigs =
  124. [
  125. AuthConfig#{<<"server">> => <<"unknownhost:3333">>},
  126. AuthConfig#{<<"password">> => <<"wrongpass">>},
  127. AuthConfig#{<<"database">> => <<"wrongdatabase">>}
  128. ],
  129. lists:foreach(
  130. fun(Config) ->
  131. {ok, _} = emqx:update_config(
  132. ?PATH,
  133. {create_authenticator, ?GLOBAL, Config}
  134. ),
  135. emqx_authn_test_lib:delete_config(?ResourceID),
  136. ?assertEqual(
  137. {error, {not_found, {chain, ?GLOBAL}}},
  138. emqx_authn_chains:list_authenticators(?GLOBAL)
  139. )
  140. end,
  141. InvalidConfigs
  142. ).
  143. t_authenticate(_Config) ->
  144. ok = lists:foreach(
  145. fun(Sample) ->
  146. ct:pal("test_user_auth sample: ~p", [Sample]),
  147. test_user_auth(Sample)
  148. end,
  149. user_seeds()
  150. ).
  151. test_user_auth(#{
  152. credentials := Credentials0,
  153. config_params := SpecificConfigParams,
  154. result := Result
  155. }) ->
  156. AuthConfig = maps:merge(raw_pgsql_auth_config(), SpecificConfigParams),
  157. {ok, _} = emqx:update_config(
  158. ?PATH,
  159. {create_authenticator, ?GLOBAL, AuthConfig}
  160. ),
  161. Credentials = Credentials0#{
  162. listener => 'tcp:default',
  163. protocol => mqtt
  164. },
  165. ?assertEqual(Result, emqx_access_control:authenticate(Credentials)),
  166. emqx_authn_test_lib:delete_authenticators(
  167. [authentication],
  168. ?GLOBAL
  169. ).
  170. t_authenticate_disabled_prepared_statements(_Config) ->
  171. ResConfig = maps:merge(pgsql_config(), #{disable_prepared_statements => true}),
  172. {ok, _} = emqx_resource:recreate_local(postgresql, ?PGSQL_RESOURCE, emqx_postgresql, ResConfig),
  173. on_exit(fun() ->
  174. emqx_resource:recreate_local(postgresql, ?PGSQL_RESOURCE, emqx_postgresql, pgsql_config())
  175. end),
  176. ok = lists:foreach(
  177. fun(Sample0) ->
  178. Sample = maps:update_with(
  179. config_params,
  180. fun(Cfg) -> Cfg#{<<"disable_prepared_statements">> => true} end,
  181. Sample0
  182. ),
  183. ct:pal("test_user_auth sample: ~p", [Sample]),
  184. test_user_auth(Sample)
  185. end,
  186. user_seeds()
  187. ).
  188. t_destroy(_Config) ->
  189. AuthConfig = raw_pgsql_auth_config(),
  190. {ok, _} = emqx:update_config(
  191. ?PATH,
  192. {create_authenticator, ?GLOBAL, AuthConfig}
  193. ),
  194. {ok, [#{provider := emqx_authn_postgresql, state := State}]} =
  195. emqx_authn_chains:list_authenticators(?GLOBAL),
  196. {ok, _} = emqx_authn_postgresql:authenticate(
  197. #{
  198. username => <<"plain">>,
  199. password => <<"plain">>
  200. },
  201. State
  202. ),
  203. emqx_authn_test_lib:delete_authenticators(
  204. [authentication],
  205. ?GLOBAL
  206. ),
  207. % Authenticator should not be usable anymore
  208. ?assertMatch(
  209. ignore,
  210. emqx_authn_postgresql:authenticate(
  211. #{
  212. username => <<"plain">>,
  213. password => <<"plain">>
  214. },
  215. State
  216. )
  217. ).
  218. t_update(_Config) ->
  219. CorrectConfig = raw_pgsql_auth_config(),
  220. IncorrectConfig =
  221. CorrectConfig#{
  222. <<"query">> =>
  223. <<
  224. "SELECT password_hash, salt, is_superuser_str as is_superuser\n"
  225. " FROM users where username = ${username} LIMIT 0"
  226. >>
  227. },
  228. {ok, _} = emqx:update_config(
  229. ?PATH,
  230. {create_authenticator, ?GLOBAL, IncorrectConfig}
  231. ),
  232. {error, not_authorized} = emqx_access_control:authenticate(
  233. #{
  234. username => <<"plain">>,
  235. password => <<"plain">>,
  236. listener => 'tcp:default',
  237. protocol => mqtt
  238. }
  239. ),
  240. % We update with config with correct query, provider should update and work properly
  241. {ok, _} = emqx:update_config(
  242. ?PATH,
  243. {update_authenticator, ?GLOBAL, <<"password_based:postgresql">>, CorrectConfig}
  244. ),
  245. {ok, _} = emqx_access_control:authenticate(
  246. #{
  247. username => <<"plain">>,
  248. password => <<"plain">>,
  249. listener => 'tcp:default',
  250. protocol => mqtt
  251. }
  252. ).
  253. t_is_superuser(_Config) ->
  254. Config = raw_pgsql_auth_config(),
  255. {ok, _} = emqx:update_config(
  256. ?PATH,
  257. {create_authenticator, ?GLOBAL, Config}
  258. ),
  259. Checks = [
  260. {is_superuser_str, "0", false},
  261. {is_superuser_str, "", false},
  262. {is_superuser_str, null, false},
  263. {is_superuser_str, "1", true},
  264. {is_superuser_str, "val", false},
  265. {is_superuser_int, 0, false},
  266. {is_superuser_int, null, false},
  267. {is_superuser_int, 1, true},
  268. {is_superuser_int, 123, true},
  269. {is_superuser_bool, false, false},
  270. {is_superuser_bool, null, false},
  271. {is_superuser_bool, true, true}
  272. ],
  273. lists:foreach(fun test_is_superuser/1, Checks).
  274. test_is_superuser({Field, Value, ExpectedValue}) ->
  275. {ok, _} = q("DELETE FROM users"),
  276. UserData = #{
  277. username => "user",
  278. password_hash => "plainsalt",
  279. salt => "salt",
  280. Field => Value
  281. },
  282. ok = create_user(UserData),
  283. Query =
  284. "SELECT password_hash, salt, " ++ atom_to_list(Field) ++
  285. " as is_superuser "
  286. "FROM users where username = ${username} LIMIT 1",
  287. Config = maps:put(<<"query">>, Query, raw_pgsql_auth_config()),
  288. {ok, _} = emqx:update_config(
  289. ?PATH,
  290. {update_authenticator, ?GLOBAL, <<"password_based:postgresql">>, Config}
  291. ),
  292. Credentials = #{
  293. listener => 'tcp:default',
  294. protocol => mqtt,
  295. username => <<"user">>,
  296. password => <<"plain">>
  297. },
  298. ?assertEqual(
  299. {ok, #{is_superuser => ExpectedValue}},
  300. emqx_access_control:authenticate(Credentials)
  301. ).
  302. %%------------------------------------------------------------------------------
  303. %% Helpers
  304. %%------------------------------------------------------------------------------
  305. raw_pgsql_auth_config() ->
  306. #{
  307. <<"mechanism">> => <<"password_based">>,
  308. <<"password_hash_algorithm">> => #{
  309. <<"name">> => <<"plain">>,
  310. <<"salt_position">> => <<"suffix">>
  311. },
  312. <<"enable">> => <<"true">>,
  313. <<"backend">> => <<"postgresql">>,
  314. <<"database">> => <<"mqtt">>,
  315. <<"username">> => <<"root">>,
  316. <<"password">> => <<"public">>,
  317. <<"query">> =>
  318. <<
  319. "SELECT password_hash, salt, is_superuser_str as is_superuser\n"
  320. " FROM users where username = ${username} LIMIT 1"
  321. >>,
  322. <<"server">> => pgsql_server()
  323. }.
  324. user_seeds() ->
  325. [
  326. #{
  327. data => #{
  328. username => "plain",
  329. password_hash => "plainsalt",
  330. salt => "salt",
  331. is_superuser_str => "1"
  332. },
  333. credentials => #{
  334. username => <<"plain">>,
  335. password => <<"plain">>
  336. },
  337. config_params => #{},
  338. result => {ok, #{is_superuser => true}}
  339. },
  340. #{
  341. data => #{
  342. username => "md5",
  343. password_hash => "9b4d0c43d206d48279e69b9ad7132e22",
  344. salt => "salt",
  345. is_superuser_str => "0"
  346. },
  347. credentials => #{
  348. username => <<"md5">>,
  349. password => <<"md5">>
  350. },
  351. config_params => #{
  352. <<"password_hash_algorithm">> => #{
  353. <<"name">> => <<"md5">>,
  354. <<"salt_position">> => <<"suffix">>
  355. }
  356. },
  357. result => {ok, #{is_superuser => false}}
  358. },
  359. #{
  360. data => #{
  361. username => "sha256",
  362. password_hash => "ac63a624e7074776d677dd61a003b8c803eb11db004d0ec6ae032a5d7c9c5caf",
  363. salt => "salt",
  364. is_superuser_int => 1
  365. },
  366. credentials => #{
  367. clientid => <<"sha256">>,
  368. password => <<"sha256">>
  369. },
  370. config_params => #{
  371. <<"query">> =>
  372. <<
  373. "SELECT password_hash, salt, is_superuser_int as is_superuser\n"
  374. " FROM users where username = ${clientid} LIMIT 1"
  375. >>,
  376. <<"password_hash_algorithm">> => #{
  377. <<"name">> => <<"sha256">>,
  378. <<"salt_position">> => <<"prefix">>
  379. }
  380. },
  381. result => {ok, #{is_superuser => true}}
  382. },
  383. %% strip double quote support
  384. #{
  385. data => #{
  386. username => "sha256",
  387. password_hash => "ac63a624e7074776d677dd61a003b8c803eb11db004d0ec6ae032a5d7c9c5caf",
  388. salt => "salt",
  389. is_superuser_int => 1
  390. },
  391. credentials => #{
  392. username => <<"sha256">>,
  393. password => <<"sha256">>
  394. },
  395. config_params => #{
  396. <<"query">> =>
  397. <<
  398. "SELECT password_hash, salt, is_superuser_int as is_superuser\n"
  399. " FROM users where username = \"${username}\" LIMIT 1"
  400. >>,
  401. <<"password_hash_algorithm">> => #{
  402. <<"name">> => <<"sha256">>,
  403. <<"salt_position">> => <<"prefix">>
  404. }
  405. },
  406. result => {ok, #{is_superuser => true}}
  407. },
  408. #{
  409. data => #{
  410. username => "sha256",
  411. password_hash => "ac63a624e7074776d677dd61a003b8c803eb11db004d0ec6ae032a5d7c9c5caf",
  412. cert_subject => <<"cert_subject_data">>,
  413. cert_common_name => <<"cert_common_name_data">>,
  414. salt => "salt",
  415. is_superuser_int => 1
  416. },
  417. credentials => #{
  418. clientid => <<"sha256">>,
  419. password => <<"sha256">>,
  420. cert_subject => <<"cert_subject_data">>,
  421. cert_common_name => <<"cert_common_name_data">>
  422. },
  423. config_params => #{
  424. <<"query">> =>
  425. <<
  426. "SELECT password_hash, salt, is_superuser_int as is_superuser\n"
  427. " FROM users where cert_subject = ${cert_subject} AND \n"
  428. " cert_common_name = ${cert_common_name} LIMIT 1"
  429. >>,
  430. <<"password_hash_algorithm">> => #{
  431. <<"name">> => <<"sha256">>,
  432. <<"salt_position">> => <<"prefix">>
  433. }
  434. },
  435. result => {ok, #{is_superuser => true}}
  436. },
  437. #{
  438. data => #{
  439. username => <<"bcrypt">>,
  440. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  441. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  442. is_superuser_int => 0
  443. },
  444. credentials => #{
  445. username => <<"bcrypt">>,
  446. password => <<"bcrypt">>
  447. },
  448. config_params => #{
  449. <<"query">> =>
  450. <<
  451. "SELECT password_hash, salt, is_superuser_int as is_superuser\n"
  452. " FROM users where username = ${username} LIMIT 1"
  453. >>,
  454. <<"password_hash_algorithm">> => #{<<"name">> => <<"bcrypt">>}
  455. },
  456. result => {ok, #{is_superuser => false}}
  457. },
  458. #{
  459. data => #{
  460. username => <<"bcrypt0">>,
  461. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  462. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  463. is_superuser_str => "0"
  464. },
  465. credentials => #{
  466. username => <<"bcrypt0">>,
  467. password => <<"bcrypt">>
  468. },
  469. config_params => #{
  470. % clientid variable & username credentials
  471. <<"query">> =>
  472. <<
  473. "SELECT password_hash, salt, is_superuser_int as is_superuser\n"
  474. " FROM users where username = ${clientid} LIMIT 1"
  475. >>,
  476. <<"password_hash_algorithm">> => #{<<"name">> => <<"bcrypt">>}
  477. },
  478. result => {error, not_authorized}
  479. },
  480. #{
  481. data => #{
  482. username => <<"bcrypt1">>,
  483. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  484. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  485. is_superuser_str => "0"
  486. },
  487. credentials => #{
  488. username => <<"bcrypt1">>,
  489. password => <<"bcrypt">>
  490. },
  491. config_params => #{
  492. % Bad keys in query
  493. <<"query">> =>
  494. <<
  495. "SELECT 1 AS unknown_field\n"
  496. " FROM users where username = ${username} LIMIT 1"
  497. >>,
  498. <<"password_hash_algorithm">> => #{<<"name">> => <<"bcrypt">>}
  499. },
  500. result => {error, not_authorized}
  501. },
  502. #{
  503. data => #{
  504. username => <<"bcrypt2">>,
  505. password_hash => "$2b$12$wtY3h20mUjjmeaClpqZVveDWGlHzCGsvuThMlneGHA7wVeFYyns2u",
  506. salt => "$2b$12$wtY3h20mUjjmeaClpqZVve",
  507. is_superuser => "0"
  508. },
  509. credentials => #{
  510. username => <<"bcrypt2">>,
  511. % Wrong password
  512. password => <<"wrongpass">>
  513. },
  514. config_params => #{
  515. <<"password_hash_algorithm">> => #{<<"name">> => <<"bcrypt">>}
  516. },
  517. result => {error, bad_username_or_password}
  518. }
  519. ].
  520. init_seeds() ->
  521. ok = drop_seeds(),
  522. {ok, _, _} = q(
  523. "CREATE TABLE users(\n"
  524. " username varchar(255),\n"
  525. " password_hash varchar(255),\n"
  526. " salt varchar(255),\n"
  527. " cert_subject varchar(255),\n"
  528. " cert_common_name varchar(255),\n"
  529. " is_superuser_str varchar(255),\n"
  530. " is_superuser_int smallint,\n"
  531. " is_superuser_bool boolean)"
  532. ),
  533. lists:foreach(
  534. fun(#{data := Values}) ->
  535. ok = create_user(Values)
  536. end,
  537. user_seeds()
  538. ).
  539. create_user(Values) ->
  540. Fields = [
  541. username,
  542. password_hash,
  543. salt,
  544. cert_subject,
  545. cert_common_name,
  546. is_superuser_str,
  547. is_superuser_int,
  548. is_superuser_bool
  549. ],
  550. InsertQuery =
  551. "INSERT INTO users(username, password_hash, salt, cert_subject, cert_common_name, "
  552. "is_superuser_str, is_superuser_int, is_superuser_bool) "
  553. "VALUES($1, $2, $3, $4, $5, $6, $7, $8)",
  554. Params = [maps:get(F, Values, null) || F <- Fields],
  555. {ok, 1} = q(InsertQuery, Params),
  556. ok.
  557. q(Sql) ->
  558. emqx_resource:simple_sync_query(
  559. ?PGSQL_RESOURCE,
  560. {query, Sql}
  561. ).
  562. q(Sql, Params) ->
  563. emqx_resource:simple_sync_query(
  564. ?PGSQL_RESOURCE,
  565. {query, Sql, Params}
  566. ).
  567. drop_seeds() ->
  568. {ok, _, _} = q("DROP TABLE IF EXISTS users"),
  569. ok.
  570. pgsql_server() ->
  571. iolist_to_binary(io_lib:format("~s", [?PGSQL_HOST])).
  572. pgsql_config() ->
  573. #{
  574. auto_reconnect => true,
  575. disable_prepared_statements => false,
  576. database => <<"mqtt">>,
  577. username => <<"root">>,
  578. password => <<"public">>,
  579. pool_size => 8,
  580. server => pgsql_server(),
  581. ssl => #{enable => false}
  582. }.
  583. start_apps(Apps) ->
  584. lists:foreach(fun application:ensure_all_started/1, Apps).
  585. stop_apps(Apps) ->
  586. lists:foreach(fun application:stop/1, Apps).