test_auth.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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_by_req__puppeted_token__not_tracking_puppeted_mau(self):
  239. self.store.get_user_by_access_token = simple_async_mock(
  240. TokenLookupResult(
  241. user_id="@baldrick:matrix.org",
  242. device_id="device",
  243. token_owner="@admin:matrix.org",
  244. )
  245. )
  246. self.store.insert_client_ip = simple_async_mock(None)
  247. request = Mock(args={})
  248. request.getClientIP.return_value = "127.0.0.1"
  249. request.args[b"access_token"] = [self.test_token]
  250. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  251. self.get_success(self.auth.get_user_by_req(request))
  252. self.store.insert_client_ip.assert_called_once()
  253. def test_get_user_by_req__puppeted_token__tracking_puppeted_mau(self):
  254. self.auth._track_puppeted_user_ips = True
  255. self.store.get_user_by_access_token = simple_async_mock(
  256. TokenLookupResult(
  257. user_id="@baldrick:matrix.org",
  258. device_id="device",
  259. token_owner="@admin:matrix.org",
  260. )
  261. )
  262. self.store.insert_client_ip = simple_async_mock(None)
  263. request = Mock(args={})
  264. request.getClientIP.return_value = "127.0.0.1"
  265. request.args[b"access_token"] = [self.test_token]
  266. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  267. self.get_success(self.auth.get_user_by_req(request))
  268. self.assertEquals(self.store.insert_client_ip.call_count, 2)
  269. def test_get_user_from_macaroon(self):
  270. self.store.get_user_by_access_token = simple_async_mock(
  271. TokenLookupResult(user_id="@baldrick:matrix.org", device_id="device")
  272. )
  273. user_id = "@baldrick:matrix.org"
  274. macaroon = pymacaroons.Macaroon(
  275. location=self.hs.config.server.server_name,
  276. identifier="key",
  277. key=self.hs.config.key.macaroon_secret_key,
  278. )
  279. macaroon.add_first_party_caveat("gen = 1")
  280. macaroon.add_first_party_caveat("type = access")
  281. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  282. user_info = self.get_success(
  283. self.auth.get_user_by_access_token(macaroon.serialize())
  284. )
  285. self.assertEqual(user_id, user_info.user_id)
  286. # TODO: device_id should come from the macaroon, but currently comes
  287. # from the db.
  288. self.assertEqual(user_info.device_id, "device")
  289. def test_get_guest_user_from_macaroon(self):
  290. self.store.get_user_by_id = simple_async_mock({"is_guest": True})
  291. self.store.get_user_by_access_token = simple_async_mock(None)
  292. user_id = "@baldrick:matrix.org"
  293. macaroon = pymacaroons.Macaroon(
  294. location=self.hs.config.server.server_name,
  295. identifier="key",
  296. key=self.hs.config.key.macaroon_secret_key,
  297. )
  298. macaroon.add_first_party_caveat("gen = 1")
  299. macaroon.add_first_party_caveat("type = access")
  300. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  301. macaroon.add_first_party_caveat("guest = true")
  302. serialized = macaroon.serialize()
  303. user_info = self.get_success(self.auth.get_user_by_access_token(serialized))
  304. self.assertEqual(user_id, user_info.user_id)
  305. self.assertTrue(user_info.is_guest)
  306. self.store.get_user_by_id.assert_called_with(user_id)
  307. def test_blocking_mau(self):
  308. self.auth_blocking._limit_usage_by_mau = False
  309. self.auth_blocking._max_mau_value = 50
  310. lots_of_users = 100
  311. small_number_of_users = 1
  312. # Ensure no error thrown
  313. self.get_success(self.auth.check_auth_blocking())
  314. self.auth_blocking._limit_usage_by_mau = True
  315. self.store.get_monthly_active_count = simple_async_mock(lots_of_users)
  316. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  317. self.assertEquals(e.value.admin_contact, self.hs.config.server.admin_contact)
  318. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  319. self.assertEquals(e.value.code, 403)
  320. # Ensure does not throw an error
  321. self.store.get_monthly_active_count = simple_async_mock(small_number_of_users)
  322. self.get_success(self.auth.check_auth_blocking())
  323. def test_blocking_mau__depending_on_user_type(self):
  324. self.auth_blocking._max_mau_value = 50
  325. self.auth_blocking._limit_usage_by_mau = True
  326. self.store.get_monthly_active_count = simple_async_mock(100)
  327. # Support users allowed
  328. self.get_success(self.auth.check_auth_blocking(user_type=UserTypes.SUPPORT))
  329. self.store.get_monthly_active_count = simple_async_mock(100)
  330. # Bots not allowed
  331. self.get_failure(
  332. self.auth.check_auth_blocking(user_type=UserTypes.BOT), ResourceLimitError
  333. )
  334. self.store.get_monthly_active_count = simple_async_mock(100)
  335. # Real users not allowed
  336. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  337. def test_blocking_mau__appservice_requester_allowed_when_not_tracking_ips(self):
  338. self.auth_blocking._max_mau_value = 50
  339. self.auth_blocking._limit_usage_by_mau = True
  340. self.auth_blocking._track_appservice_user_ips = False
  341. self.store.get_monthly_active_count = simple_async_mock(100)
  342. self.store.user_last_seen_monthly_active = simple_async_mock()
  343. self.store.is_trial_user = simple_async_mock()
  344. appservice = ApplicationService(
  345. "abcd",
  346. self.hs.config.server.server_name,
  347. id="1234",
  348. namespaces={
  349. "users": [{"regex": "@_appservice.*:sender", "exclusive": True}]
  350. },
  351. sender="@appservice:sender",
  352. )
  353. requester = Requester(
  354. user="@appservice:server",
  355. access_token_id=None,
  356. device_id="FOOBAR",
  357. is_guest=False,
  358. shadow_banned=False,
  359. app_service=appservice,
  360. authenticated_entity="@appservice:server",
  361. )
  362. self.get_success(self.auth.check_auth_blocking(requester=requester))
  363. def test_blocking_mau__appservice_requester_disallowed_when_tracking_ips(self):
  364. self.auth_blocking._max_mau_value = 50
  365. self.auth_blocking._limit_usage_by_mau = True
  366. self.auth_blocking._track_appservice_user_ips = True
  367. self.store.get_monthly_active_count = simple_async_mock(100)
  368. self.store.user_last_seen_monthly_active = simple_async_mock()
  369. self.store.is_trial_user = simple_async_mock()
  370. appservice = ApplicationService(
  371. "abcd",
  372. self.hs.config.server.server_name,
  373. id="1234",
  374. namespaces={
  375. "users": [{"regex": "@_appservice.*:sender", "exclusive": True}]
  376. },
  377. sender="@appservice:sender",
  378. )
  379. requester = Requester(
  380. user="@appservice:server",
  381. access_token_id=None,
  382. device_id="FOOBAR",
  383. is_guest=False,
  384. shadow_banned=False,
  385. app_service=appservice,
  386. authenticated_entity="@appservice:server",
  387. )
  388. self.get_failure(
  389. self.auth.check_auth_blocking(requester=requester), ResourceLimitError
  390. )
  391. def test_reserved_threepid(self):
  392. self.auth_blocking._limit_usage_by_mau = True
  393. self.auth_blocking._max_mau_value = 1
  394. self.store.get_monthly_active_count = simple_async_mock(2)
  395. threepid = {"medium": "email", "address": "reserved@server.com"}
  396. unknown_threepid = {"medium": "email", "address": "unreserved@server.com"}
  397. self.auth_blocking._mau_limits_reserved_threepids = [threepid]
  398. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  399. self.get_failure(
  400. self.auth.check_auth_blocking(threepid=unknown_threepid), ResourceLimitError
  401. )
  402. self.get_success(self.auth.check_auth_blocking(threepid=threepid))
  403. def test_hs_disabled(self):
  404. self.auth_blocking._hs_disabled = True
  405. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  406. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  407. self.assertEquals(e.value.admin_contact, self.hs.config.server.admin_contact)
  408. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  409. self.assertEquals(e.value.code, 403)
  410. def test_hs_disabled_no_server_notices_user(self):
  411. """Check that 'hs_disabled_message' works correctly when there is no
  412. server_notices user.
  413. """
  414. # this should be the default, but we had a bug where the test was doing the wrong
  415. # thing, so let's make it explicit
  416. self.auth_blocking._server_notices_mxid = None
  417. self.auth_blocking._hs_disabled = True
  418. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  419. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  420. self.assertEquals(e.value.admin_contact, self.hs.config.server.admin_contact)
  421. self.assertEquals(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  422. self.assertEquals(e.value.code, 403)
  423. def test_server_notices_mxid_special_cased(self):
  424. self.auth_blocking._hs_disabled = True
  425. user = "@user:server"
  426. self.auth_blocking._server_notices_mxid = user
  427. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  428. self.get_success(self.auth.check_auth_blocking(user))