Matrix Docker Ansible eploy
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

180 line
6.9 KiB

  1. # SPDX-FileCopyrightText: 2026 Slavi Pantaleev
  2. #
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. """A stand-in homeserver for Molecule scenarios.
  5. Most components talk to a homeserver while starting up and exit if it is unreachable,
  6. so a scenario cannot get them running without one. A real Synapse for every role would
  7. dominate the run time and drag in Postgres, and the scenarios are not testing Synapse.
  8. This answers the handful of endpoints components touch during startup, with the blandest
  9. plausible response in each case. Deliberately permissive: an unknown path returns `{}` with
  10. a 200 rather than a 404, because the goal is to get the component past its startup checks.
  11. What it is NOT: an authentication check, a room state machine, or anything a scenario should
  12. assert *about*. Assert on what the role rendered and what the component reports about itself.
  13. A scenario that needs this stub to behave like a real homeserver has outgrown what these
  14. tests are for.
  15. """
  16. import json
  17. import os
  18. import re
  19. import sys
  20. import time
  21. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  22. from urllib.parse import parse_qs, urlparse
  23. SERVER_NAME = os.environ.get("STUB_SERVER_NAME", "molecule.local")
  24. PORT = int(os.environ.get("STUB_PORT", "8008"))
  25. # Rooms reported as already joined. Components that resolve a room mapping at startup
  26. # (matrix-alertmanager-receiver, for one) fail if the rooms they were configured with
  27. # are missing, so a scenario passes its own room IDs in.
  28. JOINED_ROOMS = [r for r in os.environ.get("STUB_JOINED_ROOMS", "").split(",") if r]
  29. USER_ID = os.environ.get("STUB_USER_ID", f"@stub:{SERVER_NAME}")
  30. # Longest a /sync call is held open. Long-polling clients ask for a 30s timeout and
  31. # immediately ask again when the call returns, so answering instantly spins them into a hot
  32. # loop that eats the test machine. Honouring the requested timeout, capped here, keeps an
  33. # idle bot idle.
  34. SYNC_MAX_HOLD_SECONDS = 30
  35. class Handler(BaseHTTPRequestHandler):
  36. protocol_version = "HTTP/1.1"
  37. def _send(self, payload, status=200):
  38. body = json.dumps(payload).encode()
  39. self.send_response(status)
  40. self.send_header("Content-Type", "application/json")
  41. self.send_header("Content-Length", str(len(body)))
  42. self.end_headers()
  43. self.wfile.write(body)
  44. def _route(self):
  45. parsed = urlparse(self.path)
  46. path = parsed.path
  47. # A client that syncs (every bot here does) needs a `next_batch` back or
  48. # the response will not deserialize, and it needs the call to block for
  49. # the timeout it asked for or it will hammer this stub. Nothing is ever
  50. # reported: an idle bot is what a scenario wants.
  51. if path.endswith("/sync"):
  52. requested_ms = parse_qs(parsed.query).get("timeout", ["0"])[0]
  53. try:
  54. hold = min(int(requested_ms) / 1000.0, SYNC_MAX_HOLD_SECONDS)
  55. except ValueError:
  56. hold = 0
  57. if hold > 0:
  58. time.sleep(hold)
  59. return {"next_batch": "molecule-stub-batch"}
  60. # Before the generic `/upload` below: this one is the end-to-end
  61. # encryption key upload, and the client insists on the key counts.
  62. if path.endswith("/keys/upload"):
  63. return {"one_time_key_counts": {}}
  64. # Media. A bot that sets its own avatar asks for the upload limits first
  65. # and refuses to proceed without them, then uploads and expects an MXC
  66. # URI back.
  67. if path.endswith("/media/config") or path.endswith("/media/v3/config"):
  68. return {"m.upload.size": 10485760}
  69. if path.endswith("/upload"):
  70. return {"content_uri": f"mxc://{SERVER_NAME}/molecule-stub-media"}
  71. # Sync filters are uploaded before the first sync and referenced by id.
  72. if path.endswith("/filter"):
  73. return {"filter_id": "molecule-stub-filter"}
  74. if path.endswith("/joined_rooms"):
  75. return {"joined_rooms": JOINED_ROOMS}
  76. if path.endswith("/whoami"):
  77. return {"user_id": USER_ID, "device_id": "STUBDEVICE"}
  78. if path.endswith("/versions"):
  79. return {
  80. "versions": ["v1.1", "v1.2", "v1.3", "v1.4", "v1.5", "v1.6"],
  81. "unstable_features": {},
  82. }
  83. if path.endswith("/capabilities"):
  84. return {"capabilities": {}}
  85. # Where bots authenticating with a username and password log in, rather than as an
  86. # appservice with a token. Matched loosely on purpose, because clients differ on the
  87. # API version prefix, and a login falling through to the catch-all `{}` below looks
  88. # to the client like bad credentials.
  89. if path.endswith("/login"):
  90. return {
  91. "user_id": USER_ID,
  92. "access_token": "stub_access_token",
  93. "device_id": "STUBDEVICE",
  94. "home_server": SERVER_NAME,
  95. }
  96. if path.endswith("/createRoom"):
  97. return {"room_id": f"!stub-room:{SERVER_NAME}"}
  98. if re.search(r"/rooms/[^/]+/join$", path) or path.endswith("/join"):
  99. return {"room_id": f"!stub-room:{SERVER_NAME}"}
  100. if "/send/" in path or "/state/" in path:
  101. return {"event_id": f"$stub-event:{SERVER_NAME}"}
  102. if path.endswith("/register"):
  103. return {
  104. "user_id": USER_ID,
  105. "access_token": "stub_access_token",
  106. "device_id": "STUBDEVICE",
  107. "home_server": SERVER_NAME,
  108. }
  109. if path.endswith("/profile") or "/profile/" in path:
  110. return {"displayname": "stub"}
  111. if path.startswith("/_matrix/key/"):
  112. return {"server_name": SERVER_NAME, "verify_keys": {}, "old_verify_keys": {}}
  113. if path.startswith("/.well-known/matrix/client"):
  114. return {"m.homeserver": {"base_url": f"http://{SERVER_NAME}:{PORT}"}}
  115. if path.startswith("/.well-known/matrix/server"):
  116. return {"m.server": f"{SERVER_NAME}:{PORT}"}
  117. if path.endswith("/health") or path.endswith("/_matrix/federation/v1/version"):
  118. return {"server": {"name": "molecule-stub", "version": "0"}}
  119. # Anything unrecognised: an empty object, so a component probing an endpoint
  120. # not listed here still gets past it.
  121. return {}
  122. def do_GET(self):
  123. self._send(self._route())
  124. def do_POST(self):
  125. length = int(self.headers.get("Content-Length") or 0)
  126. if length:
  127. self.rfile.read(length)
  128. self._send(self._route())
  129. def do_PUT(self):
  130. self.do_POST()
  131. def do_DELETE(self):
  132. self._send({})
  133. def log_message(self, fmt, *args):
  134. # Quiet by default. STUB_VERBOSE=1 when a scenario will not start and you need
  135. # to see what the component is actually asking for.
  136. if os.environ.get("STUB_VERBOSE"):
  137. sys.stderr.write("stub: " + (fmt % args) + "\n")
  138. if __name__ == "__main__":
  139. ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()