unittest.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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: MemoryReactor, clock: Clock):
  293. """
  294. Make and return a homeserver.
  295. Args:
  296. reactor: A Twisted Reactor, or something that pretends to be one.
  297. 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: The Clock, associated with the reactor.
  346. homeserver: The HomeServer to test against.
  347. Function to optionally be overridden in subclasses.
  348. """
  349. def make_request(
  350. self,
  351. method: Union[bytes, str],
  352. path: Union[bytes, str],
  353. content: Union[bytes, str, JsonDict] = b"",
  354. access_token: Optional[str] = None,
  355. request: Type[Request] = SynapseRequest,
  356. shorthand: bool = True,
  357. federation_auth_origin: Optional[bytes] = None,
  358. content_is_form: bool = False,
  359. await_result: bool = True,
  360. custom_headers: Optional[Iterable[CustomHeaderType]] = None,
  361. client_ip: str = "127.0.0.1",
  362. ) -> FakeChannel:
  363. """
  364. Create a SynapseRequest at the path using the method and containing the
  365. given content.
  366. Args:
  367. method: The HTTP request method ("verb").
  368. path: The HTTP path, suitably URL encoded (e.g. escaped UTF-8 & spaces
  369. and such). content (bytes or dict): The body of the request.
  370. JSON-encoded, if a dict.
  371. shorthand: Whether to try and be helpful and prefix the given URL
  372. with the usual REST API path, if it doesn't contain it.
  373. federation_auth_origin: if set to not-None, we will add a fake
  374. Authorization header pretenting to be the given server name.
  375. content_is_form: Whether the content is URL encoded form data. Adds the
  376. 'Content-Type': 'application/x-www-form-urlencoded' header.
  377. await_result: whether to wait for the request to complete rendering. If
  378. true (the default), will pump the test reactor until the the renderer
  379. tells the channel the request is finished.
  380. custom_headers: (name, value) pairs to add as request headers
  381. client_ip: The IP to use as the requesting IP. Useful for testing
  382. ratelimiting.
  383. Returns:
  384. The FakeChannel object which stores the result of the request.
  385. """
  386. return make_request(
  387. self.reactor,
  388. self.site,
  389. method,
  390. path,
  391. content,
  392. access_token,
  393. request,
  394. shorthand,
  395. federation_auth_origin,
  396. content_is_form,
  397. await_result,
  398. custom_headers,
  399. client_ip,
  400. )
  401. def setup_test_homeserver(self, *args: Any, **kwargs: Any) -> HomeServer:
  402. """
  403. Set up the test homeserver, meant to be called by the overridable
  404. make_homeserver. It automatically passes through the test class's
  405. clock & reactor.
  406. Args:
  407. See tests.utils.setup_test_homeserver.
  408. Returns:
  409. synapse.server.HomeServer
  410. """
  411. kwargs = dict(kwargs)
  412. kwargs.update(self._hs_args)
  413. if "config" not in kwargs:
  414. config = self.default_config()
  415. else:
  416. config = kwargs["config"]
  417. # Parse the config from a config dict into a HomeServerConfig
  418. config_obj = HomeServerConfig()
  419. config_obj.parse_config_dict(config, "", "")
  420. kwargs["config"] = config_obj
  421. async def run_bg_updates() -> None:
  422. with LoggingContext("run_bg_updates"):
  423. self.get_success(stor.db_pool.updates.run_background_updates(False))
  424. hs = setup_test_homeserver(self.addCleanup, *args, **kwargs)
  425. stor = hs.get_datastores().main
  426. # Run the database background updates, when running against "master".
  427. if hs.__class__.__name__ == "TestHomeServer":
  428. self.get_success(run_bg_updates())
  429. return hs
  430. def pump(self, by: float = 0.0) -> None:
  431. """
  432. Pump the reactor enough that Deferreds will fire.
  433. """
  434. self.reactor.pump([by] * 100)
  435. def get_success(self, d: Awaitable[TV], by: float = 0.0) -> TV:
  436. deferred: Deferred[TV] = ensureDeferred(d) # type: ignore[arg-type]
  437. self.pump(by=by)
  438. return self.successResultOf(deferred)
  439. def get_failure(
  440. self, d: Awaitable[Any], exc: Type[_ExcType]
  441. ) -> _TypedFailure[_ExcType]:
  442. """
  443. Run a Deferred and get a Failure from it. The failure must be of the type `exc`.
  444. """
  445. deferred: Deferred[Any] = ensureDeferred(d) # type: ignore[arg-type]
  446. self.pump()
  447. return self.failureResultOf(deferred, exc)
  448. def get_success_or_raise(self, d: Awaitable[TV], by: float = 0.0) -> TV:
  449. """Drive deferred to completion and return result or raise exception
  450. on failure.
  451. """
  452. deferred: Deferred[TV] = ensureDeferred(d) # type: ignore[arg-type]
  453. results: list = []
  454. deferred.addBoth(results.append)
  455. self.pump(by=by)
  456. if not results:
  457. self.fail(
  458. "Success result expected on {!r}, found no result instead".format(
  459. deferred
  460. )
  461. )
  462. result = results[0]
  463. if isinstance(result, Failure):
  464. result.raiseException()
  465. return result
  466. def register_user(
  467. self,
  468. username: str,
  469. password: str,
  470. admin: Optional[bool] = False,
  471. displayname: Optional[str] = None,
  472. ) -> str:
  473. """
  474. Register a user. Requires the Admin API be registered.
  475. Args:
  476. username: The user part of the new user.
  477. password: The password of the new user.
  478. admin: Whether the user should be created as an admin or not.
  479. displayname: The displayname of the new user.
  480. Returns:
  481. The MXID of the new user.
  482. """
  483. self.hs.config.registration.registration_shared_secret = "shared"
  484. # Create the user
  485. channel = self.make_request("GET", "/_synapse/admin/v1/register")
  486. self.assertEqual(channel.code, 200, msg=channel.result)
  487. nonce = channel.json_body["nonce"]
  488. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  489. nonce_str = b"\x00".join([username.encode("utf8"), password.encode("utf8")])
  490. if admin:
  491. nonce_str += b"\x00admin"
  492. else:
  493. nonce_str += b"\x00notadmin"
  494. want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str)
  495. want_mac_digest = want_mac.hexdigest()
  496. body = {
  497. "nonce": nonce,
  498. "username": username,
  499. "displayname": displayname,
  500. "password": password,
  501. "admin": admin,
  502. "mac": want_mac_digest,
  503. "inhibit_login": True,
  504. }
  505. channel = self.make_request("POST", "/_synapse/admin/v1/register", body)
  506. self.assertEqual(channel.code, 200, channel.json_body)
  507. user_id = channel.json_body["user_id"]
  508. return user_id
  509. def register_appservice_user(
  510. self,
  511. username: str,
  512. appservice_token: str,
  513. ) -> Tuple[str, str]:
  514. """Register an appservice user as an application service.
  515. Requires the client-facing registration API be registered.
  516. Args:
  517. username: the user to be registered by an application service.
  518. Should NOT be a full username, i.e. just "localpart" as opposed to "@localpart:hostname"
  519. appservice_token: the acccess token for that application service.
  520. Raises: if the request to '/register' does not return 200 OK.
  521. Returns:
  522. The MXID of the new user, the device ID of the new user's first device.
  523. """
  524. channel = self.make_request(
  525. "POST",
  526. "/_matrix/client/r0/register",
  527. {
  528. "username": username,
  529. "type": "m.login.application_service",
  530. },
  531. access_token=appservice_token,
  532. )
  533. self.assertEqual(channel.code, 200, channel.json_body)
  534. return channel.json_body["user_id"], channel.json_body["device_id"]
  535. def login(
  536. self,
  537. username: str,
  538. password: str,
  539. device_id: Optional[str] = None,
  540. additional_request_fields: Optional[Dict[str, str]] = None,
  541. custom_headers: Optional[Iterable[CustomHeaderType]] = None,
  542. ) -> str:
  543. """
  544. Log in a user, and get an access token. Requires the Login API be registered.
  545. Args:
  546. username: The localpart to assign to the new user.
  547. password: The password to assign to the new user.
  548. device_id: An optional device ID to assign to the new device created during
  549. login.
  550. additional_request_fields: A dictionary containing any additional /login
  551. request fields and their values.
  552. custom_headers: Custom HTTP headers and values to add to the /login request.
  553. Returns:
  554. The newly registered user's Matrix ID.
  555. """
  556. body = {"type": "m.login.password", "user": username, "password": password}
  557. if device_id:
  558. body["device_id"] = device_id
  559. if additional_request_fields:
  560. body.update(additional_request_fields)
  561. channel = self.make_request(
  562. "POST",
  563. "/_matrix/client/r0/login",
  564. body,
  565. custom_headers=custom_headers,
  566. )
  567. self.assertEqual(channel.code, 200, channel.result)
  568. access_token = channel.json_body["access_token"]
  569. return access_token
  570. def create_and_send_event(
  571. self,
  572. room_id: str,
  573. user: UserID,
  574. soft_failed: bool = False,
  575. prev_event_ids: Optional[List[str]] = None,
  576. ) -> str:
  577. """
  578. Create and send an event.
  579. Args:
  580. soft_failed: Whether to create a soft failed event or not
  581. prev_event_ids: Explicitly set the prev events,
  582. or if None just use the default
  583. Returns:
  584. The new event's ID.
  585. """
  586. event_creator = self.hs.get_event_creation_handler()
  587. requester = create_requester(user)
  588. event, context = self.get_success(
  589. event_creator.create_event(
  590. requester,
  591. {
  592. "type": EventTypes.Message,
  593. "room_id": room_id,
  594. "sender": user.to_string(),
  595. "content": {"body": secrets.token_hex(), "msgtype": "m.text"},
  596. },
  597. prev_event_ids=prev_event_ids,
  598. )
  599. )
  600. if soft_failed:
  601. event.internal_metadata.soft_failed = True
  602. self.get_success(
  603. event_creator.handle_new_client_event(
  604. requester, events_and_context=[(event, context)]
  605. )
  606. )
  607. return event.event_id
  608. def inject_room_member(self, room: str, user: str, membership: str) -> None:
  609. """
  610. Inject a membership event into a room.
  611. Deprecated: use event_injection.inject_room_member directly
  612. Args:
  613. room: Room ID to inject the event into.
  614. user: MXID of the user to inject the membership for.
  615. membership: The membership type.
  616. """
  617. self.get_success(
  618. event_injection.inject_member_event(self.hs, room, user, membership)
  619. )
  620. class FederatingHomeserverTestCase(HomeserverTestCase):
  621. """
  622. A federating homeserver, set up to validate incoming federation requests
  623. """
  624. OTHER_SERVER_NAME = "other.example.com"
  625. OTHER_SERVER_SIGNATURE_KEY = signedjson.key.generate_signing_key("test")
  626. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  627. super().prepare(reactor, clock, hs)
  628. # poke the other server's signing key into the key store, so that we don't
  629. # make requests for it
  630. verify_key = signedjson.key.get_verify_key(self.OTHER_SERVER_SIGNATURE_KEY)
  631. verify_key_id = "%s:%s" % (verify_key.alg, verify_key.version)
  632. self.get_success(
  633. hs.get_datastores().main.store_server_verify_keys(
  634. from_server=self.OTHER_SERVER_NAME,
  635. ts_added_ms=clock.time_msec(),
  636. verify_keys=[
  637. (
  638. self.OTHER_SERVER_NAME,
  639. verify_key_id,
  640. FetchKeyResult(
  641. verify_key=verify_key,
  642. valid_until_ts=clock.time_msec() + 10000,
  643. ),
  644. )
  645. ],
  646. )
  647. )
  648. def create_resource_dict(self) -> Dict[str, Resource]:
  649. d = super().create_resource_dict()
  650. d["/_matrix/federation"] = TransportLayerServer(self.hs)
  651. return d
  652. def make_signed_federation_request(
  653. self,
  654. method: str,
  655. path: str,
  656. content: Optional[JsonDict] = None,
  657. await_result: bool = True,
  658. custom_headers: Optional[Iterable[CustomHeaderType]] = None,
  659. client_ip: str = "127.0.0.1",
  660. ) -> FakeChannel:
  661. """Make an inbound signed federation request to this server
  662. The request is signed as if it came from "other.example.com", which our HS
  663. already has the keys for.
  664. """
  665. if custom_headers is None:
  666. custom_headers = []
  667. else:
  668. custom_headers = list(custom_headers)
  669. custom_headers.append(
  670. (
  671. "Authorization",
  672. _auth_header_for_request(
  673. origin=self.OTHER_SERVER_NAME,
  674. destination=self.hs.hostname,
  675. signing_key=self.OTHER_SERVER_SIGNATURE_KEY,
  676. method=method,
  677. path=path,
  678. content=content,
  679. ),
  680. )
  681. )
  682. return make_request(
  683. self.reactor,
  684. self.site,
  685. method=method,
  686. path=path,
  687. content=content if content is not None else "",
  688. shorthand=False,
  689. await_result=await_result,
  690. custom_headers=custom_headers,
  691. client_ip=client_ip,
  692. )
  693. def add_hashes_and_signatures_from_other_server(
  694. self,
  695. event_dict: JsonDict,
  696. room_version: RoomVersion = KNOWN_ROOM_VERSIONS[DEFAULT_ROOM_VERSION],
  697. ) -> JsonDict:
  698. """Adds hashes and signatures to the given event dict
  699. Returns:
  700. The modified event dict, for convenience
  701. """
  702. add_hashes_and_signatures(
  703. room_version,
  704. event_dict,
  705. signature_name=self.OTHER_SERVER_NAME,
  706. signing_key=self.OTHER_SERVER_SIGNATURE_KEY,
  707. )
  708. return event_dict
  709. def _auth_header_for_request(
  710. origin: str,
  711. destination: str,
  712. signing_key: signedjson.key.SigningKey,
  713. method: str,
  714. path: str,
  715. content: Optional[JsonDict],
  716. ) -> str:
  717. """Build a suitable Authorization header for an outgoing federation request"""
  718. request_description: JsonDict = {
  719. "method": method,
  720. "uri": path,
  721. "destination": destination,
  722. "origin": origin,
  723. }
  724. if content is not None:
  725. request_description["content"] = content
  726. signature_base64 = unpaddedbase64.encode_base64(
  727. signing_key.sign(
  728. canonicaljson.encode_canonical_json(request_description)
  729. ).signature
  730. )
  731. return (
  732. f"X-Matrix origin={origin},"
  733. f"key={signing_key.alg}:{signing_key.version},"
  734. f"sig={signature_base64}"
  735. )
  736. def override_config(extra_config: JsonDict) -> Callable[[TV], TV]:
  737. """A decorator which can be applied to test functions to give additional HS config
  738. For use
  739. For example:
  740. class MyTestCase(HomeserverTestCase):
  741. @override_config({"enable_registration": False, ...})
  742. def test_foo(self):
  743. ...
  744. Args:
  745. extra_config: Additional config settings to be merged into the default
  746. config dict before instantiating the test homeserver.
  747. """
  748. def decorator(func: TV) -> TV:
  749. # This attribute is being defined.
  750. func._extra_config = extra_config # type: ignore[attr-defined]
  751. return func
  752. return decorator
  753. def skip_unless(condition: bool, reason: str) -> Callable[[TV], TV]:
  754. """A test decorator which will skip the decorated test unless a condition is set
  755. For example:
  756. class MyTestCase(TestCase):
  757. @skip_unless(HAS_FOO, "Cannot test without foo")
  758. def test_foo(self):
  759. ...
  760. Args:
  761. condition: If true, the test will be skipped
  762. reason: the reason to give for skipping the test
  763. """
  764. def decorator(f: TV) -> TV:
  765. if not condition:
  766. f.skip = reason # type: ignore
  767. return f
  768. return decorator