Files
felhom.eu/hub/internal/api/end_notice_review_test.go
T

306 lines
14 KiB
Go

package api
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/offsitekeys"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// THE INDEPENDENT REVIEW OF THE NOTICE LOCK (2026-11-15 night). One test per finding, each seen red before its fix:
// documentation/audits/build-release-4b-2026-11-15/A/redproof-review-<n>.txt.
// Finding 3. A box could put a link-shaped word into the household's subject — `www.evil-bank.example.com`, five a
// day: the app-record's name rule allows dots and capitals, and a notice row was made for a name the hub never saw
// installed. A name that reaches a household's mail must be a plain app slug (store.ValidNoticeApp): lower-case
// letters, digits, `-`, `_`; no dot. Anything else: no row, no mail, never agreed.
func TestReview3_ALinkShapedNameNeverReachesTheHousehold(t *testing.T) {
r := newNoticeRig(t, household)
for _, name := range []string{"www.evil-bank.example.com", "evil.example", "Felhom-Support", "a.b", "x..y"} {
r.report(pressed(name, "2026-11-15T10:00:00Z"))
if got := r.to(household); len(got) != 0 {
t.Fatalf("%q reached the household: subject %q", name, got[0].subject)
}
if _, ok := r.notice(name); ok {
t.Fatalf("%q has a notice row", name)
}
}
// positive control: a plain slug is told
r.report(pressed("paperless-ngx", "2026-11-15T10:00:00Z"))
if got := r.to(household); len(got) != 1 || !strings.Contains(got[0].subject, "paperless-ngx: ") {
t.Fatalf("a plain app name must be told: %+v", got)
}
}
// The slug rule fits every app the catalog has (read from the sibling repository when it is there).
func TestReview3_EveryCatalogAppNameIsANoticeName(t *testing.T) {
dir := filepath.Join("..", "..", "..", "..", "app-catalog-felhom.eu", "templates")
entries, err := os.ReadDir(dir)
if err != nil {
t.Skipf("the catalog repository is not beside this one (%v)", err)
}
n := 0
for _, e := range entries {
if !e.IsDir() {
continue
}
if _, err := os.Stat(filepath.Join(dir, e.Name(), ".felhom.yml")); err != nil {
continue
}
n++
if !store.ValidNoticeApp(e.Name()) {
t.Errorf("the catalog app %q is not a notice name — its household could never be told, and its copies never deleted", e.Name())
}
}
if n < 50 {
t.Fatalf("only %d catalog apps read — the test stopped reading the catalog", n)
}
}
// Finding 4. The told time was the WALK's start: with many rows, the last one was „told” minutes before its mail was
// accepted — and the 30 days counted from before the mail. The told time is taken AFTER the send has returned.
func TestReview4_ToldIsTheTimeAfterTheSendReturned(t *testing.T) {
r := newNoticeRig(t, household)
r.fail = errors.New("resend: 503")
r.report(repPressed) // the row exists, nobody told
r.mu.Lock()
r.fail = nil
r.mu.Unlock()
r.d.SetSendFnForTest(func(to, subject, body string, _ map[string]string) error {
time.Sleep(1200 * time.Millisecond) // the mail service takes its time
return nil
})
start := time.Now().Add(2 * time.Hour) // the walk's clock at its start
r.h.endNotices("c1", start)
n, _ := r.notice("vikunja")
if !n.Told() {
t.Fatalf("fixture: not told: %+v", n)
}
if n.ToldAt.Unix() < start.Unix()+1 {
t.Fatalf("told at %s — the walk started at %s and the send took 1.2 s: the told time must be after the send returned, never the walk's start",
n.ToldAt.Format(time.RFC3339), start.UTC().Format(time.RFC3339))
}
}
// Finding 2. A send that ERRORS AFTER the mail service accepted it (a client timeout) was mailed again every hour,
// and it was outside the daily limit, because the limit counted only `sent` rows: 12 mails in 12 hours. Now the
// limit counts every try that reached the mail service (`sent` + `failed`), and the wait before the next try grows
// with the tries (1 h, 2 h, 4 h … at most 24 h). The operator's in-place mail has the same shape and the same
// fix. The „stuck” line after 3 days still comes.
func TestReview2_ASendThatErrorsAfterItWasAcceptedIsNotMailedEveryHour(t *testing.T) {
for _, c := range []struct{ name, email, to string }{
{"the household's notice", household, household},
{"the operator's in-place notice", "", operator},
} {
t.Run(c.name, func(t *testing.T) {
r := newNoticeRig(t, c.email)
r.d.SetSendFnForTest(func(to, subject, body string, _ map[string]string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.mails = append(r.mails, noticeMail{to, subject, body}) // the mail WENT …
return errors.New("context deadline exceeded") // … and the client gave up waiting
})
count := func() int {
n := 0
for _, m := range r.to(c.to) {
if !strings.Contains(m.subject, "offsite_end_notice_stuck") && !strings.Contains(m.subject, "offsite_end_claim_unseen") {
n++
}
}
return n
}
r.report(repPressed)
now := time.Now()
for i := 1; i <= 11; i++ { // a report every hour for twelve hours
r.h.endNotices("c1", now.Add(time.Duration(i)*61*time.Minute))
}
if n := count(); n > 4 {
t.Fatalf("12 hours of a send that errors after it was accepted: %d mails, want at most 4 (tries at 0, 1, 3 and 7 hours)", n)
}
for i := 12; i <= 100; i++ { // … and four days of it
r.h.endNotices("c1", now.Add(time.Duration(i)*61*time.Minute))
}
if n := count(); n > 5 {
t.Fatalf("four days of it: %d mails — the daily limit must count a try that failed (all of them are inside this test's real 24 hours)", n)
}
if n, _ := r.notice("vikunja"); n.Told() {
t.Fatalf("a send that returned an error counts as told: %+v", n)
}
if e := r.events(offsitekeys.EventEndNoticeStuck); len(e) != 1 {
t.Fatalf("the operator's line after 3 days: %d, want 1", len(e))
}
})
}
}
// Finding 7. The guard `n.Told() ||` in endNoticeStuck had no test: without it the suite stayed green. A row that
// WAS told to the operator (the household had no address then) and whose later household mail waits for the daily
// limit has told somebody — the operator must NOT get the line „the notice has not gone out”.
func TestReview7_ARowToldToTheOperatorNeverGetsTheStuckLine(t *testing.T) {
r := newNoticeRig(t, "")
r.report(repPressed)
if n, _ := r.notice("vikunja"); n.ToldTo != store.EndNoticeOperator {
t.Fatalf("fixture: the operator was not told: %+v", n)
}
// five days pass; the household now has an address, and its daily limit is used up by other notices
old := time.Now().UTC().Add(-5 * 24 * time.Hour)
if err := r.st.SetEndNoticeForTest("c1", "vikunja", "2026-11-15T10:00:00Z", old, old, store.EndNoticeOperator); err != nil {
t.Fatal(err)
}
if err := r.st.SaveNotificationPrefs("c1", household, []string{}, 6); err != nil {
t.Fatal(err)
}
for i := 0; i < 5; i++ {
if err := r.st.LogNotification("c1", "offsite_end_scheduled", "info", "offsite_end_scheduled other", "sent", "", "customer"); err != nil {
t.Fatal(err)
}
}
r.report(repPressed)
n, _ := r.notice("vikunja")
if n.ToldTo != store.EndNoticeOperator || !n.Told() || !strings.Contains(n.LastReason, "daily limit") {
t.Fatalf("fixture: the household's mail must have waited for the limit, the operator's notice standing: %+v", n)
}
if e := r.events(offsitekeys.EventEndNoticeStuck); len(e) != 0 {
t.Fatalf("a row that was told to the operator got the „told nobody” line: %+v", e)
}
}
// Finding 1 — THE REAL HOLE. „Told” survived a change of the household's notification address. Somebody with the
// household's login sets the address to his own, presses „delete backup data”, gets the notice, and puts the real
// address back: the row stayed told, the real address got nothing, and the hub agreed 30 days later. This is the
// case D84 exists for. Now „told to the household” counts only for the address the household has NOW: a save that
// changes, removes or adds the address un-tells the household's rows, the next report mails the current address,
// and the 30 days start again.
func (r *noticeRig) savePrefs(body string) {
r.t.Helper()
if rr := do(r.h, "POST", "/preferences", "ckey", body); rr.Code != 200 {
r.t.Fatalf("preferences → %d (%s)", rr.Code, rr.Body.String())
}
}
const intruder = "intruder@example.net"
func TestReview1_ToldDoesNotSurviveAnAddressChange(t *testing.T) {
r := newNoticeRig(t, intruder) // the address was changed to the intruder's before the press
r.report(repPressed)
n, ok := r.notice("vikunja")
if !ok || n.ToldTo != store.EndNoticeHousehold || len(r.to(intruder)) != 1 {
t.Fatalf("fixture: the notice did not go to the address on record: %+v", n)
}
// the hub's record is 40 days old — old enough to agree
old := time.Now().UTC().Add(-40 * 24 * time.Hour)
if err := r.st.SetEndNoticeForTest("c1", "vikunja", "2026-11-15T10:00:00Z", old, old, store.EndNoticeHousehold); err != nil {
t.Fatal(err)
}
// the real address is put back, through the endpoint the box uses for the household's own save
r.savePrefs(`{"customer_id":"c1","email":"` + household + `","enabled_events":[],"cooldown_hours":6,"source":"household"}`)
n, _ = r.notice("vikunja")
if n.Told() {
t.Fatalf("after the address changed the row still says told: %+v — the hub would agree with nobody at the real address told", n)
}
if time.Since(n.FirstNamed) > time.Minute || !strings.Contains(n.LastReason, "address changed") {
t.Fatalf("the save must un-tell the row itself: first named now (the operator's 3-day line counts from the change) and the reason on the row: %+v", n)
}
r.report(repPressed)
n, _ = r.notice("vikunja")
if len(r.to(household)) != 1 || n.ToldTo != store.EndNoticeHousehold || time.Since(n.ToldAt) > time.Minute {
t.Fatalf("the CURRENT address must be mailed and the 30 days start again: mails to it = %d, record %+v", len(r.to(household)), n)
}
}
// A save that does not change the address un-tells nothing: the same address in other capitals or with spaces, a
// push with an empty address (the hub keeps the stored one), and a push that only changes the switches.
func TestReview1_ASaveThatChangesNothingKeepsTheNotice(t *testing.T) {
r := newNoticeRig(t, household)
r.report(repPressed)
before, _ := r.notice("vikunja")
for _, body := range []string{
`{"customer_id":"c1","email":" Customer@Example.COM ","enabled_events":[],"cooldown_hours":6,"source":"household"}`,
`{"customer_id":"c1","email":"","enabled_events":["node_down"],"cooldown_hours":6}`,
`{"customer_id":"c1","email":"` + household + `","enabled_events":["node_down"],"cooldown_hours":12,"source":"household"}`,
} {
r.savePrefs(body)
r.report(repPressed)
n, _ := r.notice("vikunja")
if !n.Told() || !n.ToldAt.Equal(before.ToldAt) || len(r.to(household)) != 1 {
t.Fatalf("a save that did not change the address (%s) voided the notice or mailed again: %+v, %d mail(s)", body, n, len(r.to(household)))
}
}
}
// The attacker's other moves. (a) The address is changed back and forth many times in a day: whenever the record
// says told, the newest notice went to the address the household has at that moment; the daily limit delays and
// never counts as told. (b) The address is REMOVED after the notice: the household's row is un-told and the
// operator is told in its place. (c) The address changes WHILE the mail is being sent: the mail went to the old
// address, so the household is not told.
func TestReview1_BackAndForth_Removed_AndDuringTheSend(t *testing.T) {
r := newNoticeRig(t, household)
cur := household
for i := 0; i < 8; i++ {
r.report(repPressed)
n, _ := r.notice("vikunja")
mails := r.all()
var last string
for _, m := range mails {
if strings.Contains(m.subject, "vikunja: ") && !strings.Contains(m.subject, "offsite_end") {
last = m.to
}
}
if n.Told() && last != cur {
t.Fatalf("round %d: the record says told, and the newest notice went to %q — the household's address is %q", i, last, cur)
}
if !n.Told() && !strings.Contains(n.LastReason, "daily limit") {
t.Fatalf("round %d: not told, and the reason is %q", i, n.LastReason)
}
if cur == household {
cur = intruder
} else {
cur = household
}
r.savePrefs(`{"customer_id":"c1","email":"` + cur + `","enabled_events":[],"cooldown_hours":6,"source":"household"}`)
}
if n := len(r.to(household)) + len(r.to(intruder)); n != 5 {
t.Fatalf("eight address changes in a day: %d notices, want the daily limit 5", n)
}
// (b) removed
r2 := newNoticeRig(t, household)
r2.report(repPressed)
r2.savePrefs(`{"customer_id":"c1","email":"","email_cleared":true,"enabled_events":[],"cooldown_hours":6,"source":"household"}`)
if n, _ := r2.notice("vikunja"); n.Told() {
t.Fatalf("the address was removed and the row still says the household was told: %+v", n)
}
r2.report(repPressed)
if n, _ := r2.notice("vikunja"); n.ToldTo != store.EndNoticeOperator || len(r2.opNotice(offsitekeys.EventEndNoticeOperator)) != 1 {
t.Fatalf("with the address removed the operator must be told in the household's place: %+v", n)
}
// (c) during the send
r3 := newNoticeRig(t, intruder)
r3.d.SetSendFnForTest(func(to, subject, body string, _ map[string]string) error {
if to == intruder { // while the intruder's mail is on its way, the real address is put back
if err := r3.st.SaveNotificationPrefsAs("c1", household, []string{}, 6, true); err != nil {
t.Error(err)
}
}
r3.mu.Lock()
defer r3.mu.Unlock()
r3.mails = append(r3.mails, noticeMail{to, subject, body})
return nil
})
r3.report(repPressed)
if n, _ := r3.notice("vikunja"); n.Told() {
t.Fatalf("the mail went to the old address and the household counts as told: %+v", n)
}
r3.h.endNotices("c1", time.Now().Add(2*time.Hour))
if n, _ := r3.notice("vikunja"); !n.Told() || len(r3.to(household)) != 1 {
t.Fatalf("the next walk must tell the address the household has now: %+v, %d mail(s)", n, len(r3.to(household)))
}
}