test_auth.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. # Copyright 2015 - 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from unittest.mock import Mock
  15. import pymacaroons
  16. from synapse.api.auth import Auth
  17. from synapse.api.constants import UserTypes
  18. from synapse.api.errors import (
  19. AuthError,
  20. Codes,
  21. InvalidClientTokenError,
  22. MissingClientTokenError,
  23. ResourceLimitError,
  24. )
  25. from synapse.appservice import ApplicationService
  26. from synapse.storage.databases.main.registration import TokenLookupResult
  27. from synapse.types import Requester
  28. from tests import unittest
  29. from tests.test_utils import simple_async_mock
  30. from tests.unittest import override_config
  31. from tests.utils import mock_getRawHeaders
  32. class AuthTestCase(unittest.HomeserverTestCase):
  33. def prepare(self, reactor, clock, hs):
  34. self.store = Mock()
  35. hs.get_datastore = Mock(return_value=self.store)
  36. hs.get_auth_handler().store = self.store
  37. self.auth = Auth(hs)
  38. # AuthBlocking reads from the hs' config on initialization. We need to
  39. # modify its config instead of the hs'
  40. self.auth_blocking = self.auth._auth_blocking
  41. self.test_user = "@foo:bar"
  42. self.test_token = b"_test_token_"
  43. # this is overridden for the appservice tests
  44. self.store.get_app_service_by_token = Mock(return_value=None)
  45. self.store.insert_client_ip = simple_async_mock(None)
  46. self.store.is_support_user = simple_async_mock(False)
  47. def test_get_user_by_req_user_valid_token(self):
  48. user_info = TokenLookupResult(
  49. user_id=self.test_user, token_id=5, device_id="device"
  50. )
  51. self.store.get_user_by_access_token = simple_async_mock(user_info)
  52. self.store.mark_access_token_as_used = simple_async_mock(None)
  53. request = Mock(args={})
  54. request.args[b"access_token"] = [self.test_token]
  55. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  56. requester = self.get_success(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 = simple_async_mock(None)
  60. request = Mock(args={})
  61. request.args[b"access_token"] = [self.test_token]
  62. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  63. f = self.get_failure(
  64. self.auth.get_user_by_req(request), InvalidClientTokenError
  65. ).value
  66. self.assertEqual(f.code, 401)
  67. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  68. def test_get_user_by_req_user_missing_token(self):
  69. user_info = TokenLookupResult(user_id=self.test_user, token_id=5)
  70. self.store.get_user_by_access_token = simple_async_mock(user_info)
  71. request = Mock(args={})
  72. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  73. f = self.get_failure(
  74. self.auth.get_user_by_req(request), MissingClientTokenError
  75. ).value
  76. self.assertEqual(f.code, 401)
  77. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  78. def test_get_user_by_req_appservice_valid_token(self):
  79. app_service = Mock(
  80. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  81. )
  82. self.store.get_app_service_by_token = Mock(return_value=app_service)
  83. self.store.get_user_by_access_token = simple_async_mock(None)
  84. request = Mock(args={})
  85. request.getClientIP.return_value = "127.0.0.1"
  86. request.args[b"access_token"] = [self.test_token]
  87. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  88. requester = self.get_success(self.auth.get_user_by_req(request))
  89. self.assertEquals(requester.user.to_string(), self.test_user)
  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 = simple_async_mock(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 = self.get_success(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 = simple_async_mock(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. f = self.get_failure(
  121. self.auth.get_user_by_req(request), InvalidClientTokenError
  122. ).value
  123. self.assertEqual(f.code, 401)
  124. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  125. def test_get_user_by_req_appservice_bad_token(self):
  126. self.store.get_app_service_by_token = Mock(return_value=None)
  127. self.store.get_user_by_access_token = simple_async_mock(None)
  128. request = Mock(args={})
  129. request.args[b"access_token"] = [self.test_token]
  130. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  131. f = self.get_failure(
  132. self.auth.get_user_by_req(request), InvalidClientTokenError
  133. ).value
  134. self.assertEqual(f.code, 401)
  135. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  136. def test_get_user_by_req_appservice_missing_token(self):
  137. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  138. self.store.get_app_service_by_token = Mock(return_value=app_service)
  139. self.store.get_user_by_access_token = simple_async_mock(None)
  140. request = Mock(args={})
  141. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  142. f = self.get_failure(
  143. self.auth.get_user_by_req(request), MissingClientTokenError
  144. ).value
  145. self.assertEqual(f.code, 401)
  146. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  147. def test_get_user_by_req_appservice_valid_token_valid_user_id(self):
  148. masquerading_user_id = b"@doppelganger:matrix.org"
  149. app_service = Mock(
  150. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  151. )
  152. app_service.is_interested_in_user = Mock(return_value=True)
  153. self.store.get_app_service_by_token = Mock(return_value=app_service)
  154. # This just needs to return a truth-y value.
  155. self.store.get_user_by_id = simple_async_mock({"is_guest": False})
  156. self.store.get_user_by_access_token = simple_async_mock(None)
  157. request = Mock(args={})
  158. request.getClientIP.return_value = "127.0.0.1"
  159. request.args[b"access_token"] = [self.test_token]
  160. request.args[b"user_id"] = [masquerading_user_id]
  161. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  162. requester = self.get_success(self.auth.get_user_by_req(request))
  163. self.assertEquals(
  164. requester.user.to_string(), masquerading_user_id.decode("utf8")
  165. )
  166. def test_get_user_by_req_appservice_valid_token_bad_user_id(self):
  167. masquerading_user_id = b"@doppelganger:matrix.org"
  168. app_service = Mock(
  169. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  170. )
  171. app_service.is_interested_in_user = Mock(return_value=False)
  172. self.store.get_app_service_by_token = Mock(return_value=app_service)
  173. self.store.get_user_by_access_token = simple_async_mock(None)
  174. request = Mock(args={})
  175. request.getClientIP.return_value = "127.0.0.1"
  176. request.args[b"access_token"] = [self.test_token]
  177. request.args[b"user_id"] = [masquerading_user_id]
  178. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  179. self.get_failure(self.auth.get_user_by_req(request), AuthError)
  180. @override_config({"experimental_features": {"msc3202_device_masquerading": True}})
  181. def test_get_user_by_req_appservice_valid_token_valid_device_id(self):
  182. """
  183. Tests that when an application service passes the device_id URL parameter
  184. with the ID of a valid device for the user in question,
  185. the requester instance tracks that device ID.
  186. """
  187. masquerading_user_id = b"@doppelganger:matrix.org"
  188. masquerading_device_id = b"DOPPELDEVICE"
  189. app_service = Mock(
  190. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  191. )
  192. app_service.is_interested_in_user = Mock(return_value=True)
  193. self.store.get_app_service_by_token = Mock(return_value=app_service)
  194. # This just needs to return a truth-y value.
  195. self.store.get_user_by_id = simple_async_mock({"is_guest": False})
  196. self.store.get_user_by_access_token = simple_async_mock(None)
  197. # This also needs to just return a truth-y value
  198. self.store.get_device = simple_async_mock({"hidden": False})
  199. request = Mock(args={})
  200. request.getClientIP.return_value = "127.0.0.1"
  201. request.args[b"access_token"] = [self.test_token]
  202. request.args[b"user_id"] = [masquerading_user_id]
  203. request.args[b"org.matrix.msc3202.device_id"] = [masquerading_device_id]
  204. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  205. requester = self.get_success(self.auth.get_user_by_req(request))
  206. self.assertEquals(
  207. requester.user.to_string(), masquerading_user_id.decode("utf8")
  208. )
  209. self.assertEquals(requester.device_id, masquerading_device_id.decode("utf8"))
  210. @override_config({"experimental_features": {"msc3202_device_masquerading": True}})
  211. def test_get_user_by_req_appservice_valid_token_invalid_device_id(self):
  212. """
  213. Tests that when an application service passes the device_id URL parameter
  214. with an ID that is not a valid device ID for the user in question,
  215. the request fails with the appropriate error code.
  216. """
  217. masquerading_user_id = b"@doppelganger:matrix.org"
  218. masquerading_device_id = b"NOT_A_REAL_DEVICE_ID"
  219. app_service = Mock(
  220. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  221. )
  222. app_service.is_interested_in_user = Mock(return_value=True)
  223. self.store.get_app_service_by_token = Mock(return_value=app_service)
  224. # This just needs to return a truth-y value.
  225. self.store.get_user_by_id = simple_async_mock({"is_guest": False})
  226. self.store.get_user_by_access_token = simple_async_mock(None)
  227. # This also needs to just return a falsey value
  228. self.store.get_device = simple_async_mock(None)
  229. request = Mock(args={})
  230. request.getClientIP.return_value = "127.0.0.1"
  231. request.args[b"access_token"] = [self.test_token]
  232. request.args[b"user_id"] = [masquerading_user_id]
  233. request.args[b"org.matrix.msc3202.device_id"] = [masquerading_device_id]
  234. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  235. failure = self.get_failure(self.auth.get_user_by_req(request), AuthError)
  236. self.assertEquals(failure.value.code, 400)
  237. self.assertEquals(failure.value.errcode, Codes.EXCLUSIVE)
  238. def test_get_user_from_macaroon(self):
  239. self.store.get_user_by_access_token = simple_async_mock(
  240. TokenLookupResult(user_id="@baldrick:matrix.org", device_id="device")
  241. )
  242. user_id = "@baldrick:matrix.org"
  243. macaroon = pymacaroons.Macaroon(
  244. location=self.hs.config.server.server_name,
  245. identifier="key",
  246. key=self.hs.config.key.macaroon_secret_key,
  247. )
  248. macaroon.add_first_party_caveat("gen = 1")
  249. macaroon.add_first_party_caveat("type = access")
  250. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  251. user_info = self.get_success(
  252. self.auth.get_user_by_access_token(macaroon.serialize())
  253. )
  254. self.assertEqual(user_id, user_info.user_id)
  255. # TODO: device_id should come from the macaroon, but currently comes
  256. # from the db.
  257. self.assertEqual(user_info.device_id, "device")
  258. def test_get_guest_user_from_macaroon(self):
  259. self.store.get_user_by_id = simple_async_mock({"is_guest": True})
  260. self.store.get_user_by_access_token = simple_async_mock(None)
  261. user_id = "@baldrick:matrix.org"
  262. macaroon = pymacaroons.Macaroon(
  263. location=self.hs.config.server.server_name,
  264. identifier="key",
  265. key=self.hs.config.key.macaroon_secret_key,
  266. )
  267. macaroon.add_first_party_caveat("gen = 1")
  268. macaroon.add_first_party_caveat("type = access")
  269. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  270. macaroon.add_first_party_caveat("guest = true")
  271. serialized = macaroon.serialize()
  272. user_info = self.get_success(self.auth.get_user_by_access_token(serialized))
  273. self.assertEqual(user_id, user_info.user_id)
  274. self.assertTrue(user_info.is_guest)
  275. self.store.get_user_by_id.assert_called_with(user_id)
  276. def test_blocking_mau(self):
  277. self.auth_blocking._limit_usage_by_mau = False
  278. self.auth_blocking._max_mau_value = 50
  279. lots_of_users = 100
  280. small_number_of_users = 1
  281. # Ensure no error thrown
  282. self.get_success(self.auth.check_auth_blocking())
  283. self.auth_blocking._limit_usage_by_mau = True
  284. self.store.get_monthly_active_count = simple_async_mock(lots_of_users)
  285. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  286. self.assertEquals(e.value.admin_contact, self.hs.config.server.admin_contact)
  287. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  288. self.assertEquals(e.value.code, 403)
  289. # Ensure does not throw an error
  290. self.store.get_monthly_active_count = simple_async_mock(small_number_of_users)
  291. self.get_success(self.auth.check_auth_blocking())
  292. def test_blocking_mau__depending_on_user_type(self):
  293. self.auth_blocking._max_mau_value = 50
  294. self.auth_blocking._limit_usage_by_mau = True
  295. self.store.get_monthly_active_count = simple_async_mock(100)
  296. # Support users allowed
  297. self.get_success(self.auth.check_auth_blocking(user_type=UserTypes.SUPPORT))
  298. self.store.get_monthly_active_count = simple_async_mock(100)
  299. # Bots not allowed
  300. self.get_failure(
  301. self.auth.check_auth_blocking(user_type=UserTypes.BOT), ResourceLimitError
  302. )
  303. self.store.get_monthly_active_count = simple_async_mock(100)
  304. # Real users not allowed
  305. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  306. def test_blocking_mau__appservice_requester_allowed_when_not_tracking_ips(self):
  307. self.auth_blocking._max_mau_value = 50
  308. self.auth_blocking._limit_usage_by_mau = True
  309. self.auth_blocking._track_appservice_user_ips = False
  310. self.store.get_monthly_active_count = simple_async_mock(100)
  311. self.store.user_last_seen_monthly_active = simple_async_mock()
  312. self.store.is_trial_user = simple_async_mock()
  313. appservice = ApplicationService(
  314. "abcd",
  315. self.hs.config.server.server_name,
  316. id="1234",
  317. namespaces={
  318. "users": [{"regex": "@_appservice.*:sender", "exclusive": True}]
  319. },
  320. sender="@appservice:sender",
  321. )
  322. requester = Requester(
  323. user="@appservice:server",
  324. access_token_id=None,
  325. device_id="FOOBAR",
  326. is_guest=False,
  327. shadow_banned=False,
  328. app_service=appservice,
  329. authenticated_entity="@appservice:server",
  330. )
  331. self.get_success(self.auth.check_auth_blocking(requester=requester))
  332. def test_blocking_mau__appservice_requester_disallowed_when_tracking_ips(self):
  333. self.auth_blocking._max_mau_value = 50
  334. self.auth_blocking._limit_usage_by_mau = True
  335. self.auth_blocking._track_appservice_user_ips = True
  336. self.store.get_monthly_active_count = simple_async_mock(100)
  337. self.store.user_last_seen_monthly_active = simple_async_mock()
  338. self.store.is_trial_user = simple_async_mock()
  339. appservice = ApplicationService(
  340. "abcd",
  341. self.hs.config.server.server_name,
  342. id="1234",
  343. namespaces={
  344. "users": [{"regex": "@_appservice.*:sender", "exclusive": True}]
  345. },
  346. sender="@appservice:sender",
  347. )
  348. requester = Requester(
  349. user="@appservice:server",
  350. access_token_id=None,
  351. device_id="FOOBAR",
  352. is_guest=False,
  353. shadow_banned=False,
  354. app_service=appservice,
  355. authenticated_entity="@appservice:server",
  356. )
  357. self.get_failure(
  358. self.auth.check_auth_blocking(requester=requester), ResourceLimitError
  359. )
  360. def test_reserved_threepid(self):
  361. self.auth_blocking._limit_usage_by_mau = True
  362. self.auth_blocking._max_mau_value = 1
  363. self.store.get_monthly_active_count = simple_async_mock(2)
  364. threepid = {"medium": "email", "address": "reserved@server.com"}
  365. unknown_threepid = {"medium": "email", "address": "unreserved@server.com"}
  366. self.auth_blocking._mau_limits_reserved_threepids = [threepid]
  367. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  368. self.get_failure(
  369. self.auth.check_auth_blocking(threepid=unknown_threepid), ResourceLimitError
  370. )
  371. self.get_success(self.auth.check_auth_blocking(threepid=threepid))
  372. def test_hs_disabled(self):
  373. self.auth_blocking._hs_disabled = True
  374. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  375. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  376. self.assertEquals(e.value.admin_contact, self.hs.config.server.admin_contact)
  377. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  378. self.assertEquals(e.value.code, 403)
  379. def test_hs_disabled_no_server_notices_user(self):
  380. """Check that 'hs_disabled_message' works correctly when there is no
  381. server_notices user.
  382. """
  383. # this should be the default, but we had a bug where the test was doing the wrong
  384. # thing, so let's make it explicit
  385. self.auth_blocking._server_notices_mxid = None
  386. self.auth_blocking._hs_disabled = True
  387. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  388. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  389. self.assertEquals(e.value.admin_contact, self.hs.config.server.admin_contact)
  390. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  391. self.assertEquals(e.value.code, 403)
  392. def test_server_notices_mxid_special_cased(self):
  393. self.auth_blocking._hs_disabled = True
  394. user = "@user:server"
  395. self.auth_blocking._server_notices_mxid = user
  396. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  397. self.get_success(self.auth.check_auth_blocking(user))