Files
felhom-agent/internal/hub/contract_test.go
T
admin 14642e3c7b v0.119.0 — the host report carries the box's addresses
A managed box's IP was invisible in every operator surface because nothing
reported one: HostMetrics carried node/cpu/mem/disk/load/uptime/temp/wrapper-sha
and no address of any kind. The hub could not show a host's LAN IP anywhere.

Two things that looked like the answer are traps, both checked before writing
code: lan_resolver.host_ip is an OPTIONAL config value absent unless that feature
is configured, and DeriveHostIP(local_api.listen_addr) returns 169.254.253.1 —
since R-50 the local API binds a link-local address identical on every box. Both
would have produced a confident wrong answer.

New wire field addresses[], one entry per (interface, address). Deliberately
iface+cidr rather than a single lan_ip: a Proxmox host legitimately holds several
(management bridge, tailnet, WG tunnel) and picking one to call "the" LAN IP is a
guess the agent is not entitled to make — silently wrong on a box whose bridge is
not vmbr0. The agent reports what exists; the hub does the labelling.

The filter is one predicate, chosen by MEASURING both demo hosts rather than by
reasoning about interface names. IsGlobalUnicast() alone drops loopback, IPv6
link-local (one per bridge, pure noise) and IPv4 link-local (169.254/16 — exactly
the island address above). It needs no veth/fwbr/tap denylist: that per-guest
plumbing carries no IP at all and self-excludes, verified on both boxes.

No new privilege and no block I/O — net.Interfaces() is a netlink/procfs read, so
the sudoers fence is untouched and the health-check rule is honoured.

The seam DEFAULTS to the real enumerator, inverting the nil-reporter-means-off
convention: this stanza has no config gate, so a forgotten wiring call would have
shipped it silently empty — the inert-seam failure recorded four times here.

Cross-repo: the golden is duplicated byte-identically in felhom.eu and the
contract test fails on top-level key drift, so both goldens moved together and
addresses[0]'s key set is asserted bidirectionally. The field marshals as [],
never null — the repo's own no-nulls invariant caught that on the first run.

Tests +9; three red-proofs (global-unicast filter, down-interface guard, inert
collectAddresses) each run, observed failing, and reverted.
2026-07-31 08:40:58 +02:00

164 lines
6.9 KiB
Go

package hub
import (
"encoding/json"
"os"
"reflect"
"sort"
"testing"
)
// The host-report shape is a contract DUPLICATED across two repos (no shared types
// module yet). testdata/host-report.golden.json MUST be kept byte-identical with
// felhom-hub's hub/internal/api/testdata/host-report.golden.json. This test fails
// if a json tag on HostReport/HostMetrics/Guest is renamed/added/removed relative
// to the golden, catching silent drift before slices 5/6 populate the empty
// collections. (Promote to a shared types module when those land.)
func TestHostReport_ContractMatchesGolden(t *testing.T) {
raw, err := os.ReadFile("testdata/host-report.golden.json")
if err != nil {
t.Fatal(err)
}
var golden map[string]any
if err := json.Unmarshal(raw, &golden); err != nil {
t.Fatalf("golden is not valid JSON: %v", err)
}
// A constructed report mirroring the golden's populated shape: guests[0] has spec,
// storage_targets[0] is an lvmthin (so its thin_pool + smart sub-objects are exercised).
report := &HostReport{
HostID: "demo-host-01", ReportedAt: "2026-06-08T12:00:00Z", AgentVersion: "0.3.1",
Host: HostMetrics{Node: "demo-felhom", LoadAvg: []string{"0.10"}},
Guests: []Guest{
{VMID: 100, Name: "a", Status: "running", ControllerVersion: "", Spec: &GuestSpec{Cores: 2}},
{VMID: 101, Name: "b", Status: "stopped", ControllerVersion: ""},
},
StorageTargets: []StorageTarget{
{
Name: "local-lvm", Type: StorageTypeLVMThin, DurableID: "pve/data",
State: StorageStateAttached, Reachable: true, ClassHint: "fast",
ThinPool: &ThinPoolFill{DataUsedFraction: 0.42},
Smart: SmartSummary{Health: SmartUnknown},
},
{
Name: "usb-backup", Type: StorageTypeUSB, DurableID: "uuid:x",
State: StorageStateAttached, Reachable: true, MountPath: "/mnt/usb-backup", TotalBytes: 2000000000000,
Smart: SmartSummary{Health: SmartUnknown},
},
// A pbs target so the recipe's pbs coord has a storage.cfg row to resolve its namespace
// from (R-106). Without one the fixture produces namespace_state=unknown while the golden
// pins a resolved coord — key-set-equal but semantically a fiction.
{
Name: "felhom-pbs", Type: StorageTypePBS, DurableID: "repo+fp", Content: "backup",
State: StorageStateAttached, Reachable: true, PBSNamespace: "felhom-spike",
Smart: SmartSummary{Health: SmartUnknown},
},
},
Backups: []Backup{
{
TargetID: "local", VMID: 9001, Archive: "local:backup/x.tar.zst", Mode: "snapshot",
CrashConsistent: true, SizeBytes: 1, Success: true, StartedAt: "2026-06-09T11:00:00Z",
DurationSeconds: 1, UncoveredVolumes: []string{"/mnt/bulk"},
},
},
RestoreTests: []RestoreTest{
{
SourceArchive: "local:backup/x.tar.zst", SourceTier: "local", ScratchVMID: 990000,
Pass: true, Verified: "boot+running", TestedAt: "2026-06-09T11:05:00Z", DurationSeconds: 1,
// slice-7 (v0.7.0): warnings + warnings_recognized must appear in the marshaled
// shape so the bidirectional key-set guard exercises the new wire keys.
Warnings: []string{"WARN: Systemd 257 detected. You may need to enable nesting."},
WarningsRecognized: true,
},
},
PBSSnapshots: []PBSSnapshot{
{
Namespace: "root", BackupType: "ct", BackupID: "9001", BackupTime: "2026-06-09T14:18:33Z",
SizeBytes: 1, Owner: "felhom@pbs!n100", Protected: false, Encrypted: true,
VerifyState: "ok", VerifyUPID: "UPID:dooplex:x:verify:felhom-spike:u:",
},
},
AuditTail: []AuditEntry{},
Cloudflared: Cloudflared{Status: "active"},
// v0.119.0: host addresses. Populated so the bidirectional key-set guard exercises the new
// element keys, not just the presence of the array.
Addresses: []HostAddress{{Iface: "vmbr0", CIDR: "192.168.0.162/24"}},
}
// dr_recipe host-half: built from the same guest/storage/pbs facts (the production path).
report.DRRecipe = BuildDRRecipeHostHalf(report.Guests, report.StorageTargets, report.PBSSnapshots,
ConfiguredBackupTarget{StorageID: "usb-backup", Known: true})
b, _ := json.Marshal(report)
var got map[string]any
json.Unmarshal(b, &got)
assertSameKeys(t, "<top>", golden, got)
assertSameKeys(t, "host", golden["host"], got["host"])
assertSameKeys(t, "guests[0]",
firstElem(golden["guests"]), firstElem(got["guests"]))
// storage_targets[0] is the slice-5 addition — assert its full key set and both
// sub-objects (smart always present; thin_pool present for the lvmthin element).
gst := firstElem(golden["storage_targets"])
sst := firstElem(got["storage_targets"])
assertSameKeys(t, "storage_targets[0]", gst, sst)
assertSameKeys(t, "storage_targets[0].smart", field(gst, "smart"), field(sst, "smart"))
assertSameKeys(t, "storage_targets[0].thin_pool", field(gst, "thin_pool"), field(sst, "thin_pool"))
// slice-6 additions — backups[0] / restore_tests[0] key sets (the bidirectional guard).
assertSameKeys(t, "backups[0]", firstElem(golden["backups"]), firstElem(got["backups"]))
assertSameKeys(t, "restore_tests[0]", firstElem(golden["restore_tests"]), firstElem(got["restore_tests"]))
// slice-6-Phase-B addition — pbs_snapshots[0] key set.
assertSameKeys(t, "pbs_snapshots[0]", firstElem(golden["pbs_snapshots"]), firstElem(got["pbs_snapshots"]))
// v0.119.0 addition — addresses[0] key set (iface/cidr), the cross-repo wire for the hub's
// Network card.
assertSameKeys(t, "addresses[0]", firstElem(golden["addresses"]), firstElem(got["addresses"]))
// DR-recipe host-half — the agent's secret-free reconstruction-scaffolding section. Assert the
// dr_recipe key set + each sub-array's element key set (the cross-repo wire pinned in the golden).
grec, srec := golden["dr_recipe"], got["dr_recipe"]
assertSameKeys(t, "dr_recipe", grec, srec)
assertSameKeys(t, "dr_recipe.pbs", field(grec, "pbs"), field(srec, "pbs"))
assertSameKeys(t, "dr_recipe.guests[0]", firstElem(field(grec, "guests")), firstElem(field(srec, "guests")))
assertSameKeys(t, "dr_recipe.drives[0]", firstElem(field(grec, "drives")), firstElem(field(srec, "drives")))
assertSameKeys(t, "dr_recipe.pve_storage[0]", firstElem(field(grec, "pve_storage")), firstElem(field(srec, "pve_storage")))
assertSameKeys(t, "dr_recipe.backup_target", field(grec, "backup_target"), field(srec, "backup_target"))
}
// field extracts a nested object value from a decoded JSON map (nil if absent/not a map).
func field(v any, key string) any {
m, ok := v.(map[string]any)
if !ok {
return nil
}
return m[key]
}
func firstElem(v any) any {
arr, ok := v.([]any)
if !ok || len(arr) == 0 {
return map[string]any{}
}
return arr[0]
}
func assertSameKeys(t *testing.T, where string, a, b any) {
t.Helper()
ka, kb := keysOf(a), keysOf(b)
if !reflect.DeepEqual(ka, kb) {
t.Errorf("contract drift at %s:\n golden keys = %v\n struct keys = %v", where, ka, kb)
}
}
func keysOf(v any) []string {
m, ok := v.(map[string]any)
if !ok {
return nil
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}