server.py 29 KB

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