text
stringlengths
18
773k
def load_csvf(fpath, fieldnames, encoding): """ :param unicode fpath: :param Optional[list[unicode]] fieldnames: :param unicode encoding: :rtype: List[dict] """ with open(fpath, mode='r', encoding=encoding) as f: snippet = f.read(8192) f.seek(0) dialect = csv.Sniffer...
def dump_csv(data: List[dict], fieldnames: Sequence[str], with_header: bool = False, crlf: bool = False, tsv: bool = False) -> str: """ :param data: :param fieldnames: :param with_header: :param crlf: :param tsv: :return: unicode """ def force_str(v): # XXX: Dou...
def save_csvf(data: list, fieldnames: Sequence[str], fpath: str, encoding: str, with_header: bool = False, crlf: bool = False, tsv: bool = False) -> str: """ :param data: :param fieldnames: :param fpath: write path :param encoding: encoding :param with_header: :param crlf: ...
def dump_json(data, indent=None): """ :param list | dict data: :param Optional[int] indent: :rtype: unicode """ return json.dumps(data, indent=indent, ensure_ascii=False, sort_keys=True, separators=(',', ': '...
def save_jsonf(data: Union[list, dict], fpath: str, encoding: str, indent=None) -> str: """ :param data: list | dict data :param fpath: write path :param encoding: encoding :param indent: :rtype: written path """ with codecs.open(fpath, mode='w', encoding=encoding) as f: f.write(...
def dump_yaml(data): """ :param list | dict data: :rtype: unicode """ return yaml.dump(data, indent=2, encoding=None, allow_unicode=True, default_flow_style=False, Dumper=MyDumper)
def save_yamlf(data: Union[list, dict], fpath: str, encoding: str) -> str: """ :param data: list | dict data :param fpath: write path :param encoding: encoding :rtype: written path """ with codecs.open(fpath, mode='w', encoding=encoding) as f: f.write(dump_yaml(data)) return ...
def dump_table(data: List[dict], fieldnames: Sequence[str]) -> str: """ :param data: :param fieldnames: :return: Table string """ def min3(num: int) -> int: return 3 if num < 4 else num width_by_col: Dict[str, int] = { f: min3(max([string_width(str(d.get(f))) for d in data]...
def string_width(word: str) -> int: """ :param word: :return: Widths of word Usage: >>> string_width('abc') 3 >>> string_width('Abしー') 7 >>> string_width('') 0 """ return sum(map(lambda x: 2 if east_asian_width(x) in 'FWA' else 1, word))
def writeXMLFile(filename, content): """ Used only for debugging to write out intermediate files""" xmlfile = open(filename, 'w') # pretty print content = etree.tostring(content, pretty_print=True) xmlfile.write(content) xmlfile.close()
def transform(odtfile, debug=False, parsable=False, outputdir=None): """ Given an ODT file this returns a tuple containing the cnxml, a dictionary of filename -> data, and a list of errors """ # Store mapping of images extracted from the ODT file (and their bits) images = {} # Log of Errors and ...
def from_value(cls, value: str) -> T: """Create instance from symbol :param value: unique symbol :return: This instance Usage: >>> from owlmixin.samples import Animal >>> Animal.from_value('cat').crow() mewing """ return [x for x in c...
def auto_thaw(vault_client, opt): """Will thaw into a temporary location""" icefile = opt.thaw_from if not os.path.exists(icefile): raise aomi.exceptions.IceFile("%s missing" % icefile) thaw(vault_client, icefile, opt) return opt
def seed(vault_client, opt): """Will provision vault based on the definition within a Secretfile""" if opt.thaw_from: opt.secrets = tempfile.mkdtemp('aomi-thaw') auto_thaw(vault_client, opt) Context.load(get_secretfile(opt), opt) \ .fetch(vault_client) \ .sync(vault_cl...
def render(directory, opt): """Render any provided template. This includes the Secretfile, Vault policies, and inline AWS roles""" if not os.path.exists(directory) and not os.path.isdir(directory): os.mkdir(directory) a_secretfile = render_secretfile(opt) s_path = "%s/Secretfile" % director...
def export(vault_client, opt): """Export contents of a Secretfile from the Vault server into a specified directory.""" ctx = Context.load(get_secretfile(opt), opt) \ .fetch(vault_client) for resource in ctx.resources(): resource.export(opt.directory)
def maybe_colored(msg, color, opt): """Maybe it will render in color maybe it will not!""" if opt.monochrome: return msg return colored(msg, color)
def normalize_val(val): """Normalize JSON/YAML derived values as they pertain to Vault resources and comparison operations """ if is_unicode(val) and val.isdigit(): return int(val) elif isinstance(val, list): return ','.join(val) elif val is None: return '' return val
def details_dict(obj, existing, ignore_missing, opt): """Output the changes, if any, for a dict""" existing = dict_unicodeize(existing) obj = dict_unicodeize(obj) for ex_k, ex_v in iteritems(existing): new_value = normalize_val(obj.get(ex_k)) og_value = normalize_val(ex_v) if ex_...
def maybe_details(resource, opt): """At the first level of verbosity this will print out detailed change information on for the specified Vault resource""" if opt.verbose == 0: return if not resource.present: return obj = None existing = None if isinstance(resource, Resour...
def diff_a_thing(thing, opt): """Handle the diff action for a single thing. It may be a Vault backend implementation or it may be a Vault data resource""" changed = thing.diff() if changed == ADD: print("%s %s" % (maybe_colored("+", "green", opt), str(thing))) elif changed == DEL: pr...
def diff(vault_client, opt): """Derive a comparison between what is represented in the Secretfile and what is actually live on a Vault instance""" if opt.thaw_from: opt.secrets = tempfile.mkdtemp('aomi-thaw') auto_thaw(vault_client, opt) ctx = Context.load(get_secretfile(opt), opt) \ ...
def help_me(parser, opt): """Handle display of help and whatever diagnostics""" print("aomi v%s" % version) print('Get started with aomi' ' https://autodesk.github.io/aomi/quickstart') if opt.verbose == 2: tf_str = 'Token File,' if token_file() else '' app_str = 'AppID File,' i...
def extract_file_args(subparsers): """Add the command line options for the extract_file operation""" extract_parser = subparsers.add_parser('extract_file', help='Extract a single secret from' 'Vault to a local file') extra...
def mapping_args(parser): """Add various variable mapping command line options to the parser""" parser.add_argument('--add-prefix', dest='add_prefix', help='Specify a prefix to use when ' 'generating secret key names') parser.add_argume...
def aws_env_args(subparsers): """Add command line options for the aws_environment operation""" 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 environment_args(subparsers): """Add command line options for the environment operation""" env_parser = subparsers.add_parser('environment') env_parser.add_argument('vault_paths', help='Full path(s) to secret', nargs='+') env_parser.add_argumen...
def template_args(subparsers): """Add command line options for the template operation""" template_parser = subparsers.add_parser('template') template_parser.add_argument('template', help='Template source', nargs='?') template_parser.add_a...
def secretfile_args(parser): """Add Secretfile management command line arguments to parser""" parser.add_argument('--secrets', dest='secrets', help='Path where secrets are stored', default=os.path.join(os.getcwd(), ".secrets")) parser.a...
def base_args(parser): """Add the generic command line options""" generic_args(parser) parser.add_argument('--monochrome', dest='monochrome', help='Whether or not to use colors', action='store_true') parser.add_argument('--metadata'...
def export_args(subparsers): """Add command line options for the export operation""" 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...
def render_args(subparsers): """Add command line options for the render operation""" render_parser = subparsers.add_parser('render') render_parser.add_argument('directory', help='Path where Secrefile and accoutrement' ' will be rendered into') ...
def diff_args(subparsers): """Add command line options for the diff operation""" diff_parser = subparsers.add_parser('diff') secretfile_args(diff_parser) vars_args(diff_parser) base_args(diff_parser) thaw_from_args(diff_parser)
def seed_args(subparsers): """Add command line options for the seed operation""" seed_parser = subparsers.add_parser('seed') secretfile_args(seed_parser) vars_args(seed_parser) seed_parser.add_argument('--mount-only', dest='mount_only', help=...
def thaw_from_args(parser): """Adds command line options for things related to inline thawing of icefiles""" parser.add_argument('--thaw-from', dest='thaw_from', help='Thaw an ICE file containing secrets') parser.add_argument('--gpg-password-path', ...
def thaw_args(subparsers): """Add command line options for the thaw operation""" 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_...
def freeze_args(subparsers): """Add command line options for the freeze operation""" freeze_parser = subparsers.add_parser('freeze') freeze_parser.add_argument('--icefile-prefix', dest='icefile_prefix', help='Prefix of icefilename') secretfil...
def password_args(subparsers): """Add command line options for the set_password operation""" password_parser = subparsers.add_parser('set_password') password_parser.add_argument('vault_path', help='Path which contains password' 'secret to be ...
def vars_args(parser): """Add various command line options for external vars""" parser.add_argument('--extra-vars', dest='extra_vars', help='Extra template variables', default=[], type=str, ac...
def parser_factory(fake_args=None): """Return a proper contextual OptionParser""" parser = ArgumentParser(description='aomi') subparsers = parser.add_subparsers(dest='operation', help='Specify the data ' ' or extraction operation'...
def template_runner(client, parser, args): """Executes template related operations""" 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...
def ux_actions(parser, args): """Handle some human triggers actions""" # 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') a...
def do_thaw(client, args): """Execute the thaw operation, pulling in an actual Vault client if neccesary""" 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 action_runner(parser, args): """Run appropriate action, or throw help""" 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) s...
def main(): """Entrypoint, sweet Entrypoint""" 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: disa...
def grok_ttl(secret): """Parses the TTL information""" 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 tt...
def my_version(): """Return the version, checking both packaged and development locations""" 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 abspath(raw): """Return what is hopefully a OS independent path.""" 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 hard_path(path, prefix_dir): """Returns an absolute path to either the relative or absolute file.""" 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....
def is_tagged(required_tags, has_tags): """Checks if tags match""" 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_t...
def cli_hash(list_of_kv): """Parse out a hash from a list of key=value strings""" 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 merge_dicts(dict_a, dict_b): """Deep merge of two dicts""" 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 i...
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.""" LOG.debug("Reading password from TTY") new_password = getpass('Enter Password: ', stream=sys.stderr) if not new_password: raise aomi.exceptions....
def path_pieces(vault_path): """Will return a two part tuple comprising of the vault path and the key with in the stored object""" 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 mount_for_path(path, client): """Returns the mountpoint for this path""" 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: ...
def backend_type(path, client): """Returns the type of backend at the given mountpoint""" backends = client.list_secret_backends()['data'] vault_path = "%s/" % path return backends[vault_path]['type']
def load_word_file(filename): """Loads a words file as a list of lines""" words_file = resource_filename(__name__, "words/%s" % filename) handle = open(words_file, 'r') words = handle.readlines() handle.close() return words
def choose_one(things): """Returns a random entry from a list of things""" choice = SystemRandom().randint(0, len(things) - 1) return things[choice].strip()
def subdir_path(directory, relative): """Returns a file path relative to another path.""" 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: ...
def open_maybe_binary(filename): """Opens something that might be binary but also might be "plain text".""" if sys.version_info >= (3, 0): data = open(filename, 'rb').read() try: return data.decode('utf-8') except UnicodeDecodeError: return data return op...
def ensure_dir(path): """Ensures a directory exists""" if not (os.path.exists(path) and os.path.isdir(path)): os.mkdir(path)
def clean_tmpdir(path): """Invoked atexit, this removes our tmpdir""" if os.path.exists(path) and \ os.path.isdir(path): rmtree(path)
def dict_unicodeize(some_dict): """Ensure that every string in a dict is properly represented by unicode strings""" # 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...
def diff_dict(dict1, dict2, ignore_missing=False): """Performs a base type comparison between two dicts""" 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))):...
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""" if not src_key: src_key = key if src_key in src: dest[key] = src[src_key] else: if default is not None: ...
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.""" ctx = Context(context.opt) for resource in context.resources(): if resource.child:...
def ensure_backend(resource, backend, backends, opt, managed=True): """Ensure the backend for a resource is properly in context""" existing_mount = find_backend(resource.mount, backends) if not existing_mount: new_mount = backend(resource, opt, managed=managed) backends.append(new_mount) ...
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""" for mod in mods: if mod[0] != config: continue if len(mod) == 2: return mod[1] if len(mod) == 3 and...
def py_resources(): """Discovers all aomi Vault resource models. This includes anything extending aomi.model.Mount or aomi.model.Resource.""" aomi_mods = [m for m, _v in iteritems(sys.modules) if m.startswith('aomi.model')] mod_list = [] mod_map = [] for amod in...
def load(config, opt): """Loads and returns a full context object based on the Secretfile""" 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: ...
def thaw(self, tmp_dir): """Will thaw every secret into an appropriate temporary location""" for resource in self.resources(): if resource.present: resource.thaw(tmp_dir)
def freeze(self, dest_dir): """Freezes every resource within a context""" for resource in self.resources(): if resource.present: resource.freeze(dest_dir)
def resources(self): """Vault resources within context""" res = [] for resource in self._resources: res = res + resource.resources() return res
def add(self, resource): """Add a resource to the context""" if isinstance(resource, Resource): if isinstance(resource, Secret) and \ resource.mount != 'cubbyhole': ensure_backend(resource, SecretBackend, ...
def remove(self, resource): """Removes a resource from the context""" if isinstance(resource, Resource): self._resources.remove(resource)
def sync_policies(self, vault_client): """Synchronizes policies only""" 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...
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""" for auth in self.auths(): auth.sync(vault_client) auth_re...
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 mou...
def sync_mounts(self, active_mounts, resources, vault_client): """Synchronizes mount points. Removes things before adding new.""" # Create a resource set that is only explicit mounts # and sort so removals are first mounts = [x for x in resources if isinstance(x...
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.""" active_mounts = [] for audit_log in self.logs(): audit_log.sync(vault_client) ...
def prune(self, vault_client): """Will remove any mount point which is not actually defined in this context. """ existing = getattr(vault_client, SecretBackend.list_fun)()['data'].items() for mount_name, _values in existing: # ignore system paths an...
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.""" backends = [(self.mounts, SecretBackend), ...
def presets(self, presets, opt): """Will create representational objects for any preset (push) based AppRole Secrets.""" for preset in presets: secret_obj = dict(preset) secret_obj['role_name'] = self.app_name self.secret_ids.append(AppRoleSecret(secret_obj, o...
def secret_key_name(path, key, opt): """Renders a Secret key name appropriately""" 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.ad...
def grok_template_file(src): """Determine the real deal template file""" if not src.startswith('builtin:'): return abspath(src) builtin = src.split(':')[1] builtin = "templates/%s.j2" % builtin return resource_filename(__name__, builtin)
def blend_vars(secrets, opt): """Blends secret and static variables together""" 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.co...
def template(client, src, dest, paths, opt): """Writes a template using variables from a vault path""" 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) ...
def write_raw_file(secret, dest): """Writes an actual secret out to a file""" 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 = ope...
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.""" path, key = path_pieces(src) resp = client.read(path) if not resp: client.revoke_self_token() raise aomi.excep...
def env(client, paths, opt): """Renders a shell snippet based on paths in a Secretfile""" 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.warni...
def aws(client, path, opt): """Renders a shell environment snippet with AWS information""" 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: ...
def generated_key(key): """Create the proper generated key value""" 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 r...
def generate_obj(self): """Generates the secret object, respecting existing information and user specified options""" secret_obj = {} if self.existing: secret_obj = deepcopy(self.existing) for key in self.keys: key_name = key['name'] if self.e...
def unhandled(exception, opt): """ Handle uncaught/unexpected errors and be polite about it""" 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 Validatio...
def output(message, opt, extra=None): """ Politely display an unexpected error""" print(message, file=sys.stderr) if opt.verbose: if extra: print(extra) traceback.print_exc(sys.stderr)
def grok_seconds(lease): """Ensures that we are returning just seconds""" 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 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""" if opt.reuse_token: return seconds = grok_seconds(opt.lease) if not seconds: raise aomi.exceptions.AomiCommand("invalid lease %s" %...
def approle_token(vault_client, role_id, secret_id): """Returns a vault token based on the role and seret id""" 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.AomiC...
def app_token(vault_client, app_id, user_id): """Returns a vault token based on the app and user id.""" 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('...
def token_meta(opt): """Generates metadata for a token""" 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(',...