test_auth.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  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. from mock import Mock
  16. import pymacaroons
  17. from twisted.internet import defer
  18. import synapse
  19. import synapse.api.errors
  20. from synapse.api.errors import ResourceLimitError
  21. from tests import unittest
  22. from tests.test_utils import make_awaitable
  23. from tests.utils import setup_test_homeserver
  24. class AuthTestCase(unittest.TestCase):
  25. @defer.inlineCallbacks
  26. def setUp(self):
  27. self.hs = yield setup_test_homeserver(self.addCleanup)
  28. self.auth_handler = self.hs.get_auth_handler()
  29. self.macaroon_generator = self.hs.get_macaroon_generator()
  30. # MAU tests
  31. # AuthBlocking reads from the hs' config on initialization. We need to
  32. # modify its config instead of the hs'
  33. self.auth_blocking = self.hs.get_auth()._auth_blocking
  34. self.auth_blocking._max_mau_value = 50
  35. self.small_number_of_users = 1
  36. self.large_number_of_users = 100
  37. def test_token_is_a_macaroon(self):
  38. token = self.macaroon_generator.generate_access_token("some_user")
  39. # Check that we can parse the thing with pymacaroons
  40. macaroon = pymacaroons.Macaroon.deserialize(token)
  41. # The most basic of sanity checks
  42. if "some_user" not in macaroon.inspect():
  43. self.fail("some_user was not in %s" % macaroon.inspect())
  44. def test_macaroon_caveats(self):
  45. self.hs.get_clock().now = 5000
  46. token = self.macaroon_generator.generate_access_token("a_user")
  47. macaroon = pymacaroons.Macaroon.deserialize(token)
  48. def verify_gen(caveat):
  49. return caveat == "gen = 1"
  50. def verify_user(caveat):
  51. return caveat == "user_id = a_user"
  52. def verify_type(caveat):
  53. return caveat == "type = access"
  54. def verify_nonce(caveat):
  55. return caveat.startswith("nonce =")
  56. v = pymacaroons.Verifier()
  57. v.satisfy_general(verify_gen)
  58. v.satisfy_general(verify_user)
  59. v.satisfy_general(verify_type)
  60. v.satisfy_general(verify_nonce)
  61. v.verify(macaroon, self.hs.config.macaroon_secret_key)
  62. @defer.inlineCallbacks
  63. def test_short_term_login_token_gives_user_id(self):
  64. self.hs.get_clock().now = 1000
  65. token = self.macaroon_generator.generate_short_term_login_token("a_user", 5000)
  66. user_id = yield defer.ensureDeferred(
  67. self.auth_handler.validate_short_term_login_token_and_get_user_id(token)
  68. )
  69. self.assertEqual("a_user", user_id)
  70. # when we advance the clock, the token should be rejected
  71. self.hs.get_clock().now = 6000
  72. with self.assertRaises(synapse.api.errors.AuthError):
  73. yield defer.ensureDeferred(
  74. self.auth_handler.validate_short_term_login_token_and_get_user_id(token)
  75. )
  76. @defer.inlineCallbacks
  77. def test_short_term_login_token_cannot_replace_user_id(self):
  78. token = self.macaroon_generator.generate_short_term_login_token("a_user", 5000)
  79. macaroon = pymacaroons.Macaroon.deserialize(token)
  80. user_id = yield defer.ensureDeferred(
  81. self.auth_handler.validate_short_term_login_token_and_get_user_id(
  82. macaroon.serialize()
  83. )
  84. )
  85. self.assertEqual("a_user", user_id)
  86. # add another "user_id" caveat, which might allow us to override the
  87. # user_id.
  88. macaroon.add_first_party_caveat("user_id = b_user")
  89. with self.assertRaises(synapse.api.errors.AuthError):
  90. yield defer.ensureDeferred(
  91. self.auth_handler.validate_short_term_login_token_and_get_user_id(
  92. macaroon.serialize()
  93. )
  94. )
  95. @defer.inlineCallbacks
  96. def test_mau_limits_disabled(self):
  97. self.auth_blocking._limit_usage_by_mau = False
  98. # Ensure does not throw exception
  99. yield defer.ensureDeferred(
  100. self.auth_handler.get_access_token_for_user_id(
  101. "user_a", device_id=None, valid_until_ms=None
  102. )
  103. )
  104. yield defer.ensureDeferred(
  105. self.auth_handler.validate_short_term_login_token_and_get_user_id(
  106. self._get_macaroon().serialize()
  107. )
  108. )
  109. @defer.inlineCallbacks
  110. def test_mau_limits_exceeded_large(self):
  111. self.auth_blocking._limit_usage_by_mau = True
  112. self.hs.get_datastore().get_monthly_active_count = Mock(
  113. return_value=make_awaitable(self.large_number_of_users)
  114. )
  115. with self.assertRaises(ResourceLimitError):
  116. yield defer.ensureDeferred(
  117. self.auth_handler.get_access_token_for_user_id(
  118. "user_a", device_id=None, valid_until_ms=None
  119. )
  120. )
  121. self.hs.get_datastore().get_monthly_active_count = Mock(
  122. return_value=make_awaitable(self.large_number_of_users)
  123. )
  124. with self.assertRaises(ResourceLimitError):
  125. yield defer.ensureDeferred(
  126. self.auth_handler.validate_short_term_login_token_and_get_user_id(
  127. self._get_macaroon().serialize()
  128. )
  129. )
  130. @defer.inlineCallbacks
  131. def test_mau_limits_parity(self):
  132. self.auth_blocking._limit_usage_by_mau = True
  133. # If not in monthly active cohort
  134. self.hs.get_datastore().get_monthly_active_count = Mock(
  135. return_value=make_awaitable(self.auth_blocking._max_mau_value)
  136. )
  137. with self.assertRaises(ResourceLimitError):
  138. yield defer.ensureDeferred(
  139. self.auth_handler.get_access_token_for_user_id(
  140. "user_a", device_id=None, valid_until_ms=None
  141. )
  142. )
  143. self.hs.get_datastore().get_monthly_active_count = Mock(
  144. return_value=make_awaitable(self.auth_blocking._max_mau_value)
  145. )
  146. with self.assertRaises(ResourceLimitError):
  147. yield defer.ensureDeferred(
  148. self.auth_handler.validate_short_term_login_token_and_get_user_id(
  149. self._get_macaroon().serialize()
  150. )
  151. )
  152. # If in monthly active cohort
  153. self.hs.get_datastore().user_last_seen_monthly_active = Mock(
  154. return_value=make_awaitable(self.hs.get_clock().time_msec())
  155. )
  156. self.hs.get_datastore().get_monthly_active_count = Mock(
  157. return_value=make_awaitable(self.auth_blocking._max_mau_value)
  158. )
  159. yield defer.ensureDeferred(
  160. self.auth_handler.get_access_token_for_user_id(
  161. "user_a", device_id=None, valid_until_ms=None
  162. )
  163. )
  164. self.hs.get_datastore().user_last_seen_monthly_active = Mock(
  165. return_value=make_awaitable(self.hs.get_clock().time_msec())
  166. )
  167. self.hs.get_datastore().get_monthly_active_count = Mock(
  168. return_value=make_awaitable(self.auth_blocking._max_mau_value)
  169. )
  170. yield defer.ensureDeferred(
  171. self.auth_handler.validate_short_term_login_token_and_get_user_id(
  172. self._get_macaroon().serialize()
  173. )
  174. )
  175. @defer.inlineCallbacks
  176. def test_mau_limits_not_exceeded(self):
  177. self.auth_blocking._limit_usage_by_mau = True
  178. self.hs.get_datastore().get_monthly_active_count = Mock(
  179. return_value=make_awaitable(self.small_number_of_users)
  180. )
  181. # Ensure does not raise exception
  182. yield defer.ensureDeferred(
  183. self.auth_handler.get_access_token_for_user_id(
  184. "user_a", device_id=None, valid_until_ms=None
  185. )
  186. )
  187. self.hs.get_datastore().get_monthly_active_count = Mock(
  188. return_value=make_awaitable(self.small_number_of_users)
  189. )
  190. yield defer.ensureDeferred(
  191. self.auth_handler.validate_short_term_login_token_and_get_user_id(
  192. self._get_macaroon().serialize()
  193. )
  194. )
  195. def _get_macaroon(self):
  196. token = self.macaroon_generator.generate_short_term_login_token("user_a", 5000)
  197. return pymacaroons.Macaroon.deserialize(token)