server.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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, succeed
  12. from twisted.internet.error import DNSLookupError
  13. from twisted.internet.interfaces import (
  14. IHostnameResolver,
  15. IProtocol,
  16. IPullProducer,
  17. IPushProducer,
  18. IReactorPluggableNameResolver,
  19. IResolverSimple,
  20. ITransport,
  21. )
  22. from twisted.python.failure import Failure
  23. from twisted.test.proto_helpers import AccumulatingProtocol, MemoryReactorClock
  24. from twisted.web.http_headers import Headers
  25. from twisted.web.resource import IResource
  26. from twisted.web.server import Site
  27. from synapse.http.site import SynapseRequest
  28. from synapse.util import Clock
  29. from tests.utils import setup_test_homeserver as _sth
  30. logger = logging.getLogger(__name__)
  31. class TimedOutException(Exception):
  32. """
  33. A web query timed out.
  34. """
  35. @attr.s
  36. class FakeChannel:
  37. """
  38. A fake Twisted Web Channel (the part that interfaces with the
  39. wire).
  40. """
  41. site = attr.ib(type=Union[Site, "FakeSite"])
  42. _reactor = attr.ib()
  43. result = attr.ib(type=dict, default=attr.Factory(dict))
  44. _ip = attr.ib(type=str, default="127.0.0.1")
  45. _producer = None # type: Optional[Union[IPullProducer, IPushProducer]]
  46. @property
  47. def json_body(self):
  48. return json.loads(self.text_body)
  49. @property
  50. def text_body(self) -> str:
  51. """The body of the result, utf-8-decoded.
  52. Raises an exception if the request has not yet completed.
  53. """
  54. if not self.is_finished:
  55. raise Exception("Request not yet completed")
  56. return self.result["body"].decode("utf8")
  57. def is_finished(self) -> bool:
  58. """check if the response has been completely received"""
  59. return self.result.get("done", False)
  60. @property
  61. def code(self):
  62. if not self.result:
  63. raise Exception("No result yet.")
  64. return int(self.result["code"])
  65. @property
  66. def headers(self) -> Headers:
  67. if not self.result:
  68. raise Exception("No result yet.")
  69. h = Headers()
  70. for i in self.result["headers"]:
  71. h.addRawHeader(*i)
  72. return h
  73. def writeHeaders(self, version, code, reason, headers):
  74. self.result["version"] = version
  75. self.result["code"] = code
  76. self.result["reason"] = reason
  77. self.result["headers"] = headers
  78. def write(self, content):
  79. assert isinstance(content, bytes), "Should be bytes! " + repr(content)
  80. if "body" not in self.result:
  81. self.result["body"] = b""
  82. self.result["body"] += content
  83. def registerProducer(self, producer, streaming):
  84. self._producer = producer
  85. self.producerStreaming = streaming
  86. def _produce():
  87. if self._producer:
  88. self._producer.resumeProducing()
  89. self._reactor.callLater(0.1, _produce)
  90. if not streaming:
  91. self._reactor.callLater(0.0, _produce)
  92. def unregisterProducer(self):
  93. if self._producer is None:
  94. return
  95. self._producer = None
  96. def requestDone(self, _self):
  97. self.result["done"] = True
  98. def getPeer(self):
  99. # We give an address so that getClientIP returns a non null entry,
  100. # causing us to record the MAU
  101. return address.IPv4Address("TCP", self._ip, 3423)
  102. def getHost(self):
  103. # this is called by Request.__init__ to configure Request.host.
  104. return address.IPv4Address("TCP", "127.0.0.1", 8888)
  105. def isSecure(self):
  106. return False
  107. @property
  108. def transport(self):
  109. return self
  110. def await_result(self, timeout: int = 100) -> None:
  111. """
  112. Wait until the request is finished.
  113. """
  114. self._reactor.run()
  115. x = 0
  116. while not self.is_finished():
  117. # If there's a producer, tell it to resume producing so we get content
  118. if self._producer:
  119. self._producer.resumeProducing()
  120. x += 1
  121. if x > timeout:
  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. lookups = self.lookups = {} # type: Dict[str, str]
  252. self._thread_callbacks = deque() # type: Deque[Callable[[], None]]
  253. @implementer(IResolverSimple)
  254. class FakeResolver:
  255. def getHostByName(self, name, timeout=None):
  256. if name not in lookups:
  257. return fail(DNSLookupError("OH NO: unknown %s" % (name,)))
  258. return succeed(lookups[name])
  259. self.nameResolver = SimpleResolverComplexifier(FakeResolver())
  260. super().__init__()
  261. def installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver:
  262. raise NotImplementedError()
  263. def listenUDP(self, port, protocol, interface="", maxPacketSize=8196):
  264. p = udp.Port(port, protocol, interface, maxPacketSize, self)
  265. p.startListening()
  266. self._udp.append(p)
  267. return p
  268. def callFromThread(self, callback, *args, **kwargs):
  269. """
  270. Make the callback fire in the next reactor iteration.
  271. """
  272. cb = lambda: callback(*args, **kwargs)
  273. # it's not safe to call callLater() here, so we append the callback to a
  274. # separate queue.
  275. self._thread_callbacks.append(cb)
  276. def getThreadPool(self):
  277. return self.threadpool
  278. def add_tcp_client_callback(self, host, port, callback):
  279. """Add a callback that will be invoked when we receive a connection
  280. attempt to the given IP/port using `connectTCP`.
  281. Note that the callback gets run before we return the connection to the
  282. client, which means callbacks cannot block while waiting for writes.
  283. """
  284. self._tcp_callbacks[(host, port)] = callback
  285. def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
  286. """Fake L{IReactorTCP.connectTCP}."""
  287. conn = super().connectTCP(
  288. host, port, factory, timeout=timeout, bindAddress=None
  289. )
  290. callback = self._tcp_callbacks.get((host, port))
  291. if callback:
  292. callback()
  293. return conn
  294. def advance(self, amount):
  295. # first advance our reactor's time, and run any "callLater" callbacks that
  296. # makes ready
  297. super().advance(amount)
  298. # now run any "callFromThread" callbacks
  299. while True:
  300. try:
  301. callback = self._thread_callbacks.popleft()
  302. except IndexError:
  303. break
  304. callback()
  305. # check for more "callLater" callbacks added by the thread callback
  306. # This isn't required in a regular reactor, but it ends up meaning that
  307. # our database queries can complete in a single call to `advance` [1] which
  308. # simplifies tests.
  309. #
  310. # [1]: we replace the threadpool backing the db connection pool with a
  311. # mock ThreadPool which doesn't really use threads; but we still use
  312. # reactor.callFromThread to feed results back from the db functions to the
  313. # main thread.
  314. super().advance(0)
  315. class ThreadPool:
  316. """
  317. Threadless thread pool.
  318. """
  319. def __init__(self, reactor):
  320. self._reactor = reactor
  321. def start(self):
  322. pass
  323. def stop(self):
  324. pass
  325. def callInThreadWithCallback(self, onResult, function, *args, **kwargs):
  326. def _(res):
  327. if isinstance(res, Failure):
  328. onResult(False, res)
  329. else:
  330. onResult(True, res)
  331. d = Deferred()
  332. d.addCallback(lambda x: function(*args, **kwargs))
  333. d.addBoth(_)
  334. self._reactor.callLater(0, d.callback, True)
  335. return d
  336. def setup_test_homeserver(cleanup_func, *args, **kwargs):
  337. """
  338. Set up a synchronous test server, driven by the reactor used by
  339. the homeserver.
  340. """
  341. server = _sth(cleanup_func, *args, **kwargs)
  342. # Make the thread pool synchronous.
  343. clock = server.get_clock()
  344. for database in server.get_datastores().databases:
  345. pool = database._db_pool
  346. def runWithConnection(func, *args, **kwargs):
  347. return threads.deferToThreadPool(
  348. pool._reactor,
  349. pool.threadpool,
  350. pool._runWithConnection,
  351. func,
  352. *args,
  353. **kwargs,
  354. )
  355. def runInteraction(interaction, *args, **kwargs):
  356. return threads.deferToThreadPool(
  357. pool._reactor,
  358. pool.threadpool,
  359. pool._runInteraction,
  360. interaction,
  361. *args,
  362. **kwargs,
  363. )
  364. pool.runWithConnection = runWithConnection
  365. pool.runInteraction = runInteraction
  366. pool.threadpool = ThreadPool(clock._reactor)
  367. pool.running = True
  368. # We've just changed the Databases to run DB transactions on the same
  369. # thread, so we need to disable the dedicated thread behaviour.
  370. server.get_datastores().main.USE_DEDICATED_DB_THREADS_FOR_EVENT_FETCHING = False
  371. return server
  372. def get_clock():
  373. clock = ThreadedMemoryReactorClock()
  374. hs_clock = Clock(clock)
  375. return clock, hs_clock
  376. @implementer(ITransport)
  377. @attr.s(cmp=False)
  378. class FakeTransport:
  379. """
  380. A twisted.internet.interfaces.ITransport implementation which sends all its data
  381. straight into an IProtocol object: it exists to connect two IProtocols together.
  382. To use it, instantiate it with the receiving IProtocol, and then pass it to the
  383. sending IProtocol's makeConnection method:
  384. server = HTTPChannel()
  385. client.makeConnection(FakeTransport(server, self.reactor))
  386. If you want bidirectional communication, you'll need two instances.
  387. """
  388. other = attr.ib()
  389. """The Protocol object which will receive any data written to this transport.
  390. :type: twisted.internet.interfaces.IProtocol
  391. """
  392. _reactor = attr.ib()
  393. """Test reactor
  394. :type: twisted.internet.interfaces.IReactorTime
  395. """
  396. _protocol = attr.ib(default=None)
  397. """The Protocol which is producing data for this transport. Optional, but if set
  398. will get called back for connectionLost() notifications etc.
  399. """
  400. disconnecting = False
  401. disconnected = False
  402. connected = True
  403. buffer = attr.ib(default=b"")
  404. producer = attr.ib(default=None)
  405. autoflush = attr.ib(default=True)
  406. def getPeer(self):
  407. return None
  408. def getHost(self):
  409. return None
  410. def loseConnection(self, reason=None):
  411. if not self.disconnecting:
  412. logger.info("FakeTransport: loseConnection(%s)", reason)
  413. self.disconnecting = True
  414. if self._protocol:
  415. self._protocol.connectionLost(reason)
  416. # if we still have data to write, delay until that is done
  417. if self.buffer:
  418. logger.info(
  419. "FakeTransport: Delaying disconnect until buffer is flushed"
  420. )
  421. else:
  422. self.connected = False
  423. self.disconnected = True
  424. def abortConnection(self):
  425. logger.info("FakeTransport: abortConnection()")
  426. if not self.disconnecting:
  427. self.disconnecting = True
  428. if self._protocol:
  429. self._protocol.connectionLost(None)
  430. self.disconnected = True
  431. def pauseProducing(self):
  432. if not self.producer:
  433. return
  434. self.producer.pauseProducing()
  435. def resumeProducing(self):
  436. if not self.producer:
  437. return
  438. self.producer.resumeProducing()
  439. def unregisterProducer(self):
  440. if not self.producer:
  441. return
  442. self.producer = None
  443. def registerProducer(self, producer, streaming):
  444. self.producer = producer
  445. self.producerStreaming = streaming
  446. def _produce():
  447. d = self.producer.resumeProducing()
  448. d.addCallback(lambda x: self._reactor.callLater(0.1, _produce))
  449. if not streaming:
  450. self._reactor.callLater(0.0, _produce)
  451. def write(self, byt):
  452. if self.disconnecting:
  453. raise Exception("Writing to disconnecting FakeTransport")
  454. self.buffer = self.buffer + byt
  455. # always actually do the write asynchronously. Some protocols (notably the
  456. # TLSMemoryBIOProtocol) get very confused if a read comes back while they are
  457. # still doing a write. Doing a callLater here breaks the cycle.
  458. if self.autoflush:
  459. self._reactor.callLater(0.0, self.flush)
  460. def writeSequence(self, seq):
  461. for x in seq:
  462. self.write(x)
  463. def flush(self, maxbytes=None):
  464. if not self.buffer:
  465. # nothing to do. Don't write empty buffers: it upsets the
  466. # TLSMemoryBIOProtocol
  467. return
  468. if self.disconnected:
  469. return
  470. if maxbytes is not None:
  471. to_write = self.buffer[:maxbytes]
  472. else:
  473. to_write = self.buffer
  474. logger.info("%s->%s: %s", self._protocol, self.other, to_write)
  475. try:
  476. self.other.dataReceived(to_write)
  477. except Exception as e:
  478. logger.exception("Exception writing to protocol: %s", e)
  479. return
  480. self.buffer = self.buffer[len(to_write) :]
  481. if self.buffer and self.autoflush:
  482. self._reactor.callLater(0.0, self.flush)
  483. if not self.buffer and self.disconnecting:
  484. logger.info("FakeTransport: Buffer now empty, completing disconnect")
  485. self.disconnected = True
  486. def connect_client(
  487. reactor: ThreadedMemoryReactorClock, client_id: int
  488. ) -> Tuple[IProtocol, AccumulatingProtocol]:
  489. """
  490. Connect a client to a fake TCP transport.
  491. Args:
  492. reactor
  493. factory: The connecting factory to build.
  494. """
  495. factory = reactor.tcpClients.pop(client_id)[2]
  496. client = factory.buildProtocol(None)
  497. server = AccumulatingProtocol()
  498. server.makeConnection(FakeTransport(client, reactor))
  499. client.makeConnection(FakeTransport(server, reactor))
  500. return client, server