def validate(self, *args, **kwargs): try: self.validator.validate(*args, **kwargs) except jsonschema.ValidationError as ex: if isinstance(ex.cause, webob.exc.HTTPBadRequest): detail = str(ex.cause) elif len(ex.path) > 0: detail = _("Invalid input for field/attribute %(path)s." " Value: %(value)s. %(message)s") % { 'path': ex.path.pop(), 'value': ex.instance, 'message': ex.message } else: detail = ex.message raise exception.ValidationError(detail=detail) except TypeError as ex: # NOTE: If passing non string value to patternProperties parameter, # TypeError happens. Here is for catching the TypeError. detail = six.text_type(ex) raise exception.ValidationError(detail=detail)
def _validate_attribute_name(self, target): if not self.attribute: msg = ("Rule '%(rule)s' doesn't contain attribute name") raise exception.ValidationError(msg % {"rule": self}) if '*' in self.attribute: msg = ("Rule '%(rule)s' contains invalid attribute name " "'%(attribute)s'") raise exception.ValidationError(msg % { "rule": self, "attribute": self.attribute }) if target and self.attribute not in target: if not self._attribute_special_field(target): msg = ("Rule '%(rule)s' contains invalid attribute name " "'%(attribute)s'") raise exception.ValidationError(msg % { "rule": self, "attribute": self.attribute })
def _parse_filter(filter_rule): """Parse a filter rule and return an appropriate Filter object.""" try: tokens = filter_rule.split(',') filter_type = None if len(tokens) >= 3: if tokens[0] in _filters.SUPPORTED_OP_ONE: filter_type = 'simple_filter_expr_one' elif tokens[0] in _filters.SUPPORTED_OP_MULTI: filter_type = 'simple_filter_expr_multi' except Exception: msg = 'Failed to understand filter %s' % filter_rule raise exception.ValidationError(msg) if filter_type in _filters.registered_filters: return _filters.registered_filters[filter_type](tokens[0], tokens[1], tokens[2:]) else: msg = 'Failed to understand filter %s' % filter_rule raise exception.ValidationError(msg)
def _validate_operators(self): super(SimpleFilterExprOne, self)._validate_operators() if self.values and isinstance(self.values, list) and \ len(self.values) > 1: msg = _("Rule '%(rule)s' contains operator '%(operator)s' " "which supports only one value, but multiple values " "'%(values)s' are provided") raise exception.ValidationError( msg % { "rule": self, "operator": self.operator, 'values': ",".join(self.values) })
def parse_filter_rule(filter_rule, target=None): """Parses filter query parameter to the tree. Translates a filter written in the filter language into a tree of Filter objects. """ # Parse the token stream state = ParseState() for tok, value in _parse_tokenize(filter_rule): state.shift(tok, value) try: return state.result(target) except ValueError: err_msg = 'Failed to understand filter %s' % filter_rule raise exception.ValidationError(err_msg)
def wrapper(*args, **kwargs): # NOTE(tpatil): The second argument of the method # calling this method should always be 'request'. if 'request' in kwargs: req = kwargs['request'] else: req = args[1] try: req.GET.dict_of_lists() except UnicodeDecodeError: msg = _('Query string is not UTF-8 encoded') raise exceptions.ValidationError(msg) query_opts = {} query_opts.update(req.GET) schema_validator = validators._SchemaValidator(query_params_schema) schema_validator.validate(query_opts) return func(*args, **kwargs)
def _validate_data_type(self, target): if not self.values: msg = ("Rule '%(rule)s' contains empty value") raise exception.ValidationError(msg % {"rule": self}) special_attribute = self._attribute_special_field(target) if special_attribute: attribute_info = target.get(special_attribute) else: attribute_info = target.get(self.attribute) for value in self.values: error = False if attribute_info[1] == 'string' and not isinstance( value, six.string_types): error = True elif attribute_info[1] == 'number': if not strutils.is_int_like(value): error = True elif attribute_info[1] == 'uuid': if not uuidutils.is_uuid_like(value): error = True elif attribute_info[1] == 'datetime': try: timeutils.parse_isotime(value) except ValueError: error = True elif attribute_info[1] == 'enum': if value not in attribute_info[3]: msg = ("Rule '%(rule)s' contains data type '%(type)s' " "with invalid value. It should be one of " "%(valid_value)s") raise exception.ValidationError( msg % { "rule": self, "valid_value": ",".join(attribute_info[3]), 'type': attribute_info[1] }) if error: msg = ("Rule '%(rule)s' contains invalid data type for value " "'%(value)s'. The data type should be '%(type)s'") raise exception.ValidationError(msg % { "rule": self, "value": value, 'type': attribute_info[1] }) # Also, check whether the data type is supported by operator if attribute_info[1] not in \ self.OPERATOR_SUPPORTED_DATA_TYPES.get(self.operator): msg = ("Rule '%(rule)s' contains operator '%(operator)s' " "which doesn't support data type '%(type)s' for " "attribute '%(attribute)s'") raise exception.ValidationError( msg % { "rule": self, "operator": self.operator, 'type': attribute_info[1], 'attribute': self.attribute })
def validate_attribute_fields(cls, all_fields=None, fields=None, exclude_fields=None, exclude_default=None): if all_fields and (fields or exclude_fields or exclude_default): msg = ("Invalid query parameter combination: 'all_fields' " "cannot be combined with 'fields' or 'exclude_fields' " "or 'exclude_default'") raise exception.ValidationError(msg) if fields and (all_fields or exclude_fields): msg = ("Invalid query parameter combination: 'fields' " "cannot be combined with 'all_fields' or 'exclude_fields' ") raise exception.ValidationError(msg) if exclude_fields and (all_fields or fields or exclude_default): msg = ("Invalid query parameter combination: 'exclude_fields' " "cannot be combined with 'all_fields' or 'fields' " "or 'exclude_default'") raise exception.ValidationError(msg) if exclude_default and (all_fields or exclude_fields): msg = ("Invalid query parameter combination: 'exclude_default' " "cannot be combined with 'all_fields' or 'exclude_fields' ") raise exception.ValidationError(msg) def _validate_complex_attributes(query_parameter, fields): msg = ("Invalid query parameter '%(query_parameter)s'. " "Value: %(field)s") for field in fields: if field in cls.COMPLEX_ATTRIBUTES: continue elif '*' in field: # Field should never contain '*' as it's reserved for # special purpose for handling key-value pairs. raise exception.ValidationError(msg % { "query_parameter": query_parameter, "field": field }) elif field not in cls.FLATTEN_COMPLEX_ATTRIBUTES: # Special case for field with key-value pairs. # In this particular case, key will act as an attribute # in structure so you need to treat it differently than # other fields. All key-value pair field will be post-fix # with '*' in FLATTEN_COMPLEX_ATTRIBUTES. Request # with field which contains '*' will be treated as an # error. special_field = False for attribute in cls.FLATTEN_COMPLEX_ATTRIBUTES: if '*' in attribute and field.startswith( attribute.split('*')[0]): special_field = True if not special_field: raise exception.ValidationError(msg % { "query_parameter": query_parameter, "field": field }) if fields: _validate_complex_attributes("fields", fields.split(',')) elif exclude_fields: _validate_complex_attributes("exclude_fields", exclude_fields.split(","))