You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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