auth.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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
  24. from synapse.types import UserID
  25. from synapse.util.caches import CACHE_SIZE_FACTOR, register_cache
  26. from synapse.util.caches.lrucache import LruCache
  27. from synapse.util.metrics import Measure
  28. logger = logging.getLogger(__name__)
  29. AuthEventTypes = (
  30. EventTypes.Create, EventTypes.Member, EventTypes.PowerLevels,
  31. EventTypes.JoinRules, EventTypes.RoomHistoryVisibility,
  32. EventTypes.ThirdPartyInvite,
  33. )
  34. # guests always get this device id.
  35. GUEST_DEVICE_ID = "guest_device"
  36. class _InvalidMacaroonException(Exception):
  37. pass
  38. class Auth(object):
  39. """
  40. FIXME: This class contains a mix of functions for authenticating users
  41. of our client-server API and authenticating events added to room graphs.
  42. """
  43. def __init__(self, hs):
  44. self.hs = hs
  45. self.clock = hs.get_clock()
  46. self.store = hs.get_datastore()
  47. self.state = hs.get_state_handler()
  48. self.TOKEN_NOT_FOUND_HTTP_STATUS = 401
  49. self.token_cache = LruCache(CACHE_SIZE_FACTOR * 10000)
  50. register_cache("cache", "token_cache", self.token_cache)
  51. @defer.inlineCallbacks
  52. def check_from_context(self, event, context, do_sig_check=True):
  53. auth_events_ids = yield self.compute_auth_events(
  54. event, context.prev_state_ids, for_verification=True,
  55. )
  56. auth_events = yield self.store.get_events(auth_events_ids)
  57. auth_events = {
  58. (e.type, e.state_key): e for e in itervalues(auth_events)
  59. }
  60. self.check(event, auth_events=auth_events, do_sig_check=do_sig_check)
  61. def check(self, event, auth_events, do_sig_check=True):
  62. """ Checks if this event is correctly authed.
  63. Args:
  64. event: the event being checked.
  65. auth_events (dict: event-key -> event): the existing room state.
  66. Returns:
  67. True if the auth checks pass.
  68. """
  69. with Measure(self.clock, "auth.check"):
  70. event_auth.check(event, auth_events, do_sig_check=do_sig_check)
  71. @defer.inlineCallbacks
  72. def check_joined_room(self, room_id, user_id, current_state=None):
  73. """Check if the user is currently joined in the room
  74. Args:
  75. room_id(str): The room to check.
  76. user_id(str): The user to check.
  77. current_state(dict): Optional map of the current state of the room.
  78. If provided then that map is used to check whether they are a
  79. member of the room. Otherwise the current membership is
  80. loaded from the database.
  81. Raises:
  82. AuthError if the user is not in the room.
  83. Returns:
  84. A deferred membership event for the user if the user is in
  85. the room.
  86. """
  87. if current_state:
  88. member = current_state.get(
  89. (EventTypes.Member, user_id),
  90. None
  91. )
  92. else:
  93. member = yield self.state.get_current_state(
  94. room_id=room_id,
  95. event_type=EventTypes.Member,
  96. state_key=user_id
  97. )
  98. self._check_joined_room(member, user_id, room_id)
  99. defer.returnValue(member)
  100. @defer.inlineCallbacks
  101. def check_user_was_in_room(self, room_id, user_id):
  102. """Check if the user was in the room at some point.
  103. Args:
  104. room_id(str): The room to check.
  105. user_id(str): The user to check.
  106. Raises:
  107. AuthError if the user was never in the room.
  108. Returns:
  109. A deferred membership event for the user if the user was in the
  110. room. This will be the join event if they are currently joined to
  111. the room. This will be the leave event if they have left the room.
  112. """
  113. member = yield self.state.get_current_state(
  114. room_id=room_id,
  115. event_type=EventTypes.Member,
  116. state_key=user_id
  117. )
  118. membership = member.membership if member else None
  119. if membership not in (Membership.JOIN, Membership.LEAVE):
  120. raise AuthError(403, "User %s not in room %s" % (
  121. user_id, room_id
  122. ))
  123. if membership == Membership.LEAVE:
  124. forgot = yield self.store.did_forget(user_id, room_id)
  125. if forgot:
  126. raise AuthError(403, "User %s not in room %s" % (
  127. user_id, room_id
  128. ))
  129. defer.returnValue(member)
  130. @defer.inlineCallbacks
  131. def check_host_in_room(self, room_id, host):
  132. with Measure(self.clock, "check_host_in_room"):
  133. latest_event_ids = yield self.store.is_host_joined(room_id, host)
  134. defer.returnValue(latest_event_ids)
  135. def _check_joined_room(self, member, user_id, room_id):
  136. if not member or member.membership != Membership.JOIN:
  137. raise AuthError(403, "User %s not in room %s (%s)" % (
  138. user_id, room_id, repr(member)
  139. ))
  140. def can_federate(self, event, auth_events):
  141. creation_event = auth_events.get((EventTypes.Create, ""))
  142. return creation_event.content.get("m.federate", True) is True
  143. def get_public_keys(self, invite_event):
  144. return event_auth.get_public_keys(invite_event)
  145. @defer.inlineCallbacks
  146. def get_user_by_req(self, request, allow_guest=False, rights="access"):
  147. """ Get a registered user's ID.
  148. Args:
  149. request - An HTTP request with an access_token query parameter.
  150. Returns:
  151. defer.Deferred: resolves to a ``synapse.types.Requester`` object
  152. Raises:
  153. AuthError if no user by that token exists or the token is invalid.
  154. """
  155. # Can optionally look elsewhere in the request (e.g. headers)
  156. try:
  157. user_id, app_service = yield self._get_appservice_user_id(request)
  158. if user_id:
  159. request.authenticated_entity = user_id
  160. defer.returnValue(
  161. synapse.types.create_requester(user_id, app_service=app_service)
  162. )
  163. access_token = self.get_access_token_from_request(
  164. request, self.TOKEN_NOT_FOUND_HTTP_STATUS
  165. )
  166. user_info = yield self.get_user_by_access_token(access_token, rights)
  167. user = user_info["user"]
  168. token_id = user_info["token_id"]
  169. is_guest = user_info["is_guest"]
  170. # device_id may not be present if get_user_by_access_token has been
  171. # stubbed out.
  172. device_id = user_info.get("device_id")
  173. ip_addr = self.hs.get_ip_from_request(request)
  174. user_agent = request.requestHeaders.getRawHeaders(
  175. b"User-Agent",
  176. default=[b""]
  177. )[0]
  178. if user and access_token and ip_addr:
  179. self.store.insert_client_ip(
  180. user_id=user.to_string(),
  181. access_token=access_token,
  182. ip=ip_addr,
  183. user_agent=user_agent,
  184. device_id=device_id,
  185. )
  186. if is_guest and not allow_guest:
  187. raise AuthError(
  188. 403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN
  189. )
  190. request.authenticated_entity = user.to_string()
  191. defer.returnValue(synapse.types.create_requester(
  192. user, token_id, is_guest, device_id, app_service=app_service)
  193. )
  194. except KeyError:
  195. raise AuthError(
  196. self.TOKEN_NOT_FOUND_HTTP_STATUS, "Missing access token.",
  197. errcode=Codes.MISSING_TOKEN
  198. )
  199. @defer.inlineCallbacks
  200. def _get_appservice_user_id(self, request):
  201. app_service = self.store.get_app_service_by_token(
  202. self.get_access_token_from_request(
  203. request, self.TOKEN_NOT_FOUND_HTTP_STATUS
  204. )
  205. )
  206. if app_service is None:
  207. defer.returnValue((None, None))
  208. if app_service.ip_range_whitelist:
  209. ip_address = IPAddress(self.hs.get_ip_from_request(request))
  210. if ip_address not in app_service.ip_range_whitelist:
  211. defer.returnValue((None, None))
  212. if "user_id" not in request.args:
  213. defer.returnValue((app_service.sender, app_service))
  214. user_id = request.args["user_id"][0]
  215. if app_service.sender == user_id:
  216. defer.returnValue((app_service.sender, app_service))
  217. if not app_service.is_interested_in_user(user_id):
  218. raise AuthError(
  219. 403,
  220. "Application service cannot masquerade as this user."
  221. )
  222. if not (yield self.store.get_user_by_id(user_id)):
  223. raise AuthError(
  224. 403,
  225. "Application service has not registered this user"
  226. )
  227. defer.returnValue((user_id, app_service))
  228. @defer.inlineCallbacks
  229. def get_user_by_access_token(self, token, rights="access"):
  230. """ Validate access token and get user_id from it
  231. Args:
  232. token (str): The access token to get the user by.
  233. rights (str): The operation being performed; the access token must
  234. allow this.
  235. Returns:
  236. Deferred[dict]: dict that includes:
  237. `user` (UserID)
  238. `is_guest` (bool)
  239. `token_id` (int|None): access token id. May be None if guest
  240. `device_id` (str|None): device corresponding to access token
  241. Raises:
  242. AuthError if no user by that token exists or the token is invalid.
  243. """
  244. try:
  245. user_id, guest = self._parse_and_validate_macaroon(token, rights)
  246. except _InvalidMacaroonException:
  247. # doesn't look like a macaroon: treat it as an opaque token which
  248. # must be in the database.
  249. # TODO: it would be nice to get rid of this, but apparently some
  250. # people use access tokens which aren't macaroons
  251. r = yield self._look_up_user_by_access_token(token)
  252. defer.returnValue(r)
  253. try:
  254. user = UserID.from_string(user_id)
  255. if guest:
  256. # Guest access tokens are not stored in the database (there can
  257. # only be one access token per guest, anyway).
  258. #
  259. # In order to prevent guest access tokens being used as regular
  260. # user access tokens (and hence getting around the invalidation
  261. # process), we look up the user id and check that it is indeed
  262. # a guest user.
  263. #
  264. # It would of course be much easier to store guest access
  265. # tokens in the database as well, but that would break existing
  266. # guest tokens.
  267. stored_user = yield self.store.get_user_by_id(user_id)
  268. if not stored_user:
  269. raise AuthError(
  270. self.TOKEN_NOT_FOUND_HTTP_STATUS,
  271. "Unknown user_id %s" % user_id,
  272. errcode=Codes.UNKNOWN_TOKEN
  273. )
  274. if not stored_user["is_guest"]:
  275. raise AuthError(
  276. self.TOKEN_NOT_FOUND_HTTP_STATUS,
  277. "Guest access token used for regular user",
  278. errcode=Codes.UNKNOWN_TOKEN
  279. )
  280. ret = {
  281. "user": user,
  282. "is_guest": True,
  283. "token_id": None,
  284. # all guests get the same device id
  285. "device_id": GUEST_DEVICE_ID,
  286. }
  287. elif rights == "delete_pusher":
  288. # We don't store these tokens in the database
  289. ret = {
  290. "user": user,
  291. "is_guest": False,
  292. "token_id": None,
  293. "device_id": None,
  294. }
  295. else:
  296. # This codepath exists for several reasons:
  297. # * so that we can actually return a token ID, which is used
  298. # in some parts of the schema (where we probably ought to
  299. # use device IDs instead)
  300. # * the only way we currently have to invalidate an
  301. # access_token is by removing it from the database, so we
  302. # have to check here that it is still in the db
  303. # * some attributes (notably device_id) aren't stored in the
  304. # macaroon. They probably should be.
  305. # TODO: build the dictionary from the macaroon once the
  306. # above are fixed
  307. ret = yield self._look_up_user_by_access_token(token)
  308. if ret["user"] != user:
  309. logger.error(
  310. "Macaroon user (%s) != DB user (%s)",
  311. user,
  312. ret["user"]
  313. )
  314. raise AuthError(
  315. self.TOKEN_NOT_FOUND_HTTP_STATUS,
  316. "User mismatch in macaroon",
  317. errcode=Codes.UNKNOWN_TOKEN
  318. )
  319. defer.returnValue(ret)
  320. except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError):
  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. logger.warn("Unrecognised access token - not in store.")
  428. raise AuthError(
  429. self.TOKEN_NOT_FOUND_HTTP_STATUS, "Unrecognised access token.",
  430. errcode=Codes.UNKNOWN_TOKEN
  431. )
  432. # we use ret.get() below because *lots* of unit tests stub out
  433. # get_user_by_access_token in a way where it only returns a couple of
  434. # the fields.
  435. user_info = {
  436. "user": UserID.from_string(ret.get("name")),
  437. "token_id": ret.get("token_id", None),
  438. "is_guest": False,
  439. "device_id": ret.get("device_id"),
  440. }
  441. defer.returnValue(user_info)
  442. def get_appservice_by_req(self, request):
  443. try:
  444. token = self.get_access_token_from_request(
  445. request, self.TOKEN_NOT_FOUND_HTTP_STATUS
  446. )
  447. service = self.store.get_app_service_by_token(token)
  448. if not service:
  449. logger.warn("Unrecognised appservice access token.")
  450. raise AuthError(
  451. self.TOKEN_NOT_FOUND_HTTP_STATUS,
  452. "Unrecognised access token.",
  453. errcode=Codes.UNKNOWN_TOKEN
  454. )
  455. request.authenticated_entity = service.sender
  456. return defer.succeed(service)
  457. except KeyError:
  458. raise AuthError(
  459. self.TOKEN_NOT_FOUND_HTTP_STATUS, "Missing access token."
  460. )
  461. def is_server_admin(self, user):
  462. """ Check if the given user is a local server admin.
  463. Args:
  464. user (str): mxid of user to check
  465. Returns:
  466. bool: True if the user is an admin
  467. """
  468. return self.store.is_server_admin(user)
  469. @defer.inlineCallbacks
  470. def add_auth_events(self, builder, context):
  471. auth_ids = yield self.compute_auth_events(builder, context.prev_state_ids)
  472. auth_events_entries = yield self.store.add_event_hashes(
  473. auth_ids
  474. )
  475. builder.auth_events = auth_events_entries
  476. @defer.inlineCallbacks
  477. def compute_auth_events(self, event, current_state_ids, for_verification=False):
  478. if event.type == EventTypes.Create:
  479. defer.returnValue([])
  480. auth_ids = []
  481. key = (EventTypes.PowerLevels, "", )
  482. power_level_event_id = current_state_ids.get(key)
  483. if power_level_event_id:
  484. auth_ids.append(power_level_event_id)
  485. key = (EventTypes.JoinRules, "", )
  486. join_rule_event_id = current_state_ids.get(key)
  487. key = (EventTypes.Member, event.user_id, )
  488. member_event_id = current_state_ids.get(key)
  489. key = (EventTypes.Create, "", )
  490. create_event_id = current_state_ids.get(key)
  491. if create_event_id:
  492. auth_ids.append(create_event_id)
  493. if join_rule_event_id:
  494. join_rule_event = yield self.store.get_event(join_rule_event_id)
  495. join_rule = join_rule_event.content.get("join_rule")
  496. is_public = join_rule == JoinRules.PUBLIC if join_rule else False
  497. else:
  498. is_public = False
  499. if event.type == EventTypes.Member:
  500. e_type = event.content["membership"]
  501. if e_type in [Membership.JOIN, Membership.INVITE]:
  502. if join_rule_event_id:
  503. auth_ids.append(join_rule_event_id)
  504. if e_type == Membership.JOIN:
  505. if member_event_id and not is_public:
  506. auth_ids.append(member_event_id)
  507. else:
  508. if member_event_id:
  509. auth_ids.append(member_event_id)
  510. if for_verification:
  511. key = (EventTypes.Member, event.state_key, )
  512. existing_event_id = current_state_ids.get(key)
  513. if existing_event_id:
  514. auth_ids.append(existing_event_id)
  515. if e_type == Membership.INVITE:
  516. if "third_party_invite" in event.content:
  517. key = (
  518. EventTypes.ThirdPartyInvite,
  519. event.content["third_party_invite"]["signed"]["token"]
  520. )
  521. third_party_invite_id = current_state_ids.get(key)
  522. if third_party_invite_id:
  523. auth_ids.append(third_party_invite_id)
  524. elif member_event_id:
  525. member_event = yield self.store.get_event(member_event_id)
  526. if member_event.content["membership"] == Membership.JOIN:
  527. auth_ids.append(member_event.event_id)
  528. defer.returnValue(auth_ids)
  529. def check_redaction(self, event, auth_events):
  530. """Check whether the event sender is allowed to redact the target event.
  531. Returns:
  532. True if the the sender is allowed to redact the target event if the
  533. target event was created by them.
  534. False if the sender is allowed to redact the target event with no
  535. further checks.
  536. Raises:
  537. AuthError if the event sender is definitely not allowed to redact
  538. the target event.
  539. """
  540. return event_auth.check_redaction(event, auth_events)
  541. @defer.inlineCallbacks
  542. def check_can_change_room_list(self, room_id, user):
  543. """Check if the user is allowed to edit the room's entry in the
  544. published room list.
  545. Args:
  546. room_id (str)
  547. user (UserID)
  548. """
  549. is_admin = yield self.is_server_admin(user)
  550. if is_admin:
  551. defer.returnValue(True)
  552. user_id = user.to_string()
  553. yield self.check_joined_room(room_id, user_id)
  554. # We currently require the user is a "moderator" in the room. We do this
  555. # by checking if they would (theoretically) be able to change the
  556. # m.room.aliases events
  557. power_level_event = yield self.state.get_current_state(
  558. room_id, EventTypes.PowerLevels, ""
  559. )
  560. auth_events = {}
  561. if power_level_event:
  562. auth_events[(EventTypes.PowerLevels, "")] = power_level_event
  563. send_level = event_auth.get_send_level(
  564. EventTypes.Aliases, "", power_level_event,
  565. )
  566. user_level = event_auth.get_user_power_level(user_id, auth_events)
  567. if user_level < send_level:
  568. raise AuthError(
  569. 403,
  570. "This server requires you to be a moderator in the room to"
  571. " edit its room list entry"
  572. )
  573. @staticmethod
  574. def has_access_token(request):
  575. """Checks if the request has an access_token.
  576. Returns:
  577. bool: False if no access_token was given, True otherwise.
  578. """
  579. query_params = request.args.get("access_token")
  580. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  581. return bool(query_params) or bool(auth_headers)
  582. @staticmethod
  583. def get_access_token_from_request(request, token_not_found_http_status=401):
  584. """Extracts the access_token from the request.
  585. Args:
  586. request: The http request.
  587. token_not_found_http_status(int): The HTTP status code to set in the
  588. AuthError if the token isn't found. This is used in some of the
  589. legacy APIs to change the status code to 403 from the default of
  590. 401 since some of the old clients depended on auth errors returning
  591. 403.
  592. Returns:
  593. str: The access_token
  594. Raises:
  595. AuthError: If there isn't an access_token in the request.
  596. """
  597. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  598. query_params = request.args.get(b"access_token")
  599. if auth_headers:
  600. # Try the get the access_token from a "Authorization: Bearer"
  601. # header
  602. if query_params is not None:
  603. raise AuthError(
  604. token_not_found_http_status,
  605. "Mixing Authorization headers and access_token query parameters.",
  606. errcode=Codes.MISSING_TOKEN,
  607. )
  608. if len(auth_headers) > 1:
  609. raise AuthError(
  610. token_not_found_http_status,
  611. "Too many Authorization headers.",
  612. errcode=Codes.MISSING_TOKEN,
  613. )
  614. parts = auth_headers[0].split(" ")
  615. if parts[0] == "Bearer" and len(parts) == 2:
  616. return parts[1]
  617. else:
  618. raise AuthError(
  619. token_not_found_http_status,
  620. "Invalid Authorization header.",
  621. errcode=Codes.MISSING_TOKEN,
  622. )
  623. else:
  624. # Try to get the access_token from the query params.
  625. if not query_params:
  626. raise AuthError(
  627. token_not_found_http_status,
  628. "Missing access token.",
  629. errcode=Codes.MISSING_TOKEN
  630. )
  631. return query_params[0]