utils.py 30 KB

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