Beispiel #1
0
    def _test_obtain_certificate_common(self, key, csr):
        self._mock_obtain_certificate()

        # return_value is essentially set to (None, None) in
        # _mock_obtain_certificate(), which breaks this test.
        # Thus fixed by the next line.

        authzr = []

        # domain ordering should not be affected by authorization order
        for domain in reversed(self.eg_domains):
            authzr.append(
                mock.MagicMock(
                    body=mock.MagicMock(
                        identifier=mock.MagicMock(
                            value=domain))))

        self.client.auth_handler.get_authorizations.return_value = authzr

        with test_util.patch_get_utility():
            result = self.client.obtain_certificate(self.eg_domains)

        self.assertEqual(
            result,
            (mock.sentinel.certr, mock.sentinel.chain, key, csr))
        self._check_obtain_certificate()
Beispiel #2
0
    def setUp(self):
        super().setUp()
        get_utility_patch = test_util.patch_get_utility()
        self.mock_get_utility = get_utility_patch.start()
        self.addCleanup(get_utility_patch.stop)

        self.http_achall = acme_util.HTTP01_A
        self.dns_achall = acme_util.DNS01_A
        self.dns_achall_2 = acme_util.DNS01_A_2
        self.achalls = [self.http_achall, self.dns_achall, self.dns_achall_2]
        for d in ["config_dir", "work_dir", "in_progress"]:
            filesystem.mkdir(os.path.join(self.tempdir, d))
            # "backup_dir" and "temp_checkpoint_dir" get created in
            # certbot.util.make_or_verify_dir() during the Reverter
            # initialization.
        self.config = mock.MagicMock(
            http01_port=0,
            manual_auth_hook=None,
            manual_cleanup_hook=None,
            noninteractive_mode=False,
            validate_hooks=False,
            config_dir=os.path.join(self.tempdir, "config_dir"),
            work_dir=os.path.join(self.tempdir, "work_dir"),
            backup_dir=os.path.join(self.tempdir, "backup_dir"),
            temp_checkpoint_dir=os.path.join(self.tempdir,
                                             "temp_checkpoint_dir"),
            in_progress_dir=os.path.join(self.tempdir, "in_progess"))

        from certbot._internal.plugins.manual import Authenticator
        self.auth = Authenticator(self.config, name='manual')
Beispiel #3
0
    def test_best_effort(self):
        def _conditional_mock_on_poll(authzr):
            """This mock will invalidate one authzr, and invalidate the other one"""
            valid_mock = _gen_mock_on_poll(messages.STATUS_VALID)
            invalid_mock = _gen_mock_on_poll(messages.STATUS_INVALID)

            if authzr.body.identifier.value == 'will-be-invalid':
                return invalid_mock(authzr)
            return valid_mock(authzr)

        # Two authzrs. Only one will be valid.
        authzrs = [gen_dom_authzr(domain="will-be-valid", challs=acme_util.CHALLENGES),
                   gen_dom_authzr(domain="will-be-invalid", challs=acme_util.CHALLENGES)]
        self.mock_net.poll.side_effect = _conditional_mock_on_poll

        mock_order = mock.MagicMock(authorizations=authzrs)

        with mock.patch('certbot.auth_handler._report_failed_authzrs') as mock_report:
            valid_authzr = self.handler.handle_authorizations(mock_order, True)

        # Because best_effort=True, we did not blow up. Instead ...
        self.assertEqual(len(valid_authzr), 1)  # ... the valid authzr has been processed
        self.assertEqual(mock_report.call_count, 1)  # ... the invalid authzr has been reported

        self.mock_net.poll.side_effect = _gen_mock_on_poll(status=messages.STATUS_INVALID)

        with test_util.patch_get_utility():
            with self.assertRaises(errors.AuthorizationError) as error:
                self.handler.handle_authorizations(mock_order, True)

        # Despite best_effort=True, process will fail because no authzr is valid.
        self.assertTrue('All challenges have failed.' in str(error.exception))
Beispiel #4
0
    def test_incomplete_authzr_error(self):
        authzrs = [gen_dom_authzr(domain="0", challs=acme_util.CHALLENGES)]
        mock_order = mock.MagicMock(authorizations=authzrs)
        self.mock_net.poll.side_effect = _gen_mock_on_poll(status=messages.STATUS_INVALID)

        with test_util.patch_get_utility():
            with self.assertRaises(errors.AuthorizationError) as error:
                self.handler.handle_authorizations(mock_order, False)
        self.assertTrue('Some challenges have failed.' in str(error.exception))
        self.assertEqual(self.mock_auth.cleanup.call_count, 1)
        self.assertEqual(
            self.mock_auth.cleanup.call_args[0][0][0].typ, "tls-sni-01")
Beispiel #5
0
    def _test_error(self, enhance_error=False, restart_error=False):
        self.config.redirect = True
        with mock.patch('certbot._internal.client.logger') as mock_logger, \
             test_util.patch_get_utility() as mock_gu:
            self.assertRaises(errors.PluginError,
                              self._test_with_all_supported)

        if enhance_error:
            self.assertEqual(mock_logger.error.call_count, 1)
            self.assertIn('Unable to set enhancement',
                          mock_logger.error.call_args_list[0][0][0])
        if restart_error:
            mock_logger.critical.assert_called_with(
                'Rolling back to previous server configuration...')
Beispiel #6
0
    def _help_output(self, args):
        "Run a command, and return the output string for scrutiny"

        output = six.StringIO()

        def write_msg(message, *args, **kwargs): # pylint: disable=missing-docstring,unused-argument
            output.write(message)

        with mock.patch('certbot.main.sys.stdout', new=output):
            with test_util.patch_get_utility() as mock_get_utility:
                mock_get_utility().notification.side_effect = write_msg
                with mock.patch('certbot.main.sys.stderr'):
                    self.assertRaises(SystemExit, self._unmocked_parse, args, output)

        return output.getvalue()
Beispiel #7
0
    def _help_output(self, args):
        "Run a command, and return the output string for scrutiny"

        output = six.StringIO()

        def write_msg(message, *args, **kwargs): # pylint: disable=missing-docstring,unused-argument
            output.write(message)

        with mock.patch('certbot.main.sys.stdout', new=output):
            with test_util.patch_get_utility() as mock_get_utility:
                mock_get_utility().notification.side_effect = write_msg
                with mock.patch('certbot.main.sys.stderr'):
                    self.assertRaises(SystemExit, self._unmocked_parse, args, output)

        return output.getvalue()
Beispiel #8
0
    def test_obtain_certificate_dry_run_authz_deactivations_failed(
            self, mock_acme_crypto, mock_crypto, mock_log):
        from acme import messages
        csr = util.CSR(form="pem", file=None, data=CSR_SAN)
        mock_acme_crypto.make_csr.return_value = CSR_SAN
        mock_crypto.make_key.return_value = mock.sentinel.key_pem
        key = util.Key(file=None, pem=mock.sentinel.key_pem)
        self._set_mock_from_fullchain(
            mock_crypto.cert_and_chain_from_fullchain)

        self._mock_obtain_certificate()
        self.client.config.dry_run = True

        # Two authzs that are already valid and should get deactivated (dry run)
        authzrs = self._authzr_from_domains(["example.com", "www.example.com"])
        for authzr in authzrs:
            authzr.body.status = messages.STATUS_VALID

        # One deactivation succeeds, one fails
        auth_handler = self.client.auth_handler
        auth_handler.deactivate_valid_authorizations.return_value = ([
            authzrs[0]
        ], [authzrs[1]])

        # Certificate should get issued despite one failed deactivation
        self.eg_order.authorizations = authzrs
        self.client.auth_handler.handle_authorizations.return_value = authzrs
        with test_util.patch_get_utility():
            result = self.client.obtain_certificate(self.eg_domains)
        self.assertEqual(result,
                         (mock.sentinel.cert, mock.sentinel.chain, key, csr))
        self._check_obtain_certificate(1)

        # Deactivation success/failure should have been handled properly
        self.assertEqual(
            auth_handler.deactivate_valid_authorizations.call_count, 1,
            "Deactivate authorizations should be called")
        self.assertEqual(
            self.acme.new_order.call_count, 2,
            "Order should be recreated due to successfully deactivated authorizations"
        )
        mock_log.warning.assert_called_with(
            "Certbot was unable to obtain fresh authorizations for"
            " every domain. The dry run will continue, but results"
            " may not be accurate.")
Beispiel #9
0
    def _test_obtain_certificate_common(self, key, csr, authzr_ret=None, auth_count=1):
        self._mock_obtain_certificate()

        # return_value is essentially set to (None, None) in
        # _mock_obtain_certificate(), which breaks this test.
        # Thus fixed by the next line.
        authzr = authzr_ret or self._authzr_from_domains(self.eg_domains)

        self.eg_order.authorizations = authzr
        self.client.auth_handler.handle_authorizations.return_value = authzr

        with test_util.patch_get_utility():
            result = self.client.obtain_certificate(self.eg_domains)

        self.assertEqual(
            result,
            (mock.sentinel.cert, mock.sentinel.chain, key, csr))
        self._check_obtain_certificate(auth_count)
Beispiel #10
0
    def _test_obtain_certificate_common(self, key, csr, authzr_ret=None, auth_count=1):
        self._mock_obtain_certificate()

        # return_value is essentially set to (None, None) in
        # _mock_obtain_certificate(), which breaks this test.
        # Thus fixed by the next line.
        authzr = authzr_ret or self._authzr_from_domains(self.eg_domains)

        self.eg_order.authorizations = authzr
        self.client.auth_handler.handle_authorizations.return_value = authzr

        with test_util.patch_get_utility():
            result = self.client.obtain_certificate(self.eg_domains)

        self.assertEqual(
            result,
            (mock.sentinel.cert, mock.sentinel.chain, key, csr))
        self._check_obtain_certificate(auth_count)
Beispiel #11
0
    def _test_obtain_certificate_common(self, key, csr):
        self._mock_obtain_certificate()

        # return_value is essentially set to (None, None) in
        # _mock_obtain_certificate(), which breaks this test.
        # Thus fixed by the next line.

        authzr = []

        # domain ordering should not be affected by authorization order
        for domain in reversed(self.eg_domains):
            authzr.append(
                mock.MagicMock(body=mock.MagicMock(identifier=mock.MagicMock(
                    value=domain))))

        self.client.auth_handler.get_authorizations.return_value = authzr

        with test_util.patch_get_utility():
            result = self.client.obtain_certificate(self.eg_domains)

        self.assertEqual(result,
                         (mock.sentinel.certr, mock.sentinel.chain, key, csr))
        self._check_obtain_certificate()
 def setUp(self):
     get_utility_patch = test_util.patch_get_utility()
     self.mock_get_utility = get_utility_patch.start()
     self.addCleanup(get_utility_patch.stop)
     self.config = mock.MagicMock()
     self.config.certname = None
Beispiel #13
0
 def parse(*args, **kwargs):
     """Mocks zope.component.getUtility and calls _unmocked_parse."""
     with test_util.patch_get_utility():
         return ParseTest._unmocked_parse(*args, **kwargs)
Beispiel #14
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)
 def setUp(self):
     self.get_utility_patch = test_util.patch_get_utility()
     self.mock_get_utility = self.get_utility_patch.start()
     self.config = mock.MagicMock()
     self.config.certname = None
Beispiel #16
0
 def parse(*args, **kwargs):
     """Mocks zope.component.getUtility and calls _unmocked_parse."""
     with test_util.patch_get_utility():
         return ParseTest._unmocked_parse(*args, **kwargs)
Beispiel #17
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)
Beispiel #18
0
 def setUp(self):
     self.get_utility_patch = test_util.patch_get_utility()
     self.mock_get_utility = self.get_utility_patch.start()
     self.config = mock.MagicMock()
     self.config.certname = None
Beispiel #19
0
 def _test_error(self):
     self.config.redirect = True
     with test_util.patch_get_utility() as mock_gu:
         self.assertRaises(
             errors.PluginError, self._test_with_all_supported)
     self.assertEqual(mock_gu().add_message.call_count, 1)
Beispiel #20
0
 def _test_error(self):
     self.config.redirect = True
     with test_util.patch_get_utility() as mock_gu:
         self.assertRaises(
             errors.PluginError, self._test_with_all_supported)
     self.assertEqual(mock_gu().add_message.call_count, 1)
 def test_no_subscribe_with_no_prompt(self, mock_subscribe):
     self.config.eff_email = False
     with test_util.patch_get_utility() as mock_get_utility:
         self._call()
     self.assertFalse(mock_subscribe.called)
     self._assert_no_get_utility_calls(mock_get_utility)