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