1
0

test_auth.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. # -*- coding: utf-8 -*-
  2. """
  3. :codeauthor: Mike Place <mp@saltstack.com>
  4. """
  5. # Import Python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import time
  8. # Import Salt libraries
  9. import salt.master
  10. import salt.utils.platform
  11. from salt import auth
  12. from salt.exceptions import SaltDeserializationError
  13. from tests.support.case import ModuleCase
  14. from tests.support.mock import MagicMock, call, patch
  15. # Import Salt Testing libs
  16. from tests.support.unit import TestCase, skipIf
  17. class LoadAuthTestCase(TestCase):
  18. def setUp(self): # pylint: disable=W0221
  19. patches = (
  20. ("salt.payload.Serial", None),
  21. (
  22. "salt.loader.auth",
  23. dict(
  24. return_value={
  25. "pam.auth": "fake_func_str",
  26. "pam.groups": "fake_groups_function_str",
  27. }
  28. ),
  29. ),
  30. (
  31. "salt.loader.eauth_tokens",
  32. dict(
  33. return_value={
  34. "localfs.mk_token": "fake_func_mktok",
  35. "localfs.get_token": "fake_func_gettok",
  36. "localfs.rm_roken": "fake_func_rmtok",
  37. }
  38. ),
  39. ),
  40. )
  41. for mod, mock in patches:
  42. if mock:
  43. patcher = patch(mod, **mock)
  44. else:
  45. patcher = patch(mod)
  46. patcher.start()
  47. self.addCleanup(patcher.stop)
  48. self.lauth = auth.LoadAuth({}) # Load with empty opts
  49. def test_get_tok_with_broken_file_will_remove_bad_token(self):
  50. fake_get_token = MagicMock(side_effect=SaltDeserializationError("hi"))
  51. patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"})
  52. patch_get_token = patch.dict(
  53. self.lauth.tokens, {"testfs.get_token": fake_get_token},
  54. )
  55. mock_rm_token = MagicMock()
  56. patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token)
  57. with patch_opts, patch_get_token, patch_rm_token:
  58. expected_token = "fnord"
  59. self.lauth.get_tok(expected_token)
  60. mock_rm_token.assert_called_with(expected_token)
  61. def test_get_tok_with_no_expiration_should_remove_bad_token(self):
  62. fake_get_token = MagicMock(return_value={"no_expire_here": "Nope"})
  63. patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"})
  64. patch_get_token = patch.dict(
  65. self.lauth.tokens, {"testfs.get_token": fake_get_token},
  66. )
  67. mock_rm_token = MagicMock()
  68. patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token)
  69. with patch_opts, patch_get_token, patch_rm_token:
  70. expected_token = "fnord"
  71. self.lauth.get_tok(expected_token)
  72. mock_rm_token.assert_called_with(expected_token)
  73. def test_get_tok_with_expire_before_current_time_should_remove_token(self):
  74. fake_get_token = MagicMock(return_value={"expire": time.time() - 1})
  75. patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"})
  76. patch_get_token = patch.dict(
  77. self.lauth.tokens, {"testfs.get_token": fake_get_token},
  78. )
  79. mock_rm_token = MagicMock()
  80. patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token)
  81. with patch_opts, patch_get_token, patch_rm_token:
  82. expected_token = "fnord"
  83. self.lauth.get_tok(expected_token)
  84. mock_rm_token.assert_called_with(expected_token)
  85. def test_get_tok_with_valid_expiration_should_return_token(self):
  86. expected_token = {"expire": time.time() + 1}
  87. fake_get_token = MagicMock(return_value=expected_token)
  88. patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"})
  89. patch_get_token = patch.dict(
  90. self.lauth.tokens, {"testfs.get_token": fake_get_token},
  91. )
  92. mock_rm_token = MagicMock()
  93. patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token)
  94. with patch_opts, patch_get_token, patch_rm_token:
  95. token_name = "fnord"
  96. actual_token = self.lauth.get_tok(token_name)
  97. mock_rm_token.assert_not_called()
  98. assert expected_token is actual_token, "Token was not returned"
  99. def test_load_name(self):
  100. valid_eauth_load = {
  101. "username": "test_user",
  102. "show_timeout": False,
  103. "test_password": "",
  104. "eauth": "pam",
  105. }
  106. # Test a case where the loader auth doesn't have the auth type
  107. without_auth_type = dict(valid_eauth_load)
  108. without_auth_type.pop("eauth")
  109. ret = self.lauth.load_name(without_auth_type)
  110. self.assertEqual(
  111. ret, "", "Did not bail when the auth loader didn't have the auth type."
  112. )
  113. # Test a case with valid params
  114. with patch(
  115. "salt.utils.args.arg_lookup",
  116. MagicMock(return_value={"args": ["username", "password"]}),
  117. ) as format_call_mock:
  118. expected_ret = call("fake_func_str")
  119. ret = self.lauth.load_name(valid_eauth_load)
  120. format_call_mock.assert_has_calls((expected_ret,), any_order=True)
  121. self.assertEqual(ret, "test_user")
  122. def test_get_groups(self):
  123. valid_eauth_load = {
  124. "username": "test_user",
  125. "show_timeout": False,
  126. "test_password": "",
  127. "eauth": "pam",
  128. }
  129. with patch("salt.utils.args.format_call") as format_call_mock:
  130. expected_ret = call(
  131. "fake_groups_function_str",
  132. {
  133. "username": "test_user",
  134. "test_password": "",
  135. "show_timeout": False,
  136. "eauth": "pam",
  137. },
  138. expected_extra_kws=auth.AUTH_INTERNAL_KEYWORDS,
  139. )
  140. self.lauth.get_groups(valid_eauth_load)
  141. format_call_mock.assert_has_calls((expected_ret,), any_order=True)
  142. class MasterACLTestCase(ModuleCase):
  143. """
  144. A class to check various aspects of the publisher ACL system
  145. """
  146. def setUp(self):
  147. self.fire_event_mock = MagicMock(return_value="dummy_tag")
  148. self.addCleanup(delattr, self, "fire_event_mock")
  149. opts = self.get_temp_config("master")
  150. patches = (
  151. ("zmq.Context", MagicMock()),
  152. ("salt.payload.Serial.dumps", MagicMock()),
  153. ("salt.master.tagify", MagicMock()),
  154. ("salt.utils.event.SaltEvent.fire_event", self.fire_event_mock),
  155. ("salt.auth.LoadAuth.time_auth", MagicMock(return_value=True)),
  156. ("salt.minion.MasterMinion", MagicMock()),
  157. ("salt.utils.verify.check_path_traversal", MagicMock()),
  158. ("salt.client.get_local_client", MagicMock(return_value=opts["conf_file"])),
  159. )
  160. for mod, mock in patches:
  161. patcher = patch(mod, mock)
  162. patcher.start()
  163. self.addCleanup(patcher.stop)
  164. opts["publisher_acl"] = {}
  165. opts["publisher_acl_blacklist"] = {}
  166. opts["master_job_cache"] = ""
  167. opts["sign_pub_messages"] = False
  168. opts["con_cache"] = ""
  169. opts["external_auth"] = {}
  170. opts["external_auth"]["pam"] = {
  171. "test_user": [
  172. {"*": ["test.ping"]},
  173. {"minion_glob*": ["foo.bar"]},
  174. {"minion_func_test": ["func_test.*"]},
  175. ],
  176. "test_group%": [{"*": ["test.echo"]}],
  177. "test_user_mminion": [{"target_minion": ["test.ping"]}],
  178. "*": [{"my_minion": ["my_mod.my_func"]}],
  179. "test_user_func": [
  180. {
  181. "*": [
  182. {"test.echo": {"args": ["MSG:.*"]}},
  183. {
  184. "test.echo": {
  185. "kwargs": {
  186. "text": "KWMSG:.*",
  187. "anything": ".*",
  188. "none": None,
  189. }
  190. }
  191. },
  192. {
  193. "my_mod.*": {
  194. "args": ["a.*", "b.*"],
  195. "kwargs": {"kwa": "kwa.*", "kwb": "kwb"},
  196. }
  197. },
  198. ]
  199. },
  200. {
  201. "minion1": [
  202. {"test.echo": {"args": ["TEST", None, "TEST.*"]}},
  203. {"test.empty": {}},
  204. ]
  205. },
  206. ],
  207. }
  208. self.clear = salt.master.ClearFuncs(opts, MagicMock())
  209. self.addCleanup(delattr, self, "clear")
  210. # overwrite the _send_pub method so we don't have to serialize MagicMock
  211. self.clear._send_pub = lambda payload: True
  212. # make sure to return a JID, instead of a mock
  213. self.clear.mminion.returners = {".prep_jid": lambda x: 1}
  214. self.valid_clear_load = {
  215. "tgt_type": "glob",
  216. "jid": "",
  217. "cmd": "publish",
  218. "tgt": "test_minion",
  219. "kwargs": {
  220. "username": "test_user",
  221. "password": "test_password",
  222. "show_timeout": False,
  223. "eauth": "pam",
  224. "show_jid": False,
  225. },
  226. "ret": "",
  227. "user": "test_user",
  228. "key": "",
  229. "arg": "",
  230. "fun": "test.ping",
  231. }
  232. self.addCleanup(delattr, self, "valid_clear_load")
  233. @skipIf(salt.utils.platform.is_windows(), "PAM eauth not available on Windows")
  234. def test_master_publish_name(self):
  235. """
  236. Test to ensure a simple name can auth against a given function.
  237. This tests to ensure test_user can access test.ping but *not* sys.doc
  238. """
  239. _check_minions_return = {"minions": ["some_minions"], "missing": []}
  240. with patch(
  241. "salt.utils.minions.CkMinions.check_minions",
  242. MagicMock(return_value=_check_minions_return),
  243. ):
  244. # Can we access test.ping?
  245. self.clear.publish(self.valid_clear_load)
  246. self.assertEqual(self.fire_event_mock.call_args[0][0]["fun"], "test.ping")
  247. # Are we denied access to sys.doc?
  248. sys_doc_load = self.valid_clear_load
  249. sys_doc_load["fun"] = "sys.doc"
  250. self.clear.publish(sys_doc_load)
  251. self.assertNotEqual(
  252. self.fire_event_mock.call_args[0][0]["fun"], "sys.doc"
  253. ) # If sys.doc were to fire, this would match
  254. def test_master_publish_group(self):
  255. """
  256. Tests to ensure test_group can access test.echo but *not* sys.doc
  257. """
  258. _check_minions_return = {"minions": ["some_minions"], "missing": []}
  259. with patch(
  260. "salt.utils.minions.CkMinions.check_minions",
  261. MagicMock(return_value=_check_minions_return),
  262. ):
  263. self.valid_clear_load["kwargs"]["user"] = "new_user"
  264. self.valid_clear_load["fun"] = "test.echo"
  265. self.valid_clear_load["arg"] = "hello"
  266. with patch(
  267. "salt.auth.LoadAuth.get_groups",
  268. return_value=["test_group", "second_test_group"],
  269. ):
  270. self.clear.publish(self.valid_clear_load)
  271. # Did we fire test.echo?
  272. self.assertEqual(self.fire_event_mock.call_args[0][0]["fun"], "test.echo")
  273. # Request sys.doc
  274. self.valid_clear_load["fun"] = "sys.doc"
  275. # Did we fire it?
  276. self.assertNotEqual(self.fire_event_mock.call_args[0][0]["fun"], "sys.doc")
  277. def test_master_publish_some_minions(self):
  278. """
  279. Tests to ensure we can only target minions for which we
  280. have permission with publisher acl.
  281. Note that in order for these sorts of tests to run correctly that
  282. you should NOT patch check_minions!
  283. """
  284. self.valid_clear_load["kwargs"]["username"] = "test_user_mminion"
  285. self.valid_clear_load["user"] = "test_user_mminion"
  286. self.clear.publish(self.valid_clear_load)
  287. self.assertEqual(self.fire_event_mock.mock_calls, [])
  288. def test_master_not_user_glob_all(self):
  289. """
  290. Test to ensure that we DO NOT access to a given
  291. function to all users with publisher acl. ex:
  292. '*':
  293. my_minion:
  294. - my_func
  295. Yes, this seems like a bit of a no-op test but it's
  296. here to document that this functionality
  297. is NOT supported currently.
  298. WARNING: Do not patch this wit
  299. """
  300. self.valid_clear_load["kwargs"]["username"] = "NOT_A_VALID_USERNAME"
  301. self.valid_clear_load["user"] = "NOT_A_VALID_USERNAME"
  302. self.valid_clear_load["fun"] = "test.ping"
  303. self.clear.publish(self.valid_clear_load)
  304. self.assertEqual(self.fire_event_mock.mock_calls, [])
  305. @skipIf(salt.utils.platform.is_windows(), "PAM eauth not available on Windows")
  306. def test_master_minion_glob(self):
  307. """
  308. Test to ensure we can allow access to a given
  309. function for a user to a subset of minions
  310. selected by a glob. ex:
  311. test_user:
  312. 'minion_glob*':
  313. - glob_mod.glob_func
  314. This test is a bit tricky, because ultimately the real functionality
  315. lies in what's returned from check_minions, but this checks a limited
  316. amount of logic on the way there as well. Note the inline patch.
  317. """
  318. requested_function = "foo.bar"
  319. requested_tgt = "minion_glob1"
  320. self.valid_clear_load["tgt"] = requested_tgt
  321. self.valid_clear_load["fun"] = requested_function
  322. _check_minions_return = {"minions": ["minion_glob1"], "missing": []}
  323. with patch(
  324. "salt.utils.minions.CkMinions.check_minions",
  325. MagicMock(return_value=_check_minions_return),
  326. ): # Assume that there is a listening minion match
  327. self.clear.publish(self.valid_clear_load)
  328. self.assertTrue(
  329. self.fire_event_mock.called,
  330. "Did not fire {0} for minion tgt {1}".format(
  331. requested_function, requested_tgt
  332. ),
  333. )
  334. self.assertEqual(
  335. self.fire_event_mock.call_args[0][0]["fun"],
  336. requested_function,
  337. "Did not fire {0} for minion glob".format(requested_function),
  338. )
  339. def test_master_function_glob(self):
  340. """
  341. Test to ensure that we can allow access to a given
  342. set of functions in an execution module as selected
  343. by a glob. ex:
  344. my_user:
  345. my_minion:
  346. 'test.*'
  347. """
  348. # Unimplemented
  349. @skipIf(salt.utils.platform.is_windows(), "PAM eauth not available on Windows")
  350. def test_args_empty_spec(self):
  351. """
  352. Test simple arg restriction allowed.
  353. 'test_user_func':
  354. minion1:
  355. - test.empty:
  356. """
  357. _check_minions_return = {"minions": ["minion1"], "missing": []}
  358. with patch(
  359. "salt.utils.minions.CkMinions.check_minions",
  360. MagicMock(return_value=_check_minions_return),
  361. ):
  362. self.valid_clear_load["kwargs"].update({"username": "test_user_func"})
  363. self.valid_clear_load.update(
  364. {
  365. "user": "test_user_func",
  366. "tgt": "minion1",
  367. "fun": "test.empty",
  368. "arg": ["TEST"],
  369. }
  370. )
  371. self.clear.publish(self.valid_clear_load)
  372. self.assertEqual(self.fire_event_mock.call_args[0][0]["fun"], "test.empty")
  373. @skipIf(salt.utils.platform.is_windows(), "PAM eauth not available on Windows")
  374. def test_args_simple_match(self):
  375. """
  376. Test simple arg restriction allowed.
  377. 'test_user_func':
  378. minion1:
  379. - test.echo:
  380. args:
  381. - 'TEST'
  382. - 'TEST.*'
  383. """
  384. _check_minions_return = {"minions": ["minion1"], "missing": []}
  385. with patch(
  386. "salt.utils.minions.CkMinions.check_minions",
  387. MagicMock(return_value=_check_minions_return),
  388. ):
  389. self.valid_clear_load["kwargs"].update({"username": "test_user_func"})
  390. self.valid_clear_load.update(
  391. {
  392. "user": "test_user_func",
  393. "tgt": "minion1",
  394. "fun": "test.echo",
  395. "arg": ["TEST", "any", "TEST ABC"],
  396. }
  397. )
  398. self.clear.publish(self.valid_clear_load)
  399. self.assertEqual(self.fire_event_mock.call_args[0][0]["fun"], "test.echo")
  400. @skipIf(salt.utils.platform.is_windows(), "PAM eauth not available on Windows")
  401. def test_args_more_args(self):
  402. """
  403. Test simple arg restriction allowed to pass unlisted args.
  404. 'test_user_func':
  405. minion1:
  406. - test.echo:
  407. args:
  408. - 'TEST'
  409. - 'TEST.*'
  410. """
  411. _check_minions_return = {"minions": ["minion1"], "missing": []}
  412. with patch(
  413. "salt.utils.minions.CkMinions.check_minions",
  414. MagicMock(return_value=_check_minions_return),
  415. ):
  416. self.valid_clear_load["kwargs"].update({"username": "test_user_func"})
  417. self.valid_clear_load.update(
  418. {
  419. "user": "test_user_func",
  420. "tgt": "minion1",
  421. "fun": "test.echo",
  422. "arg": [
  423. "TEST",
  424. "any",
  425. "TEST ABC",
  426. "arg 3",
  427. {"kwarg1": "val1", "__kwarg__": True},
  428. ],
  429. }
  430. )
  431. self.clear.publish(self.valid_clear_load)
  432. self.assertEqual(self.fire_event_mock.call_args[0][0]["fun"], "test.echo")
  433. def test_args_simple_forbidden(self):
  434. """
  435. Test simple arg restriction forbidden.
  436. 'test_user_func':
  437. minion1:
  438. - test.echo:
  439. args:
  440. - 'TEST'
  441. - 'TEST.*'
  442. """
  443. _check_minions_return = {"minions": ["minion1"], "missing": []}
  444. with patch(
  445. "salt.utils.minions.CkMinions.check_minions",
  446. MagicMock(return_value=_check_minions_return),
  447. ):
  448. self.valid_clear_load["kwargs"].update({"username": "test_user_func"})
  449. # Wrong last arg
  450. self.valid_clear_load.update(
  451. {
  452. "user": "test_user_func",
  453. "tgt": "minion1",
  454. "fun": "test.echo",
  455. "arg": ["TEST", "any", "TESLA"],
  456. }
  457. )
  458. self.clear.publish(self.valid_clear_load)
  459. self.assertEqual(self.fire_event_mock.mock_calls, [])
  460. # Wrong first arg
  461. self.valid_clear_load["arg"] = ["TES", "any", "TEST1234"]
  462. self.clear.publish(self.valid_clear_load)
  463. self.assertEqual(self.fire_event_mock.mock_calls, [])
  464. # Missing the last arg
  465. self.valid_clear_load["arg"] = ["TEST", "any"]
  466. self.clear.publish(self.valid_clear_load)
  467. self.assertEqual(self.fire_event_mock.mock_calls, [])
  468. # No args
  469. self.valid_clear_load["arg"] = []
  470. self.clear.publish(self.valid_clear_load)
  471. self.assertEqual(self.fire_event_mock.mock_calls, [])
  472. @skipIf(salt.utils.platform.is_windows(), "PAM eauth not available on Windows")
  473. def test_args_kwargs_match(self):
  474. """
  475. Test simple kwargs restriction allowed.
  476. 'test_user_func':
  477. '*':
  478. - test.echo:
  479. kwargs:
  480. text: 'KWMSG:.*'
  481. """
  482. _check_minions_return = {"minions": ["some_minions"], "missing": []}
  483. with patch(
  484. "salt.utils.minions.CkMinions.check_minions",
  485. MagicMock(return_value=_check_minions_return),
  486. ):
  487. self.valid_clear_load["kwargs"].update({"username": "test_user_func"})
  488. self.valid_clear_load.update(
  489. {
  490. "user": "test_user_func",
  491. "tgt": "*",
  492. "fun": "test.echo",
  493. "arg": [
  494. {
  495. "text": "KWMSG: a message",
  496. "anything": "hello all",
  497. "none": "hello none",
  498. "__kwarg__": True,
  499. }
  500. ],
  501. }
  502. )
  503. self.clear.publish(self.valid_clear_load)
  504. self.assertEqual(self.fire_event_mock.call_args[0][0]["fun"], "test.echo")
  505. def test_args_kwargs_mismatch(self):
  506. """
  507. Test simple kwargs restriction allowed.
  508. 'test_user_func':
  509. '*':
  510. - test.echo:
  511. kwargs:
  512. text: 'KWMSG:.*'
  513. """
  514. _check_minions_return = {"minions": ["some_minions"], "missing": []}
  515. with patch(
  516. "salt.utils.minions.CkMinions.check_minions",
  517. MagicMock(return_value=_check_minions_return),
  518. ):
  519. self.valid_clear_load["kwargs"].update({"username": "test_user_func"})
  520. self.valid_clear_load.update(
  521. {"user": "test_user_func", "tgt": "*", "fun": "test.echo"}
  522. )
  523. # Wrong kwarg value
  524. self.valid_clear_load["arg"] = [
  525. {
  526. "text": "KWMSG a message",
  527. "anything": "hello all",
  528. "none": "hello none",
  529. "__kwarg__": True,
  530. }
  531. ]
  532. self.clear.publish(self.valid_clear_load)
  533. self.assertEqual(self.fire_event_mock.mock_calls, [])
  534. # Missing kwarg value
  535. self.valid_clear_load["arg"] = [
  536. {"anything": "hello all", "none": "hello none", "__kwarg__": True}
  537. ]
  538. self.clear.publish(self.valid_clear_load)
  539. self.assertEqual(self.fire_event_mock.mock_calls, [])
  540. self.valid_clear_load["arg"] = [{"__kwarg__": True}]
  541. self.clear.publish(self.valid_clear_load)
  542. self.assertEqual(self.fire_event_mock.mock_calls, [])
  543. self.valid_clear_load["arg"] = [{}]
  544. self.clear.publish(self.valid_clear_load)
  545. self.assertEqual(self.fire_event_mock.mock_calls, [])
  546. self.valid_clear_load["arg"] = []
  547. self.clear.publish(self.valid_clear_load)
  548. self.assertEqual(self.fire_event_mock.mock_calls, [])
  549. # Missing kwarg allowing any value
  550. self.valid_clear_load["arg"] = [
  551. {"text": "KWMSG: a message", "none": "hello none", "__kwarg__": True}
  552. ]
  553. self.clear.publish(self.valid_clear_load)
  554. self.assertEqual(self.fire_event_mock.mock_calls, [])
  555. self.valid_clear_load["arg"] = [
  556. {"text": "KWMSG: a message", "anything": "hello all", "__kwarg__": True}
  557. ]
  558. self.clear.publish(self.valid_clear_load)
  559. self.assertEqual(self.fire_event_mock.mock_calls, [])
  560. @skipIf(salt.utils.platform.is_windows(), "PAM eauth not available on Windows")
  561. def test_args_mixed_match(self):
  562. """
  563. Test mixed args and kwargs restriction allowed.
  564. 'test_user_func':
  565. '*':
  566. - 'my_mod.*':
  567. args:
  568. - 'a.*'
  569. - 'b.*'
  570. kwargs:
  571. 'kwa': 'kwa.*'
  572. 'kwb': 'kwb'
  573. """
  574. _check_minions_return = {"minions": ["some_minions"], "missing": []}
  575. with patch(
  576. "salt.utils.minions.CkMinions.check_minions",
  577. MagicMock(return_value=_check_minions_return),
  578. ):
  579. self.valid_clear_load["kwargs"].update({"username": "test_user_func"})
  580. self.valid_clear_load.update(
  581. {
  582. "user": "test_user_func",
  583. "tgt": "*",
  584. "fun": "my_mod.some_func",
  585. "arg": [
  586. "alpha",
  587. "beta",
  588. "gamma",
  589. {
  590. "kwa": "kwarg #1",
  591. "kwb": "kwb",
  592. "one_more": "just one more",
  593. "__kwarg__": True,
  594. },
  595. ],
  596. }
  597. )
  598. self.clear.publish(self.valid_clear_load)
  599. self.assertEqual(
  600. self.fire_event_mock.call_args[0][0]["fun"], "my_mod.some_func"
  601. )
  602. def test_args_mixed_mismatch(self):
  603. """
  604. Test mixed args and kwargs restriction forbidden.
  605. 'test_user_func':
  606. '*':
  607. - 'my_mod.*':
  608. args:
  609. - 'a.*'
  610. - 'b.*'
  611. kwargs:
  612. 'kwa': 'kwa.*'
  613. 'kwb': 'kwb'
  614. """
  615. _check_minions_return = {"minions": ["some_minions"], "missing": []}
  616. with patch(
  617. "salt.utils.minions.CkMinions.check_minions",
  618. MagicMock(return_value=_check_minions_return),
  619. ):
  620. self.valid_clear_load["kwargs"].update({"username": "test_user_func"})
  621. self.valid_clear_load.update(
  622. {"user": "test_user_func", "tgt": "*", "fun": "my_mod.some_func"}
  623. )
  624. # Wrong arg value
  625. self.valid_clear_load["arg"] = [
  626. "alpha",
  627. "gamma",
  628. {
  629. "kwa": "kwarg #1",
  630. "kwb": "kwb",
  631. "one_more": "just one more",
  632. "__kwarg__": True,
  633. },
  634. ]
  635. self.clear.publish(self.valid_clear_load)
  636. self.assertEqual(self.fire_event_mock.mock_calls, [])
  637. # Wrong kwarg value
  638. self.valid_clear_load["arg"] = [
  639. "alpha",
  640. "beta",
  641. "gamma",
  642. {
  643. "kwa": "kkk",
  644. "kwb": "kwb",
  645. "one_more": "just one more",
  646. "__kwarg__": True,
  647. },
  648. ]
  649. self.clear.publish(self.valid_clear_load)
  650. self.assertEqual(self.fire_event_mock.mock_calls, [])
  651. # Missing arg
  652. self.valid_clear_load["arg"] = [
  653. "alpha",
  654. {
  655. "kwa": "kwarg #1",
  656. "kwb": "kwb",
  657. "one_more": "just one more",
  658. "__kwarg__": True,
  659. },
  660. ]
  661. self.clear.publish(self.valid_clear_load)
  662. self.assertEqual(self.fire_event_mock.mock_calls, [])
  663. # Missing kwarg
  664. self.valid_clear_load["arg"] = [
  665. "alpha",
  666. "beta",
  667. "gamma",
  668. {"kwa": "kwarg #1", "one_more": "just one more", "__kwarg__": True},
  669. ]
  670. self.clear.publish(self.valid_clear_load)
  671. self.assertEqual(self.fire_event_mock.mock_calls, [])
  672. class AuthACLTestCase(ModuleCase):
  673. """
  674. A class to check various aspects of the publisher ACL system
  675. """
  676. def setUp(self):
  677. self.auth_check_mock = MagicMock(return_value=True)
  678. opts = self.get_temp_config("master")
  679. patches = (
  680. ("salt.minion.MasterMinion", MagicMock()),
  681. ("salt.utils.verify.check_path_traversal", MagicMock()),
  682. ("salt.utils.minions.CkMinions.auth_check", self.auth_check_mock),
  683. ("salt.auth.LoadAuth.time_auth", MagicMock(return_value=True)),
  684. ("salt.client.get_local_client", MagicMock(return_value=opts["conf_file"])),
  685. )
  686. for mod, mock in patches:
  687. patcher = patch(mod, mock)
  688. patcher.start()
  689. self.addCleanup(patcher.stop)
  690. self.addCleanup(delattr, self, "auth_check_mock")
  691. opts["publisher_acl"] = {}
  692. opts["publisher_acl_blacklist"] = {}
  693. opts["master_job_cache"] = ""
  694. opts["sign_pub_messages"] = False
  695. opts["con_cache"] = ""
  696. opts["external_auth"] = {}
  697. opts["external_auth"]["pam"] = {"test_user": [{"alpha_minion": ["test.ping"]}]}
  698. self.clear = salt.master.ClearFuncs(opts, MagicMock())
  699. self.addCleanup(delattr, self, "clear")
  700. # overwrite the _send_pub method so we don't have to serialize MagicMock
  701. self.clear._send_pub = lambda payload: True
  702. # make sure to return a JID, instead of a mock
  703. self.clear.mminion.returners = {".prep_jid": lambda x: 1}
  704. self.valid_clear_load = {
  705. "tgt_type": "glob",
  706. "jid": "",
  707. "cmd": "publish",
  708. "tgt": "test_minion",
  709. "kwargs": {
  710. "username": "test_user",
  711. "password": "test_password",
  712. "show_timeout": False,
  713. "eauth": "pam",
  714. "show_jid": False,
  715. },
  716. "ret": "",
  717. "user": "test_user",
  718. "key": "",
  719. "arg": "",
  720. "fun": "test.ping",
  721. }
  722. self.addCleanup(delattr, self, "valid_clear_load")
  723. @skipIf(salt.utils.platform.is_windows(), "PAM eauth not available on Windows")
  724. def test_acl_simple_allow(self):
  725. self.clear.publish(self.valid_clear_load)
  726. self.assertEqual(
  727. self.auth_check_mock.call_args[0][0], [{"alpha_minion": ["test.ping"]}]
  728. )
  729. def test_acl_simple_deny(self):
  730. with patch(
  731. "salt.auth.LoadAuth.get_auth_list",
  732. MagicMock(return_value=[{"beta_minion": ["test.ping"]}]),
  733. ):
  734. self.clear.publish(self.valid_clear_load)
  735. self.assertEqual(
  736. self.auth_check_mock.call_args[0][0], [{"beta_minion": ["test.ping"]}]
  737. )