File: dns_common_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 (237 lines) | stat: -rw-r--r-- 8,522 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""Tests for certbot.plugins.dns_common."""

import collections
import logging
import sys
import unittest
from unittest import mock

import pytest

from certbot import errors
from certbot import util
from certbot.compat import os
from certbot.display import util as display_util
from certbot.plugins import dns_common
from certbot.plugins import dns_test_common
from certbot.tests import util as test_util


class DNSAuthenticatorTest(test_util.TempDirTestCase, dns_test_common.BaseAuthenticatorTest):
    # pylint: disable=protected-access

    class _FakeDNSAuthenticator(dns_common.DNSAuthenticator):
        _setup_credentials = mock.MagicMock()
        _perform = mock.MagicMock()
        _cleanup = mock.MagicMock()

        def more_info(self):  # pylint: disable=missing-docstring,no-self-use
            return 'A fake authenticator for testing.'

    class _FakeConfig:
        fake_propagation_seconds = 0
        fake_config_key = 1
        fake_other_key = None
        fake_file_path = None

    def setUp(self):
        super().setUp()

        self.config = DNSAuthenticatorTest._FakeConfig()

        self.auth = DNSAuthenticatorTest._FakeDNSAuthenticator(self.config, "fake")

    @test_util.patch_display_util()
    def test_perform(self, unused_mock_get_utility):
        self.auth.perform([self.achall])

        self.auth._perform.assert_called_once_with(dns_test_common.DOMAIN, mock.ANY, mock.ANY)

    def test_cleanup(self):
        self.auth._attempt_cleanup = True

        self.auth.cleanup([self.achall])

        self.auth._cleanup.assert_called_once_with(dns_test_common.DOMAIN, mock.ANY, mock.ANY)

    @test_util.patch_display_util()
    def test_prompt(self, mock_get_utility):
        mock_display = mock_get_utility()
        mock_display.input.side_effect = ((display_util.OK, "",),
                                          (display_util.OK, "value",))

        self.auth._configure("other_key", "")
        assert self.auth.config.fake_other_key == "value"

    @test_util.patch_display_util()
    def test_prompt_canceled(self, mock_get_utility):
        mock_display = mock_get_utility()
        mock_display.input.side_effect = ((display_util.CANCEL, "c",),)

        with pytest.raises(errors.PluginError):
            self.auth._configure("other_key", "")

    @test_util.patch_display_util()
    def test_prompt_file(self, mock_get_utility):
        path = os.path.join(self.tempdir, 'file.ini')
        open(path, "wb").close()

        mock_display = mock_get_utility()
        mock_display.directory_select.side_effect = ((display_util.OK, "",),
                                                     (display_util.OK, "not-a-file.ini",),
                                                     (display_util.OK, self.tempdir),
                                                     (display_util.OK, path,))

        self.auth._configure_file("file_path", "")
        assert self.auth.config.fake_file_path == path

    @test_util.patch_display_util()
    def test_prompt_file_canceled(self, mock_get_utility):
        mock_display = mock_get_utility()
        mock_display.directory_select.side_effect = ((display_util.CANCEL, "c",),)

        with pytest.raises(errors.PluginError):
            self.auth._configure_file("file_path", "")

    def test_configure_credentials(self):
        path = os.path.join(self.tempdir, 'file.ini')
        dns_test_common.write({"fake_test": "value"}, path)
        setattr(self.config, "fake_credentials", path)

        credentials = self.auth._configure_credentials("credentials", "", {"test": ""})

        assert credentials.conf("test") == "value"

    @test_util.patch_display_util()
    def test_prompt_credentials(self, mock_get_utility):
        bad_path = os.path.join(self.tempdir, 'bad-file.ini')
        dns_test_common.write({"fake_other": "other_value"}, bad_path)

        path = os.path.join(self.tempdir, 'file.ini')
        dns_test_common.write({"fake_test": "value"}, path)
        setattr(self.config, "fake_credentials", "")

        mock_display = mock_get_utility()
        mock_display.directory_select.side_effect = ((display_util.OK, "",),
                                                     (display_util.OK, "not-a-file.ini",),
                                                     (display_util.OK, self.tempdir),
                                                     (display_util.OK, bad_path),
                                                     (display_util.OK, path,))

        credentials = self.auth._configure_credentials("credentials", "", {"test": ""})
        assert credentials.conf("test") == "value"

    def test_auth_hint(self):
        assert 'try increasing --fake-propagation-seconds (currently 0 seconds).' in \
            self.auth.auth_hint([mock.MagicMock()])


class CredentialsConfigurationTest(test_util.TempDirTestCase):
    class _MockLoggingHandler(logging.Handler):
        messages = None

        def __init__(self, *args, **kwargs):
            self.reset()
            super().__init__(*args, **kwargs)

        def emit(self, record):
            self.messages[record.levelname.lower()].append(record.getMessage())

        def reset(self):
            """Allows the handler to be reset between tests."""
            self.messages = collections.defaultdict(list)

    def test_valid_file(self):
        path = os.path.join(self.tempdir, 'too-permissive-file.ini')

        dns_test_common.write({"test": "value", "other": 1}, path)

        credentials_configuration = dns_common.CredentialsConfiguration(path)
        assert "value" == credentials_configuration.conf("test")
        assert "1" == credentials_configuration.conf("other")

    def test_nonexistent_file(self):
        path = os.path.join(self.tempdir, 'not-a-file.ini')

        with pytest.raises(errors.PluginError):
            dns_common.CredentialsConfiguration(path)

    def test_valid_file_with_unsafe_permissions(self):
        log = self._MockLoggingHandler()
        dns_common.logger.addHandler(log)

        path = os.path.join(self.tempdir, 'too-permissive-file.ini')
        util.safe_open(path, "wb", 0o744).close()

        dns_common.CredentialsConfiguration(path)

        assert 1 == len([_ for _ in log.messages['warning'] if _.startswith("Unsafe")])


class CredentialsConfigurationRequireTest(test_util.TempDirTestCase):

    def setUp(self):
        super().setUp()

        self.path = os.path.join(self.tempdir, 'file.ini')

    def _write(self, values):
        dns_test_common.write(values, self.path)

    def test_valid(self):
        self._write({"test": "value", "other": 1})

        credentials_configuration = dns_common.CredentialsConfiguration(self.path)
        credentials_configuration.require({"test": "", "other": ""})

    def test_valid_but_extra(self):
        self._write({"test": "value", "other": 1})

        credentials_configuration = dns_common.CredentialsConfiguration(self.path)
        credentials_configuration.require({"test": ""})

    def test_valid_empty(self):
        self._write({})

        credentials_configuration = dns_common.CredentialsConfiguration(self.path)
        credentials_configuration.require({})

    def test_missing(self):
        self._write({})

        credentials_configuration = dns_common.CredentialsConfiguration(self.path)
        with pytest.raises(errors.PluginError):
            credentials_configuration.require({"test": ""})

    def test_blank(self):
        self._write({"test": ""})

        credentials_configuration = dns_common.CredentialsConfiguration(self.path)
        with pytest.raises(errors.PluginError):
            credentials_configuration.require({"test": ""})

    def test_typo(self):
        self._write({"tets": "typo!"})

        credentials_configuration = dns_common.CredentialsConfiguration(self.path)
        with pytest.raises(errors.PluginError):
            credentials_configuration.require({"test": ""})


class DomainNameGuessTest(unittest.TestCase):

    def test_simple_case(self):
        assert 'example.com' in \
            dns_common.base_domain_name_guesses("example.com")

    def test_sub_domain(self):
        assert 'example.com' in \
            dns_common.base_domain_name_guesses("foo.bar.baz.example.com")

    def test_second_level_domain(self):
        assert 'example.co.uk' in \
            dns_common.base_domain_name_guesses("foo.bar.baz.example.co.uk")


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