1
0

unittest.py 35 KB

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