unittest.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector
  3. # Copyright 2019 Matrix.org Federation C.I.C
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import gc
  17. import hashlib
  18. import hmac
  19. import json
  20. import logging
  21. import secrets
  22. import time
  23. from typing import (
  24. Any,
  25. Awaitable,
  26. Callable,
  27. ClassVar,
  28. Dict,
  29. Generic,
  30. Iterable,
  31. List,
  32. 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 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, 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. class _TypedFailure(Generic[_ExcType], Protocol):
  86. """Extension to twisted.Failure, where the 'value' has a certain type."""
  87. @property
  88. def value(self) -> _ExcType:
  89. ...
  90. def around(target):
  91. """A CLOS-style 'around' modifier, which wraps the original method of the
  92. given instance with another piece of code.
  93. @around(self)
  94. def method_name(orig, *args, **kwargs):
  95. return orig(*args, **kwargs)
  96. """
  97. def _around(code):
  98. name = code.__name__
  99. orig = getattr(target, name)
  100. def new(*args, **kwargs):
  101. return code(orig, *args, **kwargs)
  102. setattr(target, name, new)
  103. return _around
  104. class TestCase(unittest.TestCase):
  105. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  106. attributes on both itself and its individual test methods, to override the
  107. root logger's logging level while that test (case|method) runs."""
  108. def __init__(self, methodName: str):
  109. super().__init__(methodName)
  110. method = getattr(self, methodName)
  111. level = getattr(method, "loglevel", getattr(self, "loglevel", None))
  112. @around(self)
  113. def setUp(orig):
  114. # if we're not starting in the sentinel logcontext, then to be honest
  115. # all future bets are off.
  116. if current_context():
  117. self.fail(
  118. "Test starting with non-sentinel logging context %s"
  119. % (current_context(),)
  120. )
  121. old_level = logging.getLogger().level
  122. if level is not None and old_level != level:
  123. @around(self)
  124. def tearDown(orig):
  125. ret = orig()
  126. logging.getLogger().setLevel(old_level)
  127. return ret
  128. logging.getLogger().setLevel(level)
  129. # Trial messes with the warnings configuration, thus this has to be
  130. # done in the context of an individual TestCase.
  131. self.addCleanup(setup_awaitable_errors())
  132. return orig()
  133. @around(self)
  134. def tearDown(orig):
  135. ret = orig()
  136. # force a GC to workaround problems with deferreds leaking logcontexts when
  137. # they are GCed (see the logcontext docs)
  138. gc.collect()
  139. set_current_context(SENTINEL_CONTEXT)
  140. return ret
  141. def assertObjectHasAttributes(self, attrs, obj):
  142. """Asserts that the given object has each of the attributes given, and
  143. that the value of each matches according to assertEqual."""
  144. for key in attrs.keys():
  145. if not hasattr(obj, key):
  146. raise AssertionError("Expected obj to have a '.%s'" % key)
  147. try:
  148. self.assertEqual(attrs[key], getattr(obj, key))
  149. except AssertionError as e:
  150. raise (type(e))(f"Assert error for '.{key}':") from e
  151. def assert_dict(self, required, actual):
  152. """Does a partial assert of a dict.
  153. Args:
  154. required (dict): The keys and value which MUST be in 'actual'.
  155. actual (dict): The test result. Extra keys will not be checked.
  156. """
  157. for key in required:
  158. self.assertEqual(
  159. required[key], actual[key], msg="%s mismatch. %s" % (key, actual)
  160. )
  161. def DEBUG(target):
  162. """A decorator to set the .loglevel attribute to logging.DEBUG.
  163. Can apply to either a TestCase or an individual test method."""
  164. target.loglevel = logging.DEBUG
  165. return target
  166. def INFO(target):
  167. """A decorator to set the .loglevel attribute to logging.INFO.
  168. Can apply to either a TestCase or an individual test method."""
  169. target.loglevel = logging.INFO
  170. return target
  171. def logcontext_clean(target):
  172. """A decorator which marks the TestCase or method as 'logcontext_clean'
  173. ... ie, any logcontext errors should cause a test failure
  174. """
  175. def logcontext_error(msg):
  176. raise AssertionError("logcontext error: %s" % (msg))
  177. patcher = patch("synapse.logging.context.logcontext_error", new=logcontext_error)
  178. return patcher(target)
  179. class HomeserverTestCase(TestCase):
  180. """
  181. A base TestCase that reduces boilerplate for HomeServer-using test cases.
  182. Defines a setUp method which creates a mock reactor, and instantiates a homeserver
  183. running on that reactor.
  184. There are various hooks for modifying the way that the homeserver is instantiated:
  185. * override make_homeserver, for example by making it pass different parameters into
  186. setup_test_homeserver.
  187. * override default_config, to return a modified configuration dictionary for use
  188. by setup_test_homeserver.
  189. * On a per-test basis, you can use the @override_config decorator to give a
  190. dictionary containing additional configuration settings to be added to the basic
  191. config dict.
  192. Attributes:
  193. servlets: List of servlet registration function.
  194. user_id (str): The user ID to assume if auth is hijacked.
  195. hijack_auth: Whether to hijack auth to return the user specified
  196. in user_id.
  197. """
  198. hijack_auth: ClassVar[bool] = True
  199. needs_threadpool: ClassVar[bool] = False
  200. servlets: ClassVar[List[RegisterServletsFunc]] = []
  201. def __init__(self, methodName: str):
  202. super().__init__(methodName)
  203. # see if we have any additional config for this test
  204. method = getattr(self, methodName)
  205. self._extra_config = getattr(method, "_extra_config", None)
  206. def setUp(self):
  207. """
  208. Set up the TestCase by calling the homeserver constructor, optionally
  209. hijacking the authentication system to return a fixed user, and then
  210. calling the prepare function.
  211. """
  212. self.reactor, self.clock = get_clock()
  213. self._hs_args = {"clock": self.clock, "reactor": self.reactor}
  214. self.hs = self.make_homeserver(self.reactor, self.clock)
  215. # Honour the `use_frozen_dicts` config option. We have to do this
  216. # manually because this is taken care of in the app `start` code, which
  217. # we don't run. Plus we want to reset it on tearDown.
  218. events.USE_FROZEN_DICTS = self.hs.config.server.use_frozen_dicts
  219. if self.hs is None:
  220. raise Exception("No homeserver returned from make_homeserver.")
  221. if not isinstance(self.hs, HomeServer):
  222. raise Exception("A homeserver wasn't returned, but %r" % (self.hs,))
  223. # create the root resource, and a site to wrap it.
  224. self.resource = self.create_test_resource()
  225. self.site = SynapseSite(
  226. logger_name="synapse.access.http.fake",
  227. site_tag=self.hs.config.server.server_name,
  228. config=self.hs.config.server.listeners[0],
  229. resource=self.resource,
  230. server_version_string="1",
  231. max_request_body_size=1234,
  232. reactor=self.reactor,
  233. )
  234. from tests.rest.client.utils import RestHelper
  235. self.helper = RestHelper(self.hs, self.site, getattr(self, "user_id", None))
  236. if hasattr(self, "user_id"):
  237. if self.hijack_auth:
  238. assert self.helper.auth_user_id is not None
  239. # We need a valid token ID to satisfy foreign key constraints.
  240. token_id = self.get_success(
  241. self.hs.get_datastores().main.add_access_token_to_user(
  242. self.helper.auth_user_id,
  243. "some_fake_token",
  244. None,
  245. None,
  246. )
  247. )
  248. async def get_user_by_access_token(token=None, allow_guest=False):
  249. assert self.helper.auth_user_id is not None
  250. return {
  251. "user": UserID.from_string(self.helper.auth_user_id),
  252. "token_id": token_id,
  253. "is_guest": False,
  254. }
  255. async def get_user_by_req(request, allow_guest=False, rights="access"):
  256. assert self.helper.auth_user_id is not None
  257. return create_requester(
  258. UserID.from_string(self.helper.auth_user_id),
  259. token_id,
  260. False,
  261. False,
  262. None,
  263. )
  264. # Type ignore: mypy doesn't like us assigning to methods.
  265. self.hs.get_auth().get_user_by_req = get_user_by_req # type: ignore[assignment]
  266. self.hs.get_auth().get_user_by_access_token = get_user_by_access_token # type: ignore[assignment]
  267. self.hs.get_auth().get_access_token_from_request = Mock( # type: ignore[assignment]
  268. return_value="1234"
  269. )
  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):
  277. # Reset to not use frozen dicts.
  278. events.USE_FROZEN_DICTS = False
  279. def wait_on_thread(self, deferred, timeout=10):
  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(self, reactor, clock):
  299. """
  300. Make and return a homeserver.
  301. Args:
  302. reactor: A Twisted Reactor, or something that pretends to be one.
  303. clock (synapse.util.Clock): The Clock, associated with the reactor.
  304. Returns:
  305. A homeserver (synapse.server.HomeServer) suitable for testing.
  306. Function to be overridden in subclasses.
  307. """
  308. hs = self.setup_test_homeserver()
  309. return hs
  310. def create_test_resource(self) -> Resource:
  311. """
  312. Create a the root resource for the test server.
  313. The default calls `self.create_resource_dict` and builds the resultant dict
  314. into a tree.
  315. """
  316. root_resource = Resource()
  317. create_resource_tree(self.create_resource_dict(), root_resource)
  318. return root_resource
  319. def create_resource_dict(self) -> Dict[str, Resource]:
  320. """Create a resource tree for the test server
  321. A resource tree is a mapping from path to twisted.web.resource.
  322. The default implementation creates a JsonResource and calls each function in
  323. `servlets` to register servlets against it.
  324. """
  325. servlet_resource = JsonResource(self.hs)
  326. for servlet in self.servlets:
  327. servlet(self.hs, servlet_resource)
  328. return {
  329. "/_matrix/client": servlet_resource,
  330. "/_synapse/admin": servlet_resource,
  331. }
  332. def default_config(self):
  333. """
  334. Get a default HomeServer config dict.
  335. """
  336. config = default_config("test")
  337. # apply any additional config which was specified via the override_config
  338. # decorator.
  339. if self._extra_config is not None:
  340. config.update(self._extra_config)
  341. return config
  342. def prepare(self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer):
  343. """
  344. Prepare for the test. This involves things like mocking out parts of
  345. the homeserver, or building test data common across the whole test
  346. suite.
  347. Args:
  348. reactor: A Twisted Reactor, or something that pretends to be one.
  349. clock (synapse.util.Clock): The Clock, associated with the reactor.
  350. homeserver (synapse.server.HomeServer): The HomeServer to test
  351. against.
  352. Function to optionally be overridden in subclasses.
  353. """
  354. def make_request(
  355. self,
  356. method: Union[bytes, str],
  357. path: Union[bytes, str],
  358. content: Union[bytes, str, JsonDict] = b"",
  359. access_token: Optional[str] = None,
  360. request: Type[Request] = SynapseRequest,
  361. shorthand: bool = True,
  362. federation_auth_origin: Optional[bytes] = None,
  363. content_is_form: bool = False,
  364. await_result: bool = True,
  365. custom_headers: Optional[Iterable[CustomHeaderType]] = None,
  366. client_ip: str = "127.0.0.1",
  367. ) -> FakeChannel:
  368. """
  369. Create a SynapseRequest at the path using the method and containing the
  370. given content.
  371. Args:
  372. method (bytes/unicode): The HTTP request method ("verb").
  373. path (bytes/unicode): The HTTP path, suitably URL encoded (e.g.
  374. escaped UTF-8 & spaces and such).
  375. content (bytes or dict): The body of the request. JSON-encoded, if
  376. a dict.
  377. shorthand: Whether to try and be helpful and prefix the given URL
  378. with the usual REST API path, if it doesn't contain it.
  379. federation_auth_origin: if set to not-None, we will add a fake
  380. Authorization header pretenting to be the given server name.
  381. content_is_form: Whether the content is URL encoded form data. Adds the
  382. 'Content-Type': 'application/x-www-form-urlencoded' header.
  383. await_result: whether to wait for the request to complete rendering. If
  384. true (the default), will pump the test reactor until the the renderer
  385. tells the channel the request is finished.
  386. custom_headers: (name, value) pairs to add as request headers
  387. client_ip: The IP to use as the requesting IP. Useful for testing
  388. ratelimiting.
  389. Returns:
  390. The FakeChannel object which stores the result of the request.
  391. """
  392. return make_request(
  393. self.reactor,
  394. self.site,
  395. method,
  396. path,
  397. content,
  398. access_token,
  399. request,
  400. shorthand,
  401. federation_auth_origin,
  402. content_is_form,
  403. await_result,
  404. custom_headers,
  405. client_ip,
  406. )
  407. def setup_test_homeserver(self, *args: Any, **kwargs: Any) -> HomeServer:
  408. """
  409. Set up the test homeserver, meant to be called by the overridable
  410. make_homeserver. It automatically passes through the test class's
  411. clock & reactor.
  412. Args:
  413. See tests.utils.setup_test_homeserver.
  414. Returns:
  415. synapse.server.HomeServer
  416. """
  417. kwargs = dict(kwargs)
  418. kwargs.update(self._hs_args)
  419. if "config" not in kwargs:
  420. config = self.default_config()
  421. else:
  422. config = kwargs["config"]
  423. # Parse the config from a config dict into a HomeServerConfig
  424. config_obj = HomeServerConfig()
  425. config_obj.parse_config_dict(config, "", "")
  426. kwargs["config"] = config_obj
  427. async def run_bg_updates():
  428. with LoggingContext("run_bg_updates"):
  429. self.get_success(stor.db_pool.updates.run_background_updates(False))
  430. hs = setup_test_homeserver(self.addCleanup, *args, **kwargs)
  431. stor = hs.get_datastores().main
  432. # Run the database background updates, when running against "master".
  433. if hs.__class__.__name__ == "TestHomeServer":
  434. self.get_success(run_bg_updates())
  435. return hs
  436. def pump(self, by: float = 0.0) -> None:
  437. """
  438. Pump the reactor enough that Deferreds will fire.
  439. """
  440. self.reactor.pump([by] * 100)
  441. def get_success(
  442. self,
  443. d: Awaitable[TV],
  444. by: float = 0.0,
  445. ) -> TV:
  446. deferred: Deferred[TV] = ensureDeferred(d) # type: ignore[arg-type]
  447. self.pump(by=by)
  448. return self.successResultOf(deferred)
  449. def get_failure(
  450. self, d: Awaitable[Any], exc: Type[_ExcType]
  451. ) -> _TypedFailure[_ExcType]:
  452. """
  453. Run a Deferred and get a Failure from it. The failure must be of the type `exc`.
  454. """
  455. deferred: Deferred[Any] = ensureDeferred(d) # type: ignore[arg-type]
  456. self.pump()
  457. return self.failureResultOf(deferred, exc)
  458. def get_success_or_raise(self, d: Awaitable[TV], by: float = 0.0) -> TV:
  459. """Drive deferred to completion and return result or raise exception
  460. on failure.
  461. """
  462. deferred: Deferred[TV] = ensureDeferred(d) # type: ignore[arg-type]
  463. results: list = []
  464. deferred.addBoth(results.append)
  465. self.pump(by=by)
  466. if not results:
  467. self.fail(
  468. "Success result expected on {!r}, found no result instead".format(
  469. deferred
  470. )
  471. )
  472. result = results[0]
  473. if isinstance(result, Failure):
  474. result.raiseException()
  475. return result
  476. def register_user(
  477. self,
  478. username: str,
  479. password: str,
  480. admin: Optional[bool] = False,
  481. displayname: Optional[str] = None,
  482. ) -> str:
  483. """
  484. Register a user. Requires the Admin API be registered.
  485. Args:
  486. username: The user part of the new user.
  487. password: The password of the new user.
  488. admin: Whether the user should be created as an admin or not.
  489. displayname: The displayname of the new user.
  490. Returns:
  491. The MXID of the new user.
  492. """
  493. self.hs.config.registration.registration_shared_secret = "shared"
  494. # Create the user
  495. channel = self.make_request("GET", "/_synapse/admin/v1/register")
  496. self.assertEqual(channel.code, 200, msg=channel.result)
  497. nonce = channel.json_body["nonce"]
  498. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  499. nonce_str = b"\x00".join([username.encode("utf8"), password.encode("utf8")])
  500. if admin:
  501. nonce_str += b"\x00admin"
  502. else:
  503. nonce_str += b"\x00notadmin"
  504. want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str)
  505. want_mac_digest = want_mac.hexdigest()
  506. body = json.dumps(
  507. {
  508. "nonce": nonce,
  509. "username": username,
  510. "displayname": displayname,
  511. "password": password,
  512. "admin": admin,
  513. "mac": want_mac_digest,
  514. "inhibit_login": True,
  515. }
  516. )
  517. channel = self.make_request(
  518. "POST", "/_synapse/admin/v1/register", body.encode("utf8")
  519. )
  520. self.assertEqual(channel.code, 200, channel.json_body)
  521. user_id = channel.json_body["user_id"]
  522. return user_id
  523. def register_appservice_user(
  524. self,
  525. username: str,
  526. appservice_token: str,
  527. ) -> Tuple[str, str]:
  528. """Register an appservice user as an application service.
  529. Requires the client-facing registration API be registered.
  530. Args:
  531. username: the user to be registered by an application service.
  532. Should NOT be a full username, i.e. just "localpart" as opposed to "@localpart:hostname"
  533. appservice_token: the acccess token for that application service.
  534. Raises: if the request to '/register' does not return 200 OK.
  535. Returns:
  536. The MXID of the new user, the device ID of the new user's first device.
  537. """
  538. channel = self.make_request(
  539. "POST",
  540. "/_matrix/client/r0/register",
  541. {
  542. "username": username,
  543. "type": "m.login.application_service",
  544. },
  545. access_token=appservice_token,
  546. )
  547. self.assertEqual(channel.code, 200, channel.json_body)
  548. return channel.json_body["user_id"], channel.json_body["device_id"]
  549. def login(
  550. self,
  551. username: str,
  552. password: str,
  553. device_id: Optional[str] = None,
  554. custom_headers: Optional[Iterable[CustomHeaderType]] = None,
  555. ) -> str:
  556. """
  557. Log in a user, and get an access token. Requires the Login API be
  558. registered.
  559. """
  560. body = {"type": "m.login.password", "user": username, "password": password}
  561. if device_id:
  562. body["device_id"] = device_id
  563. channel = self.make_request(
  564. "POST",
  565. "/_matrix/client/r0/login",
  566. json.dumps(body).encode("utf8"),
  567. custom_headers=custom_headers,
  568. )
  569. self.assertEqual(channel.code, 200, channel.result)
  570. access_token = channel.json_body["access_token"]
  571. return access_token
  572. def create_and_send_event(
  573. self,
  574. room_id: str,
  575. user: UserID,
  576. soft_failed: bool = False,
  577. prev_event_ids: Optional[List[str]] = None,
  578. ) -> str:
  579. """
  580. Create and send an event.
  581. Args:
  582. soft_failed: Whether to create a soft failed event or not
  583. prev_event_ids: Explicitly set the prev events,
  584. or if None just use the default
  585. Returns:
  586. The new event's ID.
  587. """
  588. event_creator = self.hs.get_event_creation_handler()
  589. requester = create_requester(user)
  590. event, context = self.get_success(
  591. event_creator.create_event(
  592. requester,
  593. {
  594. "type": EventTypes.Message,
  595. "room_id": room_id,
  596. "sender": user.to_string(),
  597. "content": {"body": secrets.token_hex(), "msgtype": "m.text"},
  598. },
  599. prev_event_ids=prev_event_ids,
  600. )
  601. )
  602. if soft_failed:
  603. event.internal_metadata.soft_failed = True
  604. self.get_success(
  605. event_creator.handle_new_client_event(requester, event, context)
  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):
  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() + 1000,
  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(
  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):
  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(dict): Additional config settings to be merged into the default
  746. config dict before instantiating the test homeserver.
  747. """
  748. def decorator(func):
  749. func._extra_config = extra_config
  750. return func
  751. return decorator
  752. def skip_unless(condition: bool, reason: str) -> Callable[[TV], TV]:
  753. """A test decorator which will skip the decorated test unless a condition is set
  754. For example:
  755. class MyTestCase(TestCase):
  756. @skip_unless(HAS_FOO, "Cannot test without foo")
  757. def test_foo(self):
  758. ...
  759. Args:
  760. condition: If true, the test will be skipped
  761. reason: the reason to give for skipping the test
  762. """
  763. def decorator(f: TV) -> TV:
  764. if not condition:
  765. f.skip = reason # type: ignore
  766. return f
  767. return decorator