Feature: let the web console move a host to another group

The Go server now keeps a per-device group override (device_groups.json)
edited from the card's "..." menu below Edit remark. The override wins
over the group the host reported (or the offline history record) in the
device list, the group filter, get_groups and the MCP host tools, so
offline records can be regrouped and the change survives restarts. An
empty value clears the override; names are capped at 23 characters,
matching the Win32 regroup dialog.

The command is admin-only and honours the device ACL; it refuses IDs the
server has never seen (online or in history) so a stale card cannot
create an orphan entry, and the remark handler gets the same guard. Each
change is audited as admin.device.group, deleting a device drops its
override, and values loaded from disk are trimmed and capped like
remarks. The menu entry is gated on the groupEdit capability, so the
shared page hides it on the MFC server.

Like remarks, the override is a Go-side label: no CMD_SET_GROUP is sent,
so the host keeps reporting its own group to other masters. Verified
with go test ./..., go vet, gofmt and a node --check pass on the page.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-27 15:15:27 +01:00
1 parent 5f764b2425
commit 034b11fa6a
16 files changed
+895 -54

No files matched your search

+1
View File
@@ -39,6 +39,7 @@ const (
auditDeviceBind = "admin.device.bind"
auditDeviceUnbind = "admin.device.unbind"
auditDeviceRemark = "admin.device.remark"
auditDeviceGroup = "admin.device.group"
auditQuery = "admin.audit.query"
)
+251
View File
@@ -0,0 +1,251 @@
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
}
+230
View File
@@ -0,0 +1,230 @@
package web
import (
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"unicode/utf8"
)
// TestDeviceGroupsSetPersistClear covers the store: sanitize, save, reload,
// clear, the rune cap and the corrupt-file write protection.
func TestDeviceGroupsSetPersistClear(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_groups.json")
groups := NewDeviceGroups(path)
if err := groups.Set("dev-1", " Office\nWest\t", "admin"); err != nil {
t.Fatalf("Set: %v", err)
}
if got := groups.Group("dev-1"); got != "Office West" {
t.Fatalf("Group = %q, want %q", got, "Office West")
}
reloaded := NewDeviceGroups(path)
if err := reloaded.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
if got := reloaded.Group("dev-1"); got != "Office West" {
t.Fatalf("reloaded Group = %q, want %q", got, "Office West")
}
// The cap matches the Win32 regroup dialog (< 24 characters).
if err := groups.Set("dev-1", strings.Repeat("x", MaxGroupRunes+1), "admin"); err == nil {
t.Fatal("Set accepted an over-long group")
}
if err := groups.Set("dev-1", strings.Repeat("y", MaxGroupRunes), "admin"); err != nil {
t.Fatalf("Set at the limit: %v", err)
}
// An empty group clears the override.
if err := groups.Set("dev-1", " ", "admin"); err != nil {
t.Fatalf("clear: %v", err)
}
if got := groups.Group("dev-1"); got != "" {
t.Fatalf("Group after clear = %q, want empty", got)
}
// Groups() is the bulk snapshot callers take per listing; it must be a copy.
if err := groups.Set("dev-2", "Bulk", "admin"); err != nil {
t.Fatalf("Set dev-2: %v", err)
}
snap := groups.Groups()
if snap["dev-2"] != "Bulk" {
t.Fatalf("Groups()[dev-2] = %q, want %q", snap["dev-2"], "Bulk")
}
snap["dev-2"] = "mutated"
if got := groups.Group("dev-2"); got != "Bulk" {
t.Fatalf("mutating the snapshot changed the store: %q", got)
}
if err := groups.Remove("dev-2"); err != nil {
t.Fatalf("Remove: %v", err)
}
if err := groups.Remove("dev-2"); err != nil {
t.Fatalf("Remove twice: %v", err)
}
if got := groups.Group("dev-2"); got != "" {
t.Fatalf("Group after Remove = %q", got)
}
}
// TestDeviceGroupsBadFileRefusesWrites: an unparsable file must never be
// replaced by the first save.
func TestDeviceGroupsBadFileRefusesWrites(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_groups.json")
bad := []byte("{not json")
if err := os.WriteFile(path, bad, 0644); err != nil {
t.Fatalf("seed: %v", err)
}
groups := NewDeviceGroups(path)
if err := groups.Load(); err == nil {
t.Fatal("Load accepted a malformed file")
}
if err := groups.Set("dev-1", "x", "admin"); err == nil {
t.Fatal("Set wrote over a file that failed to load")
}
if got, _ := os.ReadFile(path); string(got) != string(bad) {
t.Fatalf("original file was modified: %q", got)
}
}
// TestDeviceGroupsLoadAppliesInvariants: values read back from disk are
// sanitized and capped, so a restored file cannot break the card layout.
func TestDeviceGroupsLoadAppliesInvariants(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_groups.json")
long := "Team\nA " + strings.Repeat("x", MaxGroupRunes)
data, err := json.Marshal(deviceGroupsFile{Version: deviceGroupsFileVersion,
Devices: map[string]DeviceGroupEntry{"dev-1": {Group: long}}})
if err != nil {
t.Fatalf("marshal: %v", err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatalf("seed: %v", err)
}
groups := NewDeviceGroups(path)
if err := groups.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
got := groups.Group("dev-1")
if strings.ContainsAny(got, "\r\n\t") {
t.Fatalf("loaded group kept control characters: %q", got)
}
if n := utf8.RuneCountInString(got); n != MaxGroupRunes {
t.Fatalf("loaded group has %d runes, want %d", n, MaxGroupRunes)
}
}
// TestSetDeviceGroupHandler exercises the WebSocket path: the superadmin moves
// a host, device_list reports the override plus groupEdit, get_groups offers
// the new name, and clearing restores the reported group.
func TestSetDeviceGroupHandler(t *testing.T) {
wh, _, _ := aclTestHub(t)
groups := NewDeviceGroups(filepath.Join(t.TempDir(), "device_groups.json"))
wh.withDeviceGroups(groups)
c, tok := aclTestClient(t, wh, "admin", "admin")
send := func(id, group string) map[string]any {
raw, err := json.Marshal(map[string]any{"token": tok, "id": id, "group": group})
if err != nil {
t.Fatalf("marshal: %v", err)
}
wh.dispatch(c, "set_device_group", raw)
return readUntilCmd(t, c, "set_device_group_result")
}
res := send("pub", " Office\nWest ")
if res["ok"] != true {
t.Fatalf("set group failed: %v", res)
}
if res["group"] != "Office West" {
t.Fatalf("reply group = %v, want %q", res["group"], "Office West")
}
// device_list reports the override and the capability the menu keys off.
rawList, _ := json.Marshal(map[string]any{"token": tok})
wh.dispatch(c, "get_devices", rawList)
list := readUntilCmd(t, c, "device_list")
if list["groupEdit"] != true {
t.Fatalf("device_list groupEdit = %v, want true", list["groupEdit"])
}
found := false
for _, it := range list["devices"].([]any) {
m := it.(map[string]any)
if m["id"] == "pub" {
found = true
if m["group"] != "Office West" {
t.Fatalf("device_list group = %v, want override", m["group"])
}
}
}
if !found {
t.Fatal("device_list did not include the public device")
}
// get_groups offers the override name.
rawGroups, _ := json.Marshal(map[string]any{"token": tok})
wh.dispatch(c, "get_groups", rawGroups)
gr := readUntilCmd(t, c, "groups")
var names []string
for _, g := range gr["groups"].([]any) {
names = append(names, g.(string))
}
if !slices.Contains(names, "Office West") {
t.Fatalf("groups = %v, want the override included", names)
}
// The overridden device's stale reported group must not linger in the list.
if slices.Contains(names, "shared") {
t.Fatalf("groups = %v, want the overridden reported group omitted", names)
}
// A stale card (device deleted between render and save) must not create an
// orphan override.
if res := send("ghost-id", "Nowhere"); res["ok"] == true {
t.Fatalf("group override accepted for an unknown device: %v", res)
}
// Clearing restores the group the host reported.
res = send("pub", "")
if res["ok"] != true {
t.Fatalf("clear group failed: %v", res)
}
wh.dispatch(c, "get_devices", rawList)
list = readUntilCmd(t, c, "device_list")
for _, it := range list["devices"].([]any) {
m := it.(map[string]any)
if m["id"] == "pub" && m["group"] != "shared" {
t.Fatalf("group after clear = %v, want reported %q", m["group"], "shared")
}
}
}
// TestSetDeviceGroupPermissions: viewers cannot edit, and an admin that cannot
// see a private device cannot move it.
func TestSetDeviceGroupPermissions(t *testing.T) {
wh, _, _ := aclTestHub(t)
wh.withDeviceGroups(NewDeviceGroups(""))
attempt := func(c *wsClient, tok, id string) map[string]any {
raw, _ := json.Marshal(map[string]any{"token": tok, "id": id, "group": "x"})
wh.dispatch(c, "set_device_group", raw)
return readUntilCmd(t, c, "set_device_group_result")
}
cv, tokv := aclTestClient(t, wh, "viewer1", "viewer")
if res := attempt(cv, tokv, "pub"); res["ok"] == true {
t.Fatal("viewer was allowed to move a host")
}
ca, toka := aclTestClient(t, wh, "other-admin", "admin")
if res := attempt(ca, toka, "a-dev"); res["ok"] == true {
t.Fatal("admin without device access was allowed to move a host")
}
cs, toks := aclTestClient(t, wh, "admin", "admin")
if res := attempt(cs, toks, "a-dev"); res["ok"] != true {
t.Fatalf("superadmin was refused: %v", res)
}
}
+11 -9
View File
@@ -83,7 +83,7 @@ func (n *DeviceNotes) Load() error {
id = strings.TrimSpace(id)
// Apply the same invariants Set enforces: a hand-edited or restored
// file must not put a multi-line / over-long label on a card.
e.Note = capRemark(sanitizeRemark(e.Note))
e.Note = capRunes(sanitizeLabel(e.Note), MaxRemarkRunes)
if id == "" || e.Note == "" {
continue
}
@@ -154,7 +154,7 @@ func (n *DeviceNotes) Set(deviceID, note, actor string) error {
if deviceID == "" {
return fmt.Errorf("empty device id")
}
note = sanitizeRemark(note)
note = sanitizeLabel(note)
if utf8.RuneCountInString(note) > MaxRemarkRunes {
return fmt.Errorf("remark is too long (max %d characters)", MaxRemarkRunes)
}
@@ -212,10 +212,11 @@ func (n *DeviceNotes) Remove(deviceID string) error {
return nil
}
// sanitizeRemark folds line breaks and other control characters (including
// sanitizeLabel folds line breaks and other control characters (including
// bidi/zero-width formatting runes, which could reorder the card title) to
// spaces so the label always renders on one line, then trims both ends.
func sanitizeRemark(s string) string {
// Shared by the per-device remark and group tables.
func sanitizeLabel(s string) string {
s = strings.Map(func(r rune) rune {
if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
return ' '
@@ -225,13 +226,14 @@ func sanitizeRemark(s string) string {
return strings.TrimSpace(s)
}
// capRemark truncates s to MaxRemarkRunes runes. Used on values read back
// from disk, where an older/hand-edited file may exceed the current limit.
func capRemark(s string) string {
if utf8.RuneCountInString(s) <= MaxRemarkRunes {
// capRunes truncates s to max runes. Used on values read back from disk, where
// an older/hand-edited file may exceed the current limit. Trims again after the
// cut so the stored label cannot end in an invisible space.
func capRunes(s string, max int) string {
if utf8.RuneCountInString(s) <= max {
return s
}
return string([]rune(s)[:MaxRemarkRunes])
return strings.TrimSpace(string([]rune(s)[:max]))
}
// saveLocked writes the table via a temp file + rename. Caller holds n.mu.
+8
View File
@@ -165,6 +165,14 @@ func TestSetDeviceRemarkHandler(t *testing.T) {
if got := notes.Note("pub"); got != "Keep" {
t.Fatalf("invalid payload changed the remark to %q", got)
}
// A stale card (device deleted between render and save) must not create an
// orphan remark.
rawGhost, _ := json.Marshal(map[string]any{"token": tok, "id": "ghost-id", "remark": "x"})
wh.dispatch(c, "set_device_remark", rawGhost)
if ghost := readUntilCmd(t, c, "set_device_remark_result"); ghost["ok"] == true {
t.Fatalf("remark accepted for an unknown device: %v", ghost)
}
}
// TestDeviceNotesBadFileRefusesWrites: a file that cannot be parsed must not
+6
View File
@@ -34,6 +34,7 @@ type Server struct {
history *devicehistory.Store // nil → no offline devices
deviceACL *DeviceACL // nil → no per-device owner filtering
deviceNotes *DeviceNotes // nil → no "edit remark" entry in the UI
deviceGroups *DeviceGroups // nil → no "edit group" entry in the UI
ws *wsHub
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
loginIPLimit *wsauth.RateLimiter
@@ -103,6 +104,9 @@ type Config struct {
// shared page hides the action on a backend that does not implement it
// (the MFC server).
DeviceNotes *DeviceNotes
// DeviceGroups is the per-device group override table. nil disables the
// "edit group" menu entry the same way (device_list reports groupEdit).
DeviceGroups *DeviceGroups
// TransferTarget ("host:port") and TransferDays pre-fill the web UI's
// "transfer host" dialog. Reporting them is also what tells the shared
// page that this backend implements COMMAND_ASSIGN_MASTER — the MFC server
@@ -146,6 +150,7 @@ func (s *Server) WithConfig(cfg Config) *Server {
s.sso = cfg.SSO
s.deviceACL = cfg.DeviceACL
s.deviceNotes = cfg.DeviceNotes
s.deviceGroups = cfg.DeviceGroups
s.transferTarget = cfg.TransferTarget
s.transferDays = cfg.TransferDays
s.transferTransport = cfg.TransferTransport
@@ -175,6 +180,7 @@ func (s *Server) Start() error {
withTrustForwardedFor(s.trustForwardedFor).
withDeviceACL(s.deviceACL).
withDeviceNotes(s.deviceNotes).
withDeviceGroups(s.deviceGroups).
withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport)
mux := http.NewServeMux()
+10
View File
@@ -162,6 +162,7 @@ type wsHub struct {
history *devicehistory.Store // nil → device_list stays online-only
acl *DeviceACL // nil → every device is public (tests/embedders)
notes *DeviceNotes // nil → no "edit remark" entry (MFC backend)
groups *DeviceGroups // nil → no "edit group" entry (MFC backend)
log *logger.Logger
mu sync.RWMutex
@@ -247,6 +248,15 @@ func (h *wsHub) withDeviceNotes(notes *DeviceNotes) *wsHub {
return h
}
// withDeviceGroups installs the per-device group override table. A nil table
// disables "edit group": its presence is what the device_list reply reports as
// groupEdit, so the shared page only offers the menu entry on a backend that
// implements it (the MFC server does not).
func (h *wsHub) withDeviceGroups(groups *DeviceGroups) *wsHub {
h.groups = groups
return h
}
// withTransferDefaults installs the pre-filled target/days and the link type
// (protocol.TransferTransport*) for the web UI's "transfer host" dialog. An
// empty target still enables the feature: the operator types the address in
+133 -6
View File
@@ -106,6 +106,8 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) {
h.handleUnbindDevice(c, raw)
case "set_device_remark":
h.handleSetDeviceRemark(c, raw)
case "set_device_group":
h.handleSetDeviceGroup(c, raw)
case "get_groups":
h.handleGetGroups(c, raw)
case "query_audit":
@@ -124,6 +126,16 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) {
}
}
// deviceExists reports whether id is online or has a history record. Handlers
// that write per-device side tables use it so a stale card (the device was
// deleted between render and save) cannot create an orphan entry.
func (h *wsHub) deviceExists(id string) bool {
if h.devices.IsOnline(id) {
return true
}
return h.history != nil && h.history.Has(id)
}
// requireAdmin combines token validation with a role=="admin" check. The
// reply on failure has the standard `{cmd, ok:false, msg}` shape so the
// front-end's generic toast handler can surface the reason.
@@ -807,6 +819,8 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
// remark table reports it, so the shared page hides the menu entry
// on the MFC server.
"remarkEdit": h.notes != nil,
// ... and for "edit group", which only the Go server implements.
"groupEdit": h.groups != nil,
}))
}
@@ -819,6 +833,10 @@ type deviceListItem struct {
// Remark is the operator's label for this host, rendered as
// "hostname (remark)" on the card. Set by the Go web console only.
Remark string `json:"remark,omitempty"`
// GroupOverride marks Group as a web-console override rather than the
// group the host reported, so the edit dialog can prefill without turning
// the reported value into a permanent override.
GroupOverride bool `json:"groupOverride,omitempty"`
// TransferTo / TransferUntil carry the "handed over to another master"
// marker so the card can say where the host went and how long it stays
// there. Absent for a host that was never transferred.
@@ -838,6 +856,10 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
if h.notes != nil {
remarks = h.notes.Snapshot()
}
var groups map[string]string
if h.groups != nil {
groups = h.groups.Groups()
}
out := make([]deviceListItem, 0, len(all))
for _, d := range all {
if !h.canAccessDevice(c, d.ID) {
@@ -851,6 +873,12 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
if remarks != nil {
item.Remark = remarks[d.ID].Note
}
// A web-console group override wins over the group the host reported
// at login (and over the group stored in the offline history record).
if g := groups[d.ID]; g != "" {
item.DeviceInfo.Group = g
item.GroupOverride = true
}
if h.history != nil {
if target, until, ok := h.history.Transfer(d.ID); ok {
item.TransferTo, item.TransferUntil = target, until
@@ -1302,6 +1330,7 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
// client that happens to reuse the same ID.
h.dropDeviceBinding(in.ID)
h.dropDeviceNote(in.ID)
h.dropDeviceGroup(in.ID)
h.audit(c, false, auditDeviceAdmin, map[string]any{
"device_id": in.ID,
"mode": "uninstall",
@@ -1344,6 +1373,7 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
}
h.dropDeviceBinding(in.ID)
h.dropDeviceNote(in.ID)
h.dropDeviceGroup(in.ID)
h.audit(c, false, auditDeviceAdmin, map[string]any{
"device_id": in.ID,
"mode": "removed",
@@ -1595,16 +1625,21 @@ func (h *wsHub) handleListUsers(c *wsClient, raw []byte) {
}))
}
// handleGetGroups returns the deduplicated set of group labels currently
// observed on online devices, plus a synthetic "default" entry that the
// admin UI uses for ungrouped devices. Admin-only — non-admins don't get
// to enumerate the device fleet's groups. Matches the contract of
// CWebService::HandleGetGroups (WebService.cpp:1130).
// handleGetGroups returns the deduplicated set of group labels the admin UI
// can offer: Web-console overrides (including groups that exist only on
// offline records) plus the groups online devices report, and a synthetic
// "default" entry for ungrouped devices. A device whose group is overridden
// contributes only the override, never its stale reported group. Admin-only —
// non-admins don't get to enumerate the device fleet's groups.
func (h *wsHub) handleGetGroups(c *wsClient, raw []byte) {
const replyCmd = "groups"
if !h.requireAdmin(c, raw, replyCmd) {
return
}
var overrides map[string]string
if h.groups != nil {
overrides = h.groups.Groups()
}
seen := map[string]struct{}{"default": {}}
for _, d := range h.devices.ListDevices() {
// Group names are device metadata: do not reveal groups that only
@@ -1612,12 +1647,23 @@ func (h *wsHub) handleGetGroups(c *wsClient, raw []byte) {
if !h.canAccessDevice(c, d.ID) {
continue
}
if overrides[d.ID] != "" {
continue // the override loop below adds the effective group
}
g := d.Group
if g == "" {
g = "default"
}
seen[g] = struct{}{}
}
// Web-console overrides define groups too, including groups that only
// exist on offline records; the per-device access check still applies.
for id, g := range overrides {
if g == "" || !h.canAccessDevice(c, id) {
continue
}
seen[g] = struct{}{}
}
groups := make([]string, 0, len(seen))
for g := range seen {
groups = append(groups, g)
@@ -1780,9 +1826,13 @@ func (h *wsHub) handleSetDeviceRemark(c *wsClient, raw []byte) {
if h.denyIfNoDeviceAccess(c, id, replyCmd) {
return
}
if !h.deviceExists(id) {
fail("Device not found", "not_found")
return
}
// Sanitize before the length check and the reply so the echoed value is
// exactly what the store keeps (control characters folded to spaces).
remark := sanitizeRemark(in.Remark)
remark := sanitizeLabel(in.Remark)
if utf8.RuneCountInString(remark) > MaxRemarkRunes {
fail("Remark is too long (max "+strconv.Itoa(MaxRemarkRunes)+" characters)", "too_long")
return
@@ -1803,6 +1853,73 @@ func (h *wsHub) handleSetDeviceRemark(c *wsClient, raw []byte) {
}))
}
// handleSetDeviceGroup sets the web-console group override for one device.
// Admin role only, and only for a device the caller can access. An empty group
// clears the override, so the device falls back to the group it reports.
//
// The override changes every Go-side view (device list, group filter, MCP) and
// works for offline records, but it does not send CMD_SET_GROUP: the host keeps
// reporting its own group to other masters.
func (h *wsHub) handleSetDeviceGroup(c *wsClient, raw []byte) {
const replyCmd = "set_device_group_result"
if !h.requireAdmin(c, raw, replyCmd) {
return
}
var in struct {
ID string `json:"id"`
Group string `json:"group"`
}
id := ""
fail := func(msg, reason string) {
h.audit(c, true, auditDeviceGroup, map[string]any{
"device_id": id,
"ok": false,
"reason": reason,
"error": msg,
})
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": msg}))
}
if err := json.Unmarshal(raw, &in); err != nil {
fail("Invalid request", "invalid_request")
return
}
id = strings.TrimSpace(in.ID)
if id == "" {
fail("Invalid device id", "invalid_id")
return
}
if h.groups == nil {
fail("Device groups are not enabled on this server", "disabled")
return
}
if h.denyIfNoDeviceAccess(c, id, replyCmd) {
return
}
if !h.deviceExists(id) {
fail("Device not found", "not_found")
return
}
group := sanitizeLabel(in.Group)
if utf8.RuneCountInString(group) > MaxGroupRunes {
fail("Group is too long (max "+strconv.Itoa(MaxGroupRunes)+" characters)", "too_long")
return
}
if err := h.groups.Set(id, group, c.user); err != nil {
fail("Failed to save group: "+err.Error(), "save_failed")
return
}
h.audit(c, false, auditDeviceGroup, map[string]any{
"device_id": id,
"ok": true,
"cleared": group == "",
})
// Every open console re-reads the list so the card and group filter move.
h.broadcastAuthenticated(`{"cmd":"devices_changed"}`)
c.queue(mustJSON(map[string]any{
"cmd": replyCmd, "ok": true, "id": id, "group": group,
}))
}
// normalizeDeviceIDs merges the batch and single-device forms, trims blanks
// and dedupes while preserving order.
func normalizeDeviceIDs(ids []string, single string) []string {
@@ -1912,6 +2029,16 @@ func (h *wsHub) dropDeviceNote(deviceID string) {
}
}
// dropDeviceGroup removes the group override together with the device record.
func (h *wsHub) dropDeviceGroup(deviceID string) {
if h.groups == nil {
return
}
if err := h.groups.Remove(deviceID); err != nil {
h.log.Warn("device group remove failed for %s: %v", deviceID, err)
}
}
// handleTermOpen kicks off a web terminal session. On success the wsClient
// records `termWatching = deviceID` so subsequent term_input / term_resize
// have a target, and the hub sends COMMAND_SHELL to the device. The