utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. "uploads_path": "uploads",
  104. # the test signing key is just an arbitrary ed25519 key to keep the config
  105. # parser happy
  106. "signing_key": "ed25519 a_lPym qvioDNmfExFBRPgdTU+wtFYKq4JfwFRv7sYVgWvmgJg",
  107. "event_cache_size": 1,
  108. "enable_registration": True,
  109. "enable_registration_captcha": False,
  110. "macaroon_secret_key": "not even a little secret",
  111. "trusted_third_party_id_servers": [],
  112. "room_invite_state_types": [],
  113. "password_providers": [],
  114. "worker_replication_url": "",
  115. "worker_app": None,
  116. "block_non_admin_invites": False,
  117. "federation_domain_whitelist": None,
  118. "filter_timeline_limit": 5000,
  119. "user_directory_search_all_users": False,
  120. "user_consent_server_notice_content": None,
  121. "block_events_without_consent_error": None,
  122. "user_consent_at_registration": False,
  123. "user_consent_policy_name": "Privacy Policy",
  124. "media_storage_providers": [],
  125. "autocreate_auto_join_rooms": True,
  126. "auto_join_rooms": [],
  127. "limit_usage_by_mau": False,
  128. "hs_disabled": False,
  129. "hs_disabled_message": "",
  130. "max_mau_value": 50,
  131. "mau_trial_days": 0,
  132. "mau_stats_only": False,
  133. "mau_limits_reserved_threepids": [],
  134. "admin_contact": None,
  135. "rc_message": {"per_second": 10000, "burst_count": 10000},
  136. "rc_registration": {"per_second": 10000, "burst_count": 10000},
  137. "rc_login": {
  138. "address": {"per_second": 10000, "burst_count": 10000},
  139. "account": {"per_second": 10000, "burst_count": 10000},
  140. "failed_attempts": {"per_second": 10000, "burst_count": 10000},
  141. },
  142. "rc_joins": {
  143. "local": {"per_second": 10000, "burst_count": 10000},
  144. "remote": {"per_second": 10000, "burst_count": 10000},
  145. },
  146. "rc_3pid_validation": {"per_second": 10000, "burst_count": 10000},
  147. "saml2_enabled": False,
  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, config=config, version_string="Synapse/tests", reactor=reactor,
  234. )
  235. # Install @cache_in_self attributes
  236. for key, val in kwargs.items():
  237. setattr(hs, "_" + key, val)
  238. # Mock TLS
  239. hs.tls_server_context_factory = Mock()
  240. hs.tls_client_options_factory = Mock()
  241. hs.setup()
  242. if homeserver_to_use == TestHomeServer:
  243. hs.setup_background_tasks()
  244. if isinstance(db_engine, PostgresEngine):
  245. database = hs.get_datastores().databases[0]
  246. # We need to do cleanup on PostgreSQL
  247. def cleanup():
  248. import psycopg2
  249. # Close all the db pools
  250. database._db_pool.close()
  251. dropped = False
  252. # Drop the test database
  253. db_conn = db_engine.module.connect(
  254. database=POSTGRES_BASE_DB,
  255. user=POSTGRES_USER,
  256. host=POSTGRES_HOST,
  257. password=POSTGRES_PASSWORD,
  258. )
  259. db_conn.autocommit = True
  260. cur = db_conn.cursor()
  261. # Try a few times to drop the DB. Some things may hold on to the
  262. # database for a few more seconds due to flakiness, preventing
  263. # us from dropping it when the test is over. If we can't drop
  264. # it, warn and move on.
  265. for x in range(5):
  266. try:
  267. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  268. db_conn.commit()
  269. dropped = True
  270. except psycopg2.OperationalError as e:
  271. warnings.warn(
  272. "Couldn't drop old db: " + str(e), category=UserWarning
  273. )
  274. time.sleep(0.5)
  275. cur.close()
  276. db_conn.close()
  277. if not dropped:
  278. warnings.warn("Failed to drop old DB.", category=UserWarning)
  279. if not LEAVE_DB:
  280. # Register the cleanup hook
  281. cleanup_func(cleanup)
  282. # bcrypt is far too slow to be doing in unit tests
  283. # Need to let the HS build an auth handler and then mess with it
  284. # because AuthHandler's constructor requires the HS, so we can't make one
  285. # beforehand and pass it in to the HS's constructor (chicken / egg)
  286. async def hash(p):
  287. return hashlib.md5(p.encode("utf8")).hexdigest()
  288. hs.get_auth_handler().hash = hash
  289. async def validate_hash(p, h):
  290. return hashlib.md5(p.encode("utf8")).hexdigest() == h
  291. hs.get_auth_handler().validate_hash = validate_hash
  292. return hs
  293. def mock_getRawHeaders(headers=None):
  294. headers = headers if headers is not None else {}
  295. def getRawHeaders(name, default=None):
  296. return headers.get(name, default)
  297. return getRawHeaders
  298. # This is a mock /resource/ not an entire server
  299. class MockHttpResource:
  300. def __init__(self, prefix=""):
  301. self.callbacks = [] # 3-tuple of method/pattern/function
  302. self.prefix = prefix
  303. def trigger_get(self, path):
  304. return self.trigger(b"GET", path, None)
  305. @patch("twisted.web.http.Request")
  306. @defer.inlineCallbacks
  307. def trigger(
  308. self, http_method, path, content, mock_request, federation_auth_origin=None
  309. ):
  310. """ Fire an HTTP event.
  311. Args:
  312. http_method : The HTTP method
  313. path : The HTTP path
  314. content : The HTTP body
  315. mock_request : Mocked request to pass to the event so it can get
  316. content.
  317. federation_auth_origin (bytes|None): domain to authenticate as, for federation
  318. Returns:
  319. A tuple of (code, response)
  320. Raises:
  321. KeyError If no event is found which will handle the path.
  322. """
  323. path = self.prefix + path
  324. # annoyingly we return a twisted http request which has chained calls
  325. # to get at the http content, hence mock it here.
  326. mock_content = Mock()
  327. config = {"read.return_value": content}
  328. mock_content.configure_mock(**config)
  329. mock_request.content = mock_content
  330. mock_request.method = http_method.encode("ascii")
  331. mock_request.uri = path.encode("ascii")
  332. mock_request.getClientIP.return_value = "-"
  333. headers = {}
  334. if federation_auth_origin is not None:
  335. headers[b"Authorization"] = [
  336. b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,)
  337. ]
  338. mock_request.requestHeaders.getRawHeaders = mock_getRawHeaders(headers)
  339. # return the right path if the event requires it
  340. mock_request.path = path
  341. # add in query params to the right place
  342. try:
  343. mock_request.args = urlparse.parse_qs(path.split("?")[1])
  344. mock_request.path = path.split("?")[0]
  345. path = mock_request.path
  346. except Exception:
  347. pass
  348. if isinstance(path, bytes):
  349. path = path.decode("utf8")
  350. for (method, pattern, func) in self.callbacks:
  351. if http_method != method:
  352. continue
  353. matcher = pattern.match(path)
  354. if matcher:
  355. try:
  356. args = [urlparse.unquote(u) for u in matcher.groups()]
  357. (code, response) = yield defer.ensureDeferred(
  358. func(mock_request, *args)
  359. )
  360. return code, response
  361. except CodeMessageException as e:
  362. return (e.code, cs_error(e.msg, code=e.errcode))
  363. raise KeyError("No event can handle %s" % path)
  364. def register_paths(self, method, path_patterns, callback, servlet_name):
  365. for path_pattern in path_patterns:
  366. self.callbacks.append((method, path_pattern, callback))
  367. class MockKey:
  368. alg = "mock_alg"
  369. version = "mock_version"
  370. signature = b"\x9a\x87$"
  371. @property
  372. def verify_key(self):
  373. return self
  374. def sign(self, message):
  375. return self
  376. def verify(self, message, sig):
  377. assert sig == b"\x9a\x87$"
  378. def encode(self):
  379. return b"<fake_encoded_key>"
  380. class MockClock:
  381. now = 1000
  382. def __init__(self):
  383. # list of lists of [absolute_time, callback, expired] in no particular
  384. # order
  385. self.timers = []
  386. self.loopers = []
  387. def time(self):
  388. return self.now
  389. def time_msec(self):
  390. return self.time() * 1000
  391. def call_later(self, delay, callback, *args, **kwargs):
  392. ctx = current_context()
  393. def wrapped_callback():
  394. set_current_context(ctx)
  395. callback(*args, **kwargs)
  396. t = [self.now + delay, wrapped_callback, False]
  397. self.timers.append(t)
  398. return t
  399. def looping_call(self, function, interval, *args, **kwargs):
  400. self.loopers.append([function, interval / 1000.0, self.now, args, kwargs])
  401. def cancel_call_later(self, timer, ignore_errs=False):
  402. if timer[2]:
  403. if not ignore_errs:
  404. raise Exception("Cannot cancel an expired timer")
  405. timer[2] = True
  406. self.timers = [t for t in self.timers if t != timer]
  407. # For unit testing
  408. def advance_time(self, secs):
  409. self.now += secs
  410. timers = self.timers
  411. self.timers = []
  412. for t in timers:
  413. time, callback, expired = t
  414. if expired:
  415. raise Exception("Timer already expired")
  416. if self.now >= time:
  417. t[2] = True
  418. callback()
  419. else:
  420. self.timers.append(t)
  421. for looped in self.loopers:
  422. func, interval, last, args, kwargs = looped
  423. if last + interval < self.now:
  424. func(*args, **kwargs)
  425. looped[2] = self.now
  426. def advance_time_msec(self, ms):
  427. self.advance_time(ms / 1000.0)
  428. def time_bound_deferred(self, d, *args, **kwargs):
  429. # We don't bother timing things out for now.
  430. return d
  431. async def create_room(hs, room_id: str, creator_id: str):
  432. """Creates and persist a creation event for the given room
  433. """
  434. persistence_store = hs.get_storage().persistence
  435. store = hs.get_datastore()
  436. event_builder_factory = hs.get_event_builder_factory()
  437. event_creation_handler = hs.get_event_creation_handler()
  438. await store.store_room(
  439. room_id=room_id,
  440. room_creator_user_id=creator_id,
  441. is_public=False,
  442. room_version=RoomVersions.V1,
  443. )
  444. builder = event_builder_factory.for_room_version(
  445. RoomVersions.V1,
  446. {
  447. "type": EventTypes.Create,
  448. "state_key": "",
  449. "sender": creator_id,
  450. "room_id": room_id,
  451. "content": {},
  452. },
  453. )
  454. event, context = await event_creation_handler.create_new_client_event(builder)
  455. await persistence_store.persist_event(event, context)