server.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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 ISynapseReactor, 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. # ISynapseReactor implies IReactorPluggableNameResolver, but explicitly
  336. # marking this as an implementer of the latter seems to keep mypy-zope happier.
  337. @implementer(IReactorPluggableNameResolver, ISynapseReactor)
  338. class ThreadedMemoryReactorClock(MemoryReactorClock):
  339. """
  340. A MemoryReactorClock that supports callFromThread.
  341. """
  342. def __init__(self):
  343. self.threadpool = ThreadPool(self)
  344. self._tcp_callbacks: Dict[Tuple[str, int], Callable] = {}
  345. self._udp = []
  346. self.lookups: Dict[str, str] = {}
  347. self._thread_callbacks: Deque[Callable[[], None]] = deque()
  348. lookups = self.lookups
  349. @implementer(IResolverSimple)
  350. class FakeResolver:
  351. def getHostByName(self, name, timeout=None):
  352. if name not in lookups:
  353. return fail(DNSLookupError("OH NO: unknown %s" % (name,)))
  354. return succeed(lookups[name])
  355. self.nameResolver = SimpleResolverComplexifier(FakeResolver())
  356. super().__init__()
  357. def installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver:
  358. raise NotImplementedError()
  359. def listenUDP(self, port, protocol, interface="", maxPacketSize=8196):
  360. p = udp.Port(port, protocol, interface, maxPacketSize, self)
  361. p.startListening()
  362. self._udp.append(p)
  363. return p
  364. def callFromThread(self, callback, *args, **kwargs):
  365. """
  366. Make the callback fire in the next reactor iteration.
  367. """
  368. cb = lambda: callback(*args, **kwargs)
  369. # it's not safe to call callLater() here, so we append the callback to a
  370. # separate queue.
  371. self._thread_callbacks.append(cb)
  372. def getThreadPool(self):
  373. return self.threadpool
  374. def add_tcp_client_callback(self, host: str, port: int, callback: Callable):
  375. """Add a callback that will be invoked when we receive a connection
  376. attempt to the given IP/port using `connectTCP`.
  377. Note that the callback gets run before we return the connection to the
  378. client, which means callbacks cannot block while waiting for writes.
  379. """
  380. self._tcp_callbacks[(host, port)] = callback
  381. def connectTCP(self, host: str, port: int, factory, timeout=30, bindAddress=None):
  382. """Fake L{IReactorTCP.connectTCP}."""
  383. conn = super().connectTCP(
  384. host, port, factory, timeout=timeout, bindAddress=None
  385. )
  386. callback = self._tcp_callbacks.get((host, port))
  387. if callback:
  388. callback()
  389. return conn
  390. def advance(self, amount):
  391. # first advance our reactor's time, and run any "callLater" callbacks that
  392. # makes ready
  393. super().advance(amount)
  394. # now run any "callFromThread" callbacks
  395. while True:
  396. try:
  397. callback = self._thread_callbacks.popleft()
  398. except IndexError:
  399. break
  400. callback()
  401. # check for more "callLater" callbacks added by the thread callback
  402. # This isn't required in a regular reactor, but it ends up meaning that
  403. # our database queries can complete in a single call to `advance` [1] which
  404. # simplifies tests.
  405. #
  406. # [1]: we replace the threadpool backing the db connection pool with a
  407. # mock ThreadPool which doesn't really use threads; but we still use
  408. # reactor.callFromThread to feed results back from the db functions to the
  409. # main thread.
  410. super().advance(0)
  411. class ThreadPool:
  412. """
  413. Threadless thread pool.
  414. """
  415. def __init__(self, reactor):
  416. self._reactor = reactor
  417. def start(self):
  418. pass
  419. def stop(self):
  420. pass
  421. def callInThreadWithCallback(self, onResult, function, *args, **kwargs):
  422. def _(res):
  423. if isinstance(res, Failure):
  424. onResult(False, res)
  425. else:
  426. onResult(True, res)
  427. d = Deferred()
  428. d.addCallback(lambda x: function(*args, **kwargs))
  429. d.addBoth(_)
  430. self._reactor.callLater(0, d.callback, True)
  431. return d
  432. def _make_test_homeserver_synchronous(server: HomeServer) -> None:
  433. """
  434. Make the given test homeserver's database interactions synchronous.
  435. """
  436. clock = server.get_clock()
  437. for database in server.get_datastores().databases:
  438. pool = database._db_pool
  439. def runWithConnection(func, *args, **kwargs):
  440. return threads.deferToThreadPool(
  441. pool._reactor,
  442. pool.threadpool,
  443. pool._runWithConnection,
  444. func,
  445. *args,
  446. **kwargs,
  447. )
  448. def runInteraction(interaction, *args, **kwargs):
  449. return threads.deferToThreadPool(
  450. pool._reactor,
  451. pool.threadpool,
  452. pool._runInteraction,
  453. interaction,
  454. *args,
  455. **kwargs,
  456. )
  457. pool.runWithConnection = runWithConnection
  458. pool.runInteraction = runInteraction
  459. # Replace the thread pool with a threadless 'thread' pool
  460. pool.threadpool = ThreadPool(clock._reactor)
  461. pool.running = True
  462. # We've just changed the Databases to run DB transactions on the same
  463. # thread, so we need to disable the dedicated thread behaviour.
  464. server.get_datastores().main.USE_DEDICATED_DB_THREADS_FOR_EVENT_FETCHING = False
  465. def get_clock() -> Tuple[ThreadedMemoryReactorClock, Clock]:
  466. clock = ThreadedMemoryReactorClock()
  467. hs_clock = Clock(clock)
  468. return clock, hs_clock
  469. @implementer(ITransport)
  470. @attr.s(cmp=False)
  471. class FakeTransport:
  472. """
  473. A twisted.internet.interfaces.ITransport implementation which sends all its data
  474. straight into an IProtocol object: it exists to connect two IProtocols together.
  475. To use it, instantiate it with the receiving IProtocol, and then pass it to the
  476. sending IProtocol's makeConnection method:
  477. server = HTTPChannel()
  478. client.makeConnection(FakeTransport(server, self.reactor))
  479. If you want bidirectional communication, you'll need two instances.
  480. """
  481. other = attr.ib()
  482. """The Protocol object which will receive any data written to this transport.
  483. :type: twisted.internet.interfaces.IProtocol
  484. """
  485. _reactor = attr.ib()
  486. """Test reactor
  487. :type: twisted.internet.interfaces.IReactorTime
  488. """
  489. _protocol = attr.ib(default=None)
  490. """The Protocol which is producing data for this transport. Optional, but if set
  491. will get called back for connectionLost() notifications etc.
  492. """
  493. _peer_address: Optional[IAddress] = attr.ib(default=None)
  494. """The value to be returned by getPeer"""
  495. _host_address: Optional[IAddress] = attr.ib(default=None)
  496. """The value to be returned by getHost"""
  497. disconnecting = False
  498. disconnected = False
  499. connected = True
  500. buffer = attr.ib(default=b"")
  501. producer = attr.ib(default=None)
  502. autoflush = attr.ib(default=True)
  503. def getPeer(self) -> Optional[IAddress]:
  504. return self._peer_address
  505. def getHost(self) -> Optional[IAddress]:
  506. return self._host_address
  507. def loseConnection(self, reason=None):
  508. if not self.disconnecting:
  509. logger.info("FakeTransport: loseConnection(%s)", reason)
  510. self.disconnecting = True
  511. if self._protocol:
  512. self._protocol.connectionLost(reason)
  513. # if we still have data to write, delay until that is done
  514. if self.buffer:
  515. logger.info(
  516. "FakeTransport: Delaying disconnect until buffer is flushed"
  517. )
  518. else:
  519. self.connected = False
  520. self.disconnected = True
  521. def abortConnection(self):
  522. logger.info("FakeTransport: abortConnection()")
  523. if not self.disconnecting:
  524. self.disconnecting = True
  525. if self._protocol:
  526. self._protocol.connectionLost(None)
  527. self.disconnected = True
  528. def pauseProducing(self):
  529. if not self.producer:
  530. return
  531. self.producer.pauseProducing()
  532. def resumeProducing(self):
  533. if not self.producer:
  534. return
  535. self.producer.resumeProducing()
  536. def unregisterProducer(self):
  537. if not self.producer:
  538. return
  539. self.producer = None
  540. def registerProducer(self, producer, streaming):
  541. self.producer = producer
  542. self.producerStreaming = streaming
  543. def _produce():
  544. if not self.producer:
  545. # we've been unregistered
  546. return
  547. # some implementations of IProducer (for example, FileSender)
  548. # don't return a deferred.
  549. d = maybeDeferred(self.producer.resumeProducing)
  550. d.addCallback(lambda x: self._reactor.callLater(0.1, _produce))
  551. if not streaming:
  552. self._reactor.callLater(0.0, _produce)
  553. def write(self, byt):
  554. if self.disconnecting:
  555. raise Exception("Writing to disconnecting FakeTransport")
  556. self.buffer = self.buffer + byt
  557. # always actually do the write asynchronously. Some protocols (notably the
  558. # TLSMemoryBIOProtocol) get very confused if a read comes back while they are
  559. # still doing a write. Doing a callLater here breaks the cycle.
  560. if self.autoflush:
  561. self._reactor.callLater(0.0, self.flush)
  562. def writeSequence(self, seq):
  563. for x in seq:
  564. self.write(x)
  565. def flush(self, maxbytes=None):
  566. if not self.buffer:
  567. # nothing to do. Don't write empty buffers: it upsets the
  568. # TLSMemoryBIOProtocol
  569. return
  570. if self.disconnected:
  571. return
  572. if maxbytes is not None:
  573. to_write = self.buffer[:maxbytes]
  574. else:
  575. to_write = self.buffer
  576. logger.info("%s->%s: %s", self._protocol, self.other, to_write)
  577. try:
  578. self.other.dataReceived(to_write)
  579. except Exception as e:
  580. logger.exception("Exception writing to protocol: %s", e)
  581. return
  582. self.buffer = self.buffer[len(to_write) :]
  583. if self.buffer and self.autoflush:
  584. self._reactor.callLater(0.0, self.flush)
  585. if not self.buffer and self.disconnecting:
  586. logger.info("FakeTransport: Buffer now empty, completing disconnect")
  587. self.disconnected = True
  588. def connect_client(
  589. reactor: ThreadedMemoryReactorClock, client_id: int
  590. ) -> Tuple[IProtocol, AccumulatingProtocol]:
  591. """
  592. Connect a client to a fake TCP transport.
  593. Args:
  594. reactor
  595. factory: The connecting factory to build.
  596. """
  597. factory = reactor.tcpClients.pop(client_id)[2]
  598. client = factory.buildProtocol(None)
  599. server = AccumulatingProtocol()
  600. server.makeConnection(FakeTransport(client, reactor))
  601. client.makeConnection(FakeTransport(server, reactor))
  602. return client, server
  603. class TestHomeServer(HomeServer):
  604. DATASTORE_CLASS = DataStore
  605. def setup_test_homeserver(
  606. cleanup_func,
  607. name="test",
  608. config=None,
  609. reactor=None,
  610. homeserver_to_use: Type[HomeServer] = TestHomeServer,
  611. **kwargs,
  612. ):
  613. """
  614. Setup a homeserver suitable for running tests against. Keyword arguments
  615. are passed to the Homeserver constructor.
  616. If no datastore is supplied, one is created and given to the homeserver.
  617. Args:
  618. cleanup_func : The function used to register a cleanup routine for
  619. after the test.
  620. Calling this method directly is deprecated: you should instead derive from
  621. HomeserverTestCase.
  622. """
  623. if reactor is None:
  624. from twisted.internet import reactor
  625. if config is None:
  626. config = default_config(name, parse=True)
  627. config.caches.resize_all_caches()
  628. config.ldap_enabled = False
  629. if "clock" not in kwargs:
  630. kwargs["clock"] = MockClock()
  631. if USE_POSTGRES_FOR_TESTS:
  632. test_db = "synapse_test_%s" % uuid.uuid4().hex
  633. database_config = {
  634. "name": "psycopg2",
  635. "args": {
  636. "database": test_db,
  637. "host": POSTGRES_HOST,
  638. "password": POSTGRES_PASSWORD,
  639. "user": POSTGRES_USER,
  640. "port": POSTGRES_PORT,
  641. "cp_min": 1,
  642. "cp_max": 5,
  643. },
  644. }
  645. else:
  646. if SQLITE_PERSIST_DB:
  647. # The current working directory is in _trial_temp, so this gets created within that directory.
  648. test_db_location = os.path.abspath("test.db")
  649. logger.debug("Will persist db to %s", test_db_location)
  650. # Ensure each test gets a clean database.
  651. try:
  652. os.remove(test_db_location)
  653. except FileNotFoundError:
  654. pass
  655. else:
  656. logger.debug("Removed existing DB at %s", test_db_location)
  657. else:
  658. test_db_location = ":memory:"
  659. database_config = {
  660. "name": "sqlite3",
  661. "args": {"database": test_db_location, "cp_min": 1, "cp_max": 1},
  662. }
  663. if "db_txn_limit" in kwargs:
  664. database_config["txn_limit"] = kwargs["db_txn_limit"]
  665. database = DatabaseConnectionConfig("master", database_config)
  666. config.database.databases = [database]
  667. db_engine = create_engine(database.config)
  668. # Create the database before we actually try and connect to it, based off
  669. # the template database we generate in setupdb()
  670. if isinstance(db_engine, PostgresEngine):
  671. db_conn = db_engine.module.connect(
  672. database=POSTGRES_BASE_DB,
  673. user=POSTGRES_USER,
  674. host=POSTGRES_HOST,
  675. port=POSTGRES_PORT,
  676. password=POSTGRES_PASSWORD,
  677. )
  678. db_conn.autocommit = True
  679. cur = db_conn.cursor()
  680. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  681. cur.execute(
  682. "CREATE DATABASE %s WITH TEMPLATE %s;" % (test_db, POSTGRES_BASE_DB)
  683. )
  684. cur.close()
  685. db_conn.close()
  686. hs = homeserver_to_use(
  687. name,
  688. config=config,
  689. version_string="Synapse/tests",
  690. reactor=reactor,
  691. )
  692. # Install @cache_in_self attributes
  693. for key, val in kwargs.items():
  694. setattr(hs, "_" + key, val)
  695. # Mock TLS
  696. hs.tls_server_context_factory = Mock()
  697. hs.setup()
  698. if homeserver_to_use == TestHomeServer:
  699. hs.setup_background_tasks()
  700. if isinstance(db_engine, PostgresEngine):
  701. database = hs.get_datastores().databases[0]
  702. # We need to do cleanup on PostgreSQL
  703. def cleanup():
  704. import psycopg2
  705. # Close all the db pools
  706. database._db_pool.close()
  707. dropped = False
  708. # Drop the test database
  709. db_conn = db_engine.module.connect(
  710. database=POSTGRES_BASE_DB,
  711. user=POSTGRES_USER,
  712. host=POSTGRES_HOST,
  713. port=POSTGRES_PORT,
  714. password=POSTGRES_PASSWORD,
  715. )
  716. db_conn.autocommit = True
  717. cur = db_conn.cursor()
  718. # Try a few times to drop the DB. Some things may hold on to the
  719. # database for a few more seconds due to flakiness, preventing
  720. # us from dropping it when the test is over. If we can't drop
  721. # it, warn and move on.
  722. for _ in range(5):
  723. try:
  724. cur.execute("DROP DATABASE IF EXISTS %s;" % (test_db,))
  725. db_conn.commit()
  726. dropped = True
  727. except psycopg2.OperationalError as e:
  728. warnings.warn(
  729. "Couldn't drop old db: " + str(e), category=UserWarning
  730. )
  731. time.sleep(0.5)
  732. cur.close()
  733. db_conn.close()
  734. if not dropped:
  735. warnings.warn("Failed to drop old DB.", category=UserWarning)
  736. if not LEAVE_DB:
  737. # Register the cleanup hook
  738. cleanup_func(cleanup)
  739. # bcrypt is far too slow to be doing in unit tests
  740. # Need to let the HS build an auth handler and then mess with it
  741. # because AuthHandler's constructor requires the HS, so we can't make one
  742. # beforehand and pass it in to the HS's constructor (chicken / egg)
  743. async def hash(p):
  744. return hashlib.md5(p.encode("utf8")).hexdigest()
  745. hs.get_auth_handler().hash = hash
  746. async def validate_hash(p, h):
  747. return hashlib.md5(p.encode("utf8")).hexdigest() == h
  748. hs.get_auth_handler().validate_hash = validate_hash
  749. # Make the threadpool and database transactions synchronous for testing.
  750. _make_test_homeserver_synchronous(hs)
  751. # Load any configured modules into the homeserver
  752. module_api = hs.get_module_api()
  753. for module, config in hs.config.modules.loaded_modules:
  754. module(config=config, api=module_api)
  755. load_legacy_spam_checkers(hs)
  756. load_legacy_third_party_event_rules(hs)
  757. load_legacy_presence_router(hs)
  758. load_legacy_password_auth_providers(hs)
  759. return hs