Geen omschrijving
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 16KB

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