test_auth.py 18 KB

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