VaultAPI-Client 0.1.2__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ import json
4
4
  from .exceptions import VaultAPIClientError
5
5
  from .main import LOGGER, VaultAPIClient
6
6
 
7
- version = "0.1.2"
7
+ version = "0.2.0"
8
8
 
9
9
 
10
10
  def commandline():
@@ -15,6 +15,7 @@ class AWSClient:
15
15
  def __init__(self):
16
16
  """Instantiates the client object."""
17
17
  try:
18
+ # noinspection PyPackageRequirements,PyUnresolvedReferences
18
19
  import boto3
19
20
  except ModuleNotFoundError:
20
21
  raise EnvironmentError(
@@ -46,7 +47,7 @@ class AWSClient:
46
47
  response = self.secret_client.get_secret_value(SecretId=name)
47
48
  except Exception as error:
48
49
  LOGGER.exception(error)
49
- return
50
+ return None
50
51
  return response["SecretString"]
51
52
  paginator = self.secret_client.get_paginator("list_secrets")
52
53
  page_results = paginator.paginate().build_full_result()
@@ -68,7 +69,7 @@ class AWSClient:
68
69
  response = self.ssm_client.get_parameter(Name=name, WithDecryption=True)
69
70
  except Exception as error:
70
71
  LOGGER.exception(error)
71
- return
72
+ return None
72
73
  return response["Parameter"]["Value"]
73
74
  paginator = self.ssm_client.get_paginator("describe_parameters")
74
75
  page_results = paginator.paginate().build_full_result()
@@ -1,12 +1,13 @@
1
1
  import os
2
+ from typing import NoReturn
2
3
 
3
4
  import dotenv
4
5
  import requests
5
6
  from cryptography.fernet import Fernet
6
7
 
7
- from vaultapi.aws import AWSClient
8
- from vaultapi.exceptions import VaultAPIClientError
9
- from vaultapi.util import urljoin
8
+ from vaultapi_client.aws import AWSClient
9
+ from vaultapi_client.exceptions import VaultAPIClientError, VaultAPIServerError
10
+ from vaultapi_client.util import urljoin
10
11
 
11
12
  env_file = os.environ.get("ENV_FILE") or os.environ.get("env_file") or ".env"
12
13
  dotenv.load_dotenv(env_file)
@@ -48,10 +49,18 @@ class EnvConfig:
48
49
  self.transit_key_length: int = int(kwargs.get("vault_transit_key_length"))
49
50
  self.__assert__()
50
51
 
51
- def __assert__(self):
52
+ def __assert__(self) -> None | NoReturn:
52
53
  """Run assertions for server config."""
53
- response = requests.get(url=urljoin(self.vault_server, server_map.health))
54
- assert response.ok, response.text
54
+ try:
55
+ response = requests.get(
56
+ url=urljoin(self.vault_server, server_map.health), timeout=(1, 1)
57
+ )
58
+ response.raise_for_status()
59
+ except requests.RequestException as error:
60
+ raise VaultAPIServerError(
61
+ message=error.response.text or error.__context__,
62
+ status_code=getattr(error.response, "status_code", None),
63
+ )
55
64
  try:
56
65
  assert self.transit_key_length in (16, 24, 32)
57
66
  except AssertionError:
@@ -82,7 +91,7 @@ def getenv(*args, default: str = None) -> str:
82
91
  return default
83
92
 
84
93
 
85
- def resolve_secrets(try_aws: bool):
94
+ def resolve_secrets(try_aws: bool) -> EnvConfig | NoReturn:
86
95
  """Tries to retrieve the required secret from environment variable or AWS parameter or the AWS secrets manager."""
87
96
  base_env_vars = dict(
88
97
  vault_server=getenv("vault_server", "server"),
@@ -0,0 +1,20 @@
1
+ class VaultAPIError(BaseException):
2
+ """Base error class for VaultAPI."""
3
+
4
+
5
+ class VaultAPIClientError(VaultAPIError):
6
+ """Subclass for client error."""
7
+
8
+
9
+ class InvalidCipherText(VaultAPIClientError):
10
+ """Subclass for invalid tag."""
11
+
12
+
13
+ class VaultAPIServerError(VaultAPIClientError):
14
+ """Subclass for errors when connecting to the server."""
15
+
16
+ def __init__(self, message: str, status_code: int = None):
17
+ """Super class to handle custom error message and status code."""
18
+ self.message = message
19
+ self.status_code = status_code
20
+ super().__init__(message)
@@ -1,23 +1,13 @@
1
1
  import os
2
- from typing import Any, Dict, List
2
+ from typing import Dict, List
3
3
 
4
4
  import dotenv
5
- import requests
6
5
 
7
- from vaultapi.aws import LOGGER
8
- from vaultapi.config import getenv, resolve_secrets, server_map
9
- from vaultapi.transit import TransitShield
10
- from vaultapi.util import urljoin
11
-
12
-
13
- def process_response(response: requests.Response) -> Any:
14
- """Asserts on the response code, and returns the response detail.
15
-
16
- Args:
17
- response: Takes the Response object as an argument.
18
- """
19
- assert response.ok, response.text
20
- return response.json()["detail"]
6
+ from vaultapi_client.aws import LOGGER
7
+ from vaultapi_client.config import getenv, resolve_secrets, server_map
8
+ from vaultapi_client.session import Session
9
+ from vaultapi_client.transit import TransitShield
10
+ from vaultapi_client.util import urljoin
21
11
 
22
12
 
23
13
  class VaultAPIClient:
@@ -31,7 +21,7 @@ class VaultAPIClient:
31
21
  """Instantiates the VaultAPIClient object."""
32
22
  self.env_config = resolve_secrets(aws)
33
23
  self.transit_shield = TransitShield(self.env_config)
34
- self.SESSION = requests.Session()
24
+ self.SESSION = Session()
35
25
  self.SESSION.headers = {
36
26
  "accept": "application/json",
37
27
  "Authorization": f"Bearer {self.env_config.vault_apikey}",
@@ -48,11 +38,10 @@ class VaultAPIClient:
48
38
  str:
49
39
  Returns the ciphertext.
50
40
  """
51
- response = self.SESSION.get(
41
+ return self.SESSION.get(
52
42
  server_url,
53
43
  params=query_params,
54
44
  )
55
- return process_response(response)
56
45
 
57
46
  def dotenv_to_table(self, table_name: str, dotenv_file: str) -> Dict[str, str]:
58
47
  """Store all the env vars from a .env file into the database.
@@ -80,14 +69,13 @@ class VaultAPIClient:
80
69
  Returns the server response.
81
70
  """
82
71
  url = urljoin(self.env_config.vault_server, server_map.put_secret)
83
- response = self.SESSION.put(
72
+ return self.SESSION.put(
84
73
  url,
85
74
  json={
86
75
  "secrets": self.transit_shield.encrypt(payload=secrets),
87
76
  "table_name": table_name,
88
77
  },
89
78
  )
90
- return process_response(response)
91
79
 
92
80
  def delete_secret(self, key: str, table_name: str) -> Dict[str, str]:
93
81
  """Delete a secret from the vault.
@@ -101,14 +89,13 @@ class VaultAPIClient:
101
89
  Returns the server response.
102
90
  """
103
91
  url = urljoin(self.env_config.vault_server, server_map.delete_secret)
104
- response = self.SESSION.delete(
92
+ return self.SESSION.delete(
105
93
  url,
106
94
  json={
107
95
  "key": key,
108
96
  "table_name": table_name,
109
97
  },
110
98
  )
111
- return process_response(response)
112
99
 
113
100
  def list_tables(self) -> List[str]:
114
101
  """List all available tables.
@@ -118,8 +105,7 @@ class VaultAPIClient:
118
105
  Returns the available table names as a list of strings.
119
106
  """
120
107
  url = urljoin(self.env_config.vault_server, server_map.list_tables)
121
- response = self.SESSION.get(url)
122
- return process_response(response)
108
+ return self.SESSION.get(url)
123
109
 
124
110
  def create_table(self, table_name: str) -> Dict[str, str]:
125
111
  """Creates a new table in the vault.
@@ -132,8 +118,7 @@ class VaultAPIClient:
132
118
  Returns the server response.
133
119
  """
134
120
  url = urljoin(self.env_config.vault_server, server_map.create_table)
135
- response = self.SESSION.post(url, params={"table_name": table_name})
136
- return process_response(response)
121
+ return self.SESSION.post(url, params={"table_name": table_name})
137
122
 
138
123
  def delete_table(self, table_name: str) -> Dict[str, str]:
139
124
  """Deletes an existing table.
@@ -146,8 +131,7 @@ class VaultAPIClient:
146
131
  Returns the server response.
147
132
  """
148
133
  url = urljoin(self.env_config.vault_server, server_map.delete_table)
149
- response = self.SESSION.delete(url, params={"table_name": table_name})
150
- return process_response(response)
134
+ return self.SESSION.delete(url, params={"table_name": table_name})
151
135
 
152
136
  def get_secret(self, key: str, table_name: str) -> Dict[str, str]:
153
137
  """Retrieves multiple secrets from a table.
@@ -0,0 +1,63 @@
1
+ from typing import Any, NoReturn
2
+
3
+ import requests
4
+
5
+ from vaultapi_client.exceptions import VaultAPIServerError
6
+
7
+
8
+ def _request_error(error: requests.RequestException) -> NoReturn:
9
+ """Uses requests module base exception to raise a custom server error."""
10
+ raise VaultAPIServerError(
11
+ f"Request failed: {error}",
12
+ status_code=getattr(error.response, "status_code", None),
13
+ )
14
+
15
+
16
+ def process_response(response: requests.Response) -> Any:
17
+ """Asserts on the response code, and returns the response detail.
18
+
19
+ Args:
20
+ response: Takes the Response object as an argument.
21
+ """
22
+ try:
23
+ response.raise_for_status()
24
+ return response.json()["detail"]
25
+ except requests.RequestException as error:
26
+ _request_error(error)
27
+ except requests.JSONDecodeError as error:
28
+ raise VaultAPIServerError(
29
+ message=f"Invalid JSON response from the server: {error}"
30
+ )
31
+
32
+
33
+ class Session(requests.Session):
34
+ """Custom requests session with centralized error handling.
35
+
36
+ >>> Session
37
+
38
+ """
39
+
40
+ def request(self, method, url, **kwargs) -> Any:
41
+ """Intercepts all HTTP requests and applies centralized error handling."""
42
+ try:
43
+ response = super().request(method, url, **kwargs)
44
+ response.raise_for_status()
45
+ return process_response(response)
46
+ except requests.exceptions.RequestException as error:
47
+ _request_error(error)
48
+
49
+ def get(self, url, **kwargs) -> Any:
50
+ """Make GET request to the server and process the response."""
51
+ return self.request("GET", url, **kwargs)
52
+
53
+ def put(self, url, **kwargs) -> Any:
54
+ """Make PUT request to the server and process the response."""
55
+ return self.request("PUT", url, **kwargs)
56
+
57
+ def post(self, url, **kwargs) -> Any:
58
+ """Make POST request to the server and process the response."""
59
+ return self.request("POST", url, **kwargs)
60
+
61
+ def delete(self, url, **kwargs) -> Any:
62
+ """Make DELETE request to the server and process the response."""
63
+ return self.request("DELETE", url, **kwargs)
@@ -5,9 +5,11 @@ import secrets
5
5
  import time
6
6
  from typing import Any, ByteString, Dict
7
7
 
8
+ from cryptography.exceptions import InvalidTag
8
9
  from cryptography.hazmat.primitives.ciphers.aead import AESGCM
9
10
 
10
- from vaultapi.config import EnvConfig
11
+ from vaultapi_client.config import EnvConfig
12
+ from vaultapi_client.exceptions import InvalidCipherText
11
13
 
12
14
 
13
15
  class TransitShield:
@@ -83,5 +85,8 @@ class TransitShield:
83
85
  aes_key = hash_object.digest()[: self.env_config.transit_key_length]
84
86
  if isinstance(ciphertext, str):
85
87
  ciphertext = base64.b64decode(ciphertext)
86
- decrypted = AESGCM(aes_key).decrypt(ciphertext[:12], ciphertext[12:], b"")
88
+ try:
89
+ decrypted = AESGCM(aes_key).decrypt(ciphertext[:12], ciphertext[12:], b"")
90
+ except InvalidTag:
91
+ raise InvalidCipherText("Ciphertext has either expired or invalid!")
87
92
  return json.loads(decrypted)
@@ -1,5 +1,5 @@
1
1
  def urljoin(*args) -> str:
2
- """Joins given arguments into an url. Trailing but not leading slashes are stripped for each argument.
2
+ """Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument.
3
3
 
4
4
  Returns:
5
5
  str:
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: VaultAPI-Client
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: Client application for VaultAPI Server
5
5
  Author-email: Vignesh Rao <svignesh1793@gmail.com>
6
6
  License: MIT License
@@ -40,6 +40,7 @@ Provides-Extra: dev
40
40
  Requires-Dist: pre-commit; extra == "dev"
41
41
  Provides-Extra: aws
42
42
  Requires-Dist: boto3==1.36.*; extra == "aws"
43
+ Dynamic: license-file
43
44
 
44
45
  # VaultAPI-Client-python
45
46
  Client application for VaultAPI Server
@@ -72,12 +73,12 @@ python -m pip install vaultapi
72
73
  ```
73
74
 
74
75
  **Initiate - IDE**
75
- ```python
76
- import vaultapi
77
76
 
77
+ ```python
78
+ import vaultapi_client
78
79
 
79
80
  if __name__ == '__main__':
80
- vaultapi_client = vaultapi.VaultAPIClient()
81
+ vaultapi_client = vaultapi_client.VaultAPIClient()
81
82
  vaultapi_client.get_secret(key="mykey", table_name="mytable")
82
83
  ```
83
84
 
@@ -0,0 +1,14 @@
1
+ vaultapi_client/__init__.py,sha256=LHW0GcEjPPZAUdv1I659tjDuV5F6WPTzgoIVQ0Pe8OE,1507
2
+ vaultapi_client/aws.py,sha256=jOoddFCU1zdi5aqcjjCcSE2X8lwTZvFHrsCpZmCVsm8,2804
3
+ vaultapi_client/config.py,sha256=SQPWKUCk2VNF_8-pwrYiQE0O9F12gtTZeNmOyM5xblM,4291
4
+ vaultapi_client/exceptions.py,sha256=ezm_UbAK51_EoavBT19Tten41YgoZ4FkMRj9ktwblGc,595
5
+ vaultapi_client/main.py,sha256=iZsSHcntXg_RC6kfSgBjyMFqdIYKYUW0EbrlpAzKHEY,6075
6
+ vaultapi_client/session.py,sha256=ApeQD8hPdGG6caz06y49xn7OS0QFpNx86575YwAb1nE,2111
7
+ vaultapi_client/transit.py,sha256=ZH4OF-TO50zQfcCy6e1f202QWYaBPk9bzZ2bWhSPQxo,3114
8
+ vaultapi_client/util.py,sha256=95W56Z9vfYxkiLG3U9T9-iIPuvpLSpQpyMduLlMsubc,261
9
+ vaultapi_client-0.2.0.dist-info/licenses/LICENSE,sha256=_sOIKJWdD2o1WwwDIwYB2qTP2nlSWqT5Tyg9jr1Xa4w,1070
10
+ vaultapi_client-0.2.0.dist-info/METADATA,sha256=LiTU6Xlr6MarR429GLutqospENz5MFtdeBnsqHnV9rE,5719
11
+ vaultapi_client-0.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
12
+ vaultapi_client-0.2.0.dist-info/entry_points.txt,sha256=P3CaBVJ9RvRJy7xvd9A4o3HYEfoM4wStZcQ8L6837NE,64
13
+ vaultapi_client-0.2.0.dist-info/top_level.txt,sha256=J0qf2Tuj66RGC_VTF9f3Ce137qPqL8n0V21-1xwp1nw,16
14
+ vaultapi_client-0.2.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (75.8.0)
2
+ Generator: setuptools (80.9.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vaultapi-client = vaultapi_client:commandline
@@ -0,0 +1 @@
1
+ vaultapi_client
@@ -1,13 +0,0 @@
1
- vaultapi/__init__.py,sha256=4Qrvj-J-MKCdBly6xVIxdVV1ueDp30hwqSfiBWjab8I,1507
2
- vaultapi/aws.py,sha256=FpFDP9jDmiXek_zzgVMQ5FZoqzyh0HIR4vqnry0Ap-U,2722
3
- vaultapi/config.py,sha256=06PBsWd5RxehK1BvFfDCzm96Dic1RK-qOp9rCRpZC6k,3873
4
- vaultapi/exceptions.py,sha256=KUTAshsxk7ewcZsjGibGP0076L0QrLzuADRnrv30FK4,90
5
- vaultapi/main.py,sha256=zcVAPOzKVdB0eDqbxr8GNCNBXfC3L2LSEc2Jh8lim1o,6593
6
- vaultapi/transit.py,sha256=VaP4bSryulgpMn4tXcGnEUCJ1AAZYzHw4EwYhdIF4XE,2878
7
- vaultapi/util.py,sha256=REd8SIycx9q6AQoaHG8UfkbWfPHUtSSz7E3ngWRc4WM,262
8
- VaultAPI_Client-0.1.2.dist-info/LICENSE,sha256=_sOIKJWdD2o1WwwDIwYB2qTP2nlSWqT5Tyg9jr1Xa4w,1070
9
- VaultAPI_Client-0.1.2.dist-info/METADATA,sha256=3sWt5TXIHhgB0uWooRgHbYVK3YJL8u6e_a0QCSqi3ko,5683
10
- VaultAPI_Client-0.1.2.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
11
- VaultAPI_Client-0.1.2.dist-info/entry_points.txt,sha256=MKe6sVDEAHC3YBZoYWLMvgwupRE_QJ_iHK0umfgGOzs,50
12
- VaultAPI_Client-0.1.2.dist-info/top_level.txt,sha256=17jtNvOOJqazNgWn2ZTmJqfQau5jan_xF82NAJOINQg,9
13
- VaultAPI_Client-0.1.2.dist-info/RECORD,,
@@ -1,2 +0,0 @@
1
- [console_scripts]
2
- vaultapi = vaultapi:commandline
@@ -1 +0,0 @@
1
- vaultapi
vaultapi/exceptions.py DELETED
@@ -1,2 +0,0 @@
1
- class VaultAPIClientError(Exception):
2
- """Base error class for the VaultAPI Client."""