provisioning_api.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. self.app.router.add_get("/api/whoami", self.status)
  39. self.app.router.add_options("/api/link", self.login_options)
  40. self.app.router.add_options("/api/link/wait", self.login_options)
  41. # self.app.router.add_options("/api/register", self.login_options)
  42. # self.app.router.add_options("/api/register/code", self.login_options)
  43. self.app.router.add_options("/api/logout", self.login_options)
  44. self.app.router.add_post("/api/link", self.link)
  45. self.app.router.add_post("/api/link/wait_for_scan", self.link_wait_for_scan)
  46. self.app.router.add_post("/api/link/wait", self.link_wait)
  47. # self.app.router.add_post("/api/register", self.register)
  48. # self.app.router.add_post("/api/register/code", self.register_code)
  49. self.app.router.add_post("/api/logout", self.logout)
  50. @property
  51. def _acao_headers(self) -> dict[str, str]:
  52. return {
  53. "Access-Control-Allow-Origin": "*",
  54. "Access-Control-Allow-Headers": "Authorization, Content-Type",
  55. "Access-Control-Allow-Methods": "POST, OPTIONS",
  56. }
  57. @property
  58. def _headers(self) -> dict[str, str]:
  59. return {
  60. **self._acao_headers,
  61. "Content-Type": "application/json",
  62. }
  63. async def login_options(self, _: web.Request) -> web.Response:
  64. return web.Response(status=200, headers=self._headers)
  65. async def check_token(self, request: web.Request) -> "u.User":
  66. try:
  67. token = request.headers["Authorization"]
  68. token = token[len("Bearer ") :]
  69. except KeyError:
  70. raise web.HTTPBadRequest(
  71. text='{"error": "Missing Authorization header"}', headers=self._headers
  72. )
  73. except IndexError:
  74. raise web.HTTPBadRequest(
  75. text='{"error": "Malformed Authorization header"}', headers=self._headers
  76. )
  77. if token != self.shared_secret:
  78. raise web.HTTPForbidden(text='{"error": "Invalid token"}', headers=self._headers)
  79. try:
  80. user_id = request.query["user_id"]
  81. except KeyError:
  82. raise web.HTTPBadRequest(
  83. text='{"error": "Missing user_id query param"}', headers=self._headers
  84. )
  85. if not self.bridge.signal.is_connected:
  86. await self.bridge.signal.wait_for_connected()
  87. return await u.User.get_by_mxid(UserID(user_id))
  88. async def status(self, request: web.Request) -> web.Response:
  89. user = await self.check_token(request)
  90. data = {
  91. "permissions": user.permission_level,
  92. "mxid": user.mxid,
  93. "signal": None,
  94. }
  95. if await user.is_logged_in():
  96. try:
  97. profile = await self.bridge.signal.get_profile(
  98. username=user.username, address=Address(number=user.username)
  99. )
  100. except Exception as e:
  101. self.log.exception(f"Failed to get {user.username}'s profile for whoami")
  102. auth_failed = "org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException"
  103. if isinstance(e, InternalError) and auth_failed in e.data.get("exceptions", []):
  104. await user.push_bridge_state(BridgeStateEvent.BAD_CREDENTIALS, error=str(e))
  105. data["signal"] = {
  106. "number": user.username,
  107. "ok": False,
  108. "error": str(e),
  109. }
  110. else:
  111. addr = profile.address if profile else None
  112. number = addr.number if addr else None
  113. uuid = addr.uuid if addr else None
  114. data["signal"] = {
  115. "number": number or user.username,
  116. "uuid": str(uuid or user.uuid or ""),
  117. "name": profile.name if profile else None,
  118. "ok": True,
  119. }
  120. return web.json_response(data, headers=self._acao_headers)
  121. async def link(self, request: web.Request) -> web.Response:
  122. user = await self.check_token(request)
  123. if await user.is_logged_in():
  124. raise web.HTTPConflict(
  125. text="""{"error": "You're already logged in"}""", headers=self._headers
  126. )
  127. try:
  128. data = await request.json()
  129. except json.JSONDecodeError:
  130. raise web.HTTPBadRequest(text='{"error": "Malformed JSON"}', headers=self._headers)
  131. device_name = data.get("device_name", "Mautrix-Signal bridge")
  132. sess = await self.bridge.signal.start_link()
  133. user.command_status = {
  134. "action": "Link",
  135. "session_id": sess.session_id,
  136. "device_name": device_name,
  137. }
  138. self.log.debug(f"Returning linking URI for {user.mxid} / {sess.session_id}")
  139. return web.json_response({"uri": sess.uri}, headers=self._acao_headers)
  140. async def link_wait_for_scan(self, request: web.Request) -> web.Response:
  141. user = await self.check_token(request)
  142. if not user.command_status or user.command_status["action"] != "Link":
  143. raise web.HTTPBadRequest(
  144. text='{"error": "No Signal linking started"}', headers=self._headers
  145. )
  146. session_id = user.command_status["session_id"]
  147. try:
  148. await self.bridge.signal.wait_for_scan(session_id)
  149. status_endpoint = self.bridge.config["homeserver.status_endpoint"]
  150. if status_endpoint:
  151. state = BridgeState(state_event=BridgeStateEvent.CONNECTING).fill()
  152. asyncio.create_task(state.send(status_endpoint, self.bridge.az.as_token, self.log))
  153. except Exception as e:
  154. self.log.exception(f"Failed waiting for scan. Error: {e}")
  155. self.log.info(e.__class__)
  156. raise web.HTTPBadRequest(
  157. text='{"error": "Failed to wait for scan"}', headers=self._headers
  158. )
  159. else:
  160. return web.json_response()
  161. async def _shielded_link(self, user: "u.User", session_id: str, device_name: str) -> Account:
  162. try:
  163. self.log.debug(f"Starting finish link request for {user.mxid} / {session_id}")
  164. account = await self.bridge.signal.finish_link(
  165. session_id=session_id, overwrite=True, device_name=device_name
  166. )
  167. except TimeoutException:
  168. self.log.warning(f"Timed out waiting for linking to finish (session {session_id})")
  169. raise
  170. except Exception:
  171. self.log.exception(
  172. f"Fatal error while waiting for linking to finish (session {session_id})"
  173. )
  174. raise
  175. else:
  176. await user.on_signin(account)
  177. return account
  178. async def link_wait(self, request: web.Request) -> web.Response:
  179. user = await self.check_token(request)
  180. if not user.command_status or user.command_status["action"] != "Link":
  181. raise web.HTTPBadRequest(
  182. text='{"error": "No Signal linking started"}', headers=self._headers
  183. )
  184. session_id = user.command_status["session_id"]
  185. device_name = user.command_status["device_name"]
  186. try:
  187. account = await asyncio.shield(self._shielded_link(user, session_id, device_name))
  188. except asyncio.CancelledError:
  189. self.log.warning(
  190. f"Client cancelled link wait request ({session_id}) before it finished"
  191. )
  192. except TimeoutException:
  193. raise web.HTTPBadRequest(
  194. text='{"error": "Signal linking timed out"}', headers=self._headers
  195. )
  196. except InternalError as ie:
  197. if "java.io.IOException" in ie.exceptions:
  198. raise web.HTTPBadRequest(
  199. text='{"error": "Signald websocket disconnected before linking finished"}',
  200. headers=self._headers,
  201. )
  202. raise web.HTTPInternalServerError(
  203. text='{"error": "Fatal error in Signal linking"}', headers=self._headers
  204. )
  205. except Exception:
  206. raise web.HTTPInternalServerError(
  207. text='{"error": "Fatal error in Signal linking"}', headers=self._headers
  208. )
  209. else:
  210. return web.json_response(account.address.serialize())
  211. async def logout(self, request: web.Request) -> web.Response:
  212. user = await self.check_token(request)
  213. if not await user.is_logged_in():
  214. raise web.HTTPNotFound(
  215. text="""{"error": "You're not logged in"}""", headers=self._headers
  216. )
  217. await user.logout()
  218. return web.json_response({}, headers=self._acao_headers)