Skip to content

Commit 822d0de

Browse files
committed
fix(ingress): give wildcard certificates their own certbot lineage
With both x.com and *.x.com in DOMAINS, certbot names the lineages x.com and x.com-0001, but cert_dir_name and certman._lineage_name mapped both names to x.com: one of them was served the other's certificate (a name mismatch), the evidence attested the wrong certificate, and renewals targeted the wrong lineage. Derived-key certificates shared deterministic/x.com the same way. certonly now passes an explicit --cert-name, and a wildcard's is _wildcard.x.com (an underscore cannot appear in a certificate host name, so it never collides with a domain). certman.py and functions.sh use the same mapping. Existing deployments: a lineage certbot named itself (x.com or x.com-NNNN) that holds exactly the wildcard is renamed to the new name, so the certificate stays in service without re-issuance. A lineage that serves the base name is left alone. The new renewal config is written last, so an interrupted rename leaves the old lineage intact. Signed-off-by: Kevin Wang <wy721@qq.com>
1 parent c8b9238 commit 822d0de

3 files changed

Lines changed: 88 additions & 18 deletions

File tree

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

Lines changed: 58 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
246246
# For `renew`, certbot reuses the authenticator + hooks saved in the
247247
# renewal config from the initial `certonly`, so we don't re-specify
248248
# them here (and must not fall back to the DNS plugin).
249-
if action == "renew":
249+
if not deterministic_key.enabled():
250250
base_cmd.extend(["--cert-name", self._lineage_name(domain)])
251251
# Explicit on `renew` too: certbot would otherwise take the server
252252
# saved in the lineage, whatever the configuration says now.
@@ -289,11 +289,13 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
289289
else:
290290
base_cmd.append("--register-unsafely-without-email")
291291
base_cmd.extend(["-d", domain])
292-
if action == "renew":
292+
if not deterministic_key.enabled():
293293
# Without this, `certbot renew` renews *every* lineage in
294294
# /etc/letsencrypt/renewal. run_pass calls this once per domain, so
295295
# N domains meant N passes over all N lineages, and the result was
296-
# then reported against whichever domain happened to ask.
296+
# then reported against whichever domain happened to ask. On
297+
# `certonly` it pins the lineage name certbot would otherwise pick
298+
# (see _lineage_name). --csr issues outside any lineage.
297299
base_cmd.extend(["--cert-name", self._lineage_name(domain)])
298300
base_cmd.extend(["--server", acme_server()])
299301

@@ -544,8 +546,58 @@ def certificate_exists(self, domain: str) -> bool:
544546

545547
@staticmethod
546548
def _lineage_name(domain: str) -> str:
547-
"""certbot stores a wildcard lineage under the bare name."""
548-
return domain[2:] if domain.startswith("*.") else domain
549+
"""The lineage name, passed to certbot as --cert-name.
550+
551+
Left to itself certbot names a wildcard lineage after the bare name,
552+
the same as the base domain's, so with both in DOMAINS one became
553+
<name>-0001 while both mapped to <name>. An underscore cannot appear in
554+
a certificate's host name, so this one never collides with a domain.
555+
"""
556+
return f"_wildcard.{domain[2:]}" if domain.startswith("*.") else domain
557+
558+
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.
565+
"""
566+
base = domain[2:] if domain.startswith("*.") else domain
567+
wildcard = f"*.{base}"
568+
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"):
572+
return
573+
pattern = re.compile(rf"{re.escape(base)}(-\d{{4}})?\.conf")
574+
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+
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
549601

550602
def _renewal_conf_path(self, domain: str) -> str:
551603
"""Where certbot keeps this lineage's renewal config."""
@@ -717,6 +769,7 @@ def run_action(
717769
Returns:
718770
(success, needs_evidence): success status and whether evidence should be generated
719771
"""
772+
self.migrate_wildcard_lineage(domain)
720773
self._adopt_legacy_deterministic(domain)
721774
if action == "auto":
722775
if not self.certificate_exists(domain):

‎custom-domain/dstack-ingress/scripts/functions.sh‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -166,12 +166,16 @@ sanitize_proxy_buffers() {
166166
fi
167167
}
168168

169-
# Get the certbot certificate directory name for a domain.
170-
# Certbot stores wildcard certs without the "*." prefix:
171-
# *.example.com → /etc/letsencrypt/live/example.com/
169+
# The certbot lineage name for a domain, as certman.py passes it (--cert-name).
170+
# A wildcard gets its own, so it never shares one with the base domain:
171+
# *.example.com → /etc/letsencrypt/live/_wildcard.example.com/
172172
cert_dir_name() {
173173
local domain="$1"
174-
echo "${domain#\*.}"
174+
if [[ "$domain" == \*.* ]]; then
175+
echo "_wildcard.${domain#\*.}"
176+
else
177+
echo "$domain"
178+
fi
175179
}
176180

177181
# certman.py decides which ACME server is in use (ACME_STAGING,

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

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,10 @@ def test_a_failed_write_leaves_the_original_intact(self):
140140
os.chmod(self.dir, 0o700)
141141
self.assertEqual(self.read(), original)
142142

143-
def test_wildcard_uses_the_bare_lineage_name(self):
143+
def test_wildcard_lineage_is_apart_from_the_base(self):
144144
self.assertEqual(
145-
certman.CertManager._lineage_name("*.example.com"), "example.com"
145+
certman.CertManager._lineage_name("*.example.com"),
146+
"_wildcard.example.com",
146147
)
147148
self.assertEqual(
148149
certman.CertManager._lineage_name("example.com"), "example.com"
@@ -212,15 +213,27 @@ def test_renew_is_scoped_to_one_lineage(self):
212213
self.assertIn("--cert-name", cmd)
213214
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "a.example.com")
214215

215-
def test_renew_uses_the_bare_name_for_a_wildcard(self):
216+
def test_renew_uses_the_wildcard_lineage(self):
216217
cmd = _command_manager()._build_certbot_command("renew", "*.example.com", "")
217-
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "example.com")
218-
219-
def test_certonly_is_scoped_by_d_not_cert_name(self):
220-
cmd = _command_manager()._build_certbot_command(
221-
"certonly", "a.example.com", "")
218+
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "_wildcard.example.com")
219+
220+
def test_certonly_names_the_lineage(self):
221+
"""certbot's own pick for a wildcard is the base domain's name."""
222+
for delegation in ("", "deleg.example.net"):
223+
os.environ["DELEGATION_ZONE"] = delegation
224+
cmd = _command_manager()._build_certbot_command(
225+
"certonly", "*.example.com", "")
226+
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "_wildcard.example.com")
227+
self.assertEqual(cmd[cmd.index("-d") + 1], "*.example.com")
228+
229+
def test_csr_issuance_has_no_lineage(self):
230+
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"]
222236
self.assertNotIn("--cert-name", cmd)
223-
self.assertIn("-d", cmd)
224237

225238
def test_delegation_renew_is_scoped_too(self):
226239
os.environ["DELEGATION_ZONE"] = "deleg.example.net"

0 commit comments

Comments
 (0)