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.
 
 
 
 
 
 

222 lines
6.8 KiB

  1. # Copyright 2018 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
  16. from twisted.web.server import Request
  17. from synapse.http.server import HttpServer
  18. from synapse.logging.opentracing import active_span
  19. from synapse.replication.http._base import ReplicationEndpoint
  20. from synapse.types import JsonDict
  21. if TYPE_CHECKING:
  22. from synapse.server import HomeServer
  23. logger = logging.getLogger(__name__)
  24. class ReplicationUserDevicesResyncRestServlet(ReplicationEndpoint):
  25. """Ask master to resync the device list for a user by contacting their
  26. server.
  27. This must happen on master so that the results can be correctly cached in
  28. the database and streamed to workers.
  29. Request format:
  30. POST /_synapse/replication/user_device_resync/:user_id
  31. {}
  32. Response is equivalent to ` /_matrix/federation/v1/user/devices/:user_id`
  33. response, e.g.:
  34. {
  35. "user_id": "@alice:example.org",
  36. "devices": [
  37. {
  38. "device_id": "JLAFKJWSCS",
  39. "keys": { ... },
  40. "device_display_name": "Alice's Mobile Phone"
  41. }
  42. ]
  43. }
  44. """
  45. NAME = "user_device_resync"
  46. PATH_ARGS = ("user_id",)
  47. CACHE = False
  48. def __init__(self, hs: "HomeServer"):
  49. super().__init__(hs)
  50. from synapse.handlers.device import DeviceHandler
  51. handler = hs.get_device_handler()
  52. assert isinstance(handler, DeviceHandler)
  53. self.device_list_updater = handler.device_list_updater
  54. self.store = hs.get_datastores().main
  55. self.clock = hs.get_clock()
  56. @staticmethod
  57. async def _serialize_payload(user_id: str) -> JsonDict: # type: ignore[override]
  58. return {}
  59. async def _handle_request( # type: ignore[override]
  60. self, request: Request, content: JsonDict, user_id: str
  61. ) -> Tuple[int, Optional[JsonDict]]:
  62. user_devices = await self.device_list_updater.user_device_resync(user_id)
  63. return 200, user_devices
  64. class ReplicationMultiUserDevicesResyncRestServlet(ReplicationEndpoint):
  65. """Ask master to resync the device list for multiple users from the same
  66. remote server by contacting their server.
  67. This must happen on master so that the results can be correctly cached in
  68. the database and streamed to workers.
  69. Request format:
  70. POST /_synapse/replication/multi_user_device_resync
  71. {
  72. "user_ids": ["@alice:example.org", "@bob:example.org", ...]
  73. }
  74. Response is roughly equivalent to ` /_matrix/federation/v1/user/devices/:user_id`
  75. response, but there is a map from user ID to response, e.g.:
  76. {
  77. "@alice:example.org": {
  78. "devices": [
  79. {
  80. "device_id": "JLAFKJWSCS",
  81. "keys": { ... },
  82. "device_display_name": "Alice's Mobile Phone"
  83. }
  84. ]
  85. },
  86. ...
  87. }
  88. """
  89. NAME = "multi_user_device_resync"
  90. PATH_ARGS = ()
  91. CACHE = False
  92. def __init__(self, hs: "HomeServer"):
  93. super().__init__(hs)
  94. from synapse.handlers.device import DeviceHandler
  95. handler = hs.get_device_handler()
  96. assert isinstance(handler, DeviceHandler)
  97. self.device_list_updater = handler.device_list_updater
  98. self.store = hs.get_datastores().main
  99. self.clock = hs.get_clock()
  100. @staticmethod
  101. async def _serialize_payload(user_ids: List[str]) -> JsonDict: # type: ignore[override]
  102. return {"user_ids": user_ids}
  103. async def _handle_request( # type: ignore[override]
  104. self, request: Request, content: JsonDict
  105. ) -> Tuple[int, Dict[str, Optional[JsonDict]]]:
  106. user_ids: List[str] = content["user_ids"]
  107. logger.info("Resync for %r", user_ids)
  108. span = active_span()
  109. if span:
  110. span.set_tag("user_ids", f"{user_ids!r}")
  111. multi_user_devices = await self.device_list_updater.multi_user_device_resync(
  112. user_ids
  113. )
  114. return 200, multi_user_devices
  115. class ReplicationUploadKeysForUserRestServlet(ReplicationEndpoint):
  116. """Ask master to upload keys for the user and send them out over federation to
  117. update other servers.
  118. For now, only the master is permitted to handle key upload requests;
  119. any worker can handle key query requests (since they're read-only).
  120. Calls to e2e_keys_handler.upload_keys_for_user(user_id, device_id, keys) on
  121. the main process to accomplish this.
  122. Defined in https://spec.matrix.org/v1.4/client-server-api/#post_matrixclientv3keysupload
  123. Request format(borrowed and expanded from KeyUploadServlet):
  124. POST /_synapse/replication/upload_keys_for_user
  125. {
  126. "user_id": "<user_id>",
  127. "device_id": "<device_id>",
  128. "keys": {
  129. ....this part can be found in KeyUploadServlet in rest/client/keys.py....
  130. }
  131. }
  132. Response is equivalent to ` /_matrix/client/v3/keys/upload` found in KeyUploadServlet
  133. """
  134. NAME = "upload_keys_for_user"
  135. PATH_ARGS = ()
  136. CACHE = False
  137. def __init__(self, hs: "HomeServer"):
  138. super().__init__(hs)
  139. self.e2e_keys_handler = hs.get_e2e_keys_handler()
  140. self.store = hs.get_datastores().main
  141. self.clock = hs.get_clock()
  142. @staticmethod
  143. async def _serialize_payload( # type: ignore[override]
  144. user_id: str, device_id: str, keys: JsonDict
  145. ) -> JsonDict:
  146. return {
  147. "user_id": user_id,
  148. "device_id": device_id,
  149. "keys": keys,
  150. }
  151. async def _handle_request( # type: ignore[override]
  152. self, request: Request, content: JsonDict
  153. ) -> Tuple[int, JsonDict]:
  154. user_id = content["user_id"]
  155. device_id = content["device_id"]
  156. keys = content["keys"]
  157. results = await self.e2e_keys_handler.upload_keys_for_user(
  158. user_id, device_id, keys
  159. )
  160. return 200, results
  161. def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
  162. ReplicationUserDevicesResyncRestServlet(hs).register(http_server)
  163. ReplicationMultiUserDevicesResyncRestServlet(hs).register(http_server)
  164. ReplicationUploadKeysForUserRestServlet(hs).register(http_server)