test_auth.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 twisted.test.proto_helpers import MemoryReactor
  17. from synapse.api.auth import Auth
  18. from synapse.api.constants import UserTypes
  19. from synapse.api.errors import (
  20. AuthError,
  21. Codes,
  22. InvalidClientTokenError,
  23. MissingClientTokenError,
  24. ResourceLimitError,
  25. )
  26. from synapse.appservice import ApplicationService
  27. from synapse.server import HomeServer
  28. from synapse.storage.databases.main.registration import TokenLookupResult
  29. from synapse.types import Requester
  30. from synapse.util import Clock
  31. from tests import unittest
  32. from tests.test_utils import simple_async_mock
  33. from tests.unittest import override_config
  34. from tests.utils import mock_getRawHeaders
  35. class AuthTestCase(unittest.HomeserverTestCase):
  36. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer):
  37. self.store = Mock()
  38. hs.datastores.main = self.store
  39. hs.get_auth_handler().store = self.store
  40. self.auth = Auth(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 = simple_async_mock(None)
  49. self.store.is_support_user = simple_async_mock(False)
  50. def test_get_user_by_req_user_valid_token(self):
  51. user_info = TokenLookupResult(
  52. user_id=self.test_user, token_id=5, device_id="device"
  53. )
  54. self.store.get_user_by_access_token = simple_async_mock(user_info)
  55. self.store.mark_access_token_as_used = simple_async_mock(None)
  56. request = Mock(args={})
  57. request.args[b"access_token"] = [self.test_token]
  58. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  59. requester = self.get_success(self.auth.get_user_by_req(request))
  60. self.assertEqual(requester.user.to_string(), self.test_user)
  61. def test_get_user_by_req_user_bad_token(self):
  62. self.store.get_user_by_access_token = simple_async_mock(None)
  63. request = Mock(args={})
  64. request.args[b"access_token"] = [self.test_token]
  65. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  66. f = self.get_failure(
  67. self.auth.get_user_by_req(request), InvalidClientTokenError
  68. ).value
  69. self.assertEqual(f.code, 401)
  70. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  71. def test_get_user_by_req_user_missing_token(self):
  72. user_info = TokenLookupResult(user_id=self.test_user, token_id=5)
  73. self.store.get_user_by_access_token = simple_async_mock(user_info)
  74. request = Mock(args={})
  75. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  76. f = self.get_failure(
  77. self.auth.get_user_by_req(request), MissingClientTokenError
  78. ).value
  79. self.assertEqual(f.code, 401)
  80. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  81. def test_get_user_by_req_appservice_valid_token(self):
  82. app_service = Mock(
  83. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  84. )
  85. self.store.get_app_service_by_token = Mock(return_value=app_service)
  86. self.store.get_user_by_access_token = simple_async_mock(None)
  87. request = Mock(args={})
  88. request.getClientIP.return_value = "127.0.0.1"
  89. request.args[b"access_token"] = [self.test_token]
  90. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  91. requester = self.get_success(self.auth.get_user_by_req(request))
  92. self.assertEqual(requester.user.to_string(), self.test_user)
  93. def test_get_user_by_req_appservice_valid_token_good_ip(self):
  94. from netaddr import IPSet
  95. app_service = Mock(
  96. token="foobar",
  97. url="a_url",
  98. sender=self.test_user,
  99. ip_range_whitelist=IPSet(["192.168/16"]),
  100. )
  101. self.store.get_app_service_by_token = Mock(return_value=app_service)
  102. self.store.get_user_by_access_token = simple_async_mock(None)
  103. request = Mock(args={})
  104. request.getClientIP.return_value = "192.168.10.10"
  105. request.args[b"access_token"] = [self.test_token]
  106. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  107. requester = self.get_success(self.auth.get_user_by_req(request))
  108. self.assertEqual(requester.user.to_string(), self.test_user)
  109. def test_get_user_by_req_appservice_valid_token_bad_ip(self):
  110. from netaddr import IPSet
  111. app_service = Mock(
  112. token="foobar",
  113. url="a_url",
  114. sender=self.test_user,
  115. ip_range_whitelist=IPSet(["192.168/16"]),
  116. )
  117. self.store.get_app_service_by_token = Mock(return_value=app_service)
  118. self.store.get_user_by_access_token = simple_async_mock(None)
  119. request = Mock(args={})
  120. request.getClientIP.return_value = "131.111.8.42"
  121. request.args[b"access_token"] = [self.test_token]
  122. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  123. f = self.get_failure(
  124. self.auth.get_user_by_req(request), InvalidClientTokenError
  125. ).value
  126. self.assertEqual(f.code, 401)
  127. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  128. def test_get_user_by_req_appservice_bad_token(self):
  129. self.store.get_app_service_by_token = Mock(return_value=None)
  130. self.store.get_user_by_access_token = simple_async_mock(None)
  131. request = Mock(args={})
  132. request.args[b"access_token"] = [self.test_token]
  133. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  134. f = self.get_failure(
  135. self.auth.get_user_by_req(request), InvalidClientTokenError
  136. ).value
  137. self.assertEqual(f.code, 401)
  138. self.assertEqual(f.errcode, "M_UNKNOWN_TOKEN")
  139. def test_get_user_by_req_appservice_missing_token(self):
  140. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  141. self.store.get_app_service_by_token = Mock(return_value=app_service)
  142. self.store.get_user_by_access_token = simple_async_mock(None)
  143. request = Mock(args={})
  144. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  145. f = self.get_failure(
  146. self.auth.get_user_by_req(request), MissingClientTokenError
  147. ).value
  148. self.assertEqual(f.code, 401)
  149. self.assertEqual(f.errcode, "M_MISSING_TOKEN")
  150. def test_get_user_by_req_appservice_valid_token_valid_user_id(self):
  151. masquerading_user_id = b"@doppelganger:matrix.org"
  152. app_service = Mock(
  153. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  154. )
  155. app_service.is_interested_in_user = Mock(return_value=True)
  156. self.store.get_app_service_by_token = Mock(return_value=app_service)
  157. # This just needs to return a truth-y value.
  158. self.store.get_user_by_id = simple_async_mock({"is_guest": False})
  159. self.store.get_user_by_access_token = simple_async_mock(None)
  160. request = Mock(args={})
  161. request.getClientIP.return_value = "127.0.0.1"
  162. request.args[b"access_token"] = [self.test_token]
  163. request.args[b"user_id"] = [masquerading_user_id]
  164. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  165. requester = self.get_success(self.auth.get_user_by_req(request))
  166. self.assertEqual(
  167. requester.user.to_string(), masquerading_user_id.decode("utf8")
  168. )
  169. def test_get_user_by_req_appservice_valid_token_bad_user_id(self):
  170. masquerading_user_id = b"@doppelganger:matrix.org"
  171. app_service = Mock(
  172. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  173. )
  174. app_service.is_interested_in_user = Mock(return_value=False)
  175. self.store.get_app_service_by_token = Mock(return_value=app_service)
  176. self.store.get_user_by_access_token = simple_async_mock(None)
  177. request = Mock(args={})
  178. request.getClientIP.return_value = "127.0.0.1"
  179. request.args[b"access_token"] = [self.test_token]
  180. request.args[b"user_id"] = [masquerading_user_id]
  181. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  182. self.get_failure(self.auth.get_user_by_req(request), AuthError)
  183. @override_config({"experimental_features": {"msc3202_device_masquerading": True}})
  184. def test_get_user_by_req_appservice_valid_token_valid_device_id(self):
  185. """
  186. Tests that when an application service passes the device_id URL parameter
  187. with the ID of a valid device for the user in question,
  188. the requester instance tracks that device ID.
  189. """
  190. masquerading_user_id = b"@doppelganger:matrix.org"
  191. masquerading_device_id = b"DOPPELDEVICE"
  192. app_service = Mock(
  193. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  194. )
  195. app_service.is_interested_in_user = Mock(return_value=True)
  196. self.store.get_app_service_by_token = Mock(return_value=app_service)
  197. # This just needs to return a truth-y value.
  198. self.store.get_user_by_id = simple_async_mock({"is_guest": False})
  199. self.store.get_user_by_access_token = simple_async_mock(None)
  200. # This also needs to just return a truth-y value
  201. self.store.get_device = simple_async_mock({"hidden": False})
  202. request = Mock(args={})
  203. request.getClientIP.return_value = "127.0.0.1"
  204. request.args[b"access_token"] = [self.test_token]
  205. request.args[b"user_id"] = [masquerading_user_id]
  206. request.args[b"org.matrix.msc3202.device_id"] = [masquerading_device_id]
  207. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  208. requester = self.get_success(self.auth.get_user_by_req(request))
  209. self.assertEqual(
  210. requester.user.to_string(), masquerading_user_id.decode("utf8")
  211. )
  212. self.assertEqual(requester.device_id, masquerading_device_id.decode("utf8"))
  213. @override_config({"experimental_features": {"msc3202_device_masquerading": True}})
  214. def test_get_user_by_req_appservice_valid_token_invalid_device_id(self):
  215. """
  216. Tests that when an application service passes the device_id URL parameter
  217. with an ID that is not a valid device ID for the user in question,
  218. the request fails with the appropriate error code.
  219. """
  220. masquerading_user_id = b"@doppelganger:matrix.org"
  221. masquerading_device_id = b"NOT_A_REAL_DEVICE_ID"
  222. app_service = Mock(
  223. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  224. )
  225. app_service.is_interested_in_user = Mock(return_value=True)
  226. self.store.get_app_service_by_token = Mock(return_value=app_service)
  227. # This just needs to return a truth-y value.
  228. self.store.get_user_by_id = simple_async_mock({"is_guest": False})
  229. self.store.get_user_by_access_token = simple_async_mock(None)
  230. # This also needs to just return a falsey value
  231. self.store.get_device = simple_async_mock(None)
  232. request = Mock(args={})
  233. request.getClientIP.return_value = "127.0.0.1"
  234. request.args[b"access_token"] = [self.test_token]
  235. request.args[b"user_id"] = [masquerading_user_id]
  236. request.args[b"org.matrix.msc3202.device_id"] = [masquerading_device_id]
  237. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  238. failure = self.get_failure(self.auth.get_user_by_req(request), AuthError)
  239. self.assertEqual(failure.value.code, 400)
  240. self.assertEqual(failure.value.errcode, Codes.EXCLUSIVE)
  241. def test_get_user_by_req__puppeted_token__not_tracking_puppeted_mau(self):
  242. self.store.get_user_by_access_token = simple_async_mock(
  243. TokenLookupResult(
  244. user_id="@baldrick:matrix.org",
  245. device_id="device",
  246. token_owner="@admin:matrix.org",
  247. )
  248. )
  249. self.store.insert_client_ip = simple_async_mock(None)
  250. request = Mock(args={})
  251. request.getClientIP.return_value = "127.0.0.1"
  252. request.args[b"access_token"] = [self.test_token]
  253. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  254. self.get_success(self.auth.get_user_by_req(request))
  255. self.store.insert_client_ip.assert_called_once()
  256. def test_get_user_by_req__puppeted_token__tracking_puppeted_mau(self):
  257. self.auth._track_puppeted_user_ips = True
  258. self.store.get_user_by_access_token = simple_async_mock(
  259. TokenLookupResult(
  260. user_id="@baldrick:matrix.org",
  261. device_id="device",
  262. token_owner="@admin:matrix.org",
  263. )
  264. )
  265. self.store.insert_client_ip = simple_async_mock(None)
  266. request = Mock(args={})
  267. request.getClientIP.return_value = "127.0.0.1"
  268. request.args[b"access_token"] = [self.test_token]
  269. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  270. self.get_success(self.auth.get_user_by_req(request))
  271. self.assertEqual(self.store.insert_client_ip.call_count, 2)
  272. def test_get_user_from_macaroon(self):
  273. self.store.get_user_by_access_token = simple_async_mock(
  274. TokenLookupResult(user_id="@baldrick:matrix.org", device_id="device")
  275. )
  276. user_id = "@baldrick:matrix.org"
  277. macaroon = pymacaroons.Macaroon(
  278. location=self.hs.config.server.server_name,
  279. identifier="key",
  280. key=self.hs.config.key.macaroon_secret_key,
  281. )
  282. macaroon.add_first_party_caveat("gen = 1")
  283. macaroon.add_first_party_caveat("type = access")
  284. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  285. user_info = self.get_success(
  286. self.auth.get_user_by_access_token(macaroon.serialize())
  287. )
  288. self.assertEqual(user_id, user_info.user_id)
  289. # TODO: device_id should come from the macaroon, but currently comes
  290. # from the db.
  291. self.assertEqual(user_info.device_id, "device")
  292. def test_get_guest_user_from_macaroon(self):
  293. self.store.get_user_by_id = simple_async_mock({"is_guest": True})
  294. self.store.get_user_by_access_token = simple_async_mock(None)
  295. user_id = "@baldrick:matrix.org"
  296. macaroon = pymacaroons.Macaroon(
  297. location=self.hs.config.server.server_name,
  298. identifier="key",
  299. key=self.hs.config.key.macaroon_secret_key,
  300. )
  301. macaroon.add_first_party_caveat("gen = 1")
  302. macaroon.add_first_party_caveat("type = access")
  303. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  304. macaroon.add_first_party_caveat("guest = true")
  305. serialized = macaroon.serialize()
  306. user_info = self.get_success(self.auth.get_user_by_access_token(serialized))
  307. self.assertEqual(user_id, user_info.user_id)
  308. self.assertTrue(user_info.is_guest)
  309. self.store.get_user_by_id.assert_called_with(user_id)
  310. def test_blocking_mau(self):
  311. self.auth_blocking._limit_usage_by_mau = False
  312. self.auth_blocking._max_mau_value = 50
  313. lots_of_users = 100
  314. small_number_of_users = 1
  315. # Ensure no error thrown
  316. self.get_success(self.auth.check_auth_blocking())
  317. self.auth_blocking._limit_usage_by_mau = True
  318. self.store.get_monthly_active_count = simple_async_mock(lots_of_users)
  319. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  320. self.assertEqual(e.value.admin_contact, self.hs.config.server.admin_contact)
  321. self.assertEqual(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  322. self.assertEqual(e.value.code, 403)
  323. # Ensure does not throw an error
  324. self.store.get_monthly_active_count = simple_async_mock(small_number_of_users)
  325. self.get_success(self.auth.check_auth_blocking())
  326. def test_blocking_mau__depending_on_user_type(self):
  327. self.auth_blocking._max_mau_value = 50
  328. self.auth_blocking._limit_usage_by_mau = True
  329. self.store.get_monthly_active_count = simple_async_mock(100)
  330. # Support users allowed
  331. self.get_success(self.auth.check_auth_blocking(user_type=UserTypes.SUPPORT))
  332. self.store.get_monthly_active_count = simple_async_mock(100)
  333. # Bots not allowed
  334. self.get_failure(
  335. self.auth.check_auth_blocking(user_type=UserTypes.BOT), ResourceLimitError
  336. )
  337. self.store.get_monthly_active_count = simple_async_mock(100)
  338. # Real users not allowed
  339. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  340. def test_blocking_mau__appservice_requester_allowed_when_not_tracking_ips(self):
  341. self.auth_blocking._max_mau_value = 50
  342. self.auth_blocking._limit_usage_by_mau = True
  343. self.auth_blocking._track_appservice_user_ips = False
  344. self.store.get_monthly_active_count = simple_async_mock(100)
  345. self.store.user_last_seen_monthly_active = simple_async_mock()
  346. self.store.is_trial_user = simple_async_mock()
  347. appservice = ApplicationService(
  348. "abcd",
  349. self.hs.config.server.server_name,
  350. id="1234",
  351. namespaces={
  352. "users": [{"regex": "@_appservice.*:sender", "exclusive": True}]
  353. },
  354. sender="@appservice:sender",
  355. )
  356. requester = Requester(
  357. user="@appservice:server",
  358. access_token_id=None,
  359. device_id="FOOBAR",
  360. is_guest=False,
  361. shadow_banned=False,
  362. app_service=appservice,
  363. authenticated_entity="@appservice:server",
  364. )
  365. self.get_success(self.auth.check_auth_blocking(requester=requester))
  366. def test_blocking_mau__appservice_requester_disallowed_when_tracking_ips(self):
  367. self.auth_blocking._max_mau_value = 50
  368. self.auth_blocking._limit_usage_by_mau = True
  369. self.auth_blocking._track_appservice_user_ips = True
  370. self.store.get_monthly_active_count = simple_async_mock(100)
  371. self.store.user_last_seen_monthly_active = simple_async_mock()
  372. self.store.is_trial_user = simple_async_mock()
  373. appservice = ApplicationService(
  374. "abcd",
  375. self.hs.config.server.server_name,
  376. id="1234",
  377. namespaces={
  378. "users": [{"regex": "@_appservice.*:sender", "exclusive": True}]
  379. },
  380. sender="@appservice:sender",
  381. )
  382. requester = Requester(
  383. user="@appservice:server",
  384. access_token_id=None,
  385. device_id="FOOBAR",
  386. is_guest=False,
  387. shadow_banned=False,
  388. app_service=appservice,
  389. authenticated_entity="@appservice:server",
  390. )
  391. self.get_failure(
  392. self.auth.check_auth_blocking(requester=requester), ResourceLimitError
  393. )
  394. def test_reserved_threepid(self):
  395. self.auth_blocking._limit_usage_by_mau = True
  396. self.auth_blocking._max_mau_value = 1
  397. self.store.get_monthly_active_count = simple_async_mock(2)
  398. threepid = {"medium": "email", "address": "reserved@server.com"}
  399. unknown_threepid = {"medium": "email", "address": "unreserved@server.com"}
  400. self.auth_blocking._mau_limits_reserved_threepids = [threepid]
  401. self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  402. self.get_failure(
  403. self.auth.check_auth_blocking(threepid=unknown_threepid), ResourceLimitError
  404. )
  405. self.get_success(self.auth.check_auth_blocking(threepid=threepid))
  406. def test_hs_disabled(self):
  407. self.auth_blocking._hs_disabled = True
  408. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  409. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  410. self.assertEqual(e.value.admin_contact, self.hs.config.server.admin_contact)
  411. self.assertEqual(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  412. self.assertEqual(e.value.code, 403)
  413. def test_hs_disabled_no_server_notices_user(self):
  414. """Check that 'hs_disabled_message' works correctly when there is no
  415. server_notices user.
  416. """
  417. # this should be the default, but we had a bug where the test was doing the wrong
  418. # thing, so let's make it explicit
  419. self.auth_blocking._server_notices_mxid = None
  420. self.auth_blocking._hs_disabled = True
  421. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  422. e = self.get_failure(self.auth.check_auth_blocking(), ResourceLimitError)
  423. self.assertEqual(e.value.admin_contact, self.hs.config.server.admin_contact)
  424. self.assertEqual(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  425. self.assertEqual(e.value.code, 403)
  426. def test_server_notices_mxid_special_cased(self):
  427. self.auth_blocking._hs_disabled = True
  428. user = "@user:server"
  429. self.auth_blocking._server_notices_mxid = user
  430. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  431. self.get_success(self.auth.check_auth_blocking(user))