Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1089 lignes
34 KiB

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