auth.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. # Copyright 2014 - 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Optional, Tuple
  16. import pymacaroons
  17. from netaddr import IPAddress
  18. from twisted.web.server import Request
  19. from synapse import event_auth
  20. from synapse.api.auth_blocking import AuthBlocking
  21. from synapse.api.constants import EventTypes, HistoryVisibility, Membership
  22. from synapse.api.errors import (
  23. AuthError,
  24. Codes,
  25. InvalidClientTokenError,
  26. MissingClientTokenError,
  27. )
  28. from synapse.appservice import ApplicationService
  29. from synapse.events import EventBase
  30. from synapse.http import get_request_user_agent
  31. from synapse.http.site import SynapseRequest
  32. from synapse.logging.opentracing import active_span, force_tracing, start_active_span
  33. from synapse.storage.databases.main.registration import TokenLookupResult
  34. from synapse.types import Requester, StateMap, UserID, create_requester
  35. from synapse.util.caches.lrucache import LruCache
  36. from synapse.util.macaroons import get_value_from_macaroon, satisfy_expiry
  37. if TYPE_CHECKING:
  38. from synapse.server import HomeServer
  39. logger = logging.getLogger(__name__)
  40. # guests always get this device id.
  41. GUEST_DEVICE_ID = "guest_device"
  42. class _InvalidMacaroonException(Exception):
  43. pass
  44. class Auth:
  45. """
  46. This class contains functions for authenticating users of our client-server API.
  47. """
  48. def __init__(self, hs: "HomeServer"):
  49. self.hs = hs
  50. self.clock = hs.get_clock()
  51. self.store = hs.get_datastore()
  52. self.state = hs.get_state_handler()
  53. self._account_validity_handler = hs.get_account_validity_handler()
  54. self.token_cache: LruCache[str, Tuple[str, bool]] = LruCache(
  55. 10000, "token_cache"
  56. )
  57. self._auth_blocking = AuthBlocking(self.hs)
  58. self._track_appservice_user_ips = hs.config.appservice.track_appservice_user_ips
  59. self._track_puppeted_user_ips = hs.config.api.track_puppeted_user_ips
  60. self._macaroon_secret_key = hs.config.key.macaroon_secret_key
  61. self._force_tracing_for_users = hs.config.tracing.force_tracing_for_users
  62. async def check_user_in_room(
  63. self,
  64. room_id: str,
  65. user_id: str,
  66. current_state: Optional[StateMap[EventBase]] = None,
  67. allow_departed_users: bool = False,
  68. ) -> EventBase:
  69. """Check if the user is in the room, or was at some point.
  70. Args:
  71. room_id: The room to check.
  72. user_id: The user to check.
  73. current_state: Optional map of the current state of the room.
  74. If provided then that map is used to check whether they are a
  75. member of the room. Otherwise the current membership is
  76. loaded from the database.
  77. allow_departed_users: if True, accept users that were previously
  78. members but have now departed.
  79. Raises:
  80. AuthError if the user is/was not in the room.
  81. Returns:
  82. Membership event for the user if the user was in the
  83. room. This will be the join event if they are currently joined to
  84. the room. This will be the leave event if they have left the room.
  85. """
  86. if current_state:
  87. member = current_state.get((EventTypes.Member, user_id), None)
  88. else:
  89. member = await self.state.get_current_state(
  90. room_id=room_id, event_type=EventTypes.Member, state_key=user_id
  91. )
  92. if member:
  93. membership = member.membership
  94. if membership == Membership.JOIN:
  95. return member
  96. # XXX this looks totally bogus. Why do we not allow users who have been banned,
  97. # or those who were members previously and have been re-invited?
  98. if allow_departed_users and membership == Membership.LEAVE:
  99. forgot = await self.store.did_forget(user_id, room_id)
  100. if not forgot:
  101. return member
  102. raise AuthError(403, "User %s not in room %s" % (user_id, room_id))
  103. async def get_user_by_req(
  104. self,
  105. request: SynapseRequest,
  106. allow_guest: bool = False,
  107. rights: str = "access",
  108. allow_expired: bool = False,
  109. ) -> Requester:
  110. """Get a registered user's ID.
  111. Args:
  112. request: An HTTP request with an access_token query parameter.
  113. allow_guest: If False, will raise an AuthError if the user making the
  114. request is a guest.
  115. rights: The operation being performed; the access token must allow this
  116. allow_expired: If True, allow the request through even if the account
  117. is expired, or session token lifetime has ended. Note that
  118. /login will deliver access tokens regardless of expiration.
  119. Returns:
  120. Resolves to the requester
  121. Raises:
  122. InvalidClientCredentialsError if no user by that token exists or the token
  123. is invalid.
  124. AuthError if access is denied for the user in the access token
  125. """
  126. parent_span = active_span()
  127. with start_active_span("get_user_by_req"):
  128. requester = await self._wrapped_get_user_by_req(
  129. request, allow_guest, rights, allow_expired
  130. )
  131. if parent_span:
  132. if requester.authenticated_entity in self._force_tracing_for_users:
  133. # request tracing is enabled for this user, so we need to force it
  134. # tracing on for the parent span (which will be the servlet span).
  135. #
  136. # It's too late for the get_user_by_req span to inherit the setting,
  137. # so we also force it on for that.
  138. force_tracing()
  139. force_tracing(parent_span)
  140. parent_span.set_tag(
  141. "authenticated_entity", requester.authenticated_entity
  142. )
  143. parent_span.set_tag("user_id", requester.user.to_string())
  144. if requester.device_id is not None:
  145. parent_span.set_tag("device_id", requester.device_id)
  146. if requester.app_service is not None:
  147. parent_span.set_tag("appservice_id", requester.app_service.id)
  148. return requester
  149. async def _wrapped_get_user_by_req(
  150. self,
  151. request: SynapseRequest,
  152. allow_guest: bool,
  153. rights: str,
  154. allow_expired: bool,
  155. ) -> Requester:
  156. """Helper for get_user_by_req
  157. Once get_user_by_req has set up the opentracing span, this does the actual work.
  158. """
  159. try:
  160. ip_addr = request.getClientIP()
  161. user_agent = get_request_user_agent(request)
  162. access_token = self.get_access_token_from_request(request)
  163. (
  164. user_id,
  165. device_id,
  166. app_service,
  167. ) = await self._get_appservice_user_id_and_device_id(request)
  168. if user_id and app_service:
  169. if ip_addr and self._track_appservice_user_ips:
  170. await self.store.insert_client_ip(
  171. user_id=user_id,
  172. access_token=access_token,
  173. ip=ip_addr,
  174. user_agent=user_agent,
  175. device_id="dummy-device"
  176. if device_id is None
  177. else device_id, # stubbed
  178. )
  179. requester = create_requester(
  180. user_id, app_service=app_service, device_id=device_id
  181. )
  182. request.requester = user_id
  183. return requester
  184. user_info = await self.get_user_by_access_token(
  185. access_token, rights, allow_expired=allow_expired
  186. )
  187. token_id = user_info.token_id
  188. is_guest = user_info.is_guest
  189. shadow_banned = user_info.shadow_banned
  190. # Deny the request if the user account has expired.
  191. if not allow_expired:
  192. if await self._account_validity_handler.is_user_expired(
  193. user_info.user_id
  194. ):
  195. # Raise the error if either an account validity module has determined
  196. # the account has expired, or the legacy account validity
  197. # implementation is enabled and determined the account has expired
  198. raise AuthError(
  199. 403,
  200. "User account has expired",
  201. errcode=Codes.EXPIRED_ACCOUNT,
  202. )
  203. device_id = user_info.device_id
  204. if access_token and ip_addr:
  205. await self.store.insert_client_ip(
  206. user_id=user_info.token_owner,
  207. access_token=access_token,
  208. ip=ip_addr,
  209. user_agent=user_agent,
  210. device_id=device_id,
  211. )
  212. # Track also the puppeted user client IP if enabled and the user is puppeting
  213. if (
  214. user_info.user_id != user_info.token_owner
  215. and self._track_puppeted_user_ips
  216. ):
  217. await self.store.insert_client_ip(
  218. user_id=user_info.user_id,
  219. access_token=access_token,
  220. ip=ip_addr,
  221. user_agent=user_agent,
  222. device_id=device_id,
  223. )
  224. if is_guest and not allow_guest:
  225. raise AuthError(
  226. 403,
  227. "Guest access not allowed",
  228. errcode=Codes.GUEST_ACCESS_FORBIDDEN,
  229. )
  230. # Mark the token as used. This is used to invalidate old refresh
  231. # tokens after some time.
  232. if not user_info.token_used and token_id is not None:
  233. await self.store.mark_access_token_as_used(token_id)
  234. requester = create_requester(
  235. user_info.user_id,
  236. token_id,
  237. is_guest,
  238. shadow_banned,
  239. device_id,
  240. app_service=app_service,
  241. authenticated_entity=user_info.token_owner,
  242. )
  243. request.requester = requester
  244. return requester
  245. except KeyError:
  246. raise MissingClientTokenError()
  247. async def validate_appservice_can_control_user_id(
  248. self, app_service: ApplicationService, user_id: str
  249. ) -> None:
  250. """Validates that the app service is allowed to control
  251. the given user.
  252. Args:
  253. app_service: The app service that controls the user
  254. user_id: The author MXID that the app service is controlling
  255. Raises:
  256. AuthError: If the application service is not allowed to control the user
  257. (user namespace regex does not match, wrong homeserver, etc)
  258. or if the user has not been registered yet.
  259. """
  260. # It's ok if the app service is trying to use the sender from their registration
  261. if app_service.sender == user_id:
  262. pass
  263. # Check to make sure the app service is allowed to control the user
  264. elif not app_service.is_interested_in_user(user_id):
  265. raise AuthError(
  266. 403,
  267. "Application service cannot masquerade as this user (%s)." % user_id,
  268. )
  269. # Check to make sure the user is already registered on the homeserver
  270. elif not (await self.store.get_user_by_id(user_id)):
  271. raise AuthError(
  272. 403, "Application service has not registered this user (%s)" % user_id
  273. )
  274. async def _get_appservice_user_id_and_device_id(
  275. self, request: Request
  276. ) -> Tuple[Optional[str], Optional[str], Optional[ApplicationService]]:
  277. """
  278. Given a request, reads the request parameters to determine:
  279. - whether it's an application service that's making this request
  280. - what user the application service should be treated as controlling
  281. (the user_id URI parameter allows an application service to masquerade
  282. any applicable user in its namespace)
  283. - what device the application service should be treated as controlling
  284. (the device_id[^1] URI parameter allows an application service to masquerade
  285. as any device that exists for the relevant user)
  286. [^1] Unstable and provided by MSC3202.
  287. Must use `org.matrix.msc3202.device_id` in place of `device_id` for now.
  288. Returns:
  289. 3-tuple of
  290. (user ID?, device ID?, application service?)
  291. Postconditions:
  292. - If an application service is returned, so is a user ID
  293. - A user ID is never returned without an application service
  294. - A device ID is never returned without a user ID or an application service
  295. - The returned application service, if present, is permitted to control the
  296. returned user ID.
  297. - The returned device ID, if present, has been checked to be a valid device ID
  298. for the returned user ID.
  299. """
  300. DEVICE_ID_ARG_NAME = b"org.matrix.msc3202.device_id"
  301. app_service = self.store.get_app_service_by_token(
  302. self.get_access_token_from_request(request)
  303. )
  304. if app_service is None:
  305. return None, None, None
  306. if app_service.ip_range_whitelist:
  307. ip_address = IPAddress(request.getClientIP())
  308. if ip_address not in app_service.ip_range_whitelist:
  309. return None, None, None
  310. # This will always be set by the time Twisted calls us.
  311. assert request.args is not None
  312. if b"user_id" in request.args:
  313. effective_user_id = request.args[b"user_id"][0].decode("utf8")
  314. await self.validate_appservice_can_control_user_id(
  315. app_service, effective_user_id
  316. )
  317. else:
  318. effective_user_id = app_service.sender
  319. effective_device_id: Optional[str] = None
  320. if (
  321. self.hs.config.experimental.msc3202_device_masquerading_enabled
  322. and DEVICE_ID_ARG_NAME in request.args
  323. ):
  324. effective_device_id = request.args[DEVICE_ID_ARG_NAME][0].decode("utf8")
  325. # We only just set this so it can't be None!
  326. assert effective_device_id is not None
  327. device_opt = await self.store.get_device(
  328. effective_user_id, effective_device_id
  329. )
  330. if device_opt is None:
  331. # For now, use 400 M_EXCLUSIVE if the device doesn't exist.
  332. # This is an open thread of discussion on MSC3202 as of 2021-12-09.
  333. raise AuthError(
  334. 400,
  335. f"Application service trying to use a device that doesn't exist ('{effective_device_id}' for {effective_user_id})",
  336. Codes.EXCLUSIVE,
  337. )
  338. return effective_user_id, effective_device_id, app_service
  339. async def get_user_by_access_token(
  340. self,
  341. token: str,
  342. rights: str = "access",
  343. allow_expired: bool = False,
  344. ) -> TokenLookupResult:
  345. """Validate access token and get user_id from it
  346. Args:
  347. token: The access token to get the user by
  348. rights: The operation being performed; the access token must
  349. allow this
  350. allow_expired: If False, raises an InvalidClientTokenError
  351. if the token is expired
  352. Raises:
  353. InvalidClientTokenError if a user by that token exists, but the token is
  354. expired
  355. InvalidClientCredentialsError if no user by that token exists or the token
  356. is invalid
  357. """
  358. if rights == "access":
  359. # first look in the database
  360. r = await self.store.get_user_by_access_token(token)
  361. if r:
  362. valid_until_ms = r.valid_until_ms
  363. if (
  364. not allow_expired
  365. and valid_until_ms is not None
  366. and valid_until_ms < self.clock.time_msec()
  367. ):
  368. # there was a valid access token, but it has expired.
  369. # soft-logout the user.
  370. raise InvalidClientTokenError(
  371. msg="Access token has expired", soft_logout=True
  372. )
  373. return r
  374. # otherwise it needs to be a valid macaroon
  375. try:
  376. user_id, guest = self._parse_and_validate_macaroon(token, rights)
  377. if rights == "access":
  378. if not guest:
  379. # non-guest access tokens must be in the database
  380. logger.warning("Unrecognised access token - not in store.")
  381. raise InvalidClientTokenError()
  382. # Guest access tokens are not stored in the database (there can
  383. # only be one access token per guest, anyway).
  384. #
  385. # In order to prevent guest access tokens being used as regular
  386. # user access tokens (and hence getting around the invalidation
  387. # process), we look up the user id and check that it is indeed
  388. # a guest user.
  389. #
  390. # It would of course be much easier to store guest access
  391. # tokens in the database as well, but that would break existing
  392. # guest tokens.
  393. stored_user = await self.store.get_user_by_id(user_id)
  394. if not stored_user:
  395. raise InvalidClientTokenError("Unknown user_id %s" % user_id)
  396. if not stored_user["is_guest"]:
  397. raise InvalidClientTokenError(
  398. "Guest access token used for regular user"
  399. )
  400. ret = TokenLookupResult(
  401. user_id=user_id,
  402. is_guest=True,
  403. # all guests get the same device id
  404. device_id=GUEST_DEVICE_ID,
  405. )
  406. elif rights == "delete_pusher":
  407. # We don't store these tokens in the database
  408. ret = TokenLookupResult(user_id=user_id, is_guest=False)
  409. else:
  410. raise RuntimeError("Unknown rights setting %s", rights)
  411. return ret
  412. except (
  413. _InvalidMacaroonException,
  414. pymacaroons.exceptions.MacaroonException,
  415. TypeError,
  416. ValueError,
  417. ) as e:
  418. logger.warning("Invalid macaroon in auth: %s %s", type(e), e)
  419. raise InvalidClientTokenError("Invalid macaroon passed.")
  420. def _parse_and_validate_macaroon(
  421. self, token: str, rights: str = "access"
  422. ) -> Tuple[str, bool]:
  423. """Takes a macaroon and tries to parse and validate it. This is cached
  424. if and only if rights == access and there isn't an expiry.
  425. On invalid macaroon raises _InvalidMacaroonException
  426. Returns:
  427. (user_id, is_guest)
  428. """
  429. if rights == "access":
  430. cached = self.token_cache.get(token, None)
  431. if cached:
  432. return cached
  433. try:
  434. macaroon = pymacaroons.Macaroon.deserialize(token)
  435. except Exception: # deserialize can throw more-or-less anything
  436. # doesn't look like a macaroon: treat it as an opaque token which
  437. # must be in the database.
  438. # TODO: it would be nice to get rid of this, but apparently some
  439. # people use access tokens which aren't macaroons
  440. raise _InvalidMacaroonException()
  441. try:
  442. user_id = get_value_from_macaroon(macaroon, "user_id")
  443. guest = False
  444. for caveat in macaroon.caveats:
  445. if caveat.caveat_id == "guest = true":
  446. guest = True
  447. self.validate_macaroon(macaroon, rights, user_id=user_id)
  448. except (
  449. pymacaroons.exceptions.MacaroonException,
  450. KeyError,
  451. TypeError,
  452. ValueError,
  453. ):
  454. raise InvalidClientTokenError("Invalid macaroon passed.")
  455. if rights == "access":
  456. self.token_cache[token] = (user_id, guest)
  457. return user_id, guest
  458. def validate_macaroon(
  459. self, macaroon: pymacaroons.Macaroon, type_string: str, user_id: str
  460. ) -> None:
  461. """
  462. validate that a Macaroon is understood by and was signed by this server.
  463. Args:
  464. macaroon: The macaroon to validate
  465. type_string: The kind of token required (e.g. "access", "delete_pusher")
  466. user_id: The user_id required
  467. """
  468. v = pymacaroons.Verifier()
  469. # the verifier runs a test for every caveat on the macaroon, to check
  470. # that it is met for the current request. Each caveat must match at
  471. # least one of the predicates specified by satisfy_exact or
  472. # specify_general.
  473. v.satisfy_exact("gen = 1")
  474. v.satisfy_exact("type = " + type_string)
  475. v.satisfy_exact("user_id = %s" % user_id)
  476. v.satisfy_exact("guest = true")
  477. satisfy_expiry(v, self.clock.time_msec)
  478. # access_tokens include a nonce for uniqueness: any value is acceptable
  479. v.satisfy_general(lambda c: c.startswith("nonce = "))
  480. v.verify(macaroon, self._macaroon_secret_key)
  481. def get_appservice_by_req(self, request: SynapseRequest) -> ApplicationService:
  482. token = self.get_access_token_from_request(request)
  483. service = self.store.get_app_service_by_token(token)
  484. if not service:
  485. logger.warning("Unrecognised appservice access token.")
  486. raise InvalidClientTokenError()
  487. request.requester = create_requester(service.sender, app_service=service)
  488. return service
  489. async def is_server_admin(self, user: UserID) -> bool:
  490. """Check if the given user is a local server admin.
  491. Args:
  492. user: user to check
  493. Returns:
  494. True if the user is an admin
  495. """
  496. return await self.store.is_server_admin(user)
  497. async def check_can_change_room_list(self, room_id: str, user: UserID) -> bool:
  498. """Determine whether the user is allowed to edit the room's entry in the
  499. published room list.
  500. Args:
  501. room_id
  502. user
  503. """
  504. is_admin = await self.is_server_admin(user)
  505. if is_admin:
  506. return True
  507. user_id = user.to_string()
  508. await self.check_user_in_room(room_id, user_id)
  509. # We currently require the user is a "moderator" in the room. We do this
  510. # by checking if they would (theoretically) be able to change the
  511. # m.room.canonical_alias events
  512. power_level_event = await self.state.get_current_state(
  513. room_id, EventTypes.PowerLevels, ""
  514. )
  515. auth_events = {}
  516. if power_level_event:
  517. auth_events[(EventTypes.PowerLevels, "")] = power_level_event
  518. send_level = event_auth.get_send_level(
  519. EventTypes.CanonicalAlias, "", power_level_event
  520. )
  521. user_level = event_auth.get_user_power_level(user_id, auth_events)
  522. return user_level >= send_level
  523. @staticmethod
  524. def has_access_token(request: Request) -> bool:
  525. """Checks if the request has an access_token.
  526. Returns:
  527. False if no access_token was given, True otherwise.
  528. """
  529. # This will always be set by the time Twisted calls us.
  530. assert request.args is not None
  531. query_params = request.args.get(b"access_token")
  532. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  533. return bool(query_params) or bool(auth_headers)
  534. @staticmethod
  535. def get_access_token_from_request(request: Request) -> str:
  536. """Extracts the access_token from the request.
  537. Args:
  538. request: The http request.
  539. Returns:
  540. The access_token
  541. Raises:
  542. MissingClientTokenError: If there isn't a single access_token in the
  543. request
  544. """
  545. # This will always be set by the time Twisted calls us.
  546. assert request.args is not None
  547. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  548. query_params = request.args.get(b"access_token")
  549. if auth_headers:
  550. # Try the get the access_token from a "Authorization: Bearer"
  551. # header
  552. if query_params is not None:
  553. raise MissingClientTokenError(
  554. "Mixing Authorization headers and access_token query parameters."
  555. )
  556. if len(auth_headers) > 1:
  557. raise MissingClientTokenError("Too many Authorization headers.")
  558. parts = auth_headers[0].split(b" ")
  559. if parts[0] == b"Bearer" and len(parts) == 2:
  560. return parts[1].decode("ascii")
  561. else:
  562. raise MissingClientTokenError("Invalid Authorization header.")
  563. else:
  564. # Try to get the access_token from the query params.
  565. if not query_params:
  566. raise MissingClientTokenError()
  567. return query_params[0].decode("ascii")
  568. async def check_user_in_room_or_world_readable(
  569. self, room_id: str, user_id: str, allow_departed_users: bool = False
  570. ) -> Tuple[str, Optional[str]]:
  571. """Checks that the user is or was in the room or the room is world
  572. readable. If it isn't then an exception is raised.
  573. Args:
  574. room_id: room to check
  575. user_id: user to check
  576. allow_departed_users: if True, accept users that were previously
  577. members but have now departed
  578. Returns:
  579. Resolves to the current membership of the user in the room and the
  580. membership event ID of the user. If the user is not in the room and
  581. never has been, then `(Membership.JOIN, None)` is returned.
  582. """
  583. try:
  584. # check_user_in_room will return the most recent membership
  585. # event for the user if:
  586. # * The user is a non-guest user, and was ever in the room
  587. # * The user is a guest user, and has joined the room
  588. # else it will throw.
  589. member_event = await self.check_user_in_room(
  590. room_id, user_id, allow_departed_users=allow_departed_users
  591. )
  592. return member_event.membership, member_event.event_id
  593. except AuthError:
  594. visibility = await self.state.get_current_state(
  595. room_id, EventTypes.RoomHistoryVisibility, ""
  596. )
  597. if (
  598. visibility
  599. and visibility.content.get("history_visibility")
  600. == HistoryVisibility.WORLD_READABLE
  601. ):
  602. return Membership.JOIN, None
  603. raise AuthError(
  604. 403,
  605. "User %s not in room %s, and room previews are disabled"
  606. % (user_id, room_id),
  607. )
  608. async def check_auth_blocking(
  609. self,
  610. user_id: Optional[str] = None,
  611. threepid: Optional[dict] = None,
  612. user_type: Optional[str] = None,
  613. requester: Optional[Requester] = None,
  614. ) -> None:
  615. await self._auth_blocking.check_auth_blocking(
  616. user_id=user_id, threepid=threepid, user_type=user_type, requester=requester
  617. )