test_auth.py 22 KB

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