You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

64 lines
2.1 KiB

  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  2. #
  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. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Any, Iterable
  15. import jsonschema
  16. from synapse.config._base import ConfigError
  17. from synapse.types import JsonDict
  18. def validate_config(
  19. json_schema: JsonDict, config: Any, config_path: Iterable[str]
  20. ) -> None:
  21. """Validates a config setting against a JsonSchema definition
  22. This can be used to validate a section of the config file against a schema
  23. definition. If the validation fails, a ConfigError is raised with a textual
  24. description of the problem.
  25. Args:
  26. json_schema: the schema to validate against
  27. config: the configuration value to be validated
  28. config_path: the path within the config file. This will be used as a basis
  29. for the error message.
  30. """
  31. try:
  32. jsonschema.validate(config, json_schema)
  33. except jsonschema.ValidationError as e:
  34. raise json_error_to_config_error(e, config_path)
  35. def json_error_to_config_error(
  36. e: jsonschema.ValidationError, config_path: Iterable[str]
  37. ) -> ConfigError:
  38. """Converts a json validation error to a user-readable ConfigError
  39. Args:
  40. e: the exception to be converted
  41. config_path: the path within the config file. This will be used as a basis
  42. for the error message.
  43. Returns:
  44. a ConfigError
  45. """
  46. # copy `config_path` before modifying it.
  47. path = list(config_path)
  48. for p in list(e.absolute_path):
  49. if isinstance(p, int):
  50. path.append("<item %i>" % p)
  51. else:
  52. path.append(str(p))
  53. return ConfigError(e.message, path)