test_auth.py 18 KB

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