Files
SimpleRemoter/server/go/web/device_notes_test.go
T
yuanyuanxianganddeepseek-flash 5f764b2425 Feature: return web-console remarks from the Go MCP host tools
list_hosts and get_host_detail now include the remark an admin set in the
web console, and the name/query filters match it like the Win32 server
(name: hostname + remark; query: hostname + remark + IP). The text-only
host table gains a remark column, and the MCP instructions stop claiming
the Go server keeps no remarks.

The remark table is injected through a small Note() interface so the mcp
package still does not import web. An optional Notes() snapshot
capability is borrowed once per call, so a listing neither takes a read
lock per device nor mixes labels across a concurrent save. The design
docs are updated to match the new fields and table column.

Verified: go build ./..., go vet, gofmt and the full go test ./... pass;
new tests cover remark projection, both filters and the snapshot path.

Co-Authored-By: deepseek-flash
2026-11-27 14:51:15 +01:00

274 lines
9.0 KiB
Go

package web
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"unicode/utf8"
)
// TestDeviceNotesSetPersistClear covers the store on its own: sanitize, save,
// reload, clear, and the rune cap.
func TestDeviceNotesSetPersistClear(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_notes.json")
notes := NewDeviceNotes(path)
// Control characters are folded to spaces and the ends trimmed, so the
// label always renders on one line.
if err := notes.Set("dev-1", " Reception\nPC\t", "admin"); err != nil {
t.Fatalf("Set: %v", err)
}
if got := notes.Note("dev-1"); got != "Reception PC" {
t.Fatalf("Note = %q, want %q", got, "Reception PC")
}
// The table survives a restart.
reloaded := NewDeviceNotes(path)
if err := reloaded.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
if got := reloaded.Note("dev-1"); got != "Reception PC" {
t.Fatalf("reloaded Note = %q, want %q", got, "Reception PC")
}
// More than MaxRemarkRunes runes is rejected without touching the table.
tooLong := strings.Repeat("x", MaxRemarkRunes+1)
if err := notes.Set("dev-1", tooLong, "admin"); err == nil {
t.Fatal("Set accepted an over-long remark")
}
if got := notes.Note("dev-1"); got != "Reception PC" {
t.Fatalf("rejected Set changed the note to %q", got)
}
if err := notes.Set("dev-1", strings.Repeat("y", MaxRemarkRunes), "admin"); err != nil {
t.Fatalf("Set at the limit: %v", err)
}
// An empty remark clears the entry, and the clearing is persisted.
if err := notes.Set("dev-1", " ", "admin"); err != nil {
t.Fatalf("clear: %v", err)
}
if got := notes.Note("dev-1"); got != "" {
t.Fatalf("Note after clear = %q, want empty", got)
}
reloaded = NewDeviceNotes(path)
if err := reloaded.Load(); err != nil {
t.Fatalf("Load after clear: %v", err)
}
if got := reloaded.Note("dev-1"); got != "" {
t.Fatalf("reloaded Note after clear = %q, want empty", got)
}
// Remove is idempotent and drops the entry.
if err := notes.Set("dev-2", "Keep", "admin"); err != nil {
t.Fatalf("Set dev-2: %v", err)
}
if err := notes.Remove("dev-2"); err != nil {
t.Fatalf("Remove: %v", err)
}
if err := notes.Remove("dev-2"); err != nil {
t.Fatalf("Remove twice: %v", err)
}
if got := notes.Note("dev-2"); got != "" {
t.Fatalf("Note after Remove = %q, want empty", got)
}
// Notes() is the bulk snapshot callers take per listing; it must be a
// copy, not a live view of the table.
if err := notes.Set("dev-3", "Bulk", "admin"); err != nil {
t.Fatalf("Set dev-3: %v", err)
}
snap := notes.Notes()
if snap["dev-3"] != "Bulk" {
t.Fatalf("Notes()[dev-3] = %q, want %q", snap["dev-3"], "Bulk")
}
snap["dev-3"] = "mutated"
if got := notes.Note("dev-3"); got != "Bulk" {
t.Fatalf("mutating the snapshot changed the store: %q", got)
}
}
// TestSetDeviceRemarkHandler exercises the WebSocket path: the superadmin
// sets a remark, device_list reports it (plus the remarkEdit capability), and
// clearing removes it.
func TestSetDeviceRemarkHandler(t *testing.T) {
wh, _, _ := aclTestHub(t)
path := filepath.Join(t.TempDir(), "device_notes.json")
notes := NewDeviceNotes(path)
wh.withDeviceNotes(notes)
c, tok := aclTestClient(t, wh, "admin", "admin")
send := func(id, remark string) map[string]any {
raw, err := json.Marshal(map[string]any{"token": tok, "id": id, "remark": remark})
if err != nil {
t.Fatalf("marshal: %v", err)
}
wh.dispatch(c, "set_device_remark", raw)
return readUntilCmd(t, c, "set_device_remark_result")
}
res := send("pub", " Reception\nPC ")
if res["ok"] != true {
t.Fatalf("set remark failed: %v", res)
}
if res["remark"] != "Reception PC" {
t.Fatalf("reply remark = %v, want %q", res["remark"], "Reception PC")
}
if got := notes.Note("pub"); got != "Reception PC" {
t.Fatalf("stored remark = %q", got)
}
// device_list carries the label 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["remarkEdit"] != true {
t.Fatalf("device_list remarkEdit = %v, want true", list["remarkEdit"])
}
items, _ := list["devices"].([]any)
found := false
for _, it := range items {
m, _ := it.(map[string]any)
if m["id"] == "pub" {
found = true
if m["remark"] != "Reception PC" {
t.Fatalf("device_list remark = %v, want %q", m["remark"], "Reception PC")
}
}
}
if !found {
t.Fatal("device_list did not include the public device")
}
// Empty remark clears it.
res = send("pub", "")
if res["ok"] != true {
t.Fatalf("clear remark failed: %v", res)
}
if got := notes.Note("pub"); got != "" {
t.Fatalf("remark after clear = %q", got)
}
// A payload with a non-string remark must be rejected, not treated as an
// empty remark (which would clear the label).
if err := notes.Set("pub", "Keep", "admin"); err != nil {
t.Fatalf("Set before invalid payload: %v", err)
}
rawBad, _ := json.Marshal(map[string]any{"token": tok, "id": "pub", "remark": 123})
wh.dispatch(c, "set_device_remark", rawBad)
bad := readUntilCmd(t, c, "set_device_remark_result")
if bad["ok"] == true {
t.Fatalf("invalid payload accepted: %v", bad)
}
if got := notes.Note("pub"); got != "Keep" {
t.Fatalf("invalid payload changed the remark to %q", got)
}
}
// TestDeviceNotesBadFileRefusesWrites: a file that cannot be parsed must not
// be replaced by the first save (that would destroy every remark in it).
func TestDeviceNotesBadFileRefusesWrites(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "device_notes.json")
bad := []byte("{not json")
if err := os.WriteFile(path, bad, 0644); err != nil {
t.Fatalf("seed: %v", err)
}
notes := NewDeviceNotes(path)
if err := notes.Load(); err == nil {
t.Fatal("Load accepted a malformed file")
}
if err := notes.Set("dev-1", "x", "admin"); err == nil {
t.Fatal("Set wrote over a file that failed to load")
}
if err := notes.Remove("dev-1"); err == nil {
t.Fatal("Remove 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)
}
// A newer on-disk version is refused the same way.
future, err := json.Marshal(deviceNotesFile{Version: deviceNotesFileVersion + 1,
Devices: map[string]DeviceNoteEntry{"dev-1": {Note: "x"}}})
if err != nil {
t.Fatalf("marshal future file: %v", err)
}
if err := os.WriteFile(path, future, 0644); err != nil {
t.Fatalf("seed future: %v", err)
}
futureNotes := NewDeviceNotes(path)
if err := futureNotes.Load(); err == nil {
t.Fatal("Load accepted a newer file version")
}
if err := futureNotes.Set("dev-1", "y", "admin"); err == nil {
t.Fatal("Set wrote over a newer file version")
}
if got, _ := os.ReadFile(path); string(got) != string(future) {
t.Fatal("newer file was modified")
}
}
// TestDeviceNotesLoadAppliesInvariants: values read back from disk go through
// the same sanitize + rune cap as Set, so a restored file cannot put a
// multi-line or over-long label on a card.
func TestDeviceNotesLoadAppliesInvariants(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_notes.json")
long := "Reception\nPC " + strings.Repeat("x", MaxRemarkRunes)
data, err := json.Marshal(deviceNotesFile{Version: deviceNotesFileVersion,
Devices: map[string]DeviceNoteEntry{"dev-1": {Note: long}}})
if err != nil {
t.Fatalf("marshal: %v", err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatalf("seed: %v", err)
}
notes := NewDeviceNotes(path)
if err := notes.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
got := notes.Note("dev-1")
if strings.ContainsAny(got, "\r\n\t") {
t.Fatalf("loaded remark kept control characters: %q", got)
}
if n := utf8.RuneCountInString(got); n != MaxRemarkRunes {
t.Fatalf("loaded remark has %d runes, want %d", n, MaxRemarkRunes)
}
if !strings.HasPrefix(got, "Reception PC ") {
t.Fatalf("loaded remark lost its prefix: %q", got)
}
}
// TestSetDeviceRemarkPermissions: viewers cannot edit, and an admin that the
// ACL does not let see a private device cannot edit it either.
func TestSetDeviceRemarkPermissions(t *testing.T) {
wh, _, _ := aclTestHub(t)
wh.withDeviceNotes(NewDeviceNotes(""))
attempt := func(c *wsClient, tok, id string) map[string]any {
raw, _ := json.Marshal(map[string]any{"token": tok, "id": id, "remark": "x"})
wh.dispatch(c, "set_device_remark", raw)
return readUntilCmd(t, c, "set_device_remark_result")
}
cv, tokv := aclTestClient(t, wh, "viewer1", "viewer")
if res := attempt(cv, tokv, "pub"); res["ok"] == true {
t.Fatal("viewer was allowed to edit a remark")
}
// a-dev is bound to a@corp.com; another admin cannot see it, so the server
// must refuse to label it as well.
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 edit a remark")
}
// The superadmin can label any device.
cs, toks := aclTestClient(t, wh, "admin", "admin")
if res := attempt(cs, toks, "a-dev"); res["ok"] != true {
t.Fatalf("superadmin was refused: %v", res)
}
}