desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Check if the provided filter is valid. This inspects all definitions contained within the filter. Args: user_filter_json(dict): The filter Raises: SynapseError: If the filter is not valid.'
def check_valid_filter(self, user_filter_json):
try: jsonschema.validate(user_filter_json, USER_FILTER_SCHEMA, format_checker=FormatChecker()) except jsonschema.ValidationError as e: raise SynapseError(400, e.message)
'Checks whether the filter matches the given event. Returns: bool: True if the event matches'
def check(self, event):
if isinstance(event, UserPresenceState): sender = event.user_id room_id = None ev_type = 'm.presence' is_url = False else: sender = event.get('sender', None) if (not sender): content = event.get('content') if isinstance(content, dict): ...
'Checks whether the filter matches the given event fields. Returns: bool: True if the event fields match'
def check_fields(self, room_id, sender, event_type, contains_url):
literal_keys = {'rooms': (lambda v: (room_id == v)), 'senders': (lambda v: (sender == v)), 'types': (lambda v: _matches_wildcard(event_type, v))} for (name, match_func) in literal_keys.items(): not_name = ('not_%s' % (name,)) disallowed_values = getattr(self, not_name) if any(map(match_f...
'Apply the \'rooms\' filter to a given list of rooms. Args: room_ids (list): A list of room_ids. Returns: list: A list of room_ids that match the filter'
def filter_rooms(self, room_ids):
room_ids = set(room_ids) disallowed_rooms = set(self.filter_json.get('not_rooms', [])) room_ids -= disallowed_rooms allowed_rooms = self.filter_json.get('rooms', None) if (allowed_rooms is not None): room_ids &= set(allowed_rooms) return room_ids
'Checks if this event is correctly authed. Args: event: the event being checked. auth_events (dict: event-key -> event): the existing room state. Returns: True if the auth checks pass.'
def check(self, event, auth_events, do_sig_check=True):
with Measure(self.clock, 'auth.check'): event_auth.check(event, auth_events, do_sig_check=do_sig_check)
'Check if the user is currently joined in the room Args: room_id(str): The room to check. user_id(str): The user to check. current_state(dict): Optional map of the current state of the room. If provided then that map is used to check whether they are a member of the room. Otherwise the current membership is loaded from...
@defer.inlineCallbacks def check_joined_room(self, room_id, user_id, current_state=None):
if current_state: member = current_state.get((EventTypes.Member, user_id), None) else: member = (yield self.state.get_current_state(room_id=room_id, event_type=EventTypes.Member, state_key=user_id)) self._check_joined_room(member, user_id, room_id) defer.returnValue(member)
'Check if the user was in the room at some point. Args: room_id(str): The room to check. user_id(str): The user to check. Raises: AuthError if the user was never in the room. Returns: A deferred membership event for the user if the user was in the room. This will be the join event if they are currently joined to the ro...
@defer.inlineCallbacks def check_user_was_in_room(self, room_id, user_id):
member = (yield self.state.get_current_state(room_id=room_id, event_type=EventTypes.Member, state_key=user_id)) membership = (member.membership if member else None) if (membership not in (Membership.JOIN, Membership.LEAVE)): raise AuthError(403, ('User %s not in room %s' % (user_id, r...
'Get a registered user\'s ID. Args: request - An HTTP request with an access_token query parameter. Returns: defer.Deferred: resolves to a ``synapse.types.Requester`` object Raises: AuthError if no user by that token exists or the token is invalid.'
@defer.inlineCallbacks def get_user_by_req(self, request, allow_guest=False, rights='access'):
try: (user_id, app_service) = (yield self._get_appservice_user_id(request)) if user_id: request.authenticated_entity = user_id defer.returnValue(synapse.types.create_requester(user_id, app_service=app_service)) access_token = get_access_token_from_request(request, sel...
'Validate access token and get user_id from it Args: token (str): The access token to get the user by. rights (str): The operation being performed; the access token must allow this. Returns: dict : dict that includes the user and the ID of their access token. Raises: AuthError if no user by that token exists or the tok...
@defer.inlineCallbacks def get_user_by_access_token(self, token, rights='access'):
try: (user_id, guest) = self._parse_and_validate_macaroon(token, rights) except _InvalidMacaroonException: r = (yield self._look_up_user_by_access_token(token)) defer.returnValue(r) try: user = UserID.from_string(user_id) if guest: stored_user = (yield sel...
'Takes a macaroon and tries to parse and validate it. This is cached if and only if rights == access and there isn\'t an expiry. On invalid macaroon raises _InvalidMacaroonException Returns: (user_id, is_guest)'
def _parse_and_validate_macaroon(self, token, rights='access'):
if (rights == 'access'): cached = self.token_cache.get(token, None) if cached: return cached try: macaroon = pymacaroons.Macaroon.deserialize(token) except Exception: raise _InvalidMacaroonException() try: user_id = self.get_user_id_from_macaroon(macar...
'Retrieve the user_id given by the caveats on the macaroon. Does *not* validate the macaroon. Args: macaroon (pymacaroons.Macaroon): The macaroon to validate Returns: (str) user id Raises: AuthError if there is no user_id caveat in the macaroon'
def get_user_id_from_macaroon(self, macaroon):
user_prefix = 'user_id = ' for caveat in macaroon.caveats: if caveat.caveat_id.startswith(user_prefix): return caveat.caveat_id[len(user_prefix):] raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, 'No user caveat in macaroon', errcode=Codes.UNKNOWN_TOKEN)
'validate that a Macaroon is understood by and was signed by this server. Args: macaroon(pymacaroons.Macaroon): The macaroon to validate type_string(str): The kind of token required (e.g. "access", "delete_pusher") verify_expiry(bool): Whether to verify whether the macaroon has expired. user_id (str): The user_id requi...
def validate_macaroon(self, macaroon, type_string, verify_expiry, user_id):
v = pymacaroons.Verifier() v.satisfy_exact('gen = 1') v.satisfy_exact(('type = ' + type_string)) v.satisfy_exact(('user_id = %s' % user_id)) v.satisfy_exact('guest = true') if verify_expiry: v.satisfy_general(self._verify_expiry) else: v.satisfy_genera...
'Check whether the event sender is allowed to redact the target event. Returns: True if the the sender is allowed to redact the target event if the target event was created by them. False if the sender is allowed to redact the target event with no further checks. Raises: AuthError if the event sender is definitely not ...
def check_redaction(self, event, auth_events):
return event_auth.check_redaction(event, auth_events)
'Check if the user is allowed to edit the room\'s entry in the published room list. Args: room_id (str) user (UserID)'
@defer.inlineCallbacks def check_can_change_room_list(self, room_id, user):
is_admin = (yield self.is_server_admin(user)) if is_admin: defer.returnValue(True) user_id = user.to_string() (yield self.check_joined_room(room_id, user_id)) power_level_event = (yield self.state.get_current_state(room_id, EventTypes.PowerLevels, '')) auth_events = {} if power_level...
'Constructs a synapse error. Args: code (int): The integer error code (an HTTP response code) msg (str): The human-readable error message. errcode (str): The matrix error code e.g \'M_FORBIDDEN\''
def __init__(self, code, msg, errcode=Codes.UNKNOWN):
super(SynapseError, self).__init__(code, msg) self.errcode = errcode
'Make a SynapseError based on an HTTPResponseException This is useful when a proxied request has failed, and we need to decide how to map the failure onto a matrix error to send back to the client. An attempt is made to parse the body of the http response as a matrix error. If that succeeds, the errcode and error messa...
@classmethod def from_http_response_exception(cls, err):
try: j = json.loads(err.response) except ValueError: j = {} errcode = j.get('errcode', Codes.UNKNOWN) errmsg = j.get('error', err.msg) res = SynapseError(err.code, errmsg, errcode) return res
'Args: code (int): HTTP status code msg (str): reason phrase from HTTP response status line response (str): body of response'
def __init__(self, code, msg, response):
super(HttpResponseException, self).__init__(code, msg) self.response = response
'Can the user send a message? Args: user_id: The user sending a message. time_now_s: The time now. msg_rate_hz: The long term number of messages a user can send in a second. burst_count: How many messages the user can send before being limited. update (bool): Whether to update the message rates or not. This is useful t...
def send_message(self, user_id, time_now_s, msg_rate_hz, burst_count, update=True):
self.prune_message_counts(time_now_s) (message_count, time_start, _ignored) = self.message_counts.get(user_id, (0.0, time_now_s, None)) time_delta = (time_now_s - time_start) sent_count = (message_count - (time_delta * msg_rate_hz)) if (sent_count < 0): allowed = True time_start = ti...
'Fetches the events stream for a given user. If `only_keys` is not None, events from keys will be sent down.'
@defer.inlineCallbacks @log_function def get_stream(self, auth_user_id, pagin_config, timeout=0, as_client_event=True, affect_presence=True, only_keys=None, room_id=None, is_guest=False):
auth_user = UserID.from_string(auth_user_id) presence_handler = self.hs.get_presence_handler() context = (yield presence_handler.user_syncing(auth_user_id, affect_presence=affect_presence)) with context: if timeout: timeout = max(timeout, 500) timeout = random.randint(int...
'Retrieve a single specified event. Args: user (synapse.types.UserID): The user requesting the event event_id (str): The event ID to obtain. Returns: dict: An event, or None if there is no event matching this ID. Raises: SynapseError if there was a problem retrieving this event, or AuthError if the user does not have t...
@defer.inlineCallbacks def get_event(self, user, event_id):
event = (yield self.store.get_event(event_id)) if (not event): defer.returnValue(None) return if hasattr(event, 'room_id'): (yield self.auth.check_joined_room(event.room_id, user.to_string())) defer.returnValue(event)
'Registers a new client on the server. Args: localpart : The local part of the user ID to register. If None, one will be generated. password (str) : The password to assign to this user so they can login again. This can be None which means they cannot login again via a password (e.g. the user is an application service u...
@defer.inlineCallbacks def register(self, localpart=None, password=None, generate_token=True, guest_access_token=None, make_guest=False, admin=False):
(yield run_on_reactor()) password_hash = None if password: password_hash = self.auth_handler().hash(password) if localpart: (yield self.check_username(localpart, guest_access_token=guest_access_token)) was_guest = (guest_access_token is not None) if (not was_guest): ...
'Checks a recaptcha is correct. Used only by c/s api v1'
@defer.inlineCallbacks def check_recaptcha(self, ip, private_key, challenge, response):
captcha_response = (yield self._validate_captcha(ip, private_key, challenge, response)) if (not captcha_response['valid']): logger.info('Invalid captcha entered from %s. Error: %s', ip, captcha_response['error_url']) raise InvalidCaptchaError(error_url=captcha_response['error_u...
'Registers email_id as SAML2 Based Auth.'
@defer.inlineCallbacks def register_saml2(self, localpart):
if (urllib.quote(localpart) != localpart): raise SynapseError(400, 'User ID must only contain characters which do not require URL encoding.') user = UserID(localpart, self.hs.hostname) user_id = user.to_string() (yield self.check_user_id_not_appservice_exclusive(...
'Registers emails with an identity server. Used only by c/s api v1'
@defer.inlineCallbacks def register_email(self, threepidCreds):
for c in threepidCreds: logger.info('validating theeepidcred sid %s on id server %s', c['sid'], c['idServer']) try: identity_handler = self.hs.get_handlers().identity_handler threepid = (yield identity_handler.threepid_from_creds(c)) except: ...
'Links emails with a user ID and informs an identity server. Used only by c/s api v1'
@defer.inlineCallbacks def bind_emails(self, user_id, threepidCreds):
for c in threepidCreds: identity_handler = self.hs.get_handlers().identity_handler (yield identity_handler.bind_threepid(c, user_id))
'Validates the captcha provided. Used only by c/s api v1 Returns: dict: Containing \'valid\'(bool) and \'error_url\'(str) if invalid.'
@defer.inlineCallbacks def _validate_captcha(self, ip_addr, private_key, challenge, response):
response = (yield self._submit_captcha(ip_addr, private_key, challenge, response)) lines = response.split('\n') json = {'valid': (lines[0] == 'true'), 'error_url': ('http://www.google.com/recaptcha/api/challenge?' + ('error=%s' % lines[1]))} defer.returnValue(json)
'Used only by c/s api v1'
@defer.inlineCallbacks def _submit_captcha(self, ip_addr, private_key, challenge, response):
data = (yield self.captcha_client.post_urlencoded_get_raw('http://www.google.com:80/recaptcha/api/verify', args={'privatekey': private_key, 'remoteip': ip_addr, 'challenge': challenge, 'response': response})) defer.returnValue(data)
'Creates a new user if the user does not exist, else revokes all previous access tokens and generates a new one. Args: localpart : The local part of the user ID to register. If None, one will be randomly generated. Returns: A tuple of (user_id, access_token). Raises: RegistrationError if there was a problem registering...
@defer.inlineCallbacks def get_or_create_user(self, requester, localpart, displayname, password_hash=None):
(yield run_on_reactor()) if (localpart is None): raise SynapseError(400, 'Request must include user id') need_register = True try: (yield self.check_username(localpart)) except SynapseError as e: if (e.errcode == Codes.USER_IN_USE): need_register = Fal...
'target_user is the user whose displayname is to be changed; auth_user is the user attempting to make this change.'
@defer.inlineCallbacks def set_displayname(self, target_user, requester, new_displayname, by_admin=False):
if (not self.hs.is_mine(target_user)): raise SynapseError(400, 'User is not hosted on this Home Server') if ((not by_admin) and (target_user != requester.user)): raise AuthError(400, "Cannot set another user's displayname") if (new_displayname == ''): ...
'target_user is the user whose avatar_url is to be changed; auth_user is the user attempting to make this change.'
@defer.inlineCallbacks def set_avatar_url(self, target_user, requester, new_avatar_url, by_admin=False):
if (not self.hs.is_mine(target_user)): raise SynapseError(400, 'User is not hosted on this Home Server') if ((not by_admin) and (target_user != requester.user)): raise AuthError(400, "Cannot set another user's avatar_url") (yield self.store.set_profile_avatar...
'Performs a full text search for a user. Args: user (UserID) content (dict): Search parameters batch (str): The next_batch parameter. Used for pagination. Returns: dict to be returned to the client with results of search'
@defer.inlineCallbacks def search(self, user, content, batch=None):
batch_group = None batch_group_key = None batch_token = None if batch: try: b = decode_base64(batch) (batch_group, batch_group_key, batch_token) = b.split('\n') assert (batch_group is not None) assert (batch_group_key is not None) asser...
'Args: hs (synapse.server.HomeServer): server'
def __init__(self, hs):
self.store = hs.get_datastore() self.notifier = hs.get_notifier() self.is_mine_id = hs.is_mine_id self.federation = hs.get_federation_sender() hs.get_replication_layer().register_edu_handler('m.direct_to_device', self.on_direct_to_device_edu)
'Searches for users in directory Returns: dict of the form:: "limited": <bool>, # whether there were more results or not "results": [ # Ordered by best match first "user_id": <user_id>, "display_name": <display_name>, "avatar_url": <avatar_url>'
def search_users(self, user_id, search_term, limit):
return self.store.search_user_dir(user_id, search_term, limit)
'Called when there may be more deltas to process'
@defer.inlineCallbacks def notify_new_event(self):
if (not self.update_user_directory): return if self._is_processing: return self._is_processing = True try: (yield self._unsafe_process()) finally: self._is_processing = False
'Populates the user_directory from the current state of the DB, used when synapse first starts with user_directory support'
@defer.inlineCallbacks def _do_initial_spam(self):
new_pos = (yield self.store.get_max_stream_id_in_current_state_deltas()) (yield self.store.delete_all_from_user_dir()) room_ids = (yield self.store.get_all_rooms()) logger.info('Doing initial update of user directory. %d rooms', len(room_ids)) num_processed_rooms = 1 for roo...
'Called when we initially fill out user_directory one room at a time'
@defer.inlineCallbacks def _handle_intial_room(self, room_id):
is_in_room = (yield self.store.is_host_joined(room_id, self.server_name)) if (not is_in_room): return is_public = (yield self.store.is_room_world_readable_or_publicly_joinable(room_id)) users_with_profile = (yield self.state.get_current_user_in_room(room_id)) user_ids = set(users_with_profil...
'Called with the state deltas to process'
@defer.inlineCallbacks def _handle_deltas(self, deltas):
for delta in deltas: typ = delta['type'] state_key = delta['state_key'] room_id = delta['room_id'] event_id = delta['event_id'] prev_event_id = delta['prev_event_id'] logger.debug('Handling: %r %r, %s', typ, state_key, event_id) if (typ in (EventTypes...
'Handle a room having potentially changed from/to world_readable/publically joinable. Args: room_id (str) prev_event_id (str|None): The previous event before the state change event_id (str|None): The new event after the state change typ (str): Type of the event'
@defer.inlineCallbacks def _handle_room_publicity_change(self, room_id, prev_event_id, event_id, typ):
logger.debug('Handling change for %s: %s', typ, room_id) if (typ == EventTypes.RoomHistoryVisibility): change = (yield self._get_key_change(prev_event_id, event_id, key_name='history_visibility', public_value='world_readable')) elif (typ == EventTypes.JoinRules): change = (yield ...
'Called when we might need to add user to directory Args: room_id (str): room_id that user joined or started being public that user_id (str)'
@defer.inlineCallbacks def _handle_new_user(self, room_id, user_id, profile):
logger.debug('Adding user to dir, %r', user_id) row = (yield self.store.get_user_in_directory(user_id)) if (not row): (yield self.store.add_profiles_to_user_dir(room_id, {user_id: profile})) is_public = (yield self.store.is_room_world_readable_or_publicly_joinable(room_id)) if is...
'Called when we might need to remove user to directory Args: room_id (str): room_id that user left or stopped being public that user_id (str)'
@defer.inlineCallbacks def _handle_remove_user(self, room_id, user_id):
logger.debug('Maybe removing user %r', user_id) row = (yield self.store.get_user_in_directory(user_id)) update_user_dir = (row and (row['room_id'] == room_id)) row = (yield self.store.get_user_in_public_room(user_id)) update_user_in_public = (row and (row['room_id'] == room_id)) if (upd...
'Check member event changes for any profile changes and update the database if there are.'
@defer.inlineCallbacks def _handle_profile_change(self, user_id, room_id, prev_event_id, event_id):
if ((not prev_event_id) or (not event_id)): return prev_event = (yield self.store.get_event(prev_event_id, allow_none=True)) event = (yield self.store.get_event(event_id, allow_none=True)) if ((not prev_event) or (not event)): return if (event.membership != Membership.JOIN): ...
'Given two events check if the `key_name` field in content changed from not matching `public_value` to doing so. For example, check if `history_visibility` (`key_name`) changed from `shared` to `world_readable` (`public_value`). Returns: None if the field in the events either both match `public_value` or if neither do,...
@defer.inlineCallbacks def _get_key_change(self, prev_event_id, event_id, key_name, public_value):
prev_event = None event = None if prev_event_id: prev_event = (yield self.store.get_event(prev_event_id, allow_none=True)) if event_id: event = (yield self.store.get_event(event_id, allow_none=True)) if ((not event) and (not prev_event)): logger.debug('Neither event exi...
'Args: hs (synapse.server.HomeServer):'
def __init__(self, hs):
self.store = hs.get_datastore() self.auth = hs.get_auth() self.notifier = hs.get_notifier() self.state_handler = hs.get_state_handler() self.distributor = hs.get_distributor() self.ratelimiter = hs.get_ratelimiter() self.clock = hs.get_clock() self.hs = hs self.server_name = hs.hostn...
'Ratelimits requests. Args: requester (Requester) update (bool): Whether to record that a request is being processed. Set to False when doing multiple checks for one request (e.g. to check up front if we would reject the request), and set to True for the last call for a given request. Raises: LimitExceededError if the ...
@defer.inlineCallbacks def ratelimit(self, requester, update=True):
time_now = self.clock.time() user_id = requester.user.to_string() app_service = self.store.get_app_service_by_user_id(user_id) if (app_service is not None): return if (requester.app_service and (not requester.app_service.is_rate_limited())): return override = (yield self.store.ge...
'Args: hs (synapse.server.HomeServer):'
def __init__(self, hs):
super(AuthHandler, self).__init__(hs) self.checkers = {LoginType.PASSWORD: self._check_password_auth, LoginType.RECAPTCHA: self._check_recaptcha, LoginType.EMAIL_IDENTITY: self._check_email_identity, LoginType.MSISDN: self._check_msisdn, LoginType.DUMMY: self._check_dummy_auth} self.bcrypt_rounds = hs.confi...
'Takes a dictionary sent by the client in the login / registration protocol and handles the login flow. As a side effect, this function fills in the \'creds\' key on the user\'s session with a map, which maps each auth-type (str) to the relevant identity authenticated by that auth-type (mostly str, but for captcha, boo...
@defer.inlineCallbacks def check_auth(self, flows, clientdict, clientip):
authdict = None sid = None if (clientdict and ('auth' in clientdict)): authdict = clientdict['auth'] del clientdict['auth'] if ('session' in authdict): sid = authdict['session'] session = self._get_session_info(sid) if (len(clientdict) > 0): session['clien...
'Adds the result of out-of-band authentication into an existing auth session. Currently used for adding the result of fallback auth.'
@defer.inlineCallbacks def add_oob_auth(self, stagetype, authdict, clientip):
if (stagetype not in self.checkers): raise LoginError(400, '', Codes.MISSING_PARAM) if ('session' not in authdict): raise LoginError(400, '', Codes.MISSING_PARAM) sess = self._get_session_info(authdict['session']) if ('creds' not in sess): sess['creds'] = {} creds = sess['cre...
'Gets the session ID for a client given the client dictionary Args: clientdict: The dictionary sent by the client in the request Returns: str|None: The string session ID the client sent. If the client did not send a session ID, returns None.'
def get_session_id(self, clientdict):
sid = None if (clientdict and ('auth' in clientdict)): authdict = clientdict['auth'] if ('session' in authdict): sid = authdict['session'] return sid
'Store a key-value pair into the sessions data associated with this request. This data is stored server-side and cannot be modified by the client. Args: session_id (string): The ID of this session as returned from check_auth key (string): The key to store the data under value (any): The data to store'
def set_session_data(self, session_id, key, value):
sess = self._get_session_info(session_id) sess.setdefault('serverdict', {})[key] = value self._save_session(sess)
'Retrieve data stored with set_session_data Args: session_id (string): The ID of this session as returned from check_auth key (string): The key to store the data under default (any): Value to return if the key has not been set'
def get_session_data(self, session_id, key, default=None):
sess = self._get_session_info(session_id) return sess.setdefault('serverdict', {}).get(key, default)
'Authenticates the user with their username and password. Used only by the v1 login API. Args: user_id (str): complete @user:id password (str): Password Returns: defer.Deferred: (str) canonical user id Raises: StoreError if there was a problem accessing the database LoginError if there was an authentication problem.'
def validate_password_login(self, user_id, password):
return self._check_password(user_id, password)
'Creates a new access token for the user with the given user ID. The user is assumed to have been authenticated by some other machanism (e.g. CAS), and the user_id converted to the canonical case. The device will be recorded in the table if it is not there already. Args: user_id (str): canonical User ID device_id (str|...
@defer.inlineCallbacks def get_access_token_for_user_id(self, user_id, device_id=None, initial_display_name=None):
logger.info('Logging in user %s on device %s', user_id, device_id) access_token = (yield self.issue_access_token(user_id, device_id)) if (device_id is not None): (yield self.device_handler.check_device_registered(user_id, device_id, initial_display_name)) defer.returnValue(acce...
'Checks to see if a user with the given id exists. Will check case insensitively, but return None if there are multiple inexact matches. Args: (str) user_id: complete @user:id Returns: defer.Deferred: (str) canonical_user_id, or None if zero or multiple matches'
@defer.inlineCallbacks def check_user_exists(self, user_id):
res = (yield self._find_user_id_and_pwd_hash(user_id)) if (res is not None): defer.returnValue(res[0]) defer.returnValue(None)
'Checks to see if a user with the given id exists. Will check case insensitively, but will return None if there are multiple inexact matches. Returns: tuple: A 2-tuple of `(canonical_user_id, password_hash)` None: if there is not exactly one match'
@defer.inlineCallbacks def _find_user_id_and_pwd_hash(self, user_id):
user_infos = (yield self.store.get_users_by_id_case_insensitive(user_id)) result = None if (not user_infos): logger.warn('Attempted to login as %s but they do not exist', user_id) elif (len(user_infos) == 1): result = user_infos.popitem() elif (user_id in u...
'Authenticate a user against the LDAP and local databases. user_id is checked case insensitively against the local database, but will throw if there are multiple inexact matches. Args: user_id (str): complete @user:id Returns: (str) the canonical_user_id Raises: LoginError if login fails'
@defer.inlineCallbacks def _check_password(self, user_id, password):
for provider in self.password_providers: is_valid = (yield provider.check_password(user_id, password)) if is_valid: defer.returnValue(user_id) canonical_user_id = (yield self._check_local_password(user_id, password)) if canonical_user_id: defer.returnValue(canonical_user_...
'Authenticate a user against the local password database. user_id is checked case insensitively, but will return None if there are multiple inexact matches. Args: user_id (str): complete @user:id Returns: (str) the canonical_user_id, or None if unknown user / bad password'
@defer.inlineCallbacks def _check_local_password(self, user_id, password):
lookupres = (yield self._find_user_id_and_pwd_hash(user_id)) if (not lookupres): defer.returnValue(None) (user_id, password_hash) = lookupres result = self.validate_hash(password, password_hash) if (not result): logger.warn('Failed password login for user %s', user_id)...
'Computes a secure hash of password. Args: password (str): Password to hash. Returns: Hashed password (str).'
def hash(self, password):
return bcrypt.hashpw((password.encode('utf8') + self.hs.config.password_pepper), bcrypt.gensalt(self.bcrypt_rounds))
'Validates that self.hash(password) == stored_hash. Args: password (str): Password to hash. stored_hash (str): Expected hash value. Returns: Whether self.hash(password) == stored_hash (bool).'
def validate_hash(self, password, stored_hash):
if stored_hash: return (bcrypt.hashpw((password.encode('utf8') + self.hs.config.password_pepper), stored_hash.encode('utf8')) == stored_hash) else: return False
'Check if user exissts. Returns: Deferred(bool)'
def check_user_exists(self, user_id):
return self._check_user_exists(user_id)
'Registers a new user with given localpart Returns: Deferred: a 2-tuple of (user_id, access_token)'
def register(self, localpart):
reg = self.hs.get_handlers().registration_handler return reg.register(localpart=localpart)
'If the given device has not been registered, register it with the supplied display name. If no device_id is supplied, we make one up. Args: user_id (str): @user:id device_id (str | None): device id supplied by client initial_device_display_name (str | None): device display name from client Returns: str: device id (ge...
@defer.inlineCallbacks def check_device_registered(self, user_id, device_id, initial_device_display_name=None):
if (device_id is not None): new_device = (yield self.store.store_device(user_id=user_id, device_id=device_id, initial_device_display_name=initial_device_display_name)) if new_device: (yield self.notify_device_update(user_id, [device_id])) defer.returnValue(device_id) attempts...
'Retrieve the given user\'s devices Args: user_id (str): Returns: defer.Deferred: list[dict[str, X]]: info on each device'
@defer.inlineCallbacks def get_devices_by_user(self, user_id):
device_map = (yield self.store.get_devices_by_user(user_id)) ips = (yield self.store.get_last_client_ip_by_device(user_id, device_id=None)) devices = device_map.values() for device in devices: _update_device_from_client_ips(device, ips) defer.returnValue(devices)
'Retrieve the given device Args: user_id (str): device_id (str): Returns: defer.Deferred: dict[str, X]: info on the device Raises: errors.NotFoundError: if the device was not found'
@defer.inlineCallbacks def get_device(self, user_id, device_id):
try: device = (yield self.store.get_device(user_id, device_id)) except errors.StoreError: raise errors.NotFoundError ips = (yield self.store.get_last_client_ip_by_device(user_id, device_id)) _update_device_from_client_ips(device, ips) defer.returnValue(device)
'Delete the given device Args: user_id (str): device_id (str): Returns: defer.Deferred:'
@defer.inlineCallbacks def delete_device(self, user_id, device_id):
try: (yield self.store.delete_device(user_id, device_id)) except errors.StoreError as e: if (e.code == 404): pass else: raise (yield self.store.user_delete_access_tokens(user_id, device_id=device_id, delete_refresh_tokens=True)) (yield self.store.delete_e2...
'Delete several devices Args: user_id (str): device_ids (str): The list of device IDs to delete Returns: defer.Deferred:'
@defer.inlineCallbacks def delete_devices(self, user_id, device_ids):
try: (yield self.store.delete_devices(user_id, device_ids)) except errors.StoreError as e: if (e.code == 404): pass else: raise for device_id in device_ids: (yield self.store.user_delete_access_tokens(user_id, device_id=device_id, delete_refresh_tokens...
'Update the given device Args: user_id (str): device_id (str): content (dict): body of update request Returns: defer.Deferred:'
@defer.inlineCallbacks def update_device(self, user_id, device_id, content):
try: (yield self.store.update_device(user_id, device_id, new_display_name=content.get('display_name'))) (yield self.notify_device_update(user_id, [device_id])) except errors.StoreError as e: if (e.code == 404): raise errors.NotFoundError() else: raise
'Notify that a user\'s device(s) has changed. Pokes the notifier, and remote servers if the user is local.'
@measure_func('notify_device_update') @defer.inlineCallbacks def notify_device_update(self, user_id, device_ids):
users_who_share_room = (yield self.store.get_users_who_share_room_with_user(user_id)) hosts = set() if self.hs.is_mine_id(user_id): hosts.update((get_domain_from_id(u) for u in users_who_share_room)) hosts.discard(self.server_name) position = (yield self.store.add_device_change_to_stream...
'Get list of users that have had the devices updated, or have newly joined a room, that `user_id` may be interested in. Args: user_id (str) from_token (StreamToken)'
@measure_func('device.get_user_ids_changed') @defer.inlineCallbacks def get_user_ids_changed(self, user_id, from_token):
room_ids = (yield self.store.get_rooms_for_user(user_id)) changed = (yield self.store.get_user_whose_devices_changed(from_token.device_list_key)) rooms_changed = self.store.get_rooms_that_changed(room_ids, from_token.room_key) stream_ordering = RoomStreamToken.parse_stream_token(from_token.room_key).str...
'Called on incoming device list update from federation. Responsible for parsing the EDU and adding to pending updates list.'
@defer.inlineCallbacks def incoming_device_list_update(self, origin, edu_content):
user_id = edu_content.pop('user_id') device_id = edu_content.pop('device_id') stream_id = str(edu_content.pop('stream_id')) prev_ids = edu_content.pop('prev_id', []) prev_ids = [str(p) for p in prev_ids] if (get_domain_from_id(user_id) != origin): logger.warning('Got device list ...
'Actually handle pending updates.'
@measure_func('_incoming_device_list_update') @defer.inlineCallbacks def _handle_device_updates(self, user_id):
with (yield self._remote_edu_linearizer.queue(user_id)): pending_updates = self._pending_updates.pop(user_id, []) if (not pending_updates): return resync = (yield self._need_to_do_resync(user_id, pending_updates)) if resync: origin = get_domain_from_id(user_id...
'Given a list of updates for a user figure out if we need to do a full resync, or whether we have enough data that we can just apply the delta.'
@defer.inlineCallbacks def _need_to_do_resync(self, user_id, updates):
seen_updates = self._seen_updates.get(user_id, set()) extremity = (yield self.store.get_device_list_last_stream_id_for_remote(user_id)) stream_id_in_updates = set() for (_, stream_id, prev_ids, _) in updates: if (not prev_ids): defer.returnValue(True) for prev_id in prev_ids:...
'Handle a device key query from a client "device_keys": { "<user_id>": ["<device_id>"] "device_keys": { "<user_id>": { "<device_id>": {'
@defer.inlineCallbacks def query_devices(self, query_body, timeout):
device_keys_query = query_body.get('device_keys', {}) local_query = {} remote_queries = {} for (user_id, device_ids) in device_keys_query.items(): if self.is_mine_id(user_id): local_query[user_id] = device_ids else: remote_queries[user_id] = device_ids failure...
'Get E2E device keys for local users Args: query (dict[string, list[string]|None): map from user_id to a list of devices to query (None for all devices) Returns: defer.Deferred: (resolves to dict[string, dict[string, dict]]): map from user_id -> device_id -> device details'
@defer.inlineCallbacks def query_local_devices(self, query):
local_query = [] result_dict = {} for (user_id, device_ids) in query.items(): if (not self.is_mine_id(user_id)): logger.warning('Request for keys for non-local user %s', user_id) raise SynapseError(400, 'Not a user here') if (not device_ids)...
'Handle a device key query from a federated server'
@defer.inlineCallbacks def on_federation_query_client_keys(self, query_body):
device_keys_query = query_body.get('device_keys', {}) res = (yield self.query_local_devices(device_keys_query)) defer.returnValue({'device_keys': res})
'Edit the entry of the room in the published room list. requester room_id (str) visibility (str): "public" or "private"'
@defer.inlineCallbacks def edit_published_room_list(self, requester, room_id, visibility):
if requester.is_guest: raise AuthError(403, 'Guests cannot edit the published room list') if (visibility not in ['public', 'private']): raise SynapseError(400, 'Invalid visibility setting') room = (yield self.store.get_room(room_id)) if (room is None): rai...
'Add or remove a room from the appservice/network specific public room list. Args: appservice_id (str): ID of the appservice that owns the list network_id (str): The ID of the network the list is associated with room_id (str) visibility (str): either "public" or "private"'
@defer.inlineCallbacks def edit_published_appservice_room_list(self, appservice_id, network_id, room_id, visibility):
if (visibility not in ['public', 'private']): raise SynapseError(400, 'Invalid visibility setting') (yield self.store.set_room_is_public_appservice(room_id, appservice_id, network_id, (visibility == 'public')))
'Make the result appear empty if there are no updates. This is used to tell if room needs to be part of the sync result.'
def __nonzero__(self):
return bool(self.events)
'Make the result appear empty if there are no updates. This is used to tell if room needs to be part of the sync result.'
def __nonzero__(self):
return bool((self.timeline or self.state or self.ephemeral or self.account_data))
'Make the result appear empty if there are no updates. This is used to tell if room needs to be part of the sync result.'
def __nonzero__(self):
return bool((self.timeline or self.state or self.account_data))
'Invited rooms should always be reported to the client'
def __nonzero__(self):
return True
'Make the result appear empty if there are no updates. This is used to tell if the notifier needs to wait for more events when polling for events.'
def __nonzero__(self):
return bool((self.presence or self.joined or self.invited or self.archived or self.account_data or self.to_device or self.device_lists))
'Get the sync for a client if we have new data for it now. Otherwise wait for new data to arrive on the server. If the timeout expires, then return an empty sync result. Returns: A Deferred SyncResult.'
def wait_for_sync_for_user(self, sync_config, since_token=None, timeout=0, full_state=False):
result = self.response_cache.get(sync_config.request_key) if (not result): result = self.response_cache.set(sync_config.request_key, self._wait_for_sync_for_user(sync_config, since_token, timeout, full_state)) return result
'Get the sync for client needed to match what the server has now. Returns: A Deferred SyncResult.'
def current_sync_for_user(self, sync_config, since_token=None, full_state=False):
return self.generate_sync_result(sync_config, since_token, full_state)
'Get the ephemeral events for each room the user is in Args: sync_config (SyncConfig): The flags, filters and user for the sync. now_token (StreamToken): Where the server is currently up to. since_token (StreamToken): Where the server was when the client last synced. Returns: A tuple of the now StreamToken, updated to ...
@defer.inlineCallbacks def ephemeral_by_room(self, sync_config, now_token, since_token=None):
with Measure(self.clock, 'ephemeral_by_room'): typing_key = (since_token.typing_key if since_token else '0') room_ids = (yield self.store.get_rooms_for_user(sync_config.user.to_string())) typing_source = self.event_sources.sources['typing'] (typing, typing_key) = (yield typing_source...
'Returns: a Deferred TimelineBatch'
@defer.inlineCallbacks def _load_filtered_recents(self, room_id, sync_config, now_token, since_token=None, recents=None, newly_joined_room=False):
with Measure(self.clock, 'load_filtered_recents'): timeline_limit = sync_config.filter_collection.timeline_limit() block_all_timeline = sync_config.filter_collection.blocks_all_room_timeline() if ((recents is None) or newly_joined_room or (timeline_limit < len(recents))): limited...
'Get the room state after the given event Args: event(synapse.events.EventBase): event of interest Returns: A Deferred map from ((type, state_key)->Event)'
@defer.inlineCallbacks def get_state_after_event(self, event):
state_ids = (yield self.store.get_state_ids_for_event(event.event_id)) if event.is_state(): state_ids = state_ids.copy() state_ids[(event.type, event.state_key)] = event.event_id defer.returnValue(state_ids)
'Get the room state at a particular stream position Args: room_id(str): room for which to get state stream_position(StreamToken): point at which to get state Returns: A Deferred map from ((type, state_key)->Event)'
@defer.inlineCallbacks def get_state_at(self, room_id, stream_position):
(last_events, token) = (yield self.store.get_recent_events_for_room(room_id, end_token=stream_position.room_key, limit=1)) if last_events: last_event = last_events[(-1)] state = (yield self.get_state_after_event(last_event)) else: state = {} defer.returnValue(state)
'Works out the differnce in state between the start of the timeline and the previous sync. Args: room_id(str): batch(synapse.handlers.sync.TimelineBatch): The timeline batch for the room that will be sent to the user. sync_config(synapse.handlers.sync.SyncConfig): since_token(str|None): Token of the end of the previous...
@defer.inlineCallbacks def compute_state_delta(self, room_id, batch, sync_config, since_token, now_token, full_state):
with Measure(self.clock, 'compute_state_delta'): if full_state: if batch: current_state_ids = (yield self.store.get_state_ids_for_event(batch.events[(-1)].event_id)) state_ids = (yield self.store.get_state_ids_for_event(batch.events[0].event_id)) else:...
'Generates a sync result. Args: sync_config (SyncConfig) since_token (StreamToken) full_state (bool) Returns: Deferred(SyncResult)'
@defer.inlineCallbacks def generate_sync_result(self, sync_config, since_token=None, full_state=False):
logger.info('Calculating sync response for %r', sync_config.user) now_token = (yield self.event_sources.get_current_token()) sync_result_builder = SyncResultBuilder(sync_config, full_state, since_token=since_token, now_token=now_token) account_data_by_room = (yield self._generate_sync_entry_...
'Generates the portion of the sync response. Populates `sync_result_builder` with the result. Args: sync_result_builder(SyncResultBuilder) Returns: Deferred(dict): A dictionary containing the per room account data.'
@defer.inlineCallbacks def _generate_sync_entry_for_to_device(self, sync_result_builder):
user_id = sync_result_builder.sync_config.user.to_string() device_id = sync_result_builder.sync_config.device_id now_token = sync_result_builder.now_token since_stream_id = 0 if (sync_result_builder.since_token is not None): since_stream_id = int(sync_result_builder.since_token.to_device_key...
'Generates the account data portion of the sync response. Populates `sync_result_builder` with the result. Args: sync_result_builder(SyncResultBuilder) Returns: Deferred(dict): A dictionary containing the per room account data.'
@defer.inlineCallbacks def _generate_sync_entry_for_account_data(self, sync_result_builder):
sync_config = sync_result_builder.sync_config user_id = sync_result_builder.sync_config.user.to_string() since_token = sync_result_builder.since_token if (since_token and (not sync_result_builder.full_state)): (account_data, account_data_by_room) = (yield self.store.get_updated_account_data_for_...
'Generates the presence portion of the sync response. Populates the `sync_result_builder` with the result. Args: sync_result_builder(SyncResultBuilder) newly_joined_rooms(list): List of rooms that the user has joined since the last sync (or empty if an initial sync) newly_joined_users(list): List of users that have joi...
@defer.inlineCallbacks def _generate_sync_entry_for_presence(self, sync_result_builder, newly_joined_rooms, newly_joined_users):
now_token = sync_result_builder.now_token sync_config = sync_result_builder.sync_config user = sync_result_builder.sync_config.user presence_source = self.event_sources.sources['presence'] since_token = sync_result_builder.since_token if (since_token and (not sync_result_builder.full_state)): ...
'Generates the rooms portion of the sync response. Populates the `sync_result_builder` with the result. Args: sync_result_builder(SyncResultBuilder) account_data_by_room(dict): Dictionary of per room account data Returns: Deferred(tuple): Returns a 2-tuple of `(newly_joined_rooms, newly_joined_users)`'
@defer.inlineCallbacks def _generate_sync_entry_for_rooms(self, sync_result_builder, account_data_by_room):
user_id = sync_result_builder.sync_config.user.to_string() block_all_room_ephemeral = ((sync_result_builder.since_token is None) and sync_result_builder.sync_config.filter_collection.blocks_all_room_ephemeral()) if block_all_room_ephemeral: ephemeral_by_room = {} else: (now_token, epheme...
'Returns whether there may be any new events that should be sent down the sync. Returns True if there are.'
@defer.inlineCallbacks def _have_rooms_changed(self, sync_result_builder):
user_id = sync_result_builder.sync_config.user.to_string() since_token = sync_result_builder.since_token now_token = sync_result_builder.now_token assert since_token rooms_changed = (yield self.store.get_membership_changes_for_user(user_id, since_token.room_key, now_token.room_key)) if rooms_cha...
'Gets the the changes that have happened since the last sync. Args: sync_result_builder(SyncResultBuilder) ignored_users(set(str)): Set of users ignored by user. Returns: Deferred(tuple): Returns a tuple of the form: `([RoomSyncResultBuilder], [InvitedSyncResult], newly_joined_rooms)`'
@defer.inlineCallbacks def _get_rooms_changed(self, sync_result_builder, ignored_users):
user_id = sync_result_builder.sync_config.user.to_string() since_token = sync_result_builder.since_token now_token = sync_result_builder.now_token sync_config = sync_result_builder.sync_config assert since_token app_service = self.store.get_app_service_by_user_id(user_id) if app_service: ...
'Returns entries for all rooms for the user. Args: sync_result_builder(SyncResultBuilder) ignored_users(set(str)): Set of users ignored by user. Returns: Deferred(tuple): Returns a tuple of the form: `([RoomSyncResultBuilder], [InvitedSyncResult], [])`'
@defer.inlineCallbacks def _get_all_rooms(self, sync_result_builder, ignored_users):
user_id = sync_result_builder.sync_config.user.to_string() since_token = sync_result_builder.since_token now_token = sync_result_builder.now_token sync_config = sync_result_builder.sync_config membership_list = (Membership.INVITE, Membership.JOIN, Membership.LEAVE, Membership.BAN) room_list = (y...
'Populates the `joined` and `archived` section of `sync_result_builder` based on the `room_builder`. Args: sync_result_builder(SyncResultBuilder) ignored_users(set(str)): Set of users ignored by user. room_builder(RoomSyncResultBuilder) ephemeral(list): List of new ephemeral events for room tags(list): List of *all* ta...
@defer.inlineCallbacks def _generate_room_entry(self, sync_result_builder, ignored_users, room_builder, ephemeral, tags, account_data, always_include=False):
newly_joined = room_builder.newly_joined full_state = (room_builder.full_state or newly_joined or sync_result_builder.full_state) events = room_builder.events if (not (always_include or account_data or ephemeral or full_state)): if ((events == []) and (tags is None)): return sinc...
'Args: sync_config(SyncConfig) full_state(bool): The full_state flag as specified by user since_token(StreamToken): The token supplied by user, or None. now_token(StreamToken): The token to sync up to.'
def __init__(self, sync_config, full_state, since_token, now_token):
self.sync_config = sync_config self.full_state = full_state self.since_token = since_token self.now_token = now_token self.presence = [] self.account_data = [] self.joined = [] self.invited = [] self.archived = [] self.device = []
'Args: room_id(str) rtype(str): One of `"joined"` or `"archived"` events(list): List of events to include in the room, (more events may be added when generating result). newly_joined(bool): If the user has newly joined the room full_state(bool): Whether the full state should be sent in result since_token(StreamToken): ...
def __init__(self, room_id, rtype, events, newly_joined, full_state, since_token, upto_token):
self.room_id = room_id self.rtype = rtype self.events = events self.newly_joined = newly_joined self.full_state = full_state self.since_token = since_token self.upto_token = upto_token
'Function to reterive a list of users in users table. Args: Returns: defer.Deferred: resolves to list[dict[str, Any]]'
@defer.inlineCallbacks def get_users(self):
ret = (yield self.store.get_users()) defer.returnValue(ret)