identity.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. # Copyright 2017 Vector Creations Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Utilities for interacting with Identity Servers"""
  17. import logging
  18. import simplejson as json
  19. from twisted.internet import defer
  20. from synapse.api.errors import (
  21. MatrixCodeMessageException, CodeMessageException
  22. )
  23. from ._base import BaseHandler
  24. from synapse.util.async import run_on_reactor
  25. from synapse.api.errors import SynapseError, Codes
  26. logger = logging.getLogger(__name__)
  27. class IdentityHandler(BaseHandler):
  28. def __init__(self, hs):
  29. super(IdentityHandler, self).__init__(hs)
  30. self.http_client = hs.get_simple_http_client()
  31. self.trusted_id_servers = set(hs.config.trusted_third_party_id_servers)
  32. self.trust_any_id_server_just_for_testing_do_not_use = (
  33. hs.config.use_insecure_ssl_client_just_for_testing_do_not_use
  34. )
  35. def _should_trust_id_server(self, id_server):
  36. if id_server not in self.trusted_id_servers:
  37. if self.trust_any_id_server_just_for_testing_do_not_use:
  38. logger.warn(
  39. "Trusting untrustworthy ID server %r even though it isn't"
  40. " in the trusted id list for testing because"
  41. " 'use_insecure_ssl_client_just_for_testing_do_not_use'"
  42. " is set in the config",
  43. id_server,
  44. )
  45. else:
  46. return False
  47. return True
  48. @defer.inlineCallbacks
  49. def threepid_from_creds(self, creds):
  50. yield run_on_reactor()
  51. if 'id_server' in creds:
  52. id_server = creds['id_server']
  53. elif 'idServer' in creds:
  54. id_server = creds['idServer']
  55. else:
  56. raise SynapseError(400, "No id_server in creds")
  57. if 'client_secret' in creds:
  58. client_secret = creds['client_secret']
  59. elif 'clientSecret' in creds:
  60. client_secret = creds['clientSecret']
  61. else:
  62. raise SynapseError(400, "No client_secret in creds")
  63. if not self._should_trust_id_server(id_server):
  64. logger.warn(
  65. '%s is not a trusted ID server: rejecting 3pid ' +
  66. 'credentials', id_server
  67. )
  68. defer.returnValue(None)
  69. data = {}
  70. try:
  71. data = yield self.http_client.get_json(
  72. "https://%s%s" % (
  73. id_server,
  74. "/_matrix/identity/api/v1/3pid/getValidated3pid"
  75. ),
  76. {'sid': creds['sid'], 'client_secret': client_secret}
  77. )
  78. except MatrixCodeMessageException as e:
  79. logger.info("getValidated3pid failed with Matrix error: %r", e)
  80. raise SynapseError(e.code, e.msg, e.errcode)
  81. except CodeMessageException as e:
  82. data = json.loads(e.msg)
  83. if 'medium' in data:
  84. defer.returnValue(data)
  85. defer.returnValue(None)
  86. @defer.inlineCallbacks
  87. def bind_threepid(self, creds, mxid):
  88. yield run_on_reactor()
  89. logger.debug("binding threepid %r to %s", creds, mxid)
  90. data = None
  91. if 'id_server' in creds:
  92. id_server = creds['id_server']
  93. elif 'idServer' in creds:
  94. id_server = creds['idServer']
  95. else:
  96. raise SynapseError(400, "No id_server in creds")
  97. if 'client_secret' in creds:
  98. client_secret = creds['client_secret']
  99. elif 'clientSecret' in creds:
  100. client_secret = creds['clientSecret']
  101. else:
  102. raise SynapseError(400, "No client_secret in creds")
  103. try:
  104. data = yield self.http_client.post_urlencoded_get_json(
  105. "https://%s%s" % (
  106. id_server, "/_matrix/identity/api/v1/3pid/bind"
  107. ),
  108. {
  109. 'sid': creds['sid'],
  110. 'client_secret': client_secret,
  111. 'mxid': mxid,
  112. }
  113. )
  114. logger.debug("bound threepid %r to %s", creds, mxid)
  115. except CodeMessageException as e:
  116. data = json.loads(e.msg)
  117. defer.returnValue(data)
  118. @defer.inlineCallbacks
  119. def requestEmailToken(self, id_server, email, client_secret, send_attempt, **kwargs):
  120. yield run_on_reactor()
  121. if not self._should_trust_id_server(id_server):
  122. raise SynapseError(
  123. 400, "Untrusted ID server '%s'" % id_server,
  124. Codes.SERVER_NOT_TRUSTED
  125. )
  126. params = {
  127. 'email': email,
  128. 'client_secret': client_secret,
  129. 'send_attempt': send_attempt,
  130. }
  131. params.update(kwargs)
  132. try:
  133. data = yield self.http_client.post_json_get_json(
  134. "https://%s%s" % (
  135. id_server,
  136. "/_matrix/identity/api/v1/validate/email/requestToken"
  137. ),
  138. params
  139. )
  140. defer.returnValue(data)
  141. except MatrixCodeMessageException as e:
  142. logger.info("Proxied requestToken failed with Matrix error: %r", e)
  143. raise SynapseError(e.code, e.msg, e.errcode)
  144. except CodeMessageException as e:
  145. logger.info("Proxied requestToken failed: %r", e)
  146. raise e
  147. @defer.inlineCallbacks
  148. def requestMsisdnToken(
  149. self, id_server, country, phone_number,
  150. client_secret, send_attempt, **kwargs
  151. ):
  152. yield run_on_reactor()
  153. if not self._should_trust_id_server(id_server):
  154. raise SynapseError(
  155. 400, "Untrusted ID server '%s'" % id_server,
  156. Codes.SERVER_NOT_TRUSTED
  157. )
  158. params = {
  159. 'country': country,
  160. 'phone_number': phone_number,
  161. 'client_secret': client_secret,
  162. 'send_attempt': send_attempt,
  163. }
  164. params.update(kwargs)
  165. try:
  166. data = yield self.http_client.post_json_get_json(
  167. "https://%s%s" % (
  168. id_server,
  169. "/_matrix/identity/api/v1/validate/msisdn/requestToken"
  170. ),
  171. params
  172. )
  173. defer.returnValue(data)
  174. except MatrixCodeMessageException as e:
  175. logger.info("Proxied requestToken failed with Matrix error: %r", e)
  176. raise SynapseError(e.code, e.msg, e.errcode)
  177. except CodeMessageException as e:
  178. logger.info("Proxied requestToken failed: %r", e)
  179. raise e