def __validate_fields(self): validate_parameter_exists(self.start, "result", "start") validate_type(self.start, "start", int) validate_parameter_exists(self.end, "result", "end") validate_type(self.end, "end", int) validate_parameter_not_empty(self.entity_type, "result", "entity_type") if self.start < 0 or self.end < 0: raise InvalidParamException( "Invalid input, result start and end must be positive") if self.start >= self.end: raise InvalidParamException( f"Invalid input, start index '{self.start}' " f"must be smaller than end index '{self.end}'")
def __validate_fields(self): if self.start is None: self.__validate_field("start") if self.end is None: self.__validate_field("end") if self.entity_type is None: self.__validate_field("entity_type") if self.score is None: self.__validate_field("score") if self.start < 0 or self.end < 0: raise InvalidParamException( f"Invalid input, analyzer result start and end must be positive") if self.start >= self.end: raise InvalidParamException( f"Invalid input, analyzer result start index '{self.start}' " f"must be smaller than end index '{self.end}'")
def __validate_position_in_text(self, start: int, end: int): """Validate the start and end position match the text length.""" if self.text_len < start or end > self.text_len: err_msg = ( f"Invalid analyzer result, start: {start} and end: " f"{end}, while text length is only {self.text_len}." ) raise InvalidParamException(err_msg)
def validate_parameter(parameter_value, parameter_name: str, parameter_type: type) -> None: """Validate an anonymizer parameter. Both validate the existence of an anonymizer parameter and that it is an instance of the parameter_type. Otherwise, raise the appropriate InvalidParamException with the parameter_name as content. """ if parameter_value is None: raise InvalidParamException(f"Expected parameter {parameter_name}") validate_type(parameter_value, parameter_name, parameter_type)
def create_operator_class(self, operator_name: str, operator_type: OperatorType) -> Operator: """ Extract the operator class from the operators list. :param operator_type: Either Anonymize or Decrypt to defer between operators. :type operator_name: operator name. :return: operator class entity. """ operators_by_type = self.__get_operators_classes().get(operator_type) if not operators_by_type: self.logger.error(f"No such operator type {operator_type}") raise InvalidParamException( f"Invalid operator type '{operator_type}'.") operator_class = operators_by_type.get(operator_name) if not operator_class: self.logger.error(f"No such operator class {operator_name}") raise InvalidParamException( f"Invalid operator class '{operator_name}'.") self.logger.debug(f"applying class {operator_class}") return operator_class()
def __get_anonymizer_class(self, anonymizer_name: str) -> Anonymizer: """ Extract the anonymizer class from the anonymizers list. :param anonymizer_name: a single anonymizer value :return: Anonymizer """ anonymizer_class = Anonymizer.get_anonymizers().get(anonymizer_name) if not anonymizer_class: self.logger.error(f"No such anonymizer class {anonymizer_name}") raise InvalidParamException( f"Invalid anonymizer class '{anonymizer_name}'.") self.logger.debug(f"applying class {anonymizer_class}") return anonymizer_class
def validate(self, params: Dict = None) -> None: """ Validate Decrypt parameters. :param params: * *key* The key supplied by the user for the encryption. Should be a string of 128, 192 or 256 bits length. :raises InvalidParamException in case on an invalid parameter. """ key = params.get(self.KEY) validate_parameter(key, self.KEY, str) if not AESCipher.is_valid_key_size(key.encode("utf8")): raise InvalidParamException( f"Invalid input, {self.KEY} must be of length 128, 192 or 256 bits" )
def analyzer_results_from_json( data: List[Dict]) -> List['RecognizerResult']: """ Go over analyzer results, validate them and convert to List[RecognizerResult]. :param data: contains the anonymizers and analyzer_results_json """ if data is None: raise InvalidParamException( "Invalid input, " "request must contain analyzer results") return [ RecognizerResult.from_json(analyzer_result) for analyzer_result in data ]
def validate_type(parameter_value, parameter_name, parameter_type): """ Validate an anonymizer parameter. Validate it exists and if so, that it is the instance of the parameter_type. Otherwise, raise the appropriate InvalidParamException with the parameter_name as content. """ if parameter_value and not isinstance(parameter_value, parameter_type): message = _get_bad_typed_parameter_error_message( parameter_name, expected_type=parameter_type, actual_type=type(parameter_value), ) raise InvalidParamException(message)
def validate_parameter_in_range(values_range, parameter_value, parameter_name: str, parameter_type: type) -> None: """Validate an anonymizer parameter. validates the existence of an anonymizer parameter and that it is an instance of the parameter_type and that it is within the range of provided values. Otherwise, raise the appropriate InvalidParamException with the parameter_name as content. """ validate_parameter(parameter_value, parameter_name, object) if parameter_value not in values_range: raise InvalidParamException( f"Parameter {parameter_name} value {parameter_value} is not in " f"range of values {values_range}")
def handle_analyzer_results_json(cls, data: Dict) -> AnalyzerResults: """ Go over analyzer results, validate them and convert to List[AnalyzeResult]. :param data: contains the anonymizers and analyzer_results_json """ analyzer_results = AnalyzerResults() analyzer_results_json = data.get("analyzer_results") if analyzer_results_json is None: cls.logger.debug( "invalid input, json missing field: analyzer_results_json") raise InvalidParamException( "Invalid input, " "request must contain analyzer results") for analyzer_result in analyzer_results_json: analyzer_result = RecognizerResult.from_json(analyzer_result) analyzer_results.append(analyzer_result) return analyzer_results
def validate(self, params: Dict = None) -> None: """ Validate the parameters for mask. :param params: masking_char: The character to be masked with chars_to_mask: The amount of characters to mask from_end: Whether to mask the text from it's end """ masking_char = params.get(self.MASKING_CHAR) validate_parameter(masking_char, self.MASKING_CHAR, str) if len(masking_char) > 1: raise InvalidParamException( f"Invalid input, {self.MASKING_CHAR} must be a character") validate_parameter(params.get(self.CHARS_TO_MASK), self.CHARS_TO_MASK, int) validate_parameter(params.get(self.FROM_END), self.FROM_END, bool)
def decrypt(self, key: str, text: str) -> str: """ Decrypts a previously AES-CBC encrypted anonymized text. :param key: AES encryption key. :param text: The text for decryption. :returns: The decrypted text. """ validate_parameter(key, "key", str) validate_parameter(text, "text", str) encoded_key = key.encode("utf8") if not AESCipher.is_valid_key_size(encoded_key): message = "Invalid input, key must be of length 128, 192 or 256 bits" self.logger.info(message) raise InvalidParamException(message) decrypted_text = AESCipher.decrypt(key=encoded_key, text=text) return decrypted_text
def __validate_text_not_empty(self, text: str): if not text: self.logger.debug("invalid input, json is missing text field") raise InvalidParamException("Invalid input, text can not be empty")
def validate_parameter_not_empty(parameter_value, entity: str, parameter_name: str) -> None: """Validate parameter exists and not only empty.""" if not parameter_value: raise InvalidParamException( f"Invalid input, {entity} must contain {parameter_name}")
def __validate_field(self, field_name: str): self.logger.debug(f"invalid parameter, {field_name} cannot be empty") raise InvalidParamException( f"Invalid input, analyzer result must contain {field_name}")
def validate_parameter_exists(parameter_value, entity: str, parameter_name: str) -> None: """Validate parameter is not empty.""" if parameter_value is None: raise InvalidParamException( f"Invalid input, {entity} must contain {parameter_name}")