utils.py 18 KB

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