This repository has been archived by the owner on Mar 20, 2023. It is now read-only.
/
keyvault.py
268 lines (252 loc) · 10.7 KB
/
keyvault.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# compat imports
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from builtins import ( # noqa
bytes, dict, int, list, object, range, str, ascii, chr, hex, input,
next, oct, open, pow, round, super, filter, map, zip)
# stdlib imports
import json
import logging
import zlib
# non-stdlib imports
import azure.common.credentials
import azure.keyvault
import ruamel.yaml
# local imports
from . import settings
from . import util
# create logger
logger = logging.getLogger(__name__)
util.setup_logger(logger)
# global defines
_SECRET_ENCODED_FORMAT_KEY = 'format'
_SECRET_ENCODED_FORMAT_VALUE = 'zlib+base64'
def _explode_secret_id(uri):
# type: (str) -> Tuple[str, str, str]
"""Explode Secret Id URI into parts
:param str uri: secret id uri
:rtype: tuple
:return: base url, secret name, version
"""
tmp = uri.split('/')
base_url = '/'.join(tmp[:3])
nparam = len(tmp[4:])
if nparam == 1:
return base_url, tmp[4], ''
elif nparam == 2:
return base_url, tmp[4], tmp[5]
else:
raise ValueError(
'cannot handle keyvault secret id uri: {}'.format(uri))
def fetch_credentials_conf(
client, keyvault_uri, keyvault_credentials_secret_id):
# type: (azure.keyvault.KeyVaultClient, str, str) -> dict
"""Fetch credentials conf from KeyVault
:param azure.keyvault.KeyVaultClient client: keyvault client
:param str keyvault_uri: keyvault uri
:param str keyvault_credentials_secret_id: secret id for creds conf
:rtype: dict
:return: credentials dict
"""
if client is None:
raise RuntimeError(
'KeyVault client not initialized, please ensure proper AAD '
'credentials and KeyVault parameters have been provided')
logger.debug('fetching credentials conf from keyvault')
if util.is_none_or_empty(keyvault_credentials_secret_id):
raise RuntimeError(
'cannot fetch credentials conf from keyvault without a valid '
'keyvault credentials secret id')
cred = client.get_secret(
*_explode_secret_id(keyvault_credentials_secret_id))
if util.is_none_or_empty(cred.value):
raise ValueError(
'credential conf from secret id {} is invalid'.format(
keyvault_credentials_secret_id))
# check for encoding and decode/decompress if necessary
if cred.tags is not None:
try:
if (cred.tags[_SECRET_ENCODED_FORMAT_KEY] ==
_SECRET_ENCODED_FORMAT_VALUE):
cred.value = util.decode_string(
zlib.decompress(util.base64_decode_string(cred.value)))
else:
raise RuntimeError(
'{} encoding format is invalid'.format(
cred.tags[_SECRET_ENCODED_FORMAT_KEY]))
except KeyError:
pass
return ruamel.yaml.load(cred.value, Loader=ruamel.yaml.RoundTripLoader)
def store_credentials_conf(client, config, keyvault_uri, secret_name):
# type: (azure.keyvault.KeyVaultClient, dict, str, str) -> None
"""Store credentials conf in KeyVault
:param azure.keyvault.KeyVaultClient client: keyvault client
:param dict config: configuration dict
:param str keyvault_uri: keyvault uri
:param str secret_name: secret name for creds conf
"""
if client is None:
raise RuntimeError(
'KeyVault client not initialized, please ensure proper AAD '
'credentials and KeyVault parameters have been provided')
creds = {
'credentials': settings.raw_credentials(config, True)
}
creds = json.dumps(creds).encode('utf8')
# first zlib compress and encode as base64
encoded = util.base64_encode_string(zlib.compress(creds))
# store secret
logger.debug('storing secret in keyvault {} with name {}'.format(
keyvault_uri, secret_name))
bundle = client.set_secret(
keyvault_uri, secret_name, encoded,
tags={_SECRET_ENCODED_FORMAT_KEY: _SECRET_ENCODED_FORMAT_VALUE}
)
logger.info('keyvault secret id for name {}: {}'.format(
secret_name,
azure.keyvault.KeyVaultId.parse_secret_id(bundle.id).base_id))
def delete_secret(client, keyvault_uri, secret_name):
# type: (azure.keyvault.KeyVaultClient, str, str) -> None
"""Delete secret from KeyVault
:param azure.keyvault.KeyVaultClient client: keyvault client
:param str keyvault_uri: keyvault uri
:param str secret_name: secret name for creds conf
"""
if client is None:
raise RuntimeError(
'KeyVault client not initialized, please ensure proper AAD '
'credentials and KeyVault parameters have been provided')
logger.info('deleting secret in keyvault {} with name {}'.format(
keyvault_uri, secret_name))
client.delete_secret(keyvault_uri, secret_name)
def list_secrets(client, keyvault_uri):
# type: (azure.keyvault.KeyVaultClient, str) -> None
"""List all secret ids and metadata from KeyVault
:param azure.keyvault.KeyVaultClient client: keyvault client
:param str keyvault_uri: keyvault uri
"""
if client is None:
raise RuntimeError(
'KeyVault client not initialized, please ensure proper AAD '
'credentials and KeyVault parameters have been provided')
logger.debug('listing secret ids in keyvault {}'.format(keyvault_uri))
secrets = client.get_secrets(keyvault_uri)
for secret in secrets:
logger.info('id={} enabled={} tags={} content_type={}'.format(
secret.id, secret.attributes.enabled, secret.tags,
secret.content_type))
def get_secret(client, secret_id, value_is_json=False):
# type: (azure.keyvault.KeyVaultClient, str, bool) -> str
"""Get secret from KeyVault
:param azure.keyvault.KeyVaultClient client: keyvault client
:param str secret_id: secret id to retrieve
:param bool value_is_json: expected value is json or yaml
:rtype: str
:return: secret value
"""
if client is None:
raise RuntimeError(
'cannot retrieve secret {} with invalid KeyVault client'.format(
secret_id))
value = client.get_secret(*_explode_secret_id(secret_id)).value
if value_is_json and util.is_not_empty(value):
return ruamel.yaml.load(value, Loader=ruamel.yaml.RoundTripLoader)
else:
return value
def parse_secret_ids(client, config):
# type: (azure.keyvault.KeyVaultClient, dict) -> None
"""Parse secret ids in credentials, fetch values from KeyVault, and add
appropriate values to config
:param azure.keyvault.KeyVaultClient client: keyvault client
:param dict config: configuration dict
"""
# batch account key
secid = settings.credentials_batch_account_key_secret_id(config)
if secid is not None:
logger.debug('fetching batch account key from keyvault')
bakey = get_secret(client, secid)
if util.is_none_or_empty(bakey):
raise ValueError(
'batch account key retrieved for secret id {} is '
'invalid'.format(secid))
settings.set_credentials_batch_account_key(config, bakey)
# storage account keys
for ssel in settings.iterate_storage_credentials(config):
secid = settings.credentials_storage_account_key_secret_id(
config, ssel)
if secid is None:
continue
logger.debug(
'fetching storage account key for link {} from keyvault'.format(
ssel))
sakey = get_secret(client, secid)
if util.is_none_or_empty(sakey):
raise ValueError(
'storage account key retrieved for secret id {} is '
'invalid'.format(secid))
settings.set_credentials_storage_account(config, ssel, sakey)
# docker registry passwords
for reg in settings.credentials_iterate_registry_servers(config, True):
secid = settings.credentials_registry_password_secret_id(
config, reg, True)
if secid is None:
continue
logger.debug(
('fetching Docker registry password for registry {} '
'from keyvault').format(reg))
password = get_secret(client, secid)
if util.is_none_or_empty(password):
raise ValueError(
'Docker registry password retrieved for secret id {} is '
'invalid'.format(secid))
settings.set_credentials_registry_password(config, reg, True, password)
# singularity registry passwords
for reg in settings.credentials_iterate_registry_servers(config, False):
secid = settings.credentials_registry_password_secret_id(
config, reg, False)
if secid is None:
continue
logger.debug(
('fetching Singularity registry password for registry {} '
'from keyvault').format(reg))
password = get_secret(client, secid)
if util.is_none_or_empty(password):
raise ValueError(
'Singularity registry password retrieved for secret id {} is '
'invalid'.format(secid))
settings.set_credentials_registry_password(
config, reg, False, password)
# monitioring passwords
secid = settings.credentials_grafana_admin_password_secret_id(config)
if secid is not None:
logger.debug('fetching Grafana admin password from keyvault')
password = get_secret(client, secid)
if util.is_none_or_empty(password):
raise ValueError(
'Grafana admin password retrieved for secret id {} is '
'invalid'.format(secid))
settings.set_credentials_grafana_admin_password(config, password)