Beispiel #1
0
    def _load_config(self):
        keyring_cfg = os.path.join(platform.config_root(), 'keyringrc.cfg')
        if not os.path.exists(keyring_cfg):
            return

        config = configparser.RawConfigParser()
        config.read(keyring_cfg)
        try:
            self.pass_key_prefix = config.get('pass', 'key-prefix')
        except (configparser.NoSectionError, configparser.NoOptionError):
            pass
def run(args):
    """Handle keyring script."""
    parser = argparse.ArgumentParser(
        description=(
            "Modify Home Assistant secrets in the default keyring. "
            "Use the secrets in configuration files with: "
            "!secret <name>"
        )
    )
    parser.add_argument("--script", choices=["keyring"])
    parser.add_argument(
        "action",
        choices=["get", "set", "del", "info"],
        help="Get, set or delete a secret",
    )
    parser.add_argument("name", help="Name of the secret", nargs="?", default=None)

    import keyring  # pylint: disable=import-outside-toplevel

    # pylint: disable=import-outside-toplevel
    from keyring.util import platform_ as platform

    args = parser.parse_args(args)

    if args.action == "info":
        keyr = keyring.get_keyring()
        print("Keyring version {}\n".format(REQUIREMENTS[0].split("==")[1]))
        print(f"Active keyring  : {keyr.__module__}")
        config_name = os.path.join(platform.config_root(), "keyringrc.cfg")
        print(f"Config location : {config_name}")
        print(f"Data location   : {platform.data_root()}\n")
    elif args.name is None:
        parser.print_help()
        return 1

    if args.action == "set":
        entered_secret = getpass.getpass(f"Please enter the secret for {args.name}: ")
        keyring.set_password(_SECRET_NAMESPACE, args.name, entered_secret)
        print(f"Secret {args.name} set successfully")
    elif args.action == "get":
        the_secret = keyring.get_password(_SECRET_NAMESPACE, args.name)
        if the_secret is None:
            print(f"Secret {args.name} not found")
        else:
            print(f"Secret {args.name}={the_secret}")
    elif args.action == "del":
        try:
            keyring.delete_password(_SECRET_NAMESPACE, args.name)
            print(f"Deleted secret {args.name}")
        except keyring.errors.PasswordDeleteError:
            print(f"Secret {args.name} not found")
Beispiel #3
0
def run(args):
    """Handle keyring script."""
    parser = argparse.ArgumentParser(
        description=("Modify Home Assistant secrets in the default keyring. "
                     "Use the secrets in configuration files with: "
                     "!secret <name>"))
    parser.add_argument('--script', choices=['keyring'])
    parser.add_argument('action',
                        choices=['get', 'set', 'del', 'info'],
                        help="Get, set or delete a secret")
    parser.add_argument('name',
                        help="Name of the secret",
                        nargs='?',
                        default=None)

    import keyring
    from keyring.util import platform_ as platform

    args = parser.parse_args(args)

    if args.action == 'info':
        keyr = keyring.get_keyring()
        print('Keyring version {}\n'.format(REQUIREMENTS[0].split('==')[1]))
        print('Active keyring  : {}'.format(keyr.__module__))
        config_name = os.path.join(platform.config_root(), 'keyringrc.cfg')
        print('Config location : {}'.format(config_name))
        print('Data location   : {}\n'.format(platform.data_root()))
    elif args.name is None:
        parser.print_help()
        return 1

    if args.action == 'set':
        the_secret = getpass.getpass('Please enter the secret for {}: '.format(
            args.name))
        keyring.set_password(_SECRET_NAMESPACE, args.name, the_secret)
        print('Secret {} set successfully'.format(args.name))
    elif args.action == 'get':
        the_secret = keyring.get_password(_SECRET_NAMESPACE, args.name)
        if the_secret is None:
            print('Secret {} not found'.format(args.name))
        else:
            print('Secret {}={}'.format(args.name, the_secret))
    elif args.action == 'del':
        try:
            keyring.delete_password(_SECRET_NAMESPACE, args.name)
            print('Deleted secret {}'.format(args.name))
        except keyring.errors.PasswordDeleteError:
            print('Secret {} not found'.format(args.name))
Beispiel #4
0
def run(args):
    """Handle keyring script."""
    parser = argparse.ArgumentParser(
        description=("Modify Home Assistant secrets in the default keyring. "
                     "Use the secrets in configuration files with: "
                     "!secret <name>"))
    parser.add_argument(
        '--script', choices=['keyring'])
    parser.add_argument(
        'action', choices=['get', 'set', 'del', 'info'],
        help="Get, set or delete a secret")
    parser.add_argument(
        'name', help="Name of the secret", nargs='?', default=None)

    import keyring
    from keyring.util import platform_ as platform

    args = parser.parse_args(args)

    if args.action == 'info':
        keyr = keyring.get_keyring()
        print('Keyring version {}\n'.format(keyring.__version__))
        print('Active keyring  : {}'.format(keyr.__module__))
        config_name = os.path.join(platform.config_root(), 'keyringrc.cfg')
        print('Config location : {}'.format(config_name))
        print('Data location   : {}\n'.format(platform.data_root()))
    elif args.name is None:
        parser.print_help()
        return 1

    if args.action == 'set':
        the_secret = getpass.getpass(
            'Please enter the secret for {}: '.format(args.name))
        keyring.set_password(_SECRET_NAMESPACE, args.name, the_secret)
        print('Secret {} set successfully'.format(args.name))
    elif args.action == 'get':
        the_secret = keyring.get_password(_SECRET_NAMESPACE, args.name)
        if the_secret is None:
            print('Secret {} not found'.format(args.name))
        else:
            print('Secret {}={}'.format(args.name, the_secret))
    elif args.action == 'del':
        try:
            keyring.delete_password(_SECRET_NAMESPACE, args.name)
            print('Deleted secret {}'.format(args.name))
        except keyring.errors.PasswordDeleteError:
            print('Secret {} not found'.format(args.name))
def load_config():
    """Load a keyring using the config file.

    The config file can be in the current working directory, or in the user's
    home directory.
    """
    keyring = None

    filename = 'keyringrc.cfg'

    local_path = os.path.join(os.getcwd(), filename)
    config_path = os.path.join(platform.config_root(), filename)

    # search from current working directory and the data root
    keyring_cfg_candidates = [local_path, config_path]

    # initialize the keyring_config with the first detected config file
    keyring_cfg = None
    for path in keyring_cfg_candidates:
        keyring_cfg = path
        if os.path.exists(path):
            break

    if os.path.exists(keyring_cfg):
        config = configparser.RawConfigParser()
        config.read(keyring_cfg)
        _load_keyring_path(config)

        # load the keyring class name, and then load this keyring
        try:
            if config.has_section("backend"):
                keyring_name = config.get("backend", "default-keyring").strip()
            else:
                raise configparser.NoOptionError('backend', 'default-keyring')

            keyring = load_keyring(None, keyring_name)
        except (configparser.NoOptionError, ImportError):
            logger.warning("Keyring config file contains incorrect values.\n" +
                           "Config file: %s" % keyring_cfg)

    return keyring
Beispiel #6
0
def load_config():
    """Load a keyring using the config file.

    The config file can be in the current working directory, or in the user's
    home directory.
    """
    keyring = None

    filename = 'keyringrc.cfg'

    local_path = os.path.join(os.getcwd(), filename)
    config_path = os.path.join(platform.config_root(), filename)

    # search from current working directory and the data root
    keyring_cfg_candidates = [local_path, config_path]

    # initialize the keyring_config with the first detected config file
    keyring_cfg = None
    for path in keyring_cfg_candidates:
        keyring_cfg = path
        if os.path.exists(path):
            break

    if os.path.exists(keyring_cfg):
        config = configparser.RawConfigParser()
        config.read(keyring_cfg)
        _load_keyring_path(config)

        # load the keyring class name, and then load this keyring
        try:
            if config.has_section("backend"):
                keyring_name = config.get("backend", "default-keyring").strip()
            else:
                raise configparser.NoOptionError('backend', 'default-keyring')

            keyring = load_keyring(None, keyring_name)
        except (configparser.NoOptionError, ImportError):
            logger.warning("Keyring config file contains incorrect values.\n" +
                           "Config file: %s" % keyring_cfg)

    return keyring
Beispiel #7
0
def _describe_credentials():
    import keyring
    from keyring.util import platform_

    def describe_keyring_backend(be):
        be_repr = repr(be)
        return be.name if 'object at 0' in be_repr else be_repr.strip('<>')

    # might later add information on non-keyring credentials gh-4981
    props = {}

    active_keyring = keyring.get_keyring()
    krp = {
        'config_file':
        Path(platform_.config_root(), 'keyringrc.cfg'),
        'data_root':
        platform_.data_root(),
        'active_backends': [
            describe_keyring_backend(be)
            for be in getattr(active_keyring, 'backends', [active_keyring])
        ],
    }
    props.update(keyring=krp, )
    return props
Beispiel #8
0
def keyringrc_file():
    return op.join(config_root(), "keyringrc.cfg")
Beispiel #9
0
def keyringrc_file() -> Path:
    return Path(config_root(), "keyringrc.cfg")