server.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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 json
  15. import logging
  16. from collections import deque
  17. from io import SEEK_END, BytesIO
  18. from typing import Callable, Dict, Iterable, MutableMapping, Optional, Tuple, Union
  19. import attr
  20. from typing_extensions import Deque
  21. from zope.interface import implementer
  22. from twisted.internet import address, threads, udp
  23. from twisted.internet._resolver import SimpleResolverComplexifier
  24. from twisted.internet.defer import Deferred, fail, maybeDeferred, succeed
  25. from twisted.internet.error import DNSLookupError
  26. from twisted.internet.interfaces import (
  27. IAddress,
  28. IHostnameResolver,
  29. IProtocol,
  30. IPullProducer,
  31. IPushProducer,
  32. IReactorPluggableNameResolver,
  33. IReactorTime,
  34. IResolverSimple,
  35. ITransport,
  36. )
  37. from twisted.python.failure import Failure
  38. from twisted.test.proto_helpers import AccumulatingProtocol, MemoryReactorClock
  39. from twisted.web.http_headers import Headers
  40. from twisted.web.resource import IResource
  41. from twisted.web.server import Request, Site
  42. from synapse.http.site import SynapseRequest
  43. from synapse.types import JsonDict
  44. from synapse.util import Clock
  45. from tests.utils import setup_test_homeserver as _sth
  46. logger = logging.getLogger(__name__)
  47. class TimedOutException(Exception):
  48. """
  49. A web query timed out.
  50. """
  51. @attr.s
  52. class FakeChannel:
  53. """
  54. A fake Twisted Web Channel (the part that interfaces with the
  55. wire).
  56. """
  57. site = attr.ib(type=Union[Site, "FakeSite"])
  58. _reactor = attr.ib()
  59. result = attr.ib(type=dict, default=attr.Factory(dict))
  60. _ip = attr.ib(type=str, default="127.0.0.1")
  61. _producer: Optional[Union[IPullProducer, IPushProducer]] = None
  62. @property
  63. def json_body(self):
  64. return json.loads(self.text_body)
  65. @property
  66. def text_body(self) -> str:
  67. """The body of the result, utf-8-decoded.
  68. Raises an exception if the request has not yet completed.
  69. """
  70. if not self.is_finished:
  71. raise Exception("Request not yet completed")
  72. return self.result["body"].decode("utf8")
  73. def is_finished(self) -> bool:
  74. """check if the response has been completely received"""
  75. return self.result.get("done", False)
  76. @property
  77. def code(self):
  78. if not self.result:
  79. raise Exception("No result yet.")
  80. return int(self.result["code"])
  81. @property
  82. def headers(self) -> Headers:
  83. if not self.result:
  84. raise Exception("No result yet.")
  85. h = Headers()
  86. for i in self.result["headers"]:
  87. h.addRawHeader(*i)
  88. return h
  89. def writeHeaders(self, version, code, reason, headers):
  90. self.result["version"] = version
  91. self.result["code"] = code
  92. self.result["reason"] = reason
  93. self.result["headers"] = headers
  94. def write(self, content):
  95. assert isinstance(content, bytes), "Should be bytes! " + repr(content)
  96. if "body" not in self.result:
  97. self.result["body"] = b""
  98. self.result["body"] += content
  99. def registerProducer(self, producer, streaming):
  100. self._producer = producer
  101. self.producerStreaming = streaming
  102. def _produce():
  103. if self._producer:
  104. self._producer.resumeProducing()
  105. self._reactor.callLater(0.1, _produce)
  106. if not streaming:
  107. self._reactor.callLater(0.0, _produce)
  108. def unregisterProducer(self):
  109. if self._producer is None:
  110. return
  111. self._producer = None
  112. def requestDone(self, _self):
  113. self.result["done"] = True
  114. def getPeer(self):
  115. # We give an address so that getClientIP returns a non null entry,
  116. # causing us to record the MAU
  117. return address.IPv4Address("TCP", self._ip, 3423)
  118. def getHost(self):
  119. # this is called by Request.__init__ to configure Request.host.
  120. return address.IPv4Address("TCP", "127.0.0.1", 8888)
  121. def isSecure(self):
  122. return False
  123. @property
  124. def transport(self):
  125. return self
  126. def await_result(self, timeout_ms: int = 1000) -> None:
  127. """
  128. Wait until the request is finished.
  129. """
  130. end_time = self._reactor.seconds() + timeout_ms / 1000.0
  131. self._reactor.run()
  132. while not self.is_finished():
  133. # If there's a producer, tell it to resume producing so we get content
  134. if self._producer:
  135. self._producer.resumeProducing()
  136. if self._reactor.seconds() > end_time:
  137. raise TimedOutException("Timed out waiting for request to finish.")
  138. self._reactor.advance(0.1)
  139. def extract_cookies(self, cookies: MutableMapping[str, str]) -> None:
  140. """Process the contents of any Set-Cookie headers in the response
  141. Any cookines found are added to the given dict
  142. """
  143. headers = self.headers.getRawHeaders("Set-Cookie")
  144. if not headers:
  145. return
  146. for h in headers:
  147. parts = h.split(";")
  148. k, v = parts[0].split("=", maxsplit=1)
  149. cookies[k] = v
  150. class FakeSite:
  151. """
  152. A fake Twisted Web Site, with mocks of the extra things that
  153. Synapse adds.
  154. """
  155. server_version_string = b"1"
  156. site_tag = "test"
  157. access_logger = logging.getLogger("synapse.access.http.fake")
  158. def __init__(self, resource: IResource, reactor: IReactorTime):
  159. """
  160. Args:
  161. resource: the resource to be used for rendering all requests
  162. """
  163. self._resource = resource
  164. self.reactor = reactor
  165. def getResourceFor(self, request):
  166. return self._resource
  167. def make_request(
  168. reactor,
  169. site: Union[Site, FakeSite],
  170. method: Union[bytes, str],
  171. path: Union[bytes, str],
  172. content: Union[bytes, str, JsonDict] = b"",
  173. access_token: Optional[str] = None,
  174. request: Request = SynapseRequest,
  175. shorthand: bool = True,
  176. federation_auth_origin: Optional[bytes] = None,
  177. content_is_form: bool = False,
  178. await_result: bool = True,
  179. custom_headers: Optional[
  180. Iterable[Tuple[Union[bytes, str], Union[bytes, str]]]
  181. ] = None,
  182. client_ip: str = "127.0.0.1",
  183. ) -> FakeChannel:
  184. """
  185. Make a web request using the given method, path and content, and render it
  186. Returns the fake Channel object which records the response to the request.
  187. Args:
  188. reactor:
  189. site: The twisted Site to use to render the request
  190. method: The HTTP request method ("verb").
  191. path: The HTTP path, suitably URL encoded (e.g. escaped UTF-8 & spaces and such).
  192. content: The body of the request. JSON-encoded, if a str of bytes.
  193. access_token: The access token to add as authorization for the request.
  194. request: The request class to create.
  195. shorthand: Whether to try and be helpful and prefix the given URL
  196. with the usual REST API path, if it doesn't contain it.
  197. federation_auth_origin: if set to not-None, we will add a fake
  198. Authorization header pretenting to be the given server name.
  199. content_is_form: Whether the content is URL encoded form data. Adds the
  200. 'Content-Type': 'application/x-www-form-urlencoded' header.
  201. await_result: whether to wait for the request to complete rendering. If true,
  202. will pump the reactor until the the renderer tells the channel the request
  203. is finished.
  204. custom_headers: (name, value) pairs to add as request headers
  205. client_ip: The IP to use as the requesting IP. Useful for testing
  206. ratelimiting.
  207. Returns:
  208. channel
  209. """
  210. if not isinstance(method, bytes):
  211. method = method.encode("ascii")
  212. if not isinstance(path, bytes):
  213. path = path.encode("ascii")
  214. # Decorate it to be the full path, if we're using shorthand
  215. if (
  216. shorthand
  217. and not path.startswith(b"/_matrix")
  218. and not path.startswith(b"/_synapse")
  219. ):
  220. if path.startswith(b"/"):
  221. path = path[1:]
  222. path = b"/_matrix/client/r0/" + path
  223. if not path.startswith(b"/"):
  224. path = b"/" + path
  225. if isinstance(content, dict):
  226. content = json.dumps(content).encode("utf8")
  227. if isinstance(content, str):
  228. content = content.encode("utf8")
  229. channel = FakeChannel(site, reactor, ip=client_ip)
  230. req = request(channel, site)
  231. req.content = BytesIO(content)
  232. # Twisted expects to be at the end of the content when parsing the request.
  233. req.content.seek(SEEK_END)
  234. if access_token:
  235. req.requestHeaders.addRawHeader(
  236. b"Authorization", b"Bearer " + access_token.encode("ascii")
  237. )
  238. if federation_auth_origin is not None:
  239. req.requestHeaders.addRawHeader(
  240. b"Authorization",
  241. b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,),
  242. )
  243. if content:
  244. if content_is_form:
  245. req.requestHeaders.addRawHeader(
  246. b"Content-Type", b"application/x-www-form-urlencoded"
  247. )
  248. else:
  249. # Assume the body is JSON
  250. req.requestHeaders.addRawHeader(b"Content-Type", b"application/json")
  251. if custom_headers:
  252. for k, v in custom_headers:
  253. req.requestHeaders.addRawHeader(k, v)
  254. req.parseCookies()
  255. req.requestReceived(method, path, b"1.1")
  256. if await_result:
  257. channel.await_result()
  258. return channel
  259. @implementer(IReactorPluggableNameResolver)
  260. class ThreadedMemoryReactorClock(MemoryReactorClock):
  261. """
  262. A MemoryReactorClock that supports callFromThread.
  263. """
  264. def __init__(self):
  265. self.threadpool = ThreadPool(self)
  266. self._tcp_callbacks: Dict[Tuple[str, int], Callable] = {}
  267. self._udp = []
  268. self.lookups: Dict[str, str] = {}
  269. self._thread_callbacks: Deque[Callable[[], None]] = deque()
  270. lookups = self.lookups
  271. @implementer(IResolverSimple)
  272. class FakeResolver:
  273. def getHostByName(self, name, timeout=None):
  274. if name not in lookups:
  275. return fail(DNSLookupError("OH NO: unknown %s" % (name,)))
  276. return succeed(lookups[name])
  277. self.nameResolver = SimpleResolverComplexifier(FakeResolver())
  278. super().__init__()
  279. def installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver:
  280. raise NotImplementedError()
  281. def listenUDP(self, port, protocol, interface="", maxPacketSize=8196):
  282. p = udp.Port(port, protocol, interface, maxPacketSize, self)
  283. p.startListening()
  284. self._udp.append(p)
  285. return p
  286. def callFromThread(self, callback, *args, **kwargs):
  287. """
  288. Make the callback fire in the next reactor iteration.
  289. """
  290. cb = lambda: callback(*args, **kwargs)
  291. # it's not safe to call callLater() here, so we append the callback to a
  292. # separate queue.
  293. self._thread_callbacks.append(cb)
  294. def getThreadPool(self):
  295. return self.threadpool
  296. def add_tcp_client_callback(self, host: str, port: int, callback: Callable):
  297. """Add a callback that will be invoked when we receive a connection
  298. attempt to the given IP/port using `connectTCP`.
  299. Note that the callback gets run before we return the connection to the
  300. client, which means callbacks cannot block while waiting for writes.
  301. """
  302. self._tcp_callbacks[(host, port)] = callback
  303. def connectTCP(self, host: str, port: int, factory, timeout=30, bindAddress=None):
  304. """Fake L{IReactorTCP.connectTCP}."""
  305. conn = super().connectTCP(
  306. host, port, factory, timeout=timeout, bindAddress=None
  307. )
  308. callback = self._tcp_callbacks.get((host, port))
  309. if callback:
  310. callback()
  311. return conn
  312. def advance(self, amount):
  313. # first advance our reactor's time, and run any "callLater" callbacks that
  314. # makes ready
  315. super().advance(amount)
  316. # now run any "callFromThread" callbacks
  317. while True:
  318. try:
  319. callback = self._thread_callbacks.popleft()
  320. except IndexError:
  321. break
  322. callback()
  323. # check for more "callLater" callbacks added by the thread callback
  324. # This isn't required in a regular reactor, but it ends up meaning that
  325. # our database queries can complete in a single call to `advance` [1] which
  326. # simplifies tests.
  327. #
  328. # [1]: we replace the threadpool backing the db connection pool with a
  329. # mock ThreadPool which doesn't really use threads; but we still use
  330. # reactor.callFromThread to feed results back from the db functions to the
  331. # main thread.
  332. super().advance(0)
  333. class ThreadPool:
  334. """
  335. Threadless thread pool.
  336. """
  337. def __init__(self, reactor):
  338. self._reactor = reactor
  339. def start(self):
  340. pass
  341. def stop(self):
  342. pass
  343. def callInThreadWithCallback(self, onResult, function, *args, **kwargs):
  344. def _(res):
  345. if isinstance(res, Failure):
  346. onResult(False, res)
  347. else:
  348. onResult(True, res)
  349. d = Deferred()
  350. d.addCallback(lambda x: function(*args, **kwargs))
  351. d.addBoth(_)
  352. self._reactor.callLater(0, d.callback, True)
  353. return d
  354. def setup_test_homeserver(cleanup_func, *args, **kwargs):
  355. """
  356. Set up a synchronous test server, driven by the reactor used by
  357. the homeserver.
  358. """
  359. server = _sth(cleanup_func, *args, **kwargs)
  360. # Make the thread pool synchronous.
  361. clock = server.get_clock()
  362. for database in server.get_datastores().databases:
  363. pool = database._db_pool
  364. def runWithConnection(func, *args, **kwargs):
  365. return threads.deferToThreadPool(
  366. pool._reactor,
  367. pool.threadpool,
  368. pool._runWithConnection,
  369. func,
  370. *args,
  371. **kwargs,
  372. )
  373. def runInteraction(interaction, *args, **kwargs):
  374. return threads.deferToThreadPool(
  375. pool._reactor,
  376. pool.threadpool,
  377. pool._runInteraction,
  378. interaction,
  379. *args,
  380. **kwargs,
  381. )
  382. pool.runWithConnection = runWithConnection
  383. pool.runInteraction = runInteraction
  384. pool.threadpool = ThreadPool(clock._reactor)
  385. pool.running = True
  386. # We've just changed the Databases to run DB transactions on the same
  387. # thread, so we need to disable the dedicated thread behaviour.
  388. server.get_datastores().main.USE_DEDICATED_DB_THREADS_FOR_EVENT_FETCHING = False
  389. return server
  390. def get_clock() -> Tuple[ThreadedMemoryReactorClock, Clock]:
  391. clock = ThreadedMemoryReactorClock()
  392. hs_clock = Clock(clock)
  393. return clock, hs_clock
  394. @implementer(ITransport)
  395. @attr.s(cmp=False)
  396. class FakeTransport:
  397. """
  398. A twisted.internet.interfaces.ITransport implementation which sends all its data
  399. straight into an IProtocol object: it exists to connect two IProtocols together.
  400. To use it, instantiate it with the receiving IProtocol, and then pass it to the
  401. sending IProtocol's makeConnection method:
  402. server = HTTPChannel()
  403. client.makeConnection(FakeTransport(server, self.reactor))
  404. If you want bidirectional communication, you'll need two instances.
  405. """
  406. other = attr.ib()
  407. """The Protocol object which will receive any data written to this transport.
  408. :type: twisted.internet.interfaces.IProtocol
  409. """
  410. _reactor = attr.ib()
  411. """Test reactor
  412. :type: twisted.internet.interfaces.IReactorTime
  413. """
  414. _protocol = attr.ib(default=None)
  415. """The Protocol which is producing data for this transport. Optional, but if set
  416. will get called back for connectionLost() notifications etc.
  417. """
  418. _peer_address: Optional[IAddress] = attr.ib(default=None)
  419. """The value to be returend by getPeer"""
  420. disconnecting = False
  421. disconnected = False
  422. connected = True
  423. buffer = attr.ib(default=b"")
  424. producer = attr.ib(default=None)
  425. autoflush = attr.ib(default=True)
  426. def getPeer(self):
  427. return self._peer_address
  428. def getHost(self):
  429. return None
  430. def loseConnection(self, reason=None):
  431. if not self.disconnecting:
  432. logger.info("FakeTransport: loseConnection(%s)", reason)
  433. self.disconnecting = True
  434. if self._protocol:
  435. self._protocol.connectionLost(reason)
  436. # if we still have data to write, delay until that is done
  437. if self.buffer:
  438. logger.info(
  439. "FakeTransport: Delaying disconnect until buffer is flushed"
  440. )
  441. else:
  442. self.connected = False
  443. self.disconnected = True
  444. def abortConnection(self):
  445. logger.info("FakeTransport: abortConnection()")
  446. if not self.disconnecting:
  447. self.disconnecting = True
  448. if self._protocol:
  449. self._protocol.connectionLost(None)
  450. self.disconnected = True
  451. def pauseProducing(self):
  452. if not self.producer:
  453. return
  454. self.producer.pauseProducing()
  455. def resumeProducing(self):
  456. if not self.producer:
  457. return
  458. self.producer.resumeProducing()
  459. def unregisterProducer(self):
  460. if not self.producer:
  461. return
  462. self.producer = None
  463. def registerProducer(self, producer, streaming):
  464. self.producer = producer
  465. self.producerStreaming = streaming
  466. def _produce():
  467. if not self.producer:
  468. # we've been unregistered
  469. return
  470. # some implementations of IProducer (for example, FileSender)
  471. # don't return a deferred.
  472. d = maybeDeferred(self.producer.resumeProducing)
  473. d.addCallback(lambda x: self._reactor.callLater(0.1, _produce))
  474. if not streaming:
  475. self._reactor.callLater(0.0, _produce)
  476. def write(self, byt):
  477. if self.disconnecting:
  478. raise Exception("Writing to disconnecting FakeTransport")
  479. self.buffer = self.buffer + byt
  480. # always actually do the write asynchronously. Some protocols (notably the
  481. # TLSMemoryBIOProtocol) get very confused if a read comes back while they are
  482. # still doing a write. Doing a callLater here breaks the cycle.
  483. if self.autoflush:
  484. self._reactor.callLater(0.0, self.flush)
  485. def writeSequence(self, seq):
  486. for x in seq:
  487. self.write(x)
  488. def flush(self, maxbytes=None):
  489. if not self.buffer:
  490. # nothing to do. Don't write empty buffers: it upsets the
  491. # TLSMemoryBIOProtocol
  492. return
  493. if self.disconnected:
  494. return
  495. if maxbytes is not None:
  496. to_write = self.buffer[:maxbytes]
  497. else:
  498. to_write = self.buffer
  499. logger.info("%s->%s: %s", self._protocol, self.other, to_write)
  500. try:
  501. self.other.dataReceived(to_write)
  502. except Exception as e:
  503. logger.exception("Exception writing to protocol: %s", e)
  504. return
  505. self.buffer = self.buffer[len(to_write) :]
  506. if self.buffer and self.autoflush:
  507. self._reactor.callLater(0.0, self.flush)
  508. if not self.buffer and self.disconnecting:
  509. logger.info("FakeTransport: Buffer now empty, completing disconnect")
  510. self.disconnected = True
  511. def connect_client(
  512. reactor: ThreadedMemoryReactorClock, client_id: int
  513. ) -> Tuple[IProtocol, AccumulatingProtocol]:
  514. """
  515. Connect a client to a fake TCP transport.
  516. Args:
  517. reactor
  518. factory: The connecting factory to build.
  519. """
  520. factory = reactor.tcpClients.pop(client_id)[2]
  521. client = factory.buildProtocol(None)
  522. server = AccumulatingProtocol()
  523. server.makeConnection(FakeTransport(client, reactor))
  524. client.makeConnection(FakeTransport(server, reactor))
  525. return client, server