server.py 19 KB

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