utils.py 24 KB

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