1
0

unittest.py 34 KB

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