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

+227 -11
View File
@@ -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))
+86
View File
@@ -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{})
+119
View File
@@ -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"
}