Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def ensure_secret_backend(client):
"""Ensure that vault has a KV backend mounted at secret.
:param client: Client to use to talk to vault
:type client: CharmVaultClient
"""
try:
client.hvac_client.enable_secret_backend(
backend_type='kv',
description='Charm created KV backend',
mount_point='secret',
options={'version': 1})
except hvac.exceptions.InvalidRequest:
pass
def test_error(self):
with self.server_span:
with self.assertRaises(InvalidRequest):
self.context.vault.initialize()
server_span_observer = self.baseplate_observer.get_only_child()
span_observer = server_span_observer.get_only_child()
self.assertTrue(span_observer.on_start_called)
self.assertTrue(span_observer.on_finish_called)
self.assertIsNotNone(span_observer.on_finish_exc_info)
span_observer.span.name == "vault.request"
span_observer.assert_tag("http.method", "PUT")
span_observer.assert_tag("http.url", "/v1/sys/init")
raises=exceptions.InvalidRequest,
exception_message='must provide at least one value to add or remove',
),
# TODO: wrong role type (gce)
])
def test_edit_service_accounts_on_iam_role(self, label, add=None, remove=None, create_role_first=True, raises=None, exception_message=''):
role_name = 'hvac'
project_id = 'test-hvac-project-not-a-real-project'
if create_role_first:
self.client.auth.gcp.create_role(
name=role_name,
role_type='iam',
project_id=project_id,
bound_service_accounts=['hvac-integration-test@appspot.gserviceaccount.com'],
mount_point=self.TEST_MOUNT_POINT,
)
if raises:
def test_should_catch_approle_invalid_secret_id_abort_the_run(hvac):
config = {
'vault_addr' : 'http://someaddr.com',
'vault_role_id' : 'mighty_id',
'vault_role_secret' : 'expired'
}
fake_client = MagicMock()
fake_client.auth_approle.side_effect = InvalidRequest()
hvac.Client.return_value = fake_client
with pytest.raises(InvalidExperiment):
create_vault_client(config)
token = data.get('{}_token'.format(hookenv.local_unit()))
if all([vault_url, role_id, token]):
token = json.loads(token)
vault_url = json.loads(vault_url)
# Tokens may change when secret_id's are being
# reissued - if so use token to get new secret_id
token_success = False
try:
secret_id = retrieve_secret_id(
url=vault_url,
token=token
)
token_success = True
except hvac.exceptions.InvalidRequest:
# Try next
pass
if token_success:
db.set('secret-id', secret_id)
db.flush()
ctxt['vault_url'] = vault_url
ctxt['role_id'] = json.loads(role_id)
ctxt['secret_id'] = secret_id
ctxt['secret_backend'] = self.secret_backend
vault_ca = data.get('vault_ca')
if vault_ca:
ctxt['vault_ca'] = json.loads(vault_ca)
self.complete = True
"""Helper method to raise exceptions based on the status code of a response received back from Vault.
:param status_code: Status code received in a response from Vault.
:type status_code: int
: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)
def __raise_error(self, status_code, message=None, errors=None):
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)
def vault_relation_complete(backend=None):
"""Determine whether vault relation is complete
:param backend: Name of secrets backend requested
:ptype backend: string
:returns: whether the relation to vault is complete
:rtype: bool"""
try:
import hvac
except ImportError:
return False
try:
vault_kv = VaultKVContext(secret_backend=backend or VAULTLOCKER_BACKEND)
vault_kv()
return vault_kv.complete
except hvac.exceptions.InvalidRequest:
return False
def revoke_token(self, token, orphan=False, accessor=False):
"""
POST /auth/token/revoke/
POST /auth/token/revoke-orphan/
POST /auth/token/revoke-accessor/
"""
if accessor and orphan:
msg = "revoke_token does not support 'orphan' and 'accessor' flags together"
raise exceptions.InvalidRequest(msg)
elif accessor:
self._post('/v1/auth/token/revoke-accessor/{0}'.format(token))
elif orphan:
self._post('/v1/auth/token/revoke-orphan/{0}'.format(token))
else:
self._post('/v1/auth/token/revoke/{0}'.format(token))
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