package web import ( "encoding/json" "fmt" "os" "path/filepath" "strings" "sync" "time" ) // DeviceACLEntry is one device-to-owner binding. type DeviceACLEntry struct { Owner string `json:"owner"` UpdatedAt time.Time `json:"updated_at"` UpdatedBy string `json:"updated_by,omitempty"` } // deviceACLFile is the on-disk shape of device_acl.json. Version is reserved // for future migrations; v1 is a flat deviceID -> owner map. type deviceACLFile struct { Version int `json:"version"` Devices map[string]DeviceACLEntry `json:"devices"` } // DeviceACL is the per-device owner table used by the web console. A device // with no entry is "public": admin-role users may see and control it, viewers // may not. A device with an owner is visible/controllable only by that owner // (plus the built-in superadmin). // // The table is process-local and persisted atomically to Path. An empty Path // disables persistence (tests). type DeviceACL struct { mu sync.RWMutex path string entries map[string]DeviceACLEntry } // NewDeviceACL returns an empty table backed by path. func NewDeviceACL(path string) *DeviceACL { return &DeviceACL{path: path, entries: make(map[string]DeviceACLEntry)} } // Load reads Path into memory. A missing file is an empty table. A malformed // file is returned as an error: silently starting with no bindings would turn // every private device public, so the caller must fail closed. func (a *DeviceACL) Load() error { if a.path == "" { return nil } data, err := os.ReadFile(a.path) if err != nil { if os.IsNotExist(err) { return nil } return fmt.Errorf("read %s: %w", a.path, err) } var f deviceACLFile if err := json.Unmarshal(data, &f); err != nil { return fmt.Errorf("parse %s: %w", a.path, err) } entries := make(map[string]DeviceACLEntry, len(f.Devices)) for id, e := range f.Devices { id = strings.TrimSpace(id) e.Owner = strings.TrimSpace(e.Owner) if id == "" || e.Owner == "" { continue } entries[id] = e } a.mu.Lock() a.entries = entries a.mu.Unlock() return nil } // deviceAllowed is the single visibility rule shared by the WebSocket handlers // and the REST device list: // // acl == nil -> legacy: every authenticated session // username == admin -> superadmin: every device // unbound device -> admin role only (shared public pool) // bound device -> its owner only (plus superadmin) func deviceAllowed(acl *DeviceACL, username, role, deviceID string) bool { if deviceID == "" { return false } if acl == nil { return true } if role == "admin" && username == "admin" { return true } owner := acl.Owner(deviceID) if owner == "" { return role == "admin" } return username != "" && username == owner } // Owner returns the owner of deviceID, or "" when the device is public. func (a *DeviceACL) Owner(deviceID string) string { if a == nil { return "" } a.mu.RLock() defer a.mu.RUnlock() return a.entries[deviceID].Owner } // Owners returns a copy of the deviceID -> owner map. Callers that check many // ids in a loop (the audit scanner walks up to 32 MB of records) take this // snapshot once instead of taking the read lock per record, so a concurrent // bind's file fsync cannot sit between their checks. func (a *DeviceACL) Owners() map[string]string { if a == nil { return map[string]string{} } a.mu.RLock() defer a.mu.RUnlock() out := make(map[string]string, len(a.entries)) for id, e := range a.entries { out[id] = e.Owner } return out } // Snapshot returns a copy of the table (for admin listings/tests). func (a *DeviceACL) Snapshot() map[string]DeviceACLEntry { if a == nil { return map[string]DeviceACLEntry{} } a.mu.RLock() defer a.mu.RUnlock() out := make(map[string]DeviceACLEntry, len(a.entries)) for id, e := range a.entries { out[id] = e } return out } // Bind assigns owner to every device in ids. On persistence failure the // in-memory table is rolled back so it never claims a binding that would not // survive a restart. func (a *DeviceACL) Bind(ids []string, owner, actor string) error { owner = strings.TrimSpace(owner) if owner == "" { return fmt.Errorf("empty owner") } a.mu.Lock() defer a.mu.Unlock() prev := make(map[string]DeviceACLEntry, len(ids)) now := time.Now().UTC() changed := false for _, id := range ids { id = strings.TrimSpace(id) if id == "" { continue } prev[id] = a.entries[id] a.entries[id] = DeviceACLEntry{Owner: owner, UpdatedAt: now, UpdatedBy: actor} changed = true } if !changed { return fmt.Errorf("no device ids") } if err := a.saveLocked(); err != nil { for id, e := range prev { if e.Owner == "" { delete(a.entries, id) } else { a.entries[id] = e } } return err } return nil } // Unbind removes the binding for every device in ids (idempotent). func (a *DeviceACL) Unbind(ids []string) error { a.mu.Lock() defer a.mu.Unlock() prev := make(map[string]DeviceACLEntry, len(ids)) for _, id := range ids { id = strings.TrimSpace(id) if id == "" { continue } if e, ok := a.entries[id]; ok { prev[id] = e delete(a.entries, id) } } if len(prev) == 0 { return nil } if err := a.saveLocked(); err != nil { for id, e := range prev { a.entries[id] = e } return err } return nil } // Remove drops the binding for one device (called when the device record is // deleted, so a future client reusing the same ID cannot inherit it). func (a *DeviceACL) Remove(deviceID string) error { return a.Unbind([]string{deviceID}) } // saveLocked writes the table via a temp file + rename. Caller holds a.mu. func (a *DeviceACL) saveLocked() error { if a.path == "" { return nil } f := deviceACLFile{Version: 1, Devices: a.entries} data, err := json.MarshalIndent(f, "", " ") if err != nil { return fmt.Errorf("encode device acl: %w", err) } dir := filepath.Dir(a.path) if dir == "" { dir = "." } tmp, err := os.CreateTemp(dir, ".device_acl-*.tmp") if err != nil { return fmt.Errorf("create temp acl: %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 acl: %w", err) } if err := tmp.Sync(); err != nil { _ = tmp.Close() return fmt.Errorf("sync temp acl: %w", err) } if err := tmp.Close(); err != nil { return fmt.Errorf("close temp acl: %w", err) } if err := os.Rename(tmpName, a.path); err != nil { return fmt.Errorf("rename acl: %w", err) } return nil }