1
0

unittest.py 32 KB

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