utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018-2019 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import atexit
  16. import os
  17. from unittest.mock import Mock, patch
  18. from urllib import parse as urlparse
  19. from twisted.internet import defer
  20. from synapse.api.constants import EventTypes
  21. from synapse.api.errors import CodeMessageException, cs_error
  22. from synapse.api.room_versions import RoomVersions
  23. from synapse.config.homeserver import HomeServerConfig
  24. from synapse.config.server import DEFAULT_ROOM_VERSION
  25. from synapse.logging.context import current_context, set_current_context
  26. from synapse.storage.database import LoggingDatabaseConnection
  27. from synapse.storage.engines import create_engine
  28. from synapse.storage.prepare_database import prepare_database
  29. # set this to True to run the tests against postgres instead of sqlite.
  30. #
  31. # When running under postgres, we first create a base database with the name
  32. # POSTGRES_BASE_DB and update it to the current schema. Then, for each test case, we
  33. # create another unique database, using the base database as a template.
  34. USE_POSTGRES_FOR_TESTS = os.environ.get("SYNAPSE_POSTGRES", False)
  35. LEAVE_DB = os.environ.get("SYNAPSE_LEAVE_DB", False)
  36. POSTGRES_USER = os.environ.get("SYNAPSE_POSTGRES_USER", None)
  37. POSTGRES_HOST = os.environ.get("SYNAPSE_POSTGRES_HOST", None)
  38. POSTGRES_PASSWORD = os.environ.get("SYNAPSE_POSTGRES_PASSWORD", None)
  39. POSTGRES_BASE_DB = "_synapse_unit_tests_base_%s" % (os.getpid(),)
  40. # When debugging a specific test, it's occasionally useful to write the
  41. # DB to disk and query it with the sqlite CLI.
  42. SQLITE_PERSIST_DB = os.environ.get("SYNAPSE_TEST_PERSIST_SQLITE_DB") is not None
  43. # the dbname we will connect to in order to create the base database.
  44. POSTGRES_DBNAME_FOR_INITIAL_CREATE = "postgres"
  45. def setupdb():
  46. # If we're using PostgreSQL, set up the db once
  47. if USE_POSTGRES_FOR_TESTS:
  48. # create a PostgresEngine
  49. db_engine = create_engine({"name": "psycopg2", "args": {}})
  50. # connect to postgres to create the base database.
  51. db_conn = db_engine.module.connect(
  52. user=POSTGRES_USER,
  53. host=POSTGRES_HOST,
  54. password=POSTGRES_PASSWORD,
  55. dbname=POSTGRES_DBNAME_FOR_INITIAL_CREATE,
  56. )
  57. db_conn.autocommit = True
  58. cur = db_conn.cursor()
  59. cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
  60. cur.execute(
  61. "CREATE DATABASE %s ENCODING 'UTF8' LC_COLLATE='C' LC_CTYPE='C' "
  62. "template=template0;" % (POSTGRES_BASE_DB,)
  63. )
  64. cur.close()
  65. db_conn.close()
  66. # Set up in the db
  67. db_conn = db_engine.module.connect(
  68. database=POSTGRES_BASE_DB,
  69. user=POSTGRES_USER,
  70. host=POSTGRES_HOST,
  71. password=POSTGRES_PASSWORD,
  72. )
  73. db_conn = LoggingDatabaseConnection(db_conn, db_engine, "tests")
  74. prepare_database(db_conn, db_engine, None)
  75. db_conn.close()
  76. def _cleanup():
  77. db_conn = db_engine.module.connect(
  78. user=POSTGRES_USER,
  79. host=POSTGRES_HOST,
  80. password=POSTGRES_PASSWORD,
  81. dbname=POSTGRES_DBNAME_FOR_INITIAL_CREATE,
  82. )
  83. db_conn.autocommit = True
  84. cur = db_conn.cursor()
  85. cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
  86. cur.close()
  87. db_conn.close()
  88. atexit.register(_cleanup)
  89. def default_config(name, parse=False):
  90. """
  91. Create a reasonable test config.
  92. """
  93. config_dict = {
  94. "server_name": name,
  95. "send_federation": False,
  96. "media_store_path": "media",
  97. # the test signing key is just an arbitrary ed25519 key to keep the config
  98. # parser happy
  99. "signing_key": "ed25519 a_lPym qvioDNmfExFBRPgdTU+wtFYKq4JfwFRv7sYVgWvmgJg",
  100. "event_cache_size": 1,
  101. "enable_registration": True,
  102. "enable_registration_captcha": False,
  103. "macaroon_secret_key": "not even a little secret",
  104. "password_providers": [],
  105. "worker_replication_url": "",
  106. "worker_app": None,
  107. "block_non_admin_invites": False,
  108. "federation_domain_whitelist": None,
  109. "filter_timeline_limit": 5000,
  110. "user_directory_search_all_users": False,
  111. "user_consent_server_notice_content": None,
  112. "block_events_without_consent_error": None,
  113. "user_consent_at_registration": False,
  114. "user_consent_policy_name": "Privacy Policy",
  115. "media_storage_providers": [],
  116. "autocreate_auto_join_rooms": True,
  117. "auto_join_rooms": [],
  118. "limit_usage_by_mau": False,
  119. "hs_disabled": False,
  120. "hs_disabled_message": "",
  121. "max_mau_value": 50,
  122. "mau_trial_days": 0,
  123. "mau_stats_only": False,
  124. "mau_limits_reserved_threepids": [],
  125. "admin_contact": None,
  126. "rc_message": {"per_second": 10000, "burst_count": 10000},
  127. "rc_registration": {"per_second": 10000, "burst_count": 10000},
  128. "rc_login": {
  129. "address": {"per_second": 10000, "burst_count": 10000},
  130. "account": {"per_second": 10000, "burst_count": 10000},
  131. "failed_attempts": {"per_second": 10000, "burst_count": 10000},
  132. },
  133. "rc_joins": {
  134. "local": {"per_second": 10000, "burst_count": 10000},
  135. "remote": {"per_second": 10000, "burst_count": 10000},
  136. },
  137. "rc_invites": {
  138. "per_room": {"per_second": 10000, "burst_count": 10000},
  139. "per_user": {"per_second": 10000, "burst_count": 10000},
  140. },
  141. "rc_3pid_validation": {"per_second": 10000, "burst_count": 10000},
  142. "saml2_enabled": False,
  143. "public_baseurl": None,
  144. "default_identity_server": None,
  145. "key_refresh_interval": 24 * 60 * 60 * 1000,
  146. "old_signing_keys": {},
  147. "tls_fingerprints": [],
  148. "use_frozen_dicts": False,
  149. # We need a sane default_room_version, otherwise attempts to create
  150. # rooms will fail.
  151. "default_room_version": DEFAULT_ROOM_VERSION,
  152. # disable user directory updates, because they get done in the
  153. # background, which upsets the test runner.
  154. "update_user_directory": False,
  155. "caches": {"global_factor": 1},
  156. "listeners": [{"port": 0, "type": "http"}],
  157. }
  158. if parse:
  159. config = HomeServerConfig()
  160. config.parse_config_dict(config_dict, "", "")
  161. return config
  162. return config_dict
  163. def mock_getRawHeaders(headers=None):
  164. headers = headers if headers is not None else {}
  165. def getRawHeaders(name, default=None):
  166. return headers.get(name, default)
  167. return getRawHeaders
  168. # This is a mock /resource/ not an entire server
  169. class MockHttpResource:
  170. def __init__(self, prefix=""):
  171. self.callbacks = [] # 3-tuple of method/pattern/function
  172. self.prefix = prefix
  173. def trigger_get(self, path):
  174. return self.trigger(b"GET", path, None)
  175. @patch("twisted.web.http.Request")
  176. @defer.inlineCallbacks
  177. def trigger(
  178. self, http_method, path, content, mock_request, federation_auth_origin=None
  179. ):
  180. """Fire an HTTP event.
  181. Args:
  182. http_method : The HTTP method
  183. path : The HTTP path
  184. content : The HTTP body
  185. mock_request : Mocked request to pass to the event so it can get
  186. content.
  187. federation_auth_origin (bytes|None): domain to authenticate as, for federation
  188. Returns:
  189. A tuple of (code, response)
  190. Raises:
  191. KeyError If no event is found which will handle the path.
  192. """
  193. path = self.prefix + path
  194. # annoyingly we return a twisted http request which has chained calls
  195. # to get at the http content, hence mock it here.
  196. mock_content = Mock()
  197. config = {"read.return_value": content}
  198. mock_content.configure_mock(**config)
  199. mock_request.content = mock_content
  200. mock_request.method = http_method.encode("ascii")
  201. mock_request.uri = path.encode("ascii")
  202. mock_request.getClientIP.return_value = "-"
  203. headers = {}
  204. if federation_auth_origin is not None:
  205. headers[b"Authorization"] = [
  206. b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,)
  207. ]
  208. mock_request.requestHeaders.getRawHeaders = mock_getRawHeaders(headers)
  209. # return the right path if the event requires it
  210. mock_request.path = path
  211. # add in query params to the right place
  212. try:
  213. mock_request.args = urlparse.parse_qs(path.split("?")[1])
  214. mock_request.path = path.split("?")[0]
  215. path = mock_request.path
  216. except Exception:
  217. pass
  218. if isinstance(path, bytes):
  219. path = path.decode("utf8")
  220. for (method, pattern, func) in self.callbacks:
  221. if http_method != method:
  222. continue
  223. matcher = pattern.match(path)
  224. if matcher:
  225. try:
  226. args = [urlparse.unquote(u) for u in matcher.groups()]
  227. (code, response) = yield defer.ensureDeferred(
  228. func(mock_request, *args)
  229. )
  230. return code, response
  231. except CodeMessageException as e:
  232. return e.code, cs_error(e.msg, code=e.errcode)
  233. raise KeyError("No event can handle %s" % path)
  234. def register_paths(self, method, path_patterns, callback, servlet_name):
  235. for path_pattern in path_patterns:
  236. self.callbacks.append((method, path_pattern, callback))
  237. class MockKey:
  238. alg = "mock_alg"
  239. version = "mock_version"
  240. signature = b"\x9a\x87$"
  241. @property
  242. def verify_key(self):
  243. return self
  244. def sign(self, message):
  245. return self
  246. def verify(self, message, sig):
  247. assert sig == b"\x9a\x87$"
  248. def encode(self):
  249. return b"<fake_encoded_key>"
  250. class MockClock:
  251. now = 1000
  252. def __init__(self):
  253. # list of lists of [absolute_time, callback, expired] in no particular
  254. # order
  255. self.timers = []
  256. self.loopers = []
  257. def time(self):
  258. return self.now
  259. def time_msec(self):
  260. return self.time() * 1000
  261. def call_later(self, delay, callback, *args, **kwargs):
  262. ctx = current_context()
  263. def wrapped_callback():
  264. set_current_context(ctx)
  265. callback(*args, **kwargs)
  266. t = [self.now + delay, wrapped_callback, False]
  267. self.timers.append(t)
  268. return t
  269. def looping_call(self, function, interval, *args, **kwargs):
  270. self.loopers.append([function, interval / 1000.0, self.now, args, kwargs])
  271. def cancel_call_later(self, timer, ignore_errs=False):
  272. if timer[2]:
  273. if not ignore_errs:
  274. raise Exception("Cannot cancel an expired timer")
  275. timer[2] = True
  276. self.timers = [t for t in self.timers if t != timer]
  277. # For unit testing
  278. def advance_time(self, secs):
  279. self.now += secs
  280. timers = self.timers
  281. self.timers = []
  282. for t in timers:
  283. time, callback, expired = t
  284. if expired:
  285. raise Exception("Timer already expired")
  286. if self.now >= time:
  287. t[2] = True
  288. callback()
  289. else:
  290. self.timers.append(t)
  291. for looped in self.loopers:
  292. func, interval, last, args, kwargs = looped
  293. if last + interval < self.now:
  294. func(*args, **kwargs)
  295. looped[2] = self.now
  296. def advance_time_msec(self, ms):
  297. self.advance_time(ms / 1000.0)
  298. def time_bound_deferred(self, d, *args, **kwargs):
  299. # We don't bother timing things out for now.
  300. return d
  301. async def create_room(hs, room_id: str, creator_id: str):
  302. """Creates and persist a creation event for the given room"""
  303. persistence_store = hs.get_storage().persistence
  304. store = hs.get_datastores().main
  305. event_builder_factory = hs.get_event_builder_factory()
  306. event_creation_handler = hs.get_event_creation_handler()
  307. await store.store_room(
  308. room_id=room_id,
  309. room_creator_user_id=creator_id,
  310. is_public=False,
  311. room_version=RoomVersions.V1,
  312. )
  313. builder = event_builder_factory.for_room_version(
  314. RoomVersions.V1,
  315. {
  316. "type": EventTypes.Create,
  317. "state_key": "",
  318. "sender": creator_id,
  319. "room_id": room_id,
  320. "content": {},
  321. },
  322. )
  323. event, context = await event_creation_handler.create_new_client_event(builder)
  324. await persistence_store.persist_event(event, context)