test_auth.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015 - 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from mock import Mock
  16. import pymacaroons
  17. from twisted.internet import defer
  18. import synapse.handlers.auth
  19. from synapse.api.auth import Auth
  20. from synapse.api.errors import AuthError, Codes, ResourceLimitError
  21. from synapse.types import UserID
  22. from tests import unittest
  23. from tests.utils import mock_getRawHeaders, setup_test_homeserver
  24. class TestHandlers(object):
  25. def __init__(self, hs):
  26. self.auth_handler = synapse.handlers.auth.AuthHandler(hs)
  27. class AuthTestCase(unittest.TestCase):
  28. @defer.inlineCallbacks
  29. def setUp(self):
  30. self.state_handler = Mock()
  31. self.store = Mock()
  32. self.hs = yield setup_test_homeserver(self.addCleanup, handlers=None)
  33. self.hs.get_datastore = Mock(return_value=self.store)
  34. self.hs.handlers = TestHandlers(self.hs)
  35. self.auth = Auth(self.hs)
  36. self.test_user = "@foo:bar"
  37. self.test_token = b"_test_token_"
  38. # this is overridden for the appservice tests
  39. self.store.get_app_service_by_token = Mock(return_value=None)
  40. @defer.inlineCallbacks
  41. def test_get_user_by_req_user_valid_token(self):
  42. user_info = {"name": self.test_user, "token_id": "ditto", "device_id": "device"}
  43. self.store.get_user_by_access_token = Mock(return_value=user_info)
  44. request = Mock(args={})
  45. request.args[b"access_token"] = [self.test_token]
  46. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  47. requester = yield self.auth.get_user_by_req(request)
  48. self.assertEquals(requester.user.to_string(), self.test_user)
  49. def test_get_user_by_req_user_bad_token(self):
  50. self.store.get_user_by_access_token = Mock(return_value=None)
  51. request = Mock(args={})
  52. request.args[b"access_token"] = [self.test_token]
  53. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  54. d = self.auth.get_user_by_req(request)
  55. self.failureResultOf(d, AuthError)
  56. def test_get_user_by_req_user_missing_token(self):
  57. user_info = {"name": self.test_user, "token_id": "ditto"}
  58. self.store.get_user_by_access_token = Mock(return_value=user_info)
  59. request = Mock(args={})
  60. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  61. d = self.auth.get_user_by_req(request)
  62. self.failureResultOf(d, AuthError)
  63. @defer.inlineCallbacks
  64. def test_get_user_by_req_appservice_valid_token(self):
  65. app_service = Mock(
  66. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  67. )
  68. self.store.get_app_service_by_token = Mock(return_value=app_service)
  69. self.store.get_user_by_access_token = Mock(return_value=None)
  70. request = Mock(args={})
  71. request.getClientIP.return_value = "127.0.0.1"
  72. request.args[b"access_token"] = [self.test_token]
  73. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  74. requester = yield self.auth.get_user_by_req(request)
  75. self.assertEquals(requester.user.to_string(), self.test_user)
  76. @defer.inlineCallbacks
  77. def test_get_user_by_req_appservice_valid_token_good_ip(self):
  78. from netaddr import IPSet
  79. app_service = Mock(
  80. token="foobar",
  81. url="a_url",
  82. sender=self.test_user,
  83. ip_range_whitelist=IPSet(["192.168/16"]),
  84. )
  85. self.store.get_app_service_by_token = Mock(return_value=app_service)
  86. self.store.get_user_by_access_token = Mock(return_value=None)
  87. request = Mock(args={})
  88. request.getClientIP.return_value = "192.168.10.10"
  89. request.args[b"access_token"] = [self.test_token]
  90. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  91. requester = yield self.auth.get_user_by_req(request)
  92. self.assertEquals(requester.user.to_string(), self.test_user)
  93. def test_get_user_by_req_appservice_valid_token_bad_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 = Mock(return_value=None)
  103. request = Mock(args={})
  104. request.getClientIP.return_value = "131.111.8.42"
  105. request.args[b"access_token"] = [self.test_token]
  106. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  107. d = self.auth.get_user_by_req(request)
  108. self.failureResultOf(d, AuthError)
  109. def test_get_user_by_req_appservice_bad_token(self):
  110. self.store.get_app_service_by_token = Mock(return_value=None)
  111. self.store.get_user_by_access_token = Mock(return_value=None)
  112. request = Mock(args={})
  113. request.args[b"access_token"] = [self.test_token]
  114. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  115. d = self.auth.get_user_by_req(request)
  116. self.failureResultOf(d, AuthError)
  117. def test_get_user_by_req_appservice_missing_token(self):
  118. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  119. self.store.get_app_service_by_token = Mock(return_value=app_service)
  120. self.store.get_user_by_access_token = Mock(return_value=None)
  121. request = Mock(args={})
  122. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  123. d = self.auth.get_user_by_req(request)
  124. self.failureResultOf(d, AuthError)
  125. @defer.inlineCallbacks
  126. def test_get_user_by_req_appservice_valid_token_valid_user_id(self):
  127. masquerading_user_id = b"@doppelganger:matrix.org"
  128. app_service = Mock(
  129. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  130. )
  131. app_service.is_interested_in_user = Mock(return_value=True)
  132. self.store.get_app_service_by_token = Mock(return_value=app_service)
  133. self.store.get_user_by_access_token = Mock(return_value=None)
  134. request = Mock(args={})
  135. request.getClientIP.return_value = "127.0.0.1"
  136. request.args[b"access_token"] = [self.test_token]
  137. request.args[b"user_id"] = [masquerading_user_id]
  138. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  139. requester = yield self.auth.get_user_by_req(request)
  140. self.assertEquals(
  141. requester.user.to_string(), masquerading_user_id.decode('utf8')
  142. )
  143. def test_get_user_by_req_appservice_valid_token_bad_user_id(self):
  144. masquerading_user_id = b"@doppelganger:matrix.org"
  145. app_service = Mock(
  146. token="foobar", url="a_url", sender=self.test_user, ip_range_whitelist=None
  147. )
  148. app_service.is_interested_in_user = Mock(return_value=False)
  149. self.store.get_app_service_by_token = Mock(return_value=app_service)
  150. self.store.get_user_by_access_token = Mock(return_value=None)
  151. request = Mock(args={})
  152. request.getClientIP.return_value = "127.0.0.1"
  153. request.args[b"access_token"] = [self.test_token]
  154. request.args[b"user_id"] = [masquerading_user_id]
  155. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  156. d = self.auth.get_user_by_req(request)
  157. self.failureResultOf(d, AuthError)
  158. @defer.inlineCallbacks
  159. def test_get_user_from_macaroon(self):
  160. # TODO(danielwh): Remove this mock when we remove the
  161. # get_user_by_access_token fallback.
  162. self.store.get_user_by_access_token = Mock(
  163. return_value={"name": "@baldrick:matrix.org", "device_id": "device"}
  164. )
  165. user_id = "@baldrick:matrix.org"
  166. macaroon = pymacaroons.Macaroon(
  167. location=self.hs.config.server_name,
  168. identifier="key",
  169. key=self.hs.config.macaroon_secret_key,
  170. )
  171. macaroon.add_first_party_caveat("gen = 1")
  172. macaroon.add_first_party_caveat("type = access")
  173. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  174. user_info = yield self.auth.get_user_by_access_token(macaroon.serialize())
  175. user = user_info["user"]
  176. self.assertEqual(UserID.from_string(user_id), user)
  177. # TODO: device_id should come from the macaroon, but currently comes
  178. # from the db.
  179. self.assertEqual(user_info["device_id"], "device")
  180. @defer.inlineCallbacks
  181. def test_get_guest_user_from_macaroon(self):
  182. self.store.get_user_by_id = Mock(return_value={"is_guest": True})
  183. user_id = "@baldrick:matrix.org"
  184. macaroon = pymacaroons.Macaroon(
  185. location=self.hs.config.server_name,
  186. identifier="key",
  187. key=self.hs.config.macaroon_secret_key,
  188. )
  189. macaroon.add_first_party_caveat("gen = 1")
  190. macaroon.add_first_party_caveat("type = access")
  191. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  192. macaroon.add_first_party_caveat("guest = true")
  193. serialized = macaroon.serialize()
  194. user_info = yield self.auth.get_user_by_access_token(serialized)
  195. user = user_info["user"]
  196. is_guest = user_info["is_guest"]
  197. self.assertEqual(UserID.from_string(user_id), user)
  198. self.assertTrue(is_guest)
  199. self.store.get_user_by_id.assert_called_with(user_id)
  200. @defer.inlineCallbacks
  201. def test_get_user_from_macaroon_user_db_mismatch(self):
  202. self.store.get_user_by_access_token = Mock(
  203. return_value={"name": "@percy:matrix.org"}
  204. )
  205. user = "@baldrick:matrix.org"
  206. macaroon = pymacaroons.Macaroon(
  207. location=self.hs.config.server_name,
  208. identifier="key",
  209. key=self.hs.config.macaroon_secret_key,
  210. )
  211. macaroon.add_first_party_caveat("gen = 1")
  212. macaroon.add_first_party_caveat("type = access")
  213. macaroon.add_first_party_caveat("user_id = %s" % (user,))
  214. with self.assertRaises(AuthError) as cm:
  215. yield self.auth.get_user_by_access_token(macaroon.serialize())
  216. self.assertEqual(401, cm.exception.code)
  217. self.assertIn("User mismatch", cm.exception.msg)
  218. @defer.inlineCallbacks
  219. def test_get_user_from_macaroon_missing_caveat(self):
  220. # TODO(danielwh): Remove this mock when we remove the
  221. # get_user_by_access_token fallback.
  222. self.store.get_user_by_access_token = Mock(
  223. return_value={"name": "@baldrick:matrix.org"}
  224. )
  225. macaroon = pymacaroons.Macaroon(
  226. location=self.hs.config.server_name,
  227. identifier="key",
  228. key=self.hs.config.macaroon_secret_key,
  229. )
  230. macaroon.add_first_party_caveat("gen = 1")
  231. macaroon.add_first_party_caveat("type = access")
  232. with self.assertRaises(AuthError) as cm:
  233. yield self.auth.get_user_by_access_token(macaroon.serialize())
  234. self.assertEqual(401, cm.exception.code)
  235. self.assertIn("No user caveat", cm.exception.msg)
  236. @defer.inlineCallbacks
  237. def test_get_user_from_macaroon_wrong_key(self):
  238. # TODO(danielwh): Remove this mock when we remove the
  239. # get_user_by_access_token fallback.
  240. self.store.get_user_by_access_token = Mock(
  241. return_value={"name": "@baldrick:matrix.org"}
  242. )
  243. user = "@baldrick:matrix.org"
  244. macaroon = pymacaroons.Macaroon(
  245. location=self.hs.config.server_name,
  246. identifier="key",
  247. key=self.hs.config.macaroon_secret_key + "wrong",
  248. )
  249. macaroon.add_first_party_caveat("gen = 1")
  250. macaroon.add_first_party_caveat("type = access")
  251. macaroon.add_first_party_caveat("user_id = %s" % (user,))
  252. with self.assertRaises(AuthError) as cm:
  253. yield self.auth.get_user_by_access_token(macaroon.serialize())
  254. self.assertEqual(401, cm.exception.code)
  255. self.assertIn("Invalid macaroon", cm.exception.msg)
  256. @defer.inlineCallbacks
  257. def test_get_user_from_macaroon_unknown_caveat(self):
  258. # TODO(danielwh): Remove this mock when we remove the
  259. # get_user_by_access_token fallback.
  260. self.store.get_user_by_access_token = Mock(
  261. return_value={"name": "@baldrick:matrix.org"}
  262. )
  263. user = "@baldrick:matrix.org"
  264. macaroon = pymacaroons.Macaroon(
  265. location=self.hs.config.server_name,
  266. identifier="key",
  267. key=self.hs.config.macaroon_secret_key,
  268. )
  269. macaroon.add_first_party_caveat("gen = 1")
  270. macaroon.add_first_party_caveat("type = access")
  271. macaroon.add_first_party_caveat("user_id = %s" % (user,))
  272. macaroon.add_first_party_caveat("cunning > fox")
  273. with self.assertRaises(AuthError) as cm:
  274. yield self.auth.get_user_by_access_token(macaroon.serialize())
  275. self.assertEqual(401, cm.exception.code)
  276. self.assertIn("Invalid macaroon", cm.exception.msg)
  277. @defer.inlineCallbacks
  278. def test_get_user_from_macaroon_expired(self):
  279. # TODO(danielwh): Remove this mock when we remove the
  280. # get_user_by_access_token fallback.
  281. self.store.get_user_by_access_token = Mock(
  282. return_value={"name": "@baldrick:matrix.org"}
  283. )
  284. self.store.get_user_by_access_token = Mock(
  285. return_value={"name": "@baldrick:matrix.org"}
  286. )
  287. user = "@baldrick:matrix.org"
  288. macaroon = pymacaroons.Macaroon(
  289. location=self.hs.config.server_name,
  290. identifier="key",
  291. key=self.hs.config.macaroon_secret_key,
  292. )
  293. macaroon.add_first_party_caveat("gen = 1")
  294. macaroon.add_first_party_caveat("type = access")
  295. macaroon.add_first_party_caveat("user_id = %s" % (user,))
  296. macaroon.add_first_party_caveat("time < -2000") # ms
  297. self.hs.clock.now = 5000 # seconds
  298. self.hs.config.expire_access_token = True
  299. # yield self.auth.get_user_by_access_token(macaroon.serialize())
  300. # TODO(daniel): Turn on the check that we validate expiration, when we
  301. # validate expiration (and remove the above line, which will start
  302. # throwing).
  303. with self.assertRaises(AuthError) as cm:
  304. yield self.auth.get_user_by_access_token(macaroon.serialize())
  305. self.assertEqual(401, cm.exception.code)
  306. self.assertIn("Invalid macaroon", cm.exception.msg)
  307. @defer.inlineCallbacks
  308. def test_get_user_from_macaroon_with_valid_duration(self):
  309. # TODO(danielwh): Remove this mock when we remove the
  310. # get_user_by_access_token fallback.
  311. self.store.get_user_by_access_token = Mock(
  312. return_value={"name": "@baldrick:matrix.org"}
  313. )
  314. self.store.get_user_by_access_token = Mock(
  315. return_value={"name": "@baldrick:matrix.org"}
  316. )
  317. user_id = "@baldrick:matrix.org"
  318. macaroon = pymacaroons.Macaroon(
  319. location=self.hs.config.server_name,
  320. identifier="key",
  321. key=self.hs.config.macaroon_secret_key,
  322. )
  323. macaroon.add_first_party_caveat("gen = 1")
  324. macaroon.add_first_party_caveat("type = access")
  325. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  326. macaroon.add_first_party_caveat("time < 900000000") # ms
  327. self.hs.clock.now = 5000 # seconds
  328. self.hs.config.expire_access_token = True
  329. user_info = yield self.auth.get_user_by_access_token(macaroon.serialize())
  330. user = user_info["user"]
  331. self.assertEqual(UserID.from_string(user_id), user)
  332. @defer.inlineCallbacks
  333. def test_cannot_use_regular_token_as_guest(self):
  334. USER_ID = "@percy:matrix.org"
  335. self.store.add_access_token_to_user = Mock()
  336. token = yield self.hs.handlers.auth_handler.issue_access_token(
  337. USER_ID, "DEVICE"
  338. )
  339. self.store.add_access_token_to_user.assert_called_with(USER_ID, token, "DEVICE")
  340. def get_user(tok):
  341. if token != tok:
  342. return None
  343. return {
  344. "name": USER_ID,
  345. "is_guest": False,
  346. "token_id": 1234,
  347. "device_id": "DEVICE",
  348. }
  349. self.store.get_user_by_access_token = get_user
  350. self.store.get_user_by_id = Mock(return_value={"is_guest": False})
  351. # check the token works
  352. request = Mock(args={})
  353. request.args[b"access_token"] = [token.encode('ascii')]
  354. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  355. requester = yield self.auth.get_user_by_req(request, allow_guest=True)
  356. self.assertEqual(UserID.from_string(USER_ID), requester.user)
  357. self.assertFalse(requester.is_guest)
  358. # add an is_guest caveat
  359. mac = pymacaroons.Macaroon.deserialize(token)
  360. mac.add_first_party_caveat("guest = true")
  361. guest_tok = mac.serialize()
  362. # the token should *not* work now
  363. request = Mock(args={})
  364. request.args[b"access_token"] = [guest_tok.encode('ascii')]
  365. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  366. with self.assertRaises(AuthError) as cm:
  367. yield self.auth.get_user_by_req(request, allow_guest=True)
  368. self.assertEqual(401, cm.exception.code)
  369. self.assertEqual("Guest access token used for regular user", cm.exception.msg)
  370. self.store.get_user_by_id.assert_called_with(USER_ID)
  371. @defer.inlineCallbacks
  372. def test_blocking_mau(self):
  373. self.hs.config.limit_usage_by_mau = False
  374. self.hs.config.max_mau_value = 50
  375. lots_of_users = 100
  376. small_number_of_users = 1
  377. # Ensure no error thrown
  378. yield self.auth.check_auth_blocking()
  379. self.hs.config.limit_usage_by_mau = True
  380. self.store.get_monthly_active_count = Mock(
  381. return_value=defer.succeed(lots_of_users)
  382. )
  383. with self.assertRaises(ResourceLimitError) as e:
  384. yield self.auth.check_auth_blocking()
  385. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  386. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  387. self.assertEquals(e.exception.code, 403)
  388. # Ensure does not throw an error
  389. self.store.get_monthly_active_count = Mock(
  390. return_value=defer.succeed(small_number_of_users)
  391. )
  392. yield self.auth.check_auth_blocking()
  393. @defer.inlineCallbacks
  394. def test_reserved_threepid(self):
  395. self.hs.config.limit_usage_by_mau = True
  396. self.hs.config.max_mau_value = 1
  397. self.store.get_monthly_active_count = lambda: defer.succeed(2)
  398. threepid = {'medium': 'email', 'address': 'reserved@server.com'}
  399. unknown_threepid = {'medium': 'email', 'address': 'unreserved@server.com'}
  400. self.hs.config.mau_limits_reserved_threepids = [threepid]
  401. yield self.store.register(user_id='user1', token="123", password_hash=None)
  402. with self.assertRaises(ResourceLimitError):
  403. yield self.auth.check_auth_blocking()
  404. with self.assertRaises(ResourceLimitError):
  405. yield self.auth.check_auth_blocking(threepid=unknown_threepid)
  406. yield self.auth.check_auth_blocking(threepid=threepid)
  407. @defer.inlineCallbacks
  408. def test_hs_disabled(self):
  409. self.hs.config.hs_disabled = True
  410. self.hs.config.hs_disabled_message = "Reason for being disabled"
  411. with self.assertRaises(ResourceLimitError) as e:
  412. yield self.auth.check_auth_blocking()
  413. self.assertEquals(e.exception.admin_contact, self.hs.config.admin_contact)
  414. self.assertEquals(e.exception.errcode, Codes.RESOURCE_LIMIT_EXCEEDED)
  415. self.assertEquals(e.exception.code, 403)
  416. @defer.inlineCallbacks
  417. def test_server_notices_mxid_special_cased(self):
  418. self.hs.config.hs_disabled = True
  419. user = "@user:server"
  420. self.hs.config.server_notices_mxid = user
  421. self.hs.config.hs_disabled_message = "Reason for being disabled"
  422. yield self.auth.check_auth_blocking(user)