1
0

utils.py 28 KB

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