No Description
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.

validator.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. #-*- coding: utf-8 -*-
  2. import sys
  3. import os.path
  4. import re
  5. import socket
  6. import inspect
  7. import copy
  8. from lodel.context import LodelContext
  9. LodelContext.expose_modules(globals(), {
  10. 'lodel.mlnamedobject.mlnamedobject': ['MlNamedObject'],
  11. 'lodel.exceptions': ['LodelException', 'LodelExceptions',
  12. 'LodelFatalError', 'FieldValidationError']})
  13. # @package lodel.settings.validator Lodel2 settings validators/cast module
  14. #
  15. # Validator are registered in the Validator class.
  16. # @note to get a list of registered default validators just run
  17. # <pre>$ python scripts/settings_validator.py</pre>
  18. # @brief Exception class that should be raised when a validation fails
  19. class ValidationError(Exception):
  20. pass
  21. # @brief Handles settings validators
  22. #
  23. # Class instance are callable objects that takes a value argument (the value to validate). It raises
  24. # a ValidationError if validation fails, else it returns a properly
  25. # casted value.
  26. #@todo implement an IP validator and use it in multisite confspec
  27. class Validator(MlNamedObject):
  28. _validators = dict()
  29. _description = dict()
  30. # @brief Instanciate a validator
  31. #@param name str : validator name
  32. #@param none_is_valid bool : if True None will be validated
  33. #@param **kwargs : more arguement for the validator
  34. def __init__(self, name, none_is_valid=False, display_name=None, help_text=None, **kwargs):
  35. if name is not None and name not in self._validators:
  36. raise LodelFatalError("No validator named '%s'" % name)
  37. self.__none_is_valid = none_is_valid
  38. self.__name = name
  39. self._opt_args = kwargs
  40. if display_name is None:
  41. display_name = name
  42. super().__init__(display_name, help_text)
  43. # @brief Call the validator
  44. # @param value *
  45. # @return properly casted value
  46. # @throw ValidationError
  47. def __call__(self, value):
  48. if self.__none_is_valid and value is None:
  49. return None
  50. try:
  51. ret = self._validators[self.__name](value, **self._opt_args)
  52. return ret
  53. except Exception as exp:
  54. raise ValidationError(exp)
  55. # @brief Register a new validator
  56. # @param name str : validator name
  57. # @param callback callable : the function that will validate a value
  58. # @param description str
  59. @classmethod
  60. def register_validator(cls, name, callback, description=None):
  61. if name in cls._validators:
  62. raise NameError("A validator named '%s' allready exists" % name)
  63. # Broken test for callable
  64. if not inspect.isfunction(callback) and not inspect.ismethod(callback) and not hasattr(callback, '__call__'):
  65. raise TypeError("Callable expected but got %s" % type(callback))
  66. cls._validators[name] = callback
  67. cls._description[name] = description
  68. # @brief Get the validator list associated with description
  69. @classmethod
  70. def validators_list(cls):
  71. return copy.copy(cls._description)
  72. # @brief Create and register a list validator
  73. # @param elt_validator callable : The validator that will be used for validate each elt value
  74. # @param validator_name str
  75. # @param description None | str
  76. # @param separator str : The element separator
  77. # @return A Validator instance
  78. @classmethod
  79. def create_list_validator(cls, validator_name, elt_validator, description=None, separator=','):
  80. def list_validator(value):
  81. res = list()
  82. for elt in value.split(separator):
  83. elt = elt_validator(elt)
  84. if len(elt) > 0:
  85. res.append(elt)
  86. return res
  87. description = "Convert value to an array" if description is None else description
  88. cls.register_validator(validator_name, list_validator, description)
  89. return cls(validator_name)
  90. # @brief Create and register a list validator which reads an array and returns a string
  91. # @param elt_validator callable : The validator that will be used for validate each elt value
  92. # @param validator_name str
  93. # @param description None | str
  94. # @param separator str : The element separator
  95. # @return A Validator instance
  96. @classmethod
  97. def create_write_list_validator(cls, validator_name, elt_validator, description=None, separator=','):
  98. def write_list_validator(value):
  99. res = ''
  100. for elt in value:
  101. res += elt_validator(elt) + ','
  102. return res[:len(res) - 1]
  103. description = "Convert value to a string" if description is None else description
  104. cls.register_validator(validator_name, write_list_validator, description)
  105. return cls(validator_name)
  106. # @brief Create and register a regular expression validator
  107. # @param pattern str : regex pattern
  108. # @param validator_name str : The validator name
  109. # @param description str : Validator description
  110. # @return a Validator instance
  111. @classmethod
  112. def create_re_validator(cls, pattern, validator_name, description=None):
  113. def re_validator(value):
  114. if not re.match(pattern, value):
  115. raise ValidationError(
  116. "The value '%s' doesn't match the following pattern '%s'"
  117. % pattern)
  118. return value
  119. # registering the validator
  120. cls.register_validator(validator_name, re_validator,
  121. ("Match value to '%s'" % pattern)
  122. if description is None else description)
  123. return cls(validator_name)
  124. #  @return a list of registered validators
  125. @classmethod
  126. def validators_list_str(cls):
  127. result = ''
  128. for name in sorted(cls._validators.keys()):
  129. result += "\t%016s" % name
  130. if name in cls._description and cls._description[name] is not None:
  131. result += ": %s" % cls._description[name]
  132. result += "\n"
  133. return result
  134. # @brief Integer value validator callback
  135. def int_val(value):
  136. return int(value)
  137. # @brief Output file validator callback
  138. # @return A file object (if filename is '-' return sys.stderr)
  139. def file_err_output(value):
  140. if not isinstance(value, str):
  141. raise ValidationError("A string was expected but got '%s' " % value)
  142. if value == '-':
  143. return None
  144. return value
  145. # @brief Boolean value validator callback
  146. def boolean_val(value):
  147. if isinstance(value, bool):
  148. return value
  149. if value.strip().lower() == 'true' or value.strip() == '1':
  150. value = True
  151. elif value.strip().lower() == 'false' or value.strip() == '0':
  152. value = False
  153. else:
  154. raise ValidationError("A boolean was expected but got '%s' " % value)
  155. return bool(value)
  156. # @brief Validate a directory path
  157. def directory_val(value):
  158. res = Validator('strip')(value)
  159. if not os.path.isdir(res):
  160. raise ValidationError("Following path don't exists or is not a directory : '%s'" % res)
  161. return res
  162. # @brief Validate a loglevel value
  163. def loglevel_val(value):
  164. valids = ['DEBUG', 'INFO', 'WARNING', 'SECURITY', 'ERROR', 'CRITICAL']
  165. if value.upper() not in valids:
  166. raise ValidationError(
  167. "The value '%s' is not a valid loglevel" % value)
  168. return value.upper()
  169. # @brief Validate a path
  170. def path_val(value):
  171. if value is None or not os.path.exists(value):
  172. raise ValidationError(
  173. "path '%s' doesn't exists" % value)
  174. return value
  175. # @brief Validate None
  176. def none_val(value):
  177. if value is None:
  178. return None
  179. raise ValidationError("This settings cannot be set in configuration file")
  180. # @brief Validate a string
  181. def str_val(value):
  182. try:
  183. return str(value)
  184. except Exception as exp:
  185. raise ValidationError("Can't to convert value to string: " + str(exp))
  186. # @brief Validate using a regex
  187. def regex_val(value, pattern):
  188. if re.match(pattern, value) is None:
  189. raise ValidationError("The value '%s' is not validated by : \
  190. r\"%s\"" % (value, pattern))
  191. return value
  192. # @brief Validate a hostname (ipv4 or ipv6)
  193. def host_val(value):
  194. if value == 'localhost':
  195. return value
  196. ok = False
  197. try:
  198. socket.inet_aton(value)
  199. return value
  200. except (TypeError, OSError):
  201. pass
  202. try:
  203. socket.inet_pton(socket.AF_INET6, value)
  204. return value
  205. except (TypeError, OSError):
  206. pass
  207. try:
  208. socket.getaddrinfo(value, 80)
  209. return value
  210. except (TypeError, socket.gaierror):
  211. msg = "The value '%s' is not a valid host"
  212. raise ValidationError(msg % value)
  213. def custom_list_validator(value, validator_name, validator_kwargs=None):
  214. validator_kwargs = dict() if validator_kwargs is None else validator_kwargs
  215. validator = Validator(validator_name, **validator_kwargs)
  216. for item in value.split():
  217. validator(item)
  218. return value.split()
  219. #
  220. # Default validators registration
  221. #
  222. Validator.register_validator('custom_list', custom_list_validator,
  223. 'A list validator that takes a "validator_name" as argument')
  224. Validator.register_validator('dummy', lambda value: value, 'Validate anything')
  225. Validator.register_validator('none', none_val, 'Validate None')
  226. Validator.register_validator('string', str_val, 'Validate string values')
  227. Validator.register_validator('strip', str.strip, 'String trim')
  228. Validator.register_validator('int', int_val, 'Integer value validator')
  229. Validator.register_validator('bool', boolean_val, 'Boolean value validator')
  230. Validator.register_validator('errfile', file_err_output,
  231. 'Error output file validator (return stderr if filename is "-")')
  232. Validator.register_validator('directory', directory_val,
  233. 'Directory path validator')
  234. Validator.register_validator('loglevel', loglevel_val, 'Loglevel validator')
  235. Validator.register_validator('path', path_val, 'path validator')
  236. Validator.register_validator('host', host_val, 'host validator')
  237. Validator.register_validator('regex', regex_val,
  238. 'RegEx name validator (take re as argument)')
  239. Validator.create_list_validator('list', Validator('strip'), description="Simple list validator. Validate a list of values separated by ','",
  240. separator=',')
  241. Validator.create_list_validator(
  242. 'directory_list',
  243. Validator('directory'),
  244. description="Validator for a list of directory path separated with ','",
  245. separator=',')
  246. Validator.create_write_list_validator(
  247. 'write_list',
  248. Validator('directory'),
  249. description="Validator for an array of values \
  250. which will be set in a string, separated by ','",
  251. separator=',')
  252. Validator.create_re_validator(
  253. r'^https?://[^\./]+.[^\./]+/?.*$',
  254. 'http_url',
  255. 'Url validator')
  256. # @brief Validator for Editorial model component
  257. #
  258. # Designed to validate a conf that indicate a class.field in an EM
  259. #@todo modified the hardcoded dyncode import (it's a warning)
  260. def emfield_val(value):
  261. LodelContext.expose_modules(globals(),
  262. {'lodel.plugin.hooks': ['LodelHook']})
  263. spl = value.split('.')
  264. if len(spl) != 2:
  265. msg = "Expected a value in the form CLASSNAME.FIELDNAME but got : %s"
  266. raise SettingsValidationError(msg % value)
  267. value = tuple(spl)
  268. # Late validation hook
  269. @LodelHook('lodel2_dyncode_bootstraped')
  270. def emfield_conf_check(hookname, caller, payload):
  271. import leapi_dyncode as dyncode # <-- dirty & quick
  272. classnames = {cls.__name__.lower(): cls for cls in dyncode.dynclasses}
  273. if value[0].lower() not in classnames:
  274. msg = "Following dynamic class do not exists in current EM : %s"
  275. raise SettingsValidationError(msg % value[0])
  276. ccls = classnames[value[0].lower()]
  277. if value[1].lower() not in ccls.fieldnames(True):
  278. msg = "Following field not found in class %s : %s"
  279. raise SettingsValidationError(msg % value)
  280. return value
  281. # @brief Validator for plugin name & optionnaly type
  282. #
  283. # Able to check that the value is a plugin and if it is of a specific type
  284. def plugin_validator(value, ptype=None):
  285. LodelContext.expose_modules(globals(), {
  286. 'lodel.plugin.hooks': ['LodelHook']})
  287. value = copy.copy(value)
  288. @LodelHook('lodel2_dyncode_bootstraped')
  289. def plugin_type_checker(hookname, caller, payload):
  290. LodelContext.expose_modules(globals(), {
  291. 'lodel.plugin.plugins': ['Plugin'],
  292. 'lodel.plugin.exceptions': ['PluginError']})
  293. if value is None:
  294. return
  295. try:
  296. plugin = Plugin.get(value)
  297. except PluginError:
  298. msg = "No plugin named %s found"
  299. msg %= value
  300. raise ValidationError(msg)
  301. if plugin._type_conf_name.lower() != ptype.lower():
  302. msg = "A plugin of type '%s' was expected but found a plugin \
  303. named '%s' that is a '%s' plugin"
  304. msg %= (ptype, value, plugin._type_conf_name)
  305. raise ValidationError(msg)
  306. return value
  307. Validator.register_validator(
  308. 'plugin',
  309. plugin_validator,
  310. 'plugin name & type validator')
  311. Validator.register_validator(
  312. 'emfield',
  313. emfield_val,
  314. 'EmField name validator')
  315. #
  316. # Lodel 2 configuration specification
  317. #
  318. # @brief Append a piece of confspec
  319. #@note orig is modified during the process
  320. #@param orig dict : the confspec to update
  321. #@param section str : section name
  322. #@param key str
  323. #@param validator Validator : the validator to use to check this configuration key's value
  324. #@param default
  325. #@return new confspec
  326. def confspec_append(orig, section, key, validator, default):
  327. if section not in orig:
  328. orig[section] = dict()
  329. if key not in orig[section]:
  330. orig[section][key] = (default, validator)
  331. return orig
  332. # @brief Global specifications for lodel2 settings
  333. LODEL2_CONF_SPECS = {
  334. 'lodel2': {
  335. 'debug': (True, Validator('bool')),
  336. 'sitename': ('noname', Validator('strip')),
  337. 'runtest': (False, Validator('bool')),
  338. },
  339. 'lodel2.logging.*': {
  340. 'level': ('ERROR', Validator('loglevel')),
  341. 'context': (False, Validator('bool')),
  342. 'filename': ("-", Validator('errfile', none_is_valid=False)),
  343. 'backupcount': (5, Validator('int', none_is_valid=False)),
  344. 'maxbytes': (1024 * 10, Validator('int', none_is_valid=False)),
  345. },
  346. 'lodel2.editorialmodel': {
  347. 'emfile': ('em.pickle', Validator('strip')),
  348. 'emtranslator': ('picklefile', Validator('strip')),
  349. 'dyncode': ('leapi_dyncode.py', Validator('strip')),
  350. 'groups': ('', Validator('list')),
  351. 'editormode': (False, Validator('bool')),
  352. },
  353. 'lodel2.datasources.*': {
  354. 'read_only': (False, Validator('bool')),
  355. 'identifier': (None, Validator('string')),
  356. },
  357. 'lodel2.auth': {
  358. 'login_classfield': ('user.login', Validator('emfield')),
  359. 'pass_classfield': ('user.password', Validator('emfield')),
  360. },
  361. }