test_auth.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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.constants import UserTypes
  21. from synapse.api.errors import (
  22. AuthError,
  23. Codes,
  24. InvalidClientCredentialsError,
  25. InvalidClientTokenError,
  26. MissingClientTokenError,
  27. ResourceLimitError,
  28. )
  29. from synapse.types import UserID
  30. from tests import unittest
  31. from tests.utils import mock_getRawHeaders, setup_test_homeserver
  32. class TestHandlers(object):
  33. def __init__(self, hs):
  34. self.auth_handler = synapse.handlers.auth.AuthHandler(hs)
  35. class AuthTestCase(unittest.TestCase):
  36. @defer.inlineCallbacks
  37. def setUp(self):
  38. self.state_handler = Mock()
  39. self.store = Mock()
  40. self.hs = yield setup_test_homeserver(self.addCleanup, handlers=None)
  41. self.hs.get_datastore = Mock(return_value=self.store)
  42. self.hs.handlers = TestHandlers(self.hs)
  43. self.auth = Auth(self.hs)
  44. self.test_user = "@foo:bar"
  45. self.test_token = b"_test_token_"
  46. # this is overridden for the appservice tests
  47. self.store.get_app_service_by_token = Mock(return_value=None)
  48. self.store.is_support_user = Mock(return_value=defer.succeed(False))
  49. @defer.inlineCallbacks
  50. def test_get_user_by_req_user_valid_token(self):
  51. user_info = {"name": self.test_user, "token_id": "ditto", "device_id": "device"}
  52. self.store.get_user_by_access_token = Mock(return_value=user_info)
  53. request = Mock(args={})
  54. request.args[b"access_token"] = [self.test_token]
  55. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  56. requester = yield self.auth.get_user_by_req(request)
  57. self.assertEquals(requester.user.to_string(), self.test_user)
  58. def test_get_user_by_req_user_bad_token(self):
  59. self.store.get_user_by_access_token = Mock(return_value=None)
  60. request = Mock(args={})
  61. request.args[b"access_token"] = [self.test_token]
  62. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  63. d = self.auth.get_user_by_req(request)
  64. f = self.failureResultOf(d, InvalidClientTokenError).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 = {"name": self.test_user, "token_id": "ditto"}
  69. self.store.get_user_by_access_token = Mock(return_value=user_info)
  70. request = Mock(args={})
  71. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  72. d = self.auth.get_user_by_req(request)
  73. f = self.failureResultOf(d, MissingClientTokenError).value
  74. self.assertEqual(f.code, 401)
  75. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  76. @defer.inlineCallbacks
  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 = Mock(return_value=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 = yield self.auth.get_user_by_req(request)
  88. self.assertEquals(requester.user.to_string(), self.test_user)
  89. @defer.inlineCallbacks
  90. def test_get_user_by_req_appservice_valid_token_good_ip(self):
  91. from netaddr import IPSet
  92. app_service = Mock(
  93. token="foobar",
  94. url="a_url",
  95. sender=self.test_user,
  96. ip_range_whitelist=IPSet(["192.168/16"]),
  97. )
  98. self.store.get_app_service_by_token = Mock(return_value=app_service)
  99. self.store.get_user_by_access_token = Mock(return_value=None)
  100. request = Mock(args={})
  101. request.getClientIP.return_value = "192.168.10.10"
  102. request.args[b"access_token"] = [self.test_token]
  103. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  104. requester = yield self.auth.get_user_by_req(request)
  105. self.assertEquals(requester.user.to_string(), self.test_user)
  106. def test_get_user_by_req_appservice_valid_token_bad_ip(self):
  107. from netaddr import IPSet
  108. app_service = Mock(
  109. token="foobar",
  110. url="a_url",
  111. sender=self.test_user,
  112. ip_range_whitelist=IPSet(["192.168/16"]),
  113. )
  114. self.store.get_app_service_by_token = Mock(return_value=app_service)
  115. self.store.get_user_by_access_token = Mock(return_value=None)
  116. request = Mock(args={})
  117. request.getClientIP.return_value = "131.111.8.42"
  118. request.args[b"access_token"] = [self.test_token]
  119. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  120. d = self.auth.get_user_by_req(request)
  121. f = self.failureResultOf(d, InvalidClientTokenError).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 = Mock(return_value=None)
  127. request = Mock(args={})
  128. request.args[b"access_token"] = [self.test_token]
  129. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  130. d = self.auth.get_user_by_req(request)
  131. f = self.failureResultOf(d, InvalidClientTokenError).value
  132. self.assertEqual(f.code, 401)
  133. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  134. def test_get_user_by_req_appservice_missing_token(self):
  135. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  136. self.store.get_app_service_by_token = Mock(return_value=app_service)
  137. self.store.get_user_by_access_token = Mock(return_value=None)
  138. request = Mock(args={})
  139. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  140. d = self.auth.get_user_by_req(request)
  141. f = self.failureResultOf(d, MissingClientTokenError).value
  142. self.assertEqual(f.code, 401)
  143. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  144. @defer.inlineCallbacks
  145. def test_get_user_by_req_appservice_valid_token_valid_user_id(self):
  146. masquerading_user_id = b"@doppelganger:matrix.org"
  147. app_service = Mock(
  148. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  149. )
  150. app_service.is_interested_in_user = Mock(return_value=True)
  151. self.store.get_app_service_by_token = Mock(return_value=app_service)
  152. self.store.get_user_by_access_token = Mock(return_value=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 = yield 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 = Mock(return_value=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. d = self.auth.get_user_by_req(request)
  176. self.failureResultOf(d, AuthError)
  177. @defer.inlineCallbacks
  178. def test_get_user_from_macaroon(self):
  179. self.store.get_user_by_access_token = Mock(
  180. return_value={"name": "@baldrick:matrix.org", "device_id": "device"}
  181. )
  182. user_id = "@baldrick:matrix.org"
  183. macaroon = pymacaroons.Macaroon(
  184. location=self.hs.config.server_name,
  185. identifier="key",
  186. key=self.hs.config.macaroon_secret_key,
  187. )
  188. macaroon.add_first_party_caveat("gen = 1")
  189. macaroon.add_first_party_caveat("type = access")
  190. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  191. user_info = yield self.auth.get_user_by_access_token(macaroon.serialize())
  192. user = user_info["user"]
  193. self.assertEqual(UserID.from_string(user_id), user)
  194. # TODO: device_id should come from the macaroon, but currently comes
  195. # from the db.
  196. self.assertEqual(user_info["device_id"], "device")
  197. @defer.inlineCallbacks
  198. def test_get_guest_user_from_macaroon(self):
  199. self.store.get_user_by_id = Mock(return_value={"is_guest": True})
  200. self.store.get_user_by_access_token = Mock(return_value=None)
  201. user_id = "@baldrick:matrix.org"
  202. macaroon = pymacaroons.Macaroon(
  203. location=self.hs.config.server_name,
  204. identifier="key",
  205. key=self.hs.config.macaroon_secret_key,
  206. )
  207. macaroon.add_first_party_caveat("gen = 1")
  208. macaroon.add_first_party_caveat("type = access")
  209. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  210. macaroon.add_first_party_caveat("guest = true")
  211. serialized = macaroon.serialize()
  212. user_info = yield self.auth.get_user_by_access_token(serialized)
  213. user = user_info["user"]
  214. is_guest = user_info["is_guest"]
  215. self.assertEqual(UserID.from_string(user_id), user)
  216. self.assertTrue(is_guest)
  217. self.store.get_user_by_id.assert_called_with(user_id)
  218. @defer.inlineCallbacks
  219. def test_cannot_use_regular_token_as_guest(self):
  220. USER_ID = "@percy:matrix.org"
  221. self.store.add_access_token_to_user = Mock()
  222. token = yield self.hs.handlers.auth_handler.get_access_token_for_user_id(
  223. USER_ID, "DEVICE", valid_until_ms=None
  224. )
  225. self.store.add_access_token_to_user.assert_called_with(
  226. USER_ID, token, "DEVICE", None
  227. )
  228. def get_user(tok):
  229. if token != tok:
  230. return None
  231. return {
  232. "name": USER_ID,
  233. "is_guest": False,
  234. "token_id": 1234,
  235. "device_id": "DEVICE",
  236. }
  237. self.store.get_user_by_access_token = get_user
  238. self.store.get_user_by_id = Mock(return_value={"is_guest": False})
  239. # check the token works
  240. request = Mock(args={})
  241. request.args[b"access_token"] = [token.encode("ascii")]
  242. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  243. requester = yield self.auth.get_user_by_req(request, allow_guest=True)
  244. self.assertEqual(UserID.from_string(USER_ID), requester.user)
  245. self.assertFalse(requester.is_guest)
  246. # add an is_guest caveat
  247. mac = pymacaroons.Macaroon.deserialize(token)
  248. mac.add_first_party_caveat("guest = true")
  249. guest_tok = mac.serialize()
  250. # the token should *not* work now
  251. request = Mock(args={})
  252. request.args[b"access_token"] = [guest_tok.encode("ascii")]
  253. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  254. with self.assertRaises(InvalidClientCredentialsError) as cm:
  255. yield self.auth.get_user_by_req(request, allow_guest=True)
  256. self.assertEqual(401, cm.exception.code)
  257. self.assertEqual("Guest access token used for regular user", cm.exception.msg)
  258. self.store.get_user_by_id.assert_called_with(USER_ID)
  259. @defer.inlineCallbacks
  260. def test_blocking_mau(self):
  261. self.hs.config.limit_usage_by_mau = False
  262. self.hs.config.max_mau_value = 50
  263. lots_of_users = 100
  264. small_number_of_users = 1
  265. # Ensure no error thrown
  266. yield self.auth.check_auth_blocking()
  267. self.hs.config.limit_usage_by_mau = True
  268. self.store.get_monthly_active_count = Mock(
  269. return_value=defer.succeed(lots_of_users)
  270. )
  271. with self.assertRaises(ResourceLimitError) as e:
  272. yield self.auth.check_auth_blocking()
  273. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  274. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  275. self.assertEquals(e.exception.code, 403)
  276. # Ensure does not throw an error
  277. self.store.get_monthly_active_count = Mock(
  278. return_value=defer.succeed(small_number_of_users)
  279. )
  280. yield self.auth.check_auth_blocking()
  281. @defer.inlineCallbacks
  282. def test_blocking_mau__depending_on_user_type(self):
  283. self.hs.config.max_mau_value = 50
  284. self.hs.config.limit_usage_by_mau = True
  285. self.store.get_monthly_active_count = Mock(return_value=defer.succeed(100))
  286. # Support users allowed
  287. yield self.auth.check_auth_blocking(user_type=UserTypes.SUPPORT)
  288. self.store.get_monthly_active_count = Mock(return_value=defer.succeed(100))
  289. # Bots not allowed
  290. with self.assertRaises(ResourceLimitError):
  291. yield self.auth.check_auth_blocking(user_type=UserTypes.BOT)
  292. self.store.get_monthly_active_count = Mock(return_value=defer.succeed(100))
  293. # Real users not allowed
  294. with self.assertRaises(ResourceLimitError):
  295. yield self.auth.check_auth_blocking()
  296. @defer.inlineCallbacks
  297. def test_reserved_threepid(self):
  298. self.hs.config.limit_usage_by_mau = True
  299. self.hs.config.max_mau_value = 1
  300. self.store.get_monthly_active_count = lambda: defer.succeed(2)
  301. threepid = {"medium": "email", "address": "reserved@server.com"}
  302. unknown_threepid = {"medium": "email", "address": "unreserved@server.com"}
  303. self.hs.config.mau_limits_reserved_threepids = [threepid]
  304. yield self.store.register_user(user_id="user1", password_hash=None)
  305. with self.assertRaises(ResourceLimitError):
  306. yield self.auth.check_auth_blocking()
  307. with self.assertRaises(ResourceLimitError):
  308. yield self.auth.check_auth_blocking(threepid=unknown_threepid)
  309. yield self.auth.check_auth_blocking(threepid=threepid)
  310. @defer.inlineCallbacks
  311. def test_hs_disabled(self):
  312. self.hs.config.hs_disabled = True
  313. self.hs.config.hs_disabled_message = "Reason for being disabled"
  314. with self.assertRaises(ResourceLimitError) as e:
  315. yield self.auth.check_auth_blocking()
  316. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  317. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  318. self.assertEquals(e.exception.code, 403)
  319. @defer.inlineCallbacks
  320. def test_hs_disabled_no_server_notices_user(self):
  321. """Check that 'hs_disabled_message' works correctly when there is no
  322. server_notices user.
  323. """
  324. # this should be the default, but we had a bug where the test was doing the wrong
  325. # thing, so let's make it explicit
  326. self.hs.config.server_notices_mxid = None
  327. self.hs.config.hs_disabled = True
  328. self.hs.config.hs_disabled_message = "Reason for being disabled"
  329. with self.assertRaises(ResourceLimitError) as e:
  330. yield self.auth.check_auth_blocking()
  331. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  332. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  333. self.assertEquals(e.exception.code, 403)
  334. @defer.inlineCallbacks
  335. def test_server_notices_mxid_special_cased(self):
  336. self.hs.config.hs_disabled = True
  337. user = "@user:server"
  338. self.hs.config.server_notices_mxid = user
  339. self.hs.config.hs_disabled_message = "Reason for being disabled"
  340. yield self.auth.check_auth_blocking(user)