test_auth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector
  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 typing import List, Union
  16. from twisted.internet.defer import succeed
  17. import synapse.rest.admin
  18. from synapse.api.constants import LoginType
  19. from synapse.handlers.ui_auth.checkers import UserInteractiveAuthChecker
  20. from synapse.http.site import SynapseRequest
  21. from synapse.rest.client.v1 import login
  22. from synapse.rest.client.v2_alpha import auth, devices, register
  23. from synapse.types import JsonDict
  24. from tests import unittest
  25. from tests.server import FakeChannel
  26. class DummyRecaptchaChecker(UserInteractiveAuthChecker):
  27. def __init__(self, hs):
  28. super().__init__(hs)
  29. self.recaptcha_attempts = []
  30. def check_auth(self, authdict, clientip):
  31. self.recaptcha_attempts.append((authdict, clientip))
  32. return succeed(True)
  33. class DummyPasswordChecker(UserInteractiveAuthChecker):
  34. def check_auth(self, authdict, clientip):
  35. return succeed(authdict["identifier"]["user"])
  36. class FallbackAuthTests(unittest.HomeserverTestCase):
  37. servlets = [
  38. auth.register_servlets,
  39. register.register_servlets,
  40. ]
  41. hijack_auth = False
  42. def make_homeserver(self, reactor, clock):
  43. config = self.default_config()
  44. config["enable_registration_captcha"] = True
  45. config["recaptcha_public_key"] = "brokencake"
  46. config["registrations_require_3pid"] = []
  47. hs = self.setup_test_homeserver(config=config)
  48. return hs
  49. def prepare(self, reactor, clock, hs):
  50. self.recaptcha_checker = DummyRecaptchaChecker(hs)
  51. auth_handler = hs.get_auth_handler()
  52. auth_handler.checkers[LoginType.RECAPTCHA] = self.recaptcha_checker
  53. def register(self, expected_response: int, body: JsonDict) -> FakeChannel:
  54. """Make a register request."""
  55. request, channel = self.make_request(
  56. "POST", "register", body
  57. ) # type: SynapseRequest, FakeChannel
  58. self.render(request)
  59. self.assertEqual(request.code, expected_response)
  60. return channel
  61. def recaptcha(
  62. self, session: str, expected_post_response: int, post_session: str = None
  63. ) -> None:
  64. """Get and respond to a fallback recaptcha. Returns the second request."""
  65. if post_session is None:
  66. post_session = session
  67. request, channel = self.make_request(
  68. "GET", "auth/m.login.recaptcha/fallback/web?session=" + session
  69. ) # type: SynapseRequest, FakeChannel
  70. self.render(request)
  71. self.assertEqual(request.code, 200)
  72. request, channel = self.make_request(
  73. "POST",
  74. "auth/m.login.recaptcha/fallback/web?session="
  75. + post_session
  76. + "&g-recaptcha-response=a",
  77. )
  78. self.render(request)
  79. self.assertEqual(request.code, expected_post_response)
  80. # The recaptcha handler is called with the response given
  81. attempts = self.recaptcha_checker.recaptcha_attempts
  82. self.assertEqual(len(attempts), 1)
  83. self.assertEqual(attempts[0][0]["response"], "a")
  84. @unittest.INFO
  85. def test_fallback_captcha(self):
  86. """Ensure that fallback auth via a captcha works."""
  87. # Returns a 401 as per the spec
  88. channel = self.register(
  89. 401, {"username": "user", "type": "m.login.password", "password": "bar"},
  90. )
  91. # Grab the session
  92. session = channel.json_body["session"]
  93. # Assert our configured public key is being given
  94. self.assertEqual(
  95. channel.json_body["params"]["m.login.recaptcha"]["public_key"], "brokencake"
  96. )
  97. # Complete the recaptcha step.
  98. self.recaptcha(session, 200)
  99. # also complete the dummy auth
  100. self.register(200, {"auth": {"session": session, "type": "m.login.dummy"}})
  101. # Now we should have fulfilled a complete auth flow, including
  102. # the recaptcha fallback step, we can then send a
  103. # request to the register API with the session in the authdict.
  104. channel = self.register(200, {"auth": {"session": session}})
  105. # We're given a registered user.
  106. self.assertEqual(channel.json_body["user_id"], "@user:test")
  107. def test_complete_operation_unknown_session(self):
  108. """
  109. Attempting to mark an invalid session as complete should error.
  110. """
  111. # Make the initial request to register. (Later on a different password
  112. # will be used.)
  113. # Returns a 401 as per the spec
  114. channel = self.register(
  115. 401, {"username": "user", "type": "m.login.password", "password": "bar"}
  116. )
  117. # Grab the session
  118. session = channel.json_body["session"]
  119. # Assert our configured public key is being given
  120. self.assertEqual(
  121. channel.json_body["params"]["m.login.recaptcha"]["public_key"], "brokencake"
  122. )
  123. # Attempt to complete the recaptcha step with an unknown session.
  124. # This results in an error.
  125. self.recaptcha(session, 400, session + "unknown")
  126. class UIAuthTests(unittest.HomeserverTestCase):
  127. servlets = [
  128. auth.register_servlets,
  129. devices.register_servlets,
  130. login.register_servlets,
  131. synapse.rest.admin.register_servlets_for_client_rest_resource,
  132. register.register_servlets,
  133. ]
  134. def prepare(self, reactor, clock, hs):
  135. auth_handler = hs.get_auth_handler()
  136. auth_handler.checkers[LoginType.PASSWORD] = DummyPasswordChecker(hs)
  137. self.user_pass = "pass"
  138. self.user = self.register_user("test", self.user_pass)
  139. self.user_tok = self.login("test", self.user_pass)
  140. def get_device_ids(self) -> List[str]:
  141. # Get the list of devices so one can be deleted.
  142. request, channel = self.make_request(
  143. "GET", "devices", access_token=self.user_tok,
  144. ) # type: SynapseRequest, FakeChannel
  145. self.render(request)
  146. # Get the ID of the device.
  147. self.assertEqual(request.code, 200)
  148. return [d["device_id"] for d in channel.json_body["devices"]]
  149. def delete_device(
  150. self, device: str, expected_response: int, body: Union[bytes, JsonDict] = b""
  151. ) -> FakeChannel:
  152. """Delete an individual device."""
  153. request, channel = self.make_request(
  154. "DELETE", "devices/" + device, body, access_token=self.user_tok
  155. ) # type: SynapseRequest, FakeChannel
  156. self.render(request)
  157. # Ensure the response is sane.
  158. self.assertEqual(request.code, expected_response)
  159. return channel
  160. def delete_devices(self, expected_response: int, body: JsonDict) -> FakeChannel:
  161. """Delete 1 or more devices."""
  162. # Note that this uses the delete_devices endpoint so that we can modify
  163. # the payload half-way through some tests.
  164. request, channel = self.make_request(
  165. "POST", "delete_devices", body, access_token=self.user_tok,
  166. ) # type: SynapseRequest, FakeChannel
  167. self.render(request)
  168. # Ensure the response is sane.
  169. self.assertEqual(request.code, expected_response)
  170. return channel
  171. def test_ui_auth(self):
  172. """
  173. Test user interactive authentication outside of registration.
  174. """
  175. device_id = self.get_device_ids()[0]
  176. # Attempt to delete this device.
  177. # Returns a 401 as per the spec
  178. channel = self.delete_device(device_id, 401)
  179. # Grab the session
  180. session = channel.json_body["session"]
  181. # Ensure that flows are what is expected.
  182. self.assertIn({"stages": ["m.login.password"]}, channel.json_body["flows"])
  183. # Make another request providing the UI auth flow.
  184. self.delete_device(
  185. device_id,
  186. 200,
  187. {
  188. "auth": {
  189. "type": "m.login.password",
  190. "identifier": {"type": "m.id.user", "user": self.user},
  191. "password": self.user_pass,
  192. "session": session,
  193. },
  194. },
  195. )
  196. def test_can_change_body(self):
  197. """
  198. The client dict can be modified during the user interactive authentication session.
  199. Note that it is not spec compliant to modify the client dict during a
  200. user interactive authentication session, but many clients currently do.
  201. When Synapse is updated to be spec compliant, the call to re-use the
  202. session ID should be rejected.
  203. """
  204. # Create a second login.
  205. self.login("test", self.user_pass)
  206. device_ids = self.get_device_ids()
  207. self.assertEqual(len(device_ids), 2)
  208. # Attempt to delete the first device.
  209. # Returns a 401 as per the spec
  210. channel = self.delete_devices(401, {"devices": [device_ids[0]]})
  211. # Grab the session
  212. session = channel.json_body["session"]
  213. # Ensure that flows are what is expected.
  214. self.assertIn({"stages": ["m.login.password"]}, channel.json_body["flows"])
  215. # Make another request providing the UI auth flow, but try to delete the
  216. # second device.
  217. self.delete_devices(
  218. 200,
  219. {
  220. "devices": [device_ids[1]],
  221. "auth": {
  222. "type": "m.login.password",
  223. "identifier": {"type": "m.id.user", "user": self.user},
  224. "password": self.user_pass,
  225. "session": session,
  226. },
  227. },
  228. )
  229. def test_cannot_change_uri(self):
  230. """
  231. The initial requested URI cannot be modified during the user interactive authentication session.
  232. """
  233. # Create a second login.
  234. self.login("test", self.user_pass)
  235. device_ids = self.get_device_ids()
  236. self.assertEqual(len(device_ids), 2)
  237. # Attempt to delete the first device.
  238. # Returns a 401 as per the spec
  239. channel = self.delete_device(device_ids[0], 401)
  240. # Grab the session
  241. session = channel.json_body["session"]
  242. # Ensure that flows are what is expected.
  243. self.assertIn({"stages": ["m.login.password"]}, channel.json_body["flows"])
  244. # Make another request providing the UI auth flow, but try to delete the
  245. # second device. This results in an error.
  246. self.delete_device(
  247. device_ids[1],
  248. 403,
  249. {
  250. "auth": {
  251. "type": "m.login.password",
  252. "identifier": {"type": "m.id.user", "user": self.user},
  253. "password": self.user_pass,
  254. "session": session,
  255. },
  256. },
  257. )