Esempio n. 1
0
def _restore_required_config_elements(config, renewalparams):
    """Sets non-plugin specific values in config from renewalparams

    :param configuration.NamespaceConfig config: configuration for the
        current lineage
    :param configobj.Section renewalparams: parameters from the renewal
        configuration file that defines this lineage

    """
    # string-valued items to add if they're present
    for config_item in STR_CONFIG_ITEMS:
        if config_item in renewalparams and not cli.set_by_cli(config_item):
            value = renewalparams[config_item]
            # Unfortunately, we've lost type information from ConfigObj,
            # so we don't know if the original was NoneType or str!
            if value == "None":
                value = None
            setattr(config.namespace, config_item, value)
    # int-valued items to add if they're present
    for config_item in INT_CONFIG_ITEMS:
        if config_item in renewalparams and not cli.set_by_cli(config_item):
            config_value = renewalparams[config_item]
            # the default value for http01_port was None during private beta
            if config_item == "http01_port" and config_value == "None":
                logger.info("updating legacy http01_port value")
                int_value = cli.flag_default("http01_port")
            else:
                try:
                    int_value = int(config_value)
                except ValueError:
                    raise errors.Error(
                        "Expected a numeric value for {0}".format(config_item))
            setattr(config.namespace, config_item, int_value)
Esempio n. 2
0
def _restore_webroot_config(config, renewalparams):
    """
    webroot_map is, uniquely, a dict, and the general-purpose configuration
    restoring logic is not able to correctly parse it from the serialized
    form.
    """
    if "webroot_map" in renewalparams and not cli.set_by_cli("webroot_map"):
        config.webroot_map = renewalparams["webroot_map"]
    # To understand why webroot_path and webroot_map processing are not mutually exclusive,
    # see https://github.com/certbot/certbot/pull/7095
    if "webroot_path" in renewalparams and not cli.set_by_cli("webroot_path"):
        wp = renewalparams["webroot_path"]
        if isinstance(wp, six.string_types):  # prior to 0.1.0, webroot_path was a string
            wp = [wp]
        config.webroot_path = wp
Esempio n. 3
0
def supported_challenges_validator(data):
    """Supported challenges validator for the `argparse`.

    It should be passed as `type` argument to `add_argument`.

    """
    if cli.set_by_cli("standalone_supported_challenges"):
        sys.stderr.write(
            "WARNING: The standalone specific "
            "supported challenges flag is deprecated.\n"
            "Please use the --preferred-challenges flag instead.\n")
    challs = data.split(",")

    # tls-sni-01 was dvsni during private beta
    if "dvsni" in challs:
        logger.info("Updating legacy standalone_supported_challenges value")
        challs = [challenges.TLSSNI01.typ if chall == "dvsni" else chall
                  for chall in challs]
        data = ",".join(challs)

    unrecognized = [name for name in challs
                    if name not in challenges.Challenge.TYPES]
    if unrecognized:
        raise argparse.ArgumentTypeError(
            "Unrecognized challenges: {0}".format(", ".join(unrecognized)))

    choices = set(chall.typ for chall in SUPPORTED_CHALLENGES)
    if not set(challs).issubset(choices):
        raise argparse.ArgumentTypeError(
            "Plugin does not support the following (valid) "
            "challenges: {0}".format(", ".join(set(challs) - choices)))

    return data
Esempio n. 4
0
def relevant_values(all_values):
    """Return a new dict containing only items relevant for renewal.

    :param dict all_values: The original values.

    :returns: A new dictionary containing items that can be used in renewal.
    :rtype dict:"""

    from certbot import cli

    def _is_cli_default(option, value):
        # Look through the CLI parser defaults and see if this option is
        # both present and equal to the specified value. If not, return
        # False.
        # pylint: disable=protected-access
        for x in cli.helpful_parser.parser._actions:
            if x.dest == option:
                if x.default == value:
                    return True
                else:
                    break
        return False

    values = dict()
    for option, value in all_values.iteritems():
        # Try to find reasons to store this item in the
        # renewal config.  It can be stored if it is relevant and
        # (it is set_by_cli() or flag_default() is different
        # from the value or flag_default() doesn't exist).
        if _relevant(option):
            if (cli.set_by_cli(option) or not _is_cli_default(option, value)):
                #                or option not in constants.CLI_DEFAULTS
                #                or constants.CLI_DEFAULTS[option] != value):
                values[option] = value
    return values
Esempio n. 5
0
def supported_challenges_validator(data):
    """Supported challenges validator for the `argparse`.

    It should be passed as `type` argument to `add_argument`.

    """
    if cli.set_by_cli("standalone_supported_challenges"):
        sys.stderr.write(
            "WARNING: The standalone specific "
            "supported challenges flag is deprecated.\n"
            "Please use the --preferred-challenges flag instead.\n")
    challs = data.split(",")

    # tls-sni-01 was dvsni during private beta
    if "dvsni" in challs:
        logger.info("Updating legacy standalone_supported_challenges value")
        challs = [challenges.TLSSNI01.typ if chall == "dvsni" else chall
                  for chall in challs]
        data = ",".join(challs)

    unrecognized = [name for name in challs
                    if name not in challenges.Challenge.TYPES]
    if unrecognized:
        raise argparse.ArgumentTypeError(
            "Unrecognized challenges: {0}".format(", ".join(unrecognized)))

    choices = set(chall.typ for chall in SUPPORTED_CHALLENGES)
    if not set(challs).issubset(choices):
        raise argparse.ArgumentTypeError(
            "Plugin does not support the following (valid) "
            "challenges: {0}".format(", ".join(set(challs) - choices)))

    return data
Esempio n. 6
0
def _restore_webroot_config(config, renewalparams):
    """
    webroot_map is, uniquely, a dict, and the general-purpose configuration
    restoring logic is not able to correctly parse it from the serialized
    form.
    """
    if "webroot_map" in renewalparams:
        if not cli.set_by_cli("webroot_map"):
            config.namespace.webroot_map = renewalparams["webroot_map"]
    elif "webroot_path" in renewalparams:
        logger.debug("Ancient renewal conf file without webroot-map, restoring webroot-path")
        wp = renewalparams["webroot_path"]
        if isinstance(wp, str):  # prior to 0.1.0, webroot_path was a string
            wp = [wp]
        config.namespace.webroot_path = wp
Esempio n. 7
0
def _open_pem_file(cli_arg_path, pem_path):
    """Open a pem file.

    If cli_arg_path was set by the client, open that.
    Otherwise, uniquify the file path.

    :param str cli_arg_path: the cli arg name, e.g. cert_path
    :param str pem_path: the pem file path to open

    :returns: a tuple of file object and its absolute file path

    """
    if cli.set_by_cli(cli_arg_path):
        return util.safe_open(pem_path, chmod=0o644, mode="wb"),\
            os.path.abspath(pem_path)
    uniq = util.unique_file(pem_path, 0o644, "wb")
    return uniq[0], os.path.abspath(uniq[1])
Esempio n. 8
0
def _open_pem_file(cli_arg_path, pem_path):
    """Open a pem file.

    If cli_arg_path was set by the client, open that.
    Otherwise, uniquify the file path.

    :param str cli_arg_path: the cli arg name, e.g. cert_path
    :param str pem_path: the pem file path to open

    :returns: a tuple of file object and its absolute file path

    """
    if cli.set_by_cli(cli_arg_path):
        return util.safe_open(pem_path, chmod=0o644, mode="wb"),\
            os.path.abspath(pem_path)
    uniq = util.unique_file(pem_path, 0o644, "wb")
    return uniq[0], os.path.abspath(uniq[1])
Esempio n. 9
0
def restore_required_config_elements(config, renewalparams):
    """Sets non-plugin specific values in config from renewalparams

    :param configuration.NamespaceConfig config: configuration for the
        current lineage
    :param configobj.Section renewalparams: parameters from the renewal
        configuration file that defines this lineage

    """

    required_items = itertools.chain(
        six.moves.zip(BOOL_CONFIG_ITEMS, itertools.repeat(_restore_bool)),
        six.moves.zip(INT_CONFIG_ITEMS, itertools.repeat(_restore_int)),
        six.moves.zip(STR_CONFIG_ITEMS, itertools.repeat(_restore_str)))
    for item_name, restore_func in required_items:
        if item_name in renewalparams and not cli.set_by_cli(item_name):
            value = restore_func(item_name, renewalparams[item_name])
            setattr(config.namespace, item_name, value)
Esempio n. 10
0
def restore_required_config_elements(config, renewalparams):
    """Sets non-plugin specific values in config from renewalparams

    :param configuration.NamespaceConfig config: configuration for the
        current lineage
    :param configobj.Section renewalparams: parameters from the renewal
        configuration file that defines this lineage

    """

    required_items = itertools.chain(
        (("pref_challs", _restore_pref_challs),),
        six.moves.zip(BOOL_CONFIG_ITEMS, itertools.repeat(_restore_bool)),
        six.moves.zip(INT_CONFIG_ITEMS, itertools.repeat(_restore_int)),
        six.moves.zip(STR_CONFIG_ITEMS, itertools.repeat(_restore_str)))
    for item_name, restore_func in required_items:
        if item_name in renewalparams and not cli.set_by_cli(item_name):
            value = restore_func(item_name, renewalparams[item_name])
            setattr(config.namespace, item_name, value)
Esempio n. 11
0
def _restore_plugin_configs(config, renewalparams):
    """Sets plugin specific values in config from renewalparams

    :param configuration.NamespaceConfig config: configuration for the
        current lineage
    :param configobj.Section renewalparams: Parameters from the renewal
        configuration file that defines this lineage

    """
    # Now use parser to get plugin-prefixed items with correct types
    # XXX: the current approach of extracting only prefixed items
    #      related to the actually-used installer and authenticator
    #      works as long as plugins don't need to read plugin-specific
    #      variables set by someone else (e.g., assuming Apache
    #      configurator doesn't need to read webroot_ variables).
    # Note: if a parameter that used to be defined in the parser is no
    #      longer defined, stored copies of that parameter will be
    #      deserialized as strings by this logic even if they were
    #      originally meant to be some other type.
    plugin_prefixes = []  # type: List[str]
    if renewalparams["authenticator"] == "webroot":
        _restore_webroot_config(config, renewalparams)
    else:
        plugin_prefixes.append(renewalparams["authenticator"])

    if renewalparams.get("installer") is not None:
        plugin_prefixes.append(renewalparams["installer"])

    for plugin_prefix in set(plugin_prefixes):
        plugin_prefix = plugin_prefix.replace('-', '_')
        for config_item, config_value in six.iteritems(renewalparams):
            if config_item.startswith(plugin_prefix +
                                      "_") and not cli.set_by_cli(config_item):
                # Values None, True, and False need to be treated specially,
                # As their types aren't handled correctly by configobj
                if config_value in ("None", "True", "False"):
                    # bool("False") == True
                    # pylint: disable=eval-used
                    setattr(config, config_item, eval(config_value))
                else:
                    cast = cli.argparse_type(config_item)
                    setattr(config, config_item, cast(config_value))
Esempio n. 12
0
def _restore_plugin_configs(config, renewalparams):
    """Sets plugin specific values in config from renewalparams

    :param configuration.NamespaceConfig config: configuration for the
        current lineage
    :param configobj.Section renewalparams: Parameters from the renewal
        configuration file that defines this lineage

    """
    # Now use parser to get plugin-prefixed items with correct types
    # XXX: the current approach of extracting only prefixed items
    #      related to the actually-used installer and authenticator
    #      works as long as plugins don't need to read plugin-specific
    #      variables set by someone else (e.g., assuming Apache
    #      configurator doesn't need to read webroot_ variables).
    # Note: if a parameter that used to be defined in the parser is no
    #      longer defined, stored copies of that parameter will be
    #      deserialized as strings by this logic even if they were
    #      originally meant to be some other type.
    plugin_prefixes = []  # type: List[str]
    if renewalparams["authenticator"] == "webroot":
        _restore_webroot_config(config, renewalparams)
    else:
        plugin_prefixes.append(renewalparams["authenticator"])

    if renewalparams.get("installer") is not None:
        plugin_prefixes.append(renewalparams["installer"])

    for plugin_prefix in set(plugin_prefixes):
        plugin_prefix = plugin_prefix.replace('-', '_')
        for config_item, config_value in six.iteritems(renewalparams):
            if config_item.startswith(plugin_prefix + "_") and not cli.set_by_cli(config_item):
                # Values None, True, and False need to be treated specially,
                # As their types aren't handled correctly by configobj
                if config_value in ("None", "True", "False"):
                    # bool("False") == True
                    # pylint: disable=eval-used
                    setattr(config, config_item, eval(config_value))
                else:
                    cast = cli.argparse_type(config_item)
                    setattr(config, config_item, cast(config_value))
Esempio n. 13
0
def relevant_values(all_values):
    """Return a new dict containing only items relevant for renewal.

    :param dict all_values: The original values.

    :returns: A new dictionary containing items that can be used in renewal.
    :rtype dict:"""

    from certbot import cli

    def _is_cli_default(option, value):
        # Look through the CLI parser defaults and see if this option is
        # both present and equal to the specified value. If not, return
        # False.
        # pylint: disable=protected-access
        for x in cli.helpful_parser.parser._actions:
            if x.dest == option:
                if x.default == value:
                    return True
                else:
                    break
        return False

    values = dict()
    for option, value in all_values.iteritems():
        # Try to find reasons to store this item in the
        # renewal config.  It can be stored if it is relevant and
        # (it is set_by_cli() or flag_default() is different
        # from the value or flag_default() doesn't exist).
        if _relevant(option):
            if (cli.set_by_cli(option)
                or not _is_cli_default(option, value)):
#                or option not in constants.CLI_DEFAULTS
#                or constants.CLI_DEFAULTS[option] != value):
                values[option] = value
    return values
Esempio n. 14
0
def _call_set_by_cli(var, args, verb):
    with mock.patch('certbot.cli.helpful_parser') as mock_parser:
        mock_parser.args = args
        mock_parser.verb = verb
        return cli.set_by_cli(var)
Esempio n. 15
0
def _call_set_by_cli(var, args, verb):
    with mock.patch('certbot.cli.helpful_parser') as mock_parser:
        with test_util.patch_get_utility():
            mock_parser.args = args
            mock_parser.verb = verb
            return cli.set_by_cli(var)
Esempio n. 16
0
def _call_set_by_cli(var, args, verb):
    with mock.patch("certbot.cli.helpful_parser") as mock_parser:
        mock_parser.args = args
        mock_parser.verb = verb
        return cli.set_by_cli(var)