utils.py 30 KB

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