hub (unreleased): R-922 option A — a household's clear deletes its notification address (email_cleared); MAIL-HOLD — a restored hub sends no mail until released; two log lines drop the address; runbooks: mail hold is restore step 1; 07 §6.4 R-921 pre-check; R-921/R-922 narrowed
gates / gates (push) Successful in 5m25s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-09 12:37:29 +02:00
1 parent 2c48feb325
commit d55c590c5a
35 files changed
+861 -23

No files matched your search

+79 -10
View File
@@ -3,6 +3,7 @@ package notify
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
@@ -11,6 +12,7 @@ import (
"sync"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/mailhold"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
"gitea.dooplex.hu/admin/felhom-hub/internal/i18n"
@@ -40,8 +42,32 @@ type Dispatcher struct {
// afterFn schedules a delayed call (time.AfterFunc; a seam so tests run the retries at once). Used by
// retryOperatorEmail (the lost alarm of 2026-10-05).
afterFn func(time.Duration, func())
// mailHold is the hub-wide mail gate (internal/mailhold): while its marker exists, deliver() hands nothing to
// sendEmailFn. nil never holds.
mailHold *mailhold.Hold
}
// SetMailHold wires the hub-wide mail gate (the MAIL-HOLD marker in the data dir).
func (d *Dispatcher) SetMailHold(m *mailhold.Hold) {
d.mailHold = m
}
// deliver is the ONE way the dispatcher sends a mail: the MAIL-HOLD gate, then sendEmailFn. Every send in this file
// goes through it, so the hold cannot be bypassed by a path someone adds later without calling sendEmailFn directly
// (pinned by TestMailHold_EverySendPathIsGated). kind names the mail; who is a customer ID or "operator" — the hold's
// log line carries those two and never the address. A held mail returns mailhold.ErrHeld and is DROPPED, never
// queued: see the package comment for why.
func (d *Dispatcher) deliver(kind, who, to, subject, body string, headers map[string]string) error {
if err := d.mailHold.Check(kind, who); err != nil {
return err
}
return d.sendEmailFn(to, subject, body, headers)
}
// isHeld reports whether a send error is the mail hold (not a delivery failure).
func isHeld(err error) bool { return errors.Is(err, mailhold.ErrHeld) }
// operatorRetryDelays are the waits before each further try of an operator mail whose send FAILED (the lost alarm of 2026-10-05). Measured
// 2026-10-05: demo-hp's whole_guest_backup_failed (error) hit a 10 s Resend client timeout, was logged `failed`, and was
// never sent — the only operator mail of 692 that failed, and the one alarm the operator needed that night. The
@@ -77,7 +103,12 @@ func (d *Dispatcher) retryOperatorEmail(customerID, eventType, severity, message
}
d.afterFn(operatorRetryDelays[attempt], func() {
n := attempt + 1
if err := d.sendEmailFn(d.operatorEmail, subject, body, headers); err != nil {
if err := d.deliver("operator mail "+eventType+" (retry)", "operator", d.operatorEmail, subject, body, headers); err != nil {
if isHeld(err) {
// The hold began between tries: the mail is dropped like every other held mail, and the retries stop.
d.store.LogNotification(customerID, eventType, severity, message, "held", "MAIL-HOLD marker present — dropped", "operator")
return
}
d.logger.Printf("[ERROR] Operator email retry %d failed for %s/%s: %v", n, customerID, eventType, err)
d.store.LogNotification(customerID, eventType, severity, message, "failed", fmt.Sprintf("retry %d: %v", n, err), "operator")
d.retryOperatorEmail(customerID, eventType, severity, message, subject, body, headers, n)
@@ -246,7 +277,9 @@ func (d *Dispatcher) sendTestEmail(customerID string) {
subject := b.Msg(lang, "mail.test.subject")
body := b.Msg(lang, "mail.test.body")
if err := d.sendEmailFn(prefs.Email, subject, body, nil); err != nil {
if err := d.deliver("test mail", customerID, prefs.Email, subject, body, nil); isHeld(err) {
d.store.LogNotification(customerID, "test", "info", "Teszt értesítés", "held", "MAIL-HOLD marker present — dropped", "customer")
} else if err != nil {
d.logger.Printf("[ERROR] Test email to %s failed: %v", prefs.Email, err)
d.store.LogNotification(customerID, "test", "info", "Teszt értesítés", "failed", err.Error(), "customer")
} else {
@@ -268,7 +301,10 @@ headers render correctly. The customer test mail result is recorded in the
notification log.
Dashboard: https://hub.felhom.eu/customers/%s`, customerID, customerID)
if err := d.sendEmailFn(d.operatorEmail, opSubject, opBody, priorityHeaders("critical")); err != nil {
if err := d.deliver("operator test mail", "operator", d.operatorEmail, opSubject, opBody, priorityHeaders("critical")); isHeld(err) {
d.store.LogNotification(customerID, "test", "info", "operator test copy", "held", "MAIL-HOLD marker present — dropped", "operator")
return
} else if err != nil {
d.logger.Printf("[ERROR] Operator test email failed for %s: %v", customerID, err)
d.store.LogNotification(customerID, "test", "info", "operator test copy", "failed", err.Error(), "operator")
return
@@ -330,7 +366,11 @@ func (d *Dispatcher) processRecovery(customerID, eventType, severity, message, m
subject, body := FormatCustomerEmail(d.store.CustomerLanguage(customerID),
customerID, eventType, severity, message, messageCustomer, detailsJSON)
if err := d.sendEmailFn(prefs.Email, subject, body, priorityHeaders(severity)); err != nil {
if err := d.deliver("customer recovery mail "+eventType, customerID, prefs.Email, subject, body, priorityHeaders(severity)); isHeld(err) {
d.forgetCustomerCooldown(cooldownKey)
d.store.LogNotification(customerID, eventType, severity, message, "held", "MAIL-HOLD marker present — dropped", "customer")
return
} else if err != nil {
d.logger.Printf("[ERROR] Customer recovery email failed for %s/%s: %v", customerID, eventType, err)
d.store.LogNotification(customerID, eventType, severity, message, "failed", err.Error(), "customer")
return
@@ -607,7 +647,15 @@ func (d *Dispatcher) processOperator(customerID, eventType, severity, message, d
subject, body := FormatOperatorEmail(customerID, eventType, severity, message, detailsJSON)
hdrs := priorityHeaders(severity)
if err := d.sendEmailFn(d.operatorEmail, subject, body, hdrs); err != nil {
if err := d.deliver("operator mail "+eventType, "operator", d.operatorEmail, subject, body, hdrs); isHeld(err) {
// Dropped, and the cooldown it armed is given back: the first real alarm after the release must not be
// silenced by a mail that was never sent.
d.mu.Lock()
delete(d.opCooldowns, cooldownKey)
d.mu.Unlock()
d.store.LogNotification(customerID, eventType, severity, message, "held", "MAIL-HOLD marker present — dropped", "operator")
return
} else if err != nil {
d.logger.Printf("[ERROR] Operator email failed for %s/%s: %v — retrying in %v", customerID, eventType, err, operatorRetryDelays[0])
d.store.LogNotification(customerID, eventType, severity, message, "failed", err.Error(), "operator")
d.retryOperatorEmail(customerID, eventType, severity, message, subject, body, hdrs, 0)
@@ -883,12 +931,16 @@ func (d *Dispatcher) processCustomer(customerID, eventType, severity, message, m
subject, body := FormatCustomerEmail(d.store.CustomerLanguage(customerID),
customerID, eventType, severity, message, messageCustomer, detailsJSON)
if err := d.sendEmailFn(prefs.Email, subject, body, priorityHeaders(severity)); err != nil {
if err := d.deliver("customer mail "+eventType, customerID, prefs.Email, subject, body, priorityHeaders(severity)); isHeld(err) {
d.forgetCustomerCooldown(cooldownKey)
d.store.LogNotification(customerID, eventType, severity, message, "held", "MAIL-HOLD marker present — dropped", "customer")
return
} else if err != nil {
d.logger.Printf("[ERROR] Customer email failed for %s/%s: %v", customerID, eventType, err)
d.store.LogNotification(customerID, eventType, severity, message, "failed", err.Error(), "customer")
return
}
d.logger.Printf("[INFO] Customer email sent to %s for %s/%s", prefs.Email, customerID, eventType)
d.logger.Printf("[INFO] Customer email sent for %s/%s", customerID, eventType) // never the address (R-922)
d.store.LogNotification(customerID, eventType, severity, message, "sent", "", "customer")
}
@@ -944,6 +996,13 @@ func (d *Dispatcher) replyToFor(to string) string {
return op
}
// forgetCustomerCooldown gives back a customer cooldown armed for a mail the hold dropped.
func (d *Dispatcher) forgetCustomerCooldown(key string) {
d.mu.Lock()
delete(d.custCooldowns, key)
d.mu.Unlock()
}
func isEventEnabled(enabledEvents []string, eventType string) bool {
for _, e := range enabledEvents {
if e == eventType {
@@ -964,7 +1023,10 @@ func (d *Dispatcher) SendClaimEmail(kind, customerID, email, domain, code string
}
subject, body := FormatClaimEmail(d.store.CustomerLanguage(customerID), kind, customerID, domain, code)
eventType := "claim_" + kind
if err := d.sendEmailFn(email, subject, body, nil); err != nil {
if err := d.deliver("claim "+kind+" mail", customerID, email, subject, body, nil); isHeld(err) {
d.store.LogNotification(customerID, eventType, "info", subject, "held", "MAIL-HOLD marker present — dropped", "customer")
return err
} else if err != nil {
d.logger.Printf("[ERROR] claim %s email to customer %s failed: %v", kind, customerID, err)
d.store.LogNotification(customerID, eventType, "info", subject, "failed", err.Error(), "customer")
return err
@@ -985,7 +1047,10 @@ func (d *Dispatcher) SendSelfBindEmail(customerID, email, link string) error {
return fmt.Errorf("notify: no resend api key")
}
subject, body := FormatSelfBindEmail(d.store.CustomerLanguage(customerID), customerID, link)
if err := d.sendEmailFn(email, subject, body, nil); err != nil {
if err := d.deliver("self-bind link mail", customerID, email, subject, body, nil); isHeld(err) {
d.store.LogNotification(customerID, "selfbind_link", "info", subject, "held", "MAIL-HOLD marker present — dropped", "customer")
return err
} else if err != nil {
d.logger.Printf("[ERROR] self-bind link email to customer %s failed: %v", customerID, err)
d.store.LogNotification(customerID, "selfbind_link", "info", subject, "failed", err.Error(), "customer")
return err
@@ -1018,7 +1083,11 @@ func (d *Dispatcher) SendKernelNotice(customerID, kver string) (string, error) {
}
lang := d.store.CustomerLanguage(customerID)
subject, body := FormatKernelNoticeEmail(lang)
if err := d.sendEmailFn(to, subject, body, nil); err != nil {
if err := d.deliver("kernel notice", customerID, to, subject, body, nil); isHeld(err) {
// The caller runs no kernel step on an error (no mail, no step) — exactly right for a held hub.
d.store.LogNotification(customerID, "kernel_notice", "info", subject, "held", "MAIL-HOLD marker present — dropped", "customer")
return lang, err
} else if err != nil {
d.logger.Printf("[ERROR] kernel notice (%s) to customer %s failed: %v", kver, customerID, err)
d.store.LogNotification(customerID, "kernel_notice", "info", subject, "failed", err.Error(), "customer")
return lang, err
+143
View File
@@ -0,0 +1,143 @@
package notify
import (
"bytes"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/mailhold"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// MAIL-HOLD — a restored hub starts quiet. Evidence: the 2026-10-09 restore drill
// (documentation/audits/dooplex-survival-2026-10-09/partD-05-checks.txt): a hub started on a restored database mailed
// households pending kernel notices within a minute, and `notifications.operator_enabled: false` did not stop it.
//
// COMPANION RED-PROOF (REPORT): make deliver() skip the mailHold.Check call (the pre-fix shape: sendEmailFn is reached
// directly) → TestMailHold_DispatcherSendsNothingWhileHeld fails with every path's mail SENT.
type holdRecorder struct {
mu sync.Mutex
sent []string // subjects
}
func (r *holdRecorder) fn(to, subject, body string, headers map[string]string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.sent = append(r.sent, subject)
return nil
}
func (r *holdRecorder) count() int {
r.mu.Lock()
defer r.mu.Unlock()
return len(r.sent)
}
// holdDispatcher returns a dispatcher whose household c1 has a registered address, notification prefs with
// backup_failed on, the operator channel ON, the MAIL-HOLD marker present, and a log captured in buf.
func holdDispatcher(t *testing.T) (*Dispatcher, *store.Store, *holdRecorder, *mailhold.Hold, *bytes.Buffer) {
t.Helper()
st := newDispStore(t)
if err := st.SaveCustomerConfig(&store.CustomerConfig{CustomerID: "c1", APIKey: "k", RetrievalPassword: "p", Email: "household@example.hu"}); err != nil {
t.Fatal(err)
}
if err := st.SaveNotificationPrefs("c1", "household@example.hu", []string{"backup_failed"}, 6); err != nil {
t.Fatal(err)
}
buf := &bytes.Buffer{}
logger := log.New(buf, "", 0)
d := NewDispatcher(st, "test-key", "from@felhom.eu", "op@felhom.eu", true, logger)
rec := &holdRecorder{}
d.sendEmailFn = rec.fn
d.afterFn = func(time.Duration, func()) {} // a retry must never fire in these tests
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, mailhold.FileName), nil, 0o644); err != nil {
t.Fatal(err)
}
hold := mailhold.New(dir, logger)
d.SetMailHold(hold)
return d, st, rec, hold, buf
}
// The consequence asserted: with the marker present, NOT ONE mail reaches the sender, on any dispatcher path —
// household event, operator event, recovery, test mail, kernel notice, claim code, self-bind link.
func TestMailHold_DispatcherSendsNothingWhileHeld(t *testing.T) {
d, st, rec, _, buf := holdDispatcher(t)
d.ProcessEvent("c1", "backup_failed", "error", "Backup failed", "", "box") // operator + household
d.ProcessEvent("c1", "test", "info", "test", "", "operator") // test mail, both channels
if _, err := d.SendKernelNotice("c1", "6.8.12-1"); err == nil {
t.Errorf("kernel notice: a held mail must report an error (the caller then runs no kernel step)")
}
if err := d.SendClaimEmail("claim", "c1", "household@example.hu", "c1.example", "CODE-1234"); err == nil {
t.Errorf("claim mail: a held mail must report an error")
}
if err := d.SendSelfBindEmail("c1", "household@example.hu", "https://hub.example/bind/x"); err == nil {
t.Errorf("self-bind mail: a held mail must report an error")
}
if n := rec.count(); n != 0 {
t.Fatalf("MAIL-HOLD present but %d mail(s) were SENT: %v", n, rec.sent)
}
out := buf.String()
if got := strings.Count(out, "[WARN] MAIL-HOLD: not sending"); got < 7 {
t.Errorf("each held mail is logged once: want >= 7 MAIL-HOLD lines, got %d\n%s", got, out)
}
if strings.Contains(out, "household@example.hu") || strings.Contains(out, "op@felhom.eu") {
t.Errorf("the hold's log must carry no address:\n%s", out)
}
if strings.Contains(out, "CODE-1234") {
t.Errorf("the hold's log must carry no mail body")
}
// The record says what happened: held, not sent and not failed.
if _, ok, _ := st.LastCustomerSentAt("c1", []string{"backup_failed"}); ok {
t.Errorf("a held household mail was recorded as SENT")
}
}
// After the release the hub mails again — and the very same event key mails at once: the cooldown a held mail armed is
// given back, so the first real alarm after the release is not silenced by a mail that was never sent.
func TestMailHold_ReleaseResumesSends(t *testing.T) {
d, _, rec, hold, _ := holdDispatcher(t)
d.ProcessEvent("c1", "backup_failed", "error", "Backup failed", "", "box")
if rec.count() != 0 {
t.Fatalf("held: %d mail(s) sent", rec.count())
}
if err := hold.Release(); err != nil {
t.Fatalf("release: %v", err)
}
if hold.Held() {
t.Fatalf("the marker is still there after Release")
}
d.ProcessEvent("c1", "backup_failed", "error", "Backup failed", "", "box")
if n := rec.count(); n != 2 {
t.Fatalf("after the release the operator AND the household mail must go out: sent=%d %v", n, rec.sent)
}
// Held mails are DROPPED, not re-sent: exactly the two fresh ones, no backlog.
}
// Belt for the "one gate" claim: in dispatcher.go the sender seam is called in exactly ONE place, inside deliver().
// A new send path that calls sendEmailFn directly would bypass the hold; this fails when one appears.
func TestMailHold_EverySendPathIsGated(t *testing.T) {
src, err := os.ReadFile("dispatcher.go")
if err != nil {
t.Fatal(err)
}
calls := regexp.MustCompile(`d\.sendEmailFn\(`).FindAllIndex(src, -1)
if len(calls) != 1 {
t.Fatalf("dispatcher.go calls d.sendEmailFn( %d times; every send must go through deliver() (the MAIL-HOLD gate)", len(calls))
}
body := string(src)
i := strings.Index(body, "func (d *Dispatcher) deliver(")
if i < 0 || calls[0][0] < i || calls[0][0] > i+600 {
t.Fatalf("the one d.sendEmailFn( call is not inside deliver()")
}
}