registerservlet.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import absolute_import
  16. from twisted.web.resource import Resource
  17. from twisted.internet import defer
  18. import logging
  19. import json
  20. from six.moves import urllib
  21. from sydent.http.servlets import get_args, jsonwrap, deferjsonwrap, send_cors
  22. from sydent.http.httpclient import FederationHttpClient
  23. from sydent.users.tokens import issueToken
  24. from sydent.util.stringutils import is_valid_matrix_server_name
  25. logger = logging.getLogger(__name__)
  26. class RegisterServlet(Resource):
  27. isLeaf = True
  28. def __init__(self, syd):
  29. self.sydent = syd
  30. self.client = FederationHttpClient(self.sydent)
  31. @deferjsonwrap
  32. @defer.inlineCallbacks
  33. def render_POST(self, request):
  34. """
  35. Register with the Identity Server
  36. """
  37. send_cors(request)
  38. args = get_args(request, ('matrix_server_name', 'access_token'))
  39. matrix_server = args['matrix_server_name'].lower()
  40. if not is_valid_matrix_server_name(matrix_server):
  41. request.setResponseCode(400)
  42. return {
  43. 'errcode': 'M_INVALID_PARAM',
  44. 'error': 'matrix_server_name must be a valid Matrix server name (IP address or hostname)'
  45. }
  46. result = yield self.client.get_json(
  47. "matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s"
  48. % (
  49. matrix_server,
  50. urllib.parse.quote(args['access_token']),
  51. ),
  52. 1024 * 5,
  53. )
  54. if 'sub' not in result:
  55. raise Exception("Invalid response from homeserver")
  56. user_id = result['sub']
  57. if not isinstance(user_id, str):
  58. request.setResponseCode(500)
  59. return {
  60. 'errcode': 'M_UNKNOWN',
  61. 'error': 'The Matrix homeserver returned a malformed reply'
  62. }
  63. user_id_components = user_id.split(':', 1)
  64. # Ensure there's a localpart and domain in the returned user ID.
  65. if len(user_id_components) != 2:
  66. request.setResponseCode(500)
  67. return {
  68. 'errcode': 'M_UNKNOWN',
  69. 'error': 'The Matrix homeserver returned an invalid MXID'
  70. }
  71. user_id_server = user_id_components[1]
  72. if not is_valid_matrix_server_name(user_id_server):
  73. request.setResponseCode(500)
  74. return {
  75. 'errcode': 'M_UNKNOWN',
  76. 'error': 'The Matrix homeserver returned an invalid MXID'
  77. }
  78. if user_id_server != matrix_server:
  79. request.setResponseCode(500)
  80. return {
  81. 'errcode': 'M_UNKNOWN',
  82. 'error': 'The Matrix homeserver returned a MXID belonging to another homeserver'
  83. }
  84. tok = yield issueToken(self.sydent, user_id)
  85. # XXX: `token` is correct for the spec, but we released with `access_token`
  86. # for a substantial amount of time. Serve both to make spec-compliant clients
  87. # happy.
  88. defer.returnValue({
  89. "access_token": tok,
  90. "token": tok,
  91. })
  92. def render_OPTIONS(self, request):
  93. send_cors(request)
  94. return b''