Files
felhom.eu/hub/internal/notify/end_notice_test.go
T

265 lines
12 KiB
Go

package notify
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/mailhold"
)
// THE NOTICE LOCK, the mail's half (`09` §3 decisions 315 and 316; `07-backup-architecture.md` §8.2f). The household's
// notice is sent by the hub from its own state (SendEndNotice, called by api.endNotices) — never from the box's event.
// These tests replace TestD84_Receipt_* of the first build, whose mail left from the event.
// RED-PROOFS: documentation/audits/build-release-4b-2026-11-15/A/redproof-notice-mail.txt and …/B/redproof-texts.txt.
type receiptMail struct{ to, subject, body string }
func receiptDispatcher(t *testing.T, prefsEmail string, enabled []string) (*Dispatcher, *[]receiptMail) {
t.Helper()
st := opOnlyStore(t)
if prefsEmail != "" || enabled != nil {
if err := st.SaveNotificationPrefs("c1", prefsEmail, enabled, 6); err != nil {
t.Fatal(err)
}
}
d := opOnlyDispatcher(t, st, &sentTo{})
var mails []receiptMail
d.sendEmailFn = func(to, subject, body string, _ map[string]string) error {
mails = append(mails, receiptMail{to, subject, body})
return nil
}
return d, &mails
}
// noticeDay: 2026-12-15 12:00 UTC — the same calendar day in Budapest.
var noticeDay = time.Date(2026, 12, 15, 12, 0, 0, 0, time.UTC)
const receiptDetails = `{"stack_name":"vikunja","removed_at":"2026-11-15T10:00:00Z","ends_at":"2026-12-15T10:00:00Z","subject":"vikunja|2026-11-15T10:00:00Z"}`
// The notice reaches the household's own address although EVERY group switch is off. Its subject names the deletion
// and its day (not „Information”); its body names the day, the way back, and what to do if the household did not ask
// for this. The operator is not mailed, and no raw details are in it.
func TestNotice_ReachesTheHouseholdWhateverItsSwitches(t *testing.T) {
d, mails := receiptDispatcher(t, "customer@example.com", []string{})
if out, why, _ := d.SendEndNotice("c1", "vikunja", noticeDay); out != EndNoticeSent {
t.Fatalf("outcome = %s (%s), want sent", out, why)
}
if len(*mails) != 1 {
t.Fatalf("mails = %d, want exactly one (to the household): %+v", len(*mails), *mails)
}
m := (*mails)[0]
if m.to != "customer@example.com" {
t.Fatalf("the notice went to %q, not to the household's own address", m.to)
}
if m.subject != "[Felhom] vikunja: a távoli másolatok törlésének napja: 2026. 12. 15." {
t.Fatalf("the subject does not name the deletion and its day: %q", m.subject)
}
for _, want := range []string{"Törlésük napja: 2026. 12. 15. Addig", "Mégis megtartom", "Mentések oldalon",
"\n\nHa ezt nem te kérted, vond vissza a Mentések oldalon, és változtasd meg a jelszavadat.\n\nHa kérdésed van"} {
if !strings.Contains(m.body, want) {
t.Fatalf("the body lacks %q:\n%s", want, m.body)
}
}
if strings.Contains(m.body, "removed_at") || strings.Contains(m.body, "{") {
t.Fatalf("the body carries raw details:\n%s", m.body)
}
// the hub's own sent log holds it (the daily limit counts there)
if n, err := d.store.CountCustomerSentSince("c1", EndNoticeEvent, time.Now().Add(-time.Hour)); err != nil || n != 1 {
t.Fatalf("sent log rows = %d (%v), want 1", n, err)
}
}
// An English household reads it in English, with the English date form.
func TestNotice_FollowsTheHouseholdsLanguage(t *testing.T) {
d, mails := receiptDispatcher(t, "customer@example.com", nil)
if err := d.store.SaveReport("c1", []byte(`{"customer_id":"c1","language":"en"}`)); err != nil {
t.Fatal(err)
}
if out, _, _ := d.SendEndNotice("c1", "vikunja", noticeDay); out != EndNoticeSent || len(*mails) != 1 {
t.Fatalf("outcome %s, mails %d", out, len(*mails))
}
m := (*mails)[0]
if m.subject != "[Felhom] vikunja: the off-site copies will be deleted on 2026-12-15" {
t.Fatalf("not the English subject: %q", m.subject)
}
for _, want := range []string{"They are deleted on: 2026-12-15.", "Keep it after all",
"\n\nIf you did not ask for this, take it back on the Backups page and change your password.\n\nIf you have any questions"} {
if !strings.Contains(m.body, want) {
t.Fatalf("the English body lacks %q:\n%s", want, m.body)
}
}
if strings.Contains(m.body, "Mégis megtartom") || strings.Contains(m.body, "nem te") {
t.Fatalf("Hungarian in an English household's mail:\n%s", m.body)
}
}
// THE BOX'S EVENT MAILS NOBODY — whether it arrives once, twice, with invented words or never. (The wrong cases „the
// event never arrives” and „it arrives twice”: the notice does not depend on it.)
func TestNotice_TheBoxesEventMailsNobody(t *testing.T) {
d, mails := receiptDispatcher(t, "customer@example.com", []string{})
evil := "ANY WORDS THE BOX CHOOSES: pay at http://evil.example"
d.ProcessBoxEvent("c1", "offsite_end_scheduled", "info", "x", "", receiptDetails, "controller")
d.ProcessBoxEvent("c1", "offsite_end_scheduled", "info", "x", "", receiptDetails, "controller")
for i := 0; i < 50; i++ {
d.ProcessBoxEvent("c1", "offsite_end_scheduled", "warning", evil, evil,
fmt.Sprintf(`{"stack_name":"app-%d","removed_at":"2026-11-15T10:00:00Z","ends_at":"2026-12-15T10:00:00Z"}`, i), "controller")
}
if len(*mails) != 0 {
t.Fatalf("the box's event caused %d mail(s); first: %+v", len(*mails), (*mails)[0])
}
// positive control: the same dispatcher does mail an ordinary event of the box
if err := d.store.SaveNotificationPrefs("c1", "customer@example.com", []string{"app_stopped_unhealthy"}, 6); err != nil {
t.Fatal(err)
}
d.ProcessBoxEvent("c1", "app_stopped_unhealthy", "error", "x", "", `{"stack_name":"vikunja"}`, "controller")
if len(*mails) == 0 {
t.Fatal("control: the dispatcher mails nothing at all — the test above proves nothing")
}
}
// A household with no address, and a blocked one: nobody is mailed here, and the outcome says „no address” so that
// the caller tells the operator in its place.
func TestNotice_NoAddressOrBlocked_SaysSoAndMailsNobody(t *testing.T) {
d, mails := receiptDispatcher(t, "", nil)
if out, _, _ := d.SendEndNotice("c1", "vikunja", noticeDay); out != EndNoticeNoAddress || len(*mails) != 0 {
t.Fatalf("no address: outcome %s, %d mail(s)", out, len(*mails))
}
d, mails = receiptDispatcher(t, "customer@example.com", nil)
if err := d.store.SetCustomerConfigStatus("c1", "blocked"); err != nil {
t.Fatal(err)
}
if out, _, _ := d.SendEndNotice("c1", "vikunja", noticeDay); out != EndNoticeNoAddress || len(*mails) != 0 {
t.Fatalf("blocked: outcome %s, %d mail(s)", out, len(*mails))
}
if err := d.store.SetCustomerConfigStatus("c1", "active"); err != nil {
t.Fatal(err)
}
if out, _, _ := d.SendEndNotice("c1", "vikunja", noticeDay); out != EndNoticeSent || len(*mails) != 1 {
t.Fatalf("positive control: an unblocked household must get the notice: outcome %s, %d mail(s)", out, len(*mails))
}
}
// The daily limit DELAYS: the sixth notice of 24 hours is not sent and says „limit”; a hub restart (a new dispatcher
// on the same store) does not give five more; a day later it goes.
func TestNotice_TheDailyLimitDelaysAndSurvivesARestart(t *testing.T) {
d, mails := receiptDispatcher(t, "customer@example.com", nil)
for i := 0; i < receiptsPerDay; i++ {
if out, why, _ := d.SendEndNotice("c1", fmt.Sprintf("app-%d", i), noticeDay); out != EndNoticeSent {
t.Fatalf("notice %d: %s (%s)", i, out, why)
}
}
if out, why, _ := d.SendEndNotice("c1", "one-more", noticeDay); out != EndNoticeLimit || !strings.Contains(why, "later") {
t.Fatalf("the sixth notice: outcome %s (%q), want limit", out, why)
}
d2 := opOnlyDispatcher(t, d.store, &sentTo{}) // the restart: nothing in memory
n2 := 0
d2.sendEmailFn = func(string, string, string, map[string]string) error { n2++; return nil }
if out, _, _ := d2.SendEndNotice("c1", "one-more", noticeDay); out != EndNoticeLimit || n2 != 0 {
t.Fatalf("after a restart: outcome %s, %d mail(s) — the limit must be the hub's sent log", out, n2)
}
if len(*mails) != receiptsPerDay {
t.Fatalf("mails = %d, want %d", len(*mails), receiptsPerDay)
}
// a day later the log's rows are older than 24 hours: the delayed notice goes
if err := d.store.BackdateNotificationLogForTest("c1", 25*time.Hour); err != nil {
t.Fatal(err)
}
if out, why, _ := d.SendEndNotice("c1", "one-more", noticeDay); out != EndNoticeSent {
t.Fatalf("a day later: %s (%s), want sent — the limit delays, it does not drop", out, why)
}
}
// The mail hold and a failed send tell nobody, and say which it was.
func TestNotice_HeldOrFailed_IsNotSent(t *testing.T) {
d, mails := receiptDispatcher(t, "customer@example.com", nil)
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, mailhold.FileName), nil, 0o644); err != nil {
t.Fatal(err)
}
d.SetMailHold(mailhold.New(dir, nil))
if out, why, _ := d.SendEndNotice("c1", "vikunja", noticeDay); out != EndNoticeHeld || !strings.Contains(why, "MAIL-HOLD") || len(*mails) != 0 {
t.Fatalf("held: outcome %s (%q), %d mail(s)", out, why, len(*mails))
}
if !d.MailHeld() {
t.Fatal("MailHeld() = false with the marker present")
}
d.SetMailHold(nil)
d.sendEmailFn = func(string, string, string, map[string]string) error { return errors.New("resend: 503") }
if out, _, _ := d.SendEndNotice("c1", "vikunja", noticeDay); out != EndNoticeFailed {
t.Fatalf("failed send: outcome %s", out)
}
// neither left a „sent” row: the limit must not count a mail that did not go
if n, _ := d.store.CountCustomerSentSince("c1", EndNoticeEvent, time.Now().Add(-time.Hour)); n != 0 {
t.Fatalf("sent rows after a held and a failed try: %d", n)
}
// no mail service at all
d.resendAPIKey = ""
if out, _, _ := d.SendEndNotice("c1", "vikunja", noticeDay); out != EndNoticeFailed {
t.Fatalf("no mail service: outcome %s", out)
}
}
// A name that is not an app name never reaches a mail.
func TestNotice_OnlyAnAppNameIsMailed(t *testing.T) {
d, mails := receiptDispatcher(t, "customer@example.com", nil)
for _, app := range []string{"", "pay now at evil.example", "<b>x</b>", "traefik", "_shares", strings.Repeat("a", 65)} {
if out, _, _ := d.SendEndNotice("c1", app, noticeDay); out == EndNoticeSent || len(*mails) != 0 {
t.Fatalf("%q: outcome %s, %d mail(s)", app, out, len(*mails))
}
}
}
// The receipt register does not open any other type: an ordinary info event still mails nobody, and a type the
// household switched off still stays off.
func TestD84_Receipt_OpensNothingElse(t *testing.T) {
d, mails := receiptDispatcher(t, "customer@example.com", []string{})
d.ProcessBoxEvent("c1", "app_removed", "info", "Alkalmazás eltávolítva.", "", `{"stack_name":"vikunja"}`, "controller")
d.ProcessBoxEvent("c1", "app_stopped_unhealthy", "error", "x", "", `{"stack_name":"vikunja"}`, "controller")
for _, m := range *mails {
if m.to == "customer@example.com" {
t.Fatalf("the household was mailed a type it switched off / an info event: %+v", m)
}
}
if len(householdReceiptEvents) != 1 || !householdReceiptEvents["offsite_end_scheduled"] {
t.Fatalf("the receipt register changed: %v — every entry bypasses the household's switches and needs its own ruling", householdReceiptEvents)
}
if operatorOnlyEvents["offsite_end_scheduled"] {
t.Fatal("a receipt cannot be operator-only")
}
}
// SendOperatorNow answers only when the mail service has: nil = accepted. It refuses a type a household could get.
func TestNotice_SendOperatorNow(t *testing.T) {
d, mails := receiptDispatcher(t, "customer@example.com", nil)
if err := d.SendOperatorNow("c1", "offsite_end_notice_operator", "warning", "m", `{"subject":"vikunja"}`); err != nil || len(*mails) != 1 {
t.Fatalf("err=%v mails=%d", err, len(*mails))
}
if (*mails)[0].to != "operator@felhom.eu" {
t.Fatalf("went to %q", (*mails)[0].to)
}
if err := d.SendOperatorNow("c1", "app_stopped_unhealthy", "warning", "m", ""); err == nil {
t.Fatal("a type that is not operator-only was accepted")
}
d.sendEmailFn = func(string, string, string, map[string]string) error { return errors.New("resend: 503") }
if err := d.SendOperatorNow("c1", "offsite_end_notice_operator", "warning", "m", ""); err == nil {
t.Fatal("a failed send answered nil — the caller would start the 30 days on a mail that never went")
}
d.operatorOn = false
if err := d.SendOperatorNow("c1", "offsite_end_notice_operator", "warning", "m", ""); err == nil {
t.Fatal("the operator's mail is off, and the call answered nil")
}
for _, typ := range []string{"offsite_end_notice_operator", "offsite_end_notice_stuck"} {
if !IsOperatorOnly(typ) {
t.Fatalf("%s must be operator-only", typ)
}
}
if !HasPerSubjectCooldown("offsite_end_notice_stuck") {
t.Fatal("offsite_end_notice_stuck: two apps stuck in one hour must be two mails")
}
}