test_account.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import re
  16. from email.parser import Parser
  17. from http import HTTPStatus
  18. from typing import Any, Dict, List, Optional, Union
  19. from unittest.mock import Mock
  20. import pkg_resources
  21. from twisted.internet.interfaces import IReactorTCP
  22. from twisted.test.proto_helpers import MemoryReactor
  23. import synapse.rest.admin
  24. from synapse.api.constants import LoginType, Membership
  25. from synapse.api.errors import Codes, HttpResponseException
  26. from synapse.appservice import ApplicationService
  27. from synapse.rest import admin
  28. from synapse.rest.client import account, login, register, room
  29. from synapse.rest.synapse.client.password_reset import PasswordResetSubmitTokenResource
  30. from synapse.server import HomeServer
  31. from synapse.types import JsonDict, UserID
  32. from synapse.util import Clock
  33. from tests import unittest
  34. from tests.server import FakeSite, make_request
  35. from tests.unittest import override_config
  36. class PasswordResetTestCase(unittest.HomeserverTestCase):
  37. servlets = [
  38. account.register_servlets,
  39. synapse.rest.admin.register_servlets_for_client_rest_resource,
  40. register.register_servlets,
  41. login.register_servlets,
  42. ]
  43. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  44. config = self.default_config()
  45. # Email config.
  46. config["email"] = {
  47. "enable_notifs": False,
  48. "template_dir": os.path.abspath(
  49. pkg_resources.resource_filename("synapse", "res/templates")
  50. ),
  51. "smtp_host": "127.0.0.1",
  52. "smtp_port": 20,
  53. "require_transport_security": False,
  54. "smtp_user": None,
  55. "smtp_pass": None,
  56. "notif_from": "test@example.com",
  57. }
  58. config["public_baseurl"] = "https://example.com"
  59. hs = self.setup_test_homeserver(config=config)
  60. async def sendmail(
  61. reactor: IReactorTCP,
  62. smtphost: str,
  63. smtpport: int,
  64. from_addr: str,
  65. to_addr: str,
  66. msg_bytes: bytes,
  67. *args: Any,
  68. **kwargs: Any,
  69. ) -> None:
  70. self.email_attempts.append(msg_bytes)
  71. self.email_attempts: List[bytes] = []
  72. hs.get_send_email_handler()._sendmail = sendmail
  73. return hs
  74. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  75. self.store = hs.get_datastores().main
  76. self.submit_token_resource = PasswordResetSubmitTokenResource(hs)
  77. def attempt_wrong_password_login(self, username: str, password: str) -> None:
  78. """Attempts to login as the user with the given password, asserting
  79. that the attempt *fails*.
  80. """
  81. body = {"type": "m.login.password", "user": username, "password": password}
  82. channel = self.make_request("POST", "/_matrix/client/r0/login", body)
  83. self.assertEqual(channel.code, HTTPStatus.FORBIDDEN, channel.result)
  84. def test_basic_password_reset(self) -> None:
  85. """Test basic password reset flow"""
  86. old_password = "monkey"
  87. new_password = "kangeroo"
  88. user_id = self.register_user("kermit", old_password)
  89. self.login("kermit", old_password)
  90. email = "test@example.com"
  91. # Add a threepid
  92. self.get_success(
  93. self.store.user_add_threepid(
  94. user_id=user_id,
  95. medium="email",
  96. address=email,
  97. validated_at=0,
  98. added_at=0,
  99. )
  100. )
  101. client_secret = "foobar"
  102. session_id = self._request_token(email, client_secret)
  103. self.assertEqual(len(self.email_attempts), 1)
  104. link = self._get_link_from_email()
  105. self._validate_token(link)
  106. self._reset_password(new_password, session_id, client_secret)
  107. # Assert we can log in with the new password
  108. self.login("kermit", new_password)
  109. # Assert we can't log in with the old password
  110. self.attempt_wrong_password_login("kermit", old_password)
  111. @override_config({"rc_3pid_validation": {"burst_count": 3}})
  112. def test_ratelimit_by_email(self) -> None:
  113. """Test that we ratelimit /requestToken for the same email."""
  114. old_password = "monkey"
  115. new_password = "kangeroo"
  116. user_id = self.register_user("kermit", old_password)
  117. self.login("kermit", old_password)
  118. email = "test1@example.com"
  119. # Add a threepid
  120. self.get_success(
  121. self.store.user_add_threepid(
  122. user_id=user_id,
  123. medium="email",
  124. address=email,
  125. validated_at=0,
  126. added_at=0,
  127. )
  128. )
  129. def reset(ip: str) -> None:
  130. client_secret = "foobar"
  131. session_id = self._request_token(email, client_secret, ip)
  132. self.assertEqual(len(self.email_attempts), 1)
  133. link = self._get_link_from_email()
  134. self._validate_token(link)
  135. self._reset_password(new_password, session_id, client_secret)
  136. self.email_attempts.clear()
  137. # We expect to be able to make three requests before getting rate
  138. # limited.
  139. #
  140. # We change IPs to ensure that we're not being ratelimited due to the
  141. # same IP
  142. reset("127.0.0.1")
  143. reset("127.0.0.2")
  144. reset("127.0.0.3")
  145. with self.assertRaises(HttpResponseException) as cm:
  146. reset("127.0.0.4")
  147. self.assertEqual(cm.exception.code, 429)
  148. def test_basic_password_reset_canonicalise_email(self) -> None:
  149. """Test basic password reset flow
  150. Request password reset with different spelling
  151. """
  152. old_password = "monkey"
  153. new_password = "kangeroo"
  154. user_id = self.register_user("kermit", old_password)
  155. self.login("kermit", old_password)
  156. email_profile = "test@example.com"
  157. email_passwort_reset = "TEST@EXAMPLE.COM"
  158. # Add a threepid
  159. self.get_success(
  160. self.store.user_add_threepid(
  161. user_id=user_id,
  162. medium="email",
  163. address=email_profile,
  164. validated_at=0,
  165. added_at=0,
  166. )
  167. )
  168. client_secret = "foobar"
  169. session_id = self._request_token(email_passwort_reset, client_secret)
  170. self.assertEqual(len(self.email_attempts), 1)
  171. link = self._get_link_from_email()
  172. self._validate_token(link)
  173. self._reset_password(new_password, session_id, client_secret)
  174. # Assert we can log in with the new password
  175. self.login("kermit", new_password)
  176. # Assert we can't log in with the old password
  177. self.attempt_wrong_password_login("kermit", old_password)
  178. def test_cant_reset_password_without_clicking_link(self) -> None:
  179. """Test that we do actually need to click the link in the email"""
  180. old_password = "monkey"
  181. new_password = "kangeroo"
  182. user_id = self.register_user("kermit", old_password)
  183. self.login("kermit", old_password)
  184. email = "test@example.com"
  185. # Add a threepid
  186. self.get_success(
  187. self.store.user_add_threepid(
  188. user_id=user_id,
  189. medium="email",
  190. address=email,
  191. validated_at=0,
  192. added_at=0,
  193. )
  194. )
  195. client_secret = "foobar"
  196. session_id = self._request_token(email, client_secret)
  197. self.assertEqual(len(self.email_attempts), 1)
  198. # Attempt to reset password without clicking the link
  199. self._reset_password(new_password, session_id, client_secret, expected_code=401)
  200. # Assert we can log in with the old password
  201. self.login("kermit", old_password)
  202. # Assert we can't log in with the new password
  203. self.attempt_wrong_password_login("kermit", new_password)
  204. def test_no_valid_token(self) -> None:
  205. """Test that we do actually need to request a token and can't just
  206. make a session up.
  207. """
  208. old_password = "monkey"
  209. new_password = "kangeroo"
  210. user_id = self.register_user("kermit", old_password)
  211. self.login("kermit", old_password)
  212. email = "test@example.com"
  213. # Add a threepid
  214. self.get_success(
  215. self.store.user_add_threepid(
  216. user_id=user_id,
  217. medium="email",
  218. address=email,
  219. validated_at=0,
  220. added_at=0,
  221. )
  222. )
  223. client_secret = "foobar"
  224. session_id = "weasle"
  225. # Attempt to reset password without even requesting an email
  226. self._reset_password(new_password, session_id, client_secret, expected_code=401)
  227. # Assert we can log in with the old password
  228. self.login("kermit", old_password)
  229. # Assert we can't log in with the new password
  230. self.attempt_wrong_password_login("kermit", new_password)
  231. @unittest.override_config({"request_token_inhibit_3pid_errors": True})
  232. def test_password_reset_bad_email_inhibit_error(self) -> None:
  233. """Test that triggering a password reset with an email address that isn't bound
  234. to an account doesn't leak the lack of binding for that address if configured
  235. that way.
  236. """
  237. self.register_user("kermit", "monkey")
  238. self.login("kermit", "monkey")
  239. email = "test@example.com"
  240. client_secret = "foobar"
  241. session_id = self._request_token(email, client_secret)
  242. self.assertIsNotNone(session_id)
  243. def _request_token(
  244. self,
  245. email: str,
  246. client_secret: str,
  247. ip: str = "127.0.0.1",
  248. ) -> str:
  249. channel = self.make_request(
  250. "POST",
  251. b"account/password/email/requestToken",
  252. {"client_secret": client_secret, "email": email, "send_attempt": 1},
  253. client_ip=ip,
  254. )
  255. if channel.code != 200:
  256. raise HttpResponseException(
  257. channel.code,
  258. channel.result["reason"],
  259. channel.result["body"],
  260. )
  261. return channel.json_body["sid"]
  262. def _validate_token(self, link: str) -> None:
  263. # Remove the host
  264. path = link.replace("https://example.com", "")
  265. # Load the password reset confirmation page
  266. channel = make_request(
  267. self.reactor,
  268. FakeSite(self.submit_token_resource, self.reactor),
  269. "GET",
  270. path,
  271. shorthand=False,
  272. )
  273. self.assertEqual(HTTPStatus.OK, channel.code, channel.result)
  274. # Now POST to the same endpoint, mimicking the same behaviour as clicking the
  275. # password reset confirm button
  276. # Confirm the password reset
  277. channel = make_request(
  278. self.reactor,
  279. FakeSite(self.submit_token_resource, self.reactor),
  280. "POST",
  281. path,
  282. content=b"",
  283. shorthand=False,
  284. content_is_form=True,
  285. )
  286. self.assertEqual(HTTPStatus.OK, channel.code, channel.result)
  287. def _get_link_from_email(self) -> str:
  288. assert self.email_attempts, "No emails have been sent"
  289. raw_msg = self.email_attempts[-1].decode("UTF-8")
  290. mail = Parser().parsestr(raw_msg)
  291. text = None
  292. for part in mail.walk():
  293. if part.get_content_type() == "text/plain":
  294. text = part.get_payload(decode=True).decode("UTF-8")
  295. break
  296. if not text:
  297. self.fail("Could not find text portion of email to parse")
  298. assert text is not None
  299. match = re.search(r"https://example.com\S+", text)
  300. assert match, "Could not find link in email"
  301. return match.group(0)
  302. def _reset_password(
  303. self,
  304. new_password: str,
  305. session_id: str,
  306. client_secret: str,
  307. expected_code: int = HTTPStatus.OK,
  308. ) -> None:
  309. channel = self.make_request(
  310. "POST",
  311. b"account/password",
  312. {
  313. "new_password": new_password,
  314. "auth": {
  315. "type": LoginType.EMAIL_IDENTITY,
  316. "threepid_creds": {
  317. "client_secret": client_secret,
  318. "sid": session_id,
  319. },
  320. },
  321. },
  322. )
  323. self.assertEqual(expected_code, channel.code, channel.result)
  324. class DeactivateTestCase(unittest.HomeserverTestCase):
  325. servlets = [
  326. synapse.rest.admin.register_servlets_for_client_rest_resource,
  327. login.register_servlets,
  328. account.register_servlets,
  329. room.register_servlets,
  330. ]
  331. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  332. self.hs = self.setup_test_homeserver()
  333. return self.hs
  334. def test_deactivate_account(self) -> None:
  335. user_id = self.register_user("kermit", "test")
  336. tok = self.login("kermit", "test")
  337. self.deactivate(user_id, tok)
  338. store = self.hs.get_datastores().main
  339. # Check that the user has been marked as deactivated.
  340. self.assertTrue(self.get_success(store.get_user_deactivated_status(user_id)))
  341. # Check that this access token has been invalidated.
  342. channel = self.make_request("GET", "account/whoami", access_token=tok)
  343. self.assertEqual(channel.code, 401)
  344. def test_pending_invites(self) -> None:
  345. """Tests that deactivating a user rejects every pending invite for them."""
  346. store = self.hs.get_datastores().main
  347. inviter_id = self.register_user("inviter", "test")
  348. inviter_tok = self.login("inviter", "test")
  349. invitee_id = self.register_user("invitee", "test")
  350. invitee_tok = self.login("invitee", "test")
  351. # Make @inviter:test invite @invitee:test in a new room.
  352. room_id = self.helper.create_room_as(inviter_id, tok=inviter_tok)
  353. self.helper.invite(
  354. room=room_id, src=inviter_id, targ=invitee_id, tok=inviter_tok
  355. )
  356. # Make sure the invite is here.
  357. pending_invites = self.get_success(
  358. store.get_invited_rooms_for_local_user(invitee_id)
  359. )
  360. self.assertEqual(len(pending_invites), 1, pending_invites)
  361. self.assertEqual(pending_invites[0].room_id, room_id, pending_invites)
  362. # Deactivate @invitee:test.
  363. self.deactivate(invitee_id, invitee_tok)
  364. # Check that the invite isn't there anymore.
  365. pending_invites = self.get_success(
  366. store.get_invited_rooms_for_local_user(invitee_id)
  367. )
  368. self.assertEqual(len(pending_invites), 0, pending_invites)
  369. # Check that the membership of @invitee:test in the room is now "leave".
  370. memberships = self.get_success(
  371. store.get_rooms_for_local_user_where_membership_is(
  372. invitee_id, [Membership.LEAVE]
  373. )
  374. )
  375. self.assertEqual(len(memberships), 1, memberships)
  376. self.assertEqual(memberships[0].room_id, room_id, memberships)
  377. def test_deactivate_account_deletes_server_side_backup_keys(self) -> None:
  378. key_handler = self.hs.get_e2e_room_keys_handler()
  379. room_keys = {
  380. "rooms": {
  381. "!abc:matrix.org": {
  382. "sessions": {
  383. "c0ff33": {
  384. "first_message_index": 1,
  385. "forwarded_count": 1,
  386. "is_verified": False,
  387. "session_data": "SSBBTSBBIEZJU0gK",
  388. }
  389. }
  390. }
  391. }
  392. }
  393. user_id = self.register_user("missPiggy", "test")
  394. tok = self.login("missPiggy", "test")
  395. # add some backup keys/versions
  396. version = self.get_success(
  397. key_handler.create_version(
  398. user_id,
  399. {
  400. "algorithm": "m.megolm_backup.v1",
  401. "auth_data": "first_version_auth_data",
  402. },
  403. )
  404. )
  405. self.get_success(key_handler.upload_room_keys(user_id, version, room_keys))
  406. version2 = self.get_success(
  407. key_handler.create_version(
  408. user_id,
  409. {
  410. "algorithm": "m.megolm_backup.v1",
  411. "auth_data": "second_version_auth_data",
  412. },
  413. )
  414. )
  415. self.get_success(key_handler.upload_room_keys(user_id, version2, room_keys))
  416. self.deactivate(user_id, tok)
  417. store = self.hs.get_datastores().main
  418. # Check that the user has been marked as deactivated.
  419. self.assertTrue(self.get_success(store.get_user_deactivated_status(user_id)))
  420. # Check that there are no entries in 'e2e_room_keys` and `e2e_room_keys_versions`
  421. res = self.get_success(
  422. self.hs.get_datastores().main.db_pool.simple_select_list(
  423. "e2e_room_keys", {"user_id": user_id}, "*", "simple_select"
  424. )
  425. )
  426. self.assertEqual(len(res), 0)
  427. res2 = self.get_success(
  428. self.hs.get_datastores().main.db_pool.simple_select_list(
  429. "e2e_room_keys_versions", {"user_id": user_id}, "*", "simple_select"
  430. )
  431. )
  432. self.assertEqual(len(res2), 0)
  433. def test_background_update_deletes_deactivated_users_server_side_backup_keys(
  434. self,
  435. ) -> None:
  436. key_handler = self.hs.get_e2e_room_keys_handler()
  437. room_keys = {
  438. "rooms": {
  439. "!abc:matrix.org": {
  440. "sessions": {
  441. "c0ff33": {
  442. "first_message_index": 1,
  443. "forwarded_count": 1,
  444. "is_verified": False,
  445. "session_data": "SSBBTSBBIEZJU0gK",
  446. }
  447. }
  448. }
  449. }
  450. }
  451. self.store = self.hs.get_datastores().main
  452. # create a bunch of users and add keys for them
  453. users = []
  454. for i in range(0, 20):
  455. user_id = self.register_user("missPiggy" + str(i), "test")
  456. users.append((user_id,))
  457. # add some backup keys/versions
  458. version = self.get_success(
  459. key_handler.create_version(
  460. user_id,
  461. {
  462. "algorithm": "m.megolm_backup.v1",
  463. "auth_data": str(i) + "_version_auth_data",
  464. },
  465. )
  466. )
  467. self.get_success(key_handler.upload_room_keys(user_id, version, room_keys))
  468. version2 = self.get_success(
  469. key_handler.create_version(
  470. user_id,
  471. {
  472. "algorithm": "m.megolm_backup.v1",
  473. "auth_data": str(i) + "_version_auth_data",
  474. },
  475. )
  476. )
  477. self.get_success(key_handler.upload_room_keys(user_id, version2, room_keys))
  478. # deactivate most of the users by editing DB
  479. self.get_success(
  480. self.store.db_pool.simple_update_many(
  481. table="users",
  482. key_names=("name",),
  483. key_values=users[0:18],
  484. value_names=("deactivated",),
  485. value_values=[(1,) for i in range(1, 19)],
  486. desc="",
  487. )
  488. )
  489. # run background update
  490. self.get_success(
  491. self.store.db_pool.simple_insert(
  492. "background_updates",
  493. {
  494. "update_name": "delete_e2e_backup_keys_for_deactivated_users",
  495. "progress_json": "{}",
  496. },
  497. )
  498. )
  499. self.store.db_pool.updates._all_done = False
  500. self.wait_for_background_updates()
  501. # check that keys are deleted for the deactivated users but not the others
  502. res = self.get_success(
  503. self.hs.get_datastores().main.db_pool.simple_select_list(
  504. "e2e_room_keys", None, ("user_id",), "simple_select"
  505. )
  506. )
  507. self.assertEqual(len(res), 4)
  508. res2 = self.get_success(
  509. self.hs.get_datastores().main.db_pool.simple_select_list(
  510. "e2e_room_keys_versions", None, ("user_id",), "simple_select"
  511. )
  512. )
  513. self.assertEqual(len(res2), 4)
  514. def deactivate(self, user_id: str, tok: str) -> None:
  515. request_data = {
  516. "auth": {
  517. "type": "m.login.password",
  518. "user": user_id,
  519. "password": "test",
  520. },
  521. "erase": False,
  522. }
  523. channel = self.make_request(
  524. "POST", "account/deactivate", request_data, access_token=tok
  525. )
  526. self.assertEqual(channel.code, 200, channel.json_body)
  527. class WhoamiTestCase(unittest.HomeserverTestCase):
  528. servlets = [
  529. synapse.rest.admin.register_servlets_for_client_rest_resource,
  530. login.register_servlets,
  531. account.register_servlets,
  532. register.register_servlets,
  533. ]
  534. def default_config(self) -> Dict[str, Any]:
  535. config = super().default_config()
  536. config["allow_guest_access"] = True
  537. return config
  538. def test_GET_whoami(self) -> None:
  539. device_id = "wouldgohere"
  540. user_id = self.register_user("kermit", "test")
  541. tok = self.login("kermit", "test", device_id=device_id)
  542. whoami = self._whoami(tok)
  543. self.assertEqual(
  544. whoami,
  545. {
  546. "user_id": user_id,
  547. "device_id": device_id,
  548. "is_guest": False,
  549. },
  550. )
  551. def test_GET_whoami_guests(self) -> None:
  552. channel = self.make_request(
  553. b"POST", b"/_matrix/client/r0/register?kind=guest", b"{}"
  554. )
  555. tok = channel.json_body["access_token"]
  556. user_id = channel.json_body["user_id"]
  557. device_id = channel.json_body["device_id"]
  558. whoami = self._whoami(tok)
  559. self.assertEqual(
  560. whoami,
  561. {
  562. "user_id": user_id,
  563. "device_id": device_id,
  564. "is_guest": True,
  565. },
  566. )
  567. def test_GET_whoami_appservices(self) -> None:
  568. user_id = "@as:test"
  569. as_token = "i_am_an_app_service"
  570. appservice = ApplicationService(
  571. as_token,
  572. id="1234",
  573. namespaces={"users": [{"regex": user_id, "exclusive": True}]},
  574. sender=user_id,
  575. )
  576. self.hs.get_datastores().main.services_cache.append(appservice)
  577. whoami = self._whoami(as_token)
  578. self.assertEqual(
  579. whoami,
  580. {
  581. "user_id": user_id,
  582. "is_guest": False,
  583. },
  584. )
  585. self.assertFalse(hasattr(whoami, "device_id"))
  586. def _whoami(self, tok: str) -> JsonDict:
  587. channel = self.make_request("GET", "account/whoami", {}, access_token=tok)
  588. self.assertEqual(channel.code, 200)
  589. return channel.json_body
  590. class ThreepidEmailRestTestCase(unittest.HomeserverTestCase):
  591. servlets = [
  592. account.register_servlets,
  593. login.register_servlets,
  594. synapse.rest.admin.register_servlets_for_client_rest_resource,
  595. ]
  596. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  597. config = self.default_config()
  598. # Email config.
  599. config["email"] = {
  600. "enable_notifs": False,
  601. "template_dir": os.path.abspath(
  602. pkg_resources.resource_filename("synapse", "res/templates")
  603. ),
  604. "smtp_host": "127.0.0.1",
  605. "smtp_port": 20,
  606. "require_transport_security": False,
  607. "smtp_user": None,
  608. "smtp_pass": None,
  609. "notif_from": "test@example.com",
  610. }
  611. config["public_baseurl"] = "https://example.com"
  612. self.hs = self.setup_test_homeserver(config=config)
  613. async def sendmail(
  614. reactor: IReactorTCP,
  615. smtphost: str,
  616. smtpport: int,
  617. from_addr: str,
  618. to_addr: str,
  619. msg_bytes: bytes,
  620. *args: Any,
  621. **kwargs: Any,
  622. ) -> None:
  623. self.email_attempts.append(msg_bytes)
  624. self.email_attempts: List[bytes] = []
  625. self.hs.get_send_email_handler()._sendmail = sendmail
  626. return self.hs
  627. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  628. self.store = hs.get_datastores().main
  629. self.user_id = self.register_user("kermit", "test")
  630. self.user_id_tok = self.login("kermit", "test")
  631. self.email = "test@example.com"
  632. self.url_3pid = b"account/3pid"
  633. def test_add_valid_email(self) -> None:
  634. self._add_email(self.email, self.email)
  635. def test_add_valid_email_second_time(self) -> None:
  636. self._add_email(self.email, self.email)
  637. self._request_token_invalid_email(
  638. self.email,
  639. expected_errcode=Codes.THREEPID_IN_USE,
  640. expected_error="Email is already in use",
  641. )
  642. def test_add_valid_email_second_time_canonicalise(self) -> None:
  643. self._add_email(self.email, self.email)
  644. self._request_token_invalid_email(
  645. "TEST@EXAMPLE.COM",
  646. expected_errcode=Codes.THREEPID_IN_USE,
  647. expected_error="Email is already in use",
  648. )
  649. def test_add_email_no_at(self) -> None:
  650. self._request_token_invalid_email(
  651. "address-without-at.bar",
  652. expected_errcode=Codes.BAD_JSON,
  653. expected_error="Unable to parse email address",
  654. )
  655. def test_add_email_two_at(self) -> None:
  656. self._request_token_invalid_email(
  657. "foo@foo@test.bar",
  658. expected_errcode=Codes.BAD_JSON,
  659. expected_error="Unable to parse email address",
  660. )
  661. def test_add_email_bad_format(self) -> None:
  662. self._request_token_invalid_email(
  663. "user@bad.example.net@good.example.com",
  664. expected_errcode=Codes.BAD_JSON,
  665. expected_error="Unable to parse email address",
  666. )
  667. def test_add_email_domain_to_lower(self) -> None:
  668. self._add_email("foo@TEST.BAR", "foo@test.bar")
  669. def test_add_email_domain_with_umlaut(self) -> None:
  670. self._add_email("foo@Öumlaut.com", "foo@öumlaut.com")
  671. def test_add_email_address_casefold(self) -> None:
  672. self._add_email("Strauß@Example.com", "strauss@example.com")
  673. def test_address_trim(self) -> None:
  674. self._add_email(" foo@test.bar ", "foo@test.bar")
  675. @override_config({"rc_3pid_validation": {"burst_count": 3}})
  676. def test_ratelimit_by_ip(self) -> None:
  677. """Tests that adding emails is ratelimited by IP"""
  678. # We expect to be able to set three emails before getting ratelimited.
  679. self._add_email("foo1@test.bar", "foo1@test.bar")
  680. self._add_email("foo2@test.bar", "foo2@test.bar")
  681. self._add_email("foo3@test.bar", "foo3@test.bar")
  682. with self.assertRaises(HttpResponseException) as cm:
  683. self._add_email("foo4@test.bar", "foo4@test.bar")
  684. self.assertEqual(cm.exception.code, 429)
  685. def test_add_email_if_disabled(self) -> None:
  686. """Test adding email to profile when doing so is disallowed"""
  687. self.hs.config.registration.enable_3pid_changes = False
  688. client_secret = "foobar"
  689. channel = self.make_request(
  690. "POST",
  691. b"/_matrix/client/unstable/account/3pid/email/requestToken",
  692. {
  693. "client_secret": client_secret,
  694. "email": "test@example.com",
  695. "send_attempt": 1,
  696. },
  697. )
  698. self.assertEqual(
  699. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  700. )
  701. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  702. def test_delete_email(self) -> None:
  703. """Test deleting an email from profile"""
  704. # Add a threepid
  705. self.get_success(
  706. self.store.user_add_threepid(
  707. user_id=self.user_id,
  708. medium="email",
  709. address=self.email,
  710. validated_at=0,
  711. added_at=0,
  712. )
  713. )
  714. channel = self.make_request(
  715. "POST",
  716. b"account/3pid/delete",
  717. {"medium": "email", "address": self.email},
  718. access_token=self.user_id_tok,
  719. )
  720. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  721. # Get user
  722. channel = self.make_request(
  723. "GET",
  724. self.url_3pid,
  725. access_token=self.user_id_tok,
  726. )
  727. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  728. self.assertFalse(channel.json_body["threepids"])
  729. def test_delete_email_if_disabled(self) -> None:
  730. """Test deleting an email from profile when disallowed"""
  731. self.hs.config.registration.enable_3pid_changes = False
  732. # Add a threepid
  733. self.get_success(
  734. self.store.user_add_threepid(
  735. user_id=self.user_id,
  736. medium="email",
  737. address=self.email,
  738. validated_at=0,
  739. added_at=0,
  740. )
  741. )
  742. channel = self.make_request(
  743. "POST",
  744. b"account/3pid/delete",
  745. {"medium": "email", "address": self.email},
  746. access_token=self.user_id_tok,
  747. )
  748. self.assertEqual(
  749. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  750. )
  751. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  752. # Get user
  753. channel = self.make_request(
  754. "GET",
  755. self.url_3pid,
  756. access_token=self.user_id_tok,
  757. )
  758. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  759. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  760. self.assertEqual(self.email, channel.json_body["threepids"][0]["address"])
  761. def test_cant_add_email_without_clicking_link(self) -> None:
  762. """Test that we do actually need to click the link in the email"""
  763. client_secret = "foobar"
  764. session_id = self._request_token(self.email, client_secret)
  765. self.assertEqual(len(self.email_attempts), 1)
  766. # Attempt to add email without clicking the link
  767. channel = self.make_request(
  768. "POST",
  769. b"/_matrix/client/unstable/account/3pid/add",
  770. {
  771. "client_secret": client_secret,
  772. "sid": session_id,
  773. "auth": {
  774. "type": "m.login.password",
  775. "user": self.user_id,
  776. "password": "test",
  777. },
  778. },
  779. access_token=self.user_id_tok,
  780. )
  781. self.assertEqual(
  782. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  783. )
  784. self.assertEqual(Codes.THREEPID_AUTH_FAILED, channel.json_body["errcode"])
  785. # Get user
  786. channel = self.make_request(
  787. "GET",
  788. self.url_3pid,
  789. access_token=self.user_id_tok,
  790. )
  791. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  792. self.assertFalse(channel.json_body["threepids"])
  793. def test_no_valid_token(self) -> None:
  794. """Test that we do actually need to request a token and can't just
  795. make a session up.
  796. """
  797. client_secret = "foobar"
  798. session_id = "weasle"
  799. # Attempt to add email without even requesting an email
  800. channel = self.make_request(
  801. "POST",
  802. b"/_matrix/client/unstable/account/3pid/add",
  803. {
  804. "client_secret": client_secret,
  805. "sid": session_id,
  806. "auth": {
  807. "type": "m.login.password",
  808. "user": self.user_id,
  809. "password": "test",
  810. },
  811. },
  812. access_token=self.user_id_tok,
  813. )
  814. self.assertEqual(
  815. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  816. )
  817. self.assertEqual(Codes.THREEPID_AUTH_FAILED, channel.json_body["errcode"])
  818. # Get user
  819. channel = self.make_request(
  820. "GET",
  821. self.url_3pid,
  822. access_token=self.user_id_tok,
  823. )
  824. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  825. self.assertFalse(channel.json_body["threepids"])
  826. @override_config({"next_link_domain_whitelist": None})
  827. def test_next_link(self) -> None:
  828. """Tests a valid next_link parameter value with no whitelist (good case)"""
  829. self._request_token(
  830. "something@example.com",
  831. "some_secret",
  832. next_link="https://example.com/a/good/site",
  833. expect_code=HTTPStatus.OK,
  834. )
  835. @override_config({"next_link_domain_whitelist": None})
  836. def test_next_link_exotic_protocol(self) -> None:
  837. """Tests using a esoteric protocol as a next_link parameter value.
  838. Someone may be hosting a client on IPFS etc.
  839. """
  840. self._request_token(
  841. "something@example.com",
  842. "some_secret",
  843. next_link="some-protocol://abcdefghijklmopqrstuvwxyz",
  844. expect_code=HTTPStatus.OK,
  845. )
  846. @override_config({"next_link_domain_whitelist": None})
  847. def test_next_link_file_uri(self) -> None:
  848. """Tests next_link parameters cannot be file URI"""
  849. # Attempt to use a next_link value that points to the local disk
  850. self._request_token(
  851. "something@example.com",
  852. "some_secret",
  853. next_link="file:///host/path",
  854. expect_code=HTTPStatus.BAD_REQUEST,
  855. )
  856. @override_config({"next_link_domain_whitelist": ["example.com", "example.org"]})
  857. def test_next_link_domain_whitelist(self) -> None:
  858. """Tests next_link parameters must fit the whitelist if provided"""
  859. # Ensure not providing a next_link parameter still works
  860. self._request_token(
  861. "something@example.com",
  862. "some_secret",
  863. next_link=None,
  864. expect_code=HTTPStatus.OK,
  865. )
  866. self._request_token(
  867. "something@example.com",
  868. "some_secret",
  869. next_link="https://example.com/some/good/page",
  870. expect_code=HTTPStatus.OK,
  871. )
  872. self._request_token(
  873. "something@example.com",
  874. "some_secret",
  875. next_link="https://example.org/some/also/good/page",
  876. expect_code=HTTPStatus.OK,
  877. )
  878. self._request_token(
  879. "something@example.com",
  880. "some_secret",
  881. next_link="https://bad.example.org/some/bad/page",
  882. expect_code=HTTPStatus.BAD_REQUEST,
  883. )
  884. @override_config({"next_link_domain_whitelist": []})
  885. def test_empty_next_link_domain_whitelist(self) -> None:
  886. """Tests an empty next_lint_domain_whitelist value, meaning next_link is essentially
  887. disallowed
  888. """
  889. self._request_token(
  890. "something@example.com",
  891. "some_secret",
  892. next_link="https://example.com/a/page",
  893. expect_code=HTTPStatus.BAD_REQUEST,
  894. )
  895. def _request_token(
  896. self,
  897. email: str,
  898. client_secret: str,
  899. next_link: Optional[str] = None,
  900. expect_code: int = HTTPStatus.OK,
  901. ) -> Optional[str]:
  902. """Request a validation token to add an email address to a user's account
  903. Args:
  904. email: The email address to validate
  905. client_secret: A secret string
  906. next_link: A link to redirect the user to after validation
  907. expect_code: Expected return code of the call
  908. Returns:
  909. The ID of the new threepid validation session, or None if the response
  910. did not contain a session ID.
  911. """
  912. body = {"client_secret": client_secret, "email": email, "send_attempt": 1}
  913. if next_link:
  914. body["next_link"] = next_link
  915. channel = self.make_request(
  916. "POST",
  917. b"account/3pid/email/requestToken",
  918. body,
  919. )
  920. if channel.code != expect_code:
  921. raise HttpResponseException(
  922. channel.code,
  923. channel.result["reason"],
  924. channel.result["body"],
  925. )
  926. return channel.json_body.get("sid")
  927. def _request_token_invalid_email(
  928. self,
  929. email: str,
  930. expected_errcode: str,
  931. expected_error: str,
  932. client_secret: str = "foobar",
  933. ) -> None:
  934. channel = self.make_request(
  935. "POST",
  936. b"account/3pid/email/requestToken",
  937. {"client_secret": client_secret, "email": email, "send_attempt": 1},
  938. )
  939. self.assertEqual(
  940. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  941. )
  942. self.assertEqual(expected_errcode, channel.json_body["errcode"])
  943. self.assertIn(expected_error, channel.json_body["error"])
  944. def _validate_token(self, link: str) -> None:
  945. # Remove the host
  946. path = link.replace("https://example.com", "")
  947. channel = self.make_request("GET", path, shorthand=False)
  948. self.assertEqual(HTTPStatus.OK, channel.code, channel.result)
  949. def _get_link_from_email(self) -> str:
  950. assert self.email_attempts, "No emails have been sent"
  951. raw_msg = self.email_attempts[-1].decode("UTF-8")
  952. mail = Parser().parsestr(raw_msg)
  953. text = None
  954. for part in mail.walk():
  955. if part.get_content_type() == "text/plain":
  956. text = part.get_payload(decode=True).decode("UTF-8")
  957. break
  958. if not text:
  959. self.fail("Could not find text portion of email to parse")
  960. assert text is not None
  961. match = re.search(r"https://example.com\S+", text)
  962. assert match, "Could not find link in email"
  963. return match.group(0)
  964. def _add_email(self, request_email: str, expected_email: str) -> None:
  965. """Test adding an email to profile"""
  966. previous_email_attempts = len(self.email_attempts)
  967. client_secret = "foobar"
  968. session_id = self._request_token(request_email, client_secret)
  969. self.assertEqual(len(self.email_attempts) - previous_email_attempts, 1)
  970. link = self._get_link_from_email()
  971. self._validate_token(link)
  972. channel = self.make_request(
  973. "POST",
  974. b"/_matrix/client/unstable/account/3pid/add",
  975. {
  976. "client_secret": client_secret,
  977. "sid": session_id,
  978. "auth": {
  979. "type": "m.login.password",
  980. "user": self.user_id,
  981. "password": "test",
  982. },
  983. },
  984. access_token=self.user_id_tok,
  985. )
  986. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  987. # Get user
  988. channel = self.make_request(
  989. "GET",
  990. self.url_3pid,
  991. access_token=self.user_id_tok,
  992. )
  993. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  994. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  995. threepids = {threepid["address"] for threepid in channel.json_body["threepids"]}
  996. self.assertIn(expected_email, threepids)
  997. class AccountStatusTestCase(unittest.HomeserverTestCase):
  998. servlets = [
  999. account.register_servlets,
  1000. admin.register_servlets,
  1001. login.register_servlets,
  1002. ]
  1003. url = "/_matrix/client/unstable/org.matrix.msc3720/account_status"
  1004. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1005. config = self.default_config()
  1006. config["experimental_features"] = {"msc3720_enabled": True}
  1007. return self.setup_test_homeserver(config=config)
  1008. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1009. self.requester = self.register_user("requester", "password")
  1010. self.requester_tok = self.login("requester", "password")
  1011. self.server_name = hs.config.server.server_name
  1012. def test_missing_mxid(self) -> None:
  1013. """Tests that not providing any MXID raises an error."""
  1014. self._test_status(
  1015. users=None,
  1016. expected_status_code=HTTPStatus.BAD_REQUEST,
  1017. expected_errcode=Codes.MISSING_PARAM,
  1018. )
  1019. def test_invalid_mxid(self) -> None:
  1020. """Tests that providing an invalid MXID raises an error."""
  1021. self._test_status(
  1022. users=["bad:test"],
  1023. expected_status_code=HTTPStatus.BAD_REQUEST,
  1024. expected_errcode=Codes.INVALID_PARAM,
  1025. )
  1026. def test_local_user_not_exists(self) -> None:
  1027. """Tests that the account status endpoints correctly reports that a user doesn't
  1028. exist.
  1029. """
  1030. user = "@unknown:" + self.hs.config.server.server_name
  1031. self._test_status(
  1032. users=[user],
  1033. expected_statuses={
  1034. user: {
  1035. "exists": False,
  1036. },
  1037. },
  1038. expected_failures=[],
  1039. )
  1040. def test_local_user_exists(self) -> None:
  1041. """Tests that the account status endpoint correctly reports that a user doesn't
  1042. exist.
  1043. """
  1044. user = self.register_user("someuser", "password")
  1045. self._test_status(
  1046. users=[user],
  1047. expected_statuses={
  1048. user: {
  1049. "exists": True,
  1050. "deactivated": False,
  1051. },
  1052. },
  1053. expected_failures=[],
  1054. )
  1055. def test_local_user_deactivated(self) -> None:
  1056. """Tests that the account status endpoint correctly reports a deactivated user."""
  1057. user = self.register_user("someuser", "password")
  1058. self.get_success(
  1059. self.hs.get_datastores().main.set_user_deactivated_status(
  1060. user, deactivated=True
  1061. )
  1062. )
  1063. self._test_status(
  1064. users=[user],
  1065. expected_statuses={
  1066. user: {
  1067. "exists": True,
  1068. "deactivated": True,
  1069. },
  1070. },
  1071. expected_failures=[],
  1072. )
  1073. def test_mixed_local_and_remote_users(self) -> None:
  1074. """Tests that if some users are remote the account status endpoint correctly
  1075. merges the remote responses with the local result.
  1076. """
  1077. # We use 3 users: one doesn't exist but belongs on the local homeserver, one is
  1078. # deactivated and belongs on one remote homeserver, and one belongs to another
  1079. # remote homeserver that didn't return any result (the federation code should
  1080. # mark that user as a failure).
  1081. users = [
  1082. "@unknown:" + self.hs.config.server.server_name,
  1083. "@deactivated:remote",
  1084. "@failed:otherremote",
  1085. "@bad:badremote",
  1086. ]
  1087. async def post_json(
  1088. destination: str,
  1089. path: str,
  1090. data: Optional[JsonDict] = None,
  1091. *a: Any,
  1092. **kwa: Any,
  1093. ) -> Union[JsonDict, list]:
  1094. if destination == "remote":
  1095. return {
  1096. "account_statuses": {
  1097. users[1]: {
  1098. "exists": True,
  1099. "deactivated": True,
  1100. },
  1101. }
  1102. }
  1103. elif destination == "badremote":
  1104. # badremote tries to overwrite the status of a user that doesn't belong
  1105. # to it (i.e. users[1]) with false data, which Synapse is expected to
  1106. # ignore.
  1107. return {
  1108. "account_statuses": {
  1109. users[3]: {
  1110. "exists": False,
  1111. },
  1112. users[1]: {
  1113. "exists": False,
  1114. },
  1115. }
  1116. }
  1117. # if destination == "otherremote"
  1118. else:
  1119. return {}
  1120. # Register a mock that will return the expected result depending on the remote.
  1121. self.hs.get_federation_http_client().post_json = Mock(side_effect=post_json) # type: ignore[assignment]
  1122. # Check that we've got the correct response from the client-side endpoint.
  1123. self._test_status(
  1124. users=users,
  1125. expected_statuses={
  1126. users[0]: {
  1127. "exists": False,
  1128. },
  1129. users[1]: {
  1130. "exists": True,
  1131. "deactivated": True,
  1132. },
  1133. users[3]: {
  1134. "exists": False,
  1135. },
  1136. },
  1137. expected_failures=[users[2]],
  1138. )
  1139. @unittest.override_config(
  1140. {
  1141. "use_account_validity_in_account_status": True,
  1142. }
  1143. )
  1144. def test_no_account_validity(self) -> None:
  1145. """Tests that if we decide to include account validity in the response but no
  1146. account validity 'is_user_expired' callback is provided, we default to marking all
  1147. users as not expired.
  1148. """
  1149. user = self.register_user("someuser", "password")
  1150. self._test_status(
  1151. users=[user],
  1152. expected_statuses={
  1153. user: {
  1154. "exists": True,
  1155. "deactivated": False,
  1156. "org.matrix.expired": False,
  1157. },
  1158. },
  1159. expected_failures=[],
  1160. )
  1161. @unittest.override_config(
  1162. {
  1163. "use_account_validity_in_account_status": True,
  1164. }
  1165. )
  1166. def test_account_validity_expired(self) -> None:
  1167. """Test that if we decide to include account validity in the response and the user
  1168. is expired, we return the correct info.
  1169. """
  1170. user = self.register_user("someuser", "password")
  1171. async def is_expired(user_id: str) -> bool:
  1172. # We can't blindly say everyone is expired, otherwise the request to get the
  1173. # account status will fail.
  1174. return UserID.from_string(user_id).localpart == "someuser"
  1175. account_validity_callbacks = self.hs.get_module_api_callbacks().account_validity
  1176. account_validity_callbacks.is_user_expired_callbacks.append(is_expired)
  1177. self._test_status(
  1178. users=[user],
  1179. expected_statuses={
  1180. user: {
  1181. "exists": True,
  1182. "deactivated": False,
  1183. "org.matrix.expired": True,
  1184. },
  1185. },
  1186. expected_failures=[],
  1187. )
  1188. def _test_status(
  1189. self,
  1190. users: Optional[List[str]],
  1191. expected_status_code: int = HTTPStatus.OK,
  1192. expected_statuses: Optional[Dict[str, Dict[str, bool]]] = None,
  1193. expected_failures: Optional[List[str]] = None,
  1194. expected_errcode: Optional[str] = None,
  1195. ) -> None:
  1196. """Send a request to the account status endpoint and check that the response
  1197. matches with what's expected.
  1198. Args:
  1199. users: The account(s) to request the status of, if any. If set to None, no
  1200. `user_id` query parameter will be included in the request.
  1201. expected_status_code: The expected HTTP status code.
  1202. expected_statuses: The expected account statuses, if any.
  1203. expected_failures: The expected failures, if any.
  1204. expected_errcode: The expected Matrix error code, if any.
  1205. """
  1206. content = {}
  1207. if users is not None:
  1208. content["user_ids"] = users
  1209. channel = self.make_request(
  1210. method="POST",
  1211. path=self.url,
  1212. content=content,
  1213. access_token=self.requester_tok,
  1214. )
  1215. self.assertEqual(channel.code, expected_status_code)
  1216. if expected_statuses is not None:
  1217. self.assertEqual(channel.json_body["account_statuses"], expected_statuses)
  1218. if expected_failures is not None:
  1219. self.assertEqual(channel.json_body["failures"], expected_failures)
  1220. if expected_errcode is not None:
  1221. self.assertEqual(channel.json_body["errcode"], expected_errcode)