unittest.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector
  4. # Copyright 2019 Matrix.org Federation C.I.C
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import gc
  18. import hashlib
  19. import hmac
  20. import inspect
  21. import logging
  22. import time
  23. from typing import Optional, Tuple, Type, TypeVar, Union
  24. from mock import Mock
  25. from canonicaljson import json
  26. from twisted.internet.defer import Deferred, ensureDeferred, succeed
  27. from twisted.python.threadpool import ThreadPool
  28. from twisted.trial import unittest
  29. from synapse.api.constants import EventTypes, Membership
  30. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  31. from synapse.config.homeserver import HomeServerConfig
  32. from synapse.config.ratelimiting import FederationRateLimitConfig
  33. from synapse.federation.transport import server as federation_server
  34. from synapse.http.server import JsonResource
  35. from synapse.http.site import SynapseRequest, SynapseSite
  36. from synapse.logging.context import LoggingContext
  37. from synapse.server import HomeServer
  38. from synapse.types import Requester, UserID, create_requester
  39. from synapse.util.ratelimitutils import FederationRateLimiter
  40. from tests.server import (
  41. FakeChannel,
  42. get_clock,
  43. make_request,
  44. render,
  45. setup_test_homeserver,
  46. )
  47. from tests.test_utils.logging_setup import setup_logging
  48. from tests.utils import default_config, setupdb
  49. setupdb()
  50. setup_logging()
  51. def around(target):
  52. """A CLOS-style 'around' modifier, which wraps the original method of the
  53. given instance with another piece of code.
  54. @around(self)
  55. def method_name(orig, *args, **kwargs):
  56. return orig(*args, **kwargs)
  57. """
  58. def _around(code):
  59. name = code.__name__
  60. orig = getattr(target, name)
  61. def new(*args, **kwargs):
  62. return code(orig, *args, **kwargs)
  63. setattr(target, name, new)
  64. return _around
  65. T = TypeVar("T")
  66. class TestCase(unittest.TestCase):
  67. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  68. attributes on both itself and its individual test methods, to override the
  69. root logger's logging level while that test (case|method) runs."""
  70. def __init__(self, methodName, *args, **kwargs):
  71. super(TestCase, self).__init__(methodName, *args, **kwargs)
  72. method = getattr(self, methodName)
  73. level = getattr(method, "loglevel", getattr(self, "loglevel", None))
  74. @around(self)
  75. def setUp(orig):
  76. # if we're not starting in the sentinel logcontext, then to be honest
  77. # all future bets are off.
  78. if LoggingContext.current_context() is not LoggingContext.sentinel:
  79. self.fail(
  80. "Test starting with non-sentinel logging context %s"
  81. % (LoggingContext.current_context(),)
  82. )
  83. old_level = logging.getLogger().level
  84. if level is not None and old_level != level:
  85. @around(self)
  86. def tearDown(orig):
  87. ret = orig()
  88. logging.getLogger().setLevel(old_level)
  89. return ret
  90. logging.getLogger().setLevel(level)
  91. return orig()
  92. @around(self)
  93. def tearDown(orig):
  94. ret = orig()
  95. # force a GC to workaround problems with deferreds leaking logcontexts when
  96. # they are GCed (see the logcontext docs)
  97. gc.collect()
  98. LoggingContext.set_current_context(LoggingContext.sentinel)
  99. return ret
  100. def assertObjectHasAttributes(self, attrs, obj):
  101. """Asserts that the given object has each of the attributes given, and
  102. that the value of each matches according to assertEquals."""
  103. for (key, value) in attrs.items():
  104. if not hasattr(obj, key):
  105. raise AssertionError("Expected obj to have a '.%s'" % key)
  106. try:
  107. self.assertEquals(attrs[key], getattr(obj, key))
  108. except AssertionError as e:
  109. raise (type(e))(e.message + " for '.%s'" % key)
  110. def assert_dict(self, required, actual):
  111. """Does a partial assert of a dict.
  112. Args:
  113. required (dict): The keys and value which MUST be in 'actual'.
  114. actual (dict): The test result. Extra keys will not be checked.
  115. """
  116. for key in required:
  117. self.assertEquals(
  118. required[key], actual[key], msg="%s mismatch. %s" % (key, actual)
  119. )
  120. def DEBUG(target):
  121. """A decorator to set the .loglevel attribute to logging.DEBUG.
  122. Can apply to either a TestCase or an individual test method."""
  123. target.loglevel = logging.DEBUG
  124. return target
  125. def INFO(target):
  126. """A decorator to set the .loglevel attribute to logging.INFO.
  127. Can apply to either a TestCase or an individual test method."""
  128. target.loglevel = logging.INFO
  129. return target
  130. class HomeserverTestCase(TestCase):
  131. """
  132. A base TestCase that reduces boilerplate for HomeServer-using test cases.
  133. Defines a setUp method which creates a mock reactor, and instantiates a homeserver
  134. running on that reactor.
  135. There are various hooks for modifying the way that the homeserver is instantiated:
  136. * override make_homeserver, for example by making it pass different parameters into
  137. setup_test_homeserver.
  138. * override default_config, to return a modified configuration dictionary for use
  139. by setup_test_homeserver.
  140. * On a per-test basis, you can use the @override_config decorator to give a
  141. dictionary containing additional configuration settings to be added to the basic
  142. config dict.
  143. Attributes:
  144. servlets (list[function]): List of servlet registration function.
  145. user_id (str): The user ID to assume if auth is hijacked.
  146. hijack_auth (bool): Whether to hijack auth to return the user specified
  147. in user_id.
  148. """
  149. servlets = []
  150. hijack_auth = True
  151. needs_threadpool = False
  152. def __init__(self, methodName, *args, **kwargs):
  153. super().__init__(methodName, *args, **kwargs)
  154. # see if we have any additional config for this test
  155. method = getattr(self, methodName)
  156. self._extra_config = getattr(method, "_extra_config", None)
  157. def setUp(self):
  158. """
  159. Set up the TestCase by calling the homeserver constructor, optionally
  160. hijacking the authentication system to return a fixed user, and then
  161. calling the prepare function.
  162. """
  163. self.reactor, self.clock = get_clock()
  164. self._hs_args = {"clock": self.clock, "reactor": self.reactor}
  165. self.hs = self.make_homeserver(self.reactor, self.clock)
  166. if self.hs is None:
  167. raise Exception("No homeserver returned from make_homeserver.")
  168. if not isinstance(self.hs, HomeServer):
  169. raise Exception("A homeserver wasn't returned, but %r" % (self.hs,))
  170. # Register the resources
  171. self.resource = self.create_test_json_resource()
  172. # create a site to wrap the resource.
  173. self.site = SynapseSite(
  174. logger_name="synapse.access.http.fake",
  175. site_tag="test",
  176. config={},
  177. resource=self.resource,
  178. server_version_string="1",
  179. )
  180. from tests.rest.client.v1.utils import RestHelper
  181. self.helper = RestHelper(self.hs, self.resource, getattr(self, "user_id", None))
  182. if hasattr(self, "user_id"):
  183. if self.hijack_auth:
  184. def get_user_by_access_token(token=None, allow_guest=False):
  185. return succeed(
  186. {
  187. "user": UserID.from_string(self.helper.auth_user_id),
  188. "token_id": 1,
  189. "is_guest": False,
  190. }
  191. )
  192. def get_user_by_req(request, allow_guest=False, rights="access"):
  193. return succeed(
  194. create_requester(
  195. UserID.from_string(self.helper.auth_user_id), 1, False, None
  196. )
  197. )
  198. self.hs.get_auth().get_user_by_req = get_user_by_req
  199. self.hs.get_auth().get_user_by_access_token = get_user_by_access_token
  200. self.hs.get_auth().get_access_token_from_request = Mock(
  201. return_value="1234"
  202. )
  203. if self.needs_threadpool:
  204. self.reactor.threadpool = ThreadPool()
  205. self.addCleanup(self.reactor.threadpool.stop)
  206. self.reactor.threadpool.start()
  207. if hasattr(self, "prepare"):
  208. self.prepare(self.reactor, self.clock, self.hs)
  209. def wait_on_thread(self, deferred, timeout=10):
  210. """
  211. Wait until a Deferred is done, where it's waiting on a real thread.
  212. """
  213. start_time = time.time()
  214. while not deferred.called:
  215. if start_time + timeout < time.time():
  216. raise ValueError("Timed out waiting for threadpool")
  217. self.reactor.advance(0.01)
  218. time.sleep(0.01)
  219. def make_homeserver(self, reactor, clock):
  220. """
  221. Make and return a homeserver.
  222. Args:
  223. reactor: A Twisted Reactor, or something that pretends to be one.
  224. clock (synapse.util.Clock): The Clock, associated with the reactor.
  225. Returns:
  226. A homeserver (synapse.server.HomeServer) suitable for testing.
  227. Function to be overridden in subclasses.
  228. """
  229. hs = self.setup_test_homeserver()
  230. return hs
  231. def create_test_json_resource(self):
  232. """
  233. Create a test JsonResource, with the relevant servlets registerd to it
  234. The default implementation calls each function in `servlets` to do the
  235. registration.
  236. Returns:
  237. JsonResource:
  238. """
  239. resource = JsonResource(self.hs)
  240. for servlet in self.servlets:
  241. servlet(self.hs, resource)
  242. return resource
  243. def default_config(self, name="test"):
  244. """
  245. Get a default HomeServer config dict.
  246. Args:
  247. name (str): The homeserver name/domain.
  248. """
  249. config = default_config(name)
  250. # apply any additional config which was specified via the override_config
  251. # decorator.
  252. if self._extra_config is not None:
  253. config.update(self._extra_config)
  254. return config
  255. def prepare(self, reactor, clock, homeserver):
  256. """
  257. Prepare for the test. This involves things like mocking out parts of
  258. the homeserver, or building test data common across the whole test
  259. suite.
  260. Args:
  261. reactor: A Twisted Reactor, or something that pretends to be one.
  262. clock (synapse.util.Clock): The Clock, associated with the reactor.
  263. homeserver (synapse.server.HomeServer): The HomeServer to test
  264. against.
  265. Function to optionally be overridden in subclasses.
  266. """
  267. def make_request(
  268. self,
  269. method: Union[bytes, str],
  270. path: Union[bytes, str],
  271. content: Union[bytes, dict] = b"",
  272. access_token: Optional[str] = None,
  273. request: Type[T] = SynapseRequest,
  274. shorthand: bool = True,
  275. federation_auth_origin: str = None,
  276. ) -> Tuple[T, FakeChannel]:
  277. """
  278. Create a SynapseRequest at the path using the method and containing the
  279. given content.
  280. Args:
  281. method (bytes/unicode): The HTTP request method ("verb").
  282. path (bytes/unicode): The HTTP path, suitably URL encoded (e.g.
  283. escaped UTF-8 & spaces and such).
  284. content (bytes or dict): The body of the request. JSON-encoded, if
  285. a dict.
  286. shorthand: Whether to try and be helpful and prefix the given URL
  287. with the usual REST API path, if it doesn't contain it.
  288. federation_auth_origin (bytes|None): if set to not-None, we will add a fake
  289. Authorization header pretenting to be the given server name.
  290. Returns:
  291. Tuple[synapse.http.site.SynapseRequest, channel]
  292. """
  293. if isinstance(content, dict):
  294. content = json.dumps(content).encode("utf8")
  295. return make_request(
  296. self.reactor,
  297. method,
  298. path,
  299. content,
  300. access_token,
  301. request,
  302. shorthand,
  303. federation_auth_origin,
  304. )
  305. def render(self, request):
  306. """
  307. Render a request against the resources registered by the test class's
  308. servlets.
  309. Args:
  310. request (synapse.http.site.SynapseRequest): The request to render.
  311. """
  312. render(request, self.resource, self.reactor)
  313. def setup_test_homeserver(self, *args, **kwargs):
  314. """
  315. Set up the test homeserver, meant to be called by the overridable
  316. make_homeserver. It automatically passes through the test class's
  317. clock & reactor.
  318. Args:
  319. See tests.utils.setup_test_homeserver.
  320. Returns:
  321. synapse.server.HomeServer
  322. """
  323. kwargs = dict(kwargs)
  324. kwargs.update(self._hs_args)
  325. if "config" not in kwargs:
  326. config = self.default_config()
  327. else:
  328. config = kwargs["config"]
  329. # Parse the config from a config dict into a HomeServerConfig
  330. config_obj = HomeServerConfig()
  331. config_obj.parse_config_dict(config, "", "")
  332. kwargs["config"] = config_obj
  333. hs = setup_test_homeserver(self.addCleanup, *args, **kwargs)
  334. stor = hs.get_datastore()
  335. # Run the database background updates, when running against "master".
  336. if hs.__class__.__name__ == "TestHomeServer":
  337. while not self.get_success(
  338. stor.db.updates.has_completed_background_updates()
  339. ):
  340. self.get_success(stor.db.updates.do_next_background_update(1))
  341. return hs
  342. def pump(self, by=0.0):
  343. """
  344. Pump the reactor enough that Deferreds will fire.
  345. """
  346. self.reactor.pump([by] * 100)
  347. def get_success(self, d, by=0.0):
  348. if inspect.isawaitable(d):
  349. d = ensureDeferred(d)
  350. if not isinstance(d, Deferred):
  351. return d
  352. self.pump(by=by)
  353. return self.successResultOf(d)
  354. def get_failure(self, d, exc):
  355. """
  356. Run a Deferred and get a Failure from it. The failure must be of the type `exc`.
  357. """
  358. if inspect.isawaitable(d):
  359. d = ensureDeferred(d)
  360. if not isinstance(d, Deferred):
  361. return d
  362. self.pump()
  363. return self.failureResultOf(d, exc)
  364. def register_user(self, username, password, admin=False):
  365. """
  366. Register a user. Requires the Admin API be registered.
  367. Args:
  368. username (bytes/unicode): The user part of the new user.
  369. password (bytes/unicode): The password of the new user.
  370. admin (bool): Whether the user should be created as an admin
  371. or not.
  372. Returns:
  373. The MXID of the new user (unicode).
  374. """
  375. self.hs.config.registration_shared_secret = "shared"
  376. # Create the user
  377. request, channel = self.make_request("GET", "/_matrix/client/r0/admin/register")
  378. self.render(request)
  379. self.assertEqual(channel.code, 200, msg=channel.result)
  380. nonce = channel.json_body["nonce"]
  381. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  382. nonce_str = b"\x00".join([username.encode("utf8"), password.encode("utf8")])
  383. if admin:
  384. nonce_str += b"\x00admin"
  385. else:
  386. nonce_str += b"\x00notadmin"
  387. want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str)
  388. want_mac = want_mac.hexdigest()
  389. body = json.dumps(
  390. {
  391. "nonce": nonce,
  392. "username": username,
  393. "password": password,
  394. "admin": admin,
  395. "mac": want_mac,
  396. }
  397. )
  398. request, channel = self.make_request(
  399. "POST", "/_matrix/client/r0/admin/register", body.encode("utf8")
  400. )
  401. self.render(request)
  402. self.assertEqual(channel.code, 200, channel.json_body)
  403. user_id = channel.json_body["user_id"]
  404. return user_id
  405. def login(self, username, password, device_id=None):
  406. """
  407. Log in a user, and get an access token. Requires the Login API be
  408. registered.
  409. """
  410. body = {"type": "m.login.password", "user": username, "password": password}
  411. if device_id:
  412. body["device_id"] = device_id
  413. request, channel = self.make_request(
  414. "POST", "/_matrix/client/r0/login", json.dumps(body).encode("utf8")
  415. )
  416. self.render(request)
  417. self.assertEqual(channel.code, 200, channel.result)
  418. access_token = channel.json_body["access_token"]
  419. return access_token
  420. def create_and_send_event(
  421. self, room_id, user, soft_failed=False, prev_event_ids=None
  422. ):
  423. """
  424. Create and send an event.
  425. Args:
  426. soft_failed (bool): Whether to create a soft failed event or not
  427. prev_event_ids (list[str]|None): Explicitly set the prev events,
  428. or if None just use the default
  429. Returns:
  430. str: The new event's ID.
  431. """
  432. event_creator = self.hs.get_event_creation_handler()
  433. secrets = self.hs.get_secrets()
  434. requester = Requester(user, None, False, None, None)
  435. event, context = self.get_success(
  436. event_creator.create_event(
  437. requester,
  438. {
  439. "type": EventTypes.Message,
  440. "room_id": room_id,
  441. "sender": user.to_string(),
  442. "content": {"body": secrets.token_hex(), "msgtype": "m.text"},
  443. },
  444. prev_event_ids=prev_event_ids,
  445. )
  446. )
  447. if soft_failed:
  448. event.internal_metadata.soft_failed = True
  449. self.get_success(event_creator.send_nonmember_event(requester, event, context))
  450. return event.event_id
  451. def add_extremity(self, room_id, event_id):
  452. """
  453. Add the given event as an extremity to the room.
  454. """
  455. self.get_success(
  456. self.hs.get_datastore().db.simple_insert(
  457. table="event_forward_extremities",
  458. values={"room_id": room_id, "event_id": event_id},
  459. desc="test_add_extremity",
  460. )
  461. )
  462. self.hs.get_datastore().get_latest_event_ids_in_room.invalidate((room_id,))
  463. def attempt_wrong_password_login(self, username, password):
  464. """Attempts to login as the user with the given password, asserting
  465. that the attempt *fails*.
  466. """
  467. body = {"type": "m.login.password", "user": username, "password": password}
  468. request, channel = self.make_request(
  469. "POST", "/_matrix/client/r0/login", json.dumps(body).encode("utf8")
  470. )
  471. self.render(request)
  472. self.assertEqual(channel.code, 403, channel.result)
  473. def inject_room_member(self, room: str, user: str, membership: Membership) -> None:
  474. """
  475. Inject a membership event into a room.
  476. Args:
  477. room: Room ID to inject the event into.
  478. user: MXID of the user to inject the membership for.
  479. membership: The membership type.
  480. """
  481. event_builder_factory = self.hs.get_event_builder_factory()
  482. event_creation_handler = self.hs.get_event_creation_handler()
  483. room_version = self.get_success(
  484. self.hs.get_datastore().get_room_version_id(room)
  485. )
  486. builder = event_builder_factory.for_room_version(
  487. KNOWN_ROOM_VERSIONS[room_version],
  488. {
  489. "type": EventTypes.Member,
  490. "sender": user,
  491. "state_key": user,
  492. "room_id": room,
  493. "content": {"membership": membership},
  494. },
  495. )
  496. event, context = self.get_success(
  497. event_creation_handler.create_new_client_event(builder)
  498. )
  499. self.get_success(
  500. self.hs.get_storage().persistence.persist_event(event, context)
  501. )
  502. class FederatingHomeserverTestCase(HomeserverTestCase):
  503. """
  504. A federating homeserver that authenticates incoming requests as `other.example.com`.
  505. """
  506. def prepare(self, reactor, clock, homeserver):
  507. class Authenticator(object):
  508. def authenticate_request(self, request, content):
  509. return succeed("other.example.com")
  510. ratelimiter = FederationRateLimiter(
  511. clock,
  512. FederationRateLimitConfig(
  513. window_size=1,
  514. sleep_limit=1,
  515. sleep_msec=1,
  516. reject_limit=1000,
  517. concurrent_requests=1000,
  518. ),
  519. )
  520. federation_server.register_servlets(
  521. homeserver, self.resource, Authenticator(), ratelimiter
  522. )
  523. return super().prepare(reactor, clock, homeserver)
  524. def override_config(extra_config):
  525. """A decorator which can be applied to test functions to give additional HS config
  526. For use
  527. For example:
  528. class MyTestCase(HomeserverTestCase):
  529. @override_config({"enable_registration": False, ...})
  530. def test_foo(self):
  531. ...
  532. Args:
  533. extra_config(dict): Additional config settings to be merged into the default
  534. config dict before instantiating the test homeserver.
  535. """
  536. def decorator(func):
  537. func._extra_config = extra_config
  538. return func
  539. return decorator