test_auth.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 tests import unittest
  16. from twisted.internet import defer
  17. from mock import Mock
  18. from synapse.api.auth import Auth
  19. from synapse.api.errors import AuthError
  20. from synapse.types import UserID
  21. from tests.utils import setup_test_homeserver
  22. import pymacaroons
  23. class AuthTestCase(unittest.TestCase):
  24. @defer.inlineCallbacks
  25. def setUp(self):
  26. self.state_handler = Mock()
  27. self.store = Mock()
  28. self.hs = yield setup_test_homeserver(handlers=None)
  29. self.hs.get_datastore = Mock(return_value=self.store)
  30. self.auth = Auth(self.hs)
  31. self.test_user = "@foo:bar"
  32. self.test_token = "_test_token_"
  33. @defer.inlineCallbacks
  34. def test_get_user_by_req_user_valid_token(self):
  35. self.store.get_app_service_by_token = Mock(return_value=None)
  36. user_info = {
  37. "name": self.test_user,
  38. "token_id": "ditto",
  39. "device_id": "device",
  40. }
  41. self.store.get_user_by_access_token = Mock(return_value=user_info)
  42. request = Mock(args={})
  43. request.args["access_token"] = [self.test_token]
  44. request.requestHeaders.getRawHeaders = Mock(return_value=[""])
  45. requester = yield self.auth.get_user_by_req(request)
  46. self.assertEquals(requester.user.to_string(), self.test_user)
  47. def test_get_user_by_req_user_bad_token(self):
  48. self.store.get_app_service_by_token = Mock(return_value=None)
  49. self.store.get_user_by_access_token = Mock(return_value=None)
  50. request = Mock(args={})
  51. request.args["access_token"] = [self.test_token]
  52. request.requestHeaders.getRawHeaders = Mock(return_value=[""])
  53. d = self.auth.get_user_by_req(request)
  54. self.failureResultOf(d, AuthError)
  55. def test_get_user_by_req_user_missing_token(self):
  56. self.store.get_app_service_by_token = Mock(return_value=None)
  57. user_info = {
  58. "name": self.test_user,
  59. "token_id": "ditto",
  60. }
  61. self.store.get_user_by_access_token = Mock(return_value=user_info)
  62. request = Mock(args={})
  63. request.requestHeaders.getRawHeaders = Mock(return_value=[""])
  64. d = self.auth.get_user_by_req(request)
  65. self.failureResultOf(d, AuthError)
  66. @defer.inlineCallbacks
  67. def test_get_user_by_req_appservice_valid_token(self):
  68. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  69. self.store.get_app_service_by_token = Mock(return_value=app_service)
  70. self.store.get_user_by_access_token = Mock(return_value=None)
  71. request = Mock(args={})
  72. request.args["access_token"] = [self.test_token]
  73. request.requestHeaders.getRawHeaders = Mock(return_value=[""])
  74. requester = yield self.auth.get_user_by_req(request)
  75. self.assertEquals(requester.user.to_string(), self.test_user)
  76. def test_get_user_by_req_appservice_bad_token(self):
  77. self.store.get_app_service_by_token = Mock(return_value=None)
  78. self.store.get_user_by_access_token = Mock(return_value=None)
  79. request = Mock(args={})
  80. request.args["access_token"] = [self.test_token]
  81. request.requestHeaders.getRawHeaders = Mock(return_value=[""])
  82. d = self.auth.get_user_by_req(request)
  83. self.failureResultOf(d, AuthError)
  84. def test_get_user_by_req_appservice_missing_token(self):
  85. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  86. self.store.get_app_service_by_token = Mock(return_value=app_service)
  87. self.store.get_user_by_access_token = Mock(return_value=None)
  88. request = Mock(args={})
  89. request.requestHeaders.getRawHeaders = Mock(return_value=[""])
  90. d = self.auth.get_user_by_req(request)
  91. self.failureResultOf(d, AuthError)
  92. @defer.inlineCallbacks
  93. def test_get_user_by_req_appservice_valid_token_valid_user_id(self):
  94. masquerading_user_id = "@doppelganger:matrix.org"
  95. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  96. app_service.is_interested_in_user = Mock(return_value=True)
  97. self.store.get_app_service_by_token = Mock(return_value=app_service)
  98. self.store.get_user_by_access_token = Mock(return_value=None)
  99. request = Mock(args={})
  100. request.args["access_token"] = [self.test_token]
  101. request.args["user_id"] = [masquerading_user_id]
  102. request.requestHeaders.getRawHeaders = Mock(return_value=[""])
  103. requester = yield self.auth.get_user_by_req(request)
  104. self.assertEquals(requester.user.to_string(), masquerading_user_id)
  105. def test_get_user_by_req_appservice_valid_token_bad_user_id(self):
  106. masquerading_user_id = "@doppelganger:matrix.org"
  107. app_service = Mock(token="foobar", url="a_url", sender=self.test_user)
  108. app_service.is_interested_in_user = Mock(return_value=False)
  109. self.store.get_app_service_by_token = Mock(return_value=app_service)
  110. self.store.get_user_by_access_token = Mock(return_value=None)
  111. request = Mock(args={})
  112. request.args["access_token"] = [self.test_token]
  113. request.args["user_id"] = [masquerading_user_id]
  114. request.requestHeaders.getRawHeaders = Mock(return_value=[""])
  115. d = self.auth.get_user_by_req(request)
  116. self.failureResultOf(d, AuthError)
  117. @defer.inlineCallbacks
  118. def test_get_user_from_macaroon(self):
  119. # TODO(danielwh): Remove this mock when we remove the
  120. # get_user_by_access_token fallback.
  121. self.store.get_user_by_access_token = Mock(
  122. return_value={
  123. "name": "@baldrick:matrix.org",
  124. "device_id": "device",
  125. }
  126. )
  127. user_id = "@baldrick:matrix.org"
  128. macaroon = pymacaroons.Macaroon(
  129. location=self.hs.config.server_name,
  130. identifier="key",
  131. key=self.hs.config.macaroon_secret_key)
  132. macaroon.add_first_party_caveat("gen = 1")
  133. macaroon.add_first_party_caveat("type = access")
  134. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  135. user_info = yield self.auth.get_user_from_macaroon(macaroon.serialize())
  136. user = user_info["user"]
  137. self.assertEqual(UserID.from_string(user_id), user)
  138. # TODO: device_id should come from the macaroon, but currently comes
  139. # from the db.
  140. self.assertEqual(user_info["device_id"], "device")
  141. @defer.inlineCallbacks
  142. def test_get_guest_user_from_macaroon(self):
  143. user_id = "@baldrick:matrix.org"
  144. macaroon = pymacaroons.Macaroon(
  145. location=self.hs.config.server_name,
  146. identifier="key",
  147. key=self.hs.config.macaroon_secret_key)
  148. macaroon.add_first_party_caveat("gen = 1")
  149. macaroon.add_first_party_caveat("type = access")
  150. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  151. macaroon.add_first_party_caveat("guest = true")
  152. serialized = macaroon.serialize()
  153. user_info = yield self.auth.get_user_from_macaroon(serialized)
  154. user = user_info["user"]
  155. is_guest = user_info["is_guest"]
  156. self.assertEqual(UserID.from_string(user_id), user)
  157. self.assertTrue(is_guest)
  158. @defer.inlineCallbacks
  159. def test_get_user_from_macaroon_user_db_mismatch(self):
  160. self.store.get_user_by_access_token = Mock(
  161. return_value={"name": "@percy:matrix.org"}
  162. )
  163. user = "@baldrick:matrix.org"
  164. macaroon = pymacaroons.Macaroon(
  165. location=self.hs.config.server_name,
  166. identifier="key",
  167. key=self.hs.config.macaroon_secret_key)
  168. macaroon.add_first_party_caveat("gen = 1")
  169. macaroon.add_first_party_caveat("type = access")
  170. macaroon.add_first_party_caveat("user_id = %s" % (user,))
  171. with self.assertRaises(AuthError) as cm:
  172. yield self.auth.get_user_from_macaroon(macaroon.serialize())
  173. self.assertEqual(401, cm.exception.code)
  174. self.assertIn("User mismatch", cm.exception.msg)
  175. @defer.inlineCallbacks
  176. def test_get_user_from_macaroon_missing_caveat(self):
  177. # TODO(danielwh): Remove this mock when we remove the
  178. # get_user_by_access_token fallback.
  179. self.store.get_user_by_access_token = Mock(
  180. return_value={"name": "@baldrick:matrix.org"}
  181. )
  182. macaroon = pymacaroons.Macaroon(
  183. location=self.hs.config.server_name,
  184. identifier="key",
  185. key=self.hs.config.macaroon_secret_key)
  186. macaroon.add_first_party_caveat("gen = 1")
  187. macaroon.add_first_party_caveat("type = access")
  188. with self.assertRaises(AuthError) as cm:
  189. yield self.auth.get_user_from_macaroon(macaroon.serialize())
  190. self.assertEqual(401, cm.exception.code)
  191. self.assertIn("No user caveat", cm.exception.msg)
  192. @defer.inlineCallbacks
  193. def test_get_user_from_macaroon_wrong_key(self):
  194. # TODO(danielwh): Remove this mock when we remove the
  195. # get_user_by_access_token fallback.
  196. self.store.get_user_by_access_token = Mock(
  197. return_value={"name": "@baldrick:matrix.org"}
  198. )
  199. user = "@baldrick:matrix.org"
  200. macaroon = pymacaroons.Macaroon(
  201. location=self.hs.config.server_name,
  202. identifier="key",
  203. key=self.hs.config.macaroon_secret_key + "wrong")
  204. macaroon.add_first_party_caveat("gen = 1")
  205. macaroon.add_first_party_caveat("type = access")
  206. macaroon.add_first_party_caveat("user_id = %s" % (user,))
  207. with self.assertRaises(AuthError) as cm:
  208. yield self.auth.get_user_from_macaroon(macaroon.serialize())
  209. self.assertEqual(401, cm.exception.code)
  210. self.assertIn("Invalid macaroon", cm.exception.msg)
  211. @defer.inlineCallbacks
  212. def test_get_user_from_macaroon_unknown_caveat(self):
  213. # TODO(danielwh): Remove this mock when we remove the
  214. # get_user_by_access_token fallback.
  215. self.store.get_user_by_access_token = Mock(
  216. return_value={"name": "@baldrick:matrix.org"}
  217. )
  218. user = "@baldrick:matrix.org"
  219. macaroon = pymacaroons.Macaroon(
  220. location=self.hs.config.server_name,
  221. identifier="key",
  222. key=self.hs.config.macaroon_secret_key)
  223. macaroon.add_first_party_caveat("gen = 1")
  224. macaroon.add_first_party_caveat("type = access")
  225. macaroon.add_first_party_caveat("user_id = %s" % (user,))
  226. macaroon.add_first_party_caveat("cunning > fox")
  227. with self.assertRaises(AuthError) as cm:
  228. yield self.auth.get_user_from_macaroon(macaroon.serialize())
  229. self.assertEqual(401, cm.exception.code)
  230. self.assertIn("Invalid macaroon", cm.exception.msg)
  231. @defer.inlineCallbacks
  232. def test_get_user_from_macaroon_expired(self):
  233. # TODO(danielwh): Remove this mock when we remove the
  234. # get_user_by_access_token fallback.
  235. self.store.get_user_by_access_token = Mock(
  236. return_value={"name": "@baldrick:matrix.org"}
  237. )
  238. self.store.get_user_by_access_token = Mock(
  239. return_value={"name": "@baldrick:matrix.org"}
  240. )
  241. user = "@baldrick:matrix.org"
  242. macaroon = pymacaroons.Macaroon(
  243. location=self.hs.config.server_name,
  244. identifier="key",
  245. key=self.hs.config.macaroon_secret_key)
  246. macaroon.add_first_party_caveat("gen = 1")
  247. macaroon.add_first_party_caveat("type = access")
  248. macaroon.add_first_party_caveat("user_id = %s" % (user,))
  249. macaroon.add_first_party_caveat("time < -2000") # ms
  250. self.hs.clock.now = 5000 # seconds
  251. self.hs.config.expire_access_token = True
  252. # yield self.auth.get_user_from_macaroon(macaroon.serialize())
  253. # TODO(daniel): Turn on the check that we validate expiration, when we
  254. # validate expiration (and remove the above line, which will start
  255. # throwing).
  256. with self.assertRaises(AuthError) as cm:
  257. yield self.auth.get_user_from_macaroon(macaroon.serialize())
  258. self.assertEqual(401, cm.exception.code)
  259. self.assertIn("Invalid macaroon", cm.exception.msg)
  260. @defer.inlineCallbacks
  261. def test_get_user_from_macaroon_with_valid_duration(self):
  262. # TODO(danielwh): Remove this mock when we remove the
  263. # get_user_by_access_token fallback.
  264. self.store.get_user_by_access_token = Mock(
  265. return_value={"name": "@baldrick:matrix.org"}
  266. )
  267. self.store.get_user_by_access_token = Mock(
  268. return_value={"name": "@baldrick:matrix.org"}
  269. )
  270. user_id = "@baldrick:matrix.org"
  271. macaroon = pymacaroons.Macaroon(
  272. location=self.hs.config.server_name,
  273. identifier="key",
  274. key=self.hs.config.macaroon_secret_key)
  275. macaroon.add_first_party_caveat("gen = 1")
  276. macaroon.add_first_party_caveat("type = access")
  277. macaroon.add_first_party_caveat("user_id = %s" % (user_id,))
  278. macaroon.add_first_party_caveat("time < 900000000") # ms
  279. self.hs.clock.now = 5000 # seconds
  280. self.hs.config.expire_access_token = True
  281. user_info = yield self.auth.get_user_from_macaroon(macaroon.serialize())
  282. user = user_info["user"]
  283. self.assertEqual(UserID.from_string(user_id), user)