How to use the hvac.exceptions.Forbidden function in hvac

To help you get started, we’ve selected a few hvac 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 kiwicom / konfetti / test / test_vault.py View on Github external
def test_invalid_token(config, monkeypatch):
    monkeypatch.setenv("VAULT_TOKEN", "invalid")
    with pytest.raises(hvac.exceptions.Forbidden):
        config.SECRET
github peopledoc / vault-cli / tests / unit / test_client_hvac.py View on Github external
        (hvac.exceptions.Forbidden, exceptions.VaultForbidden),
        (hvac.exceptions.InvalidRequest, exceptions.VaultInvalidRequest),
        (hvac.exceptions.Unauthorized, exceptions.VaultUnauthorized),
        (hvac.exceptions.InternalServerError, exceptions.VaultInternalServerError),
        (hvac.exceptions.VaultDown, exceptions.VaultSealed),
        (hvac.exceptions.UnexpectedError, exceptions.VaultAPIException),
    ],
)
def test_handle_errors(hvac_exc, vault_cli_exc):
    with pytest.raises(vault_cli_exc):
        with client.handle_errors():
            raise hvac_exc
github deepmind / kapitan / kapitan / refs / secrets / vaultkv.py View on Github external
client = vault_obj(self.vault_params)
            # token will comprise of two parts path_in_vault:key
            data = self.data.decode("utf-8").rstrip().split(":")
            return_data = ""
            if self.vault_params.get("engine") == "kv":
                response = client.secrets.kv.v1.read_secret(
                    path=data[0], mount_point=self.vault_params.get("mount", "secret")
                )
                return_data = response["data"][data[1]]
            else:
                response = client.secrets.kv.v2.read_secret_version(
                    path=data[0], mount_point=self.vault_params.get("mount", "secret")
                )
                return_data = response["data"]["data"][data[1]]
            client.adapter.close()
        except Forbidden:
            VaultError(
                "Permission Denied. "
                + "make sure the token is authorised to access {path} on Vault".format(path=data[0])
            )
        except InvalidPath:
            VaultError("{path} does not exist on Vault secret".format(path=data[0]))

        if return_data is "":
            VaultError("'{key}' doesn't exist on '{path}'".format(key=data[1], path=data[0]))
        return return_data
github Autodesk / aomi / aomi / vault.py View on Github external
def func_wrapper(self, vault_client):
            try:
                return func(self, vault_client)
            except (hvac.exceptions.InvalidRequest,
                    hvac.exceptions.Forbidden) as vault_exception:
                if vault_exception.errors[0] == 'permission denied':
                    error_output("Permission denied %s from %s" %
                                 (msg, self.path), self.opt)
                else:
                    raise
github peopledoc / vault-cli / vault_cli / hvac.py View on Github external
def handle_errors(self):
        try:
            yield

        except json.decoder.JSONDecodeError as exc:
            raise exceptions.VaultNonJsonResponse(errors=[str(exc)])

        except hvac.exceptions.InvalidRequest as exc:
            raise exceptions.VaultInvalidRequest(errors=exc.errors) from exc

        except hvac.exceptions.Unauthorized as exc:
            raise exceptions.VaultUnauthorized(errors=exc.errors) from exc

        except hvac.exceptions.Forbidden as exc:
            raise exceptions.VaultForbidden(errors=exc.errors) from exc

        except hvac.exceptions.InternalServerError as exc:
            raise exceptions.VaultInternalServerError(errors=exc.errors) from exc

        except hvac.exceptions.VaultDown as exc:
            raise exceptions.VaultSealed(errors=exc.errors) from exc

        except hvac.exceptions.UnexpectedError as exc:
            raise exceptions.VaultAPIException(errors=exc.errors) from exc
github Autodesk / aomi / aomi / seed.py View on Github external
def delete(client, path, opt):
    """Delete from Vault while handling non-surprising errors."""
    try:
        client.delete(path)
    except (hvac.exceptions.InvalidRequest,
            hvac.exceptions.Forbidden) as vault_exception:
        client.revoke_self_token()
        if vault_exception.errors[0] == 'permission denied':
            error_output("Permission denied deleting %s" % path, opt)
        else:
            raise
github hvac / hvac / hvac / utils.py View on Github external
:param message: Optional message to include in a resulting exception.
    :type message: str
    :param errors: Optional errors to include in a resulting exception.
    :type errors: list | str

    :raises: hvac.exceptions.InvalidRequest | hvac.exceptions.Unauthorized | hvac.exceptions.Forbidden |
        hvac.exceptions.InvalidPath | hvac.exceptions.RateLimitExceeded | hvac.exceptions.InternalServerError |
        hvac.exceptions.VaultNotInitialized | hvac.exceptions.VaultDown | hvac.exceptions.UnexpectedError

    """
    if status_code == 400:
        raise exceptions.InvalidRequest(message, errors=errors)
    elif status_code == 401:
        raise exceptions.Unauthorized(message, errors=errors)
    elif status_code == 403:
        raise exceptions.Forbidden(message, errors=errors)
    elif status_code == 404:
        raise exceptions.InvalidPath(message, errors=errors)
    elif status_code == 429:
        raise exceptions.RateLimitExceeded(message, errors=errors)
    elif status_code == 500:
        raise exceptions.InternalServerError(message, errors=errors)
    elif status_code == 501:
        raise exceptions.VaultNotInitialized(message, errors=errors)
    elif status_code == 503:
        raise exceptions.VaultDown(message, errors=errors)
    else:
        raise exceptions.UnexpectedError(message)
github kiwicom / konfetti / src / konfetti / vault / synchronous.py View on Github external
# type: (str, str, Optional[str], Optional[str], Optional[str]) -> Any
        vault_logger.debug('Access "%s" in Vault', path)
        import hvac  # pylint: disable=import-outside-toplevel

        vault = hvac.Client(url=url, token=token)
        if not token and (username and password):
            if self._token is not NOT_SET:
                vault.auth.adapter.token = self._token
            else:
                vault_logger.debug("Retrieving a new token")
                vault.auth_userpass(username, password)
                self._token = vault.auth.adapter.token

        try:
            response = self.read_path(path, vault)
        except hvac.exceptions.Forbidden as exc:
            if username and password:
                vault_logger.debug("Token is invalid. Retrieving a new token")
                vault.auth_userpass(username, password)
                self._token = vault.auth.adapter.token
                response = self.read_path(path, vault)
            else:
                raise exc

        return response["data"]
github jhuapl-boss / boss-tools / bossutils / vault.py View on Github external
def wrapper(self, *args, **kwargs):
        try:
            return function(self, *args, **kwargs)
        except hvac.exceptions.Forbidden as e:
            blog = BossLogger().logger
            blog.info(str(e))
            msg = "Your token had expired.  Dynamically creating a new one."
            blog.info(msg)
            Vault.login(self)
            return function(self, *args, **kwargs)
    return wrapper