certbot-dns-nameocean 0.1.0__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yuix Networks Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: certbot-dns-nameocean
3
+ Version: 0.1.0
4
+ Summary: Certbot DNS authenticator for NameOcean DNS
5
+ Author-email: NameOcean <support@nameocean.net>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/NameOcean/certbot-dns-nameocean
8
+ Project-URL: Documentation, https://nameocean.net/developers/guides/letsencrypt-dns-01/
9
+ Project-URL: Issues, https://github.com/NameOcean/certbot-dns-nameocean/issues
10
+ Keywords: certbot,letsencrypt,acme,dns-01,nameocean
11
+ Classifier: Environment :: Plugins
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Internet :: Name Service (DNS)
14
+ Classifier: Topic :: Security
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: certbot>=2.0
19
+ Requires-Dist: requests>=2.27
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest; extra == "dev"
22
+ Requires-Dist: requests_mock; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # certbot-dns-nameocean
26
+
27
+ A [Certbot](https://certbot.eff.org/) DNS authenticator for [NameOcean DNS](https://nameocean.net/dns/). It answers the ACME `dns-01` challenge by adding a TXT record through NameOcean's [API](https://nameocean.net/developers/api/) and removes it afterwards, so you can get wildcard certificates and certificates for servers that are not reachable from the internet.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ pip install certbot-dns-nameocean
33
+ ```
34
+
35
+ Certbot must be installed with pip in the same environment (the snap and distribution packages can't load pip plugins).
36
+
37
+ ## Credentials
38
+
39
+ Create an API key with the `dns:read` and `dns:write` scopes in the [dashboard](https://nameocean.net/dashboard/api/). It can be limited to the domains Certbot manages and to your server's IP addresses. The domain's zone must be on NameOcean DNS in the same account.
40
+
41
+ Put it in an INI file that only you can read:
42
+
43
+ ```ini
44
+ # ~/.secrets/certbot/nameocean.ini
45
+ dns_nameocean_api_key = no_live_...
46
+ ```
47
+
48
+ ```sh
49
+ chmod 600 ~/.secrets/certbot/nameocean.ini
50
+ ```
51
+
52
+ Without `--dns-nameocean-credentials`, the `NAMEOCEAN_API_KEY` environment variable is used.
53
+
54
+ ## Usage
55
+
56
+ ```sh
57
+ certbot certonly \
58
+ --authenticator dns-nameocean \
59
+ --dns-nameocean-credentials ~/.secrets/certbot/nameocean.ini \
60
+ -d example.com -d '*.example.com'
61
+ ```
62
+
63
+ | Option | Default | |
64
+ |---|---|---|
65
+ | `--dns-nameocean-credentials` | (none) | INI file with `dns_nameocean_api_key` |
66
+ | `--dns-nameocean-propagation-seconds` | 20 | Seconds to wait before Let's Encrypt checks the record |
67
+
68
+ Renewals (`certbot renew`) reuse the same settings.
69
+
70
+ ## How it works
71
+
72
+ - The zone is the longest of your NameOcean zones that the name ends with, so `_acme-challenge.app.example.com` goes into `example.com` (or into `app.example.com` if that is its own zone).
73
+ - Each challenge value is its own TXT record with a 5 minute TTL; existing TXT records are left alone, so an apex and its wildcard can be issued together.
74
+ - Cleanup deletes only the records this run added (or, after a restart, the TXT record with exactly that value).
75
+
76
+ ## Development
77
+
78
+ ```sh
79
+ pip install -e '.[dev]'
80
+ pytest
81
+ ```
82
+
83
+ Releases: bump `version` in `pyproject.toml`, then `git tag vX.Y.Z && git push --tags`; GitHub Actions tests, builds and publishes to PyPI (trusted publishing).
84
+
85
+ ## License
86
+
87
+ MIT
@@ -0,0 +1,63 @@
1
+ # certbot-dns-nameocean
2
+
3
+ A [Certbot](https://certbot.eff.org/) DNS authenticator for [NameOcean DNS](https://nameocean.net/dns/). It answers the ACME `dns-01` challenge by adding a TXT record through NameOcean's [API](https://nameocean.net/developers/api/) and removes it afterwards, so you can get wildcard certificates and certificates for servers that are not reachable from the internet.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pip install certbot-dns-nameocean
9
+ ```
10
+
11
+ Certbot must be installed with pip in the same environment (the snap and distribution packages can't load pip plugins).
12
+
13
+ ## Credentials
14
+
15
+ Create an API key with the `dns:read` and `dns:write` scopes in the [dashboard](https://nameocean.net/dashboard/api/). It can be limited to the domains Certbot manages and to your server's IP addresses. The domain's zone must be on NameOcean DNS in the same account.
16
+
17
+ Put it in an INI file that only you can read:
18
+
19
+ ```ini
20
+ # ~/.secrets/certbot/nameocean.ini
21
+ dns_nameocean_api_key = no_live_...
22
+ ```
23
+
24
+ ```sh
25
+ chmod 600 ~/.secrets/certbot/nameocean.ini
26
+ ```
27
+
28
+ Without `--dns-nameocean-credentials`, the `NAMEOCEAN_API_KEY` environment variable is used.
29
+
30
+ ## Usage
31
+
32
+ ```sh
33
+ certbot certonly \
34
+ --authenticator dns-nameocean \
35
+ --dns-nameocean-credentials ~/.secrets/certbot/nameocean.ini \
36
+ -d example.com -d '*.example.com'
37
+ ```
38
+
39
+ | Option | Default | |
40
+ |---|---|---|
41
+ | `--dns-nameocean-credentials` | (none) | INI file with `dns_nameocean_api_key` |
42
+ | `--dns-nameocean-propagation-seconds` | 20 | Seconds to wait before Let's Encrypt checks the record |
43
+
44
+ Renewals (`certbot renew`) reuse the same settings.
45
+
46
+ ## How it works
47
+
48
+ - The zone is the longest of your NameOcean zones that the name ends with, so `_acme-challenge.app.example.com` goes into `example.com` (or into `app.example.com` if that is its own zone).
49
+ - Each challenge value is its own TXT record with a 5 minute TTL; existing TXT records are left alone, so an apex and its wildcard can be issued together.
50
+ - Cleanup deletes only the records this run added (or, after a restart, the TXT record with exactly that value).
51
+
52
+ ## Development
53
+
54
+ ```sh
55
+ pip install -e '.[dev]'
56
+ pytest
57
+ ```
58
+
59
+ Releases: bump `version` in `pyproject.toml`, then `git tag vX.Y.Z && git push --tags`; GitHub Actions tests, builds and publishes to PyPI (trusted publishing).
60
+
61
+ ## License
62
+
63
+ MIT
@@ -0,0 +1 @@
1
+ """Certbot DNS authenticator for NameOcean DNS (https://nameocean.net/dns/)."""
@@ -0,0 +1,170 @@
1
+ """DNS Authenticator for NameOcean DNS.
2
+
3
+ Adds the ``_acme-challenge`` TXT record through NameOcean's API v1
4
+ (``POST /api/v1/dns/{zone}/records``) and removes exactly that record afterwards
5
+ (``DELETE /api/v1/dns/{zone}/records/TXT/{id}``).
6
+ """
7
+
8
+ import logging
9
+ import os
10
+ from typing import Any, Callable, Optional
11
+
12
+ import requests
13
+ from certbot import errors
14
+ from certbot.plugins import dns_common
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ API_URL = "https://nameocean.net/api/v1"
19
+ TTL = "5m" # the shortest TTL NameOcean accepts
20
+ KEYS_URL = "https://nameocean.net/dashboard/api/"
21
+
22
+
23
+ class Authenticator(dns_common.DNSAuthenticator):
24
+ """DNS Authenticator for NameOcean.
25
+
26
+ Fulfills a dns-01 challenge with a TXT record in a NameOcean DNS zone.
27
+ """
28
+
29
+ description = (
30
+ "Obtain certificates using a DNS TXT record (if you are using NameOcean for DNS)."
31
+ )
32
+
33
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
34
+ super().__init__(*args, **kwargs)
35
+ self.credentials: Optional[dns_common.CredentialsConfiguration] = None
36
+ self._client: Optional[_NameOceanClient] = None
37
+
38
+ @classmethod
39
+ def add_parser_arguments(
40
+ cls, add: Callable[..., None], default_propagation_seconds: int = 20
41
+ ) -> None:
42
+ super().add_parser_arguments(add, default_propagation_seconds)
43
+ add(
44
+ "credentials",
45
+ help="NameOcean credentials INI file (dns_nameocean_api_key = ...). "
46
+ "Without it the NAMEOCEAN_API_KEY environment variable is used.",
47
+ )
48
+
49
+ def more_info(self) -> str:
50
+ return (
51
+ "This plugin configures a DNS TXT record to respond to a dns-01 challenge "
52
+ "using the NameOcean API."
53
+ )
54
+
55
+ def _setup_credentials(self) -> None:
56
+ if not self.conf("credentials") and os.environ.get("NAMEOCEAN_API_KEY"):
57
+ return
58
+ self.credentials = self._configure_credentials(
59
+ "credentials",
60
+ "NameOcean credentials INI file",
61
+ {
62
+ "api_key": "API key with the dns:read and dns:write scopes, from " + KEYS_URL,
63
+ },
64
+ )
65
+
66
+ def _perform(self, domain: str, validation_name: str, validation: str) -> None:
67
+ self._get_client().add_txt(domain, validation_name, validation)
68
+
69
+ def _cleanup(self, domain: str, validation_name: str, validation: str) -> None:
70
+ self._get_client().del_txt(domain, validation_name, validation)
71
+
72
+ def _get_client(self) -> "_NameOceanClient":
73
+ if self._client is None:
74
+ key = None
75
+ if self.credentials:
76
+ key = self.credentials.conf("api_key")
77
+ key = key or os.environ.get("NAMEOCEAN_API_KEY")
78
+ if not key:
79
+ raise errors.PluginError(
80
+ "No NameOcean API key: pass --dns-nameocean-credentials or set NAMEOCEAN_API_KEY."
81
+ )
82
+ url = (self.credentials.conf("api_url") if self.credentials else None) or API_URL
83
+ self._client = _NameOceanClient(key, url)
84
+ return self._client
85
+
86
+
87
+ class _NameOceanClient:
88
+ """The few NameOcean API v1 calls a dns-01 challenge needs."""
89
+
90
+ def __init__(self, api_key: str, api_url: str = API_URL, timeout: int = 30) -> None:
91
+ self.api_url = api_url.rstrip("/")
92
+ self.timeout = timeout
93
+ self.session = requests.Session()
94
+ self.session.headers.update(
95
+ {
96
+ "Authorization": "Bearer " + api_key,
97
+ "Accept": "application/json",
98
+ "User-Agent": "certbot-dns-nameocean",
99
+ }
100
+ )
101
+ self._zones: Optional[list[str]] = None
102
+ # (zone, hostname, value) -> record id, for the records this run added
103
+ self._added: dict[tuple[str, str, str], int] = {}
104
+
105
+ def _request(self, method: str, path: str, **kwargs: Any) -> requests.Response:
106
+ try:
107
+ resp = self.session.request(method, self.api_url + path, timeout=self.timeout, **kwargs)
108
+ except requests.RequestException as e:
109
+ raise errors.PluginError(f"NameOcean API: {method} {path}: {e}")
110
+ if resp.status_code >= 400:
111
+ try:
112
+ message = resp.json().get("error") or resp.text
113
+ except ValueError:
114
+ message = resp.text
115
+ raise errors.PluginError(
116
+ f"NameOcean API: {method} {path}: HTTP {resp.status_code}: {message}"
117
+ )
118
+ return resp
119
+
120
+ def _zone_for(self, domain: str) -> str:
121
+ if self._zones is None:
122
+ data = self._request("GET", "/dns").json()
123
+ self._zones = [z["name"].lower().rstrip(".") for z in data.get("zones", [])]
124
+ for guess in dns_common.base_domain_name_guesses(domain.lower().rstrip(".")):
125
+ if guess in self._zones:
126
+ return guess
127
+ raise errors.PluginError(
128
+ f"No NameOcean DNS zone for {domain} on this account "
129
+ f"(the API key sees: {', '.join(self._zones) or 'none'})."
130
+ )
131
+
132
+ @staticmethod
133
+ def _hostname(validation_name: str, zone: str) -> str:
134
+ name = validation_name.lower().rstrip(".")
135
+ if name == zone:
136
+ return "@"
137
+ return name[: -len(zone) - 1]
138
+
139
+ def add_txt(self, domain: str, validation_name: str, validation: str) -> None:
140
+ zone = self._zone_for(domain)
141
+ hostname = self._hostname(validation_name, zone)
142
+ body = {"type": "TXT", "hostname": hostname, "text": validation, "ttl": TTL}
143
+ resp = self._request("POST", f"/dns/{zone}/records", json=body)
144
+ self._added[(zone, hostname, validation)] = resp.json()["id"]
145
+ logger.debug("Added TXT %s in %s (id %s)", hostname, zone, self._added[(zone, hostname, validation)])
146
+
147
+ def del_txt(self, domain: str, validation_name: str, validation: str) -> None:
148
+ try:
149
+ zone = self._zone_for(domain)
150
+ hostname = self._hostname(validation_name, zone)
151
+ ids = []
152
+ if (zone, hostname, validation) in self._added:
153
+ ids.append(self._added.pop((zone, hostname, validation)))
154
+ else:
155
+ records = self._request("GET", f"/dns/{zone}/records").json().get("records", [])
156
+ ids = [
157
+ r["id"]
158
+ for r in records
159
+ if r.get("type") == "TXT"
160
+ and r.get("hostname", "").lower() == hostname
161
+ and r.get("text") == validation
162
+ ]
163
+ for record_id in ids:
164
+ try:
165
+ self._request("DELETE", f"/dns/{zone}/records/TXT/{record_id}")
166
+ except errors.PluginError as e:
167
+ if "HTTP 404" not in str(e):
168
+ raise
169
+ except errors.PluginError as e:
170
+ logger.warning("Could not remove the TXT record for %s: %s", validation_name, e)
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: certbot-dns-nameocean
3
+ Version: 0.1.0
4
+ Summary: Certbot DNS authenticator for NameOcean DNS
5
+ Author-email: NameOcean <support@nameocean.net>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/NameOcean/certbot-dns-nameocean
8
+ Project-URL: Documentation, https://nameocean.net/developers/guides/letsencrypt-dns-01/
9
+ Project-URL: Issues, https://github.com/NameOcean/certbot-dns-nameocean/issues
10
+ Keywords: certbot,letsencrypt,acme,dns-01,nameocean
11
+ Classifier: Environment :: Plugins
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Internet :: Name Service (DNS)
14
+ Classifier: Topic :: Security
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: certbot>=2.0
19
+ Requires-Dist: requests>=2.27
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest; extra == "dev"
22
+ Requires-Dist: requests_mock; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # certbot-dns-nameocean
26
+
27
+ A [Certbot](https://certbot.eff.org/) DNS authenticator for [NameOcean DNS](https://nameocean.net/dns/). It answers the ACME `dns-01` challenge by adding a TXT record through NameOcean's [API](https://nameocean.net/developers/api/) and removes it afterwards, so you can get wildcard certificates and certificates for servers that are not reachable from the internet.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ pip install certbot-dns-nameocean
33
+ ```
34
+
35
+ Certbot must be installed with pip in the same environment (the snap and distribution packages can't load pip plugins).
36
+
37
+ ## Credentials
38
+
39
+ Create an API key with the `dns:read` and `dns:write` scopes in the [dashboard](https://nameocean.net/dashboard/api/). It can be limited to the domains Certbot manages and to your server's IP addresses. The domain's zone must be on NameOcean DNS in the same account.
40
+
41
+ Put it in an INI file that only you can read:
42
+
43
+ ```ini
44
+ # ~/.secrets/certbot/nameocean.ini
45
+ dns_nameocean_api_key = no_live_...
46
+ ```
47
+
48
+ ```sh
49
+ chmod 600 ~/.secrets/certbot/nameocean.ini
50
+ ```
51
+
52
+ Without `--dns-nameocean-credentials`, the `NAMEOCEAN_API_KEY` environment variable is used.
53
+
54
+ ## Usage
55
+
56
+ ```sh
57
+ certbot certonly \
58
+ --authenticator dns-nameocean \
59
+ --dns-nameocean-credentials ~/.secrets/certbot/nameocean.ini \
60
+ -d example.com -d '*.example.com'
61
+ ```
62
+
63
+ | Option | Default | |
64
+ |---|---|---|
65
+ | `--dns-nameocean-credentials` | (none) | INI file with `dns_nameocean_api_key` |
66
+ | `--dns-nameocean-propagation-seconds` | 20 | Seconds to wait before Let's Encrypt checks the record |
67
+
68
+ Renewals (`certbot renew`) reuse the same settings.
69
+
70
+ ## How it works
71
+
72
+ - The zone is the longest of your NameOcean zones that the name ends with, so `_acme-challenge.app.example.com` goes into `example.com` (or into `app.example.com` if that is its own zone).
73
+ - Each challenge value is its own TXT record with a 5 minute TTL; existing TXT records are left alone, so an apex and its wildcard can be issued together.
74
+ - Cleanup deletes only the records this run added (or, after a restart, the TXT record with exactly that value).
75
+
76
+ ## Development
77
+
78
+ ```sh
79
+ pip install -e '.[dev]'
80
+ pytest
81
+ ```
82
+
83
+ Releases: bump `version` in `pyproject.toml`, then `git tag vX.Y.Z && git push --tags`; GitHub Actions tests, builds and publishes to PyPI (trusted publishing).
84
+
85
+ ## License
86
+
87
+ MIT
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ certbot_dns_nameocean/__init__.py
5
+ certbot_dns_nameocean/dns_nameocean.py
6
+ certbot_dns_nameocean.egg-info/PKG-INFO
7
+ certbot_dns_nameocean.egg-info/SOURCES.txt
8
+ certbot_dns_nameocean.egg-info/dependency_links.txt
9
+ certbot_dns_nameocean.egg-info/entry_points.txt
10
+ certbot_dns_nameocean.egg-info/requires.txt
11
+ certbot_dns_nameocean.egg-info/top_level.txt
12
+ tests/test_dns_nameocean.py
@@ -0,0 +1,2 @@
1
+ [certbot.plugins]
2
+ dns-nameocean = certbot_dns_nameocean.dns_nameocean:Authenticator
@@ -0,0 +1,6 @@
1
+ certbot>=2.0
2
+ requests>=2.27
3
+
4
+ [dev]
5
+ pytest
6
+ requests_mock
@@ -0,0 +1 @@
1
+ certbot_dns_nameocean
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "certbot-dns-nameocean"
7
+ version = "0.1.0"
8
+ description = "Certbot DNS authenticator for NameOcean DNS"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "NameOcean", email = "support@nameocean.net" }]
14
+ keywords = ["certbot", "letsencrypt", "acme", "dns-01", "nameocean"]
15
+ classifiers = [
16
+ "Environment :: Plugins",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Internet :: Name Service (DNS)",
19
+ "Topic :: Security",
20
+ ]
21
+ dependencies = ["certbot>=2.0", "requests>=2.27"]
22
+
23
+ [project.optional-dependencies]
24
+ dev = ["pytest", "requests_mock"]
25
+
26
+ [project.entry-points."certbot.plugins"]
27
+ dns-nameocean = "certbot_dns_nameocean.dns_nameocean:Authenticator"
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/NameOcean/certbot-dns-nameocean"
31
+ Documentation = "https://nameocean.net/developers/guides/letsencrypt-dns-01/"
32
+ Issues = "https://github.com/NameOcean/certbot-dns-nameocean/issues"
33
+
34
+ [tool.setuptools]
35
+ packages = ["certbot_dns_nameocean"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,134 @@
1
+ """Tests for certbot_dns_nameocean.dns_nameocean."""
2
+
3
+ import os
4
+ import unittest
5
+ from unittest import mock
6
+
7
+ import pytest
8
+ import requests_mock
9
+ from certbot import errors
10
+ from certbot.plugins import dns_test_common
11
+ from certbot.plugins.dns_test_common import DOMAIN
12
+ from certbot.tests import util as test_util
13
+
14
+ from certbot_dns_nameocean.dns_nameocean import API_URL, Authenticator, _NameOceanClient
15
+
16
+ KEY = "no_live_test"
17
+
18
+
19
+ class AuthenticatorTest(test_util.TempDirTestCase, dns_test_common.BaseAuthenticatorTest):
20
+ def setUp(self):
21
+ super().setUp()
22
+ path = os.path.join(self.tempdir, "file.ini")
23
+ dns_test_common.write({"nameocean_api_key": KEY}, path)
24
+ self.config = mock.MagicMock(nameocean_credentials=path, nameocean_propagation_seconds=0)
25
+ self.auth = Authenticator(self.config, "nameocean")
26
+ self.mock_client = mock.MagicMock()
27
+ setattr(self.auth, "_get_client", mock.MagicMock(return_value=self.mock_client))
28
+
29
+ @test_util.patch_display_util()
30
+ def test_perform(self, unused_mock_get_utility):
31
+ self.auth.perform([self.achall])
32
+ assert self.mock_client.mock_calls == [
33
+ mock.call.add_txt(DOMAIN, "_acme-challenge." + DOMAIN, mock.ANY)
34
+ ]
35
+
36
+ def test_cleanup(self):
37
+ self.auth._attempt_cleanup = True
38
+ self.auth.cleanup([self.achall])
39
+ assert self.mock_client.mock_calls == [
40
+ mock.call.del_txt(DOMAIN, "_acme-challenge." + DOMAIN, mock.ANY)
41
+ ]
42
+
43
+
44
+ class CredentialsTest(test_util.TempDirTestCase):
45
+ def test_key_from_file(self):
46
+ path = os.path.join(self.tempdir, "file.ini")
47
+ dns_test_common.write({"nameocean_api_key": KEY}, path)
48
+ auth = Authenticator(mock.MagicMock(nameocean_credentials=path), "nameocean")
49
+ auth._setup_credentials()
50
+ assert auth._get_client().session.headers["Authorization"] == "Bearer " + KEY
51
+
52
+ def test_key_from_env(self):
53
+ auth = Authenticator(mock.MagicMock(nameocean_credentials=None), "nameocean")
54
+ with mock.patch.dict(os.environ, {"NAMEOCEAN_API_KEY": "from-env"}):
55
+ auth._setup_credentials()
56
+ assert auth._get_client().session.headers["Authorization"] == "Bearer from-env"
57
+
58
+
59
+ ZONES = {"zones": [{"name": "example.com", "serial": 1}, {"name": "sub.example.com", "serial": 1}]}
60
+
61
+
62
+ class ClientTest(unittest.TestCase):
63
+ def setUp(self):
64
+ self.client = _NameOceanClient(KEY)
65
+
66
+ def test_add_and_delete_own_record(self):
67
+ with requests_mock.Mocker() as m:
68
+ m.get(API_URL + "/dns", json=ZONES)
69
+ post = m.post(API_URL + "/dns/example.com/records", json={"id": 42}, status_code=201)
70
+ delete = m.delete(API_URL + "/dns/example.com/records/TXT/42", status_code=204)
71
+ self.client.add_txt("www.example.com", "_acme-challenge.www.example.com", "value1")
72
+ assert post.last_request.json() == {
73
+ "type": "TXT",
74
+ "hostname": "_acme-challenge.www",
75
+ "text": "value1",
76
+ "ttl": "5m",
77
+ }
78
+ assert post.last_request.headers["Authorization"] == "Bearer " + KEY
79
+ self.client.del_txt("www.example.com", "_acme-challenge.www.example.com", "value1")
80
+ assert delete.called_once
81
+
82
+ def test_longest_zone_wins(self):
83
+ with requests_mock.Mocker() as m:
84
+ m.get(API_URL + "/dns", json=ZONES)
85
+ post = m.post(API_URL + "/dns/sub.example.com/records", json={"id": 7}, status_code=201)
86
+ self.client.add_txt("sub.example.com", "_acme-challenge.sub.example.com", "v")
87
+ assert post.last_request.json()["hostname"] == "_acme-challenge"
88
+
89
+ def test_delete_finds_record_by_value(self):
90
+ # another certbot run added it: look it up, delete only the matching value
91
+ with requests_mock.Mocker() as m:
92
+ m.get(API_URL + "/dns", json=ZONES)
93
+ m.get(
94
+ API_URL + "/dns/example.com/records",
95
+ json={
96
+ "records": [
97
+ {"id": 1, "type": "TXT", "hostname": "_acme-challenge", "text": "keep"},
98
+ {"id": 2, "type": "TXT", "hostname": "_acme-challenge", "text": "mine"},
99
+ {"id": 3, "type": "A", "hostname": "_acme-challenge", "ip": "192.0.2.1"},
100
+ ]
101
+ },
102
+ )
103
+ d2 = m.delete(API_URL + "/dns/example.com/records/TXT/2", status_code=204)
104
+ self.client.del_txt("example.com", "_acme-challenge.example.com", "mine")
105
+ assert d2.called_once
106
+ assert [r.method for r in m.request_history].count("DELETE") == 1
107
+
108
+ def test_no_zone(self):
109
+ with requests_mock.Mocker() as m:
110
+ m.get(API_URL + "/dns", json=ZONES)
111
+ with pytest.raises(errors.PluginError, match="No NameOcean DNS zone for other.org"):
112
+ self.client.add_txt("other.org", "_acme-challenge.other.org", "v")
113
+
114
+ def test_api_error_message(self):
115
+ with requests_mock.Mocker() as m:
116
+ m.get(API_URL + "/dns", status_code=401, json={"error": "Invalid API key.", "code": "unauthorized"})
117
+ with pytest.raises(errors.PluginError, match="HTTP 401: Invalid API key."):
118
+ self.client.add_txt("example.com", "_acme-challenge.example.com", "v")
119
+
120
+ def test_cleanup_never_raises(self):
121
+ with requests_mock.Mocker() as m:
122
+ m.get(API_URL + "/dns", json=ZONES)
123
+ m.post(API_URL + "/dns/example.com/records", json={"id": 9}, status_code=201)
124
+ m.delete(API_URL + "/dns/example.com/records/TXT/9", status_code=500, text="boom")
125
+ self.client.add_txt("example.com", "_acme-challenge.example.com", "v")
126
+ self.client.del_txt("example.com", "_acme-challenge.example.com", "v") # logs, no raise
127
+
128
+ def test_already_deleted(self):
129
+ with requests_mock.Mocker() as m:
130
+ m.get(API_URL + "/dns", json=ZONES)
131
+ m.post(API_URL + "/dns/example.com/records", json={"id": 9}, status_code=201)
132
+ m.delete(API_URL + "/dns/example.com/records/TXT/9", status_code=404, json={"error": "No TXT record"})
133
+ self.client.add_txt("example.com", "_acme-challenge.example.com", "v")
134
+ self.client.del_txt("example.com", "_acme-challenge.example.com", "v")