Files
felhom.eu/hub/internal/store/offsite_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

332 lines
13 KiB
Go

package store
import (
"database/sql"
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
"time"
)
// D72 / D84 (`09` §3 decisions 292 and 309; `07-backup-architecture.md` §8.2f part 4) — THE HUB'S OWN RECORD of which
// apps a box runs, kept by the hub's clock. A box may ask a clean-up window to remove the off-site snapshots of an app
// the household removed 30 days ago; the hub agrees only when THIS table says the app has been absent from that box's
// reported app list for 30 days. The box's own dates are never read for that.
//
// One row per (household, app) the hub has seen in a report's `stacks.deployed`, or that the box named in a pending
// end record. `absent_since` is the hub's time of the FIRST report that did not list the app; it is cleared the moment
// a report lists the app again (an install ends every claim). Rows go with the household (residueQueries,
// orphanTables).
// migrateOffsiteEnded creates the presence table and the three window columns. Idempotent.
func (s *Store) migrateOffsiteEnded() error {
if _, err := s.db.Exec(`
CREATE TABLE IF NOT EXISTS offsite_app_presence (
customer_id TEXT NOT NULL,
app TEXT NOT NULL,
absent_since TEXT,
PRIMARY KEY (customer_id, app)
);`); err != nil {
return fmt.Errorf("offsite_app_presence: %w", err)
}
// What the hub agreed to at the open, what it refused, and what the box then named as removed (only ids the hub
// agreed to are kept). JSON text; NULL on every window that had no ended app.
s.db.Exec("ALTER TABLE offsite_windows ADD COLUMN ended_agreed TEXT")
s.db.Exec("ALTER TABLE offsite_windows ADD COLUMN ended_refused TEXT")
s.db.Exec("ALTER TABLE offsite_windows ADD COLUMN ended_removed TEXT")
s.db.Exec("ALTER TABLE offsite_windows ADD COLUMN ended_apps TEXT") // agreed app → its agreed ids (the per-app record)
return nil
}
// AppPresence is the hub's record of one app on one box.
type AppPresence struct {
// Present: the newest report lists the app.
Present bool
// AbsentSince is the hub's time of the first report without the app (zero while Present).
AbsentSince time.Time
}
// A box's lists are the box's own word, so the record is bounded three ways (security review of 2026-11-15):
//
// 1. ONE REPORT may name at most maxPresenceApps apps in each list.
// 2. A NAME is stored only when it has the shape of an app name (ValidPresenceApp) and is not reserved
// (ReservedPresenceApp: the shares pseudo-app, the tier's marker, the box's own infrastructure stacks).
// 3. ONE HOUSEHOLD holds at most maxPresenceRows rows. A new name above that first takes the place of the oldest
// ABSENT row that the same report does not name in a pending end record; when there is no such row the new name
// is not stored, and the hub says so in its log once per household (not per report).
//
// THERE IS NO AGE LIMIT ON A ROW, on purpose. An absent row is what makes a real ended app eligible exactly 30 days
// after the hub saw it leave; a row that aged out would start that clock again at the next claim — LATER than the
// household was told. So a row leaves only with the household (PurgeCustomerResidue, PurgeOrphanRows), by an install
// of the app (it becomes present), or by rule 3. Rule 3 can never make an app eligible EARLIER: an evicted app has no
// row, a claim for it starts a new clock at that moment, and 30 days are counted from there. It can make one LATER —
// only for a household that has passed maxPresenceRows names AND whose report did not carry the claim (its off-site
// tier was off). A row is ~60 bytes; 400 rows per household is the whole cost.
const (
maxPresenceApps = 300
maxPresenceRows = 400
maxPresenceName = 64
)
// ValidPresenceApp: the shape of an app (stack) name — 1..64 of letters, digits, `.`, `_`, `-`, starting with a
// letter or a digit. Anything else a box sends is not stored and can never be agreed.
func ValidPresenceApp(app string) bool {
if app == "" || len(app) > maxPresenceName {
return false
}
for i, r := range app {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
case i > 0 && (r == '.' || r == '_' || r == '-'):
default:
return false
}
}
return true
}
// reservedPresenceApps are names that are never an app a household removes: the tier's marker tag and the box's own
// infrastructure stacks (the controller's protected list: `controller.yaml.default` plus its always-protected
// `samba`). The shares pseudo-app `_shares` is refused by its shape already (ValidPresenceApp).
var reservedPresenceApps = map[string]bool{
"felhom-offbox": true, "traefik": true, "cloudflared": true, "felhom-controller": true, "filebrowser": true,
"samba": true, "felhom-samba": true,
}
// ReservedPresenceApp reports a reserved name (case does not matter, as on the box).
func ReservedPresenceApp(app string) bool { return reservedPresenceApps[strings.ToLower(app)] }
// NoteAppList updates the record from ONE report: `deployed` is the report's app list, `claimed` the apps the box
// names in pending off-site end records. now is the HUB's clock.
//
// - an app in `deployed` is present (its absence, if any, is forgotten);
// - an app the hub knew as present and that is not in `deployed` is absent since now;
// - a claimed app the hub has NO row for and that is not in `deployed` gets a row, absent since now — the hub's
// clock for an app removed before the hub kept this record starts when the hub first hears the claim, never at a
// date the box names.
//
// It writes only when something changes, so a steady box costs one read per report.
func (s *Store) NoteAppList(customerID string, deployed, claimed []string, now time.Time) error {
if customerID == "" {
return fmt.Errorf("NoteAppList: empty customer_id")
}
if len(deployed) > maxPresenceApps {
deployed = deployed[:maxPresenceApps]
}
if len(claimed) > maxPresenceApps {
claimed = claimed[:maxPresenceApps]
}
cur, err := s.AppPresences(customerID)
if err != nil {
return err
}
stamp := now.UTC().Format(time.RFC3339)
in := make(map[string]bool, len(deployed))
isClaimed := make(map[string]bool, len(claimed))
for _, app := range claimed {
isClaimed[app] = true
}
type change struct {
app string
absent sql.NullString
}
var changes, added []change // changes touch a row that exists; added need a NEW row (rule 3)
for _, app := range deployed {
if !ValidPresenceApp(app) || ReservedPresenceApp(app) || in[app] {
continue
}
in[app] = true
if p, ok := cur[app]; !ok {
added = append(added, change{app: app})
} else if !p.Present {
changes = append(changes, change{app: app})
}
}
for app, p := range cur {
if p.Present && !in[app] {
changes = append(changes, change{app: app, absent: sql.NullString{String: stamp, Valid: true}})
}
}
seen := map[string]bool{}
for _, app := range claimed {
if !ValidPresenceApp(app) || ReservedPresenceApp(app) || in[app] || seen[app] {
continue
}
seen[app] = true
if _, ok := cur[app]; !ok {
added = append(added, change{app: app, absent: sql.NullString{String: stamp, Valid: true}})
}
}
// Rule 3: the household's row limit. Room is made only from absent rows this report does not claim, oldest first.
var evict []string
refusedNew := 0
if over := len(cur) + len(added) - maxPresenceRows; over > 0 {
type old struct {
app string
since time.Time
}
var free []old
for app, p := range cur {
if !p.Present && !in[app] && !isClaimed[app] {
free = append(free, old{app, p.AbsentSince})
}
}
sort.Slice(free, func(i, j int) bool {
if !free[i].since.Equal(free[j].since) {
return free[i].since.Before(free[j].since)
}
return free[i].app < free[j].app
})
for i := 0; i < len(free) && i < over; i++ {
evict = append(evict, free[i].app)
}
if short := over - len(evict); short > 0 {
refusedNew = short
added = added[:len(added)-short] // the report's app list first, then its claims: the tail goes
}
}
s.notePresenceFull(customerID, refusedNew, len(evict))
changes = append(changes, added...)
if len(changes) == 0 && len(evict) == 0 {
return nil
}
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
for _, app := range evict {
if _, err := tx.Exec(`DELETE FROM offsite_app_presence WHERE customer_id = ? AND app = ?`, customerID, app); err != nil {
return fmt.Errorf("NoteAppList %s/%s: %w", customerID, app, err)
}
}
for _, c := range changes {
if _, err := tx.Exec(`INSERT INTO offsite_app_presence (customer_id, app, absent_since) VALUES (?, ?, ?)
ON CONFLICT(customer_id, app) DO UPDATE SET absent_since = excluded.absent_since`, customerID, c.app, c.absent); err != nil {
return fmt.Errorf("NoteAppList %s/%s: %w", customerID, c.app, err)
}
}
return tx.Commit()
}
// presenceFull remembers, per household, that the row limit was said in the log — so a box that sends new names in
// every report gives ONE line, not one per report. In memory: a hub restart says it once more.
var (
presenceFullMu sync.Mutex
presenceFull = map[string]bool{}
)
func (s *Store) notePresenceFull(customerID string, refusedNew, evicted int) {
presenceFullMu.Lock()
defer presenceFullMu.Unlock()
if refusedNew == 0 && evicted == 0 {
delete(presenceFull, customerID)
return
}
if presenceFull[customerID] {
return
}
presenceFull[customerID] = true
if s.logger != nil {
s.logger.Printf("[WARN] offsite app record for %s is at its limit of %d names: this report took the place of %d old absent name(s) and %d new name(s) were NOT stored. A box does not run that many apps — look at what it reports. (Said once; not repeated per report.)",
customerID, maxPresenceRows, evicted, refusedNew)
}
}
// AppPresences returns the hub's record for one household, by app.
func (s *Store) AppPresences(customerID string) (map[string]AppPresence, error) {
rows, err := s.db.Query(`SELECT app, absent_since FROM offsite_app_presence WHERE customer_id = ?`, customerID)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]AppPresence{}
for rows.Next() {
var app string
var absent sql.NullString
if err := rows.Scan(&app, &absent); err != nil {
return nil, err
}
p := AppPresence{Present: !absent.Valid || absent.String == ""}
if !p.Present {
// A date that cannot be read stays the zero time, and the caller REFUSES an absent app with a zero
// AbsentSince: an unreadable date is never "absent long ago".
if t, perr := time.Parse(time.RFC3339, absent.String); perr == nil {
p.AbsentSince = t
}
}
out[app] = p
}
return out, rows.Err()
}
// EndedRefusal is one app the hub refused in a window, with the reason in plain words.
type EndedRefusal struct {
App string `json:"app"`
Reason string `json:"reason"`
}
// SetOffsiteWindowEnded records, on the window's own row, the snapshot ids the hub agreed to for ended apps and the
// apps it refused. Called once, at the open.
func (s *Store) SetOffsiteWindowEnded(id int64, agreed []string, byApp map[string][]string, refused []EndedRefusal) error {
var a, r, m sql.NullString
if len(byApp) > 0 {
b, _ := json.Marshal(byApp)
m = sql.NullString{String: string(b), Valid: true}
}
if len(agreed) > 0 {
b, _ := json.Marshal(agreed)
a = sql.NullString{String: string(b), Valid: true}
}
if len(refused) > 0 {
b, _ := json.Marshal(refused)
r = sql.NullString{String: string(b), Valid: true}
}
_, err := s.db.Exec(`UPDATE offsite_windows SET ended_agreed = ?, ended_refused = ?, ended_apps = ? WHERE id = ?`, a, r, m, id)
return err
}
// SetOffsiteWindowEndedRemoved records which agreed ids the box named as removed. The caller passes only ids the hub
// agreed to; this function checks it again against the row, so an id the hub never agreed to can not be stored.
func (s *Store) SetOffsiteWindowEndedRemoved(id int64, removed []string) ([]string, error) {
w, err := s.GetOffsiteWindow(id)
if err != nil || w == nil {
return nil, fmt.Errorf("SetOffsiteWindowEndedRemoved: window %d: %v", id, err)
}
ok := make(map[string]bool, len(w.EndedAgreed))
for _, a := range w.EndedAgreed {
ok[a] = true
}
var kept []string
dup := map[string]bool{}
for _, r := range removed {
if ok[r] && !dup[r] {
dup[r] = true
kept = append(kept, r)
}
}
sort.Strings(kept)
var v sql.NullString
if len(kept) > 0 {
b, _ := json.Marshal(kept)
v = sql.NullString{String: string(b), Valid: true}
}
if _, err := s.db.Exec(`UPDATE offsite_windows SET ended_removed = ? WHERE id = ?`, v, id); err != nil {
return nil, err
}
return kept, nil
}
func jsonStrings(v sql.NullString) []string {
if !v.Valid || v.String == "" {
return nil
}
var out []string
if json.Unmarshal([]byte(v.String), &out) != nil {
return nil
}
return out
}