2016-05-27 16:08:40 +00:00
|
|
|
import argparse
|
|
|
|
|
|
|
|
from dateutil.parser import parse as parse_date
|
|
|
|
|
2016-04-14 20:14:23 +00:00
|
|
|
from app import app
|
|
|
|
from data import model
|
|
|
|
from data.database import ServiceKeyApprovalType
|
2019-01-08 19:03:28 +00:00
|
|
|
from data.logs_model import logs_model
|
2016-04-14 20:14:23 +00:00
|
|
|
|
|
|
|
|
2016-04-29 14:14:50 +00:00
|
|
|
def generate_key(service, name, expiration_date=None, notes=None):
|
2016-04-14 20:14:23 +00:00
|
|
|
metadata = {
|
|
|
|
'created_by': 'CLI tool',
|
|
|
|
}
|
|
|
|
|
|
|
|
# Generate a key with a private key that we *never save*.
|
|
|
|
(private_key, key) = model.service_keys.generate_service_key(service, expiration_date,
|
|
|
|
metadata=metadata,
|
|
|
|
name=name)
|
|
|
|
# Auto-approve the service key.
|
2018-08-13 15:40:50 +00:00
|
|
|
model.service_keys.approve_service_key(key.kid, ServiceKeyApprovalType.AUTOMATIC, notes=notes or '')
|
2016-04-14 20:14:23 +00:00
|
|
|
|
|
|
|
# Log the creation and auto-approval of the service key.
|
|
|
|
key_log_metadata = {
|
|
|
|
'kid': key.kid,
|
|
|
|
'preshared': True,
|
|
|
|
'service': service,
|
|
|
|
'name': name,
|
|
|
|
'expiration_date': expiration_date,
|
|
|
|
'auto_approved': True,
|
|
|
|
}
|
|
|
|
|
2019-01-08 19:03:28 +00:00
|
|
|
logs_model.log_action('service_key_create', metadata=key_log_metadata)
|
|
|
|
logs_model.log_action('service_key_approve', metadata=key_log_metadata)
|
2016-04-27 19:37:48 +00:00
|
|
|
return private_key, key.kid
|
2016-04-14 20:14:23 +00:00
|
|
|
|
|
|
|
|
2016-05-27 16:08:40 +00:00
|
|
|
def valid_date(s):
|
|
|
|
try:
|
|
|
|
return parse_date(s)
|
|
|
|
except ValueError:
|
|
|
|
msg = "Not a valid date: '{0}'.".format(s)
|
|
|
|
raise argparse.ArgumentTypeError(msg)
|
|
|
|
|
|
|
|
|
2016-04-14 20:14:23 +00:00
|
|
|
if __name__ == '__main__':
|
|
|
|
parser = argparse.ArgumentParser(description='Generates a preshared key')
|
|
|
|
parser.add_argument('service', help='The service name for which the key is being generated')
|
|
|
|
parser.add_argument('name', help='The friendly name for the key')
|
2016-05-27 16:08:40 +00:00
|
|
|
parser.add_argument('--expiration', default=None, type=valid_date,
|
|
|
|
help='The optional expiration date for the key')
|
2016-04-14 20:14:23 +00:00
|
|
|
parser.add_argument('--notes', help='Optional notes about the key', default=None)
|
|
|
|
|
|
|
|
args = parser.parse_args()
|
2016-04-29 20:21:19 +00:00
|
|
|
generated, _ = generate_key(args.service, args.name, args.expiration, args.notes)
|
2016-04-14 20:14:23 +00:00
|
|
|
print generated.exportKey('PEM')
|