Python API

A Simple Example

You can access account information from Avendesora using Python using a simple relatively high-level interface as shown in this example:

from avendesora import PasswordGenerator, PasswordError
from inform import display, fatal, os_error
from shlib import Run
from pathlib import Path

try:
    pw = PasswordGenerator()
    account = pw.get_account('mybank')
    name = account.get_value('name')
    username = account.get_username()
    passcode = account.get_passcode()
    url = account.get_value('ofxurl')
except PasswordError as e:
    e.terminate()

try:
    curl = Run(
        f'curl -K - {url!s}',
        stdin = f'user="{username!s}:{passcode!s}"',
        modes='sOEW0'
    )
    Path(f'{name!s}.ofx').write_text(curl.stdout)
except OSError as e:
    fatal(os_error(e))

Basically, the approach is to open the password generator, open an account, and then accessing values of that account. The various components of the Avendesora programming interface are described next.

Components

This section documents the programming interface for Avendesora. You can view the Avendesora source code, particularly avendesora.command, for further examples on how to use this interface.

PasswordGenerator Class

This is the entry class to Avendesora. It is the only class you need instantiate directly. By instantiating it you cause Avendesora to read the user’s account files.

class avendesora.PasswordGenerator(init=False, gpg_ids=None)

Initializes the password generator. You should pass no arguments unless you are creating the user’s Avendesora data directory.

Calling this class causes Avendesora to open all the various account files and returns an object that allows you access to the accounts. Specifically you can use the get_account() or all_accounts() methods to access an account or all the accounts.

Parameters:
  • init (bool) – Create user’s directory.
  • gpg_ids (list of strings) – List of GPG identities to use when creating user’s directory.
Raises:

avendesora.PasswordError – Indicates an issue opening the user’s accounts.

all_accounts()

Iterate through all accounts.

challenge_response(name, challenge)

Generate a response to a challenge.

Given the name of a master seed (actually the basename of the file that contains the master seed), returns an identifying response to a challenge. If no challenge is provided, one is generated based on the time and date. Returns both the challenge and the expected response as a tuple.

Parameters:
  • name (str) – The name of the master seed.
  • challenge (str) – The challenge (may be empty).
discover_account(title=None, verbose=False)

Discover the account from the environment.

Examine the environment and return the account that matches. If more than one account/secret matches, user is queried to resolve the ambiguity.

Parameters:
  • title (str) – Override the window title. This is used for debugging.
  • verbose (bool) – Run the discovery process in verbose mode (adds more information to log file that can help debug account discovery.
Raises:

avendesora.PasswordError – There is no account that matches the given environment.

find_accounts(target)

Find accounts with names or aliases that contain a substring.

Parameters:target (str) – The desired substring.
Returns:Iterates through matching accounts.
Return type:avendesora.Account
get_account(name, request_seed=False, stealth_name=None)

Return a specific account.

Parameters:
  • name (str) – Looks up an account by name and returns it. This name must match an account name or an account alias. The matching algorithm ignores case and treats dash and underscore as equivalent.
  • request_seed (str or bool) – If specified an additional seed is provided to the account (see: misdirection). It may be specified as a string, in which case it is used as the seed. Otherwise if true, the seed it requested directly from the user.
  • stealth_name (str) – The name used as the account name if the account is a stealth account.
Returns:

An account. The class itself is returned, and not an instance of the class.

Return type:

avendesora.Account

Raises:

avendesora.PasswordError – There is no account that matches the given name.

search_accounts(target)

Find accounts with values that contain a substring.

Parameters:target (str) – The desired substring.
Returns:Iterates through matching accounts.
Return type:avendesora.Account

Account Class

class avendesora.Account

Class that holds all the information specific to an account.

Add desired account information as attributes of the class.

classmethod get_composite(name)

Get field value given a field name.

A lower level interface than get_value() that given a name returns the value of the associated field, which may be a scalar (string or integer) or a composite (array of dictionary). Unlike get_value(), the actual value is returned, not a object that contains multiple facets of the value.

Parameters:name (str) – The name of the field.
Returns:The requested value.
classmethod get_fields(all=False)

Iterate through fields.

Iterates through the field names.

Example:

for name, keys in account.get_fields():
    if keys:
        display(name + ':')
        for key, value in account.get_values(name):
            display(indent(
                value.render(('{k}) {d}: {v}', '{k}: {v}'))
            ))
    else:
        value = account.get_value(name)
        display(value.render('{n}: {v}'))
Parameters:all (bool) – If False, ignore the tool fields.
Returns:A pair (2-tuple) that contains both field name and the key names. None is returned for the key names if the field holds a scalar value.
classmethod get_name()

Get account name.

Returns:Returns the primary account name. This is generally the class name converted to lower case unless it was overridden with the NAME attribute.
classmethod get_passcode()

Get the passcode.

Like get_value(), but tries the credential_secrets in order and returns the first found. credential_secrets is an Avendesora configuration setting that by default is password, passphrase, and passcode.

Returns:The passcode.
classmethod get_scalar(name, key=None, default=False)

Get field Value given a field name and key.

A lower level interface than get_value() that given a name and perhaps a key returns a scalar value. Also takes an optional default value that is returned if the value is not found. Unlike get_value(), the actual value is returned, not a object that contains multiple facets of the value.

The name is the field name, and the key would identity which value is desired if the field is a composite. If default is False, an error is raised if the value is not present, otherwise the default value itself is returned.

Parameters:
  • name (str) – The name of the field.
  • key (str or int) – The key for the desired value (should be None for scalar values).
  • default – The value to return if the requested value is not available.
Returns:

The requested value.

classmethod get_username()

Get the username.

Like get_value(), but tries the credential_ids in order and returns the first found. credential_ids is an Avendesora configuration setting that by default is username and email.

Returns:The username or email address.
classmethod get_value(field=None)

Get account value.

Return value from the account given a user friendly identifier or script. User friendly identifiers include:

None: value of default field
name: scalar value
name.key or name[key]:
member of a dictionary or array
key is string for dictionary, integer for array

Scripts are simply strings with embedded attributes. Ex: ‘username: {username}, password: {passcode}’

Parameters:field (str) – Field identifier or script.
Returns:the desired value.
Return type:avendesora.AccountValue
classmethod get_values(name)

Iterate through the values for a field.

Parameters:name (str) – The name of the field.
Returns:Returns a pair (2-tuple) that contains the key and the value given as an avendesora.AccountValue for each of the values. If the value is a scalar, the key is None.

AccountValue Class

class avendesora.AccountValue(value, is_secret, name=None, key=None, desc=None)

An account value.

This is the object returned by avendesora.Account.get_value() and avendesora.Account.get_values(). It contains information about a single account value. Specifically, it provides the following attributes: value, is_secret, name, key, field, and desc.

render(fmts=('{f} ({d}): {v}', '{f}: {v}'))

Return value formatted as a string.

Parameters:fmts (collection of strings) –

fmts contains a sequence of format strings that are tried in sequence. The first one for which all keys are known is used. The possible keys are:

n – name (identifier for the first level of a field)
k – key (identifier for the second level of a field)
f – field (name.key)
d – description
v – value

If none work, the value alone is returned.

Returns:The value rendered as a string.

PasswordError Exception

exception avendesora.PasswordError(*args, **kwargs)

Password error.

This exception subclasses Inform.Error.

This exception subclasses inform.Error.

get_culprit()

Get exception culprit.

If the culprit keyword argument was specified as a string, it is returned. If it was specified as a collection, the members are converted to strings and joined with commas. The resulting string is returned.

get_message()

Get exception message.

If the template keyword argument was specified, it is treated as a format string and is passed both the unnamed and named arguments. The resulting string is treated as the message and returned.

Otherwise the unnamed are joined using spaces to form the message.

report()

Report exception.

The inform.error() function is called with the exception arguments.

terminate()

Report exception and terminate.

The inform.fatal() function is called with the exception arguments.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Example: Displaying Account Values

The following example prints out all account values for account whose name are found in a list.

from avendesora import PasswordGenerator
from inform import display, indent, Error

accounts = ['bank', 'credit-union', 'brokerage']

try:
    pw = PasswordGenerator()

    for account_name in accounts:
        account = pw.get_account(account_name)
        description = account.get_scalar('desc', None, account_name)
        display(description, len(description)*'=', sep='\n')

        for name, keys in account.get_fields():
            if keys:
                display(name + ':')
                for key, value in account.get_values(name):
                    display(indent(
                        value.render(('{k}) {d}: {v}', '{k}: {v}'))
                    ))
            else:
                value = account.get_value(name)
                display(value.render('{n}: {v}'))
        display()
except Error as e:
    e.terminate()

Example: Add SSH Keys

#!/usr/bin/env python3
"""
Add SSH keys

Add SSH keys to SSH agent.
The following keys are added: {keys}.

Usage:
    addsshkeys [options]

Options:
    -v, --verbose    list the keys as they are being added
"""
# This assumes that the Avendesora account that contains the ssh key's
# passphrase has a name or alias of the form <name>-ssh-key. It also assumes
# that the account contains a field named 'keyfile' or 'keyfiles' that contains
# an absolute path or paths to the ssh key files in a string.

from avendesora import PasswordGenerator, PasswordError
from inform import Inform, codicil, error, fatal, narrate
from docopt import docopt
from pathlib import Path
import pexpect

SSHkeys = ['primary', 'github', 'backups']
SSHadd = 'ssh-add'

cmdline = docopt(__doc__.format(keys = ', '.join(SSHkeys)))
Inform(narrate=cmdline['--verbose'])

try:
    pw = PasswordGenerator()
except PasswordError as e:
    e.terminate()

for key in SSHkeys:
    name = key + '-ssh-key'
    try:
        account = pw.get_account(name)
        passphrase = account.get_passcode().value
        if account.has_field('keyfiles'):
            keyfiles = account.get_value('keyfiles').value
        else:
            keyfiles = account.get_value('keyfile').value
        for keyfile in keyfiles.split():
            path = Path(keyfile).expanduser()
            narrate('adding.', culprit=keyfile)
            try:
                sshadd = pexpect.spawn(SSHadd, [str(path)])
                sshadd.expect('Enter passphrase for %s: ' % (path), timeout=4)
                sshadd.sendline(passphrase)
                sshadd.expect(pexpect.EOF)
                sshadd.close()
                response = sshadd.before.decode('utf-8')
                if 'identity added' in response.lower():
                    continue
            except (pexpect.EOF, pexpect.TIMEOUT):
                pass
            error('failed.', culprit=path)
            codicil('response:', sshadd.before.decode('utf8'), culprit=SSHadd)
            codicil('exit status:', sshadd.exitstatus , culprit=SSHadd)
    except PasswordError as e:
        fatal(e, culprit=path)

Example: Postmortem Letter

This is a program that generates messages for a person’s children and business partners. It is assumed that these messages would be placed into a safe place to be found and read upon the person’s death.

Modify the program so that it goes through all accounts and look for a particular fields, such as target and value. The target would be a string that contains the name of the person for which it is a message, and value would contain an estimate of the total account value.

It generates an encrypted file for each of the recipients that contains accounts that contain an postmortem_recipient whose value matches the recipient.

#!/bin/env python3

from avendesora import PasswordGenerator
from inform import done, Error, indent, os_error, terminate
import gnupg

recipients = dict(
    kids='dominique@chappell.name lonny@chappell.name tabatha@chappell.name',
    henry='dominique@chappell.name  lynna.titus625@gmail.com',
)

try:
    pw = PasswordGenerator()

    for recipient, idents in recipients.items():
        # extract account information
        accounts = []
        for account in pw.all_accounts():
            if recipient == account.get_scalar('postmortem_recipient', default=None):
                account_name = account.get_name()
                description = account.get_scalar('desc', None, account_name)
                lines = [description, len(description)*'=']

                for name, keys in account.get_fields():
                    if name == 'postmortem_recipient':
                        continue
                    if keys:
                        lines.append(name + ':')
                        for key, value in account.get_values(name):
                            lines += indent(
                                value.render(('{k}) {d}: {v}', '{k}: {v}'))
                            ).split('\n')
                    else:
                        value = account.get_value(name)
                        lines += value.render('{n}: {v}').split('\n')
                accounts.append('\n'.join(lines))

        # write GPG file containing accounts
        gpg = gnupg.GPG(gpgbinary='gpg2')
        encrypted = gpg.encrypt('\n\n\n'.join(accounts), idents.split())
        if not encrypted.ok:
            raise Error(
                'unable to encrypt:', encrypted.stderr, culprit=recipient
            )
        try:
            filename = recipient + '.gpg'
            with open(filename, 'w') as file:
                file.write(str(encrypted))
            narrate("created.", culprit=filename)
        except OSError as e:
            raise Error(os_error(e))

except KeyboardInterrupt:
    terminate('Killed by user')
except Error as e:
    e.terminate()