certbot-dns-poweradmin 0.1.1__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,103 @@
1
+ """
2
+ The `~certbot_dns_poweradmin._internal.dns_poweradmin` plugin automates the process of
3
+ completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
4
+ subsequently removing, TXT records using the PowerAdmin API.
5
+
6
+
7
+ Named Arguments
8
+ ---------------
9
+
10
+ ========================================== ===================================
11
+ ``--dns-poweradmin-credentials`` PowerAdmin credentials INI file.
12
+ (Required)
13
+ ``--dns-poweradmin-propagation-seconds`` The number of seconds to wait for
14
+ DNS to propagate before asking the
15
+ ACME server to verify the DNS
16
+ record.
17
+ (Default: 120)
18
+ ========================================== ===================================
19
+
20
+
21
+ Credentials
22
+ -----------
23
+
24
+ Use of this plugin requires a configuration file containing PowerAdmin API
25
+ credentials, obtained from your PowerAdmin installation.
26
+
27
+ .. code-block:: ini
28
+ :name: credentials.ini
29
+ :caption: Example credentials file:
30
+
31
+ # PowerAdmin API credentials
32
+ dns_poweradmin_api_url = https://poweradmin.example.com
33
+ dns_poweradmin_api_key = your-api-key-here
34
+ dns_poweradmin_api_version = v2
35
+
36
+ The path to this file can be provided interactively or using the
37
+ ``--dns-poweradmin-credentials`` command-line argument. Certbot records the path
38
+ to this file for use during renewal but does not store the file's contents.
39
+
40
+ .. caution::
41
+ You should protect these API credentials as you would the password to your
42
+ PowerAdmin account. Users who can read this file can use these credentials
43
+ to issue arbitrary API calls on your behalf. Users who can cause Certbot to
44
+ run using these credentials can complete a ``dns-01`` challenge to acquire
45
+ new certificates or revoke existing certificates for associated domains,
46
+ even if this server isn't managing those domains.
47
+
48
+ Certbot will emit a warning if it detects that the credential file can be
49
+ accessed by other users on your system. The warning reads "Unsafe permissions
50
+ on credential configuration file", followed by the path to the credential
51
+ file. This warning will be emitted each time Certbot uses the credential file,
52
+ including for renewal, and cannot be silenced except by addressing the issue
53
+ (e.g., by using a command like ``chmod 600`` to restrict access to the file).
54
+
55
+
56
+ API Version
57
+ -----------
58
+
59
+ PowerAdmin supports two API versions:
60
+
61
+ - ``v1``: Stable API version
62
+ - ``v2``: Enhanced API with additional features (default)
63
+
64
+ You can specify the API version in your credential file using the
65
+ ``dns_poweradmin_api_version`` option. If not specified, ``v2`` is used by default.
66
+
67
+
68
+ Examples
69
+ --------
70
+
71
+ .. code-block:: bash
72
+ :caption: To acquire a certificate for ``example.com``
73
+
74
+ certbot certonly \\
75
+ --authenticator dns-poweradmin \\
76
+ --dns-poweradmin-credentials ~/.secrets/certbot/poweradmin.ini \\
77
+ -d example.com
78
+
79
+ .. code-block:: bash
80
+ :caption: To acquire a single certificate for both ``example.com`` and
81
+ ``www.example.com``
82
+
83
+ certbot certonly \\
84
+ --authenticator dns-poweradmin \\
85
+ --dns-poweradmin-credentials ~/.secrets/certbot/poweradmin.ini \\
86
+ -d example.com \\
87
+ -d www.example.com
88
+
89
+ .. code-block:: bash
90
+ :caption: To acquire a certificate for ``example.com``, waiting 300 seconds
91
+ for DNS propagation
92
+
93
+ certbot certonly \\
94
+ --authenticator dns-poweradmin \\
95
+ --dns-poweradmin-credentials ~/.secrets/certbot/poweradmin.ini \\
96
+ --dns-poweradmin-propagation-seconds 300 \\
97
+ -d example.com
98
+
99
+ """
100
+
101
+ from certbot_dns_poweradmin._internal.dns_poweradmin import Authenticator
102
+
103
+ __all__ = ["Authenticator"]
@@ -0,0 +1 @@
1
+ """Internal implementation of certbot-dns-poweradmin plugin."""
@@ -0,0 +1,315 @@
1
+ """DNS Authenticator for PowerAdmin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import Callable
7
+ from typing import Any
8
+
9
+ import requests
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
+ DEFAULT_API_VERSION = "v2"
17
+ SUPPORTED_API_VERSIONS = ("v1", "v2")
18
+
19
+
20
+ class Authenticator(dns_common.DNSAuthenticator):
21
+ """DNS Authenticator for PowerAdmin.
22
+
23
+ This Authenticator uses the PowerAdmin API to fulfill a dns-01 challenge.
24
+ """
25
+
26
+ description = (
27
+ "Obtain certificates using a DNS TXT record (if you are using PowerAdmin for DNS)."
28
+ )
29
+ ttl = 120
30
+
31
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
32
+ super().__init__(*args, **kwargs)
33
+ self.credentials: CredentialsConfiguration | None = None
34
+
35
+ @classmethod
36
+ def add_parser_arguments(
37
+ cls, add: Callable[..., None], default_propagation_seconds: int = 120
38
+ ) -> None:
39
+ super().add_parser_arguments(add, default_propagation_seconds)
40
+ add("credentials", help="PowerAdmin credentials INI file.")
41
+
42
+ def more_info(self) -> str:
43
+ return (
44
+ "This plugin configures a DNS TXT record to respond to a dns-01 challenge "
45
+ "using the PowerAdmin API."
46
+ )
47
+
48
+ def _setup_credentials(self) -> None:
49
+ self.credentials = self._configure_credentials(
50
+ "credentials",
51
+ "PowerAdmin credentials INI file",
52
+ None,
53
+ self._validate_credentials,
54
+ )
55
+
56
+ def _validate_credentials(self, credentials: CredentialsConfiguration) -> None:
57
+ api_url = credentials.conf("api-url")
58
+ api_key = credentials.conf("api-key")
59
+ api_version = credentials.conf("api-version")
60
+
61
+ if not api_url:
62
+ raise errors.PluginError("PowerAdmin API URL is required (dns_poweradmin_api_url)")
63
+ if not api_key:
64
+ raise errors.PluginError("PowerAdmin API key is required (dns_poweradmin_api_key)")
65
+ if api_version and api_version not in SUPPORTED_API_VERSIONS:
66
+ raise errors.PluginError(
67
+ f"Invalid API version: {api_version}. "
68
+ f"Supported versions: {', '.join(SUPPORTED_API_VERSIONS)}"
69
+ )
70
+
71
+ def _perform(self, domain: str, validation_name: str, validation: str) -> None:
72
+ self._get_poweradmin_client().add_txt_record(domain, validation_name, validation, self.ttl)
73
+
74
+ def _cleanup(self, domain: str, validation_name: str, validation: str) -> None:
75
+ self._get_poweradmin_client().del_txt_record(domain, validation_name, validation)
76
+
77
+ def _get_poweradmin_client(self) -> _PowerAdminClient:
78
+ if self.credentials is None:
79
+ raise errors.PluginError("Credentials not configured")
80
+
81
+ api_url = self.credentials.conf("api-url")
82
+ api_key = self.credentials.conf("api-key")
83
+ api_version = self.credentials.conf("api-version") or DEFAULT_API_VERSION
84
+
85
+ # These are validated in _validate_credentials, so they should never be None
86
+ assert api_url is not None
87
+ assert api_key is not None
88
+
89
+ return _PowerAdminClient(
90
+ api_url=api_url,
91
+ api_key=api_key,
92
+ api_version=api_version,
93
+ )
94
+
95
+
96
+ class _PowerAdminClient:
97
+ """Encapsulates all communication with the PowerAdmin API."""
98
+
99
+ def __init__(self, api_url: str, api_key: str, api_version: str = "v2") -> None:
100
+ self.api_url = api_url.rstrip("/")
101
+ self.api_key = api_key
102
+ self.api_version = api_version
103
+ self.session = requests.Session()
104
+ self.session.headers.update(
105
+ {
106
+ "X-API-Key": self.api_key,
107
+ "Content-Type": "application/json",
108
+ "Accept": "application/json",
109
+ }
110
+ )
111
+
112
+ def add_txt_record(
113
+ self, domain: str, record_name: str, record_content: str, record_ttl: int
114
+ ) -> None:
115
+ """Add a TXT record using the PowerAdmin API.
116
+
117
+ Args:
118
+ domain: The domain to use for finding the zone.
119
+ record_name: The record name (FQDN, e.g., _acme-challenge.example.com).
120
+ record_content: The record content (validation token).
121
+ record_ttl: The record TTL in seconds.
122
+ """
123
+ zone_id, _zone_name = self._find_zone_id(domain)
124
+ if zone_id is None:
125
+ raise errors.PluginError(f"Unable to find a PowerAdmin zone for {domain}")
126
+
127
+ # Check if a record already exists (idempotent)
128
+ existing_record = self._find_txt_record(zone_id, record_name, record_content)
129
+ if existing_record is not None:
130
+ logger.debug("TXT record already exists, skipping creation")
131
+ return
132
+
133
+ # Create the TXT record
134
+ record_data = {
135
+ "name": record_name,
136
+ "type": "TXT",
137
+ "content": record_content,
138
+ "ttl": record_ttl,
139
+ }
140
+
141
+ url = f"{self.api_url}/api/{self.api_version}/zones/{zone_id}/records"
142
+ try:
143
+ response = self.session.post(url, json=record_data)
144
+ response.raise_for_status()
145
+ logger.debug("Successfully added TXT record for %s", record_name)
146
+ except requests.exceptions.HTTPError as e:
147
+ hint = self._get_error_hint(e.response)
148
+ raise errors.PluginError(f"Error adding TXT record: {e}{hint}") from e
149
+ except requests.exceptions.RequestException as e:
150
+ raise errors.PluginError(f"Error communicating with PowerAdmin API: {e}") from e
151
+
152
+ def del_txt_record(self, domain: str, record_name: str, record_content: str) -> None:
153
+ """Delete a TXT record using the PowerAdmin API.
154
+
155
+ Args:
156
+ domain: The domain to use for finding the zone.
157
+ record_name: The record name (FQDN).
158
+ record_content: The record content (validation token).
159
+ """
160
+ try:
161
+ zone_id, _zone_name = self._find_zone_id(domain)
162
+ if zone_id is None:
163
+ logger.debug("Unable to find zone for %s during cleanup", domain)
164
+ return
165
+
166
+ record = self._find_txt_record(zone_id, record_name, record_content)
167
+ if record is None:
168
+ logger.debug("TXT record not found for %s during cleanup", record_name)
169
+ return
170
+
171
+ record_id = record.get("id")
172
+ if record_id is None:
173
+ logger.warning("Record found but has no ID, cannot delete")
174
+ return
175
+
176
+ url = f"{self.api_url}/api/{self.api_version}/zones/{zone_id}/records/{record_id}"
177
+ response = self.session.delete(url)
178
+ response.raise_for_status()
179
+ logger.debug("Successfully deleted TXT record for %s", record_name)
180
+
181
+ except requests.exceptions.RequestException as e:
182
+ logger.warning("Error deleting TXT record during cleanup: %s", e)
183
+
184
+ def _find_zone_id(self, domain: str) -> tuple[int | None, str | None]:
185
+ """Find the zone ID for a given domain.
186
+
187
+ Args:
188
+ domain: The domain being validated.
189
+
190
+ Returns:
191
+ Tuple of (zone_id, zone_name) or (None, None) if not found.
192
+ """
193
+ zone_name_guesses = dns_common.base_domain_name_guesses(domain)
194
+
195
+ for zone_name in zone_name_guesses:
196
+ logger.debug("Looking for zone: %s", zone_name)
197
+ zone_id = self._get_zone_id_by_name(zone_name)
198
+ if zone_id is not None:
199
+ logger.debug("Found zone %s with ID %s", zone_name, zone_id)
200
+ return zone_id, zone_name
201
+
202
+ return None, None
203
+
204
+ def _get_zone_id_by_name(self, zone_name: str) -> int | None:
205
+ """Get zone ID by zone name from PowerAdmin API.
206
+
207
+ Args:
208
+ zone_name: The zone name to look up.
209
+
210
+ Returns:
211
+ The zone ID if found, None otherwise.
212
+ """
213
+ url = f"{self.api_url}/api/{self.api_version}/zones"
214
+ try:
215
+ response = self.session.get(url)
216
+ response.raise_for_status()
217
+ zones = response.json()
218
+
219
+ # Handle various response formats from PowerAdmin API
220
+ if isinstance(zones, dict) and "data" in zones:
221
+ zones = zones["data"]
222
+ # API v2 returns {"data": {"zones": [...]}}
223
+ if isinstance(zones, dict) and "zones" in zones:
224
+ zones = zones["zones"]
225
+
226
+ for zone in zones:
227
+ # Zone name might be stored with or without a trailing dot
228
+ zone_stored_name = zone.get("name", "").rstrip(".")
229
+ if zone_stored_name == zone_name or zone_stored_name == zone_name.rstrip("."):
230
+ zone_id: int | None = zone.get("id")
231
+ return zone_id
232
+
233
+ return None
234
+
235
+ except requests.exceptions.RequestException as e:
236
+ logger.debug("Error fetching zones: %s", e)
237
+ return None
238
+
239
+ def _find_txt_record(
240
+ self, zone_id: int, record_name: str, record_content: str
241
+ ) -> dict[str, Any] | None:
242
+ """Find a specific TXT record in a zone.
243
+
244
+ Args:
245
+ zone_id: The zone ID to search in.
246
+ record_name: The record name to find.
247
+ record_content: The record content to match.
248
+
249
+ Returns:
250
+ The record dict if found, None otherwise.
251
+ """
252
+ url = f"{self.api_url}/api/{self.api_version}/zones/{zone_id}/records"
253
+ try:
254
+ response = self.session.get(url)
255
+ response.raise_for_status()
256
+ records = response.json()
257
+
258
+ # Handle both list and dict response formats
259
+ if isinstance(records, dict) and "data" in records:
260
+ records = records["data"]
261
+
262
+ for record in records:
263
+ if record.get("type") != "TXT":
264
+ continue
265
+
266
+ # Compare record name (with or without a trailing dot)
267
+ stored_name = record.get("name", "").rstrip(".")
268
+ target_name = record_name.rstrip(".")
269
+ if stored_name != target_name:
270
+ continue
271
+
272
+ # Compare content (may be quoted in API response)
273
+ stored_content = record.get("content", "").strip('"')
274
+ if stored_content == record_content:
275
+ result: dict[str, Any] = record
276
+ return result
277
+
278
+ return None
279
+
280
+ except requests.exceptions.RequestException as e:
281
+ logger.debug("Error fetching records: %s", e)
282
+ return None
283
+
284
+ @staticmethod
285
+ def _get_error_hint(response: requests.Response | None) -> str:
286
+ """Extract error hint from API response.
287
+
288
+ Args:
289
+ response: The HTTP response object.
290
+
291
+ Returns:
292
+ A hint string for the error, or empty string.
293
+ """
294
+ if response is None:
295
+ return ""
296
+
297
+ hint = ""
298
+ try:
299
+ error_data = response.json()
300
+ if isinstance(error_data, dict):
301
+ message = error_data.get("message") or error_data.get("error")
302
+ if message:
303
+ hint = f" ({message})"
304
+ except (ValueError, KeyError):
305
+ pass
306
+
307
+ # Add specific hints based on the status code
308
+ if response.status_code == 401:
309
+ hint = hint or " (Is your API key correct?)"
310
+ elif response.status_code == 403:
311
+ hint = hint or " (Does your API key have sufficient permissions?)"
312
+ elif response.status_code == 404:
313
+ hint = hint or " (Zone or record not found)"
314
+
315
+ return hint
@@ -0,0 +1 @@
1
+ """Tests for certbot-dns-poweradmin plugin."""
@@ -0,0 +1,283 @@
1
+ """Tests for certbot_dns_poweradmin._internal.dns_poweradmin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import unittest
6
+ from unittest import mock
7
+
8
+ import requests_mock
9
+ from certbot import errors
10
+ from certbot.compat import os
11
+ from certbot.plugins import dns_test_common
12
+ from certbot.plugins.dns_test_common import DOMAIN
13
+ from certbot.tests import util as test_util
14
+
15
+ from certbot_dns_poweradmin import Authenticator
16
+ from certbot_dns_poweradmin._internal.dns_poweradmin import _PowerAdminClient
17
+
18
+ API_URL = "https://poweradmin.example.com"
19
+ API_KEY = "test-api-key"
20
+ API_VERSION = "v2"
21
+
22
+
23
+ class AuthenticatorTest(test_util.TempDirTestCase, dns_test_common.BaseAuthenticatorTest):
24
+ """Tests for Authenticator class."""
25
+
26
+ def setUp(self) -> None:
27
+ super().setUp()
28
+
29
+ path = os.path.join(self.tempdir, "credentials.ini")
30
+ dns_test_common.write(
31
+ {
32
+ "poweradmin_api_url": API_URL,
33
+ "poweradmin_api_key": API_KEY,
34
+ "poweradmin_api_version": API_VERSION,
35
+ },
36
+ path,
37
+ )
38
+
39
+ self.config = mock.MagicMock(
40
+ poweradmin_credentials=path,
41
+ poweradmin_propagation_seconds=0,
42
+ )
43
+ self.auth = Authenticator(self.config, "poweradmin")
44
+
45
+ self.mock_client = mock.MagicMock()
46
+ self.auth._get_poweradmin_client = mock.MagicMock(return_value=self.mock_client)
47
+
48
+ @test_util.patch_display_util()
49
+ def test_perform(self, _: mock.MagicMock) -> None:
50
+ self.auth.perform([self.achall])
51
+ expected = [
52
+ mock.call.add_txt_record(DOMAIN, "_acme-challenge." + DOMAIN, mock.ANY, mock.ANY)
53
+ ]
54
+ self.assertEqual(expected, self.mock_client.mock_calls)
55
+
56
+ @test_util.patch_display_util()
57
+ def test_cleanup(self, _: mock.MagicMock) -> None:
58
+ self.auth._attempt_cleanup = True
59
+ self.auth.cleanup([self.achall])
60
+ expected = [mock.call.del_txt_record(DOMAIN, "_acme-challenge." + DOMAIN, mock.ANY)]
61
+ self.assertEqual(expected, self.mock_client.mock_calls)
62
+
63
+
64
+ class PowerAdminClientTest(unittest.TestCase):
65
+ """Tests for _PowerAdminClient class."""
66
+
67
+ record_name = "_acme-challenge.example.com"
68
+ record_content = "validation-token"
69
+ record_ttl = 120
70
+
71
+ def setUp(self) -> None:
72
+ self.adapter = requests_mock.Adapter()
73
+ self.client = _PowerAdminClient(API_URL, API_KEY, API_VERSION)
74
+ self.client.session.mount("https://", self.adapter)
75
+
76
+ def _register_zones_response(
77
+ self, zones: list[dict] | None = None, api_v2_format: bool = False
78
+ ) -> None:
79
+ """Register a mock response for zones endpoint.
80
+
81
+ Args:
82
+ zones: List of zone dicts.
83
+ api_v2_format: If True, wrap in {"data": {"zones": [...]}},
84
+ otherwise use {"data": [...]}.
85
+ """
86
+ if zones is None:
87
+ zones = [{"id": 1, "name": "example.com"}]
88
+
89
+ data: dict[str, list[dict[str, str | int]]] | list[dict[str, str | int]] = (
90
+ {"zones": zones} if api_v2_format else zones
91
+ )
92
+ response = {"data": data}
93
+
94
+ self.adapter.register_uri(
95
+ "GET",
96
+ f"{API_URL}/api/{API_VERSION}/zones",
97
+ json=response,
98
+ )
99
+
100
+ def _register_records_response(
101
+ self, zone_id: int = 1, records: list[dict] | None = None
102
+ ) -> None:
103
+ """Register a mock response for records endpoint."""
104
+ if records is None:
105
+ records = []
106
+ self.adapter.register_uri(
107
+ "GET",
108
+ f"{API_URL}/api/{API_VERSION}/zones/{zone_id}/records",
109
+ json={"data": records},
110
+ )
111
+
112
+ def _register_add_record_response(self, zone_id: int = 1, status_code: int = 201) -> None:
113
+ """Register a mock response for adding a record."""
114
+ self.adapter.register_uri(
115
+ "POST",
116
+ f"{API_URL}/api/{API_VERSION}/zones/{zone_id}/records",
117
+ status_code=status_code,
118
+ json={"id": 100, "name": self.record_name, "type": "TXT"},
119
+ )
120
+
121
+ def _register_delete_record_response(
122
+ self, zone_id: int = 1, record_id: int = 100, status_code: int = 204
123
+ ) -> None:
124
+ """Register a mock response for deleting a record."""
125
+ self.adapter.register_uri(
126
+ "DELETE",
127
+ f"{API_URL}/api/{API_VERSION}/zones/{zone_id}/records/{record_id}",
128
+ status_code=status_code,
129
+ )
130
+
131
+ def test_add_txt_record(self) -> None:
132
+ """Test adding a TXT record."""
133
+ self._register_zones_response()
134
+ self._register_records_response()
135
+ self._register_add_record_response()
136
+
137
+ self.client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
138
+
139
+ # Verify the POST request was made
140
+ history = self.adapter.request_history
141
+ post_request = [r for r in history if r.method == "POST"][0]
142
+ self.assertIn("TXT", post_request.text)
143
+
144
+ def test_add_txt_record_already_exists(self) -> None:
145
+ """Test adding a TXT record that already exists."""
146
+ self._register_zones_response()
147
+ self._register_records_response(
148
+ records=[
149
+ {
150
+ "id": 50,
151
+ "name": self.record_name,
152
+ "type": "TXT",
153
+ "content": self.record_content,
154
+ }
155
+ ]
156
+ )
157
+
158
+ # Should not raise, should just return (idempotent)
159
+ self.client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
160
+
161
+ # Verify no POST request was made
162
+ history = self.adapter.request_history
163
+ post_requests = [r for r in history if r.method == "POST"]
164
+ self.assertEqual(len(post_requests), 0)
165
+
166
+ def test_add_txt_record_zone_not_found(self) -> None:
167
+ """Test adding a TXT record when a zone is not found."""
168
+ self._register_zones_response(zones=[])
169
+
170
+ with self.assertRaises(errors.PluginError) as context:
171
+ self.client.add_txt_record(
172
+ DOMAIN, self.record_name, self.record_content, self.record_ttl
173
+ )
174
+
175
+ self.assertIn("Unable to find", str(context.exception))
176
+
177
+ def test_del_txt_record(self) -> None:
178
+ """Test deleting a TXT record."""
179
+ self._register_zones_response()
180
+ self._register_records_response(
181
+ records=[
182
+ {
183
+ "id": 100,
184
+ "name": self.record_name,
185
+ "type": "TXT",
186
+ "content": self.record_content,
187
+ }
188
+ ]
189
+ )
190
+ self._register_delete_record_response()
191
+
192
+ self.client.del_txt_record(DOMAIN, self.record_name, self.record_content)
193
+
194
+ # Verify the DELETE request was made
195
+ history = self.adapter.request_history
196
+ delete_requests = [r for r in history if r.method == "DELETE"]
197
+ self.assertEqual(len(delete_requests), 1)
198
+
199
+ def test_del_txt_record_not_found(self) -> None:
200
+ """Test deleting a TXT record that doesn't exist."""
201
+ self._register_zones_response()
202
+ self._register_records_response(records=[])
203
+
204
+ # Should not raise (graceful cleanup)
205
+ self.client.del_txt_record(DOMAIN, self.record_name, self.record_content)
206
+
207
+ def test_del_txt_record_zone_not_found(self) -> None:
208
+ """Test deleting when a zone is not found."""
209
+ self._register_zones_response(zones=[])
210
+
211
+ # Should not raise (graceful cleanup)
212
+ self.client.del_txt_record(DOMAIN, self.record_name, self.record_content)
213
+
214
+ def test_find_zone_with_trailing_dot(self) -> None:
215
+ """Test finding a zone when API returns name with trailing dot."""
216
+ self._register_zones_response(zones=[{"id": 1, "name": "example.com."}])
217
+ self._register_records_response()
218
+ self._register_add_record_response()
219
+
220
+ # Should find the zone despite trailing dot
221
+ self.client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
222
+
223
+ def test_api_error_handling(self) -> None:
224
+ """Test API error handling."""
225
+ self._register_zones_response()
226
+ self._register_records_response()
227
+ self.adapter.register_uri(
228
+ "POST",
229
+ f"{API_URL}/api/{API_VERSION}/zones/1/records",
230
+ status_code=401,
231
+ json={"message": "Invalid API key"},
232
+ )
233
+
234
+ with self.assertRaises(errors.PluginError) as context:
235
+ self.client.add_txt_record(
236
+ DOMAIN, self.record_name, self.record_content, self.record_ttl
237
+ )
238
+
239
+ self.assertIn("401", str(context.exception))
240
+
241
+ def test_headers_contain_api_key(self) -> None:
242
+ """Test that requests contain the API key header."""
243
+ self._register_zones_response()
244
+
245
+ # Trigger a request
246
+ self.client._get_zone_id_by_name("example.com")
247
+
248
+ # Verify headers
249
+ history = self.adapter.request_history
250
+ self.assertEqual(len(history), 1)
251
+ self.assertEqual(history[0].headers["X-API-Key"], API_KEY)
252
+
253
+ def test_zones_api_v2_nested_format(self) -> None:
254
+ """Test handling of API v2 nested zones response format."""
255
+ self._register_zones_response(api_v2_format=True)
256
+ self._register_records_response()
257
+ self._register_add_record_response()
258
+
259
+ # Should find the zone with nested format
260
+ self.client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
261
+
262
+ # Verify the POST request was made
263
+ history = self.adapter.request_history
264
+ post_requests = [r for r in history if r.method == "POST"]
265
+ self.assertEqual(len(post_requests), 1)
266
+
267
+ def test_zones_api_v1_flat_format(self) -> None:
268
+ """Test handling of API v1 flat zones response format."""
269
+ self._register_zones_response(api_v2_format=False)
270
+ self._register_records_response()
271
+ self._register_add_record_response()
272
+
273
+ # Should find the zone with flat format
274
+ self.client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
275
+
276
+ # Verify the POST request was made
277
+ history = self.adapter.request_history
278
+ post_requests = [r for r in history if r.method == "POST"]
279
+ self.assertEqual(len(post_requests), 1)
280
+
281
+
282
+ if __name__ == "__main__":
283
+ unittest.main()
File without changes
@@ -0,0 +1,189 @@
1
+ Metadata-Version: 2.4
2
+ Name: certbot-dns-poweradmin
3
+ Version: 0.1.1
4
+ Summary: PowerAdmin DNS Authenticator plugin for Certbot
5
+ Project-URL: Homepage, https://github.com/poweradmin/certbot-dns-poweradmin
6
+ Project-URL: Bug Reports, https://github.com/poweradmin/certbot-dns-poweradmin/issues
7
+ Project-URL: Source, https://github.com/poweradmin/certbot-dns-poweradmin
8
+ Author-email: Edmondas Girkantas <edmondas@girkantas.lt>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: System Administrators
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Internet :: WWW/HTTP
22
+ Classifier: Topic :: Security
23
+ Classifier: Topic :: System :: Networking
24
+ Classifier: Topic :: System :: Systems Administration
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: acme>=5.1.0
27
+ Requires-Dist: certbot>=5.1.0
28
+ Requires-Dist: requests>=2.32.5
29
+ Provides-Extra: dev
30
+ Requires-Dist: mypy>=1.13.0; extra == 'dev'
31
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
32
+ Requires-Dist: pytest>=7.0.0; extra == 'dev'
33
+ Requires-Dist: requests-mock>=1.11.0; extra == 'dev'
34
+ Requires-Dist: ruff>=0.8.0; extra == 'dev'
35
+ Requires-Dist: tox>=4.0.0; extra == 'dev'
36
+ Requires-Dist: types-requests>=2.32.0; extra == 'dev'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # certbot-dns-poweradmin
40
+
41
+ [![Test](https://github.com/poweradmin/certbot-dns-poweradmin/actions/workflows/test.yml/badge.svg)](https://github.com/poweradmin/certbot-dns-poweradmin/actions/workflows/test.yml)
42
+ [![codecov](https://codecov.io/gh/poweradmin/certbot-dns-poweradmin/graph/badge.svg?token=3686WTALGK)](https://codecov.io/gh/poweradmin/certbot-dns-poweradmin)
43
+ [![PyPI](https://img.shields.io/pypi/v/certbot-dns-poweradmin)](https://pypi.org/project/certbot-dns-poweradmin/)
44
+ [![Python](https://img.shields.io/pypi/pyversions/certbot-dns-poweradmin)](https://pypi.org/project/certbot-dns-poweradmin/)
45
+
46
+ PowerAdmin DNS Authenticator plugin for Certbot
47
+
48
+ This plugin automates the process of completing a `dns-01` challenge by creating, and subsequently removing, TXT records using the PowerAdmin API.
49
+
50
+ ## Installation
51
+
52
+ ```
53
+ pip install certbot-dns-poweradmin
54
+ ```
55
+
56
+ ## PowerAdmin Configuration
57
+
58
+ Your PowerAdmin installation needs to have the API enabled. The plugin supports both API v1 and v2.
59
+
60
+ You'll need an API key with permissions to:
61
+ - List zones
62
+ - Create DNS records
63
+ - Delete DNS records
64
+
65
+ ## Usage
66
+
67
+ 1. Create a credential file (e.g., `/etc/letsencrypt/poweradmin.ini`):
68
+
69
+ ```ini
70
+ dns_poweradmin_api_url = https://poweradmin.example.com
71
+ dns_poweradmin_api_key = your-api-key-here
72
+ dns_poweradmin_api_version = v2
73
+ ```
74
+
75
+ The `api_version` is optional and defaults to `v2`. Set it to `v1` if your PowerAdmin installation uses the older API.
76
+
77
+ 2. Secure the credential file:
78
+
79
+ ```
80
+ chmod 600 /etc/letsencrypt/poweradmin.ini
81
+ ```
82
+
83
+ 3. Run certbot:
84
+
85
+ ```
86
+ certbot certonly \
87
+ --authenticator dns-poweradmin \
88
+ --dns-poweradmin-credentials /etc/letsencrypt/poweradmin.ini \
89
+ -d example.com
90
+ ```
91
+
92
+ ## Arguments
93
+
94
+ | Argument | Description |
95
+ |----------------------------------------|----------------------------------------------------|
96
+ | `--dns-poweradmin-credentials` | Path to credentials INI file (required) |
97
+ | `--dns-poweradmin-propagation-seconds` | Seconds to wait for DNS propagation (default: 120) |
98
+
99
+ ## Examples
100
+
101
+ Get a certificate for a single domain:
102
+
103
+ ```
104
+ certbot certonly \
105
+ --authenticator dns-poweradmin \
106
+ --dns-poweradmin-credentials /etc/letsencrypt/poweradmin.ini \
107
+ -d example.com
108
+ ```
109
+
110
+ Get a wildcard certificate:
111
+
112
+ ```
113
+ certbot certonly \
114
+ --authenticator dns-poweradmin \
115
+ --dns-poweradmin-credentials /etc/letsencrypt/poweradmin.ini \
116
+ -d example.com \
117
+ -d "*.example.com"
118
+ ```
119
+
120
+ With custom propagation time:
121
+
122
+ ```
123
+ certbot certonly \
124
+ --authenticator dns-poweradmin \
125
+ --dns-poweradmin-credentials /etc/letsencrypt/poweradmin.ini \
126
+ --dns-poweradmin-propagation-seconds 300 \
127
+ -d example.com
128
+ ```
129
+
130
+ ## Docker
131
+
132
+ ```dockerfile
133
+ FROM certbot/certbot
134
+ RUN pip install certbot-dns-poweradmin
135
+ ```
136
+
137
+ Build and run:
138
+
139
+ ```
140
+ docker build -t certbot/dns-poweradmin .
141
+
142
+ docker run --rm \
143
+ -v /etc/letsencrypt:/etc/letsencrypt \
144
+ -v /var/lib/letsencrypt:/var/lib/letsencrypt \
145
+ certbot/dns-poweradmin certonly \
146
+ --authenticator dns-poweradmin \
147
+ --dns-poweradmin-credentials /etc/letsencrypt/poweradmin.ini \
148
+ -d example.com
149
+ ```
150
+
151
+ ## Troubleshooting
152
+
153
+ ### Plugin not found by certbot
154
+
155
+ If `certbot plugins` doesn't show `dns-poweradmin`, ensure both certbot and the plugin are installed in the same Python environment:
156
+
157
+ ```bash
158
+ # Check where certbot is installed
159
+ which certbot
160
+
161
+ # If using system certbot but plugin in venv, either:
162
+ # Option 1: Install certbot in the same venv
163
+ pip install certbot certbot-dns-poweradmin
164
+
165
+ # Option 2: Use certbot from the venv
166
+ python -m certbot plugins
167
+ ```
168
+
169
+ ### Virtual environment usage
170
+
171
+ When using a virtual environment, install both certbot and the plugin together:
172
+
173
+ ```bash
174
+ python3 -m venv certbot-env
175
+ source certbot-env/bin/activate
176
+ pip install certbot certbot-dns-poweradmin
177
+
178
+ # Run certbot from the venv
179
+ certbot plugins # should show dns-poweradmin
180
+ ```
181
+
182
+ ### API connection issues
183
+
184
+ - Verify your API URL is correct and accessible
185
+ - Check that your API key has the required permissions
186
+
187
+ ## License
188
+
189
+ Apache License 2.0
@@ -0,0 +1,11 @@
1
+ certbot_dns_poweradmin/__init__.py,sha256=9fIRPdIiZ7-dPVor851Y0ZdcvDuyk1GUA_FvFeYZHVU,3771
2
+ certbot_dns_poweradmin/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ certbot_dns_poweradmin/_internal/__init__.py,sha256=UDMjoJeWxCW0PO15TzBKzrpqYkn5CR9qwsBeGO0JjD0,64
4
+ certbot_dns_poweradmin/_internal/dns_poweradmin.py,sha256=OwTj_KGUOvJSVXJPzvLy6jk5U01DhdgaRuL0DxI7pww,11667
5
+ certbot_dns_poweradmin/_internal/tests/__init__.py,sha256=xoKF-9-hut6f08ERpJUb4xbkWg-i3JKVVyQyBlcINVo,47
6
+ certbot_dns_poweradmin/_internal/tests/dns_poweradmin_test.py,sha256=EKYm96KTTX7ZbzM4L9l2UiVF6h7dO0wpQWNdCcCI_hY,10364
7
+ certbot_dns_poweradmin-0.1.1.dist-info/METADATA,sha256=ujzuXrsmxFPiNmeNqEiD16lkMbF9G4CeteFjkvwiE_Y,5694
8
+ certbot_dns_poweradmin-0.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ certbot_dns_poweradmin-0.1.1.dist-info/entry_points.txt,sha256=erkikti0fCRn2YbHCGAUYlfEgxx6NJCWAt3i6ZfyJ6w,97
10
+ certbot_dns_poweradmin-0.1.1.dist-info/licenses/LICENSE,sha256=jxIpEpEufD33Bn_5ZgjKHGGpK8H1xZNCPKqBeEta4jg,11348
11
+ certbot_dns_poweradmin-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [certbot.plugins]
2
+ dns-poweradmin = certbot_dns_poweradmin._internal.dns_poweradmin:Authenticator
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Edmondas Girkantas
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.