How to use the yamlpath.eyaml.exceptions.EYAMLCommandException function in yamlpath

To help you get started, we’ve selected a few yamlpath examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github wwkimball / yamlpath / tests / test_eyaml_eyamlprocessor.py View on Github external
def test_decrypt_calledprocesserror(self, quiet_logger, force_subprocess_run_cpe):
        processor = EYAMLProcessor(quiet_logger, None)
        with pytest.raises(EYAMLCommandException):
            processor.decrypt_eyaml("ENC[...]")
github wwkimball / yamlpath / tests / test_eyaml_eyamlprocessor.py View on Github external
def test_bad_encryption_keys(self, quiet_logger):
        processor = EYAMLProcessor(quiet_logger, None)
        processor.privatekey = "/no/such/file"
        processor.publickey = "/no/such/file"

        with pytest.raises(EYAMLCommandException):
            processor.encrypt_eyaml("test")
github wwkimball / yamlpath / yamlpath / eyaml / eyamlprocessor.py View on Github external
Parameters:
        1. value (str) the value to encrypt
        2. output (EYAMLOutputFormats) the output format of the encryption

        Returns:  (str) The encrypted result or the original value if it was
        already an EYAML encryption.

        Raises:
            - `EYAMLCommandException` when the eyaml binary cannot be utilized.
        """
        if self.is_eyaml_value(value):
            return value

        if not self._can_run_eyaml():
            raise EYAMLCommandException(
                "The eyaml binary is not executable at {}.".format(self.eyaml)
            )

        cmdstr: str = ("{} encrypt --quiet --stdin --output={}"
                       .format(self.eyaml, output))
        if self.publickey:
            cmdstr += " --pkcs7-public-key={}".format(self.publickey)
        if self.privatekey:
            cmdstr += " --pkcs7-private-key={}".format(self.privatekey)

        cmd: List[str] = cmdstr.split()
        self.logger.debug(
            "EYAMLPath::encrypt_eyaml:  About to execute:  {}"
            .format(" ".join(cmd))
        )
        bval: bytes = value.encode("ascii")
github wwkimball / yamlpath / yamlpath / eyaml / eyamlprocessor.py View on Github external
Decrypt an EYAML value.

        Parameters:
        1. value (str) The EYAML value to decrypt

        Returns:  (str) The decrypted value or the original value if it was not
        actually encrypted.

        Raises:
            - `EYAMLCommandException` when the eyaml binary cannot be utilized
        """
        if not self.is_eyaml_value(value):
            return value

        if not self._can_run_eyaml():
            raise EYAMLCommandException("No accessible eyaml command.")

        cmdstr: str = "{} decrypt --quiet --stdin".format(self.eyaml)
        if self.publickey:
            cmdstr += " --pkcs7-public-key={}".format(self.publickey)
        if self.privatekey:
            cmdstr += " --pkcs7-private-key={}".format(self.privatekey)

        cmd: List[str] = cmdstr.split()
        cleanval: str = str(value).replace("\n", "").replace(" ", "").rstrip()
        bval: bytes = cleanval.encode("ascii")
        self.logger.debug(
            "EYAMLPath::decrypt_eyaml:  About to execute {} against:\n{}"
            .format(cmdstr, cleanval)
        )

        try:
github wwkimball / yamlpath / yamlpath / commands / yaml_get.py View on Github external
if yaml_data is None:
        # An error message has already been logged
        sys.exit(1)

    # Seek the queried value(s)
    discovered_nodes = []
    processor = EYAMLProcessor(
        log, yaml_data, binary=args.eyaml,
        publickey=args.publickey, privatekey=args.privatekey)
    try:
        for node in processor.get_eyaml_values(yaml_path, mustexist=True):
            log.debug("Got {} from {}.".format(repr(node), yaml_path))
            discovered_nodes.append(unwrap_node_coords(node))
    except YAMLPathException as ex:
        log.critical(ex, 1)
    except EYAMLCommandException as ex:
        log.critical(ex, 2)

    for node in discovered_nodes:
        if isinstance(node, (dict, list)):
            print(json.dumps(node))
        else:
            print("{}".format(str(node).replace("\n", r"\n")))
github wwkimball / yamlpath / yamlpath / commands / yaml_set.py View on Github external
# then they must both be set in order to decrypt this value.
                # This is enforced only when the value must be decrypted due to
                # a --check request.
                if (
                        (args.publickey and not args.privatekey)
                        or (args.privatekey and not args.publickey)
                ):
                    log.error(
                        "Neither or both private and public EYAML keys must be"
                        + " set when --check is required to decrypt the old"
                        + " value.")
                    sys.exit(1)

                try:
                    check_value = processor.decrypt_eyaml(node_coordinate.node)
                except EYAMLCommandException as ex:
                    log.critical(ex, 1)
            else:
                check_value = node_coordinate.node

            if not args.check == check_value:
                log.critical(
                    '"{}" does not match the check value.'
                    .format(args.check),
                    20
                )

    # Save the old value, if desired and possible
    if args.saveto:
        # Only one can be saved; otherwise it is impossible to meaningfully
        # convey to the end-user from exactly which other YAML node each saved
        # value came.
github wwkimball / yamlpath / yamlpath / eyaml / eyamlprocessor.py View on Github external
input=bval,
                check=True,
                shell=False
            ).stdout.decode('ascii').rstrip()
        except CalledProcessError as ex:
            raise EYAMLCommandException(
                "The {} command cannot be run due to exit code:  {}"
                .format(self.eyaml, ex.returncode)
            )

        # Check for bad decryptions
        self.logger.debug(
            "EYAMLPath::decrypt_eyaml:  Decrypted result:  {}".format(retval)
        )
        if not retval or retval == cleanval:
            raise EYAMLCommandException(
                "Unable to decrypt value!  Please verify you are using the"
                + " correct old EYAML keys and the value is not corrupt:  {}"
                .format(cleanval)
            )

        return retval
github wwkimball / yamlpath / yamlpath / eyaml / eyamlprocessor.py View on Github external
"EYAMLPath::encrypt_eyaml:  About to execute:  {}"
            .format(" ".join(cmd))
        )
        bval: bytes = value.encode("ascii")

        try:
            # self.eyaml is untrusted, so shell must always be False and
            # all parameters must be supplied via a List.
            retval: str = (
                run(cmd, stdout=PIPE, input=bval, check=True, shell=False)
                .stdout
                .decode('ascii')
                .rstrip()
            )
        except CalledProcessError as ex:
            raise EYAMLCommandException(
                "The {} command cannot be run due to exit code:  {}"
                .format(self.eyaml, ex.returncode)
            )

        if not retval:
            raise EYAMLCommandException(
                ("The {} command was unable to encrypt your value.  Please"
                 + " verify this process can run that command and read your"
                 + " EYAML keys.").format(self.eyaml)
            )

        if output is EYAMLOutputFormats.BLOCK:
            retval = re.sub(r" +", "", retval) + "\n"

        self.logger.debug(
            "EYAMLPath::encrypt_eyaml:  Encrypted result:\n{}".format(retval)
github wwkimball / yamlpath / yamlpath / eyaml / eyamlprocessor.py View on Github external
"EYAMLPath::decrypt_eyaml:  About to execute {} against:\n{}"
            .format(cmdstr, cleanval)
        )

        try:
            # self.eyaml is untrusted, so shell must always be False and
            # all parameters must be supplied via a List.
            retval: str = run(
                cmd,
                stdout=PIPE,
                input=bval,
                check=True,
                shell=False
            ).stdout.decode('ascii').rstrip()
        except CalledProcessError as ex:
            raise EYAMLCommandException(
                "The {} command cannot be run due to exit code:  {}"
                .format(self.eyaml, ex.returncode)
            )

        # Check for bad decryptions
        self.logger.debug(
            "EYAMLPath::decrypt_eyaml:  Decrypted result:  {}".format(retval)
        )
        if not retval or retval == cleanval:
            raise EYAMLCommandException(
                "Unable to decrypt value!  Please verify you are using the"
                + " correct old EYAML keys and the value is not corrupt:  {}"
                .format(cleanval)
            )

        return retval