unittest.py 31 KB

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