utils.py 21 KB

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