1
0

test_auth.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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_owner="@admin:matrix.org",
  248. )
  249. )
  250. self.store.insert_client_ip = simple_async_mock(None)
  251. request = Mock(args={})
  252. request.getClientAddress.return_value.host = "127.0.0.1"
  253. request.args[b"access_token"] = [self.test_token]
  254. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  255. self.get_success(self.auth.get_user_by_req(request))
  256. self.store.insert_client_ip.assert_called_once()
  257. def test_get_user_by_req__puppeted_token__tracking_puppeted_mau(self):
  258. self.auth._track_puppeted_user_ips = True
  259. self.store.get_user_by_access_token = simple_async_mock(
  260. TokenLookupResult(
  261. user_id="@baldrick:matrix.org",
  262. device_id="device",
  263. token_owner="@admin:matrix.org",
  264. )
  265. )
  266. self.store.insert_client_ip = simple_async_mock(None)
  267. request = Mock(args={})
  268. request.getClientAddress.return_value.host = "127.0.0.1"
  269. request.args[b"access_token"] = [self.test_token]
  270. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  271. self.get_success(self.auth.get_user_by_req(request))
  272. self.assertEqual(self.store.insert_client_ip.call_count, 2)
  273. def test_get_user_from_macaroon(self):
  274. self.store.get_user_by_access_token = simple_async_mock(None)
  275. user_id = "@baldrick:matrix.org"
  276. macaroon = pymacaroons.Macaroon(
  277. location=self.hs.config.server.server_name,
  278. identifier="key",
  279. key=self.hs.config.key.macaroon_secret_key,
  280. )
  281. # "Legacy" macaroons should not work for regular users not in the database
  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. serialized = macaroon.serialize()
  286. self.get_failure(
  287. self.auth.get_user_by_access_token(serialized), InvalidClientTokenError
  288. )
  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_blocking.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(
  317. self.auth_blocking.check_auth_blocking(), ResourceLimitError
  318. )
  319. self.assertEqual(e.value.admin_contact, self.hs.config.server.admin_contact)
  320. self.assertEqual(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  321. self.assertEqual(e.value.code, 403)
  322. # Ensure does not throw an error
  323. self.store.get_monthly_active_count = simple_async_mock(small_number_of_users)
  324. self.get_success(self.auth_blocking.check_auth_blocking())
  325. def test_blocking_mau__depending_on_user_type(self):
  326. self.auth_blocking._max_mau_value = 50
  327. self.auth_blocking._limit_usage_by_mau = True
  328. self.store.get_monthly_active_count = simple_async_mock(100)
  329. # Support users allowed
  330. self.get_success(
  331. self.auth_blocking.check_auth_blocking(user_type=UserTypes.SUPPORT)
  332. )
  333. self.store.get_monthly_active_count = simple_async_mock(100)
  334. # Bots not allowed
  335. self.get_failure(
  336. self.auth_blocking.check_auth_blocking(user_type=UserTypes.BOT),
  337. ResourceLimitError,
  338. )
  339. self.store.get_monthly_active_count = simple_async_mock(100)
  340. # Real users not allowed
  341. self.get_failure(self.auth_blocking.check_auth_blocking(), ResourceLimitError)
  342. def test_blocking_mau__appservice_requester_allowed_when_not_tracking_ips(self):
  343. self.auth_blocking._max_mau_value = 50
  344. self.auth_blocking._limit_usage_by_mau = True
  345. self.auth_blocking._track_appservice_user_ips = False
  346. self.store.get_monthly_active_count = simple_async_mock(100)
  347. self.store.user_last_seen_monthly_active = simple_async_mock()
  348. self.store.is_trial_user = simple_async_mock()
  349. appservice = ApplicationService(
  350. "abcd",
  351. id="1234",
  352. namespaces={
  353. "users": [{"regex": "@_appservice.*:sender", "exclusive": True}]
  354. },
  355. sender="@appservice:sender",
  356. )
  357. requester = Requester(
  358. user="@appservice:server",
  359. access_token_id=None,
  360. device_id="FOOBAR",
  361. is_guest=False,
  362. shadow_banned=False,
  363. app_service=appservice,
  364. authenticated_entity="@appservice:server",
  365. )
  366. self.get_success(self.auth_blocking.check_auth_blocking(requester=requester))
  367. def test_blocking_mau__appservice_requester_disallowed_when_tracking_ips(self):
  368. self.auth_blocking._max_mau_value = 50
  369. self.auth_blocking._limit_usage_by_mau = True
  370. self.auth_blocking._track_appservice_user_ips = True
  371. self.store.get_monthly_active_count = simple_async_mock(100)
  372. self.store.user_last_seen_monthly_active = simple_async_mock()
  373. self.store.is_trial_user = simple_async_mock()
  374. appservice = ApplicationService(
  375. "abcd",
  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_blocking.check_auth_blocking(requester=requester),
  393. ResourceLimitError,
  394. )
  395. def test_reserved_threepid(self):
  396. self.auth_blocking._limit_usage_by_mau = True
  397. self.auth_blocking._max_mau_value = 1
  398. self.store.get_monthly_active_count = simple_async_mock(2)
  399. threepid = {"medium": "email", "address": "reserved@server.com"}
  400. unknown_threepid = {"medium": "email", "address": "unreserved@server.com"}
  401. self.auth_blocking._mau_limits_reserved_threepids = [threepid]
  402. self.get_failure(self.auth_blocking.check_auth_blocking(), ResourceLimitError)
  403. self.get_failure(
  404. self.auth_blocking.check_auth_blocking(threepid=unknown_threepid),
  405. ResourceLimitError,
  406. )
  407. self.get_success(self.auth_blocking.check_auth_blocking(threepid=threepid))
  408. def test_hs_disabled(self):
  409. self.auth_blocking._hs_disabled = True
  410. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  411. e = self.get_failure(
  412. self.auth_blocking.check_auth_blocking(), ResourceLimitError
  413. )
  414. self.assertEqual(e.value.admin_contact, self.hs.config.server.admin_contact)
  415. self.assertEqual(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  416. self.assertEqual(e.value.code, 403)
  417. def test_hs_disabled_no_server_notices_user(self):
  418. """Check that 'hs_disabled_message' works correctly when there is no
  419. server_notices user.
  420. """
  421. # this should be the default, but we had a bug where the test was doing the wrong
  422. # thing, so let's make it explicit
  423. self.auth_blocking._server_notices_mxid = None
  424. self.auth_blocking._hs_disabled = True
  425. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  426. e = self.get_failure(
  427. self.auth_blocking.check_auth_blocking(), ResourceLimitError
  428. )
  429. self.assertEqual(e.value.admin_contact, self.hs.config.server.admin_contact)
  430. self.assertEqual(e.value.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  431. self.assertEqual(e.value.code, 403)
  432. def test_server_notices_mxid_special_cased(self):
  433. self.auth_blocking._hs_disabled = True
  434. user = "@user:server"
  435. self.auth_blocking._server_notices_mxid = user
  436. self.auth_blocking._hs_disabled_message = "Reason for being disabled"
  437. self.get_success(self.auth_blocking.check_auth_blocking(user))