server.py 29 KB

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