fix(certificates): add reliable issuance progress and DNS propagation handling

- replace raw ACME terminal logs with a scrollable TUI progress console
  - check authoritative DNS servers to avoid stale recursive cache delays
  - add per-order timeouts and actionable failure messages
  - support safe cancellation with DNS challenge cleanup
  - add background progress, summaries, and activity history
  - expand certificate workflow and TUI regression tests
This commit is contained in:
Meghdad committed 2026-07-13 06:53:45 +03:30
1 parent e925ade94a
commit 2518e345fc
15 files changed
+719 -44

No files matched your search

+64 -5
View File
@@ -404,6 +404,10 @@ func TestJournaledDNSProviderExactRecordLifecycle(t *testing.T) {
return provider.Auth{CredentialID: "credential-1", Token: "secret"}, "zone-1", nil
}
dnsProvider := NewJournaledDNSProvider(solver, repository, resolver, "job-1")
var presentedDomain, presentedFQDN string
dnsProvider.OnPresented = func(domainName, fqdn string) {
presentedDomain, presentedFQDN = domainName, fqdn
}
if err := dnsProvider.Present(context.Background(), "example.com", "token-1", "key-auth"); err != nil {
t.Fatal(err)
}
@@ -413,9 +417,17 @@ func TestJournaledDNSProviderExactRecordLifecycle(t *testing.T) {
if repository.challenges[0].ValueHash == "" || solver.presentedJob != "job-1" {
t.Fatalf("challenge was not hashed/tagged: %#v", repository.challenges[0])
}
if err := dnsProvider.CleanUp(context.Background(), "example.com", "token-1", "key-auth"); err != nil {
if presentedDomain != "example.com" || presentedFQDN != "_acme-challenge.example.com." {
t.Fatalf("presented callback = %q, %q", presentedDomain, presentedFQDN)
}
cancelled, cancel := context.WithCancel(context.Background())
cancel()
if err := dnsProvider.CleanUp(cancelled, "example.com", "token-1", "key-auth"); err != nil {
t.Fatal(err)
}
if solver.cleanupContextErr != nil {
t.Fatalf("cleanup inherited cancelled issuance context: %v", solver.cleanupContextErr)
}
if !slices.Equal(solver.cleaned, []string{"record-1"}) {
t.Fatalf("cleaned = %#v", solver.cleaned)
}
@@ -518,6 +530,46 @@ func TestIssueBatchCapsConcurrencyAndUsesFreshKeys(t *testing.T) {
}
}
func TestIssueDeadlineStopsAStalledBackendAndReportsStage(t *testing.T) {
accountKey, err := GeneratePrivateKey(domain.KeyECDSAP256)
if err != nil {
t.Fatal(err)
}
accountKeyPEM, err := MarshalPrivateKeyPKCS8(accountKey)
if err != nil {
t.Fatal(err)
}
registrationJSON, _ := json.Marshal(&acme.ExtendedAccount{Location: "https://acme.test/acct/1"})
repository := &memoryRepository{account: domain.ACMEAccount{
ID: "account-1", Environment: EnvironmentStaging, DirectoryURL: "https://acme.test/directory",
Email: "ops@example.com", Registration: string(registrationJSON), SecretRef: "secret-1",
}}
secrets := &memorySecrets{values: map[string][]byte{"secret-1": accountKeyPEM}}
backend := &fakeBackend{obtainDelay: time.Hour}
engine := NewEngine(repository, secrets, &fakeSolver{}, func(context.Context, string) (provider.Auth, string, error) {
return provider.Auth{}, "zone-1", nil
}, WithBackendFactory(fakeBackendFactory{backend: backend}), WithIssuanceTimeout(40*time.Millisecond))
plan, err := NewWildcardPlan("zone-1", "example.com")
if err != nil {
t.Fatal(err)
}
var progress []IssueProgress
started := time.Now()
_, err = engine.Issue(context.Background(), IssueRequest{
JobID: "job", Environment: EnvironmentStaging, Plan: plan,
Progress: func(value IssueProgress) { progress = append(progress, value) },
})
if err == nil || !strings.Contains(err.Error(), "safety deadline") || !strings.Contains(err.Error(), "acme-validation") {
t.Fatalf("deadline error = %v", err)
}
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("stalled issue returned after %s", elapsed)
}
if len(progress) < 2 || progress[0].Stage != "preflight" || progress[1].Stage != "acme-order" {
t.Fatalf("progress = %#v", progress)
}
}
func TestRenewSetsARIReplacementAndKeepsIdentifiers(t *testing.T) {
accountKey, err := GeneratePrivateKey(domain.KeyECDSAP256)
if err != nil {
@@ -1093,8 +1145,9 @@ func testVersion(id, lineageID string, artifact Artifact) domain.CertificateVers
}
type fakeSolver struct {
presentedJob string
cleaned []string
presentedJob string
cleaned []string
cleanupContextErr error
}
type recoverySolver struct {
@@ -1120,7 +1173,8 @@ func (s *fakeSolver) PresentDNS01(_ context.Context, _ provider.Auth, _, _, _, j
s.presentedJob = jobID
return "record-1", nil
}
func (s *fakeSolver) CleanupDNS01(_ context.Context, _ provider.Auth, _ string, recordID string) error {
func (s *fakeSolver) CleanupDNS01(ctx context.Context, _ provider.Auth, _ string, recordID string) error {
s.cleanupContextErr = ctx.Err()
s.cleaned = append(s.cleaned, recordID)
return nil
}
@@ -1291,6 +1345,7 @@ type fakeBackend struct {
replaces []string
renewalInfo *certificate.RenewalInfo
renewalErr error
obtainDelay time.Duration
}
func (b *fakeBackend) Obtain(ctx context.Context, request certificate.ObtainRequest) (*certificate.Resource, error) {
@@ -1302,8 +1357,12 @@ func (b *fakeBackend) Obtain(ctx context.Context, request certificate.ObtainRequ
}
}
defer b.active.Add(-1)
delay := b.obtainDelay
if delay <= 0 {
delay = 15 * time.Millisecond
}
select {
case <-time.After(15 * time.Millisecond):
case <-time.After(delay):
case <-ctx.Done():
return nil, ctx.Err()
}
+11 -2
View File
@@ -47,6 +47,7 @@ type JournaledDNSProvider struct {
PropagationTimeout time.Duration
PollingInterval time.Duration
OnWriteObserved func(context.Context, string, string) error
OnPresented func(domainName, fqdn string)
mu sync.Mutex
presented map[string]presentedChallenge
@@ -108,6 +109,9 @@ func (p *JournaledDNSProvider) Present(ctx context.Context, domainName, token, k
recordID: recordID,
}
p.mu.Unlock()
if p.OnPresented != nil {
p.OnPresented(domainName, info.EffectiveFQDN)
}
return nil
}
@@ -122,11 +126,16 @@ func (p *JournaledDNSProvider) CleanUp(ctx context.Context, domainName, token, _
if !ok {
return fmt.Errorf("DNS-01 record for %s is not present in this process", domainName)
}
if err := p.Solver.CleanupDNS01(ctx, presented.auth, presented.zoneID, presented.recordID); err != nil {
// lego calls cleanup with the issuance context, which may already be
// cancelled or expired. Give exact-record cleanup its own bounded window so
// operator cancellation does not strand a live ACME TXT record.
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 45*time.Second)
defer cancel()
if err := p.Solver.CleanupDNS01(cleanupCtx, presented.auth, presented.zoneID, presented.recordID); err != nil {
return fmt.Errorf("delete DNS-01 record %s: %w", presented.recordID, err)
}
cleanedAt := time.Now().UTC()
if err := p.Repository.MarkChallengeCleaned(ctx, presented.journalID, cleanedAt); err != nil {
if err := p.Repository.MarkChallengeCleaned(cleanupCtx, presented.journalID, cleanedAt); err != nil {
return fmt.Errorf("mark DNS-01 challenge %s cleaned: %w", presented.journalID, err)
}
p.mu.Lock()
+88 -13
View File
@@ -18,10 +18,14 @@ import (
"github.com/go-acme/lego/v5/certcrypto"
"github.com/go-acme/lego/v5/certificate"
"github.com/go-acme/lego/v5/challenge"
"github.com/go-acme/lego/v5/challenge/dns01"
"github.com/go-acme/lego/v5/lego"
)
const maxIssuanceConcurrency = 3
const (
maxIssuanceConcurrency = 3
defaultIssuanceTimeout = 10 * time.Minute
)
type EngineRepository interface {
AccountRepository
@@ -49,6 +53,7 @@ type Engine struct {
preflights []PreflightHook
writeObserver func(context.Context, string, string) error
concurrency int
issueTimeout time.Duration
}
type EngineOption func(*Engine)
@@ -83,6 +88,14 @@ func WithIssuanceConcurrency(concurrency int) EngineOption {
}
}
func WithIssuanceTimeout(timeout time.Duration) EngineOption {
return func(engine *Engine) {
if timeout > 0 {
engine.issueTimeout = timeout
}
}
}
func WithACMEHTTPClient(client *http.Client, userAgent string) EngineOption {
return func(engine *Engine) {
engine.accounts.HTTPClient = client
@@ -93,12 +106,13 @@ func WithACMEHTTPClient(client *http.Client, userAgent string) EngineOption {
func NewEngine(repository EngineRepository, secrets SecretStore, solver provider.DNS01Solver, resolve ZoneResolver, options ...EngineOption) *Engine {
engine := &Engine{
accounts: &AccountService{Repository: repository, Secrets: secrets},
repository: repository,
solver: solver,
resolve: resolve,
factory: &legoBackendFactory{},
concurrency: maxIssuanceConcurrency,
accounts: &AccountService{Repository: repository, Secrets: secrets},
repository: repository,
solver: solver,
resolve: resolve,
factory: &legoBackendFactory{},
concurrency: maxIssuanceConcurrency,
issueTimeout: defaultIssuanceTimeout,
}
for _, option := range options {
option(engine)
@@ -109,11 +123,20 @@ func NewEngine(repository EngineRepository, secrets SecretStore, solver provider
func (e *Engine) Accounts() *AccountService { return e.accounts }
type IssueRequest struct {
JobID string `json:"job_id"`
Environment string `json:"environment"`
Plan Plan `json:"plan"`
ConfirmProduction bool `json:"confirm_production"`
ReplacesCertID string `json:"-"`
JobID string `json:"job_id"`
Environment string `json:"environment"`
Plan Plan `json:"plan"`
ConfirmProduction bool `json:"confirm_production"`
ReplacesCertID string `json:"-"`
Progress func(IssueProgress) `json:"-"`
}
type IssueProgress struct {
Stage string
Message string
Domain string
Percent int
WaitingDNS bool
}
type IssueResult struct {
@@ -136,6 +159,14 @@ func (e *Engine) Issue(ctx context.Context, request IssueRequest) (IssueResult,
if request.Environment == EnvironmentProduction && !request.ConfirmProduction {
return IssueResult{}, errors.New("production issuance requires explicit confirmation")
}
timeout := e.issueTimeout
if timeout <= 0 {
timeout = defaultIssuanceTimeout
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
stage := "preflight"
reportIssueProgress(request, IssueProgress{Stage: stage, Message: "Checking zone, credential, DNS, and CAA prerequisites", Percent: 10})
for _, preflight := range e.preflights {
if err := preflight(ctx, request.Plan); err != nil {
return IssueResult{}, fmt.Errorf("certificate preflight: %w", err)
@@ -151,6 +182,15 @@ func (e *Engine) Issue(ctx context.Context, request IssueRequest) (IssueResult,
}
dnsProvider := NewJournaledDNSProvider(e.solver, e.repository, e.resolve, request.JobID)
dnsProvider.OnWriteObserved = e.writeObserver
dnsProvider.OnPresented = func(domainName, fqdn string) {
stage = "dns-propagation"
reportIssueProgress(request, IssueProgress{
Stage: stage, Domain: domainName, Percent: 45, WaitingDNS: true,
Message: fmt.Sprintf("DNS challenge published for %s; waiting for authoritative propagation", fqdn),
})
}
stage = "acme-order"
reportIssueProgress(request, IssueProgress{Stage: stage, Message: "Creating ACME order", Percent: 20})
backend, err := e.factory.New(ctx, account, dnsProvider)
if err != nil {
return IssueResult{}, fmt.Errorf("create ACME backend: %w", err)
@@ -159,6 +199,7 @@ func (e *Engine) Issue(ctx context.Context, request IssueRequest) (IssueResult,
if err != nil {
return IssueResult{}, err
}
stage = "acme-validation"
resource, err := backend.Obtain(ctx, certificate.ObtainRequest{
Domains: slices.Clone(request.Plan.Identifiers),
PrivateKey: privateKey,
@@ -170,8 +211,16 @@ func (e *Engine) Issue(ctx context.Context, request IssueRequest) (IssueResult,
AlwaysDeactivateAuthorizations: true,
})
if err != nil {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return IssueResult{}, fmt.Errorf("ACME order for %s exceeded the %s safety deadline during %s: %w", request.Plan.Name, timeout, stage, ctx.Err())
}
if errors.Is(ctx.Err(), context.Canceled) {
return IssueResult{}, fmt.Errorf("ACME order for %s cancelled during %s: %w", request.Plan.Name, stage, ctx.Err())
}
return IssueResult{}, fmt.Errorf("obtain certificate for %s: %w", request.Plan.Name, err)
}
stage = "certificate-validation"
reportIssueProgress(request, IssueProgress{Stage: stage, Message: "Certificate issued; validating returned key and chain", Percent: 82})
artifact, err := artifactFromResource(resource, privateKey, request.Plan.Identifiers)
if err != nil {
return IssueResult{}, fmt.Errorf("validate ACME result: %w", err)
@@ -192,6 +241,12 @@ func (e *Engine) Issue(ctx context.Context, request IssueRequest) (IssueResult,
}, nil
}
func reportIssueProgress(request IssueRequest, progress IssueProgress) {
if request.Progress != nil {
request.Progress(progress)
}
}
type BatchResult struct {
Request IssueRequest `json:"request"`
Result IssueResult `json:"-"`
@@ -450,7 +505,27 @@ func (f *legoBackendFactory) New(_ context.Context, material AccountMaterial, dn
return nil, err
}
if dnsProvider != nil {
if err := client.Challenge.SetDNS01Provider(dnsProvider); err != nil {
contextAwarePrecheck := dns01.WrapPreCheck(func(ctx context.Context, _ string, fqdn, value string, check dns01.PreCheckFunc) (bool, error) {
if err := ctx.Err(); err != nil {
return true, err
}
checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
ready, err := check(checkCtx, fqdn, value)
if ctxErr := ctx.Err(); ctxErr != nil {
return true, ctxErr
}
return ready, err
})
// Recursive resolvers can retain a negative _acme-challenge response for
// the zone's SOA negative TTL long after Cloudflare is authoritative for
// the new TXT value. Gate on every authoritative nameserver instead; the
// ACME server still performs its own independent validation afterward.
if err := client.Challenge.SetDNS01Provider(
dnsProvider,
dns01.DisableRecursiveNSsPropagationRequirement(),
contextAwarePrecheck,
); err != nil {
return nil, fmt.Errorf("configure DNS-01 provider: %w", err)
}
}