test_auth.py 17 KB

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