def test_evict(self): setup_expire_lru_cache_entries(self.hs) cache = LruCache(5, clock=self.hs.get_clock()) # Check that we evict entries we haven't accessed for 30 minutes. cache["key1"] = 1 cache["key2"] = 2 self.reactor.advance(20 * 60) self.assertEqual(cache.get("key1"), 1) self.reactor.advance(20 * 60) # We have only touched `key1` in the last 30m, so we expect that to # still be in the cache while `key2` should have been evicted. self.assertEqual(cache.get("key1"), 1) self.assertEqual(cache.get("key2"), None) # Check that re-adding an expired key works correctly. cache["key2"] = 3 self.assertEqual(cache.get("key2"), 3) self.reactor.advance(20 * 60) self.assertEqual(cache.get("key2"), 3) self.reactor.advance(20 * 60) self.assertEqual(cache.get("key1"), None) self.assertEqual(cache.get("key2"), 3)
def test_setdefault(self): cache = LruCache(1) self.assertEquals(cache.setdefault("key", 1), 1) self.assertEquals(cache.get("key"), 1) self.assertEquals(cache.setdefault("key", 2), 1) self.assertEquals(cache.get("key"), 1) cache["key"] = 2 # Make sure overriding works. self.assertEquals(cache.get("key"), 2)
def test_eviction(self): cache = LruCache(2) cache[1] = 1 cache[2] = 2 self.assertEquals(cache.get(1), 1) self.assertEquals(cache.get(2), 2) cache[3] = 3 self.assertEquals(cache.get(1), None) self.assertEquals(cache.get(2), 2) self.assertEquals(cache.get(3), 3)
class SlavedClientIpStore(BaseSlavedStore): def __init__(self, database: DatabasePool, db_conn, hs): super().__init__(database, db_conn, hs) self.client_ip_last_seen = LruCache( cache_name="client_ip_last_seen", keylen=4, max_size=50000) # type: LruCache[tuple, int] async def insert_client_ip(self, user_id, access_token, ip, user_agent, device_id): now = int(self._clock.time_msec()) key = (user_id, access_token, ip) try: last_seen = self.client_ip_last_seen.get(key) except KeyError: last_seen = None # Rate-limited inserts if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY: return self.client_ip_last_seen.set(key, now) self.hs.get_tcp_replication().send_user_ip(user_id, access_token, ip, user_agent, device_id, now)
def test_del_multi(self): cache = LruCache(4, 2, cache_type=TreeCache) cache[("animal", "cat")] = "mew" cache[("animal", "dog")] = "woof" cache[("vehicles", "car")] = "vroom" cache[("vehicles", "train")] = "chuff" self.assertEquals(len(cache), 4) self.assertEquals(cache.get(("animal", "cat")), "mew") self.assertEquals(cache.get(("vehicles", "car")), "vroom") cache.del_multi(("animal",)) self.assertEquals(len(cache), 2) self.assertEquals(cache.get(("animal", "cat")), None) self.assertEquals(cache.get(("animal", "dog")), None) self.assertEquals(cache.get(("vehicles", "car")), "vroom") self.assertEquals(cache.get(("vehicles", "train")), "chuff")
def test_get(self): m = Mock() cache = LruCache(1) cache.set("key", "value") self.assertFalse(m.called) cache.get("key", callbacks=[m]) self.assertFalse(m.called) cache.get("key", "value") self.assertFalse(m.called) cache.set("key", "value2") self.assertEquals(m.call_count, 1) cache.set("key", "value") self.assertEquals(m.call_count, 1)
def test_evict_memory(self, jemalloc_interface) -> None: mock_jemalloc_class = Mock(spec=JemallocStats) jemalloc_interface.return_value = mock_jemalloc_class # set the return value of get_stat() to be greater than max_cache_memory_usage mock_jemalloc_class.get_stat.return_value = 924288000 setup_expire_lru_cache_entries(self.hs) cache = LruCache(4, clock=self.hs.get_clock()) cache["key1"] = 1 cache["key2"] = 2 # advance the reactor less than the min_cache_ttl self.reactor.advance(60 * 2) # our items should still be in the cache self.assertEqual(cache.get("key1"), 1) self.assertEqual(cache.get("key2"), 2) # advance the reactor past the min_cache_ttl self.reactor.advance(60 * 6) # the items should be cleared from cache self.assertEqual(cache.get("key1"), None) self.assertEqual(cache.get("key2"), None) # add more stuff to caches cache["key1"] = 1 cache["key2"] = 2 # set the return value of get_stat() to be lower than target_cache_memory_usage mock_jemalloc_class.get_stat.return_value = 10000 # advance the reactor past the min_cache_ttl self.reactor.advance(60 * 6) # the items should still be in the cache self.assertEqual(cache.get("key1"), 1) self.assertEqual(cache.get("key2"), 2)
def test_eviction(self): m1 = Mock(name="m1") m2 = Mock(name="m2") m3 = Mock(name="m3") cache = LruCache(2) cache.set("key1", "value", callbacks=[m1]) cache.set("key2", "value", callbacks=[m2]) self.assertEquals(m1.call_count, 0) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 0) cache.set("key3", "value", callbacks=[m3]) self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 0) cache.set("key3", "value") self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 0) cache.get("key2") self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 0) cache.set("key1", "value", callbacks=[m1]) self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 1)
def test_evict(self): cache = LruCache(5, size_callback=len) cache["key1"] = [0] cache["key2"] = [1, 2] cache["key3"] = [3] cache["key4"] = [4] self.assertEquals(cache["key1"], [0]) self.assertEquals(cache["key2"], [1, 2]) self.assertEquals(cache["key3"], [3]) self.assertEquals(cache["key4"], [4]) self.assertEquals(len(cache), 5) cache["key5"] = [5, 6] self.assertEquals(len(cache), 4) self.assertEquals(cache.get("key1"), None) self.assertEquals(cache.get("key2"), None) self.assertEquals(cache["key3"], [3]) self.assertEquals(cache["key4"], [4]) self.assertEquals(cache["key5"], [5, 6])
class EventFederationWorkerStore(EventsWorkerStore, SignatureWorkerStore, SQLBaseStore): def __init__(self, database: DatabasePool, db_conn, hs): super().__init__(database, db_conn, hs) if hs.config.run_background_tasks: hs.get_clock().looping_call(self._delete_old_forward_extrem_cache, 60 * 60 * 1000) # Cache of event ID to list of auth event IDs and their depths. self._event_auth_cache = LruCache( 500000, "_event_auth_cache", size_callback=len) # type: LruCache[str, List[Tuple[str, int]]] async def get_auth_chain(self, event_ids: Collection[str], include_given: bool = False) -> List[EventBase]: """Get auth events for given event_ids. The events *must* be state events. Args: event_ids: state events include_given: include the given events in result Returns: list of events """ event_ids = await self.get_auth_chain_ids(event_ids, include_given=include_given) return await self.get_events_as_list(event_ids) async def get_auth_chain_ids( self, event_ids: Collection[str], include_given: bool = False, ) -> List[str]: """Get auth events for given event_ids. The events *must* be state events. Args: event_ids: state events include_given: include the given events in result Returns: An awaitable which resolve to a list of event_ids """ return await self.db_pool.runInteraction( "get_auth_chain_ids", self._get_auth_chain_ids_txn, event_ids, include_given, ) def _get_auth_chain_ids_txn(self, txn: LoggingTransaction, event_ids: Collection[str], include_given: bool) -> List[str]: if include_given: results = set(event_ids) else: results = set() # We pull out the depth simply so that we can populate the # `_event_auth_cache` cache. base_sql = """ SELECT a.event_id, auth_id, depth FROM event_auth AS a INNER JOIN events AS e ON (e.event_id = a.auth_id) WHERE """ front = set(event_ids) while front: new_front = set() for chunk in batch_iter(front, 100): # Pull the auth events either from the cache or DB. to_fetch = [] # Event IDs to fetch from DB # type: List[str] for event_id in chunk: res = self._event_auth_cache.get(event_id) if res is None: to_fetch.append(event_id) else: new_front.update(auth_id for auth_id, depth in res) if to_fetch: clause, args = make_in_list_sql_clause( txn.database_engine, "a.event_id", to_fetch) txn.execute(base_sql + clause, args) # Note we need to batch up the results by event ID before # adding to the cache. to_cache = {} for event_id, auth_event_id, auth_event_depth in txn: to_cache.setdefault(event_id, []).append( (auth_event_id, auth_event_depth)) new_front.add(auth_event_id) for event_id, auth_events in to_cache.items(): self._event_auth_cache.set(event_id, auth_events) new_front -= results front = new_front results.update(front) return list(results) async def get_auth_chain_difference( self, room_id: str, state_sets: List[Set[str]]) -> Set[str]: """Given sets of state events figure out the auth chain difference (as per state res v2 algorithm). This equivalent to fetching the full auth chain for each set of state and returning the events that don't appear in each and every auth chain. Returns: The set of the difference in auth chains. """ return await self.db_pool.runInteraction( "get_auth_chain_difference", self._get_auth_chain_difference_txn, state_sets, ) def _get_auth_chain_difference_txn(self, txn, state_sets: List[Set[str]]) -> Set[str]: # Algorithm Description # ~~~~~~~~~~~~~~~~~~~~~ # # The idea here is to basically walk the auth graph of each state set in # tandem, keeping track of which auth events are reachable by each state # set. If we reach an auth event we've already visited (via a different # state set) then we mark that auth event and all ancestors as reachable # by the state set. This requires that we keep track of the auth chains # in memory. # # Doing it in a such a way means that we can stop early if all auth # events we're currently walking are reachable by all state sets. # # *Note*: We can't stop walking an event's auth chain if it is reachable # by all state sets. This is because other auth chains we're walking # might be reachable only via the original auth chain. For example, # given the following auth chain: # # A -> C -> D -> E # / / # B -´---------´ # # and state sets {A} and {B} then walking the auth chains of A and B # would immediately show that C is reachable by both. However, if we # stopped at C then we'd only reach E via the auth chain of B and so E # would errornously get included in the returned difference. # # The other thing that we do is limit the number of auth chains we walk # at once, due to practical limits (i.e. we can only query the database # with a limited set of parameters). We pick the auth chains we walk # each iteration based on their depth, in the hope that events with a # lower depth are likely reachable by those with higher depths. # # We could use any ordering that we believe would give a rough # topological ordering, e.g. origin server timestamp. If the ordering # chosen is not topological then the algorithm still produces the right # result, but perhaps a bit more inefficiently. This is why it is safe # to use "depth" here. initial_events = set(state_sets[0]).union(*state_sets[1:]) # Dict from events in auth chains to which sets *cannot* reach them. # I.e. if the set is empty then all sets can reach the event. event_to_missing_sets = { event_id: {i for i, a in enumerate(state_sets) if event_id not in a} for event_id in initial_events } # The sorted list of events whose auth chains we should walk. search = [] # type: List[Tuple[int, str]] # We need to get the depth of the initial events for sorting purposes. sql = """ SELECT depth, event_id FROM events WHERE %s """ # the list can be huge, so let's avoid looking them all up in one massive # query. for batch in batch_iter(initial_events, 1000): clause, args = make_in_list_sql_clause(txn.database_engine, "event_id", batch) txn.execute(sql % (clause, ), args) # I think building a temporary list with fetchall is more efficient than # just `search.extend(txn)`, but this is unconfirmed search.extend(txn.fetchall()) # sort by depth search.sort() # Map from event to its auth events event_to_auth_events = {} # type: Dict[str, Set[str]] base_sql = """ SELECT a.event_id, auth_id, depth FROM event_auth AS a INNER JOIN events AS e ON (e.event_id = a.auth_id) WHERE """ while search: # Check whether all our current walks are reachable by all state # sets. If so we can bail. if all(not event_to_missing_sets[eid] for _, eid in search): break # Fetch the auth events and their depths of the N last events we're # currently walking, either from cache or DB. search, chunk = search[:-100], search[-100:] found = [] # Results found # type: List[Tuple[str, str, int]] to_fetch = [] # Event IDs to fetch from DB # type: List[str] for _, event_id in chunk: res = self._event_auth_cache.get(event_id) if res is None: to_fetch.append(event_id) else: found.extend( (event_id, auth_id, depth) for auth_id, depth in res) if to_fetch: clause, args = make_in_list_sql_clause(txn.database_engine, "a.event_id", to_fetch) txn.execute(base_sql + clause, args) # We parse the results and add the to the `found` set and the # cache (note we need to batch up the results by event ID before # adding to the cache). to_cache = {} for event_id, auth_event_id, auth_event_depth in txn: to_cache.setdefault(event_id, []).append( (auth_event_id, auth_event_depth)) found.append((event_id, auth_event_id, auth_event_depth)) for event_id, auth_events in to_cache.items(): self._event_auth_cache.set(event_id, auth_events) for event_id, auth_event_id, auth_event_depth in found: event_to_auth_events.setdefault(event_id, set()).add(auth_event_id) sets = event_to_missing_sets.get(auth_event_id) if sets is None: # First time we're seeing this event, so we add it to the # queue of things to fetch. search.append((auth_event_depth, auth_event_id)) # Assume that this event is unreachable from any of the # state sets until proven otherwise sets = event_to_missing_sets[auth_event_id] = set( range(len(state_sets))) else: # We've previously seen this event, so look up its auth # events and recursively mark all ancestors as reachable # by the current event's state set. a_ids = event_to_auth_events.get(auth_event_id) while a_ids: new_aids = set() for a_id in a_ids: event_to_missing_sets[a_id].intersection_update( event_to_missing_sets[event_id]) b = event_to_auth_events.get(a_id) if b: new_aids.update(b) a_ids = new_aids # Mark that the auth event is reachable by the approriate sets. sets.intersection_update(event_to_missing_sets[event_id]) search.sort() # Return all events where not all sets can reach them. return {eid for eid, n in event_to_missing_sets.items() if n} async def get_oldest_events_with_depth_in_room(self, room_id): return await self.db_pool.runInteraction( "get_oldest_events_with_depth_in_room", self.get_oldest_events_with_depth_in_room_txn, room_id, ) def get_oldest_events_with_depth_in_room_txn(self, txn, room_id): sql = ("SELECT b.event_id, MAX(e.depth) FROM events as e" " INNER JOIN event_edges as g" " ON g.event_id = e.event_id" " INNER JOIN event_backward_extremities as b" " ON g.prev_event_id = b.event_id" " WHERE b.room_id = ? AND g.is_state is ?" " GROUP BY b.event_id") txn.execute(sql, (room_id, False)) return dict(txn) async def get_max_depth_of(self, event_ids: List[str]) -> int: """Returns the max depth of a set of event IDs Args: event_ids: The event IDs to calculate the max depth of. """ rows = await self.db_pool.simple_select_many_batch( table="events", column="event_id", iterable=event_ids, retcols=("depth", ), desc="get_max_depth_of", ) if not rows: return 0 else: return max(row["depth"] for row in rows) async def get_prev_events_for_room(self, room_id: str) -> List[str]: """ Gets a subset of the current forward extremities in the given room. Limits the result to 10 extremities, so that we can avoid creating events which refer to hundreds of prev_events. Args: room_id: room_id Returns: The event ids of the forward extremities. """ return await self.db_pool.runInteraction( "get_prev_events_for_room", self._get_prev_events_for_room_txn, room_id) def _get_prev_events_for_room_txn(self, txn, room_id: str): # we just use the 10 newest events. Older events will become # prev_events of future events. sql = """ SELECT e.event_id FROM event_forward_extremities AS f INNER JOIN events AS e USING (event_id) WHERE f.room_id = ? ORDER BY e.depth DESC LIMIT 10 """ txn.execute(sql, (room_id, )) return [row[0] for row in txn] async def get_rooms_with_many_extremities( self, min_count: int, limit: int, room_id_filter: Iterable[str]) -> List[str]: """Get the top rooms with at least N extremities. Args: min_count: The minimum number of extremities limit: The maximum number of rooms to return. room_id_filter: room_ids to exclude from the results Returns: At most `limit` room IDs that have at least `min_count` extremities, sorted by extremity count. """ def _get_rooms_with_many_extremities_txn(txn): where_clause = "1=1" if room_id_filter: where_clause = "room_id NOT IN (%s)" % (",".join( "?" for _ in room_id_filter), ) sql = """ SELECT room_id FROM event_forward_extremities WHERE %s GROUP BY room_id HAVING count(*) > ? ORDER BY count(*) DESC LIMIT ? """ % (where_clause, ) query_args = list( itertools.chain(room_id_filter, [min_count, limit])) txn.execute(sql, query_args) return [room_id for room_id, in txn] return await self.db_pool.runInteraction( "get_rooms_with_many_extremities", _get_rooms_with_many_extremities_txn) @cached(max_entries=5000, iterable=True) async def get_latest_event_ids_in_room(self, room_id: str) -> List[str]: return await self.db_pool.simple_select_onecol( table="event_forward_extremities", keyvalues={"room_id": room_id}, retcol="event_id", desc="get_latest_event_ids_in_room", ) async def get_min_depth(self, room_id: str) -> int: """For the given room, get the minimum depth we have seen for it. """ return await self.db_pool.runInteraction( "get_min_depth", self._get_min_depth_interaction, room_id) def _get_min_depth_interaction(self, txn, room_id): min_depth = self.db_pool.simple_select_one_onecol_txn( txn, table="room_depth", keyvalues={"room_id": room_id}, retcol="min_depth", allow_none=True, ) return int(min_depth) if min_depth is not None else None async def get_forward_extremeties_for_room( self, room_id: str, stream_ordering: int) -> List[str]: """For a given room_id and stream_ordering, return the forward extremeties of the room at that point in "time". Throws a StoreError if we have since purged the index for stream_orderings from that point. Args: room_id: stream_ordering: Returns: A list of event_ids """ # We want to make the cache more effective, so we clamp to the last # change before the given ordering. last_change = self._events_stream_cache.get_max_pos_of_last_change( room_id) # We don't always have a full stream_to_exterm_id table, e.g. after # the upgrade that introduced it, so we make sure we never ask for a # stream_ordering from before a restart last_change = max(self._stream_order_on_start, last_change) # provided the last_change is recent enough, we now clamp the requested # stream_ordering to it. if last_change > self.stream_ordering_month_ago: stream_ordering = min(last_change, stream_ordering) return await self._get_forward_extremeties_for_room( room_id, stream_ordering) @cached(max_entries=5000, num_args=2) async def _get_forward_extremeties_for_room(self, room_id, stream_ordering): """For a given room_id and stream_ordering, return the forward extremeties of the room at that point in "time". Throws a StoreError if we have since purged the index for stream_orderings from that point. """ if stream_ordering <= self.stream_ordering_month_ago: raise StoreError( 400, "stream_ordering too old %s" % (stream_ordering, )) sql = """ SELECT event_id FROM stream_ordering_to_exterm INNER JOIN ( SELECT room_id, MAX(stream_ordering) AS stream_ordering FROM stream_ordering_to_exterm WHERE stream_ordering <= ? GROUP BY room_id ) AS rms USING (room_id, stream_ordering) WHERE room_id = ? """ def get_forward_extremeties_for_room_txn(txn): txn.execute(sql, (stream_ordering, room_id)) return [event_id for event_id, in txn] return await self.db_pool.runInteraction( "get_forward_extremeties_for_room", get_forward_extremeties_for_room_txn) async def get_backfill_events(self, room_id: str, event_list: list, limit: int): """Get a list of Events for a given topic that occurred before (and including) the events in event_list. Return a list of max size `limit` Args: room_id event_list limit """ event_ids = await self.db_pool.runInteraction( "get_backfill_events", self._get_backfill_events, room_id, event_list, limit, ) events = await self.get_events_as_list(event_ids) return sorted(events, key=lambda e: -e.depth) def _get_backfill_events(self, txn, room_id, event_list, limit): logger.debug("_get_backfill_events: %s, %r, %s", room_id, event_list, limit) event_results = set() # We want to make sure that we do a breadth-first, "depth" ordered # search. query = ("SELECT depth, prev_event_id FROM event_edges" " INNER JOIN events" " ON prev_event_id = events.event_id" " WHERE event_edges.event_id = ?" " AND event_edges.is_state = ?" " LIMIT ?") queue = PriorityQueue() for event_id in event_list: depth = self.db_pool.simple_select_one_onecol_txn( txn, table="events", keyvalues={ "event_id": event_id, "room_id": room_id }, retcol="depth", allow_none=True, ) if depth: queue.put((-depth, event_id)) while not queue.empty() and len(event_results) < limit: try: _, event_id = queue.get_nowait() except Empty: break if event_id in event_results: continue event_results.add(event_id) txn.execute(query, (event_id, False, limit - len(event_results))) for row in txn: if row[1] not in event_results: queue.put((-row[0], row[1])) return event_results async def get_missing_events(self, room_id, earliest_events, latest_events, limit): ids = await self.db_pool.runInteraction( "get_missing_events", self._get_missing_events, room_id, earliest_events, latest_events, limit, ) return await self.get_events_as_list(ids) def _get_missing_events(self, txn, room_id, earliest_events, latest_events, limit): seen_events = set(earliest_events) front = set(latest_events) - seen_events event_results = [] query = ("SELECT prev_event_id FROM event_edges " "WHERE room_id = ? AND event_id = ? AND is_state = ? " "LIMIT ?") while front and len(event_results) < limit: new_front = set() for event_id in front: txn.execute( query, (room_id, event_id, False, limit - len(event_results))) new_results = {t[0] for t in txn} - seen_events new_front |= new_results seen_events |= new_results event_results.extend(new_results) front = new_front # we built the list working backwards from latest_events; we now need to # reverse it so that the events are approximately chronological. event_results.reverse() return event_results async def get_successor_events(self, event_ids: Iterable[str]) -> List[str]: """Fetch all events that have the given events as a prev event Args: event_ids: The events to use as the previous events. """ rows = await self.db_pool.simple_select_many_batch( table="event_edges", column="prev_event_id", iterable=event_ids, retcols=("event_id", ), desc="get_successor_events", ) return [row["event_id"] for row in rows] @wrap_as_background_process("delete_old_forward_extrem_cache") async def _delete_old_forward_extrem_cache(self) -> None: def _delete_old_forward_extrem_cache_txn(txn): # Delete entries older than a month, while making sure we don't delete # the only entries for a room. sql = """ DELETE FROM stream_ordering_to_exterm WHERE room_id IN ( SELECT room_id FROM stream_ordering_to_exterm WHERE stream_ordering > ? ) AND stream_ordering < ? """ txn.execute(sql, (self.stream_ordering_month_ago, self.stream_ordering_month_ago)) await self.db_pool.runInteraction( "_delete_old_forward_extrem_cache", _delete_old_forward_extrem_cache_txn, )
class Auth(object): """ FIXME: This class contains a mix of functions for authenticating users of our client-server API and authenticating events added to room graphs. """ def __init__(self, hs): self.hs = hs self.clock = hs.get_clock() self.store = hs.get_datastore() self.state = hs.get_state_handler() self.token_cache = LruCache(CACHE_SIZE_FACTOR * 10000) register_cache("cache", "token_cache", self.token_cache) self._auth_blocking = AuthBlocking(self.hs) self._account_validity = hs.config.account_validity self._track_appservice_user_ips = hs.config.track_appservice_user_ips self._macaroon_secret_key = hs.config.macaroon_secret_key @defer.inlineCallbacks def check_from_context(self, room_version: str, event, context, do_sig_check=True): prev_state_ids = yield context.get_prev_state_ids() auth_events_ids = yield self.compute_auth_events( event, prev_state_ids, for_verification=True ) auth_events = yield self.store.get_events(auth_events_ids) auth_events = {(e.type, e.state_key): e for e in itervalues(auth_events)} room_version_obj = KNOWN_ROOM_VERSIONS[room_version] event_auth.check( room_version_obj, event, auth_events=auth_events, do_sig_check=do_sig_check ) @defer.inlineCallbacks def check_user_in_room( self, room_id: str, user_id: str, current_state: Optional[StateMap[EventBase]] = None, allow_departed_users: bool = False, ): """Check if the user is in the room, or was at some point. Args: room_id: The room to check. user_id: The user to check. current_state: 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 the database. allow_departed_users: if True, accept users that were previously members but have now departed. Raises: AuthError if the user is/was not in the room. Returns: Deferred[Optional[EventBase]]: 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 room. This will be the leave event if they have left the room. """ 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 ) membership = member.membership if member else None if membership == Membership.JOIN: return member # XXX this looks totally bogus. Why do we not allow users who have been banned, # or those who were members previously and have been re-invited? if allow_departed_users and membership == Membership.LEAVE: forgot = yield self.store.did_forget(user_id, room_id) if not forgot: return member raise AuthError(403, "User %s not in room %s" % (user_id, room_id)) @defer.inlineCallbacks def check_host_in_room(self, room_id, host): with Measure(self.clock, "check_host_in_room"): latest_event_ids = yield self.store.is_host_joined(room_id, host) return latest_event_ids def can_federate(self, event, auth_events): creation_event = auth_events.get((EventTypes.Create, "")) return creation_event.content.get("m.federate", True) is True def get_public_keys(self, invite_event): return event_auth.get_public_keys(invite_event) @defer.inlineCallbacks def get_user_by_req( self, request, allow_guest=False, rights="access", allow_expired=False ): """ Get a registered user's ID. Args: request - An HTTP request with an access_token query parameter. allow_expired - Whether to allow the request through even if the account is expired. If true, Synapse will still require an access token to be provided but won't check if the account it belongs to has expired. This works thanks to /login delivering access tokens regardless of accounts' expiration. Returns: defer.Deferred: resolves to a ``synapse.types.Requester`` object Raises: InvalidClientCredentialsError if no user by that token exists or the token is invalid. AuthError if access is denied for the user in the access token """ try: ip_addr = self.hs.get_ip_from_request(request) user_agent = request.requestHeaders.getRawHeaders( b"User-Agent", default=[b""] )[0].decode("ascii", "surrogateescape") access_token = self.get_access_token_from_request(request) user_id, app_service = yield self._get_appservice_user_id(request) if user_id: request.authenticated_entity = user_id opentracing.set_tag("authenticated_entity", user_id) opentracing.set_tag("appservice_id", app_service.id) if ip_addr and self._track_appservice_user_ips: yield self.store.insert_client_ip( user_id=user_id, access_token=access_token, ip=ip_addr, user_agent=user_agent, device_id="dummy-device", # stubbed ) return synapse.types.create_requester(user_id, app_service=app_service) user_info = yield self.get_user_by_access_token(access_token, rights) user = user_info["user"] token_id = user_info["token_id"] is_guest = user_info["is_guest"] # Deny the request if the user account has expired. if self._account_validity.enabled and not allow_expired: user_id = user.to_string() expiration_ts = yield self.store.get_expiration_ts_for_user(user_id) if ( expiration_ts is not None and self.clock.time_msec() >= expiration_ts ): raise AuthError( 403, "User account has expired", errcode=Codes.EXPIRED_ACCOUNT ) # device_id may not be present if get_user_by_access_token has been # stubbed out. device_id = user_info.get("device_id") if user and access_token and ip_addr: yield self.store.insert_client_ip( user_id=user.to_string(), access_token=access_token, ip=ip_addr, user_agent=user_agent, device_id=device_id, ) if is_guest and not allow_guest: raise AuthError( 403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN, ) request.authenticated_entity = user.to_string() opentracing.set_tag("authenticated_entity", user.to_string()) if device_id: opentracing.set_tag("device_id", device_id) return synapse.types.create_requester( user, token_id, is_guest, device_id, app_service=app_service ) except KeyError: raise MissingClientTokenError() @defer.inlineCallbacks def _get_appservice_user_id(self, request): app_service = self.store.get_app_service_by_token( self.get_access_token_from_request(request) ) if app_service is None: return None, None if app_service.ip_range_whitelist: ip_address = IPAddress(self.hs.get_ip_from_request(request)) if ip_address not in app_service.ip_range_whitelist: return None, None if b"user_id" not in request.args: return app_service.sender, app_service user_id = request.args[b"user_id"][0].decode("utf8") if app_service.sender == user_id: return app_service.sender, app_service if not app_service.is_interested_in_user(user_id): raise AuthError(403, "Application service cannot masquerade as this user.") if not (yield self.store.get_user_by_id(user_id)): raise AuthError(403, "Application service has not registered this user") return user_id, app_service @defer.inlineCallbacks def get_user_by_access_token(self, token, rights="access"): """ 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: Deferred[dict]: dict that includes: `user` (UserID) `is_guest` (bool) `token_id` (int|None): access token id. May be None if guest `device_id` (str|None): device corresponding to access token Raises: InvalidClientCredentialsError if no user by that token exists or the token is invalid. """ if rights == "access": # first look in the database r = yield self._look_up_user_by_access_token(token) if r: valid_until_ms = r["valid_until_ms"] if ( valid_until_ms is not None and valid_until_ms < self.clock.time_msec() ): # there was a valid access token, but it has expired. # soft-logout the user. raise InvalidClientTokenError( msg="Access token has expired", soft_logout=True ) return r # otherwise it needs to be a valid macaroon try: user_id, guest = self._parse_and_validate_macaroon(token, rights) user = UserID.from_string(user_id) if rights == "access": if not guest: # non-guest access tokens must be in the database logger.warning("Unrecognised access token - not in store.") raise InvalidClientTokenError() # Guest access tokens are not stored in the database (there can # only be one access token per guest, anyway). # # In order to prevent guest access tokens being used as regular # user access tokens (and hence getting around the invalidation # process), we look up the user id and check that it is indeed # a guest user. # # It would of course be much easier to store guest access # tokens in the database as well, but that would break existing # guest tokens. stored_user = yield self.store.get_user_by_id(user_id) if not stored_user: raise InvalidClientTokenError("Unknown user_id %s" % user_id) if not stored_user["is_guest"]: raise InvalidClientTokenError( "Guest access token used for regular user" ) ret = { "user": user, "is_guest": True, "token_id": None, # all guests get the same device id "device_id": GUEST_DEVICE_ID, } elif rights == "delete_pusher": # We don't store these tokens in the database ret = { "user": user, "is_guest": False, "token_id": None, "device_id": None, } else: raise RuntimeError("Unknown rights setting %s", rights) return ret except ( _InvalidMacaroonException, pymacaroons.exceptions.MacaroonException, TypeError, ValueError, ) as e: logger.warning("Invalid macaroon in auth: %s %s", type(e), e) raise InvalidClientTokenError("Invalid macaroon passed.") def _parse_and_validate_macaroon(self, token, rights="access"): """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) """ if rights == "access": cached = self.token_cache.get(token, None) if cached: return cached try: macaroon = pymacaroons.Macaroon.deserialize(token) except Exception: # deserialize can throw more-or-less anything # doesn't look like a macaroon: treat it as an opaque token which # must be in the database. # TODO: it would be nice to get rid of this, but apparently some # people use access tokens which aren't macaroons raise _InvalidMacaroonException() try: user_id = self.get_user_id_from_macaroon(macaroon) guest = False for caveat in macaroon.caveats: if caveat.caveat_id == "guest = true": guest = True self.validate_macaroon(macaroon, rights, user_id=user_id) except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError): raise InvalidClientTokenError("Invalid macaroon passed.") if rights == "access": self.token_cache[token] = (user_id, guest) return user_id, guest def get_user_id_from_macaroon(self, macaroon): """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: InvalidClientCredentialsError if there is no user_id caveat in the 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 InvalidClientTokenError("No user caveat in macaroon") def validate_macaroon(self, macaroon, type_string, user_id): """ 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") user_id (str): The user_id required """ v = pymacaroons.Verifier() # the verifier runs a test for every caveat on the macaroon, to check # that it is met for the current request. Each caveat must match at # least one of the predicates specified by satisfy_exact or # specify_general. v.satisfy_exact("gen = 1") v.satisfy_exact("type = " + type_string) v.satisfy_exact("user_id = %s" % user_id) v.satisfy_exact("guest = true") v.satisfy_general(self._verify_expiry) # access_tokens include a nonce for uniqueness: any value is acceptable v.satisfy_general(lambda c: c.startswith("nonce = ")) v.verify(macaroon, self._macaroon_secret_key) def _verify_expiry(self, caveat): prefix = "time < " if not caveat.startswith(prefix): return False expiry = int(caveat[len(prefix) :]) now = self.hs.get_clock().time_msec() return now < expiry @defer.inlineCallbacks def _look_up_user_by_access_token(self, token): ret = yield self.store.get_user_by_access_token(token) if not ret: return None # we use ret.get() below because *lots* of unit tests stub out # get_user_by_access_token in a way where it only returns a couple of # the fields. user_info = { "user": UserID.from_string(ret.get("name")), "token_id": ret.get("token_id", None), "is_guest": False, "device_id": ret.get("device_id"), "valid_until_ms": ret.get("valid_until_ms"), } return user_info def get_appservice_by_req(self, request): token = self.get_access_token_from_request(request) service = self.store.get_app_service_by_token(token) if not service: logger.warning("Unrecognised appservice access token.") raise InvalidClientTokenError() request.authenticated_entity = service.sender return defer.succeed(service) def is_server_admin(self, user): """ Check if the given user is a local server admin. Args: user (UserID): user to check Returns: bool: True if the user is an admin """ return self.store.is_server_admin(user) def compute_auth_events( self, event, current_state_ids: StateMap[str], for_verification: bool = False, ): """Given an event and current state return the list of event IDs used to auth an event. If `for_verification` is False then only return auth events that should be added to the event's `auth_events`. Returns: defer.Deferred(list[str]): List of event IDs. """ if event.type == EventTypes.Create: return defer.succeed([]) # Currently we ignore the `for_verification` flag even though there are # some situations where we can drop particular auth events when adding # to the event's `auth_events` (e.g. joins pointing to previous joins # when room is publically joinable). Dropping event IDs has the # advantage that the auth chain for the room grows slower, but we use # the auth chain in state resolution v2 to order events, which means # care must be taken if dropping events to ensure that it doesn't # introduce undesirable "state reset" behaviour. # # All of which sounds a bit tricky so we don't bother for now. auth_ids = [] for etype, state_key in event_auth.auth_types_for_event(event): auth_ev_id = current_state_ids.get((etype, state_key)) if auth_ev_id: auth_ids.append(auth_ev_id) return defer.succeed(auth_ids) async def check_can_change_room_list(self, room_id: str, user: UserID): """Determine whether the user is allowed to edit the room's entry in the published room list. Args: room_id user """ is_admin = await self.is_server_admin(user) if is_admin: return True user_id = user.to_string() await self.check_user_in_room(room_id, user_id) # We currently require the user is a "moderator" in the room. We do this # by checking if they would (theoretically) be able to change the # m.room.canonical_alias events power_level_event = await self.state.get_current_state( room_id, EventTypes.PowerLevels, "" ) auth_events = {} if power_level_event: auth_events[(EventTypes.PowerLevels, "")] = power_level_event send_level = event_auth.get_send_level( EventTypes.CanonicalAlias, "", power_level_event ) user_level = event_auth.get_user_power_level(user_id, auth_events) return user_level >= send_level @staticmethod def has_access_token(request): """Checks if the request has an access_token. Returns: bool: False if no access_token was given, True otherwise. """ query_params = request.args.get(b"access_token") auth_headers = request.requestHeaders.getRawHeaders(b"Authorization") return bool(query_params) or bool(auth_headers) @staticmethod def get_access_token_from_request(request): """Extracts the access_token from the request. Args: request: The http request. Returns: unicode: The access_token Raises: MissingClientTokenError: If there isn't a single access_token in the request """ auth_headers = request.requestHeaders.getRawHeaders(b"Authorization") query_params = request.args.get(b"access_token") if auth_headers: # Try the get the access_token from a "Authorization: Bearer" # header if query_params is not None: raise MissingClientTokenError( "Mixing Authorization headers and access_token query parameters." ) if len(auth_headers) > 1: raise MissingClientTokenError("Too many Authorization headers.") parts = auth_headers[0].split(b" ") if parts[0] == b"Bearer" and len(parts) == 2: return parts[1].decode("ascii") else: raise MissingClientTokenError("Invalid Authorization header.") else: # Try to get the access_token from the query params. if not query_params: raise MissingClientTokenError() return query_params[0].decode("ascii") @defer.inlineCallbacks def check_user_in_room_or_world_readable( self, room_id: str, user_id: str, allow_departed_users: bool = False ): """Checks that the user is or was in the room or the room is world readable. If it isn't then an exception is raised. Args: room_id: room to check user_id: user to check allow_departed_users: if True, accept users that were previously members but have now departed Returns: Deferred[tuple[str, str|None]]: Resolves to the current membership of the user in the room and the membership event ID of the user. If the user is not in the room and never has been, then `(Membership.JOIN, None)` is returned. """ try: # check_user_in_room will return the most recent membership # event for the user if: # * The user is a non-guest user, and was ever in the room # * The user is a guest user, and has joined the room # else it will throw. member_event = yield self.check_user_in_room( room_id, user_id, allow_departed_users=allow_departed_users ) return member_event.membership, member_event.event_id except AuthError: visibility = yield self.state.get_current_state( room_id, EventTypes.RoomHistoryVisibility, "" ) if ( visibility and visibility.content["history_visibility"] == "world_readable" ): return Membership.JOIN, None raise AuthError( 403, "User %s not in room %s, and room previews are disabled" % (user_id, room_id), ) def check_auth_blocking(self, *args, **kwargs): return self._auth_blocking.check_auth_blocking(*args, **kwargs)
class DictionaryCache(object): """Caches key -> dictionary lookups, supporting caching partial dicts, i.e. fetching a subset of dictionary keys for a particular key. """ def __init__(self, name, max_entries=1000): self.cache = LruCache(max_size=max_entries) self.name = name self.sequence = 0 self.thread = None # caches_by_name[name] = self.cache class Sentinel(object): __slots__ = [] self.sentinel = Sentinel() caches_by_name[name] = self.cache def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get(self, key, dict_keys=None): entry = self.cache.get(key, self.sentinel) if entry is not self.sentinel: cache_counter.inc_hits(self.name) if dict_keys is None: return DictionaryEntry(entry.full, dict(entry.value)) else: return DictionaryEntry(entry.full, { k: entry.value[k] for k in dict_keys if k in entry.value }) cache_counter.inc_misses(self.name) return DictionaryEntry(False, {}) def invalidate(self, key): self.check_thread() # Increment the sequence number so that any SELECT statements that # raced with the INSERT don't update the cache (SYN-369) self.sequence += 1 self.cache.pop(key, None) def invalidate_all(self): self.check_thread() self.sequence += 1 self.cache.clear() def update(self, sequence, key, value, full=False): self.check_thread() if self.sequence == sequence: # Only update the cache if the caches sequence number matches the # number that the cache had before the SELECT was started (SYN-369) if full: self._insert(key, value) else: self._update_or_insert(key, value) def _update_or_insert(self, key, value): entry = self.cache.setdefault(key, DictionaryEntry(False, {})) entry.value.update(value) def _insert(self, key, value): self.cache[key] = DictionaryEntry(True, value)
class Cache(object): __slots__ = ( "cache", "max_entries", "name", "keylen", "thread", "metrics", "_pending_deferred_cache", ) def __init__(self, name, max_entries=1000, keylen=1, tree=False, iterable=False): cache_type = TreeCache if tree else dict self._pending_deferred_cache = cache_type() self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type, size_callback=(lambda d: len(d)) if iterable else None, evicted_callback=self._on_evicted, ) self.name = name self.keylen = keylen self.thread = None self.metrics = register_cache("cache", name, self.cache) def _on_evicted(self, evicted_count): self.metrics.inc_evictions(evicted_count) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True): """Looks the key up in the caches. Args: key(tuple) default: What is returned if key is not in the caches. If not specified then function throws KeyError instead callback(fn): Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: Either a Deferred or the raw result """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _CacheSentinel) if val is not _CacheSentinel: val.callbacks.update(callbacks) if update_metrics: self.metrics.inc_hits() return val.deferred val = self.cache.get(key, _CacheSentinel, callbacks=callbacks) if val is not _CacheSentinel: self.metrics.inc_hits() return val if update_metrics: self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def set(self, key, value, callback=None): callbacks = [callback] if callback else [] self.check_thread() entry = CacheEntry( deferred=value, callbacks=callbacks, ) existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() self._pending_deferred_cache[key] = entry def shuffle(result): existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: self.cache.set(key, result, entry.callbacks) else: # oops, the _pending_deferred_cache has been updated since # we started our query, so we are out of date. # # Better put back whatever we took out. (We do it this way # round, rather than peeking into the _pending_deferred_cache # and then removing on a match, to make the common case faster) if existing_entry is not None: self._pending_deferred_cache[key] = existing_entry # we're not going to put this entry into the cache, so need # to make sure that the invalidation callbacks are called. # That was probably done when _pending_deferred_cache was # updated, but it's possible that `set` was called without # `invalidate` being previously called, in which case it may # not have been. Either way, let's double-check now. entry.invalidate() return result entry.deferred.addCallback(shuffle) def prefill(self, key, value, callback=None): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): self.check_thread() self.cache.pop(key, None) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, which will (a) stop it being returned # for future queries and (b) stop it being persisted as a proper entry # in self.cache. entry = self._pending_deferred_cache.pop(key, None) # run the invalidation callbacks now, rather than waiting for the # deferred to resolve. if entry: entry.invalidate() def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError( "The cache key must be a tuple not %r" % (type(key),) ) self.cache.del_multi(key) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, as above entry_dict = self._pending_deferred_cache.pop(key, None) if entry_dict is not None: for entry in iterate_tree_cache_entry(entry_dict): entry.invalidate() def invalidate_all(self): self.check_thread() self.cache.clear() for entry in itervalues(self._pending_deferred_cache): entry.invalidate() self._pending_deferred_cache.clear()
class Cache(object): __slots__ = ( "cache", "max_entries", "name", "keylen", "thread", "metrics", "_pending_deferred_cache", ) def __init__(self, name, max_entries=1000, keylen=1, tree=False, iterable=False): cache_type = TreeCache if tree else dict self._pending_deferred_cache = cache_type() self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type, size_callback=(lambda d: len(d)) if iterable else None, evicted_callback=self._on_evicted, ) self.name = name self.keylen = keylen self.thread = None self.metrics = register_cache("cache", name, self.cache) def _on_evicted(self, evicted_count): self.metrics.inc_evictions(evicted_count) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread") def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True): """Looks the key up in the caches. Args: key(tuple) default: What is returned if key is not in the caches. If not specified then function throws KeyError instead callback(fn): Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: Either a Deferred or the raw result """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _CacheSentinel) if val is not _CacheSentinel: val.callbacks.update(callbacks) if update_metrics: self.metrics.inc_hits() return val.deferred val = self.cache.get(key, _CacheSentinel, callbacks=callbacks) if val is not _CacheSentinel: self.metrics.inc_hits() return val if update_metrics: self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def set(self, key, value, callback=None): callbacks = [callback] if callback else [] self.check_thread() entry = CacheEntry( deferred=value, callbacks=callbacks, ) existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() self._pending_deferred_cache[key] = entry def shuffle(result): existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: self.cache.set(key, result, entry.callbacks) else: # oops, the _pending_deferred_cache has been updated since # we started our query, so we are out of date. # # Better put back whatever we took out. (We do it this way # round, rather than peeking into the _pending_deferred_cache # and then removing on a match, to make the common case faster) if existing_entry is not None: self._pending_deferred_cache[key] = existing_entry # we're not going to put this entry into the cache, so need # to make sure that the invalidation callbacks are called. # That was probably done when _pending_deferred_cache was # updated, but it's possible that `set` was called without # `invalidate` being previously called, in which case it may # not have been. Either way, let's double-check now. entry.invalidate() return result entry.deferred.addCallback(shuffle) def prefill(self, key, value, callback=None): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): self.check_thread() self.cache.pop(key, None) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, which will (a) stop it being returned # for future queries and (b) stop it being persisted as a proper entry # in self.cache. entry = self._pending_deferred_cache.pop(key, None) # run the invalidation callbacks now, rather than waiting for the # deferred to resolve. if entry: entry.invalidate() def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError("The cache key must be a tuple not %r" % (type(key), )) self.cache.del_multi(key) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, as above entry_dict = self._pending_deferred_cache.pop(key, None) if entry_dict is not None: for entry in iterate_tree_cache_entry(entry_dict): entry.invalidate() def invalidate_all(self): self.check_thread() self.cache.clear() for entry in itervalues(self._pending_deferred_cache): entry.invalidate() self._pending_deferred_cache.clear()
class Cache(object): __slots__ = ( "cache", "max_entries", "name", "keylen", "sequence", "thread", "metrics", "_pending_deferred_cache", ) def __init__(self, name, max_entries=1000, keylen=1, tree=False, iterable=False): cache_type = TreeCache if tree else dict self._pending_deferred_cache = cache_type() self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type, size_callback=(lambda d: len(d)) if iterable else None, ) self.name = name self.keylen = keylen self.sequence = 0 self.thread = None self.metrics = register_cache(name, self.cache) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True): """Looks the key up in the caches. Args: key(tuple) default: What is returned if key is not in the caches. If not specified then function throws KeyError instead callback(fn): Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: Either a Deferred or the raw result """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _CacheSentinel) if val is not _CacheSentinel: if val.sequence == self.sequence: val.callbacks.update(callbacks) if update_metrics: self.metrics.inc_hits() return val.deferred val = self.cache.get(key, _CacheSentinel, callbacks=callbacks) if val is not _CacheSentinel: self.metrics.inc_hits() return val if update_metrics: self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def set(self, key, value, callback=None): callbacks = [callback] if callback else [] self.check_thread() entry = CacheEntry( deferred=value, sequence=self.sequence, callbacks=callbacks, ) entry.callbacks.update(callbacks) existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() self._pending_deferred_cache[key] = entry def shuffle(result): if self.sequence == entry.sequence: existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: self.cache.set(key, result, entry.callbacks) else: entry.invalidate() else: entry.invalidate() return result entry.deferred.addCallback(shuffle) def prefill(self, key, value, callback=None): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): self.check_thread() # Increment the sequence number so that any SELECT statements that # raced with the INSERT don't update the cache (SYN-369) self.sequence += 1 entry = self._pending_deferred_cache.pop(key, None) if entry: entry.invalidate() self.cache.pop(key, None) def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError( "The cache key must be a tuple not %r" % (type(key),) ) self.sequence += 1 self.cache.del_multi(key) entry_dict = self._pending_deferred_cache.pop(key, None) if entry_dict is not None: for entry in iterate_tree_cache_entry(entry_dict): entry.invalidate() def invalidate_all(self): self.check_thread() self.sequence += 1 self.cache.clear()
class DictionaryCache(object): """Caches key -> dictionary lookups, supporting caching partial dicts, i.e. fetching a subset of dictionary keys for a particular key. """ def __init__(self, name, max_entries=1000): self.cache = LruCache(max_size=max_entries) self.name = name self.sequence = 0 self.thread = None # caches_by_name[name] = self.cache class Sentinel(object): __slots__ = [] self.sentinel = Sentinel() caches_by_name[name] = self.cache def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread") def get(self, key, dict_keys=None): entry = self.cache.get(key, self.sentinel) if entry is not self.sentinel: cache_counter.inc_hits(self.name) if dict_keys is None: return DictionaryEntry(entry.full, dict(entry.value)) else: return DictionaryEntry( entry.full, {k: entry.value[k] for k in dict_keys if k in entry.value}) cache_counter.inc_misses(self.name) return DictionaryEntry(False, {}) def invalidate(self, key): self.check_thread() # Increment the sequence number so that any SELECT statements that # raced with the INSERT don't update the cache (SYN-369) self.sequence += 1 self.cache.pop(key, None) def invalidate_all(self): self.check_thread() self.sequence += 1 self.cache.clear() def update(self, sequence, key, value, full=False): self.check_thread() if self.sequence == sequence: # Only update the cache if the caches sequence number matches the # number that the cache had before the SELECT was started (SYN-369) if full: self._insert(key, value) else: self._update_or_insert(key, value) def _update_or_insert(self, key, value): entry = self.cache.setdefault(key, DictionaryEntry(False, {})) entry.value.update(value) def _insert(self, key, value): self.cache[key] = DictionaryEntry(True, value)
def test_get_set(self): cache = LruCache(1) cache["key"] = "value" self.assertEquals(cache.get("key"), "value") self.assertEquals(cache["key"], "value")
def test_setdefault(self): cache = LruCache(1) self.assertEquals(cache.setdefault("key", 1), 1) self.assertEquals(cache.get("key"), 1) self.assertEquals(cache.setdefault("key", 2), 1) self.assertEquals(cache.get("key"), 1)
class Auth(object): """ FIXME: This class contains a mix of functions for authenticating users of our client-server API and authenticating events added to room graphs. """ def __init__(self, hs): self.hs = hs self.clock = hs.get_clock() self.store = hs.get_datastore() self.state = hs.get_state_handler() self.token_cache = LruCache(CACHE_SIZE_FACTOR * 10000) register_cache("cache", "token_cache", self.token_cache) self._account_validity = hs.config.account_validity @defer.inlineCallbacks def check_from_context(self, room_version, event, context, do_sig_check=True): prev_state_ids = yield context.get_prev_state_ids(self.store) auth_events_ids = yield self.compute_auth_events(event, prev_state_ids, for_verification=True) auth_events = yield self.store.get_events(auth_events_ids) auth_events = {(e.type, e.state_key): e for e in itervalues(auth_events)} event_auth.check(room_version, event, auth_events=auth_events, do_sig_check=do_sig_check) @defer.inlineCallbacks def check_joined_room(self, room_id, user_id, current_state=None): """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 the database. Raises: AuthError if the user is not in the room. Returns: A deferred membership event for the user if the user is in the room. """ 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) return member @defer.inlineCallbacks def check_user_was_in_room(self, room_id, user_id): """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 room. This will be the leave event if they have left the room. """ 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, room_id)) if membership == Membership.LEAVE: forgot = yield self.store.did_forget(user_id, room_id) if forgot: raise AuthError(403, "User %s not in room %s" % (user_id, room_id)) return member @defer.inlineCallbacks def check_host_in_room(self, room_id, host): with Measure(self.clock, "check_host_in_room"): latest_event_ids = yield self.store.is_host_joined(room_id, host) return latest_event_ids def _check_joined_room(self, member, user_id, room_id): if not member or member.membership != Membership.JOIN: raise AuthError( 403, "User %s not in room %s (%s)" % (user_id, room_id, repr(member))) def can_federate(self, event, auth_events): creation_event = auth_events.get((EventTypes.Create, "")) return creation_event.content.get("m.federate", True) is True def get_public_keys(self, invite_event): return event_auth.get_public_keys(invite_event) @defer.inlineCallbacks def get_user_by_req(self, request, allow_guest=False, rights="access", allow_expired=False): """ Get a registered user's ID. Args: request - An HTTP request with an access_token query parameter. allow_expired - Whether to allow the request through even if the account is expired. If true, Synapse will still require an access token to be provided but won't check if the account it belongs to has expired. This works thanks to /login delivering access tokens regardless of accounts' expiration. Returns: defer.Deferred: resolves to a ``synapse.types.Requester`` object Raises: InvalidClientCredentialsError if no user by that token exists or the token is invalid. AuthError if access is denied for the user in the access token """ try: ip_addr = self.hs.get_ip_from_request(request) user_agent = request.requestHeaders.getRawHeaders( b"User-Agent", default=[b""])[0].decode("ascii", "surrogateescape") access_token = self.get_access_token_from_request(request) user_id, app_service = yield self._get_appservice_user_id(request) if user_id: request.authenticated_entity = user_id opentracing.set_tag("authenticated_entity", user_id) opentracing.set_tag("appservice_id", app_service.id) if ip_addr and self.hs.config.track_appservice_user_ips: yield self.store.insert_client_ip( user_id=user_id, access_token=access_token, ip=ip_addr, user_agent=user_agent, device_id="dummy-device", # stubbed ) return synapse.types.create_requester(user_id, app_service=app_service) user_info = yield self.get_user_by_access_token( access_token, rights) user = user_info["user"] token_id = user_info["token_id"] is_guest = user_info["is_guest"] # Deny the request if the user account has expired. if self._account_validity.enabled and not allow_expired: user_id = user.to_string() expiration_ts = yield self.store.get_expiration_ts_for_user( user_id) if (expiration_ts is not None and self.clock.time_msec() >= expiration_ts): raise AuthError(403, "User account has expired", errcode=Codes.EXPIRED_ACCOUNT) # device_id may not be present if get_user_by_access_token has been # stubbed out. device_id = user_info.get("device_id") if user and access_token and ip_addr: yield self.store.insert_client_ip( user_id=user.to_string(), access_token=access_token, ip=ip_addr, user_agent=user_agent, device_id=device_id, ) if is_guest and not allow_guest: raise AuthError( 403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN, ) request.authenticated_entity = user.to_string() opentracing.set_tag("authenticated_entity", user.to_string()) if device_id: opentracing.set_tag("device_id", device_id) return synapse.types.create_requester(user, token_id, is_guest, device_id, app_service=app_service) except KeyError: raise MissingClientTokenError() @defer.inlineCallbacks def _get_appservice_user_id(self, request): app_service = self.store.get_app_service_by_token( self.get_access_token_from_request(request)) if app_service is None: return None, None if app_service.ip_range_whitelist: ip_address = IPAddress(self.hs.get_ip_from_request(request)) if ip_address not in app_service.ip_range_whitelist: return None, None if b"user_id" not in request.args: return app_service.sender, app_service user_id = request.args[b"user_id"][0].decode("utf8") if app_service.sender == user_id: return app_service.sender, app_service if not app_service.is_interested_in_user(user_id): raise AuthError( 403, "Application service cannot masquerade as this user.") if not (yield self.store.get_user_by_id(user_id)): raise AuthError( 403, "Application service has not registered this user") return user_id, app_service @defer.inlineCallbacks def get_user_by_access_token(self, token, rights="access"): """ 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: Deferred[dict]: dict that includes: `user` (UserID) `is_guest` (bool) `token_id` (int|None): access token id. May be None if guest `device_id` (str|None): device corresponding to access token Raises: InvalidClientCredentialsError if no user by that token exists or the token is invalid. """ if rights == "access": # first look in the database r = yield self._look_up_user_by_access_token(token) if r: valid_until_ms = r["valid_until_ms"] if (valid_until_ms is not None and valid_until_ms < self.clock.time_msec()): # there was a valid access token, but it has expired. # soft-logout the user. raise InvalidClientTokenError( msg="Access token has expired", soft_logout=True) return r # otherwise it needs to be a valid macaroon try: user_id, guest = self._parse_and_validate_macaroon(token, rights) user = UserID.from_string(user_id) if rights == "access": if not guest: # non-guest access tokens must be in the database logger.warning("Unrecognised access token - not in store.") raise InvalidClientTokenError() # Guest access tokens are not stored in the database (there can # only be one access token per guest, anyway). # # In order to prevent guest access tokens being used as regular # user access tokens (and hence getting around the invalidation # process), we look up the user id and check that it is indeed # a guest user. # # It would of course be much easier to store guest access # tokens in the database as well, but that would break existing # guest tokens. stored_user = yield self.store.get_user_by_id(user_id) if not stored_user: raise InvalidClientTokenError("Unknown user_id %s" % user_id) if not stored_user["is_guest"]: raise InvalidClientTokenError( "Guest access token used for regular user") ret = { "user": user, "is_guest": True, "token_id": None, # all guests get the same device id "device_id": GUEST_DEVICE_ID, } elif rights == "delete_pusher": # We don't store these tokens in the database ret = { "user": user, "is_guest": False, "token_id": None, "device_id": None, } else: raise RuntimeError("Unknown rights setting %s", rights) return ret except ( _InvalidMacaroonException, pymacaroons.exceptions.MacaroonException, TypeError, ValueError, ) as e: logger.warning("Invalid macaroon in auth: %s %s", type(e), e) raise InvalidClientTokenError("Invalid macaroon passed.") def _parse_and_validate_macaroon(self, token, rights="access"): """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) """ if rights == "access": cached = self.token_cache.get(token, None) if cached: return cached try: macaroon = pymacaroons.Macaroon.deserialize(token) except Exception: # deserialize can throw more-or-less anything # doesn't look like a macaroon: treat it as an opaque token which # must be in the database. # TODO: it would be nice to get rid of this, but apparently some # people use access tokens which aren't macaroons raise _InvalidMacaroonException() try: user_id = self.get_user_id_from_macaroon(macaroon) guest = False for caveat in macaroon.caveats: if caveat.caveat_id == "guest = true": guest = True self.validate_macaroon(macaroon, rights, user_id=user_id) except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError): raise InvalidClientTokenError("Invalid macaroon passed.") if rights == "access": self.token_cache[token] = (user_id, guest) return user_id, guest def get_user_id_from_macaroon(self, macaroon): """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: InvalidClientCredentialsError if there is no user_id caveat in the 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 InvalidClientTokenError("No user caveat in macaroon") def validate_macaroon(self, macaroon, type_string, user_id): """ 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") user_id (str): The user_id required """ v = pymacaroons.Verifier() # the verifier runs a test for every caveat on the macaroon, to check # that it is met for the current request. Each caveat must match at # least one of the predicates specified by satisfy_exact or # specify_general. v.satisfy_exact("gen = 1") v.satisfy_exact("type = " + type_string) v.satisfy_exact("user_id = %s" % user_id) v.satisfy_exact("guest = true") v.satisfy_general(self._verify_expiry) # access_tokens include a nonce for uniqueness: any value is acceptable v.satisfy_general(lambda c: c.startswith("nonce = ")) v.verify(macaroon, self.hs.config.macaroon_secret_key) def _verify_expiry(self, caveat): prefix = "time < " if not caveat.startswith(prefix): return False expiry = int(caveat[len(prefix):]) now = self.hs.get_clock().time_msec() return now < expiry @defer.inlineCallbacks def _look_up_user_by_access_token(self, token): ret = yield self.store.get_user_by_access_token(token) if not ret: return None # we use ret.get() below because *lots* of unit tests stub out # get_user_by_access_token in a way where it only returns a couple of # the fields. user_info = { "user": UserID.from_string(ret.get("name")), "token_id": ret.get("token_id", None), "is_guest": False, "device_id": ret.get("device_id"), "valid_until_ms": ret.get("valid_until_ms"), } return user_info def get_appservice_by_req(self, request): token = self.get_access_token_from_request(request) service = self.store.get_app_service_by_token(token) if not service: logger.warn("Unrecognised appservice access token.") raise InvalidClientTokenError() request.authenticated_entity = service.sender return defer.succeed(service) def is_server_admin(self, user): """ Check if the given user is a local server admin. Args: user (UserID): user to check Returns: bool: True if the user is an admin """ return self.store.is_server_admin(user) @defer.inlineCallbacks def compute_auth_events(self, event, current_state_ids, for_verification=False): if event.type == EventTypes.Create: return [] auth_ids = [] key = (EventTypes.PowerLevels, "") power_level_event_id = current_state_ids.get(key) if power_level_event_id: auth_ids.append(power_level_event_id) key = (EventTypes.JoinRules, "") join_rule_event_id = current_state_ids.get(key) key = (EventTypes.Member, event.sender) member_event_id = current_state_ids.get(key) key = (EventTypes.Create, "") create_event_id = current_state_ids.get(key) if create_event_id: auth_ids.append(create_event_id) if join_rule_event_id: join_rule_event = yield self.store.get_event(join_rule_event_id) join_rule = join_rule_event.content.get("join_rule") is_public = join_rule == JoinRules.PUBLIC if join_rule else False else: is_public = False if event.type == EventTypes.Member: e_type = event.content["membership"] if e_type in [Membership.JOIN, Membership.INVITE]: if join_rule_event_id: auth_ids.append(join_rule_event_id) if e_type == Membership.JOIN: if member_event_id and not is_public: auth_ids.append(member_event_id) else: if member_event_id: auth_ids.append(member_event_id) if for_verification: key = (EventTypes.Member, event.state_key) existing_event_id = current_state_ids.get(key) if existing_event_id: auth_ids.append(existing_event_id) if e_type == Membership.INVITE: if "third_party_invite" in event.content: key = ( EventTypes.ThirdPartyInvite, event.content["third_party_invite"]["signed"]["token"], ) third_party_invite_id = current_state_ids.get(key) if third_party_invite_id: auth_ids.append(third_party_invite_id) elif member_event_id: member_event = yield self.store.get_event(member_event_id) if member_event.content["membership"] == Membership.JOIN: auth_ids.append(member_event.event_id) return auth_ids @defer.inlineCallbacks def check_can_change_room_list(self, room_id, user): """Check if the user is allowed to edit the room's entry in the published room list. Args: room_id (str) user (UserID) """ is_admin = yield self.is_server_admin(user) if is_admin: return True user_id = user.to_string() yield self.check_joined_room(room_id, user_id) # We currently require the user is a "moderator" in the room. We do this # by checking if they would (theoretically) be able to change the # m.room.aliases events power_level_event = yield self.state.get_current_state( room_id, EventTypes.PowerLevels, "") auth_events = {} if power_level_event: auth_events[(EventTypes.PowerLevels, "")] = power_level_event send_level = event_auth.get_send_level(EventTypes.Aliases, "", power_level_event) user_level = event_auth.get_user_power_level(user_id, auth_events) if user_level < send_level: raise AuthError( 403, "This server requires you to be a moderator in the room to" " edit its room list entry", ) @staticmethod def has_access_token(request): """Checks if the request has an access_token. Returns: bool: False if no access_token was given, True otherwise. """ query_params = request.args.get(b"access_token") auth_headers = request.requestHeaders.getRawHeaders(b"Authorization") return bool(query_params) or bool(auth_headers) @staticmethod def get_access_token_from_request(request): """Extracts the access_token from the request. Args: request: The http request. Returns: unicode: The access_token Raises: MissingClientTokenError: If there isn't a single access_token in the request """ auth_headers = request.requestHeaders.getRawHeaders(b"Authorization") query_params = request.args.get(b"access_token") if auth_headers: # Try the get the access_token from a "Authorization: Bearer" # header if query_params is not None: raise MissingClientTokenError( "Mixing Authorization headers and access_token query parameters." ) if len(auth_headers) > 1: raise MissingClientTokenError( "Too many Authorization headers.") parts = auth_headers[0].split(b" ") if parts[0] == b"Bearer" and len(parts) == 2: return parts[1].decode("ascii") else: raise MissingClientTokenError("Invalid Authorization header.") else: # Try to get the access_token from the query params. if not query_params: raise MissingClientTokenError() return query_params[0].decode("ascii") @defer.inlineCallbacks def check_in_room_or_world_readable(self, room_id, user_id): """Checks that the user is or was in the room or the room is world readable. If it isn't then an exception is raised. Returns: Deferred[tuple[str, str|None]]: Resolves to the current membership of the user in the room and the membership event ID of the user. If the user is not in the room and never has been, then `(Membership.JOIN, None)` is returned. """ try: # check_user_was_in_room will return the most recent membership # event for the user if: # * The user is a non-guest user, and was ever in the room # * The user is a guest user, and has joined the room # else it will throw. member_event = yield self.check_user_was_in_room(room_id, user_id) return member_event.membership, member_event.event_id except AuthError: visibility = yield self.state.get_current_state( room_id, EventTypes.RoomHistoryVisibility, "") if (visibility and visibility.content["history_visibility"] == "world_readable"): return Membership.JOIN, None raise AuthError(403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN) @defer.inlineCallbacks def check_auth_blocking(self, user_id=None, threepid=None, user_type=None): """Checks if the user should be rejected for some external reason, such as monthly active user limiting or global disable flag Args: user_id(str|None): If present, checks for presence against existing MAU cohort threepid(dict|None): If present, checks for presence against configured reserved threepid. Used in cases where the user is trying register with a MAU blocked server, normally they would be rejected but their threepid is on the reserved list. user_id and threepid should never be set at the same time. user_type(str|None): If present, is used to decide whether to check against certain blocking reasons like MAU. """ # Never fail an auth check for the server notices users or support user # This can be a problem where event creation is prohibited due to blocking if user_id is not None: if user_id == self.hs.config.server_notices_mxid: return if (yield self.store.is_support_user(user_id)): return if self.hs.config.hs_disabled: raise ResourceLimitError( 403, self.hs.config.hs_disabled_message, errcode=Codes.RESOURCE_LIMIT_EXCEEDED, admin_contact=self.hs.config.admin_contact, limit_type=LimitBlockingTypes.HS_DISABLED, ) if self.hs.config.limit_usage_by_mau is True: assert not (user_id and threepid) # If the user is already part of the MAU cohort or a trial user if user_id: timestamp = yield self.store.user_last_seen_monthly_active( user_id) if timestamp: return is_trial = yield self.store.is_trial_user(user_id) if is_trial: return elif threepid: # If the user does not exist yet, but is signing up with a # reserved threepid then pass auth check if is_threepid_reserved( self.hs.config.mau_limits_reserved_threepids, threepid): return elif user_type == UserTypes.SUPPORT: # If the user does not exist yet and is of type "support", # allow registration. Support users are excluded from MAU checks. return # Else if there is no room in the MAU bucket, bail current_mau = yield self.store.get_monthly_active_count() if current_mau >= self.hs.config.max_mau_value: raise ResourceLimitError( 403, "Monthly Active User Limit Exceeded", admin_contact=self.hs.config.admin_contact, errcode=Codes.RESOURCE_LIMIT_EXCEEDED, limit_type=LimitBlockingTypes.MONTHLY_ACTIVE_USER, )
class Auth(object): """ FIXME: This class contains a mix of functions for authenticating users of our client-server API and authenticating events added to room graphs. """ def __init__(self, hs): self.hs = hs self.clock = hs.get_clock() self.store = hs.get_datastore() self.state = hs.get_state_handler() self.TOKEN_NOT_FOUND_HTTP_STATUS = 401 self.token_cache = LruCache(CACHE_SIZE_FACTOR * 10000) register_cache("cache", "token_cache", self.token_cache) self._account_validity = hs.config.account_validity @defer.inlineCallbacks def check_from_context(self, room_version, event, context, do_sig_check=True): prev_state_ids = yield context.get_prev_state_ids(self.store) auth_events_ids = yield self.compute_auth_events( event, prev_state_ids, for_verification=True, ) auth_events = yield self.store.get_events(auth_events_ids) auth_events = { (e.type, e.state_key): e for e in itervalues(auth_events) } self.check( room_version, event, auth_events=auth_events, do_sig_check=do_sig_check, ) def check(self, room_version, event, auth_events, do_sig_check=True): """ Checks if this event is correctly authed. Args: room_version (str): version of the room event: the event being checked. auth_events (dict: event-key -> event): the existing room state. Returns: True if the auth checks pass. """ with Measure(self.clock, "auth.check"): event_auth.check( room_version, event, auth_events, do_sig_check=do_sig_check ) @defer.inlineCallbacks def check_joined_room(self, room_id, user_id, current_state=None): """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 the database. Raises: AuthError if the user is not in the room. Returns: A deferred membership event for the user if the user is in the room. """ 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) @defer.inlineCallbacks def check_user_was_in_room(self, room_id, user_id): """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 room. This will be the leave event if they have left the room. """ 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, room_id )) if membership == Membership.LEAVE: forgot = yield self.store.did_forget(user_id, room_id) if forgot: raise AuthError(403, "User %s not in room %s" % ( user_id, room_id )) defer.returnValue(member) @defer.inlineCallbacks def check_host_in_room(self, room_id, host): with Measure(self.clock, "check_host_in_room"): latest_event_ids = yield self.store.is_host_joined(room_id, host) defer.returnValue(latest_event_ids) def _check_joined_room(self, member, user_id, room_id): if not member or member.membership != Membership.JOIN: raise AuthError(403, "User %s not in room %s (%s)" % ( user_id, room_id, repr(member) )) def can_federate(self, event, auth_events): creation_event = auth_events.get((EventTypes.Create, "")) return creation_event.content.get("m.federate", True) is True def get_public_keys(self, invite_event): return event_auth.get_public_keys(invite_event) @defer.inlineCallbacks def get_user_by_req(self, request, allow_guest=False, rights="access"): """ 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. """ # Can optionally look elsewhere in the request (e.g. headers) try: ip_addr = self.hs.get_ip_from_request(request) user_agent = request.requestHeaders.getRawHeaders( b"User-Agent", default=[b""] )[0].decode('ascii', 'surrogateescape') access_token = self.get_access_token_from_request( request, self.TOKEN_NOT_FOUND_HTTP_STATUS ) user_id, app_service = yield self._get_appservice_user_id(request) if user_id: request.authenticated_entity = user_id if ip_addr and self.hs.config.track_appservice_user_ips: yield self.store.insert_client_ip( user_id=user_id, access_token=access_token, ip=ip_addr, user_agent=user_agent, device_id="dummy-device", # stubbed ) defer.returnValue( synapse.types.create_requester(user_id, app_service=app_service) ) user_info = yield self.get_user_by_access_token(access_token, rights) user = user_info["user"] token_id = user_info["token_id"] is_guest = user_info["is_guest"] # Deny the request if the user account has expired. if self._account_validity.enabled: user_id = user.to_string() expiration_ts = yield self.store.get_expiration_ts_for_user(user_id) if expiration_ts is not None and self.clock.time_msec() >= expiration_ts: raise AuthError( 403, "User account has expired", errcode=Codes.EXPIRED_ACCOUNT, ) # device_id may not be present if get_user_by_access_token has been # stubbed out. device_id = user_info.get("device_id") if user and access_token and ip_addr: yield self.store.insert_client_ip( user_id=user.to_string(), access_token=access_token, ip=ip_addr, user_agent=user_agent, device_id=device_id, ) if is_guest and not allow_guest: raise AuthError( 403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN ) request.authenticated_entity = user.to_string() defer.returnValue(synapse.types.create_requester( user, token_id, is_guest, device_id, app_service=app_service) ) except KeyError: raise AuthError( self.TOKEN_NOT_FOUND_HTTP_STATUS, "Missing access token.", errcode=Codes.MISSING_TOKEN ) @defer.inlineCallbacks def _get_appservice_user_id(self, request): app_service = self.store.get_app_service_by_token( self.get_access_token_from_request( request, self.TOKEN_NOT_FOUND_HTTP_STATUS ) ) if app_service is None: defer.returnValue((None, None)) if app_service.ip_range_whitelist: ip_address = IPAddress(self.hs.get_ip_from_request(request)) if ip_address not in app_service.ip_range_whitelist: defer.returnValue((None, None)) if b"user_id" not in request.args: defer.returnValue((app_service.sender, app_service)) user_id = request.args[b"user_id"][0].decode('utf8') if app_service.sender == user_id: defer.returnValue((app_service.sender, app_service)) if not app_service.is_interested_in_user(user_id): raise AuthError( 403, "Application service cannot masquerade as this user." ) if not (yield self.store.get_user_by_id(user_id)): raise AuthError( 403, "Application service has not registered this user" ) defer.returnValue((user_id, app_service)) @defer.inlineCallbacks def get_user_by_access_token(self, token, rights="access"): """ 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: Deferred[dict]: dict that includes: `user` (UserID) `is_guest` (bool) `token_id` (int|None): access token id. May be None if guest `device_id` (str|None): device corresponding to access token Raises: AuthError if no user by that token exists or the token is invalid. """ if rights == "access": # first look in the database r = yield self._look_up_user_by_access_token(token) if r: defer.returnValue(r) # otherwise it needs to be a valid macaroon try: user_id, guest = self._parse_and_validate_macaroon(token, rights) user = UserID.from_string(user_id) if rights == "access": if not guest: # non-guest access tokens must be in the database logger.warning("Unrecognised access token - not in store.") raise AuthError( self.TOKEN_NOT_FOUND_HTTP_STATUS, "Unrecognised access token.", errcode=Codes.UNKNOWN_TOKEN, ) # Guest access tokens are not stored in the database (there can # only be one access token per guest, anyway). # # In order to prevent guest access tokens being used as regular # user access tokens (and hence getting around the invalidation # process), we look up the user id and check that it is indeed # a guest user. # # It would of course be much easier to store guest access # tokens in the database as well, but that would break existing # guest tokens. stored_user = yield self.store.get_user_by_id(user_id) if not stored_user: raise AuthError( self.TOKEN_NOT_FOUND_HTTP_STATUS, "Unknown user_id %s" % user_id, errcode=Codes.UNKNOWN_TOKEN ) if not stored_user["is_guest"]: raise AuthError( self.TOKEN_NOT_FOUND_HTTP_STATUS, "Guest access token used for regular user", errcode=Codes.UNKNOWN_TOKEN ) ret = { "user": user, "is_guest": True, "token_id": None, # all guests get the same device id "device_id": GUEST_DEVICE_ID, } elif rights == "delete_pusher": # We don't store these tokens in the database ret = { "user": user, "is_guest": False, "token_id": None, "device_id": None, } else: raise RuntimeError("Unknown rights setting %s", rights) defer.returnValue(ret) except ( _InvalidMacaroonException, pymacaroons.exceptions.MacaroonException, TypeError, ValueError, ) as e: logger.warning("Invalid macaroon in auth: %s %s", type(e), e) raise AuthError( self.TOKEN_NOT_FOUND_HTTP_STATUS, "Invalid macaroon passed.", errcode=Codes.UNKNOWN_TOKEN ) def _parse_and_validate_macaroon(self, token, rights="access"): """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) """ if rights == "access": cached = self.token_cache.get(token, None) if cached: return cached try: macaroon = pymacaroons.Macaroon.deserialize(token) except Exception: # deserialize can throw more-or-less anything # doesn't look like a macaroon: treat it as an opaque token which # must be in the database. # TODO: it would be nice to get rid of this, but apparently some # people use access tokens which aren't macaroons raise _InvalidMacaroonException() try: user_id = self.get_user_id_from_macaroon(macaroon) has_expiry = False guest = False for caveat in macaroon.caveats: if caveat.caveat_id.startswith("time "): has_expiry = True elif caveat.caveat_id == "guest = true": guest = True self.validate_macaroon( macaroon, rights, self.hs.config.expire_access_token, user_id=user_id, ) except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError): raise AuthError( self.TOKEN_NOT_FOUND_HTTP_STATUS, "Invalid macaroon passed.", errcode=Codes.UNKNOWN_TOKEN ) if not has_expiry and rights == "access": self.token_cache[token] = (user_id, guest) return user_id, guest def get_user_id_from_macaroon(self, macaroon): """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 """ 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 ) def validate_macaroon(self, macaroon, type_string, verify_expiry, user_id): """ 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 required """ v = pymacaroons.Verifier() # the verifier runs a test for every caveat on the macaroon, to check # that it is met for the current request. Each caveat must match at # least one of the predicates specified by satisfy_exact or # specify_general. v.satisfy_exact("gen = 1") v.satisfy_exact("type = " + type_string) v.satisfy_exact("user_id = %s" % user_id) v.satisfy_exact("guest = true") # verify_expiry should really always be True, but there exist access # tokens in the wild which expire when they should not, so we can't # enforce expiry yet (so we have to allow any caveat starting with # 'time < ' in access tokens). # # On the other hand, short-term login tokens (as used by CAS login, for # example) have an expiry time which we do want to enforce. if verify_expiry: v.satisfy_general(self._verify_expiry) else: v.satisfy_general(lambda c: c.startswith("time < ")) # access_tokens include a nonce for uniqueness: any value is acceptable v.satisfy_general(lambda c: c.startswith("nonce = ")) v.verify(macaroon, self.hs.config.macaroon_secret_key) def _verify_expiry(self, caveat): prefix = "time < " if not caveat.startswith(prefix): return False expiry = int(caveat[len(prefix):]) now = self.hs.get_clock().time_msec() return now < expiry @defer.inlineCallbacks def _look_up_user_by_access_token(self, token): ret = yield self.store.get_user_by_access_token(token) if not ret: defer.returnValue(None) # we use ret.get() below because *lots* of unit tests stub out # get_user_by_access_token in a way where it only returns a couple of # the fields. user_info = { "user": UserID.from_string(ret.get("name")), "token_id": ret.get("token_id", None), "is_guest": False, "device_id": ret.get("device_id"), } defer.returnValue(user_info) def get_appservice_by_req(self, request): try: token = self.get_access_token_from_request( request, self.TOKEN_NOT_FOUND_HTTP_STATUS ) service = self.store.get_app_service_by_token(token) if not service: logger.warn("Unrecognised appservice access token.") raise AuthError( self.TOKEN_NOT_FOUND_HTTP_STATUS, "Unrecognised access token.", errcode=Codes.UNKNOWN_TOKEN ) request.authenticated_entity = service.sender return defer.succeed(service) except KeyError: raise AuthError( self.TOKEN_NOT_FOUND_HTTP_STATUS, "Missing access token." ) def is_server_admin(self, user): """ Check if the given user is a local server admin. Args: user (UserID): user to check Returns: bool: True if the user is an admin """ return self.store.is_server_admin(user) @defer.inlineCallbacks def compute_auth_events(self, event, current_state_ids, for_verification=False): if event.type == EventTypes.Create: defer.returnValue([]) auth_ids = [] key = (EventTypes.PowerLevels, "", ) power_level_event_id = current_state_ids.get(key) if power_level_event_id: auth_ids.append(power_level_event_id) key = (EventTypes.JoinRules, "", ) join_rule_event_id = current_state_ids.get(key) key = (EventTypes.Member, event.sender, ) member_event_id = current_state_ids.get(key) key = (EventTypes.Create, "", ) create_event_id = current_state_ids.get(key) if create_event_id: auth_ids.append(create_event_id) if join_rule_event_id: join_rule_event = yield self.store.get_event(join_rule_event_id) join_rule = join_rule_event.content.get("join_rule") is_public = join_rule == JoinRules.PUBLIC if join_rule else False else: is_public = False if event.type == EventTypes.Member: e_type = event.content["membership"] if e_type in [Membership.JOIN, Membership.INVITE]: if join_rule_event_id: auth_ids.append(join_rule_event_id) if e_type == Membership.JOIN: if member_event_id and not is_public: auth_ids.append(member_event_id) else: if member_event_id: auth_ids.append(member_event_id) if for_verification: key = (EventTypes.Member, event.state_key, ) existing_event_id = current_state_ids.get(key) if existing_event_id: auth_ids.append(existing_event_id) if e_type == Membership.INVITE: if "third_party_invite" in event.content: key = ( EventTypes.ThirdPartyInvite, event.content["third_party_invite"]["signed"]["token"] ) third_party_invite_id = current_state_ids.get(key) if third_party_invite_id: auth_ids.append(third_party_invite_id) elif member_event_id: member_event = yield self.store.get_event(member_event_id) if member_event.content["membership"] == Membership.JOIN: auth_ids.append(member_event.event_id) defer.returnValue(auth_ids) def check_redaction(self, room_version, event, auth_events): """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 allowed to redact the target event. """ return event_auth.check_redaction(room_version, event, auth_events) @defer.inlineCallbacks def check_can_change_room_list(self, room_id, user): """Check if the user is allowed to edit the room's entry in the published room list. Args: room_id (str) user (UserID) """ 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) # We currently require the user is a "moderator" in the room. We do this # by checking if they would (theoretically) be able to change the # m.room.aliases events power_level_event = yield self.state.get_current_state( room_id, EventTypes.PowerLevels, "" ) auth_events = {} if power_level_event: auth_events[(EventTypes.PowerLevels, "")] = power_level_event send_level = event_auth.get_send_level( EventTypes.Aliases, "", power_level_event, ) user_level = event_auth.get_user_power_level(user_id, auth_events) if user_level < send_level: raise AuthError( 403, "This server requires you to be a moderator in the room to" " edit its room list entry" ) @staticmethod def has_access_token(request): """Checks if the request has an access_token. Returns: bool: False if no access_token was given, True otherwise. """ query_params = request.args.get(b"access_token") auth_headers = request.requestHeaders.getRawHeaders(b"Authorization") return bool(query_params) or bool(auth_headers) @staticmethod def get_access_token_from_request(request, token_not_found_http_status=401): """Extracts the access_token from the request. Args: request: The http request. token_not_found_http_status(int): The HTTP status code to set in the AuthError if the token isn't found. This is used in some of the legacy APIs to change the status code to 403 from the default of 401 since some of the old clients depended on auth errors returning 403. Returns: unicode: The access_token Raises: AuthError: If there isn't an access_token in the request. """ auth_headers = request.requestHeaders.getRawHeaders(b"Authorization") query_params = request.args.get(b"access_token") if auth_headers: # Try the get the access_token from a "Authorization: Bearer" # header if query_params is not None: raise AuthError( token_not_found_http_status, "Mixing Authorization headers and access_token query parameters.", errcode=Codes.MISSING_TOKEN, ) if len(auth_headers) > 1: raise AuthError( token_not_found_http_status, "Too many Authorization headers.", errcode=Codes.MISSING_TOKEN, ) parts = auth_headers[0].split(b" ") if parts[0] == b"Bearer" and len(parts) == 2: return parts[1].decode('ascii') else: raise AuthError( token_not_found_http_status, "Invalid Authorization header.", errcode=Codes.MISSING_TOKEN, ) else: # Try to get the access_token from the query params. if not query_params: raise AuthError( token_not_found_http_status, "Missing access token.", errcode=Codes.MISSING_TOKEN ) return query_params[0].decode('ascii') @defer.inlineCallbacks def check_in_room_or_world_readable(self, room_id, user_id): """Checks that the user is or was in the room or the room is world readable. If it isn't then an exception is raised. Returns: Deferred[tuple[str, str|None]]: Resolves to the current membership of the user in the room and the membership event ID of the user. If the user is not in the room and never has been, then `(Membership.JOIN, None)` is returned. """ try: # check_user_was_in_room will return the most recent membership # event for the user if: # * The user is a non-guest user, and was ever in the room # * The user is a guest user, and has joined the room # else it will throw. member_event = yield self.check_user_was_in_room(room_id, user_id) defer.returnValue((member_event.membership, member_event.event_id)) except AuthError: visibility = yield self.state.get_current_state( room_id, EventTypes.RoomHistoryVisibility, "" ) if ( visibility and visibility.content["history_visibility"] == "world_readable" ): defer.returnValue((Membership.JOIN, None)) return raise AuthError( 403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN ) @defer.inlineCallbacks def check_auth_blocking(self, user_id=None, threepid=None): """Checks if the user should be rejected for some external reason, such as monthly active user limiting or global disable flag Args: user_id(str|None): If present, checks for presence against existing MAU cohort threepid(dict|None): If present, checks for presence against configured reserved threepid. Used in cases where the user is trying register with a MAU blocked server, normally they would be rejected but their threepid is on the reserved list. user_id and threepid should never be set at the same time. """ # Never fail an auth check for the server notices users or support user # This can be a problem where event creation is prohibited due to blocking if user_id is not None: if user_id == self.hs.config.server_notices_mxid: return if (yield self.store.is_support_user(user_id)): return if self.hs.config.hs_disabled: raise ResourceLimitError( 403, self.hs.config.hs_disabled_message, errcode=Codes.RESOURCE_LIMIT_EXCEEDED, admin_contact=self.hs.config.admin_contact, limit_type=self.hs.config.hs_disabled_limit_type ) if self.hs.config.limit_usage_by_mau is True: assert not (user_id and threepid) # If the user is already part of the MAU cohort or a trial user if user_id: timestamp = yield self.store.user_last_seen_monthly_active(user_id) if timestamp: return is_trial = yield self.store.is_trial_user(user_id) if is_trial: return elif threepid: # If the user does not exist yet, but is signing up with a # reserved threepid then pass auth check if is_threepid_reserved( self.hs.config.mau_limits_reserved_threepids, threepid ): return # Else if there is no room in the MAU bucket, bail current_mau = yield self.store.get_monthly_active_count() if current_mau >= self.hs.config.max_mau_value: raise ResourceLimitError( 403, "Monthly Active User Limit Exceeded", admin_contact=self.hs.config.admin_contact, errcode=Codes.RESOURCE_LIMIT_EXCEEDED, limit_type="monthly_active_user" )
class ClientIpStore(ClientIpWorkerStore): def __init__(self, database: DatabasePool, db_conn, hs): self.client_ip_last_seen = LruCache( cache_name="client_ip_last_seen", max_size=50000 ) super().__init__(database, db_conn, hs) # (user_id, access_token, ip,) -> (user_agent, device_id, last_seen) self._batch_row_update = {} self._client_ip_looper = self._clock.looping_call( self._update_client_ips_batch, 5 * 1000 ) self.hs.get_reactor().addSystemEventTrigger( "before", "shutdown", self._update_client_ips_batch ) async def insert_client_ip( self, user_id, access_token, ip, user_agent, device_id, now=None ): if not now: now = int(self._clock.time_msec()) key = (user_id, access_token, ip) try: last_seen = self.client_ip_last_seen.get(key) except KeyError: last_seen = None await self.populate_monthly_active_users(user_id) # Rate-limited inserts if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY: return self.client_ip_last_seen.set(key, now) self._batch_row_update[key] = (user_agent, device_id, now) @wrap_as_background_process("update_client_ips") async def _update_client_ips_batch(self) -> None: # If the DB pool has already terminated, don't try updating if not self.db_pool.is_running(): return to_update = self._batch_row_update self._batch_row_update = {} await self.db_pool.runInteraction( "_update_client_ips_batch", self._update_client_ips_batch_txn, to_update ) def _update_client_ips_batch_txn(self, txn, to_update): if "user_ips" in self.db_pool._unsafe_to_upsert_tables or ( not self.database_engine.can_native_upsert ): self.database_engine.lock_table(txn, "user_ips") for entry in to_update.items(): (user_id, access_token, ip), (user_agent, device_id, last_seen) = entry self.db_pool.simple_upsert_txn( txn, table="user_ips", keyvalues={"user_id": user_id, "access_token": access_token, "ip": ip}, values={ "user_agent": user_agent, "device_id": device_id, "last_seen": last_seen, }, lock=False, ) # Technically an access token might not be associated with # a device so we need to check. if device_id: # this is always an update rather than an upsert: the row should # already exist, and if it doesn't, that may be because it has been # deleted, and we don't want to re-create it. self.db_pool.simple_update_txn( txn, table="devices", keyvalues={"user_id": user_id, "device_id": device_id}, updatevalues={ "user_agent": user_agent, "last_seen": last_seen, "ip": ip, }, ) async def get_last_client_ip_by_device( self, user_id: str, device_id: Optional[str] ) -> Dict[Tuple[str, str], dict]: """For each device_id listed, give the user_ip it was last seen on Args: user_id: The user to fetch devices for. device_id: If None fetches all devices for the user Returns: A dictionary mapping a tuple of (user_id, device_id) to dicts, with keys giving the column names from the devices table. """ ret = await super().get_last_client_ip_by_device(user_id, device_id) # Update what is retrieved from the database with data which is pending # insertion, as if it has already been stored in the database. for key in self._batch_row_update: uid, _access_token, ip = key if uid == user_id: user_agent, did, last_seen = self._batch_row_update[key] if did is None: # These updates don't make it to the `devices` table continue if not device_id or did == device_id: ret[(user_id, did)] = { "user_id": user_id, "ip": ip, "user_agent": user_agent, "device_id": did, "last_seen": last_seen, } return ret async def get_user_ip_and_agents( self, user: UserID, since_ts: int = 0 ) -> List[Dict[str, Union[str, int]]]: """ Fetch IP/User Agent connection since a given timestamp. """ user_id = user.to_string() results = {} for key in self._batch_row_update: ( uid, access_token, ip, ) = key if uid == user_id: user_agent, _, last_seen = self._batch_row_update[key] if last_seen >= since_ts: results[(access_token, ip)] = (user_agent, last_seen) def get_recent(txn): txn.execute( """ SELECT access_token, ip, user_agent, last_seen FROM user_ips WHERE last_seen >= ? AND user_id = ? ORDER BY last_seen DESC """, (since_ts, user_id), ) return txn.fetchall() rows = await self.db_pool.runInteraction( desc="get_user_ip_and_agents", func=get_recent ) results.update( ((access_token, ip), (user_agent, last_seen)) for access_token, ip, user_agent, last_seen in rows ) return [ { "access_token": access_token, "ip": ip, "user_agent": user_agent, "last_seen": last_seen, } for (access_token, ip), (user_agent, last_seen) in results.items() ]
class DictionaryCache: """Caches key -> dictionary lookups, supporting caching partial dicts, i.e. fetching a subset of dictionary keys for a particular key. """ def __init__(self, name, max_entries=1000): self.cache = LruCache( max_size=max_entries, cache_name=name, size_callback=len) # type: LruCache[Any, DictionaryEntry] self.name = name self.sequence = 0 self.thread = None def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread") def get(self, key, dict_keys=None): """Fetch an entry out of the cache Args: key dict_key(list): If given a set of keys then return only those keys that exist in the cache. Returns: DictionaryEntry """ entry = self.cache.get(key, _Sentinel.sentinel) if entry is not _Sentinel.sentinel: if dict_keys is None: return DictionaryEntry(entry.full, entry.known_absent, dict(entry.value)) else: return DictionaryEntry( entry.full, entry.known_absent, {k: entry.value[k] for k in dict_keys if k in entry.value}, ) return DictionaryEntry(False, set(), {}) def invalidate(self, key): self.check_thread() # Increment the sequence number so that any SELECT statements that # raced with the INSERT don't update the cache (SYN-369) self.sequence += 1 self.cache.pop(key, None) def invalidate_all(self): self.check_thread() self.sequence += 1 self.cache.clear() def update(self, sequence, key, value, fetched_keys=None): """Updates the entry in the cache Args: sequence key (K) value (dict[X,Y]): The value to update the cache with. fetched_keys (None|set[X]): All of the dictionary keys which were fetched from the database. If None, this is the complete value for key K. Otherwise, it is used to infer a list of keys which we know don't exist in the full dict. """ self.check_thread() if self.sequence == sequence: # Only update the cache if the caches sequence number matches the # number that the cache had before the SELECT was started (SYN-369) if fetched_keys is None: self._insert(key, value, set()) else: self._update_or_insert(key, value, fetched_keys) def _update_or_insert(self, key, value, known_absent): # We pop and reinsert as we need to tell the cache the size may have # changed entry = self.cache.pop(key, DictionaryEntry(False, set(), {})) entry.value.update(value) entry.known_absent.update(known_absent) self.cache[key] = entry def _insert(self, key, value, known_absent): self.cache[key] = DictionaryEntry(True, known_absent, value)
class DictionaryCache(object): """Caches key -> dictionary lookups, supporting caching partial dicts, i.e. fetching a subset of dictionary keys for a particular key. """ def __init__(self, name, max_entries=1000): self.cache = LruCache(max_size=max_entries, size_callback=len) self.name = name self.sequence = 0 self.thread = None # caches_by_name[name] = self.cache class Sentinel(object): __slots__ = [] self.sentinel = Sentinel() self.metrics = register_cache(name, self.cache) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread") def get(self, key, dict_keys=None): """Fetch an entry out of the cache Args: key dict_key(list): If given a set of keys then return only those keys that exist in the cache. Returns: DictionaryEntry """ entry = self.cache.get(key, self.sentinel) if entry is not self.sentinel: self.metrics.inc_hits() if dict_keys is None: return DictionaryEntry(entry.full, entry.known_absent, dict(entry.value)) else: return DictionaryEntry( entry.full, entry.known_absent, {k: entry.value[k] for k in dict_keys if k in entry.value}) self.metrics.inc_misses() return DictionaryEntry(False, set(), {}) def invalidate(self, key): self.check_thread() # Increment the sequence number so that any SELECT statements that # raced with the INSERT don't update the cache (SYN-369) self.sequence += 1 self.cache.pop(key, None) def invalidate_all(self): self.check_thread() self.sequence += 1 self.cache.clear() def update(self, sequence, key, value, full=False, known_absent=None): """Updates the entry in the cache Args: sequence key value (dict): The value to update the cache with. full (bool): Whether the given value is the full dict, or just a partial subset there of. If not full then any existing entries for the key will be updated. known_absent (set): Set of keys that we know don't exist in the full dict. """ self.check_thread() if self.sequence == sequence: # Only update the cache if the caches sequence number matches the # number that the cache had before the SELECT was started (SYN-369) if known_absent is None: known_absent = set() if full: self._insert(key, value, known_absent) else: self._update_or_insert(key, value, known_absent) def _update_or_insert(self, key, value, known_absent): # We pop and reinsert as we need to tell the cache the size may have # changed entry = self.cache.pop(key, DictionaryEntry(False, set(), {})) entry.value.update(value) entry.known_absent.update(known_absent) self.cache[key] = entry def _insert(self, key, value, known_absent): self.cache[key] = DictionaryEntry(True, known_absent, value)
class Auth(object): """ FIXME: This class contains a mix of functions for authenticating users of our client-server API and authenticating events added to room graphs. """ def __init__(self, hs): self.hs = hs self.clock = hs.get_clock() self.store = hs.get_datastore() self.state = hs.get_state_handler() self.TOKEN_NOT_FOUND_HTTP_STATUS = 401 self.token_cache = LruCache(CACHE_SIZE_FACTOR * 10000) register_cache("token_cache", self.token_cache) @defer.inlineCallbacks def check_from_context(self, event, context, do_sig_check=True): auth_events_ids = yield self.compute_auth_events( event, context.prev_state_ids, for_verification=True, ) auth_events = yield self.store.get_events(auth_events_ids) auth_events = {(e.type, e.state_key): e for e in auth_events.values()} self.check(event, auth_events=auth_events, do_sig_check=do_sig_check) def check(self, event, auth_events, do_sig_check=True): """ 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. """ with Measure(self.clock, "auth.check"): event_auth.check(event, auth_events, do_sig_check=do_sig_check) @defer.inlineCallbacks def check_joined_room(self, room_id, user_id, current_state=None): """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 the database. Raises: AuthError if the user is not in the room. Returns: A deferred membership event for the user if the user is in the room. """ 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) @defer.inlineCallbacks def check_user_was_in_room(self, room_id, user_id): """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 room. This will be the leave event if they have left the room. """ 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, room_id)) if membership == Membership.LEAVE: forgot = yield self.store.did_forget(user_id, room_id) if forgot: raise AuthError(403, "User %s not in room %s" % (user_id, room_id)) defer.returnValue(member) @defer.inlineCallbacks def check_host_in_room(self, room_id, host): with Measure(self.clock, "check_host_in_room"): latest_event_ids = yield self.store.is_host_joined(room_id, host) defer.returnValue(latest_event_ids) def _check_joined_room(self, member, user_id, room_id): if not member or member.membership != Membership.JOIN: raise AuthError( 403, "User %s not in room %s (%s)" % (user_id, room_id, repr(member))) def can_federate(self, event, auth_events): creation_event = auth_events.get((EventTypes.Create, "")) return creation_event.content.get("m.federate", True) is True def get_public_keys(self, invite_event): return event_auth.get_public_keys(invite_event) @defer.inlineCallbacks def get_user_by_req(self, request, allow_guest=False, rights="access"): """ 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. """ # Can optionally look elsewhere in the request (e.g. headers) 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, self.TOKEN_NOT_FOUND_HTTP_STATUS) user_info = yield self.get_user_by_access_token( access_token, rights) user = user_info["user"] token_id = user_info["token_id"] is_guest = user_info["is_guest"] # device_id may not be present if get_user_by_access_token has been # stubbed out. device_id = user_info.get("device_id") ip_addr = self.hs.get_ip_from_request(request) user_agent = request.requestHeaders.getRawHeaders(b"User-Agent", default=[b""])[0] if user and access_token and ip_addr: self.store.insert_client_ip( user_id=user.to_string(), access_token=access_token, ip=ip_addr, user_agent=user_agent, device_id=device_id, ) if is_guest and not allow_guest: raise AuthError(403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN) request.authenticated_entity = user.to_string() defer.returnValue( synapse.types.create_requester(user, token_id, is_guest, device_id, app_service=app_service)) except KeyError: raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, "Missing access token.", errcode=Codes.MISSING_TOKEN) @defer.inlineCallbacks def _get_appservice_user_id(self, request): app_service = self.store.get_app_service_by_token( get_access_token_from_request(request, self.TOKEN_NOT_FOUND_HTTP_STATUS)) if app_service is None: defer.returnValue((None, None)) if "user_id" not in request.args: defer.returnValue((app_service.sender, app_service)) user_id = request.args["user_id"][0] if app_service.sender == user_id: defer.returnValue((app_service.sender, app_service)) if not app_service.is_interested_in_user(user_id): raise AuthError( 403, "Application service cannot masquerade as this user.") if not (yield self.store.get_user_by_id(user_id)): raise AuthError( 403, "Application service has not registered this user") defer.returnValue((user_id, app_service)) @defer.inlineCallbacks def get_user_by_access_token(self, token, rights="access"): """ 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: Deferred[dict]: dict that includes: `user` (UserID) `is_guest` (bool) `token_id` (int|None): access token id. May be None if guest `device_id` (str|None): device corresponding to access token Raises: AuthError if no user by that token exists or the token is invalid. """ try: user_id, guest = self._parse_and_validate_macaroon(token, rights) except _InvalidMacaroonException: # doesn't look like a macaroon: treat it as an opaque token which # must be in the database. # TODO: it would be nice to get rid of this, but apparently some # people use access tokens which aren't macaroons r = yield self._look_up_user_by_access_token(token) defer.returnValue(r) try: user = UserID.from_string(user_id) if guest: # Guest access tokens are not stored in the database (there can # only be one access token per guest, anyway). # # In order to prevent guest access tokens being used as regular # user access tokens (and hence getting around the invalidation # process), we look up the user id and check that it is indeed # a guest user. # # It would of course be much easier to store guest access # tokens in the database as well, but that would break existing # guest tokens. stored_user = yield self.store.get_user_by_id(user_id) if not stored_user: raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, "Unknown user_id %s" % user_id, errcode=Codes.UNKNOWN_TOKEN) if not stored_user["is_guest"]: raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, "Guest access token used for regular user", errcode=Codes.UNKNOWN_TOKEN) ret = { "user": user, "is_guest": True, "token_id": None, # all guests get the same device id "device_id": GUEST_DEVICE_ID, } elif rights == "delete_pusher": # We don't store these tokens in the database ret = { "user": user, "is_guest": False, "token_id": None, "device_id": None, } else: # This codepath exists for several reasons: # * so that we can actually return a token ID, which is used # in some parts of the schema (where we probably ought to # use device IDs instead) # * the only way we currently have to invalidate an # access_token is by removing it from the database, so we # have to check here that it is still in the db # * some attributes (notably device_id) aren't stored in the # macaroon. They probably should be. # TODO: build the dictionary from the macaroon once the # above are fixed ret = yield self._look_up_user_by_access_token(token) if ret["user"] != user: logger.error("Macaroon user (%s) != DB user (%s)", user, ret["user"]) raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, "User mismatch in macaroon", errcode=Codes.UNKNOWN_TOKEN) defer.returnValue(ret) except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError): raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, "Invalid macaroon passed.", errcode=Codes.UNKNOWN_TOKEN) def _parse_and_validate_macaroon(self, token, rights="access"): """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) """ if rights == "access": cached = self.token_cache.get(token, None) if cached: return cached try: macaroon = pymacaroons.Macaroon.deserialize(token) except Exception: # deserialize can throw more-or-less anything # doesn't look like a macaroon: treat it as an opaque token which # must be in the database. # TODO: it would be nice to get rid of this, but apparently some # people use access tokens which aren't macaroons raise _InvalidMacaroonException() try: user_id = self.get_user_id_from_macaroon(macaroon) has_expiry = False guest = False for caveat in macaroon.caveats: if caveat.caveat_id.startswith("time "): has_expiry = True elif caveat.caveat_id == "guest = true": guest = True self.validate_macaroon( macaroon, rights, self.hs.config.expire_access_token, user_id=user_id, ) except (pymacaroons.exceptions.MacaroonException, TypeError, ValueError): raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, "Invalid macaroon passed.", errcode=Codes.UNKNOWN_TOKEN) if not has_expiry and rights == "access": self.token_cache[token] = (user_id, guest) return user_id, guest def get_user_id_from_macaroon(self, macaroon): """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 """ 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) def validate_macaroon(self, macaroon, type_string, verify_expiry, user_id): """ 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 required """ v = pymacaroons.Verifier() # the verifier runs a test for every caveat on the macaroon, to check # that it is met for the current request. Each caveat must match at # least one of the predicates specified by satisfy_exact or # specify_general. v.satisfy_exact("gen = 1") v.satisfy_exact("type = " + type_string) v.satisfy_exact("user_id = %s" % user_id) v.satisfy_exact("guest = true") # verify_expiry should really always be True, but there exist access # tokens in the wild which expire when they should not, so we can't # enforce expiry yet (so we have to allow any caveat starting with # 'time < ' in access tokens). # # On the other hand, short-term login tokens (as used by CAS login, for # example) have an expiry time which we do want to enforce. if verify_expiry: v.satisfy_general(self._verify_expiry) else: v.satisfy_general(lambda c: c.startswith("time < ")) # access_tokens include a nonce for uniqueness: any value is acceptable v.satisfy_general(lambda c: c.startswith("nonce = ")) v.verify(macaroon, self.hs.config.macaroon_secret_key) def _verify_expiry(self, caveat): prefix = "time < " if not caveat.startswith(prefix): return False expiry = int(caveat[len(prefix):]) now = self.hs.get_clock().time_msec() return now < expiry @defer.inlineCallbacks def _look_up_user_by_access_token(self, token): ret = yield self.store.get_user_by_access_token(token) if not ret: logger.warn("Unrecognised access token - not in store: %s" % (token, )) raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, "Unrecognised access token.", errcode=Codes.UNKNOWN_TOKEN) # we use ret.get() below because *lots* of unit tests stub out # get_user_by_access_token in a way where it only returns a couple of # the fields. user_info = { "user": UserID.from_string(ret.get("name")), "token_id": ret.get("token_id", None), "is_guest": False, "device_id": ret.get("device_id"), } defer.returnValue(user_info) def get_appservice_by_req(self, request): try: token = get_access_token_from_request( request, self.TOKEN_NOT_FOUND_HTTP_STATUS) service = self.store.get_app_service_by_token(token) if not service: logger.warn("Unrecognised appservice access token: %s" % (token, )) raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, "Unrecognised access token.", errcode=Codes.UNKNOWN_TOKEN) request.authenticated_entity = service.sender return defer.succeed(service) except KeyError: raise AuthError(self.TOKEN_NOT_FOUND_HTTP_STATUS, "Missing access token.") def is_server_admin(self, user): """ Check if the given user is a local server admin. Args: user (str): mxid of user to check Returns: bool: True if the user is an admin """ return self.store.is_server_admin(user) @defer.inlineCallbacks def add_auth_events(self, builder, context): auth_ids = yield self.compute_auth_events(builder, context.prev_state_ids) auth_events_entries = yield self.store.add_event_hashes(auth_ids) builder.auth_events = auth_events_entries @defer.inlineCallbacks def compute_auth_events(self, event, current_state_ids, for_verification=False): if event.type == EventTypes.Create: defer.returnValue([]) auth_ids = [] key = ( EventTypes.PowerLevels, "", ) power_level_event_id = current_state_ids.get(key) if power_level_event_id: auth_ids.append(power_level_event_id) key = ( EventTypes.JoinRules, "", ) join_rule_event_id = current_state_ids.get(key) key = ( EventTypes.Member, event.user_id, ) member_event_id = current_state_ids.get(key) key = ( EventTypes.Create, "", ) create_event_id = current_state_ids.get(key) if create_event_id: auth_ids.append(create_event_id) if join_rule_event_id: join_rule_event = yield self.store.get_event(join_rule_event_id) join_rule = join_rule_event.content.get("join_rule") is_public = join_rule == JoinRules.PUBLIC if join_rule else False else: is_public = False if event.type == EventTypes.Member: e_type = event.content["membership"] if e_type in [Membership.JOIN, Membership.INVITE]: if join_rule_event_id: auth_ids.append(join_rule_event_id) if e_type == Membership.JOIN: if member_event_id and not is_public: auth_ids.append(member_event_id) else: if member_event_id: auth_ids.append(member_event_id) if for_verification: key = ( EventTypes.Member, event.state_key, ) existing_event_id = current_state_ids.get(key) if existing_event_id: auth_ids.append(existing_event_id) if e_type == Membership.INVITE: if "third_party_invite" in event.content: key = ( EventTypes.ThirdPartyInvite, event.content["third_party_invite"]["signed"]["token"]) third_party_invite_id = current_state_ids.get(key) if third_party_invite_id: auth_ids.append(third_party_invite_id) elif member_event_id: member_event = yield self.store.get_event(member_event_id) if member_event.content["membership"] == Membership.JOIN: auth_ids.append(member_event.event_id) defer.returnValue(auth_ids) def check_redaction(self, event, auth_events): """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 allowed to redact the target event. """ return event_auth.check_redaction(event, auth_events) @defer.inlineCallbacks def check_can_change_room_list(self, room_id, user): """Check if the user is allowed to edit the room's entry in the published room list. Args: room_id (str) user (UserID) """ 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) # We currently require the user is a "moderator" in the room. We do this # by checking if they would (theoretically) be able to change the # m.room.aliases events power_level_event = yield self.state.get_current_state( room_id, EventTypes.PowerLevels, "") auth_events = {} if power_level_event: auth_events[(EventTypes.PowerLevels, "")] = power_level_event send_level = event_auth.get_send_level(EventTypes.Aliases, "", auth_events) user_level = event_auth.get_user_power_level(user_id, auth_events) if user_level < send_level: raise AuthError( 403, "This server requires you to be a moderator in the room to" " edit its room list entry")
class DictionaryCache(object): """Caches key -> dictionary lookups, supporting caching partial dicts, i.e. fetching a subset of dictionary keys for a particular key. """ def __init__(self, name, max_entries=1000): self.cache = LruCache(max_size=max_entries, size_callback=len) self.name = name self.sequence = 0 self.thread = None # caches_by_name[name] = self.cache class Sentinel(object): __slots__ = [] self.sentinel = Sentinel() self.metrics = register_cache(name, self.cache) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get(self, key, dict_keys=None): """Fetch an entry out of the cache Args: key dict_key(list): If given a set of keys then return only those keys that exist in the cache. Returns: DictionaryEntry """ entry = self.cache.get(key, self.sentinel) if entry is not self.sentinel: self.metrics.inc_hits() if dict_keys is None: return DictionaryEntry(entry.full, entry.known_absent, dict(entry.value)) else: return DictionaryEntry(entry.full, entry.known_absent, { k: entry.value[k] for k in dict_keys if k in entry.value }) self.metrics.inc_misses() return DictionaryEntry(False, set(), {}) def invalidate(self, key): self.check_thread() # Increment the sequence number so that any SELECT statements that # raced with the INSERT don't update the cache (SYN-369) self.sequence += 1 self.cache.pop(key, None) def invalidate_all(self): self.check_thread() self.sequence += 1 self.cache.clear() def update(self, sequence, key, value, full=False, known_absent=None): """Updates the entry in the cache Args: sequence key value (dict): The value to update the cache with. full (bool): Whether the given value is the full dict, or just a partial subset there of. If not full then any existing entries for the key will be updated. known_absent (set): Set of keys that we know don't exist in the full dict. """ self.check_thread() if self.sequence == sequence: # Only update the cache if the caches sequence number matches the # number that the cache had before the SELECT was started (SYN-369) if known_absent is None: known_absent = set() if full: self._insert(key, value, known_absent) else: self._update_or_insert(key, value, known_absent) def _update_or_insert(self, key, value, known_absent): # We pop and reinsert as we need to tell the cache the size may have # changed entry = self.cache.pop(key, DictionaryEntry(False, set(), {})) entry.value.update(value) entry.known_absent.update(known_absent) self.cache[key] = entry def _insert(self, key, value, known_absent): self.cache[key] = DictionaryEntry(True, known_absent, value)
class ClientIpStore(ClientIpWorkerStore): def __init__(self, database: DatabasePool, db_conn, hs): self.client_ip_last_seen = LruCache(cache_name="client_ip_last_seen", keylen=4, max_size=50000) super().__init__(database, db_conn, hs) # (user_id, access_token, ip,) -> (user_agent, device_id, last_seen) self._batch_row_update = {} self._client_ip_looper = self._clock.looping_call( self._update_client_ips_batch, 5 * 1000) self.hs.get_reactor().addSystemEventTrigger( "before", "shutdown", self._update_client_ips_batch) async def insert_client_ip(self, user_id, access_token, ip, user_agent, device_id, now=None): if not now: now = int(self._clock.time_msec()) key = (user_id, access_token, ip) try: last_seen = self.client_ip_last_seen.get(key) except KeyError: last_seen = None await self.populate_monthly_active_users(user_id) # Rate-limited inserts if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY: return self.client_ip_last_seen.set(key, now) self._batch_row_update[key] = (user_agent, device_id, now) @wrap_as_background_process("update_client_ips") async def _update_client_ips_batch(self) -> None: # If the DB pool has already terminated, don't try updating if not self.db_pool.is_running(): return to_update = self._batch_row_update self._batch_row_update = {} await self.db_pool.runInteraction("_update_client_ips_batch", self._update_client_ips_batch_txn, to_update) def _update_client_ips_batch_txn(self, txn, to_update): if "user_ips" in self.db_pool._unsafe_to_upsert_tables or ( not self.database_engine.can_native_upsert): self.database_engine.lock_table(txn, "user_ips") for entry in to_update.items(): (user_id, access_token, ip), (user_agent, device_id, last_seen) = entry try: self.db_pool.simple_upsert_txn( txn, table="user_ips", keyvalues={ "user_id": user_id, "access_token": access_token, "ip": ip, }, values={ "user_agent": user_agent, "device_id": device_id, "last_seen": last_seen, }, lock=False, ) # Technically an access token might not be associated with # a device so we need to check. if device_id: # this is always an update rather than an upsert: the row should # already exist, and if it doesn't, that may be because it has been # deleted, and we don't want to re-create it. self.db_pool.simple_update_txn( txn, table="devices", keyvalues={ "user_id": user_id, "device_id": device_id }, updatevalues={ "user_agent": user_agent, "last_seen": last_seen, "ip": ip, }, ) except Exception as e: # Failed to upsert, log and continue logger.error("Failed to insert client IP %r: %r", entry, e) async def get_last_client_ip_by_device( self, user_id: str, device_id: Optional[str]) -> Dict[Tuple[str, str], dict]: """For each device_id listed, give the user_ip it was last seen on Args: user_id: The user to fetch devices for. device_id: If None fetches all devices for the user Returns: A dictionary mapping a tuple of (user_id, device_id) to dicts, with keys giving the column names from the devices table. """ keyvalues = {"user_id": user_id} if device_id is not None: keyvalues["device_id"] = device_id res = await self.db_pool.simple_select_list( table="devices", keyvalues=keyvalues, retcols=("user_id", "ip", "user_agent", "device_id", "last_seen"), ) ret = {(d["user_id"], d["device_id"]): d for d in res} for key in self._batch_row_update: uid, access_token, ip = key if uid == user_id: user_agent, did, last_seen = self._batch_row_update[key] if not device_id or did == device_id: ret[(user_id, device_id)] = { "user_id": user_id, "access_token": access_token, "ip": ip, "user_agent": user_agent, "device_id": did, "last_seen": last_seen, } return ret async def get_user_ip_and_agents(self, user): user_id = user.to_string() results = {} for key in self._batch_row_update: uid, access_token, ip, = key if uid == user_id: user_agent, _, last_seen = self._batch_row_update[key] results[(access_token, ip)] = (user_agent, last_seen) rows = await self.db_pool.simple_select_list( table="user_ips", keyvalues={"user_id": user_id}, retcols=["access_token", "ip", "user_agent", "last_seen"], desc="get_user_ip_and_agents", ) results.update(((row["access_token"], row["ip"]), (row["user_agent"], row["last_seen"])) for row in rows) return [{ "access_token": access_token, "ip": ip, "user_agent": user_agent, "last_seen": last_seen, } for (access_token, ip), (user_agent, last_seen) in results.items()]
class DeferredCache(Generic[KT, VT]): """Wraps an LruCache, adding support for Deferred results. It expects that each entry added with set() will be a Deferred; likewise get() will return a Deferred. """ __slots__ = ( "cache", "thread", "_pending_deferred_cache", ) def __init__( self, name: str, max_entries: int = 1000, tree: bool = False, iterable: bool = False, apply_cache_factor_from_config: bool = True, ): """ Args: name: The name of the cache max_entries: Maximum amount of entries that the cache will hold keylen: The length of the tuple used as the cache key. Ignored unless `tree` is True. tree: Use a TreeCache instead of a dict as the underlying cache type iterable: If True, count each item in the cached object as an entry, rather than each cached object apply_cache_factor_from_config: Whether cache factors specified in the config file affect `max_entries` """ cache_type = TreeCache if tree else dict # _pending_deferred_cache maps from the key value to a `CacheEntry` object. self._pending_deferred_cache = ( cache_type() ) # type: Union[TreeCache, MutableMapping[KT, CacheEntry]] def metrics_cb(): cache_pending_metric.labels(name).set(len(self._pending_deferred_cache)) # cache is used for completed results and maps to the result itself, rather than # a Deferred. self.cache = LruCache( max_size=max_entries, cache_name=name, cache_type=cache_type, size_callback=(lambda d: len(d) or 1) if iterable else None, metrics_collection_callback=metrics_cb, apply_cache_factor_from_config=apply_cache_factor_from_config, ) # type: LruCache[KT, VT] self.thread = None # type: Optional[threading.Thread] @property def max_entries(self): return self.cache.max_size def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get( self, key: KT, callback: Optional[Callable[[], None]] = None, update_metrics: bool = True, ) -> defer.Deferred: """Looks the key up in the caches. For symmetry with set(), this method does *not* follow the synapse logcontext rules: the logcontext will not be cleared on return, and the Deferred will run its callbacks in the sentinel context. In other words: wrap the result with make_deferred_yieldable() before `await`ing it. Args: key: callback: Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: A Deferred which completes with the result. Note that this may later fail if there is an ongoing set() operation which later completes with a failure. Raises: KeyError if the key is not found in the cache """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _Sentinel.sentinel) if val is not _Sentinel.sentinel: val.callbacks.update(callbacks) if update_metrics: m = self.cache.metrics assert m # we always have a name, so should always have metrics m.inc_hits() return val.deferred.observe() val2 = self.cache.get( key, _Sentinel.sentinel, callbacks=callbacks, update_metrics=update_metrics ) if val2 is _Sentinel.sentinel: raise KeyError() else: return defer.succeed(val2) def get_immediate( self, key: KT, default: T, update_metrics: bool = True ) -> Union[VT, T]: """If we have a *completed* cached value, return it.""" return self.cache.get(key, default, update_metrics=update_metrics) def set( self, key: KT, value: defer.Deferred, callback: Optional[Callable[[], None]] = None, ) -> defer.Deferred: """Adds a new entry to the cache (or updates an existing one). The given `value` *must* be a Deferred. First any existing entry for the same key is invalidated. Then a new entry is added to the cache for the given key. Until the `value` completes, calls to `get()` for the key will also result in an incomplete Deferred, which will ultimately complete with the same result as `value`. If `value` completes successfully, subsequent calls to `get()` will then return a completed deferred with the same result. If it *fails*, the cache is invalidated and subequent calls to `get()` will raise a KeyError. If another call to `set()` happens before `value` completes, then (a) any invalidation callbacks registered in the interim will be called, (b) any `get()`s in the interim will continue to complete with the result from the *original* `value`, (c) any future calls to `get()` will complete with the result from the *new* `value`. It is expected that `value` does *not* follow the synapse logcontext rules - ie, if it is incomplete, it runs its callbacks in the sentinel context. Args: key: Key to be set value: a deferred which will complete with a result to add to the cache callback: An optional callback to be called when the entry is invalidated """ if not isinstance(value, defer.Deferred): raise TypeError("not a Deferred") callbacks = [callback] if callback else [] self.check_thread() existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() # XXX: why don't we invalidate the entry in `self.cache` yet? # we can save a whole load of effort if the deferred is ready. if value.called: result = value.result if not isinstance(result, failure.Failure): self.cache.set(key, result, callbacks) return value # otherwise, we'll add an entry to the _pending_deferred_cache for now, # and add callbacks to add it to the cache properly later. observable = ObservableDeferred(value, consumeErrors=True) observer = observable.observe() entry = CacheEntry(deferred=observable, callbacks=callbacks) self._pending_deferred_cache[key] = entry def compare_and_pop(): """Check if our entry is still the one in _pending_deferred_cache, and if so, pop it. Returns true if the entries matched. """ existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: return True # oops, the _pending_deferred_cache has been updated since # we started our query, so we are out of date. # # Better put back whatever we took out. (We do it this way # round, rather than peeking into the _pending_deferred_cache # and then removing on a match, to make the common case faster) if existing_entry is not None: self._pending_deferred_cache[key] = existing_entry return False def cb(result): if compare_and_pop(): self.cache.set(key, result, entry.callbacks) else: # we're not going to put this entry into the cache, so need # to make sure that the invalidation callbacks are called. # That was probably done when _pending_deferred_cache was # updated, but it's possible that `set` was called without # `invalidate` being previously called, in which case it may # not have been. Either way, let's double-check now. entry.invalidate() def eb(_fail): compare_and_pop() entry.invalidate() # once the deferred completes, we can move the entry from the # _pending_deferred_cache to the real cache. # observer.addCallbacks(cb, eb) # we return a new Deferred which will be called before any subsequent observers. return observable.observe() def prefill( self, key: KT, value: VT, callback: Optional[Callable[[], None]] = None ): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): """Delete a key, or tree of entries If the cache is backed by a regular dict, then "key" must be of the right type for this cache If the cache is backed by a TreeCache, then "key" must be a tuple, but may be of lower cardinality than the TreeCache - in which case the whole subtree is deleted. """ self.check_thread() self.cache.del_multi(key) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, which will (a) stop it being returned # for future queries and (b) stop it being persisted as a proper entry # in self.cache. entry = self._pending_deferred_cache.pop(key, None) # run the invalidation callbacks now, rather than waiting for the # deferred to resolve. if entry: # _pending_deferred_cache.pop should either return a CacheEntry, or, in the # case of a TreeCache, a dict of keys to cache entries. Either way calling # iterate_tree_cache_entry on it will do the right thing. for entry in iterate_tree_cache_entry(entry): entry.invalidate() def invalidate_all(self): self.check_thread() self.cache.clear() for entry in self._pending_deferred_cache.values(): entry.invalidate() self._pending_deferred_cache.clear()
class Cache(object): __slots__ = ( "cache", "name", "keylen", "thread", "metrics", "_pending_deferred_cache", ) def __init__( self, name: str, max_entries: int = 1000, keylen: int = 1, tree: bool = False, iterable: bool = False, apply_cache_factor_from_config: bool = True, ): """ Args: name: The name of the cache max_entries: Maximum amount of entries that the cache will hold keylen: The length of the tuple used as the cache key tree: Use a TreeCache instead of a dict as the underlying cache type iterable: If True, count each item in the cached object as an entry, rather than each cached object apply_cache_factor_from_config: Whether cache factors specified in the config file affect `max_entries` Returns: Cache """ cache_type = TreeCache if tree else dict self._pending_deferred_cache = cache_type() self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type, size_callback=(lambda d: len(d)) if iterable else None, evicted_callback=self._on_evicted, apply_cache_factor_from_config=apply_cache_factor_from_config, ) self.name = name self.keylen = keylen self.thread = None self.metrics = register_cache( "cache", name, self.cache, collect_callback=self._metrics_collection_callback, ) @property def max_entries(self): return self.cache.max_size def _on_evicted(self, evicted_count): self.metrics.inc_evictions(evicted_count) def _metrics_collection_callback(self): cache_pending_metric.labels(self.name).set( len(self._pending_deferred_cache)) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread") def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True): """Looks the key up in the caches. Args: key(tuple) default: What is returned if key is not in the caches. If not specified then function throws KeyError instead callback(fn): Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: Either an ObservableDeferred or the raw result """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _CacheSentinel) if val is not _CacheSentinel: val.callbacks.update(callbacks) if update_metrics: self.metrics.inc_hits() return val.deferred val = self.cache.get(key, _CacheSentinel, callbacks=callbacks) if val is not _CacheSentinel: self.metrics.inc_hits() return val if update_metrics: self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def set(self, key, value, callback=None): if not isinstance(value, defer.Deferred): raise TypeError("not a Deferred") callbacks = [callback] if callback else [] self.check_thread() observable = ObservableDeferred(value, consumeErrors=True) observer = defer.maybeDeferred(observable.observe) entry = CacheEntry(deferred=observable, callbacks=callbacks) existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() self._pending_deferred_cache[key] = entry def compare_and_pop(): """Check if our entry is still the one in _pending_deferred_cache, and if so, pop it. Returns true if the entries matched. """ existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: return True # oops, the _pending_deferred_cache has been updated since # we started our query, so we are out of date. # # Better put back whatever we took out. (We do it this way # round, rather than peeking into the _pending_deferred_cache # and then removing on a match, to make the common case faster) if existing_entry is not None: self._pending_deferred_cache[key] = existing_entry return False def cb(result): if compare_and_pop(): self.cache.set(key, result, entry.callbacks) else: # we're not going to put this entry into the cache, so need # to make sure that the invalidation callbacks are called. # That was probably done when _pending_deferred_cache was # updated, but it's possible that `set` was called without # `invalidate` being previously called, in which case it may # not have been. Either way, let's double-check now. entry.invalidate() def eb(_fail): compare_and_pop() entry.invalidate() # once the deferred completes, we can move the entry from the # _pending_deferred_cache to the real cache. # observer.addCallbacks(cb, eb) return observable def prefill(self, key, value, callback=None): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): self.check_thread() self.cache.pop(key, None) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, which will (a) stop it being returned # for future queries and (b) stop it being persisted as a proper entry # in self.cache. entry = self._pending_deferred_cache.pop(key, None) # run the invalidation callbacks now, rather than waiting for the # deferred to resolve. if entry: entry.invalidate() def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError("The cache key must be a tuple not %r" % (type(key), )) self.cache.del_multi(key) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, as above entry_dict = self._pending_deferred_cache.pop(key, None) if entry_dict is not None: for entry in iterate_tree_cache_entry(entry_dict): entry.invalidate() def invalidate_all(self): self.check_thread() self.cache.clear() for entry in self._pending_deferred_cache.values(): entry.invalidate() self._pending_deferred_cache.clear()
class Auth: """ FIXME: This class contains a mix of functions for authenticating users of our client-server API and authenticating events added to room graphs. The latter should be moved to synapse.handlers.event_auth.EventAuthHandler. """ def __init__(self, hs: "HomeServer"): self.hs = hs self.clock = hs.get_clock() self.store = hs.get_datastore() self.state = hs.get_state_handler() self.token_cache = LruCache( 10000, "token_cache") # type: LruCache[str, Tuple[str, bool]] self._auth_blocking = AuthBlocking(self.hs) self._account_validity_enabled = ( hs.config.account_validity.account_validity_enabled) self._track_appservice_user_ips = hs.config.track_appservice_user_ips self._macaroon_secret_key = hs.config.macaroon_secret_key self._force_tracing_for_users = hs.config.tracing.force_tracing_for_users async def check_from_context(self, room_version: str, event, context, do_sig_check=True) -> None: prev_state_ids = await context.get_prev_state_ids() auth_events_ids = self.compute_auth_events(event, prev_state_ids, for_verification=True) auth_events_by_id = await self.store.get_events(auth_events_ids) auth_events = {(e.type, e.state_key): e for e in auth_events_by_id.values()} room_version_obj = KNOWN_ROOM_VERSIONS[room_version] event_auth.check(room_version_obj, event, auth_events=auth_events, do_sig_check=do_sig_check) async def check_user_in_room( self, room_id: str, user_id: str, current_state: Optional[StateMap[EventBase]] = None, allow_departed_users: bool = False, ) -> EventBase: """Check if the user is in the room, or was at some point. Args: room_id: The room to check. user_id: The user to check. current_state: 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 the database. allow_departed_users: if True, accept users that were previously members but have now departed. Raises: AuthError if the user is/was not in the room. Returns: 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 room. This will be the leave event if they have left the room. """ if current_state: member = current_state.get((EventTypes.Member, user_id), None) else: member = await self.state.get_current_state( room_id=room_id, event_type=EventTypes.Member, state_key=user_id) if member: membership = member.membership if membership == Membership.JOIN: return member # XXX this looks totally bogus. Why do we not allow users who have been banned, # or those who were members previously and have been re-invited? if allow_departed_users and membership == Membership.LEAVE: forgot = await self.store.did_forget(user_id, room_id) if not forgot: return member raise AuthError(403, "User %s not in room %s" % (user_id, room_id)) async def check_host_in_room(self, room_id: str, host: str) -> bool: with Measure(self.clock, "check_host_in_room"): return await self.store.is_host_joined(room_id, host) def get_public_keys(self, invite_event: EventBase) -> List[Dict[str, Any]]: return event_auth.get_public_keys(invite_event) async def get_user_by_req( self, request: SynapseRequest, allow_guest: bool = False, rights: str = "access", allow_expired: bool = False, ) -> Requester: """Get a registered user's ID. Args: request: An HTTP request with an access_token query parameter. allow_guest: If False, will raise an AuthError if the user making the request is a guest. rights: The operation being performed; the access token must allow this allow_expired: If True, allow the request through even if the account is expired, or session token lifetime has ended. Note that /login will deliver access tokens regardless of expiration. Returns: Resolves to the requester Raises: InvalidClientCredentialsError if no user by that token exists or the token is invalid. AuthError if access is denied for the user in the access token """ try: ip_addr = request.getClientIP() user_agent = get_request_user_agent(request) access_token = self.get_access_token_from_request(request) user_id, app_service = await self._get_appservice_user_id(request) if user_id and app_service: if ip_addr and self._track_appservice_user_ips: await self.store.insert_client_ip( user_id=user_id, access_token=access_token, ip=ip_addr, user_agent=user_agent, device_id="dummy-device", # stubbed ) requester = create_requester(user_id, app_service=app_service) request.requester = user_id if user_id in self._force_tracing_for_users: opentracing.set_tag(opentracing.tags.SAMPLING_PRIORITY, 1) opentracing.set_tag("authenticated_entity", user_id) opentracing.set_tag("user_id", user_id) opentracing.set_tag("appservice_id", app_service.id) return requester user_info = await self.get_user_by_access_token( access_token, rights, allow_expired=allow_expired) token_id = user_info.token_id is_guest = user_info.is_guest shadow_banned = user_info.shadow_banned # Deny the request if the user account has expired. if self._account_validity_enabled and not allow_expired: if await self.store.is_account_expired(user_info.user_id, self.clock.time_msec()): raise AuthError(403, "User account has expired", errcode=Codes.EXPIRED_ACCOUNT) device_id = user_info.device_id if access_token and ip_addr: await self.store.insert_client_ip( user_id=user_info.token_owner, access_token=access_token, ip=ip_addr, user_agent=user_agent, device_id=device_id, ) if is_guest and not allow_guest: raise AuthError( 403, "Guest access not allowed", errcode=Codes.GUEST_ACCESS_FORBIDDEN, ) requester = create_requester( user_info.user_id, token_id, is_guest, shadow_banned, device_id, app_service=app_service, authenticated_entity=user_info.token_owner, ) request.requester = requester if user_info.token_owner in self._force_tracing_for_users: opentracing.set_tag(opentracing.tags.SAMPLING_PRIORITY, 1) opentracing.set_tag("authenticated_entity", user_info.token_owner) opentracing.set_tag("user_id", user_info.user_id) if device_id: opentracing.set_tag("device_id", device_id) return requester except KeyError: raise MissingClientTokenError() async def _get_appservice_user_id( self, request: Request ) -> Tuple[Optional[str], Optional[ApplicationService]]: app_service = self.store.get_app_service_by_token( self.get_access_token_from_request(request)) if app_service is None: return None, None if app_service.ip_range_whitelist: ip_address = IPAddress(request.getClientIP()) if ip_address not in app_service.ip_range_whitelist: return None, None # This will always be set by the time Twisted calls us. assert request.args is not None if b"user_id" not in request.args: return app_service.sender, app_service user_id = request.args[b"user_id"][0].decode("utf8") if app_service.sender == user_id: return app_service.sender, app_service if not app_service.is_interested_in_user(user_id): raise AuthError( 403, "Application service cannot masquerade as this user.") if not (await self.store.get_user_by_id(user_id)): raise AuthError( 403, "Application service has not registered this user") return user_id, app_service async def get_user_by_access_token( self, token: str, rights: str = "access", allow_expired: bool = False, ) -> TokenLookupResult: """Validate access token and get user_id from it Args: token: The access token to get the user by rights: The operation being performed; the access token must allow this allow_expired: If False, raises an InvalidClientTokenError if the token is expired Raises: InvalidClientTokenError if a user by that token exists, but the token is expired InvalidClientCredentialsError if no user by that token exists or the token is invalid """ if rights == "access": # first look in the database r = await self.store.get_user_by_access_token(token) if r: valid_until_ms = r.valid_until_ms if (not allow_expired and valid_until_ms is not None and valid_until_ms < self.clock.time_msec()): # there was a valid access token, but it has expired. # soft-logout the user. raise InvalidClientTokenError( msg="Access token has expired", soft_logout=True) return r # otherwise it needs to be a valid macaroon try: user_id, guest = self._parse_and_validate_macaroon(token, rights) if rights == "access": if not guest: # non-guest access tokens must be in the database logger.warning("Unrecognised access token - not in store.") raise InvalidClientTokenError() # Guest access tokens are not stored in the database (there can # only be one access token per guest, anyway). # # In order to prevent guest access tokens being used as regular # user access tokens (and hence getting around the invalidation # process), we look up the user id and check that it is indeed # a guest user. # # It would of course be much easier to store guest access # tokens in the database as well, but that would break existing # guest tokens. stored_user = await self.store.get_user_by_id(user_id) if not stored_user: raise InvalidClientTokenError("Unknown user_id %s" % user_id) if not stored_user["is_guest"]: raise InvalidClientTokenError( "Guest access token used for regular user") ret = TokenLookupResult( user_id=user_id, is_guest=True, # all guests get the same device id device_id=GUEST_DEVICE_ID, ) elif rights == "delete_pusher": # We don't store these tokens in the database ret = TokenLookupResult(user_id=user_id, is_guest=False) else: raise RuntimeError("Unknown rights setting %s", rights) return ret except ( _InvalidMacaroonException, pymacaroons.exceptions.MacaroonException, TypeError, ValueError, ) as e: logger.warning("Invalid macaroon in auth: %s %s", type(e), e) raise InvalidClientTokenError("Invalid macaroon passed.") def _parse_and_validate_macaroon(self, token: str, rights: str = "access" ) -> Tuple[str, bool]: """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) """ if rights == "access": cached = self.token_cache.get(token, None) if cached: return cached try: macaroon = pymacaroons.Macaroon.deserialize(token) except Exception: # deserialize can throw more-or-less anything # doesn't look like a macaroon: treat it as an opaque token which # must be in the database. # TODO: it would be nice to get rid of this, but apparently some # people use access tokens which aren't macaroons raise _InvalidMacaroonException() try: user_id = get_value_from_macaroon(macaroon, "user_id") guest = False for caveat in macaroon.caveats: if caveat.caveat_id == "guest = true": guest = True self.validate_macaroon(macaroon, rights, user_id=user_id) except ( pymacaroons.exceptions.MacaroonException, KeyError, TypeError, ValueError, ): raise InvalidClientTokenError("Invalid macaroon passed.") if rights == "access": self.token_cache[token] = (user_id, guest) return user_id, guest def validate_macaroon(self, macaroon: pymacaroons.Macaroon, type_string: str, user_id: str) -> None: """ validate that a Macaroon is understood by and was signed by this server. Args: macaroon: The macaroon to validate type_string: The kind of token required (e.g. "access", "delete_pusher") user_id: The user_id required """ v = pymacaroons.Verifier() # the verifier runs a test for every caveat on the macaroon, to check # that it is met for the current request. Each caveat must match at # least one of the predicates specified by satisfy_exact or # specify_general. v.satisfy_exact("gen = 1") v.satisfy_exact("type = " + type_string) v.satisfy_exact("user_id = %s" % user_id) v.satisfy_exact("guest = true") satisfy_expiry(v, self.clock.time_msec) # access_tokens include a nonce for uniqueness: any value is acceptable v.satisfy_general(lambda c: c.startswith("nonce = ")) v.verify(macaroon, self._macaroon_secret_key) def get_appservice_by_req(self, request: SynapseRequest) -> ApplicationService: token = self.get_access_token_from_request(request) service = self.store.get_app_service_by_token(token) if not service: logger.warning("Unrecognised appservice access token.") raise InvalidClientTokenError() request.requester = create_requester(service.sender, app_service=service) return service async def is_server_admin(self, user: UserID) -> bool: """Check if the given user is a local server admin. Args: user: user to check Returns: True if the user is an admin """ return await self.store.is_server_admin(user) def compute_auth_events( self, event, current_state_ids: StateMap[str], for_verification: bool = False, ) -> List[str]: """Given an event and current state return the list of event IDs used to auth an event. If `for_verification` is False then only return auth events that should be added to the event's `auth_events`. Returns: List of event IDs. """ if event.type == EventTypes.Create: return [] # Currently we ignore the `for_verification` flag even though there are # some situations where we can drop particular auth events when adding # to the event's `auth_events` (e.g. joins pointing to previous joins # when room is publicly joinable). Dropping event IDs has the # advantage that the auth chain for the room grows slower, but we use # the auth chain in state resolution v2 to order events, which means # care must be taken if dropping events to ensure that it doesn't # introduce undesirable "state reset" behaviour. # # All of which sounds a bit tricky so we don't bother for now. auth_ids = [] for etype, state_key in event_auth.auth_types_for_event(event): auth_ev_id = current_state_ids.get((etype, state_key)) if auth_ev_id: auth_ids.append(auth_ev_id) return auth_ids async def check_can_change_room_list(self, room_id: str, user: UserID) -> bool: """Determine whether the user is allowed to edit the room's entry in the published room list. Args: room_id user """ is_admin = await self.is_server_admin(user) if is_admin: return True user_id = user.to_string() await self.check_user_in_room(room_id, user_id) # We currently require the user is a "moderator" in the room. We do this # by checking if they would (theoretically) be able to change the # m.room.canonical_alias events power_level_event = await self.state.get_current_state( room_id, EventTypes.PowerLevels, "") auth_events = {} if power_level_event: auth_events[(EventTypes.PowerLevels, "")] = power_level_event send_level = event_auth.get_send_level(EventTypes.CanonicalAlias, "", power_level_event) user_level = event_auth.get_user_power_level(user_id, auth_events) return user_level >= send_level @staticmethod def has_access_token(request: Request) -> bool: """Checks if the request has an access_token. Returns: False if no access_token was given, True otherwise. """ # This will always be set by the time Twisted calls us. assert request.args is not None query_params = request.args.get(b"access_token") auth_headers = request.requestHeaders.getRawHeaders(b"Authorization") return bool(query_params) or bool(auth_headers) @staticmethod def get_access_token_from_request(request: Request) -> str: """Extracts the access_token from the request. Args: request: The http request. Returns: The access_token Raises: MissingClientTokenError: If there isn't a single access_token in the request """ # This will always be set by the time Twisted calls us. assert request.args is not None auth_headers = request.requestHeaders.getRawHeaders(b"Authorization") query_params = request.args.get(b"access_token") if auth_headers: # Try the get the access_token from a "Authorization: Bearer" # header if query_params is not None: raise MissingClientTokenError( "Mixing Authorization headers and access_token query parameters." ) if len(auth_headers) > 1: raise MissingClientTokenError( "Too many Authorization headers.") parts = auth_headers[0].split(b" ") if parts[0] == b"Bearer" and len(parts) == 2: return parts[1].decode("ascii") else: raise MissingClientTokenError("Invalid Authorization header.") else: # Try to get the access_token from the query params. if not query_params: raise MissingClientTokenError() return query_params[0].decode("ascii") async def check_user_in_room_or_world_readable( self, room_id: str, user_id: str, allow_departed_users: bool = False) -> Tuple[str, Optional[str]]: """Checks that the user is or was in the room or the room is world readable. If it isn't then an exception is raised. Args: room_id: room to check user_id: user to check allow_departed_users: if True, accept users that were previously members but have now departed Returns: Resolves to the current membership of the user in the room and the membership event ID of the user. If the user is not in the room and never has been, then `(Membership.JOIN, None)` is returned. """ try: # check_user_in_room will return the most recent membership # event for the user if: # * The user is a non-guest user, and was ever in the room # * The user is a guest user, and has joined the room # else it will throw. member_event = await self.check_user_in_room( room_id, user_id, allow_departed_users=allow_departed_users) return member_event.membership, member_event.event_id except AuthError: visibility = await self.state.get_current_state( room_id, EventTypes.RoomHistoryVisibility, "") if (visibility and visibility.content.get("history_visibility") == HistoryVisibility.WORLD_READABLE): return Membership.JOIN, None raise AuthError( 403, "User %s not in room %s, and room previews are disabled" % (user_id, room_id), ) async def check_auth_blocking(self, *args, **kwargs) -> None: await self._auth_blocking.check_auth_blocking(*args, **kwargs)
class Cache(object): __slots__ = ( "cache", "max_entries", "name", "keylen", "sequence", "thread", "metrics", ) def __init__(self, name, max_entries=1000, keylen=1, tree=False): cache_type = TreeCache if tree else dict self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type ) self.name = name self.keylen = keylen self.sequence = 0 self.thread = None self.metrics = register_cache(name, self.cache) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get(self, key, default=_CacheSentinel, callback=None): val = self.cache.get(key, _CacheSentinel, callback=callback) if val is not _CacheSentinel: self.metrics.inc_hits() return val self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def update(self, sequence, key, value, callback=None): self.check_thread() if self.sequence == sequence: # Only update the cache if the caches sequence number matches the # number that the cache had before the SELECT was started (SYN-369) self.prefill(key, value, callback=callback) def prefill(self, key, value, callback=None): self.cache.set(key, value, callback=callback) def invalidate(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError( "The cache key must be a tuple not %r" % (type(key),) ) # Increment the sequence number so that any SELECT statements that # raced with the INSERT don't update the cache (SYN-369) self.sequence += 1 self.cache.pop(key, None) def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError( "The cache key must be a tuple not %r" % (type(key),) ) self.sequence += 1 self.cache.del_multi(key) def invalidate_all(self): self.check_thread() self.sequence += 1 self.cache.clear()