File: standalone_test.py

package info (click to toggle)
python-certbot 4.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,688 kB
  • sloc: python: 21,764; makefile: 182; sh: 108
file content (191 lines) | stat: -rw-r--r-- 6,767 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""Tests for certbot._internal.plugins.standalone."""
import errno
import socket
import sys
from typing import Dict
from typing import Set
from typing import Tuple
import unittest
from unittest import mock

import josepy as jose
import pytest

from acme import challenges
from acme import standalone as acme_standalone
from certbot import achallenges
from certbot import errors
from certbot.tests import acme_util
from certbot.tests import util as test_util


class ServerManagerTest(unittest.TestCase):
    """Tests for certbot._internal.plugins.standalone.ServerManager."""

    def setUp(self):
        from certbot._internal.plugins.standalone import ServerManager, _KeyAndCert
        self.certs: Dict[bytes, _KeyAndCert] = {}
        self.http_01_resources: Set[acme_standalone.HTTP01RequestHandler.HTTP01Resource] = {}
        self.mgr = ServerManager(self.certs, self.http_01_resources)

    def test_init(self):
        assert self.mgr.certs is self.certs
        assert self.mgr.http_01_resources is self.http_01_resources

    def _test_run_stop(self, challenge_type):
        server = self.mgr.run(port=0, challenge_type=challenge_type)
        port = server.getsocknames()[0][1]
        assert self.mgr.running() == {port: server}
        self.mgr.stop(port=port)
        assert self.mgr.running() == {}

    def test_run_stop_http_01(self):
        self._test_run_stop(challenges.HTTP01)

    def test_run_idempotent(self):
        server = self.mgr.run(port=0, challenge_type=challenges.HTTP01)
        port = server.getsocknames()[0][1]
        server2 = self.mgr.run(port=port, challenge_type=challenges.HTTP01)
        assert self.mgr.running() == {port: server}
        assert server is server2
        self.mgr.stop(port)
        assert self.mgr.running() == {}

    def test_run_bind_error(self):
        some_server = socket.socket(socket.AF_INET6)
        some_server.bind(("", 0))
        port = some_server.getsockname()[1]
        maybe_another_server = socket.socket()
        try:
            maybe_another_server.bind(("", port))
        except OSError:
            pass
        with pytest.raises(errors.StandaloneBindError):
            self.mgr.run(port,
            challenge_type=challenges.HTTP01)
        assert self.mgr.running() == {}
        some_server.close()
        maybe_another_server.close()


def get_open_port():
    """Gets an open port number from the OS."""
    open_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
    open_socket.bind(("", 0))
    port = open_socket.getsockname()[1]
    open_socket.close()
    return port


class AuthenticatorTest(unittest.TestCase):
    """Tests for certbot._internal.plugins.standalone.Authenticator."""

    def setUp(self):
        from certbot._internal.plugins.standalone import Authenticator

        self.config = mock.MagicMock(http01_port=get_open_port())
        self.auth = Authenticator(self.config, name="standalone")
        self.auth.servers = mock.MagicMock()

    def test_more_info(self):
        assert isinstance(self.auth.more_info(), str)

    def test_get_chall_pref(self):
        assert self.auth.get_chall_pref(domain=None) == \
                         [challenges.HTTP01]

    def test_perform(self):
        achalls = self._get_achalls()
        response = self.auth.perform(achalls)

        expected = [achall.response(achall.account_key) for achall in achalls]
        assert response == expected

    @test_util.patch_display_util()
    def test_perform_eaddrinuse_retry(self, mock_get_utility):
        mock_utility = mock_get_utility()
        encountered_errno = errno.EADDRINUSE
        error = errors.StandaloneBindError(mock.MagicMock(errno=encountered_errno), -1)
        self.auth.servers.run.side_effect = [error] + 2 * [mock.MagicMock()]
        mock_yesno = mock_utility.yesno
        mock_yesno.return_value = True

        self.test_perform()
        self._assert_correct_yesno_call(mock_yesno)

    @test_util.patch_display_util()
    def test_perform_eaddrinuse_no_retry(self, mock_get_utility):
        mock_utility = mock_get_utility()
        mock_yesno = mock_utility.yesno
        mock_yesno.return_value = False

        encountered_errno = errno.EADDRINUSE
        with pytest.raises(errors.PluginError):
            self._fail_perform(encountered_errno)
        self._assert_correct_yesno_call(mock_yesno)

    def _assert_correct_yesno_call(self, mock_yesno):
        yesno_args, yesno_kwargs = mock_yesno.call_args
        assert "in use" in yesno_args[0]
        assert not yesno_kwargs.get("default", True)

    def test_perform_eacces(self):
        encountered_errno = errno.EACCES
        with pytest.raises(errors.PluginError):
            self._fail_perform(encountered_errno)

    def test_perform_unexpected_socket_error(self):
        encountered_errno = errno.ENOTCONN
        with pytest.raises(errors.StandaloneBindError):
            self._fail_perform(encountered_errno)

    def _fail_perform(self, encountered_errno):
        error = errors.StandaloneBindError(mock.MagicMock(errno=encountered_errno), -1)
        self.auth.servers.run.side_effect = error
        self.auth.perform(self._get_achalls())

    @classmethod
    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)

        return [http_01]

    def test_cleanup(self):
        self.auth.servers.running.return_value = {
            1: "server1",
            2: "server2",
        }
        self.auth.served["server1"].add("chall1")
        self.auth.served["server2"].update(["chall2", "chall3"])

        self.auth.cleanup(["chall1"])
        assert self.auth.served == {
            "server1": set(), "server2": {"chall2", "chall3"}}
        self.auth.servers.stop.assert_called_once_with(1)

        self.auth.servers.running.return_value = {
            2: "server2",
        }
        self.auth.cleanup(["chall2"])
        assert self.auth.served == {
            "server1": set(), "server2": {"chall3"}}
        assert 1 == self.auth.servers.stop.call_count

        self.auth.cleanup(["chall3"])
        assert self.auth.served == {
            "server1": set(), "server2": set()}
        self.auth.servers.stop.assert_called_with(2)

    def test_auth_hint(self):
        self.config.http01_port = "80"
        self.config.http01_address = None
        assert "on port 80" in self.auth.auth_hint([])
        self.config.http01_address = "127.0.0.1"
        assert "on 127.0.0.1:80" in self.auth.auth_hint([])


if __name__ == "__main__":
    sys.exit(pytest.main(sys.argv[1:] + [__file__]))  # pragma: no cover