You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

202 lines
8.3 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016-2017 LasLabs Inc.
  3. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
  4. from datetime import datetime
  5. import mock
  6. import string
  7. from openerp.exceptions import ValidationError
  8. from openerp.tests.common import TransactionCase
  9. from ..exceptions import (
  10. MfaTokenError,
  11. MfaTokenInvalidError,
  12. MfaTokenExpiredError,
  13. )
  14. from ..models.res_users_authenticator import ResUsersAuthenticator
  15. DATETIME_PATH = 'openerp.addons.auth_totp.models.res_users.datetime'
  16. class TestResUsers(TransactionCase):
  17. def setUp(self):
  18. super(TestResUsers, self).setUp()
  19. self.test_user = self.env.ref('base.user_root')
  20. self.test_user.mfa_enabled = False
  21. self.test_user.authenticator_ids = False
  22. self.env.uid = self.test_user.id
  23. def test_check_enabled_with_authenticator_mfa_no_auth(self):
  24. '''Should raise correct error if MFA enabled without authenticators'''
  25. with self.assertRaisesRegexp(ValidationError, 'locked out'):
  26. self.test_user.mfa_enabled = True
  27. def test_check_enabled_with_authenticator_no_mfa_auth(self):
  28. '''Should not raise error if MFA not enabled with authenticators'''
  29. try:
  30. self.env['res.users.authenticator'].create({
  31. 'name': 'Test Name',
  32. 'secret_key': 'Test Key',
  33. 'user_id': self.test_user.id,
  34. })
  35. except ValidationError:
  36. self.fail('A ValidationError was raised and should not have been.')
  37. def test_check_enabled_with_authenticator_mfa_auth(self):
  38. '''Should not raise error if MFA enabled with authenticators'''
  39. try:
  40. self.env['res.users.authenticator'].create({
  41. 'name': 'Test Name',
  42. 'secret_key': 'Test Key',
  43. 'user_id': self.test_user.id,
  44. })
  45. self.test_user.mfa_enabled = True
  46. except ValidationError:
  47. self.fail('A ValidationError was raised and should not have been.')
  48. def test_check_credentials_no_match(self):
  49. '''Should raise appropriate error if there is no match'''
  50. with self.assertRaises(MfaTokenInvalidError):
  51. self.env['res.users'].check_credentials('invalid')
  52. @mock.patch(DATETIME_PATH)
  53. def test_check_credentials_expired(self, datetime_mock):
  54. '''Should raise appropriate error if match based on expired token'''
  55. datetime_mock.now.return_value = datetime(2016, 12, 1)
  56. self.test_user.generate_mfa_login_token()
  57. test_token = self.test_user.mfa_login_token
  58. datetime_mock.now.return_value = datetime(2017, 12, 1)
  59. with self.assertRaises(MfaTokenExpiredError):
  60. self.env['res.users'].check_credentials(test_token)
  61. def test_check_credentials_current(self):
  62. '''Should not raise error if match based on active token'''
  63. self.test_user.generate_mfa_login_token()
  64. test_token = self.test_user.mfa_login_token
  65. try:
  66. self.env['res.users'].check_credentials(test_token)
  67. except MfaTokenError:
  68. self.fail('An MfaTokenError was raised and should not have been.')
  69. def test_generate_mfa_login_token_token_field_content(self):
  70. '''Should set token field to 20 char string of ASCII letters/digits'''
  71. self.test_user.generate_mfa_login_token()
  72. test_chars = set(string.ascii_letters + string.digits)
  73. self.assertEqual(len(self.test_user.mfa_login_token), 20)
  74. self.assertTrue(set(self.test_user.mfa_login_token) <= test_chars)
  75. def test_generate_mfa_login_token_token_field_random(self):
  76. '''Should set token field to new value each time'''
  77. test_tokens = set([])
  78. for __ in xrange(3):
  79. self.test_user.generate_mfa_login_token()
  80. test_tokens.add(self.test_user.mfa_login_token)
  81. self.assertEqual(len(test_tokens), 3)
  82. @mock.patch(DATETIME_PATH)
  83. def test_generate_mfa_login_token_exp_field_default(self, datetime_mock):
  84. '''Should set token lifetime to 15 minutes if no argument provided'''
  85. datetime_mock.now.return_value = datetime(2016, 12, 1)
  86. self.test_user.generate_mfa_login_token()
  87. self.assertEqual(
  88. self.test_user.mfa_login_token_exp,
  89. '2016-12-01 00:15:00'
  90. )
  91. @mock.patch(DATETIME_PATH)
  92. def test_generate_mfa_login_token_exp_field_custom(self, datetime_mock):
  93. '''Should set token lifetime to value provided'''
  94. datetime_mock.now.return_value = datetime(2016, 12, 1)
  95. self.test_user.generate_mfa_login_token(45)
  96. self.assertEqual(
  97. self.test_user.mfa_login_token_exp,
  98. '2016-12-01 00:45:00'
  99. )
  100. def test_user_from_mfa_login_token_validate_not_singleton(self):
  101. '''Should raise correct error when recordset is not a singleton'''
  102. self.test_user.copy()
  103. test_set = self.env['res.users'].search([('id', '>', 0)], limit=2)
  104. with self.assertRaises(MfaTokenInvalidError):
  105. self.env['res.users']._user_from_mfa_login_token_validate()
  106. with self.assertRaises(MfaTokenInvalidError):
  107. test_set._user_from_mfa_login_token_validate()
  108. @mock.patch(DATETIME_PATH)
  109. def test_user_from_mfa_login_token_validate_expired(self, datetime_mock):
  110. '''Should raise correct error when record has expired token'''
  111. datetime_mock.now.return_value = datetime(2016, 12, 1)
  112. self.test_user.generate_mfa_login_token()
  113. datetime_mock.now.return_value = datetime(2017, 12, 1)
  114. with self.assertRaises(MfaTokenExpiredError):
  115. self.test_user._user_from_mfa_login_token_validate()
  116. def test_user_from_mfa_login_token_validate_current_singleton(self):
  117. '''Should not raise error when one record with active token'''
  118. self.test_user.generate_mfa_login_token()
  119. try:
  120. self.test_user._user_from_mfa_login_token_validate()
  121. except MfaTokenError:
  122. self.fail('An MfaTokenError was raised and should not have been.')
  123. def test_user_from_mfa_login_token_match(self):
  124. '''Should retreive correct user when there is a current match'''
  125. self.test_user.generate_mfa_login_token()
  126. test_token = self.test_user.mfa_login_token
  127. self.assertEqual(
  128. self.env['res.users'].user_from_mfa_login_token(test_token),
  129. self.test_user,
  130. )
  131. def test_user_from_mfa_login_token_falsy(self):
  132. '''Should raise correct error when token is falsy'''
  133. with self.assertRaises(MfaTokenInvalidError):
  134. self.env['res.users'].user_from_mfa_login_token(None)
  135. def test_user_from_mfa_login_token_no_match(self):
  136. '''Should raise correct error when there is no match'''
  137. with self.assertRaises(MfaTokenInvalidError):
  138. self.env['res.users'].user_from_mfa_login_token('Test Token')
  139. @mock.patch(DATETIME_PATH)
  140. def test_user_from_mfa_login_token_match_expired(self, datetime_mock):
  141. '''Should raise correct error when the match is expired'''
  142. datetime_mock.now.return_value = datetime(2016, 12, 1)
  143. self.test_user.generate_mfa_login_token()
  144. test_token = self.test_user.mfa_login_token
  145. datetime_mock.now.return_value = datetime(2017, 12, 1)
  146. with self.assertRaises(MfaTokenExpiredError):
  147. self.env['res.users'].user_from_mfa_login_token(test_token)
  148. def test_validate_mfa_confirmation_code_not_singleton(self):
  149. '''Should raise correct error when recordset is not singleton'''
  150. test_user_2 = self.env['res.users']
  151. test_user_3 = self.env.ref('base.public_user')
  152. test_set = self.test_user + test_user_3
  153. with self.assertRaisesRegexp(ValueError, 'Expected singleton'):
  154. test_user_2.validate_mfa_confirmation_code('Test Code')
  155. with self.assertRaisesRegexp(ValueError, 'Expected singleton'):
  156. test_set.validate_mfa_confirmation_code('Test Code')
  157. @mock.patch.object(ResUsersAuthenticator, 'validate_conf_code')
  158. def test_validate_mfa_confirmation_code_singleton_return(self, mock_func):
  159. '''Should return validate_conf_code() value if singleton recordset'''
  160. mock_func.return_value = 'Test Result'
  161. self.assertEqual(
  162. self.test_user.validate_mfa_confirmation_code('Test Code'),
  163. 'Test Result',
  164. )