text stringlengths 79 3.72M |
|---|
<vulnerable_code> b" object-src 'self';",
)
request.setHeader(
b"Referrer-Policy", b"no-referrer",
)
server_name, media_id, name = parse_media_id(request)
if server_name == self.server_name:<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fix... |
<vulnerable_code> # Failed to find the file anywhere, lets download it.
try:
media_info = await self._download_remote_file(server_name, media_id,)
except SynapseError:
raise
except Exception as e:
responder = await self.media_storage.fetch_media(file_info)... |
<vulnerable_code> return fname
async def write_to_file(self, source: IO, output: IO):
"""Asynchronously write the `source` to `output`.
"""
await defer_to_thread(self.reactor, _write_file_synchronously, source, output)
@contextlib.contextmanager
path = attr.ib(type=str)
... |
<vulnerable_code> )
async def _expire_url_cache_data(self) -> None:
"""Clean up expired url cache content, media and thumbnails.
"""
# TODO: Delete from backup media store
assert self._worker_run_media_background_jobs<commit_title>[PATCH 01/14] Fix some typos.<commit_descrip... |
<vulnerable_code>
class ResourceLimitsServerNotices:
""" Keeps track of whether the server has reached it's resource limit and
ensures that the client is kept up to date.
"""
<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
class ResourceLimitsServerNotices:
"""Keeps track ... |
<vulnerable_code> async def resolve_state_groups_for_events(
self, room_id: str, event_ids: Iterable[str]
) -> _StateCacheEntry:
""" Given a list of event_ids this method fetches the state at each
event, resolves conflicts between them and returns them.
Args:
retu... |
<vulnerable_code> if event.room_id != room_id:
raise Exception(
"Attempting to state-resolve for room %s with event %s which is in %s"
% (room_id, event.event_id, event.room_id,)
)
# get the ids of the auth events which allow us to authenticate the
... |
<vulnerable_code> if event.room_id != room_id:
raise Exception(
"Attempting to state-resolve for room %s with event %s which is in %s"
% (room_id, event.event_id, event.room_id,)
)
full_conflicted_set = {eid for eid in full_conflicted_set if eid in eve... |
<vulnerable_code>
class Storage:
"""The high level interfaces for talking to various storage layers.
"""
def __init__(self, hs: "HomeServer", stores: Databases):
# We include the main data store here mainly so that we don't have to<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fix... |
<vulnerable_code>
class BackgroundUpdater:
""" Background updates are updates to the database that run in the
background. Each update processes a batch of data at once. We attempt to
limit the impact of each update by monitoring how long each batch takes to
process and autotuning the batch size.
... |
<vulnerable_code>def make_pool(
reactor, db_config: DatabaseConnectionConfig, engine: BaseDatabaseEngine
) -> adbapi.ConnectionPool:
"""Get the connection pool for the database.
"""
# By default enable `cp_reconnect`. We need to fiddle with db_args in case
# someone has explicitly set `cp_reconnect... |
<vulnerable_code> database_config.databases,
)
prepare_database(
db_conn, engine, hs.config, databases=database_config.databases,
)
database = DatabasePool(hs, database_config, engine)<commit_title>[PATCH 01/14] Fix ... |
<vulnerable_code> return self.services_cache
def get_if_app_services_interested_in_user(self, user_id: str) -> bool:
"""Check if the user is one associated with an app service (exclusively)
"""
if self.exclusive_user_regex:
return bool(self.exclusive_user_regex.match(user... |
<vulnerable_code> return batch_size
async def _devices_last_seen_update(self, progress, batch_size):
"""Background update to insert last seen info into devices table
"""
last_user_id = progress.get("last_user_id", "")
last_device_id = progress.get("last_device_id", "")
... |
<vulnerable_code>
# make sure we go through the devices in stream order
device_ids = sorted(
user_devices.keys(), key=lambda i: query_map[(user_id, i)][0],
)
for device_id in device_ids:
async def mark_as_sent_devices_by_remote(
self, destinat... |
<vulnerable_code> servers: Iterable[str],
creator: Optional[str] = None,
) -> None:
""" Creates an association between a room alias and room_id/servers
Args:
room_alias: The alias to create.
return room_id
async def update_aliases_for_room(
self, old_... |
<vulnerable_code> async def count_e2e_one_time_keys(
self, user_id: str, device_id: str
) -> Dict[str, int]:
""" Count the number of one time keys the server has for a device
Returns:
A mapping from algorithm to number of keys for that algorithm.
"""
)
def... |
<vulnerable_code> 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.
# origin chain.
... |
<vulnerable_code>
def _deserialize_action(actions, is_highlight):
"""Custom deserializer for actions. This allows us to "compress" common actions
"""
if actions:
return db_to_json(actions)
@cached(num_args=3, tree=True, max_entries=5000)
async def get_unread_event_push_actions_by_room_for... |
<vulnerable_code> self._update_current_state_txn(txn, state_delta_for_room, min_stream_order)
def _persist_event_auth_chain_txn(
self, txn: LoggingTransaction, events: List[EventBase],
) -> None:
# We only care about state events, so this if there are no state events.
event_to_r... |
<vulnerable_code>
@attr.s(slots=True, frozen=True)
class _CalculateChainCover:
"""Return value for _calculate_chain_cover_txn.
"""
# The last room_id/depth/stream processed.
room_id = attr.ib(type=str)
)
self.db_pool.updates.register_background_update_handler(
"rejected_eve... |
<vulnerable_code> if txn.rowcount > 0:
# Invalidate the cache
self._invalidate_cache_and_stream(
txn, self.get_latest_event_ids_in_room, (room_id,),
)
return txn.rowcount
return self.db_pool.cursor_to_dict(txn)
... |
<vulnerable_code> # SQLite).
if hs.get_instance_name() in hs.config.worker.writers.events:
self._stream_id_gen = StreamIdGenerator(
db_conn, "events", "stream_ordering",
)
self._backfill_id_gen = StreamIdGenerator(
... |
<vulnerable_code> )
async def get_rooms_for_summary_by_category(
self, group_id: str, include_private: bool = False,
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
"""Get the rooms and categories that should be included in a summary request
async def is_user_invited_to_local_grou... |
<vulnerable_code>
class KeyStore(SQLBaseStore):
"""Persistence for signature verification keys
"""
@cached()
def _get_server_verify_key(self, server_name_and_key_id):<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
class KeyStore(SQLBaseStore):
"""Persistence for signa... |
<vulnerable_code> )
async def get_local_media_before(
self, before_ts: int, size_gt: int, keep_profiles: bool,
) -> List[str]:
# to find files that have never been accessed (last_access_ts IS NULL)
)
async def get_remote_media_thumbnail(
self, origin: str, media_id:... |
<vulnerable_code> raise NotImplementedError()
@cachedList(
cached_method_name="_get_presence_for_user", list_name="user_ids", num_args=1,
)
async def get_presence_for_users(self, user_ids):
rows = await self.db_pool.simple_select_many_batch(<commit_title>[PATCH 01/14] Fix some typos.... |
<vulnerable_code> )
async def is_subscribed_remote_profile_for_user(self, user_id):
"""Check whether we are interested in a remote user's profile.
"""
res = await self.db_pool.simple_select_one_onecol(
table="group_users",
keyvalues={"user_id": user_id},
... |
<vulnerable_code> )
@cachedList(
cached_method_name="get_push_rules_for_user", list_name="user_ids", num_args=1,
)
async def bulk_get_push_rules(self, user_ids):
if not user_ids:
use_new_defaults = user_id in self._users_new_default_push_rules
results[use... |
<vulnerable_code> raise NotImplementedError()
@cachedList(
cached_method_name="get_if_user_has_pusher", list_name="user_ids", num_args=1,
)
async def get_if_users_have_pushers(
self, user_ids: Iterable[str]
params_by_room = {}
for row in res:
params_by_roo... |
<vulnerable_code> async def _get_linearized_receipts_for_room(
self, room_id: str, to_key: int, from_key: Optional[int] = None
) -> List[dict]:
"""See get_linearized_receipts_for_room
"""
def f(txn):
if from_key:
}
return results
@cached(num_args=... |
<vulnerable_code> # call `find_max_generated_user_id_localpart` each time, which is
# expensive if there are many entries.
self._user_id_seq = build_sequence_generator(
database.engine, find_max_generated_user_id_localpart, "user_id_seq",
)
self._account_validity = hs... |
<vulnerable_code> )
async def get_room_count(self) -> int:
"""Retrieve the total number of rooms.
"""
def f(txn):
sql = "SELECT count(*) FROM rooms"
return rooms, room_count[0]
return await self.db_pool.runInteraction(
"get_rooms_paginat... |
<vulnerable_code> ):
self._known_servers_count = 1
self.hs.get_clock().looping_call(
self._count_known_servers, 60 * 1000,
)
self.hs.get_clock().call_later(
1000, self._count_known_servers,
)
LaterGauge(
... |
<vulnerable_code>
def run_upgrade(cur, database_engine, *args, **kwargs):
cur.execute(
"UPDATE remote_media_cache SET last_access_ts = ?", (int(time.time() * 1000),),
)<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
def run_upgrade(cur, database_engine, *args, **kwargs):
... |
<vulnerable_code>
# this inherits from EventsWorkerStore because it calls self.get_events
class StateGroupWorkerStore(EventsWorkerStore, SQLBaseStore):
"""The parts of StateGroupStore that can be called from workers.
"""
def __init__(self, database: DatabasePool, db_conn, hs):
super().__init__(data... |
<vulnerable_code> ORDER BY {order_by_column} {order}
LIMIT ? OFFSET ?
""".format(
sql_base=sql_base, order_by_column=order_by_column, order=order,
)
args += [limit, start]<commit_title>[PATCH 01/14] Fix some typos.<commit_description><f... |
<vulnerable_code> AND e.stream_ordering > ? AND e.stream_ordering <= ?
ORDER BY e.stream_ordering ASC
"""
txn.execute(sql, (user_id, min_from_id, max_to_id,))
rows = [
_EventDictReturn(event_id, None, stream_ordering)
re... |
<vulnerable_code>
class TransactionStore(TransactionWorkerStore):
"""A collection of queries for handling PDUs.
"""
def __init__(self, database: DatabasePool, db_conn, hs):
super().__init__(database, db_conn, hs)
)
async def store_destination_rooms_entries(
self, destinati... |
<vulnerable_code> """
async def create_ui_auth_session(
self, clientdict: JsonDict, uri: str, method: str, description: str,
) -> UIAuthSessionData:
"""
Creates a new user interactive authentication session.
return UIAuthSessionData(session_id, **result)
async def mark_u... |
<vulnerable_code> return len(users_to_work_on)
async def is_room_world_readable_or_publicly_joinable(self, room_id):
"""Check if the room is either world_readable or publically joinable
"""
# Create a state filter that only queries join and history state event
types_to_filte... |
<vulnerable_code>
class StateGroupDataStore(StateBackgroundUpdateStore, SQLBaseStore):
"""A data store for fetching/storing state groups.
"""
def __init__(self, database: DatabasePool, db_conn, hs):
super().__init__(database, db_conn, hs)
50000,
)
self._state_group_memb... |
<vulnerable_code> @property
@abc.abstractmethod
def server_version(self) -> str:
"""Gets a string giving the server version. For example: '3.22.0'
"""
...
@abc.abstractmethod
def in_transaction(self, conn: Connection) -> bool:
"""Whether the connection is currently in... |
<vulnerable_code>
@property
def supports_using_any_list(self):
"""Do we support using `a = ANY(?)` and passing a list
"""
return True
def is_deadlock(self, error):<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
@property
def supports_using_any_li... |
<vulnerable_code> super().__init__(database_module, database_config)
database = database_config.get("args", {}).get("database")
self._is_in_memory = database in (None, ":memory:",)
if platform.python_implementation() == "PyPy":
# pypy's sqlite3 module doesn't handle bytearra... |
<vulnerable_code> )
for room_id, ev_ctx_rm in events_by_room.items():
latest_event_ids = await self.main_store.get_latest_event_ids_in_room(
room_id
)
new_latest_event_ids = aw... |
<vulnerable_code> # We don't support using the same file name in the same delta version.
raise PrepareDatabaseException(
"Found multiple delta files with the same name in v%d: %s"
% (v, duplicates,)
)
# We sort to ensure that we apply the delta... |
<vulnerable_code>
class PurgeEventsStorage:
"""High level interface for purging rooms and event history.
"""
def __init__(self, hs: "HomeServer", stores: Databases):
self.stores = stores
async def purge_room(self, room_id: str) -> None:
"""Deletes all record of a room
"""
... |
<vulnerable_code>
class StateGroupStorage:
"""High level interface to fetching state for event.
"""
def __init__(self, hs: "HomeServer", stores: "Databases"):
self.stores = stores
async def get_state_groups(
self, room_id: str, event_ids: Iterable[str]
) -> Dict[int, List[EventBase... |
<vulnerable_code> self._load_current_ids(db_conn, tables)
def _load_current_ids(
self, db_conn, tables: List[Tuple[str, str, str]],
):
cur = db_conn.cursor(txn_name="_load_current_ids")
rows.sort()
with self._lock:
for (instance, stream_id,) in r... |
<vulnerable_code> stream_name: Optional[str] = None,
positive: bool = True,
):
"""See SequenceGenerator.check_consistency for docstring.
"""
txn = db_conn.cursor(txn_name="sequence.check_consistency")
<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>... |
<vulnerable_code> )
def __attrs_post_init__(self):
"""Validates that both `topological` and `instance_map` aren't set.
"""
if self.instance_map and self.topological:
raise ValueError(
instance_name = await store.get_name_from_instance_id(instance_id)
... |
<vulnerable_code> self.key_to_defer = {} # type: Dict[Hashable, _LinearizerEntry]
def is_queued(self, key: Hashable) -> bool:
"""Checks whether there is a process queued up waiting
"""
entry = self.key_to_defer.get(key)
if not entry:
# No entry so nothing is wait... |
<vulnerable_code>
def intern_string(string):
"""Takes a (potentially) unicode string and interns it if it's ascii
"""
if string is None:
return None
def intern_dict(dictionary):
"""Takes a dictionary and interns well known keys and their values
"""
return {
KNOWN_KEYS.get(key... |
<vulnerable_code>
def lru_cache(
max_entries: int = 1000, cache_context: bool = False,
) -> Callable[[F], _LruCachedFunction[F]]:
"""A method decorator that applies a memoizing cache around the function.
def func(orig: F) -> _LruCachedFunction[F]:
desc = LruCacheDescriptor(
orig, max_... |
<vulnerable_code> return False
def has_entity_changed(self, entity: EntityType, stream_pos: int) -> bool:
"""Returns True if the entity may have been updated since stream_pos
"""
assert isinstance(stream_pos, int)
if stream_pos < self._earliest_known_stream_pos:
retu... |
<vulnerable_code> return await maybe_awaitable(observer(*args, **kwargs))
except Exception as e:
logger.warning(
"%s signal observer %s failed: %r", self.name, observer, e,
)
deferreds = [run_in_background(do, o) for o in self.obser... |
<vulnerable_code> self._producer.resumeProducing()
def unregisterProducer(self):
"""Part of IProducer interface
"""
self._producer = None
if not self._finished_deferred.called:
self._bytes_queue.put_nowait(None)
def write(self, bytes):
"""Part of ... |
<vulnerable_code>
def sorted_topologically(
nodes: Iterable[T], graph: Mapping[T, Collection[T]],
) -> Generator[T, None, None]:
"""Given a set of nodes and a graph, yield the nodes in toplogical order.
<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
def sorted_topologically(
... |
<vulnerable_code>
class JsonEncodedObject:
""" A common base class for defining protocol units that are represented
as JSON.
Attributes:
"""
def __init__(self, **kwargs):
""" Takes the dict of `kwargs` and loads all keys that are *valid*
(i.e., are included in the `valid_keys` lis... |
<vulnerable_code> return self._logging_context.get_resource_usage()
def _update_in_flight(self, metrics):
"""Gets called when processing in flight metrics
"""
duration = self.clock.time() - self.start
metrics.real_time_max = max(metrics.real_time_max, duration)<commit_title>... |
<vulnerable_code>
def load_module(provider: dict, config_path: Iterable[str]) -> Tuple[Type, Any]:
""" Loads a synapse module with its config
Args:
provider: a dict with keys 'module' (the module name) and 'config'<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
def load_m... |
<vulnerable_code> # We don't raise here as its perfectly valid for contexts to
# change in a function, as long as it sets the correct context
# on resolving (which is checked separately).
err = (
"%s changed context from %s to %s, happen... |
<vulnerable_code> runner.args.loops = orig_loops
loops = "auto"
runner.bench_time_func(
suite.__name__ + "_" + str(loops), make_test(suite.main),
)<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
runner.args.loops = orig_loops
... |
<vulnerable_code>
logger = logging.getLogger("synapse.logging.test_terse_json")
_setup_stdlib_logging(
hs_config, log_config, logBeginner=beginner,
)
# Wait for it to connect...<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
logger = logging.getLogger("synapse.l... |
<vulnerable_code> if token != tok:
return None
return TokenLookupResult(
user_id=USER_ID, is_guest=False, token_id=1234, device_id="DEVICE",
)
self.store.get_user_by_access_token = get_user<commit_title>[PATCH 01/14] Fix some typos.<commit_desc... |
<vulnerable_code>
def test_allowed_appservice_ratelimited_via_can_requester_do_action(self):
appservice = ApplicationService(
None, "example.com", id="foo", rate_limited=True, sender="@as:example.com",
)
as_requester = create_requester("@user:example.com", app_service=appservice)... |
<vulnerable_code> self.assertEqual(cache.max_size, 150)
def test_cache_with_asterisk_in_name(self):
"""Some caches have asterisks in their name, test that they are set correctly.
"""
config = {
"caches": {
t.read_config(config, config_dir_path="", data_dir_path="... |
<vulnerable_code> )
def build_perspectives_response(
self, server_name: str, signing_key: SigningKey, valid_until_ts: int,
) -> dict:
"""
Build a valid perspectives server response to a request for the given key
VALID_UNTIL_TS = 200 * 1000
response = self.build_p... |
<vulnerable_code>
event, context = self.get_success(
create_event(
self.hs, room_id=self.room_id, type="m.test", sender=self.user_id,
)
)
<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
event, context = self.get_success(
... |
<vulnerable_code> )
# Artificially raise the complexity
self.hs.get_datastore().get_current_state_event_counts = lambda x: make_awaitable(
600
)
d = handler._remote_join(<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
)
# ... |
<vulnerable_code>
ret = self.get_success(
e2e_handler.upload_signatures_for_device_keys(
u1, {u1: {"D1": d1_json, "D2": d2_json}},
)
)
self.assertEqual(ret["failures"], {})
self.assertGreaterEqual(content["stream_id"], prev_stream_id)
r... |
<vulnerable_code> self.token2 = self.login("user2", "password")
def test_single_public_joined_room(self):
"""Test that we write *all* events for a public room
"""
room_id = self.helper.create_room_as(
self.user1, tok=self.token1, is_public=True
)
self.asse... |
<vulnerable_code> # Create a new login for the user and dehydrated the device
device_id, access_token = self.get_success(
self.registration.register_device(
user_id=user_id, device_id=None, initial_display_name="new device",
)
)
<commit_title>[PATCH 01/14] ... |
<vulnerable_code> """A user can create an alias for a room they're in."""
self.get_success(
self.handler.create_association(
create_requester(self.test_user), self.room_alias, self.room_id,
)
)
self.get_failure(
self.handler.create_ass... |
<vulnerable_code> self.store = self.hs.get_datastore()
def test_query_local_devices_no_devices(self):
"""If the user has no devices, we expect an empty list.
"""
local_user = "@boris:" + self.hs.hostname
res = self.get_success(self.handler.query_local_devices({local_user: Non... |
<vulnerable_code> self.assertEqual(res, 404)
def test_create_version(self):
"""Check that we can create and then retrieve versions.
"""
res = self.get_success(
self.handler.create_version(
self.local_user,
)
def test_update_version(self):
... |
<vulnerable_code> for i in range(3):
event = create_invite()
self.get_success(
self.handler.on_invite_request(other_server, event, event.room_version,)
)
event = create_invite()
self.get_failure(
self.handler.on_invite_request(other... |
<vulnerable_code> self.room_id = self.helper.create_room_as(self.user_id, tok=self.access_token)
self.info = self.get_success(
self.hs.get_datastore().get_user_by_access_token(self.access_token,)
)
self.token_id = self.info.token_id
self.room_id = self.helper.create_... |
<vulnerable_code>
# Mismatching session
session = self._generate_oidc_session_token(
state="state", nonce="nonce", client_redirect_url="http://client/redirect",
)
request.args = {}
request.args[b"state"] = [b"mismatching state"]
# Internal server error with no... |
<vulnerable_code> }
)
def test_no_local_user_fallback_login(self):
"""localdb_enabled can block login with the local password
"""
self.register_user("localuser", "localpass")
# check_password must return an awaitable
}
)
def test_no_local_user_fallback_ui_... |
<vulnerable_code> )
def _add_new_user(self, room_id, user_id):
"""Add new user to the room by creating an event and poking the federation API.
"""
hostname = get_domain_from_id(user_id)
<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
)
def _a... |
<vulnerable_code> # Set avatar to an empty string
self.get_success(
self.handler.set_avatar_url(
self.frank, synapse.types.create_requester(self.frank), "",
)
)
<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
# Set avatar... |
<vulnerable_code> self.datastore.get_current_state_deltas = Mock(return_value=(0, None))
self.datastore.get_to_device_stream_token = lambda: 0
self.datastore.get_new_device_msgs_for_remote = lambda *args, **kargs: make_awaitable(
([], 0)
)
self.datastore.delete_device... |
<vulnerable_code>
# Check that the room has an encryption state event
event_content = self.helper.get_state(
room_id=room_id, event_type=EventTypes.RoomEncryption, tok=user_token,
)
self.assertEqual(event_content, {"algorithm": RoomEncryptionAlgorithms.DEFAULT})
# C... |
<vulnerable_code> self.successResultOf(test_d)
def test_get_well_known(self):
"""Test the behaviour when the .well-known delegates elsewhere
"""
self.mock_resolver.resolve_service.side_effect = generate_resolve_service([])
self.reactor.lookups["testserv"] = "1.2.3.4"
... |
<vulnerable_code>
# Check that the event was sent
self.event_creation_handler.create_and_send_nonmember_event.assert_called_with(
expected_requester, event_dict, ratelimit=False, ignore_shadow_ban=True,
)
# Create and send a state event<commit_title>[PATCH 01/14] Fix some ty... |
<vulnerable_code>
repl_handler = ReplicationCommandHandler(self.worker_hs)
self.client = ClientReplicationStreamProtocol(
self.worker_hs, "client", "test", clock, repl_handler,
)
self._client_transport = None
if self.hs.config.redis.redis_enabled:
# Handl... |
<vulnerable_code>
self.get_success(
self.master_store.store_room(
ROOM_ID, USER_ID, is_public=False, room_version=RoomVersions.V1,
)
)
<commit_title>[PATCH 01/14] Fix some typos.<commit_description><fixed_code>
self.get_success(
self.master_st... |
<vulnerable_code>
class AccountDataStreamTestCase(BaseStreamTestCase):
def test_update_function_room_account_data_limit(self):
"""Test replication with many room account data updates
"""
store = self.hs.get_datastore()
# generate lots of account data updates
self.assertEqual... |
<vulnerable_code> )
pls["users"][OTHER_USER] = 50
self.helper.send_state(
self.room_id, EventTypes.PowerLevels, pls, tok=self.user_tok,
)
# this is the point in the DAG where we make a fork
self.assertIsNone(sr.event_id)
def test_update_function_state... |
<vulnerable_code> self.factory = ReplicationStreamProtocolFactory(hs)
def _make_client(self) -> Tuple[IProtocol, StringTransport]:
"""Create a new direct TCP replication connection
"""
proto = self.factory.buildProtocol(("127.0.0.1", 0))
transport = StringTransport()<commit_... |
<vulnerable_code> )
def test_no_auth(self):
"""With no authentication the request should finish.
"""
channel = self._test_register()
self.assertEqual(channel.code, 200)
@override_config({"main_replication_secret": "my-secret"})
def test_missing_auth(self):
"... |
<vulnerable_code> return config
def test_register_single_worker(self):
"""Test that registration works when using a single client reader worker.
"""
worker_hs = self.make_worker_hs("synapse.app.client_reader")
site = self._hs_to_site[worker_hs]
self.assertEqual(chann... |
<vulnerable_code>
class MediaRepoShardTestCase(BaseMultiWorkerStreamTestCase):
"""Checks running multiple media repos work correctly.
"""
servlets = [
admin.register_servlets_for_client_rest_resource,
return channel, request
def test_basic(self):
"""Test basic fetching of remo... |
<vulnerable_code>
class PusherShardTestCase(BaseMultiWorkerStreamTestCase):
"""Checks pusher sharding works
"""
servlets = [
admin.register_servlets_for_client_rest_resource,
return event_id
def test_send_push_single_worker(self):
"""Test that registration works when using a p... |
<vulnerable_code>
class EventPersisterShardTestCase(BaseMultiWorkerStreamTestCase):
"""Checks event persisting sharding works
"""
# Event persister sharding requires postgres (due to needing
# `MutliWriterIdGenerator`).
return conf
def _create_room(self, room_id: str, user_id: str, tok: s... |
<vulnerable_code> )
def _get_groups_user_is_in(self, access_token):
"""Returns the list of groups the user is in (given their access token)
"""
channel = self.make_request(
"GET", "/joined_groups".encode("ascii"), access_token=access_token
)
class QuarantineMedi... |
<vulnerable_code> If the user is not a server admin, an error is returned.
"""
channel = self.make_request(
"GET", self.url, access_token=self.other_user_token,
)
self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
self.assertEqual(C... |
<vulnerable_code> # Two rooms and two users. Every user sends and reports every room event
for i in range(5):
self._create_event_and_report(
room_id=self.room_id1, user_tok=self.other_user_tok,
)
for i in range(5):
self._create_event_and_report(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.