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.
 
 
 
 
 
 

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