コード例 #1
0
ファイル: storage_test.py プロジェクト: M69W/letsencrypt
    def test_names(self):
        # Trying the current version
        test_cert = test_util.load_vector("cert-san.pem")
        os.symlink(
            os.path.join("..", "..", "archive", "example.org", "cert12.pem"),
            self.test_rc.cert)
        with open(self.test_rc.cert, "w") as f:
            f.write(test_cert)
        self.assertEqual(self.test_rc.names(),
                         ["example.com", "www.example.com"])

        # Trying a non-current version
        test_cert = test_util.load_vector("cert.pem")
        os.unlink(self.test_rc.cert)
        os.symlink(
            os.path.join("..", "..", "archive", "example.org", "cert15.pem"),
            self.test_rc.cert)
        with open(self.test_rc.cert, "w") as f:
            f.write(test_cert)
        self.assertEqual(self.test_rc.names(12),
                         ["example.com", "www.example.com"])

        # Trying missing cert
        os.unlink(self.test_rc.cert)
        self.assertRaises(errors.CertStorageError, self.test_rc.names)
コード例 #2
0
    def test_save_certificate(self):
        certs = ["matching_cert.pem", "cert.pem", "cert-san.pem"]
        tmp_path = tempfile.mkdtemp()
        os.chmod(tmp_path, 0o755)  # TODO: really??

        certr = mock.MagicMock(body=test_util.load_comparable_cert(certs[0]))
        chain_cert = [test_util.load_comparable_cert(certs[1]),
                      test_util.load_comparable_cert(certs[2])]
        candidate_cert_path = os.path.join(tmp_path, "certs", "cert.pem")
        candidate_chain_path = os.path.join(tmp_path, "chains", "chain.pem")
        candidate_fullchain_path = os.path.join(tmp_path, "chains", "fullchain.pem")

        cert_path, chain_path, fullchain_path = self.client.save_certificate(
            certr, chain_cert, candidate_cert_path, candidate_chain_path,
            candidate_fullchain_path)

        self.assertEqual(os.path.dirname(cert_path),
                         os.path.dirname(candidate_cert_path))
        self.assertEqual(os.path.dirname(chain_path),
                         os.path.dirname(candidate_chain_path))
        self.assertEqual(os.path.dirname(fullchain_path),
                         os.path.dirname(candidate_fullchain_path))

        with open(cert_path, "r") as cert_file:
            cert_contents = cert_file.read()
        self.assertEqual(cert_contents, test_util.load_vector(certs[0]))

        with open(chain_path, "r") as chain_file:
            chain_contents = chain_file.read()
        self.assertEqual(chain_contents, test_util.load_vector(certs[1]) +
                         test_util.load_vector(certs[2]))

        shutil.rmtree(tmp_path)
コード例 #3
0
ファイル: cli_test.py プロジェクト: UFHH01/certbot
    def test_find_duplicative_names(self, unused_makedir):
        from certbot.main import _find_duplicative_certs
        test_cert = test_util.load_vector('cert-san.pem')
        with open(self.test_rc.cert, 'w') as f:
            f.write(test_cert)

        # No overlap at all
        result = _find_duplicative_certs(self.cli_config,
                                         ['wow.net', 'hooray.org'])
        self.assertEqual(result, (None, None))

        # Totally identical
        result = _find_duplicative_certs(self.cli_config,
                                         ['example.com', 'www.example.com'])
        self.assertTrue(
            result[0].configfile.filename.endswith('example.org.conf'))
        self.assertEqual(result[1], None)

        # Superset
        result = _find_duplicative_certs(
            self.cli_config,
            ['example.com', 'www.example.com', 'something.new'])
        self.assertEqual(result[0], None)
        self.assertTrue(
            result[1].configfile.filename.endswith('example.org.conf'))

        # Partial overlap doesn't count
        result = _find_duplicative_certs(self.cli_config,
                                         ['example.com', 'something.new'])
        self.assertEqual(result, (None, None))
コード例 #4
0
ファイル: common_test.py プロジェクト: DownMoney/certbot
    def test_setup_challenge_cert(self):
        # This is a helper function that can be used for handling
        # open context managers more elegantly. It avoids dealing with
        # __enter__ and __exit__ calls.
        # http://www.voidspace.org.uk/python/mock/helpers.html#mock.mock_open
        mock_open, mock_safe_open = mock.mock_open(), mock.mock_open()

        response = challenges.TLSSNI01Response()
        achall = mock.MagicMock()
        key = test_util.load_pyopenssl_private_key("rsa512_key.pem")
        achall.response_and_validation.return_value = (
            response, (test_util.load_cert("cert.pem"), key))

        with mock.patch("certbot.plugins.common.open",
                        mock_open, create=True):
            with mock.patch("certbot.plugins.common.util.safe_open",
                            mock_safe_open):
                # pylint: disable=protected-access
                self.assertEqual(response, self.sni._setup_challenge_cert(
                    achall, "randomS1"))

        # pylint: disable=no-member
        mock_open.assert_called_once_with(self.sni.get_cert_path(achall), "wb")
        mock_open.return_value.write.assert_called_once_with(
            test_util.load_vector("cert.pem"))
        mock_safe_open.assert_called_once_with(
            self.sni.get_key_path(achall), "wb", chmod=0o400)
        mock_safe_open.return_value.write.assert_called_once_with(
            OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key))
コード例 #5
0
    def test_names(self):
        # Trying the current version
        self._write_out_kind("cert", 12, test_util.load_vector("cert-san.pem"))
        self.assertEqual(self.test_rc.names(), ["example.com", "www.example.com"])

        # Trying a non-current version
        self._write_out_kind("cert", 15, test_util.load_vector("cert.pem"))
        self.assertEqual(self.test_rc.names(12), ["example.com", "www.example.com"])

        # Testing common name is listed first
        self._write_out_kind("cert", 12, test_util.load_vector("cert-5sans.pem"))
        self.assertEqual(self.test_rc.names(12), ["example.com"] + ["{0}.example.com".format(c) for c in "abcd"])

        # Trying missing cert
        os.unlink(self.test_rc.cert)
        self.assertRaises(errors.CertStorageError, self.test_rc.names)
コード例 #6
0
    def test_perform2(self):
        domain = b"localhost"
        key = jose.JWK.load(test_util.load_vector("rsa512_key.pem"))
        http_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.HTTP01_P, domain=domain, account_key=key
        )
        tls_sni_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.TLSSNI01_P, domain=domain, account_key=key
        )

        self.auth.servers = mock.MagicMock()

        def _run(port, tls):  # pylint: disable=unused-argument
            return "server{0}".format(port)

        self.auth.servers.run.side_effect = _run
        responses = self.auth.perform2([http_01, tls_sni_01])

        self.assertTrue(isinstance(responses, list))
        self.assertEqual(2, len(responses))
        self.assertTrue(isinstance(responses[0], challenges.HTTP01Response))
        self.assertTrue(isinstance(responses[1], challenges.TLSSNI01Response))

        self.assertEqual(
            self.auth.servers.run.mock_calls, [mock.call(4321, challenges.HTTP01), mock.call(1234, challenges.TLSSNI01)]
        )
        self.assertEqual(self.auth.served, {"server1234": set([tls_sni_01]), "server4321": set([http_01])})
        self.assertEqual(1, len(self.auth.http_01_resources))
        self.assertEqual(1, len(self.auth.certs))
        self.assertEqual(
            list(self.auth.http_01_resources),
            [acme_standalone.HTTP01RequestHandler.HTTP01Resource(acme_util.HTTP01, responses[0], mock.ANY)],
        )
コード例 #7
0
ファイル: util.py プロジェクト: 1resu/letsencrypt
    def setUp(self, test_dir="debian_apache_2_4/multiple_vhosts",
              config_root="debian_apache_2_4/multiple_vhosts/apache2",
              vhost_root="debian_apache_2_4/multiple_vhosts/apache2/sites-available"):
        # pylint: disable=arguments-differ
        super(ApacheTest, self).setUp()

        self.temp_dir, self.config_dir, self.work_dir = common.dir_setup(
            test_dir=test_dir,
            pkg="certbot_apache.tests")

        self.ssl_options = common.setup_ssl_options(
            self.config_dir, constants.os_constant("MOD_SSL_CONF_SRC"),
            constants.MOD_SSL_CONF_DEST)

        self.config_path = os.path.join(self.temp_dir, config_root)
        self.vhost_path = os.path.join(self.temp_dir, vhost_root)

        self.rsa512jwk = jose.JWKRSA.load(test_util.load_vector(
            "rsa512_key.pem"))

        # Make sure all vhosts in sites-enabled are symlinks (Python packaging
        # does not preserve symlinks)
        sites_enabled = os.path.join(self.config_path, "sites-enabled")
        if not os.path.exists(sites_enabled):
            return

        for vhost_basename in os.listdir(sites_enabled):
            vhost = os.path.join(sites_enabled, vhost_basename)
            if not os.path.islink(vhost):  # pragma: no cover
                os.remove(vhost)
                target = os.path.join(
                    os.path.pardir, "sites-available", vhost_basename)
                os.symlink(target, vhost)
コード例 #8
0
    def setUp(
        self,
        test_dir="debian_apache_2_4/multiple_vhosts",
        config_root="debian_apache_2_4/multiple_vhosts/apache2",
        vhost_root="debian_apache_2_4/multiple_vhosts/apache2/sites-available"
    ):
        # pylint: disable=arguments-differ
        super(ApacheTest, self).setUp()

        self.temp_dir, self.config_dir, self.work_dir = common.dir_setup(
            test_dir=test_dir, pkg="certbot_apache.tests")

        self.ssl_options = common.setup_ssl_options(
            self.config_dir, constants.os_constant("MOD_SSL_CONF_SRC"),
            constants.MOD_SSL_CONF_DEST)

        self.config_path = os.path.join(self.temp_dir, config_root)
        self.vhost_path = os.path.join(self.temp_dir, vhost_root)

        self.rsa512jwk = jose.JWKRSA.load(
            test_util.load_vector("rsa512_key.pem"))

        # Make sure all vhosts in sites-enabled are symlinks (Python packaging
        # does not preserve symlinks)
        sites_enabled = os.path.join(self.config_path, "sites-enabled")
        if not os.path.exists(sites_enabled):
            return

        for vhost_basename in os.listdir(sites_enabled):
            vhost = os.path.join(sites_enabled, vhost_basename)
            if not os.path.islink(vhost):  # pragma: no cover
                os.remove(vhost)
                target = os.path.join(os.path.pardir, "sites-available",
                                      vhost_basename)
                os.symlink(target, vhost)
コード例 #9
0
    def test_perform2(self):
        domain = b'localhost'
        key = jose.JWK.load(test_util.load_vector('rsa512_key.pem'))
        http_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.HTTP01_P, domain=domain, account_key=key)
        tls_sni_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.TLSSNI01_P, domain=domain, account_key=key)

        self.auth.servers = mock.MagicMock()

        def _run(port, tls):  # pylint: disable=unused-argument
            return "server{0}".format(port)

        self.auth.servers.run.side_effect = _run
        responses = self.auth.perform2([http_01, tls_sni_01])

        self.assertTrue(isinstance(responses, list))
        self.assertEqual(2, len(responses))
        self.assertTrue(isinstance(responses[0], challenges.HTTP01Response))
        self.assertTrue(isinstance(responses[1], challenges.TLSSNI01Response))

        self.assertEqual(self.auth.servers.run.mock_calls, [
            mock.call(4321, challenges.HTTP01),
            mock.call(1234, challenges.TLSSNI01),
        ])
        self.assertEqual(self.auth.served, {
            "server1234": set([tls_sni_01]),
            "server4321": set([http_01]),
        })
        self.assertEqual(1, len(self.auth.http_01_resources))
        self.assertEqual(1, len(self.auth.certs))
        self.assertEqual(list(self.auth.http_01_resources), [
            acme_standalone.HTTP01RequestHandler.HTTP01Resource(
                acme_util.HTTP01, responses[0], mock.ANY)
        ])
コード例 #10
0
    def test_setup_challenge_cert(self):
        # This is a helper function that can be used for handling
        # open context managers more elegantly. It avoids dealing with
        # __enter__ and __exit__ calls.
        # http://www.voidspace.org.uk/python/mock/helpers.html#mock.mock_open
        mock_open, mock_safe_open = mock.mock_open(), mock.mock_open()

        response = challenges.TLSSNI01Response()
        achall = mock.MagicMock()
        key = test_util.load_pyopenssl_private_key("rsa512_key.pem")
        achall.response_and_validation.return_value = (
            response, (test_util.load_cert("cert.pem"), key))

        with mock.patch("certbot.plugins.common.open",
                        mock_open, create=True):
            with mock.patch("certbot.plugins.common.le_util.safe_open",
                            mock_safe_open):
                # pylint: disable=protected-access
                self.assertEqual(response, self.sni._setup_challenge_cert(
                    achall, "randomS1"))

        # pylint: disable=no-member
        mock_open.assert_called_once_with(self.sni.get_cert_path(achall), "wb")
        mock_open.return_value.write.assert_called_once_with(
            test_util.load_vector("cert.pem"))
        mock_safe_open.assert_called_once_with(
            self.sni.get_key_path(achall), "wb", chmod=0o400)
        mock_safe_open.return_value.write.assert_called_once_with(
            OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key))
コード例 #11
0
ファイル: cli_test.py プロジェクト: jskrzypek/certbot
    def test_find_duplicative_names(self, unused_makedir):
        from certbot.main import _find_duplicative_certs
        test_cert = test_util.load_vector('cert-san.pem')
        with open(self.test_rc.cert, 'w') as f:
            f.write(test_cert)

        # No overlap at all
        result = _find_duplicative_certs(
            self.cli_config, ['wow.net', 'hooray.org'])
        self.assertEqual(result, (None, None))

        # Totally identical
        result = _find_duplicative_certs(
            self.cli_config, ['example.com', 'www.example.com'])
        self.assertTrue(result[0].configfile.filename.endswith('example.org.conf'))
        self.assertEqual(result[1], None)

        # Superset
        result = _find_duplicative_certs(
            self.cli_config, ['example.com', 'www.example.com', 'something.new'])
        self.assertEqual(result[0], None)
        self.assertTrue(result[1].configfile.filename.endswith('example.org.conf'))

        # Partial overlap doesn't count
        result = _find_duplicative_certs(
            self.cli_config, ['example.com', 'something.new'])
        self.assertEqual(result, (None, None))
コード例 #12
0
    def test_pem_csr(self):
        csrfile = test_util.vector_path('csr.pem')
        data = test_util.load_vector('csr.pem')

        self.assertEqual((
            OpenSSL.crypto.FILETYPE_PEM,
            util.CSR(file=csrfile, data=data, form="pem"),
            ["example.com"],
        ), self._call(csrfile, data))
コード例 #13
0
    def _get_achalls(cls):
        domain = b'localhost'
        key = jose.JWK.load(test_util.load_vector('rsa512_key.pem'))
        http_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.HTTP01_P, domain=domain, account_key=key)
        tls_sni_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.TLSSNI01_P, domain=domain, account_key=key)

        return [http_01, tls_sni_01]
コード例 #14
0
    def test_der_csr(self):
        csrfile = test_util.vector_path('csr.der')
        data = test_util.load_vector('csr.der')

        self.assertEqual((
            OpenSSL.crypto.FILETYPE_ASN1,
            le_util.CSR(file=csrfile, data=data, form="der"),
            ["example.com"],
        ), self._call(csrfile, data))
コード例 #15
0
    def _get_achalls(cls):
        domain = b'localhost'
        key = jose.JWK.load(test_util.load_vector('rsa512_key.pem'))
        http_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.HTTP01_P, domain=domain, account_key=key)
        tls_sni_01 = achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.TLSSNI01_P, domain=domain, account_key=key)

        return [http_01, tls_sni_01]
コード例 #16
0
class TLSSNI01Test(unittest.TestCase):
    """Tests for certbot.plugins.common.TLSSNI01."""

    auth_key = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem"))
    achalls = [
        achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.chall_to_challb(
                challenges.TLSSNI01(token=b'token1'), "pending"),
            domain="encryption-example.demo",
            account_key=auth_key),
        achallenges.KeyAuthorizationAnnotatedChallenge(
            challb=acme_util.chall_to_challb(
                challenges.TLSSNI01(token=b'token2'), "pending"),
            domain="certbot.demo",
            account_key=auth_key),
    ]

    def setUp(self):
        from certbot.plugins.common import TLSSNI01
        self.sni = TLSSNI01(configurator=mock.MagicMock())

    def test_add_chall(self):
        self.sni.add_chall(self.achalls[0], 0)
        self.assertEqual(1, len(self.sni.achalls))
        self.assertEqual([0], self.sni.indices)

    def test_setup_challenge_cert(self):
        # This is a helper function that can be used for handling
        # open context managers more elegantly. It avoids dealing with
        # __enter__ and __exit__ calls.
        # http://www.voidspace.org.uk/python/mock/helpers.html#mock.mock_open
        mock_open, mock_safe_open = mock.mock_open(), mock.mock_open()

        response = challenges.TLSSNI01Response()
        achall = mock.MagicMock()
        key = test_util.load_pyopenssl_private_key("rsa512_key.pem")
        achall.response_and_validation.return_value = (response, (
            test_util.load_cert("cert.pem"), key))

        with mock.patch("certbot.plugins.common.open", mock_open, create=True):
            with mock.patch("certbot.plugins.common.util.safe_open",
                            mock_safe_open):
                # pylint: disable=protected-access
                self.assertEqual(
                    response,
                    self.sni._setup_challenge_cert(achall, "randomS1"))

        # pylint: disable=no-member
        mock_open.assert_called_once_with(self.sni.get_cert_path(achall), "wb")
        mock_open.return_value.write.assert_called_once_with(
            test_util.load_vector("cert.pem"))
        mock_safe_open.assert_called_once_with(self.sni.get_key_path(achall),
                                               "wb",
                                               chmod=0o400)
        mock_safe_open.return_value.write.assert_called_once_with(
            OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key))
コード例 #17
0
ファイル: client_test.py プロジェクト: xianliy/certbot
    def test_save_certificate(self, mock_parser):
        # pylint: disable=too-many-locals
        certs = ["matching_cert.pem", "cert.pem", "cert-san.pem"]
        tmp_path = tempfile.mkdtemp()
        os.chmod(tmp_path, 0o755)  # TODO: really??

        certr = mock.MagicMock(body=test_util.load_comparable_cert(certs[0]))
        chain_cert = [
            test_util.load_comparable_cert(certs[1]),
            test_util.load_comparable_cert(certs[2])
        ]
        candidate_cert_path = os.path.join(tmp_path, "certs", "cert.pem")
        candidate_chain_path = os.path.join(tmp_path, "chains", "chain.pem")
        candidate_fullchain_path = os.path.join(tmp_path, "chains",
                                                "fullchain.pem")
        mock_parser.verb = "certonly"
        mock_parser.args = [
            "--cert-path", candidate_cert_path, "--chain-path",
            candidate_chain_path, "--fullchain-path", candidate_fullchain_path
        ]

        cert_path, chain_path, fullchain_path = self.client.save_certificate(
            certr, chain_cert, candidate_cert_path, candidate_chain_path,
            candidate_fullchain_path)

        self.assertEqual(os.path.dirname(cert_path),
                         os.path.dirname(candidate_cert_path))
        self.assertEqual(os.path.dirname(chain_path),
                         os.path.dirname(candidate_chain_path))
        self.assertEqual(os.path.dirname(fullchain_path),
                         os.path.dirname(candidate_fullchain_path))

        with open(cert_path, "rb") as cert_file:
            cert_contents = cert_file.read()
        self.assertEqual(cert_contents, test_util.load_vector(certs[0]))

        with open(chain_path, "rb") as chain_file:
            chain_contents = chain_file.read()
        self.assertEqual(
            chain_contents,
            test_util.load_vector(certs[1]) + test_util.load_vector(certs[2]))

        shutil.rmtree(tmp_path)
コード例 #18
0
ファイル: crypto_util_test.py プロジェクト: 52M/letsencrypt
    def test_pem_csr(self):
        csrfile = test_util.vector_path('csr.pem')
        data = test_util.load_vector('csr.pem')

        self.assertEqual(
            (OpenSSL.crypto.FILETYPE_PEM,
             util.CSR(file=csrfile,
                      data=data,
                      form="pem"),
             ["example.com"],),
            self._call(csrfile, data))
コード例 #19
0
 def test_extract_six_sans(self):
     self.assertEqual(
         set(self._call(test_util.load_vector('csr-6sans.pem'))),
         set((
             "example.com",
             "example.org",
             "example.net",
             "example.info",
             "subdomain.example.com",
             "other.subdomain.example.com",
         )))
コード例 #20
0
ファイル: storage_test.py プロジェクト: zhmch/certbot
    def test_names(self):
        # Trying the current version
        self._write_out_kind("cert", 12, test_util.load_vector("cert-san.pem"))
        self.assertEqual(self.test_rc.names(),
                         ["example.com", "www.example.com"])

        # Trying a non-current version
        self._write_out_kind("cert", 15, test_util.load_vector("cert.pem"))
        self.assertEqual(self.test_rc.names(12),
                         ["example.com", "www.example.com"])

        # Testing common name is listed first
        self._write_out_kind("cert", 12,
                             test_util.load_vector("cert-5sans.pem"))
        self.assertEqual(self.test_rc.names(12), ["example.com"] +
                         ["{0}.example.com".format(c) for c in "abcd"])

        # Trying missing cert
        os.unlink(self.test_rc.cert)
        self.assertRaises(errors.CertStorageError, self.test_rc.names)
コード例 #21
0
ファイル: util.py プロジェクト: yan12125/certbot
    def setUp(self):
        super(NginxTest, self).setUp()

        self.temp_dir, self.config_dir, self.work_dir = common.dir_setup("etc_nginx", "certbot_nginx.tests")

        self.ssl_options = common.setup_ssl_options(
            self.config_dir, constants.MOD_SSL_CONF_SRC, constants.MOD_SSL_CONF_DEST
        )

        self.config_path = os.path.join(self.temp_dir, "etc_nginx")

        self.rsa512jwk = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem"))
コード例 #22
0
    def test_save_certificate(self, mock_parser):
        # pylint: disable=too-many-locals
        certs = ["matching_cert.pem", "cert.pem", "cert-san.pem"]
        tmp_path = tempfile.mkdtemp()
        os.chmod(tmp_path, 0o755)  # TODO: really??

        certr = mock.MagicMock(body=test_util.load_comparable_cert(certs[0]))
        chain_cert = [test_util.load_comparable_cert(certs[1]),
                      test_util.load_comparable_cert(certs[2])]
        candidate_cert_path = os.path.join(tmp_path, "certs", "cert.pem")
        candidate_chain_path = os.path.join(tmp_path, "chains", "chain.pem")
        candidate_fullchain_path = os.path.join(tmp_path, "chains", "fullchain.pem")
        mock_parser.verb = "certonly"
        mock_parser.args = ["--cert-path", candidate_cert_path,
                "--chain-path", candidate_chain_path,
                "--fullchain-path", candidate_fullchain_path]

        cert_path, chain_path, fullchain_path = self.client.save_certificate(
            certr, chain_cert, candidate_cert_path, candidate_chain_path,
            candidate_fullchain_path)

        self.assertEqual(os.path.dirname(cert_path),
                         os.path.dirname(candidate_cert_path))
        self.assertEqual(os.path.dirname(chain_path),
                         os.path.dirname(candidate_chain_path))
        self.assertEqual(os.path.dirname(fullchain_path),
                         os.path.dirname(candidate_fullchain_path))

        with open(cert_path, "rb") as cert_file:
            cert_contents = cert_file.read()
        self.assertEqual(cert_contents, test_util.load_vector(certs[0]))

        with open(chain_path, "rb") as chain_file:
            chain_contents = chain_file.read()
        self.assertEqual(chain_contents, test_util.load_vector(certs[1]) +
                         test_util.load_vector(certs[2]))

        shutil.rmtree(tmp_path)
コード例 #23
0
    def setUp(self):
        super(NginxTest, self).setUp()

        self.temp_dir, self.config_dir, self.work_dir = common.dir_setup(
            "etc_nginx", "certbot_nginx.tests")

        self.ssl_options = common.setup_ssl_options(
            self.config_dir, constants.MOD_SSL_CONF_SRC,
            constants.MOD_SSL_CONF_DEST)

        self.config_path = os.path.join(self.temp_dir, "etc_nginx")

        self.rsa512jwk = jose.JWKRSA.load(test_util.load_vector(
            "rsa512_key.pem"))
コード例 #24
0
ファイル: storage_test.py プロジェクト: 52M/letsencrypt
    def test_names(self):
        # Trying the current version
        test_cert = test_util.load_vector("cert-san.pem")
        os.symlink(os.path.join("..", "..", "archive", "example.org",
                                "cert12.pem"), self.test_rc.cert)
        with open(self.test_rc.cert, "w") as f:
            f.write(test_cert)
        self.assertEqual(self.test_rc.names(),
                         ["example.com", "www.example.com"])

        # Trying a non-current version
        test_cert = test_util.load_vector("cert.pem")
        os.unlink(self.test_rc.cert)
        os.symlink(os.path.join("..", "..", "archive", "example.org",
                                "cert15.pem"), self.test_rc.cert)
        with open(self.test_rc.cert, "w") as f:
            f.write(test_cert)
        self.assertEqual(self.test_rc.names(12),
                         ["example.com", "www.example.com"])

        # Trying missing cert
        os.unlink(self.test_rc.cert)
        self.assertRaises(errors.CertStorageError, self.test_rc.names)
コード例 #25
0
ファイル: storage_test.py プロジェクト: zhmch/certbot
    def test_time_interval_judgments(self, mock_datetime):
        """Test should_autodeploy() and should_autorenew() on the basis
        of expiry time windows."""
        test_cert = test_util.load_vector("cert.pem")
        self._write_out_ex_kinds()

        self.test_rc.update_all_links_to(12)
        with open(self.test_rc.cert, "wb") as f:
            f.write(test_cert)
        self.test_rc.update_all_links_to(11)
        with open(self.test_rc.cert, "wb") as f:
            f.write(test_cert)

        mock_datetime.timedelta = datetime.timedelta

        for (current_time, interval, result) in [
                # 2014-12-13 12:00:00+00:00 (about 5 days prior to expiry)
                # Times that should result in autorenewal/autodeployment
            (1418472000, "2 months", True),
            (1418472000, "1 week", True),
                # Times that should not
            (1418472000, "4 days", False),
            (1418472000, "2 days", False),
                # 2009-05-01 12:00:00+00:00 (about 5 years prior to expiry)
                # Times that should result in autorenewal/autodeployment
            (1241179200, "7 years", True),
            (1241179200, "11 years 2 months", True),
                # Times that should not
            (1241179200, "8 hours", False),
            (1241179200, "2 days", False),
            (1241179200, "40 days", False),
            (1241179200, "9 months", False),
                # 2015-01-01 (after expiry has already happened, so all
                #            intervals should cause autorenewal/autodeployment)
            (1420070400, "0 seconds", True),
            (1420070400, "10 seconds", True),
            (1420070400, "10 minutes", True),
            (1420070400, "10 weeks", True),
            (1420070400, "10 months", True),
            (1420070400, "10 years", True),
            (1420070400, "99 months", True),
        ]:
            sometime = datetime.datetime.utcfromtimestamp(current_time)
            mock_datetime.datetime.utcnow.return_value = sometime
            self.test_rc.configuration["deploy_before_expiry"] = interval
            self.test_rc.configuration["renew_before_expiry"] = interval
            self.assertEqual(self.test_rc.should_autodeploy(), result)
            self.assertEqual(self.test_rc.should_autorenew(), result)
コード例 #26
0
    def test_time_interval_judgments(self, mock_datetime):
        """Test should_autodeploy() and should_autorenew() on the basis
        of expiry time windows."""
        test_cert = test_util.load_vector("cert.pem")
        self._write_out_ex_kinds()

        self.test_rc.update_all_links_to(12)
        with open(self.test_rc.cert, "wb") as f:
            f.write(test_cert)
        self.test_rc.update_all_links_to(11)
        with open(self.test_rc.cert, "wb") as f:
            f.write(test_cert)

        mock_datetime.timedelta = datetime.timedelta

        for (current_time, interval, result) in [
            # 2014-12-13 12:00:00+00:00 (about 5 days prior to expiry)
            # Times that should result in autorenewal/autodeployment
            (1418472000, "2 months", True),
            (1418472000, "1 week", True),
            # Times that should not
            (1418472000, "4 days", False),
            (1418472000, "2 days", False),
            # 2009-05-01 12:00:00+00:00 (about 5 years prior to expiry)
            # Times that should result in autorenewal/autodeployment
            (1241179200, "7 years", True),
            (1241179200, "11 years 2 months", True),
            # Times that should not
            (1241179200, "8 hours", False),
            (1241179200, "2 days", False),
            (1241179200, "40 days", False),
            (1241179200, "9 months", False),
            # 2015-01-01 (after expiry has already happened, so all
            #            intervals should cause autorenewal/autodeployment)
            (1420070400, "0 seconds", True),
            (1420070400, "10 seconds", True),
            (1420070400, "10 minutes", True),
            (1420070400, "10 weeks", True),
            (1420070400, "10 months", True),
            (1420070400, "10 years", True),
            (1420070400, "99 months", True),
        ]:
            sometime = datetime.datetime.utcfromtimestamp(current_time)
            mock_datetime.datetime.utcnow.return_value = sometime
            self.test_rc.configuration["deploy_before_expiry"] = interval
            self.test_rc.configuration["renew_before_expiry"] = interval
            self.assertEqual(self.test_rc.should_autodeploy(), result)
            self.assertEqual(self.test_rc.should_autorenew(), result)
コード例 #27
0
"""Tests for certbot.crypto_util."""
import logging
import shutil
import tempfile
import unittest

import OpenSSL
import mock
import zope.component

from certbot import errors
from certbot import interfaces
from certbot.tests import test_util


RSA256_KEY = test_util.load_vector('rsa256_key.pem')
RSA512_KEY = test_util.load_vector('rsa512_key.pem')
CERT_PATH = test_util.vector_path('cert.pem')
CERT = test_util.load_vector('cert.pem')
SAN_CERT = test_util.load_vector('cert-san.pem')


class InitSaveKeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.init_save_key."""
    def setUp(self):
        logging.disable(logging.CRITICAL)
        zope.component.provideUtility(
            mock.Mock(strict_permissions=True), interfaces.IConfig)
        self.key_dir = tempfile.mkdtemp('key_dir')

    def tearDown(self):
コード例 #28
0
 def test_common_name_sans_order(self):
     # Tests that the common name comes first
     # followed by the SANS in alphabetical order
     self.assertEqual(
         ['example.com'] + ['{0}.example.com'.format(c) for c in 'abcd'],
         self._call(test_util.load_vector('cert-5sans.pem')))
コード例 #29
0
 def test_san(self):
     self.assertEqual(['example.com', 'www.example.com'],
                      self._call(test_util.load_vector('cert-san.pem')))
コード例 #30
0
 def test_extract_six_sans(self):
     self.assertEqual(self._call(test_util.load_vector('csr-6sans.pem')),
                      ["example.com", "example.org", "example.net",
                       "example.info", "subdomain.example.com",
                       "other.subdomain.example.com"])
コード例 #31
0
 def test_extract_one_san(self):
     self.assertEqual(['example.com'], self._call(
         test_util.load_vector('csr.pem')))
コード例 #32
0
 def test_single(self):
     self.assertEqual([], self._call(test_util.load_vector('cert.pem')))
コード例 #33
0
 def test_valid_true(self):
     self.assertTrue(self._call(
         test_util.load_vector('csr.pem'), RSA512_KEY))
コード例 #34
0
ファイル: crypto_util_test.py プロジェクト: 52M/letsencrypt
 def test_bad_csr(self):
     self.assertRaises(errors.Error, self._call,
                       test_util.vector_path('cert.pem'),
                       test_util.load_vector('cert.pem'))
コード例 #35
0
 def test_bad_csr(self):
     self.assertRaises(errors.Error, self._call,
                       test_util.vector_path('cert.pem'),
                       test_util.load_vector('cert.pem'))
コード例 #36
0
 def test_parse_no_sans(self):
     self.assertEqual(["example.org"],
                      self._call(test_util.load_vector('csr-nosans.pem')))
コード例 #37
0
"""Tests for certbot.crypto_util."""
import logging
import shutil
import tempfile
import unittest

import OpenSSL
import mock
import zope.component

from certbot import errors
from certbot import interfaces
from certbot import util
from certbot.tests import test_util

RSA256_KEY = test_util.load_vector('rsa256_key.pem')
RSA512_KEY = test_util.load_vector('rsa512_key.pem')
CERT_PATH = test_util.vector_path('cert.pem')
CERT = test_util.load_vector('cert.pem')
SAN_CERT = test_util.load_vector('cert-san.pem')


class InitSaveKeyTest(unittest.TestCase):
    """Tests for certbot.crypto_util.init_save_key."""
    def setUp(self):
        logging.disable(logging.CRITICAL)
        zope.component.provideUtility(mock.Mock(strict_permissions=True),
                                      interfaces.IConfig)
        self.key_dir = tempfile.mkdtemp('key_dir')

    def tearDown(self):
コード例 #38
0
 def test_valid_pem_san_true(self):
     self.assertTrue(self._call(test_util.load_vector('csr-san.pem')))
コード例 #39
0
ファイル: client_test.py プロジェクト: pmorawik/certbot
import shutil
import tempfile
import unittest

import OpenSSL
import mock

from acme import jose

from certbot import account
from certbot import errors
from certbot import util

from certbot.tests import test_util

KEY = test_util.load_vector("rsa512_key.pem")
CSR_SAN = test_util.load_vector("csr-san.der")


class ConfigHelper(object):
    """Creates a dummy object to imitate a namespace object

        Example: cfg = ConfigHelper(redirect=True, hsts=False, uir=False)
        will result in: cfg.redirect=True, cfg.hsts=False, etc.
    """
    def __init__(self, **kwds):
        self.__dict__.update(kwds)


class RegisterTest(unittest.TestCase):
    """Tests for certbot.client.register."""
コード例 #40
0
 def test_valid_der_san_false(self):
     self.assertFalse(self._call(test_util.load_vector('csr-san.der')))
コード例 #41
0
 def test_valid_pem_san_true(self):
     self.assertTrue(self._call(test_util.load_vector('csr-san.pem')))
コード例 #42
0
 def test_valid_der_san_false(self):
     self.assertFalse(self._call(test_util.load_vector('csr-san.der')))
コード例 #43
0
import mock
import zope.component

from acme import jose
from acme import messages

from certbot import account
from certbot import errors
from certbot import interfaces

from certbot.display import util as display_util

from certbot.tests import test_util


KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem"))


class GetEmailTest(unittest.TestCase):
    """Tests for certbot.display.ops.get_email."""

    def setUp(self):
        mock_display = mock.MagicMock()
        self.input = mock_display.input
        zope.component.provideUtility(mock_display, interfaces.IDisplay)

    @classmethod
    def _call(cls, **kwargs):
        from certbot.display.ops import get_email
        return get_email(**kwargs)
コード例 #44
0
 def test_invalid_false(self):
     self.assertFalse(self._call(
         test_util.load_vector('csr.pem'), RSA256_KEY))
コード例 #45
0
import tempfile
import unittest

import OpenSSL
import mock

from acme import jose

from certbot import account
from certbot import errors
from certbot import util

from certbot.tests import test_util


KEY = test_util.load_vector("rsa512_key.pem")
CSR_SAN = test_util.load_vector("csr-san.der")


class ConfigHelper(object):
    """Creates a dummy object to imitate a namespace object

        Example: cfg = ConfigHelper(redirect=True, hsts=False, uir=False)
        will result in: cfg.redirect=True, cfg.hsts=False, etc.
    """
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

class RegisterTest(unittest.TestCase):
    """Tests for certbot.client.register."""
コード例 #46
0
 def test_san(self):
     self.assertEqual(
         ['example.com', 'www.example.com'],
         self._call(test_util.load_vector('cert-san.pem')))
コード例 #47
0
 def test_valid_true(self):
     self.assertTrue(
         self._call(test_util.load_vector('csr.pem'), RSA512_KEY))
コード例 #48
0
 def test_extract_two_sans(self):
     self.assertEqual(['example.com', 'www.example.com'], self._call(
         test_util.load_vector('csr-san.pem')))
コード例 #49
0
import mock
import zope.component

from acme import jose
from acme import messages

from certbot import account
from certbot import errors
from certbot import interfaces

from certbot.display import util as display_util

from certbot.tests import test_util

KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem"))


class GetEmailTest(unittest.TestCase):
    """Tests for certbot.display.ops.get_email."""
    def setUp(self):
        mock_display = mock.MagicMock()
        self.input = mock_display.input
        zope.component.provideUtility(mock_display, interfaces.IDisplay)

    @classmethod
    def _call(cls, **kwargs):
        from certbot.display.ops import get_email
        return get_email(**kwargs)

    def test_cancel_none(self):
コード例 #50
0
 def test_parse_no_sans(self):
     self.assertEqual(
         [], self._call(test_util.load_vector('csr-nosans.pem')))
コード例 #51
0
 def test_single(self):
     self.assertEqual(['example.com'],
                      self._call(test_util.load_vector('cert.pem')))
コード例 #52
0
 def test_extract_one_san(self):
     self.assertEqual(['example.com'],
                      self._call(test_util.load_vector('csr.pem')))
コード例 #53
0
 def test_invalid_false(self):
     self.assertFalse(
         self._call(test_util.load_vector('csr.pem'), RSA256_KEY))
コード例 #54
0
 def test_common_name_sans_order(self):
     # Tests that the common name comes first
     # followed by the SANS in alphabetical order
     self.assertEqual(['example.com'] +
                      ['{0}.example.com'.format(c) for c in 'abcd'],
                      self._call(test_util.load_vector('cert-5sans.pem')))
コード例 #55
0
 def test_extract_two_sans(self):
     self.assertEqual(set((
         'example.com',
         'www.example.com',
     )), set(self._call(test_util.load_vector('csr-san.pem'))))