cmdctl_test.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. # Copyright (C) 2009 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. import unittest
  16. import socket
  17. import tempfile
  18. from cmdctl import *
  19. # Rewrite the class for unittest.
  20. class MySecureHTTPRequestHandler(SecureHTTPRequestHandler):
  21. def __init__(self):
  22. pass
  23. def send_response(self, rcode):
  24. self.rcode = rcode
  25. def end_headers(self):
  26. pass
  27. def do_GET(self):
  28. self.wfile = open('tmp.file', 'wb')
  29. super().do_GET()
  30. self.wfile.close()
  31. os.remove('tmp.file')
  32. def do_POST(self):
  33. self.wfile = open("tmp.file", 'wb')
  34. super().do_POST()
  35. self.wfile.close()
  36. os.remove('tmp.file')
  37. class FakeSecureHTTPServer(SecureHTTPServer):
  38. def __init__(self):
  39. self.user_sessions = {}
  40. self.cmdctl = FakeCommandControlForTestRequestHandler()
  41. self._verbose = True
  42. self._user_infos = {}
  43. self.idle_timeout = 1200
  44. self._lock = threading.Lock()
  45. class FakeCommandControlForTestRequestHandler(CommandControl):
  46. def __init__(self):
  47. self._config_data = {}
  48. self.modules_spec = {}
  49. self._lock = threading.Lock()
  50. def send_command(self, mod, cmd, param):
  51. return 0, {}
  52. class TestSecureHTTPRequestHandler(unittest.TestCase):
  53. def setUp(self):
  54. self.old_stdout = sys.stdout
  55. sys.stdout = open(os.devnull, 'w')
  56. self.handler = MySecureHTTPRequestHandler()
  57. self.handler.server = FakeSecureHTTPServer()
  58. self.handler.server.user_sessions = {}
  59. self.handler.server._user_infos = {}
  60. self.handler.headers = {}
  61. self.handler.rfile = open("check.tmp", 'w+b')
  62. def tearDown(self):
  63. sys.stdout = self.old_stdout
  64. self.handler.rfile.close()
  65. os.remove('check.tmp')
  66. def test_parse_request_path(self):
  67. self.handler.path = ''
  68. mod, cmd = self.handler._parse_request_path()
  69. self.assertTrue((mod == None) and (cmd == None))
  70. self.handler.path = '/abc'
  71. mod, cmd = self.handler._parse_request_path()
  72. self.assertTrue((mod == 'abc') and (cmd == None))
  73. self.handler.path = '/abc/edf'
  74. mod, cmd = self.handler._parse_request_path()
  75. self.assertTrue((mod == 'abc') and (cmd == 'edf'))
  76. self.handler.path = '/abc/edf/ghi'
  77. mod, cmd = self.handler._parse_request_path()
  78. self.assertTrue((mod == 'abc') and (cmd == 'edf'))
  79. def test_parse_request_path_1(self):
  80. self.handler.path = '/ab*c'
  81. mod, cmd = self.handler._parse_request_path()
  82. self.assertTrue((mod == 'ab') and cmd == None)
  83. self.handler.path = '/abc/ed*fdd/ddd'
  84. mod, cmd = self.handler._parse_request_path()
  85. self.assertTrue((mod == 'abc') and cmd == 'ed')
  86. self.handler.path = '/-*/edfdd/ddd'
  87. mod, cmd = self.handler._parse_request_path()
  88. self.assertTrue((mod == None) and (cmd == None))
  89. self.handler.path = '/-*/edfdd/ddd'
  90. mod, cmd = self.handler._parse_request_path()
  91. self.assertTrue((mod == None) and (cmd == None))
  92. def test_do_GET(self):
  93. self.handler.do_GET()
  94. self.assertEqual(self.handler.rcode, http.client.BAD_REQUEST)
  95. def test_do_GET_1(self):
  96. self.handler.headers['cookie'] = 12345
  97. self.handler.do_GET()
  98. self.assertEqual(self.handler.rcode, http.client.UNAUTHORIZED)
  99. def test_do_GET_2(self):
  100. self.handler.headers['cookie'] = 12345
  101. self.handler.server.user_sessions[12345] = time.time() + 1000000
  102. self.handler.path = '/how/are'
  103. self.handler.do_GET()
  104. self.assertEqual(self.handler.rcode, http.client.NO_CONTENT)
  105. def test_do_GET_3(self):
  106. self.handler.headers['cookie'] = 12346
  107. self.handler.server.user_sessions[12346] = time.time() + 1000000
  108. path_vec = ['config_data', 'module_spec']
  109. for path in path_vec:
  110. self.handler.path = '/' + path
  111. self.handler.do_GET()
  112. self.assertEqual(self.handler.rcode, http.client.OK)
  113. def test_user_logged_in(self):
  114. self.handler.server.user_sessions = {}
  115. self.handler.session_id = 12345
  116. self.assertTrue(self.handler._is_user_logged_in() == False)
  117. self.handler.server.user_sessions[12345] = time.time()
  118. self.assertTrue(self.handler._is_user_logged_in())
  119. self.handler.server.user_sessions[12345] = time.time() - 1500
  120. self.handler.idle_timeout = 1200
  121. self.assertTrue(self.handler._is_user_logged_in() == False)
  122. def test_check_user_name_and_pwd(self):
  123. self.handler.headers = {}
  124. ret, msg = self.handler._check_user_name_and_pwd()
  125. self.assertTrue(ret == False)
  126. self.assertEqual(msg, ['invalid username or password'])
  127. def test_check_user_name_and_pwd_1(self):
  128. user_info = {'username':'root', 'password':'abc123'}
  129. len = self.handler.rfile.write(json.dumps(user_info).encode())
  130. self.handler.headers['Content-Length'] = len
  131. self.handler.rfile.seek(0, 0)
  132. self.handler.server._user_infos['root'] = ['aa', 'aaa']
  133. ret, msg = self.handler._check_user_name_and_pwd()
  134. self.assertTrue(ret == False)
  135. self.assertEqual(msg, ['password doesn\'t match'])
  136. def test_check_user_name_and_pwd_2(self):
  137. user_info = {'username':'root', 'password':'abc123'}
  138. len = self.handler.rfile.write(json.dumps(user_info).encode())
  139. self.handler.headers['Content-Length'] = len - 1
  140. self.handler.rfile.seek(0, 0)
  141. ret, msg = self.handler._check_user_name_and_pwd()
  142. self.assertTrue(ret == False)
  143. self.assertEqual(msg, ['invalid username or password'])
  144. def test_check_user_name_and_pwd_3(self):
  145. user_info = {'usernae':'root', 'password':'abc123'}
  146. len = self.handler.rfile.write(json.dumps(user_info).encode())
  147. self.handler.headers['Content-Length'] = len
  148. self.handler.rfile.seek(0, 0)
  149. ret, msg = self.handler._check_user_name_and_pwd()
  150. self.assertTrue(ret == False)
  151. self.assertEqual(msg, ['need user name'])
  152. def test_check_user_name_and_pwd_4(self):
  153. user_info = {'username':'root', 'pssword':'abc123'}
  154. len = self.handler.rfile.write(json.dumps(user_info).encode())
  155. self.handler.headers['Content-Length'] = len
  156. self.handler.rfile.seek(0, 0)
  157. self.handler.server._user_infos['root'] = ['aa', 'aaa']
  158. ret, msg = self.handler._check_user_name_and_pwd()
  159. self.assertTrue(ret == False)
  160. self.assertEqual(msg, ['need password'])
  161. def test_check_user_name_and_pwd_5(self):
  162. user_info = {'username':'root', 'password':'abc123'}
  163. len = self.handler.rfile.write(json.dumps(user_info).encode())
  164. self.handler.headers['Content-Length'] = len
  165. self.handler.rfile.seek(0, 0)
  166. ret, msg = self.handler._check_user_name_and_pwd()
  167. self.assertTrue(ret == False)
  168. self.assertEqual(msg, ['user doesn\'t exist'])
  169. def test_do_POST(self):
  170. self.handler.headers = {}
  171. self.handler.do_POST()
  172. self.assertEqual(self.handler.rcode, http.client.BAD_REQUEST)
  173. def test_do_POST_1(self):
  174. self.handler.headers = {}
  175. self.handler.headers['cookie'] = 12345
  176. self.handler.path = '/'
  177. self.handler.do_POST()
  178. self.assertEqual(self.handler.rcode, http.client.UNAUTHORIZED)
  179. def test_handle_post_request(self):
  180. self.handler.path = '/cfgmgr/revert'
  181. self.handler.headers = {}
  182. rcode, reply = self.handler._handle_post_request()
  183. self.assertEqual(http.client.BAD_REQUEST, rcode)
  184. def test_handle_post_request_1(self):
  185. self.handler.path = '/*d/revert'
  186. self.handler.headers = {}
  187. rcode, reply = self.handler._handle_post_request()
  188. self.assertEqual(http.client.BAD_REQUEST, rcode)
  189. def _gen_module_spec(self):
  190. spec = { 'commands': [
  191. { 'command_name' :'command',
  192. 'command_args': [ {
  193. 'item_name' : 'param1',
  194. 'item_type' : 'integer',
  195. 'item_optional' : False,
  196. 'item_default' : 0
  197. } ],
  198. 'command_description' : 'cmd description'
  199. }
  200. ]
  201. }
  202. return spec
  203. def test_handle_post_request_2(self):
  204. params = {'param1':123}
  205. len = self.handler.rfile.write(json.dumps(params).encode())
  206. self.handler.headers['Content-Length'] = len
  207. self.handler.rfile.seek(0, 0)
  208. self.handler.path = '/module/command'
  209. self.handler.server.cmdctl.modules_spec = {}
  210. self.handler.server.cmdctl.modules_spec['module'] = self._gen_module_spec()
  211. rcode, reply = self.handler._handle_post_request()
  212. self.assertEqual(http.client.OK, rcode)
  213. def test_handle_post_request_3(self):
  214. params = {'param1':'abc'}
  215. len = self.handler.rfile.write(json.dumps(params).encode())
  216. self.handler.headers['Content-Length'] = len
  217. self.handler.rfile.seek(0, 0)
  218. self.handler.path = '/module/command'
  219. self.handler.server.cmdctl.modules_spec = {}
  220. self.handler.server.cmdctl.modules_spec['module'] = self._gen_module_spec()
  221. rcode, reply = self.handler._handle_post_request()
  222. self.assertEqual(http.client.BAD_REQUEST, rcode)
  223. class MyCommandControl(CommandControl):
  224. def _get_modules_specification(self):
  225. return {}
  226. def _get_config_data_from_config_manager(self):
  227. return {}
  228. def _setup_session(self):
  229. module_spec = isc.config.module_spec_from_file(SPECFILE_LOCATION)
  230. config = isc.config.config_data.ConfigData(module_spec)
  231. self._cmdctl_config_data = config.get_full_config()
  232. def _handle_msg_from_msgq(self):
  233. pass
  234. class TestCommandControl(unittest.TestCase):
  235. def setUp(self):
  236. self.old_stdout = sys.stdout
  237. sys.stdout = open(os.devnull, 'w')
  238. self.cmdctl = MyCommandControl(None, True)
  239. def tearDown(self):
  240. sys.stdout = self.old_stdout
  241. def _check_config(self, cmdctl):
  242. key, cert, account = cmdctl.get_cmdctl_config_data()
  243. self.assertIsNotNone(key)
  244. self.assertIsNotNone(cert)
  245. self.assertIsNotNone(account)
  246. def test_get_cmdctl_config_data(self):
  247. old_env = os.environ
  248. if 'B10_FROM_SOURCE' in os.environ:
  249. del os.environ['B10_FROM_SOURCE']
  250. self.cmdctl.get_cmdctl_config_data()
  251. self._check_config(self.cmdctl)
  252. os.environ = old_env
  253. old_env = os.environ
  254. os.environ['B10_FROM_SOURCE'] = '../'
  255. self._check_config(self.cmdctl)
  256. os.environ = old_env
  257. def test_parse_command_result(self):
  258. self.assertEqual({}, self.cmdctl._parse_command_result(1, {'error' : 1}))
  259. self.assertEqual({'a': 1}, self.cmdctl._parse_command_result(0, {'a' : 1}))
  260. def _check_answer(self, answer, rcode_, msg_):
  261. rcode, msg = ccsession.parse_answer(answer)
  262. self.assertEqual(rcode, rcode_)
  263. self.assertEqual(msg, msg_)
  264. def test_command_handler(self):
  265. answer = self.cmdctl.command_handler('unknown-command', None)
  266. self._check_answer(answer, 1, 'unknown command: unknown-command')
  267. answer = self.cmdctl.command_handler('print_settings', None)
  268. self._check_answer(answer, 0, None)
  269. def test_check_config_handler(self):
  270. answer = self.cmdctl.config_handler({'non-exist': 123})
  271. self._check_answer(answer, 1, 'unknown config item: non-exist')
  272. old_env = os.environ
  273. os.environ['B10_FROM_SOURCE'] = '../'
  274. self._check_config(self.cmdctl)
  275. os.environ = old_env
  276. answer = self.cmdctl.config_handler({'key_file': '/user/non-exist_folder'})
  277. self._check_answer(answer, 1, "the file doesn't exist: /user/non-exist_folder")
  278. answer = self.cmdctl.config_handler({'cert_file': '/user/non-exist_folder'})
  279. self._check_answer(answer, 1, "the file doesn't exist: /user/non-exist_folder")
  280. answer = self.cmdctl.config_handler({'accounts_file': '/user/non-exist_folder'})
  281. self._check_answer(answer, 1,
  282. "Invalid accounts file: [Errno 2] No such file or directory: '/user/non-exist_folder'")
  283. # Test with invalid accounts file
  284. file_name = 'tmp.account.file'
  285. temp_file = open(file_name, 'w')
  286. writer = csv.writer(temp_file)
  287. writer.writerow(['a', 'b'])
  288. temp_file.close()
  289. answer = self.cmdctl.config_handler({'accounts_file': file_name})
  290. self._check_answer(answer, 1, "Invalid accounts file: list index out of range")
  291. os.remove(file_name)
  292. def test_send_command(self):
  293. rcode, value = self.cmdctl.send_command(MODULE_NAME, 'print_settings', None)
  294. self.assertEqual(rcode, 0)
  295. class MySecureHTTPServer(SecureHTTPServer):
  296. def server_bind(self):
  297. pass
  298. class TestSecureHTTPServer(unittest.TestCase):
  299. def setUp(self):
  300. self.old_stdout = sys.stdout
  301. sys.stdout = open(os.devnull, 'w')
  302. self.server = MySecureHTTPServer(('localhost', 8080),
  303. MySecureHTTPRequestHandler,
  304. MyCommandControl, verbose=True)
  305. def tearDown(self):
  306. sys.stdout = self.old_stdout
  307. def test_create_user_info(self):
  308. self.server._create_user_info('/local/not-exist')
  309. self.assertEqual(0, len(self.server._user_infos))
  310. self.server._create_user_info('../cmdctl-accounts.csv')
  311. self.assertEqual(1, len(self.server._user_infos))
  312. self.assertTrue('root' in self.server._user_infos)
  313. def test_wrap_sock_in_ssl_context(self):
  314. sock = socket.socket()
  315. self.server._wrap_socket_in_ssl_context(sock,
  316. '../cmdctl-keyfile',
  317. '../cmdctl-certfile')
  318. class TestFuncNotInClass(unittest.TestCase):
  319. def test_check_port(self):
  320. self.assertRaises(OptionValueError, check_port, None, 'port', -1, None)
  321. self.assertRaises(OptionValueError, check_port, None, 'port', 65536, None)
  322. self.assertRaises(OptionValueError, check_addr, None, 'ipstr', 'a.b.d', None)
  323. self.assertRaises(OptionValueError, check_addr, None, 'ipstr', '1::0:a.b', None)
  324. if __name__== "__main__":
  325. unittest.main()