utils.py 21 KB

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