server.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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. """
  276. conn = super().connectTCP(
  277. host, port, factory, timeout=timeout, bindAddress=None
  278. )
  279. callback = self._tcp_callbacks.get((host, port))
  280. if callback:
  281. callback()
  282. return conn
  283. def advance(self, amount):
  284. # first advance our reactor's time, and run any "callLater" callbacks that
  285. # makes ready
  286. super().advance(amount)
  287. # now run any "callFromThread" callbacks
  288. while True:
  289. try:
  290. callback = self._thread_callbacks.popleft()
  291. except IndexError:
  292. break
  293. callback()
  294. # check for more "callLater" callbacks added by the thread callback
  295. # This isn't required in a regular reactor, but it ends up meaning that
  296. # our database queries can complete in a single call to `advance` [1] which
  297. # simplifies tests.
  298. #
  299. # [1]: we replace the threadpool backing the db connection pool with a
  300. # mock ThreadPool which doesn't really use threads; but we still use
  301. # reactor.callFromThread to feed results back from the db functions to the
  302. # main thread.
  303. super().advance(0)
  304. class ThreadPool:
  305. """
  306. Threadless thread pool.
  307. """
  308. def __init__(self, reactor):
  309. self._reactor = reactor
  310. def start(self):
  311. pass
  312. def stop(self):
  313. pass
  314. def callInThreadWithCallback(self, onResult, function, *args, **kwargs):
  315. def _(res):
  316. if isinstance(res, Failure):
  317. onResult(False, res)
  318. else:
  319. onResult(True, res)
  320. d = Deferred()
  321. d.addCallback(lambda x: function(*args, **kwargs))
  322. d.addBoth(_)
  323. self._reactor.callLater(0, d.callback, True)
  324. return d
  325. def setup_test_homeserver(cleanup_func, *args, **kwargs):
  326. """
  327. Set up a synchronous test server, driven by the reactor used by
  328. the homeserver.
  329. """
  330. server = _sth(cleanup_func, *args, **kwargs)
  331. # Make the thread pool synchronous.
  332. clock = server.get_clock()
  333. for database in server.get_datastores().databases:
  334. pool = database._db_pool
  335. def runWithConnection(func, *args, **kwargs):
  336. return threads.deferToThreadPool(
  337. pool._reactor,
  338. pool.threadpool,
  339. pool._runWithConnection,
  340. func,
  341. *args,
  342. **kwargs,
  343. )
  344. def runInteraction(interaction, *args, **kwargs):
  345. return threads.deferToThreadPool(
  346. pool._reactor,
  347. pool.threadpool,
  348. pool._runInteraction,
  349. interaction,
  350. *args,
  351. **kwargs,
  352. )
  353. pool.runWithConnection = runWithConnection
  354. pool.runInteraction = runInteraction
  355. pool.threadpool = ThreadPool(clock._reactor)
  356. pool.running = True
  357. # We've just changed the Databases to run DB transactions on the same
  358. # thread, so we need to disable the dedicated thread behaviour.
  359. server.get_datastores().main.USE_DEDICATED_DB_THREADS_FOR_EVENT_FETCHING = False
  360. return server
  361. def get_clock():
  362. clock = ThreadedMemoryReactorClock()
  363. hs_clock = Clock(clock)
  364. return clock, hs_clock
  365. @attr.s(cmp=False)
  366. class FakeTransport:
  367. """
  368. A twisted.internet.interfaces.ITransport implementation which sends all its data
  369. straight into an IProtocol object: it exists to connect two IProtocols together.
  370. To use it, instantiate it with the receiving IProtocol, and then pass it to the
  371. sending IProtocol's makeConnection method:
  372. server = HTTPChannel()
  373. client.makeConnection(FakeTransport(server, self.reactor))
  374. If you want bidirectional communication, you'll need two instances.
  375. """
  376. other = attr.ib()
  377. """The Protocol object which will receive any data written to this transport.
  378. :type: twisted.internet.interfaces.IProtocol
  379. """
  380. _reactor = attr.ib()
  381. """Test reactor
  382. :type: twisted.internet.interfaces.IReactorTime
  383. """
  384. _protocol = attr.ib(default=None)
  385. """The Protocol which is producing data for this transport. Optional, but if set
  386. will get called back for connectionLost() notifications etc.
  387. """
  388. disconnecting = False
  389. disconnected = False
  390. connected = True
  391. buffer = attr.ib(default=b"")
  392. producer = attr.ib(default=None)
  393. autoflush = attr.ib(default=True)
  394. def getPeer(self):
  395. return None
  396. def getHost(self):
  397. return None
  398. def loseConnection(self, reason=None):
  399. if not self.disconnecting:
  400. logger.info("FakeTransport: loseConnection(%s)", reason)
  401. self.disconnecting = True
  402. if self._protocol:
  403. self._protocol.connectionLost(reason)
  404. # if we still have data to write, delay until that is done
  405. if self.buffer:
  406. logger.info(
  407. "FakeTransport: Delaying disconnect until buffer is flushed"
  408. )
  409. else:
  410. self.connected = False
  411. self.disconnected = True
  412. def abortConnection(self):
  413. logger.info("FakeTransport: abortConnection()")
  414. if not self.disconnecting:
  415. self.disconnecting = True
  416. if self._protocol:
  417. self._protocol.connectionLost(None)
  418. self.disconnected = True
  419. def pauseProducing(self):
  420. if not self.producer:
  421. return
  422. self.producer.pauseProducing()
  423. def resumeProducing(self):
  424. if not self.producer:
  425. return
  426. self.producer.resumeProducing()
  427. def unregisterProducer(self):
  428. if not self.producer:
  429. return
  430. self.producer = None
  431. def registerProducer(self, producer, streaming):
  432. self.producer = producer
  433. self.producerStreaming = streaming
  434. def _produce():
  435. d = self.producer.resumeProducing()
  436. d.addCallback(lambda x: self._reactor.callLater(0.1, _produce))
  437. if not streaming:
  438. self._reactor.callLater(0.0, _produce)
  439. def write(self, byt):
  440. if self.disconnecting:
  441. raise Exception("Writing to disconnecting FakeTransport")
  442. self.buffer = self.buffer + byt
  443. # always actually do the write asynchronously. Some protocols (notably the
  444. # TLSMemoryBIOProtocol) get very confused if a read comes back while they are
  445. # still doing a write. Doing a callLater here breaks the cycle.
  446. if self.autoflush:
  447. self._reactor.callLater(0.0, self.flush)
  448. def writeSequence(self, seq):
  449. for x in seq:
  450. self.write(x)
  451. def flush(self, maxbytes=None):
  452. if not self.buffer:
  453. # nothing to do. Don't write empty buffers: it upsets the
  454. # TLSMemoryBIOProtocol
  455. return
  456. if self.disconnected:
  457. return
  458. if getattr(self.other, "transport") is None:
  459. # the other has no transport yet; reschedule
  460. if self.autoflush:
  461. self._reactor.callLater(0.0, self.flush)
  462. return
  463. if maxbytes is not None:
  464. to_write = self.buffer[:maxbytes]
  465. else:
  466. to_write = self.buffer
  467. logger.info("%s->%s: %s", self._protocol, self.other, to_write)
  468. try:
  469. self.other.dataReceived(to_write)
  470. except Exception as e:
  471. logger.exception("Exception writing to protocol: %s", e)
  472. return
  473. self.buffer = self.buffer[len(to_write) :]
  474. if self.buffer and self.autoflush:
  475. self._reactor.callLater(0.0, self.flush)
  476. if not self.buffer and self.disconnecting:
  477. logger.info("FakeTransport: Buffer now empty, completing disconnect")
  478. self.disconnected = True
  479. def connect_client(reactor: IReactorTCP, client_id: int) -> AccumulatingProtocol:
  480. """
  481. Connect a client to a fake TCP transport.
  482. Args:
  483. reactor
  484. factory: The connecting factory to build.
  485. """
  486. factory = reactor.tcpClients.pop(client_id)[2]
  487. client = factory.buildProtocol(None)
  488. server = AccumulatingProtocol()
  489. server.makeConnection(FakeTransport(client, reactor))
  490. client.makeConnection(FakeTransport(server, reactor))
  491. return client, server