auth.py 31 KB

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