VaultAPI-Client 0.2.0__py3-none-any.whl → 0.3.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.
- vaultapi_client/__init__.py +10 -19
- vaultapi_client/aws.py +5 -9
- vaultapi_client/config.py +53 -22
- vaultapi_client/exceptions.py +1 -1
- vaultapi_client/main.py +72 -35
- vaultapi_client/session.py +113 -17
- vaultapi_client/util.py +13 -2
- {vaultapi_client-0.2.0.dist-info → vaultapi_client-0.3.0.dist-info}/METADATA +3 -1
- vaultapi_client-0.3.0.dist-info/RECORD +14 -0
- {vaultapi_client-0.2.0.dist-info → vaultapi_client-0.3.0.dist-info}/WHEEL +1 -1
- vaultapi_client-0.2.0.dist-info/RECORD +0 -14
- {vaultapi_client-0.2.0.dist-info → vaultapi_client-0.3.0.dist-info}/entry_points.txt +0 -0
- {vaultapi_client-0.2.0.dist-info → vaultapi_client-0.3.0.dist-info}/licenses/LICENSE +0 -0
- {vaultapi_client-0.2.0.dist-info → vaultapi_client-0.3.0.dist-info}/top_level.txt +0 -0
vaultapi_client/__init__.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import argparse
|
|
2
2
|
import json
|
|
3
3
|
|
|
4
|
-
from .exceptions import VaultAPIClientError
|
|
5
|
-
from .main import
|
|
4
|
+
from .exceptions import VaultAPIClientError # noqa: F401
|
|
5
|
+
from .main import VaultAPIClient
|
|
6
6
|
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
def commandline():
|
|
@@ -20,28 +20,19 @@ def commandline():
|
|
|
20
20
|
"Requires 'pip install VaultAPI-Client[aws]'",
|
|
21
21
|
)
|
|
22
22
|
parser.add_argument(
|
|
23
|
-
"--get-secret",
|
|
24
|
-
|
|
25
|
-
parser.add_argument(
|
|
26
|
-
"--get-secrets",
|
|
27
|
-
help="Retrieve multiple secrets from Vault with a comma separated list of keys",
|
|
23
|
+
"--get-secret",
|
|
24
|
+
help="Retrieve a secret from Vault using the secret key, or leave it empty to get the entire table.",
|
|
28
25
|
)
|
|
29
26
|
parser.add_argument(
|
|
30
27
|
"--table",
|
|
31
|
-
help="Table name where the secrets are stored. "
|
|
32
|
-
"Can be used with --get-secret/--get-secrets or itself to retrieve all the secrets in a table",
|
|
28
|
+
help="Table name where the secrets are stored. Required to retrieve a secret from the Vault API.",
|
|
33
29
|
)
|
|
34
|
-
|
|
35
|
-
if
|
|
30
|
+
kwargs = dict(parser.parse_args()._get_kwargs())
|
|
31
|
+
if kwargs["version"]:
|
|
36
32
|
print(f"VaultAPI Client: {version}")
|
|
37
33
|
exit(0)
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
except VaultAPIClientError as error:
|
|
41
|
-
LOGGER.exception(error)
|
|
42
|
-
exit(1)
|
|
43
|
-
kwargs = dict(args._get_kwargs())
|
|
34
|
+
assert kwargs["table"] is not None, "table name must be provided"
|
|
35
|
+
vaultapi_client = VaultAPIClient(aws=kwargs["aws"])
|
|
44
36
|
kwargs.pop("version", None)
|
|
45
37
|
kwargs.pop("aws", None)
|
|
46
|
-
LOGGER.debug(kwargs)
|
|
47
38
|
print(json.dumps(vaultapi_client.decrypt(**kwargs), indent=2))
|
vaultapi_client/aws.py
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
import logging
|
|
2
1
|
import os
|
|
2
|
+
import warnings
|
|
3
3
|
from typing import List
|
|
4
4
|
|
|
5
|
-
LOGGER = logging.getLogger(__name__)
|
|
6
|
-
|
|
7
5
|
|
|
8
6
|
class AWSClient:
|
|
9
7
|
"""AWS client object to retrieve parameters (parameter store) or secrets (from secrets manager).
|
|
@@ -31,7 +29,7 @@ class AWSClient:
|
|
|
31
29
|
self.secret_client = session.client(service_name="secretsmanager")
|
|
32
30
|
self.ssm_client = session.client(service_name="ssm")
|
|
33
31
|
|
|
34
|
-
def get_aws_secrets(self, name: str = None) -> str | List[str] | None:
|
|
32
|
+
def get_aws_secrets(self, name: str | None = None) -> str | List[str] | None:
|
|
35
33
|
"""Get secrets from AWS secretsmanager.
|
|
36
34
|
|
|
37
35
|
Args:
|
|
@@ -42,18 +40,17 @@ class AWSClient:
|
|
|
42
40
|
Returns the value of the secret or list of all secrets' names.
|
|
43
41
|
"""
|
|
44
42
|
if name:
|
|
45
|
-
LOGGER.info("Retrieving the secret '%s' from AWS secrets manager", name)
|
|
46
43
|
try:
|
|
47
44
|
response = self.secret_client.get_secret_value(SecretId=name)
|
|
48
45
|
except Exception as error:
|
|
49
|
-
|
|
46
|
+
warnings.warn(error.__str__(), category=UserWarning, stacklevel=3)
|
|
50
47
|
return None
|
|
51
48
|
return response["SecretString"]
|
|
52
49
|
paginator = self.secret_client.get_paginator("list_secrets")
|
|
53
50
|
page_results = paginator.paginate().build_full_result()
|
|
54
51
|
return [page["Name"] for page in page_results["SecretList"]]
|
|
55
52
|
|
|
56
|
-
def get_aws_params(self, name: str = None) -> str | List[str] | None:
|
|
53
|
+
def get_aws_params(self, name: str | None = None) -> str | List[str] | None:
|
|
57
54
|
"""Get SSM parameters from AWS.
|
|
58
55
|
|
|
59
56
|
Args:
|
|
@@ -64,11 +61,10 @@ class AWSClient:
|
|
|
64
61
|
Returns the value of the parameter or list of all parameter names.
|
|
65
62
|
"""
|
|
66
63
|
if name:
|
|
67
|
-
LOGGER.info("Retrieving the parameter '%s' from AWS parameter store", name)
|
|
68
64
|
try:
|
|
69
65
|
response = self.ssm_client.get_parameter(Name=name, WithDecryption=True)
|
|
70
66
|
except Exception as error:
|
|
71
|
-
|
|
67
|
+
warnings.warn(error.__str__(), category=UserWarning, stacklevel=3)
|
|
72
68
|
return None
|
|
73
69
|
return response["Parameter"]["Value"]
|
|
74
70
|
paginator = self.ssm_client.get_paginator("describe_parameters")
|
vaultapi_client/config.py
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import os
|
|
2
|
+
from enum import Enum
|
|
2
3
|
from typing import NoReturn
|
|
3
4
|
|
|
4
5
|
import dotenv
|
|
5
6
|
import requests
|
|
6
7
|
from cryptography.fernet import Fernet
|
|
8
|
+
from packaging import version
|
|
7
9
|
|
|
8
10
|
from vaultapi_client.aws import AWSClient
|
|
9
11
|
from vaultapi_client.exceptions import VaultAPIClientError, VaultAPIServerError
|
|
@@ -11,26 +13,26 @@ from vaultapi_client.util import urljoin
|
|
|
11
13
|
|
|
12
14
|
env_file = os.environ.get("ENV_FILE") or os.environ.get("env_file") or ".env"
|
|
13
15
|
dotenv.load_dotenv(env_file)
|
|
16
|
+
MINIMUM_SERVER_VERSION = version.parse("0.6.0")
|
|
14
17
|
|
|
15
18
|
|
|
16
|
-
class EndpointMapping:
|
|
19
|
+
class EndpointMapping(Enum):
|
|
17
20
|
"""Enum like function to get all endpoint names to avoid hard coding.
|
|
18
21
|
|
|
19
22
|
>>> EndpointMapping
|
|
20
23
|
|
|
21
24
|
"""
|
|
22
25
|
|
|
23
|
-
health
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
server_map = EndpointMapping()
|
|
26
|
+
health = "/health"
|
|
27
|
+
version = "/version"
|
|
28
|
+
get_table = "/get-table"
|
|
29
|
+
get_secret = "/get-secret"
|
|
30
|
+
put_secret = "/put-secret"
|
|
31
|
+
list_tables = "/list-tables"
|
|
32
|
+
create_table = "/create-table"
|
|
33
|
+
rename_table = "/rename-table"
|
|
34
|
+
delete_table = "/delete-table"
|
|
35
|
+
delete_secret = "/delete-secret"
|
|
34
36
|
|
|
35
37
|
|
|
36
38
|
class EnvConfig:
|
|
@@ -40,27 +42,56 @@ class EnvConfig:
|
|
|
40
42
|
|
|
41
43
|
"""
|
|
42
44
|
|
|
43
|
-
def __init__(
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
vault_server: str,
|
|
48
|
+
vault_apikey: str,
|
|
49
|
+
vault_secret: str,
|
|
50
|
+
vault_transit_key_length: int,
|
|
51
|
+
vault_transit_time_bucket: int,
|
|
52
|
+
) -> None:
|
|
44
53
|
"""Instantiates the env config."""
|
|
45
|
-
self.vault_server: str =
|
|
46
|
-
self.vault_apikey: str =
|
|
47
|
-
self.vault_secret: str =
|
|
48
|
-
self.
|
|
49
|
-
self.
|
|
54
|
+
self.vault_server: str = vault_server
|
|
55
|
+
self.vault_apikey: str = vault_apikey
|
|
56
|
+
self.vault_secret: str = vault_secret
|
|
57
|
+
self.transit_key_length: int = int(vault_transit_key_length)
|
|
58
|
+
self.transit_time_bucket: int = int(vault_transit_time_bucket)
|
|
50
59
|
self.__assert__()
|
|
51
60
|
|
|
52
|
-
def
|
|
53
|
-
"""
|
|
61
|
+
def server_check(self, endpoint: EndpointMapping) -> None | NoReturn:
|
|
62
|
+
"""Checks if the server is reachable and matches the required version.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
endpoint: Endpoint to check.
|
|
66
|
+
"""
|
|
54
67
|
try:
|
|
55
68
|
response = requests.get(
|
|
56
|
-
url=urljoin(self.vault_server,
|
|
69
|
+
url=urljoin(self.vault_server, endpoint), timeout=(1, 1)
|
|
57
70
|
)
|
|
58
71
|
response.raise_for_status()
|
|
59
72
|
except requests.RequestException as error:
|
|
73
|
+
context = (
|
|
74
|
+
error.response.text
|
|
75
|
+
if (error.response and error.response.text)
|
|
76
|
+
else str(error.__context__)
|
|
77
|
+
)
|
|
60
78
|
raise VaultAPIServerError(
|
|
61
|
-
message=
|
|
79
|
+
message=context,
|
|
62
80
|
status_code=getattr(error.response, "status_code", None),
|
|
63
81
|
)
|
|
82
|
+
if endpoint == EndpointMapping.version:
|
|
83
|
+
# Make sure server_version is more than MINIMUM_SERVER_VERSION
|
|
84
|
+
server_version = version.parse(response.json())
|
|
85
|
+
if server_version < MINIMUM_SERVER_VERSION:
|
|
86
|
+
raise VaultAPIServerError(
|
|
87
|
+
f"Server version [{server_version}] is below the minimum required version "
|
|
88
|
+
f"[{MINIMUM_SERVER_VERSION}]. Please upgrade the server [OR] use the client version <=0.2.0."
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def __assert__(self) -> None | NoReturn:
|
|
92
|
+
"""Run assertions for server config."""
|
|
93
|
+
self.server_check(EndpointMapping.health)
|
|
94
|
+
self.server_check(EndpointMapping.version)
|
|
64
95
|
try:
|
|
65
96
|
assert self.transit_key_length in (16, 24, 32)
|
|
66
97
|
except AssertionError:
|
vaultapi_client/exceptions.py
CHANGED
|
@@ -13,7 +13,7 @@ class InvalidCipherText(VaultAPIClientError):
|
|
|
13
13
|
class VaultAPIServerError(VaultAPIClientError):
|
|
14
14
|
"""Subclass for errors when connecting to the server."""
|
|
15
15
|
|
|
16
|
-
def __init__(self, message: str, status_code: int = None):
|
|
16
|
+
def __init__(self, message: str, status_code: int | None = None):
|
|
17
17
|
"""Super class to handle custom error message and status code."""
|
|
18
18
|
self.message = message
|
|
19
19
|
self.status_code = status_code
|
vaultapi_client/main.py
CHANGED
|
@@ -3,11 +3,9 @@ from typing import Dict, List
|
|
|
3
3
|
|
|
4
4
|
import dotenv
|
|
5
5
|
|
|
6
|
-
from vaultapi_client.
|
|
7
|
-
from vaultapi_client.config import getenv, resolve_secrets, server_map
|
|
6
|
+
from vaultapi_client.config import EndpointMapping, getenv, resolve_secrets
|
|
8
7
|
from vaultapi_client.session import Session
|
|
9
8
|
from vaultapi_client.transit import TransitShield
|
|
10
|
-
from vaultapi_client.util import urljoin
|
|
11
9
|
|
|
12
10
|
|
|
13
11
|
class VaultAPIClient:
|
|
@@ -21,17 +19,15 @@ class VaultAPIClient:
|
|
|
21
19
|
"""Instantiates the VaultAPIClient object."""
|
|
22
20
|
self.env_config = resolve_secrets(aws)
|
|
23
21
|
self.transit_shield = TransitShield(self.env_config)
|
|
24
|
-
self.SESSION = Session()
|
|
25
|
-
self.SESSION.headers = {
|
|
26
|
-
"accept": "application/json",
|
|
27
|
-
"Authorization": f"Bearer {self.env_config.vault_apikey}",
|
|
28
|
-
}
|
|
22
|
+
self.SESSION = Session(self.env_config)
|
|
29
23
|
|
|
30
|
-
def _get_cipher(
|
|
24
|
+
def _get_cipher(
|
|
25
|
+
self, endpoint: EndpointMapping, query_params: Dict[str, str]
|
|
26
|
+
) -> str:
|
|
31
27
|
"""Get ciphertext from the server.
|
|
32
28
|
|
|
33
29
|
Args:
|
|
34
|
-
|
|
30
|
+
endpoint: API endpoint to request.
|
|
35
31
|
query_params: Query parameters to send with the request.
|
|
36
32
|
|
|
37
33
|
Returns:
|
|
@@ -39,7 +35,7 @@ class VaultAPIClient:
|
|
|
39
35
|
Returns the ciphertext.
|
|
40
36
|
"""
|
|
41
37
|
return self.SESSION.get(
|
|
42
|
-
|
|
38
|
+
endpoint,
|
|
43
39
|
params=query_params,
|
|
44
40
|
)
|
|
45
41
|
|
|
@@ -54,9 +50,31 @@ class VaultAPIClient:
|
|
|
54
50
|
assert os.path.isfile(dotenv_file)
|
|
55
51
|
except AssertionError:
|
|
56
52
|
raise FileNotFoundError(dotenv_file)
|
|
57
|
-
env_vars =
|
|
53
|
+
env_vars = {
|
|
54
|
+
k: v for k, v in dotenv.dotenv_values(dotenv_file).items() if v is not None
|
|
55
|
+
}
|
|
58
56
|
return self.update_secret(secrets=env_vars, table_name=table_name)
|
|
59
57
|
|
|
58
|
+
def table_to_env(self, table_name: str, dotenv_file: str | None = None) -> None:
|
|
59
|
+
"""Retrieve all secrets from the database and store them as env vars.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
table_name: Vault table name,
|
|
63
|
+
dotenv_file: Dot env filename to store secrets in addition to env vars.
|
|
64
|
+
"""
|
|
65
|
+
if dotenv_file:
|
|
66
|
+
try:
|
|
67
|
+
assert os.path.isfile(dotenv_file)
|
|
68
|
+
except AssertionError:
|
|
69
|
+
raise FileNotFoundError(dotenv_file)
|
|
70
|
+
secrets = self.get_table(table_name)
|
|
71
|
+
for key, value in secrets.items():
|
|
72
|
+
os.environ[key] = value
|
|
73
|
+
if dotenv_file:
|
|
74
|
+
dotenv.set_key(
|
|
75
|
+
dotenv_path=dotenv_file, key_to_set=key, value_to_set=value
|
|
76
|
+
)
|
|
77
|
+
|
|
60
78
|
def update_secret(self, secrets: Dict[str, str], table_name: str) -> Dict[str, str]:
|
|
61
79
|
"""Update or create secrets in the vault.
|
|
62
80
|
|
|
@@ -68,9 +86,8 @@ class VaultAPIClient:
|
|
|
68
86
|
Dict[str, str]:
|
|
69
87
|
Returns the server response.
|
|
70
88
|
"""
|
|
71
|
-
url = urljoin(self.env_config.vault_server, server_map.put_secret)
|
|
72
89
|
return self.SESSION.put(
|
|
73
|
-
|
|
90
|
+
EndpointMapping.put_secret,
|
|
74
91
|
json={
|
|
75
92
|
"secrets": self.transit_shield.encrypt(payload=secrets),
|
|
76
93
|
"table_name": table_name,
|
|
@@ -88,9 +105,8 @@ class VaultAPIClient:
|
|
|
88
105
|
Dict[str, str]:
|
|
89
106
|
Returns the server response.
|
|
90
107
|
"""
|
|
91
|
-
url = urljoin(self.env_config.vault_server, server_map.delete_secret)
|
|
92
108
|
return self.SESSION.delete(
|
|
93
|
-
|
|
109
|
+
EndpointMapping.delete_secret,
|
|
94
110
|
json={
|
|
95
111
|
"key": key,
|
|
96
112
|
"table_name": table_name,
|
|
@@ -104,11 +120,10 @@ class VaultAPIClient:
|
|
|
104
120
|
List[str]:
|
|
105
121
|
Returns the available table names as a list of strings.
|
|
106
122
|
"""
|
|
107
|
-
|
|
108
|
-
return self.SESSION.get(url)
|
|
123
|
+
return self.SESSION.get(EndpointMapping.list_tables)
|
|
109
124
|
|
|
110
125
|
def create_table(self, table_name: str) -> Dict[str, str]:
|
|
111
|
-
"""Creates a new table in the vault.
|
|
126
|
+
"""Creates a new table in the vault database.
|
|
112
127
|
|
|
113
128
|
Args:
|
|
114
129
|
table_name: Table name.
|
|
@@ -117,8 +132,26 @@ class VaultAPIClient:
|
|
|
117
132
|
Dict[str, str]:
|
|
118
133
|
Returns the server response.
|
|
119
134
|
"""
|
|
120
|
-
|
|
121
|
-
|
|
135
|
+
return self.SESSION.post(
|
|
136
|
+
EndpointMapping.create_table, params={"table_name": table_name}
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def rename_table(self, table_name: str, new_name: str) -> str:
|
|
140
|
+
"""Renames a table in the vault database.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
table_name: Table name to rename.
|
|
144
|
+
new_name: New table name.
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
str:
|
|
148
|
+
Returns the server response.
|
|
149
|
+
"""
|
|
150
|
+
return self.SESSION.patch(
|
|
151
|
+
EndpointMapping.rename_table,
|
|
152
|
+
params={"table_name": table_name},
|
|
153
|
+
json=dict(new_name=new_name),
|
|
154
|
+
)
|
|
122
155
|
|
|
123
156
|
def delete_table(self, table_name: str) -> Dict[str, str]:
|
|
124
157
|
"""Deletes an existing table.
|
|
@@ -130,8 +163,9 @@ class VaultAPIClient:
|
|
|
130
163
|
Dict[str, str]:
|
|
131
164
|
Returns the server response.
|
|
132
165
|
"""
|
|
133
|
-
|
|
134
|
-
|
|
166
|
+
return self.SESSION.delete(
|
|
167
|
+
EndpointMapping.delete_table, params={"table_name": table_name}
|
|
168
|
+
)
|
|
135
169
|
|
|
136
170
|
def get_secret(self, key: str, table_name: str) -> Dict[str, str]:
|
|
137
171
|
"""Retrieves multiple secrets from a table.
|
|
@@ -144,9 +178,10 @@ class VaultAPIClient:
|
|
|
144
178
|
Dict[str, str]:
|
|
145
179
|
Returns a dictionary of decrypted values.
|
|
146
180
|
"""
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
181
|
+
cipher_text = self._get_cipher(
|
|
182
|
+
EndpointMapping.get_secret, {"key": key, "table_name": table_name}
|
|
183
|
+
)
|
|
184
|
+
return self.transit_shield.decrypt(ciphertext=cipher_text)
|
|
150
185
|
|
|
151
186
|
def get_table(self, table_name: str) -> Dict[str, str]:
|
|
152
187
|
"""Retrieves all the secrets stored in a table.
|
|
@@ -158,14 +193,15 @@ class VaultAPIClient:
|
|
|
158
193
|
Dict[str, str]:
|
|
159
194
|
Returns a dictionary of decrypted values.
|
|
160
195
|
"""
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
196
|
+
cipher_text = self._get_cipher(
|
|
197
|
+
EndpointMapping.get_table, {"table_name": table_name}
|
|
198
|
+
)
|
|
199
|
+
return self.transit_shield.decrypt(ciphertext=cipher_text)
|
|
164
200
|
|
|
165
201
|
def decrypt(
|
|
166
202
|
self,
|
|
167
203
|
table: str,
|
|
168
|
-
get_secret: str = None,
|
|
204
|
+
get_secret: str | None = None,
|
|
169
205
|
) -> Dict[str, str] | str:
|
|
170
206
|
"""Decrypt function.
|
|
171
207
|
|
|
@@ -178,12 +214,13 @@ class VaultAPIClient:
|
|
|
178
214
|
Returns a dictionary of decrypted values.
|
|
179
215
|
"""
|
|
180
216
|
if not table:
|
|
181
|
-
|
|
182
|
-
return {}
|
|
217
|
+
raise ValueError("Table name is required to decrypt.")
|
|
183
218
|
params = dict(table_name=table)
|
|
184
219
|
if get_secret:
|
|
185
|
-
|
|
220
|
+
endpoint = EndpointMapping.get_secret
|
|
186
221
|
params["key"] = get_secret
|
|
187
222
|
else:
|
|
188
|
-
|
|
189
|
-
return self.transit_shield.decrypt(
|
|
223
|
+
endpoint = EndpointMapping.get_table
|
|
224
|
+
return self.transit_shield.decrypt(
|
|
225
|
+
self._get_cipher(endpoint=EndpointMapping(endpoint), query_params=params)
|
|
226
|
+
)
|
vaultapi_client/session.py
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import time
|
|
4
|
+
from typing import Any, Callable, Dict, NoReturn
|
|
2
5
|
|
|
3
6
|
import requests
|
|
4
7
|
|
|
8
|
+
from vaultapi_client.config import EndpointMapping, EnvConfig
|
|
5
9
|
from vaultapi_client.exceptions import VaultAPIServerError
|
|
10
|
+
from vaultapi_client.util import urljoin
|
|
6
11
|
|
|
7
12
|
|
|
8
13
|
def _request_error(error: requests.RequestException) -> NoReturn:
|
|
@@ -13,6 +18,35 @@ def _request_error(error: requests.RequestException) -> NoReturn:
|
|
|
13
18
|
)
|
|
14
19
|
|
|
15
20
|
|
|
21
|
+
def generate_bearer_token(token: str) -> str:
|
|
22
|
+
"""Generate an authentication header value for API requests.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
token: Shared API token used as the HMAC secret key.
|
|
26
|
+
|
|
27
|
+
See Also:
|
|
28
|
+
- The generated header contains:
|
|
29
|
+
- A Unix timestamp in seconds.
|
|
30
|
+
- An HMAC-SHA512 signature computed using the API token as the secret key and the timestamp as the message.
|
|
31
|
+
- | The server can validate the signature and ensure the timestamp is within an acceptable age window,
|
|
32
|
+
| to reduce replay attacks.
|
|
33
|
+
|
|
34
|
+
Example:
|
|
35
|
+
Authorization: Signature=<signature>,timestamp=<timestamp>
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
str:
|
|
39
|
+
Authentication header value containing the signature and timestamp.
|
|
40
|
+
"""
|
|
41
|
+
timestamp = str(int(time.time()))
|
|
42
|
+
signature = hmac.new(
|
|
43
|
+
token.encode("utf-8"),
|
|
44
|
+
timestamp.encode("utf-8"),
|
|
45
|
+
hashlib.sha512,
|
|
46
|
+
).hexdigest()
|
|
47
|
+
return f"Signature={signature},timestamp={timestamp}"
|
|
48
|
+
|
|
49
|
+
|
|
16
50
|
def process_response(response: requests.Response) -> Any:
|
|
17
51
|
"""Asserts on the response code, and returns the response detail.
|
|
18
52
|
|
|
@@ -30,34 +64,96 @@ def process_response(response: requests.Response) -> Any:
|
|
|
30
64
|
)
|
|
31
65
|
|
|
32
66
|
|
|
33
|
-
class Session
|
|
34
|
-
"""Custom requests session with centralized error handling.
|
|
67
|
+
class Session:
|
|
68
|
+
"""Custom requests session with centralized error handling, headers infusion, and response processing.
|
|
35
69
|
|
|
36
70
|
>>> Session
|
|
37
71
|
|
|
38
72
|
"""
|
|
39
73
|
|
|
40
|
-
def
|
|
41
|
-
|
|
74
|
+
def __init__(self, env_config: EnvConfig) -> None:
|
|
75
|
+
self.apikey = env_config.vault_apikey
|
|
76
|
+
self.secret = env_config.vault_secret
|
|
77
|
+
self.server = env_config.vault_server
|
|
78
|
+
self.headers: Callable = lambda token: {
|
|
79
|
+
"Accept": "application/json",
|
|
80
|
+
"Authorization": f"Bearer {generate_bearer_token(token)}",
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
def request(
|
|
84
|
+
self,
|
|
85
|
+
method: str,
|
|
86
|
+
endpoint: EndpointMapping,
|
|
87
|
+
params: Dict[str, Any] | None = None,
|
|
88
|
+
json: Dict[str, Any] | None = None,
|
|
89
|
+
) -> Any:
|
|
90
|
+
"""Intercepts all HTTP requests and applies centralized error handling.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
method: HTTP method to make a request.
|
|
94
|
+
endpoint: Endpoint to make a request.
|
|
95
|
+
params: Query parameters to pass to the request.
|
|
96
|
+
json: JSON data to pass to the request.
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
Any:
|
|
100
|
+
Response data from the server.
|
|
101
|
+
"""
|
|
102
|
+
url = urljoin(self.server, endpoint)
|
|
103
|
+
if method in ("GET", "POST"):
|
|
104
|
+
headers = self.headers(token=self.apikey)
|
|
105
|
+
else:
|
|
106
|
+
headers = self.headers(token=f"{self.apikey}.{self.secret}")
|
|
42
107
|
try:
|
|
43
|
-
response =
|
|
108
|
+
response = requests.request(
|
|
109
|
+
method=method, url=url, headers=headers, params=params, json=json
|
|
110
|
+
)
|
|
44
111
|
response.raise_for_status()
|
|
45
112
|
return process_response(response)
|
|
46
113
|
except requests.exceptions.RequestException as error:
|
|
47
114
|
_request_error(error)
|
|
48
115
|
|
|
49
|
-
def get(
|
|
116
|
+
def get(
|
|
117
|
+
self,
|
|
118
|
+
endpoint: EndpointMapping,
|
|
119
|
+
params: Dict[str, Any] | None = None,
|
|
120
|
+
json: Dict[str, Any] | None = None,
|
|
121
|
+
) -> Any:
|
|
50
122
|
"""Make GET request to the server and process the response."""
|
|
51
|
-
return self.request("GET",
|
|
52
|
-
|
|
53
|
-
def put(
|
|
123
|
+
return self.request("GET", endpoint, params=params, json=json)
|
|
124
|
+
|
|
125
|
+
def put(
|
|
126
|
+
self,
|
|
127
|
+
endpoint: EndpointMapping,
|
|
128
|
+
params: Dict[str, Any] | None = None,
|
|
129
|
+
json: Dict[str, Any] | None = None,
|
|
130
|
+
) -> Any:
|
|
54
131
|
"""Make PUT request to the server and process the response."""
|
|
55
|
-
return self.request("PUT",
|
|
56
|
-
|
|
57
|
-
def post(
|
|
132
|
+
return self.request("PUT", endpoint, params=params, json=json)
|
|
133
|
+
|
|
134
|
+
def post(
|
|
135
|
+
self,
|
|
136
|
+
endpoint: EndpointMapping,
|
|
137
|
+
params: Dict[str, Any] | None = None,
|
|
138
|
+
json: Dict[str, Any] | None = None,
|
|
139
|
+
) -> Any:
|
|
58
140
|
"""Make POST request to the server and process the response."""
|
|
59
|
-
return self.request("POST",
|
|
60
|
-
|
|
61
|
-
def
|
|
141
|
+
return self.request("POST", endpoint, params=params, json=json)
|
|
142
|
+
|
|
143
|
+
def patch(
|
|
144
|
+
self,
|
|
145
|
+
endpoint: EndpointMapping,
|
|
146
|
+
params: Dict[str, Any] | None = None,
|
|
147
|
+
json: Dict[str, Any] | None = None,
|
|
148
|
+
) -> Any:
|
|
149
|
+
"""Make PATCH request to the server and process the response."""
|
|
150
|
+
return self.request("PATCH", endpoint, params=params, json=json)
|
|
151
|
+
|
|
152
|
+
def delete(
|
|
153
|
+
self,
|
|
154
|
+
endpoint: EndpointMapping,
|
|
155
|
+
params: Dict[str, Any] | None = None,
|
|
156
|
+
json: Dict[str, Any] | None = None,
|
|
157
|
+
) -> Any:
|
|
62
158
|
"""Make DELETE request to the server and process the response."""
|
|
63
|
-
return self.request("DELETE",
|
|
159
|
+
return self.request("DELETE", endpoint, params=params, json=json)
|
vaultapi_client/util.py
CHANGED
|
@@ -1,8 +1,19 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def normalize(segment: Any) -> str:
|
|
6
|
+
"""Normalize the URL."""
|
|
7
|
+
if isinstance(segment, Enum):
|
|
8
|
+
segment = segment.value
|
|
9
|
+
return str(segment).strip("/")
|
|
10
|
+
|
|
11
|
+
|
|
1
12
|
def urljoin(*args) -> str:
|
|
2
|
-
"""Joins given arguments into a url.
|
|
13
|
+
"""Joins given arguments into a url.
|
|
3
14
|
|
|
4
15
|
Returns:
|
|
5
16
|
str:
|
|
6
17
|
Joined url.
|
|
7
18
|
"""
|
|
8
|
-
return "/".join(map(lambda x:
|
|
19
|
+
return "/".join(map(lambda x: normalize(x), args))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: VaultAPI-Client
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Client application for VaultAPI Server
|
|
5
5
|
Author-email: Vignesh Rao <svignesh1793@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -100,6 +100,8 @@ vaultapi --table mytable
|
|
|
100
100
|
- **APIKEY** - API Key for authentication.
|
|
101
101
|
- **SECRET** - Secret key used for transit encryption.
|
|
102
102
|
- **VAULT_SERVER** - VaultAPI server URL.
|
|
103
|
+
- **TRANSIT_KEY_LENGTH** - AES key length used for transit encryption. Defaults to `32`
|
|
104
|
+
- **TRANSIT_TIME_BUCKET** - Interval for which the transit epoch will remain constant. Defaults to `60`
|
|
103
105
|
|
|
104
106
|
## Coding Standards
|
|
105
107
|
Docstring format: [`Google`][google-docs] <br>
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
vaultapi_client/__init__.py,sha256=EpHR8g5-TpGoV-6fo_5PEy43sJaKdy8wMrCl_F0hrsQ,1308
|
|
2
|
+
vaultapi_client/aws.py,sha256=1y-hSg76K5oc1wqbOBVuGhVZV3Ckt2ttTEdL5O0i4yo,2694
|
|
3
|
+
vaultapi_client/config.py,sha256=Z8dGcxk5FKuQj0HpAe8Wq_bwEcuT8TamrXdrbNadFVg,5456
|
|
4
|
+
vaultapi_client/exceptions.py,sha256=hpZxtnSa1SHNDaTJwYdwXFuUkzi2ZdB23apKrKOOUzk,602
|
|
5
|
+
vaultapi_client/main.py,sha256=6joJFNJRFNM1Te2ixzGdzB9iGbrgonIvYZeAUQ60ncc,6956
|
|
6
|
+
vaultapi_client/session.py,sha256=rh2aazo-8gjFIIiSohaZdmiUiZpjWxMQZqCVxl09uqo,5287
|
|
7
|
+
vaultapi_client/transit.py,sha256=ZH4OF-TO50zQfcCy6e1f202QWYaBPk9bzZ2bWhSPQxo,3114
|
|
8
|
+
vaultapi_client/util.py,sha256=qMD1Hpu3_GmwxNJ8AM-k5yu-QlN--qes00LT--Q5kkQ,393
|
|
9
|
+
vaultapi_client-0.3.0.dist-info/licenses/LICENSE,sha256=_sOIKJWdD2o1WwwDIwYB2qTP2nlSWqT5Tyg9jr1Xa4w,1070
|
|
10
|
+
vaultapi_client-0.3.0.dist-info/METADATA,sha256=t7T2o9UBD37po-Sa6UArzhY1Tt5X4_nJadSdocFTsOw,5911
|
|
11
|
+
vaultapi_client-0.3.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
12
|
+
vaultapi_client-0.3.0.dist-info/entry_points.txt,sha256=P3CaBVJ9RvRJy7xvd9A4o3HYEfoM4wStZcQ8L6837NE,64
|
|
13
|
+
vaultapi_client-0.3.0.dist-info/top_level.txt,sha256=J0qf2Tuj66RGC_VTF9f3Ce137qPqL8n0V21-1xwp1nw,16
|
|
14
|
+
vaultapi_client-0.3.0.dist-info/RECORD,,
|
|
@@ -1,14 +0,0 @@
|
|
|
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,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|