provisioning_api.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # mautrix-signal - A Matrix-Signal puppeting bridge
  2. # Copyright (C) 2020 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from __future__ import annotations
  17. from typing import TYPE_CHECKING
  18. import asyncio
  19. import json
  20. import logging
  21. from aiohttp import web
  22. from mausignald.errors import InternalError, TimeoutException
  23. from mausignald.types import Account, Address
  24. from mautrix.types import UserID
  25. from mautrix.util.bridge_state import BridgeState, BridgeStateEvent
  26. from mautrix.util.logging import TraceLogger
  27. from .. import user as u
  28. if TYPE_CHECKING:
  29. from ..__main__ import SignalBridge
  30. class ProvisioningAPI:
  31. log: TraceLogger = logging.getLogger("mau.web.provisioning")
  32. app: web.Application
  33. bridge: "SignalBridge"
  34. def __init__(self, bridge: "SignalBridge", shared_secret: str) -> None:
  35. self.bridge = bridge
  36. self.app = web.Application()
  37. self.shared_secret = shared_secret
  38. # Whoami
  39. self.app.router.add_get("/v1/api/whoami", self.status)
  40. self.app.router.add_get("/v2/whoami", self.status)
  41. # Logout
  42. self.app.router.add_options("/v1/api/logout", self.login_options)
  43. self.app.router.add_post("/v1/api/logout", self.logout)
  44. self.app.router.add_options("/v2/logout", self.login_options)
  45. self.app.router.add_post("/v2/logout", self.logout)
  46. # Link API (will be deprecated soon)
  47. self.app.router.add_options("/v1/api/link", self.login_options)
  48. self.app.router.add_options("/v1/api/link/wait", self.login_options)
  49. self.app.router.add_post("/v1/api/link", self.link)
  50. self.app.router.add_post("/v1/api/link/wait", self.link_wait)
  51. # New Login API
  52. self.app.router.add_options("/v2/link/new", self.login_options)
  53. self.app.router.add_options("/v2/link/wait/scan", self.login_options)
  54. self.app.router.add_options("/v2/link/wait/account", self.login_options)
  55. self.app.router.add_post("/v2/link/new", self.link_new)
  56. self.app.router.add_post("/v2/link/wait/scan", self.link_wait_for_scan)
  57. self.app.router.add_post("/v2/link/wait/account", self.link_wait_for_account)
  58. @property
  59. def _acao_headers(self) -> dict[str, str]:
  60. return {
  61. "Access-Control-Allow-Origin": "*",
  62. "Access-Control-Allow-Headers": "Authorization, Content-Type",
  63. "Access-Control-Allow-Methods": "POST, OPTIONS",
  64. }
  65. @property
  66. def _headers(self) -> dict[str, str]:
  67. return {
  68. **self._acao_headers,
  69. "Content-Type": "application/json",
  70. }
  71. async def login_options(self, _: web.Request) -> web.Response:
  72. return web.Response(status=200, headers=self._headers)
  73. async def check_token(self, request: web.Request) -> "u.User":
  74. try:
  75. token = request.headers["Authorization"]
  76. token = token[len("Bearer ") :]
  77. except KeyError:
  78. raise web.HTTPBadRequest(
  79. text='{"error": "Missing Authorization header"}', headers=self._headers
  80. )
  81. except IndexError:
  82. raise web.HTTPBadRequest(
  83. text='{"error": "Malformed Authorization header"}', headers=self._headers
  84. )
  85. if token != self.shared_secret:
  86. raise web.HTTPForbidden(text='{"error": "Invalid token"}', headers=self._headers)
  87. try:
  88. user_id = request.query["user_id"]
  89. except KeyError:
  90. raise web.HTTPBadRequest(
  91. text='{"error": "Missing user_id query param"}', headers=self._headers
  92. )
  93. if not self.bridge.signal.is_connected:
  94. await self.bridge.signal.wait_for_connected()
  95. return await u.User.get_by_mxid(UserID(user_id))
  96. async def status(self, request: web.Request) -> web.Response:
  97. user = await self.check_token(request)
  98. data = {
  99. "permissions": user.permission_level,
  100. "mxid": user.mxid,
  101. "signal": None,
  102. }
  103. if await user.is_logged_in():
  104. try:
  105. profile = await self.bridge.signal.get_profile(
  106. username=user.username, address=Address(number=user.username)
  107. )
  108. except Exception as e:
  109. self.log.exception(f"Failed to get {user.username}'s profile for whoami")
  110. auth_failed = "org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException"
  111. if isinstance(e, InternalError) and auth_failed in e.data.get("exceptions", []):
  112. await user.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=str(e))
  113. data["signal"] = {
  114. "number": user.username,
  115. "ok": False,
  116. "error": str(e),
  117. }
  118. else:
  119. addr = profile.address if profile else None
  120. number = addr.number if addr else None
  121. uuid = addr.uuid if addr else None
  122. data["signal"] = {
  123. "number": number or user.username,
  124. "uuid": str(uuid or user.uuid or ""),
  125. "name": profile.name if profile else None,
  126. "ok": True,
  127. }
  128. return web.json_response(data, headers=self._acao_headers)
  129. async def _shielded_link(self, user: "u.User", session_id: str, device_name: str) -> Account:
  130. try:
  131. self.log.debug(f"Starting finish link request for {user.mxid} / {session_id}")
  132. account = await self.bridge.signal.finish_link(
  133. session_id=session_id, device_name=device_name, overwrite=True
  134. )
  135. except TimeoutException:
  136. self.log.warning(f"Timed out waiting for linking to finish (session {session_id})")
  137. raise
  138. except Exception:
  139. self.log.exception(
  140. f"Fatal error while waiting for linking to finish (session {session_id})"
  141. )
  142. raise
  143. else:
  144. await user.on_signin(account)
  145. return account
  146. async def _try_shielded_link(
  147. self, user: "u.User", session_id: str, device_name: str
  148. ) -> web.Response:
  149. try:
  150. account = await asyncio.shield(self._shielded_link(user, session_id, device_name))
  151. except asyncio.CancelledError:
  152. error_text = f"Client cancelled link wait request ({session_id}) before it finished"
  153. self.log.warning(error_text)
  154. raise web.HTTPInternalServerError(
  155. text=f'{{"error": "{error_text}"}}', headers=self._headers
  156. )
  157. except TimeoutException:
  158. raise web.HTTPBadRequest(
  159. text='{"error": "Signal linking timed out"}', headers=self._headers
  160. )
  161. except InternalError as ie:
  162. if "java.io.IOException" in ie.exceptions:
  163. raise web.HTTPBadRequest(
  164. text='{"error": "Signald websocket disconnected before linking finished"}',
  165. headers=self._headers,
  166. )
  167. raise web.HTTPInternalServerError(
  168. text='{"error": "Fatal error in Signal linking"}', headers=self._headers
  169. )
  170. except Exception:
  171. raise web.HTTPInternalServerError(
  172. text='{"error": "Fatal error in Signal linking"}', headers=self._headers
  173. )
  174. else:
  175. return web.json_response(account.address.serialize())
  176. # region Old Link API
  177. async def link(self, request: web.Request) -> web.Response:
  178. user = await self.check_token(request)
  179. if await user.is_logged_in():
  180. raise web.HTTPConflict(
  181. text="""{"error": "You're already logged in"}""", headers=self._headers
  182. )
  183. try:
  184. data = await request.json()
  185. except json.JSONDecodeError:
  186. raise web.HTTPBadRequest(text='{"error": "Malformed JSON"}', headers=self._headers)
  187. device_name = data.get("device_name", "Mautrix-Signal bridge")
  188. sess = await self.bridge.signal.start_link()
  189. user.command_status = {
  190. "action": "Link",
  191. "session_id": sess.session_id,
  192. "device_name": device_name,
  193. }
  194. self.log.debug(f"Returning linking URI for {user.mxid} / {sess.session_id}")
  195. return web.json_response({"uri": sess.uri}, headers=self._acao_headers)
  196. async def link_wait(self, request: web.Request) -> web.Response:
  197. user = await self.check_token(request)
  198. if not user.command_status or user.command_status["action"] != "Link":
  199. raise web.HTTPBadRequest(
  200. text='{"error": "No Signal linking started"}', headers=self._headers
  201. )
  202. session_id = user.command_status["session_id"]
  203. device_name = user.command_status["device_name"]
  204. return await self._try_shielded_link(user, session_id, device_name)
  205. # endregion
  206. # region New Link API
  207. async def _get_request_data(self, request: web.Request) -> tuple[u.User, web.Response]:
  208. user = await self.check_token(request)
  209. if await user.is_logged_in():
  210. error_text = """{"error": "You're already logged in"}"""
  211. raise web.HTTPConflict(text=error_text, headers=self._headers)
  212. try:
  213. return user, (await request.json())
  214. except json.JSONDecodeError:
  215. raise web.HTTPBadRequest(text='{"error": "Malformed JSON"}', headers=self._headers)
  216. async def link_new(self, request: web.Request) -> web.Response:
  217. """
  218. Starts a new link session.
  219. Params: none
  220. Returns a JSON object with the following fields:
  221. * session_id: a session ID that should be used for all future link-related commands
  222. (wait_for_scan and wait_for_account).
  223. * uri: a URI that should be used to display the QR code.
  224. """
  225. user, _ = await self._get_request_data(request)
  226. self.log.debug(f"Getting session ID and link URI for {user.mxid}")
  227. sess = await self.bridge.signal.start_link()
  228. self.log.debug(f"Returning session ID and link URI for {user.mxid} / {sess.session_id}")
  229. return web.json_response(sess, headers=self._acao_headers)
  230. async def link_wait_for_scan(self, request: web.Request) -> web.Response:
  231. """
  232. Waits for the QR code associated with the provided session ID to be scanned.
  233. Params: a JSON object with the following field:
  234. * session_id: a session ID that you got from a call to /link/v2/new.
  235. """
  236. _, request_data = await self._get_request_data(request)
  237. try:
  238. session_id = request_data["session_id"]
  239. except KeyError:
  240. error_text = '{"error": "session_id not provided"}'
  241. raise web.HTTPBadRequest(text=error_text, headers=self._headers)
  242. try:
  243. await self.bridge.signal.wait_for_scan(session_id)
  244. except Exception as e:
  245. error_text = f"Failed waiting for scan. Error: {e}"
  246. self.log.exception(error_text)
  247. self.log.info(e.__class__)
  248. raise web.HTTPBadRequest(text=error_text, headers=self._headers)
  249. else:
  250. return web.json_response({}, headers=self._acao_headers)
  251. async def link_wait_for_account(self, request: web.Request) -> web.Response:
  252. """
  253. Waits for the link to the user's phone to complete.
  254. Params: a JSON object with the following fields:
  255. * session_id: a session ID that you got from a call to /link/v2/new.
  256. * device_name: the device name that will show up in Linked Devices on the user's device.
  257. Returns: a JSON object representing the user's account.
  258. """
  259. user, request_data = await self._get_request_data(request)
  260. try:
  261. session_id = request_data["session_id"]
  262. device_name = request_data.get("device_name", "Mautrix-Signal bridge")
  263. except KeyError:
  264. error_text = '{"error": "session_id not provided"}'
  265. raise web.HTTPBadRequest(text=error_text, headers=self._headers)
  266. return await self._try_shielded_link(user, session_id, device_name)
  267. async def logout(self, request: web.Request) -> web.Response:
  268. user = await self.check_token(request)
  269. if not await user.is_logged_in():
  270. raise web.HTTPNotFound(
  271. text="""{"error": "You're not logged in"}""", headers=self._headers
  272. )
  273. await user.logout()
  274. return web.json_response({}, headers=self._acao_headers)