utils.py 18 KB

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