1
0

unittest.py 31 KB

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