1
0

unittest.py 22 KB

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