code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
extract_parser = subparsers.add_parser('extract_file',
help='Extract a single secret from'
'Vault to a local file')
extract_parser.add_argument('vault_path',
help='Full path (including key)... | def extract_file_args(subparsers) | Add the command line options for the extract_file operation | 4.272552 | 4.152361 | 1.028945 |
parser.add_argument('--add-prefix',
dest='add_prefix',
help='Specify a prefix to use when '
'generating secret key names')
parser.add_argument('--add-suffix',
dest='add_suffix',
help='Spe... | def mapping_args(parser) | Add various variable mapping command line options to the parser | 2.247946 | 2.203188 | 1.020315 |
env_parser = subparsers.add_parser('aws_environment')
env_parser.add_argument('vault_path',
help='Full path(s) to the AWS secret')
export_arg(env_parser)
base_args(env_parser) | def aws_env_args(subparsers) | Add command line options for the aws_environment operation | 5.475689 | 4.864695 | 1.125598 |
env_parser = subparsers.add_parser('environment')
env_parser.add_argument('vault_paths',
help='Full path(s) to secret',
nargs='+')
env_parser.add_argument('--prefix',
dest='prefix',
help='Old... | def environment_args(subparsers) | Add command line options for the environment operation | 5.11306 | 5.131509 | 0.996405 |
template_parser = subparsers.add_parser('template')
template_parser.add_argument('template',
help='Template source',
nargs='?')
template_parser.add_argument('destination',
help='Path to write rendered tem... | def template_args(subparsers) | Add command line options for the template operation | 3.037946 | 3.019657 | 1.006057 |
parser.add_argument('--secrets',
dest='secrets',
help='Path where secrets are stored',
default=os.path.join(os.getcwd(), ".secrets"))
parser.add_argument('--policies',
dest='policies',
he... | def secretfile_args(parser) | Add Secretfile management command line arguments to parser | 2.118712 | 2.059909 | 1.028546 |
generic_args(parser)
parser.add_argument('--monochrome',
dest='monochrome',
help='Whether or not to use colors',
action='store_true')
parser.add_argument('--metadata',
dest='metadata',
... | def base_args(parser) | Add the generic command line options | 4.023732 | 3.927159 | 1.024591 |
export_parser = subparsers.add_parser('export')
export_parser.add_argument('directory',
help='Path where secrets will be exported into')
secretfile_args(export_parser)
vars_args(export_parser)
base_args(export_parser) | def export_args(subparsers) | Add command line options for the export operation | 4.452876 | 4.352821 | 1.022986 |
render_parser = subparsers.add_parser('render')
render_parser.add_argument('directory',
help='Path where Secrefile and accoutrement'
' will be rendered into')
secretfile_args(render_parser)
vars_args(render_parser)
base_args(render_p... | def render_args(subparsers) | Add command line options for the render operation | 8.263625 | 8.172526 | 1.011147 |
diff_parser = subparsers.add_parser('diff')
secretfile_args(diff_parser)
vars_args(diff_parser)
base_args(diff_parser)
thaw_from_args(diff_parser) | def diff_args(subparsers) | Add command line options for the diff operation | 4.412574 | 4.408192 | 1.000994 |
seed_parser = subparsers.add_parser('seed')
secretfile_args(seed_parser)
vars_args(seed_parser)
seed_parser.add_argument('--mount-only',
dest='mount_only',
help='Only mount paths if needed',
default=False,
... | def seed_args(subparsers) | Add command line options for the seed operation | 3.95225 | 3.86978 | 1.021311 |
parser.add_argument('--thaw-from',
dest='thaw_from',
help='Thaw an ICE file containing secrets')
parser.add_argument('--gpg-password-path',
dest='gpg_pass_path',
help='Vault path of GPG passphrase location') | def thaw_from_args(parser) | Adds command line options for things related to inline thawing
of icefiles | 6.297376 | 5.422499 | 1.161342 |
thaw_parser = subparsers.add_parser('thaw')
thaw_parser.add_argument('--gpg-password-path',
dest='gpg_pass_path',
help='Vault path of GPG passphrase location')
thaw_parser.add_argument('--ignore-missing',
dest='ignor... | def thaw_args(subparsers) | Add command line options for the thaw operation | 4.033374 | 3.98892 | 1.011144 |
freeze_parser = subparsers.add_parser('freeze')
freeze_parser.add_argument('--icefile-prefix',
dest='icefile_prefix',
help='Prefix of icefilename')
secretfile_args(freeze_parser)
archive_args(freeze_parser)
vars_args(freeze_parser)
... | def freeze_args(subparsers) | Add command line options for the freeze operation | 4.295143 | 4.112853 | 1.044322 |
password_parser = subparsers.add_parser('set_password')
password_parser.add_argument('vault_path',
help='Path which contains password'
'secret to be udpated')
base_args(password_parser) | def password_args(subparsers) | Add command line options for the set_password operation | 6.320311 | 5.70582 | 1.107695 |
parser.add_argument('--extra-vars',
dest='extra_vars',
help='Extra template variables',
default=[],
type=str,
action='append')
parser.add_argument('--extra-vars-file',
... | def vars_args(parser) | Add various command line options for external vars | 2.6822 | 2.503111 | 1.071546 |
parser = ArgumentParser(description='aomi')
subparsers = parser.add_subparsers(dest='operation',
help='Specify the data '
' or extraction operation')
extract_file_args(subparsers)
environment_args(subparsers)
aws_env_... | def parser_factory(fake_args=None) | Return a proper contextual OptionParser | 3.723784 | 3.716953 | 1.001838 |
if args.builtin_list:
aomi.template.builtin_list()
elif args.builtin_info:
aomi.template.builtin_info(args.builtin_info)
elif args.template and args.destination and args.vault_paths:
aomi.render.template(client, args.template,
args.destination,
... | def template_runner(client, parser, args) | Executes template related operations | 3.962394 | 4.07438 | 0.972514 |
# cryptorito uses native logging (as aomi should tbh)
normal_fmt = '%(message)s'
if hasattr(args, 'verbose') and args.verbose and args.verbose >= 2:
logging.basicConfig(level=logging.DEBUG)
elif hasattr(args, 'verbose') and args.verbose >= 1:
logging.basicConfig(level=logging.INFO, ... | def ux_actions(parser, args) | Handle some human triggers actions | 4.649235 | 4.553594 | 1.021003 |
vault_client = None
if args.gpg_pass_path:
vault_client = client.connect(args)
aomi.filez.thaw(vault_client, args.icefile, args)
sys.exit(0) | def do_thaw(client, args) | Execute the thaw operation, pulling in an actual Vault
client if neccesary | 12.200193 | 11.035253 | 1.105565 |
ux_actions(parser, args)
client = aomi.vault.Client(args)
if args.operation == 'extract_file':
aomi.render.raw_file(client.connect(args),
args.vault_path, args.destination, args)
sys.exit(0)
elif args.operation == 'environment':
aomi.render.env... | def action_runner(parser, args) | Run appropriate action, or throw help | 2.775225 | 2.768833 | 1.002309 |
parser, args = parser_factory()
try:
action_runner(parser, args)
# this is our uncaught handler so yes we want to actually
# catch every error. the format may vary based on the error handler tho
except Exception as uncaught: # pylint: disable=broad-except
unhandled(uncaught, a... | def main() | Entrypoint, sweet Entrypoint | 13.493668 | 13.082532 | 1.031426 |
ttl_obj = {}
lease_msg = ''
if 'lease' in secret:
ttl_obj['lease'] = secret['lease']
lease_msg = "lease:%s" % (ttl_obj['lease'])
if 'lease_max' in secret:
ttl_obj['lease_max'] = secret['lease_max']
elif 'lease' in ttl_obj:
ttl_obj['lease_max'] = ttl_obj['lease']... | def grok_ttl(secret) | Parses the TTL information | 2.459351 | 2.367415 | 1.038834 |
if os.path.exists(resource_filename(__name__, 'version')):
return resource_string(__name__, 'version')
return open(os.path.join(os.path.dirname(__file__),
"..", "version")).read() | def my_version() | Return the version, checking both packaged and development locations | 3.444813 | 3.073906 | 1.120663 |
path_bits = []
if raw.find('/') != -1:
path_bits = raw.split('/')
elif raw.find('\\') != -1:
path_bits = raw.split('\\')
else:
path_bits = [raw]
return os.path.abspath(os.sep.join(path_bits)) | def abspath(raw) | Return what is hopefully a OS independent path. | 2.114073 | 2.02875 | 1.042057 |
relative = abspath("%s/%s" % (prefix_dir, path))
a_path = abspath(path)
if os.path.exists(relative):
LOG.debug("using relative path %s (%s)", relative, path)
return relative
LOG.debug("using absolute path %s", a_path)
return a_path | def hard_path(path, prefix_dir) | Returns an absolute path to either the relative or absolute file. | 3.180455 | 2.836138 | 1.121404 |
if not required_tags and not has_tags:
return True
elif not required_tags:
return False
found_tags = []
for tag in required_tags:
if tag in has_tags:
found_tags.append(tag)
return len(found_tags) == len(required_tags) | def is_tagged(required_tags, has_tags) | Checks if tags match | 1.830929 | 1.818755 | 1.006694 |
ev_obj = {}
for extra_var in list_of_kv:
ev_list = extra_var.split('=')
key = ev_list[0]
val = '='.join(ev_list[1:]) # b64 and other side effects
ev_obj[key] = val
return ev_obj | def cli_hash(list_of_kv) | Parse out a hash from a list of key=value strings | 4.860461 | 4.407046 | 1.102884 |
obj = {}
for key, value in iteritems(dict_a):
if key in dict_b:
if isinstance(dict_b[key], dict):
obj[key] = merge_dicts(value, dict_b.pop(key))
else:
obj[key] = value
for key, value in iteritems(dict_b):
obj[key] = value
return obj | def merge_dicts(dict_a, dict_b) | Deep merge of two dicts | 1.962991 | 1.917518 | 1.023714 |
LOG.debug("Reading password from TTY")
new_password = getpass('Enter Password: ', stream=sys.stderr)
if not new_password:
raise aomi.exceptions.AomiCommand("Must specify a password")
if not confirm:
return new_password
confirm_password = getpass('Again, Please: ', stream=sys.s... | def get_tty_password(confirm) | When returning a password from a TTY we assume a user
is entering it on a keyboard so we ask for confirmation. | 3.873181 | 3.740331 | 1.035518 |
path_bits = vault_path.split('/')
path = '/'.join(path_bits[0:len(path_bits) - 1])
key = path_bits[len(path_bits) - 1]
return path, key | def path_pieces(vault_path) | Will return a two part tuple comprising of the vault path
and the key with in the stored object | 2.306699 | 2.208912 | 1.04427 |
backend_data = client.list_secret_backends()['data']
backends = [mnt for mnt in backend_data.keys()]
path_bits = path.split('/')
if len(path_bits) == 1:
vault_path = "%s/" % path
if vault_path in backends:
return vault_path[0:len(vault_path) - 1]
else:
for i ... | def mount_for_path(path, client) | Returns the mountpoint for this path | 2.762312 | 2.696652 | 1.024349 |
backends = client.list_secret_backends()['data']
vault_path = "%s/" % path
return backends[vault_path]['type'] | def backend_type(path, client) | Returns the type of backend at the given mountpoint | 9.90077 | 8.263684 | 1.198106 |
words_file = resource_filename(__name__, "words/%s" % filename)
handle = open(words_file, 'r')
words = handle.readlines()
handle.close()
return words | def load_word_file(filename) | Loads a words file as a list of lines | 3.022005 | 2.773707 | 1.089518 |
choice = SystemRandom().randint(0, len(things) - 1)
return things[choice].strip() | def choose_one(things) | Returns a random entry from a list of things | 5.880004 | 5.357541 | 1.097519 |
item_bits = directory.split(os.sep)
relative_bits = relative.split(os.sep)
for i, _item in enumerate(item_bits):
if i == len(relative_bits) - 1:
return os.sep.join(item_bits[i:])
else:
if item_bits[i] != relative_bits[i]:
return None
return N... | def subdir_path(directory, relative) | Returns a file path relative to another path. | 2.510325 | 2.42117 | 1.036823 |
if sys.version_info >= (3, 0):
data = open(filename, 'rb').read()
try:
return data.decode('utf-8')
except UnicodeDecodeError:
return data
return open(filename, 'r').read() | def open_maybe_binary(filename) | Opens something that might be binary but also
might be "plain text". | 2.117374 | 2.268998 | 0.933176 |
if not (os.path.exists(path) and
os.path.isdir(path)):
os.mkdir(path) | def ensure_dir(path) | Ensures a directory exists | 3.09566 | 3.151799 | 0.982188 |
if os.path.exists(path) and \
os.path.isdir(path):
rmtree(path) | def clean_tmpdir(path) | Invoked atexit, this removes our tmpdir | 3.300645 | 3.280771 | 1.006058 |
# some python 2/3 compat
if isinstance(some_dict, ("".__class__, u"".__class__)):
if sys.version_info >= (3, 0):
return some_dict
return some_dict.decode('utf-8')
elif isinstance(some_dict, collections.Mapping):
return dict(map(dict_unicodeize, iteritems(some_dict)... | def dict_unicodeize(some_dict) | Ensure that every string in a dict is properly represented
by unicode strings | 2.203057 | 2.266633 | 0.971951 |
unidict1 = dict_unicodeize(dict1)
unidict2 = dict_unicodeize(dict2)
if ((not ignore_missing) and (len(unidict1) != len(unidict2))) or \
(ignore_missing and (len(unidict1) >= len(unidict2))):
return True
for comp_k, comp_v in iteritems(unidict1):
if comp_k not in unidict2:
... | def diff_dict(dict1, dict2, ignore_missing=False) | Performs a base type comparison between two dicts | 2.492561 | 2.434156 | 1.023994 |
if not src_key:
src_key = key
if src_key in src:
dest[key] = src[src_key]
else:
if default is not None:
dest[key] = default | def map_val(dest, src, key, default=None, src_key=None) | Will ensure a dict has values sourced from either
another dict or based on the provided default | 1.968521 | 2.275609 | 0.865052 |
ctx = Context(context.opt)
for resource in context.resources():
if resource.child:
continue
if resource.filtered():
ctx.add(resource)
return ctx | def filtered_context(context) | Filters a context
This will return a new context with only the resources that
are actually available for use. Uses tags and command line
options to make determination. | 9.34339 | 7.524619 | 1.241709 |
existing_mount = find_backend(resource.mount, backends)
if not existing_mount:
new_mount = backend(resource, opt, managed=managed)
backends.append(new_mount)
return new_mount
return existing_mount | def ensure_backend(resource, backend, backends, opt, managed=True) | Ensure the backend for a resource is properly in context | 3.347768 | 3.592891 | 0.931775 |
for mod in mods:
if mod[0] != config:
continue
if len(mod) == 2:
return mod[1]
if len(mod) == 3 and mod[1] in obj:
return mod[2]
return None | def find_model(config, obj, mods) | Given a list of mods (as returned by py_resources) attempts to
determine if a given Python obj fits one of the models | 2.552189 | 3.23235 | 0.789577 |
aomi_mods = [m for
m, _v in iteritems(sys.modules)
if m.startswith('aomi.model')]
mod_list = []
mod_map = []
for amod in [sys.modules[m] for m in aomi_mods]:
for _mod_bit, model in inspect.getmembers(amod):
if str(model) in mod_list:
... | def py_resources() | Discovers all aomi Vault resource models. This includes
anything extending aomi.model.Mount or aomi.model.Resource. | 3.81869 | 3.202981 | 1.19223 |
ctx = Context(opt)
seed_map = py_resources()
seed_keys = sorted(set([m[0] for m in seed_map]), key=resource_sort)
for config_key in seed_keys:
if config_key not in config:
continue
for resource_config in config[config_key]:
... | def load(config, opt) | Loads and returns a full context object based on the Secretfile | 5.184659 | 4.74353 | 1.092996 |
for resource in self.resources():
if resource.present:
resource.thaw(tmp_dir) | def thaw(self, tmp_dir) | Will thaw every secret into an appropriate temporary location | 6.731864 | 6.080348 | 1.107151 |
for resource in self.resources():
if resource.present:
resource.freeze(dest_dir) | def freeze(self, dest_dir) | Freezes every resource within a context | 7.133508 | 5.774625 | 1.23532 |
res = []
for resource in self._resources:
res = res + resource.resources()
return res | def resources(self) | Vault resources within context | 6.239805 | 5.176743 | 1.205353 |
if isinstance(resource, Resource):
if isinstance(resource, Secret) and \
resource.mount != 'cubbyhole':
ensure_backend(resource,
SecretBackend,
self._mounts,
self.opt,... | def add(self, resource) | Add a resource to the context | 4.444305 | 4.262938 | 1.042545 |
if isinstance(resource, Resource):
self._resources.remove(resource) | def remove(self, resource) | Removes a resource from the context | 4.789267 | 4.293495 | 1.11547 |
p_resources = [x for x in self.resources()
if isinstance(x, Policy)]
for resource in p_resources:
resource.sync(vault_client)
return [x for x in self.resources()
if not isinstance(x, Policy)] | def sync_policies(self, vault_client) | Synchronizes policies only | 3.750377 | 3.599478 | 1.041922 |
for auth in self.auths():
auth.sync(vault_client)
auth_resources = [x for x in resources
if isinstance(x, (LDAP, UserPass))]
for resource in auth_resources:
resource.sync(vault_client)
return [x for x in resources
... | def sync_auth(self, vault_client, resources) | Synchronizes auth mount wrappers. These happen
early in the cycle, to ensure that user backends
are proper. They may also be used to set mount
tuning | 3.914399 | 3.953135 | 0.990201 |
a_mounts = list(active_mounts)
if isinstance(resource, Secret) and resource.mount == 'cubbyhole':
return a_mounts
active_mount = find_backend(resource.mount, active_mounts)
if not active_mount:
actual_mount = find_backend(resource.mount, self._mounts)
... | def actually_mount(self, vault_client, resource, active_mounts) | Handle the actual (potential) mounting of a secret backend.
This is called in multiple contexts, but the action will always
be the same. If we were not aware of the mountpoint at the start
and it has not already been mounted, then mount it. | 3.916003 | 3.929483 | 0.996569 |
# Create a resource set that is only explicit mounts
# and sort so removals are first
mounts = [x for x in resources
if isinstance(x, (Mount, AWS))]
s_resources = sorted(mounts, key=absent_sort)
# Iterate over explicit mounts only
for resource ... | def sync_mounts(self, active_mounts, resources, vault_client) | Synchronizes mount points. Removes things before
adding new. | 6.020277 | 5.958125 | 1.010431 |
active_mounts = []
for audit_log in self.logs():
audit_log.sync(vault_client)
# Handle policies only on the first pass. This allows us
# to ensure that ACL's are in place prior to actually
# making any changes.
not_policies = self.sync_policies(vault... | def sync(self, vault_client, opt) | Synchronizes the context to the Vault server. This
has the effect of updating every resource which is
in the context and has changes pending. | 7.784199 | 7.542075 | 1.032103 |
existing = getattr(vault_client,
SecretBackend.list_fun)()['data'].items()
for mount_name, _values in existing:
# ignore system paths and cubbyhole
mount_path = normalize_vault_path(mount_name)
if mount_path.startswith('sys') or mou... | def prune(self, vault_client) | Will remove any mount point which is not actually defined
in this context. | 6.050207 | 5.498406 | 1.100357 |
backends = [(self.mounts, SecretBackend),
(self.auths, AuthBackend),
(self.logs, LogBackend)]
for b_list, b_class in backends:
backend_list = b_list()
if backend_list:
existing = getattr(vault_client, b_class.list_f... | def fetch(self, vault_client) | Updates the context based on the contents of the Vault
server. Note that some resources can not be read after
they have been written to and it is up to those classes
to handle that case properly. | 3.58993 | 3.447724 | 1.041247 |
for preset in presets:
secret_obj = dict(preset)
secret_obj['role_name'] = self.app_name
self.secret_ids.append(AppRoleSecret(secret_obj, opt)) | def presets(self, presets, opt) | Will create representational objects for any preset (push)
based AppRole Secrets. | 7.176586 | 4.601561 | 1.559598 |
value = key
if opt.merge_path:
norm_path = [x for x in path.split('/') if x]
value = "%s_%s" % ('_'.join(norm_path), key)
if opt.add_prefix:
value = "%s%s" % (opt.add_prefix, value)
if opt.add_suffix:
value = "%s%s" % (value, opt.add_suffix)
return value | def secret_key_name(path, key, opt) | Renders a Secret key name appropriately | 2.788691 | 2.709329 | 1.029292 |
if not src.startswith('builtin:'):
return abspath(src)
builtin = src.split(':')[1]
builtin = "templates/%s.j2" % builtin
return resource_filename(__name__, builtin) | def grok_template_file(src) | Determine the real deal template file | 5.915883 | 5.799932 | 1.019992 |
base_obj = load_vars(opt)
merged = merge_dicts(base_obj, secrets)
template_obj = dict((k, v) for k, v in iteritems(merged) if v)
# give templates something to iterate over
template_obj['aomi_items'] = template_obj.copy()
return template_obj | def blend_vars(secrets, opt) | Blends secret and static variables together | 6.901248 | 7.271295 | 0.949109 |
key_map = cli_hash(opt.key_map)
obj = {}
for path in paths:
response = client.read(path)
if not response:
raise aomi.exceptions.VaultData("Unable to retrieve %s" % path)
if is_aws(response['data']) and 'sts' not in path:
renew_secret(client, response, opt... | def template(client, src, dest, paths, opt) | Writes a template using variables from a vault path | 5.744488 | 5.568955 | 1.03152 |
secret_file = None
secret_filename = abspath(dest)
if sys.version_info >= (3, 0):
if not isinstance(secret, str):
secret_file = open(secret_filename, 'wb')
if not secret_file:
secret_file = open(secret_filename, 'w')
secret_file.write(secret)
secret_file.close(... | def write_raw_file(secret, dest) | Writes an actual secret out to a file | 2.3449 | 2.274024 | 1.031167 |
path, key = path_pieces(src)
resp = client.read(path)
if not resp:
client.revoke_self_token()
raise aomi.exceptions.VaultData("Unable to retrieve %s" % path)
else:
if 'data' in resp and key in resp['data']:
secret = resp['data'][key]
if is_base64(secr... | def raw_file(client, src, dest, opt) | Write the contents of a vault path/key to a file. Is
smart enough to attempt and handle binary files that are
base64 encoded. | 5.108692 | 4.851904 | 1.052925 |
old_prefix = False
old_prefix = opt.prefix and not (opt.add_prefix or
opt.add_suffix or
not opt.merge_path)
if old_prefix:
LOG.warning("the prefix option is deprecated "
"please use"
... | def env(client, paths, opt) | Renders a shell snippet based on paths in a Secretfile | 4.271206 | 4.182788 | 1.021139 |
try:
creds = client.read(path)
except (hvac.exceptions.InternalServerError) as vault_exception:
# this is how old vault behaves
if vault_exception.errors[0].find('unsupported path') > 0:
emsg = "Invalid AWS path. Did you forget the" \
" credential typ... | def aws(client, path, opt) | Renders a shell environment snippet with AWS information | 3.405773 | 3.417586 | 0.996543 |
key_name = key['name']
if key['method'] == 'uuid':
LOG.debug("Setting %s to a uuid", key_name)
return str(uuid4())
elif key['method'] == 'words':
LOG.debug("Setting %s to random words", key_name)
return random_word()
elif key['method'] == 'static':
if 'value'... | def generated_key(key) | Create the proper generated key value | 3.471036 | 3.382545 | 1.026161 |
secret_obj = {}
if self.existing:
secret_obj = deepcopy(self.existing)
for key in self.keys:
key_name = key['name']
if self.existing and \
key_name in self.existing and \
not key.get('overwrite'):
LOG.deb... | def generate_obj(self) | Generates the secret object, respecting existing information
and user specified options | 3.94223 | 3.361779 | 1.172662 |
exmod = type(exception).__module__
name = "%s.%s" % (exmod, type(exception).__name__)
# this is a Vault error
if exmod == 'aomi.exceptions' or exmod == 'cryptorito':
# This may be set for Validation or similar errors
if hasattr(exception, 'source'):
output(exception.mess... | def unhandled(exception, opt) | Handle uncaught/unexpected errors and be polite about it | 7.129563 | 7.096832 | 1.004612 |
print(message, file=sys.stderr)
if opt.verbose:
if extra:
print(extra)
traceback.print_exc(sys.stderr) | def output(message, opt, extra=None) | Politely display an unexpected error | 3.866221 | 3.564884 | 1.084529 |
if lease.endswith('s'):
return int(lease[0:-1])
elif lease.endswith('m'):
return int(lease[0:-1]) * 60
elif lease.endswith('h'):
return int(lease[0:-1]) * 3600
return None | def grok_seconds(lease) | Ensures that we are returning just seconds | 1.881396 | 1.754703 | 1.072202 |
if opt.reuse_token:
return
seconds = grok_seconds(opt.lease)
if not seconds:
raise aomi.exceptions.AomiCommand("invalid lease %s" % opt.lease)
renew = None
if client.version:
v_bits = client.version.split('.')
if int(v_bits[0]) == 0 and \
int(v_bits[... | def renew_secret(client, creds, opt) | Renews a secret. This will occur unless the user has
specified on the command line that it is not neccesary | 5.891335 | 5.908633 | 0.997072 |
resp = vault_client.auth_approle(role_id, secret_id)
if 'auth' in resp and 'client_token' in resp['auth']:
return resp['auth']['client_token']
else:
raise aomi.exceptions.AomiCredentials('invalid approle') | def approle_token(vault_client, role_id, secret_id) | Returns a vault token based on the role and seret id | 4.142991 | 4.110346 | 1.007942 |
resp = vault_client.auth_app_id(app_id, user_id)
if 'auth' in resp and 'client_token' in resp['auth']:
return resp['auth']['client_token']
else:
raise aomi.exceptions.AomiCredentials('invalid apptoken') | def app_token(vault_client, app_id, user_id) | Returns a vault token based on the app and user id. | 4.648375 | 4.496217 | 1.033841 |
meta = {
'via': 'aomi',
'operation': opt.operation,
'hostname': socket.gethostname()
}
if 'USER' in os.environ:
meta['unix_user'] = os.environ['USER']
if opt.metadata:
meta_bits = opt.metadata.split(',')
for meta_bit in meta_bits:
key, va... | def token_meta(opt) | Generates metadata for a token | 3.600725 | 3.706626 | 0.971429 |
m_norm = normalize_vault_path(path)
for mount_name, values in backends.items():
b_norm = normalize_vault_path(mount_name)
if (m_norm == b_norm) and values['type'] == backend:
return values
return None | def get_backend(backend, path, backends) | Returns mountpoint details for a backend | 5.061504 | 4.657517 | 1.086739 |
# pylint: disable=missing-docstring
def wrap_call(func):
# pylint: disable=missing-docstring
def func_wrapper(self, vault_client):
try:
return func(self, vault_client)
except (hvac.exceptions.InvalidRequest,
hvac.exceptions.Forbidd... | def wrap_hvac(msg) | Error catching Vault API wrapper
This decorator wraps API interactions with Vault. It will
catch and return appropriate error output on common
problems. Do we even need this now that we extend the
hvac class? | 4.081456 | 3.688424 | 1.106558 |
health_url = "%s/v1/sys/health" % self.vault_addr
resp = self.session.request('get', health_url, **self._kwargs)
if resp.status_code == 200 or resp.status_code == 429:
blob = resp.json()
if 'version' in blob:
return blob['version']
else:
... | def server_version(self) | Attempts to determine the version of Vault that a
server is running. Some actions will change on older
Vault deployments. | 4.798605 | 4.197073 | 1.143322 |
if not self._kwargs['verify']:
LOG.warning('Skipping SSL Validation!')
self.version = self.server_version()
self.token = self.init_token()
my_token = self.lookup_token()
if not my_token or 'data' not in my_token:
raise aomi.exceptions.AomiCredent... | def connect(self, opt) | This sets up the tokens we expect to see in a way
that hvac also expects. | 4.516992 | 4.329843 | 1.043223 |
app_filename = appid_file()
token_filename = token_file()
approle_filename = approle_file()
token = None
if 'VAULT_ROLE_ID' in os.environ and \
'VAULT_SECRET_ID' in os.environ and \
os.environ['VAULT_ROLE_ID'] and os.environ['VAULT_SECRET_ID']:
... | def init_token(self) | Generate our first token based on workstation configuration | 2.166542 | 2.133099 | 1.015678 |
args = {
'lease': opt.lease,
'display_name': display_name,
'meta': token_meta(opt)
}
try:
token = self.create_token(**args)
except (hvac.exceptions.InvalidRequest,
hvac.exceptions.Forbidden) as vault_exception:
... | def op_token(self, display_name, opt) | Return a properly annotated token for our use. This
token will be revoked at the end of the session. The token
will have some decent amounts of metadata tho. | 5.383381 | 5.098348 | 1.055907 |
path = sanitize_mount(path)
if path.startswith('cubbyhole'):
self.token = self.initial_token
val = super(Client, self).read(path, wrap_ttl)
self.token = self.operational_token
return val
return super(Client, self).read(path, wrap_ttl) | def read(self, path, wrap_ttl=None) | Wrap the hvac read call, using the right token for
cubbyhole interactions. | 5.515667 | 3.937471 | 1.400815 |
path = sanitize_mount(path)
val = None
if path.startswith('cubbyhole'):
self.token = self.initial_token
val = super(Client, self).write(path, wrap_ttl=wrap_ttl, **kwargs)
self.token = self.operational_token
else:
super(Client, self... | def write(self, path, wrap_ttl=None, **kwargs) | Wrap the hvac write call, using the right token for
cubbyhole interactions. | 4.26769 | 3.265841 | 1.306766 |
path = sanitize_mount(path)
val = None
if path.startswith('cubbyhole'):
self.token = self.initial_token
val = super(Client, self).delete(path)
self.token = self.operational_token
else:
super(Client, self).delete(path)
retu... | def delete(self, path) | Wrap the hvac delete call, using the right token for
cubbyhole interactions. | 6.027903 | 4.375585 | 1.377622 |
public_key = key_from_keybase(username)
fingerprint = public_key['fingerprint'][-8:].upper().encode('ascii')
key = public_key['bundle'].encode('ascii')
if not has_gpg_key(fingerprint):
LOG.debug("Importing gpg key for %s", username)
if not import_gpg_key(key):
raise aomi... | def from_keybase(username) | Will attempt to retrieve a GPG public key from
Keybase, importing if neccesary | 5.853936 | 5.581808 | 1.048753 |
key_ids = []
for key in config['pgp_keys']:
if key.startswith('keybase:'):
key_id = from_keybase(key[8:])
LOG.debug("Encrypting for keybase user %s", key[8:])
else:
if not has_gpg_key(key):
raise aomi.exceptions.GPG("Do not actually have k... | def grok_keys(config) | Will retrieve a GPG key from either Keybase or GPG directly | 4.907144 | 4.12631 | 1.189233 |
zip_filename = "%s/aomi-blah.zip" % tmp_dir
archive = zipfile.ZipFile(zip_filename, 'w')
for root, _dirnames, filenames in os.walk(dest_prefix):
for filename in filenames:
relative_path = subdir_path(root, dest_prefix).split(os.sep)[1:]
relative_path = os.sep.join(relati... | def freeze_archive(tmp_dir, dest_prefix) | Generates a ZIP file of secrets | 2.664567 | 2.645624 | 1.00716 |
pgp_keys = grok_keys(config)
icefile_prefix = "aomi-%s" % \
os.path.basename(os.path.dirname(opt.secretfile))
if opt.icefile_prefix:
icefile_prefix = opt.icefile_prefix
timestamp = time.strftime("%H%M%S-%m-%d-%Y",
datetime.datetime.now().t... | def freeze_encrypt(dest_dir, zip_filename, config, opt) | Encrypts the zip file | 4.845659 | 4.914597 | 0.985973 |
tmp_dir = ensure_tmpdir()
dest_prefix = "%s/dest" % tmp_dir
ensure_dir(dest_dir)
ensure_dir(dest_prefix)
config = get_secretfile(opt)
Context.load(config, opt) \
.freeze(dest_prefix)
zip_filename = freeze_archive(tmp_dir, dest_prefix)
ice_file = freeze_encrypt(dest_dir, z... | def freeze(dest_dir, opt) | Iterates over the Secretfile looking for secrets to freeze | 6.22454 | 5.782474 | 1.076449 |
if not os.path.isdir(opt.secrets):
LOG.info("Creating secret directory %s", opt.secrets)
os.mkdir(opt.secrets)
zip_file = "%s/aomi.zip" % tmp_dir
if opt.gpg_pass_path:
gpg_path_bits = opt.gpg_pass_path.split('/')
gpg_path = '/'.join(gpg_path_bits[0:len(gpg_path_bits) ... | def thaw_decrypt(vault_client, src_file, tmp_dir, opt) | Decrypts the encrypted ice file | 2.748559 | 2.782323 | 0.987865 |
if not os.path.exists(src_file):
raise aomi.exceptions.AomiFile("%s does not exist" % src_file)
tmp_dir = ensure_tmpdir()
zip_file = thaw_decrypt(vault_client, src_file, tmp_dir, opt)
archive = zipfile.ZipFile(zip_file, 'r')
for archive_file in archive.namelist():
archive.extra... | def thaw(vault_client, src_file, opt) | Given the combination of a Secretfile and the output of
a freeze operation, will restore secrets to usable locations | 3.872128 | 3.837741 | 1.00896 |
if not self.present:
if self.existing:
return DEL
return NOOP
is_diff = NOOP
if self.present and self.existing:
a_obj = self.config.copy()
if self.config and diff_dict(a_obj, self.existing, True):
is_diff... | def diff(self) | Determines if changes are needed for the Vault backend | 4.787996 | 4.629011 | 1.034345 |
if self.present:
if not self.existing:
LOG.info("Mounting %s backend on %s",
self.backend, self.path)
self.actually_mount(vault_client)
else:
LOG.info("%s backend already mounted on %s",
... | def sync(self, vault_client) | Synchronizes the local and remote Vault resources. Has the net
effect of adding backend if needed | 2.48223 | 2.457732 | 1.009968 |
if not self.config:
return
a_prefix = self.tune_prefix
if self.tune_prefix:
a_prefix = "%s/" % self.tune_prefix
v_path = "sys/mounts/%s%s/tune" % (a_prefix, self.path)
a_obj = self.config.copy()
if 'description' in a_obj:
del... | def sync_tunables(self, vault_client) | Synchtonizes any tunables we have set | 4.473488 | 4.425883 | 1.010756 |
if not is_mounted(self.backend, self.path, backends) or \
self.tune_prefix is None:
return
backend_details = get_backend(self.backend, self.path, backends)
self.existing = backend_details['config']
if backend_details['description']:
self.exist... | def fetch(self, vault_client, backends) | Updates local resource with context on whether this
backend is actually mounted and available | 3.865945 | 3.79124 | 1.019704 |
getattr(client, self.unmount_fun)(mount_point=self.path) | def unmount(self, client) | Unmounts a backend within Vault | 11.275233 | 15.08169 | 0.747611 |
a_obj = self.config.copy()
if 'description' in a_obj:
del a_obj['description']
try:
m_fun = getattr(client, self.mount_fun)
if self.description and a_obj:
m_fun(self.backend,
mount_point=self.path,
... | def actually_mount(self, client) | Actually mount something in Vault | 3.035984 | 2.96951 | 1.022386 |
for sfile in self.secrets():
src_file = "%s/%s" % (tmp_dir, sfile)
err_msg = "%s secret missing from icefile" % (self)
if not os.path.exists(src_file):
if hasattr(self.opt, 'ignore_missing') and \
self.opt.ignore_missing:
... | def thaw(self, tmp_dir) | Will perform some validation and copy a
decrypted secret to it's final location | 3.210599 | 3.092292 | 1.038259 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.