Files
felhom-controller/controller/internal/web/offsite_ends_test.go
T
admin 10df99b89f
gates / gates (push) Successful in 45s
The remove dialog shows the older sentence about the nightly snapshots only where no end date is shown (felhom.eu decision 316, R-1374)
Household-facing, built and NOT published. No string changed; layout.html only.
The 144 i18n_parity fixtures are patched on the dialog's lines only.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 16:39:13 +01:00

330 lines
16 KiB
Go

package web
import (
"io"
"log"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
"gitea.dooplex.hu/admin/felhom-controller/internal/i18n"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// D72 / D84 (`09` §3 decisions 292, 309; `07-backup-architecture.md` §8.2f part 2): the household sees the date and
// can take it back. RED-PROOFS: felhom.eu/documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-page.txt.
func endsRestoreData(rows []OffsiteRestoreRow) map[string]interface{} {
d := i18nLayoutData("backups-restore", "Visszaállítás a mentésből")
d["Backup"] = i18nBackupStatus(false, false)
d["OffboxConfigured"] = true
d["OffsiteStoreState"] = "known"
d["OffsiteRestoreRows"] = rows
return d
}
// The page, per branch of its gates (the seam-wiring rule): a marked app shows its line and ONLY „keep it after all”;
// a removed app with kept copies shows the kept line and „delete in 30 days”; an installed app shows neither; a
// carried-out end is one history line. In both languages.
func TestD72_RestorePageShowsTheEndPerBranch(t *testing.T) {
rows := []OffsiteRestoreRow{
{App: "vikunja", DisplayName: "vikunja", InStore: true, EndDate: "Törlésre kijelölve. Törlés napja: 2026. 12. 15."},
{App: "kimai", DisplayName: "kimai", InStore: true, EndOffered: true},
{App: "immich", DisplayName: "Immich", InStore: true, Installed: true},
}
d := endsRestoreData(rows)
d["OffsiteEndsDone"] = []offsiteEndDoneRow{{App: "docmost", Line: "A távoli másolatok törölve: 2026. 11. 08."}}
html := renderBackupPage(t, "backups_restore", d)
for _, want := range []string{
`data-offsite-end="marked">Törlésre kijelölve. Törlés napja: 2026. 12. 15.</span>`,
`action="/backup/offsite-end/keep"`, `name="app" value="vikunja"`, "Mégis megtartom",
`data-offsite-end="kept">Ennek az alkalmazásnak a távoli másolatai megmaradtak.</span>`,
`action="/backup/offsite-end/start"`, `name="app" value="kimai"`, "Törlés 30 nap múlva",
`data-offsite-end="done">docmost: A távoli másolatok törölve: 2026. 11. 08.</p>`,
} {
if !strings.Contains(html, want) {
t.Errorf("the restore page lacks %q", want)
}
}
if n := strings.Count(html, `action="/backup/offsite-end/keep"`); n != 1 {
t.Errorf("%d „keep it after all” forms, want one (the marked app's)", n)
}
if n := strings.Count(html, `action="/backup/offsite-end/start"`); n != 1 {
t.Errorf("%d „delete in 30 days” forms, want one (the removed app with kept copies)", n)
}
for _, bad := range []string{`name="app" value="immich"`} {
if strings.Contains(html, bad) {
t.Errorf("an INSTALLED app is offered an end: %q", bad)
}
}
// no record, nothing removed, no history: the page carries none of it
plain := renderBackupPage(t, "backups_restore", endsRestoreData([]OffsiteRestoreRow{{App: "immich", DisplayName: "Immich", InStore: true, Installed: true}}))
if strings.Contains(plain, `data-offsite-end="marked"`) || strings.Contains(plain, `data-offsite-end="kept"`) ||
strings.Contains(plain, `data-offsite-end="done"`) || strings.Contains(plain, "/backup/offsite-end/") {
t.Error("a page with no end record and no removed app shows the end's controls")
}
// English
en := renderBackupPageLang(t, "en", "backups_restore", endsRestoreData([]OffsiteRestoreRow{
{App: "vikunja", DisplayName: "vikunja", InStore: true, EndDate: "Marked for deletion. Deleted on: 2026-12-15."},
{App: "kimai", DisplayName: "kimai", InStore: true, EndOffered: true}}))
for _, want := range []string{"Keep it after all", "The off-site copies of this app were kept.", "Delete in 30 days", "Marked for deletion. Deleted on: 2026-12-15."} {
if !strings.Contains(en, want) {
t.Errorf("the English restore page lacks %q", want)
}
}
for _, bad := range []string{"Mégis megtartom", "Törlés 30 nap múlva", "megmaradtak"} {
if strings.Contains(en, bad) {
t.Errorf("Hungarian on the English page: %q", bad)
}
}
}
// Which row gets which: the pure rule.
func TestD72_ApplyOffsiteEnds(t *testing.T) {
date := func(e settings.OffsiteEnd) string { return "MARKED " + e.App }
ends := []settings.OffsiteEnd{{App: "vikunja"}, {App: "immich"}, {App: "ghost"}}
in := func() []OffsiteRestoreRow {
return []OffsiteRestoreRow{
{App: "vikunja", InStore: true}, // removed, record → marked
{App: "immich", InStore: true, Installed: true}, // INSTALLED with a stale record → nothing
{App: "kimai", InStore: true}, // removed, no record → the offer
{App: "docmost", InStore: true, Installed: true}, // installed → nothing
{App: "unread", InStore: false, StoreUnknown: true}, // the store could not be read → no offer
{App: "empty", InStore: false}, // nothing in the store → no offer
}
}
got := map[string]OffsiteRestoreRow{}
for _, r := range applyOffsiteEnds(in(), ends, true, date) {
got[r.App] = r
}
if got["vikunja"].EndDate != "MARKED vikunja" || got["vikunja"].EndOffered {
t.Errorf("vikunja: %+v", got["vikunja"])
}
if got["immich"].EndDate != "" || got["immich"].EndOffered {
t.Errorf("an installed app shows an end: %+v", got["immich"])
}
if !got["kimai"].EndOffered || got["kimai"].EndDate != "" {
t.Errorf("kimai (removed, copies kept): %+v", got["kimai"])
}
for _, app := range []string{"docmost", "unread", "empty"} {
if got[app].EndOffered || got[app].EndDate != "" {
t.Errorf("%s must show nothing: %+v", app, got[app])
}
}
// a record whose app has no row at all still shows — the take-back must not depend on reading the store
if g, ok := got["ghost"]; !ok || g.EndDate != "MARKED ghost" {
t.Errorf("a record with no row is not shown: %+v ok=%v", g, ok)
}
// a box where a press cannot start the clock offers nothing
for _, r := range applyOffsiteEnds(in(), nil, false, date) {
if r.EndOffered {
t.Errorf("%s: offered on a box without the hub's tier", r.App)
}
}
}
func endsServer(t *testing.T, pinned bool, living ...string) (*Server, *settings.Settings, *[]settings.OffsiteEnd) {
t.Helper()
tmp := t.TempDir()
lg := log.New(io.Discard, "", 0)
sett, err := settings.Load(filepath.Join(tmp, "settings.json"), lg)
if err != nil {
t.Fatal(err)
}
tr := ""
if pinned {
tr = settings.TransportRclonePinned
}
if err := sett.SetOffboxTarget(&settings.OffboxTarget{Enabled: true, Host: "h", User: "u", RepoPath: "/r", Transport: tr}); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
cfg.Paths.DataDir = tmp
m := backup.NewManager(cfg, sett, lg)
live := map[string]bool{}
for _, l := range living {
live[l] = true
}
m.SetOffsiteEndLiving(func(app string) bool { return live[app] })
var mails []settings.OffsiteEnd
m.SetOffsiteEndNotify(func(rec settings.OffsiteEnd) { mails = append(mails, rec) })
s := testServer(t)
s.cfg, s.backupMgr, s.logger, s.settings = cfg, m, lg, sett
return s, sett, &mails
}
// MUST-HOLD 4 — THE HOUSEHOLD CAN TAKE IT BACK, through the page's own endpoints: „delete in 30 days” writes the
// record (one mail), a second press changes nothing (no second mail), „keep it after all” deletes it, and a second
// „keep” says there is nothing marked.
func TestD72_StartAndKeepHandlers(t *testing.T) {
s, sett, mails := endsServer(t, true, "immich")
post := func(path, form string) string {
rr := httptest.NewRecorder()
req := httptest.NewRequest("POST", path, strings.NewReader(form))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if strings.HasSuffix(path, "/keep") {
s.offsiteEndKeepHandler(rr, req)
} else {
s.offsiteEndStartHandler(rr, req)
}
return rr.Header().Get("Location")
}
loc := post("/backup/offsite-end/start", "app=vikunja")
rec, ok := sett.GetOffsiteEnd("vikunja")
if !ok || !strings.Contains(loc, "offsite_end.marked") || strings.Contains(loc, "flash_error") {
t.Fatalf("start → %q, record ok=%v", loc, ok)
}
wantDate := i18n.FormatDate("hu", rec.Ends().Local())
if !strings.Contains(loc, strings.ReplaceAll(wantDate, " ", "+")) {
t.Fatalf("the flash does not carry the record's day %q: %q", wantDate, loc)
}
if d := rec.Ends().Sub(time.Now()); d < 29*24*time.Hour || d > 31*24*time.Hour {
t.Fatalf("the record ends in %s, want 30 days", d)
}
_ = post("/backup/offsite-end/start", "app=vikunja")
if again, _ := sett.GetOffsiteEnd("vikunja"); again != rec || len(*mails) != 1 {
t.Fatalf("a second press: record %+v (was %+v), %d mail(s) — want unchanged and ONE mail", again, rec, len(*mails))
}
// an installed app, the shares and a path are refused and write nothing
for _, app := range []string{"immich", "_shares", "../x", ""} {
if loc := post("/backup/offsite-end/start", "app="+app); !strings.Contains(loc, "flash_error=flash.offsite_end.not_possible") {
t.Errorf("start for %q → %q, want the refusal", app, loc)
}
}
if n := len(sett.GetOffsiteEnds()); n != 1 || len(*mails) != 1 {
t.Fatalf("records=%d mails=%d after the refused presses", n, len(*mails))
}
if loc := post("/backup/offsite-end/keep", "app=vikunja"); !strings.Contains(loc, "flash=flash.offsite_end.kept") {
t.Fatalf("keep → %q", loc)
}
if _, ok := sett.GetOffsiteEnd("vikunja"); ok {
t.Fatal("„keep it after all” left the record — the window would still delete the copies")
}
if loc := post("/backup/offsite-end/keep", "app=vikunja"); !strings.Contains(loc, "flash_error=flash.offsite_end.nothing_to_keep") {
t.Fatalf("a second keep → %q, want the page to say nothing is marked", loc)
}
// a box without the hub's tier: the press is refused, nothing is written, nobody is mailed
s2, sett2, mails2 := endsServer(t, false)
rr := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/backup/offsite-end/start", strings.NewReader("app=vikunja"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
s2.offsiteEndStartHandler(rr, req)
if !strings.Contains(rr.Header().Get("Location"), "flash.offsite_end.not_possible") || len(sett2.GetOffsiteEnds()) != 0 || len(*mails2) != 0 {
t.Fatalf("no hub tier: %q records=%d mails=%d", rr.Header().Get("Location"), len(sett2.GetOffsiteEnds()), len(*mails2))
}
}
// The page data: a record becomes the marked line with the record's own day in the page's language; a carried-out
// end becomes a history line.
func TestD72_OffsiteEndDataFromTheRecords(t *testing.T) {
s, sett, _ := endsServer(t, true)
rec, _, _ := sett.StartOffsiteEnd("vikunja", time.Date(2026, 11, 15, 10, 0, 0, 0, time.UTC))
old, _, _ := sett.StartOffsiteEnd("docmost", time.Date(2026, 10, 1, 10, 0, 0, 0, time.UTC))
if _, err := sett.CompleteOffsiteEnd("docmost", old.RemovedAt, time.Date(2026, 11, 8, 3, 0, 0, 0, time.UTC), 4); err != nil {
t.Fatal(err)
}
for lang, want := range map[string][2]string{
"hu": {"Törlésre kijelölve. Törlés napja: " + i18n.FormatDate("hu", rec.Ends().Local()), "A távoli másolatok törölve: " + i18n.FormatDate("hu", time.Date(2026, 11, 8, 3, 0, 0, 0, time.UTC).Local())},
"en": {"Marked for deletion. Deleted on: " + i18n.FormatDate("en", rec.Ends().Local()) + ".", "The off-site copies were deleted on " + i18n.FormatDate("en", time.Date(2026, 11, 8, 3, 0, 0, 0, time.UTC).Local()) + "."},
} {
data := map[string]interface{}{}
req := httptest.NewRequest("GET", "/backups/restore?lang="+lang, nil)
rows := s.offsiteEndData(req, data, []OffsiteRestoreRow{{App: "vikunja", InStore: true}, {App: "kimai", InStore: true}})
if rows[0].EndDate != want[0] {
t.Errorf("%s: marked line = %q, want %q", lang, rows[0].EndDate, want[0])
}
if !rows[1].EndOffered {
t.Errorf("%s: a removed app with copies and no record is not offered „delete in 30 days”", lang)
}
done, _ := data["OffsiteEndsDone"].([]offsiteEndDoneRow)
if len(done) != 1 || done[0].App != "docmost" || done[0].Line != want[1] {
t.Errorf("%s: history = %+v, want docmost: %q", lang, done, want[1])
}
}
}
// The routes are REACHABLE: both POSTs are in the server's switch (a handler nobody routes to is not a feature).
func TestD72_TheEndRoutesAreWired(t *testing.T) {
raw, err := os.ReadFile("server.go")
if err != nil {
t.Fatal(err)
}
for _, want := range []string{
"case path == \"/backup/offsite-end/keep\" && r.Method == http.MethodPost:\n\t\ts.offsiteEndKeepHandler(w, r)",
"case path == \"/backup/offsite-end/start\" && r.Method == http.MethodPost:\n\t\ts.offsiteEndStartHandler(w, r)",
} {
if !strings.Contains(string(raw), want) {
t.Errorf("server.go lacks the route %q", want)
}
}
h, err := os.ReadFile("handlers.go")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(h), "rows = s.offsiteEndData(r, data, rows)") {
t.Error("the restore page does not put the end records on its rows")
}
}
// THE DATE IS ON THE REMOVE DIALOG BEFORE THE PRESS (D72): the dialog's script shows the sentence, with the day the
// API gave, only when the API gave one — in both languages.
func TestD72_TheRemoveDialogNamesTheDate(t *testing.T) {
for lang, want := range map[string]string{
"hu": "A helyi mentések most törlődnek. A távoli másolatok még 30 napig megmaradnak. Törlésük napja: {date} Addig a Mentések oldalon visszavonhatod.",
"en": "The local backups are deleted now. The off-site copies stay for 30 more days. They are deleted on: {date}. Until then you can take this back on the Backups page.",
} {
html := renderBackupPageLang(t, lang, "backups_restore", endsRestoreData(nil))
if !strings.Contains(html, want) {
t.Errorf("[%s] the remove dialog lacks the sentence %q", lang, want)
}
if !strings.Contains(html, "backupResp.data.offsite_end_date ?") || !strings.Contains(html, ".replace('{date}', backupResp.data.offsite_end_date)") {
t.Errorf("[%s] the dialog does not show the sentence only with the API's date", lang)
}
}
}
// THE OLDER SENTENCE IS NOT SHOWN BESIDE THE NEW LINE (felhom.eu `09` §3 decision 316). „The nightly snapshots cannot
// be deleted one by one — they age out by the retention rules” is no longer true on a box that shows „the off-site
// copies … are deleted on <date>”. The dialog's script shows exactly ONE of the two: the new line when the API gave
// a date (a box with the hub's off-site tier), the older sentence on every other box.
//
// What this test reads: the dialog is built by a script in the browser, and no script engine runs in this suite. So
// it reads the script's two branches from the rendered page — the text after `offsite_end_date ?` up to the `:`, and
// the text after it up to the closing `)` — and checks each branch's content. No browser has run it.
// RED-PROOF: felhom.eu documentation/audits/build-release-4b-2026-11-15/B/redproof-texts-controller.txt.
func TestD72_TheRemoveDialogShowsTheOlderSentenceOnlyWithoutTheDate(t *testing.T) {
for lang, s := range map[string]struct{ newLine, older string }{
"hu": {"A távoli másolatok még 30 napig megmaradnak. Törlésük napja: {date}", "Az éjszakai restic pillanatképek nem törölhetők egyenként"},
"en": {"The off-site copies stay for 30 more days. They are deleted on: {date}.", "The nightly restic snapshots cannot be deleted one by one"},
} {
html := renderBackupPageLang(t, lang, "backups_restore", endsRestoreData(nil))
const cond = "(backupResp.data.offsite_end_date ? "
i := strings.Index(html, cond)
if i < 0 || strings.Count(html, cond) != 1 {
t.Fatalf("[%s] the dialog's script has no single `offsite_end_date ?` choice (found %d)", lang, strings.Count(html, cond))
}
rest := html[i+len(cond):]
colon := strings.Index(rest, "'</div>' : '")
end := strings.Index(rest, "'</div>') +")
if colon < 0 || end < colon {
t.Fatalf("[%s] the choice has not the shape `date ? … '</div>' : … '</div>')`:\n%.400s", lang, rest)
}
withDate, without := rest[:colon], rest[colon:end]
if !strings.Contains(withDate, s.newLine) || strings.Contains(withDate, s.older) {
t.Errorf("[%s] WITH a date the dialog must show the new line and not the older sentence:\n%s", lang, withDate)
}
if !strings.Contains(without, s.older) || strings.Contains(without, s.newLine) {
t.Errorf("[%s] WITHOUT a date the dialog must show the older sentence and not the new line:\n%s", lang, without)
}
// … and the older sentence is nowhere else in the dialog's script: it cannot show beside the new line.
if n := strings.Count(html, s.older); n != 1 {
t.Errorf("[%s] the older sentence is on the page %d times, want once (inside the no-date branch)", lang, n)
}
}
}