unittest.py 30 KB

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