test_account.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  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 deactivate(self, user_id: str, tok: str) -> None:
  378. request_data = {
  379. "auth": {
  380. "type": "m.login.password",
  381. "user": user_id,
  382. "password": "test",
  383. },
  384. "erase": False,
  385. }
  386. channel = self.make_request(
  387. "POST", "account/deactivate", request_data, access_token=tok
  388. )
  389. self.assertEqual(channel.code, 200)
  390. class WhoamiTestCase(unittest.HomeserverTestCase):
  391. servlets = [
  392. synapse.rest.admin.register_servlets_for_client_rest_resource,
  393. login.register_servlets,
  394. account.register_servlets,
  395. register.register_servlets,
  396. ]
  397. def default_config(self) -> Dict[str, Any]:
  398. config = super().default_config()
  399. config["allow_guest_access"] = True
  400. return config
  401. def test_GET_whoami(self) -> None:
  402. device_id = "wouldgohere"
  403. user_id = self.register_user("kermit", "test")
  404. tok = self.login("kermit", "test", device_id=device_id)
  405. whoami = self._whoami(tok)
  406. self.assertEqual(
  407. whoami,
  408. {
  409. "user_id": user_id,
  410. "device_id": device_id,
  411. "is_guest": False,
  412. },
  413. )
  414. def test_GET_whoami_guests(self) -> None:
  415. channel = self.make_request(
  416. b"POST", b"/_matrix/client/r0/register?kind=guest", b"{}"
  417. )
  418. tok = channel.json_body["access_token"]
  419. user_id = channel.json_body["user_id"]
  420. device_id = channel.json_body["device_id"]
  421. whoami = self._whoami(tok)
  422. self.assertEqual(
  423. whoami,
  424. {
  425. "user_id": user_id,
  426. "device_id": device_id,
  427. "is_guest": True,
  428. },
  429. )
  430. def test_GET_whoami_appservices(self) -> None:
  431. user_id = "@as:test"
  432. as_token = "i_am_an_app_service"
  433. appservice = ApplicationService(
  434. as_token,
  435. id="1234",
  436. namespaces={"users": [{"regex": user_id, "exclusive": True}]},
  437. sender=user_id,
  438. )
  439. self.hs.get_datastores().main.services_cache.append(appservice)
  440. whoami = self._whoami(as_token)
  441. self.assertEqual(
  442. whoami,
  443. {
  444. "user_id": user_id,
  445. "is_guest": False,
  446. },
  447. )
  448. self.assertFalse(hasattr(whoami, "device_id"))
  449. def _whoami(self, tok: str) -> JsonDict:
  450. channel = self.make_request("GET", "account/whoami", {}, access_token=tok)
  451. self.assertEqual(channel.code, 200)
  452. return channel.json_body
  453. class ThreepidEmailRestTestCase(unittest.HomeserverTestCase):
  454. servlets = [
  455. account.register_servlets,
  456. login.register_servlets,
  457. synapse.rest.admin.register_servlets_for_client_rest_resource,
  458. ]
  459. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  460. config = self.default_config()
  461. # Email config.
  462. config["email"] = {
  463. "enable_notifs": False,
  464. "template_dir": os.path.abspath(
  465. pkg_resources.resource_filename("synapse", "res/templates")
  466. ),
  467. "smtp_host": "127.0.0.1",
  468. "smtp_port": 20,
  469. "require_transport_security": False,
  470. "smtp_user": None,
  471. "smtp_pass": None,
  472. "notif_from": "test@example.com",
  473. }
  474. config["public_baseurl"] = "https://example.com"
  475. self.hs = self.setup_test_homeserver(config=config)
  476. async def sendmail(
  477. reactor: IReactorTCP,
  478. smtphost: str,
  479. smtpport: int,
  480. from_addr: str,
  481. to_addr: str,
  482. msg_bytes: bytes,
  483. *args: Any,
  484. **kwargs: Any,
  485. ) -> None:
  486. self.email_attempts.append(msg_bytes)
  487. self.email_attempts: List[bytes] = []
  488. self.hs.get_send_email_handler()._sendmail = sendmail
  489. return self.hs
  490. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  491. self.store = hs.get_datastores().main
  492. self.user_id = self.register_user("kermit", "test")
  493. self.user_id_tok = self.login("kermit", "test")
  494. self.email = "test@example.com"
  495. self.url_3pid = b"account/3pid"
  496. def test_add_valid_email(self) -> None:
  497. self._add_email(self.email, self.email)
  498. def test_add_valid_email_second_time(self) -> None:
  499. self._add_email(self.email, self.email)
  500. self._request_token_invalid_email(
  501. self.email,
  502. expected_errcode=Codes.THREEPID_IN_USE,
  503. expected_error="Email is already in use",
  504. )
  505. def test_add_valid_email_second_time_canonicalise(self) -> None:
  506. self._add_email(self.email, self.email)
  507. self._request_token_invalid_email(
  508. "TEST@EXAMPLE.COM",
  509. expected_errcode=Codes.THREEPID_IN_USE,
  510. expected_error="Email is already in use",
  511. )
  512. def test_add_email_no_at(self) -> None:
  513. self._request_token_invalid_email(
  514. "address-without-at.bar",
  515. expected_errcode=Codes.UNKNOWN,
  516. expected_error="Unable to parse email address",
  517. )
  518. def test_add_email_two_at(self) -> None:
  519. self._request_token_invalid_email(
  520. "foo@foo@test.bar",
  521. expected_errcode=Codes.UNKNOWN,
  522. expected_error="Unable to parse email address",
  523. )
  524. def test_add_email_bad_format(self) -> None:
  525. self._request_token_invalid_email(
  526. "user@bad.example.net@good.example.com",
  527. expected_errcode=Codes.UNKNOWN,
  528. expected_error="Unable to parse email address",
  529. )
  530. def test_add_email_domain_to_lower(self) -> None:
  531. self._add_email("foo@TEST.BAR", "foo@test.bar")
  532. def test_add_email_domain_with_umlaut(self) -> None:
  533. self._add_email("foo@Öumlaut.com", "foo@öumlaut.com")
  534. def test_add_email_address_casefold(self) -> None:
  535. self._add_email("Strauß@Example.com", "strauss@example.com")
  536. def test_address_trim(self) -> None:
  537. self._add_email(" foo@test.bar ", "foo@test.bar")
  538. @override_config({"rc_3pid_validation": {"burst_count": 3}})
  539. def test_ratelimit_by_ip(self) -> None:
  540. """Tests that adding emails is ratelimited by IP"""
  541. # We expect to be able to set three emails before getting ratelimited.
  542. self._add_email("foo1@test.bar", "foo1@test.bar")
  543. self._add_email("foo2@test.bar", "foo2@test.bar")
  544. self._add_email("foo3@test.bar", "foo3@test.bar")
  545. with self.assertRaises(HttpResponseException) as cm:
  546. self._add_email("foo4@test.bar", "foo4@test.bar")
  547. self.assertEqual(cm.exception.code, 429)
  548. def test_add_email_if_disabled(self) -> None:
  549. """Test adding email to profile when doing so is disallowed"""
  550. self.hs.config.registration.enable_3pid_changes = False
  551. client_secret = "foobar"
  552. session_id = self._request_token(self.email, client_secret)
  553. self.assertEqual(len(self.email_attempts), 1)
  554. link = self._get_link_from_email()
  555. self._validate_token(link)
  556. channel = self.make_request(
  557. "POST",
  558. b"/_matrix/client/unstable/account/3pid/add",
  559. {
  560. "client_secret": client_secret,
  561. "sid": session_id,
  562. "auth": {
  563. "type": "m.login.password",
  564. "user": self.user_id,
  565. "password": "test",
  566. },
  567. },
  568. access_token=self.user_id_tok,
  569. )
  570. self.assertEqual(
  571. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  572. )
  573. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  574. # Get user
  575. channel = self.make_request(
  576. "GET",
  577. self.url_3pid,
  578. access_token=self.user_id_tok,
  579. )
  580. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  581. self.assertFalse(channel.json_body["threepids"])
  582. def test_delete_email(self) -> None:
  583. """Test deleting an email from profile"""
  584. # Add a threepid
  585. self.get_success(
  586. self.store.user_add_threepid(
  587. user_id=self.user_id,
  588. medium="email",
  589. address=self.email,
  590. validated_at=0,
  591. added_at=0,
  592. )
  593. )
  594. channel = self.make_request(
  595. "POST",
  596. b"account/3pid/delete",
  597. {"medium": "email", "address": self.email},
  598. access_token=self.user_id_tok,
  599. )
  600. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  601. # Get user
  602. channel = self.make_request(
  603. "GET",
  604. self.url_3pid,
  605. access_token=self.user_id_tok,
  606. )
  607. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  608. self.assertFalse(channel.json_body["threepids"])
  609. def test_delete_email_if_disabled(self) -> None:
  610. """Test deleting an email from profile when disallowed"""
  611. self.hs.config.registration.enable_3pid_changes = False
  612. # Add a threepid
  613. self.get_success(
  614. self.store.user_add_threepid(
  615. user_id=self.user_id,
  616. medium="email",
  617. address=self.email,
  618. validated_at=0,
  619. added_at=0,
  620. )
  621. )
  622. channel = self.make_request(
  623. "POST",
  624. b"account/3pid/delete",
  625. {"medium": "email", "address": self.email},
  626. access_token=self.user_id_tok,
  627. )
  628. self.assertEqual(
  629. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  630. )
  631. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  632. # Get user
  633. channel = self.make_request(
  634. "GET",
  635. self.url_3pid,
  636. access_token=self.user_id_tok,
  637. )
  638. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  639. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  640. self.assertEqual(self.email, channel.json_body["threepids"][0]["address"])
  641. def test_cant_add_email_without_clicking_link(self) -> None:
  642. """Test that we do actually need to click the link in the email"""
  643. client_secret = "foobar"
  644. session_id = self._request_token(self.email, client_secret)
  645. self.assertEqual(len(self.email_attempts), 1)
  646. # Attempt to add email without clicking the link
  647. channel = self.make_request(
  648. "POST",
  649. b"/_matrix/client/unstable/account/3pid/add",
  650. {
  651. "client_secret": client_secret,
  652. "sid": session_id,
  653. "auth": {
  654. "type": "m.login.password",
  655. "user": self.user_id,
  656. "password": "test",
  657. },
  658. },
  659. access_token=self.user_id_tok,
  660. )
  661. self.assertEqual(
  662. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  663. )
  664. self.assertEqual(Codes.THREEPID_AUTH_FAILED, channel.json_body["errcode"])
  665. # Get user
  666. channel = self.make_request(
  667. "GET",
  668. self.url_3pid,
  669. access_token=self.user_id_tok,
  670. )
  671. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  672. self.assertFalse(channel.json_body["threepids"])
  673. def test_no_valid_token(self) -> None:
  674. """Test that we do actually need to request a token and can't just
  675. make a session up.
  676. """
  677. client_secret = "foobar"
  678. session_id = "weasle"
  679. # Attempt to add email without even requesting an email
  680. channel = self.make_request(
  681. "POST",
  682. b"/_matrix/client/unstable/account/3pid/add",
  683. {
  684. "client_secret": client_secret,
  685. "sid": session_id,
  686. "auth": {
  687. "type": "m.login.password",
  688. "user": self.user_id,
  689. "password": "test",
  690. },
  691. },
  692. access_token=self.user_id_tok,
  693. )
  694. self.assertEqual(
  695. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  696. )
  697. self.assertEqual(Codes.THREEPID_AUTH_FAILED, channel.json_body["errcode"])
  698. # Get user
  699. channel = self.make_request(
  700. "GET",
  701. self.url_3pid,
  702. access_token=self.user_id_tok,
  703. )
  704. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  705. self.assertFalse(channel.json_body["threepids"])
  706. @override_config({"next_link_domain_whitelist": None})
  707. def test_next_link(self) -> None:
  708. """Tests a valid next_link parameter value with no whitelist (good case)"""
  709. self._request_token(
  710. "something@example.com",
  711. "some_secret",
  712. next_link="https://example.com/a/good/site",
  713. expect_code=HTTPStatus.OK,
  714. )
  715. @override_config({"next_link_domain_whitelist": None})
  716. def test_next_link_exotic_protocol(self) -> None:
  717. """Tests using a esoteric protocol as a next_link parameter value.
  718. Someone may be hosting a client on IPFS etc.
  719. """
  720. self._request_token(
  721. "something@example.com",
  722. "some_secret",
  723. next_link="some-protocol://abcdefghijklmopqrstuvwxyz",
  724. expect_code=HTTPStatus.OK,
  725. )
  726. @override_config({"next_link_domain_whitelist": None})
  727. def test_next_link_file_uri(self) -> None:
  728. """Tests next_link parameters cannot be file URI"""
  729. # Attempt to use a next_link value that points to the local disk
  730. self._request_token(
  731. "something@example.com",
  732. "some_secret",
  733. next_link="file:///host/path",
  734. expect_code=HTTPStatus.BAD_REQUEST,
  735. )
  736. @override_config({"next_link_domain_whitelist": ["example.com", "example.org"]})
  737. def test_next_link_domain_whitelist(self) -> None:
  738. """Tests next_link parameters must fit the whitelist if provided"""
  739. # Ensure not providing a next_link parameter still works
  740. self._request_token(
  741. "something@example.com",
  742. "some_secret",
  743. next_link=None,
  744. expect_code=HTTPStatus.OK,
  745. )
  746. self._request_token(
  747. "something@example.com",
  748. "some_secret",
  749. next_link="https://example.com/some/good/page",
  750. expect_code=HTTPStatus.OK,
  751. )
  752. self._request_token(
  753. "something@example.com",
  754. "some_secret",
  755. next_link="https://example.org/some/also/good/page",
  756. expect_code=HTTPStatus.OK,
  757. )
  758. self._request_token(
  759. "something@example.com",
  760. "some_secret",
  761. next_link="https://bad.example.org/some/bad/page",
  762. expect_code=HTTPStatus.BAD_REQUEST,
  763. )
  764. @override_config({"next_link_domain_whitelist": []})
  765. def test_empty_next_link_domain_whitelist(self) -> None:
  766. """Tests an empty next_lint_domain_whitelist value, meaning next_link is essentially
  767. disallowed
  768. """
  769. self._request_token(
  770. "something@example.com",
  771. "some_secret",
  772. next_link="https://example.com/a/page",
  773. expect_code=HTTPStatus.BAD_REQUEST,
  774. )
  775. def _request_token(
  776. self,
  777. email: str,
  778. client_secret: str,
  779. next_link: Optional[str] = None,
  780. expect_code: int = HTTPStatus.OK,
  781. ) -> Optional[str]:
  782. """Request a validation token to add an email address to a user's account
  783. Args:
  784. email: The email address to validate
  785. client_secret: A secret string
  786. next_link: A link to redirect the user to after validation
  787. expect_code: Expected return code of the call
  788. Returns:
  789. The ID of the new threepid validation session, or None if the response
  790. did not contain a session ID.
  791. """
  792. body = {"client_secret": client_secret, "email": email, "send_attempt": 1}
  793. if next_link:
  794. body["next_link"] = next_link
  795. channel = self.make_request(
  796. "POST",
  797. b"account/3pid/email/requestToken",
  798. body,
  799. )
  800. if channel.code != expect_code:
  801. raise HttpResponseException(
  802. channel.code,
  803. channel.result["reason"],
  804. channel.result["body"],
  805. )
  806. return channel.json_body.get("sid")
  807. def _request_token_invalid_email(
  808. self,
  809. email: str,
  810. expected_errcode: str,
  811. expected_error: str,
  812. client_secret: str = "foobar",
  813. ) -> None:
  814. channel = self.make_request(
  815. "POST",
  816. b"account/3pid/email/requestToken",
  817. {"client_secret": client_secret, "email": email, "send_attempt": 1},
  818. )
  819. self.assertEqual(
  820. HTTPStatus.BAD_REQUEST, channel.code, msg=channel.result["body"]
  821. )
  822. self.assertEqual(expected_errcode, channel.json_body["errcode"])
  823. self.assertEqual(expected_error, channel.json_body["error"])
  824. def _validate_token(self, link: str) -> None:
  825. # Remove the host
  826. path = link.replace("https://example.com", "")
  827. channel = self.make_request("GET", path, shorthand=False)
  828. self.assertEqual(HTTPStatus.OK, channel.code, channel.result)
  829. def _get_link_from_email(self) -> str:
  830. assert self.email_attempts, "No emails have been sent"
  831. raw_msg = self.email_attempts[-1].decode("UTF-8")
  832. mail = Parser().parsestr(raw_msg)
  833. text = None
  834. for part in mail.walk():
  835. if part.get_content_type() == "text/plain":
  836. text = part.get_payload(decode=True).decode("UTF-8")
  837. break
  838. if not text:
  839. self.fail("Could not find text portion of email to parse")
  840. assert text is not None
  841. match = re.search(r"https://example.com\S+", text)
  842. assert match, "Could not find link in email"
  843. return match.group(0)
  844. def _add_email(self, request_email: str, expected_email: str) -> None:
  845. """Test adding an email to profile"""
  846. previous_email_attempts = len(self.email_attempts)
  847. client_secret = "foobar"
  848. session_id = self._request_token(request_email, client_secret)
  849. self.assertEqual(len(self.email_attempts) - previous_email_attempts, 1)
  850. link = self._get_link_from_email()
  851. self._validate_token(link)
  852. channel = self.make_request(
  853. "POST",
  854. b"/_matrix/client/unstable/account/3pid/add",
  855. {
  856. "client_secret": client_secret,
  857. "sid": session_id,
  858. "auth": {
  859. "type": "m.login.password",
  860. "user": self.user_id,
  861. "password": "test",
  862. },
  863. },
  864. access_token=self.user_id_tok,
  865. )
  866. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  867. # Get user
  868. channel = self.make_request(
  869. "GET",
  870. self.url_3pid,
  871. access_token=self.user_id_tok,
  872. )
  873. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.result["body"])
  874. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  875. threepids = {threepid["address"] for threepid in channel.json_body["threepids"]}
  876. self.assertIn(expected_email, threepids)
  877. class AccountStatusTestCase(unittest.HomeserverTestCase):
  878. servlets = [
  879. account.register_servlets,
  880. admin.register_servlets,
  881. login.register_servlets,
  882. ]
  883. url = "/_matrix/client/unstable/org.matrix.msc3720/account_status"
  884. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  885. config = self.default_config()
  886. config["experimental_features"] = {"msc3720_enabled": True}
  887. return self.setup_test_homeserver(config=config)
  888. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  889. self.requester = self.register_user("requester", "password")
  890. self.requester_tok = self.login("requester", "password")
  891. self.server_name = hs.config.server.server_name
  892. def test_missing_mxid(self) -> None:
  893. """Tests that not providing any MXID raises an error."""
  894. self._test_status(
  895. users=None,
  896. expected_status_code=HTTPStatus.BAD_REQUEST,
  897. expected_errcode=Codes.MISSING_PARAM,
  898. )
  899. def test_invalid_mxid(self) -> None:
  900. """Tests that providing an invalid MXID raises an error."""
  901. self._test_status(
  902. users=["bad:test"],
  903. expected_status_code=HTTPStatus.BAD_REQUEST,
  904. expected_errcode=Codes.INVALID_PARAM,
  905. )
  906. def test_local_user_not_exists(self) -> None:
  907. """Tests that the account status endpoints correctly reports that a user doesn't
  908. exist.
  909. """
  910. user = "@unknown:" + self.hs.config.server.server_name
  911. self._test_status(
  912. users=[user],
  913. expected_statuses={
  914. user: {
  915. "exists": False,
  916. },
  917. },
  918. expected_failures=[],
  919. )
  920. def test_local_user_exists(self) -> None:
  921. """Tests that the account status endpoint correctly reports that a user doesn't
  922. exist.
  923. """
  924. user = self.register_user("someuser", "password")
  925. self._test_status(
  926. users=[user],
  927. expected_statuses={
  928. user: {
  929. "exists": True,
  930. "deactivated": False,
  931. },
  932. },
  933. expected_failures=[],
  934. )
  935. def test_local_user_deactivated(self) -> None:
  936. """Tests that the account status endpoint correctly reports a deactivated user."""
  937. user = self.register_user("someuser", "password")
  938. self.get_success(
  939. self.hs.get_datastores().main.set_user_deactivated_status(
  940. user, deactivated=True
  941. )
  942. )
  943. self._test_status(
  944. users=[user],
  945. expected_statuses={
  946. user: {
  947. "exists": True,
  948. "deactivated": True,
  949. },
  950. },
  951. expected_failures=[],
  952. )
  953. def test_mixed_local_and_remote_users(self) -> None:
  954. """Tests that if some users are remote the account status endpoint correctly
  955. merges the remote responses with the local result.
  956. """
  957. # We use 3 users: one doesn't exist but belongs on the local homeserver, one is
  958. # deactivated and belongs on one remote homeserver, and one belongs to another
  959. # remote homeserver that didn't return any result (the federation code should
  960. # mark that user as a failure).
  961. users = [
  962. "@unknown:" + self.hs.config.server.server_name,
  963. "@deactivated:remote",
  964. "@failed:otherremote",
  965. "@bad:badremote",
  966. ]
  967. async def post_json(
  968. destination: str,
  969. path: str,
  970. data: Optional[JsonDict] = None,
  971. *a: Any,
  972. **kwa: Any,
  973. ) -> Union[JsonDict, list]:
  974. if destination == "remote":
  975. return {
  976. "account_statuses": {
  977. users[1]: {
  978. "exists": True,
  979. "deactivated": True,
  980. },
  981. }
  982. }
  983. elif destination == "badremote":
  984. # badremote tries to overwrite the status of a user that doesn't belong
  985. # to it (i.e. users[1]) with false data, which Synapse is expected to
  986. # ignore.
  987. return {
  988. "account_statuses": {
  989. users[3]: {
  990. "exists": False,
  991. },
  992. users[1]: {
  993. "exists": False,
  994. },
  995. }
  996. }
  997. # if destination == "otherremote"
  998. else:
  999. return {}
  1000. # Register a mock that will return the expected result depending on the remote.
  1001. self.hs.get_federation_http_client().post_json = Mock(side_effect=post_json)
  1002. # Check that we've got the correct response from the client-side endpoint.
  1003. self._test_status(
  1004. users=users,
  1005. expected_statuses={
  1006. users[0]: {
  1007. "exists": False,
  1008. },
  1009. users[1]: {
  1010. "exists": True,
  1011. "deactivated": True,
  1012. },
  1013. users[3]: {
  1014. "exists": False,
  1015. },
  1016. },
  1017. expected_failures=[users[2]],
  1018. )
  1019. @unittest.override_config(
  1020. {
  1021. "use_account_validity_in_account_status": True,
  1022. }
  1023. )
  1024. def test_no_account_validity(self) -> None:
  1025. """Tests that if we decide to include account validity in the response but no
  1026. account validity 'is_user_expired' callback is provided, we default to marking all
  1027. users as not expired.
  1028. """
  1029. user = self.register_user("someuser", "password")
  1030. self._test_status(
  1031. users=[user],
  1032. expected_statuses={
  1033. user: {
  1034. "exists": True,
  1035. "deactivated": False,
  1036. "org.matrix.expired": False,
  1037. },
  1038. },
  1039. expected_failures=[],
  1040. )
  1041. @unittest.override_config(
  1042. {
  1043. "use_account_validity_in_account_status": True,
  1044. }
  1045. )
  1046. def test_account_validity_expired(self) -> None:
  1047. """Test that if we decide to include account validity in the response and the user
  1048. is expired, we return the correct info.
  1049. """
  1050. user = self.register_user("someuser", "password")
  1051. async def is_expired(user_id: str) -> bool:
  1052. # We can't blindly say everyone is expired, otherwise the request to get the
  1053. # account status will fail.
  1054. return UserID.from_string(user_id).localpart == "someuser"
  1055. self.hs.get_account_validity_handler()._is_user_expired_callbacks.append(
  1056. is_expired
  1057. )
  1058. self._test_status(
  1059. users=[user],
  1060. expected_statuses={
  1061. user: {
  1062. "exists": True,
  1063. "deactivated": False,
  1064. "org.matrix.expired": True,
  1065. },
  1066. },
  1067. expected_failures=[],
  1068. )
  1069. def _test_status(
  1070. self,
  1071. users: Optional[List[str]],
  1072. expected_status_code: int = HTTPStatus.OK,
  1073. expected_statuses: Optional[Dict[str, Dict[str, bool]]] = None,
  1074. expected_failures: Optional[List[str]] = None,
  1075. expected_errcode: Optional[str] = None,
  1076. ) -> None:
  1077. """Send a request to the account status endpoint and check that the response
  1078. matches with what's expected.
  1079. Args:
  1080. users: The account(s) to request the status of, if any. If set to None, no
  1081. `user_id` query parameter will be included in the request.
  1082. expected_status_code: The expected HTTP status code.
  1083. expected_statuses: The expected account statuses, if any.
  1084. expected_failures: The expected failures, if any.
  1085. expected_errcode: The expected Matrix error code, if any.
  1086. """
  1087. content = {}
  1088. if users is not None:
  1089. content["user_ids"] = users
  1090. channel = self.make_request(
  1091. method="POST",
  1092. path=self.url,
  1093. content=content,
  1094. access_token=self.requester_tok,
  1095. )
  1096. self.assertEqual(channel.code, expected_status_code)
  1097. if expected_statuses is not None:
  1098. self.assertEqual(channel.json_body["account_statuses"], expected_statuses)
  1099. if expected_failures is not None:
  1100. self.assertEqual(channel.json_body["failures"], expected_failures)
  1101. if expected_errcode is not None:
  1102. self.assertEqual(channel.json_body["errcode"], expected_errcode)