test_auth.py 22 KB

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