utils.py 22 KB

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