register.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015 - 2016 OpenMarket Ltd
  3. # Copyright 2017 Vector Creations Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import hmac
  17. import logging
  18. import random
  19. from typing import List, Union
  20. import synapse
  21. import synapse.api.auth
  22. import synapse.types
  23. from synapse.api.constants import LoginType
  24. from synapse.api.errors import (
  25. Codes,
  26. InteractiveAuthIncompleteError,
  27. SynapseError,
  28. ThreepidValidationError,
  29. UnrecognizedRequestError,
  30. )
  31. from synapse.config import ConfigError
  32. from synapse.config.captcha import CaptchaConfig
  33. from synapse.config.consent_config import ConsentConfig
  34. from synapse.config.emailconfig import ThreepidBehaviour
  35. from synapse.config.ratelimiting import FederationRateLimitConfig
  36. from synapse.config.registration import RegistrationConfig
  37. from synapse.config.server import is_threepid_reserved
  38. from synapse.handlers.auth import AuthHandler
  39. from synapse.handlers.ui_auth import UIAuthSessionDataConstants
  40. from synapse.http.server import finish_request, respond_with_html
  41. from synapse.http.servlet import (
  42. RestServlet,
  43. assert_params_in_dict,
  44. parse_json_object_from_request,
  45. parse_string,
  46. )
  47. from synapse.metrics import threepid_send_requests
  48. from synapse.push.mailer import Mailer
  49. from synapse.util.msisdn import phone_number_to_msisdn
  50. from synapse.util.ratelimitutils import FederationRateLimiter
  51. from synapse.util.stringutils import assert_valid_client_secret, random_string
  52. from synapse.util.threepids import canonicalise_email, check_3pid_allowed
  53. from ._base import client_patterns, interactive_auth_handler
  54. # We ought to be using hmac.compare_digest() but on older pythons it doesn't
  55. # exist. It's a _really minor_ security flaw to use plain string comparison
  56. # because the timing attack is so obscured by all the other code here it's
  57. # unlikely to make much difference
  58. if hasattr(hmac, "compare_digest"):
  59. compare_digest = hmac.compare_digest
  60. else:
  61. def compare_digest(a, b):
  62. return a == b
  63. logger = logging.getLogger(__name__)
  64. class EmailRegisterRequestTokenRestServlet(RestServlet):
  65. PATTERNS = client_patterns("/register/email/requestToken$")
  66. def __init__(self, hs):
  67. """
  68. Args:
  69. hs (synapse.server.HomeServer): server
  70. """
  71. super().__init__()
  72. self.hs = hs
  73. self.identity_handler = hs.get_identity_handler()
  74. self.config = hs.config
  75. if self.hs.config.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  76. self.mailer = Mailer(
  77. hs=self.hs,
  78. app_name=self.config.email_app_name,
  79. template_html=self.config.email_registration_template_html,
  80. template_text=self.config.email_registration_template_text,
  81. )
  82. async def on_POST(self, request):
  83. if self.hs.config.threepid_behaviour_email == ThreepidBehaviour.OFF:
  84. if self.hs.config.local_threepid_handling_disabled_due_to_email_config:
  85. logger.warning(
  86. "Email registration has been disabled due to lack of email config"
  87. )
  88. raise SynapseError(
  89. 400, "Email-based registration has been disabled on this server"
  90. )
  91. body = parse_json_object_from_request(request)
  92. assert_params_in_dict(body, ["client_secret", "email", "send_attempt"])
  93. # Extract params from body
  94. client_secret = body["client_secret"]
  95. assert_valid_client_secret(client_secret)
  96. # For emails, canonicalise the address.
  97. # We store all email addresses canonicalised in the DB.
  98. # (See on_POST in EmailThreepidRequestTokenRestServlet
  99. # in synapse/rest/client/v2_alpha/account.py)
  100. try:
  101. email = canonicalise_email(body["email"])
  102. except ValueError as e:
  103. raise SynapseError(400, str(e))
  104. send_attempt = body["send_attempt"]
  105. next_link = body.get("next_link") # Optional param
  106. if not check_3pid_allowed(self.hs, "email", email):
  107. raise SynapseError(
  108. 403,
  109. "Your email domain is not authorized to register on this server",
  110. Codes.THREEPID_DENIED,
  111. )
  112. self.identity_handler.ratelimit_request_token_requests(request, "email", email)
  113. existing_user_id = await self.hs.get_datastore().get_user_id_by_threepid(
  114. "email", email
  115. )
  116. if existing_user_id is not None:
  117. if self.hs.config.request_token_inhibit_3pid_errors:
  118. # Make the client think the operation succeeded. See the rationale in the
  119. # comments for request_token_inhibit_3pid_errors.
  120. # Also wait for some random amount of time between 100ms and 1s to make it
  121. # look like we did something.
  122. await self.hs.get_clock().sleep(random.randint(1, 10) / 10)
  123. return 200, {"sid": random_string(16)}
  124. raise SynapseError(400, "Email is already in use", Codes.THREEPID_IN_USE)
  125. if self.config.threepid_behaviour_email == ThreepidBehaviour.REMOTE:
  126. assert self.hs.config.account_threepid_delegate_email
  127. # Have the configured identity server handle the request
  128. ret = await self.identity_handler.requestEmailToken(
  129. self.hs.config.account_threepid_delegate_email,
  130. email,
  131. client_secret,
  132. send_attempt,
  133. next_link,
  134. )
  135. else:
  136. # Send registration emails from Synapse
  137. sid = await self.identity_handler.send_threepid_validation(
  138. email,
  139. client_secret,
  140. send_attempt,
  141. self.mailer.send_registration_mail,
  142. next_link,
  143. )
  144. # Wrap the session id in a JSON object
  145. ret = {"sid": sid}
  146. threepid_send_requests.labels(type="email", reason="register").observe(
  147. send_attempt
  148. )
  149. return 200, ret
  150. class MsisdnRegisterRequestTokenRestServlet(RestServlet):
  151. PATTERNS = client_patterns("/register/msisdn/requestToken$")
  152. def __init__(self, hs):
  153. """
  154. Args:
  155. hs (synapse.server.HomeServer): server
  156. """
  157. super().__init__()
  158. self.hs = hs
  159. self.identity_handler = hs.get_identity_handler()
  160. async def on_POST(self, request):
  161. body = parse_json_object_from_request(request)
  162. assert_params_in_dict(
  163. body, ["client_secret", "country", "phone_number", "send_attempt"]
  164. )
  165. client_secret = body["client_secret"]
  166. assert_valid_client_secret(client_secret)
  167. country = body["country"]
  168. phone_number = body["phone_number"]
  169. send_attempt = body["send_attempt"]
  170. next_link = body.get("next_link") # Optional param
  171. msisdn = phone_number_to_msisdn(country, phone_number)
  172. if not check_3pid_allowed(self.hs, "msisdn", msisdn):
  173. raise SynapseError(
  174. 403,
  175. "Phone numbers are not authorized to register on this server",
  176. Codes.THREEPID_DENIED,
  177. )
  178. self.identity_handler.ratelimit_request_token_requests(
  179. request, "msisdn", msisdn
  180. )
  181. existing_user_id = await self.hs.get_datastore().get_user_id_by_threepid(
  182. "msisdn", msisdn
  183. )
  184. if existing_user_id is not None:
  185. if self.hs.config.request_token_inhibit_3pid_errors:
  186. # Make the client think the operation succeeded. See the rationale in the
  187. # comments for request_token_inhibit_3pid_errors.
  188. # Also wait for some random amount of time between 100ms and 1s to make it
  189. # look like we did something.
  190. await self.hs.get_clock().sleep(random.randint(1, 10) / 10)
  191. return 200, {"sid": random_string(16)}
  192. raise SynapseError(
  193. 400, "Phone number is already in use", Codes.THREEPID_IN_USE
  194. )
  195. if not self.hs.config.account_threepid_delegate_msisdn:
  196. logger.warning(
  197. "No upstream msisdn account_threepid_delegate configured on the server to "
  198. "handle this request"
  199. )
  200. raise SynapseError(
  201. 400, "Registration by phone number is not supported on this homeserver"
  202. )
  203. ret = await self.identity_handler.requestMsisdnToken(
  204. self.hs.config.account_threepid_delegate_msisdn,
  205. country,
  206. phone_number,
  207. client_secret,
  208. send_attempt,
  209. next_link,
  210. )
  211. threepid_send_requests.labels(type="msisdn", reason="register").observe(
  212. send_attempt
  213. )
  214. return 200, ret
  215. class RegistrationSubmitTokenServlet(RestServlet):
  216. """Handles registration 3PID validation token submission"""
  217. PATTERNS = client_patterns(
  218. "/registration/(?P<medium>[^/]*)/submit_token$", releases=(), unstable=True
  219. )
  220. def __init__(self, hs):
  221. """
  222. Args:
  223. hs (synapse.server.HomeServer): server
  224. """
  225. super().__init__()
  226. self.hs = hs
  227. self.auth = hs.get_auth()
  228. self.config = hs.config
  229. self.clock = hs.get_clock()
  230. self.store = hs.get_datastore()
  231. if self.config.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
  232. self._failure_email_template = (
  233. self.config.email_registration_template_failure_html
  234. )
  235. async def on_GET(self, request, medium):
  236. if medium != "email":
  237. raise SynapseError(
  238. 400, "This medium is currently not supported for registration"
  239. )
  240. if self.config.threepid_behaviour_email == ThreepidBehaviour.OFF:
  241. if self.config.local_threepid_handling_disabled_due_to_email_config:
  242. logger.warning(
  243. "User registration via email has been disabled due to lack of email config"
  244. )
  245. raise SynapseError(
  246. 400, "Email-based registration is disabled on this server"
  247. )
  248. sid = parse_string(request, "sid", required=True)
  249. client_secret = parse_string(request, "client_secret", required=True)
  250. assert_valid_client_secret(client_secret)
  251. token = parse_string(request, "token", required=True)
  252. # Attempt to validate a 3PID session
  253. try:
  254. # Mark the session as valid
  255. next_link = await self.store.validate_threepid_session(
  256. sid, client_secret, token, self.clock.time_msec()
  257. )
  258. # Perform a 302 redirect if next_link is set
  259. if next_link:
  260. if next_link.startswith("file:///"):
  261. logger.warning(
  262. "Not redirecting to next_link as it is a local file: address"
  263. )
  264. else:
  265. request.setResponseCode(302)
  266. request.setHeader("Location", next_link)
  267. finish_request(request)
  268. return None
  269. # Otherwise show the success template
  270. html = self.config.email_registration_template_success_html_content
  271. status_code = 200
  272. except ThreepidValidationError as e:
  273. status_code = e.code
  274. # Show a failure page with a reason
  275. template_vars = {"failure_reason": e.msg}
  276. html = self._failure_email_template.render(**template_vars)
  277. respond_with_html(request, status_code, html)
  278. class UsernameAvailabilityRestServlet(RestServlet):
  279. PATTERNS = client_patterns("/register/available")
  280. def __init__(self, hs):
  281. """
  282. Args:
  283. hs (synapse.server.HomeServer): server
  284. """
  285. super().__init__()
  286. self.hs = hs
  287. self.registration_handler = hs.get_registration_handler()
  288. self.ratelimiter = FederationRateLimiter(
  289. hs.get_clock(),
  290. FederationRateLimitConfig(
  291. # Time window of 2s
  292. window_size=2000,
  293. # Artificially delay requests if rate > sleep_limit/window_size
  294. sleep_limit=1,
  295. # Amount of artificial delay to apply
  296. sleep_msec=1000,
  297. # Error with 429 if more than reject_limit requests are queued
  298. reject_limit=1,
  299. # Allow 1 request at a time
  300. concurrent_requests=1,
  301. ),
  302. )
  303. async def on_GET(self, request):
  304. if not self.hs.config.enable_registration:
  305. raise SynapseError(
  306. 403, "Registration has been disabled", errcode=Codes.FORBIDDEN
  307. )
  308. ip = request.getClientIP()
  309. with self.ratelimiter.ratelimit(ip) as wait_deferred:
  310. await wait_deferred
  311. username = parse_string(request, "username", required=True)
  312. await self.registration_handler.check_username(username)
  313. return 200, {"available": True}
  314. class RegisterRestServlet(RestServlet):
  315. PATTERNS = client_patterns("/register$")
  316. def __init__(self, hs):
  317. """
  318. Args:
  319. hs (synapse.server.HomeServer): server
  320. """
  321. super().__init__()
  322. self.hs = hs
  323. self.auth = hs.get_auth()
  324. self.store = hs.get_datastore()
  325. self.auth_handler = hs.get_auth_handler()
  326. self.registration_handler = hs.get_registration_handler()
  327. self.identity_handler = hs.get_identity_handler()
  328. self.room_member_handler = hs.get_room_member_handler()
  329. self.macaroon_gen = hs.get_macaroon_generator()
  330. self.ratelimiter = hs.get_registration_ratelimiter()
  331. self.password_policy_handler = hs.get_password_policy_handler()
  332. self.clock = hs.get_clock()
  333. self._registration_enabled = self.hs.config.enable_registration
  334. self._registration_flows = _calculate_registration_flows(
  335. hs.config, self.auth_handler
  336. )
  337. @interactive_auth_handler
  338. async def on_POST(self, request):
  339. body = parse_json_object_from_request(request)
  340. client_addr = request.getClientIP()
  341. self.ratelimiter.ratelimit(client_addr, update=False)
  342. kind = b"user"
  343. if b"kind" in request.args:
  344. kind = request.args[b"kind"][0]
  345. if kind == b"guest":
  346. ret = await self._do_guest_registration(body, address=client_addr)
  347. return ret
  348. elif kind != b"user":
  349. raise UnrecognizedRequestError(
  350. "Do not understand membership kind: %s" % (kind.decode("utf8"),)
  351. )
  352. # Pull out the provided username and do basic sanity checks early since
  353. # the auth layer will store these in sessions.
  354. desired_username = None
  355. if "username" in body:
  356. if not isinstance(body["username"], str) or len(body["username"]) > 512:
  357. raise SynapseError(400, "Invalid username")
  358. desired_username = body["username"]
  359. appservice = None
  360. if self.auth.has_access_token(request):
  361. appservice = self.auth.get_appservice_by_req(request)
  362. # fork off as soon as possible for ASes which have completely
  363. # different registration flows to normal users
  364. # == Application Service Registration ==
  365. if appservice:
  366. # Set the desired user according to the AS API (which uses the
  367. # 'user' key not 'username'). Since this is a new addition, we'll
  368. # fallback to 'username' if they gave one.
  369. desired_username = body.get("user", desired_username)
  370. # XXX we should check that desired_username is valid. Currently
  371. # we give appservices carte blanche for any insanity in mxids,
  372. # because the IRC bridges rely on being able to register stupid
  373. # IDs.
  374. access_token = self.auth.get_access_token_from_request(request)
  375. if not isinstance(desired_username, str):
  376. raise SynapseError(400, "Desired Username is missing or not a string")
  377. result = await self._do_appservice_registration(
  378. desired_username, access_token, body
  379. )
  380. return 200, result
  381. # == Normal User Registration == (everyone else)
  382. if not self._registration_enabled:
  383. raise SynapseError(403, "Registration has been disabled", Codes.FORBIDDEN)
  384. # For regular registration, convert the provided username to lowercase
  385. # before attempting to register it. This should mean that people who try
  386. # to register with upper-case in their usernames don't get a nasty surprise.
  387. #
  388. # Note that we treat usernames case-insensitively in login, so they are
  389. # free to carry on imagining that their username is CrAzYh4cKeR if that
  390. # keeps them happy.
  391. if desired_username is not None:
  392. desired_username = desired_username.lower()
  393. # Check if this account is upgrading from a guest account.
  394. guest_access_token = body.get("guest_access_token", None)
  395. # Pull out the provided password and do basic sanity checks early.
  396. #
  397. # Note that we remove the password from the body since the auth layer
  398. # will store the body in the session and we don't want a plaintext
  399. # password store there.
  400. password = body.pop("password", None)
  401. if password is not None:
  402. if not isinstance(password, str) or len(password) > 512:
  403. raise SynapseError(400, "Invalid password")
  404. self.password_policy_handler.validate_password(password)
  405. if "initial_device_display_name" in body and password is None:
  406. # ignore 'initial_device_display_name' if sent without
  407. # a password to work around a client bug where it sent
  408. # the 'initial_device_display_name' param alone, wiping out
  409. # the original registration params
  410. logger.warning("Ignoring initial_device_display_name without password")
  411. del body["initial_device_display_name"]
  412. session_id = self.auth_handler.get_session_id(body)
  413. registered_user_id = None
  414. password_hash = None
  415. if session_id:
  416. # if we get a registered user id out of here, it means we previously
  417. # registered a user for this session, so we could just return the
  418. # user here. We carry on and go through the auth checks though,
  419. # for paranoia.
  420. registered_user_id = await self.auth_handler.get_session_data(
  421. session_id, UIAuthSessionDataConstants.REGISTERED_USER_ID, None
  422. )
  423. # Extract the previously-hashed password from the session.
  424. password_hash = await self.auth_handler.get_session_data(
  425. session_id, UIAuthSessionDataConstants.PASSWORD_HASH, None
  426. )
  427. # Ensure that the username is valid.
  428. if desired_username is not None:
  429. await self.registration_handler.check_username(
  430. desired_username,
  431. guest_access_token=guest_access_token,
  432. assigned_user_id=registered_user_id,
  433. )
  434. # Check if the user-interactive authentication flows are complete, if
  435. # not this will raise a user-interactive auth error.
  436. try:
  437. auth_result, params, session_id = await self.auth_handler.check_ui_auth(
  438. self._registration_flows,
  439. request,
  440. body,
  441. "register a new account",
  442. )
  443. except InteractiveAuthIncompleteError as e:
  444. # The user needs to provide more steps to complete auth.
  445. #
  446. # Hash the password and store it with the session since the client
  447. # is not required to provide the password again.
  448. #
  449. # If a password hash was previously stored we will not attempt to
  450. # re-hash and store it for efficiency. This assumes the password
  451. # does not change throughout the authentication flow, but this
  452. # should be fine since the data is meant to be consistent.
  453. if not password_hash and password:
  454. password_hash = await self.auth_handler.hash(password)
  455. await self.auth_handler.set_session_data(
  456. e.session_id,
  457. UIAuthSessionDataConstants.PASSWORD_HASH,
  458. password_hash,
  459. )
  460. raise
  461. # Check that we're not trying to register a denied 3pid.
  462. #
  463. # the user-facing checks will probably already have happened in
  464. # /register/email/requestToken when we requested a 3pid, but that's not
  465. # guaranteed.
  466. if auth_result:
  467. for login_type in [LoginType.EMAIL_IDENTITY, LoginType.MSISDN]:
  468. if login_type in auth_result:
  469. medium = auth_result[login_type]["medium"]
  470. address = auth_result[login_type]["address"]
  471. if not check_3pid_allowed(self.hs, medium, address):
  472. raise SynapseError(
  473. 403,
  474. "Third party identifiers (email/phone numbers)"
  475. + " are not authorized on this server",
  476. Codes.THREEPID_DENIED,
  477. )
  478. if registered_user_id is not None:
  479. logger.info(
  480. "Already registered user ID %r for this session", registered_user_id
  481. )
  482. # don't re-register the threepids
  483. registered = False
  484. else:
  485. # If we have a password in this request, prefer it. Otherwise, there
  486. # might be a password hash from an earlier request.
  487. if password:
  488. password_hash = await self.auth_handler.hash(password)
  489. if not password_hash:
  490. raise SynapseError(400, "Missing params: password", Codes.MISSING_PARAM)
  491. desired_username = params.get("username", None)
  492. guest_access_token = params.get("guest_access_token", None)
  493. if desired_username is not None:
  494. desired_username = desired_username.lower()
  495. threepid = None
  496. if auth_result:
  497. threepid = auth_result.get(LoginType.EMAIL_IDENTITY)
  498. # Also check that we're not trying to register a 3pid that's already
  499. # been registered.
  500. #
  501. # This has probably happened in /register/email/requestToken as well,
  502. # but if a user hits this endpoint twice then clicks on each link from
  503. # the two activation emails, they would register the same 3pid twice.
  504. for login_type in [LoginType.EMAIL_IDENTITY, LoginType.MSISDN]:
  505. if login_type in auth_result:
  506. medium = auth_result[login_type]["medium"]
  507. address = auth_result[login_type]["address"]
  508. # For emails, canonicalise the address.
  509. # We store all email addresses canonicalised in the DB.
  510. # (See on_POST in EmailThreepidRequestTokenRestServlet
  511. # in synapse/rest/client/v2_alpha/account.py)
  512. if medium == "email":
  513. try:
  514. address = canonicalise_email(address)
  515. except ValueError as e:
  516. raise SynapseError(400, str(e))
  517. existing_user_id = await self.store.get_user_id_by_threepid(
  518. medium, address
  519. )
  520. if existing_user_id is not None:
  521. raise SynapseError(
  522. 400,
  523. "%s is already in use" % medium,
  524. Codes.THREEPID_IN_USE,
  525. )
  526. entries = await self.store.get_user_agents_ips_to_ui_auth_session(
  527. session_id
  528. )
  529. registered_user_id = await self.registration_handler.register_user(
  530. localpart=desired_username,
  531. password_hash=password_hash,
  532. guest_access_token=guest_access_token,
  533. threepid=threepid,
  534. address=client_addr,
  535. user_agent_ips=entries,
  536. )
  537. # Necessary due to auth checks prior to the threepid being
  538. # written to the db
  539. if threepid:
  540. if is_threepid_reserved(
  541. self.hs.config.mau_limits_reserved_threepids, threepid
  542. ):
  543. await self.store.upsert_monthly_active_user(registered_user_id)
  544. # Remember that the user account has been registered (and the user
  545. # ID it was registered with, since it might not have been specified).
  546. await self.auth_handler.set_session_data(
  547. session_id,
  548. UIAuthSessionDataConstants.REGISTERED_USER_ID,
  549. registered_user_id,
  550. )
  551. registered = True
  552. return_dict = await self._create_registration_details(
  553. registered_user_id, params
  554. )
  555. if registered:
  556. await self.registration_handler.post_registration_actions(
  557. user_id=registered_user_id,
  558. auth_result=auth_result,
  559. access_token=return_dict.get("access_token"),
  560. )
  561. return 200, return_dict
  562. async def _do_appservice_registration(self, username, as_token, body):
  563. user_id = await self.registration_handler.appservice_register(
  564. username, as_token
  565. )
  566. return await self._create_registration_details(
  567. user_id,
  568. body,
  569. is_appservice_ghost=True,
  570. )
  571. async def _create_registration_details(
  572. self, user_id, params, is_appservice_ghost=False
  573. ):
  574. """Complete registration of newly-registered user
  575. Allocates device_id if one was not given; also creates access_token.
  576. Args:
  577. (str) user_id: full canonical @user:id
  578. (object) params: registration parameters, from which we pull
  579. device_id, initial_device_name and inhibit_login
  580. Returns:
  581. dictionary for response from /register
  582. """
  583. result = {"user_id": user_id, "home_server": self.hs.hostname}
  584. if not params.get("inhibit_login", False):
  585. device_id = params.get("device_id")
  586. initial_display_name = params.get("initial_device_display_name")
  587. device_id, access_token = await self.registration_handler.register_device(
  588. user_id,
  589. device_id,
  590. initial_display_name,
  591. is_guest=False,
  592. is_appservice_ghost=is_appservice_ghost,
  593. )
  594. result.update({"access_token": access_token, "device_id": device_id})
  595. return result
  596. async def _do_guest_registration(self, params, address=None):
  597. if not self.hs.config.allow_guest_access:
  598. raise SynapseError(403, "Guest access is disabled")
  599. user_id = await self.registration_handler.register_user(
  600. make_guest=True, address=address
  601. )
  602. # we don't allow guests to specify their own device_id, because
  603. # we have nowhere to store it.
  604. device_id = synapse.api.auth.GUEST_DEVICE_ID
  605. initial_display_name = params.get("initial_device_display_name")
  606. device_id, access_token = await self.registration_handler.register_device(
  607. user_id, device_id, initial_display_name, is_guest=True
  608. )
  609. return (
  610. 200,
  611. {
  612. "user_id": user_id,
  613. "device_id": device_id,
  614. "access_token": access_token,
  615. "home_server": self.hs.hostname,
  616. },
  617. )
  618. def _calculate_registration_flows(
  619. # technically `config` has to provide *all* of these interfaces, not just one
  620. config: Union[RegistrationConfig, ConsentConfig, CaptchaConfig],
  621. auth_handler: AuthHandler,
  622. ) -> List[List[str]]:
  623. """Get a suitable flows list for registration
  624. Args:
  625. config: server configuration
  626. auth_handler: authorization handler
  627. Returns: a list of supported flows
  628. """
  629. # FIXME: need a better error than "no auth flow found" for scenarios
  630. # where we required 3PID for registration but the user didn't give one
  631. require_email = "email" in config.registrations_require_3pid
  632. require_msisdn = "msisdn" in config.registrations_require_3pid
  633. show_msisdn = True
  634. show_email = True
  635. if config.disable_msisdn_registration:
  636. show_msisdn = False
  637. require_msisdn = False
  638. enabled_auth_types = auth_handler.get_enabled_auth_types()
  639. if LoginType.EMAIL_IDENTITY not in enabled_auth_types:
  640. show_email = False
  641. if require_email:
  642. raise ConfigError(
  643. "Configuration requires email address at registration, but email "
  644. "validation is not configured"
  645. )
  646. if LoginType.MSISDN not in enabled_auth_types:
  647. show_msisdn = False
  648. if require_msisdn:
  649. raise ConfigError(
  650. "Configuration requires msisdn at registration, but msisdn "
  651. "validation is not configured"
  652. )
  653. flows = []
  654. # only support 3PIDless registration if no 3PIDs are required
  655. if not require_email and not require_msisdn:
  656. # Add a dummy step here, otherwise if a client completes
  657. # recaptcha first we'll assume they were going for this flow
  658. # and complete the request, when they could have been trying to
  659. # complete one of the flows with email/msisdn auth.
  660. flows.append([LoginType.DUMMY])
  661. # only support the email-only flow if we don't require MSISDN 3PIDs
  662. if show_email and not require_msisdn:
  663. flows.append([LoginType.EMAIL_IDENTITY])
  664. # only support the MSISDN-only flow if we don't require email 3PIDs
  665. if show_msisdn and not require_email:
  666. flows.append([LoginType.MSISDN])
  667. if show_email and show_msisdn:
  668. # always let users provide both MSISDN & email
  669. flows.append([LoginType.MSISDN, LoginType.EMAIL_IDENTITY])
  670. # Prepend m.login.terms to all flows if we're requiring consent
  671. if config.user_consent_at_registration:
  672. for flow in flows:
  673. flow.insert(0, LoginType.TERMS)
  674. # Prepend recaptcha to all flows if we're requiring captcha
  675. if config.enable_registration_captcha:
  676. for flow in flows:
  677. flow.insert(0, LoginType.RECAPTCHA)
  678. return flows
  679. def register_servlets(hs, http_server):
  680. EmailRegisterRequestTokenRestServlet(hs).register(http_server)
  681. MsisdnRegisterRequestTokenRestServlet(hs).register(http_server)
  682. UsernameAvailabilityRestServlet(hs).register(http_server)
  683. RegistrationSubmitTokenServlet(hs).register(http_server)
  684. RegisterRestServlet(hs).register(http_server)