unittest.py 34 KB

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