Files
felhom-controller/controller/internal/web/offsite_ends_test.go
T
admin f628cb5082
gates / gates (push) Successful in 41s
The off-site copies of a removed app end 30 days after „delete backup data” — the box's half (felhom.eu R-1374 part 1; D72, D84)
Built, not released; no box has run it. felhom.eu `07-backup-architecture.md` §8.2f.
It does nothing without a hub that knows it: an older hub agrees to no id.

- The record: settings `offsite_ends` {app, removed_at, ends_at}. One writer
  (backup.StartOffsiteEnd), called by a removal only with „delete backup data”
  and by „Törlés 30 nap múlva” on the restore page. A second press changes
  nothing. No record, no deletion. Only on the hub-provisioned tier.
- The date is on the remove dialog before the press; the restore page shows
  „Törlésre kijelölve …” with „Mégis megtartom”, and one history line per
  carried-out end. An install of the same app deletes the record.
- The weekly window: after the guard has passed the policy's plan under the cap
  as before, it adds the snapshots whose app tags are ALL due records, that the
  hub agreed to and the box named in the same request; the result names them
  apart (removed_for_ended_apps). `_shares`, the box's own stacks and an
  installed app are never due.
- The report carries the pending records; the household gets one mail per
  press (offsite_end_scheduled), in both languages.

MinAgent unchanged (0.158.1). 143 parity fixtures gained the dialog's one new
script line (patched, not regenerated); one new parity case.
Tests TestD72_*, TestD84_*; 56 mutations seen red
(felhom.eu documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-*.txt).

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 14:09:47 +01:00

290 lines
14 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)
}
}
}