vtn_service.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # SPDX-License-Identifier: Apache-2.0
  2. # Copyright 2020 Contributors to OpenLEADR
  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. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from asyncio import iscoroutine
  13. from http import HTTPStatus
  14. import logging
  15. from aiohttp import web
  16. from lxml.etree import XMLSyntaxError
  17. from signxml.exceptions import InvalidSignature
  18. from .. import errors
  19. from ..enums import STATUS_CODES
  20. from ..messaging import parse_message, validate_xml_schema, authenticate_message
  21. from ..utils import generate_id, get_cert_fingerprint_from_request
  22. from dataclasses import is_dataclass, asdict
  23. logger = logging.getLogger('openleadr')
  24. class VTNService:
  25. def __init__(self, vtn_id):
  26. self.vtn_id = vtn_id
  27. self.handlers = {}
  28. for method in [getattr(self, attr) for attr in dir(self) if callable(getattr(self, attr))]:
  29. if hasattr(method, '__message_type__'):
  30. self.handlers[method.__message_type__] = method
  31. async def handler(self, request):
  32. """
  33. Handle all incoming POST requests.
  34. """
  35. try:
  36. # Check the Content-Type header
  37. content_type = request.headers.get('content-type', '')
  38. if not content_type.lower().startswith("application/xml"):
  39. raise errors.HTTPError(response_code=HTTPStatus.BAD_REQUEST,
  40. response_description="The Content-Type header must be application/xml, "
  41. "you provided {request.headers.get('content-type', '')}")
  42. content = await request.read()
  43. # Validate the message to the XML Schema
  44. message_tree = validate_xml_schema(content)
  45. # Parse the message to a type and payload dict
  46. message_type, message_payload = parse_message(content)
  47. # Authenticate the message
  48. if request.secure and 'ven_id' in message_payload:
  49. await authenticate_message(request, message_tree, message_payload,
  50. self.fingerprint_lookup)
  51. # Pass the message off to the handler and get the response type and payload
  52. try:
  53. # Add the request fingerprint to the message so that the handler can check for it.
  54. if request.secure and message_type == 'oadrCreatePartyRegistration':
  55. message_payload['fingerprint'] = get_cert_fingerprint_from_request(request)
  56. response_type, response_payload = await self.handle_message(message_type,
  57. message_payload)
  58. except Exception as err:
  59. logger.error("An exception occurred during the execution of your "
  60. f"{self.__class__.__name__} handler: "
  61. f"{err.__class__.__name__}: {err}")
  62. raise err
  63. if 'response' not in response_payload:
  64. response_payload['response'] = {'response_code': 200,
  65. 'response_description': 'OK',
  66. 'request_id': message_payload.get('request_id')}
  67. response_payload['vtn_id'] = self.vtn_id
  68. if 'ven_id' not in response_payload:
  69. response_payload['ven_id'] = message_payload.get('ven_id')
  70. except errors.ProtocolError as err:
  71. # In case of an OpenADR error, return a valid OpenADR message
  72. response_type, response_payload = self.error_response(message_type,
  73. err.response_code,
  74. err.response_description)
  75. msg = self._create_message(response_type, **response_payload)
  76. response = web.Response(text=msg,
  77. status=HTTPStatus.OK,
  78. content_type='application/xml')
  79. except errors.HTTPError as err:
  80. # If we throw a http-related error, deal with it here
  81. response = web.Response(text=err.response_description,
  82. status=err.response_code)
  83. except XMLSyntaxError as err:
  84. logger.warning(f"XML schema validation of incoming message failed: {err}.")
  85. response = web.Response(text=f'XML failed validation: {err}',
  86. status=HTTPStatus.BAD_REQUEST)
  87. except errors.FingerprintMismatch as err:
  88. logger.warning(err)
  89. response = web.Response(text=str(err),
  90. status=HTTPStatus.FORBIDDEN)
  91. except InvalidSignature:
  92. logger.warning("Incoming message had invalid signature, ignoring.")
  93. response = web.Response(text='Invalid Signature',
  94. status=HTTPStatus.FORBIDDEN)
  95. except Exception as err:
  96. # In case of some other error, return a HTTP 500
  97. logger.error(f"The VTN server encountered an error: {err.__class__.__name__}: {err}")
  98. response = web.Response(status=HTTPStatus.INTERNAL_SERVER_ERROR)
  99. else:
  100. # We've successfully handled this message
  101. msg = self._create_message(response_type, **response_payload)
  102. response = web.Response(text=msg,
  103. status=HTTPStatus.OK,
  104. content_type='application/xml')
  105. return response
  106. async def handle_message(self, message_type, message_payload):
  107. if message_type in self.handlers:
  108. handler = self.handlers[message_type]
  109. result = handler(message_payload)
  110. if iscoroutine(result):
  111. result = await result
  112. if result is not None:
  113. response_type, response_payload = result
  114. if is_dataclass(response_payload):
  115. response_payload = asdict(response_payload)
  116. elif response_payload is None:
  117. response_payload = {}
  118. else:
  119. response_type, response_payload = 'oadrResponse', {}
  120. response_payload['vtn_id'] = self.vtn_id
  121. if 'ven_id' in message_payload:
  122. response_payload['ven_id'] = message_payload['ven_id']
  123. response_payload['response'] = {'request_id': message_payload.get('request_id', None),
  124. 'response_code': 200,
  125. 'response_description': 'OK'}
  126. response_payload['request_id'] = generate_id()
  127. else:
  128. response_type, response_payload = self.error_response('oadrResponse',
  129. STATUS_CODES.COMPLIANCE_ERROR,
  130. "A message of type "
  131. f"{message_type} should not be "
  132. "sent to this endpoint")
  133. logger.info(f"Responding to {message_type} with a {response_type} message: {response_payload}.")
  134. return response_type, response_payload
  135. def error_response(self, message_type, error_code, error_description):
  136. if message_type == 'oadrCreatePartyRegistration':
  137. response_type = 'oadrCreatedPartyRegistration'
  138. if message_type == 'oadrRequestEvent':
  139. response_type = 'oadrDistributeEvent'
  140. else:
  141. response_type = 'oadrResponse'
  142. response_payload = {'response': {'response_code': error_code,
  143. 'response_description': error_description}}
  144. return response_type, response_payload