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:
15 files changed
+719
-44
No files matched your search
@@ -22,12 +22,13 @@ import (
|
||||
)
|
||||
|
||||
type CertificateService struct {
|
||||
Repository store.Repository
|
||||
Secrets store.SecretStore
|
||||
Engine *certificates.Engine
|
||||
Lifecycle *certificates.Lifecycle
|
||||
ExportRoot string
|
||||
Now func() time.Time
|
||||
Repository store.Repository
|
||||
Secrets store.SecretStore
|
||||
Engine *certificates.Engine
|
||||
Lifecycle *certificates.Lifecycle
|
||||
ExportRoot string
|
||||
Now func() time.Time
|
||||
JobObserver func(domain.Job)
|
||||
}
|
||||
|
||||
type IssueZonesRequest struct {
|
||||
@@ -143,7 +144,7 @@ func (s *CertificateService) IssueZones(ctx context.Context, request IssueZonesR
|
||||
now := s.now().UTC()
|
||||
payload, _ := json.Marshal(map[string]any{"environment": request.Environment, "plan": plan})
|
||||
job := domain.Job{ID: identifier.New("job"), Kind: "certificate.issue", State: domain.JobRunning, ResourceID: zone.ID, Progress: 5, Message: "Preparing ACME order for " + zone.Name, Payload: payload, CreatedAt: now, StartedAt: &now, UpdatedAt: now}
|
||||
if err := s.Repository.SaveJob(ctx, job); err != nil {
|
||||
if err := s.saveJob(ctx, job); err != nil {
|
||||
return IssueZonesResult{}, err
|
||||
}
|
||||
items = append(items, workItem{zone: zone, plan: plan, job: job})
|
||||
@@ -165,13 +166,27 @@ func (s *CertificateService) IssueZones(ctx context.Context, request IssueZonesR
|
||||
issued, issueErr := s.Engine.Issue(groupCtx, certificates.IssueRequest{
|
||||
JobID: item.job.ID, Environment: request.Environment, Plan: item.plan,
|
||||
ConfirmProduction: request.ConfirmProduction,
|
||||
Progress: func(progress certificates.IssueProgress) {
|
||||
job.Progress = progress.Percent
|
||||
job.Message = item.zone.Name + " · " + progress.Message
|
||||
job.UpdatedAt = s.now().UTC()
|
||||
if progress.WaitingDNS {
|
||||
job.State = domain.JobWaitingForDNS
|
||||
} else {
|
||||
job.State = domain.JobRunning
|
||||
}
|
||||
_ = s.saveJob(groupCtx, job)
|
||||
},
|
||||
})
|
||||
finished := s.now().UTC()
|
||||
if issueErr != nil {
|
||||
job.State, job.Progress = domain.JobFailed, 100
|
||||
job.Message, job.Error = "Certificate issuance failed", issueErr.Error()
|
||||
if errors.Is(issueErr, context.Canceled) {
|
||||
job.State, job.Message = domain.JobCancelled, "Certificate issuance cancelled after DNS cleanup"
|
||||
}
|
||||
job.FinishedAt, job.UpdatedAt = &finished, finished
|
||||
_ = s.Repository.SaveJob(context.WithoutCancel(groupCtx), job)
|
||||
_ = s.saveJob(context.WithoutCancel(groupCtx), job)
|
||||
failure := IssueFailure{ZoneID: item.zone.ID, Name: item.zone.Name, Error: issueErr.Error()}
|
||||
outcomes[index] = zoneOutcome{failure: &failure, err: fmt.Errorf("%s: %w", item.zone.Name, issueErr)}
|
||||
return nil
|
||||
@@ -179,6 +194,9 @@ func (s *CertificateService) IssueZones(ctx context.Context, request IssueZonesR
|
||||
|
||||
// Once the CA has issued material, finalization must get a brief chance
|
||||
// to persist it even if the caller cancels the remaining bulk job.
|
||||
job.State, job.Progress = domain.JobRunning, 90
|
||||
job.Message, job.UpdatedAt = "Storing and activating issued certificate", s.now().UTC()
|
||||
_ = s.saveJob(context.WithoutCancel(groupCtx), job)
|
||||
finalizeCtx, cancel := context.WithTimeout(context.WithoutCancel(groupCtx), 2*time.Minute)
|
||||
defer cancel()
|
||||
var previous *domain.CertificateLineage
|
||||
@@ -209,7 +227,7 @@ func (s *CertificateService) IssueZones(ctx context.Context, request IssueZonesR
|
||||
}
|
||||
job.Progress = 100
|
||||
job.FinishedAt, job.UpdatedAt = &finished, finished
|
||||
_ = s.Repository.SaveJob(finalizeCtx, job)
|
||||
_ = s.saveJob(finalizeCtx, job)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -233,6 +251,14 @@ func (s *CertificateService) IssueZones(ctx context.Context, request IssueZonesR
|
||||
return result, errors.Join(failures...)
|
||||
}
|
||||
|
||||
func (s *CertificateService) saveJob(ctx context.Context, job domain.Job) error {
|
||||
err := s.Repository.SaveJob(ctx, job)
|
||||
if s.JobObserver != nil {
|
||||
s.JobObserver(job)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *CertificateService) RenewDue(ctx context.Context, environment string, confirmProduction bool) (IssueZonesResult, error) {
|
||||
if environment == "" {
|
||||
environment = certificates.EnvironmentProduction
|
||||
@@ -299,22 +325,39 @@ func (s *CertificateService) RenewDue(ctx context.Context, environment string, c
|
||||
group.Go(func() error {
|
||||
started := s.now()
|
||||
job := domain.Job{ID: identifier.New("job"), Kind: "certificate.renew", State: domain.JobRunning, ResourceID: item.zone.ID, Progress: 5, Message: "Renewing " + item.lineage.Name, CreatedAt: started, StartedAt: &started, UpdatedAt: started}
|
||||
if saveErr := s.Repository.SaveJob(groupCtx, job); saveErr != nil {
|
||||
if saveErr := s.saveJob(groupCtx, job); saveErr != nil {
|
||||
return saveErr
|
||||
}
|
||||
plan := certificates.Plan{Name: item.lineage.Name, ZoneID: item.zone.ID, ZoneName: item.zone.Name, Identifiers: slices.Clone(item.lineage.Identifiers), KeyAlgorithm: item.lineage.KeyAlgorithm, Profile: item.lineage.Profile}
|
||||
issued, renewErr := s.Engine.Renew(groupCtx, certificates.RenewRequest{IssueRequest: certificates.IssueRequest{JobID: job.ID, Environment: environment, Plan: plan, ConfirmProduction: confirmProduction}, PreviousCertificatePEM: item.certificatePEM})
|
||||
issued, renewErr := s.Engine.Renew(groupCtx, certificates.RenewRequest{IssueRequest: certificates.IssueRequest{
|
||||
JobID: job.ID, Environment: environment, Plan: plan, ConfirmProduction: confirmProduction,
|
||||
Progress: func(progress certificates.IssueProgress) {
|
||||
job.Progress, job.Message, job.UpdatedAt = progress.Percent, item.lineage.Name+" · "+progress.Message, s.now().UTC()
|
||||
if progress.WaitingDNS {
|
||||
job.State = domain.JobWaitingForDNS
|
||||
} else {
|
||||
job.State = domain.JobRunning
|
||||
}
|
||||
_ = s.saveJob(groupCtx, job)
|
||||
},
|
||||
}, PreviousCertificatePEM: item.certificatePEM})
|
||||
finished := s.now()
|
||||
if renewErr != nil {
|
||||
job.State, job.Progress, job.Message, job.Error = domain.JobFailed, 100, "Certificate renewal failed", renewErr.Error()
|
||||
if errors.Is(renewErr, context.Canceled) {
|
||||
job.State, job.Message = domain.JobCancelled, "Certificate renewal cancelled after DNS cleanup"
|
||||
}
|
||||
job.FinishedAt, job.UpdatedAt = &finished, finished
|
||||
_ = s.Repository.SaveJob(context.Background(), job)
|
||||
_ = s.saveJob(context.Background(), job)
|
||||
resultMu.Lock()
|
||||
result.Failed = append(result.Failed, IssueFailure{ZoneID: item.zone.ID, Name: item.lineage.Name, Error: renewErr.Error()})
|
||||
failures = append(failures, fmt.Errorf("%s: %w", item.lineage.Name, renewErr))
|
||||
resultMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
job.State, job.Progress = domain.JobRunning, 90
|
||||
job.Message, job.UpdatedAt = "Storing and activating renewed certificate", s.now().UTC()
|
||||
_ = s.saveJob(context.WithoutCancel(groupCtx), job)
|
||||
finalizeCtx, cancel := context.WithTimeout(context.WithoutCancel(groupCtx), 2*time.Minute)
|
||||
defer cancel()
|
||||
exportRoot := s.managedExportRoot(environment, item.zone.Name)
|
||||
@@ -339,7 +382,7 @@ func (s *CertificateService) RenewDue(ctx context.Context, environment string, c
|
||||
resultMu.Unlock()
|
||||
}
|
||||
job.Progress, job.FinishedAt, job.UpdatedAt = 100, &finished, finished
|
||||
_ = s.Repository.SaveJob(finalizeCtx, job)
|
||||
_ = s.saveJob(finalizeCtx, job)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -173,6 +173,11 @@ func (s *Service) SetHealthCheck(check func(context.Context) error) { s.healthCh
|
||||
func (s *Service) SetUnlockHook(hook func(context.Context) error) { s.unlockHook = hook }
|
||||
func (s *Service) SetCertificateService(service *CertificateService) {
|
||||
s.certificateService = service
|
||||
if service != nil {
|
||||
service.JobObserver = func(job domain.Job) {
|
||||
s.publish(Event{Kind: "certificate.progress", Message: job.Message, Value: job})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) ResolveCredential(ctx context.Context, credentialID string) (provider.Auth, error) {
|
||||
|
||||
@@ -1158,6 +1158,23 @@ func TestDNS01RouterDispatchesExactProviderAndCredential(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateServicePublishesStructuredJobProgress(t *testing.T) {
|
||||
service := New(nil, nil)
|
||||
certificates := &CertificateService{}
|
||||
service.SetCertificateService(certificates)
|
||||
job := domain.Job{ID: "job-1", Kind: "certificate.issue", State: domain.JobWaitingForDNS, Progress: 45, Message: "Waiting for authoritative DNS propagation"}
|
||||
certificates.JobObserver(job)
|
||||
select {
|
||||
case event := <-service.Events():
|
||||
observed, ok := event.Value.(domain.Job)
|
||||
if event.Kind != "certificate.progress" || event.Message != job.Message || !ok || observed.ID != job.ID || observed.State != job.State || observed.Progress != job.Progress {
|
||||
t.Fatalf("certificate event = %#v", event)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("certificate progress event was not published")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionalProviderCapabilitiesFailClearly(t *testing.T) {
|
||||
fake := newFakeCloudProvider()
|
||||
service, _, zone := newBatchTestService(t, fake)
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"time"
|
||||
@@ -16,6 +18,7 @@ import (
|
||||
cloudflareprovider "github.com/MeghdadFadaee/domainops/internal/providers/cloudflare"
|
||||
"github.com/MeghdadFadaee/domainops/internal/secrets"
|
||||
sqlitestore "github.com/MeghdadFadaee/domainops/internal/store/sqlite"
|
||||
legolog "github.com/go-acme/lego/v5/log"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
@@ -35,10 +38,25 @@ type Runtime struct {
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, options Options) (*Runtime, error) {
|
||||
configureACMELogger()
|
||||
paths, err := config.Resolve(options.DataDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Continue with all local resource initialization only after logging is
|
||||
// isolated from stdout; JSON and alternate-screen output must stay clean.
|
||||
return openRuntime(ctx, options, paths)
|
||||
}
|
||||
|
||||
func configureACMELogger() {
|
||||
// lego's default logger writes directly to stdout, which corrupts both the
|
||||
// Bubble Tea alternate screen and JSON CLI envelopes. DomainOps exposes
|
||||
// bounded, structured certificate progress through its own job/event model.
|
||||
legolog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
}
|
||||
|
||||
func openRuntime(ctx context.Context, options Options, paths config.Paths) (*Runtime, error) {
|
||||
if err := paths.Ensure(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
legolog "github.com/go-acme/lego/v5/log"
|
||||
)
|
||||
|
||||
func TestReconcileJobsAfterRecoveryRunsOnlyAfterSuccessfulRecovery(t *testing.T) {
|
||||
@@ -26,3 +30,15 @@ func TestReconcileJobsAfterRecoveryRunsOnlyAfterSuccessfulRecovery(t *testing.T)
|
||||
t.Fatalf("successful recovery result = %v, reconcile called=%v", err, called)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureACMELoggerDoesNotWriteToTerminal(t *testing.T) {
|
||||
original := legolog.Default()
|
||||
defer legolog.SetDefault(original)
|
||||
var output bytes.Buffer
|
||||
legolog.SetDefault(slog.New(slog.NewTextHandler(&output, nil)))
|
||||
configureACMELogger()
|
||||
legolog.Info("dns01: waiting for record propagation.", slog.String("domain", "*.example.com"))
|
||||
if output.Len() != 0 {
|
||||
t.Fatalf("ACME logger escaped to terminal: %q", output.String())
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+227
-11
@@ -174,6 +174,7 @@ type Model struct {
|
||||
certificateIssueZoneValue string
|
||||
certificateLineageID string
|
||||
certificateExpectedName string
|
||||
certificateRun *certificateRunState
|
||||
}
|
||||
|
||||
type loadMsg struct {
|
||||
@@ -198,9 +199,44 @@ type loadMsg struct {
|
||||
}
|
||||
|
||||
type operationMsg struct {
|
||||
message string
|
||||
err error
|
||||
reload bool
|
||||
message string
|
||||
err error
|
||||
reload bool
|
||||
certificate bool
|
||||
}
|
||||
|
||||
type backendEventMsg struct {
|
||||
event app.Event
|
||||
ok bool
|
||||
}
|
||||
|
||||
type certificateTickMsg time.Time
|
||||
|
||||
type certificateActivity struct {
|
||||
At time.Time
|
||||
JobID string
|
||||
State domain.JobState
|
||||
Progress int
|
||||
Message string
|
||||
Error string
|
||||
}
|
||||
|
||||
type certificateRunState struct {
|
||||
Title string
|
||||
StartedAt time.Time
|
||||
Deadline time.Time
|
||||
TargetCount int
|
||||
Jobs map[string]domain.Job
|
||||
Order []string
|
||||
Activity []certificateActivity
|
||||
ActivityScroll int
|
||||
Cancel context.CancelFunc
|
||||
CancelRequested bool
|
||||
Ticking bool
|
||||
Visible bool
|
||||
Done bool
|
||||
Summary string
|
||||
Err error
|
||||
}
|
||||
|
||||
type unlockMsg struct{ err error }
|
||||
@@ -240,14 +276,35 @@ func makePasswordInputs(first bool) []textinput.Model {
|
||||
}
|
||||
|
||||
func (m *Model) Init() tea.Cmd {
|
||||
commands := make([]tea.Cmd, 0, 2)
|
||||
if m.unlock {
|
||||
return textinput.Blink
|
||||
commands = append(commands, textinput.Blink)
|
||||
} else {
|
||||
commands = append(commands, m.startLoad("", false, false))
|
||||
}
|
||||
return m.startLoad("", false, false)
|
||||
if command := waitForBackendEvent(m.backend); command != nil {
|
||||
commands = append(commands, command)
|
||||
}
|
||||
return tea.Batch(commands...)
|
||||
}
|
||||
|
||||
func (m *Model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch msg := message.(type) {
|
||||
case backendEventMsg:
|
||||
if msg.ok {
|
||||
m.applyBackendEvent(msg.event)
|
||||
if m.certificateRun != nil && !m.certificateRun.Done && !m.certificateRun.Ticking {
|
||||
m.certificateRun.Ticking = true
|
||||
return m, tea.Batch(waitForBackendEvent(m.backend), certificateTickCmd())
|
||||
}
|
||||
return m, waitForBackendEvent(m.backend)
|
||||
}
|
||||
return m, nil
|
||||
case certificateTickMsg:
|
||||
if m.certificateRun != nil && !m.certificateRun.Done {
|
||||
return m, certificateTickCmd()
|
||||
}
|
||||
return m, nil
|
||||
case tea.WindowSizeMsg:
|
||||
m.width, m.height = msg.Width, msg.Height
|
||||
m.resizeInputs()
|
||||
@@ -297,6 +354,13 @@ func (m *Model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
case operationMsg:
|
||||
m.err = msg.err
|
||||
m.operationErr = msg.err
|
||||
if msg.certificate && m.certificateRun != nil {
|
||||
m.certificateRun.Done = true
|
||||
m.certificateRun.Visible = true
|
||||
m.certificateRun.Summary = msg.message
|
||||
m.certificateRun.Err = msg.err
|
||||
m.certificateRun.Cancel = nil
|
||||
}
|
||||
if msg.err == nil {
|
||||
m.toast, m.toastAt = msg.message, time.Now()
|
||||
}
|
||||
@@ -344,6 +408,9 @@ func (m *Model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
if m.certificateRun != nil && m.certificateRun.Visible {
|
||||
return m.updateCertificateRun(message)
|
||||
}
|
||||
if key, ok := message.(tea.KeyPressMsg); ok && m.recoveryBlocked && key.String() == "R" {
|
||||
if m.busy || m.loading {
|
||||
message := "An operation is already running"
|
||||
@@ -412,6 +479,15 @@ func (m *Model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
m.toast, m.toastAt = "Load this zone’s TLS snapshot before editing", time.Now()
|
||||
return m, nil
|
||||
}
|
||||
if m.certificateRun != nil && key.String() == "o" {
|
||||
m.certificateRun.Visible = true
|
||||
return m, nil
|
||||
}
|
||||
if m.certificateRun != nil && !m.certificateRun.Done && (key.String() == "q" || key.String() == "ctrl+c") {
|
||||
m.certificateRun.Visible = true
|
||||
m.toast, m.toastAt = "Cancel the certificate operation and wait for DNS cleanup before quitting", time.Now()
|
||||
return m, nil
|
||||
}
|
||||
switch key.String() {
|
||||
case "q", "ctrl+c":
|
||||
return m, tea.Quit
|
||||
@@ -1557,16 +1633,18 @@ func (m *Model) submitCertificateForm() tea.Cmd {
|
||||
ConfirmProduction: m.certificateConfirmProduction,
|
||||
KeyAlgorithm: domain.KeyAlgorithm(strings.ToUpper(inputs[4])),
|
||||
}
|
||||
return func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Hour)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), certificateBatchTimeout(len(zoneIDs)))
|
||||
m.beginCertificateRun("ISSUING WILDCARD CERTIFICATES", len(zoneIDs), ctx, cancel)
|
||||
command := func() tea.Msg {
|
||||
defer cancel()
|
||||
result, issueErr := m.backend.IssueCertificates(ctx, request)
|
||||
message := fmt.Sprintf("Issued %d certificate(s)", len(result.Completed))
|
||||
if warnings := result.WarningCount(); warnings > 0 {
|
||||
message += fmt.Sprintf(" with %d activation warning(s)", warnings)
|
||||
}
|
||||
return operationMsg{message: message, err: issueErr, reload: true}
|
||||
return operationMsg{message: message, err: issueErr, reload: true, certificate: true}
|
||||
}
|
||||
return command
|
||||
case "import":
|
||||
zoneID := ""
|
||||
if inputs[2] != "" {
|
||||
@@ -1618,21 +1696,159 @@ func (m *Model) submitCertificateForm() tea.Cmd {
|
||||
return operationMsg{message: "Certificate revoked", err: revokeErr, reload: true}
|
||||
}
|
||||
case "renew":
|
||||
return func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Hour)
|
||||
targets := max(1, len(m.filteredLineages()))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), certificateBatchTimeout(targets))
|
||||
m.beginCertificateRun("RENEWING DUE CERTIFICATES", targets, ctx, cancel)
|
||||
command := func() tea.Msg {
|
||||
defer cancel()
|
||||
result, renewErr := m.backend.RenewCertificates(ctx, strings.ToLower(inputs[0]), m.certificateConfirmProduction)
|
||||
message := fmt.Sprintf("Renewed %d certificate(s)", len(result.Completed))
|
||||
if warnings := result.WarningCount(); warnings > 0 {
|
||||
message += fmt.Sprintf(" with %d activation warning(s)", warnings)
|
||||
}
|
||||
return operationMsg{message: message, err: renewErr, reload: true}
|
||||
return operationMsg{message: message, err: renewErr, reload: true, certificate: true}
|
||||
}
|
||||
return command
|
||||
}
|
||||
m.busy = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func waitForBackendEvent(backend Backend) tea.Cmd {
|
||||
source, ok := backend.(interface{ Events() <-chan app.Event })
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
events := source.Events()
|
||||
if events == nil {
|
||||
return nil
|
||||
}
|
||||
return func() tea.Msg {
|
||||
event, open := <-events
|
||||
return backendEventMsg{event: event, ok: open}
|
||||
}
|
||||
}
|
||||
|
||||
func certificateTickCmd() tea.Cmd {
|
||||
return tea.Tick(time.Second, func(at time.Time) tea.Msg { return certificateTickMsg(at) })
|
||||
}
|
||||
|
||||
func certificateBatchTimeout(targets int) time.Duration {
|
||||
if targets < 1 {
|
||||
targets = 1
|
||||
}
|
||||
waves := (targets + 2) / 3
|
||||
timeout := time.Duration(waves)*11*time.Minute + 2*time.Minute
|
||||
if timeout > 4*time.Hour {
|
||||
return 4 * time.Hour
|
||||
}
|
||||
return timeout
|
||||
}
|
||||
|
||||
func (m *Model) beginCertificateRun(title string, targets int, ctx context.Context, cancel context.CancelFunc) {
|
||||
deadline, _ := ctx.Deadline()
|
||||
m.certificateRun = &certificateRunState{
|
||||
Title: title, StartedAt: time.Now(), Deadline: deadline, TargetCount: max(1, targets),
|
||||
Jobs: make(map[string]domain.Job), Cancel: cancel, Visible: true,
|
||||
}
|
||||
m.certificateRun.Activity = append(m.certificateRun.Activity, certificateActivity{
|
||||
At: time.Now(), State: domain.JobQueued,
|
||||
Message: fmt.Sprintf("Queued %d certificate order(s); up to 3 run concurrently", m.certificateRun.TargetCount),
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Model) applyBackendEvent(event app.Event) {
|
||||
if event.Kind != "certificate.progress" || m.certificateRun == nil {
|
||||
return
|
||||
}
|
||||
job, ok := event.Value.(domain.Job)
|
||||
if !ok {
|
||||
if pointer, pointerOK := event.Value.(*domain.Job); pointerOK && pointer != nil {
|
||||
job, ok = *pointer, true
|
||||
}
|
||||
}
|
||||
if !ok || job.ID == "" {
|
||||
return
|
||||
}
|
||||
previous, existed := m.certificateRun.Jobs[job.ID]
|
||||
m.certificateRun.Jobs[job.ID] = job
|
||||
if !existed {
|
||||
m.certificateRun.Order = append(m.certificateRun.Order, job.ID)
|
||||
}
|
||||
if existed && previous.State == job.State && previous.Progress == job.Progress && previous.Message == job.Message && previous.Error == job.Error {
|
||||
return
|
||||
}
|
||||
at := job.UpdatedAt
|
||||
if at.IsZero() {
|
||||
at = time.Now()
|
||||
}
|
||||
m.certificateRun.Activity = append(m.certificateRun.Activity, certificateActivity{
|
||||
At: at, JobID: job.ID, State: job.State, Progress: job.Progress, Message: job.Message, Error: job.Error,
|
||||
})
|
||||
if m.certificateRun.ActivityScroll > 0 {
|
||||
m.certificateRun.ActivityScroll++
|
||||
}
|
||||
if len(m.certificateRun.Activity) > 500 {
|
||||
dropped := len(m.certificateRun.Activity) - 500
|
||||
m.certificateRun.Activity = append([]certificateActivity(nil), m.certificateRun.Activity[dropped:]...)
|
||||
m.certificateRun.ActivityScroll = max(0, m.certificateRun.ActivityScroll-dropped)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) updateCertificateRun(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
key, ok := message.(tea.KeyPressMsg)
|
||||
if !ok {
|
||||
return m, nil
|
||||
}
|
||||
window := certificateActivityWindow(m.height)
|
||||
maxScroll := max(0, len(m.certificateRun.Activity)-window)
|
||||
switch key.String() {
|
||||
case "up", "k":
|
||||
m.certificateRun.ActivityScroll = min(maxScroll, m.certificateRun.ActivityScroll+1)
|
||||
return m, nil
|
||||
case "down", "j":
|
||||
m.certificateRun.ActivityScroll = max(0, m.certificateRun.ActivityScroll-1)
|
||||
return m, nil
|
||||
case "pgup":
|
||||
m.certificateRun.ActivityScroll = min(maxScroll, m.certificateRun.ActivityScroll+window)
|
||||
return m, nil
|
||||
case "pgdown":
|
||||
m.certificateRun.ActivityScroll = max(0, m.certificateRun.ActivityScroll-window)
|
||||
return m, nil
|
||||
case "home":
|
||||
m.certificateRun.ActivityScroll = maxScroll
|
||||
return m, nil
|
||||
case "end":
|
||||
m.certificateRun.ActivityScroll = 0
|
||||
return m, nil
|
||||
case "b":
|
||||
m.certificateRun.Visible = false
|
||||
return m, nil
|
||||
}
|
||||
if m.certificateRun.Done {
|
||||
if key.String() == "enter" || key.String() == "esc" {
|
||||
m.certificateRun = nil
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
if key.String() == "c" || key.String() == "esc" || key.String() == "ctrl+c" {
|
||||
if !m.certificateRun.CancelRequested {
|
||||
m.certificateRun.CancelRequested = true
|
||||
m.certificateRun.Activity = append(m.certificateRun.Activity, certificateActivity{
|
||||
At: time.Now(), State: domain.JobCancelled, Message: "Cancellation requested; safely cleaning DNS challenges",
|
||||
})
|
||||
if m.certificateRun.Cancel != nil {
|
||||
m.certificateRun.Cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func certificateActivityWindow(height int) int {
|
||||
return max(2, min(7, height-14))
|
||||
}
|
||||
|
||||
func (m *Model) resolveZoneValues(values []string) ([]string, error) {
|
||||
byID := make(map[string]string, len(m.zones))
|
||||
byName := make(map[string][]string, len(m.zones))
|
||||
|
||||
@@ -908,6 +908,92 @@ func TestPreferredCredentialFormFitsMinimumTerminalAndShowsRoutingIdentity(t *te
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateRunRendersBoundedProgressAndCancelsSafely(t *testing.T) {
|
||||
model := New(&fakeBackend{}, Options{})
|
||||
_, _ = model.Update(tea.WindowSizeMsg{Width: 64, Height: 18})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
model.beginCertificateRun("ISSUING WILDCARD CERTIFICATES", 2, ctx, cancel)
|
||||
now := time.Now().UTC()
|
||||
model.applyBackendEvent(app.Event{Kind: "certificate.progress", Value: domain.Job{
|
||||
ID: "job-1", Kind: "certificate.issue", State: domain.JobWaitingForDNS,
|
||||
Progress: 45, Message: "DNS challenge published for _acme-challenge.example.com.; waiting for authoritative propagation", UpdatedAt: now,
|
||||
}})
|
||||
view := model.View().Content
|
||||
if height := lipgloss.Height(view); height > 18 {
|
||||
t.Fatalf("certificate progress height = %d\n%s", height, view)
|
||||
}
|
||||
for _, expected := range []string{"ISSUING WILDCARD CERTIFICATES", "DNS", "DNS challenge published", "45%", "cancel safely"} {
|
||||
if !strings.Contains(view, expected) {
|
||||
t.Fatalf("certificate progress does not show %q: %q", expected, view)
|
||||
}
|
||||
}
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'b', Text: "b"})
|
||||
if model.certificateRun.Visible || !strings.Contains(model.View().Content, "progress") {
|
||||
t.Fatalf("backgrounded certificate run = visible:%v view:%q", model.certificateRun.Visible, model.View().Content)
|
||||
}
|
||||
_, quit := model.Update(tea.KeyPressMsg{Code: 'q', Text: "q"})
|
||||
if quit != nil || !model.certificateRun.Visible || !strings.Contains(model.toast, "DNS cleanup") {
|
||||
t.Fatalf("active certificate quit guard = cmd:%v visible:%v toast:%q", quit != nil, model.certificateRun.Visible, model.toast)
|
||||
}
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'b', Text: "b"})
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'o', Text: "o"})
|
||||
if !model.certificateRun.Visible {
|
||||
t.Fatal("certificate progress shortcut did not reopen the console")
|
||||
}
|
||||
|
||||
_, command := model.Update(tea.KeyPressMsg{Code: 'c', Text: "c"})
|
||||
if command != nil || !model.certificateRun.CancelRequested {
|
||||
t.Fatalf("cancel state = command:%v requested:%v", command != nil, model.certificateRun.CancelRequested)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
default:
|
||||
t.Fatal("certificate run context was not cancelled")
|
||||
}
|
||||
if view := model.View().Content; !strings.Contains(view, "CANCELLING SAFELY") || !strings.Contains(view, "cleanup to finish") {
|
||||
t.Fatalf("cancelling progress view = %q", view)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateRunCompletionKeepsSummaryUntilDismissed(t *testing.T) {
|
||||
model := New(&fakeBackend{}, Options{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
model.beginCertificateRun("ISSUING WILDCARD CERTIFICATES", 1, ctx, cancel)
|
||||
_, _ = model.Update(operationMsg{message: "Issued 0 certificate(s)", err: errors.New("propagation deadline exceeded"), certificate: true})
|
||||
if model.certificateRun == nil || !model.certificateRun.Done || !strings.Contains(model.View().Content, "propagation deadline exceeded") {
|
||||
t.Fatalf("completion summary = %#v", model.certificateRun)
|
||||
}
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if model.certificateRun != nil {
|
||||
t.Fatal("completed certificate summary was not dismissed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateRunActivityCanScrollWithoutLosingTail(t *testing.T) {
|
||||
model := New(&fakeBackend{}, Options{})
|
||||
_, _ = model.Update(tea.WindowSizeMsg{Width: 76, Height: 18})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
model.beginCertificateRun("ISSUING WILDCARD CERTIFICATES", 1, ctx, cancel)
|
||||
for index := range 10 {
|
||||
model.applyBackendEvent(app.Event{Kind: "certificate.progress", Value: domain.Job{
|
||||
ID: "job", State: domain.JobRunning, Progress: index + 1,
|
||||
Message: fmt.Sprintf("stage-%02d", index), UpdatedAt: time.Now().Add(time.Duration(index) * time.Second),
|
||||
}})
|
||||
}
|
||||
if view := model.View().Content; !strings.Contains(view, "stage-09") {
|
||||
t.Fatalf("activity did not follow newest event: %q", view)
|
||||
}
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: tea.KeyHome})
|
||||
if view := model.View().Content; !strings.Contains(view, "stage-00") || strings.Contains(view, "stage-09") {
|
||||
t.Fatalf("activity home did not show oldest events: %q", view)
|
||||
}
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: tea.KeyEnd})
|
||||
if view := model.View().Content; !strings.Contains(view, "stage-09") {
|
||||
t.Fatalf("activity end did not return to live tail: %q", view)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreferredCredentialCancellationAndStaleRouteAreSafe(t *testing.T) {
|
||||
backend := &fakeBackend{}
|
||||
model := New(backend, Options{})
|
||||
|
||||
@@ -35,6 +35,9 @@ func (m *Model) render() string {
|
||||
if m.preferCredential {
|
||||
return m.renderPreferredCredentialForm()
|
||||
}
|
||||
if m.certificateRun != nil && m.certificateRun.Visible {
|
||||
return m.renderCertificateRun()
|
||||
}
|
||||
if m.editRecord {
|
||||
return m.renderRecordForm()
|
||||
}
|
||||
@@ -71,6 +74,114 @@ func (m *Model) render() string {
|
||||
return m.theme.app.Width(m.width).Height(m.height).Render(header + "\n" + body + "\n" + foot)
|
||||
}
|
||||
|
||||
func (m *Model) renderCertificateRun() string {
|
||||
run := m.certificateRun
|
||||
contentWidth := max(36, min(86, m.width-14))
|
||||
progress, succeeded, failed, waiting, running := certificateRunSummary(run)
|
||||
state := m.theme.statusWarn.Render("◌ WORKING")
|
||||
if run.CancelRequested && !run.Done {
|
||||
state = m.theme.statusWarn.Render("◌ CANCELLING SAFELY")
|
||||
}
|
||||
if run.Done && run.Err == nil {
|
||||
state = m.theme.statusOK.Render("● COMPLETE")
|
||||
}
|
||||
if run.Done && run.Err != nil {
|
||||
state = m.theme.statusBad.Render("● FINISHED WITH ERRORS")
|
||||
}
|
||||
elapsed := time.Since(run.StartedAt).Round(time.Second)
|
||||
remaining := time.Until(run.Deadline).Round(time.Second)
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
lines := []string{
|
||||
m.theme.brand.Render(run.Title),
|
||||
state + m.theme.mutedText.Render(fmt.Sprintf(" %d/%d done · %d DNS · %d failed · %d active", succeeded, run.TargetCount, waiting, failed, running)),
|
||||
renderProgressBar(m.theme, contentWidth, progress),
|
||||
m.theme.mutedText.Render(certificateRunTiming(elapsed, remaining, run.Deadline)),
|
||||
}
|
||||
maxEntries := certificateActivityWindow(m.height)
|
||||
end := max(0, len(run.Activity)-run.ActivityScroll)
|
||||
start := max(0, end-maxEntries)
|
||||
position := "empty"
|
||||
if end > 0 {
|
||||
position = fmt.Sprintf("%d–%d / %d", start+1, end, len(run.Activity))
|
||||
}
|
||||
lines = append(lines, m.theme.panelTitle.Render("ACTIVITY · "+position+" · ↑/↓ scroll"))
|
||||
for _, activity := range run.Activity[start:end] {
|
||||
icon := "◌"
|
||||
style := m.theme.mutedText
|
||||
switch activity.State {
|
||||
case domain.JobSucceeded:
|
||||
icon, style = "✓", m.theme.statusOK
|
||||
case domain.JobFailed:
|
||||
icon, style = "!", m.theme.statusBad
|
||||
case domain.JobCancelled:
|
||||
icon, style = "×", m.theme.statusWarn
|
||||
case domain.JobWaitingForDNS:
|
||||
icon, style = "↻", m.theme.statusWarn
|
||||
}
|
||||
message := activity.Message
|
||||
if activity.Error != "" {
|
||||
message += " · " + activity.Error
|
||||
}
|
||||
line := fmt.Sprintf("%s %s %3d%% %s", activity.At.Format("15:04:05"), icon, activity.Progress, message)
|
||||
lines = append(lines, style.Render(truncate(line, contentWidth)))
|
||||
}
|
||||
if run.Done {
|
||||
summary := run.Summary
|
||||
if run.Err != nil {
|
||||
summary += " · " + run.Err.Error()
|
||||
}
|
||||
lines = append(lines, m.theme.mutedText.Render(truncate(summary, contentWidth)), m.theme.mutedText.Render("Enter / Esc close"))
|
||||
} else if run.CancelRequested {
|
||||
lines = append(lines, m.theme.mutedText.Render("Waiting for ACME/DNS cleanup to finish…"))
|
||||
} else {
|
||||
lines = append(lines, m.theme.mutedText.Render("↑/↓ scroll · b background · c/Esc cancel safely"))
|
||||
}
|
||||
modal := m.theme.modal.Width(min(92, m.width-8)).Render(strings.Join(lines, "\n"))
|
||||
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
|
||||
}
|
||||
|
||||
func certificateRunTiming(elapsed, remaining time.Duration, deadline time.Time) string {
|
||||
if deadline.IsZero() {
|
||||
return fmt.Sprintf("Elapsed %s · bounded by the operation context", elapsed)
|
||||
}
|
||||
return fmt.Sprintf("Elapsed %s · safety deadline in %s", elapsed, remaining)
|
||||
}
|
||||
|
||||
func certificateRunSummary(run *certificateRunState) (progress, succeeded, failed, waiting, running int) {
|
||||
if run == nil || run.TargetCount < 1 {
|
||||
return 0, 0, 0, 0, 0
|
||||
}
|
||||
total := 0
|
||||
for _, job := range run.Jobs {
|
||||
total += max(0, min(100, job.Progress))
|
||||
switch job.State {
|
||||
case domain.JobSucceeded:
|
||||
succeeded++
|
||||
case domain.JobFailed, domain.JobCancelled:
|
||||
failed++
|
||||
case domain.JobWaitingForDNS:
|
||||
waiting++
|
||||
case domain.JobRunning, domain.JobQueued:
|
||||
running++
|
||||
}
|
||||
}
|
||||
progress = min(100, total/run.TargetCount)
|
||||
if run.Done && run.Err == nil {
|
||||
progress = 100
|
||||
}
|
||||
return progress, succeeded, failed, waiting, running
|
||||
}
|
||||
|
||||
func renderProgressBar(theme theme, width, progress int) string {
|
||||
barWidth := max(10, width-2)
|
||||
filled := barWidth * max(0, min(100, progress)) / 100
|
||||
done := lipgloss.NewStyle().Background(theme.primary).Render(strings.Repeat(" ", filled))
|
||||
pending := lipgloss.NewStyle().Background(theme.surface2).Render(strings.Repeat(" ", barWidth-filled))
|
||||
return "[" + done + pending + "]"
|
||||
}
|
||||
|
||||
func (m *Model) renderHeader() string {
|
||||
brand := m.theme.brand.Render("◆ DOMAINOPS")
|
||||
section := m.theme.mutedText.Render(" / " + screens[m.screen].name)
|
||||
@@ -99,6 +210,14 @@ func (m *Model) renderFooter() string {
|
||||
case screenZones:
|
||||
right = m.theme.key.Render("p") + " set route " + m.theme.key.Render("Enter") + " DNS " + m.theme.key.Render("q") + " quit"
|
||||
}
|
||||
if m.certificateRun != nil && !m.certificateRun.Visible {
|
||||
if m.width < 88 {
|
||||
left = m.theme.key.Render("?") + " help"
|
||||
right = m.theme.key.Render("o") + " progress"
|
||||
} else {
|
||||
right = m.theme.key.Render("o") + " progress " + right
|
||||
}
|
||||
}
|
||||
if m.recoveryBlocked {
|
||||
right = m.theme.key.Render("R") + " retry recovery " + m.theme.key.Render("q") + " quit"
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user