Skip to content

Commit 041e48a

Browse files
committed
refactor(ingress): root every certbot path at LETSENCRYPT_DIR, drop the #132-only migration
wildcard's certificate. Also check that replacing a wildcard keeps its lineage name. Signed-off-by: Kevin Wang <wy721@qq.com>
1 parent c4685e6 commit 041e48a

2 files changed

Lines changed: 28 additions & 33 deletions

File tree

‎custom-domain/dstack-ingress/scripts/certman.py‎

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,6 @@
2222
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
2323

2424
LETSENCRYPT_DIR = "/etc/letsencrypt"
25-
# certbot cannot keep a lineage for a key it did not generate, so certificates
26-
# for derived keys live here, apart from its lineages, and certman.py renews
27-
# them itself.
28-
DETERMINISTIC_DIR = "/etc/letsencrypt/deterministic"
2925

3026

3127
def renewal_due(cert: x509.Certificate, now: datetime) -> bool:
@@ -89,7 +85,7 @@ def account_file() -> Optional[str]:
8985
"""certbot's account for acme_server(), stored under the directory URL's
9086
host and path."""
9187
parsed = urlparse(acme_server())
92-
pattern = os.path.join("/etc/letsencrypt/accounts", parsed.netloc + parsed.path,
88+
pattern = os.path.join(LETSENCRYPT_DIR, "accounts", parsed.netloc + parsed.path,
9389
"*", "regr.json")
9490
matches = sorted(glob.glob(pattern))
9591
return matches[0] if matches else None
@@ -343,8 +339,9 @@ def obtain_certificate(self, domain: str, email: str, replace: bool = False) ->
343339
key = deterministic_key.private_key(domain)
344340
# certbot refuses to overwrite an explicit --cert-path, so issue
345341
# into a fresh directory and move the result into place.
346-
os.makedirs(DETERMINISTIC_DIR, exist_ok=True)
347-
staging = tempfile.mkdtemp(dir=DETERMINISTIC_DIR, prefix=".issue-")
342+
root = os.path.dirname(self._deterministic_dir(domain))
343+
os.makedirs(root, exist_ok=True)
344+
staging = tempfile.mkdtemp(dir=root, prefix=".issue-")
348345
csr = os.path.join(staging, "request.csr")
349346
deterministic_key.write_file(csr, deterministic_key.csr_pem(key, domain))
350347
extra_args = ("--csr", csr) + tuple(
@@ -402,9 +399,10 @@ def obtain_certificate(self, domain: str, email: str, replace: bool = False) ->
402399
shutil.rmtree(staging, ignore_errors=True)
403400

404401
def _deterministic_dir(self, domain: str) -> str:
405-
"""A wildcard's is apart from its base domain's, which may be served too."""
406-
name = f"_wildcard.{domain[2:]}" if domain.startswith("*.") else domain
407-
return os.path.join(DETERMINISTIC_DIR, name)
402+
"""certbot cannot keep a lineage for a key it did not generate, so
403+
certificates for derived keys live here, apart from its lineages, and
404+
certman.py renews them itself."""
405+
return os.path.join(LETSENCRYPT_DIR, "deterministic", self._lineage_name(domain))
408406

409407
def _install_deterministic(self, domain: str, staging: str, key) -> bool:
410408
if not deterministic_key.cert_matches(os.path.join(staging, "cert.pem"), key):
@@ -450,7 +448,7 @@ def _adopt_legacy_deterministic(self, domain: str) -> None:
450448
if (deterministic_key.enabled() and target and not os.path.exists(target)
451449
and os.path.isfile(fullchain) and not os.path.islink(fullchain)
452450
and _key_matches(live)):
453-
os.makedirs(DETERMINISTIC_DIR, exist_ok=True)
451+
os.makedirs(os.path.dirname(target), exist_ok=True)
454452
os.replace(live, target)
455453
print(f"Moved the certificate in {live} to {target}")
456454
else:
@@ -539,7 +537,7 @@ def renew_certificate(self, domain: str, email: str = "") -> Tuple[bool, bool]:
539537
def _fullchain_path(self, domain: str) -> str:
540538
if deterministic_key.enabled():
541539
return os.path.join(self._deterministic_dir(domain), "fullchain.pem")
542-
return f"/etc/letsencrypt/live/{self._lineage_name(domain)}/fullchain.pem"
540+
return f"{LETSENCRYPT_DIR}/live/{self._lineage_name(domain)}/fullchain.pem"
543541

544542
def certificate_exists(self, domain: str) -> bool:
545543
"""Check if certificate already exists for domain."""
@@ -565,18 +563,10 @@ def migrate_wildcard_lineage(self, domain: str) -> None:
565563
without re-issuance. The new renewal config is written before the old
566564
one is removed, so a lineage still found once its new name holds the
567565
same certificate names is what an interrupted rename left: it goes.
568-
The deterministic certificate the two used to share moves the same way.
569566
"""
570567
base = domain[2:] if domain.startswith("*.") else domain
571568
wildcard = f"*.{base}"
572569
new = self._lineage_name(wildcard)
573-
shared = os.path.join(DETERMINISTIC_DIR, base)
574-
if _cert_names(os.path.join(shared, "cert.pem")) == [wildcard]:
575-
if os.path.exists(self._deterministic_dir(wildcard)):
576-
shutil.rmtree(shared)
577-
else:
578-
os.replace(shared, self._deterministic_dir(wildcard))
579-
print(f"Moved the certificate for {wildcard} out of {shared}")
580570
renewal = f"{LETSENCRYPT_DIR}/renewal"
581571
if not os.path.isdir(renewal):
582572
return
@@ -618,7 +608,7 @@ def _remove_lineage(name: str) -> None:
618608

619609
def _renewal_conf_path(self, domain: str) -> str:
620610
"""Where certbot keeps this lineage's renewal config."""
621-
return f"/etc/letsencrypt/renewal/{self._lineage_name(domain)}.conf"
611+
return f"{LETSENCRYPT_DIR}/renewal/{self._lineage_name(domain)}.conf"
622612

623613
def _issuing_server(self, domain: str) -> Optional[str]:
624614
"""The ACME server the current certificate came from."""

‎custom-domain/dstack-ingress/scripts/tests/test_certman.py‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import sys
1010
import tempfile
1111
import unittest
12+
from unittest import mock
1213

1314
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
1415

@@ -232,6 +233,20 @@ def test_csr_issuance_has_no_lineage(self):
232233
"certonly", "*.example.com", "", ("--csr", "x.csr"))
233234
self.assertNotIn("--cert-name", cmd)
234235

236+
def test_replacing_keeps_the_lineage(self):
237+
mgr = _command_manager()
238+
mgr.install_plugin = lambda: True
239+
mgr.provider.validate_credentials = lambda: True
240+
mgr.setup_credentials = lambda: True
241+
cmds = []
242+
with mock.patch.object(certman.subprocess, "run",
243+
lambda cmd, **kw: cmds.append(cmd) or mock.Mock(returncode=0)):
244+
self.assertTrue(mgr.obtain_certificate("*.x.com", "", replace=True))
245+
cmd = cmds[0]
246+
self.assertIn("--force-renewal", cmd)
247+
self.assertIn("--break-my-certs", cmd)
248+
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "_wildcard.x.com")
249+
235250
def test_delegation_renew_is_scoped_too(self):
236251
os.environ["DELEGATION_ZONE"] = "deleg.example.net"
237252
cmd = _command_manager()._build_certbot_command("renew", "a.example.com", "")
@@ -334,13 +349,12 @@ def setUp(self):
334349

335350
self.root = tempfile.mkdtemp()
336351
self.key = ec.generate_private_key(ec.SECP256R1())
337-
self._saved_dirs = certman.LETSENCRYPT_DIR, certman.DETERMINISTIC_DIR
352+
self._saved_dir = certman.LETSENCRYPT_DIR
338353
certman.LETSENCRYPT_DIR = self.root
339-
certman.DETERMINISTIC_DIR = os.path.join(self.root, "deterministic")
340354
self.mgr = object.__new__(certman.CertManager)
341355

342356
def tearDown(self):
343-
certman.LETSENCRYPT_DIR, certman.DETERMINISTIC_DIR = self._saved_dirs
357+
certman.LETSENCRYPT_DIR = self._saved_dir
344358
shutil.rmtree(self.root)
345359
super().tearDown()
346360

@@ -388,15 +402,6 @@ def test_an_interrupted_rename_is_completed(self):
388402
self.assertEqual(self.lineages(), ["_wildcard.x.com"])
389403
self.assertFalse(os.path.exists(f"{self.root}/archive/x.com"))
390404

391-
def test_shared_deterministic_certificate_moves(self):
392-
shared = f"{self.root}/deterministic/x.com"
393-
os.makedirs(shared)
394-
with open(f"{shared}/cert.pem", "wb") as fh:
395-
fh.write(_cert_pem("*.x.com", self.key))
396-
self.mgr.migrate_wildcard_lineage("x.com")
397-
self.assertFalse(os.path.exists(shared))
398-
self.assertTrue(os.path.exists(f"{self.root}/deterministic/_wildcard.x.com/cert.pem"))
399-
400405
def test_legacy_wildcard_certificate_is_adopted_as_the_wildcards(self):
401406
os.environ["DETERMINISTIC_TLS_KEY"] = "true"
402407
live = f"{self.root}/live/x.com"

0 commit comments

Comments
 (0)