server.py 19 KB

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