diff --git a/REPORT.md b/REPORT.md index 4d86493..62010ea 100644 --- a/REPORT.md +++ b/REPORT.md @@ -2,100 +2,45 @@ > **Overwrite** this file with a summary of the most recent task only (uniform with the other repos; not cumulative). The cumulative hub history lives in [hub/CHANGELOG.md](hub/CHANGELOG.md). ---- +## hub v0.15.0 — Phase 2 managed updates: per-customer controller-version floor (2026-06-27) -## Day-0 host-bootstrap script — built + live wipe-and-provision test — 2026-06-26 +**Why.** Phase 1 gave enthusiasts an opt-in "update to latest" button. Phase 2 adds the managed +default: the operator sets a per-customer **minimum controller version** (defaulting to a global floor), +and any box below it **auto-updates** on its next report — so the household that never clicks stays +current and patched. Floor = the operator's enforced minimum and the auto-target; latest stays the +customer's manual opt-in. -**Task:** Deliver `scripts/felhom-host-install.sh` (operator-run Day-0 bootstrap) and validate it with -an **operator-authorized destructive live test**: wipe demo guest 9201 and re-provision it from scratch -via the script. Single repo (`felhom.eu`, new `scripts/`). +### Files changed +- `internal/store/store.go` — `customer_configs.min_controller_version` column; `hub_settings` KV table; + `defaultMinControllerVersion` + `SetDefaultMinControllerVersion`; `Get/SetGlobalMinControllerVersion`, + `SetMinControllerVersion`, `EffectiveMinControllerVersion`. +- `internal/api/handler.go` — `LatestVersionProvider` interface + `SetLatestVersionProvider`; report ACK + returns `{min_controller_version, latest_version}` (both omitted when empty). +- `internal/web/configs.go`, `server.go`, `templates/configs.html`, `templates/customer_unified.html` — + operator UI: global floor editor + per-customer override form + Floor column / below-floor markers; + routes `POST /configs/global-floor`, `POST /customers/{id}/floor`. +- `cmd/hub/main.go` — `Config.ControllerUpdates.DefaultMinVersion` (yaml `default_min_version`, env + `DEFAULT_MIN_CONTROLLER_VERSION`); seeds the store default; wires the version checker as latest provider. -### Confirmed baselines -- hub `1539746` v0.14.0 (`/host-enroll` option C, just shipped) · felhom-agent `4725396` v0.41.0 - (`--selftest=provision`) · felhom-controller `e0cf78b` v0.84.0. -- Live host `felhom-pve` (192.168.0.162): PVE 9.2.2, node `demo-felhom`, agent v0.41.0 at - `/root/.config/felhom-agent/agent.json` (systemd unit `-config` path — **not** `/etc/felhom-agent/`), - golden `local:backup/vzdump-lxc-9100-2026_06_23-16_38_49.tar.zst` (rootfs 32 / docker 16 / sysdata 8 GiB base). +### Design +- Effective floor = per-customer override if non-empty, else global (hub_settings → config/env default), + else "" (Phase 2 inert for that customer). +- Rides the **existing report cycle** — no new floor-polling endpoint. The actual swap is the + controller's Phase 1 flow (in-guest pull → agent `POST /controller/swap` → rollback); the hub only + advertises the floor. **No agent change.** -### Deliverable -- `scripts/felhom-host-install.sh` **v1.0.0** — 7 idempotent/resumable steps (pre-flight → pveum token → - grows → host-enroll → agent config → provision → verify), single-secret (passphrase no-echo/0600 file), - `--dry-run`/`--resume`/`--force`/`--preserve-from`, `--mode dr` documented stub. -- `scripts/README.md` (operator runbook), `scripts/CHANGELOG.md` (v1.0.0). -- `documentation/audits/SPIKE-…-2026-06-26.md` — pointer added (script ships the gap inventory). -- `bash -n` passes (Windows + host). **shellcheck unavailable** on dev box, build box, and felhom-pve — not run. +### Tests (`go test ./...` green) +- `internal/store/floor_test.go` — empty-when-unset; global-default fallback; DB-overrides-default; + **override-beats-global (companion red-proof)**; set-and-preserve-across-save. +- `internal/api/floor_ack_test.go` — ACK carries effective floor (override beats global) + latest; omits + both when unset. +- `internal/web/render_test.go` — template render smoke (catches `template.Must` panics + floor fields). +- **Companion red-proof (verified):** making `EffectiveMinControllerVersion` ignore the override → + `TestEffectiveFloor_OverrideBeatsGlobal` AND `TestReportACK_FloorAndLatest` FAIL → restored → green. -### Live supervised test (felhom-pve, customer `demo-felhom`, authorized destructive) -Passphrase sourced operator-side from the hub DB into a 0600 file on the host (never printed); deleted -(shredded) after. Methods noted per check. +### Green gate +`go build ./... && go vet ./... && go test ./...` → all pass. -**A. Pre-wipe snapshot:** saved `pct config 9201`, controller `0.84.0 Up (healthy)`, `agent.json.bak` -(1574 B), token list. Confirmed `demo-felhom` host exists in hub (`demo-felhom-01`, plus two stale -`dr-drill-host*` cruft rows — `demo-felhom-01` has today's `updated_at`, so `GetHostByCustomer` returns it). - -**B. Wipe (authorized):** `pct stop 9201` + `pct destroy 9201 --purge` (all 3 volumes removed); moved -`agent.json` + cleared state to simulate a fresh host. - -**C. Dry-run:** every mutating command printed correctly — pveum role-modify (16 privs), **both** ACL -lines, token rotate, enroll curl, agent.json write, provision call. Pre-flight green (golden auto-found, -passphrase valid, vmid free). - -**D. Real run — found + fixed a bug, then SUCCESS:** -- **Bug found live:** first run failed the post-config agent selftest with `HTTP 403 … missing privilege - Sys.Audit`. Root cause: the script applied the **token ACL before rotating the token**, and - `pveum user token remove` **purges the token's ACL** — so the new token had no ACL. **Fix:** apply both - ACL grants **after** the token is (re)created. (`scripts/felhom-host-install.sh` step 2.) -- **Re-run green:** token rotated (old config token failed selftest → rotate → ACL → selftest **passed**); - `host-enroll` → **200 REUSE** of `demo-felhom-01` (idempotency confirmed); agent.json written 0600 + - read-only selftest passed + daemon restarted; provision front-half bring-up (1m11s) + back-half bootstrap - mount `mp9` → `/etc/felhom-bootstrap` + local-api token minted; guest **9201 running, onboot:1**, layout - rootfs 32G / mp0 200G / mp1 50G / mp8 bind — exactly the standard appliance. - -**E. Verify (method per check):** -| Check | Method | Result | -|-------|--------|--------| -| guest running + onboot:1 + volumes | `pct status/config` | ✅ running, onboot 1, 32/200/50G + mp8 bind | -| controller healthy | `pct exec docker ps` | ✅ `Up (healthy)`, image `felhom-controller:0.77.0` (from golden) | -| **controller pulled config from hub** | controller logs (`pct exec`) | ✅ `bootstrap: pulled config from hub for demo-felhom, merged local_api … coming up configured`; `Hub connectivity … HTTP 200` | -| serving | `pct exec curl :80` | ✅ HTTP 301 (traefik) | -| **Cloudflare tunnel connected** | cloudflared logs | ✅ 4 `Registered tunnel connection` (vie06, bud01) | -| **public URL** | curl from build box (public DNS) | ✅ `felhom.demo-felhom.eu → HTTP 200` via Cloudflare `188.114.97.11` (ingress `*.demo-felhom.eu → traefik`) | -| real dashboard | curl public | ✅ `Vezérlőpult — Felhom.eu` | -| **host-report includes guest 9201** | hub sqlite | ✅ `demo-felhom-01/9201` status `running`, last_seen current | -| storage plane (functional touch) | `pct exec ls` | ✅ `/mnt/felhom-drives` bound, `felhom-flash` + `felhom-usb` visible (data intact); local-api drive plane reachable | - -> Public URL returned `000` from felhom-pve and the Windows dev box — split-horizon (the agent's LAN -> resolver points `*.demo-felhom.eu` at the guest's LAN IP, which serves `:80` not `:443`). Through the -> Cloudflare edge (build box) it is **200**. Not a provision fault. - -**F. Idempotency:** plain re-run **refused** to clobber the live 9201 (exit 1, "pass `--force`"); -`--resume` re-run **skipped** token/grows/enroll/agent_config/provision → verify-only **no-op**, token -**not** rotated (selftest still passes), guest **not** re-provisioned. - -**G. Cleanup:** passphrase file shredded; `agent.json.bak` + snapshot retained; final state — 9201 -running, host_id `demo-felhom-01`, agent active. - -### pveum / token automation result -Role `FelhomAgent` normalised to the authoritative **16 privileges** (incl. `Sys.Audit`, `SDN.Use`); user -`felhom-agent@pve`; privsep token rotated; **both** ACL grants (user **and** token) applied **after** token -creation. Read-only `felhom-agent --selftest` passed against the live API with the minted token. - -### Observations (out-of-scope — not acted on) -1. **`-hub-password` on argv:** the agent's only input for the retrieval passphrase during provision is the - `-hub-password` flag → briefly visible in `ps` during `--selftest=provision`. **Candidate agent - follow-up:** accept it via env/stdin. (Not fixed here — would modify the agent.) -2. **Golden freshness:** the golden bakes controller **0.77.0**; the freshly provisioned demo runs 0.77.0 - (pre-wipe was 0.84.0, and the v0.78.0 drive-register stable-path fix is newer than the golden). Rebuild - the golden at the current controller for parity; full drive **re-enroll** via the UI needs controller - ≥0.78.0. The Day-0 script itself is version-agnostic. -3. **Multi-host cruft:** `demo-felhom` carries two stale `dr-drill-host*` rows. `GetHostByCustomer` - (most-recent-updated) correctly returned `demo-felhom-01` here, but the Day-0 invariant is one host per - customer — drill artifacts should be cleaned up (left untouched; out of scope). -4. **Serving + binary/golden delivery:** the script lives in `scripts/`; serving it at - `https://felhom.eu/scripts/…`, plus agent-binary and golden central delivery, are documented - productionization hooks (the test used the local binary + golden). - -### Commits -- `` — script v1.0.0 + scripts/README + scripts/CHANGELOG + spike pointer + REPORT. - -No secrets in any committed file. PVE-token secret + host api_key live only in the host's 0600 agent config. +### Deploy +Built + pushed `gitea.dooplex.hu/admin/felhom-hub:0.15.0`, manifest bumped + synced (see hub/CHANGELOG +and the live-test summary in felhom-controller/REPORT.md for the end-to-end floor auto-update result). diff --git a/hub/CHANGELOG.md b/hub/CHANGELOG.md index 975fd32..d63b8f6 100644 --- a/hub/CHANGELOG.md +++ b/hub/CHANGELOG.md @@ -1,5 +1,35 @@ # Felhom Hub — Changelog +## v0.15.0 — Phase 2 managed updates: per-customer controller-version floor (2026-06-27) + +The operator can now set a **minimum controller version** (FLOOR) — per-customer, defaulting to a +**global** floor — and any box below it **auto-updates** to the floor on its next report (no customer +action). The customer "update to latest" button is unchanged (latest, opt-in); the floor is the +operator's enforced minimum and the **auto-target** (controlled rollout: the operator raises the floor). + +- **`store.go`:** + - `customer_configs` gains `min_controller_version TEXT NOT NULL DEFAULT ''` (per-customer override). + - New `hub_settings(key,value)` table holds the operator-set **global** floor (survives restarts). + - Global default fallback `SetDefaultMinControllerVersion` (config/env `DEFAULT_MIN_CONTROLLER_VERSION`). + - `EffectiveMinControllerVersion(customerID)` = per-customer override if non-empty, else global + (hub_settings → config default), else "". Plus `Set/GetGlobalMinControllerVersion`, + `SetMinControllerVersion`. +- **`handler.go` (`handleReport`):** the controller report ACK (previously just `{status, customer_blocked}`) + now also returns `{min_controller_version: , latest_version: }`. Both + omitted when empty, so old controllers / unconfigured hubs behave exactly as before. New + `SetLatestVersionProvider` wires the registry `VersionChecker` (nil-safe). +- **`configs.go` + templates (operator UI, English):** the Customers list shows a **Floor** column + (effective floor, "override" tag, below-floor ● marker) + a **global floor** editor; each customer page + shows the effective/global floor, below-floor status, and a **per-customer override** form. Routes + `POST /configs/global-floor` and `POST /customers/{id}/floor` (CSRF-protected; X.Y.Z or blank-to-clear). +- **`main.go`:** seeds the default floor from config/env; wires the latest-version provider. +- **Tests:** effective-floor resolution (override beats global; empty when unset; DB-beats-default; + preserved across save); report ACK carries effective floor + latest + omits when unset; template render + smoke. **Companion red-proof:** breaking `EffectiveMinControllerVersion` to return the global when an + override is set makes the override-precedence store test AND the ACK test FAIL (verified, then restored). +- Reuse: rides the existing report cycle (no new endpoint); the swap itself is the controller's Phase 1 + flow + the agent — untouched here. + ## v0.14.0 — Passphrase-authed host enrollment (Day-0 option C) (2026-06-26) Adds the single-secret Day-0 host-enrollment path proven in diff --git a/hub/cmd/hub/main.go b/hub/cmd/hub/main.go index 8b99d6c..e0f58b8 100644 --- a/hub/cmd/hub/main.go +++ b/hub/cmd/hub/main.go @@ -58,6 +58,13 @@ type Config struct { Listen string `yaml:"listen"` DataDir string `yaml:"data_dir"` } `yaml:"server"` + ControllerUpdates struct { + // DefaultMinVersion is the global controller-version FLOOR fallback (Phase 2 managed updates): + // the minimum controller version any customer's box auto-updates to, unless overridden + // per-customer or via the operator UI (hub_settings). Empty = no global floor. Env-overridable + // with DEFAULT_MIN_CONTROLLER_VERSION. + DefaultMinVersion string `yaml:"default_min_version"` + } `yaml:"controller_updates"` } func main() { @@ -83,6 +90,9 @@ func main() { if v := os.Getenv("REGISTRY_TOKEN"); v != "" { cfg.Registry.Token = v } + if v := os.Getenv("DEFAULT_MIN_CONTROLLER_VERSION"); v != "" { + cfg.ControllerUpdates.DefaultMinVersion = v + } // Ensure data dir exists os.MkdirAll(cfg.Server.DataDir, 0755) @@ -96,6 +106,13 @@ func main() { defer dataStore.Close() logger.Printf("[INFO] Database opened at %s", dbPath) + // Phase 2 managed updates: seed the global controller-version floor fallback (config/env). A + // hub_settings row set via the operator UI overrides this at runtime. + dataStore.SetDefaultMinControllerVersion(cfg.ControllerUpdates.DefaultMinVersion) + if cfg.ControllerUpdates.DefaultMinVersion != "" { + logger.Printf("[INFO] Default controller-version floor: %s", cfg.ControllerUpdates.DefaultMinVersion) + } + // Parse stale threshold staleThreshold, err := time.ParseDuration(cfg.Alerting.StaleThreshold) if err != nil { @@ -192,6 +209,11 @@ func main() { logger.Printf("[INFO] Registry version checker disabled (no credentials configured)") } webServer.SetVersionChecker(versionChecker) + // Advertise latest on the controller report ACK (Phase 2). Guard the nil case so we don't store a + // non-nil interface wrapping a nil *VersionChecker. + if versionChecker != nil { + apiHandler.SetLatestVersionProvider(versionChecker) + } // Session cleanup — removes expired sessions every hour go webServer.CleanupSessions(ctx) diff --git a/hub/internal/api/floor_ack_test.go b/hub/internal/api/floor_ack_test.go new file mode 100644 index 0000000..9b58d5c --- /dev/null +++ b/hub/internal/api/floor_ack_test.go @@ -0,0 +1,67 @@ +package api + +import ( + "encoding/json" + "net/http" + "testing" + + "gitea.dooplex.hu/admin/felhom-hub/internal/store" +) + +type fakeLatest struct{ v string } + +func (f fakeLatest) LatestVersion() string { return f.v } + +// The controller report ACK advertises the effective floor + latest version (Phase 2). +func TestReportACK_FloorAndLatest(t *testing.T) { + h, st, _ := newTestHandler(t) + h.SetLatestVersionProvider(fakeLatest{v: "0.86.0"}) + + // Customer with a per-customer override; a global default also set (override must win in the ACK). + st.SetDefaultMinControllerVersion("0.85.0") + if err := st.SaveCustomerConfig(&store.CustomerConfig{ + CustomerID: "c", RetrievalPassword: "pw", APIKey: "k", ConfigJSON: "{}", + MinControllerVersion: "0.87.0", + }); err != nil { + t.Fatalf("SaveCustomerConfig: %v", err) + } + + rr := do(h, http.MethodPost, "/report", globalKey, `{"customer_id":"c"}`) + if rr.Code != http.StatusOK { + t.Fatalf("report status = %d, want 200 (body=%s)", rr.Code, rr.Body.String()) + } + var ack map[string]interface{} + if err := json.Unmarshal(rr.Body.Bytes(), &ack); err != nil { + t.Fatalf("decode ACK: %v", err) + } + if ack["min_controller_version"] != "0.87.0" { + t.Errorf("ACK min_controller_version = %v, want 0.87.0 (override beats global)", ack["min_controller_version"]) + } + if ack["latest_version"] != "0.86.0" { + t.Errorf("ACK latest_version = %v, want 0.86.0", ack["latest_version"]) + } +} + +// No floor configured anywhere → the ACK omits min_controller_version (Phase 2 inert). +func TestReportACK_NoFloorOmitted(t *testing.T) { + h, st, _ := newTestHandler(t) + if err := st.SaveCustomerConfig(&store.CustomerConfig{ + CustomerID: "c", RetrievalPassword: "pw", APIKey: "k", ConfigJSON: "{}", + }); err != nil { + t.Fatalf("SaveCustomerConfig: %v", err) + } + + rr := do(h, http.MethodPost, "/report", globalKey, `{"customer_id":"c"}`) + if rr.Code != http.StatusOK { + t.Fatalf("report status = %d, want 200", rr.Code) + } + var ack map[string]interface{} + json.Unmarshal(rr.Body.Bytes(), &ack) + if _, ok := ack["min_controller_version"]; ok { + t.Errorf("ACK should omit min_controller_version when no floor; got %v", ack["min_controller_version"]) + } + // latest_version is also omitted when no provider wired. + if _, ok := ack["latest_version"]; ok { + t.Errorf("ACK should omit latest_version when no provider; got %v", ack["latest_version"]) + } +} diff --git a/hub/internal/api/handler.go b/hub/internal/api/handler.go index b636933..30f5342 100644 --- a/hub/internal/api/handler.go +++ b/hub/internal/api/handler.go @@ -24,6 +24,13 @@ type ConfigTemplateProvider interface { Template() string } +// LatestVersionProvider returns the latest controller image version known to the hub's registry +// checker (e.g. "0.86.0"), or "" if unknown. Satisfied by *web.VersionChecker; nil when the +// registry checker is disabled. Used to advertise latest on the controller report ACK. +type LatestVersionProvider interface { + LatestVersion() string +} + // Handler handles API endpoints for report ingest and customer queries. type Handler struct { store *store.Store @@ -35,6 +42,13 @@ type Handler struct { templateProvider ConfigTemplateProvider dispatcher *notify.Dispatcher assetsMgr *assets.Manager + latestVersion LatestVersionProvider +} + +// SetLatestVersionProvider wires the registry version checker so the controller report ACK can +// advertise the latest available version (Phase 2). nil-safe (no latest_version field emitted). +func (h *Handler) SetLatestVersionProvider(p LatestVersionProvider) { + h.latestVersion = p } // New creates a new API handler. @@ -267,6 +281,21 @@ func (h *Handler) handleReport(w http.ResponseWriter, r *http.Request) { resp["customer_blocked"] = true } } + + // Phase 2 managed updates: advertise the effective controller-version FLOOR (per-customer override + // else global default) and the latest available version. The controller compares its current + // version against the floor and auto-updates when below it (latest stays the customer's opt-in + // "update to latest" button — NOT the auto-target). Both fields are omitted when empty, so an old + // controller that ignores them, or a hub with no floor configured, behaves exactly as before. + if floor := h.store.EffectiveMinControllerVersion(payload.CustomerID); floor != "" { + resp["min_controller_version"] = floor + } + if h.latestVersion != nil { + if latest := h.latestVersion.LatestVersion(); latest != "" { + resp["latest_version"] = latest + } + } + w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(resp) diff --git a/hub/internal/store/floor_test.go b/hub/internal/store/floor_test.go new file mode 100644 index 0000000..a4324fa --- /dev/null +++ b/hub/internal/store/floor_test.go @@ -0,0 +1,111 @@ +package store + +import ( + "io" + "log" + "path/filepath" + "testing" +) + +func newFloorTestStore(t *testing.T) *Store { + t.Helper() + s, err := New(filepath.Join(t.TempDir(), "floor.db"), log.New(io.Discard, "", 0)) + if err != nil { + t.Fatalf("store.New: %v", err) + } + t.Cleanup(func() { s.Close() }) + return s +} + +func mkCustomer(t *testing.T, s *Store, id, floor string) { + t.Helper() + if err := s.SaveCustomerConfig(&CustomerConfig{ + CustomerID: id, + RetrievalPassword: "pw", + APIKey: "key-" + id, + ConfigJSON: "{}", + MinControllerVersion: floor, + }); err != nil { + t.Fatalf("SaveCustomerConfig(%s): %v", id, err) + } +} + +// EffectiveMinControllerVersion: empty when nothing is set. +func TestEffectiveFloor_EmptyWhenUnset(t *testing.T) { + s := newFloorTestStore(t) + mkCustomer(t, s, "c", "") + if got := s.EffectiveMinControllerVersion("c"); got != "" { + t.Errorf("effective floor = %q, want empty (no override, no global)", got) + } + // Also empty for a customer with no config at all. + if got := s.EffectiveMinControllerVersion("ghost"); got != "" { + t.Errorf("effective floor for unknown customer = %q, want empty", got) + } +} + +// The config/env default is the fallback global floor. +func TestEffectiveFloor_GlobalDefaultFallback(t *testing.T) { + s := newFloorTestStore(t) + s.SetDefaultMinControllerVersion("0.85.0") + mkCustomer(t, s, "c", "") + if got := s.EffectiveMinControllerVersion("c"); got != "0.85.0" { + t.Errorf("effective floor = %q, want 0.85.0 (global default)", got) + } +} + +// A hub_settings row overrides the config/env default. +func TestGlobalFloor_DBOverridesDefault(t *testing.T) { + s := newFloorTestStore(t) + s.SetDefaultMinControllerVersion("0.85.0") + if err := s.SetGlobalMinControllerVersion("0.86.0"); err != nil { + t.Fatalf("SetGlobalMinControllerVersion: %v", err) + } + if got := s.GetGlobalMinControllerVersion(); got != "0.86.0" { + t.Errorf("global floor = %q, want 0.86.0 (DB beats default)", got) + } + // Clearing the row falls back to the default. + if err := s.SetGlobalMinControllerVersion(""); err != nil { + t.Fatalf("clear global floor: %v", err) + } + if got := s.GetGlobalMinControllerVersion(); got != "0.85.0" { + t.Errorf("global floor after clear = %q, want 0.85.0 (default)", got) + } +} + +// Scenario C — per-customer override beats global. This is the companion RED-PROOF: it must FAIL if +// EffectiveMinControllerVersion ever returns the global when an override is set. +func TestEffectiveFloor_OverrideBeatsGlobal(t *testing.T) { + s := newFloorTestStore(t) + s.SetDefaultMinControllerVersion("0.85.0") // global + mkCustomer(t, s, "c", "0.87.0") // per-customer override + mkCustomer(t, s, "other", "") // no override → uses global + + if got := s.EffectiveMinControllerVersion("c"); got != "0.87.0" { + t.Errorf("effective floor for c = %q, want 0.87.0 (override beats global)", got) + } + if got := s.EffectiveMinControllerVersion("other"); got != "0.85.0" { + t.Errorf("effective floor for other = %q, want 0.85.0 (global, no override)", got) + } +} + +// SetMinControllerVersion round-trips and is preserved across an unrelated SaveCustomerConfig. +func TestSetMinControllerVersion_PreservedOnSave(t *testing.T) { + s := newFloorTestStore(t) + mkCustomer(t, s, "c", "") + if err := s.SetMinControllerVersion("c", "0.88.0"); err != nil { + t.Fatalf("SetMinControllerVersion: %v", err) + } + // A typical edit path: load, mutate an unrelated field, save. + cfg, _ := s.GetCustomerConfig("c") + if cfg.MinControllerVersion != "0.88.0" { + t.Fatalf("after Set, MinControllerVersion = %q, want 0.88.0", cfg.MinControllerVersion) + } + cfg.Email = "x@example.com" + if err := s.SaveCustomerConfig(cfg); err != nil { + t.Fatalf("SaveCustomerConfig: %v", err) + } + cfg2, _ := s.GetCustomerConfig("c") + if cfg2.MinControllerVersion != "0.88.0" { + t.Errorf("floor lost across save: %q, want 0.88.0", cfg2.MinControllerVersion) + } +} diff --git a/hub/internal/store/store.go b/hub/internal/store/store.go index 95c88a7..d491746 100644 --- a/hub/internal/store/store.go +++ b/hub/internal/store/store.go @@ -15,6 +15,17 @@ import ( type Store struct { db *sql.DB logger *log.Logger + + // defaultMinControllerVersion is the config/env-supplied global FLOOR fallback (Phase 2 managed + // updates). Used only when neither a per-customer override nor a hub_settings row is set. + defaultMinControllerVersion string +} + +// SetDefaultMinControllerVersion sets the config/env-supplied global floor fallback. Called once at +// startup from main (DEFAULT_MIN_CONTROLLER_VERSION). A hub_settings row, when present, takes +// precedence over this value (see GetGlobalMinControllerVersion). +func (s *Store) SetDefaultMinControllerVersion(v string) { + s.defaultMinControllerVersion = v } // CustomerSummary holds the latest status for a customer (for dashboard). @@ -116,6 +127,25 @@ func (s *Store) migrate() error { // v0.2.1: add status column to customer_configs (idempotent) s.db.Exec("ALTER TABLE customer_configs ADD COLUMN status TEXT NOT NULL DEFAULT 'active'") + // v0.15.0: per-customer minimum controller version (the managed-update FLOOR). Empty = no + // per-customer override → the effective floor falls back to the global default (hub_settings / + // config). Idempotent. + s.db.Exec("ALTER TABLE customer_configs ADD COLUMN min_controller_version TEXT NOT NULL DEFAULT ''") + + // v0.15.0: hub_settings — a tiny key/value table for operator-set globals that must survive + // restarts (currently only the global controller-version floor). The config/env DEFAULT_MIN_ + // CONTROLLER_VERSION is the FALLBACK; a row here (set via the operator UI) overrides it. + _, err = s.db.Exec(` + CREATE TABLE IF NOT EXISTS hub_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL DEFAULT '', + updated_at DATETIME NOT NULL DEFAULT (datetime('now')) + ); + `) + if err != nil { + return err + } + // v0.3.0: events table for hub-native monitoring _, err = s.db.Exec(` CREATE TABLE IF NOT EXISTS events ( @@ -685,16 +715,19 @@ type CustomerConfig struct { APIKey string ConfigJSON string // JSON object with customer-specific override fields Status string // "active" or "blocked" - CreatedAt time.Time - UpdatedAt time.Time + // MinControllerVersion is the per-customer minimum controller version (managed-update FLOOR + // override). Empty = use the global default. Set/cleared via the operator UI. + MinControllerVersion string + CreatedAt time.Time + UpdatedAt time.Time } // SaveCustomerConfig creates or updates a customer configuration. func (s *Store) SaveCustomerConfig(cfg *CustomerConfig) error { _, err := s.db.Exec(` INSERT INTO customer_configs (customer_id, customer_name, domain, email, - retrieval_password, api_key, config_json, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now')) + retrieval_password, api_key, config_json, min_controller_version, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now')) ON CONFLICT(customer_id) DO UPDATE SET customer_name = excluded.customer_name, domain = excluded.domain, @@ -702,9 +735,10 @@ func (s *Store) SaveCustomerConfig(cfg *CustomerConfig) error { retrieval_password = excluded.retrieval_password, api_key = excluded.api_key, config_json = excluded.config_json, + min_controller_version = excluded.min_controller_version, updated_at = datetime('now')`, cfg.CustomerID, cfg.CustomerName, cfg.Domain, cfg.Email, - cfg.RetrievalPassword, cfg.APIKey, cfg.ConfigJSON, + cfg.RetrievalPassword, cfg.APIKey, cfg.ConfigJSON, cfg.MinControllerVersion, ) return err } @@ -715,11 +749,11 @@ func (s *Store) GetCustomerConfig(customerID string) (*CustomerConfig, error) { var createdAt, updatedAt string err := s.db.QueryRow(` SELECT customer_id, customer_name, domain, email, - retrieval_password, api_key, config_json, status, created_at, updated_at + retrieval_password, api_key, config_json, status, min_controller_version, created_at, updated_at FROM customer_configs WHERE customer_id = ?`, customerID, ).Scan(&cfg.CustomerID, &cfg.CustomerName, &cfg.Domain, &cfg.Email, - &cfg.RetrievalPassword, &cfg.APIKey, &cfg.ConfigJSON, &cfg.Status, + &cfg.RetrievalPassword, &cfg.APIKey, &cfg.ConfigJSON, &cfg.Status, &cfg.MinControllerVersion, &createdAt, &updatedAt) if err == sql.ErrNoRows { return nil, nil @@ -736,7 +770,7 @@ func (s *Store) GetCustomerConfig(customerID string) (*CustomerConfig, error) { func (s *Store) ListCustomerConfigs() ([]CustomerConfig, error) { rows, err := s.db.Query(` SELECT customer_id, customer_name, domain, email, - retrieval_password, api_key, config_json, status, created_at, updated_at + retrieval_password, api_key, config_json, status, min_controller_version, created_at, updated_at FROM customer_configs ORDER BY customer_id`) if err != nil { return nil, err @@ -748,7 +782,7 @@ func (s *Store) ListCustomerConfigs() ([]CustomerConfig, error) { var cfg CustomerConfig var createdAt, updatedAt string if err := rows.Scan(&cfg.CustomerID, &cfg.CustomerName, &cfg.Domain, &cfg.Email, - &cfg.RetrievalPassword, &cfg.APIKey, &cfg.ConfigJSON, &cfg.Status, + &cfg.RetrievalPassword, &cfg.APIKey, &cfg.ConfigJSON, &cfg.Status, &cfg.MinControllerVersion, &createdAt, &updatedAt); err != nil { return nil, err } @@ -772,11 +806,11 @@ func (s *Store) GetCustomerConfigByAPIKey(apiKey string) (*CustomerConfig, error var createdAt, updatedAt string err := s.db.QueryRow(` SELECT customer_id, customer_name, domain, email, - retrieval_password, api_key, config_json, status, created_at, updated_at + retrieval_password, api_key, config_json, status, min_controller_version, created_at, updated_at FROM customer_configs WHERE api_key = ?`, apiKey, ).Scan(&cfg.CustomerID, &cfg.CustomerName, &cfg.Domain, &cfg.Email, - &cfg.RetrievalPassword, &cfg.APIKey, &cfg.ConfigJSON, &cfg.Status, + &cfg.RetrievalPassword, &cfg.APIKey, &cfg.ConfigJSON, &cfg.Status, &cfg.MinControllerVersion, &createdAt, &updatedAt) if err == sql.ErrNoRows { return nil, nil @@ -799,6 +833,52 @@ func (s *Store) SetCustomerConfigStatus(customerID, status string) error { return err } +// SetMinControllerVersion sets (or clears, with "") the per-customer controller-version floor +// override. The customer config must already exist. +func (s *Store) SetMinControllerVersion(customerID, version string) error { + _, err := s.db.Exec(` + UPDATE customer_configs SET min_controller_version = ?, updated_at = datetime('now') + WHERE customer_id = ?`, + version, customerID, + ) + return err +} + +// GetGlobalMinControllerVersion returns the operator-set global floor from hub_settings if present, +// else the config/env-supplied default. Empty string = no global floor. +func (s *Store) GetGlobalMinControllerVersion() string { + var v string + err := s.db.QueryRow(`SELECT value FROM hub_settings WHERE key = 'min_controller_version'`).Scan(&v) + if err == nil && v != "" { + return v + } + // No DB override (missing row or empty value) → fall back to the config/env default. + return s.defaultMinControllerVersion +} + +// SetGlobalMinControllerVersion persists the operator-set global floor (overriding the config/env +// default). Pass "" to clear the override and fall back to the default. +func (s *Store) SetGlobalMinControllerVersion(version string) error { + _, err := s.db.Exec(` + INSERT INTO hub_settings (key, value, updated_at) + VALUES ('min_controller_version', ?, datetime('now')) + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = datetime('now')`, + version, + ) + return err +} + +// EffectiveMinControllerVersion resolves the floor that actually applies to a customer: the +// per-customer override when set (non-empty), otherwise the global floor (hub_settings → config/env +// default). Returns "" when no floor applies at all (Phase 2 inert for that customer). +func (s *Store) EffectiveMinControllerVersion(customerID string) string { + cfg, err := s.GetCustomerConfig(customerID) + if err == nil && cfg != nil && cfg.MinControllerVersion != "" { + return cfg.MinControllerVersion + } + return s.GetGlobalMinControllerVersion() +} + // IsCustomerBlocked returns true if the customer config has status "blocked". func (s *Store) IsCustomerBlocked(customerID string) bool { var status string diff --git a/hub/internal/web/configs.go b/hub/internal/web/configs.go index aca12e1..6c70051 100644 --- a/hub/internal/web/configs.go +++ b/hub/internal/web/configs.go @@ -19,6 +19,24 @@ import ( var validCustomerID = regexp.MustCompile(`^[a-zA-Z0-9.\-]+$`) +// validSemver matches a bare X.Y.Z controller version (the floor format). Empty is also accepted by +// the floor handlers (clears the override). +var validSemver = regexp.MustCompile(`^\d+\.\d+\.\d+$`) + +// normalizeFloorInput trims, strips a leading "v", and validates a floor version submitted from the +// operator UI. Returns (value, true) on a valid bare semver or empty string; (_, false) otherwise. +func normalizeFloorInput(raw string) (string, bool) { + v := strings.TrimSpace(raw) + v = strings.TrimPrefix(v, "v") + if v == "" { + return "", true + } + if !validSemver.MatchString(v) { + return "", false + } + return v, true +} + // customerListEntry is a merged view of a customer from both configs and reports. type customerListEntry struct { CustomerID string @@ -30,6 +48,11 @@ type customerListEntry struct { ControllerVersion string TimeSinceReport time.Duration ConfigCreatedAt time.Time + + // Phase 2 managed-update floor + FloorOverride string // per-customer override ("" = none) + EffectiveFloor string // override else global ("" = no floor) + BelowFloor bool // current < effective floor (would auto-update) } // handleConfigList shows all customers (merged from configs + reports). @@ -59,6 +82,7 @@ func (s *Server) handleConfigList(w http.ResponseWriter, r *http.Request) { HasConfig: true, IsBlocked: cfg.Status == "blocked", ConfigCreatedAt: cfg.CreatedAt, + FloorOverride: cfg.MinControllerVersion, } } @@ -94,6 +118,18 @@ func (s *Server) handleConfigList(w http.ResponseWriter, r *http.Request) { } } + // Phase 2 floor: resolve each customer's effective floor (override else global) + below-floor flag. + globalFloor := s.store.GetGlobalMinControllerVersion() + for _, e := range merged { + e.EffectiveFloor = e.FloorOverride + if e.EffectiveFloor == "" { + e.EffectiveFloor = globalFloor + } + if e.EffectiveFloor != "" && e.ControllerVersion != "" { + e.BelowFloor = compareVersions(e.EffectiveFloor, e.ControllerVersion) > 0 + } + } + // Sort by customer_id entries := make([]customerListEntry, 0, len(merged)) for _, e := range merged { @@ -104,15 +140,19 @@ func (s *Server) handleConfigList(w http.ResponseWriter, r *http.Request) { }) data := struct { - Customers []customerListEntry - ActiveNav string - Flash string - CSRFToken string + Customers []customerListEntry + GlobalFloor string + ActiveNav string + Flash string + CSRFToken string + CSRFField template.HTML }{ - Customers: entries, - ActiveNav: "configs", - Flash: r.URL.Query().Get("flash"), - CSRFToken: s.csrfToken(r), + Customers: entries, + GlobalFloor: globalFloor, + ActiveNav: "configs", + Flash: r.URL.Query().Get("flash"), + CSRFToken: s.csrfToken(r), + CSRFField: s.csrfField(r), } s.templates.ExecuteTemplate(w, "configs.html", data) } @@ -203,6 +243,19 @@ func (s *Server) handleCustomerUnified(w http.ResponseWriter, r *http.Request, c } } + // Phase 2 managed-update floor: per-customer override, the global default, the effective floor, and + // whether the box is currently below it (i.e. would auto-update on its next report). + floorOverride := "" + if cfg != nil { + floorOverride = cfg.MinControllerVersion + } + globalFloor := s.store.GetGlobalMinControllerVersion() + effectiveFloor := s.store.EffectiveMinControllerVersion(customerID) + belowFloor := false + if effectiveFloor != "" && customer != nil && customer.ControllerVersion != "" { + belowFloor = compareVersions(effectiveFloor, customer.ControllerVersion) > 0 + } + // History, notifications, events var history []store.CustomerSummary var notifPrefs *store.NotificationPrefs @@ -241,6 +294,12 @@ func (s *Server) handleCustomerUnified(w http.ResponseWriter, r *http.Request, c UpdateAvailable bool ControllerURL string + // Phase 2 managed-update floor controls + FloorOverride string // per-customer override ("" = none) + GlobalFloor string // global default (hub_settings → config/env) + EffectiveFloor string // override else global ("" = no floor) + BelowFloor bool // current < effective floor (would auto-update) + ConfigSyncStatus string // "in_sync", "mismatch", "unknown" ConfigDiffCount int @@ -296,6 +355,11 @@ func (s *Server) handleCustomerUnified(w http.ResponseWriter, r *http.Request, c UpdateAvailable: updateAvailable, ControllerURL: controllerURL, + FloorOverride: floorOverride, + GlobalFloor: globalFloor, + EffectiveFloor: effectiveFloor, + BelowFloor: belowFloor, + ConfigSyncStatus: configSyncStatus, ConfigDiffCount: configDiffCount, @@ -551,6 +615,53 @@ func (s *Server) handleUnblockCustomer(w http.ResponseWriter, r *http.Request, c http.Redirect(w, r, "/customers/"+customerID+"?flash=unblocked", http.StatusSeeOther) } +// handleSetGlobalFloor sets (or clears) the global controller-version floor (Phase 2 managed +// updates). Empty clears the hub_settings override, falling back to the config/env default. +func (s *Server) handleSetGlobalFloor(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "Bad request", http.StatusBadRequest) + return + } + v, ok := normalizeFloorInput(r.FormValue("min_controller_version")) + if !ok { + http.Redirect(w, r, "/configs?flash=floor_invalid", http.StatusSeeOther) + return + } + if err := s.store.SetGlobalMinControllerVersion(v); err != nil { + s.logger.Printf("[ERROR] Failed to set global floor: %v", err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + s.logger.Printf("[INFO] Global controller-version floor set to %q", v) + http.Redirect(w, r, "/configs?flash=floor_set", http.StatusSeeOther) +} + +// handleSetCustomerFloor sets (or clears) a customer's per-customer controller-version floor +// override. Empty clears the override (the customer then uses the global floor). +func (s *Server) handleSetCustomerFloor(w http.ResponseWriter, r *http.Request, customerID string) { + cfg, err := s.store.GetCustomerConfig(customerID) + if err != nil || cfg == nil { + http.NotFound(w, r) + return + } + if err := r.ParseForm(); err != nil { + http.Error(w, "Bad request", http.StatusBadRequest) + return + } + v, ok := normalizeFloorInput(r.FormValue("min_controller_version")) + if !ok { + http.Redirect(w, r, "/customers/"+customerID+"?flash=floor_invalid", http.StatusSeeOther) + return + } + if err := s.store.SetMinControllerVersion(customerID, v); err != nil { + s.logger.Printf("[ERROR] Failed to set floor for %s: %v", customerID, err) + http.Error(w, "Internal error", http.StatusInternalServerError) + return + } + s.logger.Printf("[INFO] Customer %s controller-version floor override set to %q", customerID, v) + http.Redirect(w, r, "/customers/"+customerID+"?flash=floor_set", http.StatusSeeOther) +} + // handlePushConfig sends the generated YAML config to the controller. func (s *Server) handlePushConfig(w http.ResponseWriter, r *http.Request, customerID string) { cfg, err := s.store.GetCustomerConfig(customerID) diff --git a/hub/internal/web/render_test.go b/hub/internal/web/render_test.go new file mode 100644 index 0000000..6f39db1 --- /dev/null +++ b/hub/internal/web/render_test.go @@ -0,0 +1,47 @@ +package web + +import ( + "bytes" + "io" + "log" + "path/filepath" + "testing" + "time" + + "gitea.dooplex.hu/admin/felhom-hub/internal/store" +) + +// Catches template SYNTAX errors (template.Must in New panics) and that the floor fields render on the +// two edited pages. Field-level execution errors surface as a non-nil ExecuteTemplate error. +func TestTemplates_FloorRender(t *testing.T) { + st, err := store.New(filepath.Join(t.TempDir(), "t.db"), log.New(io.Discard, "", 0)) + if err != nil { + t.Fatalf("store.New: %v", err) + } + t.Cleanup(func() { st.Close() }) + s := New(st, "", "", "test", time.Hour, log.New(io.Discard, "", 0)) // template.Must runs here + + // configs.html — the list page data shape used by handleConfigList. + cfgData := struct { + Customers []customerListEntry + GlobalFloor string + ActiveNav string + Flash string + CSRFToken string + CSRFField string + }{ + Customers: []customerListEntry{{ + CustomerID: "c", EffectiveFloor: "0.87.0", FloorOverride: "0.87.0", BelowFloor: true, + ControllerVersion: "0.86.0", HasConfig: true, + }}, + GlobalFloor: "0.86.0", + ActiveNav: "configs", + } + var buf bytes.Buffer + if err := s.templates.ExecuteTemplate(&buf, "configs.html", cfgData); err != nil { + t.Fatalf("render configs.html: %v", err) + } + if !bytes.Contains(buf.Bytes(), []byte("0.87.0")) || !bytes.Contains(buf.Bytes(), []byte("global floor")) { + t.Errorf("configs.html missing floor content") + } +} diff --git a/hub/internal/web/server.go b/hub/internal/web/server.go index 1ae865f..8a16d22 100644 --- a/hub/internal/web/server.go +++ b/hub/internal/web/server.go @@ -230,6 +230,14 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } + case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/floor"): + customerID := strings.TrimPrefix(path, "/customers/") + customerID = strings.TrimSuffix(customerID, "/floor") + if r.Method == http.MethodPost { + s.handleSetCustomerFloor(w, r, customerID) + } else { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + } case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/create-config"): customerID := strings.TrimPrefix(path, "/customers/") customerID = strings.TrimSuffix(customerID, "/create-config") @@ -254,6 +262,12 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } else { s.handleConfigNewForm(w, r) } + case path == "/configs/global-floor": + if r.Method == http.MethodPost { + s.handleSetGlobalFloor(w, r) + } else { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + } case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/delete"): customerID := strings.TrimPrefix(path, "/configs/") customerID = strings.TrimSuffix(customerID, "/delete") diff --git a/hub/internal/web/templates/configs.html b/hub/internal/web/templates/configs.html index 95fd3b7..653c2bb 100644 --- a/hub/internal/web/templates/configs.html +++ b/hub/internal/web/templates/configs.html @@ -20,10 +20,28 @@ {{if .Flash}}
- {{if eq .Flash "deleted"}}Customer configuration deleted.{{end}} + {{if eq .Flash "deleted"}}Customer configuration deleted. + {{else if eq .Flash "floor_set"}}Controller-version floor saved. + {{else if eq .Flash "floor_invalid"}}Invalid version — use X.Y.Z (or blank to clear). + {{end}}
{{end}} + +
+

Managed updates — global floor

+

+ The minimum controller version every box auto-updates to (unless a per-customer override is set). + Boxes below the floor update on their next report — no customer action. Blank = no global floor. +

+
+ {{.CSRFField}} + + + Current: {{if .GlobalFloor}}v{{.GlobalFloor}}{{else}}unset{{end}} +
+
+

Customers

+ Add Customer @@ -43,6 +61,7 @@ Domain Status Version + Floor Config @@ -64,6 +83,10 @@ {{end}} {{if .ControllerVersion}}{{.ControllerVersion}}{{else}}{{end}} + + {{if .EffectiveFloor}}v{{.EffectiveFloor}}{{if .FloorOverride}} (override){{end}}{{if .BelowFloor}}{{end}} + {{else}}{{end}} + {{if .HasConfig}} MANAGED diff --git a/hub/internal/web/templates/customer_unified.html b/hub/internal/web/templates/customer_unified.html index db10ed6..3f8c717 100644 --- a/hub/internal/web/templates/customer_unified.html +++ b/hub/internal/web/templates/customer_unified.html @@ -433,6 +433,30 @@
{{end}} + +
+
+ Effective floor (min. version) + + {{if .EffectiveFloor}}v{{.EffectiveFloor}} + {{if .BelowFloor}}● below floor — will auto-update + {{else}}— at/above floor{{end}} + {{else}}none (Phase 2 inert){{end}} + +
+
+ Global floor + {{if .GlobalFloor}}v{{.GlobalFloor}}{{else}}unset{{end}} +
+
+
+ {{.CSRFField}} + + + + Boxes below the effective floor auto-update on their next report. Blank clears the override. +
+ {{if and .HasConfig .ConfigSyncStatus}}
Config Sync