utils.py 21 KB

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