server.py 33 KB

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