1
0

unittest.py 31 KB

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