You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

937 lines
31 KiB

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