Skip to content

Commit c4685e6

Browse files
committed
fix(ingress): finish interrupted lineage renames, free the base name
A rename interrupted after the new renewal config was written was never completed: the wildcard's old lineage stayed under the base name, served and renewed alongside the new one. A lineage still holding exactly the wildcard once _wildcard.<name> exists is now removed instead. When certbot had given the wildcard the bare name, the base domain's <name>-NNNN lineage is renamed to <name> in the same pass, rather than left orphaned while the base is issued again. 2.4-2.6 wrote a wildcard's derived-key certificate into live/<name>, the base name, so adopt plain files there by the certificate's name, into the wildcard's deterministic directory when it is the wildcard's, and only when the key next to it matches. A wildcard certificate in the deterministic/<name> the two used to share moves the same way. --cert-name is now keyed on the absence of --csr, which is what it means. Tests patch LETSENCRYPT_DIR and DETERMINISTIC_DIR. Signed-off-by: Kevin Wang <wy721@qq.com>
1 parent 822d0de commit c4685e6

2 files changed

Lines changed: 165 additions & 48 deletions

File tree

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

Lines changed: 60 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
# Add script directory to path to import dns_providers
2222
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
2323

24+
LETSENCRYPT_DIR = "/etc/letsencrypt"
2425
# certbot cannot keep a lineage for a key it did not generate, so certificates
2526
# for derived keys live here, apart from its lineages, and certman.py renews
2627
# them itself.
@@ -228,6 +229,9 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
228229
if os.environ.get("DELEGATION_ZONE", "").strip():
229230
hook = "/scripts/acme-dns-alias-hook.sh"
230231
base_cmd = certbot_cmd + [action, "--non-interactive", "-v"]
232+
# For `renew`, certbot reuses the authenticator + hooks saved in the
233+
# renewal config from the initial `certonly`, so we don't re-specify
234+
# them here (and must not fall back to the DNS plugin).
231235
if action == "certonly":
232236
base_cmd.extend([
233237
"--manual",
@@ -243,10 +247,7 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
243247
base_cmd.append("--register-unsafely-without-email")
244248
base_cmd.extend(extra_args)
245249
base_cmd.extend(["-d", domain])
246-
# For `renew`, certbot reuses the authenticator + hooks saved in the
247-
# renewal config from the initial `certonly`, so we don't re-specify
248-
# them here (and must not fall back to the DNS plugin).
249-
if not deterministic_key.enabled():
250+
if "--csr" not in extra_args:
250251
base_cmd.extend(["--cert-name", self._lineage_name(domain)])
251252
# Explicit on `renew` too: certbot would otherwise take the server
252253
# saved in the lineage, whatever the configuration says now.
@@ -289,7 +290,7 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
289290
else:
290291
base_cmd.append("--register-unsafely-without-email")
291292
base_cmd.extend(["-d", domain])
292-
if not deterministic_key.enabled():
293+
if "--csr" not in extra_args:
293294
# Without this, `certbot renew` renews *every* lineage in
294295
# /etc/letsencrypt/renewal. run_pass calls this once per domain, so
295296
# N domains meant N passes over all N lineages, and the result was
@@ -432,16 +433,16 @@ def _adopt_legacy_deterministic(self, domain: str) -> None:
432433
them left an empty renewal config, which would push the next lineage
433434
to <name>-0001; drop that too.
434435
"""
435-
conf = self._renewal_conf_path(domain)
436+
base = domain[2:] if domain.startswith("*.") else domain
437+
conf = f"{LETSENCRYPT_DIR}/renewal/{base}.conf"
436438
if os.path.isfile(conf) and os.path.getsize(conf) == 0:
437439
os.remove(conf)
438440
print(f"Removed the empty renewal config {conf}")
439-
live = f"/etc/letsencrypt/live/{self._lineage_name(domain)}"
441+
live = f"{LETSENCRYPT_DIR}/live/{base}"
440442
privkey = os.path.join(live, "privkey.pem")
441443
if not os.path.isfile(privkey) or os.path.islink(privkey):
442444
return
443445
fullchain = os.path.join(live, "fullchain.pem")
444-
base = self._lineage_name(domain)
445446
names = _cert_names(os.path.join(live, "cert.pem"))
446447
target = None
447448
if names in ([base], [f"*.{base}"]):
@@ -556,48 +557,64 @@ def _lineage_name(domain: str) -> str:
556557
return f"_wildcard.{domain[2:]}" if domain.startswith("*.") else domain
557558

558559
def migrate_wildcard_lineage(self, domain: str) -> None:
559-
"""Rename a wildcard lineage certbot named itself (<name> or
560-
<name>-NNNN) to _lineage_name, keeping the certificate in service.
561-
562-
Only a lineage holding exactly the wildcard moves; one that serves the
563-
base name stays. The new renewal config is written last, so an
564-
interrupted run leaves the old lineage intact and is simply redone.
560+
"""Move certificates out of the lineages certbot named itself.
561+
562+
Left to itself certbot named a wildcard's lineage <name> or <name>-NNNN.
563+
One holding exactly the wildcard is renamed to _lineage_name, and one
564+
holding exactly the base name to <name>, so both stay in service
565+
without re-issuance. The new renewal config is written before the old
566+
one is removed, so a lineage still found once its new name holds the
567+
same certificate names is what an interrupted rename left: it goes.
568+
The deterministic certificate the two used to share moves the same way.
565569
"""
566570
base = domain[2:] if domain.startswith("*.") else domain
567571
wildcard = f"*.{base}"
568572
new = self._lineage_name(wildcard)
569-
root = "/etc/letsencrypt"
570-
renewal = f"{root}/renewal"
571-
if not os.path.isdir(renewal) or os.path.exists(f"{renewal}/{new}.conf"):
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}")
580+
renewal = f"{LETSENCRYPT_DIR}/renewal"
581+
if not os.path.isdir(renewal):
572582
return
573583
pattern = re.compile(rf"{re.escape(base)}(-\d{{4}})?\.conf")
574584
for old in sorted(n[:-len(".conf")] for n in os.listdir(renewal) if pattern.fullmatch(n)):
575-
try:
576-
with open(f"{root}/live/{old}/cert.pem", "rb") as fh:
577-
cert = x509.load_pem_x509_certificate(fh.read())
578-
names = cert.extensions.get_extension_for_class(
579-
x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName)
580-
with open(f"{renewal}/{old}.conf", encoding="utf-8") as fh:
581-
conf = fh.read()
582-
except (OSError, ValueError, x509.ExtensionNotFound):
583-
continue
584-
if names != [wildcard]:
585+
names = _cert_names(f"{LETSENCRYPT_DIR}/live/{old}/cert.pem")
586+
target = {(wildcard,): new, (base,): base}.get(tuple(names or ()))
587+
if target is None or target == old:
585588
continue
586-
for path in (f"{root}/archive/{new}", f"{root}/live/{new}"):
587-
shutil.rmtree(path, ignore_errors=True)
588-
shutil.copytree(f"{root}/archive/{old}", f"{root}/archive/{new}")
589-
os.makedirs(f"{root}/live/{new}")
590-
for item in ("cert", "chain", "fullchain", "privkey"):
591-
target = os.path.basename(os.readlink(f"{root}/live/{old}/{item}.pem"))
592-
os.symlink(f"../../archive/{new}/{target}", f"{root}/live/{new}/{item}.pem")
593-
conf = conf.replace(f"{root}/archive/{old}\n", f"{root}/archive/{new}\n")
594-
conf = conf.replace(f"{root}/live/{old}/", f"{root}/live/{new}/")
595-
deterministic_key.write_file(f"{renewal}/{new}.conf", conf.encode())
596-
os.remove(f"{renewal}/{old}.conf")
597-
shutil.rmtree(f"{root}/live/{old}", ignore_errors=True)
598-
shutil.rmtree(f"{root}/archive/{old}", ignore_errors=True)
599-
print(f"Renamed certbot lineage {old} to {new} for {wildcard}")
600-
return
589+
if not os.path.exists(f"{renewal}/{target}.conf"):
590+
self._rename_lineage(old, target)
591+
print(f"Renamed certbot lineage {old} to {target}")
592+
elif _cert_names(f"{LETSENCRYPT_DIR}/live/{target}/cert.pem") == names:
593+
self._remove_lineage(old)
594+
print(f"Removed certbot lineage {old}, a copy of {target}")
595+
596+
@staticmethod
597+
def _rename_lineage(old: str, new: str) -> None:
598+
root = LETSENCRYPT_DIR
599+
with open(f"{root}/renewal/{old}.conf", encoding="utf-8") as fh:
600+
conf = fh.read()
601+
for path in (f"{root}/archive/{new}", f"{root}/live/{new}"):
602+
shutil.rmtree(path, ignore_errors=True)
603+
shutil.copytree(f"{root}/archive/{old}", f"{root}/archive/{new}")
604+
os.makedirs(f"{root}/live/{new}")
605+
for item in ("cert", "chain", "fullchain", "privkey"):
606+
target = os.path.basename(os.readlink(f"{root}/live/{old}/{item}.pem"))
607+
os.symlink(f"../../archive/{new}/{target}", f"{root}/live/{new}/{item}.pem")
608+
conf = conf.replace(f"{root}/archive/{old}\n", f"{root}/archive/{new}\n")
609+
conf = conf.replace(f"{root}/live/{old}/", f"{root}/live/{new}/")
610+
deterministic_key.write_file(f"{root}/renewal/{new}.conf", conf.encode())
611+
CertManager._remove_lineage(old)
612+
613+
@staticmethod
614+
def _remove_lineage(name: str) -> None:
615+
os.remove(f"{LETSENCRYPT_DIR}/renewal/{name}.conf")
616+
shutil.rmtree(f"{LETSENCRYPT_DIR}/live/{name}", ignore_errors=True)
617+
shutil.rmtree(f"{LETSENCRYPT_DIR}/archive/{name}", ignore_errors=True)
601618

602619
def _renewal_conf_path(self, domain: str) -> str:
603620
"""Where certbot keeps this lineage's renewal config."""
@@ -769,8 +786,8 @@ def run_action(
769786
Returns:
770787
(success, needs_evidence): success status and whether evidence should be generated
771788
"""
772-
self.migrate_wildcard_lineage(domain)
773789
self._adopt_legacy_deterministic(domain)
790+
self.migrate_wildcard_lineage(domain)
774791
if action == "auto":
775792
if not self.certificate_exists(domain):
776793
success = self.obtain_certificate(domain, email)

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

Lines changed: 105 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -228,11 +228,8 @@ def test_certonly_names_the_lineage(self):
228228

229229
def test_csr_issuance_has_no_lineage(self):
230230
os.environ["DETERMINISTIC_TLS_KEY"] = "true"
231-
try:
232-
cmd = _command_manager()._build_certbot_command(
233-
"certonly", "*.example.com", "", ("--csr", "x.csr"))
234-
finally:
235-
del os.environ["DETERMINISTIC_TLS_KEY"]
231+
cmd = _command_manager()._build_certbot_command(
232+
"certonly", "*.example.com", "", ("--csr", "x.csr"))
236233
self.assertNotIn("--cert-name", cmd)
237234

238235
def test_delegation_renew_is_scoped_too(self):
@@ -311,6 +308,109 @@ def test_unknown_server_does_not_replace_every_pass(self):
311308
self.assertEqual(self.run_auto(None), ["renew"])
312309

313310

311+
def _cert_pem(name, key):
312+
from datetime import datetime, timedelta, timezone
313+
from cryptography import x509
314+
from cryptography.hazmat.primitives import hashes
315+
from cryptography.x509.oid import NameOID
316+
317+
now = datetime.now(timezone.utc)
318+
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
319+
return (x509.CertificateBuilder()
320+
.subject_name(subject).issuer_name(subject)
321+
.public_key(key.public_key()).serial_number(1)
322+
.not_valid_before(now).not_valid_after(now + timedelta(days=90))
323+
.add_extension(x509.SubjectAlternativeName([x509.DNSName(name)]), critical=False)
324+
.sign(key, hashes.SHA256())
325+
.public_bytes(certman.serialization.Encoding.PEM))
326+
327+
328+
class MigrateWildcardLineageTest(EnvTestCase):
329+
"""Lineages certbot named itself (x.com, x.com-0001) move to their own."""
330+
331+
def setUp(self):
332+
super().setUp()
333+
from cryptography.hazmat.primitives.asymmetric import ec
334+
335+
self.root = tempfile.mkdtemp()
336+
self.key = ec.generate_private_key(ec.SECP256R1())
337+
self._saved_dirs = certman.LETSENCRYPT_DIR, certman.DETERMINISTIC_DIR
338+
certman.LETSENCRYPT_DIR = self.root
339+
certman.DETERMINISTIC_DIR = os.path.join(self.root, "deterministic")
340+
self.mgr = object.__new__(certman.CertManager)
341+
342+
def tearDown(self):
343+
certman.LETSENCRYPT_DIR, certman.DETERMINISTIC_DIR = self._saved_dirs
344+
shutil.rmtree(self.root)
345+
super().tearDown()
346+
347+
def lineage(self, lineage, name):
348+
r = self.root
349+
os.makedirs(f"{r}/archive/{lineage}")
350+
os.makedirs(f"{r}/live/{lineage}")
351+
os.makedirs(f"{r}/renewal", exist_ok=True)
352+
pem = _cert_pem(name, self.key)
353+
for item in ("cert", "chain", "fullchain", "privkey"):
354+
with open(f"{r}/archive/{lineage}/{item}1.pem", "wb") as fh:
355+
fh.write(pem)
356+
os.symlink(f"../../archive/{lineage}/{item}1.pem", f"{r}/live/{lineage}/{item}.pem")
357+
with open(f"{r}/renewal/{lineage}.conf", "w", encoding="utf-8") as fh:
358+
fh.write(f"archive_dir = {r}/archive/{lineage}\ncert = {r}/live/{lineage}/cert.pem\n")
359+
360+
def names(self, lineage):
361+
return certman._cert_names(f"{self.root}/live/{lineage}/cert.pem")
362+
363+
def lineages(self):
364+
return sorted(n[:-len(".conf")] for n in os.listdir(f"{self.root}/renewal"))
365+
366+
def test_wildcard_first_frees_the_base_name(self):
367+
self.lineage("x.com", "*.x.com")
368+
self.lineage("x.com-0001", "x.com")
369+
self.mgr.migrate_wildcard_lineage("x.com")
370+
self.assertEqual(self.lineages(), ["_wildcard.x.com", "x.com"])
371+
self.assertEqual(self.names("_wildcard.x.com"), ["*.x.com"])
372+
self.assertEqual(self.names("x.com"), ["x.com"])
373+
self.assertFalse(os.path.exists(f"{self.root}/live/x.com-0001"))
374+
with open(f"{self.root}/renewal/x.com.conf", encoding="utf-8") as fh:
375+
self.assertNotIn("x.com-0001", fh.read())
376+
377+
def test_base_first_leaves_the_base_alone(self):
378+
self.lineage("x.com", "x.com")
379+
self.lineage("x.com-0001", "*.x.com")
380+
self.mgr.migrate_wildcard_lineage("*.x.com")
381+
self.assertEqual(self.lineages(), ["_wildcard.x.com", "x.com"])
382+
self.assertEqual(self.names("_wildcard.x.com"), ["*.x.com"])
383+
384+
def test_an_interrupted_rename_is_completed(self):
385+
self.lineage("_wildcard.x.com", "*.x.com")
386+
self.lineage("x.com", "*.x.com")
387+
self.mgr.migrate_wildcard_lineage("*.x.com")
388+
self.assertEqual(self.lineages(), ["_wildcard.x.com"])
389+
self.assertFalse(os.path.exists(f"{self.root}/archive/x.com"))
390+
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+
400+
def test_legacy_wildcard_certificate_is_adopted_as_the_wildcards(self):
401+
os.environ["DETERMINISTIC_TLS_KEY"] = "true"
402+
live = f"{self.root}/live/x.com"
403+
os.makedirs(live)
404+
for item in ("cert", "fullchain"):
405+
with open(f"{live}/{item}.pem", "wb") as fh:
406+
fh.write(_cert_pem("*.x.com", self.key))
407+
with open(f"{live}/privkey.pem", "wb") as fh:
408+
fh.write(certman.deterministic_key.key_pem(self.key))
409+
self.mgr._adopt_legacy_deterministic("x.com")
410+
self.assertFalse(os.path.exists(live))
411+
self.assertTrue(os.path.exists(f"{self.root}/deterministic/_wildcard.x.com/fullchain.pem"))
412+
413+
314414
class CertbotTimeoutTest(EnvTestCase):
315415
"""A fixed 300s cap could not fit every provider's own propagation wait."""
316416

0 commit comments

Comments
 (0)