Files
felhom.eu/hub/internal/offsitekeys/ended.go
T
admin a63f5b2ba8 hub: the app record a box feeds is bounded — per household, per name (security review of the D72 commit)
A box could send 300 new invented app names in every report and the
household's presence rows grew with no end.

- At most 400 names per household. A new name above that takes the place of
  the oldest ABSENT name the same report does not claim; when there is none it
  is not stored. Said once in the hub's log, not per report.
- A name is stored only when it is shaped like an app name (64 characters,
  letters, digits, . _ -) and is not reserved (_shares, the marker, the box's
  infrastructure stacks) — from the app list and from an end record alike.
  The same check decides what a window may agree to.
- No age limit on a row, on purpose: an aged-out row would start a real ended
  app's 30 days again. Making room never makes an app eligible earlier.

Tests TestD72_AppRecord_* (a box that sends new names in 40 reports);
10 mutations seen red, 2 after a redo.

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

238 lines
9.8 KiB
Go

package offsitekeys
import (
"fmt"
"sort"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// D72 / D84 (`09` §3 decisions 292 and 309; `07-backup-architecture.md` §8.2f) — THE HUB AGREES FIRST.
//
// A box asks, at a window's open, to remove the off-site snapshots of apps the household removed with „delete backup
// data” 30 days ago. Those removals have their own allowance, outside the window's cap — and ONLY for snapshot ids
// this file agreed to. The agreement uses nothing the box says about time:
//
// 1. THE APP. The hub's own record (store.AppPresences, written from the box's reports by the hub's clock) must say
// the app has been absent from that box's app list for EndedAppAfter. An app the newest report lists, an app the
// hub has no record of, an app absent for a shorter time and a reserved name are refused, each with its reason.
// 2. THE ID. A snapshot id is agreed only when the hub's own listing of the repository (the 07:10 audit's stored
// baseline — names and upload times, read over the hub's own login) holds it AND shows it uploaded no later than
// the moment the hub first saw the app absent. An app that is gone makes no new snapshots, so a younger file can
// not be its copy. An id the box lists under two apps is agreed only when both apps are.
//
// WHAT THIS DOES NOT PROVE, said plainly: the hub cannot read a snapshot's tags (the repository is encrypted and the
// password never leaves the box — decision 68). A box that is taken over AND has one honestly ended app can name, under
// that app, other snapshots that are older than the app's end. Rule 2 bounds that to files older than 30 days; it does
// not close it. The same box could already remove half the store per week inside the cap.
// EndedAppAfter is how long the hub must have seen an app absent before it agrees (D72: the number of a restore copy).
const EndedAppAfter = 30 * 24 * time.Hour
const (
EventEndedAppRemoved = "offsite_ended_app_removed" // info: the off-site copies of a removed app are gone (per app)
EventEndedAppRefused = "offsite_ended_app_refused" // warning: a box claimed an end the hub's records do not show
maxEndedClaims = 50 // apps in one request
maxEndedClaimIDs = 5000 // snapshot ids in one request, all apps together
)
// EndedClaim is one pending end record as the box sends it at a window's open. RemovedAt and EndsAt are the BOX's
// dates: they are stored for the operator to read and are never used to decide.
type EndedClaim struct {
App string `json:"app"`
RemovedAt string `json:"removed_at,omitempty"`
EndsAt string `json:"ends_at,omitempty"`
SnapshotIDs []string `json:"snapshot_ids"`
}
// reservedEndedName: the shares pseudo-app, the tier's marker tag, the box's own infrastructure stacks and anything
// that has not the shape of an app name are never apps a household removes (`07` §8.2f, the edge-case table). The
// same two checks decide what the hub's app record stores at all (store.NoteAppList).
func reservedEndedName(app string) bool {
return !store.ValidPresenceApp(app) || store.ReservedPresenceApp(app)
}
// agreeEnded is the PURE decision. presence is the hub's own record; listing the hub's own stored listing (ok=false
// when there is none). It returns the agreed ids (sorted), the agreed ids per agreed app, and every refusal.
func agreeEnded(now time.Time, presence map[string]store.AppPresence, listing store.OffsiteSnapshotListing, haveListing bool, claims []EndedClaim) (ids []string, byApp map[string][]string, refused []store.EndedRefusal) {
if len(claims) > maxEndedClaims {
for _, c := range claims[maxEndedClaims:] {
refused = append(refused, store.EndedRefusal{App: c.App, Reason: fmt.Sprintf("more than %d apps in one request", maxEndedClaims)})
}
claims = claims[:maxEndedClaims]
}
agreedApp := map[string]time.Time{} // app → the hub's absent-since
refusedApp := map[string]bool{}
seen := map[string]bool{}
for _, c := range claims {
if seen[c.App] {
continue
}
seen[c.App] = true
reason := ""
p, known := presence[c.App]
switch {
case reservedEndedName(c.App):
reason = "not an app a household removes"
case !known:
reason = "the hub has no record of this app on this box"
case p.Present:
reason = "the box's newest report lists the app as installed"
case p.AbsentSince.IsZero():
reason = "the hub's record of when the app left cannot be read"
case now.Sub(p.AbsentSince) < EndedAppAfter:
reason = fmt.Sprintf("the hub has seen the app absent since %s — %d full day(s), %d needed",
p.AbsentSince.UTC().Format("2006-01-02 15:04 UTC"), int(now.Sub(p.AbsentSince).Hours()/24), int(EndedAppAfter.Hours()/24))
}
if reason != "" {
refusedApp[c.App] = true
refused = append(refused, store.EndedRefusal{App: c.App, Reason: reason})
continue
}
agreedApp[c.App] = p.AbsentSince
}
// The ids. An id is judged against EVERY app the box listed it under.
type idState struct {
latest time.Time // the earliest absent-since among its apps: the file must be older than every one
refused bool
}
states := map[string]*idState{}
var order []string
total := 0
for _, c := range claims {
for _, id := range c.SnapshotIDs {
total++
if total > maxEndedClaimIDs {
break
}
st, ok := states[id]
if !ok {
st = &idState{}
states[id] = st
order = append(order, id)
}
since, agreed := agreedApp[c.App]
if !agreed {
st.refused = true // listed under an app the hub refused: a living app's copy is never removed
continue
}
if st.latest.IsZero() || since.Before(st.latest) {
st.latest = since
}
}
}
byApp = map[string][]string{}
idRefusals := map[string]int{}
for _, id := range order {
st := states[id]
switch {
case st.refused:
idRefusals["listed under an app the hub refused"]++
continue
case !haveListing:
idRefusals["the hub has no listing of its own for this repository yet"]++
continue
}
at, listed := listing.Entries[id]
switch {
case !snapshotID.MatchString(id) || !listed:
idRefusals["not in the hub's own listing"]++
case at.IsZero():
idRefusals["no upload time in the hub's own listing"]++
case at.After(st.latest.Add(snapTimeSlack)):
idRefusals["uploaded after the hub saw the app leave"]++
default:
ids = append(ids, id)
for _, c := range claims {
if _, ok := agreedApp[c.App]; ok {
for _, cid := range c.SnapshotIDs {
if cid == id {
byApp[c.App] = append(byApp[c.App], id)
}
}
}
}
}
}
if total > maxEndedClaimIDs {
idRefusals[fmt.Sprintf("more than %d snapshot ids in one request", maxEndedClaimIDs)] += total - maxEndedClaimIDs
}
var reasons []string
for r := range idRefusals {
reasons = append(reasons, r)
}
sort.Strings(reasons)
for _, r := range reasons {
refused = append(refused, store.EndedRefusal{App: "", Reason: fmt.Sprintf("%d snapshot id(s) refused: %s", idRefusals[r], r)})
}
sort.Strings(ids)
return ids, byApp, refused
}
// clearDisagreement: a refusal the operator must hear about. A box that asks a little early (its clock is minutes or
// hours ahead of the hub's first sight of the absence) is refused quietly and asks again next week; a box that claims
// an end for an app it reports as installed, or that the hub has seen absent for less than 29 days, is not a matter of
// minutes — its clock is wrong by a day or more (R-1384), or it is not telling the truth.
func clearDisagreement(now time.Time, presence map[string]store.AppPresence, r store.EndedRefusal) bool {
if r.App == "" {
return false
}
p, known := presence[r.App]
// An installed app has no absence date (store.AppPresences), so the zero date covers it too.
if !known || p.AbsentSince.IsZero() {
return true
}
return now.Sub(p.AbsentSince) < EndedAppAfter-24*time.Hour
}
// agreeEndedFor runs the decision for one household against the store, and tells the operator about a clear
// disagreement. It never fails a window: with a store that cannot answer, nothing is agreed.
func (s *Service) agreeEndedFor(customerID string, claims []EndedClaim) (ids []string, byApp map[string][]string, refused []store.EndedRefusal) {
if len(claims) == 0 {
return nil, nil, nil
}
now := s.now()
presence, err := s.Store.AppPresences(customerID)
if err != nil {
s.logf("[WARN] offsitekeys: ended apps %s: the hub's own app record could not be read (%v) — nothing agreed", customerID, err)
for _, c := range claims {
refused = append(refused, store.EndedRefusal{App: c.App, Reason: "the hub's own app record could not be read"})
}
return nil, nil, refused
}
listing, have := s.Store.GetOffsiteSnapshotListing(customerID)
ids, byApp, refused = agreeEnded(now, presence, listing, have, claims)
s.logf("[INFO] offsitekeys: ended apps %s: %d app(s) claimed, %d app(s) with agreed snapshots, %d snapshot id(s) agreed, %d refusal(s)",
customerID, len(claims), len(byApp), len(ids), len(refused))
for _, r := range refused {
s.logf("[WARN] offsitekeys: ended apps %s: REFUSED %q: %s", customerID, r.App, r.Reason)
if clearDisagreement(now, presence, r) {
s.event(customerID, EventEndedAppRefused, "warning",
fmt.Sprintf("Off-site clean-up: the box of %s asked to remove the off-site copies of the removed app %q, and the hub's own records do not agree: %s. Nothing of that app was removed. Check the box's clock and its app list.",
customerID, r.App, r.Reason),
map[string]any{"subject": r.App, "app": r.App, "reason": r.Reason})
}
}
return ids, byApp, refused
}
// endedRemovedByApp groups the removed ids by the app the box listed them under, for the per-app operator record.
func endedRemovedByApp(claims map[string][]string, removed []string) map[string]int {
gone := make(map[string]bool, len(removed))
for _, id := range removed {
gone[id] = true
}
out := map[string]int{}
for app, ids := range claims {
for _, id := range ids {
if gone[id] {
out[app]++
}
}
}
return out
}