unittest.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector
  3. # Copyright 2019 Matrix.org Federation C.I.C
  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 functools
  17. import gc
  18. import hashlib
  19. import hmac
  20. import json
  21. import logging
  22. import secrets
  23. import time
  24. from typing import (
  25. Any,
  26. Awaitable,
  27. Callable,
  28. ClassVar,
  29. Dict,
  30. Generic,
  31. Iterable,
  32. List,
  33. Mapping,
  34. NoReturn,
  35. Optional,
  36. Tuple,
  37. Type,
  38. TypeVar,
  39. Union,
  40. )
  41. from unittest.mock import Mock, patch
  42. import canonicaljson
  43. import signedjson.key
  44. import unpaddedbase64
  45. from typing_extensions import Concatenate, ParamSpec, Protocol
  46. from twisted.internet.defer import Deferred, ensureDeferred
  47. from twisted.python.failure import Failure
  48. from twisted.python.threadpool import ThreadPool
  49. from twisted.test.proto_helpers import MemoryReactor, MemoryReactorClock
  50. from twisted.trial import unittest
  51. from twisted.web.resource import Resource
  52. from twisted.web.server import Request
  53. from synapse import events
  54. from synapse.api.constants import EventTypes
  55. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
  56. from synapse.config._base import Config, RootConfig
  57. from synapse.config.homeserver import HomeServerConfig
  58. from synapse.config.server import DEFAULT_ROOM_VERSION
  59. from synapse.crypto.event_signing import add_hashes_and_signatures
  60. from synapse.federation.transport.server import TransportLayerServer
  61. from synapse.http.server import JsonResource, OptionsResource
  62. from synapse.http.site import SynapseRequest, SynapseSite
  63. from synapse.logging.context import (
  64. SENTINEL_CONTEXT,
  65. LoggingContext,
  66. current_context,
  67. set_current_context,
  68. )
  69. from synapse.rest import RegisterServletsFunc
  70. from synapse.server import HomeServer
  71. from synapse.storage.keys import FetchKeyResult
  72. from synapse.types import JsonDict, Requester, UserID, create_requester
  73. from synapse.util import Clock
  74. from synapse.util.httpresourcetree import create_resource_tree
  75. from tests.server import (
  76. CustomHeaderType,
  77. FakeChannel,
  78. ThreadedMemoryReactorClock,
  79. get_clock,
  80. make_request,
  81. setup_test_homeserver,
  82. )
  83. from tests.test_utils import event_injection, setup_awaitable_errors
  84. from tests.test_utils.logging_setup import setup_logging
  85. from tests.utils import checked_cast, default_config, setupdb
  86. setupdb()
  87. setup_logging()
  88. TV = TypeVar("TV")
  89. _ExcType = TypeVar("_ExcType", bound=BaseException, covariant=True)
  90. P = ParamSpec("P")
  91. R = TypeVar("R")
  92. S = TypeVar("S")
  93. class _TypedFailure(Generic[_ExcType], Protocol):
  94. """Extension to twisted.Failure, where the 'value' has a certain type."""
  95. @property
  96. def value(self) -> _ExcType:
  97. ...
  98. def around(target: TV) -> Callable[[Callable[Concatenate[S, P], R]], None]:
  99. """A CLOS-style 'around' modifier, which wraps the original method of the
  100. given instance with another piece of code.
  101. @around(self)
  102. def method_name(orig, *args, **kwargs):
  103. return orig(*args, **kwargs)
  104. """
  105. def _around(code: Callable[Concatenate[S, P], R]) -> None:
  106. name = code.__name__
  107. orig = getattr(target, name)
  108. def new(*args: P.args, **kwargs: P.kwargs) -> R:
  109. return code(orig, *args, **kwargs)
  110. setattr(target, name, new)
  111. return _around
  112. _TConfig = TypeVar("_TConfig", Config, RootConfig)
  113. def deepcopy_config(config: _TConfig) -> _TConfig:
  114. new_config: _TConfig
  115. if isinstance(config, RootConfig):
  116. new_config = config.__class__(config.config_files) # type: ignore[arg-type]
  117. else:
  118. new_config = config.__class__(config.root)
  119. for attr_name in config.__dict__:
  120. if attr_name.startswith("__") or attr_name == "root":
  121. continue
  122. attr = getattr(config, attr_name)
  123. if isinstance(attr, Config):
  124. new_attr = deepcopy_config(attr)
  125. else:
  126. new_attr = attr
  127. setattr(new_config, attr_name, new_attr)
  128. return new_config
  129. @functools.lru_cache(maxsize=8)
  130. def _parse_config_dict(config: str) -> RootConfig:
  131. config_obj = HomeServerConfig()
  132. config_obj.parse_config_dict(json.loads(config), "", "")
  133. return config_obj
  134. def make_homeserver_config_obj(config: Dict[str, Any]) -> RootConfig:
  135. """Creates a :class:`HomeServerConfig` instance with the given configuration dict.
  136. This is equivalent to::
  137. config_obj = HomeServerConfig()
  138. config_obj.parse_config_dict(config, "", "")
  139. but it keeps a cache of `HomeServerConfig` instances and deepcopies them as needed,
  140. to avoid validating the whole configuration every time.
  141. """
  142. config_obj = _parse_config_dict(json.dumps(config, sort_keys=True))
  143. return deepcopy_config(config_obj)
  144. class TestCase(unittest.TestCase):
  145. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  146. attributes on both itself and its individual test methods, to override the
  147. root logger's logging level while that test (case|method) runs."""
  148. def __init__(self, methodName: str):
  149. super().__init__(methodName)
  150. method = getattr(self, methodName)
  151. level = getattr(method, "loglevel", getattr(self, "loglevel", None))
  152. @around(self)
  153. def setUp(orig: Callable[[], R]) -> R:
  154. # if we're not starting in the sentinel logcontext, then to be honest
  155. # all future bets are off.
  156. if current_context():
  157. self.fail(
  158. "Test starting with non-sentinel logging context %s"
  159. % (current_context(),)
  160. )
  161. # Disable GC for duration of test. See below for why.
  162. gc.disable()
  163. old_level = logging.getLogger().level
  164. if level is not None and old_level != level:
  165. @around(self)
  166. def tearDown(orig: Callable[[], R]) -> R:
  167. ret = orig()
  168. logging.getLogger().setLevel(old_level)
  169. return ret
  170. logging.getLogger().setLevel(level)
  171. # Trial messes with the warnings configuration, thus this has to be
  172. # done in the context of an individual TestCase.
  173. self.addCleanup(setup_awaitable_errors())
  174. return orig()
  175. # We want to force a GC to workaround problems with deferreds leaking
  176. # logcontexts when they are GCed (see the logcontext docs).
  177. #
  178. # The easiest way to do this would be to do a full GC after each test
  179. # run, but that is very expensive. Instead, we disable GC (above) for
  180. # the duration of the test and only run a gen-0 GC, which is a lot
  181. # quicker. This doesn't clean up everything, since the TestCase
  182. # instance still holds references to objects created during the test,
  183. # such as HomeServers, so we do a full GC every so often.
  184. @around(self)
  185. def tearDown(orig: Callable[[], R]) -> R:
  186. ret = orig()
  187. gc.collect(0)
  188. # Run a full GC every 50 gen-0 GCs.
  189. gen0_stats = gc.get_stats()[0]
  190. gen0_collections = gen0_stats["collections"]
  191. if gen0_collections % 50 == 0:
  192. gc.collect()
  193. gc.enable()
  194. set_current_context(SENTINEL_CONTEXT)
  195. return ret
  196. def assertObjectHasAttributes(self, attrs: Dict[str, object], obj: object) -> None:
  197. """Asserts that the given object has each of the attributes given, and
  198. that the value of each matches according to assertEqual."""
  199. for key in attrs.keys():
  200. if not hasattr(obj, key):
  201. raise AssertionError("Expected obj to have a '.%s'" % key)
  202. try:
  203. self.assertEqual(attrs[key], getattr(obj, key))
  204. except AssertionError as e:
  205. raise (type(e))(f"Assert error for '.{key}':") from e
  206. def assert_dict(self, required: Mapping, actual: Mapping) -> None:
  207. """Does a partial assert of a dict.
  208. Args:
  209. required: The keys and value which MUST be in 'actual'.
  210. actual: The test result. Extra keys will not be checked.
  211. """
  212. for key in required:
  213. self.assertEqual(
  214. required[key], actual[key], msg="%s mismatch. %s" % (key, actual)
  215. )
  216. def DEBUG(target: TV) -> TV:
  217. """A decorator to set the .loglevel attribute to logging.DEBUG.
  218. Can apply to either a TestCase or an individual test method."""
  219. target.loglevel = logging.DEBUG # type: ignore[attr-defined]
  220. return target
  221. def INFO(target: TV) -> TV:
  222. """A decorator to set the .loglevel attribute to logging.INFO.
  223. Can apply to either a TestCase or an individual test method."""
  224. target.loglevel = logging.INFO # type: ignore[attr-defined]
  225. return target
  226. def logcontext_clean(target: TV) -> TV:
  227. """A decorator which marks the TestCase or method as 'logcontext_clean'
  228. ... ie, any logcontext errors should cause a test failure
  229. """
  230. def logcontext_error(msg: str) -> NoReturn:
  231. raise AssertionError("logcontext error: %s" % (msg))
  232. patcher = patch("synapse.logging.context.logcontext_error", new=logcontext_error)
  233. return patcher(target) # type: ignore[call-overload]
  234. class HomeserverTestCase(TestCase):
  235. """
  236. A base TestCase that reduces boilerplate for HomeServer-using test cases.
  237. Defines a setUp method which creates a mock reactor, and instantiates a homeserver
  238. running on that reactor.
  239. There are various hooks for modifying the way that the homeserver is instantiated:
  240. * override make_homeserver, for example by making it pass different parameters into
  241. setup_test_homeserver.
  242. * override default_config, to return a modified configuration dictionary for use
  243. by setup_test_homeserver.
  244. * On a per-test basis, you can use the @override_config decorator to give a
  245. dictionary containing additional configuration settings to be added to the basic
  246. config dict.
  247. Attributes:
  248. servlets: List of servlet registration function.
  249. user_id (str): The user ID to assume if auth is hijacked.
  250. hijack_auth: Whether to hijack auth to return the user specified
  251. in user_id.
  252. """
  253. hijack_auth: ClassVar[bool] = True
  254. needs_threadpool: ClassVar[bool] = False
  255. servlets: ClassVar[List[RegisterServletsFunc]] = []
  256. def __init__(self, methodName: str):
  257. super().__init__(methodName)
  258. # see if we have any additional config for this test
  259. method = getattr(self, methodName)
  260. self._extra_config = getattr(method, "_extra_config", None)
  261. def setUp(self) -> None:
  262. """
  263. Set up the TestCase by calling the homeserver constructor, optionally
  264. hijacking the authentication system to return a fixed user, and then
  265. calling the prepare function.
  266. """
  267. self.reactor, self.clock = get_clock()
  268. self._hs_args = {"clock": self.clock, "reactor": self.reactor}
  269. self.hs = self.make_homeserver(self.reactor, self.clock)
  270. # Honour the `use_frozen_dicts` config option. We have to do this
  271. # manually because this is taken care of in the app `start` code, which
  272. # we don't run. Plus we want to reset it on tearDown.
  273. events.USE_FROZEN_DICTS = self.hs.config.server.use_frozen_dicts
  274. if self.hs is None:
  275. raise Exception("No homeserver returned from make_homeserver.")
  276. if not isinstance(self.hs, HomeServer):
  277. raise Exception("A homeserver wasn't returned, but %r" % (self.hs,))
  278. # create the root resource, and a site to wrap it.
  279. self.resource = self.create_test_resource()
  280. self.site = SynapseSite(
  281. logger_name="synapse.access.http.fake",
  282. site_tag=self.hs.config.server.server_name,
  283. config=self.hs.config.server.listeners[0],
  284. resource=self.resource,
  285. server_version_string="1",
  286. max_request_body_size=4096,
  287. reactor=self.reactor,
  288. hs=self.hs,
  289. )
  290. from tests.rest.client.utils import RestHelper
  291. self.helper = RestHelper(
  292. self.hs,
  293. checked_cast(MemoryReactorClock, self.hs.get_reactor()),
  294. self.site,
  295. getattr(self, "user_id", None),
  296. )
  297. if hasattr(self, "user_id"):
  298. if self.hijack_auth:
  299. assert self.helper.auth_user_id is not None
  300. token = "some_fake_token"
  301. # We need a valid token ID to satisfy foreign key constraints.
  302. token_id = self.get_success(
  303. self.hs.get_datastores().main.add_access_token_to_user(
  304. self.helper.auth_user_id,
  305. token,
  306. None,
  307. None,
  308. )
  309. )
  310. # This has to be a function and not just a Mock, because
  311. # `self.helper.auth_user_id` is temporarily reassigned in some tests
  312. async def get_requester(*args: Any, **kwargs: Any) -> Requester:
  313. assert self.helper.auth_user_id is not None
  314. return create_requester(
  315. user_id=UserID.from_string(self.helper.auth_user_id),
  316. access_token_id=token_id,
  317. )
  318. # Type ignore: mypy doesn't like us assigning to methods.
  319. self.hs.get_auth().get_user_by_req = get_requester # type: ignore[method-assign]
  320. self.hs.get_auth().get_user_by_access_token = get_requester # type: ignore[method-assign]
  321. self.hs.get_auth().get_access_token_from_request = Mock(return_value=token) # type: ignore[method-assign]
  322. if self.needs_threadpool:
  323. self.reactor.threadpool = ThreadPool() # type: ignore[assignment]
  324. self.addCleanup(self.reactor.threadpool.stop)
  325. self.reactor.threadpool.start()
  326. if hasattr(self, "prepare"):
  327. self.prepare(self.reactor, self.clock, self.hs)
  328. def tearDown(self) -> None:
  329. # Reset to not use frozen dicts.
  330. events.USE_FROZEN_DICTS = False
  331. def wait_on_thread(self, deferred: Deferred, timeout: int = 10) -> None:
  332. """
  333. Wait until a Deferred is done, where it's waiting on a real thread.
  334. """
  335. start_time = time.time()
  336. while not deferred.called:
  337. if start_time + timeout < time.time():
  338. raise ValueError("Timed out waiting for threadpool")
  339. self.reactor.advance(0.01)
  340. time.sleep(0.01)
  341. def wait_for_background_updates(self) -> None:
  342. """Block until all background database updates have completed."""
  343. store = self.hs.get_datastores().main
  344. while not self.get_success(
  345. store.db_pool.updates.has_completed_background_updates()
  346. ):
  347. self.get_success(
  348. store.db_pool.updates.do_next_background_update(False), by=0.1
  349. )
  350. def make_homeserver(
  351. self, reactor: ThreadedMemoryReactorClock, clock: Clock
  352. ) -> HomeServer:
  353. """
  354. Make and return a homeserver.
  355. Args:
  356. reactor: A Twisted Reactor, or something that pretends to be one.
  357. clock: The Clock, associated with the reactor.
  358. Returns:
  359. A homeserver suitable for testing.
  360. Function to be overridden in subclasses.
  361. """
  362. hs = self.setup_test_homeserver()
  363. return hs
  364. def create_test_resource(self) -> Resource:
  365. """
  366. Create a the root resource for the test server.
  367. The default calls `self.create_resource_dict` and builds the resultant dict
  368. into a tree.
  369. """
  370. root_resource = OptionsResource()
  371. create_resource_tree(self.create_resource_dict(), root_resource)
  372. return root_resource
  373. def create_resource_dict(self) -> Dict[str, Resource]:
  374. """Create a resource tree for the test server
  375. A resource tree is a mapping from path to twisted.web.resource.
  376. The default implementation creates a JsonResource and calls each function in
  377. `servlets` to register servlets against it.
  378. """
  379. servlet_resource = JsonResource(self.hs)
  380. for servlet in self.servlets:
  381. servlet(self.hs, servlet_resource)
  382. return {
  383. "/_matrix/client": servlet_resource,
  384. "/_synapse/admin": servlet_resource,
  385. }
  386. def default_config(self) -> JsonDict:
  387. """
  388. Get a default HomeServer config dict.
  389. """
  390. config = default_config("test")
  391. # apply any additional config which was specified via the override_config
  392. # decorator.
  393. if self._extra_config is not None:
  394. config.update(self._extra_config)
  395. return config
  396. def prepare(
  397. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  398. ) -> None:
  399. """
  400. Prepare for the test. This involves things like mocking out parts of
  401. the homeserver, or building test data common across the whole test
  402. suite.
  403. Args:
  404. reactor: A Twisted Reactor, or something that pretends to be one.
  405. clock: The Clock, associated with the reactor.
  406. homeserver: The HomeServer to test against.
  407. Function to optionally be overridden in subclasses.
  408. """
  409. def make_request(
  410. self,
  411. method: Union[bytes, str],
  412. path: Union[bytes, str],
  413. content: Union[bytes, str, JsonDict] = b"",
  414. access_token: Optional[str] = None,
  415. request: Type[Request] = SynapseRequest,
  416. shorthand: bool = True,
  417. federation_auth_origin: Optional[bytes] = None,
  418. content_is_form: bool = False,
  419. await_result: bool = True,
  420. custom_headers: Optional[Iterable[CustomHeaderType]] = None,
  421. client_ip: str = "127.0.0.1",
  422. ) -> FakeChannel:
  423. """
  424. Create a SynapseRequest at the path using the method and containing the
  425. given content.
  426. Args:
  427. method: The HTTP request method ("verb").
  428. path: The HTTP path, suitably URL encoded (e.g. escaped UTF-8 & spaces
  429. and such). content (bytes or dict): The body of the request.
  430. JSON-encoded, if a dict.
  431. shorthand: Whether to try and be helpful and prefix the given URL
  432. with the usual REST API path, if it doesn't contain it.
  433. federation_auth_origin: if set to not-None, we will add a fake
  434. Authorization header pretenting to be the given server name.
  435. content_is_form: Whether the content is URL encoded form data. Adds the
  436. 'Content-Type': 'application/x-www-form-urlencoded' header.
  437. await_result: whether to wait for the request to complete rendering. If
  438. true (the default), will pump the test reactor until the the renderer
  439. tells the channel the request is finished.
  440. custom_headers: (name, value) pairs to add as request headers
  441. client_ip: The IP to use as the requesting IP. Useful for testing
  442. ratelimiting.
  443. Returns:
  444. The FakeChannel object which stores the result of the request.
  445. """
  446. return make_request(
  447. self.reactor,
  448. self.site,
  449. method,
  450. path,
  451. content,
  452. access_token,
  453. request,
  454. shorthand,
  455. federation_auth_origin,
  456. content_is_form,
  457. await_result,
  458. custom_headers,
  459. client_ip,
  460. )
  461. def setup_test_homeserver(
  462. self, name: Optional[str] = None, **kwargs: Any
  463. ) -> HomeServer:
  464. """
  465. Set up the test homeserver, meant to be called by the overridable
  466. make_homeserver. It automatically passes through the test class's
  467. clock & reactor.
  468. Args:
  469. See tests.utils.setup_test_homeserver.
  470. Returns:
  471. synapse.server.HomeServer
  472. """
  473. kwargs = dict(kwargs)
  474. kwargs.update(self._hs_args)
  475. if "config" not in kwargs:
  476. config = self.default_config()
  477. else:
  478. config = kwargs["config"]
  479. # The server name can be specified using either the `name` argument or a config
  480. # override. The `name` argument takes precedence over any config overrides.
  481. if name is not None:
  482. config["server_name"] = name
  483. # Parse the config from a config dict into a HomeServerConfig
  484. config_obj = make_homeserver_config_obj(config)
  485. kwargs["config"] = config_obj
  486. # The server name in the config is now `name`, if provided, or the `server_name`
  487. # from a config override, or the default of "test". Whichever it is, we
  488. # construct a homeserver with a matching name.
  489. kwargs["name"] = config_obj.server.server_name
  490. async def run_bg_updates() -> None:
  491. with LoggingContext("run_bg_updates"):
  492. self.get_success(stor.db_pool.updates.run_background_updates(False))
  493. hs = setup_test_homeserver(self.addCleanup, **kwargs)
  494. stor = hs.get_datastores().main
  495. # Run the database background updates, when running against "master".
  496. if hs.__class__.__name__ == "TestHomeServer":
  497. self.get_success(run_bg_updates())
  498. return hs
  499. def pump(self, by: float = 0.0) -> None:
  500. """
  501. Pump the reactor enough that Deferreds will fire.
  502. """
  503. self.reactor.pump([by] * 100)
  504. def get_success(self, d: Awaitable[TV], by: float = 0.0) -> TV:
  505. deferred: Deferred[TV] = ensureDeferred(d) # type: ignore[arg-type]
  506. self.pump(by=by)
  507. return self.successResultOf(deferred)
  508. def get_failure(
  509. self, d: Awaitable[Any], exc: Type[_ExcType]
  510. ) -> _TypedFailure[_ExcType]:
  511. """
  512. Run a Deferred and get a Failure from it. The failure must be of the type `exc`.
  513. """
  514. deferred: Deferred[Any] = ensureDeferred(d) # type: ignore[arg-type]
  515. self.pump()
  516. return self.failureResultOf(deferred, exc)
  517. def get_success_or_raise(self, d: Awaitable[TV], by: float = 0.0) -> TV:
  518. """Drive deferred to completion and return result or raise exception
  519. on failure.
  520. """
  521. deferred: Deferred[TV] = ensureDeferred(d) # type: ignore[arg-type]
  522. results: list = []
  523. deferred.addBoth(results.append)
  524. self.pump(by=by)
  525. if not results:
  526. self.fail(
  527. "Success result expected on {!r}, found no result instead".format(
  528. deferred
  529. )
  530. )
  531. result = results[0]
  532. if isinstance(result, Failure):
  533. result.raiseException()
  534. return result
  535. def register_user(
  536. self,
  537. username: str,
  538. password: str,
  539. admin: Optional[bool] = False,
  540. displayname: Optional[str] = None,
  541. ) -> str:
  542. """
  543. Register a user. Requires the Admin API be registered.
  544. Args:
  545. username: The user part of the new user.
  546. password: The password of the new user.
  547. admin: Whether the user should be created as an admin or not.
  548. displayname: The displayname of the new user.
  549. Returns:
  550. The MXID of the new user.
  551. """
  552. self.hs.config.registration.registration_shared_secret = "shared"
  553. # Create the user
  554. channel = self.make_request("GET", "/_synapse/admin/v1/register")
  555. self.assertEqual(channel.code, 200, msg=channel.result)
  556. nonce = channel.json_body["nonce"]
  557. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  558. nonce_str = b"\x00".join([username.encode("utf8"), password.encode("utf8")])
  559. if admin:
  560. nonce_str += b"\x00admin"
  561. else:
  562. nonce_str += b"\x00notadmin"
  563. want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str)
  564. want_mac_digest = want_mac.hexdigest()
  565. body = {
  566. "nonce": nonce,
  567. "username": username,
  568. "displayname": displayname,
  569. "password": password,
  570. "admin": admin,
  571. "mac": want_mac_digest,
  572. "inhibit_login": True,
  573. }
  574. channel = self.make_request("POST", "/_synapse/admin/v1/register", body)
  575. self.assertEqual(channel.code, 200, channel.json_body)
  576. user_id = channel.json_body["user_id"]
  577. return user_id
  578. def register_appservice_user(
  579. self,
  580. username: str,
  581. appservice_token: str,
  582. ) -> Tuple[str, str]:
  583. """Register an appservice user as an application service.
  584. Requires the client-facing registration API be registered.
  585. Args:
  586. username: the user to be registered by an application service.
  587. Should NOT be a full username, i.e. just "localpart" as opposed to "@localpart:hostname"
  588. appservice_token: the acccess token for that application service.
  589. Raises: if the request to '/register' does not return 200 OK.
  590. Returns:
  591. The MXID of the new user, the device ID of the new user's first device.
  592. """
  593. channel = self.make_request(
  594. "POST",
  595. "/_matrix/client/r0/register",
  596. {
  597. "username": username,
  598. "type": "m.login.application_service",
  599. },
  600. access_token=appservice_token,
  601. )
  602. self.assertEqual(channel.code, 200, channel.json_body)
  603. return channel.json_body["user_id"], channel.json_body["device_id"]
  604. def login(
  605. self,
  606. username: str,
  607. password: str,
  608. device_id: Optional[str] = None,
  609. additional_request_fields: Optional[Dict[str, str]] = None,
  610. custom_headers: Optional[Iterable[CustomHeaderType]] = None,
  611. ) -> str:
  612. """
  613. Log in a user, and get an access token. Requires the Login API be registered.
  614. Args:
  615. username: The localpart to assign to the new user.
  616. password: The password to assign to the new user.
  617. device_id: An optional device ID to assign to the new device created during
  618. login.
  619. additional_request_fields: A dictionary containing any additional /login
  620. request fields and their values.
  621. custom_headers: Custom HTTP headers and values to add to the /login request.
  622. Returns:
  623. The newly registered user's Matrix ID.
  624. """
  625. body = {"type": "m.login.password", "user": username, "password": password}
  626. if device_id:
  627. body["device_id"] = device_id
  628. if additional_request_fields:
  629. body.update(additional_request_fields)
  630. channel = self.make_request(
  631. "POST",
  632. "/_matrix/client/r0/login",
  633. body,
  634. custom_headers=custom_headers,
  635. )
  636. self.assertEqual(channel.code, 200, channel.result)
  637. access_token = channel.json_body["access_token"]
  638. return access_token
  639. def create_and_send_event(
  640. self,
  641. room_id: str,
  642. user: UserID,
  643. soft_failed: bool = False,
  644. prev_event_ids: Optional[List[str]] = None,
  645. ) -> str:
  646. """
  647. Create and send an event.
  648. Args:
  649. soft_failed: Whether to create a soft failed event or not
  650. prev_event_ids: Explicitly set the prev events,
  651. or if None just use the default
  652. Returns:
  653. The new event's ID.
  654. """
  655. event_creator = self.hs.get_event_creation_handler()
  656. requester = create_requester(user)
  657. event, unpersisted_context = self.get_success(
  658. event_creator.create_event(
  659. requester,
  660. {
  661. "type": EventTypes.Message,
  662. "room_id": room_id,
  663. "sender": user.to_string(),
  664. "content": {"body": secrets.token_hex(), "msgtype": "m.text"},
  665. },
  666. prev_event_ids=prev_event_ids,
  667. )
  668. )
  669. context = self.get_success(unpersisted_context.persist(event))
  670. if soft_failed:
  671. event.internal_metadata.soft_failed = True
  672. self.get_success(
  673. event_creator.handle_new_client_event(
  674. requester, events_and_context=[(event, context)]
  675. )
  676. )
  677. return event.event_id
  678. def inject_room_member(self, room: str, user: str, membership: str) -> None:
  679. """
  680. Inject a membership event into a room.
  681. Deprecated: use event_injection.inject_room_member directly
  682. Args:
  683. room: Room ID to inject the event into.
  684. user: MXID of the user to inject the membership for.
  685. membership: The membership type.
  686. """
  687. self.get_success(
  688. event_injection.inject_member_event(self.hs, room, user, membership)
  689. )
  690. class FederatingHomeserverTestCase(HomeserverTestCase):
  691. """
  692. A federating homeserver, set up to validate incoming federation requests
  693. """
  694. OTHER_SERVER_NAME = "other.example.com"
  695. OTHER_SERVER_SIGNATURE_KEY = signedjson.key.generate_signing_key("test")
  696. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  697. super().prepare(reactor, clock, hs)
  698. # poke the other server's signing key into the key store, so that we don't
  699. # make requests for it
  700. verify_key = signedjson.key.get_verify_key(self.OTHER_SERVER_SIGNATURE_KEY)
  701. verify_key_id = "%s:%s" % (verify_key.alg, verify_key.version)
  702. self.get_success(
  703. hs.get_datastores().main.store_server_keys_response(
  704. self.OTHER_SERVER_NAME,
  705. from_server=self.OTHER_SERVER_NAME,
  706. ts_added_ms=clock.time_msec(),
  707. verify_keys={
  708. verify_key_id: FetchKeyResult(
  709. verify_key=verify_key, valid_until_ts=clock.time_msec() + 10000
  710. ),
  711. },
  712. response_json={
  713. "verify_keys": {
  714. verify_key_id: {
  715. "key": signedjson.key.encode_verify_key_base64(verify_key)
  716. }
  717. }
  718. },
  719. )
  720. )
  721. def create_resource_dict(self) -> Dict[str, Resource]:
  722. d = super().create_resource_dict()
  723. d["/_matrix/federation"] = TransportLayerServer(self.hs)
  724. return d
  725. def make_signed_federation_request(
  726. self,
  727. method: str,
  728. path: str,
  729. content: Optional[JsonDict] = None,
  730. await_result: bool = True,
  731. custom_headers: Optional[Iterable[CustomHeaderType]] = None,
  732. client_ip: str = "127.0.0.1",
  733. ) -> FakeChannel:
  734. """Make an inbound signed federation request to this server
  735. The request is signed as if it came from "other.example.com", which our HS
  736. already has the keys for.
  737. """
  738. if custom_headers is None:
  739. custom_headers = []
  740. else:
  741. custom_headers = list(custom_headers)
  742. custom_headers.append(
  743. (
  744. "Authorization",
  745. _auth_header_for_request(
  746. origin=self.OTHER_SERVER_NAME,
  747. destination=self.hs.hostname,
  748. signing_key=self.OTHER_SERVER_SIGNATURE_KEY,
  749. method=method,
  750. path=path,
  751. content=content,
  752. ),
  753. )
  754. )
  755. return make_request(
  756. self.reactor,
  757. self.site,
  758. method=method,
  759. path=path,
  760. content=content if content is not None else "",
  761. shorthand=False,
  762. await_result=await_result,
  763. custom_headers=custom_headers,
  764. client_ip=client_ip,
  765. )
  766. def add_hashes_and_signatures_from_other_server(
  767. self,
  768. event_dict: JsonDict,
  769. room_version: RoomVersion = KNOWN_ROOM_VERSIONS[DEFAULT_ROOM_VERSION],
  770. ) -> JsonDict:
  771. """Adds hashes and signatures to the given event dict
  772. Returns:
  773. The modified event dict, for convenience
  774. """
  775. add_hashes_and_signatures(
  776. room_version,
  777. event_dict,
  778. signature_name=self.OTHER_SERVER_NAME,
  779. signing_key=self.OTHER_SERVER_SIGNATURE_KEY,
  780. )
  781. return event_dict
  782. def _auth_header_for_request(
  783. origin: str,
  784. destination: str,
  785. signing_key: signedjson.key.SigningKey,
  786. method: str,
  787. path: str,
  788. content: Optional[JsonDict],
  789. ) -> str:
  790. """Build a suitable Authorization header for an outgoing federation request"""
  791. request_description: JsonDict = {
  792. "method": method,
  793. "uri": path,
  794. "destination": destination,
  795. "origin": origin,
  796. }
  797. if content is not None:
  798. request_description["content"] = content
  799. signature_base64 = unpaddedbase64.encode_base64(
  800. signing_key.sign(
  801. canonicaljson.encode_canonical_json(request_description)
  802. ).signature
  803. )
  804. return (
  805. f"X-Matrix origin={origin},"
  806. f"key={signing_key.alg}:{signing_key.version},"
  807. f"sig={signature_base64}"
  808. )
  809. def override_config(extra_config: JsonDict) -> Callable[[TV], TV]:
  810. """A decorator which can be applied to test functions to give additional HS config
  811. For use
  812. For example:
  813. class MyTestCase(HomeserverTestCase):
  814. @override_config({"enable_registration": False, ...})
  815. def test_foo(self):
  816. ...
  817. Args:
  818. extra_config: Additional config settings to be merged into the default
  819. config dict before instantiating the test homeserver.
  820. """
  821. def decorator(func: TV) -> TV:
  822. # This attribute is being defined.
  823. func._extra_config = extra_config # type: ignore[attr-defined]
  824. return func
  825. return decorator
  826. def skip_unless(condition: bool, reason: str) -> Callable[[TV], TV]:
  827. """A test decorator which will skip the decorated test unless a condition is set
  828. For example:
  829. class MyTestCase(TestCase):
  830. @skip_unless(HAS_FOO, "Cannot test without foo")
  831. def test_foo(self):
  832. ...
  833. Args:
  834. condition: If true, the test will be skipped
  835. reason: the reason to give for skipping the test
  836. """
  837. def decorator(f: TV) -> TV:
  838. if not condition:
  839. f.skip = reason # type: ignore
  840. return f
  841. return decorator