registration.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. from typing import Optional
  17. from synapse.api.constants import RoomCreationPreset
  18. from synapse.config._base import Config, ConfigError
  19. from synapse.types import RoomAlias, UserID
  20. from synapse.util.stringutils import random_string_with_symbols, strtobool
  21. class RegistrationConfig(Config):
  22. section = "registration"
  23. def read_config(self, config, **kwargs):
  24. self.enable_registration = strtobool(
  25. str(config.get("enable_registration", False))
  26. )
  27. if "disable_registration" in config:
  28. self.enable_registration = not strtobool(
  29. str(config["disable_registration"])
  30. )
  31. self.registrations_require_3pid = config.get("registrations_require_3pid", [])
  32. self.allowed_local_3pids = config.get("allowed_local_3pids", [])
  33. self.enable_3pid_lookup = config.get("enable_3pid_lookup", True)
  34. self.registration_requires_token = config.get(
  35. "registration_requires_token", False
  36. )
  37. self.registration_shared_secret = config.get("registration_shared_secret")
  38. self.bcrypt_rounds = config.get("bcrypt_rounds", 12)
  39. account_threepid_delegates = config.get("account_threepid_delegates") or {}
  40. self.account_threepid_delegate_email = account_threepid_delegates.get("email")
  41. self.account_threepid_delegate_msisdn = account_threepid_delegates.get("msisdn")
  42. self.default_identity_server = config.get("default_identity_server")
  43. self.allow_guest_access = config.get("allow_guest_access", False)
  44. if config.get("invite_3pid_guest", False):
  45. raise ConfigError("invite_3pid_guest is no longer supported")
  46. self.auto_join_rooms = config.get("auto_join_rooms", [])
  47. for room_alias in self.auto_join_rooms:
  48. if not RoomAlias.is_valid(room_alias):
  49. raise ConfigError("Invalid auto_join_rooms entry %s" % (room_alias,))
  50. # Options for creating auto-join rooms if they do not exist yet.
  51. self.autocreate_auto_join_rooms = config.get("autocreate_auto_join_rooms", True)
  52. self.autocreate_auto_join_rooms_federated = config.get(
  53. "autocreate_auto_join_rooms_federated", True
  54. )
  55. self.autocreate_auto_join_room_preset = (
  56. config.get("autocreate_auto_join_room_preset")
  57. or RoomCreationPreset.PUBLIC_CHAT
  58. )
  59. self.auto_join_room_requires_invite = self.autocreate_auto_join_room_preset in {
  60. RoomCreationPreset.PRIVATE_CHAT,
  61. RoomCreationPreset.TRUSTED_PRIVATE_CHAT,
  62. }
  63. # Pull the creator/inviter from the configuration, this gets used to
  64. # send invites for invite-only rooms.
  65. mxid_localpart = config.get("auto_join_mxid_localpart")
  66. self.auto_join_user_id = None
  67. if mxid_localpart:
  68. # Convert the localpart to a full mxid.
  69. self.auto_join_user_id = UserID(
  70. mxid_localpart, self.root.server.server_name
  71. ).to_string()
  72. if self.autocreate_auto_join_rooms:
  73. # Ensure the preset is a known value.
  74. if self.autocreate_auto_join_room_preset not in {
  75. RoomCreationPreset.PUBLIC_CHAT,
  76. RoomCreationPreset.PRIVATE_CHAT,
  77. RoomCreationPreset.TRUSTED_PRIVATE_CHAT,
  78. }:
  79. raise ConfigError("Invalid value for autocreate_auto_join_room_preset")
  80. # If the preset requires invitations to be sent, ensure there's a
  81. # configured user to send them from.
  82. if self.auto_join_room_requires_invite:
  83. if not mxid_localpart:
  84. raise ConfigError(
  85. "The configuration option `auto_join_mxid_localpart` is required if "
  86. "`autocreate_auto_join_room_preset` is set to private_chat or trusted_private_chat, such that "
  87. "Synapse knows who to send invitations from. Please "
  88. "configure `auto_join_mxid_localpart`."
  89. )
  90. self.auto_join_rooms_for_guests = config.get("auto_join_rooms_for_guests", True)
  91. self.enable_set_displayname = config.get("enable_set_displayname", True)
  92. self.enable_set_avatar_url = config.get("enable_set_avatar_url", True)
  93. self.enable_3pid_changes = config.get("enable_3pid_changes", True)
  94. self.disable_msisdn_registration = config.get(
  95. "disable_msisdn_registration", False
  96. )
  97. session_lifetime = config.get("session_lifetime")
  98. if session_lifetime is not None:
  99. session_lifetime = self.parse_duration(session_lifetime)
  100. self.session_lifetime = session_lifetime
  101. # The `refreshable_access_token_lifetime` applies for tokens that can be renewed
  102. # using a refresh token, as per MSC2918.
  103. # If it is `None`, the refresh token mechanism is disabled.
  104. refreshable_access_token_lifetime = config.get(
  105. "refreshable_access_token_lifetime",
  106. "5m",
  107. )
  108. if refreshable_access_token_lifetime is not None:
  109. refreshable_access_token_lifetime = self.parse_duration(
  110. refreshable_access_token_lifetime
  111. )
  112. self.refreshable_access_token_lifetime: Optional[
  113. int
  114. ] = refreshable_access_token_lifetime
  115. if (
  116. self.session_lifetime is not None
  117. and "refreshable_access_token_lifetime" in config
  118. ):
  119. if self.session_lifetime < self.refreshable_access_token_lifetime:
  120. raise ConfigError(
  121. "Both `session_lifetime` and `refreshable_access_token_lifetime` "
  122. "configuration options have been set, but `refreshable_access_token_lifetime` "
  123. " exceeds `session_lifetime`!"
  124. )
  125. # The `nonrefreshable_access_token_lifetime` applies for tokens that can NOT be
  126. # refreshed using a refresh token.
  127. # If it is None, then these tokens last for the entire length of the session,
  128. # which is infinite by default.
  129. # The intention behind this configuration option is to help with requiring
  130. # all clients to use refresh tokens, if the homeserver administrator requires.
  131. nonrefreshable_access_token_lifetime = config.get(
  132. "nonrefreshable_access_token_lifetime",
  133. None,
  134. )
  135. if nonrefreshable_access_token_lifetime is not None:
  136. nonrefreshable_access_token_lifetime = self.parse_duration(
  137. nonrefreshable_access_token_lifetime
  138. )
  139. self.nonrefreshable_access_token_lifetime = nonrefreshable_access_token_lifetime
  140. if (
  141. self.session_lifetime is not None
  142. and self.nonrefreshable_access_token_lifetime is not None
  143. ):
  144. if self.session_lifetime < self.nonrefreshable_access_token_lifetime:
  145. raise ConfigError(
  146. "Both `session_lifetime` and `nonrefreshable_access_token_lifetime` "
  147. "configuration options have been set, but `nonrefreshable_access_token_lifetime` "
  148. " exceeds `session_lifetime`!"
  149. )
  150. refresh_token_lifetime = config.get("refresh_token_lifetime")
  151. if refresh_token_lifetime is not None:
  152. refresh_token_lifetime = self.parse_duration(refresh_token_lifetime)
  153. self.refresh_token_lifetime: Optional[int] = refresh_token_lifetime
  154. if (
  155. self.session_lifetime is not None
  156. and self.refresh_token_lifetime is not None
  157. ):
  158. if self.session_lifetime < self.refresh_token_lifetime:
  159. raise ConfigError(
  160. "Both `session_lifetime` and `refresh_token_lifetime` "
  161. "configuration options have been set, but `refresh_token_lifetime` "
  162. " exceeds `session_lifetime`!"
  163. )
  164. # The fallback template used for authenticating using a registration token
  165. self.registration_token_template = self.read_template("registration_token.html")
  166. # The success template used during fallback auth.
  167. self.fallback_success_template = self.read_template("auth_success.html")
  168. self.inhibit_user_in_use_error = config.get("inhibit_user_in_use_error", False)
  169. def generate_config_section(self, generate_secrets=False, **kwargs):
  170. if generate_secrets:
  171. registration_shared_secret = 'registration_shared_secret: "%s"' % (
  172. random_string_with_symbols(50),
  173. )
  174. else:
  175. registration_shared_secret = "#registration_shared_secret: <PRIVATE STRING>"
  176. return (
  177. """\
  178. ## Registration ##
  179. #
  180. # Registration can be rate-limited using the parameters in the "Ratelimiting"
  181. # section of this file.
  182. # Enable registration for new users.
  183. #
  184. #enable_registration: false
  185. # Time that a user's session remains valid for, after they log in.
  186. #
  187. # Note that this is not currently compatible with guest logins.
  188. #
  189. # Note also that this is calculated at login time: changes are not applied
  190. # retrospectively to users who have already logged in.
  191. #
  192. # By default, this is infinite.
  193. #
  194. #session_lifetime: 24h
  195. # Time that an access token remains valid for, if the session is
  196. # using refresh tokens.
  197. # For more information about refresh tokens, please see the manual.
  198. # Note that this only applies to clients which advertise support for
  199. # refresh tokens.
  200. #
  201. # Note also that this is calculated at login time and refresh time:
  202. # changes are not applied to existing sessions until they are refreshed.
  203. #
  204. # By default, this is 5 minutes.
  205. #
  206. #refreshable_access_token_lifetime: 5m
  207. # Time that a refresh token remains valid for (provided that it is not
  208. # exchanged for another one first).
  209. # This option can be used to automatically log-out inactive sessions.
  210. # Please see the manual for more information.
  211. #
  212. # Note also that this is calculated at login time and refresh time:
  213. # changes are not applied to existing sessions until they are refreshed.
  214. #
  215. # By default, this is infinite.
  216. #
  217. #refresh_token_lifetime: 24h
  218. # Time that an access token remains valid for, if the session is NOT
  219. # using refresh tokens.
  220. # Please note that not all clients support refresh tokens, so setting
  221. # this to a short value may be inconvenient for some users who will
  222. # then be logged out frequently.
  223. #
  224. # Note also that this is calculated at login time: changes are not applied
  225. # retrospectively to existing sessions for users that have already logged in.
  226. #
  227. # By default, this is infinite.
  228. #
  229. #nonrefreshable_access_token_lifetime: 24h
  230. # The user must provide all of the below types of 3PID when registering.
  231. #
  232. #registrations_require_3pid:
  233. # - email
  234. # - msisdn
  235. # Explicitly disable asking for MSISDNs from the registration
  236. # flow (overrides registrations_require_3pid if MSISDNs are set as required)
  237. #
  238. #disable_msisdn_registration: true
  239. # Mandate that users are only allowed to associate certain formats of
  240. # 3PIDs with accounts on this server.
  241. #
  242. #allowed_local_3pids:
  243. # - medium: email
  244. # pattern: '^[^@]+@matrix\\.org$'
  245. # - medium: email
  246. # pattern: '^[^@]+@vector\\.im$'
  247. # - medium: msisdn
  248. # pattern: '\\+44'
  249. # Enable 3PIDs lookup requests to identity servers from this server.
  250. #
  251. #enable_3pid_lookup: true
  252. # Require users to submit a token during registration.
  253. # Tokens can be managed using the admin API:
  254. # https://matrix-org.github.io/synapse/latest/usage/administration/admin_api/registration_tokens.html
  255. # Note that `enable_registration` must be set to `true`.
  256. # Disabling this option will not delete any tokens previously generated.
  257. # Defaults to false. Uncomment the following to require tokens:
  258. #
  259. #registration_requires_token: true
  260. # If set, allows registration of standard or admin accounts by anyone who
  261. # has the shared secret, even if registration is otherwise disabled.
  262. #
  263. %(registration_shared_secret)s
  264. # Set the number of bcrypt rounds used to generate password hash.
  265. # Larger numbers increase the work factor needed to generate the hash.
  266. # The default number is 12 (which equates to 2^12 rounds).
  267. # N.B. that increasing this will exponentially increase the time required
  268. # to register or login - e.g. 24 => 2^24 rounds which will take >20 mins.
  269. #
  270. #bcrypt_rounds: 12
  271. # Allows users to register as guests without a password/email/etc, and
  272. # participate in rooms hosted on this server which have been made
  273. # accessible to anonymous users.
  274. #
  275. #allow_guest_access: false
  276. # The identity server which we suggest that clients should use when users log
  277. # in on this server.
  278. #
  279. # (By default, no suggestion is made, so it is left up to the client.
  280. # This setting is ignored unless public_baseurl is also explicitly set.)
  281. #
  282. #default_identity_server: https://matrix.org
  283. # Handle threepid (email/phone etc) registration and password resets through a set of
  284. # *trusted* identity servers. Note that this allows the configured identity server to
  285. # reset passwords for accounts!
  286. #
  287. # Be aware that if `email` is not set, and SMTP options have not been
  288. # configured in the email config block, registration and user password resets via
  289. # email will be globally disabled.
  290. #
  291. # Additionally, if `msisdn` is not set, registration and password resets via msisdn
  292. # will be disabled regardless, and users will not be able to associate an msisdn
  293. # identifier to their account. This is due to Synapse currently not supporting
  294. # any method of sending SMS messages on its own.
  295. #
  296. # To enable using an identity server for operations regarding a particular third-party
  297. # identifier type, set the value to the URL of that identity server as shown in the
  298. # examples below.
  299. #
  300. # Servers handling the these requests must answer the `/requestToken` endpoints defined
  301. # by the Matrix Identity Service API specification:
  302. # https://matrix.org/docs/spec/identity_service/latest
  303. #
  304. account_threepid_delegates:
  305. #email: https://example.com # Delegate email sending to example.com
  306. #msisdn: http://localhost:8090 # Delegate SMS sending to this local process
  307. # Whether users are allowed to change their displayname after it has
  308. # been initially set. Useful when provisioning users based on the
  309. # contents of a third-party directory.
  310. #
  311. # Does not apply to server administrators. Defaults to 'true'
  312. #
  313. #enable_set_displayname: false
  314. # Whether users are allowed to change their avatar after it has been
  315. # initially set. Useful when provisioning users based on the contents
  316. # of a third-party directory.
  317. #
  318. # Does not apply to server administrators. Defaults to 'true'
  319. #
  320. #enable_set_avatar_url: false
  321. # Whether users can change the 3PIDs associated with their accounts
  322. # (email address and msisdn).
  323. #
  324. # Defaults to 'true'
  325. #
  326. #enable_3pid_changes: false
  327. # Users who register on this homeserver will automatically be joined
  328. # to these rooms.
  329. #
  330. # By default, any room aliases included in this list will be created
  331. # as a publicly joinable room when the first user registers for the
  332. # homeserver. This behaviour can be customised with the settings below.
  333. # If the room already exists, make certain it is a publicly joinable
  334. # room. The join rule of the room must be set to 'public'.
  335. #
  336. #auto_join_rooms:
  337. # - "#example:example.com"
  338. # Where auto_join_rooms are specified, setting this flag ensures that the
  339. # the rooms exist by creating them when the first user on the
  340. # homeserver registers.
  341. #
  342. # By default the auto-created rooms are publicly joinable from any federated
  343. # server. Use the autocreate_auto_join_rooms_federated and
  344. # autocreate_auto_join_room_preset settings below to customise this behaviour.
  345. #
  346. # Setting to false means that if the rooms are not manually created,
  347. # users cannot be auto-joined since they do not exist.
  348. #
  349. # Defaults to true. Uncomment the following line to disable automatically
  350. # creating auto-join rooms.
  351. #
  352. #autocreate_auto_join_rooms: false
  353. # Whether the auto_join_rooms that are auto-created are available via
  354. # federation. Only has an effect if autocreate_auto_join_rooms is true.
  355. #
  356. # Note that whether a room is federated cannot be modified after
  357. # creation.
  358. #
  359. # Defaults to true: the room will be joinable from other servers.
  360. # Uncomment the following to prevent users from other homeservers from
  361. # joining these rooms.
  362. #
  363. #autocreate_auto_join_rooms_federated: false
  364. # The room preset to use when auto-creating one of auto_join_rooms. Only has an
  365. # effect if autocreate_auto_join_rooms is true.
  366. #
  367. # This can be one of "public_chat", "private_chat", or "trusted_private_chat".
  368. # If a value of "private_chat" or "trusted_private_chat" is used then
  369. # auto_join_mxid_localpart must also be configured.
  370. #
  371. # Defaults to "public_chat", meaning that the room is joinable by anyone, including
  372. # federated servers if autocreate_auto_join_rooms_federated is true (the default).
  373. # Uncomment the following to require an invitation to join these rooms.
  374. #
  375. #autocreate_auto_join_room_preset: private_chat
  376. # The local part of the user id which is used to create auto_join_rooms if
  377. # autocreate_auto_join_rooms is true. If this is not provided then the
  378. # initial user account that registers will be used to create the rooms.
  379. #
  380. # The user id is also used to invite new users to any auto-join rooms which
  381. # are set to invite-only.
  382. #
  383. # It *must* be configured if autocreate_auto_join_room_preset is set to
  384. # "private_chat" or "trusted_private_chat".
  385. #
  386. # Note that this must be specified in order for new users to be correctly
  387. # invited to any auto-join rooms which have been set to invite-only (either
  388. # at the time of creation or subsequently).
  389. #
  390. # Note that, if the room already exists, this user must be joined and
  391. # have the appropriate permissions to invite new members.
  392. #
  393. #auto_join_mxid_localpart: system
  394. # When auto_join_rooms is specified, setting this flag to false prevents
  395. # guest accounts from being automatically joined to the rooms.
  396. #
  397. # Defaults to true.
  398. #
  399. #auto_join_rooms_for_guests: false
  400. # Whether to inhibit errors raised when registering a new account if the user ID
  401. # already exists. If turned on, that requests to /register/available will always
  402. # show a user ID as available, and Synapse won't raise an error when starting
  403. # a registration with a user ID that already exists. However, Synapse will still
  404. # raise an error if the registration completes and the username conflicts.
  405. #
  406. # Defaults to false.
  407. #
  408. #inhibit_user_in_use_error: true
  409. """
  410. % locals()
  411. )
  412. @staticmethod
  413. def add_arguments(parser: argparse.ArgumentParser) -> None:
  414. reg_group = parser.add_argument_group("registration")
  415. reg_group.add_argument(
  416. "--enable-registration",
  417. action="store_true",
  418. default=None,
  419. help="Enable registration for new users.",
  420. )
  421. def read_arguments(self, args: argparse.Namespace) -> None:
  422. if args.enable_registration is not None:
  423. self.enable_registration = strtobool(str(args.enable_registration))