utils.py 21 KB

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