test_auth.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 synapse.api.auth import Auth
  18. from synapse.api.constants import UserTypes
  19. from synapse.api.errors import (
  20. AuthError,
  21. Codes,
  22. InvalidClientCredentialsError,
  23. InvalidClientTokenError,
  24. MissingClientTokenError,
  25. ResourceLimitError,
  26. )
  27. from synapse.storage.databases.main.registration import TokenLookupResult
  28. from synapse.types import UserID
  29. from tests import unittest
  30. from tests.test_utils import simple_async_mock
  31. from tests.utils import mock_getRawHeaders
  32. class AuthTestCase(unittest.HomeserverTestCase):
  33. def prepare(self, reactor, clock, hs):
  34. self.store = Mock()
  35. hs.get_datastore = Mock(return_value=self.store)
  36. hs.get_auth_handler().store = self.store
  37. self.auth = Auth(hs)
  38. # AuthBlocking reads from the hs' config on initialization. We need to
  39. # modify its config instead of the hs'
  40. self.auth_blocking = self.auth._auth_blocking
  41. self.test_user = "@foo:bar"
  42. self.test_token = b"_test_token_"
  43. # this is overridden for the appservice tests
  44. self.store.get_app_service_by_token = Mock(return_value=None)
  45. self.store.insert_client_ip = simple_async_mock(None)
  46. self.store.is_support_user = simple_async_mock(False)
  47. def test_get_user_by_req_user_valid_token(self):
  48. user_info = TokenLookupResult(
  49. user_id=self.test_user, token_id=5, device_id="device"
  50. )
  51. self.store.get_user_by_access_token = simple_async_mock(user_info)
  52. request = Mock(args={})
  53. request.args[b"access_token"] = [self.test_token]
  54. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  55. requester = self.get_success(self.auth.get_user_by_req(request))
  56. self.assertEquals(requester.user.to_string(), self.test_user)
  57. def test_get_user_by_req_user_bad_token(self):
  58. self.store.get_user_by_access_token = simple_async_mock(None)
  59. request = Mock(args={})
  60. request.args[b"access_token"] = [self.test_token]
  61. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  62. f = self.get_failure(
  63. self.auth.get_user_by_req(request), InvalidClientTokenError
  64. ).value
  65. self.assertEqual(f.code, 401)
  66. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  67. def test_get_user_by_req_user_missing_token(self):
  68. user_info = TokenLookupResult(user_id=self.test_user, token_id=5)
  69. self.store.get_user_by_access_token = simple_async_mock(user_info)
  70. request = Mock(args={})
  71. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  72. f = self.get_failure(
  73. self.auth.get_user_by_req(request), MissingClientTokenError
  74. ).value
  75. self.assertEqual(f.code, 401)
  76. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  77. def test_get_user_by_req_appservice_valid_token(self):
  78. app_service = Mock(
  79. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  80. )
  81. self.store.get_app_service_by_token = Mock(return_value=app_service)
  82. self.store.get_user_by_access_token = simple_async_mock(None)
  83. request = Mock(args={})
  84. request.getClientIP.return_value = "127.0.0.1"
  85. request.args[b"access_token"] = [self.test_token]
  86. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  87. requester = self.get_success(self.auth.get_user_by_req(request))
  88. self.assertEquals(requester.user.to_string(), self.test_user)
  89. def test_get_user_by_req_appservice_valid_token_good_ip(self):
  90. from netaddr import IPSet
  91. app_service = Mock(
  92. token="foobar",
  93. url="a_url",
  94. sender=self.test_user,
  95. ip_range_whitelist=IPSet(["192.168/16"]),
  96. )
  97. self.store.get_app_service_by_token = Mock(return_value=app_service)
  98. self.store.get_user_by_access_token = simple_async_mock(None)
  99. request = Mock(args={})
  100. request.getClientIP.return_value = "192.168.10.10"
  101. request.args[b"access_token"] = [self.test_token]
  102. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  103. requester = self.get_success(self.auth.get_user_by_req(request))
  104. self.assertEquals(requester.user.to_string(), self.test_user)
  105. def test_get_user_by_req_appservice_valid_token_bad_ip(self):
  106. from netaddr import IPSet
  107. app_service = Mock(
  108. token="foobar",
  109. url="a_url",
  110. sender=self.test_user,
  111. ip_range_whitelist=IPSet(["192.168/16"]),
  112. )
  113. self.store.get_app_service_by_token = Mock(return_value=app_service)
  114. self.store.get_user_by_access_token = simple_async_mock(None)
  115. request = Mock(args={})
  116. request.getClientIP.return_value = "131.111.8.42"
  117. request.args[b"access_token"] = [self.test_token]
  118. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  119. f = self.get_failure(
  120. self.auth.get_user_by_req(request), InvalidClientTokenError
  121. ).value
  122. self.assertEqual(f.code, 401)
  123. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  124. def test_get_user_by_req_appservice_bad_token(self):
  125. self.store.get_app_service_by_token = Mock(return_value=None)
  126. self.store.get_user_by_access_token = simple_async_mock(None)
  127. request = Mock(args={})
  128. request.args[b"access_token"] = [self.test_token]
  129. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  130. f = self.get_failure(
  131. self.auth.get_user_by_req(request), InvalidClientTokenError
  132. ).value
  133. self.assertEqual(f.code, 401)
  134. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  135. def test_get_user_by_req_appservice_missing_token(self):
  136. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  137. self.store.get_app_service_by_token = Mock(return_value=app_service)
  138. self.store.get_user_by_access_token = simple_async_mock(None)
  139. request = Mock(args={})
  140. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  141. f = self.get_failure(
  142. self.auth.get_user_by_req(request), MissingClientTokenError
  143. ).value
  144. self.assertEqual(f.code, 401)
  145. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  146. def test_get_user_by_req_appservice_valid_token_valid_user_id(self):
  147. masquerading_user_id = b"@doppelganger:matrix.org"
  148. app_service = Mock(
  149. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  150. )
  151. app_service.is_interested_in_user = Mock(return_value=True)
  152. self.store.get_app_service_by_token = Mock(return_value=app_service)
  153. # This just needs to return a truth-y value.
  154. self.store.get_user_by_id = simple_async_mock({"is_guest": False})
  155. self.store.get_user_by_access_token = simple_async_mock(None)
  156. request = Mock(args={})
  157. request.getClientIP.return_value = "127.0.0.1"
  158. request.args[b"access_token"] = [self.test_token]
  159. request.args[b"user_id"] = [masquerading_user_id]
  160. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  161. requester = self.get_success(self.auth.get_user_by_req(request))
  162. self.assertEquals(
  163. requester.user.to_string(), masquerading_user_id.decode("utf8")
  164. )
  165. def test_get_user_by_req_appservice_valid_token_bad_user_id(self):
  166. masquerading_user_id = b"@doppelganger:matrix.org"
  167. app_service = Mock(
  168. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  169. )
  170. app_service.is_interested_in_user = Mock(return_value=False)
  171. self.store.get_app_service_by_token = Mock(return_value=app_service)
  172. self.store.get_user_by_access_token = simple_async_mock(None)
  173. request = Mock(args={})
  174. request.getClientIP.return_value = "127.0.0.1"
  175. request.args[b"access_token"] = [self.test_token]
  176. request.args[b"user_id"] = [masquerading_user_id]
  177. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  178. self.get_failure(self.auth.get_user_by_req(request), AuthError)
  179. def test_get_user_from_macaroon(self):
  180. self.store.get_user_by_access_token = simple_async_mock(
  181. TokenLookupResult(user_id="@baldrick:matrix.org", device_id="device")
  182. )
  183. user_id = "@baldrick:matrix.org"
  184. macaroon = pymacaroons.Macaroon(
  185. location=self.hs.config.server_name,
  186. identifier="key",
  187. key=self.hs.config.macaroon_secret_key,
  188. )
  189. macaroon.add_first_party_caveat("gen = 1")
  190. macaroon.add_first_party_caveat("type = access")
  191. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  192. user_info = self.get_success(
  193. self.auth.get_user_by_access_token(macaroon.serialize())
  194. )
  195. self.assertEqual(user_id, user_info.user_id)
  196. # TODO: device_id should come from the macaroon, but currently comes
  197. # from the db.
  198. self.assertEqual(user_info.device_id, "device")
  199. def test_get_guest_user_from_macaroon(self):
  200. self.store.get_user_by_id = simple_async_mock({"is_guest": True})
  201. self.store.get_user_by_access_token = simple_async_mock(None)
  202. user_id = "@baldrick:matrix.org"
  203. macaroon = pymacaroons.Macaroon(
  204. location=self.hs.config.server_name,
  205. identifier="key",
  206. key=self.hs.config.macaroon_secret_key,
  207. )
  208. macaroon.add_first_party_caveat("gen = 1")
  209. macaroon.add_first_party_caveat("type = access")
  210. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  211. macaroon.add_first_party_caveat("guest = true")
  212. serialized = macaroon.serialize()
  213. user_info = self.get_success(self.auth.get_user_by_access_token(serialized))
  214. self.assertEqual(user_id, user_info.user_id)
  215. self.assertTrue(user_info.is_guest)
  216. self.store.get_user_by_id.assert_called_with(user_id)
  217. def test_cannot_use_regular_token_as_guest(self):
  218. USER_ID = "@percy:matrix.org"
  219. self.store.add_access_token_to_user = simple_async_mock(None)
  220. self.store.get_device = simple_async_mock(None)
  221. token = self.get_success(
  222. self.hs.get_auth_handler().get_access_token_for_user_id(
  223. USER_ID, "DEVICE", valid_until_ms=None
  224. )
  225. )
  226. self.store.add_access_token_to_user.assert_called_with(
  227. user_id=USER_ID,
  228. token=token,
  229. device_id="DEVICE",
  230. valid_until_ms=None,
  231. puppets_user_id=None,
  232. )
  233. async def get_user(tok):
  234. if token != tok:
  235. return None
  236. return TokenLookupResult(
  237. user_id=USER_ID,
  238. is_guest=False,
  239. token_id=1234,
  240. device_id="DEVICE",
  241. )
  242. self.store.get_user_by_access_token = get_user
  243. self.store.get_user_by_id = simple_async_mock({"is_guest": False})
  244. # check the token works
  245. request = Mock(args={})
  246. request.args[b"access_token"] = [token.encode("ascii")]
  247. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  248. requester = self.get_success(
  249. self.auth.get_user_by_req(request, allow_guest=True)
  250. )
  251. self.assertEqual(UserID.from_string(USER_ID), requester.user)
  252. self.assertFalse(requester.is_guest)
  253. # add an is_guest caveat
  254. mac = pymacaroons.Macaroon.deserialize(token)
  255. mac.add_first_party_caveat("guest = true")
  256. guest_tok = mac.serialize()
  257. # the token should *not* work now
  258. request = Mock(args={})
  259. request.args[b"access_token"] = [guest_tok.encode("ascii")]
  260. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  261. cm = self.get_failure(
  262. self.auth.get_user_by_req(request, allow_guest=True),
  263. InvalidClientCredentialsError,
  264. )
  265. self.assertEqual(401, cm.value.code)
  266. self.assertEqual("Guest access token used for regular user", cm.value.msg)
  267. self.store.get_user_by_id.assert_called_with(USER_ID)
  268. def test_blocking_mau(self):
  269. self.auth_blocking._limit_usage_by_mau = False
  270. self.auth_blocking._max_mau_value = 50
  271. lots_of_users = 100
  272. small_number_of_users = 1
  273. # Ensure no error thrown
  274. self.get_success(self.auth.check_auth_blocking())
  275. self.auth_blocking._limit_usage_by_mau = True
  276. self.store.get_monthly_active_count = simple_async_mock(lots_of_users)
  277. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  278. self.assertEquals(e.value.admin_contact, self.hs.config.admin_contact)
  279. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  280. self.assertEquals(e.value.code, 403)
  281. # Ensure does not throw an error
  282. self.store.get_monthly_active_count = simple_async_mock(small_number_of_users)
  283. self.get_success(self.auth.check_auth_blocking())
  284. def test_blocking_mau__depending_on_user_type(self):
  285. self.auth_blocking._max_mau_value = 50
  286. self.auth_blocking._limit_usage_by_mau = True
  287. self.store.get_monthly_active_count = simple_async_mock(100)
  288. # Support users allowed
  289. self.get_success(self.auth.check_auth_blocking(user_type=UserTypes.SUPPORT))
  290. self.store.get_monthly_active_count = simple_async_mock(100)
  291. # Bots not allowed
  292. self.get_failure(
  293. self.auth.check_auth_blocking(user_type=UserTypes.BOT), ResourceLimitError
  294. )
  295. self.store.get_monthly_active_count = simple_async_mock(100)
  296. # Real users not allowed
  297. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  298. def test_reserved_threepid(self):
  299. self.auth_blocking._limit_usage_by_mau = True
  300. self.auth_blocking._max_mau_value = 1
  301. self.store.get_monthly_active_count = simple_async_mock(2)
  302. threepid = {"medium": "email", "address": "reserved@server.com"}
  303. unknown_threepid = {"medium": "email", "address": "unreserved@server.com"}
  304. self.auth_blocking._mau_limits_reserved_threepids = [threepid]
  305. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  306. self.get_failure(
  307. self.auth.check_auth_blocking(threepid=unknown_threepid), ResourceLimitError
  308. )
  309. self.get_success(self.auth.check_auth_blocking(threepid=threepid))
  310. def test_hs_disabled(self):
  311. self.auth_blocking._hs_disabled = True
  312. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  313. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  314. self.assertEquals(e.value.admin_contact, self.hs.config.admin_contact)
  315. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  316. self.assertEquals(e.value.code, 403)
  317. def test_hs_disabled_no_server_notices_user(self):
  318. """Check that 'hs_disabled_message' works correctly when there is no
  319. server_notices user.
  320. """
  321. # this should be the default, but we had a bug where the test was doing the wrong
  322. # thing, so let's make it explicit
  323. self.auth_blocking._server_notices_mxid = None
  324. self.auth_blocking._hs_disabled = True
  325. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  326. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  327. self.assertEquals(e.value.admin_contact, self.hs.config.admin_contact)
  328. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  329. self.assertEquals(e.value.code, 403)
  330. def test_server_notices_mxid_special_cased(self):
  331. self.auth_blocking._hs_disabled = True
  332. user = "@user:server"
  333. self.auth_blocking._server_notices_mxid = user
  334. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  335. self.get_success(self.auth.check_auth_blocking(user))