server.py 19 KB

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