API Reference

Version

psec.__version__

Current python_secrets version.

psec.google_oauth2

Class for sending cleartext and encrypted emails (optionally with attachments) using OAuth2 authenticated Google SMTP services.

Adapted from:

See also:

There are three tasks that can be accomplished using this class:

  1. Generating an OAuth2 token with a limited lifetime and a refresh token with an indefinite lifetime to use for login (access_token)
  2. Generating a new access token using a refresh token (refresh_token)
  3. Generating an OAuth2 string that can be passed to IMAP or SMTP servers to authenticate connections. (generate_oauth2_string())
class psec.google_oauth2.GoogleSMTP(username=None, client_id=None, client_secret=None, refresh_token=None, verbose=False, gpg_encrypt=False)[source]

Google OAuth2 SMTP class.

__dict__ = mappingproxy({'__module__': 'psec.google_oauth2', '__doc__': '\n Google OAuth2 SMTP class.\n ', 'logger': <Logger psec.google_oauth2 (WARNING)>, '__init__': <function GoogleSMTP.__init__>, 'set_client_id': <function GoogleSMTP.set_client_id>, 'set_client_secret': <function GoogleSMTP.set_client_secret>, 'command_to_url': <function GoogleSMTP.command_to_url>, 'url_escape': <function GoogleSMTP.url_escape>, 'url_unescape': <function GoogleSMTP.url_unescape>, 'url_format_params': <function GoogleSMTP.url_format_params>, 'generate_permission_url': <function GoogleSMTP.generate_permission_url>, 'find_keyid': <function GoogleSMTP.find_keyid>, 'authorize_tokens': <function GoogleSMTP.authorize_tokens>, 'generate_refresh_token': <function GoogleSMTP.generate_refresh_token>, 'generate_oauth2_string': <function GoogleSMTP.generate_oauth2_string>, 'test_imap': <function GoogleSMTP.test_imap>, 'test_smtp': <function GoogleSMTP.test_smtp>, 'get_refresh_token': <function GoogleSMTP.get_refresh_token>, 'get_authorization': <function GoogleSMTP.get_authorization>, 'refresh_authorization': <function GoogleSMTP.refresh_authorization>, 'create_msg': <function GoogleSMTP.create_msg>, 'send_mail': <function GoogleSMTP.send_mail>, '__dict__': <attribute '__dict__' of 'GoogleSMTP' objects>, '__weakref__': <attribute '__weakref__' of 'GoogleSMTP' objects>})
__init__(username=None, client_id=None, client_secret=None, refresh_token=None, verbose=False, gpg_encrypt=False)[source]

Initialize self. See help(type(self)) for accurate signature.

__module__ = 'psec.google_oauth2'
__weakref__

list of weak references to the object (if defined)

authorize_tokens(auth_token)[source]

Return OAuth 2.0 authorization token data following the flow described in “OAuth2 for Installed Applications”:

Parameters:
  • client_id – Client ID obtained by registering your app.
  • client_secret – Client secret obtained by registering your app.
  • authorization_code – code generated by Google Accounts after user grants permission.
Returns:

The decoded response from the Google Accounts server, as a dict. Expected fields include ‘access_token’, ‘expires_in’, and ‘refresh_token’.

command_to_url(command)[source]

Produce an URL for a given command.

create_msg(fromaddr, toaddr, subject, text_message=None, html_message=None, addendum=None, encrypt_msg=False)[source]

Create email message, optionally GPG encrypted.

Parameters:
  • fromaddr – Email From: address.
  • toaddr – Email To: address.
  • subject – Email Subject: string.
  • text_message – Text for body of email message.
  • html_message – Alternative HTML version of body.
  • addendum – Signature or other description of the source of the email to be appended to the end of the message following ----.
  • html_message – Alternative HTML version of body.

If no alternative HTML is included with a text message body, one will be generated.

If the class was initialized with gpg_encrypt=True, the text body will be encrypted with GPG before sending using the key associated with the recipient. If no key is found, or the encryption fails for some other reason, a RuntimeError exception is raised.

find_keyid(recipient, keyid=None)[source]

Locate the GPG keyid for encrypting a message to the recipient.

If a keyid is provided, make sure it matches the recipient and return None if it does not. Otherwise, walk through all keys in the keyring to find a match. If more than one key is found, raise a RuntimeError.

generate_oauth2_string(base64_encode=False)[source]

Generates an IMAP OAuth2 authentication string.

See https://developers.google.com/google-apps/gmail/oauth2_overview

Parameters:
  • username – the username (email address) of the account to authenticate
  • access_token – An OAuth2 access token.
  • base64_encode – Whether to base64-encode the output.
Returns:

The SASL argument for the OAuth2 mechanism.

generate_permission_url(scope='https://mail.google.com/')[source]

Generate an OAuth 2.0 authorization URL following the flow described in “OAuth2 for Installed Applications”:

Parameters:
  • client_id – Client ID obtained by registering your app.
  • scope – scope for access token, e.g. ‘https://mail.google.com
Returns:

A URL that the user should visit in their browser.

generate_refresh_token()[source]

Obtains a new OAuth2 authorization token using a refresh token.

See:
https://developers.google.com/accounts/docs/OAuth2InstalledApp#refresh
Parameters:
  • client_id – Client ID obtained by registering your app.
  • client_secret – Client secret obtained by registering your app.
  • refresh_token – A previously-obtained refresh token.
Returns:

The decoded response from the Google Accounts server, as a dict. Expected fields include ‘access_token’, ‘expires_in’, and ‘refresh_token’.

get_authorization()[source]

Get OAuth 2.0 authorization URL.

get_refresh_token()[source]

Get the OAuth 2.0 refresh token.

logger = <Logger psec.google_oauth2 (WARNING)>
refresh_authorization()[source]

Refresh OAuth 2.0 authorization token data.

send_mail(fromaddr, toaddr, msg)[source]

Send email message.

Parameters:
  • fromaddr – Email From: address.
  • toaddr – Email To: address.
  • msg – Already fully-populated Message object.
set_client_id(client_id=None)[source]

Store the OAuth 2.0 client ID.

set_client_secret(client_secret=None)[source]

Store the OAuth 2.0 client secret.

test_imap(auth_string)[source]

Authenticates to IMAP with the given auth_string.

Prints a debug trace of the attempted IMAP connection.

Parameters:
  • user – The Gmail username (full email address)
  • auth_string – A valid OAuth2 string, as returned by generate_oauth2_string(). Must not be base64-encoded, since imaplib does its own base64-encoding.
test_smtp(auth_string)[source]

Authenticates to SMTP with the given auth_string.

Parameters:
  • user – The Gmail username (full email address)
  • auth_string – A valid OAuth2 string, not base64-encoded, as returned by generate_oauth2_string().
url_escape(text)[source]

Escape characters in the URL to reduce risk.

url_format_params(params)[source]

Format a parameterized URL.

url_unescape(text)[source]

Return URL to standard form.

psec.secrets_environment

Secrets environment class and related variables, functions.

class psec.secrets_environment.SecretsEnvironment(environment=None, secrets_basedir=None, secrets_file=None, create_root=False, defer_loading=False, export_env_vars=False, preserve_existing=False, env_var_prefix=None, source=None, verbose_level=1)[source]

Class for handling secrets environment metadata.

Provides an interface to the directory contents for a secrets environment, including groups descriptions, a tmp/ directory, and any other required directories.

Typical usage example:

from psec.secrets_environment import SecretsEnvironment

se = SecretsEnvironment(environment='env_name')
environment

Name of the environment.

secrets_basedir

Base directory path to environment’s storage.

secrets_file

File name for storing secrets (defaults to ‘secrets.json’).

create_root

Controls whether the root directory is created on first use.

defer_loading

Don’t load values (just initialize attributes).

export_env_vars

Export all variables to the environment.

preserve_existing

Don’t over-write existing environment variables.

env_var_prefix

Prefix to apply to all exported environment variables.

source

Directory path from which to clone a new environment.

verbose_level

Verbosity level (pass from app args).

__dict__ = mappingproxy({'__module__': 'psec.secrets_environment', '__doc__': "\n Class for handling secrets environment metadata.\n\n Provides an interface to the directory contents for a secrets environment,\n including groups descriptions, a tmp/ directory, and any other required\n directories.\n\n Typical usage example::\n\n from psec.secrets_environment import SecretsEnvironment\n\n se = SecretsEnvironment(environment='env_name')\n\n\n Attributes:\n environment: Name of the environment.\n secrets_basedir: Base directory path to environment's storage.\n secrets_file: File name for storing secrets (defaults to 'secrets.json').\n create_root: Controls whether the root directory is created on first use.\n defer_loading: Don't load values (just initialize attributes).\n export_env_vars: Export all variables to the environment.\n preserve_existing: Don't over-write existing environment variables.\n env_var_prefix: Prefix to apply to all exported environment variables.\n source: Directory path from which to clone a new environment.\n verbose_level: Verbosity level (pass from app args).\n ", 'logger': <Logger psec.secrets_environment (WARNING)>, '__init__': <function SecretsEnvironment.__init__>, '__str__': <function SecretsEnvironment.__str__>, 'verbose_level': <property object>, 'changed': <function SecretsEnvironment.changed>, 'get_secrets_descriptions_dir': <function SecretsEnvironment.get_secrets_descriptions_dir>, 'get_secrets_basename': <function SecretsEnvironment.get_secrets_basename>, 'get_secrets_basedir': <function SecretsEnvironment.get_secrets_basedir>, 'secrets_basedir_exists': <function SecretsEnvironment.secrets_basedir_exists>, 'get_environment_path': <function SecretsEnvironment.get_environment_path>, 'environment_exists': <function SecretsEnvironment.environment_exists>, 'environment_create': <function SecretsEnvironment.environment_create>, 'get_secrets_file_path': <function SecretsEnvironment.get_secrets_file_path>, 'secrets_file_path_exists': <function SecretsEnvironment.secrets_file_path_exists>, 'get_descriptions_path': <function SecretsEnvironment.get_descriptions_path>, 'get_tmpdir_path': <function SecretsEnvironment.get_tmpdir_path>, 'requires_environment': <function SecretsEnvironment.requires_environment>, 'keys': <function SecretsEnvironment.keys>, 'items': <function SecretsEnvironment.items>, 'get_secret': <function SecretsEnvironment.get_secret>, 'get_secret_export': <function SecretsEnvironment.get_secret_export>, '_set_secret': <function SecretsEnvironment._set_secret>, 'set_secret': <function SecretsEnvironment.set_secret>, 'delete_secret': <function SecretsEnvironment.delete_secret>, 'get_type': <function SecretsEnvironment.get_type>, 'get_default_value': <function SecretsEnvironment.get_default_value>, 'read_secrets_and_descriptions': <function SecretsEnvironment.read_secrets_and_descriptions>, 'find_new_secrets': <function SecretsEnvironment.find_new_secrets>, 'read_secrets': <function SecretsEnvironment.read_secrets>, 'write_secrets': <function SecretsEnvironment.write_secrets>, 'clone_from': <function SecretsEnvironment.clone_from>, 'read_descriptions': <function SecretsEnvironment.read_descriptions>, 'write_descriptions': <function SecretsEnvironment.write_descriptions>, 'check_duplicates': <function SecretsEnvironment.check_duplicates>, 'read_secrets_descriptions': <function SecretsEnvironment.read_secrets_descriptions>, 'descriptions': <function SecretsEnvironment.descriptions>, 'get_secret_type': <function SecretsEnvironment.get_secret_type>, 'get_options': <function SecretsEnvironment.get_options>, 'get_help': <function SecretsEnvironment.get_help>, 'get_prompt': <function SecretsEnvironment.get_prompt>, 'get_secret_arguments': <function SecretsEnvironment.get_secret_arguments>, 'get_items_from_group': <function SecretsEnvironment.get_items_from_group>, 'is_item_in_group': <function SecretsEnvironment.is_item_in_group>, 'get_group': <function SecretsEnvironment.get_group>, 'get_groups': <function SecretsEnvironment.get_groups>, '__dict__': <attribute '__dict__' of 'SecretsEnvironment' objects>, '__weakref__': <attribute '__weakref__' of 'SecretsEnvironment' objects>})
__init__(environment=None, secrets_basedir=None, secrets_file=None, create_root=False, defer_loading=False, export_env_vars=False, preserve_existing=False, env_var_prefix=None, source=None, verbose_level=1)[source]

Initialize secrets environment object.

__module__ = 'psec.secrets_environment'
__str__()[source]

Produce string representation of environment identifier

__weakref__

list of weak references to the object (if defined)

changed()[source]

Return boolean reflecting changed secrets.

check_duplicates(data=None)[source]

Check to see if any ‘Variable’ dictionary elements in list match any already defined variables. If so, raise RuntimeError().

Parameters:data – list of dictionaries containing secret descriptions
Returns:None
clone_from(src: Union[pathlib.Path, str])[source]

Clone from existing definition file(s)

The source can be (a) a directory full of one or more group descriptions, (b) a single group descriptions file, or (c) an existing environment’s descriptions file(s).

delete_secret(secret)[source]

Delete a secret and record change.

Parameters:secret
type:string
Returns:
descriptions()[source]
environment_create(source=None, alias=False, mode=448)[source]

Create secrets environment directory

environment_exists(env=None, path_only=False)[source]

Return whether secrets environment directory exists and contains files other than ‘tmp’ directory.

find_new_secrets()[source]

Ensure that any new secrets defined in description files are called out and/or become new undefined secrets. :return:

get_default_value(variable)[source]

Return the default value from the Options attribute

get_descriptions_path(root=None, group=None, create=False, mode=448)[source]

Return path to secrets descriptions directory or file.

get_environment_path(env=None, subdir=None, host=None)[source]

Returns the absolute path to secrets environment directory or subdirectories within it

get_group(item)[source]

Return the group to which an item belongs.

get_groups()[source]

Get the secrets description groups

get_help(secret)[source]

Get the help documentation URL for the secret

get_items_from_group(group)[source]

Get the variables in a secrets description group

get_options(secret)[source]

Get the options for setting the secret

get_prompt(secret)[source]

Get the prompt for the secret

get_secret(secret, allow_none=False)[source]

Get the value of secret

Parameters:
  • secret (string) – Name of the secret to get
  • allow_none (boolean) – Allow returning None
Returns:

The value of the secret

Return type:

string

Raises:

SecretNotFoundError – If value is None and allow_none is False

get_secret_arguments(variable)[source]

Get the Arguments of variable from set of secrets descriptions

get_secret_export(secret)[source]

Get the specified environment variable for exporting secret

Parameters:secret
type:string
Returns:environment variable for exporting secret
get_secret_type(variable)[source]

Get the Type of variable from set of secrets descriptions

get_secrets_basedir(init=False, mode=448)[source]

Returns the directory path root for secrets storage and definitions.

When more than one environment is being used, a single top-level directory in the user’s home directory is the preferred location. This function checks to see if such a directory exists, and if so defaults to that location.

If the environment variable “D2_SECRETS_BASEDIR” is set, that location is used instead.

get_secrets_basename()[source]

Return the basename of the current secrets file

get_secrets_descriptions_dir()[source]

Return the path to the drop-in secrets description directory

get_secrets_file_path(env=None)[source]

Returns the absolute path to secrets file

get_tmpdir_path(create_path=False)[source]

Return the absolute path to secrets descriptions tmp directory

get_type(variable)[source]

Return type for variable or None if no description

is_item_in_group(item, group)[source]

Return true or false based on item being in group

items()[source]

Return the items from the secrets dictionary.

keys()[source]

Return the keys to the secrets dictionary

logger = <Logger psec.secrets_environment (WARNING)>
read_descriptions(infile=None, group=None)[source]

Read a secrets group description file and return a dictionary if valid.

Parameters:
  • infile
  • group
Returns:

dictionary of descriptions

read_secrets(from_descriptions=False)[source]

Load the current secrets file.

If no secrets have been set yet and from_descriptions is True, return a dictionary comprised of the keys from the descriptions dictionary defined to be None and set self._changed to ensure these are written out.

read_secrets_and_descriptions(ignore_errors=False)[source]

Read secrets descriptions and secrets.

read_secrets_descriptions(ignore_errors=False)[source]

Load the descriptions of groups of secrets from a .d directory

requires_environment(path_only=False)[source]

Provide consistent error handling for any commands that require an environment actually exist in order to work properly.

secrets_basedir_exists()[source]

Return whether secrets root directory exists

secrets_file_path_exists()[source]

Return whether secrets file exists

set_secret(secret, value=None)[source]

Set secret to value and record change

Parameters:
  • secret
    type:string
  • value
    type:string
Returns:

verbose_level

Returns the verbosity level.

write_descriptions(data={}, group=None, mode=448, mirror_to=None)[source]

Write out the secrets descriptions to a file.

write_secrets()[source]

Write out the current secrets if any changes were made

psec.secrets_environment.generate_secret(secret_type, **kwargs)[source]

Generate secret of the specified type.

psec.secrets_environment.is_generable(secret_type=None)[source]

Return boolean for generability of this secret type.

psec.utils

Utility functions.

class psec.utils.CustomFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]

Custom class to control arparse help output formatting.

__module__ = 'psec.utils'
class psec.utils.Memoize(fn)[source]

Memoize(fn) - an instance which acts like fn but memoizes its arguments.

Will only work on functions with non-mutable arguments. Hacked to assume that argument to function is whether to cache or not, allowing all secrets of a given type to be set to the same value.

__call__(*args)[source]

Call self as a function.

__dict__ = mappingproxy({'__module__': 'psec.utils', '__doc__': 'Memoize(fn) - an instance which acts like fn but memoizes its arguments.\n\n Will only work on functions with non-mutable arguments. Hacked to assume\n that argument to function is whether to cache or not, allowing all\n secrets of a given type to be set to the same value.\n ', '__init__': <function Memoize.__init__>, '__call__': <function Memoize.__call__>, '__dict__': <attribute '__dict__' of 'Memoize' objects>, '__weakref__': <attribute '__weakref__' of 'Memoize' objects>})
__init__(fn)[source]

Initialize self. See help(type(self)) for accurate signature.

__module__ = 'psec.utils'
__weakref__

list of weak references to the object (if defined)

class psec.utils.Timer(task_description='elapsed time', verbose=False)[source]

Timer object usable as a context manager, or for manual timing.

Based on code from http://coreygoldberg.blogspot.com/2012/06/python-timer-class-context-manager-for.html # noqa

As a context manager, do:

from timer import Timer

url = ‘https://github.com/timeline.json

with Timer() as t:
r = requests.get(url)

print ‘fetched %r in %.2f millisecs’ % (url, t.elapsed*1000)

__dict__ = mappingproxy({'__module__': 'psec.utils', '__doc__': "\n Timer object usable as a context manager, or for manual timing.\n\n Based on code from http://coreygoldberg.blogspot.com/2012/06/python-timer-class-context-manager-for.html # noqa\n\n As a context manager, do:\n\n from timer import Timer\n\n url = 'https://github.com/timeline.json'\n\n with Timer() as t:\n r = requests.get(url)\n\n print 'fetched %r in %.2f millisecs' % (url, t.elapsed*1000)\n\n ", '__init__': <function Timer.__init__>, '__enter__': <function Timer.__enter__>, '__exit__': <function Timer.__exit__>, 'start': <function Timer.start>, 'lap': <function Timer.lap>, 'stop': <function Timer.stop>, 'get_lap': <function Timer.get_lap>, 'elapsed_raw': <function Timer.elapsed_raw>, 'elapsed': <function Timer.elapsed>, '__dict__': <attribute '__dict__' of 'Timer' objects>, '__weakref__': <attribute '__weakref__' of 'Timer' objects>})
__enter__()[source]

Record initial time.

__exit__(*args)[source]

Record final time.

__init__(task_description='elapsed time', verbose=False)[source]

Initialize self. See help(type(self)) for accurate signature.

__module__ = 'psec.utils'
__weakref__

list of weak references to the object (if defined)

elapsed(start='__enter__', end='__exit__')[source]

Return a formatted string with elapsed time between ‘start’ and ‘end’ kwargs (if specified) in HH:MM:SS.SS format.

elapsed_raw(start='__enter__', end='__exit__')[source]

Return the elapsed time as a raw value.

get_lap(lap='__exit__')[source]

Get the timer for label specified by ‘lap’

lap(lap='__lap__')[source]

Records a lap time. If no lap label is specified, a single ‘last lap’ counter will be (re)used. To keep track of more laps, provide labels yourself.

start(lap=None)[source]

Record starting time.

stop()[source]

Record stop time.

psec.utils.atree(dir, print_files=True, outfile=None)[source]

Produces the tree structure for the path specified on the command line. If output is specified (e.g., as sys.stdout) it will be used, otherwise a list of strings is returned.

Uses anytree: https://anytree.readthedocs.io/en/latest/

Parameters:
  • dir
  • print_files
  • outfile
Returns:

str

psec.utils.bell()[source]

Output an ASCII BEL character to stderr.

psec.utils.clear_saved_default_environment(cwd=None)[source]

Remove saved default environment file.

psec.utils.copyanything(src, dst)[source]

Copy anything from src to dst.

psec.utils.copydescriptions(src: pathlib.Path, dst: pathlib.Path)[source]

Just copy the descriptions portion of an environment directory from src to dst.

psec.utils.ensure_secrets_basedir(secrets_basedir=None, allow_create=False, allow_prompt=False, verbose_level=1)[source]

Ensure that the secrets basedir exists.

If the path is within the user’s home directory, it is OK to create the directory automatically if it does not exist. This was the original behavior. If the path does exist and contains file, but does not have the special marker, that will be considered an error the user needs to resolve.

For paths that lie outside the user’s home directory, the user must explicitly confirm that it is OK to create the directory by responding to prompts (when possible) or by using the –init option flag or psec init command.

psec.utils.find(lst, key, value)[source]

Searches a list of dictionaries by value of a specified key.

Find the first item from a list of dicts where the key identified by key has the value specified by value.

Parameters:
  • lst (list of dict) – List of dictionaries to search
  • key (str) – Key to compare
  • value (str) – Value to find
Returns:

Index to the first entry with the matching value or None

psec.utils.get_default_environment(cwd=None)[source]

Return the default environment identifier.

There are multiple ways for a user to specify the environment to use for python_secrets commands. Some of these involve explicit settings (e.g., via command line option, a saved value in the current working directory, or an environment variable) or implicitly from the name of the current working directory.

psec.utils.get_default_secrets_basedir()[source]

Return the default secrets base directory path.

psec.utils.get_environment_paths(basedir=None)[source]

Return sorted list of valid environment paths found in basedir.

psec.utils.get_files_from_path(path=None)[source]

Gets a list of absolute paths to one or more files associated with a path.

If path is a directory, the files contained in it are returned, otherwise the path to the file is the only item in the list.

Parameters:path (str) – Candidate path.
Returns:A list of one or more absolute file paths.
Return type:list
psec.utils.get_fs_type(mypath)[source]

Identifies the file system type for a specific mount path.

Parameters:mypath (str) – Candidate path.
Returns:File system type for partition containing mypath.
Return type:string
psec.utils.get_local_default_file(cwd=None)[source]

Returns the path to the local identifier file.

psec.utils.get_myip(method='random')[source]

Return current routable source IP address.

psec.utils.get_myip_methods(include_random=False)[source]

Return list of available method ids for getting IP address.

psec.utils.get_netblock(ip=None)[source]

Derives the CIDR netblocks for an IP via WHOIS lookup.

Parameters:ip (str) – IP address
Returns:One or more CIDR blocks
Return type:string
psec.utils.get_output(cmd=['echo', 'NO COMMAND SPECIFIED'], cwd='/home/docs/checkouts/readthedocs.org/user_builds/python-secrets/checkouts/latest/docs', stderr=-2, shell=False)[source]

Uses subprocess.check_ouput() to run a sub-command.

Parameters:
  • cmd (list) – Argument list
  • cwd (str) – Directory to use for current working directory by shell
  • stderr (file handle) – Where should stderr be directed? (default: subprocess.STDOUT)
  • shell (bool) – Use a shell (default: FALSE)
Returns:

Output from command

Return type:

list of str

psec.utils.get_saved_default_environment(cwd=None)[source]

Return environment ID value saved in local file or None.

psec.utils.getmount(mypath)[source]

Identifies the filesystem mount point for the partition containing mypath.

Parameters:mypath (str) – Candidate path.
Returns:The mount point for the filesystem partition containing path.
Return type:string
psec.utils.getmount_fstype(mypath)[source]

Identifies the file system type for a specific mount path.

Parameters:mypath (str) – Candidate path.
Returns:File system type for partition containing mypath.
Return type:string
psec.utils.is_secrets_basedir(basedir=None, raise_exception=True)[source]

Validate secrets base directory by presence of a marker file.

Returns False if the directory either does not exist or does not contain the expected marker file, or True otherwise.

psec.utils.is_valid_environment(env_path, verbose_level=1)[source]

Check to see if this looks like a valid environment directory.

Parameters:
  • env_path – Path to candidate directory to test.
  • verbose_level – Verbosity level (pass from app args)
Returns:

A boolean indicating whether the directory appears to be a valid environment directory or not based on contents including a ‘secrets.json’ file or a ‘secrets.d’ directory.

psec.utils.myip_http(arg=None)[source]

Use an HTTP service that only returns IP address.

psec.utils.myip_resolver(arg=None)[source]

Use DNS resolver to get IP address.

psec.utils.natural_number(value)[source]

Tests for a natural number.

Parameters:value – The value to test
Returns:A boolean indicating whether the value is a natural number or not.
psec.utils.permissions_check(basedir='.', verbose_level=0)[source]

Check for presense of pernicious overly-permissive permissions.

psec.utils.prompt_options_dict(options=None, by_descr=True, prompt='Select from the following options')[source]

Prompt the user for a string using option dictionaries.

These dictionaries map a descriptive name to an identifier:

{'descr': 'DigitalOcean', 'ident': 'digitalocean'}
psec.utils.prompt_options_list(options=None, default=None, prompt='Select from the following options')[source]

Prompt the user for a string using a list of options.

The options will be one of the following:

‘*’ - Any user input ‘A,*’ - ‘A’, or any user input. ‘A,B’ - Only choices are ‘A’ or ‘B’.

psec.utils.prompt_string(prompt='Enter a value', default=None)[source]

Prompt the user for a string and return it

psec.utils.redact(string, redact=False)[source]
psec.utils.remove_other_perms(dst)[source]

Make all files in path dst have o-rwx permissions.

NOTE: This does not work on file system types NTFS, FAT, or FAT32. A log message will be produced when this is encountered.

psec.utils.require_options(options, *args)[source]
psec.utils.safe_delete_file(file_name=None, passes=3, verbose=False)[source]
psec.utils.save_default_environment(environment=None, cwd=None)[source]

Save environment identifier to local file for defaulting.

psec.utils.secrets_basedir_create(basedir=None, mode=448)[source]

Create secrets root directory

psec.utils.secrets_tree(env=None, outfile=None)[source]

Produces the tree structure for groups and secrets in an environment.

If output is specified (e.g., as sys.stdout) it will be used, otherwise a list of strings is returned.

Uses anytree: https://anytree.readthedocs.io/en/latest/

Parameters:
  • environment_dir
  • outfile
Returns:

str

psec.utils.show_current_value(variable=None)[source]

Pretty-print environment variable (if set).

psec.utils.umask(value)[source]

Set umask.