text
stringlengths
18
773k
def get_backend(backend, path, backends): """Returns mountpoint details for a backend""" 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 ...
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?""" # pylint: disable=missing-docstring def wrap_call(func): ...
def server_version(self): """Attempts to determine the version of Vault that a server is running. Some actions will change on older Vault deployments.""" health_url = "%s/v1/sys/health" % self.vault_addr resp = self.session.request('get', health_url, **self._kwargs) if re...
def connect(self, opt): """This sets up the tokens we expect to see in a way that hvac also expects.""" if not self._kwargs['verify']: LOG.warning('Skipping SSL Validation!') self.version = self.server_version() self.token = self.init_token() my_token = self....
def init_token(self): """Generate our first token based on workstation configuration""" 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.envi...
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.""" args = { 'lease': opt.lease, 'display_name': display_name, ...
def read(self, path, wrap_ttl=None): """Wrap the hvac read call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).read(path, wrap_ttl) ...
def write(self, path, wrap_ttl=None, **kwargs): """Wrap the hvac write call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, se...
def delete(self, path): """Wrap the hvac delete call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).delete(path) ...
def from_keybase(username): """Will attempt to retrieve a GPG public key from Keybase, importing if neccesary""" 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)...
def grok_keys(config): """Will retrieve a GPG key from either Keybase or GPG directly""" 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...
def freeze_archive(tmp_dir, dest_prefix): """Generates a ZIP file of secrets""" 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...
def freeze_encrypt(dest_dir, zip_filename, config, opt): """Encrypts the zip file""" 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...
def freeze(dest_dir, opt): """Iterates over the Secretfile looking for secrets to freeze""" 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) zi...
def thaw_decrypt(vault_client, src_file, tmp_dir, opt): """Decrypts the encrypted ice file""" 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 =...
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""" if not os.path.exists(src_file): raise aomi.exceptions.AomiFile("%s does not exist" % src_file) tmp_dir = ensure_tmpdir() zip_fil...
def diff(self): """Determines if changes are needed for the Vault backend""" 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 se...
def sync(self, vault_client): """Synchronizes the local and remote Vault resources. Has the net effect of adding backend if needed""" if self.present: if not self.existing: LOG.info("Mounting %s backend on %s", self.backend, self.path) ...
def sync_tunables(self, vault_client): """Synchtonizes any tunables we have set""" 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) ...
def fetch(self, vault_client, backends): """Updates local resource with context on whether this backend is actually mounted and available""" if not is_mounted(self.backend, self.path, backends) or \ self.tune_prefix is None: return backend_details = get_backend(se...
def unmount(self, client): """Unmounts a backend within Vault""" getattr(client, self.unmount_fun)(mount_point=self.path)
def actually_mount(self, client): """Actually mount something in Vault""" 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(...
def thaw(self, tmp_dir): """Will perform some validation and copy a decrypted secret to it's final location""" 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...
def tunable(self, obj): """A tunable resource maps against a backend...""" self.tune = dict() if 'tune' in obj: for tunable in MOUNT_TUNABLES: tunable_key = tunable[0] map_val(self.tune, obj['tune'], tunable_key) if tunable_key in self....
def export_handle(self, directory): """Get a filehandle for exporting""" filename = getattr(self, 'filename') dest_file = "%s/%s" % (directory, filename) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.mkdir(dest_dir, 0o700) return op...
def export(self, directory): """Export exportable resources decoding as needed""" if not self.existing or not hasattr(self, 'filename'): return secret_h = self.export_handle(directory) obj = self.existing if isinstance(obj, str): secret_h.write(obj) ...
def freeze(self, tmp_dir): """Copies a secret into a particular location""" for sfile in self.secrets(): src_file = hard_path(sfile, self.opt.secrets) if not os.path.exists(src_file): raise aomi_excep.IceFile("%s secret not found at %s" % ...
def grok_state(self, obj): """Determine the desired state of this resource based on data present""" if 'state' in obj: my_state = obj['state'].lower() if my_state != 'absent' and my_state != 'present': raise aomi_excep \ .Validation('st...
def validate(self, obj): """Base validation method. Will inspect class attributes to dermine just what should be present""" if 'tags' in obj and not isinstance(obj['tags'], list): raise aomi_excep.Validation('tags must be a list') if self.present: check_obj(self....
def diff(self, obj=None): """Determine if something has changed or not""" if self.no_resource: return NOOP if not self.present: if self.existing: return DEL return NOOP if not obj: obj = self.obj() is_diff = NOOP...
def fetch(self, vault_client): """Populate internal representation of remote Vault resource contents""" result = self.read(vault_client) if result: if isinstance(result, dict) and 'data' in result: self.existing = result['data'] else: ...
def sync(self, vault_client): """Update remove Vault resource contents if needed""" if self.present and not self.existing: LOG.info("Writing new %s to %s", self.secret_format, self) self.write(vault_client) elif self.present and self.existing: ...
def filtered(self): """Determines whether or not resource is filtered. Resources may be filtered if the tags do not match or the user has specified explict paths to include or exclude via command line options""" if not is_tagged(self.tags, self.opt.tags): LOG.info("Sk...
def diff_write_only(resource): """A different implementation of diff that is used for those Vault resources that are write-only such as AWS root configs""" if resource.present and not resource.existing: return ADD elif not resource.present and resource.existing: ...
def read(self, client): """Read from Vault while handling non surprising errors.""" val = None if self.no_resource: return val LOG.debug("Reading from %s", self) try: val = client.read(self.path) except hvac.exceptions.InvalidRequest as vault_exce...
def write(self, client): """Write to Vault while handling non-surprising errors.""" val = None if not self.no_resource: val = client.write(self.path, **self.obj()) return val
def find_file(name, directory): """Searches up from a directory looking for a file""" path_bits = directory.split(os.sep) for i in range(0, len(path_bits) - 1): check_path = path_bits[0:len(path_bits) - i] check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name) if os.path.exi...
def in_file(string, search_file): """Looks in a file for a string.""" handle = open(search_file, 'r') for line in handle.readlines(): if string in line: return True return False
def gitignore(opt): """Will check directories upwards from the Secretfile in order to ensure the gitignore file is set properly""" directory = os.path.dirname(abspath(opt.secretfile)) gitignore_file = find_file('.gitignore', directory) if gitignore_file: secrets_path = subdir_path(abspath(op...
def secret_file(filename): """Will check the permissions of things which really should be secret files""" filestat = os.stat(abspath(filename)) if stat.S_ISREG(filestat.st_mode) == 0 and \ stat.S_ISLNK(filestat.st_mode) == 0: e_msg = "Secret file %s must be a real file or symlink" % filen...
def validate_obj(keys, obj): """Super simple "object" validation.""" msg = '' for k in keys: if isinstance(k, str): if k not in obj or (not isinstance(obj[k], list) and not obj[k]): if msg: msg = "%s," % msg msg = "%s%s" % (msg, k) ...
def specific_path_check(path, opt): """Will make checks against include/exclude to determine if we actually care about the path in question.""" if opt.exclude: if path in opt.exclude: return False if opt.include: if path not in opt.include: return False retu...
def check_obj(keys, name, obj): """Do basic validation on an object""" msg = validate_obj(keys, obj) if msg: raise aomi.exceptions.AomiData("object check : %s in %s" % (msg, name))
def sanitize_mount(mount): """Returns a quote-unquote sanitized mount path""" sanitized_mount = mount if sanitized_mount.startswith('/'): sanitized_mount = sanitized_mount[1:] if sanitized_mount.endswith('/'): sanitized_mount = sanitized_mount[:-1] sanitized_mount = sanitized_mount...
def gpg_fingerprint(key): """Validates a GPG key fingerprint This handles both pre and post GPG 2.1""" if (len(key) == 8 and re.match(r'^[0-9A-F]{8}$', key)) or \ (len(key) == 40 and re.match(r'^[0-9A-F]{40}$', key)): return raise aomi.exceptions.Validation('Invalid GPG Fingerprint')
def is_unicode_string(string): """Validates that we are some kinda unicode string""" try: if sys.version_info >= (3, 0): # isn't a python 3 str actually unicode if not isinstance(string, str): string.decode('utf-8') else: string.decode('utf-8'...
def is_unicode(string): """Validates that the object itself is some kinda string""" str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
def safe_modulo(s, meta, checked='', print_warning=True, stacklevel=2): """Safe version of the modulo operation (%) of strings Parameters ---------- s: str string to apply the modulo operation with meta: dict or tuple meta informations to insert (usually via ``s % meta``) checke...
def get_sections(self, s, base, sections=['Parameters', 'Other Parameters']): """ Method that extracts the specified sections out of the given string if (and only if) the docstring follows the numpy documentation guidelines [1]_. Note that the section either must app...
def get_sectionsf(self, *args, **kwargs): """ Decorator method to extract sections from a function docstring Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_sections` method. Note, that the first argument will be the docstring of the s...
def _set_object_doc(self, obj, doc, stacklevel=3): """Convenience method to set the __doc__ attribute of a python object """ if isinstance(obj, types.MethodType) and six.PY2: obj = obj.im_func try: obj.__doc__ = doc except AttributeError: # probably pytho...
def dedent(self, func): """ Dedent the docstring of a function and substitute with :attr:`params` Parameters ---------- func: function function with the documentation to dedent and whose sections shall be inserted from the :attr:`params` attribute""" ...
def dedents(self, s, stacklevel=3): """ Dedent a string and substitute with the :attr:`params` attribute Parameters ---------- s: str string to dedent and insert the sections of the :attr:`params` attribute stacklevel: int The stacklev...
def with_indent(self, indent=0): """ Substitute in the docstring of a function with indented :attr:`params` Parameters ---------- indent: int The number of spaces that the substitution should be indented Returns ------- function W...
def with_indents(self, s, indent=0, stacklevel=3): """ Substitute a string with the indented :attr:`params` Parameters ---------- s: str The string in which to substitute indent: int The number of spaces that the substitution should be indented ...
def delete_params(self, base_key, *params): """ Method to delete a parameter from a parameter documentation. This method deletes the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation without the descrip...
def delete_params_s(s, params): """ Delete the given parameters from a string Same as :meth:`delete_params` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the parameters section params: list of str ...
def delete_kwargs(self, base_key, args=None, kwargs=None): """ Deletes the ``*args`` or ``**kwargs`` part from the parameters section Either `args` or `kwargs` must not be None. The resulting key will be stored in ``base_key + 'no_args'`` if `args` is not None and `...
def delete_kwargs_s(cls, s, args=None, kwargs=None): """ Deletes the ``*args`` or ``**kwargs`` part from the parameters section Either `args` or `kwargs` must not be None. Parameters ---------- s: str The string to delete the args and kwargs from arg...
def delete_types(self, base_key, out_key, *types): """ Method to delete a parameter from a parameter documentation. This method deletes the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation without the ...
def delete_types_s(s, types): """ Delete the given types from a string Same as :meth:`delete_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str ...
def keep_params(self, base_key, *params): """ Method to keep only specific parameters from a parameter documentation. This method extracts the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation with only...
def keep_params_s(s, params): """ Keep the given parameters from a string Same as :meth:`keep_params` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the parameters like section params: list of str ...
def keep_types(self, base_key, out_key, *types): """ Method to keep only specific parameters from a parameter documentation. This method extracts the given `type` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation wit...
def keep_types_s(s, types): """ Keep the given types from a string Same as :meth:`keep_types` but does not use the :attr:`params` dictionary Parameters ---------- s: str The string of the returns like section types: list of str Th...
def save_docstring(self, key): """ Descriptor method to save a docstring from a function Like the :meth:`get_sectionsf` method this method serves as a descriptor for functions but saves the entire docstring""" def func(f): self.params[key] = f.__doc__ or '' ...
def get_summary(self, s, base=None): """ Get the summary of the given docstring This method extracts the summary from the given docstring `s` which is basicly the part until two newlines appear Parameters ---------- s: str The docstring to use ...
def get_summaryf(self, *args, **kwargs): """ Extract the summary from a function docstring Parameters ---------- ``*args`` and ``**kwargs`` See the :meth:`get_summary` method. Note, that the first argument will be the docstring of the specified function ...
def get_extended_summary(self, s, base=None): """Get the extended summary from a docstring This here is the extended summary Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the ...
def get_extended_summaryf(self, *args, **kwargs): """Extract the extended summary from a function docstring This function can be used as a decorator to extract the extended summary of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ``*args...
def get_full_description(self, s, base=None): """Get the full description from a docstring This here and the line above is the full description (i.e. the combination of the :meth:`get_summary` and the :meth:`get_extended_summary`) output Parameters ---------- s:...
def get_full_descriptionf(self, *args, **kwargs): """Extract the full description from a function docstring This function can be used as a decorator to extract the full descriptions of a function docstring (similar to :meth:`get_sectionsf`). Parameters ---------- ...
def make_mergable_if_possible(cls, data, context): """ Makes an object mergable if possible. Returns the virgin object if cannot convert it to a mergable instance. :returns: :class:`.Mergable` or type(data) """ if isinstance(data, dict): return MergableDict(...
def merge(self, *args): """ Merges this instance with new instances, in-place. :param \\*args: Configuration values to merge with current instance. :type \\*args: iterable """ for data in args: if isinstance(data, str): to_merge = load_string...
def load_file(self, filename): """ load file which contains yaml configuration entries.and merge it by current instance :param files: files to load and merge into existing configuration instance :type files: list """ if not path.exists(file...
def initialize(self, init_value, context=None, force=False): """ Initialize the configuration manager :param force: force initialization even if it's already initialized :return: """ if not force and self._instance is not None: raise ConfigurationAlreadyInit...
def grok_filter_name(element): """Extracts the name, which may be embedded, for a Jinja2 filter node""" e_name = None if element.name == 'default': if isinstance(element.node, jinja2.nodes.Getattr): e_name = element.node.node.name else: e_name = element.node.name ...
def grok_for_node(element, default_vars): """Properly parses a For loop element""" if isinstance(element.iter, jinja2.nodes.Filter): if element.iter.name == 'default' \ and element.iter.node.name not in default_vars: default_vars.append(element.iter.node.name) default_var...
def grok_if_node(element, default_vars): """Properly parses a If element""" if isinstance(element.test, jinja2.nodes.Filter) and \ element.test.name == 'default': default_vars.append(element.test.node.name) return default_vars + grok_vars(element)
def grok_vars(elements): """Returns a list of vars for which the value is being appropriately set This currently includes the default filter, for-based iterators, and the explicit use of set""" default_vars = [] iterbody = None if hasattr(elements, 'body'): iterbody = elements.body e...
def jinja_env(template_path): """Sets up our Jinja environment, loading the few filters we have""" fs_loader = FileSystemLoader(os.path.dirname(template_path)) env = Environment(loader=fs_loader, autoescape=True, trim_blocks=True, lstrip_bloc...
def missing_vars(template_vars, parsed_content, obj): """If we find missing variables when rendering a template we want to give the user a friendly error""" missing = [] default_vars = grok_vars(parsed_content) for var in template_vars: if var not in default_vars and var not in obj: ...
def render(filename, obj): """Render a template, maybe mixing in extra variables""" template_path = abspath(filename) env = jinja_env(template_path) template_base = os.path.basename(template_path) try: parsed_content = env.parse(env .loader ...
def load_vars(opt): """Loads variable from cli and var files, passing in cli options as a seed (although they can be overwritten!). Note, turn this into an object so it's a nicer "cache".""" if not hasattr(opt, '_vars_cache'): cli_opts = cli_hash(opt.extra_vars) setattr(opt, '_vars_cache...
def load_var_files(opt, p_obj=None): """Load variable files, merge, return contents""" obj = {} if p_obj: obj = p_obj for var_file in opt.extra_vars_file: LOG.debug("loading vars from %s", var_file) obj = merge_dicts(obj.copy(), load_var_file(var_file, obj)) return obj
def load_var_file(filename, obj): """Loads a varible file, processing it as a template""" rendered = render(filename, obj) ext = os.path.splitext(filename)[1][1:] v_obj = dict() if ext == 'json': v_obj = json.loads(rendered) elif ext == 'yaml' or ext == 'yml': v_obj = yaml.safe_l...
def load_template_help(builtin): """Loads the help for a given template""" help_file = "templates/%s-help.yml" % builtin help_file = resource_filename(__name__, help_file) help_obj = {} if os.path.exists(help_file): help_data = yaml.safe_load(open(help_file)) if 'name' in help_data:...
def builtin_list(): """Show a listing of all our builtin templates""" for template in resource_listdir(__name__, "templates"): builtin, ext = os.path.splitext(os.path.basename(abspath(template))) if ext == '.yml': continue help_obj = load_template_help(builtin) if 'n...
def builtin_info(builtin): """Show information on a particular builtin template""" help_obj = load_template_help(builtin) if help_obj.get('name') and help_obj.get('help'): print("The %s template" % (help_obj['name'])) print(help_obj['help']) else: print("No help for %s" % builtin...
def render_secretfile(opt): """Renders and returns the Secretfile construct""" LOG.debug("Using Secretfile %s", opt.secretfile) secretfile_path = abspath(opt.secretfile) obj = load_vars(opt) return render(secretfile_path, obj)
def update_user_password(client, userpass): """Will update the password for a userpass user""" vault_path = '' user = '' user_path_bits = userpass.split('/') if len(user_path_bits) == 1: user = user_path_bits[0] vault_path = "auth/userpass/users/%s/password" % user LOG.debug(...
def update_generic_password(client, path): """Will update a single key in a generic secret backend as thought it were a password""" vault_path, key = path_pieces(path) mount = mount_for_path(vault_path, client) if not mount: client.revoke_self_token() raise aomi.exceptions.VaultConst...
def password(client, path): """Will attempt to contextually update a password in Vault""" if path.startswith('user:'): update_user_password(client, path[5:]) else: update_generic_password(client, path)
def vault_file(env, default): """The path to a misc Vault file This function will check for the env override on a file path, compute a fully qualified OS appropriate path to the desired file and return it if it exists. Otherwise returns None """ home = os.environ['HOME'] if 'HOME' in os.envi...
def vault_time_to_s(time_string): """Will convert a time string, as recognized by other Vault tooling, into an integer representation of seconds""" if not time_string or len(time_string) < 2: raise aomi.exceptions \ .AomiData("Invalid timestring %s" % time_string) last_char = ...
def run(*args, **kwargs): """Execute a command. Command can be passed as several arguments, each being a string or a list of strings; lists are flattened. If opts.verbose is True, output of the command is shown. If the command exits with non-zero, print an error message and exit. If keyward arg...
def set_executing(on: bool): """ Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread should be annotated as executing ...
def get_file_contents(source_path: str) -> str: """ Loads the contents of the source into a string for execution using multiple loading methods to handle cross-platform encoding edge cases. If none of the load methods work, a string is returned that contains an error function response that will be d...
def load_step_file(source_path: str) -> str: """ Loads the source for a step file at the given path location and then renders it in a template to add additional footer data. The footer is used to force the display to flush the print buffer and breathe the step to open things up for resolution. This...
def create_module( project: 'projects.Project', step: 'projects.ProjectStep' ): """ Creates an artificial module that will encompass the code execution for the specified step. The target module is populated with the standard dunder attributes like __file__ to simulate the normal way that...