edge: issue custom-domain certs over DNS-01 before DNS moves (#1293)
A hostname attached under a zone named in CARLOS_DNS01_ZONES gets its certificate from the issuer over DNS-01, read from the claim, before any DNS record moves. The result is an ordinary per-host entry published to control/certs/<host>, so every edge serves it the moment DNS switches. - precert.go: the issuer-only pass (claims via ClaimCache, zone filter, wildcard-covered names skipped, renew ahead of autocert's window, republish a local cert the bucket lacks, per-pass/hourly caps, per-name backoff). Unset = off. - wildcard.go: the DNS-01 order is now dns01Order, shared by wildcards and pre-issued hosts under one account; account key load-or-mint is serialized. - Fake CA gains a dns-01 mode; TestPreIssueE2E proves a non-issuer edge serves the certificate for a name that does not point anywhere yet. - hostenv allows CARLOS_DNS01_ZONES; agent.go documents it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+1,007
−45
internal/edge/certsync_e2e_test.go+16 −1internal/edge/edge.go+7 −0internal/edge/precert.go+412 −0internal/edge/precert_test.go+490 −0internal/edge/wildcard.go+77 −44internal/host/agent.go+4 −0internal/hostenv/hostenv.go+1 −0
diff --git a/internal/edge/certsync_e2e_test.go b/internal/edge/certsync_e2e_test.go| index 3dedbe096..a0aa92fb5 100644 |
| --- a/internal/edge/certsync_e2e_test.go |
| +++ b/internal/edge/certsync_e2e_test.go |
| @@ -110,6 +110,12 @@ type fakeACME struct { |
| // handlers run on the server's goroutines and, for deactivatePendingAuthz, |
| // can outlive the test. |
| faults []string |
| + // dns01TXT, when set, switches the CA to offering ONLY a dns-01 |
| + // challenge (precert_test.go): validation reads the TXT records at |
| + // _acme-challenge.<identifier, "*." stripped> through it and wants the |
| + // RFC 8555 §8.4 digest of the key authorization among them. Set before |
| + // the first order; read without the lock. |
| + dns01TXT func(name string) []string |
| } |
| type fakeACMEOrder struct { |
| @@ -776,12 +782,16 @@ func (ca *fakeACME) serveAuthorization(w http.ResponseWriter, r *http.Request) { |
| http.Error(w, "no such authz", http.StatusNotFound) |
| return |
| } |
| + chalType := "http-01" |
| + if ca.dns01TXT != nil { |
| + chalType = "dns-01" |
| + } |
| ca.mu.Lock() |
| body := map[string]any{ |
| "identifier": map[string]string{"type": "dns", "value": o.domain}, |
| "status": o.authz, |
| "challenges": []map[string]string{{ |
| - "type": "http-01", |
| + "type": chalType, |
| "url": ca.url("/chal/" + id), |
| "token": o.token, |
| "status": o.authz, |
| @@ -806,6 +816,11 @@ func (ca *fakeACME) serveChallengeAccept(w http.ResponseWriter, r *http.Request) |
| base, thumb, domain, token := ca.validateVia, ca.thumb, o.domain, o.token |
| ca.mu.Unlock() |
| + if ca.dns01TXT != nil { |
| + ca.validateDNS01(w, id, o, domain, token, thumb) |
| + return |
| + } |
| + |
| url := base + acmeChallengePrefix + token |
| got, ferr := ca.fetchChallenge(url, domain) |
| want := token + "." + thumb |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index b2fd30d8f..d204ab19e 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -5135,6 +5135,13 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun |
| warm := e.newIssuerWarm(appsDomain, parents, perHostCert, warmResolver, edgeIPs, store) |
| go warm.run() |
| log.Printf("edge: cert warm on (%s pass) — custom domains are ordered and renewed proactively, not on first handshake", warmInterval) |
| + // Certificates before DNS moves (precert.go, #1293): attached names |
| + // in the operator's CARLOS_DNS01_ZONES are issued over DNS-01 from |
| + // the claim, before they point here. nil = not configured. |
| + if p := e.newPreIssuerFromEnv(certCache, mirror, wm); p != nil { |
| + go p.run() |
| + log.Printf("edge: certificates before DNS moves on for %v (DNS-01, %s pass, issuer only)", p.zones, preIssueInterval) |
| + } |
| } |
| tlsCfg.GetCertificate = getCert |
| if mirror != nil { |
diff --git a/internal/edge/precert.go b/internal/edge/precert.go| new file mode 100644 |
| index 000000000..0f506a115 |
| --- /dev/null |
| +++ b/internal/edge/precert.go |
| @@ -0,0 +1,412 @@ |
| +package edge |
| + |
| +// Pre-issued certificates (#1293): a certificate for an attached hostname |
| +// BEFORE its DNS moves to the deployment, for hostnames in zones the |
| +// operator names and the deployment's own DNS provider writes. |
| +// |
| +// Why the ordinary path cannot do it. A custom domain's certificate is |
| +// ordered over HTTP-01 by the deployment's issuer, and only once the home |
| +// box's DNS check has stamped the name "pointing" and published it in its |
| +// edges file (certwarm.go's set, edgesfile.go's withholding). A name that |
| +// does not point at us yet is not published at all, so the issuer has never |
| +// heard of it; and HTTP-01 could not succeed before the switch anyway, |
| +// because the CA would ask the old servers. So the switch itself opens a gap: |
| +// the next DNS check (five to seven minutes), then the order. On 2026-11-19 a |
| +// production switch spent four minutes of it failing every handshake on the |
| +// home box ("acme: not available here") and was rolled back. |
| +// |
| +// DNS-01 does not care where the name points. When the deployment's DNS |
| +// provider can write the hostname's zone, the issuer can prove control and |
| +// hold a certificate before a single record moves. That is all this file |
| +// adds: |
| +// |
| +// - The source is the CLAIMS (domains/<host>.json, the deployment-wide |
| +// record every attach writes), not the edges files: a claim exists from |
| +// the moment of the attach, whatever DNS says. Read through a ClaimCache, |
| +// so the steady state is one listing per pass and a body read only for a |
| +// claim that changed. Pending (unproven, #215) claims, catch-all claims |
| +// and claims that name nothing to serve are skipped. |
| +// - The scope is CARLOS_DNS01_ZONES, named by the operator. Unset, nothing |
| +// here runs. A zone list rather than "anything the provider happens to |
| +// hold" because the provider's account may hold zones whose names |
| +// members can attach, and a certificate is an act in the operator's |
| +// zone that the operator should have asked for. |
| +// - Only the issuer orders, under the same election as every other order |
| +// (certsync.go), and only it reads the claims: a non-issuer's pass ends |
| +// at the gate and costs nothing. |
| +// - The result is an ORDINARY per-host entry under the host's own cache |
| +// name, in autocert's format, written through the publishing cache. So |
| +// it lands in control/certs/<host>, every edge's mirror serves it, the |
| +// home box's DNS sweep stamps its expiry, the cert sweep ages it out like |
| +// any other, and once the name points autocert finds it in its cache and |
| +// orders nothing. Nothing downstream knows how it was issued. |
| +// - Renewal: the same pass renews the certificate over DNS-01 a week (or a |
| +// twelfth of its lifetime, if shorter) before autocert's own HTTP-01 |
| +// renewal would start, so autocert's timer finds a fresh cache and stands |
| +// aside. If DNS-01 renewal breaks, HTTP-01 is still there behind it. |
| +// - Bounds: preIssueOrdersPerPass orders per pass, preIssueOrdersPerHour |
| +// orders an hour across all names (the DNS-01 account is shared with the |
| +// wildcards, and the CA's rate limits are per account and per registered |
| +// domain), a one-hour backoff per name after a failure, twelve hours when |
| +// the provider does not hold the zone. |
| +// |
| +// A name covered by a wildcard this box can serve is left to the wildcard. |
| + |
| +import ( |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "golang.org/x/crypto/acme/autocert" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +const ( |
| + // preIssueInterval is the pass cadence: the time from an attach to the |
| + // order, at worst. A pass on a quiet deployment is one bucket listing on |
| + // the issuer. |
| + preIssueInterval = time.Minute |
| + // preIssueOrdersPerPass bounds one pass's ACME work, so a newly listed |
| + // zone with many attached names drains over several passes rather than |
| + // in one burst. |
| + preIssueOrdersPerPass = 5 |
| + // preIssueOrdersPerHour bounds the orders this box places in any hour. |
| + preIssueOrdersPerHour = 20 |
| + // preIssueRetry is a name's backoff after a failed order: Let's Encrypt |
| + // allows five failed validations per account, hostname and hour. |
| + preIssueRetry = time.Hour |
| + // preIssueOrderTimeout budgets one order, the TXT wait included. |
| + preIssueOrderTimeout = 10 * time.Minute |
| +) |
| + |
| +// preIssueDue reports whether leaf should be replaced now: ahead of the |
| +// moment autocert's own renewal would start (min(lifetime/3, 30 days) before |
| +// expiry, renewal.go's next()), by a week or a twelfth of the lifetime, |
| +// whichever is less. Ahead, so that autocert's timer, once the name points, |
| +// finds a fresh certificate and orders nothing. |
| +func preIssueDue(leaf *x509.Certificate, now time.Time) bool { |
| + life := leaf.NotAfter.Sub(leaf.NotBefore) |
| + ahead := min(life/3, 30*24*time.Hour) + min(life/12, 7*24*time.Hour) |
| + return !now.Before(leaf.NotAfter.Add(-ahead)) |
| +} |
| + |
| +// parseDNS01Zones reads CARLOS_DNS01_ZONES: comma-separated zone names, |
| +// lowercased, trailing dot dropped, deduplicated. An entry that is not a |
| +// hostname is dropped with a log line. nil when nothing valid is listed, |
| +// which is "off". |
| +func parseDNS01Zones(raw string) []string { |
| + var out []string |
| + for _, z := range strings.Split(raw, ",") { |
| + z = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(z)), ".") |
| + if z == "" { |
| + continue |
| + } |
| + if !provision.ValidHostShape(z) { |
| + log.Printf("edge: CARLOS_DNS01_ZONES entry %q is not a zone name, ignored", z) |
| + continue |
| + } |
| + if !slices.Contains(out, z) { |
| + out = append(out, z) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// preIssuer is the pass. Every input is a field so the decisions are |
| +// testable without an ACME server; newPreIssuerFromEnv wires the real ones. |
| +type preIssuer struct { |
| + zones []string |
| + // cache is the PUBLISHING cache (certsync.go): its Get reads this box's |
| + // own disk, its Put writes the disk and then the bucket. |
| + cache autocert.Cache |
| + // store is the deployment bucket, for republishing a local certificate |
| + // whose bucket copy is missing. |
| + store release.Store |
| + issuer IssuerGate |
| + claims func(context.Context) ([]domains.Claim, error) |
| + // published reads the mirror's copy of control/certs/<name>. |
| + published func(name string) ([]byte, bool) |
| + // covered reports whether a wildcard this box can serve covers host. nil |
| + // = no wildcard manager. |
| + covered func(host string) bool |
| + // order runs one DNS-01 order for host (dns01OrderFunc in production). |
| + order func(ctx context.Context, host string) (*tls.Certificate, *ecdsa.PrivateKey, error) |
| + now func() time.Time |
| + |
| + mu sync.Mutex |
| + nextAttempt map[string]time.Time |
| + // ordered is when each order of the last hour started, oldest first. |
| + ordered []time.Time |
| + // putAt is when this box last wrote each name to the bucket, so a pass |
| + // that runs before the mirror has seen the write does not write it again. |
| + putAt map[string]time.Time |
| + lastClaimLog time.Time |
| +} |
| + |
| +func newPreIssuer(zones []string, cache autocert.Cache, store release.Store, issuer IssuerGate, |
| + claims func(context.Context) ([]domains.Claim, error), published func(string) ([]byte, bool), |
| + covered func(string) bool, order func(context.Context, string) (*tls.Certificate, *ecdsa.PrivateKey, error)) *preIssuer { |
| + return &preIssuer{ |
| + zones: zones, cache: cache, store: store, issuer: issuer, claims: claims, |
| + published: published, covered: covered, order: order, now: time.Now, |
| + nextAttempt: map[string]time.Time{}, putAt: map[string]time.Time{}, |
| + } |
| +} |
| + |
| +// dns01OrderFunc is the production order: a DNS-01 order for exactly host, |
| +// its challenge published directly at _acme-challenge.<host> in the |
| +// provider, under the deployment's DNS-01 account kept in cache. |
| +func dns01OrderFunc(cache autocert.Cache, directory string, dns dnsProvider) func(context.Context, string) (*tls.Certificate, *ecdsa.PrivateKey, error) { |
| + return func(ctx context.Context, host string) (*tls.Certificate, *ecdsa.PrivateKey, error) { |
| + return dns01Order(ctx, cache, directory, dns, host, "_acme-challenge."+host, "pre-issue "+host) |
| + } |
| +} |
| + |
| +// newPreIssuerFromEnv arms the pre-issuer, or returns nil: CARLOS_DNS01_ZONES |
| +// unset (silent, the default), or set with no DNS provider to publish through |
| +// (logged). Called only on a box with a deployment store, so the mirror and |
| +// the issuer gate exist. |
| +func (e *Edge) newPreIssuerFromEnv(cache autocert.Cache, mirror *certMirror, wm *wildcardManager) *preIssuer { |
| + zones := parseDNS01Zones(os.Getenv("CARLOS_DNS01_ZONES")) |
| + if len(zones) == 0 || e.staticStore == nil || mirror == nil { |
| + return nil |
| + } |
| + dns, reason := dnsProviderFromEnv() |
| + if dns == nil { |
| + log.Printf("edge: CARLOS_DNS01_ZONES is set but there is no DNS provider (%s) — certificates are not issued before DNS moves", reason) |
| + return nil |
| + } |
| + store := e.staticStore |
| + cc := &domains.ClaimCache{} |
| + claims := func(ctx context.Context) ([]domains.Claim, error) { return cc.List(ctx, store) } |
| + var covered func(string) bool |
| + if wm != nil { |
| + covered = func(h string) bool { return wm.certFor(h) != nil } |
| + } |
| + directory := envOr("CARLOS_ACME_DIRECTORY", letsEncryptDirectory) |
| + return newPreIssuer(zones, cache, store, e.issuerGate, claims, mirror.Cert, covered, dns01OrderFunc(cache, directory, dns)) |
| +} |
| + |
| +func (p *preIssuer) run() { |
| + for { |
| + p.pass(context.Background()) |
| + time.Sleep(preIssueInterval) |
| + } |
| +} |
| + |
| +// inZone reports whether host is a listed zone or a name under one. |
| +func (p *preIssuer) inZone(host string) bool { |
| + for _, z := range p.zones { |
| + if host == z || strings.HasSuffix(host, "."+z) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// candidates is the sorted set of hostnames the pass looks after. |
| +func (p *preIssuer) candidates(claims []domains.Claim) []string { |
| + var out []string |
| + for _, c := range claims { |
| + host := strings.TrimSuffix(strings.ToLower(c.Host), ".") |
| + switch { |
| + case c.Pending, strings.HasPrefix(host, "*."), c.Route == "" && !c.Regional(): |
| + continue |
| + case !p.inZone(host): |
| + continue |
| + case p.covered != nil && p.covered(host): |
| + continue |
| + } |
| + if !slices.Contains(out, host) { |
| + out = append(out, host) |
| + } |
| + } |
| + slices.Sort(out) |
| + return out |
| +} |
| + |
| +// current reports whether body is a certificate for host that is not yet due. |
| +func current(body []byte, host string, now time.Time) bool { |
| + cert, err := parseCertEntry(body) |
| + return err == nil && cert.Leaf.VerifyHostname(host) == nil && !preIssueDue(cert.Leaf, now) |
| +} |
| + |
| +// pass is one sweep: nothing unless this box is the issuer, then every |
| +// candidate without a current published certificate gets one, within the |
| +// bounds. |
| +func (p *preIssuer) pass(ctx context.Context) { |
| + held, ok := p.issuer() |
| + if !ok { |
| + return |
| + } |
| + cctx, cancel := context.WithTimeout(held, time.Minute) |
| + claims, err := p.claims(cctx) |
| + cancel() |
| + if err != nil { |
| + p.logClaimsFailure(err) |
| + return |
| + } |
| + hosts := p.candidates(claims) |
| + p.forget(hosts) |
| + orders := 0 |
| + for _, host := range hosts { |
| + now := p.now() |
| + if body, ok := p.published(host); ok && current(body, host, now) { |
| + continue |
| + } |
| + if p.republish(ctx, host, now) { |
| + continue |
| + } |
| + if p.backingOff(host, now) { |
| + continue |
| + } |
| + if orders >= preIssueOrdersPerPass || !p.spend(now) { |
| + return |
| + } |
| + orders++ |
| + if err := p.issue(held, host); err != nil { |
| + retry := preIssueRetry |
| + if errors.Is(err, errNoZone) { |
| + retry = noZoneRetry |
| + } |
| + log.Printf("edge: pre-issue %s: %v — retrying in %s; HTTP-01 still covers it once it points here", host, err, retry) |
| + p.mu.Lock() |
| + p.nextAttempt[host] = now.Add(retry) |
| + p.mu.Unlock() |
| + continue |
| + } |
| + p.mu.Lock() |
| + delete(p.nextAttempt, host) |
| + p.mu.Unlock() |
| + } |
| +} |
| + |
| +// issue orders host's certificate and writes it through the publishing |
| +// cache: this box's disk, then control/certs/<host>. |
| +func (p *preIssuer) issue(held context.Context, host string) error { |
| + ctx, cancel := context.WithTimeout(held, preIssueOrderTimeout) |
| + defer cancel() |
| + cert, key, err := p.order(ctx, host) |
| + if err != nil { |
| + return err |
| + } |
| + // Never store what would not serve: the right name, the matching key. |
| + if cert.Leaf == nil || cert.Leaf.VerifyHostname(host) != nil { |
| + return fmt.Errorf("issued certificate does not cover %s", host) |
| + } |
| + if !key.PublicKey.Equal(cert.Leaf.PublicKey) { |
| + return fmt.Errorf("issued certificate's key does not match") |
| + } |
| + // autocert's own cache format for an ECDSA entry: the key block, then |
| + // the chain (encodeWildcardPEM writes exactly that). |
| + raw, err := encodeWildcardPEM(cert, key) |
| + if err != nil { |
| + return fmt.Errorf("encode: %v", err) |
| + } |
| + if err := p.cache.Put(ctx, host, raw); err != nil { |
| + return fmt.Errorf("persist: %v", err) |
| + } |
| + p.mu.Lock() |
| + p.putAt[host] = p.now() |
| + p.mu.Unlock() |
| + log.Printf("edge: pre-issue %s: certificate issued over DNS-01 (valid until %s) and published for every edge", host, cert.Leaf.NotAfter.Format(time.RFC3339)) |
| + return nil |
| +} |
| + |
| +// republish handles a name whose published copy is missing or due while this |
| +// box's own disk holds a current certificate: a bucket publish that failed |
| +// after an order succeeded (publishingCache logs and swallows those). It |
| +// writes the local copy to the bucket instead of ordering again, and reports |
| +// whether the local copy was current (in which case there is nothing to |
| +// order, whether or not the write landed). A name this box wrote within the |
| +// mirror's reach of now is left alone: the mirror has not caught up yet. |
| +func (p *preIssuer) republish(ctx context.Context, host string, now time.Time) bool { |
| + gctx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| + defer cancel() |
| + body, err := p.cache.Get(gctx, host) |
| + if err != nil || !current(body, host, now) { |
| + return false |
| + } |
| + p.mu.Lock() |
| + at, recent := p.putAt[host] |
| + p.mu.Unlock() |
| + if recent && now.Sub(at) < 5*time.Minute { |
| + return true |
| + } |
| + if err := putCert(gctx, p.store, host, body); err != nil { |
| + log.Printf("edge: pre-issue %s: republishing this box's certificate failed: %v — retrying next pass", host, err) |
| + return true |
| + } |
| + p.mu.Lock() |
| + p.putAt[host] = now |
| + p.mu.Unlock() |
| + log.Printf("edge: pre-issue %s: republished this box's current certificate to %s", host, certPrefix) |
| + return true |
| +} |
| + |
| +func (p *preIssuer) backingOff(host string, now time.Time) bool { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + next, ok := p.nextAttempt[host] |
| + return ok && now.Before(next) |
| +} |
| + |
| +// spend takes one order from the hourly budget, or reports that it is spent. |
| +func (p *preIssuer) spend(now time.Time) bool { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + cut := 0 |
| + for cut < len(p.ordered) && now.Sub(p.ordered[cut]) >= time.Hour { |
| + cut++ |
| + } |
| + p.ordered = p.ordered[cut:] |
| + if len(p.ordered) >= preIssueOrdersPerHour { |
| + return false |
| + } |
| + p.ordered = append(p.ordered, now) |
| + return true |
| +} |
| + |
| +// forget drops bookkeeping for names that are no longer candidates, so the |
| +// maps track the claim set rather than every name ever attached. |
| +func (p *preIssuer) forget(hosts []string) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + for h := range p.nextAttempt { |
| + if !slices.Contains(hosts, h) { |
| + delete(p.nextAttempt, h) |
| + } |
| + } |
| + for h := range p.putAt { |
| + if !slices.Contains(hosts, h) { |
| + delete(p.putAt, h) |
| + } |
| + } |
| +} |
| + |
| +// logClaimsFailure says a failed claims read at most hourly: it repeats every |
| +// minute for as long as the bucket is unreachable. |
| +func (p *preIssuer) logClaimsFailure(err error) { |
| + now := p.now() |
| + p.mu.Lock() |
| + quiet := now.Sub(p.lastClaimLog) < time.Hour |
| + if !quiet { |
| + p.lastClaimLog = now |
| + } |
| + p.mu.Unlock() |
| + if !quiet { |
| + log.Printf("edge: pre-issue: reading the domain claims failed: %v — no certificates are issued before DNS moves until it reads again", err) |
| + } |
| +} |
diff --git a/internal/edge/precert_test.go b/internal/edge/precert_test.go| new file mode 100644 |
| index 000000000..c2f0ba8c4 |
| --- /dev/null |
| +++ b/internal/edge/precert_test.go |
| @@ -0,0 +1,490 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/sha256" |
| + "crypto/tls" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/crypto/acme/autocert" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// ---- the fake CA's dns-01 mode ----------------------------------------------- |
| + |
| +// validateDNS01 is the fake CA's dns-01 check (fakeACME.dns01TXT): the TXT |
| +// at _acme-challenge.<identifier> must carry base64url(sha256(keyAuth)), the |
| +// key authorization being token + "." + the ordering account's thumbprint. |
| +// Like the http-01 check it is a proof, not a narration: the value can only |
| +// be right if the account that ordered published it where the CA looks. |
| +func (ca *fakeACME) validateDNS01(w http.ResponseWriter, id string, o *fakeACMEOrder, domain, token, thumb string) { |
| + sum := sha256.Sum256([]byte(token + "." + thumb)) |
| + want := base64.RawURLEncoding.EncodeToString(sum[:]) |
| + name := "_acme-challenge." + strings.TrimPrefix(domain, "*.") |
| + valid := slices.Contains(ca.dns01TXT(name), want) |
| + |
| + ca.mu.Lock() |
| + ca.validations = append(ca.validations, fakeACMEValidation{url: "dns:" + name, host: domain, token: token, ok: valid}) |
| + if valid { |
| + o.authz, o.status = "valid", "ready" |
| + } else { |
| + o.authz, o.status = "invalid", "invalid" |
| + ca.faults = append(ca.faults, fmt.Sprintf("dns-01 for %s: no TXT %q at %s", domain, want, name)) |
| + } |
| + ca.mu.Unlock() |
| + |
| + writeJSON(w, http.StatusOK, map[string]string{ |
| + "type": "dns-01", "url": ca.url("/chal/" + id), "token": token, "status": "valid", |
| + }) |
| +} |
| + |
| +// liveDNS is a DNS provider whose records the fake CA can read: present adds |
| +// a TXT, cleanup removes it, and checkZone answers from a fixed zone list. |
| +type liveDNS struct { |
| + mu sync.Mutex |
| + zones []string |
| + txt map[string][]string |
| + presented []string // fqdn, in order |
| + cleaned []string // fqdn, in order |
| +} |
| + |
| +func newLiveDNS(zones ...string) *liveDNS { |
| + return &liveDNS{zones: zones, txt: map[string][]string{}} |
| +} |
| + |
| +func (d *liveDNS) holds(fqdn string) bool { |
| + for _, z := range d.zones { |
| + if fqdn == z || strings.HasSuffix(fqdn, "."+z) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func (d *liveDNS) checkZone(_ context.Context, fqdn string) error { |
| + if !d.holds(fqdn) { |
| + return errNoZone |
| + } |
| + return nil |
| +} |
| + |
| +func (d *liveDNS) present(_ context.Context, fqdn, value string) (func(context.Context) error, error) { |
| + if !d.holds(fqdn) { |
| + return nil, errNoZone |
| + } |
| + d.mu.Lock() |
| + d.txt[fqdn] = append(d.txt[fqdn], value) |
| + d.presented = append(d.presented, fqdn) |
| + d.mu.Unlock() |
| + return func(context.Context) error { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + d.txt[fqdn] = slices.DeleteFunc(d.txt[fqdn], func(v string) bool { return v == value }) |
| + d.cleaned = append(d.cleaned, fqdn) |
| + return nil |
| + }, nil |
| +} |
| + |
| +func (d *liveDNS) lookup(name string) []string { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + return append([]string(nil), d.txt[name]...) |
| +} |
| + |
| +// noTXTWait skips the real-resolver wait for a test's duration: the records |
| +// live in liveDNS, which no resolver can see. |
| +func noTXTWait(t *testing.T) { |
| + t.Helper() |
| + prev := dns01TXTWait |
| + dns01TXTWait = func(context.Context, string, string, time.Duration) {} |
| + t.Cleanup(func() { dns01TXTWait = prev }) |
| +} |
| + |
| +// ---- fixtures ------------------------------------------------------------------ |
| + |
| +// proven is a served, proven claim: what an attach writes once the hostname |
| +// is verified. |
| +func proven(host string) domains.Claim { |
| + return domains.Claim{Schema: 1, Host: host, Account: "acct", App: "shop", Route: "shop.acct.apps.example.net"} |
| +} |
| + |
| +func staticClaims(cs ...domains.Claim) func(context.Context) ([]domains.Claim, error) { |
| + return func(context.Context) ([]domains.Claim, error) { return cs, nil } |
| +} |
| + |
| +// fakeOrder is an order seam that mints a self-signed leaf for the host (a |
| +// real CA round trip is TestPreIssueE2E's job) and counts what it was asked. |
| +type fakeOrder struct { |
| + mu sync.Mutex |
| + asked []string |
| + fail error |
| + life time.Duration |
| +} |
| + |
| +func (f *fakeOrder) order(t *testing.T) func(context.Context, string) (*tls.Certificate, *ecdsa.PrivateKey, error) { |
| + return func(_ context.Context, host string) (*tls.Certificate, *ecdsa.PrivateKey, error) { |
| + f.mu.Lock() |
| + f.asked = append(f.asked, host) |
| + fail, life := f.fail, f.life |
| + f.mu.Unlock() |
| + if fail != nil { |
| + return nil, nil, fail |
| + } |
| + if life == 0 { |
| + life = 90 * 24 * time.Hour |
| + } |
| + cert, key := selfSignedLeaf(t, host, time.Now().Add(life)) |
| + return cert, key, nil |
| + } |
| +} |
| + |
| +func (f *fakeOrder) count() int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return len(f.asked) |
| +} |
| + |
| +// testPreIssuer is a pre-issuer over a DirStore bucket and a publishing cache |
| +// on a held gate, with the claims and order seams given. |
| +func testPreIssuer(t *testing.T, zones []string, claims func(context.Context) ([]domains.Claim, error), order func(context.Context, string) (*tls.Certificate, *ecdsa.PrivateKey, error)) (*preIssuer, release.Store, autocert.Cache) { |
| + t.Helper() |
| + store := release.NewDirStore(t.TempDir()) |
| + local := autocert.DirCache(t.TempDir()) |
| + held := func() (context.Context, bool) { return context.Background(), true } |
| + cache := &publishingCache{inner: local, s: store, issuer: held} |
| + published := func(name string) ([]byte, bool) { |
| + b, err := certStoreGet(t, store, certKey(name)) |
| + return b, err == nil |
| + } |
| + p := newPreIssuer(zones, cache, store, held, claims, published, nil, order) |
| + return p, store, local |
| +} |
| + |
| +// ---- the end-to-end proof: certificate before DNS ------------------------------ |
| + |
| +// TestPreIssueE2E is #1293's scenario. A hostname is attached under a zone |
| +// the deployment's DNS provider writes, and nothing points at the deployment |
| +// yet. The issuer orders over dns-01 through a real ACME exchange (the fake |
| +// CA checks the TXT value against the ordering account), the certificate |
| +// lands in control/certs/<host>, and ANOTHER edge, one that is not the |
| +// issuer, serves it for the hostname straight from its mirror. That last |
| +// step is the one that failed on 11-19. |
| +func TestPreIssueE2E(t *testing.T) { |
| + e2eQuietLogs(t) |
| + noTXTWait(t) |
| + const host = "billing.example.com" |
| + dns := newLiveDNS("example.com") |
| + ca := newFakeACME(t) |
| + ca.dns01TXT = dns.lookup |
| + |
| + p, store, _ := testPreIssuer(t, []string{"example.com"}, staticClaims(proven(host)), nil) |
| + p.order = dns01OrderFunc(p.cache, ca.directoryURL(), dns) |
| + |
| + p.pass(context.Background()) |
| + ca.checkFaults(t) |
| + |
| + if _, orders := ca.counts(); orders != 1 { |
| + t.Fatalf("CA saw %d orders, want 1", orders) |
| + } |
| + if got := dns.presented; !slices.Equal(got, []string{"_acme-challenge." + host}) { |
| + t.Fatalf("challenge published at %v, want only _acme-challenge.%s", got, host) |
| + } |
| + if got := dns.cleaned; !slices.Equal(got, []string{"_acme-challenge." + host}) { |
| + t.Fatalf("challenge cleanup %v: the TXT must not outlive the order", got) |
| + } |
| + body, err := certStoreGet(t, store, certKey(host)) |
| + if err != nil { |
| + t.Fatalf("control/certs/%s: %v — the certificate must be published for every edge", host, err) |
| + } |
| + cert, err := parseCertEntry(body) |
| + if err != nil || cert.Leaf.VerifyHostname(host) != nil { |
| + t.Fatalf("published entry does not cover %s: %v", host, err) |
| + } |
| + if cert.Leaf.Issuer.CommonName != ca.root.Subject.CommonName { |
| + t.Fatalf("published leaf issued by %q, want the CA's", cert.Leaf.Issuer.CommonName) |
| + } |
| + |
| + // The home box: a gated mirror on another disk, whose autocert refuses |
| + // exactly as IE's did on 11-19. |
| + home := newCertMirror(store, autocert.DirCache(t.TempDir())) |
| + if err := home.Refresh(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + refuse := func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return nil, errNotIssuer } |
| + got, err := home.wrapGetCertificate(refuse)(&tls.ClientHelloInfo{ServerName: host}) |
| + if err != nil || got == nil || got.Leaf.VerifyHostname(host) != nil { |
| + t.Fatalf("home box handshake for %s: cert %v, err %v — want the pre-issued certificate", host, got != nil, err) |
| + } |
| + |
| + // A second pass finds the published certificate current and orders |
| + // nothing. |
| + p.pass(context.Background()) |
| + if _, orders := ca.counts(); orders != 1 { |
| + t.Fatalf("second pass ordered again: CA saw %d orders", orders) |
| + } |
| +} |
| + |
| +// The wildcard manager's orders run through the same dns01Order after the |
| +// refactor; this pins that a *.<parent> order still completes and covers. |
| +func TestWildcardObtainOverDNS01(t *testing.T) { |
| + e2eQuietLogs(t) |
| + noTXTWait(t) |
| + dns := newLiveDNS("example.com") |
| + ca := newFakeACME(t) |
| + ca.dns01TXT = dns.lookup |
| + w := newWildcardManager([]string{"go.example.com"}, "", func() []string { return nil }, nil, "", autocert.DirCache(t.TempDir()), dns) |
| + w.directory = ca.directoryURL() |
| + w.refresh() |
| + if err := w.obtain(context.Background(), "go.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + ca.checkFaults(t) |
| + if c := w.certFor("x.go.example.com"); c == nil { |
| + t.Fatal("wildcard not serving after obtain") |
| + } |
| + if got := dns.presented; !slices.Equal(got, []string{"_acme-challenge.go.example.com"}) { |
| + t.Fatalf("challenge published at %v", got) |
| + } |
| +} |
| + |
| +// ---- which names -------------------------------------------------------------- |
| + |
| +func TestPreIssueCandidates(t *testing.T) { |
| + pending := proven("pending.example.com") |
| + pending.Pending, pending.PendingUntil = true, time.Now().Add(time.Hour).UTC().Format(time.RFC3339) |
| + noRoute := proven("noroute.example.com") |
| + noRoute.Route = "" |
| + regional := proven("regional.example.com") |
| + regional.Route = "" |
| + regional.Schema = 2 |
| + regional.Placements = []domains.Placement{{Region: "ie", Host: "shop-ie.acct.apps.example.net"}} |
| + catchall := proven("*.example.com") |
| + |
| + claims := []domains.Claim{ |
| + proven("Billing.Example.com"), // case folds |
| + proven("billing.example.com"), // and dedupes |
| + proven("example.com"), // the zone apex is inside the zone |
| + proven("deep.a.b.example.com"), |
| + proven("badexample.com"), // a suffix, not a subdomain |
| + proven("shop.other.test"), |
| + proven("x.covered.example.com"), |
| + pending, |
| + noRoute, |
| + regional, |
| + catchall, |
| + } |
| + p, _, _ := testPreIssuer(t, []string{"example.com"}, nil, nil) |
| + p.covered = func(h string) bool { return strings.HasSuffix(h, ".covered.example.com") } |
| + got := p.candidates(claims) |
| + want := []string{"billing.example.com", "deep.a.b.example.com", "example.com", "regional.example.com"} |
| + if !slices.Equal(got, want) { |
| + t.Fatalf("candidates = %v, want %v", got, want) |
| + } |
| +} |
| + |
| +func TestDNS01ZonesFromEnv(t *testing.T) { |
| + got := parseDNS01Zones(" Example.com. ,,ti.example ,not a zone, example.com,*.wild.test") |
| + want := []string{"example.com", "ti.example"} |
| + if !slices.Equal(got, want) { |
| + t.Fatalf("parseDNS01Zones = %v, want %v", got, want) |
| + } |
| + if parseDNS01Zones("") != nil { |
| + t.Fatal("unset must be nil: the feature is off") |
| + } |
| +} |
| + |
| +// ---- when to order -------------------------------------------------------------- |
| + |
| +func TestPreIssueDue(t *testing.T) { |
| + now := time.Now() |
| + leaf := func(life, left time.Duration) *tls.Certificate { |
| + c, _ := selfSignedLeaf(t, "h.example.com", now.Add(left)) |
| + c.Leaf.NotBefore = now.Add(left - life) |
| + return c |
| + } |
| + day := 24 * time.Hour |
| + // 90-day: autocert renews at 30 days left; we go a week before that. |
| + if preIssueDue(leaf(90*day, 38*day).Leaf, now) { |
| + t.Fatal("90-day cert, 38 days left: not due yet") |
| + } |
| + if !preIssueDue(leaf(90*day, 36*day).Leaf, now) { |
| + t.Fatal("90-day cert, 36 days left: due (ahead of autocert's 30)") |
| + } |
| + // 45-day: autocert's threshold is lifetime/3 = 15 days; ours stays ahead. |
| + if preIssueDue(leaf(45*day, 20*day).Leaf, now) { |
| + t.Fatal("45-day cert, 20 days left: not due yet") |
| + } |
| + if !preIssueDue(leaf(45*day, 17*day).Leaf, now) { |
| + t.Fatal("45-day cert, 17 days left: due") |
| + } |
| +} |
| + |
| +func TestPreIssueOrdersOnlyWhatLacksACurrentCert(t *testing.T) { |
| + e2eQuietLogs(t) |
| + fo := &fakeOrder{} |
| + p, store, _ := testPreIssuer(t, []string{"example.com"}, |
| + staticClaims(proven("fresh.example.com"), proven("stale.example.com"), proven("none.example.com")), fo.order(t)) |
| + ctx := context.Background() |
| + day := 24 * time.Hour |
| + now := time.Now() |
| + for name, raw := range map[string][]byte{ |
| + // 90-day certificates: 80 days left, and 10 left (inside the window). |
| + "fresh.example.com": e2eDatedCertPEM(t, "fresh.example.com", now.Add(-10*day), now.Add(80*day)), |
| + "stale.example.com": e2eDatedCertPEM(t, "stale.example.com", now.Add(-80*day), now.Add(10*day)), |
| + } { |
| + if err := putCert(ctx, store, name, raw); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + p.pass(ctx) |
| + got := append([]string(nil), fo.asked...) |
| + slices.Sort(got) |
| + if want := []string{"none.example.com", "stale.example.com"}; !slices.Equal(got, want) { |
| + t.Fatalf("ordered %v, want %v", got, want) |
| + } |
| + for _, h := range got { |
| + body, err := certStoreGet(t, store, certKey(h)) |
| + if err != nil { |
| + t.Fatalf("%s not published: %v", h, err) |
| + } |
| + if c, err := parseCertEntry(body); err != nil || preIssueDue(c.Leaf, time.Now()) { |
| + t.Fatalf("%s: published entry not current (%v)", h, err) |
| + } |
| + } |
| +} |
| + |
| +// ---- who orders --------------------------------------------------------------- |
| + |
| +// A box that is not the issuer reads no claims and orders nothing: the claim |
| +// listing is the issuer's cost alone. |
| +func TestPreIssueNonIssuerDoesNothing(t *testing.T) { |
| + fo := &fakeOrder{} |
| + read := 0 |
| + claims := func(context.Context) ([]domains.Claim, error) { |
| + read++ |
| + return []domains.Claim{proven("billing.example.com")}, nil |
| + } |
| + p, _, _ := testPreIssuer(t, []string{"example.com"}, claims, fo.order(t)) |
| + p.issuer = func() (context.Context, bool) { return nil, false } |
| + p.pass(context.Background()) |
| + if read != 0 || fo.count() != 0 { |
| + t.Fatalf("non-issuer read claims %d times and ordered %d", read, fo.count()) |
| + } |
| +} |
| + |
| +// ---- failure and bounds --------------------------------------------------------- |
| + |
| +func TestPreIssueBackoff(t *testing.T) { |
| + e2eQuietLogs(t) |
| + fo := &fakeOrder{fail: errors.New("CA said no")} |
| + p, _, _ := testPreIssuer(t, []string{"example.com"}, staticClaims(proven("a.example.com")), fo.order(t)) |
| + now := time.Now() |
| + p.now = func() time.Time { return now } |
| + ctx := context.Background() |
| + p.pass(ctx) |
| + p.pass(ctx) |
| + if fo.count() != 1 { |
| + t.Fatalf("failed name retried inside its backoff: %d orders", fo.count()) |
| + } |
| + now = now.Add(preIssueRetry + time.Second) |
| + p.pass(ctx) |
| + if fo.count() != 2 { |
| + t.Fatalf("failed name not retried after the backoff: %d orders", fo.count()) |
| + } |
| + |
| + // A zone the provider does not hold waits the long retry. |
| + fo.mu.Lock() |
| + fo.fail = fmt.Errorf("cannot publish the DNS-01 challenge: %w", errNoZone) |
| + fo.mu.Unlock() |
| + now = now.Add(preIssueRetry + time.Second) |
| + p.pass(ctx) |
| + now = now.Add(preIssueRetry + time.Second) |
| + p.pass(ctx) |
| + if fo.count() != 3 { |
| + t.Fatalf("no-zone name retried after an hour: %d orders", fo.count()) |
| + } |
| + now = now.Add(noZoneRetry) |
| + p.pass(ctx) |
| + if fo.count() != 4 { |
| + t.Fatalf("no-zone name never retried: %d orders", fo.count()) |
| + } |
| +} |
| + |
| +func TestPreIssueCaps(t *testing.T) { |
| + e2eQuietLogs(t) |
| + fo := &fakeOrder{} |
| + var cs []domains.Claim |
| + for i := range 3 * preIssueOrdersPerHour { |
| + cs = append(cs, proven(fmt.Sprintf("h%02d.example.com", i))) |
| + } |
| + p, _, _ := testPreIssuer(t, []string{"example.com"}, staticClaims(cs...), fo.order(t)) |
| + now := time.Now() |
| + p.now = func() time.Time { return now } |
| + ctx := context.Background() |
| + p.pass(ctx) |
| + if fo.count() != preIssueOrdersPerPass { |
| + t.Fatalf("one pass placed %d orders, want the per-pass cap %d", fo.count(), preIssueOrdersPerPass) |
| + } |
| + for range 2 * preIssueOrdersPerHour { |
| + now = now.Add(preIssueInterval) |
| + p.pass(ctx) |
| + } |
| + if fo.count() > preIssueOrdersPerHour+preIssueOrdersPerPass { |
| + t.Fatalf("%d orders inside about an hour, want at most the hourly cap %d", fo.count(), preIssueOrdersPerHour) |
| + } |
| + now = now.Add(2 * time.Hour) |
| + before := fo.count() |
| + p.pass(ctx) |
| + if fo.count() == before { |
| + t.Fatal("hourly cap never released") |
| + } |
| +} |
| + |
| +// A certificate this box holds locally but the bucket lacks (a publish that |
| +// failed) is republished, not ordered again. |
| +func TestPreIssueRepublishesALocalCert(t *testing.T) { |
| + e2eQuietLogs(t) |
| + fo := &fakeOrder{} |
| + const host = "billing.example.com" |
| + p, store, local := testPreIssuer(t, []string{"example.com"}, staticClaims(proven(host)), fo.order(t)) |
| + ctx := context.Background() |
| + c, _ := selfSignedLeaf(t, host, time.Now().Add(80*24*time.Hour)) |
| + raw, err := encodeWildcardPEM(c, c.PrivateKey.(*ecdsa.PrivateKey)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := local.Put(ctx, host, raw); err != nil { |
| + t.Fatal(err) |
| + } |
| + p.pass(ctx) |
| + if fo.count() != 0 { |
| + t.Fatalf("ordered %d times for a name with a current local cert", fo.count()) |
| + } |
| + if got, err := certStoreGet(t, store, certKey(host)); err != nil || string(got) != string(raw) { |
| + t.Fatalf("local cert not republished to the bucket: %v", err) |
| + } |
| +} |
| + |
| +// The claims read failing is logged and the pass ends: nothing is ordered on |
| +// a partial picture. |
| +func TestPreIssueClaimsReadFailure(t *testing.T) { |
| + e2eQuietLogs(t) |
| + fo := &fakeOrder{} |
| + p, _, _ := testPreIssuer(t, []string{"example.com"}, |
| + func(context.Context) ([]domains.Claim, error) { return nil, errors.New("bucket down") }, fo.order(t)) |
| + p.pass(context.Background()) |
| + if fo.count() != 0 { |
| + t.Fatal("ordered after a failed claims read") |
| + } |
| +} |
diff --git a/internal/edge/wildcard.go b/internal/edge/wildcard.go| index 161bc14fb..6d9855194 100644 |
| --- a/internal/edge/wildcard.go |
| +++ b/internal/edge/wildcard.go |
| @@ -691,6 +691,35 @@ const noZoneRetry = 12 * time.Hour |
| // obtain runs one full ACME DNS-01 issuance for *.parent and swaps the |
| // result in. |
| func (w *wildcardManager) obtain(ctx context.Context, parent string) error { |
| + cert, certKey, err := dns01Order(ctx, w.cache, w.directory, w.dns, "*."+parent, w.challengeFQDN(parent), "wildcard *."+parent) |
| + if err != nil { |
| + return err |
| + } |
| + // Paranoia: never store what certFor would refuse to serve. |
| + if !coversParent(cert, parent) { |
| + return fmt.Errorf("issued cert does not cover *.%s", parent) |
| + } |
| + raw, err := encodeWildcardPEM(cert, certKey) |
| + if err != nil { |
| + return fmt.Errorf("encode: %v", err) |
| + } |
| + if err := w.cache.Put(ctx, wildcardPEMKey(parent), raw); err != nil { |
| + return fmt.Errorf("persist: %v", err) |
| + } |
| + w.mu.Lock() |
| + w.certs[parent] = cert |
| + w.mu.Unlock() |
| + return nil |
| +} |
| + |
| +// dns01Order runs one ACME order for a single identifier over DNS-01 and |
| +// returns the issued chain with its fresh key. It is the CA conversation and |
| +// nothing else: the caller decides what the result must cover and where it |
| +// is kept. Two callers share it, and with it the deployment's one DNS-01 ACME |
| +// account: the wildcard manager above (identifier "*.<parent>") and the |
| +// pre-issuer (precert.go, an exact hostname). label names the work in log |
| +// lines ("wildcard *.<parent>", "pre-issue <host>"). |
| +func dns01Order(ctx context.Context, cache autocert.Cache, directory string, dns dnsProvider, identifier, challengeFQDN, label string) (*tls.Certificate, *ecdsa.PrivateKey, error) { |
| // Before the CA hears anything: can the provider publish the challenge |
| // at all? A parent whose zone lives elsewhere (per-account platform |
| // parents on a deployment whose apps domain is not in the provider's |
| @@ -699,70 +728,61 @@ func (w *wildcardManager) obtain(ctx context.Context, parent string) error { |
| // rate limits, since the authorization is deactivated and never |
| // validated, but a pointless round trip to the CA and a journal line per |
| // parent per hour. The lookup is the one present would make first. |
| - if zc, ok := w.dns.(zoneChecker); ok { |
| - if err := zc.checkZone(ctx, w.challengeFQDN(parent)); err != nil { |
| - return fmt.Errorf("cannot publish the DNS-01 challenge: %w", err) |
| + if zc, ok := dns.(zoneChecker); ok { |
| + if err := zc.checkZone(ctx, challengeFQDN); err != nil { |
| + return nil, nil, fmt.Errorf("cannot publish the DNS-01 challenge: %w", err) |
| } |
| } |
| - acctKey, err := w.accountKey(ctx) |
| + acctKey, err := dns01AccountKey(ctx, cache) |
| if err != nil { |
| - return fmt.Errorf("account key: %v", err) |
| + return nil, nil, fmt.Errorf("account key: %v", err) |
| } |
| - client := &acme.Client{Key: acctKey, DirectoryURL: w.directory} |
| + client := &acme.Client{Key: acctKey, DirectoryURL: directory} |
| if _, err := client.Register(ctx, &acme.Account{}, acme.AcceptTOS); err != nil && err != acme.ErrAccountAlreadyExists { |
| - return fmt.Errorf("acme register: %v", err) |
| + return nil, nil, fmt.Errorf("acme register: %v", err) |
| } |
| - order, err := client.AuthorizeOrder(ctx, []acme.AuthzID{{Type: "dns", Value: "*." + parent}}) |
| + order, err := client.AuthorizeOrder(ctx, []acme.AuthzID{{Type: "dns", Value: identifier}}) |
| if err != nil { |
| - return fmt.Errorf("authorize order: %v", err) |
| + return nil, nil, fmt.Errorf("authorize order: %v", err) |
| } |
| for _, zurl := range order.AuthzURLs { |
| - if err := w.solveDNS01(ctx, client, parent, zurl); err != nil { |
| - return err |
| + if err := solveDNS01(ctx, client, dns, label, challengeFQDN, zurl); err != nil { |
| + return nil, nil, err |
| } |
| } |
| certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| if err != nil { |
| - return err |
| + return nil, nil, err |
| } |
| csr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{ |
| - Subject: pkix.Name{CommonName: "*." + parent}, |
| - DNSNames: []string{"*." + parent}, |
| + Subject: pkix.Name{CommonName: identifier}, |
| + DNSNames: []string{identifier}, |
| }, certKey) |
| if err != nil { |
| - return fmt.Errorf("csr: %v", err) |
| + return nil, nil, fmt.Errorf("csr: %v", err) |
| } |
| ders, _, err := client.CreateOrderCert(ctx, order.FinalizeURL, csr, true) |
| if err != nil { |
| - return fmt.Errorf("finalize: %v", err) |
| + return nil, nil, fmt.Errorf("finalize: %v", err) |
| } |
| leaf, err := x509.ParseCertificate(ders[0]) |
| if err != nil { |
| - return fmt.Errorf("parse issued cert: %v", err) |
| - } |
| - cert := &tls.Certificate{Certificate: ders, PrivateKey: certKey, Leaf: leaf} |
| - // Paranoia: never store what certFor would refuse to serve. |
| - if !coversParent(cert, parent) { |
| - return fmt.Errorf("issued cert does not cover *.%s", parent) |
| - } |
| - raw, err := encodeWildcardPEM(cert, certKey) |
| - if err != nil { |
| - return fmt.Errorf("encode: %v", err) |
| - } |
| - if err := w.cache.Put(ctx, wildcardPEMKey(parent), raw); err != nil { |
| - return fmt.Errorf("persist: %v", err) |
| + return nil, nil, fmt.Errorf("parse issued cert: %v", err) |
| } |
| - w.mu.Lock() |
| - w.certs[parent] = cert |
| - w.mu.Unlock() |
| - return nil |
| + return &tls.Certificate{Certificate: ders, PrivateKey: certKey, Leaf: leaf}, certKey, nil |
| } |
| -// solveDNS01 answers one authorization: publish the challenge TXT record, |
| -// wait for the CA to see it, and always clean the record up afterwards. |
| -func (w *wildcardManager) solveDNS01(ctx context.Context, client *acme.Client, parent, authzURL string) (retErr error) { |
| +// dns01TXTWait is waitForTXT, held in a variable so a test whose challenge |
| +// records live in a fake provider (and so never reach a real resolver) need |
| +// not sit out its minute. |
| +var dns01TXTWait = waitForTXT |
| + |
| +// solveDNS01 answers one authorization: publish the challenge TXT record at |
| +// challengeFQDN, wait for the CA to see it, and always clean the record up |
| +// afterwards. |
| +func solveDNS01(ctx context.Context, client *acme.Client, dns dnsProvider, label, challengeFQDN, authzURL string) (retErr error) { |
| authz, err := client.GetAuthorization(ctx, authzURL) |
| if err != nil { |
| return fmt.Errorf("get authorization: %v", err) |
| @@ -780,7 +800,7 @@ func (w *wildcardManager) solveDNS01(ctx context.Context, client *acme.Client, p |
| dctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer cancel() |
| if err := client.RevokeAuthorization(dctx, authz.URI); err != nil { |
| - log.Printf("edge: wildcard *.%s: deactivate abandoned authorization: %v", parent, err) |
| + log.Printf("edge: %s: deactivate abandoned authorization: %v", label, err) |
| } |
| }() |
| var chal *acme.Challenge |
| @@ -798,8 +818,7 @@ func (w *wildcardManager) solveDNS01(ctx context.Context, client *acme.Client, p |
| return err |
| } |
| - challengeFQDN := w.challengeFQDN(parent) |
| - cleanup, err := w.dns.present(ctx, challengeFQDN, txt) |
| + cleanup, err := dns.present(ctx, challengeFQDN, txt) |
| if err != nil { |
| return fmt.Errorf("publish challenge TXT: %v", err) |
| } |
| @@ -809,14 +828,14 @@ func (w *wildcardManager) solveDNS01(ctx context.Context, client *acme.Client, p |
| cctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer cancel() |
| if err := cleanup(cctx); err != nil { |
| - log.Printf("edge: wildcard *.%s: cleanup of challenge TXT failed: %v", parent, err) |
| + log.Printf("edge: %s: cleanup of challenge TXT failed: %v", label, err) |
| } |
| }() |
| // Best-effort: give the record a moment to reach the authoritative NS |
| // before telling the CA to look. Proceed on timeout — the CA does its own |
| // retries, and a hard failure just comes back through the retry loop. |
| - waitForTXT(ctx, challengeFQDN, txt, time.Minute) |
| + dns01TXTWait(ctx, challengeFQDN, txt, time.Minute) |
| if _, err := client.Accept(ctx, chal); err != nil { |
| return fmt.Errorf("accept challenge: %v", err) |
| @@ -828,13 +847,27 @@ func (w *wildcardManager) solveDNS01(ctx context.Context, client *acme.Client, p |
| } |
| // wildcardAccountKeyName is the ACME account key's cache key — Eleven's file |
| -// name, for the same no-migration reason as wildcardPEMKey. |
| +// name, for the same no-migration reason as wildcardPEMKey. Every DNS-01 |
| +// order in the deployment, wildcard or pre-issued host, runs under it. |
| const wildcardAccountKeyName = "wildcard-account.key" |
| // accountKey loads (or mints) the ACME account key. Separate from autocert's |
| // account on purpose: this flow manages its own registration lifecycle. |
| func (w *wildcardManager) accountKey(ctx context.Context) (*ecdsa.PrivateKey, error) { |
| - raw, err := w.cache.Get(ctx, wildcardAccountKeyName) |
| + return dns01AccountKey(ctx, w.cache) |
| +} |
| + |
| +// dns01AccountMu serializes the load-or-mint below. The wildcard manager and |
| +// the pre-issuer order on separate goroutines over one cache, and two first |
| +// orders racing a miss would each mint and register an account, the second |
| +// Put orphaning the first's registration. |
| +var dns01AccountMu sync.Mutex |
| + |
| +// dns01AccountKey loads (or mints) the DNS-01 ACME account key held in cache. |
| +func dns01AccountKey(ctx context.Context, cache autocert.Cache) (*ecdsa.PrivateKey, error) { |
| + dns01AccountMu.Lock() |
| + defer dns01AccountMu.Unlock() |
| + raw, err := cache.Get(ctx, wildcardAccountKeyName) |
| if err == nil { |
| block, _ := pem.Decode(raw) |
| if block == nil { |
| @@ -859,7 +892,7 @@ func (w *wildcardManager) accountKey(ctx context.Context) (*ecdsa.PrivateKey, er |
| // Crash-safety (temp + rename, 0600) is the cache backend's contract — |
| // the dir backend inherits it from autocert.DirCache. |
| raw = pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}) |
| - if err := w.cache.Put(ctx, wildcardAccountKeyName, raw); err != nil { |
| + if err := cache.Put(ctx, wildcardAccountKeyName, raw); err != nil { |
| return nil, err |
| } |
| return key, nil |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 81206e544..376025ecb 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -139,6 +139,10 @@ |
| // - CARLOS_ACME_DELEGATION_ZONE — our own zone that delegated wildcard |
| // parents' challenge TXTs publish into (spec §4); unset or an invalid |
| // shape = delegation off, per-host and direct DNS-01 continue |
| +// - CARLOS_DNS01_ZONES — comma list of zones the DNS-01 backend writes |
| +// (tito: tito.io) whose attached hostnames the issuer certifies over |
| +// DNS-01 from the claim, before their DNS points here (edge precert.go, |
| +// #1293); unset = off, custom domains wait for HTTP-01 as before |
| // - PLATFORM_EDGE_IPS — comma-separated edge IPs custom-domain DNS checks |
| // compare against. Default: this box's public IPv4 from IMDS |
| // (best-effort). It is no longer the WHOLE comparison set: each pass |
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go| index 55da6ecba..7a8698941 100644 |
| --- a/internal/hostenv/hostenv.go |
| +++ b/internal/hostenv/hostenv.go |
| @@ -91,6 +91,7 @@ var Optional = []string{ |
| "CARLOS_DEMO_API_ORIGIN", |
| "CARLOS_DEPLOYMENT_REGION", |
| "CARLOS_DEPLOYMENT_SINGLE_TENANT", |
| + "CARLOS_DNS01_ZONES", |
| "CARLOS_DNS_PROVIDER", |
| "CARLOS_EDGE_GZIP", |
| "CARLOS_EDGE_PROTECT", |