test_account.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015-2016 OpenMarket Ltd
  3. # Copyright 2017-2018 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import json
  18. import os
  19. import re
  20. from email.parser import Parser
  21. from typing import Optional
  22. import pkg_resources
  23. import synapse.rest.admin
  24. from synapse.api.constants import LoginType, Membership
  25. from synapse.api.errors import Codes, HttpResponseException
  26. from synapse.rest.client.v1 import login, room
  27. from synapse.rest.client.v2_alpha import account, register
  28. from synapse.rest.synapse.client.password_reset import PasswordResetSubmitTokenResource
  29. from tests import unittest
  30. from tests.server import FakeSite, make_request
  31. from tests.unittest import override_config
  32. class PasswordResetTestCase(unittest.HomeserverTestCase):
  33. servlets = [
  34. account.register_servlets,
  35. synapse.rest.admin.register_servlets_for_client_rest_resource,
  36. register.register_servlets,
  37. login.register_servlets,
  38. ]
  39. def make_homeserver(self, reactor, clock):
  40. config = self.default_config()
  41. # Email config.
  42. self.email_attempts = []
  43. async def sendmail(smtphost, from_addr, to_addrs, msg, **kwargs):
  44. self.email_attempts.append(msg)
  45. return
  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, sendmail=sendmail)
  60. return hs
  61. def prepare(self, reactor, clock, hs):
  62. self.store = hs.get_datastore()
  63. self.submit_token_resource = PasswordResetSubmitTokenResource(hs)
  64. def test_basic_password_reset(self):
  65. """Test basic password reset flow
  66. """
  67. old_password = "monkey"
  68. new_password = "kangeroo"
  69. user_id = self.register_user("kermit", old_password)
  70. self.login("kermit", old_password)
  71. email = "test@example.com"
  72. # Add a threepid
  73. self.get_success(
  74. self.store.user_add_threepid(
  75. user_id=user_id,
  76. medium="email",
  77. address=email,
  78. validated_at=0,
  79. added_at=0,
  80. )
  81. )
  82. client_secret = "foobar"
  83. session_id = self._request_token(email, client_secret)
  84. self.assertEquals(len(self.email_attempts), 1)
  85. link = self._get_link_from_email()
  86. self._validate_token(link)
  87. self._reset_password(new_password, session_id, client_secret)
  88. # Assert we can log in with the new password
  89. self.login("kermit", new_password)
  90. # Assert we can't log in with the old password
  91. self.attempt_wrong_password_login("kermit", old_password)
  92. @override_config({"rc_3pid_validation": {"burst_count": 3}})
  93. def test_ratelimit_by_email(self):
  94. """Test that we ratelimit /requestToken for the same email.
  95. """
  96. old_password = "monkey"
  97. new_password = "kangeroo"
  98. user_id = self.register_user("kermit", old_password)
  99. self.login("kermit", old_password)
  100. email = "test1@example.com"
  101. # Add a threepid
  102. self.get_success(
  103. self.store.user_add_threepid(
  104. user_id=user_id,
  105. medium="email",
  106. address=email,
  107. validated_at=0,
  108. added_at=0,
  109. )
  110. )
  111. def reset(ip):
  112. client_secret = "foobar"
  113. session_id = self._request_token(email, client_secret, ip)
  114. self.assertEquals(len(self.email_attempts), 1)
  115. link = self._get_link_from_email()
  116. self._validate_token(link)
  117. self._reset_password(new_password, session_id, client_secret)
  118. self.email_attempts.clear()
  119. # We expect to be able to make three requests before getting rate
  120. # limited.
  121. #
  122. # We change IPs to ensure that we're not being ratelimited due to the
  123. # same IP
  124. reset("127.0.0.1")
  125. reset("127.0.0.2")
  126. reset("127.0.0.3")
  127. with self.assertRaises(HttpResponseException) as cm:
  128. reset("127.0.0.4")
  129. self.assertEqual(cm.exception.code, 429)
  130. def test_basic_password_reset_canonicalise_email(self):
  131. """Test basic password reset flow
  132. Request password reset with different spelling
  133. """
  134. old_password = "monkey"
  135. new_password = "kangeroo"
  136. user_id = self.register_user("kermit", old_password)
  137. self.login("kermit", old_password)
  138. email_profile = "test@example.com"
  139. email_passwort_reset = "TEST@EXAMPLE.COM"
  140. # Add a threepid
  141. self.get_success(
  142. self.store.user_add_threepid(
  143. user_id=user_id,
  144. medium="email",
  145. address=email_profile,
  146. validated_at=0,
  147. added_at=0,
  148. )
  149. )
  150. client_secret = "foobar"
  151. session_id = self._request_token(email_passwort_reset, client_secret)
  152. self.assertEquals(len(self.email_attempts), 1)
  153. link = self._get_link_from_email()
  154. self._validate_token(link)
  155. self._reset_password(new_password, session_id, client_secret)
  156. # Assert we can log in with the new password
  157. self.login("kermit", new_password)
  158. # Assert we can't log in with the old password
  159. self.attempt_wrong_password_login("kermit", old_password)
  160. def test_cant_reset_password_without_clicking_link(self):
  161. """Test that we do actually need to click the link in the email
  162. """
  163. old_password = "monkey"
  164. new_password = "kangeroo"
  165. user_id = self.register_user("kermit", old_password)
  166. self.login("kermit", old_password)
  167. email = "test@example.com"
  168. # Add a threepid
  169. self.get_success(
  170. self.store.user_add_threepid(
  171. user_id=user_id,
  172. medium="email",
  173. address=email,
  174. validated_at=0,
  175. added_at=0,
  176. )
  177. )
  178. client_secret = "foobar"
  179. session_id = self._request_token(email, client_secret)
  180. self.assertEquals(len(self.email_attempts), 1)
  181. # Attempt to reset password without clicking the link
  182. self._reset_password(new_password, session_id, client_secret, expected_code=401)
  183. # Assert we can log in with the old password
  184. self.login("kermit", old_password)
  185. # Assert we can't log in with the new password
  186. self.attempt_wrong_password_login("kermit", new_password)
  187. def test_no_valid_token(self):
  188. """Test that we do actually need to request a token and can't just
  189. make a session up.
  190. """
  191. old_password = "monkey"
  192. new_password = "kangeroo"
  193. user_id = self.register_user("kermit", old_password)
  194. self.login("kermit", old_password)
  195. email = "test@example.com"
  196. # Add a threepid
  197. self.get_success(
  198. self.store.user_add_threepid(
  199. user_id=user_id,
  200. medium="email",
  201. address=email,
  202. validated_at=0,
  203. added_at=0,
  204. )
  205. )
  206. client_secret = "foobar"
  207. session_id = "weasle"
  208. # Attempt to reset password without even requesting an email
  209. self._reset_password(new_password, session_id, client_secret, expected_code=401)
  210. # Assert we can log in with the old password
  211. self.login("kermit", old_password)
  212. # Assert we can't log in with the new password
  213. self.attempt_wrong_password_login("kermit", new_password)
  214. @unittest.override_config({"request_token_inhibit_3pid_errors": True})
  215. def test_password_reset_bad_email_inhibit_error(self):
  216. """Test that triggering a password reset with an email address that isn't bound
  217. to an account doesn't leak the lack of binding for that address if configured
  218. that way.
  219. """
  220. self.register_user("kermit", "monkey")
  221. self.login("kermit", "monkey")
  222. email = "test@example.com"
  223. client_secret = "foobar"
  224. session_id = self._request_token(email, client_secret)
  225. self.assertIsNotNone(session_id)
  226. def _request_token(self, email, client_secret, ip="127.0.0.1"):
  227. channel = self.make_request(
  228. "POST",
  229. b"account/password/email/requestToken",
  230. {"client_secret": client_secret, "email": email, "send_attempt": 1},
  231. client_ip=ip,
  232. )
  233. if channel.code != 200:
  234. raise HttpResponseException(
  235. channel.code, channel.result["reason"], channel.result["body"],
  236. )
  237. return channel.json_body["sid"]
  238. def _validate_token(self, link):
  239. # Remove the host
  240. path = link.replace("https://example.com", "")
  241. # Load the password reset confirmation page
  242. channel = make_request(
  243. self.reactor,
  244. FakeSite(self.submit_token_resource),
  245. "GET",
  246. path,
  247. shorthand=False,
  248. )
  249. self.assertEquals(200, channel.code, channel.result)
  250. # Now POST to the same endpoint, mimicking the same behaviour as clicking the
  251. # password reset confirm button
  252. # Confirm the password reset
  253. channel = make_request(
  254. self.reactor,
  255. FakeSite(self.submit_token_resource),
  256. "POST",
  257. path,
  258. content=b"",
  259. shorthand=False,
  260. content_is_form=True,
  261. )
  262. self.assertEquals(200, channel.code, channel.result)
  263. def _get_link_from_email(self):
  264. assert self.email_attempts, "No emails have been sent"
  265. raw_msg = self.email_attempts[-1].decode("UTF-8")
  266. mail = Parser().parsestr(raw_msg)
  267. text = None
  268. for part in mail.walk():
  269. if part.get_content_type() == "text/plain":
  270. text = part.get_payload(decode=True).decode("UTF-8")
  271. break
  272. if not text:
  273. self.fail("Could not find text portion of email to parse")
  274. match = re.search(r"https://example.com\S+", text)
  275. assert match, "Could not find link in email"
  276. return match.group(0)
  277. def _reset_password(
  278. self, new_password, session_id, client_secret, expected_code=200
  279. ):
  280. channel = self.make_request(
  281. "POST",
  282. b"account/password",
  283. {
  284. "new_password": new_password,
  285. "auth": {
  286. "type": LoginType.EMAIL_IDENTITY,
  287. "threepid_creds": {
  288. "client_secret": client_secret,
  289. "sid": session_id,
  290. },
  291. },
  292. },
  293. )
  294. self.assertEquals(expected_code, channel.code, channel.result)
  295. class DeactivateTestCase(unittest.HomeserverTestCase):
  296. servlets = [
  297. synapse.rest.admin.register_servlets_for_client_rest_resource,
  298. login.register_servlets,
  299. account.register_servlets,
  300. room.register_servlets,
  301. ]
  302. def make_homeserver(self, reactor, clock):
  303. self.hs = self.setup_test_homeserver()
  304. return self.hs
  305. def test_deactivate_account(self):
  306. user_id = self.register_user("kermit", "test")
  307. tok = self.login("kermit", "test")
  308. self.deactivate(user_id, tok)
  309. store = self.hs.get_datastore()
  310. # Check that the user has been marked as deactivated.
  311. self.assertTrue(self.get_success(store.get_user_deactivated_status(user_id)))
  312. # Check that this access token has been invalidated.
  313. channel = self.make_request("GET", "account/whoami")
  314. self.assertEqual(channel.code, 401)
  315. def test_pending_invites(self):
  316. """Tests that deactivating a user rejects every pending invite for them."""
  317. store = self.hs.get_datastore()
  318. inviter_id = self.register_user("inviter", "test")
  319. inviter_tok = self.login("inviter", "test")
  320. invitee_id = self.register_user("invitee", "test")
  321. invitee_tok = self.login("invitee", "test")
  322. # Make @inviter:test invite @invitee:test in a new room.
  323. room_id = self.helper.create_room_as(inviter_id, tok=inviter_tok)
  324. self.helper.invite(
  325. room=room_id, src=inviter_id, targ=invitee_id, tok=inviter_tok
  326. )
  327. # Make sure the invite is here.
  328. pending_invites = self.get_success(
  329. store.get_invited_rooms_for_local_user(invitee_id)
  330. )
  331. self.assertEqual(len(pending_invites), 1, pending_invites)
  332. self.assertEqual(pending_invites[0].room_id, room_id, pending_invites)
  333. # Deactivate @invitee:test.
  334. self.deactivate(invitee_id, invitee_tok)
  335. # Check that the invite isn't there anymore.
  336. pending_invites = self.get_success(
  337. store.get_invited_rooms_for_local_user(invitee_id)
  338. )
  339. self.assertEqual(len(pending_invites), 0, pending_invites)
  340. # Check that the membership of @invitee:test in the room is now "leave".
  341. memberships = self.get_success(
  342. store.get_rooms_for_local_user_where_membership_is(
  343. invitee_id, [Membership.LEAVE]
  344. )
  345. )
  346. self.assertEqual(len(memberships), 1, memberships)
  347. self.assertEqual(memberships[0].room_id, room_id, memberships)
  348. def deactivate(self, user_id, tok):
  349. request_data = json.dumps(
  350. {
  351. "auth": {
  352. "type": "m.login.password",
  353. "user": user_id,
  354. "password": "test",
  355. },
  356. "erase": False,
  357. }
  358. )
  359. channel = self.make_request(
  360. "POST", "account/deactivate", request_data, access_token=tok
  361. )
  362. self.assertEqual(channel.code, 200)
  363. class ThreepidEmailRestTestCase(unittest.HomeserverTestCase):
  364. servlets = [
  365. account.register_servlets,
  366. login.register_servlets,
  367. synapse.rest.admin.register_servlets_for_client_rest_resource,
  368. ]
  369. def make_homeserver(self, reactor, clock):
  370. config = self.default_config()
  371. # Email config.
  372. self.email_attempts = []
  373. async def sendmail(smtphost, from_addr, to_addrs, msg, **kwargs):
  374. self.email_attempts.append(msg)
  375. config["email"] = {
  376. "enable_notifs": False,
  377. "template_dir": os.path.abspath(
  378. pkg_resources.resource_filename("synapse", "res/templates")
  379. ),
  380. "smtp_host": "127.0.0.1",
  381. "smtp_port": 20,
  382. "require_transport_security": False,
  383. "smtp_user": None,
  384. "smtp_pass": None,
  385. "notif_from": "test@example.com",
  386. }
  387. config["public_baseurl"] = "https://example.com"
  388. self.hs = self.setup_test_homeserver(config=config, sendmail=sendmail)
  389. return self.hs
  390. def prepare(self, reactor, clock, hs):
  391. self.store = hs.get_datastore()
  392. self.user_id = self.register_user("kermit", "test")
  393. self.user_id_tok = self.login("kermit", "test")
  394. self.email = "test@example.com"
  395. self.url_3pid = b"account/3pid"
  396. def test_add_valid_email(self):
  397. self.get_success(self._add_email(self.email, self.email))
  398. def test_add_valid_email_second_time(self):
  399. self.get_success(self._add_email(self.email, self.email))
  400. self.get_success(
  401. self._request_token_invalid_email(
  402. self.email,
  403. expected_errcode=Codes.THREEPID_IN_USE,
  404. expected_error="Email is already in use",
  405. )
  406. )
  407. def test_add_valid_email_second_time_canonicalise(self):
  408. self.get_success(self._add_email(self.email, self.email))
  409. self.get_success(
  410. self._request_token_invalid_email(
  411. "TEST@EXAMPLE.COM",
  412. expected_errcode=Codes.THREEPID_IN_USE,
  413. expected_error="Email is already in use",
  414. )
  415. )
  416. def test_add_email_no_at(self):
  417. self.get_success(
  418. self._request_token_invalid_email(
  419. "address-without-at.bar",
  420. expected_errcode=Codes.UNKNOWN,
  421. expected_error="Unable to parse email address",
  422. )
  423. )
  424. def test_add_email_two_at(self):
  425. self.get_success(
  426. self._request_token_invalid_email(
  427. "foo@foo@test.bar",
  428. expected_errcode=Codes.UNKNOWN,
  429. expected_error="Unable to parse email address",
  430. )
  431. )
  432. def test_add_email_bad_format(self):
  433. self.get_success(
  434. self._request_token_invalid_email(
  435. "user@bad.example.net@good.example.com",
  436. expected_errcode=Codes.UNKNOWN,
  437. expected_error="Unable to parse email address",
  438. )
  439. )
  440. def test_add_email_domain_to_lower(self):
  441. self.get_success(self._add_email("foo@TEST.BAR", "foo@test.bar"))
  442. def test_add_email_domain_with_umlaut(self):
  443. self.get_success(self._add_email("foo@Öumlaut.com", "foo@öumlaut.com"))
  444. def test_add_email_address_casefold(self):
  445. self.get_success(self._add_email("Strauß@Example.com", "strauss@example.com"))
  446. def test_address_trim(self):
  447. self.get_success(self._add_email(" foo@test.bar ", "foo@test.bar"))
  448. @override_config({"rc_3pid_validation": {"burst_count": 3}})
  449. def test_ratelimit_by_ip(self):
  450. """Tests that adding emails is ratelimited by IP
  451. """
  452. # We expect to be able to set three emails before getting ratelimited.
  453. self.get_success(self._add_email("foo1@test.bar", "foo1@test.bar"))
  454. self.get_success(self._add_email("foo2@test.bar", "foo2@test.bar"))
  455. self.get_success(self._add_email("foo3@test.bar", "foo3@test.bar"))
  456. with self.assertRaises(HttpResponseException) as cm:
  457. self.get_success(self._add_email("foo4@test.bar", "foo4@test.bar"))
  458. self.assertEqual(cm.exception.code, 429)
  459. def test_add_email_if_disabled(self):
  460. """Test adding email to profile when doing so is disallowed
  461. """
  462. self.hs.config.enable_3pid_changes = False
  463. client_secret = "foobar"
  464. session_id = self._request_token(self.email, client_secret)
  465. self.assertEquals(len(self.email_attempts), 1)
  466. link = self._get_link_from_email()
  467. self._validate_token(link)
  468. channel = self.make_request(
  469. "POST",
  470. b"/_matrix/client/unstable/account/3pid/add",
  471. {
  472. "client_secret": client_secret,
  473. "sid": session_id,
  474. "auth": {
  475. "type": "m.login.password",
  476. "user": self.user_id,
  477. "password": "test",
  478. },
  479. },
  480. access_token=self.user_id_tok,
  481. )
  482. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  483. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  484. # Get user
  485. channel = self.make_request(
  486. "GET", self.url_3pid, access_token=self.user_id_tok,
  487. )
  488. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  489. self.assertFalse(channel.json_body["threepids"])
  490. def test_delete_email(self):
  491. """Test deleting an email from profile
  492. """
  493. # Add a threepid
  494. self.get_success(
  495. self.store.user_add_threepid(
  496. user_id=self.user_id,
  497. medium="email",
  498. address=self.email,
  499. validated_at=0,
  500. added_at=0,
  501. )
  502. )
  503. channel = self.make_request(
  504. "POST",
  505. b"account/3pid/delete",
  506. {"medium": "email", "address": self.email},
  507. access_token=self.user_id_tok,
  508. )
  509. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  510. # Get user
  511. channel = self.make_request(
  512. "GET", self.url_3pid, access_token=self.user_id_tok,
  513. )
  514. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  515. self.assertFalse(channel.json_body["threepids"])
  516. def test_delete_email_if_disabled(self):
  517. """Test deleting an email from profile when disallowed
  518. """
  519. self.hs.config.enable_3pid_changes = False
  520. # Add a threepid
  521. self.get_success(
  522. self.store.user_add_threepid(
  523. user_id=self.user_id,
  524. medium="email",
  525. address=self.email,
  526. validated_at=0,
  527. added_at=0,
  528. )
  529. )
  530. channel = self.make_request(
  531. "POST",
  532. b"account/3pid/delete",
  533. {"medium": "email", "address": self.email},
  534. access_token=self.user_id_tok,
  535. )
  536. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  537. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  538. # Get user
  539. channel = self.make_request(
  540. "GET", self.url_3pid, access_token=self.user_id_tok,
  541. )
  542. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  543. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  544. self.assertEqual(self.email, channel.json_body["threepids"][0]["address"])
  545. def test_cant_add_email_without_clicking_link(self):
  546. """Test that we do actually need to click the link in the email
  547. """
  548. client_secret = "foobar"
  549. session_id = self._request_token(self.email, client_secret)
  550. self.assertEquals(len(self.email_attempts), 1)
  551. # Attempt to add email without clicking the link
  552. channel = self.make_request(
  553. "POST",
  554. b"/_matrix/client/unstable/account/3pid/add",
  555. {
  556. "client_secret": client_secret,
  557. "sid": session_id,
  558. "auth": {
  559. "type": "m.login.password",
  560. "user": self.user_id,
  561. "password": "test",
  562. },
  563. },
  564. access_token=self.user_id_tok,
  565. )
  566. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  567. self.assertEqual(Codes.THREEPID_AUTH_FAILED, channel.json_body["errcode"])
  568. # Get user
  569. channel = self.make_request(
  570. "GET", self.url_3pid, access_token=self.user_id_tok,
  571. )
  572. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  573. self.assertFalse(channel.json_body["threepids"])
  574. def test_no_valid_token(self):
  575. """Test that we do actually need to request a token and can't just
  576. make a session up.
  577. """
  578. client_secret = "foobar"
  579. session_id = "weasle"
  580. # Attempt to add email without even requesting an email
  581. channel = self.make_request(
  582. "POST",
  583. b"/_matrix/client/unstable/account/3pid/add",
  584. {
  585. "client_secret": client_secret,
  586. "sid": session_id,
  587. "auth": {
  588. "type": "m.login.password",
  589. "user": self.user_id,
  590. "password": "test",
  591. },
  592. },
  593. access_token=self.user_id_tok,
  594. )
  595. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  596. self.assertEqual(Codes.THREEPID_AUTH_FAILED, channel.json_body["errcode"])
  597. # Get user
  598. channel = self.make_request(
  599. "GET", self.url_3pid, access_token=self.user_id_tok,
  600. )
  601. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  602. self.assertFalse(channel.json_body["threepids"])
  603. @override_config({"next_link_domain_whitelist": None})
  604. def test_next_link(self):
  605. """Tests a valid next_link parameter value with no whitelist (good case)"""
  606. self._request_token(
  607. "something@example.com",
  608. "some_secret",
  609. next_link="https://example.com/a/good/site",
  610. expect_code=200,
  611. )
  612. @override_config({"next_link_domain_whitelist": None})
  613. def test_next_link_exotic_protocol(self):
  614. """Tests using a esoteric protocol as a next_link parameter value.
  615. Someone may be hosting a client on IPFS etc.
  616. """
  617. self._request_token(
  618. "something@example.com",
  619. "some_secret",
  620. next_link="some-protocol://abcdefghijklmopqrstuvwxyz",
  621. expect_code=200,
  622. )
  623. @override_config({"next_link_domain_whitelist": None})
  624. def test_next_link_file_uri(self):
  625. """Tests next_link parameters cannot be file URI"""
  626. # Attempt to use a next_link value that points to the local disk
  627. self._request_token(
  628. "something@example.com",
  629. "some_secret",
  630. next_link="file:///host/path",
  631. expect_code=400,
  632. )
  633. @override_config({"next_link_domain_whitelist": ["example.com", "example.org"]})
  634. def test_next_link_domain_whitelist(self):
  635. """Tests next_link parameters must fit the whitelist if provided"""
  636. # Ensure not providing a next_link parameter still works
  637. self._request_token(
  638. "something@example.com", "some_secret", next_link=None, expect_code=200,
  639. )
  640. self._request_token(
  641. "something@example.com",
  642. "some_secret",
  643. next_link="https://example.com/some/good/page",
  644. expect_code=200,
  645. )
  646. self._request_token(
  647. "something@example.com",
  648. "some_secret",
  649. next_link="https://example.org/some/also/good/page",
  650. expect_code=200,
  651. )
  652. self._request_token(
  653. "something@example.com",
  654. "some_secret",
  655. next_link="https://bad.example.org/some/bad/page",
  656. expect_code=400,
  657. )
  658. @override_config({"next_link_domain_whitelist": []})
  659. def test_empty_next_link_domain_whitelist(self):
  660. """Tests an empty next_lint_domain_whitelist value, meaning next_link is essentially
  661. disallowed
  662. """
  663. self._request_token(
  664. "something@example.com",
  665. "some_secret",
  666. next_link="https://example.com/a/page",
  667. expect_code=400,
  668. )
  669. def _request_token(
  670. self,
  671. email: str,
  672. client_secret: str,
  673. next_link: Optional[str] = None,
  674. expect_code: int = 200,
  675. ) -> str:
  676. """Request a validation token to add an email address to a user's account
  677. Args:
  678. email: The email address to validate
  679. client_secret: A secret string
  680. next_link: A link to redirect the user to after validation
  681. expect_code: Expected return code of the call
  682. Returns:
  683. The ID of the new threepid validation session
  684. """
  685. body = {"client_secret": client_secret, "email": email, "send_attempt": 1}
  686. if next_link:
  687. body["next_link"] = next_link
  688. channel = self.make_request("POST", b"account/3pid/email/requestToken", body,)
  689. if channel.code != expect_code:
  690. raise HttpResponseException(
  691. channel.code, channel.result["reason"], channel.result["body"],
  692. )
  693. return channel.json_body.get("sid")
  694. def _request_token_invalid_email(
  695. self, email, expected_errcode, expected_error, client_secret="foobar",
  696. ):
  697. channel = self.make_request(
  698. "POST",
  699. b"account/3pid/email/requestToken",
  700. {"client_secret": client_secret, "email": email, "send_attempt": 1},
  701. )
  702. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  703. self.assertEqual(expected_errcode, channel.json_body["errcode"])
  704. self.assertEqual(expected_error, channel.json_body["error"])
  705. def _validate_token(self, link):
  706. # Remove the host
  707. path = link.replace("https://example.com", "")
  708. channel = self.make_request("GET", path, shorthand=False)
  709. self.assertEquals(200, channel.code, channel.result)
  710. def _get_link_from_email(self):
  711. assert self.email_attempts, "No emails have been sent"
  712. raw_msg = self.email_attempts[-1].decode("UTF-8")
  713. mail = Parser().parsestr(raw_msg)
  714. text = None
  715. for part in mail.walk():
  716. if part.get_content_type() == "text/plain":
  717. text = part.get_payload(decode=True).decode("UTF-8")
  718. break
  719. if not text:
  720. self.fail("Could not find text portion of email to parse")
  721. match = re.search(r"https://example.com\S+", text)
  722. assert match, "Could not find link in email"
  723. return match.group(0)
  724. def _add_email(self, request_email, expected_email):
  725. """Test adding an email to profile
  726. """
  727. previous_email_attempts = len(self.email_attempts)
  728. client_secret = "foobar"
  729. session_id = self._request_token(request_email, client_secret)
  730. self.assertEquals(len(self.email_attempts) - previous_email_attempts, 1)
  731. link = self._get_link_from_email()
  732. self._validate_token(link)
  733. channel = self.make_request(
  734. "POST",
  735. b"/_matrix/client/unstable/account/3pid/add",
  736. {
  737. "client_secret": client_secret,
  738. "sid": session_id,
  739. "auth": {
  740. "type": "m.login.password",
  741. "user": self.user_id,
  742. "password": "test",
  743. },
  744. },
  745. access_token=self.user_id_tok,
  746. )
  747. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  748. # Get user
  749. channel = self.make_request(
  750. "GET", self.url_3pid, access_token=self.user_id_tok,
  751. )
  752. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  753. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  754. threepids = {threepid["address"] for threepid in channel.json_body["threepids"]}
  755. self.assertIn(expected_email, threepids)