package web import ( "encoding/json" "fmt" "os" "path/filepath" "strings" "sync" "time" "unicode/utf8" ) // MaxGroupRunes bounds the per-device group label. The Win32 server's // "regroup host" dialog rejects names of 24 characters or more (the command // payload is a fixed 50-byte buffer); the Go console keeps the same limit so // a group name written here can also be handed to the client later. const MaxGroupRunes = 23 // DeviceGroupEntry is one web-console group override. type DeviceGroupEntry struct { Group string `json:"group"` UpdatedAt time.Time `json:"updated_at"` UpdatedBy string `json:"updated_by,omitempty"` } // deviceGroupsFile is the on-disk shape of device_groups.json. Version is // reserved for future migrations; v1 is a flat deviceID -> group map. type deviceGroupsFile struct { Version int `json:"version"` Devices map[string]DeviceGroupEntry `json:"devices"` } // DeviceGroups is the per-device group table used by the Go web console. A // device with no entry keeps the group it reported at login; an entry // overrides that group for every Go-side view (device list, group filter, // MCP), works for offline records too, and survives restarts. // // It deliberately does NOT write CMD_SET_GROUP to the client: the host keeps // reporting its own group to other masters. An empty Path disables // persistence (tests). type DeviceGroups struct { mu sync.RWMutex path string entries map[string]DeviceGroupEntry // loadErr records why Load failed. While set, Set/Remove refuse to write: // persisting the in-memory (empty) table would replace the unreadable file // and destroy every override it still holds. loadErr error } // NewDeviceGroups returns an empty table backed by path. func NewDeviceGroups(path string) *DeviceGroups { return &DeviceGroups{path: path, entries: make(map[string]DeviceGroupEntry)} } // Load reads Path into memory. A missing file is an empty table. A malformed // file (or one written by a newer version) is returned as an error and leaves // the table write-disabled so the unreadable file survives for recovery. func (g *DeviceGroups) Load() error { if g.path == "" { return nil } data, err := os.ReadFile(g.path) if err != nil { if os.IsNotExist(err) { return nil } return g.failLoad(fmt.Errorf("read %s: %w", g.path, err)) } var f deviceGroupsFile if err := json.Unmarshal(data, &f); err != nil { return g.failLoad(fmt.Errorf("parse %s: %w", g.path, err)) } if f.Version > deviceGroupsFileVersion { return g.failLoad(fmt.Errorf("unsupported %s version %d (this server writes %d)", g.path, f.Version, deviceGroupsFileVersion)) } entries := make(map[string]DeviceGroupEntry, len(f.Devices)) for id, e := range f.Devices { id = strings.TrimSpace(id) e.Group = capRunes(sanitizeLabel(e.Group), MaxGroupRunes) if id == "" || e.Group == "" { continue } entries[id] = e } g.mu.Lock() g.entries = entries g.loadErr = nil g.mu.Unlock() return nil } // deviceGroupsFileVersion is the on-disk format we write. A file from a newer // version is refused instead of being read as v1 and overwritten. const deviceGroupsFileVersion = 1 // failLoad records the reason writes are disabled and returns it. func (g *DeviceGroups) failLoad(err error) error { g.mu.Lock() g.loadErr = err g.mu.Unlock() return err } // Group returns the override for deviceID, or "" when the device keeps the // group it reported. func (g *DeviceGroups) Group(deviceID string) string { if g == nil { return "" } g.mu.RLock() defer g.mu.RUnlock() return g.entries[deviceID].Group } // Groups returns a copy of the deviceID -> group map. Callers that look up // many devices in one pass take this snapshot instead of a read lock per // device. func (g *DeviceGroups) Groups() map[string]string { if g == nil { return map[string]string{} } g.mu.RLock() defer g.mu.RUnlock() out := make(map[string]string, len(g.entries)) for id, e := range g.entries { out[id] = e.Group } return out } // Snapshot returns a copy of the table (for logs and tests). func (g *DeviceGroups) Snapshot() map[string]DeviceGroupEntry { if g == nil { return map[string]DeviceGroupEntry{} } g.mu.RLock() defer g.mu.RUnlock() out := make(map[string]DeviceGroupEntry, len(g.entries)) for id, e := range g.entries { out[id] = e } return out } // Set stores group for deviceID. An empty group clears the override (the // device falls back to the group it reports). Control characters are folded to // spaces, the result is trimmed, and more than MaxGroupRunes runes is // rejected. On persistence failure the in-memory table is rolled back. func (g *DeviceGroups) Set(deviceID, group, actor string) error { deviceID = strings.TrimSpace(deviceID) if deviceID == "" { return fmt.Errorf("empty device id") } group = sanitizeLabel(group) if utf8.RuneCountInString(group) > MaxGroupRunes { return fmt.Errorf("group is too long (max %d characters)", MaxGroupRunes) } g.mu.Lock() defer g.mu.Unlock() if g.loadErr != nil { return fmt.Errorf("device groups unavailable: %w", g.loadErr) } prev, had := g.entries[deviceID] if group == "" { if !had { return nil } delete(g.entries, deviceID) } else { g.entries[deviceID] = DeviceGroupEntry{Group: group, UpdatedAt: time.Now().UTC(), UpdatedBy: actor} } if err := g.saveLocked(); err != nil { if had { g.entries[deviceID] = prev } else { delete(g.entries, deviceID) } return err } return nil } // Remove drops the override of one device (idempotent). Called when the device // record is deleted so a future client reusing the same ID cannot inherit the // group. func (g *DeviceGroups) Remove(deviceID string) error { if g == nil { return nil } deviceID = strings.TrimSpace(deviceID) if deviceID == "" { return nil } g.mu.Lock() defer g.mu.Unlock() if g.loadErr != nil { return fmt.Errorf("device groups unavailable: %w", g.loadErr) } prev, ok := g.entries[deviceID] if !ok { return nil } delete(g.entries, deviceID) if err := g.saveLocked(); err != nil { g.entries[deviceID] = prev return err } return nil } // saveLocked writes the table via a temp file + rename. Caller holds g.mu. func (g *DeviceGroups) saveLocked() error { if g.path == "" { return nil } f := deviceGroupsFile{Version: deviceGroupsFileVersion, Devices: g.entries} data, err := json.MarshalIndent(f, "", " ") if err != nil { return fmt.Errorf("encode device groups: %w", err) } dir := filepath.Dir(g.path) if dir == "" { dir = "." } tmp, err := os.CreateTemp(dir, ".device_groups-*.tmp") if err != nil { return fmt.Errorf("create temp groups: %w", err) } tmpName := tmp.Name() defer func() { _ = os.Remove(tmpName) }() // no-op after a successful rename if _, err := tmp.Write(data); err != nil { _ = tmp.Close() return fmt.Errorf("write temp groups: %w", err) } if err := tmp.Sync(); err != nil { _ = tmp.Close() return fmt.Errorf("sync temp groups: %w", err) } if err := tmp.Close(); err != nil { return fmt.Errorf("close temp groups: %w", err) } if err := os.Rename(tmpName, g.path); err != nil { return fmt.Errorf("rename groups: %w", err) } return nil }