server.py 36 KB

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