_util.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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, Dict, Type, TypeVar
  15. import jsonschema
  16. from pydantic import BaseModel, ValidationError, parse_obj_as
  17. from synapse.config._base import ConfigError
  18. from synapse.types import JsonDict, StrSequence
  19. def validate_config(
  20. json_schema: JsonDict, config: Any, config_path: StrSequence
  21. ) -> None:
  22. """Validates a config setting against a JsonSchema definition
  23. This can be used to validate a section of the config file against a schema
  24. definition. If the validation fails, a ConfigError is raised with a textual
  25. description of the problem.
  26. Args:
  27. json_schema: the schema to validate against
  28. config: the configuration value to be validated
  29. config_path: the path within the config file. This will be used as a basis
  30. for the error message.
  31. Raises:
  32. ConfigError, if validation fails.
  33. """
  34. try:
  35. jsonschema.validate(config, json_schema)
  36. except jsonschema.ValidationError as e:
  37. raise json_error_to_config_error(e, config_path)
  38. def json_error_to_config_error(
  39. e: jsonschema.ValidationError, config_path: StrSequence
  40. ) -> ConfigError:
  41. """Converts a json validation error to a user-readable ConfigError
  42. Args:
  43. e: the exception to be converted
  44. config_path: the path within the config file. This will be used as a basis
  45. for the error message.
  46. Returns:
  47. a ConfigError
  48. """
  49. # copy `config_path` before modifying it.
  50. path = list(config_path)
  51. for p in list(e.absolute_path):
  52. if isinstance(p, int):
  53. path.append("<item %i>" % p)
  54. else:
  55. path.append(str(p))
  56. return ConfigError(e.message, path)
  57. Model = TypeVar("Model", bound=BaseModel)
  58. def parse_and_validate_mapping(
  59. config: Any,
  60. model_type: Type[Model],
  61. ) -> Dict[str, Model]:
  62. """Parse `config` as a mapping from strings to a given `Model` type.
  63. Args:
  64. config: The configuration data to check
  65. model_type: The BaseModel to validate and parse against.
  66. Returns:
  67. Fully validated and parsed Dict[str, Model].
  68. Raises:
  69. ConfigError, if given improper input.
  70. """
  71. try:
  72. # type-ignore: mypy doesn't like constructing `Dict[str, model_type]` because
  73. # `model_type` is a runtime variable. Pydantic is fine with this.
  74. instances = parse_obj_as(Dict[str, model_type], config) # type: ignore[valid-type]
  75. except ValidationError as e:
  76. raise ConfigError(str(e)) from e
  77. return instances