test_auth.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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.handlers.auth
  19. from synapse.api.auth import Auth
  20. from synapse.api.errors import AuthError, Codes, ResourceLimitError
  21. from synapse.types import UserID
  22. from tests import unittest
  23. from tests.utils import mock_getRawHeaders, setup_test_homeserver
  24. class TestHandlers(object):
  25. def __init__(self, hs):
  26. self.auth_handler = synapse.handlers.auth.AuthHandler(hs)
  27. class AuthTestCase(unittest.TestCase):
  28. @defer.inlineCallbacks
  29. def setUp(self):
  30. self.state_handler = Mock()
  31. self.store = Mock()
  32. self.hs = yield setup_test_homeserver(self.addCleanup, handlers=None)
  33. self.hs.get_datastore = Mock(return_value=self.store)
  34. self.hs.handlers = TestHandlers(self.hs)
  35. self.auth = Auth(self.hs)
  36. self.test_user = "@foo:bar"
  37. self.test_token = b"_test_token_"
  38. # this is overridden for the appservice tests
  39. self.store.get_app_service_by_token = Mock(return_value=None)
  40. self.store.is_support_user = Mock(return_value=defer.succeed(False))
  41. @defer.inlineCallbacks
  42. def test_get_user_by_req_user_valid_token(self):
  43. user_info = {"name": self.test_user, "token_id": "ditto", "device_id": "device"}
  44. self.store.get_user_by_access_token = Mock(return_value=user_info)
  45. request = Mock(args={})
  46. request.args[b"access_token"] = [self.test_token]
  47. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  48. requester = yield self.auth.get_user_by_req(request)
  49. self.assertEquals(requester.user.to_string(), self.test_user)
  50. def test_get_user_by_req_user_bad_token(self):
  51. self.store.get_user_by_access_token = Mock(return_value=None)
  52. request = Mock(args={})
  53. request.args[b"access_token"] = [self.test_token]
  54. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  55. d = self.auth.get_user_by_req(request)
  56. self.failureResultOf(d, AuthError)
  57. def test_get_user_by_req_user_missing_token(self):
  58. user_info = {"name": self.test_user, "token_id": "ditto"}
  59. self.store.get_user_by_access_token = Mock(return_value=user_info)
  60. request = Mock(args={})
  61. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  62. d = self.auth.get_user_by_req(request)
  63. self.failureResultOf(d, AuthError)
  64. @defer.inlineCallbacks
  65. def test_get_user_by_req_appservice_valid_token(self):
  66. app_service = Mock(
  67. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  68. )
  69. self.store.get_app_service_by_token = Mock(return_value=app_service)
  70. self.store.get_user_by_access_token = Mock(return_value=None)
  71. request = Mock(args={})
  72. request.getClientIP.return_value = "127.0.0.1"
  73. request.args[b"access_token"] = [self.test_token]
  74. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  75. requester = yield self.auth.get_user_by_req(request)
  76. self.assertEquals(requester.user.to_string(), self.test_user)
  77. @defer.inlineCallbacks
  78. def test_get_user_by_req_appservice_valid_token_good_ip(self):
  79. from netaddr import IPSet
  80. app_service = Mock(
  81. token="foobar",
  82. url="a_url",
  83. sender=self.test_user,
  84. ip_range_whitelist=IPSet(["192.168/16"]),
  85. )
  86. self.store.get_app_service_by_token = Mock(return_value=app_service)
  87. self.store.get_user_by_access_token = Mock(return_value=None)
  88. request = Mock(args={})
  89. request.getClientIP.return_value = "192.168.10.10"
  90. request.args[b"access_token"] = [self.test_token]
  91. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  92. requester = yield self.auth.get_user_by_req(request)
  93. self.assertEquals(requester.user.to_string(), self.test_user)
  94. def test_get_user_by_req_appservice_valid_token_bad_ip(self):
  95. from netaddr import IPSet
  96. app_service = Mock(
  97. token="foobar",
  98. url="a_url",
  99. sender=self.test_user,
  100. ip_range_whitelist=IPSet(["192.168/16"]),
  101. )
  102. self.store.get_app_service_by_token = Mock(return_value=app_service)
  103. self.store.get_user_by_access_token = Mock(return_value=None)
  104. request = Mock(args={})
  105. request.getClientIP.return_value = "131.111.8.42"
  106. request.args[b"access_token"] = [self.test_token]
  107. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  108. d = self.auth.get_user_by_req(request)
  109. self.failureResultOf(d, AuthError)
  110. def test_get_user_by_req_appservice_bad_token(self):
  111. self.store.get_app_service_by_token = Mock(return_value=None)
  112. self.store.get_user_by_access_token = Mock(return_value=None)
  113. request = Mock(args={})
  114. request.args[b"access_token"] = [self.test_token]
  115. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  116. d = self.auth.get_user_by_req(request)
  117. self.failureResultOf(d, AuthError)
  118. def test_get_user_by_req_appservice_missing_token(self):
  119. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  120. self.store.get_app_service_by_token = Mock(return_value=app_service)
  121. self.store.get_user_by_access_token = Mock(return_value=None)
  122. request = Mock(args={})
  123. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  124. d = self.auth.get_user_by_req(request)
  125. self.failureResultOf(d, AuthError)
  126. @defer.inlineCallbacks
  127. def test_get_user_by_req_appservice_valid_token_valid_user_id(self):
  128. masquerading_user_id = b"@doppelganger:matrix.org"
  129. app_service = Mock(
  130. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  131. )
  132. app_service.is_interested_in_user = Mock(return_value=True)
  133. self.store.get_app_service_by_token = Mock(return_value=app_service)
  134. self.store.get_user_by_access_token = Mock(return_value=None)
  135. request = Mock(args={})
  136. request.getClientIP.return_value = "127.0.0.1"
  137. request.args[b"access_token"] = [self.test_token]
  138. request.args[b"user_id"] = [masquerading_user_id]
  139. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  140. requester = yield self.auth.get_user_by_req(request)
  141. self.assertEquals(
  142. requester.user.to_string(), masquerading_user_id.decode('utf8')
  143. )
  144. def test_get_user_by_req_appservice_valid_token_bad_user_id(self):
  145. masquerading_user_id = b"@doppelganger:matrix.org"
  146. app_service = Mock(
  147. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  148. )
  149. app_service.is_interested_in_user = Mock(return_value=False)
  150. self.store.get_app_service_by_token = Mock(return_value=app_service)
  151. self.store.get_user_by_access_token = Mock(return_value=None)
  152. request = Mock(args={})
  153. request.getClientIP.return_value = "127.0.0.1"
  154. request.args[b"access_token"] = [self.test_token]
  155. request.args[b"user_id"] = [masquerading_user_id]
  156. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  157. d = self.auth.get_user_by_req(request)
  158. self.failureResultOf(d, AuthError)
  159. @defer.inlineCallbacks
  160. def test_get_user_from_macaroon(self):
  161. self.store.get_user_by_access_token = Mock(
  162. return_value={"name": "@baldrick:matrix.org", "device_id": "device"}
  163. )
  164. user_id = "@baldrick:matrix.org"
  165. macaroon = pymacaroons.Macaroon(
  166. location=self.hs.config.server_name,
  167. identifier="key",
  168. key=self.hs.config.macaroon_secret_key,
  169. )
  170. macaroon.add_first_party_caveat("gen = 1")
  171. macaroon.add_first_party_caveat("type = access")
  172. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  173. user_info = yield self.auth.get_user_by_access_token(macaroon.serialize())
  174. user = user_info["user"]
  175. self.assertEqual(UserID.from_string(user_id), user)
  176. # TODO: device_id should come from the macaroon, but currently comes
  177. # from the db.
  178. self.assertEqual(user_info["device_id"], "device")
  179. @defer.inlineCallbacks
  180. def test_get_guest_user_from_macaroon(self):
  181. self.store.get_user_by_id = Mock(return_value={"is_guest": True})
  182. self.store.get_user_by_access_token = Mock(return_value=None)
  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. macaroon.add_first_party_caveat("guest = true")
  193. serialized = macaroon.serialize()
  194. user_info = yield self.auth.get_user_by_access_token(serialized)
  195. user = user_info["user"]
  196. is_guest = user_info["is_guest"]
  197. self.assertEqual(UserID.from_string(user_id), user)
  198. self.assertTrue(is_guest)
  199. self.store.get_user_by_id.assert_called_with(user_id)
  200. @defer.inlineCallbacks
  201. def test_cannot_use_regular_token_as_guest(self):
  202. USER_ID = "@percy:matrix.org"
  203. self.store.add_access_token_to_user = Mock()
  204. token = yield self.hs.handlers.auth_handler.issue_access_token(
  205. USER_ID, "DEVICE"
  206. )
  207. self.store.add_access_token_to_user.assert_called_with(USER_ID, token, "DEVICE")
  208. def get_user(tok):
  209. if token != tok:
  210. return None
  211. return {
  212. "name": USER_ID,
  213. "is_guest": False,
  214. "token_id": 1234,
  215. "device_id": "DEVICE",
  216. }
  217. self.store.get_user_by_access_token = get_user
  218. self.store.get_user_by_id = Mock(return_value={"is_guest": False})
  219. # check the token works
  220. request = Mock(args={})
  221. request.args[b"access_token"] = [token.encode('ascii')]
  222. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  223. requester = yield self.auth.get_user_by_req(request, allow_guest=True)
  224. self.assertEqual(UserID.from_string(USER_ID), requester.user)
  225. self.assertFalse(requester.is_guest)
  226. # add an is_guest caveat
  227. mac = pymacaroons.Macaroon.deserialize(token)
  228. mac.add_first_party_caveat("guest = true")
  229. guest_tok = mac.serialize()
  230. # the token should *not* work now
  231. request = Mock(args={})
  232. request.args[b"access_token"] = [guest_tok.encode('ascii')]
  233. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  234. with self.assertRaises(AuthError) as cm:
  235. yield self.auth.get_user_by_req(request, allow_guest=True)
  236. self.assertEqual(401, cm.exception.code)
  237. self.assertEqual("Guest access token used for regular user", cm.exception.msg)
  238. self.store.get_user_by_id.assert_called_with(USER_ID)
  239. @defer.inlineCallbacks
  240. def test_blocking_mau(self):
  241. self.hs.config.limit_usage_by_mau = False
  242. self.hs.config.max_mau_value = 50
  243. lots_of_users = 100
  244. small_number_of_users = 1
  245. # Ensure no error thrown
  246. yield self.auth.check_auth_blocking()
  247. self.hs.config.limit_usage_by_mau = True
  248. self.store.get_monthly_active_count = Mock(
  249. return_value=defer.succeed(lots_of_users)
  250. )
  251. with self.assertRaises(ResourceLimitError) as e:
  252. yield self.auth.check_auth_blocking()
  253. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  254. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  255. self.assertEquals(e.exception.code, 403)
  256. # Ensure does not throw an error
  257. self.store.get_monthly_active_count = Mock(
  258. return_value=defer.succeed(small_number_of_users)
  259. )
  260. yield self.auth.check_auth_blocking()
  261. @defer.inlineCallbacks
  262. def test_reserved_threepid(self):
  263. self.hs.config.limit_usage_by_mau = True
  264. self.hs.config.max_mau_value = 1
  265. self.store.get_monthly_active_count = lambda: defer.succeed(2)
  266. threepid = {'medium': 'email', 'address': 'reserved@server.com'}
  267. unknown_threepid = {'medium': 'email', 'address': 'unreserved@server.com'}
  268. self.hs.config.mau_limits_reserved_threepids = [threepid]
  269. yield self.store.register(user_id='user1', token="123", password_hash=None)
  270. with self.assertRaises(ResourceLimitError):
  271. yield self.auth.check_auth_blocking()
  272. with self.assertRaises(ResourceLimitError):
  273. yield self.auth.check_auth_blocking(threepid=unknown_threepid)
  274. yield self.auth.check_auth_blocking(threepid=threepid)
  275. @defer.inlineCallbacks
  276. def test_hs_disabled(self):
  277. self.hs.config.hs_disabled = True
  278. self.hs.config.hs_disabled_message = "Reason for being disabled"
  279. with self.assertRaises(ResourceLimitError) as e:
  280. yield self.auth.check_auth_blocking()
  281. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  282. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  283. self.assertEquals(e.exception.code, 403)
  284. @defer.inlineCallbacks
  285. def test_server_notices_mxid_special_cased(self):
  286. self.hs.config.hs_disabled = True
  287. user = "@user:server"
  288. self.hs.config.server_notices_mxid = user
  289. self.hs.config.hs_disabled_message = "Reason for being disabled"
  290. yield self.auth.check_auth_blocking(user)