Skip to content

Commit

Permalink
Move exception handling out of (Vault) __api_write method
Browse files Browse the repository at this point in the history
Clearer this way, after the 17ea3b2 error response parsing cleanup.
  • Loading branch information
andreaso committed Jan 8, 2025
1 parent 17ea3b2 commit d120cf3
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions hv4gha/vault.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,23 +114,19 @@ def __api_write(
self,
api_path: str,
payload: None | dict[str, Any] = None,
vault_exception: type[Exception] = VaultAPIError,
) -> requests.models.Response:
update_url = self.vault_addr + api_path

if payload is None:
payload = {}

try:
response = requests.post(
update_url,
headers=self.auth_headers,
data=json.dumps(payload),
timeout=10,
)
response.raise_for_status()
except requests.exceptions.HTTPError as http_error:
raise vault_exception(http_error.response.text) from http_error
response = requests.post(
update_url,
headers=self.auth_headers,
data=json.dumps(payload),
timeout=10,
)
response.raise_for_status()

return response

Expand All @@ -154,7 +150,10 @@ def import_key(self, *, key_name: str, pem_app_key: bytes) -> None:
"allow_plaintext_backup": False,
}

self.__api_write(api_path, payload, AppKeyImportError)
try:
self.__api_write(api_path, payload)
except requests.exceptions.HTTPError as http_error:
raise AppKeyImportError(http_error.response.text) from http_error

def sign_jwt(self, *, key_name: str, app_id: str) -> str:
"""
Expand All @@ -177,9 +176,10 @@ def sign_jwt(self, *, key_name: str, app_id: str) -> str:
"signature_algorithm": "pkcs1v15",
}

response: requests.models.Response = self.__api_write(
api_path, payload, JWTSigningError
)
try:
response: requests.models.Response = self.__api_write(api_path, payload)
except requests.exceptions.HTTPError as http_error:
raise JWTSigningError(http_error.response.text) from http_error

try:
signature_bm = SignedJWT(**response.json())
Expand All @@ -197,4 +197,8 @@ def revoke_token(self) -> None:
"""Vault Token self-revoke"""

api_path = "/v1/auth/token/revoke-self"
self.__api_write(api_path, vault_exception=TokenRevokeError)

try:
self.__api_write(api_path)
except requests.exceptions.HTTPError as http_error:
raise TokenRevokeError(http_error.response.text) from http_error

0 comments on commit d120cf3

Please sign in to comment.