1
0

utils.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2017 Vector Creations Ltd
  3. # Copyright 2018-2019 New Vector Ltd
  4. # Copyright 2019-2021 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import json
  18. import re
  19. import time
  20. import urllib.parse
  21. from http import HTTPStatus
  22. from typing import (
  23. Any,
  24. AnyStr,
  25. Dict,
  26. Iterable,
  27. Mapping,
  28. MutableMapping,
  29. Optional,
  30. Tuple,
  31. overload,
  32. )
  33. from unittest.mock import patch
  34. from urllib.parse import urlencode
  35. import attr
  36. from typing_extensions import Literal
  37. from twisted.web.resource import Resource
  38. from twisted.web.server import Site
  39. from synapse.api.constants import Membership
  40. from synapse.server import HomeServer
  41. from synapse.types import JsonDict
  42. from tests.server import FakeChannel, FakeSite, make_request
  43. from tests.test_utils import FakeResponse
  44. from tests.test_utils.html_parsers import TestHtmlParser
  45. @attr.s(auto_attribs=True)
  46. class RestHelper:
  47. """Contains extra helper functions to quickly and clearly perform a given
  48. REST action, which isn't the focus of the test.
  49. """
  50. hs: HomeServer
  51. site: Site
  52. auth_user_id: Optional[str]
  53. @overload
  54. def create_room_as(
  55. self,
  56. room_creator: Optional[str] = ...,
  57. is_public: Optional[bool] = ...,
  58. room_version: Optional[str] = ...,
  59. tok: Optional[str] = ...,
  60. expect_code: Literal[200] = ...,
  61. extra_content: Optional[Dict] = ...,
  62. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = ...,
  63. ) -> str:
  64. ...
  65. @overload
  66. def create_room_as(
  67. self,
  68. room_creator: Optional[str] = ...,
  69. is_public: Optional[bool] = ...,
  70. room_version: Optional[str] = ...,
  71. tok: Optional[str] = ...,
  72. expect_code: int = ...,
  73. extra_content: Optional[Dict] = ...,
  74. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = ...,
  75. ) -> Optional[str]:
  76. ...
  77. def create_room_as(
  78. self,
  79. room_creator: Optional[str] = None,
  80. is_public: Optional[bool] = True,
  81. room_version: Optional[str] = None,
  82. tok: Optional[str] = None,
  83. expect_code: int = HTTPStatus.OK,
  84. extra_content: Optional[Dict] = None,
  85. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
  86. ) -> Optional[str]:
  87. """
  88. Create a room.
  89. Args:
  90. room_creator: The user ID to create the room with.
  91. is_public: If True, the `visibility` parameter will be set to
  92. "public". If False, it will be set to "private".
  93. If None, doesn't specify the `visibility` parameter in which
  94. case the server is supposed to make the room private according to
  95. the CS API.
  96. Defaults to public, since that is commonly needed in tests
  97. for convenience where room privacy is not a problem.
  98. room_version: The room version to create the room as. Defaults to Synapse's
  99. default room version.
  100. tok: The access token to use in the request.
  101. expect_code: The expected HTTP response code.
  102. extra_content: Extra keys to include in the body of the /createRoom request.
  103. Note that if is_public is set, the "visibility" key will be overridden.
  104. If room_version is set, the "room_version" key will be overridden.
  105. custom_headers: HTTP headers to include in the request.
  106. Returns:
  107. The ID of the newly created room, or None if the request failed.
  108. """
  109. temp_id = self.auth_user_id
  110. self.auth_user_id = room_creator
  111. path = "/_matrix/client/r0/createRoom"
  112. content = extra_content or {}
  113. if is_public is not None:
  114. content["visibility"] = "public" if is_public else "private"
  115. if room_version:
  116. content["room_version"] = room_version
  117. if tok:
  118. path = path + "?access_token=%s" % tok
  119. channel = make_request(
  120. self.hs.get_reactor(),
  121. self.site,
  122. "POST",
  123. path,
  124. json.dumps(content).encode("utf8"),
  125. custom_headers=custom_headers,
  126. )
  127. assert channel.result["code"] == b"%d" % expect_code, channel.result
  128. self.auth_user_id = temp_id
  129. if expect_code == HTTPStatus.OK:
  130. return channel.json_body["room_id"]
  131. else:
  132. return None
  133. def invite(
  134. self,
  135. room: str,
  136. src: Optional[str] = None,
  137. targ: Optional[str] = None,
  138. expect_code: int = HTTPStatus.OK,
  139. tok: Optional[str] = None,
  140. ) -> None:
  141. self.change_membership(
  142. room=room,
  143. src=src,
  144. targ=targ,
  145. tok=tok,
  146. membership=Membership.INVITE,
  147. expect_code=expect_code,
  148. )
  149. def join(
  150. self,
  151. room: str,
  152. user: Optional[str] = None,
  153. expect_code: int = HTTPStatus.OK,
  154. tok: Optional[str] = None,
  155. appservice_user_id: Optional[str] = None,
  156. ) -> None:
  157. self.change_membership(
  158. room=room,
  159. src=user,
  160. targ=user,
  161. tok=tok,
  162. appservice_user_id=appservice_user_id,
  163. membership=Membership.JOIN,
  164. expect_code=expect_code,
  165. )
  166. def knock(
  167. self,
  168. room: Optional[str] = None,
  169. user: Optional[str] = None,
  170. reason: Optional[str] = None,
  171. expect_code: int = HTTPStatus.OK,
  172. tok: Optional[str] = None,
  173. ) -> None:
  174. temp_id = self.auth_user_id
  175. self.auth_user_id = user
  176. path = "/knock/%s" % room
  177. if tok:
  178. path = path + "?access_token=%s" % tok
  179. data = {}
  180. if reason:
  181. data["reason"] = reason
  182. channel = make_request(
  183. self.hs.get_reactor(),
  184. self.site,
  185. "POST",
  186. path,
  187. json.dumps(data).encode("utf8"),
  188. )
  189. assert (
  190. int(channel.result["code"]) == expect_code
  191. ), "Expected: %d, got: %d, resp: %r" % (
  192. expect_code,
  193. int(channel.result["code"]),
  194. channel.result["body"],
  195. )
  196. self.auth_user_id = temp_id
  197. def leave(
  198. self,
  199. room: str,
  200. user: Optional[str] = None,
  201. expect_code: int = HTTPStatus.OK,
  202. tok: Optional[str] = None,
  203. ) -> None:
  204. self.change_membership(
  205. room=room,
  206. src=user,
  207. targ=user,
  208. tok=tok,
  209. membership=Membership.LEAVE,
  210. expect_code=expect_code,
  211. )
  212. def ban(
  213. self,
  214. room: str,
  215. src: str,
  216. targ: str,
  217. expect_code: int = HTTPStatus.OK,
  218. tok: Optional[str] = None,
  219. ) -> None:
  220. """A convenience helper: `change_membership` with `membership` preset to "ban"."""
  221. self.change_membership(
  222. room=room,
  223. src=src,
  224. targ=targ,
  225. tok=tok,
  226. membership=Membership.BAN,
  227. expect_code=expect_code,
  228. )
  229. def change_membership(
  230. self,
  231. room: str,
  232. src: Optional[str],
  233. targ: Optional[str],
  234. membership: str,
  235. extra_data: Optional[dict] = None,
  236. tok: Optional[str] = None,
  237. appservice_user_id: Optional[str] = None,
  238. expect_code: int = HTTPStatus.OK,
  239. expect_errcode: Optional[str] = None,
  240. ) -> None:
  241. """
  242. Send a membership state event into a room.
  243. Args:
  244. room: The ID of the room to send to
  245. src: The mxid of the event sender
  246. targ: The mxid of the event's target. The state key
  247. membership: The type of membership event
  248. extra_data: Extra information to include in the content of the event
  249. tok: The user access token to use
  250. appservice_user_id: The `user_id` URL parameter to pass.
  251. This allows driving an application service user
  252. using an application service access token in `tok`.
  253. expect_code: The expected HTTP response code
  254. expect_errcode: The expected Matrix error code
  255. """
  256. temp_id = self.auth_user_id
  257. self.auth_user_id = src
  258. path = f"/_matrix/client/r0/rooms/{room}/state/m.room.member/{targ}"
  259. url_params: Dict[str, str] = {}
  260. if tok:
  261. url_params["access_token"] = tok
  262. if appservice_user_id:
  263. url_params["user_id"] = appservice_user_id
  264. if url_params:
  265. path += "?" + urlencode(url_params)
  266. data = {"membership": membership}
  267. data.update(extra_data or {})
  268. channel = make_request(
  269. self.hs.get_reactor(),
  270. self.site,
  271. "PUT",
  272. path,
  273. json.dumps(data).encode("utf8"),
  274. )
  275. assert (
  276. int(channel.result["code"]) == expect_code
  277. ), "Expected: %d, got: %d, resp: %r" % (
  278. expect_code,
  279. int(channel.result["code"]),
  280. channel.result["body"],
  281. )
  282. if expect_errcode:
  283. assert (
  284. str(channel.json_body["errcode"]) == expect_errcode
  285. ), "Expected: %r, got: %r, resp: %r" % (
  286. expect_errcode,
  287. channel.json_body["errcode"],
  288. channel.result["body"],
  289. )
  290. self.auth_user_id = temp_id
  291. def send(
  292. self,
  293. room_id: str,
  294. body: Optional[str] = None,
  295. txn_id: Optional[str] = None,
  296. tok: Optional[str] = None,
  297. expect_code: int = HTTPStatus.OK,
  298. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
  299. ) -> JsonDict:
  300. if body is None:
  301. body = "body_text_here"
  302. content = {"msgtype": "m.text", "body": body}
  303. return self.send_event(
  304. room_id,
  305. "m.room.message",
  306. content,
  307. txn_id,
  308. tok,
  309. expect_code,
  310. custom_headers=custom_headers,
  311. )
  312. def send_event(
  313. self,
  314. room_id: str,
  315. type: str,
  316. content: Optional[dict] = None,
  317. txn_id: Optional[str] = None,
  318. tok: Optional[str] = None,
  319. expect_code: int = HTTPStatus.OK,
  320. custom_headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
  321. ) -> JsonDict:
  322. if txn_id is None:
  323. txn_id = "m%s" % (str(time.time()))
  324. path = "/_matrix/client/r0/rooms/%s/send/%s/%s" % (room_id, type, txn_id)
  325. if tok:
  326. path = path + "?access_token=%s" % tok
  327. channel = make_request(
  328. self.hs.get_reactor(),
  329. self.site,
  330. "PUT",
  331. path,
  332. json.dumps(content or {}).encode("utf8"),
  333. custom_headers=custom_headers,
  334. )
  335. assert (
  336. int(channel.result["code"]) == expect_code
  337. ), "Expected: %d, got: %d, resp: %r" % (
  338. expect_code,
  339. int(channel.result["code"]),
  340. channel.result["body"],
  341. )
  342. return channel.json_body
  343. def _read_write_state(
  344. self,
  345. room_id: str,
  346. event_type: str,
  347. body: Optional[Dict[str, Any]],
  348. tok: Optional[str],
  349. expect_code: int = HTTPStatus.OK,
  350. state_key: str = "",
  351. method: str = "GET",
  352. ) -> JsonDict:
  353. """Read or write some state from a given room
  354. Args:
  355. room_id:
  356. event_type: The type of state event
  357. body: Body that is sent when making the request. The content of the state event.
  358. If None, the request to the server will have an empty body
  359. tok: The access token to use
  360. expect_code: The HTTP code to expect in the response
  361. state_key:
  362. method: "GET" or "PUT" for reading or writing state, respectively
  363. Returns:
  364. The response body from the server
  365. Raises:
  366. AssertionError: if expect_code doesn't match the HTTP code we received
  367. """
  368. path = "/_matrix/client/r0/rooms/%s/state/%s/%s" % (
  369. room_id,
  370. event_type,
  371. state_key,
  372. )
  373. if tok:
  374. path = path + "?access_token=%s" % tok
  375. # Set request body if provided
  376. content = b""
  377. if body is not None:
  378. content = json.dumps(body).encode("utf8")
  379. channel = make_request(self.hs.get_reactor(), self.site, method, path, content)
  380. assert (
  381. int(channel.result["code"]) == expect_code
  382. ), "Expected: %d, got: %d, resp: %r" % (
  383. expect_code,
  384. int(channel.result["code"]),
  385. channel.result["body"],
  386. )
  387. return channel.json_body
  388. def get_state(
  389. self,
  390. room_id: str,
  391. event_type: str,
  392. tok: str,
  393. expect_code: int = HTTPStatus.OK,
  394. state_key: str = "",
  395. ) -> JsonDict:
  396. """Gets some state from a room
  397. Args:
  398. room_id:
  399. event_type: The type of state event
  400. tok: The access token to use
  401. expect_code: The HTTP code to expect in the response
  402. state_key:
  403. Returns:
  404. The response body from the server
  405. Raises:
  406. AssertionError: if expect_code doesn't match the HTTP code we received
  407. """
  408. return self._read_write_state(
  409. room_id, event_type, None, tok, expect_code, state_key, method="GET"
  410. )
  411. def send_state(
  412. self,
  413. room_id: str,
  414. event_type: str,
  415. body: Dict[str, Any],
  416. tok: Optional[str],
  417. expect_code: int = HTTPStatus.OK,
  418. state_key: str = "",
  419. ) -> JsonDict:
  420. """Set some state in a room
  421. Args:
  422. room_id:
  423. event_type: The type of state event
  424. body: Body that is sent when making the request. The content of the state event.
  425. tok: The access token to use
  426. expect_code: The HTTP code to expect in the response
  427. state_key:
  428. Returns:
  429. The response body from the server
  430. Raises:
  431. AssertionError: if expect_code doesn't match the HTTP code we received
  432. """
  433. return self._read_write_state(
  434. room_id, event_type, body, tok, expect_code, state_key, method="PUT"
  435. )
  436. def upload_media(
  437. self,
  438. resource: Resource,
  439. image_data: bytes,
  440. tok: str,
  441. filename: str = "test.png",
  442. expect_code: int = HTTPStatus.OK,
  443. ) -> JsonDict:
  444. """Upload a piece of test media to the media repo
  445. Args:
  446. resource: The resource that will handle the upload request
  447. image_data: The image data to upload
  448. tok: The user token to use during the upload
  449. filename: The filename of the media to be uploaded
  450. expect_code: The return code to expect from attempting to upload the media
  451. """
  452. image_length = len(image_data)
  453. path = "/_matrix/media/r0/upload?filename=%s" % (filename,)
  454. channel = make_request(
  455. self.hs.get_reactor(),
  456. FakeSite(resource, self.hs.get_reactor()),
  457. "POST",
  458. path,
  459. content=image_data,
  460. access_token=tok,
  461. custom_headers=[("Content-Length", str(image_length))],
  462. )
  463. assert channel.code == expect_code, "Expected: %d, got: %d, resp: %r" % (
  464. expect_code,
  465. int(channel.result["code"]),
  466. channel.result["body"],
  467. )
  468. return channel.json_body
  469. def login_via_oidc(self, remote_user_id: str) -> JsonDict:
  470. """Log in (as a new user) via OIDC
  471. Returns the result of the final token login.
  472. Requires that "oidc_config" in the homeserver config be set appropriately
  473. (TEST_OIDC_CONFIG is a suitable example) - and by implication, needs a
  474. "public_base_url".
  475. Also requires the login servlet and the OIDC callback resource to be mounted at
  476. the normal places.
  477. """
  478. client_redirect_url = "https://x"
  479. channel = self.auth_via_oidc({"sub": remote_user_id}, client_redirect_url)
  480. # expect a confirmation page
  481. assert channel.code == HTTPStatus.OK, channel.result
  482. # fish the matrix login token out of the body of the confirmation page
  483. m = re.search(
  484. 'a href="%s.*loginToken=([^"]*)"' % (client_redirect_url,),
  485. channel.text_body,
  486. )
  487. assert m, channel.text_body
  488. login_token = m.group(1)
  489. # finally, submit the matrix login token to the login API, which gives us our
  490. # matrix access token and device id.
  491. channel = make_request(
  492. self.hs.get_reactor(),
  493. self.site,
  494. "POST",
  495. "/login",
  496. content={"type": "m.login.token", "token": login_token},
  497. )
  498. assert channel.code == HTTPStatus.OK
  499. return channel.json_body
  500. def auth_via_oidc(
  501. self,
  502. user_info_dict: JsonDict,
  503. client_redirect_url: Optional[str] = None,
  504. ui_auth_session_id: Optional[str] = None,
  505. ) -> FakeChannel:
  506. """Perform an OIDC authentication flow via a mock OIDC provider.
  507. This can be used for either login or user-interactive auth.
  508. Starts by making a request to the relevant synapse redirect endpoint, which is
  509. expected to serve a 302 to the OIDC provider. We then make a request to the
  510. OIDC callback endpoint, intercepting the HTTP requests that will get sent back
  511. to the OIDC provider.
  512. Requires that "oidc_config" in the homeserver config be set appropriately
  513. (TEST_OIDC_CONFIG is a suitable example) - and by implication, needs a
  514. "public_base_url".
  515. Also requires the login servlet and the OIDC callback resource to be mounted at
  516. the normal places.
  517. Args:
  518. user_info_dict: the remote userinfo that the OIDC provider should present.
  519. Typically this should be '{"sub": "<remote user id>"}'.
  520. client_redirect_url: for a login flow, the client redirect URL to pass to
  521. the login redirect endpoint
  522. ui_auth_session_id: if set, we will perform a UI Auth flow. The session id
  523. of the UI auth.
  524. Returns:
  525. A FakeChannel containing the result of calling the OIDC callback endpoint.
  526. Note that the response code may be a 200, 302 or 400 depending on how things
  527. went.
  528. """
  529. cookies: Dict[str, str] = {}
  530. # if we're doing a ui auth, hit the ui auth redirect endpoint
  531. if ui_auth_session_id:
  532. # can't set the client redirect url for UI Auth
  533. assert client_redirect_url is None
  534. oauth_uri = self.initiate_sso_ui_auth(ui_auth_session_id, cookies)
  535. else:
  536. # otherwise, hit the login redirect endpoint
  537. oauth_uri = self.initiate_sso_login(client_redirect_url, cookies)
  538. # we now have a URI for the OIDC IdP, but we skip that and go straight
  539. # back to synapse's OIDC callback resource. However, we do need the "state"
  540. # param that synapse passes to the IdP via query params, as well as the cookie
  541. # that synapse passes to the client.
  542. oauth_uri_path, _ = oauth_uri.split("?", 1)
  543. assert oauth_uri_path == TEST_OIDC_AUTH_ENDPOINT, (
  544. "unexpected SSO URI " + oauth_uri_path
  545. )
  546. return self.complete_oidc_auth(oauth_uri, cookies, user_info_dict)
  547. def complete_oidc_auth(
  548. self,
  549. oauth_uri: str,
  550. cookies: Mapping[str, str],
  551. user_info_dict: JsonDict,
  552. ) -> FakeChannel:
  553. """Mock out an OIDC authentication flow
  554. Assumes that an OIDC auth has been initiated by one of initiate_sso_login or
  555. initiate_sso_ui_auth; completes the OIDC bits of the flow by making a request to
  556. Synapse's OIDC callback endpoint, intercepting the HTTP requests that will get
  557. sent back to the OIDC provider.
  558. Requires the OIDC callback resource to be mounted at the normal place.
  559. Args:
  560. oauth_uri: the OIDC URI returned by synapse's redirect endpoint (ie,
  561. from initiate_sso_login or initiate_sso_ui_auth).
  562. cookies: the cookies set by synapse's redirect endpoint, which will be
  563. sent back to the callback endpoint.
  564. user_info_dict: the remote userinfo that the OIDC provider should present.
  565. Typically this should be '{"sub": "<remote user id>"}'.
  566. Returns:
  567. A FakeChannel containing the result of calling the OIDC callback endpoint.
  568. """
  569. _, oauth_uri_qs = oauth_uri.split("?", 1)
  570. params = urllib.parse.parse_qs(oauth_uri_qs)
  571. callback_uri = "%s?%s" % (
  572. urllib.parse.urlparse(params["redirect_uri"][0]).path,
  573. urllib.parse.urlencode({"state": params["state"][0], "code": "TEST_CODE"}),
  574. )
  575. # before we hit the callback uri, stub out some methods in the http client so
  576. # that we don't have to handle full HTTPS requests.
  577. # (expected url, json response) pairs, in the order we expect them.
  578. expected_requests = [
  579. # first we get a hit to the token endpoint, which we tell to return
  580. # a dummy OIDC access token
  581. (TEST_OIDC_TOKEN_ENDPOINT, {"access_token": "TEST"}),
  582. # and then one to the user_info endpoint, which returns our remote user id.
  583. (TEST_OIDC_USERINFO_ENDPOINT, user_info_dict),
  584. ]
  585. async def mock_req(
  586. method: str,
  587. uri: str,
  588. data: Optional[dict] = None,
  589. headers: Optional[Iterable[Tuple[AnyStr, AnyStr]]] = None,
  590. ):
  591. (expected_uri, resp_obj) = expected_requests.pop(0)
  592. assert uri == expected_uri
  593. resp = FakeResponse(
  594. code=HTTPStatus.OK,
  595. phrase=b"OK",
  596. body=json.dumps(resp_obj).encode("utf-8"),
  597. )
  598. return resp
  599. with patch.object(self.hs.get_proxied_http_client(), "request", mock_req):
  600. # now hit the callback URI with the right params and a made-up code
  601. channel = make_request(
  602. self.hs.get_reactor(),
  603. self.site,
  604. "GET",
  605. callback_uri,
  606. custom_headers=[
  607. ("Cookie", "%s=%s" % (k, v)) for (k, v) in cookies.items()
  608. ],
  609. )
  610. return channel
  611. def initiate_sso_login(
  612. self, client_redirect_url: Optional[str], cookies: MutableMapping[str, str]
  613. ) -> str:
  614. """Make a request to the login-via-sso redirect endpoint, and return the target
  615. Assumes that exactly one SSO provider has been configured. Requires the login
  616. servlet to be mounted.
  617. Args:
  618. client_redirect_url: the client redirect URL to pass to the login redirect
  619. endpoint
  620. cookies: any cookies returned will be added to this dict
  621. Returns:
  622. the URI that the client gets redirected to (ie, the SSO server)
  623. """
  624. params = {}
  625. if client_redirect_url:
  626. params["redirectUrl"] = client_redirect_url
  627. # hit the redirect url (which should redirect back to the redirect url. This
  628. # is the easiest way of figuring out what the Host header ought to be set to
  629. # to keep Synapse happy.
  630. channel = make_request(
  631. self.hs.get_reactor(),
  632. self.site,
  633. "GET",
  634. "/_matrix/client/r0/login/sso/redirect?" + urllib.parse.urlencode(params),
  635. )
  636. assert channel.code == 302
  637. # hit the redirect url again with the right Host header, which should now issue
  638. # a cookie and redirect to the SSO provider.
  639. def get_location(channel: FakeChannel) -> str:
  640. location_values = channel.headers.getRawHeaders("Location")
  641. # Keep mypy happy by asserting that location_values is nonempty
  642. assert location_values
  643. return location_values[0]
  644. location = get_location(channel)
  645. parts = urllib.parse.urlsplit(location)
  646. channel = make_request(
  647. self.hs.get_reactor(),
  648. self.site,
  649. "GET",
  650. urllib.parse.urlunsplit(("", "") + parts[2:]),
  651. custom_headers=[
  652. ("Host", parts[1]),
  653. ],
  654. )
  655. assert channel.code == 302
  656. channel.extract_cookies(cookies)
  657. return get_location(channel)
  658. def initiate_sso_ui_auth(
  659. self, ui_auth_session_id: str, cookies: MutableMapping[str, str]
  660. ) -> str:
  661. """Make a request to the ui-auth-via-sso endpoint, and return the target
  662. Assumes that exactly one SSO provider has been configured. Requires the
  663. AuthRestServlet to be mounted.
  664. Args:
  665. ui_auth_session_id: the session id of the UI auth
  666. cookies: any cookies returned will be added to this dict
  667. Returns:
  668. the URI that the client gets linked to (ie, the SSO server)
  669. """
  670. sso_redirect_endpoint = (
  671. "/_matrix/client/r0/auth/m.login.sso/fallback/web?"
  672. + urllib.parse.urlencode({"session": ui_auth_session_id})
  673. )
  674. # hit the redirect url (which will issue a cookie and state)
  675. channel = make_request(
  676. self.hs.get_reactor(), self.site, "GET", sso_redirect_endpoint
  677. )
  678. # that should serve a confirmation page
  679. assert channel.code == HTTPStatus.OK, channel.text_body
  680. channel.extract_cookies(cookies)
  681. # parse the confirmation page to fish out the link.
  682. p = TestHtmlParser()
  683. p.feed(channel.text_body)
  684. p.close()
  685. assert len(p.links) == 1, "not exactly one link in confirmation page"
  686. oauth_uri = p.links[0]
  687. return oauth_uri
  688. # an 'oidc_config' suitable for login_via_oidc.
  689. TEST_OIDC_AUTH_ENDPOINT = "https://issuer.test/auth"
  690. TEST_OIDC_TOKEN_ENDPOINT = "https://issuer.test/token"
  691. TEST_OIDC_USERINFO_ENDPOINT = "https://issuer.test/userinfo"
  692. TEST_OIDC_CONFIG = {
  693. "enabled": True,
  694. "discover": False,
  695. "issuer": "https://issuer.test",
  696. "client_id": "test-client-id",
  697. "client_secret": "test-client-secret",
  698. "scopes": ["profile"],
  699. "authorization_endpoint": TEST_OIDC_AUTH_ENDPOINT,
  700. "token_endpoint": TEST_OIDC_TOKEN_ENDPOINT,
  701. "userinfo_endpoint": TEST_OIDC_USERINFO_ENDPOINT,
  702. "user_mapping_provider": {"config": {"localpart_template": "{{ user.sub }}"}},
  703. }