utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 hashlib
  17. import os
  18. import time
  19. import uuid
  20. import warnings
  21. from typing import Type
  22. from unittest.mock import Mock, patch
  23. from urllib import parse as urlparse
  24. from twisted.internet import defer
  25. from synapse.api.constants import EventTypes
  26. from synapse.api.errors import CodeMessageException, cs_error
  27. from synapse.api.room_versions import RoomVersions
  28. from synapse.config.database import DatabaseConnectionConfig
  29. from synapse.config.homeserver import HomeServerConfig
  30. from synapse.config.server import DEFAULT_ROOM_VERSION
  31. from synapse.logging.context import current_context, set_current_context
  32. from synapse.server import HomeServer
  33. from synapse.storage import DataStore
  34. from synapse.storage.database import LoggingDatabaseConnection
  35. from synapse.storage.engines import PostgresEngine, create_engine
  36. from synapse.storage.prepare_database import prepare_database
  37. # set this to True to run the tests against postgres instead of sqlite.
  38. #
  39. # When running under postgres, we first create a base database with the name
  40. # POSTGRES_BASE_DB and update it to the current schema. Then, for each test case, we
  41. # create another unique database, using the base database as a template.
  42. USE_POSTGRES_FOR_TESTS = os.environ.get("SYNAPSE_POSTGRES", False)
  43. LEAVE_DB = os.environ.get("SYNAPSE_LEAVE_DB", False)
  44. POSTGRES_USER = os.environ.get("SYNAPSE_POSTGRES_USER", None)
  45. POSTGRES_HOST = os.environ.get("SYNAPSE_POSTGRES_HOST", None)
  46. POSTGRES_PASSWORD = os.environ.get("SYNAPSE_POSTGRES_PASSWORD", None)
  47. POSTGRES_BASE_DB = "_synapse_unit_tests_base_%s" % (os.getpid(),)
  48. # the dbname we will connect to in order to create the base database.
  49. POSTGRES_DBNAME_FOR_INITIAL_CREATE = "postgres"
  50. def setupdb():
  51. # If we're using PostgreSQL, set up the db once
  52. if USE_POSTGRES_FOR_TESTS:
  53. # create a PostgresEngine
  54. db_engine = create_engine({"name": "psycopg2", "args": {}})
  55. # connect to postgres to create the base database.
  56. db_conn = db_engine.module.connect(
  57. user=POSTGRES_USER,
  58. host=POSTGRES_HOST,
  59. password=POSTGRES_PASSWORD,
  60. dbname=POSTGRES_DBNAME_FOR_INITIAL_CREATE,
  61. )
  62. db_conn.autocommit = True
  63. cur = db_conn.cursor()
  64. cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
  65. cur.execute(
  66. "CREATE DATABASE %s ENCODING 'UTF8' LC_COLLATE='C' LC_CTYPE='C' "
  67. "template=template0;" % (POSTGRES_BASE_DB,)
  68. )
  69. cur.close()
  70. db_conn.close()
  71. # Set up in the db
  72. db_conn = db_engine.module.connect(
  73. database=POSTGRES_BASE_DB,
  74. user=POSTGRES_USER,
  75. host=POSTGRES_HOST,
  76. password=POSTGRES_PASSWORD,
  77. )
  78. db_conn = LoggingDatabaseConnection(db_conn, db_engine, "tests")
  79. prepare_database(db_conn, db_engine, None)
  80. db_conn.close()
  81. def _cleanup():
  82. db_conn = db_engine.module.connect(
  83. user=POSTGRES_USER,
  84. host=POSTGRES_HOST,
  85. password=POSTGRES_PASSWORD,
  86. dbname=POSTGRES_DBNAME_FOR_INITIAL_CREATE,
  87. )
  88. db_conn.autocommit = True
  89. cur = db_conn.cursor()
  90. cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
  91. cur.close()
  92. db_conn.close()
  93. atexit.register(_cleanup)
  94. def default_config(name, parse=False):
  95. """
  96. Create a reasonable test config.
  97. """
  98. config_dict = {
  99. "server_name": name,
  100. "send_federation": False,
  101. "media_store_path": "media",
  102. # the test signing key is just an arbitrary ed25519 key to keep the config
  103. # parser happy
  104. "signing_key": "ed25519 a_lPym qvioDNmfExFBRPgdTU+wtFYKq4JfwFRv7sYVgWvmgJg",
  105. "event_cache_size": 1,
  106. "enable_registration": True,
  107. "enable_registration_captcha": False,
  108. "macaroon_secret_key": "not even a little secret",
  109. "password_providers": [],
  110. "worker_replication_url": "",
  111. "worker_app": None,
  112. "block_non_admin_invites": False,
  113. "federation_domain_whitelist": None,
  114. "filter_timeline_limit": 5000,
  115. "user_directory_search_all_users": False,
  116. "user_consent_server_notice_content": None,
  117. "block_events_without_consent_error": None,
  118. "user_consent_at_registration": False,
  119. "user_consent_policy_name": "Privacy Policy",
  120. "media_storage_providers": [],
  121. "autocreate_auto_join_rooms": True,
  122. "auto_join_rooms": [],
  123. "limit_usage_by_mau": False,
  124. "hs_disabled": False,
  125. "hs_disabled_message": "",
  126. "max_mau_value": 50,
  127. "mau_trial_days": 0,
  128. "mau_stats_only": False,
  129. "mau_limits_reserved_threepids": [],
  130. "admin_contact": None,
  131. "rc_message": {"per_second": 10000, "burst_count": 10000},
  132. "rc_registration": {"per_second": 10000, "burst_count": 10000},
  133. "rc_login": {
  134. "address": {"per_second": 10000, "burst_count": 10000},
  135. "account": {"per_second": 10000, "burst_count": 10000},
  136. "failed_attempts": {"per_second": 10000, "burst_count": 10000},
  137. },
  138. "rc_joins": {
  139. "local": {"per_second": 10000, "burst_count": 10000},
  140. "remote": {"per_second": 10000, "burst_count": 10000},
  141. },
  142. "rc_invites": {
  143. "per_room": {"per_second": 10000, "burst_count": 10000},
  144. "per_user": {"per_second": 10000, "burst_count": 10000},
  145. },
  146. "rc_3pid_validation": {"per_second": 10000, "burst_count": 10000},
  147. "saml2_enabled": False,
  148. "public_baseurl": None,
  149. "default_identity_server": None,
  150. "key_refresh_interval": 24 * 60 * 60 * 1000,
  151. "old_signing_keys": {},
  152. "tls_fingerprints": [],
  153. "use_frozen_dicts": False,
  154. # We need a sane default_room_version, otherwise attempts to create
  155. # rooms will fail.
  156. "default_room_version": DEFAULT_ROOM_VERSION,
  157. # disable user directory updates, because they get done in the
  158. # background, which upsets the test runner.
  159. "update_user_directory": False,
  160. "caches": {"global_factor": 1},
  161. "listeners": [{"port": 0, "type": "http"}],
  162. }
  163. if parse:
  164. config = HomeServerConfig()
  165. config.parse_config_dict(config_dict, "", "")
  166. return config
  167. return config_dict
  168. class TestHomeServer(HomeServer):
  169. DATASTORE_CLASS = DataStore
  170. def setup_test_homeserver(
  171. cleanup_func,
  172. name="test",
  173. config=None,
  174. reactor=None,
  175. homeserver_to_use: Type[HomeServer] = TestHomeServer,
  176. **kwargs,
  177. ):
  178. """
  179. Setup a homeserver suitable for running tests against. Keyword arguments
  180. are passed to the Homeserver constructor.
  181. If no datastore is supplied, one is created and given to the homeserver.
  182. Args:
  183. cleanup_func : The function used to register a cleanup routine for
  184. after the test.
  185. Calling this method directly is deprecated: you should instead derive from
  186. HomeserverTestCase.
  187. """
  188. if reactor is None:
  189. from twisted.internet import reactor
  190. if config is None:
  191. config = default_config(name, parse=True)
  192. config.ldap_enabled = False
  193. if "clock" not in kwargs:
  194. kwargs["clock"] = MockClock()
  195. if USE_POSTGRES_FOR_TESTS:
  196. test_db = "synapse_test_%s" % uuid.uuid4().hex
  197. database_config = {
  198. "name": "psycopg2",
  199. "args": {
  200. "database": test_db,
  201. "host": POSTGRES_HOST,
  202. "password": POSTGRES_PASSWORD,
  203. "user": POSTGRES_USER,
  204. "cp_min": 1,
  205. "cp_max": 5,
  206. },
  207. }
  208. else:
  209. database_config = {
  210. "name": "sqlite3",
  211. "args": {"database": ":memory:", "cp_min": 1, "cp_max": 1},
  212. }
  213. if "db_txn_limit" in kwargs:
  214. database_config["txn_limit"] = kwargs["db_txn_limit"]
  215. database = DatabaseConnectionConfig("master", database_config)
  216. config.database.databases = [database]
  217. db_engine = create_engine(database.config)
  218. # Create the database before we actually try and connect to it, based off
  219. # the template database we generate in setupdb()
  220. if isinstance(db_engine, PostgresEngine):
  221. db_conn = db_engine.module.connect(
  222. database=POSTGRES_BASE_DB,
  223. user=POSTGRES_USER,
  224. host=POSTGRES_HOST,
  225. password=POSTGRES_PASSWORD,
  226. )
  227. db_conn.autocommit = True
  228. cur = db_conn.cursor()
  229. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  230. cur.execute(
  231. "CREATE DATABASE %s WITH TEMPLATE %s;" % (test_db, POSTGRES_BASE_DB)
  232. )
  233. cur.close()
  234. db_conn.close()
  235. hs = homeserver_to_use(
  236. name,
  237. config=config,
  238. version_string="Synapse/tests",
  239. reactor=reactor,
  240. )
  241. # Install @cache_in_self attributes
  242. for key, val in kwargs.items():
  243. setattr(hs, "_" + key, val)
  244. # Mock TLS
  245. hs.tls_server_context_factory = Mock()
  246. hs.tls_client_options_factory = Mock()
  247. hs.setup()
  248. if homeserver_to_use == TestHomeServer:
  249. hs.setup_background_tasks()
  250. if isinstance(db_engine, PostgresEngine):
  251. database = hs.get_datastores().databases[0]
  252. # We need to do cleanup on PostgreSQL
  253. def cleanup():
  254. import psycopg2
  255. # Close all the db pools
  256. database._db_pool.close()
  257. dropped = False
  258. # Drop the test database
  259. db_conn = db_engine.module.connect(
  260. database=POSTGRES_BASE_DB,
  261. user=POSTGRES_USER,
  262. host=POSTGRES_HOST,
  263. password=POSTGRES_PASSWORD,
  264. )
  265. db_conn.autocommit = True
  266. cur = db_conn.cursor()
  267. # Try a few times to drop the DB. Some things may hold on to the
  268. # database for a few more seconds due to flakiness, preventing
  269. # us from dropping it when the test is over. If we can't drop
  270. # it, warn and move on.
  271. for _ in range(5):
  272. try:
  273. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  274. db_conn.commit()
  275. dropped = True
  276. except psycopg2.OperationalError as e:
  277. warnings.warn(
  278. "Couldn't drop old db: " + str(e), category=UserWarning
  279. )
  280. time.sleep(0.5)
  281. cur.close()
  282. db_conn.close()
  283. if not dropped:
  284. warnings.warn("Failed to drop old DB.", category=UserWarning)
  285. if not LEAVE_DB:
  286. # Register the cleanup hook
  287. cleanup_func(cleanup)
  288. # bcrypt is far too slow to be doing in unit tests
  289. # Need to let the HS build an auth handler and then mess with it
  290. # because AuthHandler's constructor requires the HS, so we can't make one
  291. # beforehand and pass it in to the HS's constructor (chicken / egg)
  292. async def hash(p):
  293. return hashlib.md5(p.encode("utf8")).hexdigest()
  294. hs.get_auth_handler().hash = hash
  295. async def validate_hash(p, h):
  296. return hashlib.md5(p.encode("utf8")).hexdigest() == h
  297. hs.get_auth_handler().validate_hash = validate_hash
  298. return hs
  299. def mock_getRawHeaders(headers=None):
  300. headers = headers if headers is not None else {}
  301. def getRawHeaders(name, default=None):
  302. return headers.get(name, default)
  303. return getRawHeaders
  304. # This is a mock /resource/ not an entire server
  305. class MockHttpResource:
  306. def __init__(self, prefix=""):
  307. self.callbacks = [] # 3-tuple of method/pattern/function
  308. self.prefix = prefix
  309. def trigger_get(self, path):
  310. return self.trigger(b"GET", path, None)
  311. @patch("twisted.web.http.Request")
  312. @defer.inlineCallbacks
  313. def trigger(
  314. self, http_method, path, content, mock_request, federation_auth_origin=None
  315. ):
  316. """Fire an HTTP event.
  317. Args:
  318. http_method : The HTTP method
  319. path : The HTTP path
  320. content : The HTTP body
  321. mock_request : Mocked request to pass to the event so it can get
  322. content.
  323. federation_auth_origin (bytes|None): domain to authenticate as, for federation
  324. Returns:
  325. A tuple of (code, response)
  326. Raises:
  327. KeyError If no event is found which will handle the path.
  328. """
  329. path = self.prefix + path
  330. # annoyingly we return a twisted http request which has chained calls
  331. # to get at the http content, hence mock it here.
  332. mock_content = Mock()
  333. config = {"read.return_value": content}
  334. mock_content.configure_mock(**config)
  335. mock_request.content = mock_content
  336. mock_request.method = http_method.encode("ascii")
  337. mock_request.uri = path.encode("ascii")
  338. mock_request.getClientIP.return_value = "-"
  339. headers = {}
  340. if federation_auth_origin is not None:
  341. headers[b"Authorization"] = [
  342. b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,)
  343. ]
  344. mock_request.requestHeaders.getRawHeaders = mock_getRawHeaders(headers)
  345. # return the right path if the event requires it
  346. mock_request.path = path
  347. # add in query params to the right place
  348. try:
  349. mock_request.args = urlparse.parse_qs(path.split("?")[1])
  350. mock_request.path = path.split("?")[0]
  351. path = mock_request.path
  352. except Exception:
  353. pass
  354. if isinstance(path, bytes):
  355. path = path.decode("utf8")
  356. for (method, pattern, func) in self.callbacks:
  357. if http_method != method:
  358. continue
  359. matcher = pattern.match(path)
  360. if matcher:
  361. try:
  362. args = [urlparse.unquote(u) for u in matcher.groups()]
  363. (code, response) = yield defer.ensureDeferred(
  364. func(mock_request, *args)
  365. )
  366. return code, response
  367. except CodeMessageException as e:
  368. return e.code, cs_error(e.msg, code=e.errcode)
  369. raise KeyError("No event can handle %s" % path)
  370. def register_paths(self, method, path_patterns, callback, servlet_name):
  371. for path_pattern in path_patterns:
  372. self.callbacks.append((method, path_pattern, callback))
  373. class MockKey:
  374. alg = "mock_alg"
  375. version = "mock_version"
  376. signature = b"\x9a\x87$"
  377. @property
  378. def verify_key(self):
  379. return self
  380. def sign(self, message):
  381. return self
  382. def verify(self, message, sig):
  383. assert sig == b"\x9a\x87$"
  384. def encode(self):
  385. return b"<fake_encoded_key>"
  386. class MockClock:
  387. now = 1000
  388. def __init__(self):
  389. # list of lists of [absolute_time, callback, expired] in no particular
  390. # order
  391. self.timers = []
  392. self.loopers = []
  393. def time(self):
  394. return self.now
  395. def time_msec(self):
  396. return self.time() * 1000
  397. def call_later(self, delay, callback, *args, **kwargs):
  398. ctx = current_context()
  399. def wrapped_callback():
  400. set_current_context(ctx)
  401. callback(*args, **kwargs)
  402. t = [self.now + delay, wrapped_callback, False]
  403. self.timers.append(t)
  404. return t
  405. def looping_call(self, function, interval, *args, **kwargs):
  406. self.loopers.append([function, interval / 1000.0, self.now, args, kwargs])
  407. def cancel_call_later(self, timer, ignore_errs=False):
  408. if timer[2]:
  409. if not ignore_errs:
  410. raise Exception("Cannot cancel an expired timer")
  411. timer[2] = True
  412. self.timers = [t for t in self.timers if t != timer]
  413. # For unit testing
  414. def advance_time(self, secs):
  415. self.now += secs
  416. timers = self.timers
  417. self.timers = []
  418. for t in timers:
  419. time, callback, expired = t
  420. if expired:
  421. raise Exception("Timer already expired")
  422. if self.now >= time:
  423. t[2] = True
  424. callback()
  425. else:
  426. self.timers.append(t)
  427. for looped in self.loopers:
  428. func, interval, last, args, kwargs = looped
  429. if last + interval < self.now:
  430. func(*args, **kwargs)
  431. looped[2] = self.now
  432. def advance_time_msec(self, ms):
  433. self.advance_time(ms / 1000.0)
  434. def time_bound_deferred(self, d, *args, **kwargs):
  435. # We don't bother timing things out for now.
  436. return d
  437. async def create_room(hs, room_id: str, creator_id: str):
  438. """Creates and persist a creation event for the given room"""
  439. persistence_store = hs.get_storage().persistence
  440. store = hs.get_datastore()
  441. event_builder_factory = hs.get_event_builder_factory()
  442. event_creation_handler = hs.get_event_creation_handler()
  443. await store.store_room(
  444. room_id=room_id,
  445. room_creator_user_id=creator_id,
  446. is_public=False,
  447. room_version=RoomVersions.V1,
  448. )
  449. builder = event_builder_factory.for_room_version(
  450. RoomVersions.V1,
  451. {
  452. "type": EventTypes.Create,
  453. "state_key": "",
  454. "sender": creator_id,
  455. "room_id": room_id,
  456. "content": {},
  457. },
  458. )
  459. event, context = await event_creation_handler.create_new_client_event(builder)
  460. await persistence_store.persist_event(event, context)