server.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. # Copyright 2018-2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import hashlib
  15. import json
  16. import logging
  17. import os
  18. import os.path
  19. import time
  20. import uuid
  21. import warnings
  22. from collections import deque
  23. from io import SEEK_END, BytesIO
  24. from typing import (
  25. Callable,
  26. Dict,
  27. Iterable,
  28. MutableMapping,
  29. Optional,
  30. Tuple,
  31. Type,
  32. Union,
  33. )
  34. from unittest.mock import Mock
  35. import attr
  36. from typing_extensions import Deque
  37. from zope.interface import implementer
  38. from twisted.internet import address, threads, udp
  39. from twisted.internet._resolver import SimpleResolverComplexifier
  40. from twisted.internet.defer import Deferred, fail, maybeDeferred, succeed
  41. from twisted.internet.error import DNSLookupError
  42. from twisted.internet.interfaces import (
  43. IAddress,
  44. IConsumer,
  45. IHostnameResolver,
  46. IProtocol,
  47. IPullProducer,
  48. IPushProducer,
  49. IReactorPluggableNameResolver,
  50. IReactorTime,
  51. IResolverSimple,
  52. ITransport,
  53. )
  54. from twisted.python.failure import Failure
  55. from twisted.test.proto_helpers import AccumulatingProtocol, MemoryReactorClock
  56. from twisted.web.http_headers import Headers
  57. from twisted.web.resource import IResource
  58. from twisted.web.server import Request, Site
  59. from synapse.config.database import DatabaseConnectionConfig
  60. from synapse.http.site import SynapseRequest
  61. from synapse.logging.context import ContextResourceUsage
  62. from synapse.server import HomeServer
  63. from synapse.storage import DataStore
  64. from synapse.storage.engines import PostgresEngine, create_engine
  65. from synapse.types import JsonDict
  66. from synapse.util import Clock
  67. from tests.utils import (
  68. LEAVE_DB,
  69. POSTGRES_BASE_DB,
  70. POSTGRES_HOST,
  71. POSTGRES_PASSWORD,
  72. POSTGRES_PORT,
  73. POSTGRES_USER,
  74. SQLITE_PERSIST_DB,
  75. USE_POSTGRES_FOR_TESTS,
  76. MockClock,
  77. default_config,
  78. )
  79. logger = logging.getLogger(__name__)
  80. # the type of thing that can be passed into `make_request` in the headers list
  81. CustomHeaderType = Tuple[Union[str, bytes], Union[str, bytes]]
  82. class TimedOutException(Exception):
  83. """
  84. A web query timed out.
  85. """
  86. @implementer(IConsumer)
  87. @attr.s(auto_attribs=True)
  88. class FakeChannel:
  89. """
  90. A fake Twisted Web Channel (the part that interfaces with the
  91. wire).
  92. """
  93. site: Union[Site, "FakeSite"]
  94. _reactor: MemoryReactorClock
  95. result: dict = attr.Factory(dict)
  96. _ip: str = "127.0.0.1"
  97. _producer: Optional[Union[IPullProducer, IPushProducer]] = None
  98. resource_usage: Optional[ContextResourceUsage] = None
  99. _request: Optional[Request] = None
  100. @property
  101. def request(self) -> Request:
  102. assert self._request is not None
  103. return self._request
  104. @request.setter
  105. def request(self, request: Request) -> None:
  106. assert self._request is None
  107. self._request = request
  108. @property
  109. def json_body(self) -> JsonDict:
  110. return json.loads(self.text_body)
  111. @property
  112. def text_body(self) -> str:
  113. """The body of the result, utf-8-decoded.
  114. Raises an exception if the request has not yet completed.
  115. """
  116. if not self.is_finished:
  117. raise Exception("Request not yet completed")
  118. return self.result["body"].decode("utf8")
  119. def is_finished(self) -> bool:
  120. """check if the response has been completely received"""
  121. return self.result.get("done", False)
  122. @property
  123. def code(self) -> int:
  124. if not self.result:
  125. raise Exception("No result yet.")
  126. return int(self.result["code"])
  127. @property
  128. def headers(self) -> Headers:
  129. if not self.result:
  130. raise Exception("No result yet.")
  131. h = Headers()
  132. for i in self.result["headers"]:
  133. h.addRawHeader(*i)
  134. return h
  135. def writeHeaders(self, version, code, reason, headers):
  136. self.result["version"] = version
  137. self.result["code"] = code
  138. self.result["reason"] = reason
  139. self.result["headers"] = headers
  140. def write(self, content: bytes) -> None:
  141. assert isinstance(content, bytes), "Should be bytes! " + repr(content)
  142. if "body" not in self.result:
  143. self.result["body"] = b""
  144. self.result["body"] += content
  145. # Type ignore: mypy doesn't like the fact that producer isn't an IProducer.
  146. def registerProducer( # type: ignore[override]
  147. self,
  148. producer: Union[IPullProducer, IPushProducer],
  149. streaming: bool,
  150. ) -> None:
  151. self._producer = producer
  152. self.producerStreaming = streaming
  153. def _produce() -> None:
  154. if self._producer:
  155. self._producer.resumeProducing()
  156. self._reactor.callLater(0.1, _produce)
  157. if not streaming:
  158. self._reactor.callLater(0.0, _produce)
  159. def unregisterProducer(self) -> None:
  160. if self._producer is None:
  161. return
  162. self._producer = None
  163. def requestDone(self, _self: Request) -> None:
  164. self.result["done"] = True
  165. if isinstance(_self, SynapseRequest):
  166. assert _self.logcontext is not None
  167. self.resource_usage = _self.logcontext.get_resource_usage()
  168. def getPeer(self) -> IAddress:
  169. # We give an address so that getClientAddress/getClientIP returns a non null entry,
  170. # causing us to record the MAU
  171. return address.IPv4Address("TCP", self._ip, 3423)
  172. def getHost(self) -> IAddress:
  173. # this is called by Request.__init__ to configure Request.host.
  174. return address.IPv4Address("TCP", "127.0.0.1", 8888)
  175. def isSecure(self) -> bool:
  176. return False
  177. @property
  178. def transport(self) -> "FakeChannel":
  179. return self
  180. def await_result(self, timeout_ms: int = 1000) -> None:
  181. """
  182. Wait until the request is finished.
  183. """
  184. end_time = self._reactor.seconds() + timeout_ms / 1000.0
  185. self._reactor.run()
  186. while not self.is_finished():
  187. # If there's a producer, tell it to resume producing so we get content
  188. if self._producer:
  189. self._producer.resumeProducing()
  190. if self._reactor.seconds() > end_time:
  191. raise TimedOutException("Timed out waiting for request to finish.")
  192. self._reactor.advance(0.1)
  193. def extract_cookies(self, cookies: MutableMapping[str, str]) -> None:
  194. """Process the contents of any Set-Cookie headers in the response
  195. Any cookines found are added to the given dict
  196. """
  197. headers = self.headers.getRawHeaders("Set-Cookie")
  198. if not headers:
  199. return
  200. for h in headers:
  201. parts = h.split(";")
  202. k, v = parts[0].split("=", maxsplit=1)
  203. cookies[k] = v
  204. class FakeSite:
  205. """
  206. A fake Twisted Web Site, with mocks of the extra things that
  207. Synapse adds.
  208. """
  209. server_version_string = b"1"
  210. site_tag = "test"
  211. access_logger = logging.getLogger("synapse.access.http.fake")
  212. def __init__(self, resource: IResource, reactor: IReactorTime):
  213. """
  214. Args:
  215. resource: the resource to be used for rendering all requests
  216. """
  217. self._resource = resource
  218. self.reactor = reactor
  219. def getResourceFor(self, request):
  220. return self._resource
  221. def make_request(
  222. reactor,
  223. site: Union[Site, FakeSite],
  224. method: Union[bytes, str],
  225. path: Union[bytes, str],
  226. content: Union[bytes, str, JsonDict] = b"",
  227. access_token: Optional[str] = None,
  228. request: Type[Request] = SynapseRequest,
  229. shorthand: bool = True,
  230. federation_auth_origin: Optional[bytes] = None,
  231. content_is_form: bool = False,
  232. await_result: bool = True,
  233. custom_headers: Optional[Iterable[CustomHeaderType]] = None,
  234. client_ip: str = "127.0.0.1",
  235. ) -> FakeChannel:
  236. """
  237. Make a web request using the given method, path and content, and render it
  238. Returns the fake Channel object which records the response to the request.
  239. Args:
  240. reactor:
  241. site: The twisted Site to use to render the request
  242. method: The HTTP request method ("verb").
  243. path: The HTTP path, suitably URL encoded (e.g. escaped UTF-8 & spaces and such).
  244. content: The body of the request. JSON-encoded, if a str of bytes.
  245. access_token: The access token to add as authorization for the request.
  246. request: The request class to create.
  247. shorthand: Whether to try and be helpful and prefix the given URL
  248. with the usual REST API path, if it doesn't contain it.
  249. federation_auth_origin: if set to not-None, we will add a fake
  250. Authorization header pretenting to be the given server name.
  251. content_is_form: Whether the content is URL encoded form data. Adds the
  252. 'Content-Type': 'application/x-www-form-urlencoded' header.
  253. await_result: whether to wait for the request to complete rendering. If true,
  254. will pump the reactor until the the renderer tells the channel the request
  255. is finished.
  256. custom_headers: (name, value) pairs to add as request headers
  257. client_ip: The IP to use as the requesting IP. Useful for testing
  258. ratelimiting.
  259. Returns:
  260. channel
  261. """
  262. if not isinstance(method, bytes):
  263. method = method.encode("ascii")
  264. if not isinstance(path, bytes):
  265. path = path.encode("ascii")
  266. # Decorate it to be the full path, if we're using shorthand
  267. if (
  268. shorthand
  269. and not path.startswith(b"/_matrix")
  270. and not path.startswith(b"/_synapse")
  271. ):
  272. if path.startswith(b"/"):
  273. path = path[1:]
  274. path = b"/_matrix/client/r0/" + path
  275. if not path.startswith(b"/"):
  276. path = b"/" + path
  277. if isinstance(content, dict):
  278. content = json.dumps(content).encode("utf8")
  279. if isinstance(content, str):
  280. content = content.encode("utf8")
  281. channel = FakeChannel(site, reactor, ip=client_ip)
  282. req = request(channel, site)
  283. channel.request = req
  284. req.content = BytesIO(content)
  285. # Twisted expects to be at the end of the content when parsing the request.
  286. req.content.seek(0, SEEK_END)
  287. if access_token:
  288. req.requestHeaders.addRawHeader(
  289. b"Authorization", b"Bearer " + access_token.encode("ascii")
  290. )
  291. if federation_auth_origin is not None:
  292. req.requestHeaders.addRawHeader(
  293. b"Authorization",
  294. b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,),
  295. )
  296. if content:
  297. if content_is_form:
  298. req.requestHeaders.addRawHeader(
  299. b"Content-Type", b"application/x-www-form-urlencoded"
  300. )
  301. else:
  302. # Assume the body is JSON
  303. req.requestHeaders.addRawHeader(b"Content-Type", b"application/json")
  304. if custom_headers:
  305. for k, v in custom_headers:
  306. req.requestHeaders.addRawHeader(k, v)
  307. req.parseCookies()
  308. req.requestReceived(method, path, b"1.1")
  309. if await_result:
  310. channel.await_result()
  311. return channel
  312. @implementer(IReactorPluggableNameResolver)
  313. class ThreadedMemoryReactorClock(MemoryReactorClock):
  314. """
  315. A MemoryReactorClock that supports callFromThread.
  316. """
  317. def __init__(self):
  318. self.threadpool = ThreadPool(self)
  319. self._tcp_callbacks: Dict[Tuple[str, int], Callable] = {}
  320. self._udp = []
  321. self.lookups: Dict[str, str] = {}
  322. self._thread_callbacks: Deque[Callable[[], None]] = deque()
  323. lookups = self.lookups
  324. @implementer(IResolverSimple)
  325. class FakeResolver:
  326. def getHostByName(self, name, timeout=None):
  327. if name not in lookups:
  328. return fail(DNSLookupError("OH NO: unknown %s" % (name,)))
  329. return succeed(lookups[name])
  330. self.nameResolver = SimpleResolverComplexifier(FakeResolver())
  331. super().__init__()
  332. def installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver:
  333. raise NotImplementedError()
  334. def listenUDP(self, port, protocol, interface="", maxPacketSize=8196):
  335. p = udp.Port(port, protocol, interface, maxPacketSize, self)
  336. p.startListening()
  337. self._udp.append(p)
  338. return p
  339. def callFromThread(self, callback, *args, **kwargs):
  340. """
  341. Make the callback fire in the next reactor iteration.
  342. """
  343. cb = lambda: callback(*args, **kwargs)
  344. # it's not safe to call callLater() here, so we append the callback to a
  345. # separate queue.
  346. self._thread_callbacks.append(cb)
  347. def getThreadPool(self):
  348. return self.threadpool
  349. def add_tcp_client_callback(self, host: str, port: int, callback: Callable):
  350. """Add a callback that will be invoked when we receive a connection
  351. attempt to the given IP/port using `connectTCP`.
  352. Note that the callback gets run before we return the connection to the
  353. client, which means callbacks cannot block while waiting for writes.
  354. """
  355. self._tcp_callbacks[(host, port)] = callback
  356. def connectTCP(self, host: str, port: int, factory, timeout=30, bindAddress=None):
  357. """Fake L{IReactorTCP.connectTCP}."""
  358. conn = super().connectTCP(
  359. host, port, factory, timeout=timeout, bindAddress=None
  360. )
  361. callback = self._tcp_callbacks.get((host, port))
  362. if callback:
  363. callback()
  364. return conn
  365. def advance(self, amount):
  366. # first advance our reactor's time, and run any "callLater" callbacks that
  367. # makes ready
  368. super().advance(amount)
  369. # now run any "callFromThread" callbacks
  370. while True:
  371. try:
  372. callback = self._thread_callbacks.popleft()
  373. except IndexError:
  374. break
  375. callback()
  376. # check for more "callLater" callbacks added by the thread callback
  377. # This isn't required in a regular reactor, but it ends up meaning that
  378. # our database queries can complete in a single call to `advance` [1] which
  379. # simplifies tests.
  380. #
  381. # [1]: we replace the threadpool backing the db connection pool with a
  382. # mock ThreadPool which doesn't really use threads; but we still use
  383. # reactor.callFromThread to feed results back from the db functions to the
  384. # main thread.
  385. super().advance(0)
  386. class ThreadPool:
  387. """
  388. Threadless thread pool.
  389. """
  390. def __init__(self, reactor):
  391. self._reactor = reactor
  392. def start(self):
  393. pass
  394. def stop(self):
  395. pass
  396. def callInThreadWithCallback(self, onResult, function, *args, **kwargs):
  397. def _(res):
  398. if isinstance(res, Failure):
  399. onResult(False, res)
  400. else:
  401. onResult(True, res)
  402. d = Deferred()
  403. d.addCallback(lambda x: function(*args, **kwargs))
  404. d.addBoth(_)
  405. self._reactor.callLater(0, d.callback, True)
  406. return d
  407. def _make_test_homeserver_synchronous(server: HomeServer) -> None:
  408. """
  409. Make the given test homeserver's database interactions synchronous.
  410. """
  411. clock = server.get_clock()
  412. for database in server.get_datastores().databases:
  413. pool = database._db_pool
  414. def runWithConnection(func, *args, **kwargs):
  415. return threads.deferToThreadPool(
  416. pool._reactor,
  417. pool.threadpool,
  418. pool._runWithConnection,
  419. func,
  420. *args,
  421. **kwargs,
  422. )
  423. def runInteraction(interaction, *args, **kwargs):
  424. return threads.deferToThreadPool(
  425. pool._reactor,
  426. pool.threadpool,
  427. pool._runInteraction,
  428. interaction,
  429. *args,
  430. **kwargs,
  431. )
  432. pool.runWithConnection = runWithConnection
  433. pool.runInteraction = runInteraction
  434. # Replace the thread pool with a threadless 'thread' pool
  435. pool.threadpool = ThreadPool(clock._reactor)
  436. pool.running = True
  437. # We've just changed the Databases to run DB transactions on the same
  438. # thread, so we need to disable the dedicated thread behaviour.
  439. server.get_datastores().main.USE_DEDICATED_DB_THREADS_FOR_EVENT_FETCHING = False
  440. def get_clock() -> Tuple[ThreadedMemoryReactorClock, Clock]:
  441. clock = ThreadedMemoryReactorClock()
  442. hs_clock = Clock(clock)
  443. return clock, hs_clock
  444. @implementer(ITransport)
  445. @attr.s(cmp=False)
  446. class FakeTransport:
  447. """
  448. A twisted.internet.interfaces.ITransport implementation which sends all its data
  449. straight into an IProtocol object: it exists to connect two IProtocols together.
  450. To use it, instantiate it with the receiving IProtocol, and then pass it to the
  451. sending IProtocol's makeConnection method:
  452. server = HTTPChannel()
  453. client.makeConnection(FakeTransport(server, self.reactor))
  454. If you want bidirectional communication, you'll need two instances.
  455. """
  456. other = attr.ib()
  457. """The Protocol object which will receive any data written to this transport.
  458. :type: twisted.internet.interfaces.IProtocol
  459. """
  460. _reactor = attr.ib()
  461. """Test reactor
  462. :type: twisted.internet.interfaces.IReactorTime
  463. """
  464. _protocol = attr.ib(default=None)
  465. """The Protocol which is producing data for this transport. Optional, but if set
  466. will get called back for connectionLost() notifications etc.
  467. """
  468. _peer_address: Optional[IAddress] = attr.ib(default=None)
  469. """The value to be returned by getPeer"""
  470. _host_address: Optional[IAddress] = attr.ib(default=None)
  471. """The value to be returned by getHost"""
  472. disconnecting = False
  473. disconnected = False
  474. connected = True
  475. buffer = attr.ib(default=b"")
  476. producer = attr.ib(default=None)
  477. autoflush = attr.ib(default=True)
  478. def getPeer(self) -> Optional[IAddress]:
  479. return self._peer_address
  480. def getHost(self) -> Optional[IAddress]:
  481. return self._host_address
  482. def loseConnection(self, reason=None):
  483. if not self.disconnecting:
  484. logger.info("FakeTransport: loseConnection(%s)", reason)
  485. self.disconnecting = True
  486. if self._protocol:
  487. self._protocol.connectionLost(reason)
  488. # if we still have data to write, delay until that is done
  489. if self.buffer:
  490. logger.info(
  491. "FakeTransport: Delaying disconnect until buffer is flushed"
  492. )
  493. else:
  494. self.connected = False
  495. self.disconnected = True
  496. def abortConnection(self):
  497. logger.info("FakeTransport: abortConnection()")
  498. if not self.disconnecting:
  499. self.disconnecting = True
  500. if self._protocol:
  501. self._protocol.connectionLost(None)
  502. self.disconnected = True
  503. def pauseProducing(self):
  504. if not self.producer:
  505. return
  506. self.producer.pauseProducing()
  507. def resumeProducing(self):
  508. if not self.producer:
  509. return
  510. self.producer.resumeProducing()
  511. def unregisterProducer(self):
  512. if not self.producer:
  513. return
  514. self.producer = None
  515. def registerProducer(self, producer, streaming):
  516. self.producer = producer
  517. self.producerStreaming = streaming
  518. def _produce():
  519. if not self.producer:
  520. # we've been unregistered
  521. return
  522. # some implementations of IProducer (for example, FileSender)
  523. # don't return a deferred.
  524. d = maybeDeferred(self.producer.resumeProducing)
  525. d.addCallback(lambda x: self._reactor.callLater(0.1, _produce))
  526. if not streaming:
  527. self._reactor.callLater(0.0, _produce)
  528. def write(self, byt):
  529. if self.disconnecting:
  530. raise Exception("Writing to disconnecting FakeTransport")
  531. self.buffer = self.buffer + byt
  532. # always actually do the write asynchronously. Some protocols (notably the
  533. # TLSMemoryBIOProtocol) get very confused if a read comes back while they are
  534. # still doing a write. Doing a callLater here breaks the cycle.
  535. if self.autoflush:
  536. self._reactor.callLater(0.0, self.flush)
  537. def writeSequence(self, seq):
  538. for x in seq:
  539. self.write(x)
  540. def flush(self, maxbytes=None):
  541. if not self.buffer:
  542. # nothing to do. Don't write empty buffers: it upsets the
  543. # TLSMemoryBIOProtocol
  544. return
  545. if self.disconnected:
  546. return
  547. if maxbytes is not None:
  548. to_write = self.buffer[:maxbytes]
  549. else:
  550. to_write = self.buffer
  551. logger.info("%s->%s: %s", self._protocol, self.other, to_write)
  552. try:
  553. self.other.dataReceived(to_write)
  554. except Exception as e:
  555. logger.exception("Exception writing to protocol: %s", e)
  556. return
  557. self.buffer = self.buffer[len(to_write) :]
  558. if self.buffer and self.autoflush:
  559. self._reactor.callLater(0.0, self.flush)
  560. if not self.buffer and self.disconnecting:
  561. logger.info("FakeTransport: Buffer now empty, completing disconnect")
  562. self.disconnected = True
  563. def connect_client(
  564. reactor: ThreadedMemoryReactorClock, client_id: int
  565. ) -> Tuple[IProtocol, AccumulatingProtocol]:
  566. """
  567. Connect a client to a fake TCP transport.
  568. Args:
  569. reactor
  570. factory: The connecting factory to build.
  571. """
  572. factory = reactor.tcpClients.pop(client_id)[2]
  573. client = factory.buildProtocol(None)
  574. server = AccumulatingProtocol()
  575. server.makeConnection(FakeTransport(client, reactor))
  576. client.makeConnection(FakeTransport(server, reactor))
  577. return client, server
  578. class TestHomeServer(HomeServer):
  579. DATASTORE_CLASS = DataStore
  580. def setup_test_homeserver(
  581. cleanup_func,
  582. name="test",
  583. config=None,
  584. reactor=None,
  585. homeserver_to_use: Type[HomeServer] = TestHomeServer,
  586. **kwargs,
  587. ):
  588. """
  589. Setup a homeserver suitable for running tests against. Keyword arguments
  590. are passed to the Homeserver constructor.
  591. If no datastore is supplied, one is created and given to the homeserver.
  592. Args:
  593. cleanup_func : The function used to register a cleanup routine for
  594. after the test.
  595. Calling this method directly is deprecated: you should instead derive from
  596. HomeserverTestCase.
  597. """
  598. if reactor is None:
  599. from twisted.internet import reactor
  600. if config is None:
  601. config = default_config(name, parse=True)
  602. config.caches.resize_all_caches()
  603. config.ldap_enabled = False
  604. if "clock" not in kwargs:
  605. kwargs["clock"] = MockClock()
  606. if USE_POSTGRES_FOR_TESTS:
  607. test_db = "synapse_test_%s" % uuid.uuid4().hex
  608. database_config = {
  609. "name": "psycopg2",
  610. "args": {
  611. "database": test_db,
  612. "host": POSTGRES_HOST,
  613. "password": POSTGRES_PASSWORD,
  614. "user": POSTGRES_USER,
  615. "port": POSTGRES_PORT,
  616. "cp_min": 1,
  617. "cp_max": 5,
  618. },
  619. }
  620. else:
  621. if SQLITE_PERSIST_DB:
  622. # The current working directory is in _trial_temp, so this gets created within that directory.
  623. test_db_location = os.path.abspath("test.db")
  624. logger.debug("Will persist db to %s", test_db_location)
  625. # Ensure each test gets a clean database.
  626. try:
  627. os.remove(test_db_location)
  628. except FileNotFoundError:
  629. pass
  630. else:
  631. logger.debug("Removed existing DB at %s", test_db_location)
  632. else:
  633. test_db_location = ":memory:"
  634. database_config = {
  635. "name": "sqlite3",
  636. "args": {"database": test_db_location, "cp_min": 1, "cp_max": 1},
  637. }
  638. if "db_txn_limit" in kwargs:
  639. database_config["txn_limit"] = kwargs["db_txn_limit"]
  640. database = DatabaseConnectionConfig("master", database_config)
  641. config.database.databases = [database]
  642. db_engine = create_engine(database.config)
  643. # Create the database before we actually try and connect to it, based off
  644. # the template database we generate in setupdb()
  645. if isinstance(db_engine, PostgresEngine):
  646. db_conn = db_engine.module.connect(
  647. database=POSTGRES_BASE_DB,
  648. user=POSTGRES_USER,
  649. host=POSTGRES_HOST,
  650. port=POSTGRES_PORT,
  651. password=POSTGRES_PASSWORD,
  652. )
  653. db_conn.autocommit = True
  654. cur = db_conn.cursor()
  655. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  656. cur.execute(
  657. "CREATE DATABASE %s WITH TEMPLATE %s;" % (test_db, POSTGRES_BASE_DB)
  658. )
  659. cur.close()
  660. db_conn.close()
  661. hs = homeserver_to_use(
  662. name,
  663. config=config,
  664. version_string="Synapse/tests",
  665. reactor=reactor,
  666. )
  667. # Install @cache_in_self attributes
  668. for key, val in kwargs.items():
  669. setattr(hs, "_" + key, val)
  670. # Mock TLS
  671. hs.tls_server_context_factory = Mock()
  672. hs.setup()
  673. if homeserver_to_use == TestHomeServer:
  674. hs.setup_background_tasks()
  675. if isinstance(db_engine, PostgresEngine):
  676. database = hs.get_datastores().databases[0]
  677. # We need to do cleanup on PostgreSQL
  678. def cleanup():
  679. import psycopg2
  680. # Close all the db pools
  681. database._db_pool.close()
  682. dropped = False
  683. # Drop the test database
  684. db_conn = db_engine.module.connect(
  685. database=POSTGRES_BASE_DB,
  686. user=POSTGRES_USER,
  687. host=POSTGRES_HOST,
  688. port=POSTGRES_PORT,
  689. password=POSTGRES_PASSWORD,
  690. )
  691. db_conn.autocommit = True
  692. cur = db_conn.cursor()
  693. # Try a few times to drop the DB. Some things may hold on to the
  694. # database for a few more seconds due to flakiness, preventing
  695. # us from dropping it when the test is over. If we can't drop
  696. # it, warn and move on.
  697. for _ in range(5):
  698. try:
  699. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  700. db_conn.commit()
  701. dropped = True
  702. except psycopg2.OperationalError as e:
  703. warnings.warn(
  704. "Couldn't drop old db: " + str(e), category=UserWarning
  705. )
  706. time.sleep(0.5)
  707. cur.close()
  708. db_conn.close()
  709. if not dropped:
  710. warnings.warn("Failed to drop old DB.", category=UserWarning)
  711. if not LEAVE_DB:
  712. # Register the cleanup hook
  713. cleanup_func(cleanup)
  714. # bcrypt is far too slow to be doing in unit tests
  715. # Need to let the HS build an auth handler and then mess with it
  716. # because AuthHandler's constructor requires the HS, so we can't make one
  717. # beforehand and pass it in to the HS's constructor (chicken / egg)
  718. async def hash(p):
  719. return hashlib.md5(p.encode("utf8")).hexdigest()
  720. hs.get_auth_handler().hash = hash
  721. async def validate_hash(p, h):
  722. return hashlib.md5(p.encode("utf8")).hexdigest() == h
  723. hs.get_auth_handler().validate_hash = validate_hash
  724. # Make the threadpool and database transactions synchronous for testing.
  725. _make_test_homeserver_synchronous(hs)
  726. return hs