certbot-dns-cloudflare 5.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,124 @@
1
+ """
2
+ The `~certbot_dns_cloudflare.dns_cloudflare` plugin automates the process of
3
+ completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
4
+ subsequently removing, TXT records using the Cloudflare API.
5
+
6
+ .. note::
7
+ The plugin is not installed by default. It can be installed by heading to
8
+ `certbot.eff.org <https://certbot.eff.org/instructions#wildcard>`_, choosing your system and
9
+ selecting the Wildcard tab.
10
+
11
+ Named Arguments
12
+ ---------------
13
+
14
+ ======================================== =====================================
15
+ ``--dns-cloudflare-credentials`` Cloudflare credentials_ INI file.
16
+ (Required)
17
+ ``--dns-cloudflare-propagation-seconds`` The number of seconds to wait for DNS
18
+ to propagate before asking the ACME
19
+ server to verify the DNS record.
20
+ (Default: 10)
21
+ ======================================== =====================================
22
+
23
+
24
+ Credentials
25
+ -----------
26
+
27
+ Use of this plugin requires a configuration file containing Cloudflare API
28
+ credentials, obtained from your
29
+ `Cloudflare dashboard <https://dash.cloudflare.com/?to=/:account/profile/api-tokens>`_.
30
+
31
+ Previously, Cloudflare's "Global API Key" was used for authentication, however
32
+ this key can access the entire Cloudflare API for all domains in your account,
33
+ meaning it could cause a lot of damage if leaked.
34
+
35
+ Cloudflare's newer API Tokens can be restricted to specific domains and
36
+ operations, and are therefore now the recommended authentication option.
37
+
38
+ The Token needed by Certbot requires ``Zone:DNS:Edit`` permissions for only the
39
+ zones you need certificates for.
40
+
41
+ Using Cloudflare Tokens also requires at least version 2.3.1 of the ``cloudflare``
42
+ Python module. If the version that automatically installed with this plugin is
43
+ older than that, and you can't upgrade it on your system, you'll have to stick to
44
+ the Global key.
45
+
46
+ .. code-block:: ini
47
+ :name: certbot_cloudflare_token.ini
48
+ :caption: Example credentials file using restricted API Token (recommended):
49
+
50
+ # Cloudflare API token used by Certbot
51
+ dns_cloudflare_api_token = 0123456789abcdef0123456789abcdef01234567
52
+
53
+ .. code-block:: ini
54
+ :name: certbot_cloudflare_key.ini
55
+ :caption: Example credentials file using Global API Key (not recommended):
56
+
57
+ # Cloudflare API credentials used by Certbot
58
+ dns_cloudflare_email = cloudflare@example.com
59
+ dns_cloudflare_api_key = 0123456789abcdef0123456789abcdef01234
60
+
61
+ The path to this file can be provided interactively or using the
62
+ ``--dns-cloudflare-credentials`` command-line argument. Certbot records the path
63
+ to this file for use during renewal, but does not store the file's contents.
64
+
65
+ .. caution::
66
+ You should protect these API credentials as you would the password to your
67
+ Cloudflare account. Users who can read this file can use these credentials
68
+ to issue arbitrary API calls on your behalf. Users who can cause Certbot to
69
+ run using these credentials can complete a ``dns-01`` challenge to acquire
70
+ new certificates or revoke existing certificates for associated domains,
71
+ even if those domains aren't being managed by this server.
72
+
73
+ Certbot will emit a warning if it detects that the credentials file can be
74
+ accessed by other users on your system. The warning reads "Unsafe permissions
75
+ on credentials configuration file", followed by the path to the credentials
76
+ file. This warning will be emitted each time Certbot uses the credentials file,
77
+ including for renewal, and cannot be silenced except by addressing the issue
78
+ (e.g., by using a command like ``chmod 600`` to restrict access to the file).
79
+
80
+ .. note::
81
+ Please note that the ``cloudflare`` Python module used by the plugin has
82
+ additional methods of providing credentials to the module, e.g. environment
83
+ variables or the ``cloudflare.cfg`` configuration file. These methods are not
84
+ supported by Certbot. If any of those additional methods of providing
85
+ credentials is being used, they must provide the same credentials (i.e.,
86
+ email and API key *or* an API token) as the credentials file provided to
87
+ Certbot. If there is a discrepancy, the ``cloudflare`` Python module will
88
+ raise an error. Also note that the credentials provided to Certbot will take
89
+ precedence over any other method of providing credentials to the ``cloudflare``
90
+ Python module.
91
+
92
+
93
+ Examples
94
+ --------
95
+
96
+ .. code-block:: bash
97
+ :caption: To acquire a certificate for ``example.com``
98
+
99
+ certbot certonly \\
100
+ --dns-cloudflare \\
101
+ --dns-cloudflare-credentials ~/.secrets/certbot/cloudflare.ini \\
102
+ -d example.com
103
+
104
+ .. code-block:: bash
105
+ :caption: To acquire a single certificate for both ``example.com`` and
106
+ ``www.example.com``
107
+
108
+ certbot certonly \\
109
+ --dns-cloudflare \\
110
+ --dns-cloudflare-credentials ~/.secrets/certbot/cloudflare.ini \\
111
+ -d example.com \\
112
+ -d www.example.com
113
+
114
+ .. code-block:: bash
115
+ :caption: To acquire a certificate for ``example.com``, waiting 60 seconds
116
+ for DNS propagation
117
+
118
+ certbot certonly \\
119
+ --dns-cloudflare \\
120
+ --dns-cloudflare-credentials ~/.secrets/certbot/cloudflare.ini \\
121
+ --dns-cloudflare-propagation-seconds 60 \\
122
+ -d example.com
123
+
124
+ """
@@ -0,0 +1 @@
1
+ """Internal implementation of `~certbot_dns_cloudflare.dns_cloudflare` plugin."""
@@ -0,0 +1,271 @@
1
+ """DNS Authenticator for Cloudflare."""
2
+ import logging
3
+ from typing import Any
4
+ from typing import Callable
5
+ from typing import Optional
6
+ from typing import cast
7
+
8
+ import CloudFlare
9
+
10
+ from certbot import errors
11
+ from certbot.plugins import dns_common
12
+ from certbot.plugins.dns_common import CredentialsConfiguration
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ ACCOUNT_URL = 'https://dash.cloudflare.com/?to=/:account/profile/api-tokens'
17
+
18
+
19
+ class Authenticator(dns_common.DNSAuthenticator):
20
+ """DNS Authenticator for Cloudflare
21
+
22
+ This Authenticator uses the Cloudflare API to fulfill a dns-01 challenge.
23
+ """
24
+
25
+ description = ('Obtain certificates using a DNS TXT record (if you are using Cloudflare for '
26
+ 'DNS).')
27
+ ttl = 120
28
+
29
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
30
+ super().__init__(*args, **kwargs)
31
+ self.credentials: Optional[CredentialsConfiguration] = None
32
+
33
+ @classmethod
34
+ def add_parser_arguments(cls, add: Callable[..., None],
35
+ default_propagation_seconds: int = 10) -> None:
36
+ super().add_parser_arguments(add, default_propagation_seconds)
37
+ add('credentials', help='Cloudflare credentials INI file.')
38
+
39
+ def more_info(self) -> str:
40
+ return 'This plugin configures a DNS TXT record to respond to a dns-01 challenge using ' + \
41
+ 'the Cloudflare API.'
42
+
43
+ def _validate_credentials(self, credentials: CredentialsConfiguration) -> None:
44
+ token = credentials.conf('api-token')
45
+ email = credentials.conf('email')
46
+ key = credentials.conf('api-key')
47
+ if token:
48
+ if email or key:
49
+ raise errors.PluginError('{}: dns_cloudflare_email and dns_cloudflare_api_key are '
50
+ 'not needed when using an API Token'
51
+ .format(credentials.confobj.filename))
52
+ elif email or key:
53
+ if not email:
54
+ raise errors.PluginError('{}: dns_cloudflare_email is required when using a Global '
55
+ 'API Key. (should be email address associated with '
56
+ 'Cloudflare account)'.format(credentials.confobj.filename))
57
+ if not key:
58
+ raise errors.PluginError('{}: dns_cloudflare_api_key is required when using a '
59
+ 'Global API Key. (see {})'
60
+ .format(credentials.confobj.filename, ACCOUNT_URL))
61
+ else:
62
+ raise errors.PluginError('{}: Either dns_cloudflare_api_token (recommended), or '
63
+ 'dns_cloudflare_email and dns_cloudflare_api_key are required.'
64
+ ' (see {})'.format(credentials.confobj.filename, ACCOUNT_URL))
65
+
66
+ def _setup_credentials(self) -> None:
67
+ self.credentials = self._configure_credentials(
68
+ 'credentials',
69
+ 'Cloudflare credentials INI file',
70
+ None,
71
+ self._validate_credentials
72
+ )
73
+
74
+ def _perform(self, domain: str, validation_name: str, validation: str) -> None:
75
+ self._get_cloudflare_client().add_txt_record(domain, validation_name, validation, self.ttl)
76
+
77
+ def _cleanup(self, domain: str, validation_name: str, validation: str) -> None:
78
+ self._get_cloudflare_client().del_txt_record(domain, validation_name, validation)
79
+
80
+ def _get_cloudflare_client(self) -> "_CloudflareClient":
81
+ if not self.credentials: # pragma: no cover
82
+ raise errors.Error("Plugin has not been prepared.")
83
+ if self.credentials.conf('api-token'):
84
+ return _CloudflareClient(api_token = self.credentials.conf('api-token'))
85
+ return _CloudflareClient(email = self.credentials.conf('email'),
86
+ api_key = self.credentials.conf('api-key'))
87
+
88
+
89
+ class _CloudflareClient:
90
+ """
91
+ Encapsulates all communication with the Cloudflare API.
92
+ """
93
+
94
+ def __init__(self, email: Optional[str] = None, api_key: Optional[str] = None,
95
+ api_token: Optional[str] = None) -> None:
96
+ if email:
97
+ # If an email was specified, we're using an email/key combination and not a token.
98
+ # We can't use named arguments in this case, as it would break compatibility with
99
+ # the Cloudflare library since version 2.10.1, as the `token` argument was used for
100
+ # tokens and keys alike and the `key` argument did not exist in earlier versions.
101
+ self.cf = CloudFlare.CloudFlare(email, api_key)
102
+ else:
103
+ # If no email was specified, we're using just a token. Let's use the named argument
104
+ # for simplicity, which is compatible with all (current) versions of the Cloudflare
105
+ # library.
106
+ self.cf = CloudFlare.CloudFlare(token=api_token)
107
+
108
+ def add_txt_record(self, domain: str, record_name: str, record_content: str,
109
+ record_ttl: int) -> None:
110
+ """
111
+ Add a TXT record using the supplied information.
112
+
113
+ :param str domain: The domain to use to look up the Cloudflare zone.
114
+ :param str record_name: The record name (typically beginning with '_acme-challenge.').
115
+ :param str record_content: The record content (typically the challenge validation).
116
+ :param int record_ttl: The record TTL (number of seconds that the record may be cached).
117
+ :raises certbot.errors.PluginError: if an error occurs communicating with the Cloudflare API
118
+ """
119
+
120
+ zone_id = self._find_zone_id(domain)
121
+
122
+ data = {'type': 'TXT',
123
+ 'name': record_name,
124
+ 'content': record_content,
125
+ 'ttl': record_ttl}
126
+
127
+ try:
128
+ logger.debug('Attempting to add record to zone %s: %s', zone_id, data)
129
+ self.cf.zones.dns_records.post(zone_id, data=data) # zones | pylint: disable=no-member
130
+ except CloudFlare.exceptions.CloudFlareAPIError as e:
131
+ code = int(e)
132
+ hint = None
133
+
134
+ if code == 1009:
135
+ hint = 'Does your API token have "Zone:DNS:Edit" permissions?'
136
+
137
+ logger.error('Encountered CloudFlareAPIError adding TXT record: %d %s', e, e)
138
+ raise errors.PluginError('Error communicating with the Cloudflare API: {0}{1}'
139
+ .format(e, ' ({0})'.format(hint) if hint else ''))
140
+
141
+ record_id = self._find_txt_record_id(zone_id, record_name, record_content)
142
+ logger.debug('Successfully added TXT record with record_id: %s', record_id)
143
+
144
+ def del_txt_record(self, domain: str, record_name: str, record_content: str) -> None:
145
+ """
146
+ Delete a TXT record using the supplied information.
147
+
148
+ Note that both the record's name and content are used to ensure that similar records
149
+ created concurrently (e.g., due to concurrent invocations of this plugin) are not deleted.
150
+
151
+ Failures are logged, but not raised.
152
+
153
+ :param str domain: The domain to use to look up the Cloudflare zone.
154
+ :param str record_name: The record name (typically beginning with '_acme-challenge.').
155
+ :param str record_content: The record content (typically the challenge validation).
156
+ """
157
+
158
+ try:
159
+ zone_id = self._find_zone_id(domain)
160
+ except errors.PluginError as e:
161
+ logger.debug('Encountered error finding zone_id during deletion: %s', e)
162
+ return
163
+
164
+ if zone_id:
165
+ record_id = self._find_txt_record_id(zone_id, record_name, record_content)
166
+ if record_id:
167
+ try:
168
+ # zones | pylint: disable=no-member
169
+ self.cf.zones.dns_records.delete(zone_id, record_id)
170
+ logger.debug('Successfully deleted TXT record.')
171
+ except CloudFlare.exceptions.CloudFlareAPIError as e:
172
+ logger.warning('Encountered CloudFlareAPIError deleting TXT record: %s', e)
173
+ else:
174
+ logger.debug('TXT record not found; no cleanup needed.')
175
+ else:
176
+ logger.debug('Zone not found; no cleanup needed.')
177
+
178
+ def _find_zone_id(self, domain: str) -> str:
179
+ """
180
+ Find the zone_id for a given domain.
181
+
182
+ :param str domain: The domain for which to find the zone_id.
183
+ :returns: The zone_id, if found.
184
+ :rtype: str
185
+ :raises certbot.errors.PluginError: if no zone_id is found.
186
+ """
187
+
188
+ zone_name_guesses = dns_common.base_domain_name_guesses(domain)
189
+ zones: list[dict[str, Any]] = []
190
+ code = msg = None
191
+
192
+ for zone_name in zone_name_guesses:
193
+ params = {'name': zone_name,
194
+ 'per_page': 1}
195
+
196
+ try:
197
+ zones = self.cf.zones.get(params=params) # zones | pylint: disable=no-member
198
+ except CloudFlare.exceptions.CloudFlareAPIError as e:
199
+ code = int(e)
200
+ msg = str(e)
201
+ hint = None
202
+
203
+ if code == 6003:
204
+ hint = ('Did you copy your entire API token/key? To use Cloudflare tokens, '
205
+ 'you\'ll need the python package cloudflare>=2.3.1.{}'
206
+ .format(' This certbot is running cloudflare ' + str(CloudFlare.__version__)
207
+ if hasattr(CloudFlare, '__version__') else ''))
208
+ elif code == 9103:
209
+ hint = 'Did you enter the correct email address and Global key?'
210
+ elif code == 9109:
211
+ hint = 'Did you enter a valid Cloudflare Token?'
212
+
213
+ if hint:
214
+ raise errors.PluginError('Error determining zone_id: {0} {1}. Please confirm '
215
+ 'that you have supplied valid Cloudflare API credentials. ({2})'
216
+ .format(code, msg, hint))
217
+ else:
218
+ logger.debug('Unrecognised CloudFlareAPIError while finding zone_id: %d %s. '
219
+ 'Continuing with next zone guess...', e, e)
220
+
221
+ if zones:
222
+ zone_id: str = zones[0]['id']
223
+ logger.debug('Found zone_id of %s for %s using name %s', zone_id, domain, zone_name)
224
+ return zone_id
225
+
226
+ if msg is not None:
227
+ if 'com.cloudflare.api.account.zone.list' in msg:
228
+ raise errors.PluginError('Unable to determine zone_id for {0} using zone names: '
229
+ '{1}. Please confirm that the domain name has been '
230
+ 'entered correctly and your Cloudflare Token has access '
231
+ 'to the domain.'.format(domain, zone_name_guesses))
232
+ else:
233
+ raise errors.PluginError('Unable to determine zone_id for {0} using zone names: '
234
+ '{1}. The error from Cloudflare was: {2} {3}.'
235
+ .format(domain, zone_name_guesses, code, msg))
236
+ else:
237
+ raise errors.PluginError('Unable to determine zone_id for {0} using zone names: '
238
+ '{1}. Please confirm that the domain name has been '
239
+ 'entered correctly and is already associated with the '
240
+ 'supplied Cloudflare account.'
241
+ .format(domain, zone_name_guesses))
242
+
243
+ def _find_txt_record_id(self, zone_id: str, record_name: str,
244
+ record_content: str) -> Optional[str]:
245
+ """
246
+ Find the record_id for a TXT record with the given name and content.
247
+
248
+ :param str zone_id: The zone_id which contains the record.
249
+ :param str record_name: The record name (typically beginning with '_acme-challenge.').
250
+ :param str record_content: The record content (typically the challenge validation).
251
+ :returns: The record_id, if found.
252
+ :rtype: str
253
+ """
254
+
255
+ params = {'type': 'TXT',
256
+ 'name': record_name,
257
+ 'content': record_content,
258
+ 'per_page': 1}
259
+ try:
260
+ # zones | pylint: disable=no-member
261
+ records = self.cf.zones.dns_records.get(zone_id, params=params)
262
+ except CloudFlare.exceptions.CloudFlareAPIError as e:
263
+ logger.debug('Encountered CloudFlareAPIError getting TXT record_id: %s', e)
264
+ records = []
265
+
266
+ if records:
267
+ # Cleanup is returning the system to the state we found it. If, for some reason,
268
+ # there are multiple matching records, we only delete one because we only added one.
269
+ return cast(str, records[0]['id'])
270
+ logger.debug('Unable to find TXT record.')
271
+ return None
@@ -0,0 +1 @@
1
+ """certbot-dns-cloudflare tests"""
@@ -0,0 +1,232 @@
1
+ """Tests for certbot_dns_cloudflare._internal.dns_cloudflare."""
2
+
3
+ import sys
4
+ import unittest
5
+ from unittest import mock
6
+
7
+ import CloudFlare
8
+ import pytest
9
+
10
+ from certbot import errors
11
+ from certbot.compat import os
12
+ from certbot.plugins import dns_test_common
13
+ from certbot.plugins.dns_test_common import DOMAIN
14
+ from certbot.tests import util as test_util
15
+
16
+ API_ERROR = CloudFlare.exceptions.CloudFlareAPIError(1000, '', '')
17
+
18
+ API_TOKEN = 'an-api-token'
19
+
20
+ API_KEY = 'an-api-key'
21
+ EMAIL = 'example@example.com'
22
+
23
+
24
+ class AuthenticatorTest(test_util.TempDirTestCase, dns_test_common.BaseAuthenticatorTest):
25
+
26
+ def setUp(self):
27
+ from certbot_dns_cloudflare._internal.dns_cloudflare import Authenticator
28
+
29
+ super().setUp()
30
+
31
+ path = os.path.join(self.tempdir, 'file.ini')
32
+ dns_test_common.write({"cloudflare_email": EMAIL, "cloudflare_api_key": API_KEY}, path)
33
+
34
+ self.config = mock.MagicMock(cloudflare_credentials=path,
35
+ cloudflare_propagation_seconds=0) # don't wait during tests
36
+
37
+ self.auth = Authenticator(self.config, "cloudflare")
38
+
39
+ self.mock_client = mock.MagicMock()
40
+ # _get_cloudflare_client | pylint: disable=protected-access
41
+ # workaround for wont-fix https://github.com/python/mypy/issues/2427 that works with
42
+ # both strict and non-strict mypy
43
+ setattr(self.auth, '_get_cloudflare_client', mock.MagicMock(return_value=self.mock_client))
44
+
45
+ @test_util.patch_display_util()
46
+ def test_perform(self, unused_mock_get_utility):
47
+ self.auth.perform([self.achall])
48
+
49
+ expected = [mock.call.add_txt_record(DOMAIN, '_acme-challenge.'+DOMAIN, mock.ANY, mock.ANY)]
50
+ assert expected == self.mock_client.mock_calls
51
+
52
+ def test_cleanup(self):
53
+ # _attempt_cleanup | pylint: disable=protected-access
54
+ self.auth._attempt_cleanup = True
55
+ self.auth.cleanup([self.achall])
56
+
57
+ expected = [mock.call.del_txt_record(DOMAIN, '_acme-challenge.'+DOMAIN, mock.ANY)]
58
+ assert expected == self.mock_client.mock_calls
59
+
60
+ @test_util.patch_display_util()
61
+ def test_api_token(self, unused_mock_get_utility):
62
+ dns_test_common.write({"cloudflare_api_token": API_TOKEN},
63
+ self.config.cloudflare_credentials)
64
+ self.auth.perform([self.achall])
65
+
66
+ expected = [mock.call.add_txt_record(DOMAIN, '_acme-challenge.'+DOMAIN, mock.ANY, mock.ANY)]
67
+ assert expected == self.mock_client.mock_calls
68
+
69
+ def test_no_creds(self):
70
+ dns_test_common.write({}, self.config.cloudflare_credentials)
71
+ with pytest.raises(errors.PluginError):
72
+ self.auth.perform([self.achall])
73
+
74
+ def test_missing_email_or_key(self):
75
+ dns_test_common.write({"cloudflare_api_key": API_KEY}, self.config.cloudflare_credentials)
76
+ with pytest.raises(errors.PluginError):
77
+ self.auth.perform([self.achall])
78
+
79
+ dns_test_common.write({"cloudflare_email": EMAIL}, self.config.cloudflare_credentials)
80
+ with pytest.raises(errors.PluginError):
81
+ self.auth.perform([self.achall])
82
+
83
+ def test_email_or_key_with_token(self):
84
+ dns_test_common.write({"cloudflare_api_token": API_TOKEN, "cloudflare_email": EMAIL},
85
+ self.config.cloudflare_credentials)
86
+ with pytest.raises(errors.PluginError):
87
+ self.auth.perform([self.achall])
88
+
89
+ dns_test_common.write({"cloudflare_api_token": API_TOKEN, "cloudflare_api_key": API_KEY},
90
+ self.config.cloudflare_credentials)
91
+ with pytest.raises(errors.PluginError):
92
+ self.auth.perform([self.achall])
93
+
94
+ dns_test_common.write({"cloudflare_api_token": API_TOKEN, "cloudflare_email": EMAIL,
95
+ "cloudflare_api_key": API_KEY}, self.config.cloudflare_credentials)
96
+ with pytest.raises(errors.PluginError):
97
+ self.auth.perform([self.achall])
98
+
99
+
100
+ class CloudflareClientTest(unittest.TestCase):
101
+ record_name = "foo"
102
+ record_content = "bar"
103
+ record_ttl = 42
104
+ zone_id = 1
105
+ record_id = 2
106
+
107
+ def setUp(self):
108
+ from certbot_dns_cloudflare._internal.dns_cloudflare import _CloudflareClient
109
+
110
+ self.cloudflare_client = _CloudflareClient(EMAIL, API_KEY)
111
+
112
+ self.cf = mock.MagicMock()
113
+ self.cloudflare_client.cf = self.cf
114
+
115
+ def test_add_txt_record(self):
116
+ self.cf.zones.get.return_value = [{'id': self.zone_id}]
117
+
118
+ self.cloudflare_client.add_txt_record(DOMAIN, self.record_name, self.record_content,
119
+ self.record_ttl)
120
+
121
+ self.cf.zones.dns_records.post.assert_called_with(self.zone_id, data=mock.ANY)
122
+
123
+ post_data = self.cf.zones.dns_records.post.call_args[1]['data']
124
+
125
+ assert 'TXT' == post_data['type']
126
+ assert self.record_name == post_data['name']
127
+ assert self.record_content == post_data['content']
128
+ assert self.record_ttl == post_data['ttl']
129
+
130
+ def test_add_txt_record_error(self):
131
+ self.cf.zones.get.return_value = [{'id': self.zone_id}]
132
+
133
+ self.cf.zones.dns_records.post.side_effect = CloudFlare.exceptions.CloudFlareAPIError(1009, '', '')
134
+
135
+ with pytest.raises(errors.PluginError):
136
+ self.cloudflare_client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
137
+
138
+ def test_add_txt_record_error_during_zone_lookup(self):
139
+ self.cf.zones.get.side_effect = API_ERROR
140
+
141
+ with pytest.raises(errors.PluginError):
142
+ self.cloudflare_client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
143
+
144
+ def test_add_txt_record_zone_not_found(self):
145
+ self.cf.zones.get.return_value = []
146
+
147
+ with pytest.raises(errors.PluginError):
148
+ self.cloudflare_client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
149
+
150
+ def test_add_txt_record_bad_creds(self):
151
+ self.cf.zones.get.side_effect = CloudFlare.exceptions.CloudFlareAPIError(6003, '', '')
152
+ with pytest.raises(errors.PluginError):
153
+ self.cloudflare_client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
154
+
155
+ self.cf.zones.get.side_effect = CloudFlare.exceptions.CloudFlareAPIError(9103, '', '')
156
+ with pytest.raises(errors.PluginError):
157
+ self.cloudflare_client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
158
+
159
+ self.cf.zones.get.side_effect = CloudFlare.exceptions.CloudFlareAPIError(9109, '', '')
160
+ with pytest.raises(errors.PluginError):
161
+ self.cloudflare_client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
162
+
163
+ self.cf.zones.get.side_effect = CloudFlare.exceptions.CloudFlareAPIError(0, 'com.cloudflare.api.account.zone.list', '')
164
+ with pytest.raises(errors.PluginError):
165
+ self.cloudflare_client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
166
+
167
+ def test_del_txt_record(self):
168
+ self.cf.zones.get.return_value = [{'id': self.zone_id}]
169
+ self.cf.zones.dns_records.get.return_value = [{'id': self.record_id}]
170
+
171
+ self.cloudflare_client.del_txt_record(DOMAIN, self.record_name, self.record_content)
172
+
173
+ expected = [mock.call.zones.get(params=mock.ANY),
174
+ mock.call.zones.dns_records.get(self.zone_id, params=mock.ANY),
175
+ mock.call.zones.dns_records.delete(self.zone_id, self.record_id)]
176
+
177
+ assert expected == self.cf.mock_calls
178
+
179
+ get_data = self.cf.zones.dns_records.get.call_args[1]['params']
180
+
181
+ assert 'TXT' == get_data['type']
182
+ assert self.record_name == get_data['name']
183
+ assert self.record_content == get_data['content']
184
+
185
+ def test_del_txt_record_error_during_zone_lookup(self):
186
+ self.cf.zones.get.side_effect = API_ERROR
187
+
188
+ self.cloudflare_client.del_txt_record(DOMAIN, self.record_name, self.record_content)
189
+
190
+ def test_del_txt_record_error_during_delete(self):
191
+ self.cf.zones.get.return_value = [{'id': self.zone_id}]
192
+ self.cf.zones.dns_records.get.return_value = [{'id': self.record_id}]
193
+ self.cf.zones.dns_records.delete.side_effect = API_ERROR
194
+
195
+ self.cloudflare_client.del_txt_record(DOMAIN, self.record_name, self.record_content)
196
+ expected = [mock.call.zones.get(params=mock.ANY),
197
+ mock.call.zones.dns_records.get(self.zone_id, params=mock.ANY),
198
+ mock.call.zones.dns_records.delete(self.zone_id, self.record_id)]
199
+
200
+ assert expected == self.cf.mock_calls
201
+
202
+ def test_del_txt_record_error_during_get(self):
203
+ self.cf.zones.get.return_value = [{'id': self.zone_id}]
204
+ self.cf.zones.dns_records.get.side_effect = API_ERROR
205
+
206
+ self.cloudflare_client.del_txt_record(DOMAIN, self.record_name, self.record_content)
207
+ expected = [mock.call.zones.get(params=mock.ANY),
208
+ mock.call.zones.dns_records.get(self.zone_id, params=mock.ANY)]
209
+
210
+ assert expected == self.cf.mock_calls
211
+
212
+ def test_del_txt_record_no_record(self):
213
+ self.cf.zones.get.return_value = [{'id': self.zone_id}]
214
+ self.cf.zones.dns_records.get.return_value = []
215
+
216
+ self.cloudflare_client.del_txt_record(DOMAIN, self.record_name, self.record_content)
217
+ expected = [mock.call.zones.get(params=mock.ANY),
218
+ mock.call.zones.dns_records.get(self.zone_id, params=mock.ANY)]
219
+
220
+ assert expected == self.cf.mock_calls
221
+
222
+ def test_del_txt_record_no_zone(self):
223
+ self.cf.zones.get.return_value = [{'id': None}]
224
+
225
+ self.cloudflare_client.del_txt_record(DOMAIN, self.record_name, self.record_content)
226
+ expected = [mock.call.zones.get(params=mock.ANY)]
227
+
228
+ assert expected == self.cf.mock_calls
229
+
230
+
231
+ if __name__ == "__main__":
232
+ sys.exit(pytest.main(sys.argv[1:] + [__file__])) # pragma: no cover
File without changes
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: certbot-dns-cloudflare
3
+ Version: 5.2.2
4
+ Summary: Cloudflare DNS Authenticator plugin for Certbot
5
+ Author-email: Certbot Project <certbot-dev@eff.org>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/certbot/certbot
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Environment :: Plugins
10
+ Classifier: Intended Audience :: System Administrators
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Internet :: WWW/HTTP
20
+ Classifier: Topic :: Security
21
+ Classifier: Topic :: System :: Installation/Setup
22
+ Classifier: Topic :: System :: Networking
23
+ Classifier: Topic :: System :: Systems Administration
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/x-rst
27
+ License-File: LICENSE.txt
28
+ Requires-Dist: cloudflare<2.20,>=2.19
29
+ Requires-Dist: acme>=5.2.2
30
+ Requires-Dist: certbot>=5.2.2
31
+ Provides-Extra: docs
32
+ Requires-Dist: Sphinx>=1.0; extra == "docs"
33
+ Requires-Dist: sphinx_rtd_theme; extra == "docs"
34
+ Provides-Extra: test
35
+ Requires-Dist: pytest; extra == "test"
36
+ Dynamic: license-file
37
+ Dynamic: requires-dist
38
+
39
+ Cloudflare DNS Authenticator plugin for Certbot
@@ -0,0 +1,12 @@
1
+ certbot_dns_cloudflare/__init__.py,sha256=zsXCb3xQiTf2lMgP6ZNuVDmPTCNnNRnlvKdDII6y17g,5309
2
+ certbot_dns_cloudflare/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ certbot_dns_cloudflare/_internal/__init__.py,sha256=CCYNHwFnJrHaoTkrPUFpa_3nZ_Pm7OmMnyGuyVGw5vE,82
4
+ certbot_dns_cloudflare/_internal/dns_cloudflare.py,sha256=y-p7hGE0L5G1L1Rw8yb2giIs47TXiZHHRpGA3LUZYgM,12903
5
+ certbot_dns_cloudflare/_internal/tests/__init__.py,sha256=MbqDbTr6GZnXfwy6j10aVdMvUskG8aqaiPXNN1m4fFA,35
6
+ certbot_dns_cloudflare/_internal/tests/dns_cloudflare_test.py,sha256=nqCJ_gsq6gtjN_m2-yFQqu50I-D9TlTKthV1AShKb-U,9913
7
+ certbot_dns_cloudflare-5.2.2.dist-info/licenses/LICENSE.txt,sha256=LMXecVrlqXbwhvukkwiAyeQhkUFz_IURG_9RTUdXEj8,10786
8
+ certbot_dns_cloudflare-5.2.2.dist-info/METADATA,sha256=qNURNgl5WRmPAMn89bcdZrHnB9y2pAojX_Mh-3tbCqE,1502
9
+ certbot_dns_cloudflare-5.2.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ certbot_dns_cloudflare-5.2.2.dist-info/entry_points.txt,sha256=UQ4767VWBw1kU_OiYE2e5JlITDWBdE2sNjpIXzmQpBI,97
11
+ certbot_dns_cloudflare-5.2.2.dist-info/top_level.txt,sha256=W4gG-UxoubWE4DhflM9xD-iv6fxoTGlgUgcGx6iR8xM,23
12
+ certbot_dns_cloudflare-5.2.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [certbot.plugins]
2
+ dns-cloudflare = certbot_dns_cloudflare._internal.dns_cloudflare:Authenticator
@@ -0,0 +1,190 @@
1
+ Copyright 2015 Electronic Frontier Foundation and others
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ Apache License
16
+ Version 2.0, January 2004
17
+ http://www.apache.org/licenses/
18
+
19
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
20
+
21
+ 1. Definitions.
22
+
23
+ "License" shall mean the terms and conditions for use, reproduction,
24
+ and distribution as defined by Sections 1 through 9 of this document.
25
+
26
+ "Licensor" shall mean the copyright owner or entity authorized by
27
+ the copyright owner that is granting the License.
28
+
29
+ "Legal Entity" shall mean the union of the acting entity and all
30
+ other entities that control, are controlled by, or are under common
31
+ control with that entity. For the purposes of this definition,
32
+ "control" means (i) the power, direct or indirect, to cause the
33
+ direction or management of such entity, whether by contract or
34
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
35
+ outstanding shares, or (iii) beneficial ownership of such entity.
36
+
37
+ "You" (or "Your") shall mean an individual or Legal Entity
38
+ exercising permissions granted by this License.
39
+
40
+ "Source" form shall mean the preferred form for making modifications,
41
+ including but not limited to software source code, documentation
42
+ source, and configuration files.
43
+
44
+ "Object" form shall mean any form resulting from mechanical
45
+ transformation or translation of a Source form, including but
46
+ not limited to compiled object code, generated documentation,
47
+ and conversions to other media types.
48
+
49
+ "Work" shall mean the work of authorship, whether in Source or
50
+ Object form, made available under the License, as indicated by a
51
+ copyright notice that is included in or attached to the work
52
+ (an example is provided in the Appendix below).
53
+
54
+ "Derivative Works" shall mean any work, whether in Source or Object
55
+ form, that is based on (or derived from) the Work and for which the
56
+ editorial revisions, annotations, elaborations, or other modifications
57
+ represent, as a whole, an original work of authorship. For the purposes
58
+ of this License, Derivative Works shall not include works that remain
59
+ separable from, or merely link (or bind by name) to the interfaces of,
60
+ the Work and Derivative Works thereof.
61
+
62
+ "Contribution" shall mean any work of authorship, including
63
+ the original version of the Work and any modifications or additions
64
+ to that Work or Derivative Works thereof, that is intentionally
65
+ submitted to Licensor for inclusion in the Work by the copyright owner
66
+ or by an individual or Legal Entity authorized to submit on behalf of
67
+ the copyright owner. For the purposes of this definition, "submitted"
68
+ means any form of electronic, verbal, or written communication sent
69
+ to the Licensor or its representatives, including but not limited to
70
+ communication on electronic mailing lists, source code control systems,
71
+ and issue tracking systems that are managed by, or on behalf of, the
72
+ Licensor for the purpose of discussing and improving the Work, but
73
+ excluding communication that is conspicuously marked or otherwise
74
+ designated in writing by the copyright owner as "Not a Contribution."
75
+
76
+ "Contributor" shall mean Licensor and any individual or Legal Entity
77
+ on behalf of whom a Contribution has been received by Licensor and
78
+ subsequently incorporated within the Work.
79
+
80
+ 2. Grant of Copyright License. Subject to the terms and conditions of
81
+ this License, each Contributor hereby grants to You a perpetual,
82
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
83
+ copyright license to reproduce, prepare Derivative Works of,
84
+ publicly display, publicly perform, sublicense, and distribute the
85
+ Work and such Derivative Works in Source or Object form.
86
+
87
+ 3. Grant of Patent License. Subject to the terms and conditions of
88
+ this License, each Contributor hereby grants to You a perpetual,
89
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
90
+ (except as stated in this section) patent license to make, have made,
91
+ use, offer to sell, sell, import, and otherwise transfer the Work,
92
+ where such license applies only to those patent claims licensable
93
+ by such Contributor that are necessarily infringed by their
94
+ Contribution(s) alone or by combination of their Contribution(s)
95
+ with the Work to which such Contribution(s) was submitted. If You
96
+ institute patent litigation against any entity (including a
97
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
98
+ or a Contribution incorporated within the Work constitutes direct
99
+ or contributory patent infringement, then any patent licenses
100
+ granted to You under this License for that Work shall terminate
101
+ as of the date such litigation is filed.
102
+
103
+ 4. Redistribution. You may reproduce and distribute copies of the
104
+ Work or Derivative Works thereof in any medium, with or without
105
+ modifications, and in Source or Object form, provided that You
106
+ meet the following conditions:
107
+
108
+ (a) You must give any other recipients of the Work or
109
+ Derivative Works a copy of this License; and
110
+
111
+ (b) You must cause any modified files to carry prominent notices
112
+ stating that You changed the files; and
113
+
114
+ (c) You must retain, in the Source form of any Derivative Works
115
+ that You distribute, all copyright, patent, trademark, and
116
+ attribution notices from the Source form of the Work,
117
+ excluding those notices that do not pertain to any part of
118
+ the Derivative Works; and
119
+
120
+ (d) If the Work includes a "NOTICE" text file as part of its
121
+ distribution, then any Derivative Works that You distribute must
122
+ include a readable copy of the attribution notices contained
123
+ within such NOTICE file, excluding those notices that do not
124
+ pertain to any part of the Derivative Works, in at least one
125
+ of the following places: within a NOTICE text file distributed
126
+ as part of the Derivative Works; within the Source form or
127
+ documentation, if provided along with the Derivative Works; or,
128
+ within a display generated by the Derivative Works, if and
129
+ wherever such third-party notices normally appear. The contents
130
+ of the NOTICE file are for informational purposes only and
131
+ do not modify the License. You may add Your own attribution
132
+ notices within Derivative Works that You distribute, alongside
133
+ or as an addendum to the NOTICE text from the Work, provided
134
+ that such additional attribution notices cannot be construed
135
+ as modifying the License.
136
+
137
+ You may add Your own copyright statement to Your modifications and
138
+ may provide additional or different license terms and conditions
139
+ for use, reproduction, or distribution of Your modifications, or
140
+ for any such Derivative Works as a whole, provided Your use,
141
+ reproduction, and distribution of the Work otherwise complies with
142
+ the conditions stated in this License.
143
+
144
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
145
+ any Contribution intentionally submitted for inclusion in the Work
146
+ by You to the Licensor shall be under the terms and conditions of
147
+ this License, without any additional terms or conditions.
148
+ Notwithstanding the above, nothing herein shall supersede or modify
149
+ the terms of any separate license agreement you may have executed
150
+ with Licensor regarding such Contributions.
151
+
152
+ 6. Trademarks. This License does not grant permission to use the trade
153
+ names, trademarks, service marks, or product names of the Licensor,
154
+ except as required for reasonable and customary use in describing the
155
+ origin of the Work and reproducing the content of the NOTICE file.
156
+
157
+ 7. Disclaimer of Warranty. Unless required by applicable law or
158
+ agreed to in writing, Licensor provides the Work (and each
159
+ Contributor provides its Contributions) on an "AS IS" BASIS,
160
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
161
+ implied, including, without limitation, any warranties or conditions
162
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
163
+ PARTICULAR PURPOSE. You are solely responsible for determining the
164
+ appropriateness of using or redistributing the Work and assume any
165
+ risks associated with Your exercise of permissions under this License.
166
+
167
+ 8. Limitation of Liability. In no event and under no legal theory,
168
+ whether in tort (including negligence), contract, or otherwise,
169
+ unless required by applicable law (such as deliberate and grossly
170
+ negligent acts) or agreed to in writing, shall any Contributor be
171
+ liable to You for damages, including any direct, indirect, special,
172
+ incidental, or consequential damages of any character arising as a
173
+ result of this License or out of the use or inability to use the
174
+ Work (including but not limited to damages for loss of goodwill,
175
+ work stoppage, computer failure or malfunction, or any and all
176
+ other commercial damages or losses), even if such Contributor
177
+ has been advised of the possibility of such damages.
178
+
179
+ 9. Accepting Warranty or Additional Liability. While redistributing
180
+ the Work or Derivative Works thereof, You may choose to offer,
181
+ and charge a fee for, acceptance of support, warranty, indemnity,
182
+ or other liability obligations and/or rights consistent with this
183
+ License. However, in accepting such obligations, You may act only
184
+ on Your own behalf and on Your sole responsibility, not on behalf
185
+ of any other Contributor, and only if You agree to indemnify,
186
+ defend, and hold each Contributor harmless for any liability
187
+ incurred by, or claims asserted against, such Contributor by reason
188
+ of your accepting any such warranty or additional liability.
189
+
190
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1 @@
1
+ certbot_dns_cloudflare