hub: the off-site copies of a removed app end after 30 days — the hub agrees first, the allowance is beside the cap, the household's mail (R-1374 part 1, D72, D84)

Built, not deployed. `07-backup-architecture.md` §8.2f parts 3-4 and decision 309.

- store: the hub's own record of which apps a box runs, by the hub's clock
  (offsite_app_presence, fed by every controller report); it goes with the household.
- offsitekeys: window-open takes the box's due end records and answers
  ended_allowed / ended_refused. An app is agreed only after 30 days of absence
  in the hub's record; an id only when the hub's own listing holds it, uploaded
  before that absence. The cap (max_remove) is unchanged; the close keeps only
  agreed ids from removed_for_ended_apps and allows them beside the cap.
- The 07:10 audit explains the ended apps' vanished files by name and still
  raises for every other vanished file.
- notify: offsite_end_scheduled is a household receipt — one mail per press to
  the household's own address, whatever its switches; the operator is not mailed.
- Two operator-only hub records: offsite_ended_app_removed (info),
  offsite_ended_app_refused (warning).

Tests TestD72_*, TestD84_*; 44 mutations seen red, 5 after a redo
(documentation/audits/build-release-4-2026-11-15/A/redproof-hub-*.txt).

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
admin committed 2026-11-15 13:26:13 +01:00
1 parent 552e19cd3d
commit 01a106b78c
33 files changed
+1834 -24

No files matched your search

+92
View File
@@ -0,0 +1,92 @@
package api
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/notify"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// D72 / D84 (`07-backup-architecture.md` §8.2f): the wire. RED-PROOFS:
// documentation/audits/build-release-4-2026-11-15/A/redproof-hub-api.txt.
// A controller report feeds the hub's OWN app record: the app list, and the apps named in pending end records. The
// box's dates in `ended_apps` never become the hub's date.
func TestD72_ReportFeedsTheHubsOwnAppRecord(t *testing.T) {
h, st, _ := newTestHandler(t)
st.SaveCustomerConfig(&store.CustomerConfig{CustomerID: "c1", APIKey: "ckey", RetrievalPassword: "pp"})
post := func(body string) {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/report", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer ckey")
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("report → %d (%s)", rr.Code, rr.Body.String())
}
}
post(`{"customer_id":"c1","stacks":{"deployed":["vikunja","immich"],"available":[]}}`)
before := time.Now().Add(-time.Minute)
// vikunja is gone; the box also holds an end record for an app the hub never saw, dated two years ago.
post(`{"customer_id":"c1","stacks":{"deployed":["immich"],"available":[]},"offsite":{"enabled":true,"ended_apps":[{"app":"oldapp","removed_at":"2024-01-01T00:00:00Z","ends_at":"2024-01-31T00:00:00Z"}]}}`)
m, err := st.AppPresences("c1")
if err != nil {
t.Fatal(err)
}
if !m["immich"].Present {
t.Fatalf("immich is listed: %+v", m)
}
for _, app := range []string{"vikunja", "oldapp"} {
p, ok := m[app]
if !ok || p.Present || p.AbsentSince.Before(before) || p.AbsentSince.After(time.Now().Add(time.Minute)) {
t.Fatalf("%s must be absent since NOW by the hub's clock (the box's 2024 date is not read): %+v ok=%v", app, p, ok)
}
}
// A report with no `stacks` object is not an empty app list: nothing becomes absent.
post(`{"customer_id":"c1"}`)
if m2, _ := st.AppPresences("c1"); !m2["immich"].Present {
t.Fatalf("a report without an app list made immich absent: %+v", m2)
}
}
// The window-open request carries the box's due end records to the service, whole.
func TestD84_WindowOpenCarriesTheEndedClaims(t *testing.T) {
h, st, _ := newTestHandler(t)
st.SaveCustomerConfig(&store.CustomerConfig{CustomerID: "c1", APIKey: "ckey", RetrievalPassword: "pp"})
f := &fakeKeySvc{}
h.SetOffsiteKeyService(f)
id := strings.Repeat("ab", 32)
req := httptest.NewRequest(http.MethodPost, "/api/v1/offsite/window-open/c1",
strings.NewReader(`{"count_before":20,"ended":[{"app":"vikunja","removed_at":"2026-10-01T00:00:00Z","ends_at":"2026-10-31T00:00:00Z","snapshot_ids":["`+id+`"]}]}`))
req.Header.Set("Authorization", "Bearer ckey")
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("window-open → %d (%s)", rr.Code, rr.Body.String())
}
if len(f.gotEnded) != 1 || f.gotEnded[0].App != "vikunja" || len(f.gotEnded[0].SnapshotIDs) != 1 || f.gotEnded[0].SnapshotIDs[0] != id {
t.Fatalf("the service did not receive the claim: %+v", f.gotEnded)
}
}
// The household's receipt is a type a box may send; the two hub-made records are not — no box can mint one.
func TestD84_EventTypes(t *testing.T) {
if !allowedEventTypes["offsite_end_scheduled"] {
t.Fatal("offsite_end_scheduled must be accepted from a box (POST /event would answer 400)")
}
if notify.IsOperatorOnly("offsite_end_scheduled") {
t.Fatal("the household's receipt must not be operator-only")
}
for _, et := range []string{"offsite_ended_app_removed", "offsite_ended_app_refused"} {
if allowedEventTypes[et] {
t.Fatalf("%s is hub-made: a box must not be able to POST it", et)
}
if !notify.IsOperatorOnly(et) {
t.Fatalf("%s must be operator-only", et)
}
}
}
+40
View File
@@ -481,6 +481,9 @@ func (h *Handler) handleReport(w http.ResponseWriter, r *http.Request) {
return
}
// D72 (`07` §8.2f part 4): the hub's own record of which apps this box runs, by the hub's clock.
h.noteAppList(payload.CustomerID, body)
// Parse and save app telemetry (backward-compatible — old controllers won't have this field)
var telemetryPayload struct {
AppTelemetry []store.AppTelemetryRecord `json:"app_telemetry"`
@@ -2490,6 +2493,10 @@ var allowedEventTypes = map[string]bool{
// — who, app, the restore's date, size. Operator-only (notify.operatorOnlyEvents) — registered in BOTH in the same
// commit.
"restore_copy_deleted": true,
// D84 (`09` §3 decision 309; `07` §8.2f): the household pressed „delete backup data” for an app — its off-site
// copies end 30 days later. A household RECEIPT (notify.householdReceiptEvents): mailed to the household's own
// address once per press, never to the operator; `mail.event.offsite_end_scheduled` in both bundles.
"offsite_end_scheduled": true,
// Special
"test": true,
}
@@ -3663,3 +3670,36 @@ func (h *Handler) recordHeldApp(customerID, eventType string, raw json.RawMessag
}
h.logger.Printf("[DEBUG] [held-apps] %s/%s held (%s since %s)", customerID, d.StackName, d.Reason, d.Since)
}
// noteAppList keeps the hub's own record of which apps a box runs (store.NoteAppList) from one controller report:
// `stacks.deployed` is the app list, `offsite.ended_apps` the apps the box holds a pending off-site end record for.
// A report with no `stacks` object changes nothing — an absent list is not an empty list. The box's dates in
// `ended_apps` are not read: the clock is the hub's (D72, `09` §3 decision 292).
func (h *Handler) noteAppList(customerID string, body []byte) {
var p struct {
Stacks *struct {
Deployed []string `json:"deployed"`
} `json:"stacks"`
Offsite *struct {
EndedApps []struct {
App string `json:"app"`
// The box's own dates. Carried on the wire for the operator's reading of a stored report; the
// hub decides by its own clock and never by these.
RemovedAt string `json:"removed_at"`
EndsAt string `json:"ends_at"`
} `json:"ended_apps"`
} `json:"offsite"`
}
if err := json.Unmarshal(body, &p); err != nil || p.Stacks == nil {
return
}
var claimed []string
if p.Offsite != nil {
for _, e := range p.Offsite.EndedApps {
claimed = append(claimed, e.App)
}
}
if err := h.store.NoteAppList(customerID, p.Stacks.Deployed, claimed, time.Now()); err != nil {
h.logger.Printf("[WARN] [api] report from %s: the hub's own app record could not be updated: %v", customerID, err)
}
}
+9 -4
View File
@@ -16,7 +16,7 @@ type OffsiteKeyService interface {
RegisterKey(ctx context.Context, customerID, pub string) (offsitekeys.InstallResult, error)
ConfirmKey(ctx context.Context, customerID, fp string) (int, error)
MoveAside(ctx context.Context, customerID string) (string, error)
OpenWindowFor(ctx context.Context, customerID string, countBefore int) (offsitekeys.WindowGrant, error)
OpenWindowFor(ctx context.Context, customerID string, countBefore int, ended ...offsitekeys.EndedClaim) (offsitekeys.WindowGrant, error)
CloseWindowFor(ctx context.Context, customerID string, r offsitekeys.WindowResult) error
RequestAbandon(ctx context.Context, customerID, path string) (offsitekeys.AbandonStatus, error)
CancelAbandon(customerID, by string) (int, error)
@@ -137,12 +137,17 @@ func (h *Handler) handleOffsiteWindowOpen(w http.ResponseWriter, r *http.Request
}
var req struct {
CountBefore int `json:"count_before"`
// D84: the box's pending end records that are due, each with the snapshot ids it would remove. The hub
// agrees per id from its OWN records (offsitekeys/ended.go); the box's dates decide nothing.
Ended []offsitekeys.EndedClaim `json:"ended"`
}
body, _ := io.ReadAll(io.LimitReader(r.Body, 4<<10))
// 1 MiB: a snapshot id is 64 characters, and a removed app can hold a few hundred snapshots. A body that is cut
// does not parse, and then nothing is claimed — the window is still decided on count_before 0, as before.
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
_ = json.Unmarshal(body, &req)
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
g, err := h.offsiteKeys.OpenWindowFor(ctx, customerID, req.CountBefore)
g, err := h.offsiteKeys.OpenWindowFor(ctx, customerID, req.CountBefore, req.Ended...)
if err != nil {
offsiteKeyErr(w, err)
return
@@ -156,7 +161,7 @@ func (h *Handler) handleOffsiteWindowClose(w http.ResponseWriter, r *http.Reques
return
}
var req offsitekeys.WindowResult
body, _ := io.ReadAll(io.LimitReader(r.Body, 8<<10))
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // D84: the result names the ended apps' removed ids
if err := json.Unmarshal(body, &req); err != nil || req.WindowID == 0 {
http.Error(w, "body must carry window_id", http.StatusBadRequest)
return
+6 -4
View File
@@ -52,9 +52,10 @@ func TestConsumePassword_RetiredReturnsNoPassword(t *testing.T) {
}
type fakeKeySvc struct {
gotPub string
gotFP string
err error
gotPub string
gotFP string
gotEnded []offsitekeys.EndedClaim
err error
}
func (f *fakeKeySvc) RegisterKey(_ context.Context, _ string, pub string) (offsitekeys.InstallResult, error) {
@@ -65,7 +66,8 @@ func (f *fakeKeySvc) ConfirmKey(_ context.Context, _ string, fp string) (int, er
f.gotFP = fp
return 1, f.err
}
func (f *fakeKeySvc) OpenWindowFor(context.Context, string, int) (offsitekeys.WindowGrant, error) {
func (f *fakeKeySvc) OpenWindowFor(_ context.Context, _ string, _ int, ended ...offsitekeys.EndedClaim) (offsitekeys.WindowGrant, error) {
f.gotEnded = ended
return offsitekeys.WindowGrant{Granted: false, Reason: "not due"}, f.err
}
func (f *fakeKeySvc) CloseWindowFor(context.Context, string, offsitekeys.WindowResult) error {