Skip to content

Commit 3fdaade

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 certman._lineage_name mapped both names to x.com: one of them was served the other's certificate, the evidence attested the wrong certificate, and renewals targeted the wrong lineage. _lineage_name now finds the lineage whose certificate holds exactly the domain, so lineages certbot named itself keep working without being renamed or re-issued. A new lineage is named explicitly: _wildcard.x.com for a wildcard (an underscore cannot appear in a certificate host name), the domain otherwise, with -NNNN appended if another certificate already holds that name. certonly passes it as --cert-name unless it is a --csr issuance, which keeps no lineage. 2.4-2.6 wrote a wildcard's derived-key files under the bare name, so the legacy live/ cleanup looks there. Signed-off-by: Kevin Wang <wy721@qq.com>
1 parent 11a5600 commit 3fdaade

2 files changed

Lines changed: 141 additions & 25 deletions

File tree

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

Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,17 @@ def renewal_due(cert: x509.Certificate, now: datetime) -> bool:
3636
return now >= not_before + (lifetime / 2 if lifetime < timedelta(days=10) else lifetime * 2 / 3)
3737

3838

39+
def _cert_names(path: str) -> Optional[List[str]]:
40+
"""The DNS names a certificate file is for, or None if it cannot be read."""
41+
try:
42+
with open(path, "rb") as fh:
43+
cert = x509.load_pem_x509_certificate(fh.read())
44+
return cert.extensions.get_extension_for_class(
45+
x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName)
46+
except (OSError, ValueError, x509.ExtensionNotFound):
47+
return None
48+
49+
3950
def staging_enabled() -> bool:
4051
"""Whether to use Let's Encrypt staging.
4152
@@ -219,9 +230,10 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
219230
# For `renew`, certbot reuses the authenticator + hooks saved in the
220231
# renewal config from the initial `certonly`, so we don't re-specify
221232
# them here (and must not fall back to the DNS plugin).
233+
if "--csr" not in extra_args:
234+
base_cmd.extend(["--cert-name", self._lineage_name(domain)])
222235
if action == "renew":
223-
base_cmd.extend(["--cert-name", self._lineage_name(domain),
224-
"--no-random-sleep-on-renew"])
236+
base_cmd.append("--no-random-sleep-on-renew")
225237
# Explicit on `renew` too: certbot would otherwise take the server
226238
# saved in the lineage, whatever the configuration says now.
227239
base_cmd.extend(["--server", acme_server()])
@@ -263,16 +275,18 @@ def _build_certbot_command(self, action: str, domain: str, email: str,
263275
else:
264276
base_cmd.append("--register-unsafely-without-email")
265277
base_cmd.extend(["-d", domain])
266-
if action == "renew":
278+
if "--csr" not in extra_args:
267279
# Without this, `certbot renew` renews *every* lineage in
268280
# /etc/letsencrypt/renewal. run_pass calls this once per domain, so
269281
# N domains meant N passes over all N lineages, and the result was
270-
# then reported against whichever domain happened to ask.
271-
#
282+
# then reported against whichever domain happened to ask. On
283+
# `certonly` it picks the lineage (see _lineage_name); --csr
284+
# issues outside any lineage.
285+
base_cmd.extend(["--cert-name", self._lineage_name(domain)])
286+
if action == "renew":
272287
# Without a TTY, certbot also sleeps up to 8 minutes before a due
273288
# renewal, which overruns _certbot_timeout and gets the run killed.
274-
base_cmd.extend(["--cert-name", self._lineage_name(domain),
275-
"--no-random-sleep-on-renew"])
289+
base_cmd.append("--no-random-sleep-on-renew")
276290
base_cmd.extend(["--server", acme_server()])
277291

278292
if getattr(self.provider, 'CERTBOT_PROPAGATION_SECONDS'):
@@ -401,10 +415,11 @@ def _clear_legacy_live(self, domain: str) -> None:
401415
to create the lineage over them left an empty renewal config, which
402416
would push the next lineage to <name>-0001.
403417
"""
404-
conf = self._renewal_conf_path(domain)
418+
base = domain[2:] if domain.startswith("*.") else domain
419+
conf = os.path.join(LETSENCRYPT_DIR, "renewal", f"{base}.conf")
405420
if os.path.isfile(conf) and os.path.getsize(conf) == 0:
406421
os.remove(conf)
407-
live = self._live_dir(domain)
422+
live = os.path.join(LETSENCRYPT_DIR, "live", base)
408423
privkey = os.path.join(live, "privkey.pem")
409424
if not os.path.isfile(privkey) or os.path.islink(privkey):
410425
return
@@ -512,8 +527,28 @@ def certificate_exists(self, domain: str) -> bool:
512527

513528
@staticmethod
514529
def _lineage_name(domain: str) -> str:
515-
"""certbot stores a wildcard lineage under the bare name."""
516-
return domain[2:] if domain.startswith("*.") else domain
530+
"""The lineage holding exactly this domain, else the name to create.
531+
532+
Left to itself certbot named a wildcard's lineage after the bare name,
533+
the same as the base domain's, so with both in DOMAINS one became
534+
<name>-0001. Existing lineages are therefore found by content. A new
535+
wildcard lineage is _wildcard.<name>: an underscore cannot appear in a
536+
certificate host name, so it never collides with a domain.
537+
"""
538+
base = domain[2:] if domain.startswith("*.") else domain
539+
new = f"_wildcard.{base}" if domain.startswith("*.") else domain
540+
renewal = os.path.join(LETSENCRYPT_DIR, "renewal")
541+
pattern = re.compile(rf"(_wildcard\.)?{re.escape(base)}(-\d{{4}})?")
542+
existing = sorted(os.path.basename(p)[:-len(".conf")]
543+
for p in glob.glob(os.path.join(renewal, "*.conf")))
544+
for name in [new] + [n for n in existing if pattern.fullmatch(n)]:
545+
if _cert_names(os.path.join(LETSENCRYPT_DIR, "live", name, "cert.pem")) == [domain]:
546+
return name
547+
name, n = new, 0
548+
while name in existing:
549+
n += 1
550+
name = f"{new}-{n:04d}"
551+
return name
517552

518553
@classmethod
519554
def _live_dir(cls, domain: str) -> str:

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

Lines changed: 95 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -141,14 +141,6 @@ def test_a_failed_write_leaves_the_original_intact(self):
141141
os.chmod(self.dir, 0o700)
142142
self.assertEqual(self.read(), original)
143143

144-
def test_wildcard_uses_the_bare_lineage_name(self):
145-
self.assertEqual(
146-
certman.CertManager._lineage_name("*.example.com"), "example.com"
147-
)
148-
self.assertEqual(
149-
certman.CertManager._lineage_name("example.com"), "example.com"
150-
)
151-
152144
def test_wildcard_has_its_own_deterministic_dir(self):
153145
with mock.patch.dict(os.environ, {"DETERMINISTIC_TLS_KEY": "true"}):
154146
self.assertEqual(certman.CertManager.cert_dir("*.example.com"),
@@ -191,6 +183,10 @@ def setUp(self):
191183
self._saved = {v: os.environ.get(v) for v in self.VARS}
192184
for v in self.VARS:
193185
os.environ.pop(v, None)
186+
self.root = tempfile.mkdtemp()
187+
self.addCleanup(shutil.rmtree, self.root)
188+
self.addCleanup(setattr, certman, "LETSENCRYPT_DIR", certman.LETSENCRYPT_DIR)
189+
certman.LETSENCRYPT_DIR = self.root
194190

195191
def tearDown(self):
196192
for v, old in self._saved.items():
@@ -213,15 +209,38 @@ def test_renew_is_scoped_to_one_lineage(self):
213209
self.assertIn("--cert-name", cmd)
214210
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "a.example.com")
215211

216-
def test_renew_uses_the_bare_name_for_a_wildcard(self):
212+
def test_renew_uses_the_wildcard_lineage(self):
217213
cmd = _command_manager()._build_certbot_command("renew", "*.example.com", "")
218-
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "example.com")
219-
220-
def test_certonly_is_scoped_by_d_not_cert_name(self):
214+
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "_wildcard.example.com")
215+
216+
def test_certonly_names_the_lineage(self):
217+
"""certbot's own pick for a wildcard is the base domain's name."""
218+
for delegation in ("", "deleg.example.net"):
219+
os.environ["DELEGATION_ZONE"] = delegation
220+
cmd = _command_manager()._build_certbot_command(
221+
"certonly", "*.example.com", "")
222+
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "_wildcard.example.com")
223+
self.assertEqual(cmd[cmd.index("-d") + 1], "*.example.com")
224+
225+
def test_csr_issuance_has_no_lineage(self):
226+
os.environ["DETERMINISTIC_TLS_KEY"] = "true"
221227
cmd = _command_manager()._build_certbot_command(
222-
"certonly", "a.example.com", "")
228+
"certonly", "*.example.com", "", ("--csr", "x.csr"))
223229
self.assertNotIn("--cert-name", cmd)
224-
self.assertIn("-d", cmd)
230+
231+
def test_replacing_keeps_the_lineage(self):
232+
mgr = _command_manager()
233+
mgr.install_plugin = lambda: True
234+
mgr.provider.validate_credentials = lambda: True
235+
mgr.setup_credentials = lambda: True
236+
cmds = []
237+
with mock.patch.object(certman.subprocess, "run",
238+
lambda cmd, **kw: cmds.append(cmd) or mock.Mock(returncode=0)):
239+
self.assertTrue(mgr.obtain_certificate("*.x.com", "", replace=True))
240+
cmd = cmds[0]
241+
self.assertIn("--force-renewal", cmd)
242+
self.assertIn("--break-my-certs", cmd)
243+
self.assertEqual(cmd[cmd.index("--cert-name") + 1], "_wildcard.x.com")
225244

226245
def test_delegation_renew_is_scoped_too(self):
227246
os.environ["DELEGATION_ZONE"] = "deleg.example.net"
@@ -313,6 +332,68 @@ def test_delegation_renew_skips_the_random_sleep(self):
313332
self.assertIn("--no-random-sleep-on-renew", cmd)
314333

315334

335+
def _cert_pem(name, key):
336+
from datetime import datetime, timedelta, timezone
337+
from cryptography import x509
338+
from cryptography.hazmat.primitives import hashes, serialization
339+
from cryptography.x509.oid import NameOID
340+
341+
now = datetime.now(timezone.utc)
342+
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
343+
return (x509.CertificateBuilder()
344+
.subject_name(subject).issuer_name(subject)
345+
.public_key(key.public_key()).serial_number(1)
346+
.not_valid_before(now).not_valid_after(now + timedelta(days=90))
347+
.add_extension(x509.SubjectAlternativeName([x509.DNSName(name)]), critical=False)
348+
.sign(key, hashes.SHA256())
349+
.public_bytes(serialization.Encoding.PEM))
350+
351+
352+
class LineageNameTest(EnvTestCase):
353+
"""Existing lineages are found by content; new ones get a name of their own."""
354+
355+
def setUp(self):
356+
super().setUp()
357+
from cryptography.hazmat.primitives.asymmetric import ec
358+
359+
self.key = ec.generate_private_key(ec.SECP256R1())
360+
self.mgr = object.__new__(certman.CertManager)
361+
362+
def lineage(self, lineage, name):
363+
os.makedirs(f"{self.root}/live/{lineage}")
364+
os.makedirs(f"{self.root}/renewal", exist_ok=True)
365+
with open(f"{self.root}/live/{lineage}/cert.pem", "wb") as fh:
366+
fh.write(_cert_pem(name, self.key))
367+
open(f"{self.root}/renewal/{lineage}.conf", "w").close()
368+
369+
def test_new_wildcard_lineage_is_apart_from_the_base(self):
370+
self.assertEqual(self.mgr._lineage_name("*.x.com"), "_wildcard.x.com")
371+
self.assertEqual(self.mgr._lineage_name("x.com"), "x.com")
372+
373+
def test_lineages_certbot_named_itself_are_found(self):
374+
self.lineage("x.com", "*.x.com")
375+
self.lineage("x.com-0001", "x.com")
376+
self.assertEqual(self.mgr._lineage_name("*.x.com"), "x.com")
377+
self.assertEqual(self.mgr._lineage_name("x.com"), "x.com-0001")
378+
379+
def test_a_name_taken_by_another_certificate_is_not_reused(self):
380+
self.lineage("x.com", "*.x.com")
381+
self.assertEqual(self.mgr._lineage_name("x.com"), "x.com-0001")
382+
383+
def test_legacy_wildcard_files_under_the_bare_name_move_to_the_wildcards(self):
384+
os.environ["DETERMINISTIC_TLS_KEY"] = "true"
385+
live = f"{self.root}/live/x.com"
386+
os.makedirs(live)
387+
for item in ("cert", "fullchain"):
388+
with open(f"{live}/{item}.pem", "wb") as fh:
389+
fh.write(_cert_pem("*.x.com", self.key))
390+
with open(f"{live}/privkey.pem", "wb") as fh:
391+
fh.write(certman.deterministic_key.key_pem(self.key))
392+
self.mgr._clear_legacy_live("*.x.com")
393+
self.assertFalse(os.path.exists(live))
394+
self.assertTrue(os.path.exists(f"{self.root}/deterministic/_wildcard.x.com/fullchain.pem"))
395+
396+
316397
class CertbotTimeoutTest(EnvTestCase):
317398
"""A fixed 300s cap could not fit every provider's own propagation wait."""
318399

0 commit comments

Comments
 (0)