server.py 18 KB

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