-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
service_account_keys_rest_handler.py
397 lines (299 loc) · 15.5 KB
/
service_account_keys_rest_handler.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import logging
import sys
import os
import re
import json
import base64
from splunk.clilib.bundle_paths import make_splunkhome_path
from splunk import ResourceNotFound
import splunk.entity as entity
from splunk.rest import simpleRequest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from google_drive_app import rest_handler
from google_drive_app.six.moves.urllib.parse import quote_plus
from google_drive_app.six import binary_type
from google_drive_app import SERVICE_KEY_REALM, SERVICE_KEY_USERNAME
path_to_mod_input_lib = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modular_input.zip')
sys.path.insert(0, path_to_mod_input_lib)
from modular_input.secure_password import get_secure_password, get_secure_password_stanza
def setup_logger(level):
"""
Setup a logger for the REST handler
"""
logger = logging.getLogger('splunk.appserver.service_account_keys_rest_handler.rest_handler')
logger.propagate = False # Prevent the log messages from being duplicated in the python.log file
logger.setLevel(level)
log_file_path = make_splunkhome_path(['var', 'log', 'splunk', 'service_account_keys_rest_handler.log'])
file_handler = logging.handlers.RotatingFileHandler(log_file_path, maxBytes=25000000,
backupCount=5)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
logger = setup_logger(logging.DEBUG)
class ServiceAccountKeysRestHandler(rest_handler.RESTHandler):
DEFAULT_NAMESPACE ="google_drive"
DEFAULT_OWNER = "nobody"
def __init__(self, command_line, command_arg):
super(ServiceAccountKeysRestHandler, self).__init__(command_line, command_arg, logger)
def is_file_name_valid(self, lookup_file):
"""
Indicate if the lookup file is valid (doesn't contain invalid characters such as "..").
"""
allowed_path = re.compile("^[-A-Z0-9_ ]+([.][-A-Z0-9_ ]+)*$", re.IGNORECASE)
if not allowed_path.match(lookup_file):
return False
else:
return True
def setAppAsConfigured(self, session_key):
postargs = {
'output_mode': 'json',
'configured' : 'true'
}
response, _ = simpleRequest('/services/apps/local/google_drive', sessionKey=session_key, method='POST', postargs=postargs, raiseAllErrors=False)
if response.status == 200:
return True
else:
return False
def setKeyForDefaultInput(self, file_name, session_key):
entity_entry = self.getDefaultGoogleDriveInputEntity(session_key)
entity_entry['service_account_key_file'] = file_name
entity_entry.namespace = ServiceAccountKeysRestHandler.DEFAULT_NAMESPACE
entity_entry.owner = ServiceAccountKeysRestHandler.DEFAULT_OWNER
entity.setEntity(entity_entry, sessionKey=session_key)
self.setAppAsConfigured(session_key)
def getDefaultGoogleDriveInputEntity(self, session_key):
return entity.getEntity('admin/conf-inputs', 'google_spreadsheet', sessionKey=session_key)
def getKeyFileContents(self, session_key):
default_password_entry = self.getDefaultGoogleDriveInputEntity(session_key)
# Make sure the file name is specified in the default entry
if 'service_account_key_file' in default_password_entry:
file_name = default_password_entry['service_account_key_file']
service_key_file_path = make_splunkhome_path(['etc', 'apps', 'google_drive', 'service_account_keys', file_name])
service_key = None
with open(service_key_file_path, 'r') as fh:
service_key = fh.read()
return service_key
return None
def getInfoFromKeyFile(self, file_name):
service_key_file_path = make_splunkhome_path(['etc', 'apps', 'google_drive', 'service_account_keys', file_name])
service_key = None
try:
with open(service_key_file_path, 'r') as fh:
service_key = json.load(fh)
client_email = service_key.get('client_email', None)
private_key_id = service_key.get('private_key_id', None)
return client_email, private_key_id
except IOError:
# File could not be loaded
return None, None
return None, None
def refreshServiceAccountKey(self, session_key):
stanza = get_secure_password_stanza(SERVICE_KEY_USERNAME, SERVICE_KEY_REALM)
_, _ = simpleRequest('/services/storage/passwords/_reload' + quote_plus(stanza), sessionKey=session_key)
def removeServiceAccountKey(self, session_key):
stanza = get_secure_password_stanza(SERVICE_KEY_USERNAME, SERVICE_KEY_REALM)
self.logger.warn("About to delete service key, stanza=%s", stanza)
response, _ = simpleRequest('/servicesNS/nobody/search/storage/passwords/' + quote_plus(stanza), sessionKey=session_key, method='DELETE')
# Check response
if response.status == 200 or response.status == 201:
return True
else:
return False
def uploadServiceAccountKeyJSON(self, file_contents, session_key):
# Parse the output
service_account_email = None
private_key_id = None
try:
service_account_email, private_key_id = self.parseServiceAccountKey(file_contents, is_base64=True)
except ValueError as e:
return self.render_error_json(str(e))
# Determine if the key already exists
existing_key = self.retrieve_raw_key_info_from_secure_storage(session_key)
# Get secure password stanza
stanza = get_secure_password_stanza(SERVICE_KEY_USERNAME, SERVICE_KEY_REALM)
# Make up the argument array
if existing_key is None:
postargs = {
'name': SERVICE_KEY_USERNAME,
'password': file_contents,
'realm': SERVICE_KEY_REALM,
'output_mode': 'json',
}
else:
self.logger.info("Service key already exists; it wil be replaced with a new one")
postargs = {
'password': file_contents,
'output_mode': 'json',
}
try:
response, content = simpleRequest('/services/storage/passwords/' + quote_plus(stanza), postargs=postargs, sessionKey=session_key, method='POST')
# Check response
if response.status == 200 or response.status == 201:
# Return a response
return self.render_json({
'filename' : '',
'private_key_id' : private_key_id,
'service_account_email' : service_account_email
})
else:
self.logger.warn("Unable to save the key file, status=%i, response=%r", response.status, content)
return self.render_error_json("Unable to save the key file")
except:
return self.render_error_json("Unable to save the key file")
def migrateKeyToSecureStorage(self, session_key):
# Find out if we have a key on the file-system
service_account_email, _, _ = self.retrieve_key_info_from_file_system(session_key)
if service_account_email is None:
return False
# Find out if we have a key in secure storage
existing_key = self.retrieve_raw_key_info_from_secure_storage(session_key)
if existing_key is not None:
return False
# Read in the file
service_key = None
try:
service_key = self.getKeyFileContents(session_key)
except:
self.logger.error('Unable to load the key file for migration')
# Convert the string to bytes so that it can be encoded
if not isinstance(service_key, binary_type):
service_key = service_key.encode('utf-8')
# Base64 encode the key
service_key_encoded = base64.b64encode(service_key)
service_key_encoded = service_key_encoded.decode('utf-8')
# Convert the key over
response = self.uploadServiceAccountKeyJSON(service_key_encoded, session_key)
if response is not None:
if 'success' in response and not response.get('success', False):
self.logger.info('Unable to load the key file for migration: %s', response['message'])
return response
def parseServiceAccountKey(self, file_contents, is_base64=False):
# Decode the content from base64 if necessary
if is_base64:
file_contents = base64.b64decode(file_contents)
file_contents = file_contents.decode('utf-8')
# Try to parse the file
account_key = None
try:
account_key = json.loads(file_contents)
except:
self.logger.warn("Unable to parse service account key")
self.logger.warn(file_contents)
raise ValueError('Key could not be parsed')
# Verify that it includes the email
if 'client_email' not in account_key:
raise ValueError('Service account key is missing the client_email')
# Get the parameters to return
service_account_email = account_key['client_email']
private_key_id = account_key.get('private_key_id', None)
return service_account_email, private_key_id
def uploadServiceAccountKey(self, file_name, file_contents, session_key):
# Ensure that the file name is valid
if not self.is_file_name_valid(file_name):
return self.render_error_json("The service account key filename contains disallowed characters")
# Parse the key and make sure it is valid
service_account_email = None
private_key_id = None
try:
self.logger.warn(file_contents)
service_account_email, private_key_id = self.parseServiceAccountKey(file_contents, is_base64=True)
except ValueError as e:
return self.render_error_json(str(e))
# Create the service account keys directory if it does not yet exist
try:
os.mkdir(make_splunkhome_path(['etc', 'apps', 'google_drive', 'service_account_keys']))
except OSError as e:
if e.errno == 17:
pass # Path already exists, thats ok
else:
raise e
# Write out the file
service_key_file_path = make_splunkhome_path(['etc', 'apps', 'google_drive', 'service_account_keys', file_name])
with open(service_key_file_path, 'wb') as fh:
fh.write(file_contents)
# Set the input such that this key is used
self.setKeyForDefaultInput(file_name, session_key)
# Return the information
return self.render_json({
'filename' : file_name,
'private_key_id' : private_key_id,
'service_account_email' : service_account_email
})
def post_key_migrate(self, request_info, **kwargs):
# Migrate the key if necessary
migrated = self.migrateKeyToSecureStorage(request_info.session_key)
# Get the updated key information
response_json = self.get_key(request_info)
# Note whether we migrated the key
response_json['migrated'] = migrated
return response_json
def post_key(self, request_info, file_name=None, file_contents=None, **kwargs):
if file_contents is None or len(file_contents.strip()) == 0:
return self.render_error_json('The key file was not provided')
# Remove the mime-type prefix
try:
file_contents = file_contents.split(',')[1]
except IndexError:
return self.render_error_json('Unable to parse the file contents.')
# Upload via secure storage
return self.uploadServiceAccountKeyJSON(file_contents, request_info.session_key)
def retrieve_raw_key_info_from_secure_storage(self, session_key):
# Get the proxy password from secure storage (if it exists)
return get_secure_password(realm=SERVICE_KEY_REALM,
username=SERVICE_KEY_USERNAME,
session_key=session_key)
def retrieve_key_info_from_secure_storage(self, session_key):
# Get the key from secure storage (if it exists)
key_contents = self.retrieve_raw_key_info_from_secure_storage(session_key)
# Stop if we don't get anything
if key_contents is None:
return None, None
# If we found the key, parse it
try:
return self.parseServiceAccountKey(key_contents['content']['clear_password'], is_base64=True)
except:
self.logger.exception("Unable to parse the service account key")
return None, None
def retrieve_key_info_from_file_system(self, session_key):
# Get the existing service key
default_password_entry = self.getDefaultGoogleDriveInputEntity(session_key)
# Make sure the file name is specified in the default entry
if 'service_account_key_file' in default_password_entry:
file_name = default_password_entry['service_account_key_file']
service_account_email, private_key_id = self.getInfoFromKeyFile(file_name)
return service_account_email, private_key_id, file_name
return None, None, None
def post_remove_key(self, request_info, **kwargs):
try:
success = self.removeServiceAccountKey(request_info.session_key)
response = self.get_key(request_info)
if success:
self.logger.info("Removed service account key from secure storage")
response['message'] = 'existing key removed'
else:
self.logger.warn("Failed to remove service account key from secure storage")
response['message'] = 'existing key was not removed'
return response
except:
self.logger.exception("Exception generated when attempting to remove the old key")
return self.render_error_json("Exception generated when attempting to remove the old key")
def get_key(self, request_info, **kwargs):
try:
file_name = None
service_account_email = None
private_key_id = None
# Try getting the information from secure storage
service_account_email, private_key_id = self.retrieve_key_info_from_secure_storage(request_info.session_key)
# Try loading the key from the file-system otherwise
if service_account_email is None:
service_account_email, private_key_id, file_name = self.retrieve_key_info_from_file_system(request_info.session_key)
# Return the information
return self.render_json({
'filename' : file_name,
'service_account_email' : service_account_email,
'private_key_id' : private_key_id
})
except:
self.logger.exception("Exception generated when attempting to get the key")
return self.render_error_json("Exception generated when attempting to get the key")