1
0

test_auth.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. # Copyright 2015 - 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from unittest.mock import Mock
  15. import pymacaroons
  16. from synapse.api.auth import Auth
  17. from synapse.api.constants import UserTypes
  18. from synapse.api.errors import (
  19. AuthError,
  20. Codes,
  21. InvalidClientTokenError,
  22. MissingClientTokenError,
  23. ResourceLimitError,
  24. )
  25. from synapse.storage.databases.main.registration import TokenLookupResult
  26. from tests import unittest
  27. from tests.test_utils import simple_async_mock
  28. from tests.utils import mock_getRawHeaders
  29. class AuthTestCase(unittest.HomeserverTestCase):
  30. def prepare(self, reactor, clock, hs):
  31. self.store = Mock()
  32. hs.get_datastore = Mock(return_value=self.store)
  33. hs.get_auth_handler().store = self.store
  34. self.auth = Auth(hs)
  35. # AuthBlocking reads from the hs' config on initialization. We need to
  36. # modify its config instead of the hs'
  37. self.auth_blocking = self.auth._auth_blocking
  38. self.test_user = "@foo:bar"
  39. self.test_token = b"_test_token_"
  40. # this is overridden for the appservice tests
  41. self.store.get_app_service_by_token = Mock(return_value=None)
  42. self.store.insert_client_ip = simple_async_mock(None)
  43. self.store.is_support_user = simple_async_mock(False)
  44. def test_get_user_by_req_user_valid_token(self):
  45. user_info = TokenLookupResult(
  46. user_id=self.test_user, token_id=5, device_id="device"
  47. )
  48. self.store.get_user_by_access_token = simple_async_mock(user_info)
  49. request = Mock(args={})
  50. request.args[b"access_token"] = [self.test_token]
  51. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  52. requester = self.get_success(self.auth.get_user_by_req(request))
  53. self.assertEquals(requester.user.to_string(), self.test_user)
  54. def test_get_user_by_req_user_bad_token(self):
  55. self.store.get_user_by_access_token = simple_async_mock(None)
  56. request = Mock(args={})
  57. request.args[b"access_token"] = [self.test_token]
  58. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  59. f = self.get_failure(
  60. self.auth.get_user_by_req(request), InvalidClientTokenError
  61. ).value
  62. self.assertEqual(f.code, 401)
  63. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  64. def test_get_user_by_req_user_missing_token(self):
  65. user_info = TokenLookupResult(user_id=self.test_user, token_id=5)
  66. self.store.get_user_by_access_token = simple_async_mock(user_info)
  67. request = Mock(args={})
  68. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  69. f = self.get_failure(
  70. self.auth.get_user_by_req(request), MissingClientTokenError
  71. ).value
  72. self.assertEqual(f.code, 401)
  73. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  74. def test_get_user_by_req_appservice_valid_token(self):
  75. app_service = Mock(
  76. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  77. )
  78. self.store.get_app_service_by_token = Mock(return_value=app_service)
  79. self.store.get_user_by_access_token = simple_async_mock(None)
  80. request = Mock(args={})
  81. request.getClientIP.return_value = "127.0.0.1"
  82. request.args[b"access_token"] = [self.test_token]
  83. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  84. requester = self.get_success(self.auth.get_user_by_req(request))
  85. self.assertEquals(requester.user.to_string(), self.test_user)
  86. def test_get_user_by_req_appservice_valid_token_good_ip(self):
  87. from netaddr import IPSet
  88. app_service = Mock(
  89. token="foobar",
  90. url="a_url",
  91. sender=self.test_user,
  92. ip_range_whitelist=IPSet(["192.168/16"]),
  93. )
  94. self.store.get_app_service_by_token = Mock(return_value=app_service)
  95. self.store.get_user_by_access_token = simple_async_mock(None)
  96. request = Mock(args={})
  97. request.getClientIP.return_value = "192.168.10.10"
  98. request.args[b"access_token"] = [self.test_token]
  99. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  100. requester = self.get_success(self.auth.get_user_by_req(request))
  101. self.assertEquals(requester.user.to_string(), self.test_user)
  102. def test_get_user_by_req_appservice_valid_token_bad_ip(self):
  103. from netaddr import IPSet
  104. app_service = Mock(
  105. token="foobar",
  106. url="a_url",
  107. sender=self.test_user,
  108. ip_range_whitelist=IPSet(["192.168/16"]),
  109. )
  110. self.store.get_app_service_by_token = Mock(return_value=app_service)
  111. self.store.get_user_by_access_token = simple_async_mock(None)
  112. request = Mock(args={})
  113. request.getClientIP.return_value = "131.111.8.42"
  114. request.args[b"access_token"] = [self.test_token]
  115. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  116. f = self.get_failure(
  117. self.auth.get_user_by_req(request), InvalidClientTokenError
  118. ).value
  119. self.assertEqual(f.code, 401)
  120. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  121. def test_get_user_by_req_appservice_bad_token(self):
  122. self.store.get_app_service_by_token = Mock(return_value=None)
  123. self.store.get_user_by_access_token = simple_async_mock(None)
  124. request = Mock(args={})
  125. request.args[b"access_token"] = [self.test_token]
  126. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  127. f = self.get_failure(
  128. self.auth.get_user_by_req(request), InvalidClientTokenError
  129. ).value
  130. self.assertEqual(f.code, 401)
  131. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  132. def test_get_user_by_req_appservice_missing_token(self):
  133. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  134. self.store.get_app_service_by_token = Mock(return_value=app_service)
  135. self.store.get_user_by_access_token = simple_async_mock(None)
  136. request = Mock(args={})
  137. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  138. f = self.get_failure(
  139. self.auth.get_user_by_req(request), MissingClientTokenError
  140. ).value
  141. self.assertEqual(f.code, 401)
  142. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  143. def test_get_user_by_req_appservice_valid_token_valid_user_id(self):
  144. masquerading_user_id = b"@doppelganger:matrix.org"
  145. app_service = Mock(
  146. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  147. )
  148. app_service.is_interested_in_user = Mock(return_value=True)
  149. self.store.get_app_service_by_token = Mock(return_value=app_service)
  150. # This just needs to return a truth-y value.
  151. self.store.get_user_by_id = simple_async_mock({"is_guest": False})
  152. self.store.get_user_by_access_token = simple_async_mock(None)
  153. request = Mock(args={})
  154. request.getClientIP.return_value = "127.0.0.1"
  155. request.args[b"access_token"] = [self.test_token]
  156. request.args[b"user_id"] = [masquerading_user_id]
  157. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  158. requester = self.get_success(self.auth.get_user_by_req(request))
  159. self.assertEquals(
  160. requester.user.to_string(), masquerading_user_id.decode("utf8")
  161. )
  162. def test_get_user_by_req_appservice_valid_token_bad_user_id(self):
  163. masquerading_user_id = b"@doppelganger:matrix.org"
  164. app_service = Mock(
  165. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  166. )
  167. app_service.is_interested_in_user = Mock(return_value=False)
  168. self.store.get_app_service_by_token = Mock(return_value=app_service)
  169. self.store.get_user_by_access_token = simple_async_mock(None)
  170. request = Mock(args={})
  171. request.getClientIP.return_value = "127.0.0.1"
  172. request.args[b"access_token"] = [self.test_token]
  173. request.args[b"user_id"] = [masquerading_user_id]
  174. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  175. self.get_failure(self.auth.get_user_by_req(request), AuthError)
  176. def test_get_user_from_macaroon(self):
  177. self.store.get_user_by_access_token = simple_async_mock(
  178. TokenLookupResult(user_id="@baldrick:matrix.org", device_id="device")
  179. )
  180. user_id = "@baldrick:matrix.org"
  181. macaroon = pymacaroons.Macaroon(
  182. location=self.hs.config.server_name,
  183. identifier="key",
  184. key=self.hs.config.macaroon_secret_key,
  185. )
  186. macaroon.add_first_party_caveat("gen = 1")
  187. macaroon.add_first_party_caveat("type = access")
  188. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  189. user_info = self.get_success(
  190. self.auth.get_user_by_access_token(macaroon.serialize())
  191. )
  192. self.assertEqual(user_id, user_info.user_id)
  193. # TODO: device_id should come from the macaroon, but currently comes
  194. # from the db.
  195. self.assertEqual(user_info.device_id, "device")
  196. def test_get_guest_user_from_macaroon(self):
  197. self.store.get_user_by_id = simple_async_mock({"is_guest": True})
  198. self.store.get_user_by_access_token = simple_async_mock(None)
  199. user_id = "@baldrick:matrix.org"
  200. macaroon = pymacaroons.Macaroon(
  201. location=self.hs.config.server_name,
  202. identifier="key",
  203. key=self.hs.config.macaroon_secret_key,
  204. )
  205. macaroon.add_first_party_caveat("gen = 1")
  206. macaroon.add_first_party_caveat("type = access")
  207. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  208. macaroon.add_first_party_caveat("guest = true")
  209. serialized = macaroon.serialize()
  210. user_info = self.get_success(self.auth.get_user_by_access_token(serialized))
  211. self.assertEqual(user_id, user_info.user_id)
  212. self.assertTrue(user_info.is_guest)
  213. self.store.get_user_by_id.assert_called_with(user_id)
  214. def test_blocking_mau(self):
  215. self.auth_blocking._limit_usage_by_mau = False
  216. self.auth_blocking._max_mau_value = 50
  217. lots_of_users = 100
  218. small_number_of_users = 1
  219. # Ensure no error thrown
  220. self.get_success(self.auth.check_auth_blocking())
  221. self.auth_blocking._limit_usage_by_mau = True
  222. self.store.get_monthly_active_count = simple_async_mock(lots_of_users)
  223. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  224. self.assertEquals(e.value.admin_contact, self.hs.config.admin_contact)
  225. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  226. self.assertEquals(e.value.code, 403)
  227. # Ensure does not throw an error
  228. self.store.get_monthly_active_count = simple_async_mock(small_number_of_users)
  229. self.get_success(self.auth.check_auth_blocking())
  230. def test_blocking_mau__depending_on_user_type(self):
  231. self.auth_blocking._max_mau_value = 50
  232. self.auth_blocking._limit_usage_by_mau = True
  233. self.store.get_monthly_active_count = simple_async_mock(100)
  234. # Support users allowed
  235. self.get_success(self.auth.check_auth_blocking(user_type=UserTypes.SUPPORT))
  236. self.store.get_monthly_active_count = simple_async_mock(100)
  237. # Bots not allowed
  238. self.get_failure(
  239. self.auth.check_auth_blocking(user_type=UserTypes.BOT), ResourceLimitError
  240. )
  241. self.store.get_monthly_active_count = simple_async_mock(100)
  242. # Real users not allowed
  243. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  244. def test_reserved_threepid(self):
  245. self.auth_blocking._limit_usage_by_mau = True
  246. self.auth_blocking._max_mau_value = 1
  247. self.store.get_monthly_active_count = simple_async_mock(2)
  248. threepid = {"medium": "email", "address": "reserved@server.com"}
  249. unknown_threepid = {"medium": "email", "address": "unreserved@server.com"}
  250. self.auth_blocking._mau_limits_reserved_threepids = [threepid]
  251. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  252. self.get_failure(
  253. self.auth.check_auth_blocking(threepid=unknown_threepid), ResourceLimitError
  254. )
  255. self.get_success(self.auth.check_auth_blocking(threepid=threepid))
  256. def test_hs_disabled(self):
  257. self.auth_blocking._hs_disabled = True
  258. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  259. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  260. self.assertEquals(e.value.admin_contact, self.hs.config.admin_contact)
  261. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  262. self.assertEquals(e.value.code, 403)
  263. def test_hs_disabled_no_server_notices_user(self):
  264. """Check that 'hs_disabled_message' works correctly when there is no
  265. server_notices user.
  266. """
  267. # this should be the default, but we had a bug where the test was doing the wrong
  268. # thing, so let's make it explicit
  269. self.auth_blocking._server_notices_mxid = None
  270. self.auth_blocking._hs_disabled = True
  271. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  272. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  273. self.assertEquals(e.value.admin_contact, self.hs.config.admin_contact)
  274. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  275. self.assertEquals(e.value.code, 403)
  276. def test_server_notices_mxid_special_cased(self):
  277. self.auth_blocking._hs_disabled = True
  278. user = "@user:server"
  279. self.auth_blocking._server_notices_mxid = user
  280. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  281. self.get_success(self.auth.check_auth_blocking(user))