auth.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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. try:
  255. user_id, guest = self._parse_and_validate_macaroon(token, rights)
  256. except _InvalidMacaroonException:
  257. # doesn't look like a macaroon: treat it as an opaque token which
  258. # must be in the database.
  259. # TODO: it would be nice to get rid of this, but apparently some
  260. # people use access tokens which aren't macaroons
  261. r = yield self._look_up_user_by_access_token(token)
  262. defer.returnValue(r)
  263. try:
  264. user = UserID.from_string(user_id)
  265. if guest:
  266. # Guest access tokens are not stored in the database (there can
  267. # only be one access token per guest, anyway).
  268. #
  269. # In order to prevent guest access tokens being used as regular
  270. # user access tokens (and hence getting around the invalidation
  271. # process), we look up the user id and check that it is indeed
  272. # a guest user.
  273. #
  274. # It would of course be much easier to store guest access
  275. # tokens in the database as well, but that would break existing
  276. # guest tokens.
  277. stored_user = yield self.store.get_user_by_id(user_id)
  278. if not stored_user:
  279. raise AuthError(
  280. self.TOKEN_NOT_FOUND_HTTP_STATUS,
  281. "Unknown user_id %s" % user_id,
  282. errcode=Codes.UNKNOWN_TOKEN
  283. )
  284. if not stored_user["is_guest"]:
  285. raise AuthError(
  286. self.TOKEN_NOT_FOUND_HTTP_STATUS,
  287. "Guest access token used for regular user",
  288. errcode=Codes.UNKNOWN_TOKEN
  289. )
  290. ret = {
  291. "user": user,
  292. "is_guest": True,
  293. "token_id": None,
  294. # all guests get the same device id
  295. "device_id": GUEST_DEVICE_ID,
  296. }
  297. elif rights == "delete_pusher":
  298. # We don't store these tokens in the database
  299. ret = {
  300. "user": user,
  301. "is_guest": False,
  302. "token_id": None,
  303. "device_id": None,
  304. }
  305. else:
  306. # This codepath exists for several reasons:
  307. # * so that we can actually return a token ID, which is used
  308. # in some parts of the schema (where we probably ought to
  309. # use device IDs instead)
  310. # * the only way we currently have to invalidate an
  311. # access_token is by removing it from the database, so we
  312. # have to check here that it is still in the db
  313. # * some attributes (notably device_id) aren't stored in the
  314. # macaroon. They probably should be.
  315. # TODO: build the dictionary from the macaroon once the
  316. # above are fixed
  317. ret = yield self._look_up_user_by_access_token(token)
  318. if ret["user"] != user:
  319. logger.error(
  320. "Macaroon user (%s) != DB user (%s)",
  321. user,
  322. ret["user"]
  323. )
  324. raise AuthError(
  325. self.TOKEN_NOT_FOUND_HTTP_STATUS,
  326. "User mismatch in macaroon",
  327. errcode=Codes.UNKNOWN_TOKEN
  328. )
  329. defer.returnValue(ret)
  330. except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError):
  331. raise AuthError(
  332. self.TOKEN_NOT_FOUND_HTTP_STATUS, "Invalid macaroon passed.",
  333. errcode=Codes.UNKNOWN_TOKEN
  334. )
  335. def _parse_and_validate_macaroon(self, token, rights="access"):
  336. """Takes a macaroon and tries to parse and validate it. This is cached
  337. if and only if rights == access and there isn't an expiry.
  338. On invalid macaroon raises _InvalidMacaroonException
  339. Returns:
  340. (user_id, is_guest)
  341. """
  342. if rights == "access":
  343. cached = self.token_cache.get(token, None)
  344. if cached:
  345. return cached
  346. try:
  347. macaroon = pymacaroons.Macaroon.deserialize(token)
  348. except Exception: # deserialize can throw more-or-less anything
  349. # doesn't look like a macaroon: treat it as an opaque token which
  350. # must be in the database.
  351. # TODO: it would be nice to get rid of this, but apparently some
  352. # people use access tokens which aren't macaroons
  353. raise _InvalidMacaroonException()
  354. try:
  355. user_id = self.get_user_id_from_macaroon(macaroon)
  356. has_expiry = False
  357. guest = False
  358. for caveat in macaroon.caveats:
  359. if caveat.caveat_id.startswith("time "):
  360. has_expiry = True
  361. elif caveat.caveat_id == "guest = true":
  362. guest = True
  363. self.validate_macaroon(
  364. macaroon, rights, self.hs.config.expire_access_token,
  365. user_id=user_id,
  366. )
  367. except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError):
  368. raise AuthError(
  369. self.TOKEN_NOT_FOUND_HTTP_STATUS, "Invalid macaroon passed.",
  370. errcode=Codes.UNKNOWN_TOKEN
  371. )
  372. if not has_expiry and rights == "access":
  373. self.token_cache[token] = (user_id, guest)
  374. return user_id, guest
  375. def get_user_id_from_macaroon(self, macaroon):
  376. """Retrieve the user_id given by the caveats on the macaroon.
  377. Does *not* validate the macaroon.
  378. Args:
  379. macaroon (pymacaroons.Macaroon): The macaroon to validate
  380. Returns:
  381. (str) user id
  382. Raises:
  383. AuthError if there is no user_id caveat in the macaroon
  384. """
  385. user_prefix = "user_id = "
  386. for caveat in macaroon.caveats:
  387. if caveat.caveat_id.startswith(user_prefix):
  388. return caveat.caveat_id[len(user_prefix):]
  389. raise AuthError(
  390. self.TOKEN_NOT_FOUND_HTTP_STATUS, "No user caveat in macaroon",
  391. errcode=Codes.UNKNOWN_TOKEN
  392. )
  393. def validate_macaroon(self, macaroon, type_string, verify_expiry, user_id):
  394. """
  395. validate that a Macaroon is understood by and was signed by this server.
  396. Args:
  397. macaroon(pymacaroons.Macaroon): The macaroon to validate
  398. type_string(str): The kind of token required (e.g. "access",
  399. "delete_pusher")
  400. verify_expiry(bool): Whether to verify whether the macaroon has expired.
  401. user_id (str): The user_id required
  402. """
  403. v = pymacaroons.Verifier()
  404. # the verifier runs a test for every caveat on the macaroon, to check
  405. # that it is met for the current request. Each caveat must match at
  406. # least one of the predicates specified by satisfy_exact or
  407. # specify_general.
  408. v.satisfy_exact("gen = 1")
  409. v.satisfy_exact("type = " + type_string)
  410. v.satisfy_exact("user_id = %s" % user_id)
  411. v.satisfy_exact("guest = true")
  412. # verify_expiry should really always be True, but there exist access
  413. # tokens in the wild which expire when they should not, so we can't
  414. # enforce expiry yet (so we have to allow any caveat starting with
  415. # 'time < ' in access tokens).
  416. #
  417. # On the other hand, short-term login tokens (as used by CAS login, for
  418. # example) have an expiry time which we do want to enforce.
  419. if verify_expiry:
  420. v.satisfy_general(self._verify_expiry)
  421. else:
  422. v.satisfy_general(lambda c: c.startswith("time < "))
  423. # access_tokens include a nonce for uniqueness: any value is acceptable
  424. v.satisfy_general(lambda c: c.startswith("nonce = "))
  425. v.verify(macaroon, self.hs.config.macaroon_secret_key)
  426. def _verify_expiry(self, caveat):
  427. prefix = "time < "
  428. if not caveat.startswith(prefix):
  429. return False
  430. expiry = int(caveat[len(prefix):])
  431. now = self.hs.get_clock().time_msec()
  432. return now < expiry
  433. @defer.inlineCallbacks
  434. def _look_up_user_by_access_token(self, token):
  435. ret = yield self.store.get_user_by_access_token(token)
  436. if not ret:
  437. logger.warn("Unrecognised access token - not in store.")
  438. raise AuthError(
  439. self.TOKEN_NOT_FOUND_HTTP_STATUS, "Unrecognised access token.",
  440. errcode=Codes.UNKNOWN_TOKEN
  441. )
  442. # we use ret.get() below because *lots* of unit tests stub out
  443. # get_user_by_access_token in a way where it only returns a couple of
  444. # the fields.
  445. user_info = {
  446. "user": UserID.from_string(ret.get("name")),
  447. "token_id": ret.get("token_id", None),
  448. "is_guest": False,
  449. "device_id": ret.get("device_id"),
  450. }
  451. defer.returnValue(user_info)
  452. def get_appservice_by_req(self, request):
  453. try:
  454. token = self.get_access_token_from_request(
  455. request, self.TOKEN_NOT_FOUND_HTTP_STATUS
  456. )
  457. service = self.store.get_app_service_by_token(token)
  458. if not service:
  459. logger.warn("Unrecognised appservice access token.")
  460. raise AuthError(
  461. self.TOKEN_NOT_FOUND_HTTP_STATUS,
  462. "Unrecognised access token.",
  463. errcode=Codes.UNKNOWN_TOKEN
  464. )
  465. request.authenticated_entity = service.sender
  466. return defer.succeed(service)
  467. except KeyError:
  468. raise AuthError(
  469. self.TOKEN_NOT_FOUND_HTTP_STATUS, "Missing access token."
  470. )
  471. def is_server_admin(self, user):
  472. """ Check if the given user is a local server admin.
  473. Args:
  474. user (str): mxid of user to check
  475. Returns:
  476. bool: True if the user is an admin
  477. """
  478. return self.store.is_server_admin(user)
  479. @defer.inlineCallbacks
  480. def add_auth_events(self, builder, context):
  481. prev_state_ids = yield context.get_prev_state_ids(self.store)
  482. auth_ids = yield self.compute_auth_events(builder, prev_state_ids)
  483. auth_events_entries = yield self.store.add_event_hashes(
  484. auth_ids
  485. )
  486. builder.auth_events = auth_events_entries
  487. @defer.inlineCallbacks
  488. def compute_auth_events(self, event, current_state_ids, for_verification=False):
  489. if event.type == EventTypes.Create:
  490. defer.returnValue([])
  491. auth_ids = []
  492. key = (EventTypes.PowerLevels, "", )
  493. power_level_event_id = current_state_ids.get(key)
  494. if power_level_event_id:
  495. auth_ids.append(power_level_event_id)
  496. key = (EventTypes.JoinRules, "", )
  497. join_rule_event_id = current_state_ids.get(key)
  498. key = (EventTypes.Member, event.user_id, )
  499. member_event_id = current_state_ids.get(key)
  500. key = (EventTypes.Create, "", )
  501. create_event_id = current_state_ids.get(key)
  502. if create_event_id:
  503. auth_ids.append(create_event_id)
  504. if join_rule_event_id:
  505. join_rule_event = yield self.store.get_event(join_rule_event_id)
  506. join_rule = join_rule_event.content.get("join_rule")
  507. is_public = join_rule == JoinRules.PUBLIC if join_rule else False
  508. else:
  509. is_public = False
  510. if event.type == EventTypes.Member:
  511. e_type = event.content["membership"]
  512. if e_type in [Membership.JOIN, Membership.INVITE]:
  513. if join_rule_event_id:
  514. auth_ids.append(join_rule_event_id)
  515. if e_type == Membership.JOIN:
  516. if member_event_id and not is_public:
  517. auth_ids.append(member_event_id)
  518. else:
  519. if member_event_id:
  520. auth_ids.append(member_event_id)
  521. if for_verification:
  522. key = (EventTypes.Member, event.state_key, )
  523. existing_event_id = current_state_ids.get(key)
  524. if existing_event_id:
  525. auth_ids.append(existing_event_id)
  526. if e_type == Membership.INVITE:
  527. if "third_party_invite" in event.content:
  528. key = (
  529. EventTypes.ThirdPartyInvite,
  530. event.content["third_party_invite"]["signed"]["token"]
  531. )
  532. third_party_invite_id = current_state_ids.get(key)
  533. if third_party_invite_id:
  534. auth_ids.append(third_party_invite_id)
  535. elif member_event_id:
  536. member_event = yield self.store.get_event(member_event_id)
  537. if member_event.content["membership"] == Membership.JOIN:
  538. auth_ids.append(member_event.event_id)
  539. defer.returnValue(auth_ids)
  540. def check_redaction(self, event, auth_events):
  541. """Check whether the event sender is allowed to redact the target event.
  542. Returns:
  543. True if the the sender is allowed to redact the target event if the
  544. target event was created by them.
  545. False if the sender is allowed to redact the target event with no
  546. further checks.
  547. Raises:
  548. AuthError if the event sender is definitely not allowed to redact
  549. the target event.
  550. """
  551. return event_auth.check_redaction(event, auth_events)
  552. @defer.inlineCallbacks
  553. def check_can_change_room_list(self, room_id, user):
  554. """Check if the user is allowed to edit the room's entry in the
  555. published room list.
  556. Args:
  557. room_id (str)
  558. user (UserID)
  559. """
  560. is_admin = yield self.is_server_admin(user)
  561. if is_admin:
  562. defer.returnValue(True)
  563. user_id = user.to_string()
  564. yield self.check_joined_room(room_id, user_id)
  565. # We currently require the user is a "moderator" in the room. We do this
  566. # by checking if they would (theoretically) be able to change the
  567. # m.room.aliases events
  568. power_level_event = yield self.state.get_current_state(
  569. room_id, EventTypes.PowerLevels, ""
  570. )
  571. auth_events = {}
  572. if power_level_event:
  573. auth_events[(EventTypes.PowerLevels, "")] = power_level_event
  574. send_level = event_auth.get_send_level(
  575. EventTypes.Aliases, "", power_level_event,
  576. )
  577. user_level = event_auth.get_user_power_level(user_id, auth_events)
  578. if user_level < send_level:
  579. raise AuthError(
  580. 403,
  581. "This server requires you to be a moderator in the room to"
  582. " edit its room list entry"
  583. )
  584. @staticmethod
  585. def has_access_token(request):
  586. """Checks if the request has an access_token.
  587. Returns:
  588. bool: False if no access_token was given, True otherwise.
  589. """
  590. query_params = request.args.get(b"access_token")
  591. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  592. return bool(query_params) or bool(auth_headers)
  593. @staticmethod
  594. def get_access_token_from_request(request, token_not_found_http_status=401):
  595. """Extracts the access_token from the request.
  596. Args:
  597. request: The http request.
  598. token_not_found_http_status(int): The HTTP status code to set in the
  599. AuthError if the token isn't found. This is used in some of the
  600. legacy APIs to change the status code to 403 from the default of
  601. 401 since some of the old clients depended on auth errors returning
  602. 403.
  603. Returns:
  604. unicode: The access_token
  605. Raises:
  606. AuthError: If there isn't an access_token in the request.
  607. """
  608. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  609. query_params = request.args.get(b"access_token")
  610. if auth_headers:
  611. # Try the get the access_token from a "Authorization: Bearer"
  612. # header
  613. if query_params is not None:
  614. raise AuthError(
  615. token_not_found_http_status,
  616. "Mixing Authorization headers and access_token query parameters.",
  617. errcode=Codes.MISSING_TOKEN,
  618. )
  619. if len(auth_headers) > 1:
  620. raise AuthError(
  621. token_not_found_http_status,
  622. "Too many Authorization headers.",
  623. errcode=Codes.MISSING_TOKEN,
  624. )
  625. parts = auth_headers[0].split(b" ")
  626. if parts[0] == b"Bearer" and len(parts) == 2:
  627. return parts[1].decode('ascii')
  628. else:
  629. raise AuthError(
  630. token_not_found_http_status,
  631. "Invalid Authorization header.",
  632. errcode=Codes.MISSING_TOKEN,
  633. )
  634. else:
  635. # Try to get the access_token from the query params.
  636. if not query_params:
  637. raise AuthError(
  638. token_not_found_http_status,
  639. "Missing access token.",
  640. errcode=Codes.MISSING_TOKEN
  641. )
  642. return query_params[0].decode('ascii')
  643. @defer.inlineCallbacks
  644. def check_in_room_or_world_readable(self, room_id, user_id):
  645. """Checks that the user is or was in the room or the room is world
  646. readable. If it isn't then an exception is raised.
  647. Returns:
  648. Deferred[tuple[str, str|None]]: Resolves to the current membership of
  649. the user in the room and the membership event ID of the user. If
  650. the user is not in the room and never has been, then
  651. `(Membership.JOIN, None)` is returned.
  652. """
  653. try:
  654. # check_user_was_in_room will return the most recent membership
  655. # event for the user if:
  656. # * The user is a non-guest user, and was ever in the room
  657. # * The user is a guest user, and has joined the room
  658. # else it will throw.
  659. member_event = yield self.check_user_was_in_room(room_id, user_id)
  660. defer.returnValue((member_event.membership, member_event.event_id))
  661. except AuthError:
  662. visibility = yield self.state.get_current_state(
  663. room_id, EventTypes.RoomHistoryVisibility, ""
  664. )
  665. if (
  666. visibility and
  667. visibility.content["history_visibility"] == "world_readable"
  668. ):
  669. defer.returnValue((Membership.JOIN, None))
  670. return
  671. raise AuthError(
  672. 403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN
  673. )
  674. @defer.inlineCallbacks
  675. def check_auth_blocking(self, user_id=None, threepid=None):
  676. """Checks if the user should be rejected for some external reason,
  677. such as monthly active user limiting or global disable flag
  678. Args:
  679. user_id(str|None): If present, checks for presence against existing
  680. MAU cohort
  681. threepid(dict|None): If present, checks for presence against configured
  682. reserved threepid. Used in cases where the user is trying register
  683. with a MAU blocked server, normally they would be rejected but their
  684. threepid is on the reserved list. user_id and
  685. threepid should never be set at the same time.
  686. """
  687. # Never fail an auth check for the server notices users or support user
  688. # This can be a problem where event creation is prohibited due to blocking
  689. is_support = yield self.store.is_support_user(user_id)
  690. if user_id == self.hs.config.server_notices_mxid or is_support:
  691. return
  692. if self.hs.config.hs_disabled:
  693. raise ResourceLimitError(
  694. 403, self.hs.config.hs_disabled_message,
  695. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  696. admin_contact=self.hs.config.admin_contact,
  697. limit_type=self.hs.config.hs_disabled_limit_type
  698. )
  699. if self.hs.config.limit_usage_by_mau is True:
  700. assert not (user_id and threepid)
  701. # If the user is already part of the MAU cohort or a trial user
  702. if user_id:
  703. timestamp = yield self.store.user_last_seen_monthly_active(user_id)
  704. if timestamp:
  705. return
  706. is_trial = yield self.store.is_trial_user(user_id)
  707. if is_trial:
  708. return
  709. elif threepid:
  710. # If the user does not exist yet, but is signing up with a
  711. # reserved threepid then pass auth check
  712. if is_threepid_reserved(self.hs.config, threepid):
  713. return
  714. # Else if there is no room in the MAU bucket, bail
  715. current_mau = yield self.store.get_monthly_active_count()
  716. if current_mau >= self.hs.config.max_mau_value:
  717. raise ResourceLimitError(
  718. 403, "Monthly Active User Limit Exceeded",
  719. admin_contact=self.hs.config.admin_contact,
  720. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  721. limit_type="monthly_active_user"
  722. )