package web import ( "encoding/json" "path/filepath" "testing" "time" "github.com/yuanyuanxiang/SimpleRemoter/server/go/connection" "github.com/yuanyuanxiang/SimpleRemoter/server/go/hub" "github.com/yuanyuanxiang/SimpleRemoter/server/go/logger" "github.com/yuanyuanxiang/SimpleRemoter/server/go/wsauth" ) // aclTestHub builds a hub with one public device and two owner-bound devices. func aclTestHub(t *testing.T) (*wsHub, *hub.Hub, *DeviceACL) { t.Helper() dir := t.TempDir() lg := logger.New(logger.Config{ Level: logger.LevelInfo, Console: false, File: filepath.Join(dir, "server.log"), }) t.Cleanup(func() { _ = lg.Close() }) devices := hub.New() devices.SetSender(func(*connection.Context, []byte) error { return nil }) devices.Register(&hub.Device{ID: "pub", Name: "Public", Group: "shared"}, &connection.Context{RemoteAddr: "10.0.0.1:1000"}) devices.Register(&hub.Device{ID: "a-dev", Name: "A", Group: "private-a"}, &connection.Context{RemoteAddr: "10.0.0.2:1000"}) devices.Register(&hub.Device{ID: "b-dev", Name: "B", Group: "private-b"}, &connection.Context{RemoteAddr: "10.0.0.3:1000"}) acl := NewDeviceACL(filepath.Join(dir, "device_acl.json")) if err := acl.Bind([]string{"a-dev"}, "a@corp.com", "admin"); err != nil { t.Fatalf("bind a-dev: %v", err) } if err := acl.Bind([]string{"b-dev"}, "b@corp.com", "admin"); err != nil { t.Fatalf("bind b-dev: %v", err) } wh := newWSHub(wsauth.New(), devices, nil, lg).withDeviceACL(acl) t.Cleanup(wh.stop) return wh, devices, acl } func aclTestClient(t *testing.T, wh *wsHub, username, role string) (*wsClient, string) { t.Helper() tok, err := wh.auth.IssueToken(username, role) if err != nil { t.Fatalf("IssueToken(%q): %v", username, err) } c := &wsClient{ send: make(chan wsMsg, 64), closed: make(chan struct{}), id: newConnID(), addr: "203.0.113.5", peerAddr: "203.0.113.5", connectedAt: time.Now(), // Simulate an already-authenticated connection: in production these // fields are installed by requireAuth on the first command. token: tok, user: username, role: role, watchIDs: make(map[string]struct{}), watchStartedAt: make(map[string]time.Time), keyframeAt: make(map[string]int64), } wh.register(c) return c, tok } // readUntilCmd drains queued messages until cmd arrives. Handlers may also // queue broadcasts (devices_changed) or revocations on the same channel. func readUntilCmd(t *testing.T, c *wsClient, cmd string) map[string]any { t.Helper() deadline := time.After(2 * time.Second) for { select { case m := <-c.send: var v map[string]any if err := json.Unmarshal(m.data, &v); err != nil { t.Fatalf("decode queued message: %v", err) } if v["cmd"] == cmd { return v } case <-deadline: t.Fatalf("timed out waiting for %q", cmd) return nil } } } func TestDeviceListACL(t *testing.T) { wh, _, _ := aclTestHub(t) tests := []struct { user string role string want []string owner string // owner of a-dev as exposed to this caller }{ {"admin", "admin", []string{"pub", "a-dev", "b-dev"}, "a@corp.com"}, {"a@corp.com", "admin", []string{"pub", "a-dev"}, ""}, {"b@corp.com", "admin", []string{"pub", "b-dev"}, ""}, {"v@corp.com", "viewer", nil, ""}, {"a@corp.com", "viewer", []string{"a-dev"}, ""}, } for _, tt := range tests { t.Run(tt.user+"/"+tt.role, func(t *testing.T) { c, tok := aclTestClient(t, wh, tt.user, tt.role) raw, _ := json.Marshal(map[string]any{"token": tok}) wh.handleGetDevices(c, raw) msg := readUntilCmd(t, c, "device_list") rawDevices, _ := json.Marshal(msg["devices"]) var items []deviceListItem if err := json.Unmarshal(rawDevices, &items); err != nil { t.Fatalf("decode devices: %v", err) } got := make(map[string]string, len(items)) for _, it := range items { got[it.ID] = it.Owner } if len(got) != len(tt.want) { t.Fatalf("visible = %v, want %v", got, tt.want) } for _, id := range tt.want { if _, ok := got[id]; !ok { t.Fatalf("visible = %v, want %v", got, tt.want) } } if tt.owner != "" && got["a-dev"] != tt.owner { t.Fatalf("a-dev owner = %q, want %q", got["a-dev"], tt.owner) } if tt.owner == "" && got["a-dev"] != "" { t.Fatalf("non-superadmin saw owner %q", got["a-dev"]) } }) } } func TestConnectDeniedForOtherOwnersDevice(t *testing.T) { wh, _, _ := aclTestHub(t) c, tok := aclTestClient(t, wh, "b@corp.com", "admin") raw, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev", "multiWatch": true}) wh.handleConnect(c, raw) msg := readUntilCmd(t, c, "connect_result") if msg["ok"] != false { t.Fatalf("connect allowed: %+v", msg) } wh.mu.RLock() _, watching := c.watchIDs["a-dev"] wh.mu.RUnlock() if watching { t.Fatal("denied connect still subscribed") } } func TestConnectAllowedForOwner(t *testing.T) { wh, _, _ := aclTestHub(t) c, tok := aclTestClient(t, wh, "a@corp.com", "admin") raw, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev", "multiWatch": true}) wh.handleConnect(c, raw) msg := readUntilCmd(t, c, "connect_result") if msg["ok"] != true { t.Fatalf("owner connect denied: %+v", msg) } } func TestTerminalDeniedForOtherOwnersDevice(t *testing.T) { wh, _, _ := aclTestHub(t) c, tok := aclTestClient(t, wh, "b@corp.com", "admin") raw, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev"}) wh.handleTermOpen(c, raw) msg := readUntilCmd(t, c, "term_closed") if msg["ok"] != false { t.Fatalf("terminal allowed: %+v", msg) } } func TestInputChannelsDeniedByACL(t *testing.T) { wh, devices, _ := aclTestHub(t) var sent int devices.SetSender(func(*connection.Context, []byte) error { sent++ return nil }) c, tok := aclTestClient(t, wh, "b@corp.com", "admin") // Simulate a subscription established before the device became private. wh.mu.Lock() c.watchIDs["a-dev"] = struct{}{} c.watchStartedAt["a-dev"] = time.Now() wh.mu.Unlock() mouse, _ := json.Marshal(map[string]any{ "token": tok, "id": "a-dev", "type": "move", "x": 10, "y": 20, }) wh.handleMouse(c, mouse) if sent != 0 { t.Fatal("mouse event reached a device the caller does not own") } key, _ := json.Marshal(map[string]any{ "token": tok, "id": "a-dev", "keyCode": 65, "down": true, }) wh.handleKey(c, key) if sent != 0 { t.Fatal("key event reached a device the caller does not own") } clip, _ := json.Marshal(map[string]any{ "token": tok, "id": "a-dev", "text": "secret", }) wh.handleClipboardSet(c, clip) if sent != 0 { t.Fatal("clipboard write reached a device the caller does not own") } kf, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev"}) wh.handleKeyframe(c, kf) reply := readUntilCmd(t, c, "keyframe_result") if reply["ok"] != false { t.Fatalf("keyframe allowed: %+v", reply) } rdp, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev"}) wh.handleRdpReset(c, rdp) if sent != 0 { t.Fatal("rdp reset reached a device the caller does not own") } } func TestBindDeviceRequiresSuperadmin(t *testing.T) { wh, _, acl := aclTestHub(t) c, tok := aclTestClient(t, wh, "a@corp.com", "admin") raw, _ := json.Marshal(map[string]any{ "token": tok, "ids": []string{"pub"}, "username": "a@corp.com", }) wh.handleBindDevice(c, raw) msg := readUntilCmd(t, c, "bind_device_result") if msg["ok"] != false || msg["msg"] != "Superadmin only" { t.Fatalf("non-superadmin bind reply = %+v", msg) } if acl.Owner("pub") != "" { t.Fatal("non-superadmin changed the ACL") } } func TestBindDeviceAndRevoke(t *testing.T) { wh, _, acl := aclTestHub(t) b, btok := aclTestClient(t, wh, "b@corp.com", "admin") // b was legitimately watching/terminalling b-dev before it became private. wh.mu.Lock() b.watchIDs["b-dev"] = struct{}{} b.watchStartedAt["b-dev"] = time.Now() b.termWatching = "b-dev" b.termStartedAt = time.Now() wh.mu.Unlock() _ = btok admin, atok := aclTestClient(t, wh, "admin", "admin") raw, _ := json.Marshal(map[string]any{ "token": atok, "ids": []string{"b-dev"}, "username": "a@corp.com", }) wh.handleBindDevice(admin, raw) msg := readUntilCmd(t, admin, "bind_device_result") if msg["ok"] != true { t.Fatalf("bind reply = %+v", msg) } if got := acl.Owner("b-dev"); got != "a@corp.com" { t.Fatalf("owner = %q", got) } wh.mu.RLock() _, watching := b.watchIDs["b-dev"] term := b.termWatching wh.mu.RUnlock() if watching { t.Fatal("revoked viewer still subscribed") } if term != "" { t.Fatal("revoked viewer still holds the terminal") } // b gets device_revoked and term_closed; both may be preceded by // devices_changed broadcasts. _ = readUntilCmd(t, b, "device_revoked") _ = readUntilCmd(t, b, "term_closed") } func TestBindRejectsBadTargets(t *testing.T) { wh, _, acl := aclTestHub(t) admin, tok := aclTestClient(t, wh, "admin", "admin") tests := []struct { name string username string }{ {"built-in admin", "admin"}, {"unknown local", "nobody"}, {"empty", ""}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { raw, _ := json.Marshal(map[string]any{ "token": tok, "ids": []string{"pub"}, "username": tt.username, }) wh.handleBindDevice(admin, raw) msg := readUntilCmd(t, admin, "bind_device_result") if msg["ok"] != false { t.Fatalf("bind(%q) accepted: %+v", tt.username, msg) } if acl.Owner("pub") != "" { t.Fatalf("bind(%q) changed the ACL", tt.username) } }) } // A local account is accepted… if err := wh.auth.CreateUser("alice", "pw", "admin", nil); err != nil { t.Fatalf("CreateUser: %v", err) } raw, _ := json.Marshal(map[string]any{ "token": tok, "ids": []string{"pub"}, "username": "alice", }) wh.handleBindDevice(admin, raw) msg := readUntilCmd(t, admin, "bind_device_result") if msg["ok"] != true { t.Fatalf("bind to local user denied: %+v", msg) } if acl.Owner("pub") != "alice" { t.Fatalf("owner = %q", acl.Owner("pub")) } } func TestDeleteDeviceDropsBinding(t *testing.T) { wh, _, acl := aclTestHub(t) c, tok := aclTestClient(t, wh, "admin", "admin") raw, _ := json.Marshal(map[string]any{"token": tok, "id": "a-dev"}) wh.handleDeleteDevice(c, raw) msg := readUntilCmd(t, c, "delete_device_result") if msg["ok"] != true { t.Fatalf("delete reply = %+v", msg) } if got := acl.Owner("a-dev"); got != "" { t.Fatalf("binding survived device deletion: %q", got) } } func TestLoginRejectsAtSignUsername(t *testing.T) { wh, _, _ := aclTestHub(t) c := &wsClient{ send: make(chan wsMsg, 8), closed: make(chan struct{}), addr: "203.0.113.5", } raw, _ := json.Marshal(map[string]any{ "username": "alice@corp.com", "response": "x", "nonce": "n", }) wh.handleLogin(c, raw) msg := readUntilCmd(t, c, "login_result") if msg["ok"] != false { t.Fatalf("password login accepted an SSO-shaped username: %+v", msg) } } func TestDeviceUpdateDoesNotLeakBoundDevices(t *testing.T) { wh, _, _ := aclTestHub(t) super, _ := aclTestClient(t, wh, "admin", "admin") other, _ := aclTestClient(t, wh, "c@corp.com", "admin") wh.OnDeviceUpdate("a-dev", 12, "Bank - Chrome") msg := readUntilCmd(t, super, "device_update") if msg["activeWindow"] != "Bank - Chrome" { t.Fatalf("superadmin update = %+v", msg) } select { case m := <-other.send: t.Fatalf("device_update for a bound device leaked: %s", m.data) case <-time.After(200 * time.Millisecond): } } func TestGetGroupsFiltersHiddenDevices(t *testing.T) { wh, _, _ := aclTestHub(t) other, tok := aclTestClient(t, wh, "c@corp.com", "admin") raw, _ := json.Marshal(map[string]any{"token": tok}) wh.handleGetGroups(other, raw) msg := readUntilCmd(t, other, "groups") got, _ := msg["groups"].([]any) for _, g := range got { if g == "private-a" || g == "private-b" { t.Fatalf("group of a hidden device leaked: %v", got) } } } func TestUnbindRevokesViewerKeepsAdmin(t *testing.T) { wh, _, acl := aclTestHub(t) if err := acl.Bind([]string{"a-dev"}, "v@corp.com", "admin"); err != nil { t.Fatalf("bind: %v", err) } viewer, _ := aclTestClient(t, wh, "v@corp.com", "viewer") adminWhilePublic, _ := aclTestClient(t, wh, "c@corp.com", "admin") super, stok := aclTestClient(t, wh, "admin", "admin") // Both sessions predate the unbind (simulated directly). wh.mu.Lock() viewer.watchIDs["a-dev"] = struct{}{} viewer.watchStartedAt["a-dev"] = time.Now() adminWhilePublic.watchIDs["a-dev"] = struct{}{} adminWhilePublic.watchStartedAt["a-dev"] = time.Now() wh.mu.Unlock() raw, _ := json.Marshal(map[string]any{"token": stok, "ids": []string{"a-dev"}}) wh.handleUnbindDevice(super, raw) if rep := readUntilCmd(t, super, "unbind_device_result"); rep["ok"] != true { t.Fatalf("unbind = %+v", rep) } wh.mu.RLock() _, viewerWatching := viewer.watchIDs["a-dev"] _, adminWatching := adminWhilePublic.watchIDs["a-dev"] wh.mu.RUnlock() if viewerWatching { t.Fatal("viewer kept watching a device that became admin-only") } if !adminWatching { t.Fatal("admin-role watcher was dropped from a now-public device") } _ = readUntilCmd(t, viewer, "device_revoked") } func TestDeleteUserUnbindsDevices(t *testing.T) { wh, _, acl := aclTestHub(t) if err := wh.auth.CreateUser("alice", "pw", "admin", nil); err != nil { t.Fatalf("CreateUser: %v", err) } if err := acl.Bind([]string{"a-dev"}, "alice", "admin"); err != nil { t.Fatalf("bind: %v", err) } super, tok := aclTestClient(t, wh, "admin", "admin") raw, _ := json.Marshal(map[string]any{"token": tok, "username": "alice"}) wh.handleDeleteUser(super, raw) rep := readUntilCmd(t, super, "delete_user_result") if rep["ok"] != true { t.Fatalf("delete_user = %+v", rep) } if got := acl.Owner("a-dev"); got != "" { t.Fatalf("binding survived user deletion: %q", got) } } // A non-superadmin admin may not delete an account that owns bound devices: // releasing those bindings would hand another user's private device to the // public pool, which only the superadmin may decide. func TestDeleteUserWithBoundDevicesRequiresSuperadmin(t *testing.T) { wh, _, acl := aclTestHub(t) if err := wh.auth.CreateUser("alice", "pw", "admin", nil); err != nil { t.Fatalf("CreateUser: %v", err) } if err := acl.Bind([]string{"a-dev"}, "alice", "admin"); err != nil { t.Fatalf("bind: %v", err) } eve, tok := aclTestClient(t, wh, "eve@corp.com", "admin") raw, _ := json.Marshal(map[string]any{"token": tok, "username": "alice"}) wh.handleDeleteUser(eve, raw) rep := readUntilCmd(t, eve, "delete_user_result") if rep["ok"] != false { t.Fatalf("delete_user = %+v, want refusal", rep) } if _, exists := wh.auth.GetSalt("alice"); !exists { t.Fatal("alice was deleted by a non-superadmin admin") } if got := acl.Owner("a-dev"); got != "alice" { t.Fatalf("binding changed: %q", got) } // An account without bound devices is still deletable by any admin. if err := wh.auth.CreateUser("carol", "pw", "admin", nil); err != nil { t.Fatalf("CreateUser: %v", err) } raw, _ = json.Marshal(map[string]any{"token": tok, "username": "carol"}) wh.handleDeleteUser(eve, raw) rep = readUntilCmd(t, eve, "delete_user_result") if rep["ok"] != true { t.Fatalf("delete_user(carol) = %+v, want success", rep) } if _, exists := wh.auth.GetSalt("carol"); exists { t.Fatal("carol was not deleted") } }