auth.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 2016 OpenMarket Ltd
  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 logging
  16. from six import itervalues
  17. import pymacaroons
  18. from netaddr import IPAddress
  19. from twisted.internet import defer
  20. import synapse.logging.opentracing as opentracing
  21. import synapse.types
  22. from synapse import event_auth
  23. from synapse.api.constants import EventTypes, JoinRules, Membership
  24. from synapse.api.errors import (
  25. AuthError,
  26. Codes,
  27. InvalidClientTokenError,
  28. MissingClientTokenError,
  29. ResourceLimitError,
  30. )
  31. from synapse.config.server import is_threepid_reserved
  32. from synapse.types import UserID
  33. from synapse.util.caches import CACHE_SIZE_FACTOR, register_cache
  34. from synapse.util.caches.lrucache import LruCache
  35. from synapse.util.metrics import Measure
  36. logger = logging.getLogger(__name__)
  37. AuthEventTypes = (
  38. EventTypes.Create,
  39. EventTypes.Member,
  40. EventTypes.PowerLevels,
  41. EventTypes.JoinRules,
  42. EventTypes.RoomHistoryVisibility,
  43. EventTypes.ThirdPartyInvite,
  44. )
  45. # guests always get this device id.
  46. GUEST_DEVICE_ID = "guest_device"
  47. class _InvalidMacaroonException(Exception):
  48. pass
  49. class Auth(object):
  50. """
  51. FIXME: This class contains a mix of functions for authenticating users
  52. of our client-server API and authenticating events added to room graphs.
  53. """
  54. def __init__(self, hs):
  55. self.hs = hs
  56. self.clock = hs.get_clock()
  57. self.store = hs.get_datastore()
  58. self.state = hs.get_state_handler()
  59. self.token_cache = LruCache(CACHE_SIZE_FACTOR * 10000)
  60. register_cache("cache", "token_cache", self.token_cache)
  61. self._account_validity = hs.config.account_validity
  62. @defer.inlineCallbacks
  63. def check_from_context(self, room_version, event, context, do_sig_check=True):
  64. prev_state_ids = yield context.get_prev_state_ids(self.store)
  65. auth_events_ids = yield self.compute_auth_events(
  66. event, prev_state_ids, for_verification=True
  67. )
  68. auth_events = yield self.store.get_events(auth_events_ids)
  69. auth_events = {(e.type, e.state_key): e for e in itervalues(auth_events)}
  70. self.check(
  71. room_version, event, auth_events=auth_events, do_sig_check=do_sig_check
  72. )
  73. def check(self, room_version, event, auth_events, do_sig_check=True):
  74. """ Checks if this event is correctly authed.
  75. Args:
  76. room_version (str): version of the room
  77. event: the event being checked.
  78. auth_events (dict: event-key -> event): the existing room state.
  79. Returns:
  80. True if the auth checks pass.
  81. """
  82. with Measure(self.clock, "auth.check"):
  83. event_auth.check(
  84. room_version, event, auth_events, do_sig_check=do_sig_check
  85. )
  86. @defer.inlineCallbacks
  87. def check_joined_room(self, room_id, user_id, current_state=None):
  88. """Check if the user is currently joined in the room
  89. Args:
  90. room_id(str): The room to check.
  91. user_id(str): The user to check.
  92. current_state(dict): Optional map of the current state of the room.
  93. If provided then that map is used to check whether they are a
  94. member of the room. Otherwise the current membership is
  95. loaded from the database.
  96. Raises:
  97. AuthError if the user is not in the room.
  98. Returns:
  99. A deferred membership event for the user if the user is in
  100. the room.
  101. """
  102. if current_state:
  103. member = current_state.get((EventTypes.Member, user_id), None)
  104. else:
  105. member = yield self.state.get_current_state(
  106. room_id=room_id, event_type=EventTypes.Member, state_key=user_id
  107. )
  108. self._check_joined_room(member, user_id, room_id)
  109. return member
  110. @defer.inlineCallbacks
  111. def check_user_was_in_room(self, room_id, user_id):
  112. """Check if the user was in the room at some point.
  113. Args:
  114. room_id(str): The room to check.
  115. user_id(str): The user to check.
  116. Raises:
  117. AuthError if the user was never in the room.
  118. Returns:
  119. A deferred membership event for the user if the user was in the
  120. room. This will be the join event if they are currently joined to
  121. the room. This will be the leave event if they have left the room.
  122. """
  123. member = yield self.state.get_current_state(
  124. room_id=room_id, event_type=EventTypes.Member, state_key=user_id
  125. )
  126. membership = member.membership if member else None
  127. if membership not in (Membership.JOIN, Membership.LEAVE):
  128. raise AuthError(403, "User %s not in room %s" % (user_id, room_id))
  129. if membership == Membership.LEAVE:
  130. forgot = yield self.store.did_forget(user_id, room_id)
  131. if forgot:
  132. raise AuthError(403, "User %s not in room %s" % (user_id, room_id))
  133. return member
  134. @defer.inlineCallbacks
  135. def check_host_in_room(self, room_id, host):
  136. with Measure(self.clock, "check_host_in_room"):
  137. latest_event_ids = yield self.store.is_host_joined(room_id, host)
  138. return latest_event_ids
  139. def _check_joined_room(self, member, user_id, room_id):
  140. if not member or member.membership != Membership.JOIN:
  141. raise AuthError(
  142. 403, "User %s not in room %s (%s)" % (user_id, room_id, repr(member))
  143. )
  144. def can_federate(self, event, auth_events):
  145. creation_event = auth_events.get((EventTypes.Create, ""))
  146. return creation_event.content.get("m.federate", True) is True
  147. def get_public_keys(self, invite_event):
  148. return event_auth.get_public_keys(invite_event)
  149. @opentracing.trace
  150. @defer.inlineCallbacks
  151. def get_user_by_req(
  152. self, request, allow_guest=False, rights="access", allow_expired=False
  153. ):
  154. """ Get a registered user's ID.
  155. Args:
  156. request - An HTTP request with an access_token query parameter.
  157. allow_expired - Whether to allow the request through even if the account is
  158. expired. If true, Synapse will still require an access token to be
  159. provided but won't check if the account it belongs to has expired. This
  160. works thanks to /login delivering access tokens regardless of accounts'
  161. expiration.
  162. Returns:
  163. defer.Deferred: resolves to a ``synapse.types.Requester`` object
  164. Raises:
  165. InvalidClientCredentialsError if no user by that token exists or the token
  166. is invalid.
  167. AuthError if access is denied for the user in the access token
  168. """
  169. try:
  170. ip_addr = self.hs.get_ip_from_request(request)
  171. user_agent = request.requestHeaders.getRawHeaders(
  172. b"User-Agent", default=[b""]
  173. )[0].decode("ascii", "surrogateescape")
  174. access_token = self.get_access_token_from_request(request)
  175. user_id, app_service = yield self._get_appservice_user_id(request)
  176. if user_id:
  177. request.authenticated_entity = user_id
  178. opentracing.set_tag("authenticated_entity", user_id)
  179. if ip_addr and self.hs.config.track_appservice_user_ips:
  180. yield self.store.insert_client_ip(
  181. user_id=user_id,
  182. access_token=access_token,
  183. ip=ip_addr,
  184. user_agent=user_agent,
  185. device_id="dummy-device", # stubbed
  186. )
  187. return synapse.types.create_requester(user_id, app_service=app_service)
  188. user_info = yield self.get_user_by_access_token(access_token, rights)
  189. user = user_info["user"]
  190. token_id = user_info["token_id"]
  191. is_guest = user_info["is_guest"]
  192. # Deny the request if the user account has expired.
  193. if self._account_validity.enabled and not allow_expired:
  194. user_id = user.to_string()
  195. expiration_ts = yield self.store.get_expiration_ts_for_user(user_id)
  196. if (
  197. expiration_ts is not None
  198. and self.clock.time_msec() >= expiration_ts
  199. ):
  200. raise AuthError(
  201. 403, "User account has expired", errcode=Codes.EXPIRED_ACCOUNT
  202. )
  203. # device_id may not be present if get_user_by_access_token has been
  204. # stubbed out.
  205. device_id = user_info.get("device_id")
  206. if user and access_token and ip_addr:
  207. yield self.store.insert_client_ip(
  208. user_id=user.to_string(),
  209. access_token=access_token,
  210. ip=ip_addr,
  211. user_agent=user_agent,
  212. device_id=device_id,
  213. )
  214. if is_guest and not allow_guest:
  215. raise AuthError(
  216. 403,
  217. "Guest access not allowed",
  218. errcode=Codes.GUEST_ACCESS_FORBIDDEN,
  219. )
  220. request.authenticated_entity = user.to_string()
  221. opentracing.set_tag("authenticated_entity", user.to_string())
  222. return synapse.types.create_requester(
  223. user, token_id, is_guest, device_id, app_service=app_service
  224. )
  225. except KeyError:
  226. raise MissingClientTokenError()
  227. @defer.inlineCallbacks
  228. def _get_appservice_user_id(self, request):
  229. app_service = self.store.get_app_service_by_token(
  230. self.get_access_token_from_request(request)
  231. )
  232. if app_service is None:
  233. return None, None
  234. if app_service.ip_range_whitelist:
  235. ip_address = IPAddress(self.hs.get_ip_from_request(request))
  236. if ip_address not in app_service.ip_range_whitelist:
  237. return None, None
  238. if b"user_id" not in request.args:
  239. return app_service.sender, app_service
  240. user_id = request.args[b"user_id"][0].decode("utf8")
  241. if app_service.sender == user_id:
  242. return app_service.sender, app_service
  243. if not app_service.is_interested_in_user(user_id):
  244. raise AuthError(403, "Application service cannot masquerade as this user.")
  245. if not (yield self.store.get_user_by_id(user_id)):
  246. raise AuthError(403, "Application service has not registered this user")
  247. return user_id, app_service
  248. @defer.inlineCallbacks
  249. def get_user_by_access_token(self, token, rights="access"):
  250. """ Validate access token and get user_id from it
  251. Args:
  252. token (str): The access token to get the user by.
  253. rights (str): The operation being performed; the access token must
  254. allow this.
  255. Returns:
  256. Deferred[dict]: dict that includes:
  257. `user` (UserID)
  258. `is_guest` (bool)
  259. `token_id` (int|None): access token id. May be None if guest
  260. `device_id` (str|None): device corresponding to access token
  261. Raises:
  262. InvalidClientCredentialsError if no user by that token exists or the token
  263. is invalid.
  264. """
  265. if rights == "access":
  266. # first look in the database
  267. r = yield self._look_up_user_by_access_token(token)
  268. if r:
  269. valid_until_ms = r["valid_until_ms"]
  270. if (
  271. valid_until_ms is not None
  272. and valid_until_ms < self.clock.time_msec()
  273. ):
  274. # there was a valid access token, but it has expired.
  275. # soft-logout the user.
  276. raise InvalidClientTokenError(
  277. msg="Access token has expired", soft_logout=True
  278. )
  279. return r
  280. # otherwise it needs to be a valid macaroon
  281. try:
  282. user_id, guest = self._parse_and_validate_macaroon(token, rights)
  283. user = UserID.from_string(user_id)
  284. if rights == "access":
  285. if not guest:
  286. # non-guest access tokens must be in the database
  287. logger.warning("Unrecognised access token - not in store.")
  288. raise InvalidClientTokenError()
  289. # Guest access tokens are not stored in the database (there can
  290. # only be one access token per guest, anyway).
  291. #
  292. # In order to prevent guest access tokens being used as regular
  293. # user access tokens (and hence getting around the invalidation
  294. # process), we look up the user id and check that it is indeed
  295. # a guest user.
  296. #
  297. # It would of course be much easier to store guest access
  298. # tokens in the database as well, but that would break existing
  299. # guest tokens.
  300. stored_user = yield self.store.get_user_by_id(user_id)
  301. if not stored_user:
  302. raise InvalidClientTokenError("Unknown user_id %s" % user_id)
  303. if not stored_user["is_guest"]:
  304. raise InvalidClientTokenError(
  305. "Guest access token used for regular user"
  306. )
  307. ret = {
  308. "user": user,
  309. "is_guest": True,
  310. "token_id": None,
  311. # all guests get the same device id
  312. "device_id": GUEST_DEVICE_ID,
  313. }
  314. elif rights == "delete_pusher":
  315. # We don't store these tokens in the database
  316. ret = {
  317. "user": user,
  318. "is_guest": False,
  319. "token_id": None,
  320. "device_id": None,
  321. }
  322. else:
  323. raise RuntimeError("Unknown rights setting %s", rights)
  324. return ret
  325. except (
  326. _InvalidMacaroonException,
  327. pymacaroons.exceptions.MacaroonException,
  328. TypeError,
  329. ValueError,
  330. ) as e:
  331. logger.warning("Invalid macaroon in auth: %s %s", type(e), e)
  332. raise InvalidClientTokenError("Invalid macaroon passed.")
  333. def _parse_and_validate_macaroon(self, token, rights="access"):
  334. """Takes a macaroon and tries to parse and validate it. This is cached
  335. if and only if rights == access and there isn't an expiry.
  336. On invalid macaroon raises _InvalidMacaroonException
  337. Returns:
  338. (user_id, is_guest)
  339. """
  340. if rights == "access":
  341. cached = self.token_cache.get(token, None)
  342. if cached:
  343. return cached
  344. try:
  345. macaroon = pymacaroons.Macaroon.deserialize(token)
  346. except Exception: # deserialize can throw more-or-less anything
  347. # doesn't look like a macaroon: treat it as an opaque token which
  348. # must be in the database.
  349. # TODO: it would be nice to get rid of this, but apparently some
  350. # people use access tokens which aren't macaroons
  351. raise _InvalidMacaroonException()
  352. try:
  353. user_id = self.get_user_id_from_macaroon(macaroon)
  354. guest = False
  355. for caveat in macaroon.caveats:
  356. if caveat.caveat_id == "guest = true":
  357. guest = True
  358. self.validate_macaroon(macaroon, rights, user_id=user_id)
  359. except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError):
  360. raise InvalidClientTokenError("Invalid macaroon passed.")
  361. if rights == "access":
  362. self.token_cache[token] = (user_id, guest)
  363. return user_id, guest
  364. def get_user_id_from_macaroon(self, macaroon):
  365. """Retrieve the user_id given by the caveats on the macaroon.
  366. Does *not* validate the macaroon.
  367. Args:
  368. macaroon (pymacaroons.Macaroon): The macaroon to validate
  369. Returns:
  370. (str) user id
  371. Raises:
  372. InvalidClientCredentialsError if there is no user_id caveat in the
  373. macaroon
  374. """
  375. user_prefix = "user_id = "
  376. for caveat in macaroon.caveats:
  377. if caveat.caveat_id.startswith(user_prefix):
  378. return caveat.caveat_id[len(user_prefix) :]
  379. raise InvalidClientTokenError("No user caveat in macaroon")
  380. def validate_macaroon(self, macaroon, type_string, user_id):
  381. """
  382. validate that a Macaroon is understood by and was signed by this server.
  383. Args:
  384. macaroon(pymacaroons.Macaroon): The macaroon to validate
  385. type_string(str): The kind of token required (e.g. "access",
  386. "delete_pusher")
  387. user_id (str): The user_id required
  388. """
  389. v = pymacaroons.Verifier()
  390. # the verifier runs a test for every caveat on the macaroon, to check
  391. # that it is met for the current request. Each caveat must match at
  392. # least one of the predicates specified by satisfy_exact or
  393. # specify_general.
  394. v.satisfy_exact("gen = 1")
  395. v.satisfy_exact("type = " + type_string)
  396. v.satisfy_exact("user_id = %s" % user_id)
  397. v.satisfy_exact("guest = true")
  398. v.satisfy_general(self._verify_expiry)
  399. # access_tokens include a nonce for uniqueness: any value is acceptable
  400. v.satisfy_general(lambda c: c.startswith("nonce = "))
  401. v.verify(macaroon, self.hs.config.macaroon_secret_key)
  402. def _verify_expiry(self, caveat):
  403. prefix = "time < "
  404. if not caveat.startswith(prefix):
  405. return False
  406. expiry = int(caveat[len(prefix) :])
  407. now = self.hs.get_clock().time_msec()
  408. return now < expiry
  409. @defer.inlineCallbacks
  410. def _look_up_user_by_access_token(self, token):
  411. ret = yield self.store.get_user_by_access_token(token)
  412. if not ret:
  413. return None
  414. # we use ret.get() below because *lots* of unit tests stub out
  415. # get_user_by_access_token in a way where it only returns a couple of
  416. # the fields.
  417. user_info = {
  418. "user": UserID.from_string(ret.get("name")),
  419. "token_id": ret.get("token_id", None),
  420. "is_guest": False,
  421. "device_id": ret.get("device_id"),
  422. "valid_until_ms": ret.get("valid_until_ms"),
  423. }
  424. return user_info
  425. def get_appservice_by_req(self, request):
  426. token = self.get_access_token_from_request(request)
  427. service = self.store.get_app_service_by_token(token)
  428. if not service:
  429. logger.warn("Unrecognised appservice access token.")
  430. raise InvalidClientTokenError()
  431. request.authenticated_entity = service.sender
  432. return defer.succeed(service)
  433. def is_server_admin(self, user):
  434. """ Check if the given user is a local server admin.
  435. Args:
  436. user (UserID): user to check
  437. Returns:
  438. bool: True if the user is an admin
  439. """
  440. return self.store.is_server_admin(user)
  441. @defer.inlineCallbacks
  442. def compute_auth_events(self, event, current_state_ids, for_verification=False):
  443. if event.type == EventTypes.Create:
  444. return []
  445. auth_ids = []
  446. key = (EventTypes.PowerLevels, "")
  447. power_level_event_id = current_state_ids.get(key)
  448. if power_level_event_id:
  449. auth_ids.append(power_level_event_id)
  450. key = (EventTypes.JoinRules, "")
  451. join_rule_event_id = current_state_ids.get(key)
  452. key = (EventTypes.Member, event.sender)
  453. member_event_id = current_state_ids.get(key)
  454. key = (EventTypes.Create, "")
  455. create_event_id = current_state_ids.get(key)
  456. if create_event_id:
  457. auth_ids.append(create_event_id)
  458. if join_rule_event_id:
  459. join_rule_event = yield self.store.get_event(join_rule_event_id)
  460. join_rule = join_rule_event.content.get("join_rule")
  461. is_public = join_rule == JoinRules.PUBLIC if join_rule else False
  462. else:
  463. is_public = False
  464. if event.type == EventTypes.Member:
  465. e_type = event.content["membership"]
  466. if e_type in [Membership.JOIN, Membership.INVITE]:
  467. if join_rule_event_id:
  468. auth_ids.append(join_rule_event_id)
  469. if e_type == Membership.JOIN:
  470. if member_event_id and not is_public:
  471. auth_ids.append(member_event_id)
  472. else:
  473. if member_event_id:
  474. auth_ids.append(member_event_id)
  475. if for_verification:
  476. key = (EventTypes.Member, event.state_key)
  477. existing_event_id = current_state_ids.get(key)
  478. if existing_event_id:
  479. auth_ids.append(existing_event_id)
  480. if e_type == Membership.INVITE:
  481. if "third_party_invite" in event.content:
  482. key = (
  483. EventTypes.ThirdPartyInvite,
  484. event.content["third_party_invite"]["signed"]["token"],
  485. )
  486. third_party_invite_id = current_state_ids.get(key)
  487. if third_party_invite_id:
  488. auth_ids.append(third_party_invite_id)
  489. elif member_event_id:
  490. member_event = yield self.store.get_event(member_event_id)
  491. if member_event.content["membership"] == Membership.JOIN:
  492. auth_ids.append(member_event.event_id)
  493. return auth_ids
  494. @defer.inlineCallbacks
  495. def check_can_change_room_list(self, room_id, user):
  496. """Check if the user is allowed to edit the room's entry in the
  497. published room list.
  498. Args:
  499. room_id (str)
  500. user (UserID)
  501. """
  502. is_admin = yield self.is_server_admin(user)
  503. if is_admin:
  504. return True
  505. user_id = user.to_string()
  506. yield self.check_joined_room(room_id, user_id)
  507. # We currently require the user is a "moderator" in the room. We do this
  508. # by checking if they would (theoretically) be able to change the
  509. # m.room.aliases events
  510. power_level_event = yield self.state.get_current_state(
  511. room_id, EventTypes.PowerLevels, ""
  512. )
  513. auth_events = {}
  514. if power_level_event:
  515. auth_events[(EventTypes.PowerLevels, "")] = power_level_event
  516. send_level = event_auth.get_send_level(
  517. EventTypes.Aliases, "", power_level_event
  518. )
  519. user_level = event_auth.get_user_power_level(user_id, auth_events)
  520. if user_level < send_level:
  521. raise AuthError(
  522. 403,
  523. "This server requires you to be a moderator in the room to"
  524. " edit its room list entry",
  525. )
  526. @staticmethod
  527. def has_access_token(request):
  528. """Checks if the request has an access_token.
  529. Returns:
  530. bool: False if no access_token was given, True otherwise.
  531. """
  532. query_params = request.args.get(b"access_token")
  533. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  534. return bool(query_params) or bool(auth_headers)
  535. @staticmethod
  536. def get_access_token_from_request(request):
  537. """Extracts the access_token from the request.
  538. Args:
  539. request: The http request.
  540. Returns:
  541. unicode: The access_token
  542. Raises:
  543. MissingClientTokenError: If there isn't a single access_token in the
  544. request
  545. """
  546. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  547. query_params = request.args.get(b"access_token")
  548. if auth_headers:
  549. # Try the get the access_token from a "Authorization: Bearer"
  550. # header
  551. if query_params is not None:
  552. raise MissingClientTokenError(
  553. "Mixing Authorization headers and access_token query parameters."
  554. )
  555. if len(auth_headers) > 1:
  556. raise MissingClientTokenError("Too many Authorization headers.")
  557. parts = auth_headers[0].split(b" ")
  558. if parts[0] == b"Bearer" and len(parts) == 2:
  559. return parts[1].decode("ascii")
  560. else:
  561. raise MissingClientTokenError("Invalid Authorization header.")
  562. else:
  563. # Try to get the access_token from the query params.
  564. if not query_params:
  565. raise MissingClientTokenError()
  566. return query_params[0].decode("ascii")
  567. @defer.inlineCallbacks
  568. def check_in_room_or_world_readable(self, room_id, user_id):
  569. """Checks that the user is or was in the room or the room is world
  570. readable. If it isn't then an exception is raised.
  571. Returns:
  572. Deferred[tuple[str, str|None]]: Resolves to the current membership of
  573. the user in the room and the membership event ID of the user. If
  574. the user is not in the room and never has been, then
  575. `(Membership.JOIN, None)` is returned.
  576. """
  577. try:
  578. # check_user_was_in_room will return the most recent membership
  579. # event for the user if:
  580. # * The user is a non-guest user, and was ever in the room
  581. # * The user is a guest user, and has joined the room
  582. # else it will throw.
  583. member_event = yield self.check_user_was_in_room(room_id, user_id)
  584. return member_event.membership, member_event.event_id
  585. except AuthError:
  586. visibility = yield self.state.get_current_state(
  587. room_id, EventTypes.RoomHistoryVisibility, ""
  588. )
  589. if (
  590. visibility
  591. and visibility.content["history_visibility"] == "world_readable"
  592. ):
  593. return Membership.JOIN, None
  594. raise AuthError(
  595. 403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN
  596. )
  597. @defer.inlineCallbacks
  598. def check_auth_blocking(self, user_id=None, threepid=None):
  599. """Checks if the user should be rejected for some external reason,
  600. such as monthly active user limiting or global disable flag
  601. Args:
  602. user_id(str|None): If present, checks for presence against existing
  603. MAU cohort
  604. threepid(dict|None): If present, checks for presence against configured
  605. reserved threepid. Used in cases where the user is trying register
  606. with a MAU blocked server, normally they would be rejected but their
  607. threepid is on the reserved list. user_id and
  608. threepid should never be set at the same time.
  609. """
  610. # Never fail an auth check for the server notices users or support user
  611. # This can be a problem where event creation is prohibited due to blocking
  612. if user_id is not None:
  613. if user_id == self.hs.config.server_notices_mxid:
  614. return
  615. if (yield self.store.is_support_user(user_id)):
  616. return
  617. if self.hs.config.hs_disabled:
  618. raise ResourceLimitError(
  619. 403,
  620. self.hs.config.hs_disabled_message,
  621. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  622. admin_contact=self.hs.config.admin_contact,
  623. limit_type=self.hs.config.hs_disabled_limit_type,
  624. )
  625. if self.hs.config.limit_usage_by_mau is True:
  626. assert not (user_id and threepid)
  627. # If the user is already part of the MAU cohort or a trial user
  628. if user_id:
  629. timestamp = yield self.store.user_last_seen_monthly_active(user_id)
  630. if timestamp:
  631. return
  632. is_trial = yield self.store.is_trial_user(user_id)
  633. if is_trial:
  634. return
  635. elif threepid:
  636. # If the user does not exist yet, but is signing up with a
  637. # reserved threepid then pass auth check
  638. if is_threepid_reserved(
  639. self.hs.config.mau_limits_reserved_threepids, threepid
  640. ):
  641. return
  642. # Else if there is no room in the MAU bucket, bail
  643. current_mau = yield self.store.get_monthly_active_count()
  644. if current_mau >= self.hs.config.max_mau_value:
  645. raise ResourceLimitError(
  646. 403,
  647. "Monthly Active User Limit Exceeded",
  648. admin_contact=self.hs.config.admin_contact,
  649. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  650. limit_type="monthly_active_user",
  651. )