utils.py 30 KB

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