def test_new_key(self): # When renewing with both reuse_key and new_key, the key should be regenerated, # the key type, key parameters and reuse_key should be kept. self.config.reuse_key = True self.config.new_key = True self.config.dry_run = True config = configuration.NamespaceConfig(self.config) rc_path = test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') lineage = storage.RenewableCert(rc_path, config) le_client = mock.MagicMock() le_client.obtain_certificate.return_value = (None, None, None, None) from certbot._internal import renewal with mock.patch('certbot._internal.renewal.hooks.renew_hook'): renewal.renew_cert(self.config, None, le_client, lineage) self.assertEqual(self.config.rsa_key_size, 2048) self.assertEqual(self.config.key_type, 'rsa') self.assertTrue(self.config.reuse_key) # None is passed as the existing key, i.e. the key is not actually being reused. le_client.obtain_certificate.assert_called_with(mock.ANY, None)
def main(cli_args=sys.argv[1:]): """Command line argument parsing and main script execution.""" sys.excepthook = functools.partial(_handle_exception, config=None) plugins = plugins_disco.PluginsRegistry.find_all() # note: arg parser internally handles --help (and exits afterwards) args = cli.prepare_and_parse_args(plugins, cli_args) config = configuration.NamespaceConfig(args) zope.component.provideUtility(config) make_or_verify_needed_dirs(config) # Setup logging ASAP, otherwise "No handlers could be found for # logger ..." TODO: this should be done before plugins discovery setup_logging(config) cli.possible_deprecation_warning(config) logger.debug("certbot version: %s", certbot.__version__) # do not log `config`, as it contains sensitive data (e.g. revoke --key)! logger.debug("Arguments: %r", cli_args) logger.debug("Discovered plugins: %r", plugins) sys.excepthook = functools.partial(_handle_exception, config=config) set_displayer(config) # Reporter report = reporter.Reporter(config) zope.component.provideUtility(report) atexit.register(report.atexit_print_messages) return config.func(config, plugins)
def setUp(self): super(BaseCertManagerTest, self).setUp() os.makedirs(os.path.join(self.tempdir, "renewal")) self.cli_config = configuration.NamespaceConfig(mock.MagicMock( config_dir=self.tempdir, work_dir=self.tempdir, logs_dir=self.tempdir, quiet=False, )) self.domains = { "example.org": None, "other.com": os.path.join(self.tempdir, "specialarchive") } self.configs = dict((domain, self._set_up_config(domain, self.domains[domain])) for domain in self.domains) # We also create a file that isn't a renewal config in the same # location to test that logic that reads in all-and-only renewal # configs will ignore it and NOT attempt to parse it. junk = open(os.path.join(self.tempdir, "renewal", "IGNORE.THIS"), "w") junk.write("This file should be ignored!") junk.close()
def main(cli_args=sys.argv[1:]): """Command line argument parsing and main script execution.""" log.pre_arg_parse_setup() plugins = plugins_disco.PluginsRegistry.find_all() logger.debug("certbot version: %s", certbot.__version__) # do not log `config`, as it contains sensitive data (e.g. revoke --key)! logger.debug("Arguments: %r", cli_args) logger.debug("Discovered plugins: %r", plugins) # note: arg parser internally handles --help (and exits afterwards) args = cli.prepare_and_parse_args(plugins, cli_args) config = configuration.NamespaceConfig(args) zope.component.provideUtility(config) log.post_arg_parse_setup(config) make_or_verify_needed_dirs(config) set_displayer(config) # Reporter report = reporter.Reporter(config) zope.component.provideUtility(report) util.atexit_register(report.print_messages) return config.func(config, plugins)
def get_nginx_configurator( config_path, config_dir, work_dir, logs_dir, version=(1, 6, 2)): """Create an Nginx Configurator with the specified options.""" backups = os.path.join(work_dir, "backups") with mock.patch("certbot_nginx.configurator.NginxConfigurator." "config_test"): with mock.patch("certbot_nginx.configurator.util." "exe_exists") as mock_exe_exists: mock_exe_exists.return_value = True config = configurator.NginxConfigurator( config=mock.MagicMock( nginx_server_root=config_path, le_vhost_ext="-le-ssl.conf", config_dir=config_dir, work_dir=work_dir, logs_dir=logs_dir, backup_dir=backups, temp_checkpoint_dir=os.path.join(work_dir, "temp_checkpoints"), in_progress_dir=os.path.join(backups, "IN_PROGRESS"), server="https://acme-server.org:443/new", http01_port=80, https_port=5001, ), name="nginx", version=version) config.prepare() # Provide general config utility. nsconfig = configuration.NamespaceConfig(config.config) zope.component.provideUtility(nsconfig) return config
def main(cli_args=sys.argv[1:]): """Command line argument parsing and main script execution.""" sys.excepthook = functools.partial(_handle_exception, config=None) plugins = plugins_disco.PluginsRegistry.find_all() # note: arg parser internally handles --help (and exits afterwards) args = cli.prepare_and_parse_args(plugins, cli_args) config = configuration.NamespaceConfig(args) zope.component.provideUtility(config) make_or_verify_needed_dirs(config) # Setup logging ASAP, otherwise "No handlers could be found for # logger ..." TODO: this should be done before plugins discovery setup_logging(config) _post_logging_setup(config, plugins, cli_args) sys.excepthook = functools.partial(_handle_exception, config=config) set_displayer(config) # Reporter report = reporter.Reporter(config) zope.component.provideUtility(report) atexit.register(report.atexit_print_messages) return _run_subcommand(config, plugins)
def setUp(self): self.args = mock.MagicMock(account=None, email=None, register_unsafely_without_email=False) self.config = configuration.NamespaceConfig(self.args) self.accs = [mock.MagicMock(id='x'), mock.MagicMock(id='y')] self.account_storage = account.AccountMemoryStorage()
def _call(self): args = 'revoke --cert-path={0}'.format(self.tmp_cert_path).split() plugins = plugins_disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot.main import revoke revoke(config, plugins)
def _call(self): args = '-a webroot -i null -d {0}'.format(self.domain).split() plugins = plugins_disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot.main import run run(config, plugins)
def _prepare_configurator(self) -> None: """Prepares the Nginx plugin for testing""" for k in constants.CLI_DEFAULTS: setattr(self.le_config, "nginx_" + k, constants.os_constant(k)) conf = configuration.NamespaceConfig(self.le_config) self._configurator = configurator.NginxConfigurator(config=conf, name="nginx") self._configurator.prepare()
def setUp(self): super(ConfigTestCase, self).setUp() self.config = configuration.NamespaceConfig( mock.MagicMock( config_dir=os.path.join(self.tempdir, 'config'), work_dir=os.path.join(self.tempdir, 'work'), logs_dir=os.path.join(self.tempdir, 'logs'), server="example.com", ))
def _call(self, args): plugins = plugins_disco.PluginsRegistry.find_all() config = configuration.NamespaceConfig( cli.prepare_and_parse_args(plugins, args)) from certbot import main with mock.patch('certbot.main._init_le_client') as mock_init: main.obtain_cert(config, plugins) return mock_init() # returns the client
def _prepare_configurator(self): """Prepares the Apache plugin for testing""" for k in entrypoint.ENTRYPOINT.OS_DEFAULTS.keys(): setattr(self.le_config, "apache_" + k, entrypoint.ENTRYPOINT.OS_DEFAULTS[k]) self._configurator = entrypoint.ENTRYPOINT( config=configuration.NamespaceConfig(self.le_config), name="apache") self._configurator.prepare()
def setUp(self): super(RenameLineageTest, self).setUp() self.mock_config = configuration.NamespaceConfig( namespace=mock.MagicMock( config_dir=self.tempdir, work_dir=self.tempdir, logs_dir=self.tempdir, certname="example.org", new_certname="after", ))
def _prepare_configurator(self): """Prepares the Nginx plugin for testing""" for k in constants.CLI_DEFAULTS.keys(): setattr(self.le_config, "nginx_" + k, constants.os_constant(k)) conf = configuration.NamespaceConfig(self.le_config) zope.component.provideUtility(conf) self._configurator = configurator.NginxConfigurator(config=conf, name="nginx") self._configurator.prepare()
def test_ancient_webroot_renewal_conf(self, mock_set_by_cli): mock_set_by_cli.return_value = False rc_path = util.make_lineage(self, 'sample-renewal-ancient.conf') args = mock.MagicMock(account=None, email=None, webroot_path=None) config = configuration.NamespaceConfig(args) lineage = storage.RenewableCert(rc_path, config) renewalparams = lineage.configuration['renewalparams'] # pylint: disable=protected-access from certbot import renewal renewal._restore_webroot_config(config, renewalparams) self.assertEqual(config.webroot_path, ['/var/www/'])
def test_ancient_webroot_renewal_conf(self, mock_set_by_cli): mock_set_by_cli.return_value = False rc_path = self._make_test_renewal_conf('sample-renewal-ancient.conf') args = mock.MagicMock(account=None, email=None, webroot_path=None) config = configuration.NamespaceConfig(args) lineage = storage.RenewableCert( rc_path, configuration.RenewerConfiguration(config)) renewalparams = lineage.configuration["renewalparams"] # pylint: disable=protected-access renewal._restore_webroot_config(config, renewalparams) self.assertEqual(config.webroot_path, ["/var/www/"])
def _prepare_configurator(self): """Prepares the Apache plugin for testing""" for k in constants.CLI_DEFAULTS_DEBIAN.keys(): setattr(self.le_config, "apache_" + k, constants.os_constant(k)) # An alias self.le_config.apache_handle_modules = self.le_config.apache_handle_mods self._configurator = configurator.ApacheConfigurator( config=configuration.NamespaceConfig(self.le_config), name="apache") self._configurator.prepare()
def setUp(self): super(ConfigTestCase, self).setUp() self.config = configuration.NamespaceConfig( mock.MagicMock(**constants.CLI_DEFAULTS)) self.config.verb = "certonly" self.config.config_dir = os.path.join(self.tempdir, 'config') self.config.work_dir = os.path.join(self.tempdir, 'work') self.config.logs_dir = os.path.join(self.tempdir, 'logs') self.config.cert_path = constants.CLI_DEFAULTS['auth_cert_path'] self.config.fullchain_path = constants.CLI_DEFAULTS['auth_chain_path'] self.config.chain_path = constants.CLI_DEFAULTS['auth_chain_path'] self.config.server = "https://example.com"
def test_certificates_no_files(self, mock_utility, mock_logger): empty_tempdir = tempfile.mkdtemp() empty_config = configuration.NamespaceConfig( mock.MagicMock(config_dir=os.path.join(empty_tempdir, "config"), work_dir=os.path.join(empty_tempdir, "work"), logs_dir=os.path.join(empty_tempdir, "logs"), quiet=False)) filesystem.makedirs(empty_config.renewal_configs_dir) self._certificates(empty_config) self.assertIs(mock_logger.warning.called, False) self.assertTrue(mock_utility.called) shutil.rmtree(empty_tempdir)
def _prepare_configurator(self, server_root, config_file): """Prepares the Apache plugin for testing""" self.le_config.apache_server_root = server_root self.le_config.apache_ctl = "apachectl -d {0} -f {1}".format( server_root, config_file) self.le_config.apache_enmod = "a2enmod.sh {0}".format(server_root) self.le_config.apache_dismod = "a2dismod.sh {0}".format(server_root) self.le_config.apache_init_script = self.le_config.apache_ctl + " -k" self._apache_configurator = configurator.ApacheConfigurator( config=configuration.NamespaceConfig(self.le_config), name="apache") self._apache_configurator.prepare()
def main(cli_args=sys.argv[1:]): """Command line argument parsing and main script execution.""" sys.excepthook = functools.partial(_handle_exception, config=None) plugins = plugins_disco.PluginsRegistry.find_all() # note: arg parser internally handles --help (and exits afterwards) args = cli.prepare_and_parse_args(plugins, cli_args) config = configuration.NamespaceConfig(args) zope.component.provideUtility(config) # Setup logging ASAP, otherwise "No handlers could be found for # logger ..." TODO: this should be done before plugins discovery for directory in config.config_dir, config.work_dir: le_util.make_or_verify_dir( directory, constants.CONFIG_DIRS_MODE, os.geteuid(), "--strict-permissions" in cli_args) # TODO: logs might contain sensitive data such as contents of the # private key! #525 le_util.make_or_verify_dir( config.logs_dir, 0o700, os.geteuid(), "--strict-permissions" in cli_args) setup_logging(config, _cli_log_handler, logfile='letsencrypt.log') cli.possible_deprecation_warning(config) logger.debug("certbot version: %s", certbot.__version__) # do not log `config`, as it contains sensitive data (e.g. revoke --key)! logger.debug("Arguments: %r", cli_args) logger.debug("Discovered plugins: %r", plugins) sys.excepthook = functools.partial(_handle_exception, config=config) # Displayer if config.quiet: config.noninteractive_mode = True displayer = display_util.NoninteractiveDisplay(open(os.devnull, "w")) elif config.noninteractive_mode: displayer = display_util.NoninteractiveDisplay(sys.stdout) elif config.text_mode: displayer = display_util.FileDisplay(sys.stdout) elif config.verb == "renew": config.noninteractive_mode = True displayer = display_util.NoninteractiveDisplay(sys.stdout) else: displayer = display_util.NcursesDisplay() zope.component.provideUtility(displayer) # Reporter report = reporter.Reporter(config) zope.component.provideUtility(report) atexit.register(report.atexit_print_messages) return config.func(config, plugins)
def main(cli_args=sys.argv[1:]): """Command line argument parsing and main script execution. :returns: result of requested command :raises errors.Error: OS errors triggered by wrong permissions :raises errors.Error: error if plugin command is not supported """ log.pre_arg_parse_setup() plugins = plugins_disco.PluginsRegistry.find_all() logger.debug("certbot version: %s", certbot.__version__) # do not log `config`, as it contains sensitive data (e.g. revoke --key)! logger.debug("Arguments: %r", cli_args) logger.debug("Discovered plugins: %r", plugins) # note: arg parser internally handles --help (and exits afterwards) args = cli.prepare_and_parse_args(plugins, cli_args) config = configuration.NamespaceConfig(args) zope.component.provideUtility(config) try: log.post_arg_parse_setup(config) make_or_verify_needed_dirs(config) except errors.Error: # Let plugins_cmd be run as un-privileged user. if config.func != plugins_cmd: raise deprecation_fmt = ( "Python %s.%s support will be dropped in the next " "release of Certbot - please upgrade your Python version.") # We use the warnings system for Python 2.6 and logging for Python 3 # because DeprecationWarnings are only reported by default in Python <= 2.6 # and warnings can be disabled by the user. if sys.version_info[:2] == (2, 6): warning = deprecation_fmt % sys.version_info[:2] warnings.warn(warning, DeprecationWarning) elif sys.version_info[:2] == (3, 3): logger.warning(deprecation_fmt, *sys.version_info[:2]) set_displayer(config) # Reporter report = reporter.Reporter(config) zope.component.provideUtility(report) util.atexit_register(report.print_messages) return config.func(config, plugins)
def test_certificates_no_files(self, mock_utility, mock_logger): tempdir = tempfile.mkdtemp() cli_config = configuration.NamespaceConfig(mock.MagicMock( config_dir=tempdir, work_dir=tempdir, logs_dir=tempdir, quiet=False, )) os.makedirs(os.path.join(tempdir, "renewal")) self._certificates(cli_config) self.assertFalse(mock_logger.warning.called) #pylint: disable=no-member self.assertTrue(mock_utility.called) shutil.rmtree(tempdir)
def test_remove_deprecated_config_elements(self, mock_set_by_cli, unused_mock_get_utility): mock_set_by_cli.return_value = False config = configuration.NamespaceConfig(self.config) config.certname = "sample-renewal-deprecated-option" rc_path = test_util.make_lineage( self.config.config_dir, 'sample-renewal-deprecated-option.conf') from certbot._internal import renewal lineage_config = copy.deepcopy(self.config) renewal_candidate = renewal._reconstitute(lineage_config, rc_path) # This means that manual_public_ip_logging_ok was not modified in the config based on its # value in the renewal conf file self.assertIsInstance(lineage_config.manual_public_ip_logging_ok, mock.MagicMock)
def setUp(self): from certbot import storage super(BaseRenewableCertTest, self).setUp() self.cli_config = configuration.NamespaceConfig( namespace=mock.MagicMock( config_dir=self.tempdir, work_dir=self.tempdir, logs_dir=self.tempdir, )) # TODO: maybe provide NamespaceConfig.make_dirs? # TODO: main() should create those dirs, c.f. #902 os.makedirs(os.path.join(self.tempdir, "live", "example.org")) archive_path = os.path.join(self.tempdir, "archive", "example.org") os.makedirs(archive_path) os.makedirs(os.path.join(self.tempdir, "renewal")) config = configobj.ConfigObj() for kind in ALL_FOUR: kind_path = os.path.join(self.tempdir, "live", "example.org", kind + ".pem") config[kind] = kind_path with open(os.path.join(self.tempdir, "live", "example.org", "README"), 'a'): pass config["archive"] = archive_path config.filename = os.path.join(self.tempdir, "renewal", "example.org.conf") config.write() self.config = config # We also create a file that isn't a renewal config in the same # location to test that logic that reads in all-and-only renewal # configs will ignore it and NOT attempt to parse it. junk = open(os.path.join(self.tempdir, "renewal", "IGNORE.THIS"), "w") junk.write("This file should be ignored!") junk.close() self.defaults = configobj.ConfigObj() with mock.patch( "certbot.storage.RenewableCert._check_symlinks") as check: check.return_value = True self.test_rc = storage.RenewableCert(config.filename, self.cli_config)
def main(cli_args=None): """Command line argument parsing and main script execution. :returns: result of requested command :raises errors.Error: OS errors triggered by wrong permissions :raises errors.Error: error if plugin command is not supported """ if not cli_args: cli_args = sys.argv[1:] log.pre_arg_parse_setup() plugins = plugins_disco.PluginsRegistry.find_all() logger.debug("certbot version: %s", certbot.__version__) # do not log `config`, as it contains sensitive data (e.g. revoke --key)! logger.debug("Arguments: %r", cli_args) logger.debug("Discovered plugins: %r", plugins) # note: arg parser internally handles --help (and exits afterwards) args = cli.prepare_and_parse_args(plugins, cli_args) config = configuration.NamespaceConfig(args) zope.component.provideUtility(config) # On windows, shell without administrative right cannot create symlinks required by certbot. # So we check the rights before continuing. misc.raise_for_non_administrative_windows_rights() try: log.post_arg_parse_setup(config) make_or_verify_needed_dirs(config) except errors.Error: # Let plugins_cmd be run as un-privileged user. if config.func != plugins_cmd: raise set_displayer(config) # Reporter report = reporter.Reporter(config) zope.component.provideUtility(report) util.atexit_register(report.print_messages) return config.func(config, plugins)
def test_reuse_key_renewal_params(self): self.config.rsa_key_size = 'INVALID_VALUE' self.config.reuse_key = True self.config.dry_run = True config = configuration.NamespaceConfig(self.config) rc_path = test_util.make_lineage(self.config.config_dir, 'sample-renewal.conf') lineage = storage.RenewableCert(rc_path, config) le_client = mock.MagicMock() le_client.obtain_certificate.return_value = (None, None, None, None) from certbot._internal import renewal with mock.patch('certbot._internal.renewal.hooks.renew_hook'): renewal.renew_cert(self.config, None, le_client, lineage) assert self.config.rsa_key_size == 2048
def setup_method(self, method): self.name = 'certbot-vault-installer' self.name_cfg = self.name.replace('-', '_') + '_' self.tempdir = tempfile.mkdtemp(dir=tempfile.gettempdir()) self.config = configuration.NamespaceConfig( mock.MagicMock(**constants.CLI_DEFAULTS)) self.config.verb = "certonly" self.config.config_dir = os.path.join(self.tempdir, 'config') self.config.work_dir = os.path.join(self.tempdir, 'work') self.config.logs_dir = os.path.join(self.tempdir, 'logs') self.config.cert_path = constants.CLI_DEFAULTS['auth_cert_path'] self.config.fullchain_path = constants.CLI_DEFAULTS['auth_chain_path'] self.config.chain_path = constants.CLI_DEFAULTS['auth_chain_path'] self.config.server = "example.com" self.config.__setattr__(self.name_cfg + 'vault-url', "http://localhost:8200") self.config.__setattr__(self.name_cfg + 'vault-url', "testike") self.subject = Installer(self.config, self.name) self.subject.hvac_client.write = mock.MagicMock(hvac.Client)
def setup_method(self, method): # Setup fake redis for testing. self.r = fakeredis.FakeStrictRedis() self.name = 'certbot-redis-auth' self.name_cfg = self.name.replace('-', '_') + '_' self.tempdir = tempfile.mkdtemp(dir=tempfile.gettempdir()) self.config = configuration.NamespaceConfig( mock.MagicMock(**constants.CLI_DEFAULTS)) self.config.verb = "certonly" self.config.config_dir = os.path.join(self.tempdir, 'config') self.config.work_dir = os.path.join(self.tempdir, 'work') self.config.logs_dir = os.path.join(self.tempdir, 'logs') self.config.cert_path = constants.CLI_DEFAULTS['auth_cert_path'] self.config.fullchain_path = constants.CLI_DEFAULTS['auth_chain_path'] self.config.chain_path = constants.CLI_DEFAULTS['auth_chain_path'] self.config.server = "example.com" self.config.__setattr__(self.name_cfg + 'redis_url', "redis://test:42") self.subject = Authenticator(self.config, self.name) self.subject.redis_client = self.r self.http_chall = acme_util.ACHALLENGES[0] # Http Chall