test_auth.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 defer.ensureDeferred(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 defer.ensureDeferred(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 defer.ensureDeferred(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 defer.ensureDeferred(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 defer.ensureDeferred(
  192. self.auth.get_user_by_access_token(macaroon.serialize())
  193. )
  194. user = user_info["user"]
  195. self.assertEqual(UserID.from_string(user_id), user)
  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. @defer.inlineCallbacks
  200. def test_get_guest_user_from_macaroon(self):
  201. self.store.get_user_by_id = Mock(return_value={"is_guest": True})
  202. self.store.get_user_by_access_token = Mock(return_value=None)
  203. user_id = "@baldrick:matrix.org"
  204. macaroon = pymacaroons.Macaroon(
  205. location=self.hs.config.server_name,
  206. identifier="key",
  207. key=self.hs.config.macaroon_secret_key,
  208. )
  209. macaroon.add_first_party_caveat("gen = 1")
  210. macaroon.add_first_party_caveat("type = access")
  211. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  212. macaroon.add_first_party_caveat("guest = true")
  213. serialized = macaroon.serialize()
  214. user_info = yield defer.ensureDeferred(
  215. self.auth.get_user_by_access_token(serialized)
  216. )
  217. user = user_info["user"]
  218. is_guest = user_info["is_guest"]
  219. self.assertEqual(UserID.from_string(user_id), user)
  220. self.assertTrue(is_guest)
  221. self.store.get_user_by_id.assert_called_with(user_id)
  222. @defer.inlineCallbacks
  223. def test_cannot_use_regular_token_as_guest(self):
  224. USER_ID = "@percy:matrix.org"
  225. self.store.add_access_token_to_user = Mock(return_value=defer.succeed(None))
  226. self.store.get_device = Mock(return_value=defer.succeed(None))
  227. token = yield defer.ensureDeferred(
  228. self.hs.handlers.auth_handler.get_access_token_for_user_id(
  229. USER_ID, "DEVICE", valid_until_ms=None
  230. )
  231. )
  232. self.store.add_access_token_to_user.assert_called_with(
  233. USER_ID, token, "DEVICE", None
  234. )
  235. def get_user(tok):
  236. if token != tok:
  237. return None
  238. return {
  239. "name": USER_ID,
  240. "is_guest": False,
  241. "token_id": 1234,
  242. "device_id": "DEVICE",
  243. }
  244. self.store.get_user_by_access_token = get_user
  245. self.store.get_user_by_id = Mock(return_value={"is_guest": False})
  246. # check the token works
  247. request = Mock(args={})
  248. request.args[b"access_token"] = [token.encode("ascii")]
  249. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  250. requester = yield defer.ensureDeferred(
  251. self.auth.get_user_by_req(request, allow_guest=True)
  252. )
  253. self.assertEqual(UserID.from_string(USER_ID), requester.user)
  254. self.assertFalse(requester.is_guest)
  255. # add an is_guest caveat
  256. mac = pymacaroons.Macaroon.deserialize(token)
  257. mac.add_first_party_caveat("guest = true")
  258. guest_tok = mac.serialize()
  259. # the token should *not* work now
  260. request = Mock(args={})
  261. request.args[b"access_token"] = [guest_tok.encode("ascii")]
  262. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  263. with self.assertRaises(InvalidClientCredentialsError) as cm:
  264. yield defer.ensureDeferred(
  265. self.auth.get_user_by_req(request, allow_guest=True)
  266. )
  267. self.assertEqual(401, cm.exception.code)
  268. self.assertEqual("Guest access token used for regular user", cm.exception.msg)
  269. self.store.get_user_by_id.assert_called_with(USER_ID)
  270. @defer.inlineCallbacks
  271. def test_blocking_mau(self):
  272. self.hs.config.limit_usage_by_mau = False
  273. self.hs.config.max_mau_value = 50
  274. lots_of_users = 100
  275. small_number_of_users = 1
  276. # Ensure no error thrown
  277. yield defer.ensureDeferred(self.auth.check_auth_blocking())
  278. self.hs.config.limit_usage_by_mau = True
  279. self.store.get_monthly_active_count = Mock(
  280. return_value=defer.succeed(lots_of_users)
  281. )
  282. with self.assertRaises(ResourceLimitError) as e:
  283. yield defer.ensureDeferred(self.auth.check_auth_blocking())
  284. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  285. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  286. self.assertEquals(e.exception.code, 403)
  287. # Ensure does not throw an error
  288. self.store.get_monthly_active_count = Mock(
  289. return_value=defer.succeed(small_number_of_users)
  290. )
  291. yield defer.ensureDeferred(self.auth.check_auth_blocking())
  292. @defer.inlineCallbacks
  293. def test_blocking_mau__depending_on_user_type(self):
  294. self.hs.config.max_mau_value = 50
  295. self.hs.config.limit_usage_by_mau = True
  296. self.store.get_monthly_active_count = Mock(return_value=defer.succeed(100))
  297. # Support users allowed
  298. yield defer.ensureDeferred(
  299. self.auth.check_auth_blocking(user_type=UserTypes.SUPPORT)
  300. )
  301. self.store.get_monthly_active_count = Mock(return_value=defer.succeed(100))
  302. # Bots not allowed
  303. with self.assertRaises(ResourceLimitError):
  304. yield defer.ensureDeferred(
  305. self.auth.check_auth_blocking(user_type=UserTypes.BOT)
  306. )
  307. self.store.get_monthly_active_count = Mock(return_value=defer.succeed(100))
  308. # Real users not allowed
  309. with self.assertRaises(ResourceLimitError):
  310. yield defer.ensureDeferred(self.auth.check_auth_blocking())
  311. @defer.inlineCallbacks
  312. def test_reserved_threepid(self):
  313. self.hs.config.limit_usage_by_mau = True
  314. self.hs.config.max_mau_value = 1
  315. self.store.get_monthly_active_count = lambda: defer.succeed(2)
  316. threepid = {"medium": "email", "address": "reserved@server.com"}
  317. unknown_threepid = {"medium": "email", "address": "unreserved@server.com"}
  318. self.hs.config.mau_limits_reserved_threepids = [threepid]
  319. with self.assertRaises(ResourceLimitError):
  320. yield defer.ensureDeferred(self.auth.check_auth_blocking())
  321. with self.assertRaises(ResourceLimitError):
  322. yield defer.ensureDeferred(
  323. self.auth.check_auth_blocking(threepid=unknown_threepid)
  324. )
  325. yield defer.ensureDeferred(self.auth.check_auth_blocking(threepid=threepid))
  326. @defer.inlineCallbacks
  327. def test_hs_disabled(self):
  328. self.hs.config.hs_disabled = True
  329. self.hs.config.hs_disabled_message = "Reason for being disabled"
  330. with self.assertRaises(ResourceLimitError) as e:
  331. yield defer.ensureDeferred(self.auth.check_auth_blocking())
  332. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  333. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  334. self.assertEquals(e.exception.code, 403)
  335. @defer.inlineCallbacks
  336. def test_hs_disabled_no_server_notices_user(self):
  337. """Check that 'hs_disabled_message' works correctly when there is no
  338. server_notices user.
  339. """
  340. # this should be the default, but we had a bug where the test was doing the wrong
  341. # thing, so let's make it explicit
  342. self.hs.config.server_notices_mxid = None
  343. self.hs.config.hs_disabled = True
  344. self.hs.config.hs_disabled_message = "Reason for being disabled"
  345. with self.assertRaises(ResourceLimitError) as e:
  346. yield defer.ensureDeferred(self.auth.check_auth_blocking())
  347. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  348. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  349. self.assertEquals(e.exception.code, 403)
  350. @defer.inlineCallbacks
  351. def test_server_notices_mxid_special_cased(self):
  352. self.hs.config.hs_disabled = True
  353. user = "@user:server"
  354. self.hs.config.server_notices_mxid = user
  355. self.hs.config.hs_disabled_message = "Reason for being disabled"
  356. yield defer.ensureDeferred(self.auth.check_auth_blocking(user))