utils.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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 inspect import getcallargs
  23. from mock import Mock, patch
  24. from six.moves.urllib import parse as urlparse
  25. from twisted.internet import defer, reactor
  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.homeserver import HomeServerConfig
  30. from synapse.federation.transport import server as federation_server
  31. from synapse.http.server import HttpServer
  32. from synapse.server import HomeServer
  33. from synapse.storage import DataStore
  34. from synapse.storage.engines import PostgresEngine, create_engine
  35. from synapse.storage.prepare_database import (
  36. _get_or_create_schema_state,
  37. _setup_new_database,
  38. prepare_database,
  39. )
  40. from synapse.util.logcontext import LoggingContext
  41. from synapse.util.ratelimitutils import FederationRateLimiter
  42. # set this to True to run the tests against postgres instead of sqlite.
  43. #
  44. # When running under postgres, we first create a base database with the name
  45. # POSTGRES_BASE_DB and update it to the current schema. Then, for each test case, we
  46. # create another unique database, using the base database as a template.
  47. USE_POSTGRES_FOR_TESTS = os.environ.get("SYNAPSE_POSTGRES", False)
  48. LEAVE_DB = os.environ.get("SYNAPSE_LEAVE_DB", False)
  49. POSTGRES_USER = os.environ.get("SYNAPSE_POSTGRES_USER", None)
  50. POSTGRES_HOST = os.environ.get("SYNAPSE_POSTGRES_HOST", None)
  51. POSTGRES_PASSWORD = os.environ.get("SYNAPSE_POSTGRES_PASSWORD", None)
  52. POSTGRES_BASE_DB = "_synapse_unit_tests_base_%s" % (os.getpid(),)
  53. # the dbname we will connect to in order to create the base database.
  54. POSTGRES_DBNAME_FOR_INITIAL_CREATE = "postgres"
  55. def setupdb():
  56. # If we're using PostgreSQL, set up the db once
  57. if USE_POSTGRES_FOR_TESTS:
  58. # create a PostgresEngine
  59. db_engine = create_engine({"name": "psycopg2", "args": {}})
  60. # connect to postgres to create the base database.
  61. db_conn = db_engine.module.connect(
  62. user=POSTGRES_USER, host=POSTGRES_HOST, password=POSTGRES_PASSWORD,
  63. dbname=POSTGRES_DBNAME_FOR_INITIAL_CREATE,
  64. )
  65. db_conn.autocommit = True
  66. cur = db_conn.cursor()
  67. cur.execute("DROP DATABASE IF EXISTS %s;" % (POSTGRES_BASE_DB,))
  68. cur.execute("CREATE DATABASE %s;" % (POSTGRES_BASE_DB,))
  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. cur = db_conn.cursor()
  79. _get_or_create_schema_state(cur, db_engine)
  80. _setup_new_database(cur, db_engine)
  81. db_conn.commit()
  82. cur.close()
  83. db_conn.close()
  84. def _cleanup():
  85. db_conn = db_engine.module.connect(
  86. user=POSTGRES_USER, host=POSTGRES_HOST, 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):
  96. """
  97. Create a reasonable test config.
  98. """
  99. config_dict = {
  100. "server_name": name,
  101. "media_store_path": "media",
  102. "uploads_path": "uploads",
  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. }
  107. config = HomeServerConfig()
  108. config.parse_config_dict(config_dict)
  109. # TODO: move this stuff into config_dict or get rid of it
  110. config.event_cache_size = 1
  111. config.enable_registration = True
  112. config.enable_registration_captcha = False
  113. config.macaroon_secret_key = "not even a little secret"
  114. config.expire_access_token = False
  115. config.trusted_third_party_id_servers = []
  116. config.room_invite_state_types = []
  117. config.password_providers = []
  118. config.worker_replication_url = ""
  119. config.worker_app = None
  120. config.email_enable_notifs = False
  121. config.block_non_admin_invites = False
  122. config.federation_domain_whitelist = None
  123. config.federation_rc_reject_limit = 10
  124. config.federation_rc_sleep_limit = 10
  125. config.federation_rc_sleep_delay = 100
  126. config.federation_rc_concurrent = 10
  127. config.filter_timeline_limit = 5000
  128. config.user_directory_search_all_users = False
  129. config.user_consent_server_notice_content = None
  130. config.block_events_without_consent_error = None
  131. config.user_consent_at_registration = False
  132. config.user_consent_policy_name = "Privacy Policy"
  133. config.media_storage_providers = []
  134. config.autocreate_auto_join_rooms = True
  135. config.auto_join_rooms = []
  136. config.limit_usage_by_mau = False
  137. config.hs_disabled = False
  138. config.hs_disabled_message = ""
  139. config.hs_disabled_limit_type = ""
  140. config.max_mau_value = 50
  141. config.mau_trial_days = 0
  142. config.mau_stats_only = False
  143. config.mau_limits_reserved_threepids = []
  144. config.admin_contact = None
  145. config.rc_messages_per_second = 10000
  146. config.rc_message_burst_count = 10000
  147. config.rc_registration.per_second = 10000
  148. config.rc_registration.burst_count = 10000
  149. config.rc_login_address.per_second = 10000
  150. config.rc_login_address.burst_count = 10000
  151. config.rc_login_account.per_second = 10000
  152. config.rc_login_account.burst_count = 10000
  153. config.rc_login_failed_attempts.per_second = 10000
  154. config.rc_login_failed_attempts.burst_count = 10000
  155. config.saml2_enabled = False
  156. config.public_baseurl = None
  157. config.default_identity_server = None
  158. config.key_refresh_interval = 24 * 60 * 60 * 1000
  159. config.old_signing_keys = {}
  160. config.tls_fingerprints = []
  161. config.use_frozen_dicts = False
  162. # we need a sane default_room_version, otherwise attempts to create rooms will
  163. # fail.
  164. config.default_room_version = "1"
  165. # disable user directory updates, because they get done in the
  166. # background, which upsets the test runner.
  167. config.update_user_directory = False
  168. return config
  169. class TestHomeServer(HomeServer):
  170. DATASTORE_CLASS = DataStore
  171. @defer.inlineCallbacks
  172. def setup_test_homeserver(
  173. cleanup_func,
  174. name="test",
  175. datastore=None,
  176. config=None,
  177. reactor=None,
  178. homeserverToUse=TestHomeServer,
  179. **kargs
  180. ):
  181. """
  182. Setup a homeserver suitable for running tests against. Keyword arguments
  183. are passed to the Homeserver constructor.
  184. If no datastore is supplied, one is created and given to the homeserver.
  185. Args:
  186. cleanup_func : The function used to register a cleanup routine for
  187. after the test.
  188. Calling this method directly is deprecated: you should instead derive from
  189. HomeserverTestCase.
  190. """
  191. if reactor is None:
  192. from twisted.internet import reactor
  193. if config is None:
  194. config = default_config(name)
  195. config.ldap_enabled = False
  196. if "clock" not in kargs:
  197. kargs["clock"] = MockClock()
  198. if USE_POSTGRES_FOR_TESTS:
  199. test_db = "synapse_test_%s" % uuid.uuid4().hex
  200. config.database_config = {
  201. "name": "psycopg2",
  202. "args": {
  203. "database": test_db,
  204. "host": POSTGRES_HOST,
  205. "password": POSTGRES_PASSWORD,
  206. "user": POSTGRES_USER,
  207. "cp_min": 1,
  208. "cp_max": 5,
  209. },
  210. }
  211. else:
  212. config.database_config = {
  213. "name": "sqlite3",
  214. "args": {"database": ":memory:", "cp_min": 1, "cp_max": 1},
  215. }
  216. db_engine = create_engine(config.database_config)
  217. # Create the database before we actually try and connect to it, based off
  218. # the template database we generate in setupdb()
  219. if datastore is None and isinstance(db_engine, PostgresEngine):
  220. db_conn = db_engine.module.connect(
  221. database=POSTGRES_BASE_DB,
  222. user=POSTGRES_USER,
  223. host=POSTGRES_HOST,
  224. password=POSTGRES_PASSWORD,
  225. )
  226. db_conn.autocommit = True
  227. cur = db_conn.cursor()
  228. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  229. cur.execute(
  230. "CREATE DATABASE %s WITH TEMPLATE %s;" % (test_db, POSTGRES_BASE_DB)
  231. )
  232. cur.close()
  233. db_conn.close()
  234. # we need to configure the connection pool to run the on_new_connection
  235. # function, so that we can test code that uses custom sqlite functions
  236. # (like rank).
  237. config.database_config["args"]["cp_openfun"] = db_engine.on_new_connection
  238. if datastore is None:
  239. hs = homeserverToUse(
  240. name,
  241. config=config,
  242. db_config=config.database_config,
  243. version_string="Synapse/tests",
  244. database_engine=db_engine,
  245. tls_server_context_factory=Mock(),
  246. tls_client_options_factory=Mock(),
  247. reactor=reactor,
  248. **kargs
  249. )
  250. # Prepare the DB on SQLite -- PostgreSQL is a copy of an already up to
  251. # date db
  252. if not isinstance(db_engine, PostgresEngine):
  253. db_conn = hs.get_db_conn()
  254. yield prepare_database(db_conn, db_engine, config)
  255. db_conn.commit()
  256. db_conn.close()
  257. else:
  258. # We need to do cleanup on PostgreSQL
  259. def cleanup():
  260. import psycopg2
  261. # Close all the db pools
  262. hs.get_db_pool().close()
  263. dropped = False
  264. # Drop the test database
  265. db_conn = db_engine.module.connect(
  266. database=POSTGRES_BASE_DB,
  267. user=POSTGRES_USER,
  268. host=POSTGRES_HOST,
  269. password=POSTGRES_PASSWORD,
  270. )
  271. db_conn.autocommit = True
  272. cur = db_conn.cursor()
  273. # Try a few times to drop the DB. Some things may hold on to the
  274. # database for a few more seconds due to flakiness, preventing
  275. # us from dropping it when the test is over. If we can't drop
  276. # it, warn and move on.
  277. for x in range(5):
  278. try:
  279. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  280. db_conn.commit()
  281. dropped = True
  282. except psycopg2.OperationalError as e:
  283. warnings.warn(
  284. "Couldn't drop old db: " + str(e), category=UserWarning
  285. )
  286. time.sleep(0.5)
  287. cur.close()
  288. db_conn.close()
  289. if not dropped:
  290. warnings.warn("Failed to drop old DB.", category=UserWarning)
  291. if not LEAVE_DB:
  292. # Register the cleanup hook
  293. cleanup_func(cleanup)
  294. hs.setup()
  295. if homeserverToUse.__name__ == "TestHomeServer":
  296. hs.setup_master()
  297. else:
  298. hs = homeserverToUse(
  299. name,
  300. db_pool=None,
  301. datastore=datastore,
  302. config=config,
  303. version_string="Synapse/tests",
  304. database_engine=db_engine,
  305. tls_server_context_factory=Mock(),
  306. tls_client_options_factory=Mock(),
  307. reactor=reactor,
  308. **kargs
  309. )
  310. # bcrypt is far too slow to be doing in unit tests
  311. # Need to let the HS build an auth handler and then mess with it
  312. # because AuthHandler's constructor requires the HS, so we can't make one
  313. # beforehand and pass it in to the HS's constructor (chicken / egg)
  314. hs.get_auth_handler().hash = lambda p: hashlib.md5(p.encode('utf8')).hexdigest()
  315. hs.get_auth_handler().validate_hash = (
  316. lambda p, h: hashlib.md5(p.encode('utf8')).hexdigest() == h
  317. )
  318. fed = kargs.get("resource_for_federation", None)
  319. if fed:
  320. register_federation_servlets(hs, fed)
  321. defer.returnValue(hs)
  322. def register_federation_servlets(hs, resource):
  323. federation_server.register_servlets(
  324. hs,
  325. resource=resource,
  326. authenticator=federation_server.Authenticator(hs),
  327. ratelimiter=FederationRateLimiter(
  328. hs.get_clock(),
  329. window_size=hs.config.federation_rc_window_size,
  330. sleep_limit=hs.config.federation_rc_sleep_limit,
  331. sleep_msec=hs.config.federation_rc_sleep_delay,
  332. reject_limit=hs.config.federation_rc_reject_limit,
  333. concurrent_requests=hs.config.federation_rc_concurrent,
  334. ),
  335. )
  336. def get_mock_call_args(pattern_func, mock_func):
  337. """ Return the arguments the mock function was called with interpreted
  338. by the pattern functions argument list.
  339. """
  340. invoked_args, invoked_kargs = mock_func.call_args
  341. return getcallargs(pattern_func, *invoked_args, **invoked_kargs)
  342. def mock_getRawHeaders(headers=None):
  343. headers = headers if headers is not None else {}
  344. def getRawHeaders(name, default=None):
  345. return headers.get(name, default)
  346. return getRawHeaders
  347. # This is a mock /resource/ not an entire server
  348. class MockHttpResource(HttpServer):
  349. def __init__(self, prefix=""):
  350. self.callbacks = [] # 3-tuple of method/pattern/function
  351. self.prefix = prefix
  352. def trigger_get(self, path):
  353. return self.trigger(b"GET", path, None)
  354. @patch('twisted.web.http.Request')
  355. @defer.inlineCallbacks
  356. def trigger(
  357. self, http_method, path, content, mock_request, federation_auth_origin=None
  358. ):
  359. """ Fire an HTTP event.
  360. Args:
  361. http_method : The HTTP method
  362. path : The HTTP path
  363. content : The HTTP body
  364. mock_request : Mocked request to pass to the event so it can get
  365. content.
  366. federation_auth_origin (bytes|None): domain to authenticate as, for federation
  367. Returns:
  368. A tuple of (code, response)
  369. Raises:
  370. KeyError If no event is found which will handle the path.
  371. """
  372. path = self.prefix + path
  373. # annoyingly we return a twisted http request which has chained calls
  374. # to get at the http content, hence mock it here.
  375. mock_content = Mock()
  376. config = {'read.return_value': content}
  377. mock_content.configure_mock(**config)
  378. mock_request.content = mock_content
  379. mock_request.method = http_method.encode('ascii')
  380. mock_request.uri = path.encode('ascii')
  381. mock_request.getClientIP.return_value = "-"
  382. headers = {}
  383. if federation_auth_origin is not None:
  384. headers[b"Authorization"] = [
  385. b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,)
  386. ]
  387. mock_request.requestHeaders.getRawHeaders = mock_getRawHeaders(headers)
  388. # return the right path if the event requires it
  389. mock_request.path = path
  390. # add in query params to the right place
  391. try:
  392. mock_request.args = urlparse.parse_qs(path.split('?')[1])
  393. mock_request.path = path.split('?')[0]
  394. path = mock_request.path
  395. except Exception:
  396. pass
  397. if isinstance(path, bytes):
  398. path = path.decode('utf8')
  399. for (method, pattern, func) in self.callbacks:
  400. if http_method != method:
  401. continue
  402. matcher = pattern.match(path)
  403. if matcher:
  404. try:
  405. args = [urlparse.unquote(u) for u in matcher.groups()]
  406. (code, response) = yield func(mock_request, *args)
  407. defer.returnValue((code, response))
  408. except CodeMessageException as e:
  409. defer.returnValue((e.code, cs_error(e.msg, code=e.errcode)))
  410. raise KeyError("No event can handle %s" % path)
  411. def register_paths(self, method, path_patterns, callback):
  412. for path_pattern in path_patterns:
  413. self.callbacks.append((method, path_pattern, callback))
  414. class MockKey(object):
  415. alg = "mock_alg"
  416. version = "mock_version"
  417. signature = b"\x9a\x87$"
  418. @property
  419. def verify_key(self):
  420. return self
  421. def sign(self, message):
  422. return self
  423. def verify(self, message, sig):
  424. assert sig == b"\x9a\x87$"
  425. def encode(self):
  426. return b"<fake_encoded_key>"
  427. class MockClock(object):
  428. now = 1000
  429. def __init__(self):
  430. # list of lists of [absolute_time, callback, expired] in no particular
  431. # order
  432. self.timers = []
  433. self.loopers = []
  434. def time(self):
  435. return self.now
  436. def time_msec(self):
  437. return self.time() * 1000
  438. def call_later(self, delay, callback, *args, **kwargs):
  439. current_context = LoggingContext.current_context()
  440. def wrapped_callback():
  441. LoggingContext.thread_local.current_context = current_context
  442. callback(*args, **kwargs)
  443. t = [self.now + delay, wrapped_callback, False]
  444. self.timers.append(t)
  445. return t
  446. def looping_call(self, function, interval):
  447. self.loopers.append([function, interval / 1000.0, self.now])
  448. def cancel_call_later(self, timer, ignore_errs=False):
  449. if timer[2]:
  450. if not ignore_errs:
  451. raise Exception("Cannot cancel an expired timer")
  452. timer[2] = True
  453. self.timers = [t for t in self.timers if t != timer]
  454. # For unit testing
  455. def advance_time(self, secs):
  456. self.now += secs
  457. timers = self.timers
  458. self.timers = []
  459. for t in timers:
  460. time, callback, expired = t
  461. if expired:
  462. raise Exception("Timer already expired")
  463. if self.now >= time:
  464. t[2] = True
  465. callback()
  466. else:
  467. self.timers.append(t)
  468. for looped in self.loopers:
  469. func, interval, last = looped
  470. if last + interval < self.now:
  471. func()
  472. looped[2] = self.now
  473. def advance_time_msec(self, ms):
  474. self.advance_time(ms / 1000.0)
  475. def time_bound_deferred(self, d, *args, **kwargs):
  476. # We don't bother timing things out for now.
  477. return d
  478. def _format_call(args, kwargs):
  479. return ", ".join(
  480. ["%r" % (a) for a in args] + ["%s=%r" % (k, v) for k, v in kwargs.items()]
  481. )
  482. class DeferredMockCallable(object):
  483. """A callable instance that stores a set of pending call expectations and
  484. return values for them. It allows a unit test to assert that the given set
  485. of function calls are eventually made, by awaiting on them to be called.
  486. """
  487. def __init__(self):
  488. self.expectations = []
  489. self.calls = []
  490. def __call__(self, *args, **kwargs):
  491. self.calls.append((args, kwargs))
  492. if not self.expectations:
  493. raise ValueError(
  494. "%r has no pending calls to handle call(%s)"
  495. % (self, _format_call(args, kwargs))
  496. )
  497. for (call, result, d) in self.expectations:
  498. if args == call[1] and kwargs == call[2]:
  499. d.callback(None)
  500. return result
  501. failure = AssertionError(
  502. "Was not expecting call(%s)" % (_format_call(args, kwargs))
  503. )
  504. for _, _, d in self.expectations:
  505. try:
  506. d.errback(failure)
  507. except Exception:
  508. pass
  509. raise failure
  510. def expect_call_and_return(self, call, result):
  511. self.expectations.append((call, result, defer.Deferred()))
  512. @defer.inlineCallbacks
  513. def await_calls(self, timeout=1000):
  514. deferred = defer.DeferredList(
  515. [d for _, _, d in self.expectations], fireOnOneErrback=True
  516. )
  517. timer = reactor.callLater(
  518. timeout / 1000,
  519. deferred.errback,
  520. AssertionError(
  521. "%d pending calls left: %s"
  522. % (
  523. len([e for e in self.expectations if not e[2].called]),
  524. [e for e in self.expectations if not e[2].called],
  525. )
  526. ),
  527. )
  528. yield deferred
  529. timer.cancel()
  530. self.calls = []
  531. def assert_had_no_calls(self):
  532. if self.calls:
  533. calls = self.calls
  534. self.calls = []
  535. raise AssertionError(
  536. "Expected not to received any calls, got:\n"
  537. + "\n".join(["call(%s)" % _format_call(c[0], c[1]) for c in calls])
  538. )
  539. @defer.inlineCallbacks
  540. def create_room(hs, room_id, creator_id):
  541. """Creates and persist a creation event for the given room
  542. Args:
  543. hs
  544. room_id (str)
  545. creator_id (str)
  546. """
  547. store = hs.get_datastore()
  548. event_builder_factory = hs.get_event_builder_factory()
  549. event_creation_handler = hs.get_event_creation_handler()
  550. builder = event_builder_factory.for_room_version(
  551. RoomVersions.V1,
  552. {
  553. "type": EventTypes.Create,
  554. "state_key": "",
  555. "sender": creator_id,
  556. "room_id": room_id,
  557. "content": {},
  558. },
  559. )
  560. event, context = yield event_creation_handler.create_new_client_event(builder)
  561. yield store.persist_event(event, context)